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
Ruby
Ruby
move wrap_scope to class level
19c36778822c09c6159c538478f296459f592687
<ide><path>activerecord/lib/active_record/associations/builder/collection_association.rb <ide> def initialize(name, scope, options, extension) <ide> super <ide> <ide> if extension <del> @scope = wrap_scope @scope, extension <add> @scope = self.class.wrap_scope @scope, extension <ide> end <ide> end <ide> <ide> def #{name.to_s.singularize}_ids=(ids) <ide> <ide> private <ide> <del> def wrap_scope(scope, mod) <add> def self.wrap_scope(scope, mod) <ide> if scope <ide> proc { |owner| instance_exec(owner, &scope).extending(mod) } <ide> else
1
Javascript
Javascript
use decodestrings public api for writable stream
79aab5dd7cfe30f807b5d197c95aea9dd59ecb40
<ide><path>lib/net.js <ide> function Socket(options) { <ide> options.allowHalfOpen = true; <ide> // For backwards compat do not emit close on destroy. <ide> options.emitClose = false; <add> // Handle strings directly. <add> options.decodeStrings = false; <ide> stream.Duplex.call(this, options); <ide> <ide> // Default to *not* allowing half open sockets. <ide> function Socket(options) { <ide> this._pendingData = null; <ide> this._pendingEncoding = ''; <ide> <del> // handle strings directly <del> this._writableState.decodeStrings = false; <del> <ide> // If we have a handle, then start the flow of data into the <ide> // buffer. if not, then this will happen when we connect <ide> if (this._handle && options.readable !== false) {
1
Text
Text
fix objective-c example in readme
015136f36eda5ec2ac08778b32b4fd10e331bd8a
<ide><path>README.md <ide> Custom iOS views can be exposed by subclassing `RCTViewManager`, implementing a <ide> <ide> RCT_EXPORT_VIEW_PROPERTY(myCustomProperty); <ide> <del>@end`} <add>@end <ide> ``` <ide> <ide> ```javascript
1
Javascript
Javascript
remove unnecessary doc ready
14186697572064184b6cad45334ed7f7303e3fec
<ide><path>client/main.js <ide> $(document).ready(function() { <ide> ga('send', 'event', 'Challenge', 'load', challengeName); <ide> } <ide> <del> $(document).ready(function() { <del> if (typeof editor !== 'undefined') { <del> $('#reset-button').on('click', resetEditor); <del> } <del> }); <add> if (typeof editor !== 'undefined') { <add> $('#reset-button').on('click', resetEditor); <add> } <ide> <ide> var CSRF_HEADER = 'X-CSRF-Token'; <ide>
1
Python
Python
relax boto3 requirment
8caa4d620f032b1b4cf914399e70b4c5117a588c
<ide><path>setup.py <ide> def get_sphinx_theme_version() -> str: <ide> # If you change this mark you should also change ./scripts/ci/check_order_setup.py <ide> # Start dependencies group <ide> amazon = [ <del> 'boto3>=1.15.0,<1.16.0', <add> 'boto3>=1.15.0,<1.18.0', <ide> 'botocore>=1.18.0,<1.19.0', <ide> 'watchtower~=0.7.3', <ide> ]
1
Javascript
Javascript
add several tests to htmlbars feature flag
82ce12a0e9a117141e0d8242f676747075ce7458
<ide><path>packages/ember-htmlbars/tests/helpers/bind_attr_test.js <ide> test("should be able to bind classes to globals with {{bind-attr class}} (DEPREC <ide> ok(view.$('img').hasClass('is-open'), "sets classname to the dasherized value of the global property"); <ide> }); <ide> <del>// HTMLBars TODO: Needs {{#each}} helper <del>if (!Ember.FEATURES.isEnabled('ember-htmlbars')) { <del> <ide> test("should be able to bind-attr to 'this' in an {{#each}} block [DEPRECATED]", function() { <ide> expectDeprecation('Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead. See http://emberjs.com/guides/deprecations/#toc_more-consistent-handlebars-scope for more details.'); <ide> <ide> test("should be able to bind-attr to var in {{#each var in list}} block", functi <ide> ok(/three\.gif$/.test(images[1].src)); <ide> }); <ide> <del>} <del> <ide> test("should teardown observers from bind-attr on rerender", function() { <ide> view = EmberView.create({ <ide> template: compile('<span {{bind-attr class="view.foo" name=view.foo}}>wat</span>'), <ide><path>packages/ember-htmlbars/tests/helpers/yield_test.js <ide> test("block should work properly even when templates are not hard-coded", functi <ide> <ide> }); <ide> <del>if (!Ember.FEATURES.isEnabled('ember-htmlbars')) { <del> <ide> test("templates should yield to block, when the yield is embedded in a hierarchy of virtual views", function() { <ide> var TimesView = EmberView.extend({ <ide> layout: compile('<div class="times">{{#each item in view.index}}{{yield}}{{/each}}</div>'), <ide> test("templates should yield to block, when the yield is embedded in a hierarchy <ide> equal(view.$('div#container div.times-item').length, 5, 'times-item is embedded within wrapping container 5 times, as expected'); <ide> }); <ide> <del>} <del> <ide> test("templates should yield to block, when the yield is embedded in a hierarchy of non-virtual views", function() { <ide> var NestingView = EmberView.extend({ <ide> layout: compile('{{#view tagName="div" classNames="nesting"}}{{yield}}{{/view}}')
2
PHP
PHP
change method order
33b508e88e322c9330908a3a2145623ae6676377
<ide><path>src/Illuminate/Container/Container.php <ide> protected function getClosure($abstract, $concrete) <ide> * Bind a callback to resolve with Container::call. <ide> * <ide> * @param string $method <del> * @param \Closure $concrete <add> * @param \Closure $callback <ide> * @return void <ide> */ <ide> public function bindMethod($method, $callback) <ide> { <ide> $this->methodBindings[$this->normalize($method)] = $callback; <ide> } <ide> <del> /** <del> * Call a method that has been bound to the container. <del> * <del> * @param callable $callback <del> * @param mixed $default <del> * @return mixed <del> */ <del> protected function callBoundMethod($callback, $default) <del> { <del> if (! is_array($callback)) { <del> return value($default); <del> } <del> <del> $class = is_string($callback[0]) ? $callback[0] : get_class($callback[0]); <del> <del> $method = $this->normalize("{$class}@{$callback[1]}"); <del> <del> if (! isset($this->methodBindings[$method])) { <del> return value($default); <del> } <del> <del> return $this->methodBindings[$method]($callback[0], $this); <del> } <del> <ide> /** <ide> * Add a contextual binding to the container. <ide> * <ide> protected function callClass($target, array $parameters = [], $defaultMethod = n <ide> return $this->call([$this->make($segments[0]), $method], $parameters); <ide> } <ide> <add> /** <add> * Call a method that has been bound to the container. <add> * <add> * @param callable $callback <add> * @param mixed $default <add> * @return mixed <add> */ <add> protected function callBoundMethod($callback, $default) <add> { <add> if (! is_array($callback)) { <add> return value($default); <add> } <add> <add> $class = is_string($callback[0]) ? $callback[0] : get_class($callback[0]); <add> <add> $method = $this->normalize("{$class}@{$callback[1]}"); <add> <add> if (! isset($this->methodBindings[$method])) { <add> return value($default); <add> } <add> <add> return $this->methodBindings[$method]($callback[0], $this); <add> } <add> <ide> /** <ide> * Get a closure to resolve the given type from the container. <ide> *
1
PHP
PHP
remove swift mailer bindings
b0609f429193d7a856816f7cdb8bdc81199c7004
<ide><path>src/Illuminate/Mail/MailServiceProvider.php <ide> public function provides() <ide> return [ <ide> 'mail.manager', <ide> 'mailer', <del> 'swift.mailer', <del> 'swift.transport', <ide> Markdown::class, <ide> ]; <ide> }
1
Python
Python
simplify import check in cli
782b8b374f191b13fa971db6bae501661139ed10
<ide><path>airflow/cli/cli_parser.py <ide> def _check_value(self, action, value): <ide> raise ArgumentError(action, message) <ide> if value == 'kubernetes': <ide> try: <del> from kubernetes.client import models <del> if not models: <del> message = "kubernetes subcommand requires that ' \ <del> 'you run pip install 'apache-airflow[cncf.kubernetes]'" <del> raise ArgumentError(action, message) <del> except Exception: # pylint: disable=W0703 <del> message = 'kubernetes subcommand requires that you pip install the kubernetes python client' <add> import kubernetes.client # noqa: F401 pylint: disable=unused-import <add> except ImportError: <add> message = ( <add> 'The kubernetes subcommand requires that you pip install the kubernetes python client.' <add> "To do it, run: pip install 'apache-airflow[cncf.kubernetes]'" <add> ) <ide> raise ArgumentError(action, message) <ide> <ide> if action.choices is not None and value not in action.choices:
1
Javascript
Javascript
fix blueprint helper test
d4facc6f0e77114d45712241f76b84b7af5ace11
<ide><path>node-tests/blueprints/helper-test.js <ide> describe('Blueprint: helper', function() { <ide> it('helper foo/bar-baz --dummy', function() { <ide> return emberGenerateDestroy(['helper', 'foo/bar-baz', '--dummy'], _file => { <ide> expect(_file('tests/dummy/src/ui/components/foo/bar-baz.js')).to.equal( <del> fixture('helper/helper.js') <add> fixture('helper/mu-helper.js') <ide> ); <ide> expect(_file('src/ui/components/foo/bar-baz.js')).to.not.exist; <ide> });
1
PHP
PHP
fix doc blocks accuracy
3558a6f2e6e8ae8e8129199d70818b6dcd2f67c4
<ide><path>src/Console/Command/UpgradeShell.php <ide> public function app_uses() { <ide> * Replace all the App::uses() calls with `use`. <ide> * <ide> * @param string $file The file to search and replace. <add> * @return mixed Replacement of uses call <ide> */ <ide> protected function _replaceUses($file) { <ide> $pattern = '#App::uses\([\'"]([a-z0-9_]+)[\'"],\s*[\'"]([a-z0-9/_]+)(?:\.([a-z0-9/_]+))?[\'"]\)#i'; <ide><path>src/Controller/Component/Acl/IniAcl.php <ide> public function initialize(Component $component) { <ide> * @param string $aro ARO The requesting object identifier. <ide> * @param string $aco ACO The controlled object identifier. <ide> * @param string $action Action (defaults to *) <add> * @return void <ide> */ <ide> public function allow($aro, $aco, $action = "*") { <ide> } <ide> public function allow($aro, $aco, $action = "*") { <ide> * @param string $aro ARO The requesting object identifier. <ide> * @param string $aco ACO The controlled object identifier. <ide> * @param string $action Action (defaults to *) <add> * @return void <ide> */ <ide> public function deny($aro, $aco, $action = "*") { <ide> } <ide> public function deny($aro, $aco, $action = "*") { <ide> * @param string $aro ARO The requesting object identifier. <ide> * @param string $aco ACO The controlled object identifier. <ide> * @param string $action Action (defaults to *) <add> * @return void <ide> */ <ide> public function inherit($aro, $aco, $action = "*") { <ide> } <ide><path>src/Controller/Component/Auth/BaseAuthenticate.php <ide> public function getUser(Request $request) { <ide> } <ide> <ide> /** <del> * Handle unauthenticated access attempt. <add> * Handle unauthenticated access attempt. In implementation, will return true to indicate <add> * the unauthenticated request has been dealt with and no more action is required by <add> * AuthComponent or void (default). <ide> * <ide> * @param Cake\Network\Request $request A request object. <ide> * @param Cake\Network\Response $response A response object. <add> * @return void <ide> */ <ide> public function unauthenticated(Request $request, Response $response) { <ide> } <ide><path>src/Controller/Controller.php <ide> public function beforeRender(Event $event) { <ide> * false to stop redirection event, <ide> * string controllers a new redirection URL or <ide> * array with the keys url, status and exit to be used by the redirect method. <add> * @return void <ide> * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks <ide> */ <ide> public function beforeRedirect(Event $event, $url, $status = null, $exit = true) { <ide> public function beforeRedirect(Event $event, $url, $status = null, $exit = true) <ide> * Called after the controller action is run and rendered. <ide> * <ide> * @param Event $event An Event instance <add> * @return void <ide> * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks <ide> */ <ide> public function afterFilter(Event $event) { <ide><path>src/Database/IdentifierQuoter.php <ide> protected function _quoteJoins($joins) { <ide> * Quotes the table name and columns for an insert query <ide> * <ide> * @param Query $query <add> * @return void <ide> */ <ide> protected function _quoteInsert($query) { <ide> list($table, $columns) = $query->clause('insert');
5
Text
Text
prefer one liners os requirement install commands
166a7fb78b207e47dbfdce5328da320f9bf085ee
<ide><path>guides/source/development_dependencies_install.md <ide> To install all run: <ide> <ide> ```bash <ide> $ sudo apt-get update <del>$ sudo apt-get install sqlite3 libsqlite3-dev <del> mysql-server libmysqlclient-dev <del> postgresql postgresql-client postgresql-contrib libpq-dev <del> redis-server memcached imagemagick ffmpeg mupdf mupdf-tools <add>$ sudo apt-get install sqlite3 libsqlite3-dev mysql-server libmysqlclient-dev postgresql postgresql-client postgresql-contrib libpq-dev redis-server memcached imagemagick ffmpeg mupdf mupdf-tools <ide> <ide> # Install Yarn <ide> $ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - <ide> $ sudo apt-get install yarn <ide> To install all run: <ide> <ide> ```bash <del>$ sudo dnf install sqlite-devel sqlite-libs <del> mysql-server mysql-devel <del> postgresql-server postgresql-devel <del> redis memcached imagemagick ffmpeg mupdf <add>$ sudo dnf install sqlite-devel sqlite-libs mysql-server mysql-devel postgresql-server postgresql-devel redis memcached imagemagick ffmpeg mupdf <ide> <ide> # Install Yarn <ide> # Use this command if you do not have Node.js installed <ide> $ sudo dnf install yarn <ide> To install all run: <ide> <ide> ```bash <del>$ sudo pacman -S sqlite <del> mariadb libmariadbclient mariadb-clients <del> postgresql postgresql-libs <del> redis memcached imagemagick ffmpeg mupdf mupdf-tools poppler <del> yarn <add>$ sudo pacman -S sqlite mariadb libmariadbclient mariadb-clients postgresql postgresql-libs redis memcached imagemagick ffmpeg mupdf mupdf-tools poppler yarn <ide> $ sudo systemctl start redis <ide> ``` <ide> <ide> use MariaDB instead (see [this announcement](https://www.archlinux.org/news/mari <ide> To install all run: <ide> <ide> ```bash <del># pkg install sqlite3 <del> mysql80-client mysql80-server <del> postgresql11-client postgresql11-server <del> memcached imagemagick ffmpeg mupdf <del> yarn <add>$ pkg install sqlite3 mysql80-client mysql80-server postgresql11-client postgresql11-server memcached imagemagick ffmpeg mupdf yarn <ide> # portmaster databases/redis <ide> ``` <ide>
1
Text
Text
improve readability of code example
a5a090ec2bcc06f9ce263046711299913f2ff5d0
<ide><path>docs/advanced/Middleware.md <ide> import { createStore, combineReducers, applyMiddleware } from 'redux'; <ide> <ide> // applyMiddleware takes createStore() and returns <ide> // a function with a compatible API. <del>let createStoreWithMiddleware = applyMiddleware( <del> logger, <del> crashReporter <del>)(createStore); <add>let createStoreWithMiddleware = applyMiddleware(logger, crashReporter)(createStore); <ide> <ide> // Use it like you would use createStore() <ide> let todoApp = combineReducers(reducers);
1
Text
Text
improve buffer code examples
fe89848dc64bb19718697d2d6149ea4ffd2c0d20
<ide><path>doc/api/buffer.md <ide> The `Buffer` class is a global within Node.js, making it unlikely that one <ide> would need to ever use `require('buffer').Buffer`. <ide> <ide> ```js <add>// Creates a zero-filled Buffer of length 10. <ide> const buf1 = Buffer.alloc(10); <del> // Creates a zero-filled Buffer of length 10. <ide> <add>// Creates a Buffer of length 10, filled with 0x1. <ide> const buf2 = Buffer.alloc(10, 1); <del> // Creates a Buffer of length 10, filled with 0x01. <ide> <add>// Creates an uninitialized buffer of length 10. <add>// This is faster than calling Buffer.alloc() but the returned <add>// Buffer instance might contain old data that needs to be <add>// overwritten using either fill() or write(). <ide> const buf3 = Buffer.allocUnsafe(10); <del> // Creates an uninitialized buffer of length 10. <del> // This is faster than calling Buffer.alloc() but the returned <del> // Buffer instance might contain old data that needs to be <del> // overwritten using either fill() or write(). <ide> <del>const buf4 = Buffer.from([1,2,3]); <del> // Creates a Buffer containing [01, 02, 03]. <add>// Creates a Buffer containing [0x1, 0x2, 0x3]. <add>const buf4 = Buffer.from([1, 2, 3]); <ide> <add>// Creates a Buffer containing ASCII bytes [0x74, 0x65, 0x73, 0x74]. <ide> const buf5 = Buffer.from('test'); <del> // Creates a Buffer containing ASCII bytes [74, 65, 73, 74]. <ide> <add>// Creates a Buffer containing UTF-8 bytes [0x74, 0xc3, 0xa9, 0x73, 0x74]. <ide> const buf6 = Buffer.from('tést', 'utf8'); <del> // Creates a Buffer containing UTF8 bytes [74, c3, a9, 73, 74]. <ide> ``` <ide> <ide> ## `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()` <ide> by using an explicit encoding method. <ide> <ide> ```js <ide> const buf = Buffer.from('hello world', 'ascii'); <add> <add>// Prints: 68656c6c6f20776f726c64 <ide> console.log(buf.toString('hex')); <del> // prints: 68656c6c6f20776f726c64 <add> <add>// Prints: aGVsbG8gd29ybGQ= <ide> console.log(buf.toString('base64')); <del> // prints: aGVsbG8gd29ybGQ= <ide> ``` <ide> <ide> The character encodings currently supported by Node.js include: <ide> a TypedArray instance by using the TypeArray object's `.buffer` property: <ide> <ide> ```js <ide> const arr = new Uint16Array(2); <add> <ide> arr[0] = 5000; <ide> arr[1] = 4000; <ide> <del>const buf1 = Buffer.from(arr); // copies the buffer <del>const buf2 = Buffer.from(arr.buffer); // shares the memory with arr; <add>// Copies the contents of `arr` <add>const buf1 = Buffer.from(arr); <add> <add>// Shares memory with `arr` <add>const buf2 = Buffer.from(arr.buffer); <ide> <add>// Prints: <Buffer 88 a0> <ide> console.log(buf1); <del> // Prints: <Buffer 88 a0>, copied buffer has only two elements <add> <add>// Prints: <Buffer 88 13 a0 0f> <ide> console.log(buf2); <del> // Prints: <Buffer 88 13 a0 0f> <ide> <ide> arr[1] = 6000; <add> <add>// Prints: <Buffer 88 a0> <ide> console.log(buf1); <del> // Prints: <Buffer 88 a0> <add> <add>// Prints: <Buffer 88 13 70 17> <ide> console.log(buf2); <del> // Prints: <Buffer 88 13 70 17> <ide> ``` <ide> <ide> Note that when creating a `Buffer` using the TypedArray's `.buffer`, it is <ide> possible to use only a portion of the underlying `ArrayBuffer` by passing in <ide> ```js <ide> const arr = new Uint16Array(20); <ide> const buf = Buffer.from(arr.buffer, 0, 16); <add> <add>// Prints: 16 <ide> console.log(buf.length); <del> // Prints: 16 <ide> ``` <ide> <ide> The `Buffer.from()` and [`TypedArray.from()`][] (e.g.`Uint8Array.from()`) have <ide> Buffers can be iterated over using the ECMAScript 2015 (ES6) `for..of` syntax: <ide> ```js <ide> const buf = Buffer.from([1, 2, 3]); <ide> <del>for (var b of buf) <del> console.log(b); <del> <ide> // Prints: <ide> // 1 <ide> // 2 <ide> // 3 <add>for (var b of buf) { <add> console.log(b); <add>} <ide> ``` <ide> <ide> Additionally, the [`buf.values()`][], [`buf.keys()`][], and <ide> deprecated: v6.0.0 <ide> Allocates a new Buffer using an `array` of octets. <ide> <ide> ```js <del>const buf = new Buffer([0x62,0x75,0x66,0x66,0x65,0x72]); <del> // creates a new Buffer containing ASCII bytes <del> // ['b','u','f','f','e','r'] <add>// Creates a new Buffer containing the ASCII bytes of the string 'buffer' <add>const buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); <ide> ``` <ide> <ide> ### new Buffer(buffer) <ide> const buf1 = new Buffer('buffer'); <ide> const buf2 = new Buffer(buf1); <ide> <ide> buf1[0] = 0x61; <add> <add>// Prints: auffer <ide> console.log(buf1.toString()); <del> // 'auffer' <add> <add>// Prints: buffer <ide> console.log(buf2.toString()); <del> // 'buffer' (copy is not changed) <ide> ``` <ide> <ide> ### new Buffer(arrayBuffer[, byteOffset [, length]]) <ide> the `arrayBuffer` that will be shared by the `Buffer`. <ide> <ide> ```js <ide> const arr = new Uint16Array(2); <add> <ide> arr[0] = 5000; <ide> arr[1] = 4000; <ide> <del>const buf = new Buffer(arr.buffer); // shares the memory with arr; <add>// Shares memory with `arr` <add>const buf = new Buffer(arr.buffer); <ide> <add>// Prints: <Buffer 88 13 a0 0f> <ide> console.log(buf); <del> // Prints: <Buffer 88 13 a0 0f> <ide> <del>// changing the TypdArray changes the Buffer also <add>// Changing the original Uint16Array changes the Buffer also <ide> arr[1] = 6000; <ide> <add>// Prints: <Buffer 88 13 70 17> <ide> console.log(buf); <del> // Prints: <Buffer 88 13 70 17> <ide> ``` <ide> <ide> ### new Buffer(size) <ide> a `Buffer` to zeroes. <ide> <ide> ```js <ide> const buf = new Buffer(5); <add> <add>// Prints (contents may vary): <Buffer 78 e0 82 02 01> <ide> console.log(buf); <del> // <Buffer 78 e0 82 02 01> <del> // (octets will be different, every time) <add> <ide> buf.fill(0); <add> <add>// Prints: <Buffer 00 00 00 00 00> <ide> console.log(buf); <del> // <Buffer 00 00 00 00 00> <ide> ``` <ide> <ide> ### new Buffer(str[, encoding]) <ide> provided, the `encoding` parameter identifies the strings character encoding. <ide> <ide> ```js <ide> const buf1 = new Buffer('this is a tést'); <add> <add>// Prints: this is a tést <ide> console.log(buf1.toString()); <del> // prints: this is a tést <add> <add>// Prints: this is a tC)st <ide> console.log(buf1.toString('ascii')); <del> // prints: this is a tC)st <add> <ide> <ide> const buf2 = new Buffer('7468697320697320612074c3a97374', 'hex'); <add> <add>// Prints: this is a tést <ide> console.log(buf2.toString()); <del> // prints: this is a tést <ide> ``` <ide> <ide> ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <ide> Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the <ide> <ide> ```js <ide> const buf = Buffer.alloc(5); <add> <add>// Prints: <Buffer 00 00 00 00 00> <ide> console.log(buf); <del> // <Buffer 00 00 00 00 00> <ide> ``` <ide> <ide> The `size` must be less than or equal to the value of <ide> If `fill` is specified, the allocated `Buffer` will be initialized by calling <ide> <ide> ```js <ide> const buf = Buffer.alloc(5, 'a'); <add> <add>// Prints: <Buffer 61 61 61 61 61> <ide> console.log(buf); <del> // <Buffer 61 61 61 61 61> <ide> ``` <ide> <ide> If both `fill` and `encoding` are specified, the allocated `Buffer` will be <ide> initialized by calling `buf.fill(fill, encoding)`. For example: <ide> <ide> ```js <ide> const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); <add> <add>// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> <ide> console.log(buf); <del> // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> <ide> ``` <ide> <ide> Calling `Buffer.alloc(size)` can be significantly slower than the alternative <ide> initialized*. The contents of the newly created `Buffer` are unknown and <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(5); <add> <add>// Prints (contents may vary): <Buffer 78 e0 82 02 01> <ide> console.log(buf); <del> // <Buffer 78 e0 82 02 01> <del> // (octets will be different, every time) <add> <ide> buf.fill(0); <add> <add>// Prints: <Buffer 00 00 00 00 00> <ide> console.log(buf); <del> // <Buffer 00 00 00 00 00> <ide> ``` <ide> <ide> A `TypeError` will be thrown if `size` is not a number. <ide> to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then <ide> copy out the relevant bits. <ide> <ide> ```js <del>// need to keep around a few small chunks of memory <add>// Need to keep around a few small chunks of memory <ide> const store = []; <ide> <ide> socket.on('readable', () => { <ide> const data = socket.read(); <del> // allocate for retained data <add> <add> // Allocate for retained data <ide> const sb = Buffer.allocUnsafeSlow(10); <del> // copy the data into the new allocation <add> <add> // Copy the data into the new allocation <ide> data.copy(sb, 0, 0, 10); <add> <ide> store.push(sb); <ide> }); <ide> ``` <ide> Example: <ide> ```js <ide> const str = '\u00bd + \u00bc = \u00be'; <ide> <add>// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes <ide> console.log(`${str}: ${str.length} characters, ` + <ide> `${Buffer.byteLength(str, 'utf8')} bytes`); <del> <del>// ½ + ¼ = ¾: 9 characters, 12 bytes <ide> ``` <ide> <ide> When `string` is a `Buffer`/[`DataView`][]/[`TypedArray`][]/`ArrayBuffer`, <ide> Compares `buf1` to `buf2` typically for the purpose of sorting arrays of <ide> Buffers. This is equivalent is calling [`buf1.compare(buf2)`][]. <ide> <ide> ```js <del>const arr = [Buffer.from('1234'), Buffer.from('0123')]; <del>arr.sort(Buffer.compare); <add>const buf1 = Buffer.from('1234'); <add>const buf2 = Buffer.from('0123'); <add>const arr = [buf1, buf2]; <add> <add>// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ] <add>// (This result is equal to: [buf2, buf1]) <add>console.log(arr.sort(Buffer.compare)); <ide> ``` <ide> <ide> ### Class Method: Buffer.concat(list[, totalLength]) <ide> const buf2 = Buffer.alloc(14); <ide> const buf3 = Buffer.alloc(18); <ide> const totalLength = buf1.length + buf2.length + buf3.length; <ide> <add>// Prints: 42 <ide> console.log(totalLength); <add> <ide> const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); <add> <add>// Prints: <Buffer 00 00 00 00 ...> <ide> console.log(bufA); <del>console.log(bufA.length); <ide> <del>// 42 <del>// <Buffer 00 00 00 00 ...> <del>// 42 <add>// Prints: 42 <add>console.log(bufA.length); <ide> ``` <ide> <ide> ### Class Method: Buffer.from(array) <ide> added: v3.0.0 <ide> Allocates a new `Buffer` using an `array` of octets. <ide> <ide> ```js <del>const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); <del> // creates a new Buffer containing ASCII bytes <del> // ['b','u','f','f','e','r'] <add>// Creates a new Buffer containing ASCII bytes of the string 'buffer' <add>const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); <ide> ``` <ide> <ide> A `TypeError` will be thrown if `array` is not an `Array`. <ide> TypedArray. <ide> <ide> ```js <ide> const arr = new Uint16Array(2); <add> <ide> arr[0] = 5000; <ide> arr[1] = 4000; <ide> <del>const buf = Buffer.from(arr.buffer); // shares the memory with arr; <add>// Shares memory with `arr` <add>const buf = Buffer.from(arr.buffer); <ide> <add>// Prints: <Buffer 88 13 a0 0f> <ide> console.log(buf); <del> // Prints: <Buffer 88 13 a0 0f> <ide> <del>// changing the TypedArray changes the Buffer also <add>// Changing the original Uint16Array changes the Buffer also <ide> arr[1] = 6000; <ide> <add>// Prints: <Buffer 88 13 70 17> <ide> console.log(buf); <del> // Prints: <Buffer 88 13 70 17> <ide> ``` <ide> <ide> The optional `byteOffset` and `length` arguments specify a memory range within <ide> the `arrayBuffer` that will be shared by the `Buffer`. <ide> ```js <ide> const ab = new ArrayBuffer(10); <ide> const buf = Buffer.from(ab, 0, 2); <add> <add>// Prints: 2 <ide> console.log(buf.length); <del> // Prints: 2 <ide> ``` <ide> <ide> A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. <ide> const buf1 = Buffer.from('buffer'); <ide> const buf2 = Buffer.from(buf1); <ide> <ide> buf1[0] = 0x61; <add> <add>// Prints: auffer <ide> console.log(buf1.toString()); <del> // 'auffer' <add> <add>// Prints: buffer <ide> console.log(buf2.toString()); <del> // 'buffer' (copy is not changed) <ide> ``` <ide> <ide> A `TypeError` will be thrown if `buffer` is not a `Buffer`. <ide> If not provided, `encoding` defaults to `'utf8'`. <ide> <ide> ```js <ide> const buf1 = Buffer.from('this is a tést'); <add> <add>// Prints: this is a tést <ide> console.log(buf1.toString()); <del> // prints: this is a tést <add> <add>// Prints: this is a tC)st <ide> console.log(buf1.toString('ascii')); <del> // prints: this is a tC)st <add> <ide> <ide> const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); <add> <add>// Prints: this is a tést <ide> console.log(buf2.toString()); <del> // prints: this is a tést <ide> ``` <ide> <ide> A `TypeError` will be thrown if `str` is not a string. <ide> range is between `0x00` and `0xFF` (hex) or `0` and `255` (decimal). <ide> Example: copy an ASCII string into a Buffer, one byte at a time: <ide> <ide> ```js <del>const str = "Node.js"; <add>const str = 'Node.js'; <ide> const buf = Buffer.allocUnsafe(str.length); <ide> <ide> for (let i = 0; i < str.length ; i++) { <ide> buf[i] = str.charCodeAt(i); <ide> } <ide> <add>// Prints: Node.js <ide> console.log(buf.toString('ascii')); <del> // Prints: Node.js <ide> ``` <ide> <ide> ### buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]]) <ide> const buf1 = Buffer.from('ABC'); <ide> const buf2 = Buffer.from('BCD'); <ide> const buf3 = Buffer.from('ABCD'); <ide> <add>// Prints: 0 <ide> console.log(buf1.compare(buf1)); <del> // Prints: 0 <add> <add>// Prints: -1 <ide> console.log(buf1.compare(buf2)); <del> // Prints: -1 <add> <add>// Prints: -1 <ide> console.log(buf1.compare(buf3)); <del> // Prints: -1 <add> <add>// Prints: 1 <ide> console.log(buf2.compare(buf1)); <del> // Prints: 1 <add> <add>// Prints: 1 <ide> console.log(buf2.compare(buf3)); <del> // Prints: 1 <ide> <del>[buf1, buf2, buf3].sort(Buffer.compare); <del> // produces sort order [buf1, buf3, buf2] <add>// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ] <add>// (This result is equal to: [buf1, buf3, buf2]) <add>console.log([buf1, buf2, buf3].sort(Buffer.compare)); <ide> ``` <ide> <ide> The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` <ide> arguments can be used to limit the comparison to specific ranges within the two <ide> const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); <ide> const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); <ide> <add>// Prints: 0 <ide> console.log(buf1.compare(buf2, 5, 9, 0, 4)); <del> // Prints: 0 <add> <add>// Prints: -1 <ide> console.log(buf1.compare(buf2, 0, 6, 4)); <del> // Prints: -1 <add> <add>// Prints: 1 <ide> console.log(buf1.compare(buf2, 5, 6, 5)); <del> // Prints: 1 <ide> ``` <ide> <ide> A `RangeError` will be thrown if: `targetStart < 0`, `sourceStart < 0`, <ide> const buf1 = Buffer.allocUnsafe(26); <ide> const buf2 = Buffer.allocUnsafe(26).fill('!'); <ide> <ide> for (let i = 0 ; i < 26 ; i++) { <del> buf1[i] = i + 97; // 97 is ASCII a <add> // 97 is the decimal ASCII value for 'a' <add> buf1[i] = i + 97; <ide> } <ide> <ide> buf1.copy(buf2, 8, 16, 20); <add> <add>// Prints: !!!!!!!!qrst!!!!!!!!!!!!! <ide> console.log(buf2.toString('ascii', 0, 25)); <del> // Prints: !!!!!!!!qrst!!!!!!!!!!!!! <ide> ``` <ide> <ide> Example: Build a single Buffer, then copy data from one region to an overlapping <ide> region in the same Buffer <ide> const buf = Buffer.allocUnsafe(26); <ide> <ide> for (var i = 0 ; i < 26 ; i++) { <del> buf[i] = i + 97; // 97 is ASCII a <add> // 97 is the decimal ASCII value for 'a' <add> buf[i] = i + 97; <ide> } <ide> <ide> buf.copy(buf, 0, 4, 10); <del>console.log(buf.toString()); <ide> <del>// efghijghijklmnopqrstuvwxyz <add>// Prints: efghijghijklmnopqrstuvwxyz <add>console.log(buf.toString()); <ide> ``` <ide> <ide> ### buf.entries() <ide> contents. <ide> <ide> ```js <ide> const buf = Buffer.from('buffer'); <del>for (var pair of buf.entries()) { <del> console.log(pair); <del>} <del>// prints: <add> <add>// Prints: <ide> // [0, 98] <ide> // [1, 117] <ide> // [2, 102] <ide> // [3, 102] <ide> // [4, 101] <ide> // [5, 114] <add>for (var pair of buf.entries()) { <add> console.log(pair); <add>} <ide> ``` <ide> <ide> ### buf.equals(otherBuffer) <ide> const buf1 = Buffer.from('ABC'); <ide> const buf2 = Buffer.from('414243', 'hex'); <ide> const buf3 = Buffer.from('ABCD'); <ide> <add>// Prints: true <ide> console.log(buf1.equals(buf2)); <del> // Prints: true <add> <add>// Prints: false <ide> console.log(buf1.equals(buf3)); <del> // Prints: false <ide> ``` <ide> <ide> ### buf.fill(value[, offset[, end]][, encoding]) <ide> creation and fill of the Buffer to be done on a single line: <ide> <ide> ```js <ide> const b = Buffer.allocUnsafe(50).fill('h'); <add> <add>// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh <ide> console.log(b.toString()); <del> // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh <ide> ``` <ide> <ide> `encoding` is only relevant if `value` is a string. Otherwise it is ignored. <ide> falls in between a multi-byte character then whatever bytes fit into the buffer <ide> are written. <ide> <ide> ```js <del>Buffer(3).fill('\u0222'); <del> // Prints: <Buffer c8 a2 c8> <add>// Prints: <Buffer c8 a2 c8> <add>console.log(Buffer.allocUnsafe(3).fill('\u0222')); <ide> ``` <ide> <ide> ### buf.indexOf(value[, byteOffset][, encoding]) <ide> integer values between `0` and `255`. <ide> ```js <ide> const buf = Buffer.from('this is a buffer'); <ide> <del>buf.indexOf('this'); <del> // returns 0 <del>buf.indexOf('is'); <del> // returns 2 <del>buf.indexOf(Buffer.from('a buffer')); <del> // returns 8 <del>buf.indexOf(97); // ascii for 'a' <del> // returns 8 <del>buf.indexOf(Buffer.from('a buffer example')); <del> // returns -1 <del>buf.indexOf(Buffer.from('a buffer example').slice(0,8)); <del> // returns 8 <add>// Prints: 0 <add>console.log(buf.indexOf('this'))); <add> <add>// Prints: 2 <add>console.log(buf.indexOf('is')); <add> <add>// Prints: 8 <add>console.log(buf.indexOf(Buffer.from('a buffer'))); <add> <add>// Prints: 8 <add>// (97 is the decimal ASCII value for 'a') <add>console.log(buf.indexOf(97)); <add> <add>// Prints: -1 <add>console.log(buf.indexOf(Buffer.from('a buffer example'))); <add> <add>// Prints: 8 <add>console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); <add> <ide> <ide> const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); <ide> <del>utf16Buffer.indexOf('\u03a3', 0, 'ucs2'); <del> // returns 4 <del>utf16Buffer.indexOf('\u03a3', -4, 'ucs2'); <del> // returns 6 <add>// Prints: 4 <add>console.log(utf16Buffer.indexOf('\u03a3', 0, 'ucs2')); <add> <add>// Prints: 6 <add>console.log(utf16Buffer.indexOf('\u03a3', -4, 'ucs2')); <ide> ``` <ide> <ide> ### buf.includes(value[, byteOffset][, encoding]) <ide> The `byteOffset` indicates the index in `buf` where searching begins. <ide> ```js <ide> const buf = Buffer.from('this is a buffer'); <ide> <del>buf.includes('this'); <del> // returns true <del>buf.includes('is'); <del> // returns true <del>buf.includes(Buffer.from('a buffer')); <del> // returns true <del>buf.includes(97); // ascii for 'a' <del> // returns true <del>buf.includes(Buffer.from('a buffer example')); <del> // returns false <del>buf.includes(Buffer.from('a buffer example').slice(0,8)); <del> // returns true <del>buf.includes('this', 4); <del> // returns false <add>// Prints: true <add>console.log(buf.includes('this')); <add> <add>// Prints: true <add>console.log(buf.includes('is')); <add> <add>// Prints: true <add>console.log(buf.includes(Buffer.from('a buffer'))); <add> <add>// Prints: true <add>// (97 is the decimal ASCII value for 'a') <add>console.log(buf.includes(97)); <add> <add>// Prints: false <add>console.log(buf.includes(Buffer.from('a buffer example'))); <add> <add>// Prints: true <add>console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); <add> <add>// Prints: false <add>console.log(buf.includes('this', 4)); <ide> ``` <ide> <ide> ### buf.keys() <ide> Creates and returns an [iterator][] of Buffer keys (indices). <ide> <ide> ```js <ide> const buf = Buffer.from('buffer'); <del>for (var key of buf.keys()) { <del> console.log(key); <del>} <del>// prints: <add> <add>// Prints: <ide> // 0 <ide> // 1 <ide> // 2 <ide> // 3 <ide> // 4 <ide> // 5 <add>for (var key of buf.keys()) { <add> console.log(key); <add>} <ide> ``` <ide> <ide> ### buf.lastIndexOf(value[, byteOffset][, encoding]) <ide> String, Buffer or Number. Strings are by default interpreted as UTF8. If <ide> `byteOffset`. <ide> <ide> ```js <del>const buf = new Buffer('this buffer is a buffer'); <add>const buf = Buffer.from('this buffer is a buffer'); <add> <add>// Prints: 0 <add>console.log(buf.lastIndexOf('this')); <add> <add>// Prints: 17 <add>console.log(buf.lastIndexOf('buffer')); <add> <add>// Prints: 17 <add>console.log(buf.lastIndexOf(Buffer.from('buffer'))); <add> <add>// Prints: 15 <add>// (97 is the decimal ASCII value for 'a') <add>console.log(buf.lastIndexOf(97)); <ide> <del>buf.lastIndexOf('this'); <del> // returns 0 <del>buf.lastIndexOf('buffer'); <del> // returns 17 <del>buf.lastIndexOf(new Buffer('buffer')); <del> // returns 17 <del>buf.lastIndexOf(97); // ascii for 'a' <del> // returns 15 <del>buf.lastIndexOf(new Buffer('yolo')); <del> // returns -1 <del>buf.lastIndexOf('buffer', 5) <del> // returns 5 <del>buf.lastIndexOf('buffer', 4) <del> // returns -1 <add>// Prints: -1 <add>console.log(buf.lastIndexOf(Buffer.from('yolo'))); <ide> <del>const utf16Buffer = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); <add>// Prints: 5 <add>console.log(buf.lastIndexOf('buffer', 5)); <ide> <del>utf16Buffer.lastIndexOf('\u03a3', null, 'ucs2'); <del> // returns 6 <del>utf16Buffer.lastIndexOf('\u03a3', -5, 'ucs2'); <del> // returns 4 <add>// Prints: -1 <add>console.log(buf.lastIndexOf('buffer', 4)); <add> <add> <add>const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); <add> <add>// Prints: 6 <add>console.log(utf16Buffer.lastIndexOf('\u03a3', null, 'ucs2')); <add> <add>// Prints: 4 <add>console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'ucs2')); <ide> ``` <ide> <ide> ### buf.length <ide> allocated, but only 11 ASCII bytes are written. <ide> ```js <ide> const buf = Buffer.alloc(1234); <ide> <add>// Prints: 1234 <ide> console.log(buf.length); <del> // Prints: 1234 <ide> <ide> buf.write('some string', 0, 'ascii'); <add> <add>// Prints: 1234 <ide> console.log(buf.length); <del> // Prints: 1234 <ide> ``` <ide> <ide> While the `length` property is not immutable, changing the value of `length` <ide> use [`buf.slice()`][] to create a new Buffer. <ide> <ide> ```js <ide> var buf = Buffer.allocUnsafe(10); <add> <ide> buf.write('abcdefghj', 0, 'ascii'); <add> <add>// Prints: 10 <ide> console.log(buf.length); <del> // Prints: 10 <del>buf = buf.slice(0,5); <add> <add>buf = buf.slice(0, 5); <add> <add>// Prints: 5 <ide> console.log(buf.length); <del> // Prints: 5 <ide> ``` <ide> <ide> ### buf.readDoubleBE(offset[, noAssert]) <ide> Setting `noAssert` to `true` skips validation of the `offset`. This allows the <ide> `offset` to be beyond the end of the Buffer. <ide> <ide> ```js <del>const buf = Buffer.from([1,2,3,4,5,6,7,8]); <add>const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); <add> <add>// Prints: 8.20788039913184e-304 <add>console.log(buf.readDoubleBE()); <ide> <del>buf.readDoubleBE(); <del> // Returns: 8.20788039913184e-304 <del>buf.readDoubleLE(); <del> // Returns: 5.447603722011605e-270 <del>buf.readDoubleLE(1); <del> // throws RangeError: Index out of range <add>// Prints: 5.447603722011605e-270 <add>console.log(buf.readDoubleLE()); <ide> <del>buf.readDoubleLE(1, true); // Warning: reads passed end of buffer! <del> // Segmentation fault! don't do this! <add>// Throws an exception: RangeError: Index out of range <add>console.log(buf.readDoubleLE(1)); <add> <add>// Warning: reads passed end of buffer! <add>// This will result in a segmentation fault! Don't do this! <add>console.log(buf.readDoubleLE(1, true)); <ide> ``` <ide> <ide> ### buf.readFloatBE(offset[, noAssert]) <ide> Setting `noAssert` to `true` skips validation of the `offset`. This allows the <ide> `offset` to be beyond the end of the Buffer. <ide> <ide> ```js <del>const buf = Buffer.from([1,2,3,4]); <add>const buf = Buffer.from([1, 2, 3, 4]); <add> <add>// Prints: 2.387939260590663e-38 <add>console.log(buf.readFloatBE()); <add> <add>// Prints: 1.539989614439558e-36 <add>console.log(buf.readFloatLE()); <ide> <del>buf.readFloatBE(); <del> // Returns: 2.387939260590663e-38 <del>buf.readFloatLE(); <del> // Returns: 1.539989614439558e-36 <del>buf.readFloatLE(1); <del> // throws RangeError: Index out of range <add>// Throws an exception: RangeError: Index out of range <add>console.log(buf.readFloatLE(1)); <ide> <del>buf.readFloatLE(1, true); // Warning: reads passed end of buffer! <del> // Segmentation fault! don't do this! <add>// Warning: reads passed end of buffer! <add>// This will result in a segmentation fault! Don't do this! <add>console.log(buf.readFloatLE(1, true)); <ide> ``` <ide> <ide> ### buf.readInt8(offset[, noAssert]) <ide> Setting `noAssert` to `true` skips validation of the `offset`. This allows the <ide> Integers read from the Buffer are interpreted as two's complement signed values. <ide> <ide> ```js <del>const buf = Buffer.from([1,-2,3,4]); <add>const buf = Buffer.from([-1, 5]); <ide> <del>buf.readInt8(0); <del> // returns 1 <del>buf.readInt8(1); <del> // returns -2 <add>// Prints: -1 <add>console.log(buf.readInt8(0)); <add> <add>// Prints: 5 <add>console.log(buf.readInt8(1)); <add> <add>// Throws an exception: RangeError: Index out of range <add>console.log(buf.readInt8(2)); <ide> ``` <ide> <ide> ### buf.readInt16BE(offset[, noAssert]) <ide> Setting `noAssert` to `true` skips validation of the `offset`. This allows the <ide> Integers read from the Buffer are interpreted as two's complement signed values. <ide> <ide> ```js <del>const buf = Buffer.from([1,-2,3,4]); <add>const buf = Buffer.from([0, 5]); <add> <add>// Prints: 5 <add>console.log(buf.readInt16BE()); <ide> <del>buf.readInt16BE(); <del> // returns 510 <del>buf.readInt16LE(1); <del> // returns 1022 <add>// Prints: 1280 <add>console.log(buf.readInt16LE(1)); <add> <add>// Throws an exception: RangeError: Index out of range <add>console.log(buf.readInt16LE(1)); <ide> ``` <ide> <ide> ### buf.readInt32BE(offset[, noAssert]) <ide> Setting `noAssert` to `true` skips validation of the `offset`. This allows the <ide> Integers read from the Buffer are interpreted as two's complement signed values. <ide> <ide> ```js <del>const buf = Buffer.from([1,-2,3,4]); <add>const buf = Buffer.from([0, 0, 0, 5]); <add> <add>// Prints: 5 <add>console.log(buf.readInt32BE()); <add> <add>// Prints: 83886080 <add>console.log(buf.readInt32LE()); <ide> <del>buf.readInt32BE(); <del> // returns 33424132 <del>buf.readInt32LE(); <del> // returns 67370497 <del>buf.readInt32LE(1); <del> // throws RangeError: Index out of range <add>// Throws an exception: RangeError: Index out of range <add>console.log(buf.readInt32LE(1)); <ide> ``` <ide> <ide> ### buf.readIntBE(offset, byteLength[, noAssert]) <ide> and interprets the result as a two's complement signed value. Supports up to 48 <ide> bits of accuracy. For example: <ide> <ide> ```js <del>const buf = Buffer.allocUnsafe(6); <del>buf.writeUInt16LE(0x90ab, 0); <del>buf.writeUInt32LE(0x12345678, 2); <del>buf.readIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits) <del>// Returns: '1234567890ab' <add>const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); <add> <add>// Prints: 1234567890ab <add>console.log(buf.readIntLE(0, 6).toString(16)); <ide> <del>buf.readIntBE(0, 6).toString(16); <del>// Returns: -546f87a9cbee <add>// Prints: -546f87a9cbee <add>console.log(buf.readIntBE(0, 6).toString(16)); <add> <add>// Throws an exception: RangeError: Index out of range <add>console.log(buf.readIntBE(1, 6).toString(16)); <ide> ``` <ide> <ide> Setting `noAssert` to `true` skips validation of the `offset`. This allows the <ide> Setting `noAssert` to `true` skips validation of the `offset`. This allows the <ide> `offset` to be beyond the end of the Buffer. <ide> <ide> ```js <del>const buf = Buffer.from([1,-2,3,4]); <add>const buf = Buffer.from([1, -2]); <add> <add>// Prints: 1 <add>console.log(buf.readUInt8(0)); <ide> <del>buf.readUInt8(0); <del> // returns 1 <del>buf.readUInt8(1); <del> // returns 254 <add>// Prints: 254 <add>console.log(buf.readUInt8(1)); <add> <add>// Throws an exception: RangeError: Index out of range <add>console.log(buf.readUInt8(2)); <ide> ``` <ide> <ide> ### buf.readUInt16BE(offset[, noAssert]) <ide> Setting `noAssert` to `true` skips validation of the `offset`. This allows the <ide> Example: <ide> <ide> ```js <del>const buf = Buffer.from([0x3, 0x4, 0x23, 0x42]); <add>const buf = Buffer.from([0x12, 0x34, 0x56]); <add> <add>// Prints: 1234 <add>console.log(buf.readUInt16BE(0).toString(16)); <add> <add>// Prints: 3412 <add>console.log(buf.readUInt16LE(0).toString(16)); <ide> <del>buf.readUInt16BE(0); <del> // Returns: 0x0304 <del>buf.readUInt16LE(0); <del> // Returns: 0x0403 <del>buf.readUInt16BE(1); <del> // Returns: 0x0423 <del>buf.readUInt16LE(1); <del> // Returns: 0x2304 <del>buf.readUInt16BE(2); <del> // Returns: 0x2342 <del>buf.readUInt16LE(2); <del> // Returns: 0x4223 <add>// Prints: 3456 <add>console.log(buf.readUInt16BE(1).toString(16)); <add> <add>// Prints: 5634 <add>console.log(buf.readUInt16LE(1).toString(16)); <add> <add>// Throws an exception: RangeError: Index out of range <add>console.log(buf.readUInt16LE(2).toString(16)); <ide> ``` <ide> <ide> ### buf.readUInt32BE(offset[, noAssert]) <ide> Setting `noAssert` to `true` skips validation of the `offset`. This allows the <ide> Example: <ide> <ide> ```js <del>const buf = Buffer.from([0x3, 0x4, 0x23, 0x42]); <add>const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); <add> <add>// Prints: 12345678 <add>console.log(buf.readUInt32BE(0).toString(16)); <add> <add>// Prints: 78563412 <add>console.log(buf.readUInt32LE(0).toString(16)); <ide> <del>buf.readUInt32BE(0); <del> // Returns: 0x03042342 <del>console.log(buf.readUInt32LE(0)); <del> // Returns: 0x42230403 <add>// Throws an exception: RangeError: Index out of range <add>console.log(buf.readUInt32LE(1).toString(16)); <ide> ``` <ide> <ide> ### buf.readUIntBE(offset, byteLength[, noAssert]) <ide> and interprets the result as an unsigned integer. Supports up to 48 <ide> bits of accuracy. For example: <ide> <ide> ```js <del>const buf = Buffer.allocUnsafe(6); <del>buf.writeUInt16LE(0x90ab, 0); <del>buf.writeUInt32LE(0x12345678, 2); <del>buf.readUIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits) <del>// Returns: '1234567890ab' <add>const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); <add> <add>// Prints: 1234567890ab <add>console.log(buf.readUIntLE(0, 6).toString(16)); <add> <add>// Prints: ab9078563412 <add>console.log(buf.readUIntBE(0, 6).toString(16)); <ide> <del>buf.readUIntBE(0, 6).toString(16); <del>// Returns: ab9078563412 <add>// Throws an exception: RangeError: Index out of range <add>console.log(buf.readUIntBE(1, 6).toString(16)); <ide> ``` <ide> <ide> Setting `noAssert` to `true` skips validation of the `offset`. This allows the <ide> byte from the original Buffer. <ide> const buf1 = Buffer.allocUnsafe(26); <ide> <ide> for (var i = 0 ; i < 26 ; i++) { <del> buf1[i] = i + 97; // 97 is ASCII a <add> // 97 is the decimal ASCII value for 'a' <add> buf1[i] = i + 97; <ide> } <ide> <ide> const buf2 = buf1.slice(0, 3); <del>buf2.toString('ascii', 0, buf2.length); <del> // Returns: 'abc' <add> <add>// Prints: abc <add>console.log(buf2.toString('ascii', 0, buf2.length)); <add> <ide> buf1[0] = 33; <del>buf2.toString('ascii', 0, buf2.length); <del> // Returns : '!bc' <add> <add>// Prints: !bc <add>console.log(buf2.toString('ascii', 0, buf2.length)); <ide> ``` <ide> <ide> Specifying negative indexes causes the slice to be generated relative to the <ide> end of the Buffer rather than the beginning. <ide> ```js <ide> const buf = Buffer.from('buffer'); <ide> <del>buf.slice(-6, -1).toString(); <del> // Returns 'buffe', equivalent to buf.slice(0, 5) <del>buf.slice(-6, -2).toString(); <del> // Returns 'buff', equivalent to buf.slice(0, 4) <del>buf.slice(-5, -2).toString(); <del> // Returns 'uff', equivalent to buf.slice(1, 4) <add>// Prints: buffe <add>// (Equivalent to buf.slice(0, 5)) <add>console.log(buf.slice(-6, -1).toString()); <add> <add>// Prints: buff <add>// (Equivalent to buf.slice(0, 4)) <add>console.log(buf.slice(-6, -2).toString()); <add> <add>// Prints: uff <add>// (Equivalent to buf.slice(1, 4)) <add>console.log(buf.slice(-5, -2).toString()); <ide> ``` <ide> <ide> ### buf.swap16() <ide> not a multiple of 16 bits. The method returns a reference to the Buffer, so <ide> calls can be chained. <ide> <ide> ```js <del>const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); <del>console.log(buf); <del> // Prints <Buffer 01 02 03 04 05 06 07 08> <del>buf.swap16(); <del>console.log(buf); <del> // Prints <Buffer 02 01 04 03 06 05 08 07> <add>const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); <add> <add>// Prints: <Buffer 01 02 03 04 05 06 07 08> <add>console.log(buf1); <add> <add>buf1.swap16(); <add> <add>// Prints: <Buffer 02 01 04 03 06 05 08 07> <add>console.log(buf1); <add> <add> <add>const buf2 = Buffer.from([0x1, 0x2, 0x3]); <add> <add>// Throws an exception: RangeError: Buffer size must be a multiple of 16-bits <add>buf2.swap32(); <ide> ``` <ide> <ide> ### buf.swap32() <ide> not a multiple of 32 bits. The method returns a reference to the Buffer, so <ide> calls can be chained. <ide> <ide> ```js <del>const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); <del>console.log(buf); <del> // Prints <Buffer 01 02 03 04 05 06 07 08> <del>buf.swap32(); <del>console.log(buf); <del> // Prints <Buffer 04 03 02 01 08 07 06 05> <add>const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); <add> <add>// Prints <Buffer 01 02 03 04 05 06 07 08> <add>console.log(buf1); <add> <add>buf1.swap32(); <add> <add>// Prints <Buffer 04 03 02 01 08 07 06 05> <add>console.log(buf1); <add> <add> <add>const buf2 = Buffer.from([0x1, 0x2, 0x3]); <add> <add>// Throws an exception: RangeError: Buffer size must be a multiple of 32-bits <add>buf2.swap32(); <ide> ``` <ide> <ide> ### buf.swap64() <ide> not a multiple of 64 bits. The method returns a reference to the Buffer, so <ide> calls can be chained. <ide> <ide> ```js <del>const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); <del>console.log(buf); <del> // Prints <Buffer 01 02 03 04 05 06 07 08> <del>buf.swap64(); <del>console.log(buf); <del> // Prints <Buffer 08 07 06 05 04 03 02 01> <add>const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); <add> <add>// Prints <Buffer 01 02 03 04 05 06 07 08> <add>console.log(buf1); <add> <add>buf1.swap64(); <add> <add>// Prints <Buffer 08 07 06 05 04 03 02 01> <add>console.log(buf1); <add> <add> <add>const buf2 = Buffer.from([0x1, 0x2, 0x3]); <add> <add>// Throws an exception: RangeError: Buffer size must be a multiple of 64-bits <add>buf2.swap64(); <ide> ``` <ide> <ide> Note that JavaScript cannot encode 64-bit integers. This method is intended <ide> Decodes and returns a string from the Buffer data using the specified <ide> character set `encoding`. <ide> <ide> ```js <del>const buf = Buffer.allocUnsafe(26); <add>const buf1 = Buffer.allocUnsafe(26); <add> <ide> for (var i = 0 ; i < 26 ; i++) { <del> buf[i] = i + 97; // 97 is ASCII a <add> // 97 is the decimal ASCII value for 'a' <add> buf1[i] = i + 97; <ide> } <del>buf.toString('ascii'); <del> // Returns: 'abcdefghijklmnopqrstuvwxyz' <del>buf.toString('ascii',0,5); <del> // Returns: 'abcde' <del>buf.toString('utf8',0,5); <del> // Returns: 'abcde' <del>buf.toString(undefined,0,5); <del> // Returns: 'abcde', encoding defaults to 'utf8' <add> <add>// Prints: abcdefghijklmnopqrstuvwxyz <add>console.log(buf.toString('ascii')); <add> <add>// Prints: abcde <add>console.log(buf.toString('ascii', 0, 5)); <add> <add> <add>const buf2 = Buffer.from('tést'); <add> <add>// Prints: tés <add>console.log(buf.toString('utf8', 0, 3)); <add> <add>// Prints: tés <add>console.log(buf.toString(undefined, 0, 3)); <ide> ``` <ide> <ide> ### buf.toJSON() <ide> implicitly calls this function when stringifying a Buffer instance. <ide> Example: <ide> <ide> ```js <del>const buf = Buffer.from('test'); <add>const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); <ide> const json = JSON.stringify(buf); <ide> <add>// Prints: {"type":"Buffer","data":[1,2,3,4,5]} <ide> console.log(json); <del>// Prints: '{"type":"Buffer","data":[116,101,115,116]}' <ide> <ide> const copy = JSON.parse(json, (key, value) => { <del> return value && value.type === 'Buffer' <del> ? Buffer.from(value.data) <del> : value; <del> }); <add> return value && value.type === 'Buffer' <add> ? Buffer.from(value.data) <add> : value; <add>}); <ide> <del>console.log(copy.toString()); <del>// Prints: 'test' <add>// Prints: <Buffer 01 02 03 04 05> <add>console.log(copy); <ide> ``` <ide> <ide> ### buf.values() <ide> called automatically when the Buffer is used in a `for..of` statement. <ide> <ide> ```js <ide> const buf = Buffer.from('buffer'); <del>for (var value of buf.values()) { <del> console.log(value); <del>} <del>// prints: <add> <add>// Prints: <ide> // 98 <ide> // 117 <ide> // 102 <ide> // 102 <ide> // 101 <ide> // 114 <del> <del>for (var value of buf) { <add>for (var value of buf.values()) { <ide> console.log(value); <ide> } <del>// prints: <add> <add>// Prints: <ide> // 98 <ide> // 117 <ide> // 102 <ide> // 102 <ide> // 101 <ide> // 114 <add>for (var value of buf) { <add> console.log(value); <add>} <ide> ``` <ide> <ide> ### buf.write(string[, offset[, length]][, encoding]) <ide> characters. <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(256); <add> <ide> const len = buf.write('\u00bd + \u00bc = \u00be', 0); <add> <add>// Prints: 12 bytes: ½ + ¼ = ¾ <ide> console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); <del> // Prints: 12 bytes: ½ + ¼ = ¾ <ide> ``` <ide> <ide> ### buf.writeDoubleBE(value, offset[, noAssert]) <ide> Example: <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(8); <add> <ide> buf.writeDoubleBE(0xdeadbeefcafebabe, 0); <ide> <add>// Prints: <Buffer 43 eb d5 b7 dd f9 5f d7> <ide> console.log(buf); <del> // Prints: <Buffer 43 eb d5 b7 dd f9 5f d7> <ide> <ide> buf.writeDoubleLE(0xdeadbeefcafebabe, 0); <ide> <add>// Prints: <Buffer d7 5f f9 dd b7 d5 eb 43> <ide> console.log(buf); <del> // Prints: <Buffer d7 5f f9 dd b7 d5 eb 43> <ide> ``` <ide> <ide> ### buf.writeFloatBE(value, offset[, noAssert]) <ide> Example: <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(4); <add> <ide> buf.writeFloatBE(0xcafebabe, 0); <ide> <add>// Prints: <Buffer 4f 4a fe bb> <ide> console.log(buf); <del> // Prints: <Buffer 4f 4a fe bb> <ide> <ide> buf.writeFloatLE(0xcafebabe, 0); <ide> <add>// Prints: <Buffer bb fe 4a 4f> <ide> console.log(buf); <del> // Prints: <Buffer bb fe 4a 4f> <ide> ``` <ide> <ide> ### buf.writeInt8(value, offset[, noAssert]) <ide> The `value` is interpreted and written as a two's complement signed integer. <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(2); <add> <ide> buf.writeInt8(2, 0); <ide> buf.writeInt8(-2, 1); <add> <add>// Prints: <Buffer 02 fe> <ide> console.log(buf); <del> // Prints: <Buffer 02 fe> <ide> ``` <ide> <ide> ### buf.writeInt16BE(value, offset[, noAssert]) <ide> The `value` is interpreted and written as a two's complement signed integer. <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(4); <del>buf.writeInt16BE(0x0102,0); <del>buf.writeInt16LE(0x0304,2); <add> <add>buf.writeInt16BE(0x0102, 0); <add>buf.writeInt16LE(0x0304, 2); <add> <add>// Prints: <Buffer 01 02 04 03> <ide> console.log(buf); <del> // Prints: <Buffer 01 02 04 03> <ide> ``` <ide> <ide> ### buf.writeInt32BE(value, offset[, noAssert]) <ide> The `value` is interpreted and written as a two's complement signed integer. <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(8); <del>buf.writeInt32BE(0x01020304,0); <del>buf.writeInt32LE(0x05060708,4); <add> <add>buf.writeInt32BE(0x01020304, 0); <add>buf.writeInt32LE(0x05060708, 4); <add> <add>// Prints: <Buffer 01 02 03 04 08 07 06 05> <ide> console.log(buf); <del> // Prints: <Buffer 01 02 03 04 08 07 06 05> <ide> ``` <ide> <ide> ### buf.writeIntBE(value, offset, byteLength[, noAssert]) <ide> Writes `value` to the Buffer at the specified `offset` and `byteLength`. <ide> Supports up to 48 bits of accuracy. For example: <ide> <ide> ```js <del>const buf1 = Buffer.allocUnsafe(6); <del>buf1.writeUIntBE(0x1234567890ab, 0, 6); <del>console.log(buf1); <del> // Prints: <Buffer 12 34 56 78 90 ab> <add>const buf = Buffer.allocUnsafe(6); <ide> <del>const buf2 = Buffer.allocUnsafe(6); <del>buf2.writeUIntLE(0x1234567890ab, 0, 6); <del>console.log(buf2); <del> // Prints: <Buffer ab 90 78 56 34 12> <add>buf.writeUIntBE(0x1234567890ab, 0, 6); <add> <add>// Prints: <Buffer 12 34 56 78 90 ab> <add>console.log(buf); <add> <add>buf.writeUIntLE(0x1234567890ab, 0, 6); <add> <add>// Prints: <Buffer ab 90 78 56 34 12> <add>console.log(buf); <ide> ``` <ide> <ide> Set `noAssert` to true to skip validation of `value` and `offset`. This means <ide> Example: <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(4); <add> <ide> buf.writeUInt8(0x3, 0); <ide> buf.writeUInt8(0x4, 1); <ide> buf.writeUInt8(0x23, 2); <ide> buf.writeUInt8(0x42, 3); <ide> <add>// Prints: <Buffer 03 04 23 42> <ide> console.log(buf); <del> // Prints: <Buffer 03 04 23 42> <ide> ``` <ide> <ide> ### buf.writeUInt16BE(value, offset[, noAssert]) <ide> Example: <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(4); <add> <ide> buf.writeUInt16BE(0xdead, 0); <ide> buf.writeUInt16BE(0xbeef, 2); <ide> <add>// Prints: <Buffer de ad be ef> <ide> console.log(buf); <del> // Prints: <Buffer de ad be ef> <ide> <ide> buf.writeUInt16LE(0xdead, 0); <ide> buf.writeUInt16LE(0xbeef, 2); <ide> <add>// Prints: <Buffer ad de ef be> <ide> console.log(buf); <del> // Prints: <Buffer ad de ef be> <ide> ``` <ide> <ide> ### buf.writeUInt32BE(value, offset[, noAssert]) <ide> Example: <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(4); <add> <ide> buf.writeUInt32BE(0xfeedface, 0); <ide> <add>// Prints: <Buffer fe ed fa ce> <ide> console.log(buf); <del> // Prints: <Buffer fe ed fa ce> <ide> <ide> buf.writeUInt32LE(0xfeedface, 0); <ide> <add>// Prints: <Buffer ce fa ed fe> <ide> console.log(buf); <del> // Prints: <Buffer ce fa ed fe> <ide> ``` <ide> <ide> ### buf.writeUIntBE(value, offset, byteLength[, noAssert]) <ide> Supports up to 48 bits of accuracy. For example: <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(6); <add> <ide> buf.writeUIntBE(0x1234567890ab, 0, 6); <add> <add>// Prints: <Buffer 12 34 56 78 90 ab> <add>console.log(buf); <add> <add>buf.writeUIntLE(0x1234567890ab, 0, 6); <add> <add>// Prints: <Buffer ab 90 78 56 34 12> <ide> console.log(buf); <del> // Prints: <Buffer 12 34 56 78 90 ab> <ide> ``` <ide> <ide> Set `noAssert` to true to skip validation of `value` and `offset`. This means <ide> pool for an indeterminate amount of time, it may be appropriate to create an <ide> un-pooled Buffer instance using `SlowBuffer` then copy out the relevant bits. <ide> <ide> ```js <del>// need to keep around a few small chunks of memory <add>// Need to keep around a few small chunks of memory <ide> const store = []; <ide> <ide> socket.on('readable', () => { <del> var data = socket.read(); <del> // allocate for retained data <del> var sb = SlowBuffer(10); <del> // copy the data into the new allocation <add> const data = socket.read(); <add> <add> // Allocate for retained data <add> const sb = SlowBuffer(10); <add> <add> // Copy the data into the new allocation <ide> data.copy(sb, 0, 0, 10); <add> <ide> store.push(sb); <ide> }); <ide> ``` <ide> sensitive data. Use [`buf.fill(0)`][] to initialize a `SlowBuffer` to zeroes. <ide> <ide> ```js <ide> const SlowBuffer = require('buffer').SlowBuffer; <add> <ide> const buf = new SlowBuffer(5); <add> <add>// Prints (contents may vary): <Buffer 78 e0 82 02 01> <ide> console.log(buf); <del> // <Buffer 78 e0 82 02 01> <del> // (octets will be different, every time) <add> <ide> buf.fill(0); <add> <add>// Prints: <Buffer 00 00 00 00 00> <ide> console.log(buf); <del> // <Buffer 00 00 00 00 00> <ide> ``` <ide> <ide> [iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
1
Go
Go
fix network attachable option
abcb699ad175859ee192388c001f55df5f88e8cd
<ide><path>api/server/router/network/network_routes.go <ide> func (n *networkRouter) buildNetworkResource(nw libnetwork.Network) *types.Netwo <ide> r.Driver = nw.Type() <ide> r.EnableIPv6 = info.IPv6Enabled() <ide> r.Internal = info.Internal() <add> r.Attachable = info.Attachable() <ide> r.Options = info.DriverOptions() <ide> r.Containers = make(map[string]types.EndpointResource) <ide> buildIpamResources(r, info) <del> r.Internal = info.Internal() <ide> r.Labels = info.Labels() <ide> <ide> peers := info.Peers() <ide><path>daemon/cluster/executor/container/container.go <ide> func (c *containerConfig) networkCreateRequest(name string) (clustertypes.Networ <ide> Options: na.Network.DriverState.Options, <ide> Labels: na.Network.Spec.Annotations.Labels, <ide> Internal: na.Network.Spec.Internal, <add> Attachable: na.Network.Spec.Attachable, <ide> EnableIPv6: na.Network.Spec.Ipv6Enabled, <ide> CheckDuplicate: true, <ide> } <ide><path>daemon/network.go <ide> func (daemon *Daemon) createNetwork(create types.NetworkCreateRequest, id string <ide> libnetwork.NetworkOptionEnableIPv6(create.EnableIPv6), <ide> libnetwork.NetworkOptionDriverOpts(create.Options), <ide> libnetwork.NetworkOptionLabels(create.Labels), <add> libnetwork.NetworkOptionAttachable(create.Attachable), <ide> } <ide> <ide> if create.IPAM != nil { <ide><path>integration-cli/docker_cli_swarm_test.go <ide> func (s *DockerSwarmSuite) TestSwarmContainerAttachByNetworkId(c *check.C) { <ide> waitAndAssert(c, 3*time.Second, checkNetwork, checker.Not(checker.Contains), "testnet") <ide> } <ide> <add>func (s *DockerSwarmSuite) TestOverlayAttachable(c *check.C) { <add> d1 := s.AddDaemon(c, true, true) <add> d2 := s.AddDaemon(c, true, false) <add> <add> out, err := d1.Cmd("network", "create", "-d", "overlay", "--attachable", "ovnet") <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> <add> // validate attachable <add> out, err = d1.Cmd("network", "inspect", "--format", "{{json .Attachable}}", "ovnet") <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> c.Assert(strings.TrimSpace(out), checker.Equals, "true") <add> <add> // validate containers can attache to this overlay network <add> out, err = d1.Cmd("run", "-d", "--network", "ovnet", "--name", "c1", "busybox", "top") <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> out, err = d2.Cmd("run", "-d", "--network", "ovnet", "--name", "c2", "busybox", "top") <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> <add> // redo validation, there was a bug that the value of attachable changes after <add> // containers attach to the network <add> out, err = d1.Cmd("network", "inspect", "--format", "{{json .Attachable}}", "ovnet") <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> c.Assert(strings.TrimSpace(out), checker.Equals, "true") <add> out, err = d2.Cmd("network", "inspect", "--format", "{{json .Attachable}}", "ovnet") <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> c.Assert(strings.TrimSpace(out), checker.Equals, "true") <add>} <add> <ide> func (s *DockerSwarmSuite) TestSwarmRemoveInternalNetwork(c *check.C) { <ide> d := s.AddDaemon(c, true, true) <ide>
4
Python
Python
change resnetfpn as an internal class
95d8a879ea2ddc63c48deed3f8e28d55d1b3a2d5
<ide><path>research/object_detection/models/faster_rcnn_resnet_v1_fpn_keras_feature_extractor.py <ide> 'conv4_block36_out', 'conv5_block3_out'], <ide> } <ide> <del>class ResnetFPN(tf.keras.layers.Layer): <add>class _ResnetFPN(tf.keras.layers.Layer): <ide> """Construct Resnet FPN layer.""" <ide> <ide> def __init__(self, <ide> def __init__(self, <ide> resnet_block_names: a list of block names of resnet. <ide> base_fpn_max_level: maximum level of fpn without coarse feature layers. <ide> """ <del> super(ResnetFPN, self).__init__() <add> super(_ResnetFPN, self).__init__() <ide> self.classification_backbone = backbone_classifier <ide> self.fpn_features_generator = fpn_features_generator <ide> self.coarse_feature_layers = coarse_feature_layers <ide> def __init__(self, <ide> self._base_fpn_max_level = base_fpn_max_level <ide> <ide> def call(self, inputs): <del> """Create ResnetFPN layer. <add> """Create internal ResnetFPN layer. <ide> <ide> Args: <ide> inputs: A [batch, height_out, width_out, channels] float32 tensor <ide> def get_proposal_feature_extractor_model(self, name=None): <ide> name=layer_name)) <ide> self._coarse_feature_layers.append(layers) <ide> <del> feature_extractor_model = ResnetFPN(self.classification_backbone, <add> feature_extractor_model = _ResnetFPN(self.classification_backbone, <ide> self._fpn_features_generator, <ide> self._coarse_feature_layers, <ide> self._pad_to_multiple,
1
Go
Go
move "import" to graph/import.go
fa27580cff5f22bcf2a4860b5582c67d275a0e11
<ide><path>graph/import.go <add>package graph <add> <add>import ( <add> "net/http" <add> "net/url" <add> <add> "github.com/docker/docker/archive" <add> "github.com/docker/docker/engine" <add> "github.com/docker/docker/utils" <add>) <add> <add>func (s *TagStore) CmdImport(job *engine.Job) engine.Status { <add> if n := len(job.Args); n != 2 && n != 3 { <add> return job.Errorf("Usage: %s SRC REPO [TAG]", job.Name) <add> } <add> var ( <add> src = job.Args[0] <add> repo = job.Args[1] <add> tag string <add> sf = utils.NewStreamFormatter(job.GetenvBool("json")) <add> archive archive.ArchiveReader <add> resp *http.Response <add> ) <add> if len(job.Args) > 2 { <add> tag = job.Args[2] <add> } <add> <add> if src == "-" { <add> archive = job.Stdin <add> } else { <add> u, err := url.Parse(src) <add> if err != nil { <add> return job.Error(err) <add> } <add> if u.Scheme == "" { <add> u.Scheme = "http" <add> u.Host = src <add> u.Path = "" <add> } <add> job.Stdout.Write(sf.FormatStatus("", "Downloading from %s", u)) <add> resp, err = utils.Download(u.String()) <add> if err != nil { <add> return job.Error(err) <add> } <add> progressReader := utils.ProgressReader(resp.Body, int(resp.ContentLength), job.Stdout, sf, true, "", "Importing") <add> defer progressReader.Close() <add> archive = progressReader <add> } <add> img, err := s.graph.Create(archive, "", "", "Imported from "+src, "", nil, nil) <add> if err != nil { <add> return job.Error(err) <add> } <add> // Optionally register the image at REPO/TAG <add> if repo != "" { <add> if err := s.Set(repo, tag, img.ID, true); err != nil { <add> return job.Error(err) <add> } <add> } <add> job.Stdout.Write(sf.FormatStatus("", img.ID)) <add> return engine.StatusOK <add>} <ide><path>graph/service.go <ide> func (s *TagStore) Install(eng *engine.Engine) error { <ide> eng.Register("images", s.CmdImages) <ide> eng.Register("viz", s.CmdViz) <ide> eng.Register("load", s.CmdLoad) <add> eng.Register("import", s.CmdImport) <ide> return nil <ide> } <ide> <ide><path>server/image.go <ide> import ( <ide> "io" <ide> "io/ioutil" <ide> "net" <del> "net/http" <ide> "net/url" <ide> "os" <ide> "os/exec" <ide> func (srv *Server) ImagePush(job *engine.Job) engine.Status { <ide> return engine.StatusOK <ide> } <ide> <del>func (srv *Server) ImageImport(job *engine.Job) engine.Status { <del> if n := len(job.Args); n != 2 && n != 3 { <del> return job.Errorf("Usage: %s SRC REPO [TAG]", job.Name) <del> } <del> var ( <del> src = job.Args[0] <del> repo = job.Args[1] <del> tag string <del> sf = utils.NewStreamFormatter(job.GetenvBool("json")) <del> archive archive.ArchiveReader <del> resp *http.Response <del> ) <del> if len(job.Args) > 2 { <del> tag = job.Args[2] <del> } <del> <del> if src == "-" { <del> archive = job.Stdin <del> } else { <del> u, err := url.Parse(src) <del> if err != nil { <del> return job.Error(err) <del> } <del> if u.Scheme == "" { <del> u.Scheme = "http" <del> u.Host = src <del> u.Path = "" <del> } <del> job.Stdout.Write(sf.FormatStatus("", "Downloading from %s", u)) <del> resp, err = utils.Download(u.String()) <del> if err != nil { <del> return job.Error(err) <del> } <del> progressReader := utils.ProgressReader(resp.Body, int(resp.ContentLength), job.Stdout, sf, true, "", "Importing") <del> defer progressReader.Close() <del> archive = progressReader <del> } <del> img, err := srv.daemon.Graph().Create(archive, "", "", "Imported from "+src, "", nil, nil) <del> if err != nil { <del> return job.Error(err) <del> } <del> // Optionally register the image at REPO/TAG <del> if repo != "" { <del> if err := srv.daemon.Repositories().Set(repo, tag, img.ID, true); err != nil { <del> return job.Error(err) <del> } <del> } <del> job.Stdout.Write(sf.FormatStatus("", img.ID)) <del> return engine.StatusOK <del>} <ide> func (srv *Server) DeleteImage(name string, imgs *engine.Table, first, force, noprune bool) error { <ide> var ( <ide> repoName, tag string <ide><path>server/init.go <ide> func InitServer(job *engine.Job) engine.Status { <ide> "log": srv.Log, <ide> "build": srv.Build, <ide> "pull": srv.ImagePull, <del> "import": srv.ImageImport, <ide> "image_delete": srv.ImageDelete, <ide> "events": srv.Events, <ide> "push": srv.ImagePush,
4
Javascript
Javascript
remove more semicolons
236065d0f6122517936fc37218f01fb07fd13e34
<ide><path>spec/panel-container-element-spec.js <ide> describe('PanelContainerElement', () => { <ide> } <ide> <ide> it("focuses the first tabbable item if available", () => { <del> const panel = createPanel(); <add> const panel = createPanel() <ide> <ide> const panelEl = panel.getElement() <ide> const inputEl = document.createElement('input') <ide> describe('PanelContainerElement', () => { <ide> }) <ide> <ide> it("focuses the entire panel item when no tabbable item is available and the panel is focusable", () => { <del> const panel = createPanel(); <add> const panel = createPanel() <ide> const panelEl = panel.getElement() <ide> <ide> spyOn(panelEl, 'focus') <ide> describe('PanelContainerElement', () => { <ide> }) <ide> <ide> it("returns focus to the original activeElement", () => { <del> const panel = createPanel(); <add> const panel = createPanel() <ide> const previousActiveElement = document.activeElement <ide> const panelEl = panel.getElement() <ide> panelEl.appendChild(document.createElement('input'))
1
Ruby
Ruby
pass explicit sort to handle apfs
8a419b47426728c03c3835c1aafa72b5ecf56f4f
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit <ide> # Check style in a single batch run up front for performance <ide> style_results = check_style_json(files, options) <ide> <del> ff.each do |f| <add> ff.sort.each do |f| <ide> options = { new_formula: new_formula, strict: strict, online: online } <ide> options[:style_offenses] = style_results.file_offenses(f.path) <ide> fa = FormulaAuditor.new(f, options)
1
Text
Text
fix broken links after we moved projects
7ac0fe481ed1ca456c9b5d8ab8e37d9d48809bb6
<ide><path>official/README.md <ide> In the near future, we will add: <ide> <ide> | Model | Reference (Paper) | <ide> |-------|-------------------| <del>| [ALBERT (A Lite BERT)](nlp/albert) | [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942) | <del>| [BERT (Bidirectional Encoder Representations from Transformers)](nlp/bert) | [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) | <add>| [ALBERT (A Lite BERT)](nlp/MODEL_GARDEN.md#available-model-configs) | [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942) | <add>| [BERT (Bidirectional Encoder Representations from Transformers)](nlp/MODEL_GARDEN.md#available-model-configs) | [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) | <ide> | [NHNet (News Headline generation model)](projects/nhnet) | [Generating Representative Headlines for News Stories](https://arxiv.org/abs/2001.09386) | <ide> | [Transformer](nlp/transformer) | [Attention Is All You Need](https://arxiv.org/abs/1706.03762) | <ide> | [XLNet](nlp/xlnet) | [XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) | <del>| [MobileBERT](nlp/projects/mobilebert) | [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) | <add>| [MobileBERT](projects/mobilebert) | [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) | <ide> <ide> ### Recommendation <ide> <ide><path>official/nlp/README.md <ide> We provide SoTA model implementations, pre-trained models, training and <ide> evaluation examples, and command lines. Detail instructions can be found in the <ide> READMEs for specific papers. <ide> <del>1. [BERT](bert): [BERT: Pre-training of Deep Bidirectional Transformers for <add>1. [BERT](MODEL_GARDEN.md#available-model-configs): [BERT: Pre-training of Deep Bidirectional Transformers for <ide> Language Understanding](https://arxiv.org/abs/1810.04805) by Devlin et al., <ide> 2018 <del>2. [ALBERT](albert): <add>2. [ALBERT](MODEL_GARDEN.md#available-model-configs): <ide> [A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942) <ide> by Lan et al., 2019 <ide> 3. [XLNet](xlnet):
2
PHP
PHP
apply suggestions from code review
7753669388d4670a0e8f4a0372248e82ea56bd0b
<ide><path>src/TestSuite/Fixture/TransactionStrategy.php <ide> protected function aliasConnections(bool $enableLogging): void <ide> ConnectionManager::alias($testConnection, $normal); <ide> $connection = ConnectionManager::get($normal); <ide> if ($connection instanceof Connection) { <del> if (!$connection->enableSavePoints(true)) { <add> $connection->enableSavePoints(); <add> if (!$connection->isSavePointsEnabled()) { <ide> throw new RuntimeException( <ide> "Could not enable save points for the `{$normal}` connection. " . <ide> 'Your database needs to support savepoints in order to use the ' . <ide> 'TransactionStrategy for fixtures.' <ide> ); <ide> } <ide> if ($enableLogging) { <del> $connection->enableQueryLogging(true); <add> $connection->enableQueryLogging(); <ide> } <ide> } <ide> } <ide> public function afterTest(): void <ide> { <ide> $connections = ConnectionManager::configured(); <ide> foreach ($connections as $connection) { <del> if (strpos($connection, 'test') === false) { <add> if (strpos($connection, 'test') !== 0) { <ide> continue; <ide> } <ide> $db = ConnectionManager::get($connection);
1
Python
Python
improve pickling tests
a8d7d04449aedacade10633890f09b0d79634231
<ide><path>tests/test_model_pickling.py <ide> import numpy as np <ide> from numpy.testing import assert_allclose <ide> <del>from keras.models import Model, Sequential <del>from keras.layers import Dense, Lambda, RepeatVector, TimeDistributed <del>from keras.layers import Input <add>import keras <add>from keras import layers <ide> from keras import optimizers <ide> from keras import losses <ide> from keras import metrics <ide> <ide> <ide> def test_sequential_model_pickling(): <del> model = Sequential() <del> model.add(Dense(2, input_shape=(3,))) <del> model.add(RepeatVector(3)) <del> model.add(TimeDistributed(Dense(3))) <add> model = keras.Sequential() <add> model.add(layers.Dense(2, input_shape=(3,))) <add> model.add(layers.RepeatVector(3)) <add> model.add(layers.TimeDistributed(layers.Dense(3))) <ide> model.compile(loss=losses.MSE, <ide> optimizer=optimizers.RMSprop(lr=0.0001), <ide> metrics=[metrics.categorical_accuracy], <ide> def test_sequential_model_pickling(): <ide> assert_allclose(out, out2, atol=1e-05) <ide> <ide> <del>def test_sequential_model_pickling_2(): <add>def test_sequential_model_pickling_custom_objects(): <ide> # test with custom optimizer, loss <del> custom_opt = optimizers.rmsprop <del> custom_loss = losses.mse <del> model = Sequential() <del> model.add(Dense(2, input_shape=(3,))) <del> model.add(Dense(3)) <del> model.compile(loss=custom_loss, optimizer=custom_opt(), metrics=['acc']) <add> class CustomSGD(optimizers.SGD): <add> pass <add> <add> def custom_mse(*args, **kwargs): <add> return losses.mse(*args, **kwargs) <add> <add> model = keras.Sequential() <add> model.add(layers.Dense(2, input_shape=(3,))) <add> model.add(layers.Dense(3)) <add> model.compile(loss=custom_mse, optimizer=CustomSGD(), metrics=['acc']) <ide> <ide> x = np.random.random((1, 3)) <ide> y = np.random.random((1, 3)) <ide> def test_sequential_model_pickling_2(): <ide> out = model.predict(x) <ide> <ide> state = pickle.dumps(model) <del> model = pickle.loads(state) <add> <add> with keras.utils.CustomObjectScope( <add> {'CustomSGD': CustomSGD, 'custom_mse': custom_mse}): <add> model = pickle.loads(state) <ide> <ide> out2 = model.predict(x) <ide> assert_allclose(out, out2, atol=1e-05) <ide> <ide> <ide> def test_functional_model_pickling(): <del> inputs = Input(shape=(3,)) <del> x = Dense(2)(inputs) <del> outputs = Dense(3)(x) <add> inputs = keras.Input(shape=(3,)) <add> x = layers.Dense(2)(inputs) <add> outputs = layers.Dense(3)(x) <ide> <del> model = Model(inputs, outputs) <add> model = keras.Model(inputs, outputs) <ide> model.compile(loss=losses.MSE, <ide> optimizer=optimizers.Adam(), <ide> metrics=[metrics.categorical_accuracy]) <ide> def test_functional_model_pickling(): <ide> <ide> <ide> def test_pickling_multiple_metrics_outputs(): <del> inputs = Input(shape=(5,)) <del> x = Dense(5)(inputs) <del> output1 = Dense(1, name='output1')(x) <del> output2 = Dense(1, name='output2')(x) <add> inputs = keras.Input(shape=(5,)) <add> x = layers.Dense(5)(inputs) <add> output1 = layers.Dense(1, name='output1')(x) <add> output2 = layers.Dense(1, name='output2')(x) <ide> <del> model = Model(inputs=inputs, outputs=[output1, output2]) <add> model = keras.Model(inputs=inputs, outputs=[output1, output2]) <ide> <ide> metrics = {'output1': ['mse', 'binary_accuracy'], <ide> 'output2': ['mse', 'binary_accuracy'] <ide> def test_pickling_multiple_metrics_outputs(): <ide> def test_pickling_without_compilation(): <ide> """Test pickling model without compiling. <ide> """ <del> model = Sequential() <del> model.add(Dense(2, input_shape=(3,))) <del> model.add(Dense(3)) <add> model = keras.Sequential() <add> model.add(layers.Dense(2, input_shape=(3,))) <add> model.add(layers.Dense(3)) <ide> <ide> model = pickle.loads(pickle.dumps(model)) <ide> <ide> <ide> def test_pickling_right_after_compilation(): <del> model = Sequential() <del> model.add(Dense(2, input_shape=(3,))) <del> model.add(Dense(3)) <add> model = keras.Sequential() <add> model.add(layers.Dense(2, input_shape=(3,))) <add> model.add(layers.Dense(3)) <ide> model.compile(loss='mse', optimizer='sgd', metrics=['acc']) <ide> model._make_train_function() <ide> <ide> model = pickle.loads(pickle.dumps(model)) <ide> <ide> <del>def test_pickling_unused_layers_is_ok(): <del> a = Input(shape=(256, 512, 6)) <del> b = Input(shape=(256, 512, 1)) <del> c = Lambda(lambda x: x[:, :, :, :1])(a) <del> <del> model = Model(inputs=[a, b], outputs=c) <del> <del> model = pickle.loads(pickle.dumps(model)) <del> <del> <ide> if __name__ == '__main__': <ide> pytest.main([__file__])
1
Python
Python
remove task group mapping for now
9322c3e5f2b849878a995bd54311351ec6dedfa3
<ide><path>airflow/decorators/task_group.py <ide> together when the DAG is displayed graphically. <ide> """ <ide> import functools <del>import warnings <ide> from inspect import signature <ide> from typing import TYPE_CHECKING, Any, Callable, Dict, Generic, Optional, TypeVar, Union, cast, overload <ide> <ide> import attr <ide> <del>from airflow.utils.task_group import MappedTaskGroup, TaskGroup <add>from airflow.utils.task_group import TaskGroup <ide> <ide> if TYPE_CHECKING: <ide> from airflow.models.dag import DAG <ide> def __call__(self, *args, **kwargs) -> Union[R, TaskGroup]: <ide> # start >> tg >> end <ide> return task_group <ide> <del> def partial(self, **kwargs) -> "MappedTaskGroupDecorator[R]": <del> return MappedTaskGroupDecorator(function=self.function, kwargs=self.kwargs).partial(**kwargs) <del> <del> def expand(self, **kwargs) -> Union[R, TaskGroup]: <del> return MappedTaskGroupDecorator(function=self.function, kwargs=self.kwargs).expand(**kwargs) <del> <del> <del>@attr.define <del>class MappedTaskGroupDecorator(TaskGroupDecorator[R]): <del> """:meta private:""" <del> <del> partial_kwargs: Dict[str, Any] = attr.ib(factory=dict) <del> """static kwargs for the decorated function""" <del> mapped_kwargs: Dict[str, Any] = attr.ib(factory=dict) <del> """kwargs for the decorated function""" <del> <del> def __call__(self, *args, **kwargs): <del> raise RuntimeError("A mapped @task_group cannot be called. Use `.map` and `.partial` instead") <del> <del> def _make_task_group(self, **kwargs) -> MappedTaskGroup: <del> tg = MappedTaskGroup(**kwargs) <del> tg.partial_kwargs = self.partial_kwargs <del> tg.mapped_kwargs = self.mapped_kwargs <del> return tg <del> <del> def partial(self, **kwargs) -> "MappedTaskGroupDecorator[R]": <del> duplicated_keys = [k for k in kwargs if k in self.partial_kwargs] <del> if len(duplicated_keys) == 1: <del> raise ValueError(f"Cannot overwrite partial argument: {duplicated_keys[0]!r}") <del> elif duplicated_keys: <del> joined = ", ".join(repr(k) for k in duplicated_keys) <del> raise ValueError(f"Cannot overwrite partial arguments: {joined}") <del> self.partial_kwargs.update(kwargs) <del> return self <del> <del> def expand(self, **kwargs) -> Union[R, TaskGroup]: <del> if self.mapped_kwargs: <del> raise RuntimeError("Already a mapped task group") <del> self.mapped_kwargs = kwargs <del> <del> call_kwargs = self.partial_kwargs.copy() <del> duplicated_keys = set(call_kwargs).intersection(kwargs) <del> if duplicated_keys: <del> raise RuntimeError(f"Cannot map partial arguments: {', '.join(sorted(duplicated_keys))}") <del> call_kwargs.update({k: object() for k in kwargs}) <del> <del> return super().__call__(**call_kwargs) <del> <del> def __del__(self): <del> if not self.mapped_kwargs: <del> warnings.warn(f"Partial task group {self.function.__name__} was never mapped!") <del> <ide> <ide> class Group(Generic[F]): <ide> """Declaration of a @task_group-decorated callable for type-checking. <ide><path>airflow/models/baseoperator.py <ide> class derived from this one results in the creation of a task object, <ide> # Set to True for an operator instantiated by a mapped operator. <ide> __from_mapped = False <ide> <del> def __new__( <del> cls, <del> dag: Optional['DAG'] = None, <del> task_group: Optional["TaskGroup"] = None, <del> _airflow_from_mapped: bool = False, # Whether called from a MappedOperator. <del> **kwargs, <del> ): <del> # If we are creating a new Task _and_ we are in the context of a MappedTaskGroup, then we should only <del> # create mapped operators. <del> from airflow.models.dag import DagContext <del> from airflow.utils.task_group import MappedTaskGroup, TaskGroupContext <del> <del> dag = dag or DagContext.get_current_dag() <del> task_group = task_group or TaskGroupContext.get_current_task_group(dag) <del> <del> if not _airflow_from_mapped and isinstance(task_group, MappedTaskGroup): <del> return cls.partial(dag=dag, task_group=task_group, **kwargs).expand() <del> return super().__new__(cls) <del> <ide> def __init__( <ide> self, <ide> task_id: str, <ide><path>airflow/models/taskmixin.py <ide> def mapped_dependants(self) -> Iterator["DAGNode"]: <ide> provide a way to record an DAG node's all downstream nodes instead. <ide> """ <ide> from airflow.models.mappedoperator import MappedOperator <del> from airflow.utils.task_group import MappedTaskGroup, TaskGroup <add> from airflow.utils.task_group import TaskGroup <ide> <ide> def _walk_group(group: TaskGroup) -> Iterable[Tuple[str, DAGNode]]: <ide> """Recursively walk children in a task group. <ide> def _walk_group(group: TaskGroup) -> Iterable[Tuple[str, DAGNode]]: <ide> for key, child in _walk_group(tg): <ide> if key == self.node_id: <ide> continue <del> if not isinstance(child, (MappedOperator, MappedTaskGroup)): <add> if not isinstance(child, MappedOperator): <ide> continue <ide> if self.node_id in child.upstream_task_ids: <ide> yield child <ide><path>airflow/serialization/serialized_objects.py <ide> from airflow.utils.docs import get_docs_url <ide> from airflow.utils.module_loading import as_importable_string, import_string <ide> from airflow.utils.operator_resources import Resources <del>from airflow.utils.task_group import MappedTaskGroup, TaskGroup <add>from airflow.utils.task_group import TaskGroup <ide> <ide> if TYPE_CHECKING: <ide> from airflow.ti_deps.deps.base_ti_dep import BaseTIDep <ide> def serialize_task_group(cls, task_group: TaskGroup) -> Optional[Dict[str, Any]] <ide> "downstream_task_ids": cls._serialize(sorted(task_group.downstream_task_ids)), <ide> } <ide> <del> if isinstance(task_group, MappedTaskGroup): <del> if task_group.mapped_arg: <del> serialize_group['mapped_arg'] = cls._serialize(task_group.mapped_arg) <del> if task_group.mapped_kwargs: <del> serialize_group['mapped_arg'] = cls._serialize(task_group.mapped_kwargs) <del> if task_group.partial_kwargs: <del> serialize_group['mapped_arg'] = cls._serialize(task_group.partial_kwargs) <del> <ide> return serialize_group <ide> <ide> @classmethod <ide><path>airflow/utils/task_group.py <ide> import copy <ide> import re <ide> import weakref <del>from typing import TYPE_CHECKING, Any, Dict, Generator, Iterable, List, Optional, Sequence, Set, Tuple, Union <add>from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Sequence, Set, Tuple, Union <ide> <ide> from airflow.exceptions import AirflowDagCycleException, AirflowException, DuplicateTaskIdFound <ide> from airflow.models.taskmixin import DAGNode, DependencyMixin <ide> from airflow.serialization.enums import DagAttributeTypes <ide> from airflow.utils.helpers import validate_group_key <del>from airflow.utils.types import NOTSET <ide> <ide> if TYPE_CHECKING: <ide> from airflow.models.baseoperator import BaseOperator <ide> def serialize_for_task_group(self) -> Tuple[DagAttributeTypes, Any]: <ide> <ide> return DagAttributeTypes.TASK_GROUP, SerializedTaskGroup.serialize_task_group(self) <ide> <del> def expand(self, arg: Iterable) -> "MappedTaskGroup": <del> if self.children: <del> raise RuntimeError("Cannot map a TaskGroup that already has children") <del> if not self.group_id: <del> raise RuntimeError("Cannot map a TaskGroup before it has a group_id") <del> if self.task_group: <del> self.task_group._remove(self) <del> return MappedTaskGroup(group_id=self._group_id, dag=self.dag, mapped_arg=arg) <del> <ide> def topological_sort(self, _include_subdag_tasks: bool = False): <ide> """ <ide> Sorts children in topographical order, such that a task comes after any of its <ide> def topological_sort(self, _include_subdag_tasks: bool = False): <ide> return graph_sorted <ide> <ide> <del>class MappedTaskGroup(TaskGroup): <del> """ <del> A TaskGroup that is dynamically expanded at run time. <del> <del> Do not create instances of this class directly, instead use :meth:`TaskGroup.map` <del> """ <del> <del> mapped_arg: Any = NOTSET <del> mapped_kwargs: Dict[str, Any] <del> partial_kwargs: Dict[str, Any] <del> <del> def __init__(self, group_id: Optional[str] = None, mapped_arg: Any = NOTSET, **kwargs): <del> if mapped_arg is not NOTSET: <del> self.mapped_arg = mapped_arg <del> self.mapped_kwargs = {} <del> self.partial_kwargs = {} <del> super().__init__(group_id=group_id, **kwargs) <del> <del> <ide> class TaskGroupContext: <ide> """TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager.""" <ide> <ide><path>tests/serialization/test_dag_serialization.py <ide> from airflow.operators.bash import BashOperator <ide> from airflow.security import permissions <ide> from airflow.serialization.json_schema import load_dag_schema_dict <del>from airflow.serialization.serialized_objects import ( <del> SerializedBaseOperator, <del> SerializedDAG, <del> SerializedTaskGroup, <del>) <add>from airflow.serialization.serialized_objects import SerializedBaseOperator, SerializedDAG <ide> from airflow.timetables.simple import NullTimetable, OnceTimetable <ide> from airflow.utils import timezone <ide> from airflow.utils.context import Context <ide> def x(arg1, arg2, arg3): <ide> "op_kwargs": {"arg1": [1, 2, {"a": "b"}]}, <ide> "retry_delay": timedelta(seconds=30), <ide> } <del> <del> <del>def test_mapped_task_group_serde(): <del> execution_date = datetime(2020, 1, 1) <del> <del> literal = [1, 2, {'a': 'b'}] <del> with DAG("test", start_date=execution_date) as dag: <del> with TaskGroup("process_one", dag=dag).expand(literal) as process_one: <del> BaseOperator(task_id='one') <del> <del> serialized = SerializedTaskGroup.serialize_task_group(process_one) <del> <del> assert serialized == { <del> '_group_id': 'process_one', <del> 'children': {'process_one.one': ('operator', 'process_one.one')}, <del> 'downstream_group_ids': [], <del> 'downstream_task_ids': [], <del> 'prefix_group_id': True, <del> 'tooltip': '', <del> 'ui_color': 'CornflowerBlue', <del> 'ui_fgcolor': '#000', <del> 'upstream_group_ids': [], <del> 'upstream_task_ids': [], <del> 'mapped_arg': [ <del> 1, <del> 2, <del> {"__type": "dict", "__var": {'a': 'b'}}, <del> ], <del> } <del> <del> with DAG("test", start_date=execution_date) as new_dag: <del> SerializedTaskGroup.deserialize_task_group(serialized, None, dag.task_dict, new_dag) <ide><path>tests/utils/test_task_group.py <ide> <ide> from airflow.decorators import dag, task_group as task_group_decorator <ide> from airflow.models import DAG <del>from airflow.models.mappedoperator import MappedOperator <ide> from airflow.models.xcom_arg import XComArg <ide> from airflow.operators.bash import BashOperator <ide> from airflow.operators.dummy import DummyOperator <ide> from airflow.operators.python import PythonOperator <ide> from airflow.utils.dates import days_ago <del>from airflow.utils.task_group import MappedTaskGroup, TaskGroup <add>from airflow.utils.task_group import TaskGroup <ide> from airflow.www.views import dag_edges, task_group_to_dict <ide> from tests.models import DEFAULT_DATE <del>from tests.test_utils.mock_operators import MockOperator <ide> <ide> EXPECTED_JSON = { <ide> 'id': None, <ide> def wrap(): <ide> wrap() <ide> <ide> <del>def test_map() -> None: <del> with DAG("test-dag", start_date=DEFAULT_DATE) as dag: <del> start = MockOperator(task_id="start") <del> end = MockOperator(task_id="end") <del> literal = ['a', 'b', 'c'] <del> with TaskGroup("process_one").expand(literal) as process_one: <del> one = MockOperator(task_id='one') <del> two = MockOperator(task_id='two') <del> three = MockOperator(task_id='three') <del> <del> one >> two >> three <del> <del> start >> process_one >> end <del> <del> # check the mapped operators are attached to the task broup <del> assert isinstance(process_one, MappedTaskGroup) <del> assert process_one.has_task(one) <del> assert process_one.mapped_arg is literal <del> <del> assert isinstance(one, MappedOperator) <del> assert start.downstream_list == [one] <del> assert one in dag.tasks <del> # At parse time there should only be two tasks! <del> assert len(dag.tasks) == 5 <del> <del> assert end.upstream_list == [three] <del> assert three.downstream_list == [end] <del> <del> <del>def test_nested_map() -> None: <del> with DAG("test-dag", start_date=DEFAULT_DATE): <del> start = MockOperator(task_id="start") <del> end = MockOperator(task_id="end") <del> literal = ['a', 'b', 'c'] <del> with TaskGroup("process_one").expand(literal) as process_one: <del> one = MockOperator(task_id='one') <del> <del> with TaskGroup("process_two").expand(literal) as process_one_two: <del> two = MockOperator(task_id='two') <del> three = MockOperator(task_id='three') <del> two >> three <del> <del> four = MockOperator(task_id='four') <del> one >> process_one_two >> four <del> <del> start >> process_one >> end <del> <del> <ide> def test_decorator_unknown_args(): <ide> """Test that unknown args passed to the decorator cause an error at parse time""" <ide> with pytest.raises(TypeError): <ide> def tg(): <ide> ] <ide> <ide> <del>def test_decorator_partial_unmapped(): <del> @task_group_decorator <del> def tg(): <del> ... <del> <del> with pytest.warns(UserWarning, match='was never mapped'): <del> with DAG("test-dag", start_date=DEFAULT_DATE): <del> tg.partial() <del> <del> <del>def test_decorator_map(): <del> @task_group_decorator <del> def my_task_group(my_arg_1: str, unmapped: bool): <del> assert unmapped is True <del> assert isinstance(my_arg_1, object) <del> task_1 = DummyOperator(task_id="task_1") <del> task_2 = BashOperator(task_id="task_2", bash_command='echo "${my_arg_1}"', env={'my_arg_1': my_arg_1}) <del> task_3 = DummyOperator(task_id="task_3") <del> task_1 >> [task_2, task_3] <del> <del> return task_1, task_2, task_3 <del> <del> with DAG("test-dag", start_date=DEFAULT_DATE) as dag: <del> lines = ["foo", "bar", "baz"] <del> <del> (task_1, task_2, task_3) = my_task_group.partial(unmapped=True).expand(my_arg_1=lines) <del> <del> assert task_1 in dag.tasks <del> <del> tg = dag.task_group.get_child_by_label("my_task_group") <del> assert isinstance(tg, MappedTaskGroup) <del> assert "my_arg_1" in tg.mapped_kwargs <del> <del> <ide> def test_topological_sort1(): <ide> dag = DAG('dag', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) <ide>
7
Ruby
Ruby
convert uninstall test to spec
4de74bf744ff3006da32bf592735718fec9798d6
<add><path>Library/Homebrew/cask/spec/cask/artifact/uninstall_spec.rb <del><path>Library/Homebrew/cask/test/cask/artifact/uninstall_test.rb <del>require "test_helper" <add>require "spec_helper" <ide> <ide> describe Hbc::Artifact::Uninstall do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-installable.rb") } <ide> Hbc::Artifact::Uninstall.new(cask, command: Hbc::FakeSystemCommand) <ide> } <ide> <del> before do <add> before(:each) do <ide> shutup do <del> TestHelper.install_without_artifacts(cask) <add> InstallHelper.install_without_artifacts(cask) <ide> end <ide> end <ide> <ide> end <ide> } <ide> <del> describe "when using launchctl" do <add> context "when using launchctl" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-uninstall-launchctl.rb") } <ide> let(:launchctl_list_cmd) { %w[/bin/launchctl list my.fancy.package.service] } <ide> let(:launchctl_remove_cmd) { %w[/bin/launchctl remove my.fancy.package.service] } <ide> EOS <ide> } <ide> <del> describe "when launchctl job is owned by user" do <add> context "when launchctl job is owned by user" do <ide> it "can uninstall" do <ide> Hbc::FakeSystemCommand.stubs_command( <ide> launchctl_list_cmd, <ide> end <ide> end <ide> <del> describe "when launchctl job is owned by system" do <add> context "when launchctl job is owned by system" do <ide> it "can uninstall" do <ide> Hbc::FakeSystemCommand.stubs_command( <ide> launchctl_list_cmd, <ide> end <ide> end <ide> <del> describe "when using pkgutil" do <add> context "when using pkgutil" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-uninstall-pkgutil.rb") } <ide> let(:main_pkg_id) { "my.fancy.package.main" } <ide> let(:agent_pkg_id) { "my.fancy.package.agent" } <ide> end <ide> end <ide> <del> describe "when using kext" do <add> context "when using kext" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-uninstall-kext.rb") } <ide> let(:kext_id) { "my.fancy.package.kernelextension" } <ide> <ide> end <ide> end <ide> <del> describe "when using quit" do <add> context "when using quit" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-uninstall-quit.rb") } <ide> let(:bundle_id) { "my.fancy.package.app" } <ide> let(:quit_application_script) { <ide> end <ide> end <ide> <del> describe "when using signal" do <add> context "when using signal" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-uninstall-signal.rb") } <ide> let(:bundle_id) { "my.fancy.package.app" } <ide> let(:signals) { %w[TERM KILL] } <ide> ) <ide> <ide> signals.each do |signal| <del> Process.expects(:kill).with(signal, *unix_pids) <add> expect(Process).to receive(:kill).with(signal, *unix_pids) <ide> end <ide> <ide> subject <ide> end <ide> end <ide> <del> describe "when using delete" do <add> context "when using delete" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-uninstall-delete.rb") } <ide> <ide> it "can uninstall" do <ide> end <ide> end <ide> <del> describe "when using trash" do <add> context "when using trash" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-uninstall-trash.rb") } <ide> <ide> it "can uninstall" do <ide> end <ide> end <ide> <del> describe "when using rmdir" do <add> context "when using rmdir" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-uninstall-rmdir.rb") } <ide> let(:dir_pathname) { Pathname.new("#{TEST_FIXTURE_DIR}/cask/empty_directory") } <ide> <ide> end <ide> end <ide> <del> describe "when using script" do <add> context "when using script" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-uninstall-script.rb") } <ide> let(:script_pathname) { cask.staged_path.join("MyFancyPkg", "FancyUninstaller.tool") } <ide> <ide> end <ide> end <ide> <del> describe "when using early_script" do <add> context "when using early_script" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-uninstall-early-script.rb") } <ide> let(:script_pathname) { cask.staged_path.join("MyFancyPkg", "FancyUninstaller.tool") } <ide> <ide> end <ide> end <ide> <del> describe "when using login_item" do <add> context "when using login_item" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-uninstall-login-item.rb") } <ide> <ide> it "can uninstall" do
1
Java
Java
update todos for spr-11574
b640b9fdfe2c1d554aa2bb8ea38401d20c2ed2dd
<ide><path>spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java <ide> public void postProcessorWorksWithComposedConfigurationWithAttributeOverridesUsi <ide> postProcessorWorksWithComposedConfigurationWithAttributeOverrides(beanDefinition); <ide> } <ide> <del> // TODO Remove expected exception when SPR-XXXXX is resolved. <add> // TODO Remove expected exception when SPR-11574 is resolved. <ide> @Test(expected = ConflictingBeanDefinitionException.class) <ide> public void postProcessorWorksWithComposedConfigurationWithAttributeOverridesUsingAsm() { <ide> RootBeanDefinition beanDefinition = new RootBeanDefinition( <ide> public void postProcessorWorksWithComposedComposedConfigurationWithAttributeOver <ide> postProcessorWorksWithComposedComposedConfigurationWithAttributeOverrides(beanDefinition); <ide> } <ide> <del> // TODO Remove expected exception when SPR-XXXXX is resolved. <add> // TODO Remove expected exception when SPR-11574 is resolved. <ide> @Test(expected = ConflictingBeanDefinitionException.class) <ide> public void postProcessorWorksWithComposedComposedConfigurationWithAttributeOverridesUsingAsm() { <ide> RootBeanDefinition beanDefinition = new RootBeanDefinition( <ide> public void postProcessorWorksWithMetaComponentScanConfigurationWithAttributeOve <ide> postProcessorWorksWithMetaComponentScanConfigurationWithAttributeOverrides(beanDefinition); <ide> } <ide> <del> // TODO Remove expected exception when SPR-XXXXX is resolved. <add> // TODO Remove expected exception when SPR-11574 is resolved. <ide> @Test(expected = ConflictingBeanDefinitionException.class) <ide> public void postProcessorWorksWithMetaComponentScanConfigurationWithAttributeOverridesUsingAsm() { <ide> RootBeanDefinition beanDefinition = new RootBeanDefinition( <ide> public void postProcessorWorksWithMetaComponentScanConfigurationWithAttributeOve <ide> postProcessorWorksWithMetaComponentScanConfigurationWithAttributeOverridesSubclass(beanDefinition); <ide> } <ide> <del> // TODO Remove expected exception when SPR-XXXXX is resolved. <add> // TODO Remove expected exception when SPR-11574 is resolved. <ide> @Test(expected = ConflictingBeanDefinitionException.class) <ide> public void postProcessorWorksWithMetaComponentScanConfigurationWithAttributeOverridesSubclassUsingAsm() { <ide> RootBeanDefinition beanDefinition = new RootBeanDefinition(
1
Javascript
Javascript
use react.lazy in suspense fixture
6d5d250bef88115ceceb906d0cab1d60ea996d7b
<ide><path>fixtures/unstable-async/suspense/src/components/App.js <del>import React, {unstable_Suspense as Suspense, PureComponent} from 'react'; <add>import React, {lazy, unstable_Suspense as Suspense, PureComponent} from 'react'; <ide> import {unstable_scheduleCallback} from 'scheduler'; <ide> import { <ide> unstable_trace as trace, <ide> unstable_wrap as wrap, <ide> } from 'scheduler/tracing'; <del>import {createResource} from 'react-cache'; <del>import {cache} from '../cache'; <ide> import Spinner from './Spinner'; <ide> import ContributorListPage from './ContributorListPage'; <ide> <del>const UserPageResource = createResource(() => import('./UserPage')); <del> <del>function UserPageLoader(props) { <del> const UserPage = UserPageResource.read(cache).default; <del> return <UserPage {...props} />; <del>} <add>const UserPage = lazy(() => import('./UserPage')); <ide> <ide> export default class App extends PureComponent { <ide> state = { <ide> export default class App extends PureComponent { <ide> Return to list <ide> </button> <ide> <Suspense maxDuration={2000} fallback={<Spinner size="large" />}> <del> <UserPageLoader id={id} /> <add> <UserPage id={id} /> <ide> </Suspense> <ide> </div> <ide> );
1
Python
Python
remove close method from memmap docstring
8a38f647215acc63bc2e953103f5d649a7c093f9
<ide><path>numpy/core/memmap.py <ide> class memmap(ndarray): <ide> This class may at some point be turned into a factory function <ide> which returns a view into an mmap buffer. <ide> <add> Delete the memmap instance to close. <add> <add> <ide> Parameters <ide> ---------- <ide> filename : str or file-like object <ide> class memmap(ndarray): <ide> <ide> Methods <ide> ------- <del> close <del> Close the memmap file. <ide> flush <ide> Flush any changes in memory to file on disk. <ide> When you delete a memmap object, flush is called first to write
1
PHP
PHP
fix mocks that were violating documented types
68afc0060723b40eee986385a64003bb62535620
<ide><path>src/Datasource/ResultSetDecorator.php <ide> class ResultSetDecorator extends Collection implements ResultSetInterface <ide> * <ide> * @return int <ide> */ <del> public function count() <add> public function count(): int <ide> { <ide> if ($this->getInnerIterator() instanceof Countable) { <ide> return $this->getInnerIterator()->count(); <ide><path>tests/TestCase/ORM/QueryTest.php <ide> */ <ide> namespace Cake\Test\TestCase\ORM; <ide> <add>use Cake\Collection\Collection; <ide> use Cake\Database\Expression\IdentifierExpression; <ide> use Cake\Database\Expression\OrderByExpression; <ide> use Cake\Database\Expression\QueryExpression; <add>use Cake\Database\StatementInterface; <ide> use Cake\Database\TypeMap; <ide> use Cake\Database\ValueBinder; <ide> use Cake\Datasource\ConnectionManager; <ide> public function testSetResult() <ide> { <ide> $query = new Query($this->connection, $this->table); <ide> <del> $stmt = $this->getMockBuilder('Cake\Database\StatementInterface')->getMock(); <add> $stmt = $this->getMockBuilder(StatementInterface::class)->getMock(); <add> $stmt->method('rowCount') <add> ->will($this->returnValue(9)); <ide> $results = new ResultSet($query, $stmt); <ide> $query->setResult($results); <ide> $this->assertSame($results, $query->all()); <ide> public function collectionMethodsProvider() <ide> $identity = function ($a) { <ide> return $a; <ide> }; <add> $collection = new Collection([]); <ide> <ide> return [ <del> ['filter', $identity], <del> ['reject', $identity], <del> ['every', $identity], <del> ['some', $identity], <del> ['contains', $identity], <del> ['map', $identity], <del> ['reduce', $identity], <del> ['extract', $identity], <del> ['max', $identity], <del> ['min', $identity], <del> ['sortBy', $identity], <del> ['groupBy', $identity], <del> ['countBy', $identity], <del> ['shuffle', $identity], <del> ['sample', $identity], <del> ['take', 1], <del> ['append', new \ArrayIterator], <del> ['compile', 1], <add> ['filter', $identity, $collection], <add> ['reject', $identity, $collection], <add> ['every', $identity, false], <add> ['some', $identity, false], <add> ['contains', $identity, true], <add> ['map', $identity, $collection], <add> ['reduce', $identity, $collection], <add> ['extract', $identity, $collection], <add> ['max', $identity, 9], <add> ['min', $identity, 1], <add> ['sortBy', $identity, $collection], <add> ['groupBy', $identity, $collection], <add> ['countBy', $identity, $collection], <add> ['shuffle', $identity, $collection], <add> ['sample', 10, $collection], <add> ['take', 1, $collection], <add> ['append', new \ArrayIterator, $collection], <add> ['compile', 1, $collection], <ide> ]; <ide> } <ide> <ide> public function testClearContain() <ide> * @dataProvider collectionMethodsProvider <ide> * @return void <ide> */ <del> public function testCollectionProxy($method, $arg) <add> public function testCollectionProxy($method, $arg, $return) <ide> { <ide> $query = $this->getMockBuilder('\Cake\ORM\Query') <ide> ->setMethods(['all']) <ide> public function testCollectionProxy($method, $arg) <ide> ->will($this->returnValue($resultSet)); <ide> $resultSet->expects($this->once()) <ide> ->method($method) <del> ->with($arg, 'extra') <del> ->will($this->returnValue(new \Cake\Collection\Collection([]))); <del> $this->assertInstanceOf( <del> '\Cake\Collection\Collection', <del> $query->{$method}($arg, 'extra') <del> ); <add> ->with($arg, 99) <add> ->will($this->returnValue($return)); <add> <add> $this->assertSame($return, $query->{$method}($arg, 99)); <ide> } <ide> <ide> /**
2
Ruby
Ruby
dump foreign keys to schema.rb
69c711f38cac85e9c8bdbe286591bf88ef720bfa
<ide><path>activerecord/lib/active_record/migration.rb <ide> def method_missing(method, *arguments, &block) <ide> unless @connection.respond_to? :revert <ide> unless arguments.empty? || [:execute, :enable_extension, :disable_extension].include?(method) <ide> arguments[0] = proper_table_name(arguments.first, table_name_options) <del> arguments[1] = proper_table_name(arguments.second, table_name_options) if method == :rename_table <add> if [:rename_table, :add_foreign_key].include?(method) <add> arguments[1] = proper_table_name(arguments.second, table_name_options) <add> end <ide> end <ide> end <ide> return super unless connection.respond_to?(method) <ide><path>activerecord/lib/active_record/schema_dumper.rb <ide> def table(table, stream) <ide> <ide> indexes(table, tbl) <ide> <add> foreign_keys(table, tbl) <add> <ide> tbl.rewind <ide> stream.print tbl.read <ide> rescue => e <ide> def indexes(table, stream) <ide> end <ide> end <ide> <add> def foreign_keys(table, stream) <add> return unless @connection.supports_foreign_keys? <add> <add> if (foreign_keys = @connection.foreign_keys(table)).any? <add> add_foreign_key_statements = foreign_keys.map do |foreign_key| <add> parts = [ <add> 'add_foreign_key ' + remove_prefix_and_suffix(foreign_key.from_table).inspect, <add> remove_prefix_and_suffix(foreign_key.to_table).inspect, <add> 'column: ' + foreign_key.column.inspect, <add> 'primary_key: ' + foreign_key.primary_key.inspect, <add> 'name: ' + foreign_key.name.inspect <add> ] <add> ' ' + parts.join(', ') <add> end <add> <add> stream.puts add_foreign_key_statements.sort.join("\n") <add> stream.puts <add> end <add> end <add> <ide> def remove_prefix_and_suffix(table) <ide> table.gsub(/^(#{@options[:table_name_prefix]})(.+)(#{@options[:table_name_suffix]})$/, "\\2") <ide> end <ide><path>activerecord/test/cases/migration/foreign_key_test.rb <ide> require 'cases/helper' <ide> require 'support/ddl_helper' <add>require 'support/schema_dumping_helper' <ide> <ide> if ActiveRecord::Base.connection.supports_foreign_keys? <ide> module ActiveRecord <ide> class Migration <ide> class ForeignKeyTest < ActiveRecord::TestCase <ide> include DdlHelper <add> include SchemaDumpingHelper <ide> <ide> class Rocket < ActiveRecord::Base <ide> end <ide> def test_remove_foreign_key_by_name <ide> @connection.remove_foreign_key :astronauts, name: "fancy_named_fk" <ide> assert_equal [], @connection.foreign_keys("astronauts") <ide> end <add> <add> def test_schema_dumping <add> output = dump_table_schema "fk_test_has_fk" <add> assert_match %r{\s+add_foreign_key "fk_test_has_fk", "fk_test_has_pk", column: "fk_id", primary_key: "id", name: "fk_name"$}, output <add> end <ide> end <ide> end <ide> end <ide><path>activerecord/test/cases/schema_dumper_test.rb <ide> def test_schema_dump_keeps_id_false_when_id_is_false_and_unique_not_null_column_ <ide> <ide> class CreateDogMigration < ActiveRecord::Migration <ide> def up <add> create_table("dog_owners") do |t| <add> end <add> <ide> create_table("dogs") do |t| <ide> t.column :name, :string <add> t.column :owner_id, :integer <ide> end <ide> add_index "dogs", [:name] <add> add_foreign_key :dogs, :dog_owners, column: "owner_id" if supports_foreign_keys? <ide> end <ide> def down <ide> drop_table("dogs") <add> drop_table("dog_owners") <ide> end <ide> end <ide> <ide> def test_schema_dump_with_table_name_prefix_and_suffix <ide> assert_no_match %r{create_table "foo_.+_bar"}, output <ide> assert_no_match %r{add_index "foo_.+_bar"}, output <ide> assert_no_match %r{create_table "schema_migrations"}, output <add> <add> if ActiveRecord::Base.connection.supports_foreign_keys? <add> assert_no_match %r{add_foreign_key "foo_.+_bar"}, output <add> assert_no_match %r{add_foreign_key "[^"]+", "foo_.+_bar"}, output <add> end <ide> ensure <ide> migration.migrate(:down) <ide> <ide> ActiveRecord::Base.table_name_suffix = ActiveRecord::Base.table_name_prefix = '' <ide> $stdout = original <ide> end <del> <ide> end <ide> <ide> class SchemaDumperDefaultsTest < ActiveRecord::TestCase
4
Python
Python
fix ec2 volume encryption
61c3e50374519212e4bc04e0f0c276054e58ec34
<ide><path>libcloud/compute/drivers/ec2.py <ide> def destroy_node(self, node): <ide> <ide> def create_volume(self, size, name, location=None, snapshot=None, <ide> ex_volume_type='standard', ex_iops=None, <del> ex_encrypted=None, ex_kms_key_id=None): <add> ex_encrypted=False, ex_kms_key_id=None): <ide> """ <ide> Create a new volume. <ide> <ide> def create_volume(self, size, name, location=None, snapshot=None, <ide> if ex_volume_type == 'io1' and ex_iops: <ide> params['Iops'] = ex_iops <ide> <del> if ex_encrypted is not None: <add> if ex_encrypted: <ide> params['Encrypted'] = 1 <ide> <del> if ex_kms_key_id is not None: <del> params['KmsKeyId'] = ex_kms_key_id <add> if ex_kms_key_id is not None: <add> params['KmsKeyId'] = ex_kms_key_id <ide> <ide> volume = self._to_volume( <ide> self.connection.request(self.path, params=params).object,
1
Java
Java
unbreak the build
287cf070cb1c072bd5fdacc0b1ee3ae85c7a388e
<ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeAccessibilityManagerSpec.java <ide> public NativeAccessibilityManagerSpec(ReactApplicationContext reactContext) { <ide> public abstract void getCurrentReduceTransparencyState(Callback onSuccess, Callback onError); <ide> <ide> @ReactMethod <del> public abstract void getCurrentInvertColorsState(Callback onSuccess, Callback onError); <add> public abstract void getCurrentBoldTextState(Callback onSuccess, Callback onError); <ide> <ide> @ReactMethod <ide> public abstract void getCurrentGrayscaleState(Callback onSuccess, Callback onError); <ide> <ide> @ReactMethod <del> public abstract void getCurrentBoldTextState(Callback onSuccess, Callback onError); <add> public abstract void getCurrentInvertColorsState(Callback onSuccess, Callback onError); <ide> <ide> @ReactMethod <ide> public abstract void setAccessibilityFocus(double reactTag); <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeAnimatedModuleSpec.java <ide> public NativeAnimatedModuleSpec(ReactApplicationContext reactContext) { <ide> } <ide> <ide> @ReactMethod <del> public abstract void dropAnimatedNode(double tag); <add> public abstract void connectAnimatedNodes(double parentTag, double childTag); <ide> <ide> @ReactMethod <del> public abstract void connectAnimatedNodes(double parentTag, double childTag); <add> public abstract void dropAnimatedNode(double tag); <ide> <ide> @ReactMethod <ide> public abstract void stopAnimation(double animationId); <ide> <add> @ReactMethod <add> public abstract void disconnectAnimatedNodeFromView(double nodeTag, double viewTag); <add> <ide> @ReactMethod <ide> public abstract void removeListeners(double count); <ide> <ide> @ReactMethod <del> public abstract void disconnectAnimatedNodeFromView(double nodeTag, double viewTag); <add> public abstract void flattenAnimatedNodeOffset(double nodeTag); <ide> <ide> @ReactMethod <ide> public abstract void removeAnimatedEventFromView(double viewTag, String eventName, <ide> double animatedNodeTag); <ide> <ide> @ReactMethod <del> public abstract void flattenAnimatedNodeOffset(double nodeTag); <add> public abstract void disconnectAnimatedNodes(double parentTag, double childTag); <ide> <ide> @ReactMethod <ide> public abstract void extractAnimatedNodeOffset(double nodeTag); <ide> <del> @ReactMethod <del> public abstract void disconnectAnimatedNodes(double parentTag, double childTag); <del> <ide> @ReactMethod <ide> public abstract void setAnimatedNodeValue(double nodeTag, double value); <ide> <ide> public abstract void removeAnimatedEventFromView(double viewTag, String eventNam <ide> @ReactMethod <ide> public abstract void setAnimatedNodeOffset(double nodeTag, double offset); <ide> <del> @ReactMethod <del> public abstract void restoreDefaultValues(double nodeTag); <del> <ide> @ReactMethod <ide> public abstract void startAnimatingNode(double animationId, double nodeTag, ReadableMap config, <ide> Callback endCallback); <ide> <add> @ReactMethod <add> public abstract void restoreDefaultValues(double nodeTag); <add> <ide> @ReactMethod <ide> public abstract void getValue(double tag, Callback saveValueCallback); <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeAnimatedTurboModuleSpec.java <ide> public NativeAnimatedTurboModuleSpec(ReactApplicationContext reactContext) { <ide> } <ide> <ide> @ReactMethod <del> public abstract void dropAnimatedNode(double tag); <add> public abstract void connectAnimatedNodes(double parentTag, double childTag); <ide> <ide> @ReactMethod <del> public abstract void connectAnimatedNodes(double parentTag, double childTag); <add> public abstract void dropAnimatedNode(double tag); <ide> <ide> @ReactMethod <ide> public abstract void stopAnimation(double animationId); <ide> <add> @ReactMethod <add> public abstract void disconnectAnimatedNodeFromView(double nodeTag, double viewTag); <add> <ide> @ReactMethod <ide> public abstract void removeListeners(double count); <ide> <ide> @ReactMethod <del> public abstract void disconnectAnimatedNodeFromView(double nodeTag, double viewTag); <add> public abstract void flattenAnimatedNodeOffset(double nodeTag); <ide> <ide> @ReactMethod <ide> public abstract void removeAnimatedEventFromView(double viewTag, String eventName, <ide> double animatedNodeTag); <ide> <ide> @ReactMethod <del> public abstract void flattenAnimatedNodeOffset(double nodeTag); <add> public abstract void disconnectAnimatedNodes(double parentTag, double childTag); <ide> <ide> @ReactMethod <ide> public abstract void extractAnimatedNodeOffset(double nodeTag); <ide> <del> @ReactMethod <del> public abstract void disconnectAnimatedNodes(double parentTag, double childTag); <del> <ide> @ReactMethod <ide> public abstract void setAnimatedNodeValue(double nodeTag, double value); <ide> <ide> public abstract void removeAnimatedEventFromView(double viewTag, String eventNam <ide> @ReactMethod <ide> public abstract void setAnimatedNodeOffset(double nodeTag, double offset); <ide> <del> @ReactMethod <del> public abstract void restoreDefaultValues(double nodeTag); <del> <ide> @ReactMethod <ide> public abstract void startAnimatingNode(double animationId, double nodeTag, ReadableMap config, <ide> Callback endCallback); <ide> <add> @ReactMethod <add> public abstract void restoreDefaultValues(double nodeTag); <add> <ide> @ReactMethod <ide> public abstract void getValue(double tag, Callback saveValueCallback); <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeAppearanceSpec.java <ide> public NativeAppearanceSpec(ReactApplicationContext reactContext) { <ide> @ReactMethod <ide> public abstract void removeListeners(double count); <ide> <del> @ReactMethod <del> public abstract void addListener(String eventName); <del> <ide> @ReactMethod( <ide> isBlockingSynchronousMethod = true <ide> ) <ide> public abstract @Nullable String getColorScheme(); <add> <add> @ReactMethod <add> public abstract void addListener(String eventName); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeAsyncStorageSpec.java <ide> public NativeAsyncStorageSpec(ReactApplicationContext reactContext) { <ide> @ReactMethod <ide> public abstract void multiSet(ReadableArray kvPairs, Callback callback); <ide> <del> @ReactMethod <del> public abstract void getAllKeys(Callback callback); <del> <ide> @ReactMethod <ide> public abstract void multiGet(ReadableArray keys, Callback callback); <ide> <ide> @ReactMethod <del> public abstract void clear(Callback callback); <add> public abstract void getAllKeys(Callback callback); <ide> <ide> @ReactMethod <ide> public abstract void multiMerge(ReadableArray kvPairs, Callback callback); <ide> <add> @ReactMethod <add> public abstract void clear(Callback callback); <add> <ide> @ReactMethod <ide> public abstract void multiRemove(ReadableArray keys, Callback callback); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeBlobModuleSpec.java <ide> public NativeBlobModuleSpec(ReactApplicationContext reactContext) { <ide> public abstract void addNetworkingHandler(); <ide> <ide> @ReactMethod <del> public abstract void createFromParts(ReadableArray parts, String withId); <add> public abstract void addWebSocketHandler(double id); <ide> <ide> @ReactMethod <del> public abstract void addWebSocketHandler(double id); <add> public abstract void createFromParts(ReadableArray parts, String withId); <ide> <ide> @ReactMethod <ide> public abstract void release(String blobId); <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeDevSettingsSpec.java <ide> public void onFastRefresh() { <ide> } <ide> <ide> @ReactMethod <del> public abstract void removeListeners(double count); <add> public abstract void reload(); <ide> <ide> @ReactMethod <del> public abstract void reload(); <add> public abstract void removeListeners(double count); <ide> <ide> @ReactMethod <ide> public abstract void setProfilingEnabled(boolean isProfilingEnabled); <ide> public void onFastRefresh() { <ide> public abstract void addMenuItem(String title); <ide> <ide> @ReactMethod <del> public abstract void toggleElementInspector(); <add> public abstract void setHotLoadingEnabled(boolean isHotLoadingEnabled); <ide> <ide> @ReactMethod <del> public abstract void setHotLoadingEnabled(boolean isHotLoadingEnabled); <add> public abstract void toggleElementInspector(); <ide> <ide> @ReactMethod <ide> public void reloadWithReason(String reason) { <ide> } <ide> <ide> @ReactMethod <del> public abstract void setIsShakeToShowDevMenuEnabled(boolean enabled); <add> public abstract void addListener(String eventName); <ide> <ide> @ReactMethod <del> public abstract void addListener(String eventName); <add> public abstract void setIsShakeToShowDevMenuEnabled(boolean enabled); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeExceptionsManagerSpec.java <ide> public void dismissRedbox() { <ide> } <ide> <ide> @ReactMethod <del> public abstract void updateExceptionMessage(String message, ReadableArray stack, <add> public abstract void reportFatalException(String message, ReadableArray stack, <ide> double exceptionId); <ide> <ide> @ReactMethod <ide> public void reportException(ReadableMap data) { <ide> } <ide> <ide> @ReactMethod <del> public abstract void reportFatalException(String message, ReadableArray stack, <add> public abstract void updateExceptionMessage(String message, ReadableArray stack, <ide> double exceptionId); <ide> <ide> @ReactMethod <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeImageLoaderAndroidSpec.java <ide> public NativeImageLoaderAndroidSpec(ReactApplicationContext reactContext) { <ide> } <ide> <ide> @ReactMethod <del> public abstract void getSize(String uri, Promise promise); <add> public abstract void abortRequest(double requestId); <ide> <ide> @ReactMethod <del> public abstract void abortRequest(double requestId); <add> public abstract void getSize(String uri, Promise promise); <ide> <ide> @ReactMethod <ide> public abstract void prefetchImage(String uri, double requestId, Promise promise); <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeImagePickerIOSSpec.java <ide> public abstract void openCameraDialog(ReadableMap config, Callback successCallba <ide> Callback cancelCallback); <ide> <ide> @ReactMethod <del> public abstract void openSelectDialog(ReadableMap config, Callback successCallback, <del> Callback cancelCallback); <add> public abstract void canUseCamera(Callback callback); <ide> <ide> @ReactMethod <del> public abstract void canUseCamera(Callback callback); <add> public abstract void openSelectDialog(ReadableMap config, Callback successCallback, <add> Callback cancelCallback); <ide> <ide> @ReactMethod <ide> public abstract void canRecordVideos(Callback callback); <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeLinkingSpec.java <ide> public NativeLinkingSpec(ReactApplicationContext reactContext) { <ide> } <ide> <ide> @ReactMethod <del> public abstract void sendIntent(String action, ReadableArray extras, Promise promise); <add> public abstract void openURL(String url, Promise promise); <ide> <ide> @ReactMethod <del> public abstract void openURL(String url, Promise promise); <add> public abstract void sendIntent(String action, ReadableArray extras, Promise promise); <ide> <ide> @ReactMethod <ide> public abstract void removeListeners(double count); <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativePermissionsAndroidSpec.java <ide> public NativePermissionsAndroidSpec(ReactApplicationContext reactContext) { <ide> } <ide> <ide> @ReactMethod <del> public abstract void requestPermission(String permission, Promise promise); <add> public abstract void checkPermission(String permission, Promise promise); <ide> <ide> @ReactMethod <del> public abstract void checkPermission(String permission, Promise promise); <add> public abstract void requestPermission(String permission, Promise promise); <ide> <ide> @ReactMethod <ide> public abstract void shouldShowRequestPermissionRationale(String permission, Promise promise); <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativePushNotificationManagerIOSSpec.java <ide> public NativePushNotificationManagerIOSSpec(ReactApplicationContext reactContext <ide> } <ide> <ide> @ReactMethod <del> public abstract void removeListeners(double count); <add> public abstract void getInitialNotification(Promise promise); <ide> <ide> @ReactMethod <del> public abstract void getInitialNotification(Promise promise); <add> public abstract void removeListeners(double count); <ide> <ide> @ReactMethod <ide> public abstract void setApplicationIconBadgeNumber(double num); <ide> public NativePushNotificationManagerIOSSpec(ReactApplicationContext reactContext <ide> public abstract void scheduleLocalNotification(ReadableMap notification); <ide> <ide> @ReactMethod <del> public abstract void getScheduledLocalNotifications(Callback callback); <add> public abstract void requestPermissions(ReadableMap permission, Promise promise); <ide> <ide> @ReactMethod <ide> public abstract void checkPermissions(Callback callback); <ide> <ide> @ReactMethod <del> public abstract void requestPermissions(ReadableMap permission, Promise promise); <add> public abstract void getScheduledLocalNotifications(Callback callback); <ide> <ide> @ReactMethod <ide> public abstract void removeAllDeliveredNotifications(); <ide> <ide> @ReactMethod <ide> public abstract void onFinishRemoteNotification(String notificationId, String fetchResult); <ide> <del> @ReactMethod <del> public abstract void cancelLocalNotifications(ReadableMap userInfo); <del> <ide> @ReactMethod <ide> public abstract void abandonPermissions(); <ide> <ide> @ReactMethod <del> public abstract void removeDeliveredNotifications(ReadableArray identifiers); <add> public abstract void cancelLocalNotifications(ReadableMap userInfo); <ide> <ide> @ReactMethod <ide> public abstract void cancelAllLocalNotifications(); <ide> <add> @ReactMethod <add> public abstract void removeDeliveredNotifications(ReadableArray identifiers); <add> <ide> @ReactMethod <ide> public abstract void getDeliveredNotifications(Callback callback); <ide> <ide> @ReactMethod <ide> public abstract void getApplicationIconBadgeNumber(Callback callback); <ide> <ide> @ReactMethod <del> public abstract void addListener(String eventType); <add> public abstract void presentLocalNotification(ReadableMap notification); <ide> <ide> @ReactMethod <del> public abstract void presentLocalNotification(ReadableMap notification); <add> public abstract void addListener(String eventType); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeToastAndroidSpec.java <ide> public NativeToastAndroidSpec(ReactApplicationContext reactContext) { <ide> } <ide> <ide> @ReactMethod <del> public abstract void showWithGravityAndOffset(String message, double duration, double gravity, <del> double xOffset, double yOffset); <add> public abstract void show(String message, double duration); <ide> <ide> @ReactMethod <del> public abstract void show(String message, double duration); <add> public abstract void showWithGravityAndOffset(String message, double duration, double gravity, <add> double xOffset, double yOffset); <ide> <ide> @ReactMethod <ide> public abstract void showWithGravity(String message, double duration, double gravity); <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeUIManagerSpec.java <ide> public abstract void configureNextLayoutAnimation(ReadableMap config, Callback c <ide> Callback errorCallback); <ide> <ide> @ReactMethod <del> public abstract void blur(Double reactTag); <add> public abstract void focus(Double reactTag); <ide> <ide> @ReactMethod <del> public abstract void focus(Double reactTag); <add> public abstract void blur(Double reactTag); <ide> <ide> @ReactMethod <ide> public abstract void removeSubviewsFromContainerWithID(double containerID); <ide> <ide> @ReactMethod <ide> public abstract void setJSResponder(Double reactTag, boolean blockNativeResponder); <ide> <del> @ReactMethod <del> public abstract void clearJSResponder(); <del> <ide> @ReactMethod <ide> public abstract void measureLayout(Double reactTag, Double ancestorReactTag, <ide> Callback errorCallback, Callback callback); <ide> <add> @ReactMethod <add> public abstract void clearJSResponder(); <add> <ide> @ReactMethod( <ide> isBlockingSynchronousMethod = true <ide> ) <ide> public abstract void dispatchViewManagerCommand(Double reactTag, double commandI <ide> public abstract void createView(Double reactTag, String viewName, double rootTag, <ide> ReadableMap props); <ide> <del> @ReactMethod <del> public abstract void sendAccessibilityEvent(Double reactTag, double eventType); <del> <ide> @ReactMethod <ide> public abstract void measureInWindow(Double reactTag, Callback callback); <ide> <ide> @ReactMethod <del> public abstract void viewIsDescendantOf(Double reactTag, Double ancestorReactTag, <del> Callback callback); <add> public abstract void sendAccessibilityEvent(Double reactTag, double eventType); <ide> <ide> @ReactMethod( <ide> isBlockingSynchronousMethod = true <ide> ) <ide> public abstract WritableMap lazilyLoadView(String name); <ide> <add> @ReactMethod <add> public abstract void viewIsDescendantOf(Double reactTag, Double ancestorReactTag, <add> Callback callback); <add> <ide> @ReactMethod <ide> public abstract void findSubviewIn(Double reactTag, ReadableArray point, Callback callback); <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeWebSocketModuleSpec.java <ide> public NativeWebSocketModuleSpec(ReactApplicationContext reactContext) { <ide> public abstract void ping(double socketID); <ide> <ide> @ReactMethod <del> public abstract void close(double code, String reason, double socketID); <add> public abstract void send(String message, double forSocketID); <ide> <ide> @ReactMethod <del> public abstract void send(String message, double forSocketID); <add> public abstract void close(double code, String reason, double socketID); <ide> <ide> @ReactMethod <ide> public abstract void connect(String url, ReadableArray protocols, ReadableMap options,
16
Mixed
Javascript
implement minimal `console.group()`
c40229a9b80736f1fdb31fac169b70a1d6af8669
<ide><path>doc/api/console.md <ide> If formatting elements (e.g. `%d`) are not found in the first string then <ide> [`util.inspect()`][] is called on each argument and the resulting string <ide> values are concatenated. See [`util.format()`][] for more information. <ide> <add>### console.group([...label]) <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* `label` {any} <add> <add>Increases indentation of subsequent lines by two spaces. <add> <add>If one or more `label`s are provided, those are printed first without the <add>additional indentation. <add> <add>### console.groupCollapsed() <add><!-- YAML <add> added: REPLACEME <add>--> <add> <add>An alias for [`console.group()`][]. <add> <add>### console.groupEnd() <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>Decreases indentation of subsequent lines by two spaces. <add> <ide> ### console.info([data][, ...args]) <ide> <!-- YAML <ide> added: v0.1.100 <ide> added: v0.1.100 <ide> The `console.warn()` function is an alias for [`console.error()`][]. <ide> <ide> [`console.error()`]: #console_console_error_data_args <add>[`console.group()`]: #console_console_group_label <ide> [`console.log()`]: #console_console_log_data_args <ide> [`console.time()`]: #console_console_time_label <ide> [`console.timeEnd()`]: #console_console_timeend_label <ide><path>lib/console.js <ide> const errors = require('internal/errors'); <ide> const util = require('util'); <ide> const kCounts = Symbol('counts'); <ide> <add>// Track amount of indentation required via `console.group()`. <add>const kGroupIndent = Symbol('groupIndent'); <add> <ide> function Console(stdout, stderr, ignoreErrors = true) { <ide> if (!(this instanceof Console)) { <ide> return new Console(stdout, stderr, ignoreErrors); <ide> function Console(stdout, stderr, ignoreErrors = true) { <ide> Object.defineProperty(this, '_stderrErrorHandler', prop); <ide> <ide> this[kCounts] = new Map(); <add> this[kGroupIndent] = ''; <ide> <ide> // bind the prototype functions to this Console instance <ide> var keys = Object.keys(Console.prototype); <ide> function write(ignoreErrors, stream, string, errorhandler) { <ide> Console.prototype.log = function log(...args) { <ide> write(this._ignoreErrors, <ide> this._stdout, <del> `${util.format.apply(null, args)}\n`, <add> `${this[kGroupIndent]}${util.format.apply(null, args)}\n`, <ide> this._stdoutErrorHandler); <ide> }; <ide> <ide> Console.prototype.info = Console.prototype.log; <ide> Console.prototype.warn = function warn(...args) { <ide> write(this._ignoreErrors, <ide> this._stderr, <del> `${util.format.apply(null, args)}\n`, <add> `${this[kGroupIndent]}${util.format.apply(null, args)}\n`, <ide> this._stderrErrorHandler); <ide> }; <ide> <ide> Console.prototype.dir = function dir(object, options) { <ide> options = Object.assign({ customInspect: false }, options); <ide> write(this._ignoreErrors, <ide> this._stdout, <del> `${util.inspect(object, options)}\n`, <add> `${this[kGroupIndent]}${util.inspect(object, options)}\n`, <ide> this._stdoutErrorHandler); <ide> }; <ide> <ide> Console.prototype.countReset = function countReset(label = 'default') { <ide> counts.delete(`${label}`); <ide> }; <ide> <add>Console.prototype.group = function group(...data) { <add> if (data.length > 0) { <add> this.log(...data); <add> } <add> this[kGroupIndent] += ' '; <add>}; <add> <add>Console.prototype.groupCollapsed = Console.prototype.group; <add> <add>Console.prototype.groupEnd = function groupEnd() { <add> this[kGroupIndent] = <add> this[kGroupIndent].slice(0, this[kGroupIndent].length - 2); <add>}; <add> <ide> module.exports = new Console(process.stdout, process.stderr); <ide> module.exports.Console = Console; <ide> <ide><path>test/parallel/test-console-group.js <add>'use strict'; <add>const common = require('../common'); <add> <add>const assert = require('assert'); <add>const Console = require('console').Console; <add> <add>let c, stdout, stderr; <add> <add>function setup() { <add> stdout = ''; <add> common.hijackStdout(function(data) { <add> stdout += data; <add> }); <add> <add> stderr = ''; <add> common.hijackStderr(function(data) { <add> stderr += data; <add> }); <add> <add> c = new Console(process.stdout, process.stderr); <add>} <add> <add>function teardown() { <add> common.restoreStdout(); <add> common.restoreStderr(); <add>} <add> <add>// Basic group() functionality <add>{ <add> setup(); <add> const expectedOut = 'This is the outer level\n' + <add> ' Level 2\n' + <add> ' Level 3\n' + <add> ' Back to level 2\n' + <add> 'Back to the outer level\n' + <add> 'Still at the outer level\n'; <add> <add> <add> const expectedErr = ' More of level 3\n'; <add> <add> c.log('This is the outer level'); <add> c.group(); <add> c.log('Level 2'); <add> c.group(); <add> c.log('Level 3'); <add> c.warn('More of level 3'); <add> c.groupEnd(); <add> c.log('Back to level 2'); <add> c.groupEnd(); <add> c.log('Back to the outer level'); <add> c.groupEnd(); <add> c.log('Still at the outer level'); <add> <add> assert.strictEqual(stdout, expectedOut); <add> assert.strictEqual(stderr, expectedErr); <add> teardown(); <add>} <add> <add>// Group indentation is tracked per Console instance. <add>{ <add> setup(); <add> const expectedOut = 'No indentation\n' + <add> 'None here either\n' + <add> ' Now the first console is indenting\n' + <add> 'But the second one does not\n'; <add> const expectedErr = ''; <add> <add> const c2 = new Console(process.stdout, process.stderr); <add> c.log('No indentation'); <add> c2.log('None here either'); <add> c.group(); <add> c.log('Now the first console is indenting'); <add> c2.log('But the second one does not'); <add> <add> assert.strictEqual(stdout, expectedOut); <add> assert.strictEqual(stderr, expectedErr); <add> teardown(); <add>} <add> <add>// Make sure labels work. <add>{ <add> setup(); <add> const expectedOut = 'This is a label\n' + <add> ' And this is the data for that label\n'; <add> const expectedErr = ''; <add> <add> c.group('This is a label'); <add> c.log('And this is the data for that label'); <add> <add> assert.strictEqual(stdout, expectedOut); <add> assert.strictEqual(stderr, expectedErr); <add> teardown(); <add>} <add> <add>// Check that console.groupCollapsed() is an alias of console.group() <add>{ <add> setup(); <add> const expectedOut = 'Label\n' + <add> ' Level 2\n' + <add> ' Level 3\n'; <add> const expectedErr = ''; <add> <add> c.groupCollapsed('Label'); <add> c.log('Level 2'); <add> c.groupCollapsed(); <add> c.log('Level 3'); <add> <add> assert.strictEqual(stdout, expectedOut); <add> assert.strictEqual(stderr, expectedErr); <add> teardown(); <add>}
3
Python
Python
remove un-necessary import
0d4e67d58d86bdc0bf500ccd4abfe25ad5f48448
<ide><path>numpy/fft/fftpack.py <ide> from numpy.core import asarray, zeros, swapaxes, shape, conjugate, \ <ide> take <ide> import fftpack_lite as fftpack <del>from helper import * <ide> <ide> _fft_cache = {} <ide> _real_fft_cache = {}
1
Javascript
Javascript
use countdown in test-http-set-cookies
6a089f93572b5f408c13ef0d833f4cdf826e2e24
<ide><path>test/parallel/test-http-set-cookies.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <add>const Countdown = require('../common/countdown'); <ide> <del>let nresponses = 0; <del> <add>const countdown = new Countdown(2, () => server.close()); <ide> const server = http.createServer(function(req, res) { <ide> if (req.url === '/one') { <ide> res.writeHead(200, [['set-cookie', 'A'], <ide> server.on('listening', function() { <ide> }); <ide> <ide> res.on('end', function() { <del> if (++nresponses === 2) { <del> server.close(); <del> } <add> countdown.dec(); <ide> }); <ide> }); <ide> <ide> server.on('listening', function() { <ide> }); <ide> <ide> res.on('end', function() { <del> if (++nresponses === 2) { <del> server.close(); <del> } <add> countdown.dec(); <ide> }); <ide> }); <ide> <ide> }); <del> <del>process.on('exit', function() { <del> assert.strictEqual(2, nresponses); <del>});
1
Java
Java
introduce resolvabletype class
6a18b0048ddbe9e65f6270946c1c17c6fdc66539
<ide><path>spring-core/src/main/java/org/springframework/core/ResolvableType.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.core; <add> <add>import java.lang.reflect.Array; <add>import java.lang.reflect.Constructor; <add>import java.lang.reflect.Field; <add>import java.lang.reflect.GenericArrayType; <add>import java.lang.reflect.Method; <add>import java.lang.reflect.ParameterizedType; <add>import java.lang.reflect.Type; <add>import java.lang.reflect.TypeVariable; <add>import java.lang.reflect.WildcardType; <add>import java.util.Collection; <add>import java.util.Map; <add> <add>import org.springframework.util.Assert; <add>import org.springframework.util.ConcurrentReferenceHashMap; <add>import org.springframework.util.ObjectUtils; <add>import org.springframework.util.StringUtils; <add> <add>/** <add> * Encapsulates a Java {@link java.lang.reflect.Type}, providing access to <add> * {@link #getSuperType() supertypes} , {@link #getInterfaces() interfaces} and <add> * {@link #getGeneric(int...) generic parameters} along with the ability to ultimately <add> * {@link #resolve() resolve} to a {@link java.lang.Class}. <add> * <add> * <p>{@code ResolvableTypes} may be obtained from {@link #forField(Field) fields}, <add> * {@link #forMethodParameter(Method, int) method parameters}, <add> * {@link #forMethodReturn(Method) method returns}, {@link #forClass(Class) classes} or <add> * directly from a {@link #forType(Type) java.lang.reflect.Type}. Most methods on this class <add> * will themselves return {@link ResolvableType}s, allowing easy navigation. For example: <add> * <pre class="code"> <add> * private HashMap&lt;Integer, List&lt;String&gt;&gt; myMap; <add> * <add> * public void example() { <add> * ResolvableType t = ResolvableType.forField(getClass().getDeclaredField("myMap")); <add> * t.getSuperType(); // AbstractMap&lt;Integer, List&lt;String&gt;&gt; <add> * t.asMap(); // Map&lt;Integer, List&lt;String&gt;&gt; <add> * t.getGeneric(0).resolve(); // Integer <add> * t.getGeneric(1).resolve(); // List <add> * t.getGeneric(1); // List&lt;String&gt; <add> * t.resolveGeneric(1, 0); // String <add> * } <add> * </pre> <add> * <add> * @author Phillip Webb <add> * @since 4.0 <add> * @see TypeVariableResolver <add> * @see #forField(Field) <add> * @see #forMethodParameter(Method, int) <add> * @see #forMethodReturn(Method) <add> * @see #forConstructorParameter(Constructor, int) <add> * @see #forClass(Class) <add> * @see #forType(Type) <add> */ <add>public final class ResolvableType implements TypeVariableResolver { <add> <add> private static ConcurrentReferenceHashMap<ResolvableType, ResolvableType> cache = <add> new ConcurrentReferenceHashMap<ResolvableType, ResolvableType>(); <add> <add> <add> /** <add> * {@code ResolvableType} returned when no value is available. {@code NONE} is used <add> * in preference to {@code null} so that multiple method calls can be safely chained. <add> */ <add> public static final ResolvableType NONE = new ResolvableType(null, null); <add> <add> <add> private static final ResolvableType[] EMPTY_TYPES_ARRAY = new ResolvableType[0]; <add> <add> <add> /** <add> * The underlying java type being managed (only ever {@code null} for {@link #NONE}) <add> */ <add> private final Type type; <add> <add> /** <add> * The {@link TypeVariableResolver} to use or {@code null} if no resolver is availble. <add> */ <add> private final TypeVariableResolver variableResolver; <add> <add> /** <add> * Stored copy of the resolved value or {@code null} if the resolve method has not <add> * yet been called. {@code void.class} is used when the resolve method failed. <add> */ <add> private Class<?> resolved; <add> <add> <add> /** <add> * Private constructor used to create a new {@link ResolvableType}. <add> * @param type the underlying java type (may only be {@code null} for {@link #NONE}) <add> * @param variableResolver the resolver used for {@link TypeVariable}s (may be {@code null}) <add> */ <add> private ResolvableType(Type type, TypeVariableResolver variableResolver) { <add> this.type = type; <add> this.variableResolver = variableResolver; <add> } <add> <add> <add> /** <add> * Return the underling java {@link Type} being managed. With the exception of <add> * the {@link #NONE} constant, this method will never return {@code null}. <add> */ <add> public Type getType() { <add> return this.type; <add> } <add> <add> /** <add> * Determines if this {@code ResolvableType} is assignable from the specified <add> * {@code type}. Attempts to follow the same rules as the Java compiler, considering <add> * if both the {@link #resolve() resolved} {@code Class} is <add> * {@link Class#isAssignableFrom(Class) assignable from} the given {@code type} as <add> * well as if all {@link #getGenerics() generics} are assignable. <add> * @param type the type to be checked <add> * @return {@code true} if the specified {@code type} can be assigned to this <add> * {@code type}. <add> */ <add> public boolean isAssignableFrom(ResolvableType type) { <add> return isAssignableFrom(type, false); <add> } <add> <add> private boolean isAssignableFrom(ResolvableType type, boolean checkingGeneric) { <add> Assert.notNull(type, "Type must not be null"); <add> <add> // If we cannot resolve types, we are not assignable <add> if (resolve() == null || type.resolve() == null) { <add> return false; <add> } <add> <add> // Deal with array by delegating to the component type <add> if (isArray()) { <add> return (type.isArray() && getComponentType().isAssignableFrom( <add> type.getComponentType())); <add> } <add> <add> // Deal with wildcard bounds <add> WildcardBounds ourBounds = WildcardBounds.get(this); <add> WildcardBounds typeBounds = WildcardBounds.get(type); <add> <add> // in the from X is assignable to <? extends Number> <add> if (typeBounds != null) { <add> return (ourBounds != null && ourBounds.isSameKind(typeBounds) <add> && ourBounds.isAssignableFrom(typeBounds.getBounds())); <add> } <add> <add> // in the form <? extends Number> is assignable to X ... <add> if (ourBounds != null) { <add> return ourBounds.isAssignableFrom(type); <add> } <add> <add> // Main assignability check <add> boolean rtn = resolve().isAssignableFrom(type.resolve()); <add> <add> // We need an exact type match for generics <add> // List<CharSequence> is not assignable from List<String> <add> rtn &= (!checkingGeneric || resolve().equals(type.resolve())); <add> <add> // Recursively check each generic <add> for (int i = 0; i < getGenerics().length; i++) { <add> rtn &= getGeneric(i).isAssignableFrom(type.as(resolve()).getGeneric(i), true); <add> } <add> <add> return rtn; <add> } <add> <add> /** <add> * Return {@code true} if this type will resolve to a Class that represents an <add> * array. <add> * @see #getComponentType() <add> */ <add> public boolean isArray() { <add> if (this == NONE) { <add> return false; <add> } <add> return (((this.type instanceof Class) && <add> ((Class<?>) this.type).isArray()) || <add> this.type instanceof GenericArrayType || <add> this.resolveType().isArray()); <add> } <add> <add> /** <add> * Return the ResolvableType representing the component type of the array or <add> * {@link #NONE} if this type does not represent an array. <add> * @see #isArray() <add> */ <add> public ResolvableType getComponentType() { <add> if (this == NONE) { <add> return NONE; <add> } <add> if (this.type instanceof Class) { <add> Class<?> componentType = ((Class<?>) this.type).getComponentType(); <add> return (componentType == null ? NONE : forType(componentType, <add> this.variableResolver)); <add> } <add> if (this.type instanceof GenericArrayType) { <add> return forType(((GenericArrayType) this.type).getGenericComponentType(), <add> this.variableResolver); <add> } <add> return resolveType().getComponentType(); <add> } <add> <add> /** <add> * Convenience method to return this type as a resolvable {@link Collection} type. <add> * Returns {@link #NONE} if this type does not implement or extend <add> * {@link Collection}. <add> * @see #as(Class) <add> * @see #asMap() <add> */ <add> public ResolvableType asCollection() { <add> return as(Collection.class); <add> } <add> <add> /** <add> * Convenience method to return this type as a resolvable {@link Map} type. <add> * Returns {@link #NONE} if this type does not implement or extend <add> * {@link Map}. <add> * @see #as(Class) <add> * @see #asCollection() <add> */ <add> public ResolvableType asMap() { <add> return as(Map.class); <add> } <add> <add> /** <add> * Return this type as a {@link ResolvableType} of the specified class. Searches <add> * {@link #getSuperType() supertype} and {@link #getInterfaces() interface} <add> * hierarchies to find a match, returning {@link #NONE} if this type does not <add> * implement or extends the specified class. <add> * @param type the required class type <add> * @return a {@link ResolvableType} representing this object as the specified type or <add> * {@link #NONE} <add> * @see #asCollection() <add> * @see #asMap() <add> * @see #getSuperType() <add> * @see #getInterfaces() <add> */ <add> public ResolvableType as(Class<?> type) { <add> if (this == NONE) { <add> return NONE; <add> } <add> if (ObjectUtils.nullSafeEquals(resolve(), type)) { <add> return this; <add> } <add> for (ResolvableType interfaceType : getInterfaces()) { <add> ResolvableType interfaceAsType = interfaceType.as(type); <add> if (interfaceAsType != NONE) { <add> return interfaceAsType; <add> } <add> } <add> return getSuperType().as(type); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} representing the direct supertype of this type. <add> * If no supertype is available this method returns {@link #NONE}. <add> * @see #getInterfaces() <add> */ <add> public ResolvableType getSuperType() { <add> Class<?> resolved = resolve(); <add> if (resolved == null || resolved.getGenericSuperclass() == null) { <add> return NONE; <add> } <add> return forType(resolved.getGenericSuperclass(), this); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} array representing the direct interfaces <add> * implemented by this type. If this type does not implement any interfaces an <add> * empty array is returned. <add> * @see #getSuperType() <add> */ <add> public ResolvableType[] getInterfaces() { <add> Class<?> resolved = resolve(); <add> if (resolved == null || ObjectUtils.isEmpty(resolved.getGenericInterfaces())) { <add> return EMPTY_TYPES_ARRAY; <add> } <add> Type[] interfaceTypes = resolved.getGenericInterfaces(); <add> ResolvableType[] interfaces = new ResolvableType[interfaceTypes.length]; <add> for (int i = 0; i < interfaceTypes.length; i++) { <add> interfaces[i] = forType(interfaceTypes[i], this); <add> } <add> return interfaces; <add> } <add> <add> /** <add> * Return {@code true} if this type contains generic parameters. <add> * @see #getGeneric(int...) <add> * @see #getGenerics() <add> */ <add> public boolean hasGenerics() { <add> return (getGenerics().length > 0); <add> } <add> <add> /** <add> * Returns a {@link ResolvableType} for the specified nesting level. See <add> * {@link #getNested(int, Map)} for details. <add> * @param nestingLevel the nesting level <add> * @return the {@link ResolvableType} type, or {@code #NONE} <add> */ <add> public ResolvableType getNested(int nestingLevel) { <add> return getNested(nestingLevel, null); <add> } <add> <add> /** <add> * Returns a {@link ResolvableType} for the specified nesting level. The nesting level <add> * refers to the specific generic parameter that should be returned. A nesting level <add> * of 1 indicates this type, 2 indicates the first nested generic, 3 the second and so <add> * on. For example, given {@code List<Set<Integer>>} level 1 refers to the <add> * {@code List}, level 2 the {@code Set} and level 3 the {@code Integer}. <add> * <add> * <p>The {@code typeIndexesPerLevel} map can be used to reference a specific generic <add> * for the given level. For example, an index of 0 would refer to a {@code Map} key, <add> * where as 1 would refer to the value. If the map does not contain an value for a <add> * specific level the last generic will be used (e.g. a {@code Map} value). <add> * <add> * <p>Nesting levels may also apply to array types, for example given <add> * {@code String[]}, a nesting level of 2 referes to {@code String}. <add> * <add> * <p>If a type does not {@link #hasGenerics() contain} generics the <add> * {@link #getSuperType() super-type} hierarchy will be considered. <add> * @param nestingLevel the required nesting level, indexed from 1 for the current <add> * type, 2 for the first nested generic, 3 for the second and so on. <add> * @param typeIndexesPerLevel a map containing the generic index for a given nesting <add> * level (may be {@code null}). <add> * @return a {@link ResolvableType} for the nested level or {@link #NONE}. <add> */ <add> public ResolvableType getNested(int nestingLevel, <add> Map<Integer, Integer> typeIndexesPerLevel) { <add> ResolvableType result = this; <add> for (int i = 2; i <= nestingLevel; i++) { <add> if (result.isArray()) { <add> result = result.getComponentType(); <add> } <add> else { <add> // Handle derived types <add> while (result != ResolvableType.NONE && !result.hasGenerics()) { <add> result = result.getSuperType(); <add> } <add> Integer index = (typeIndexesPerLevel == null ? null <add> : typeIndexesPerLevel.get(i)); <add> index = (index == null ? result.getGenerics().length - 1 : index); <add> result = result.getGeneric(index); <add> } <add> } <add> return result; <add> } <add> <add> /** <add> * Return a {@link ResolvableType} representing the generic parameter for the given <add> * indexes. Indexes are zero based, for example given the type <add> * {@code Map<Integer, List<String>>}, {@code getGeneric(0)} will access the <add> * {@code Integer}. Nested generics can be accessed by specifying multiple indexes, <add> * for example {@code getGeneric(1, 0)} will access the {@code String} from the nested <add> * {@code List}. For convenience, if no indexes are specified the first generic is <add> * returned. <add> * <add> * <p>If no generic is available at the specified indexes {@link #NONE} is returned. <add> * @param indexes the indexes that refers to the generic parameter (may be omitted to <add> * return the first generic) <add> * @return a {@link ResolvableType} for the specified generic or {@link #NONE} <add> * @see #hasGenerics() <add> * @see #getGenerics() <add> * @see #resolveGeneric(int...) <add> * @see #resolveGenerics() <add> */ <add> public ResolvableType getGeneric(int... indexes) { <add> try { <add> if (indexes == null || indexes.length == 0) { <add> return getGenerics()[0]; <add> } <add> ResolvableType rtn = this; <add> for (int index : indexes) { <add> rtn = rtn.getGenerics()[index]; <add> } <add> return rtn; <add> } <add> catch (IndexOutOfBoundsException ex) { <add> return NONE; <add> } <add> } <add> <add> /** <add> * Return an array of {@link ResolvableType} representing the generics parameters of <add> * this type. If no generics are available an empty array is returned. If you need to <add> * access a specific generic consider using the {@link #getGeneric(int...)} method as <add> * it allows access to nested generics, and protects against <add> * {@code IndexOutOfBoundsExceptions} <add> * @return an array of {@link ResolvableType}s representing the generic parameters <add> * (never {@code null}) <add> * @see #hasGenerics() <add> * @see #getGeneric(int...) <add> * @see #resolveGeneric(int...) <add> * @see #resolveGenerics() <add> */ <add> public ResolvableType[] getGenerics() { <add> if (this == NONE) { <add> return EMPTY_TYPES_ARRAY; <add> } <add> if (this.type instanceof ParameterizedType) { <add> Type[] genericTypes = ((ParameterizedType) getType()).getActualTypeArguments(); <add> ResolvableType[] generics = new ResolvableType[genericTypes.length]; <add> for (int i = 0; i < genericTypes.length; i++) { <add> generics[i] = forType(genericTypes[i], this); <add> } <add> return generics; <add> } <add> return resolveType().getGenerics(); <add> } <add> <add> /** <add> * Convenience method that will {@link #getGenerics() get} and {@link #resolve() <add> * resolve} generic parameters. <add> * @return an array of resolved generic parameters (the resulting array will never be <add> * {@code null}, but it may contain {@code null} elements}) <add> * @see #getGenerics() <add> * @see #resolve() <add> */ <add> public Class<?>[] resolveGenerics() { <add> ResolvableType[] generics = getGenerics(); <add> Class<?>[] resolvedGenerics = new Class<?>[generics.length]; <add> for (int i = 0; i < generics.length; i++) { <add> resolvedGenerics[i] = generics[i].resolve(); <add> } <add> return resolvedGenerics; <add> } <add> <add> /** <add> * Convenience method that will {@link #getGeneric(int...) get} and <add> * {@link #resolve() resolve} a specific generic parameters. <add> * @param indexes the indexes that refers to the generic parameter (may be omitted to <add> * return the first generic) <add> * @return a resolved {@link Class} or {@code null} <add> * @see #getGeneric(int...) <add> * @see #resolve() <add> */ <add> public Class<?> resolveGeneric(int... indexes) { <add> return getGeneric(indexes).resolve(); <add> } <add> <add> /** <add> * Resolve this type to a {@link java.lang.Class}, returning {@code null} if the type <add> * cannot be resolved. This method will consider bounds of {@link TypeVariable}s and <add> * {@link WildcardType}s if direct resolution fails. <add> * @return the resolved {@link Class} or {@code null} <add> * @see #resolve(Class) <add> * @see #resolveGeneric(int...) <add> * @see #resolveGenerics() <add> */ <add> public Class<?> resolve() { <add> return resolve(null); <add> } <add> <add> /** <add> * Resolve this type to a {@link java.lang.Class}, returning the specified <add> * {@code fallback} if the type cannot be resolved. This method will consider bounds <add> * of {@link TypeVariable}s and {@link WildcardType}s if direct resolution fails. <add> * @param fallback the fallback class to use if resolution fails (may be {@code null}) <add> * @return the resolved {@link Class} or the {@code fallback} <add> * @see #resolve() <add> * @see #resolveGeneric(int...) <add> * @see #resolveGenerics() <add> */ <add> public Class<?> resolve(Class<?> fallback) { <add> if (this.resolved == null) { <add> synchronized (this) { <add> this.resolved = resolveClass(); <add> this.resolved = (this.resolved == null ? void.class : this.resolved); <add> } <add> } <add> return (this.resolved == void.class ? fallback : this.resolved); <add> } <add> <add> private Class<?> resolveClass() { <add> if (this.type instanceof Class<?> || this.type == null) { <add> return (Class<?>) this.type; <add> } <add> if (this.type instanceof GenericArrayType) { <add> return Array.newInstance(getComponentType().resolve(), 0).getClass(); <add> } <add> return resolveType().resolve(); <add> } <add> <add> /** <add> * Resolve this type by a single level, returning the resolved value or {@link #NONE}. <add> */ <add> ResolvableType resolveType() { <add> Type resolved = null; <add> if (this.type instanceof ParameterizedType) { <add> resolved = ((ParameterizedType) this.type).getRawType(); <add> } <add> else if (this.type instanceof WildcardType) { <add> resolved = resolveBounds(((WildcardType) this.type).getUpperBounds()); <add> if (resolved == null) { <add> resolved = resolveBounds(((WildcardType) this.type).getLowerBounds()); <add> } <add> } <add> else if (this.type instanceof TypeVariable) { <add> if (this.variableResolver != null) { <add> resolved = this.variableResolver.resolveVariable((TypeVariable<?>) this.type); <add> } <add> if (resolved == null) { <add> resolved = resolveBounds(((TypeVariable<?>) this.type).getBounds()); <add> } <add> } <add> return (resolved == null ? NONE : forType(resolved, this.variableResolver)); <add> } <add> <add> private Type resolveBounds(Type[] bounds) { <add> if (ObjectUtils.isEmpty(bounds) || Object.class.equals(bounds[0])) { <add> return null; <add> } <add> return bounds[0]; <add> } <add> <add> public Type resolveVariable(TypeVariable<?> variable) { <add> Assert.notNull("Variable must not be null"); <add> if (this.type instanceof ParameterizedType) { <add> <add> ParameterizedType parameterizedType = (ParameterizedType) this.type; <add> Type owner = parameterizedType.getOwnerType(); <add> <add> if (parameterizedType.getRawType().equals(variable.getGenericDeclaration())) { <add> TypeVariable<?>[] variables = resolve().getTypeParameters(); <add> for (int i = 0; i < variables.length; i++) { <add> if (ObjectUtils.nullSafeEquals(variables[i].getName(), variable.getName())) { <add> return parameterizedType.getActualTypeArguments()[i]; <add> } <add> } <add> } <add> <add> Type resolved = null; <add> if (this.variableResolver != null) { <add> resolved = this.variableResolver.resolveVariable(variable); <add> } <add> if (resolved == null && owner != null) { <add> resolved = forType(owner, this.variableResolver).resolveVariable(variable); <add> } <add> return resolved; <add> } <add> <add> if (this.type instanceof TypeVariable<?>) { <add> return resolveType().resolveVariable(variable); <add> } <add> <add> return null; <add> } <add> <add> /** <add> * Return a string representation of this type in its fully resolved form <add> * (including any generic parameters). <add> * @see java.lang.Object#toString() <add> */ <add> @Override <add> public String toString() { <add> if (isArray()) { <add> return getComponentType() + "[]"; <add> } <add> StringBuilder result = new StringBuilder(); <add> result.append(resolve() == null ? "?" : resolve().getName()); <add> if (hasGenerics()) { <add> result.append("<"); <add> result.append(StringUtils.arrayToDelimitedString(getGenerics(), ", ")); <add> result.append(">"); <add> } <add> return result.toString(); <add> } <add> <add> @Override <add> public int hashCode() { <add> return ObjectUtils.nullSafeHashCode(this.type) * 31 <add> + ObjectUtils.nullSafeHashCode(this.variableResolver); <add> } <add> <add> @Override <add> public boolean equals(Object obj) { <add> if (obj == this) { <add> return true; <add> } <add> if (obj instanceof ResolvableType) { <add> ResolvableType other = (ResolvableType) obj; <add> return ObjectUtils.nullSafeEquals(this.type, other.type) <add> && ObjectUtils.nullSafeEquals(this.variableResolver, <add> other.variableResolver); <add> } <add> return false; <add> } <add> <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link Class}. For example <add> * {@code ResolvableType.forClass(MyArrayList.class)}. <add> * @param sourceClass the source class (must not be {@code null} <add> * @return a {@link ResolvableType} for the specified class <add> * @see #forClass(Class, Class) <add> */ <add> public static ResolvableType forClass(Class<?> sourceClass) { <add> Assert.notNull(sourceClass, "Source class must not be null"); <add> return forType(sourceClass); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link Class} with a given <add> * implementation. For example <add> * {@code ResolvableType.forClass(List.class, MyArrayList.class)}. <add> * @param sourceClass the source class (must not be {@code null} <add> * @param implementationClass the implementation class (must not be {@code null}) <add> * @return a {@link ResolvableType} for the specified class backed by the given <add> * implementation class <add> * @see #forClass(Class) <add> */ <add> public static ResolvableType forClass(Class<?> sourceClass, Class<?> implementationClass) { <add> Assert.notNull(sourceClass, "Source class must not be null"); <add> Assert.notNull(implementationClass, "ImplementationClass must not be null"); <add> ResolvableType asType = forType(implementationClass).as(sourceClass); <add> return (asType == NONE ? forType(sourceClass) : asType); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link Field}. <add> * @param field the source field <add> * @return a {@link ResolvableType} for the specified field <add> * @see #forField(Field, Class) <add> */ <add> public static ResolvableType forField(Field field) { <add> Assert.notNull(field, "Field must not be null"); <add> return forType(field.getGenericType()); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link Field} with a given <add> * implementation. Use this variant when the class that declares the field includes <add> * generic parameter variables that are satisfied by the implementation class. <add> * @param field the source field <add> * @param implementationClass the implementation class (must not be {@code null}) <add> * @return a {@link ResolvableType} for the specified field <add> * @see #forField(Field) <add> */ <add> public static ResolvableType forField(Field field, Class<?> implementationClass) { <add> Assert.notNull(field, "Field must not be null"); <add> Assert.notNull(implementationClass, "ImplementationClass must not be null"); <add> TypeVariableResolver variableResolver = forType(implementationClass).as( <add> field.getDeclaringClass()); <add> return forType(field.getGenericType(), variableResolver); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link Constructor} parameter. <add> * @param constructor the source constructor (must not be {@code null}) <add> * @param parameterIndex the parameter index <add> * @return a {@link ResolvableType} for the specified constructor parameter <add> * @see #forConstructorParameter(Constructor, int, Class) <add> */ <add> public static ResolvableType forConstructorParameter(Constructor<?> constructor, <add> int parameterIndex) { <add> Assert.notNull(constructor, "Constructor must not be null"); <add> return forMethodParameter(MethodParameter.forMethodOrConstructor(constructor, <add> parameterIndex)); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link Constructor} parameter <add> * with a given implementation. Use this variant when the class that declares the <add> * constructor includes generic parameter variables that are satisfied by the <add> * implementation class. <add> * @param constructor the source constructor (must not be {@code null}) <add> * @param parameterIndex the parameter index <add> * @param implementationClass the implementation class (must not be {@code null}) <add> * @return a {@link ResolvableType} for the specified constructor parameter <add> * @see #forConstructorParameter(Constructor, int) <add> */ <add> public static ResolvableType forConstructorParameter(Constructor<?> constructor, <add> int parameterIndex, Class<?> implementationClass) { <add> Assert.notNull(constructor, "Constructor must not be null"); <add> Assert.notNull(implementationClass, "ImplementationClass must not be null"); <add> return forMethodParameter( <add> MethodParameter.forMethodOrConstructor(constructor, parameterIndex), <add> implementationClass); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link Method} parameter. <add> * @param method the source method (must not be {@code null}) <add> * @param parameterIndex the parameter index <add> * @return a {@link ResolvableType} for the specified method parameter <add> * @see #forMethodParameter(Method, int, Class) <add> * @see #forMethodParameter(MethodParameter) <add> */ <add> public static ResolvableType forMethodParameter(Method method, int parameterIndex) { <add> Assert.notNull(method, "Method must not be null"); <add> return forMethodParameter(MethodParameter.forMethodOrConstructor(method, <add> parameterIndex)); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link Method} parameter with a <add> * given implementation. Use this variant when the class that declares the method <add> * includes generic parameter variables that are satisfied by the implementation <add> * class. <add> * @param method the source method (must not be {@code null}) <add> * @param parameterIndex the parameter index <add> * @param implementationClass the implementation class (must not be {@code null}) <add> * @return a {@link ResolvableType} for the specified method parameter <add> * @see #forMethodParameter(Method, int, Class) <add> * @see #forMethodParameter(MethodParameter) <add> */ <add> public static ResolvableType forMethodParameter(Method method, int parameterIndex, <add> Class<?> implementationClass) { <add> Assert.notNull(method, "Method must not be null"); <add> return forMethodParameter( <add> MethodParameter.forMethodOrConstructor(method, parameterIndex), <add> implementationClass); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link MethodParameter}. <add> * @param methodParameter the source method parameter (must not be {@code null}) <add> * @return a {@link ResolvableType} for the specified method parameter <add> * @see #forMethodParameter(MethodParameter, Class) <add> * @see #forMethodParameter(Method, int) <add> */ <add> public static ResolvableType forMethodParameter(MethodParameter methodParameter) { <add> Assert.notNull(methodParameter, "MethodParameter must not be null"); <add> return forType(methodParameter.getGenericParameterType()).getNested( <add> methodParameter.getNestingLevel(), methodParameter.typeIndexesPerLevel); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link MethodParameter} with a <add> * given implementation. Use this variant when the class that declares the method <add> * includes generic parameter variables that are satisfied by the implementation <add> * class. <add> * @param methodParameter the source method parameter (must not be {@code null}) <add> * @param implementationClass the implementation class (must not be {@code null}) <add> * @return a {@link ResolvableType} for the specified method parameter <add> * @see #forMethodParameter(MethodParameter) <add> * @see #forMethodParameter(Method, int) <add> */ <add> public static ResolvableType forMethodParameter(MethodParameter methodParameter, <add> Class<?> implementationClass) { <add> Assert.notNull(methodParameter, "MethodParameter must not be null"); <add> Assert.notNull(implementationClass, "ImplementationClass must not be null"); <add> TypeVariableResolver variableResolver = forType(implementationClass).as( <add> methodParameter.getMember().getDeclaringClass()); <add> return forType(methodParameter.getGenericParameterType(), variableResolver).getNested( <add> methodParameter.getNestingLevel(), methodParameter.typeIndexesPerLevel); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link Method} return. <add> * @param method the source for the method return <add> * @return a {@link ResolvableType} for the specified method return <add> * @see #forMethodReturn(Method, Class) <add> */ <add> public static ResolvableType forMethodReturn(Method method) { <add> Assert.notNull(method, "Method must not be null"); <add> return forType(method.getGenericReturnType()); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link Method} return. Use this <add> * variant when the class that declares the method includes generic parameter <add> * variables that are satisfied by the implementation class. <add> * @param method the source for the method return <add> * @param implementationClass the implementation class (must not be {@code null}) <add> * @return a {@link ResolvableType} for the specified method return <add> * @see #forMethodReturn(Method) <add> */ <add> public static ResolvableType forMethodReturn(Method method, <add> Class<?> implementationClass) { <add> Assert.notNull(method, "Method must not be null"); <add> Assert.notNull(implementationClass, "ImplementationClass must not be null"); <add> TypeVariableResolver variableResolver = forType(implementationClass).as( <add> method.getDeclaringClass()); <add> return forType(method.getGenericReturnType(), variableResolver); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link java.lang.reflect.Type}. <add> * @param type the source type (must not be {@code null}) <add> * @return a {@link ResolvableType} for the specified {@link java.lang.reflect.Type} <add> */ <add> public static ResolvableType forType(Type type) { <add> return forType(type, null); <add> } <add> <add> /** <add> * Return a {@link ResolvableType} for the specified {@link java.lang.reflect.Type} <add> * backed by a given {@link TypeVariableResolver}. <add> * @param type the source type (must not be {@code null}) <add> * @param variableResolver the variable resolver <add> * @return a {@link ResolvableType} for the specified {@link java.lang.reflect.Type} <add> * and {@link TypeVariableResolver} <add> */ <add> public static ResolvableType forType(Type type, TypeVariableResolver variableResolver) { <add> ResolvableType key = new ResolvableType(type, variableResolver); <add> // Check the cache, we may have a ResolvableType that may have already been resolved <add> ResolvableType resolvableType = cache.get(key); <add> if (resolvableType == null) { <add> resolvableType = key; <add> cache.put(key, resolvableType); <add> } <add> return resolvableType; <add> } <add> <add> <add> /** <add> * Internal helper to handle bounds from {@link WildcardType}s. <add> */ <add> private static class WildcardBounds { <add> <add> <add> private final Kind kind; <add> <add> private final ResolvableType[] bounds; <add> <add> <add> /** <add> * Private constructor to create a new {@link WildcardBounds} instance. <add> * @param kind the kind of bounds <add> * @param bounds the bounds <add> * @see #get(ResolvableType) <add> */ <add> private WildcardBounds(Kind kind, ResolvableType[] bounds) { <add> this.kind = kind; <add> this.bounds = bounds; <add> } <add> <add> <add> /** <add> * Return {@code true} if this bounds is the same kind as the specified bounds. <add> */ <add> public boolean isSameKind(WildcardBounds bounds) { <add> return this.kind == bounds.kind; <add> } <add> <add> /** <add> * Return {@code true} if this bounds is assignable to all the specified types. <add> * @param types the types to test against <add> * @return {@code true} if this bounds is assignable to all types <add> */ <add> public boolean isAssignableFrom(ResolvableType... types) { <add> for (ResolvableType bound : this.bounds) { <add> for (ResolvableType type : types) { <add> if (!isAssignable(bound, type)) { <add> return false; <add> } <add> } <add> } <add> return true; <add> } <add> <add> private boolean isAssignable(ResolvableType source, ResolvableType from) { <add> return (this.kind == Kind.UPPER ? source.isAssignableFrom(from) <add> : from.isAssignableFrom(source)); <add> } <add> <add> /** <add> * Return the underlying bounds. <add> */ <add> public ResolvableType[] getBounds() { <add> return bounds; <add> } <add> <add> <add> /** <add> * Get a {@link WildcardBounds} instance for the specified type, returning <add> * {@code null} if the specified type cannot be resolved to a {@link WildcardType}. <add> * @param type the source type <add> * @return a {@link WildcardBounds} instance or {@code null} <add> */ <add> public static WildcardBounds get(ResolvableType type) { <add> ResolvableType resolveToWildcard = type; <add> while(!(resolveToWildcard.getType() instanceof WildcardType)) { <add> if (resolveToWildcard == NONE) { <add> return null; <add> } <add> resolveToWildcard = resolveToWildcard.resolveType(); <add> } <add> WildcardType wildcardType = (WildcardType) resolveToWildcard.type; <add> Kind boundsType = (wildcardType.getLowerBounds().length > 0 ? Kind.LOWER <add> : Kind.UPPER); <add> Type[] bounds = boundsType == Kind.UPPER ? wildcardType.getUpperBounds() <add> : wildcardType.getLowerBounds(); <add> ResolvableType[] resolvableBounds = new ResolvableType[bounds.length]; <add> for (int i = 0; i < bounds.length; i++) { <add> resolvableBounds[i] = forType(bounds[i], type.variableResolver); <add> } <add> return new WildcardBounds(boundsType, resolvableBounds); <add> } <add> <add> <add> /** <add> * The various kinds of bounds. <add> */ <add> static enum Kind { UPPER, LOWER } <add> <add> } <add> <add>} <ide><path>spring-core/src/main/java/org/springframework/core/TypeVariableResolver.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.core; <add> <add>import java.lang.reflect.Type; <add>import java.lang.reflect.TypeVariable; <add> <add>/** <add> * Strategy interface that can be used to resolve {@link java.lang.reflect.TypeVariable}s. <add> * <add> * @author Phillip Webb <add> * @since 4.0 <add> */ <add>public interface TypeVariableResolver { <add> <add> /** <add> * Resolve the specified type variable. <add> * @param typeVariable the type variable to resolve (must not be {@code null}) <add> * @return the resolved {@link java.lang.reflect.Type} for the variable or <add> * {@code null} if the variable cannot be resolved. <add> */ <add> Type resolveVariable(TypeVariable<?> typeVariable); <add> <add>} <ide><path>spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.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.core; <add> <add>import java.io.Serializable; <add>import java.lang.reflect.Constructor; <add>import java.lang.reflect.Field; <add>import java.lang.reflect.GenericArrayType; <add>import java.lang.reflect.Method; <add>import java.lang.reflect.ParameterizedType; <add>import java.lang.reflect.Type; <add>import java.lang.reflect.TypeVariable; <add>import java.lang.reflect.WildcardType; <add>import java.util.AbstractCollection; <add>import java.util.AbstractList; <add>import java.util.ArrayList; <add>import java.util.Collection; <add>import java.util.Collections; <add>import java.util.HashMap; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.SortedSet; <add>import java.util.TreeSet; <add> <add>import org.hamcrest.Matchers; <add>import org.junit.Rule; <add>import org.junit.Test; <add>import org.junit.rules.ExpectedException; <add>import org.junit.runner.RunWith; <add>import org.mockito.ArgumentCaptor; <add>import org.mockito.Captor; <add>import org.mockito.runners.MockitoJUnitRunner; <add>import org.springframework.util.MultiValueMap; <add> <add>import static org.hamcrest.Matchers.*; <add>import static org.junit.Assert.*; <add>import static org.mockito.BDDMockito.*; <add>import static org.mockito.Matchers.*; <add>import static org.mockito.Mockito.*; <add> <add>// FIXME nested <add> <add>/** <add> * Tests for {@link ResolvableType}. <add> * <add> * @author Phillip Webb <add> */ <add>@SuppressWarnings("rawtypes") <add>@RunWith(MockitoJUnitRunner.class) <add>public class ResolvableTypeTests { <add> <add> <add> @Rule <add> public ExpectedException thrown = ExpectedException.none(); <add> <add> @Captor <add> private ArgumentCaptor<TypeVariable<?>> typeVariableCaptor; <add> <add> <add> @Test <add> public void noneReturnValues() throws Exception { <add> ResolvableType none = ResolvableType.NONE; <add> assertThat(none.as(Object.class), equalTo(ResolvableType.NONE)); <add> assertThat(none.asCollection(), equalTo(ResolvableType.NONE)); <add> assertThat(none.asMap(), equalTo(ResolvableType.NONE)); <add> assertThat(none.getComponentType(), equalTo(ResolvableType.NONE)); <add> assertThat(none.getGeneric(0), equalTo(ResolvableType.NONE)); <add> assertThat(none.getGenerics().length, equalTo(0)); <add> assertThat(none.getInterfaces().length, equalTo(0)); <add> assertThat(none.getSuperType(), equalTo(ResolvableType.NONE)); <add> assertThat(none.getType(), nullValue()); <add> assertThat(none.hasGenerics(), equalTo(false)); <add> assertThat(none.isArray(), equalTo(false)); <add> assertThat(none.resolve(), nullValue()); <add> assertThat(none.resolve(String.class), equalTo((Class) String.class)); <add> assertThat(none.resolveGeneric(0), nullValue()); <add> assertThat(none.resolveGenerics().length, equalTo(0)); <add> assertThat(none.resolveVariable(mock(TypeVariable.class)), nullValue()); <add> assertThat(none.toString(), equalTo("?")); <add> assertThat(none.isAssignableFrom(ResolvableType.forClass(Object.class)), equalTo(false)); <add> } <add> <add> @Test <add> public void forClass() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class); <add> assertThat(type.getType(), equalTo((Type) ExtendsList.class)); <add> } <add> <add> @Test <add> public void forClassMustNotBeNull() throws Exception { <add> this.thrown.expect(IllegalArgumentException.class); <add> this.thrown.expectMessage("Source class must not be null"); <add> ResolvableType.forClass(null); <add> } <add> <add> @Test <add> public void forField() throws Exception { <add> Field field = Fields.class.getField("charSequenceList"); <add> ResolvableType type = ResolvableType.forField(field); <add> assertThat(type.getType(), equalTo(field.getGenericType())); <add> } <add> <add> @Test <add> public void forPrivateField() throws Exception { <add> Field field = Fields.class.getDeclaredField("privateField"); <add> ResolvableType type = ResolvableType.forField(field); <add> assertThat(type.getType(), equalTo(field.getGenericType())); <add> assertThat(type.resolve(), equalTo((Class) List.class)); <add> } <add> <add> @Test <add> public void forFieldMustNotBeNull() throws Exception { <add> this.thrown.expect(IllegalArgumentException.class); <add> this.thrown.expectMessage("Field must not be null"); <add> ResolvableType.forField(null); <add> } <add> <add> @Test <add> public void forConstructorParameter() throws Exception { <add> Constructor<Constructors> constructor = Constructors.class.getConstructor(List.class); <add> ResolvableType type = ResolvableType.forConstructorParameter(constructor, 0); <add> assertThat(type.getType(), equalTo(constructor.getGenericParameterTypes()[0])); <add> } <add> <add> @Test <add> public void forConstructorParameterMustNotBeNull() throws Exception { <add> this.thrown.expect(IllegalArgumentException.class); <add> this.thrown.expectMessage("Constructor must not be null"); <add> ResolvableType.forConstructorParameter(null, 0); <add> } <add> <add> @Test <add> public void forMethodParameterByIndex() throws Exception { <add> Method method = Methods.class.getMethod("charSequenceParameter", List.class); <add> ResolvableType type = ResolvableType.forMethodParameter(method, 0); <add> assertThat(type.getType(), equalTo(method.getGenericParameterTypes()[0])); <add> } <add> <add> @Test <add> public void forMethodParameterByIndexMustNotBeNull() throws Exception { <add> this.thrown.expect(IllegalArgumentException.class); <add> this.thrown.expectMessage("Method must not be null"); <add> ResolvableType.forMethodParameter(null, 0); <add> } <add> <add> @Test <add> public void forMethodParameter() throws Exception { <add> Method method = Methods.class.getMethod("charSequenceParameter", List.class); <add> MethodParameter methodParameter = MethodParameter.forMethodOrConstructor(method, 0); <add> ResolvableType type = ResolvableType.forMethodParameter(methodParameter); <add> assertThat(type.getType(), equalTo(method.getGenericParameterTypes()[0])); <add> } <add> <add> @Test <add> public void forMethodParameterWithNesting() throws Exception { <add> Method method = Methods.class.getMethod("nested", Map.class); <add> MethodParameter methodParameter = MethodParameter.forMethodOrConstructor(method, 0); <add> methodParameter.increaseNestingLevel(); <add> ResolvableType type = ResolvableType.forMethodParameter(methodParameter); <add> assertThat(type.resolve(), equalTo((Class) Map.class)); <add> assertThat(type.getGeneric(0).resolve(), equalTo((Class) Byte.class)); <add> assertThat(type.getGeneric(1).resolve(), equalTo((Class) Long.class)); <add> } <add> <add> @Test <add> public void forMethodParameterWithNestingAndLevels() throws Exception { <add> Method method = Methods.class.getMethod("nested", Map.class); <add> MethodParameter methodParameter = MethodParameter.forMethodOrConstructor(method, 0); <add> methodParameter.increaseNestingLevel(); <add> methodParameter.setTypeIndexForCurrentLevel(0); <add> ResolvableType type = ResolvableType.forMethodParameter(methodParameter); <add> assertThat(type.resolve(), equalTo((Class) Map.class)); <add> assertThat(type.getGeneric(0).resolve(), equalTo((Class) String.class)); <add> assertThat(type.getGeneric(1).resolve(), equalTo((Class) Integer.class)); <add> } <add> <add> @Test <add> public void forMethodParameterMustNotBeNull() throws Exception { <add> this.thrown.expect(IllegalArgumentException.class); <add> this.thrown.expectMessage("MethodParameter must not be null"); <add> ResolvableType.forMethodParameter(null); <add> } <add> <add> @Test <add> public void forMethodReturn() throws Exception { <add> Method method = Methods.class.getMethod("charSequenceReturn"); <add> ResolvableType type = ResolvableType.forMethodReturn(method); <add> assertThat(type.getType(), equalTo(method.getGenericReturnType())); <add> } <add> <add> @Test <add> public void forMethodReturnMustNotBeNull() throws Exception { <add> this.thrown.expect(IllegalArgumentException.class); <add> this.thrown.expectMessage("Method must not be null"); <add> ResolvableType.forMethodReturn(null); <add> } <add> <add> @Test <add> public void classType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("classType")); <add> assertThat(type.getType().getClass(), equalTo((Class) Class.class)); <add> } <add> <add> @Test <add> public void paramaterizedType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("parameterizedType")); <add> assertThat(type.getType(), instanceOf(ParameterizedType.class)); <add> } <add> <add> @Test <add> public void arrayClassType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("arrayClassType")); <add> assertThat(type.getType(), instanceOf(Class.class)); <add> assertThat(((Class) type.getType()).isArray(), equalTo(true)); <add> } <add> <add> @Test <add> public void genericArrayType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("genericArrayType")); <add> assertThat(type.getType(), instanceOf(GenericArrayType.class)); <add> } <add> <add> @Test <add> public void wildcardType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("wildcardType")); <add> assertThat(type.getType(), instanceOf(ParameterizedType.class)); <add> assertThat(type.getGeneric().getType(), instanceOf(WildcardType.class)); <add> } <add> <add> @Test <add> public void typeVariableType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("typeVariableType")); <add> assertThat(type.getType(), instanceOf(TypeVariable.class)); <add> } <add> <add> @Test <add> public void getComponentTypeForClassArray() throws Exception { <add> Field field = Fields.class.getField("arrayClassType"); <add> ResolvableType type = ResolvableType.forField(field); <add> assertThat(type.isArray(), equalTo(true)); <add> assertThat(type.getComponentType().getType(), <add> equalTo((Type) ((Class) field.getGenericType()).getComponentType())); <add> } <add> <add> @Test <add> public void getComponentTypeForGenericArrayType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("genericArrayType")); <add> assertThat(type.isArray(), equalTo(true)); <add> assertThat(type.getComponentType().getType(), <add> equalTo(((GenericArrayType) type.getType()).getGenericComponentType())); <add> } <add> <add> @Test <add> public void getComponentTypeForVariableThatResolvesToGenericArray() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ListOfGenericArray.class).asCollection().getGeneric(); <add> assertThat(type.isArray(), equalTo(true)); <add> assertThat(type.getType(), instanceOf(TypeVariable.class)); <add> assertThat(type.getComponentType().getType().toString(), <add> equalTo("java.util.List<java.lang.String>")); <add> } <add> <add> @Test <add> public void getComponentTypeForNonArray() throws Exception { <add> ResolvableType type = ResolvableType.forClass(String.class); <add> assertThat(type.isArray(), equalTo(false)); <add> assertThat(type.getComponentType(), equalTo(ResolvableType.NONE)); <add> } <add> <add> @Test <add> public void asCollection() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class).asCollection(); <add> assertThat(type.resolve(), equalTo((Class) Collection.class)); <add> assertThat(type.resolveGeneric(), equalTo((Class) CharSequence.class)); <add> } <add> <add> @Test <add> public void asMap() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsMap.class).asMap(); <add> assertThat(type.resolve(), equalTo((Class) Map.class)); <add> assertThat(type.resolveGeneric(0), equalTo((Class) String.class)); <add> assertThat(type.resolveGeneric(1), equalTo((Class) Integer.class)); <add> } <add> <add> @Test <add> public void asFromInterface() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class).as(List.class); <add> assertThat(type.getType().toString(), equalTo("java.util.List<E>")); <add> } <add> <add> @Test <add> public void asFromInheritedInterface() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class).as(Collection.class); <add> assertThat(type.getType().toString(), equalTo("java.util.Collection<E>")); <add> } <add> <add> @Test <add> public void asFromSuperType() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class).as(ArrayList.class); <add> assertThat(type.getType().toString(), equalTo("java.util.ArrayList<java.lang.CharSequence>")); <add> } <add> <add> @Test <add> public void asFromInheritedSuperType() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class).as(List.class); <add> assertThat(type.getType().toString(), equalTo("java.util.List<E>")); <add> } <add> <add> @Test <add> public void asNotFound() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class).as(Map.class); <add> assertThat(type, sameInstance(ResolvableType.NONE)); <add> } <add> <add> @Test <add> public void asSelf() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class); <add> assertThat(type.as(ExtendsList.class), equalTo(type)); <add> } <add> <add> @Test <add> public void getSuperType() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class).getSuperType(); <add> assertThat(type.resolve(), equalTo((Class) ArrayList.class)); <add> type = type.getSuperType(); <add> assertThat(type.resolve(), equalTo((Class) AbstractList.class)); <add> type = type.getSuperType(); <add> assertThat(type.resolve(), equalTo((Class) AbstractCollection.class)); <add> type = type.getSuperType(); <add> assertThat(type.resolve(), equalTo((Class) Object.class)); <add> } <add> <add> @Test <add> public void getInterfaces() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class); <add> assertThat(type.getInterfaces().length, equalTo(0)); <add> SortedSet<String> interfaces = new TreeSet<String>(); <add> for (ResolvableType interfaceType : type.getSuperType().getInterfaces()) { <add> interfaces.add(interfaceType.toString()); <add> } <add> assertThat(interfaces.toString(), equalTo( <add> "[" <add> + "java.io.Serializable, " <add> + "java.lang.Cloneable, " <add> + "java.util.List<java.lang.CharSequence>, " <add> + "java.util.RandomAccess" <add> + "]")); <add> } <add> <add> @Test <add> public void noSuperType() throws Exception { <add> assertThat(ResolvableType.forClass(Object.class).getSuperType(), <add> equalTo(ResolvableType.NONE)); <add> } <add> <add> @Test <add> public void noInterfaces() throws Exception { <add> assertThat(ResolvableType.forClass(Object.class).getInterfaces().length, <add> equalTo(0)); <add> } <add> <add> @Test <add> public void nested() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("nested")); <add> type = type.getNested(2); <add> assertThat(type.resolve(), equalTo((Class) Map.class)); <add> assertThat(type.getGeneric(0).resolve(), equalTo((Class) Byte.class)); <add> assertThat(type.getGeneric(1).resolve(), equalTo((Class) Long.class)); <add> } <add> <add> @Test <add> public void nestedWithIndexes() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("nested")); <add> type = type.getNested(2, Collections.singletonMap(2, 0)); <add> assertThat(type.resolve(), equalTo((Class) Map.class)); <add> assertThat(type.getGeneric(0).resolve(), equalTo((Class) String.class)); <add> assertThat(type.getGeneric(1).resolve(), equalTo((Class) Integer.class)); <add> } <add> <add> @Test <add> public void nestedWithArray() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("genericArrayType")); <add> type = type.getNested(2); <add> assertThat(type.resolve(), equalTo((Class) List.class)); <add> assertThat(type.resolveGeneric(), equalTo((Class) String.class)); <add> } <add> <add> @Test <add> public void getGeneric() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("stringList")); <add> assertThat(type.getGeneric().getType(), equalTo((Type) String.class)); <add> } <add> <add> @Test <add> public void getGenericByIndex() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("stringIntegerMultiValueMap")); <add> assertThat(type.getGeneric(0).getType(), equalTo((Type) String.class)); <add> assertThat(type.getGeneric(1).getType(), equalTo((Type) Integer.class)); <add> } <add> <add> @Test <add> public void getGenericOfGeneric() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("stringListList")); <add> assertThat(type.getGeneric().getType().toString(), equalTo("java.util.List<java.lang.String>")); <add> assertThat(type.getGeneric().getGeneric().getType(), equalTo((Type) String.class)); <add> } <add> <add> @Test <add> public void getGenericOfGenericByIndexes() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("stringListList")); <add> assertThat(type.getGeneric(0, 0).getType(), equalTo((Type) String.class)); <add> } <add> <add> @Test <add> public void getGenericOutOfBounds() throws Exception { <add> ResolvableType type = ResolvableType.forClass(List.class, ExtendsList.class); <add> assertThat(type.getGeneric(0), not(equalTo(ResolvableType.NONE))); <add> assertThat(type.getGeneric(1), equalTo(ResolvableType.NONE)); <add> assertThat(type.getGeneric(0, 1), equalTo(ResolvableType.NONE)); <add> } <add> <add> @Test <add> public void hasGenerics() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class); <add> assertThat(type.hasGenerics(), equalTo(false)); <add> assertThat(type.asCollection().hasGenerics(), equalTo(true)); <add> } <add> <add> @Test <add> public void getGenerics() throws Exception { <add> ResolvableType type = ResolvableType.forClass(List.class, ExtendsList.class); <add> ResolvableType[] generics = type.getGenerics(); <add> assertThat(generics.length, equalTo(1)); <add> assertThat(generics[0].resolve(), equalTo((Class) CharSequence.class)); <add> } <add> <add> @Test <add> public void noGetGenerics() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class); <add> ResolvableType[] generics = type.getGenerics(); <add> assertThat(generics.length, equalTo(0)); <add> } <add> <add> @Test <add> public void getResolvedGenerics() throws Exception { <add> ResolvableType type = ResolvableType.forClass(List.class, ExtendsList.class); <add> Class<?>[] generics = type.resolveGenerics(); <add> assertThat(generics.length, equalTo(1)); <add> assertThat(generics[0], equalTo((Class) CharSequence.class)); <add> } <add> <add> @Test <add> public void resolveClassType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("classType")); <add> assertThat(type.resolve(), equalTo((Class) List.class)); <add> } <add> <add> @Test <add> public void resolveParameterizedType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("parameterizedType")); <add> assertThat(type.resolve(), equalTo((Class) List.class)); <add> } <add> <add> @Test <add> public void resolveArrayClassType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("arrayClassType")); <add> assertThat(type.resolve(), equalTo((Class) List[].class)); <add> } <add> <add> @Test <add> public void resolveGenericArrayType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("genericArrayType")); <add> assertThat(type.resolve(), equalTo((Class) List[].class)); <add> assertThat(type.getComponentType().resolve(), equalTo((Class) List.class)); <add> assertThat(type.getComponentType().getGeneric().resolve(), equalTo((Class) String.class)); <add> } <add> <add> @Test <add> public void resolveGenericMultiArrayType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("genericMultiArrayType")); <add> assertThat(type.resolve(), equalTo((Class) List[][][].class)); <add> assertThat(type.getComponentType().resolve(), equalTo((Class) List[][].class)); <add> } <add> <add> @Test <add> public void resolveGenericArrayFromGeneric() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("stringArrayList")); <add> ResolvableType generic = type.asCollection().getGeneric(); <add> assertThat(generic.getType().toString(), equalTo("E")); <add> assertThat(generic.isArray(), equalTo(true)); <add> assertThat(generic.resolve(), equalTo((Class) String[].class)); <add> } <add> <add> @Test <add> public void resolveWildcardTypeUpperBounds() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("wildcardType")); <add> assertThat(type.getGeneric().resolve(), equalTo((Class) Number.class)); <add> } <add> <add> @Test <add> public void resolveWildcardLowerBounds() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("wildcardSuperType")); <add> assertThat(type.getGeneric().resolve(), equalTo((Class) Number.class)); <add> } <add> <add> @Test <add> public void resolveVariableFromFieldType() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("stringList")); <add> assertThat(type.resolve(), equalTo((Class) List.class)); <add> assertThat(type.getGeneric().resolve(), equalTo((Class) String.class)); <add> } <add> <add> @Test <add> public void resolveVariableFromFieldTypeUnknown() throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField("parameterizedType")); <add> assertThat(type.resolve(), equalTo((Class) List.class)); <add> assertThat(type.getGeneric().resolve(), nullValue()); <add> } <add> <add> @Test <add> public void resolveVariableFromInheritedField() throws Exception { <add> ResolvableType type = ResolvableType.forField( <add> Fields.class.getField("stringIntegerMultiValueMap")).as(Map.class); <add> assertThat(type.getGeneric(0).resolve(), equalTo((Class) String.class)); <add> assertThat(type.getGeneric(1).resolve(), equalTo((Class) List.class)); <add> assertThat(type.getGeneric(1, 0).resolve(), equalTo((Class) Integer.class)); <add> } <add> <add> @Test <add> public void resolveVariableFromInheritedFieldSwitched() throws Exception { <add> ResolvableType type = ResolvableType.forField( <add> Fields.class.getField("stringIntegerMultiValueMapSwitched")).as(Map.class); <add> assertThat(type.getGeneric(0).resolve(), equalTo((Class) String.class)); <add> assertThat(type.getGeneric(1).resolve(), equalTo((Class) List.class)); <add> assertThat(type.getGeneric(1, 0).resolve(), equalTo((Class) Integer.class)); <add> } <add> <add> @Test <add> public void doesResolveFromOuterOwner() throws Exception { <add> ResolvableType type = ResolvableType.forField( <add> Fields.class.getField("listOfListOfUnknown")).as(Collection.class); <add> ResolvableType generic = type.getGeneric(0); <add> assertThat(generic.resolve(), equalTo((Class) List.class)); <add> assertThat(generic.as(Collection.class).getGeneric(0).as(Collection.class).resolve(), nullValue()); <add> } <add> <add> @Test <add> public void resolveBoundedTypeVariableResult() throws Exception { <add> ResolvableType type = ResolvableType.forMethodReturn(Methods.class.getMethod("boundedTypeVaraibleResult")); <add> assertThat(type.resolve(), equalTo((Class) CharSequence.class)); <add> } <add> <add> @Test <add> public void resolveVariableNotFound() throws Exception { <add> ResolvableType type = ResolvableType.forMethodReturn(Methods.class.getMethod("typedReturn")); <add> assertThat(type.resolve(), nullValue()); <add> } <add> <add> @Test <add> public void resolveTypeVaraibleFromMethodReturn() throws Exception { <add> ResolvableType type = ResolvableType.forMethodReturn(Methods.class.getMethod("typedReturn")); <add> assertThat(type.resolve(), nullValue()); <add> } <add> <add> @Test <add> public void resolveTypeVaraibleFromMethodReturnWithInstanceClass() throws Exception { <add> ResolvableType type = ResolvableType.forMethodReturn( <add> Methods.class.getMethod("typedReturn"), TypedMethods.class); <add> assertThat(type.resolve(), equalTo((Class) String.class)); <add> } <add> <add> @Test <add> public void resolveTypeVaraibleFromSimpleInterfaceType() { <add> ResolvableType type = ResolvableType.forClass( <add> MySimpleInterfaceType.class).as(MyInterfaceType.class); <add> assertThat(type.resolveGeneric(), equalTo((Class) String.class)); <add> } <add> <add> @Test <add> public void resolveTypeVaraibleFromSimpleCollectionInterfaceType() { <add> ResolvableType type = ResolvableType.forClass( <add> MyCollectionInterfaceType.class).as(MyInterfaceType.class); <add> assertThat(type.resolveGeneric(), equalTo((Class) Collection.class)); <add> assertThat(type.resolveGeneric(0, 0), equalTo((Class) String.class)); <add> } <add> <add> @Test <add> public void resolveTypeVaraibleFromSimpleSuperclassType() { <add> ResolvableType type = ResolvableType.forClass( <add> MySimpleSuperclassType.class).as(MySuperclassType.class); <add> assertThat(type.resolveGeneric(), equalTo((Class) String.class)); <add> } <add> <add> @Test <add> public void resolveTypeVaraibleFromSimpleCollectionSuperclassType() { <add> ResolvableType type = ResolvableType.forClass( <add> MyCollectionSuperclassType.class).as(MySuperclassType.class); <add> assertThat(type.resolveGeneric(), equalTo((Class) Collection.class)); <add> assertThat(type.resolveGeneric(0, 0), equalTo((Class) String.class)); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromFieldTypeWithImplementsClass() throws Exception { <add> ResolvableType type = ResolvableType.forField( <add> Fields.class.getField("parameterizedType"), TypedFields.class); <add> assertThat(type.resolve(), equalTo((Class) List.class)); <add> assertThat(type.getGeneric().resolve(), equalTo((Class) String.class)); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromSuperType() throws Exception { <add> ResolvableType type = ResolvableType.forClass(ExtendsList.class); <add> assertThat(type.resolve(), equalTo((Class) ExtendsList.class)); <add> assertThat(type.asCollection().resolveGeneric(), <add> equalTo((Class) CharSequence.class)); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromClassWithImplementsClass() throws Exception { <add> ResolvableType type = ResolvableType.forClass( <add> MySuperclassType.class, MyCollectionSuperclassType.class); <add> assertThat(type.resolveGeneric(), equalTo((Class) Collection.class)); <add> assertThat(type.resolveGeneric(0, 0), equalTo((Class) String.class)); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromConstructorParameter() throws Exception { <add> Constructor<?> constructor = Constructors.class.getConstructor(List.class); <add> ResolvableType type = ResolvableType.forConstructorParameter(constructor, 0); <add> assertThat(type.resolve(), equalTo((Class) List.class)); <add> assertThat(type.resolveGeneric(0), equalTo((Class) CharSequence.class)); <add> } <add> <add> @Test <add> public void resolveUnknownTypeVariableFromConstructorParameter() throws Exception { <add> Constructor<?> constructor = Constructors.class.getConstructor(Map.class); <add> ResolvableType type = ResolvableType.forConstructorParameter(constructor, 0); <add> assertThat(type.resolve(), equalTo((Class) Map.class)); <add> assertThat(type.resolveGeneric(0), nullValue()); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromConstructorParameterWithImplementsClass() throws Exception { <add> Constructor<?> constructor = Constructors.class.getConstructor(Map.class); <add> ResolvableType type = ResolvableType.forConstructorParameter( <add> constructor, 0, TypedConstructors.class); <add> assertThat(type.resolve(), equalTo((Class) Map.class)); <add> assertThat(type.resolveGeneric(0), equalTo((Class) String.class)); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromMethodParameter() throws Exception { <add> Method method = Methods.class.getMethod("typedParameter", Object.class); <add> ResolvableType type = ResolvableType.forMethodParameter(method, 0); <add> assertThat(type.resolve(), nullValue()); <add> assertThat(type.getType().toString(), equalTo("T")); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromMethodParameterWithImplementsClass() throws Exception { <add> Method method = Methods.class.getMethod("typedParameter", Object.class); <add> ResolvableType type = ResolvableType.forMethodParameter(method, 0, TypedMethods.class); <add> assertThat(type.resolve(), equalTo((Class) String.class)); <add> assertThat(type.getType().toString(), equalTo("T")); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromMethodParameterType() throws Exception { <add> Method method = Methods.class.getMethod("typedParameter", Object.class); <add> MethodParameter methodParameter = MethodParameter.forMethodOrConstructor(method, 0); <add> ResolvableType type = ResolvableType.forMethodParameter(methodParameter); <add> assertThat(type.resolve(), nullValue()); <add> assertThat(type.getType().toString(), equalTo("T")); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromMethodParameterTypeWithImplementsClass() <add> throws Exception { <add> Method method = Methods.class.getMethod("typedParameter", Object.class); <add> MethodParameter methodParameter = MethodParameter.forMethodOrConstructor(method, 0); <add> ResolvableType type = ResolvableType.forMethodParameter(methodParameter, TypedMethods.class); <add> assertThat(type.resolve(), equalTo((Class) String.class)); <add> assertThat(type.getType().toString(), equalTo("T")); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromMethodReturn() throws Exception { <add> Method method = Methods.class.getMethod("typedReturn"); <add> ResolvableType type = ResolvableType.forMethodReturn(method); <add> assertThat(type.resolve(), nullValue()); <add> assertThat(type.getType().toString(), equalTo("T")); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromMethodReturnWithImplementsClass() throws Exception { <add> Method method = Methods.class.getMethod("typedReturn"); <add> ResolvableType type = ResolvableType.forMethodReturn(method, TypedMethods.class); <add> assertThat(type.resolve(), equalTo((Class) String.class)); <add> assertThat(type.getType().toString(), equalTo("T")); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromType() throws Exception { <add> Type sourceType = Methods.class.getMethod("typedReturn").getGenericReturnType(); <add> ResolvableType type = ResolvableType.forType(sourceType); <add> assertThat(type.resolve(), nullValue()); <add> assertThat(type.getType().toString(), equalTo("T")); <add> } <add> <add> @Test <add> public void resolveTypeVariableFromTypeWithVariableResolver() throws Exception { <add> Type sourceType = Methods.class.getMethod("typedReturn").getGenericReturnType(); <add> ResolvableType type = ResolvableType.forType( <add> sourceType, ResolvableType.forClass(TypedMethods.class).as(Methods.class)); <add> assertThat(type.resolve(), equalTo((Class) String.class)); <add> assertThat(type.getType().toString(), equalTo("T")); <add> } <add> <add> @Test <add> public void resolveTypeWithCustomVariableResolver() throws Exception { <add> TypeVariableResolver variableResolver = mock(TypeVariableResolver.class); <add> given(variableResolver.resolveVariable((TypeVariable<?>) anyObject())).willReturn(Long.class); <add> <add> ResolvableType variable = ResolvableType.forType( <add> Fields.class.getField("typeVariableType").getGenericType(), variableResolver); <add> ResolvableType parameterized = ResolvableType.forType( <add> Fields.class.getField("parameterizedType").getGenericType(), variableResolver); <add> <add> assertThat(variable.resolve(), equalTo((Class) Long.class)); <add> assertThat(parameterized.resolve(), equalTo((Class) List.class)); <add> assertThat(parameterized.resolveGeneric(), equalTo((Class) Long.class)); <add> verify(variableResolver, atLeastOnce()).resolveVariable(this.typeVariableCaptor.capture()); <add> assertThat(this.typeVariableCaptor.getValue().getName(), equalTo("T")); <add> } <add> <add> @Test <add> public void toStrings() throws Exception { <add> assertThat(ResolvableType.NONE.toString(), equalTo("?")); <add> <add> assertFieldToStringValue("classType", "java.util.List"); <add> assertFieldToStringValue("typeVariableType", "?"); <add> assertFieldToStringValue("parameterizedType", "java.util.List<?>"); <add> assertFieldToStringValue("arrayClassType", "java.util.List[]"); <add> assertFieldToStringValue("genericArrayType", "java.util.List<java.lang.String>[]"); <add> assertFieldToStringValue("genericMultiArrayType", "java.util.List<java.lang.String>[][][]"); <add> assertFieldToStringValue("wildcardType", "java.util.List<java.lang.Number>"); <add> assertFieldToStringValue("wildcardSuperType", "java.util.List<java.lang.Number>"); <add> assertFieldToStringValue("charSequenceList", "java.util.List<java.lang.CharSequence>"); <add> assertFieldToStringValue("stringList", "java.util.List<java.lang.String>"); <add> assertFieldToStringValue("stringListList", "java.util.List<java.util.List<java.lang.String>>"); <add> assertFieldToStringValue("stringArrayList", "java.util.List<java.lang.String[]>"); <add> assertFieldToStringValue("stringIntegerMultiValueMap", "org.springframework.util.MultiValueMap<java.lang.String, java.lang.Integer>"); <add> assertFieldToStringValue("stringIntegerMultiValueMapSwitched", VariableNameSwitch.class.getName() + "<java.lang.Integer, java.lang.String>"); <add> assertFieldToStringValue("listOfListOfUnknown", "java.util.List<java.util.List>"); <add> <add> assertTypedFieldToStringValue("typeVariableType", "java.lang.String"); <add> assertTypedFieldToStringValue("parameterizedType", "java.util.List<java.lang.String>"); <add> <add> assertThat(ResolvableType.forClass(ListOfGenericArray.class).toString(), equalTo(ListOfGenericArray.class.getName())); <add> assertThat(ResolvableType.forClass(List.class, ListOfGenericArray.class).toString(), equalTo("java.util.List<java.util.List<java.lang.String>[]>")); <add> } <add> <add> private void assertFieldToStringValue(String field, String expected) throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField(field)); <add> assertThat("field " + field + " toString", type.toString(), equalTo(expected)); <add> } <add> <add> private void assertTypedFieldToStringValue(String field, String expected) <add> throws Exception { <add> ResolvableType type = ResolvableType.forField(Fields.class.getField(field), TypedFields.class); <add> assertThat("field " + field + " toString", type.toString(), equalTo(expected)); <add> } <add> <add> @Test <add> public void resolveFromOuterClass() throws Exception { <add> Field field = EnclosedInParameterizedType.InnerTyped.class.getField("field"); <add> ResolvableType type = ResolvableType.forField( <add> field, TypedEnclosedInParameterizedType.TypedInnerTyped.class); <add> assertThat(type.resolve(), equalTo((Type) Integer.class)); <add> } <add> <add> @Test <add> public void isAssignableFromMustNotBeNull() throws Exception { <add> this.thrown.expect(IllegalArgumentException.class); <add> this.thrown.expectMessage("Type must not be null"); <add> ResolvableType.forClass(Object.class).isAssignableFrom(null); <add> } <add> <add> @Test <add> public void isAssignableFromForNone() throws Exception { <add> ResolvableType objectType = ResolvableType.forClass(Object.class); <add> assertThat(objectType.isAssignableFrom(ResolvableType.NONE), equalTo(false)); <add> assertThat(ResolvableType.NONE.isAssignableFrom(objectType), equalTo(false)); <add> } <add> <add> @Test <add> public void isAssignableFromForClassAndClass() throws Exception { <add> ResolvableType objectType = ResolvableType.forClass(Object.class); <add> ResolvableType charSequenceType = ResolvableType.forClass(CharSequence.class); <add> ResolvableType stringType = ResolvableType.forClass(String.class); <add> <add> assertAssignable(objectType, objectType, charSequenceType, stringType).equalTo(true, true, true); <add> assertAssignable(charSequenceType, objectType, charSequenceType, stringType).equalTo(false, true, true); <add> assertAssignable(stringType, objectType, charSequenceType, stringType).equalTo(false, false, true); <add> } <add> <add> @Test <add> public void isAssignableFromCannotBeResolved() throws Exception { <add> ResolvableType objectType = ResolvableType.forClass(Object.class); <add> ResolvableType unresolvableVariable = ResolvableType.forField(AssignmentBase.class.getField("o")); <add> assertThat(unresolvableVariable.resolve(), nullValue()); <add> assertAssignable(objectType, unresolvableVariable).equalTo(false); <add> assertAssignable(unresolvableVariable, objectType).equalTo(false); <add> } <add> <add> @Test <add> public void isAssignableFromForClassAndSimpleVariable() throws Exception { <add> ResolvableType objectType = ResolvableType.forClass(Object.class); <add> ResolvableType charSequenceType = ResolvableType.forClass(CharSequence.class); <add> ResolvableType stringType = ResolvableType.forClass(String.class); <add> <add> ResolvableType objectVariable = ResolvableType.forField(AssignmentBase.class.getField("o"), Assignment.class); <add> ResolvableType charSequenceVariable = ResolvableType.forField(AssignmentBase.class.getField("c"), Assignment.class); <add> ResolvableType stringVariable = ResolvableType.forField(AssignmentBase.class.getField("s"), Assignment.class); <add> <add> assertAssignable(objectType, objectVariable, charSequenceVariable, stringVariable).equalTo(true, true, true); <add> assertAssignable(charSequenceType, objectVariable, charSequenceVariable, stringVariable).equalTo(false, true, true); <add> assertAssignable(stringType, objectVariable, charSequenceVariable, stringVariable).equalTo(false, false, true); <add> <add> assertAssignable(objectVariable, objectType, charSequenceType, stringType).equalTo(true, true, true); <add> assertAssignable(charSequenceVariable, objectType, charSequenceType, stringType).equalTo(false, true, true); <add> assertAssignable(stringVariable, objectType, charSequenceType, stringType).equalTo(false, false, true); <add> <add> assertAssignable(objectVariable, objectVariable, charSequenceVariable, stringVariable).equalTo(true, true, true); <add> assertAssignable(charSequenceVariable, objectVariable, charSequenceVariable, stringVariable).equalTo(false, true, true); <add> assertAssignable(stringVariable, objectVariable, charSequenceVariable, stringVariable).equalTo(false, false, true); <add> } <add> <add> @Test <add> public void isAssignableFromForSameClassNonExtendsGenerics() throws Exception { <add> ResolvableType objectList = ResolvableType.forField(AssignmentBase.class.getField("listo"), Assignment.class); <add> ResolvableType stringList = ResolvableType.forField(AssignmentBase.class.getField("lists"), Assignment.class); <add> <add> assertAssignable(stringList, objectList).equalTo(false); <add> assertAssignable(objectList, stringList).equalTo(false); <add> assertAssignable(stringList, stringList).equalTo(true); <add> } <add> <add> @Test <add> public void isAssignableFromForSameClassExtendsGenerics() throws Exception { <add> <add> // Generic assignment can be a little confusing, given: <add> // <add> // List<CharSequence> c1, List<? extends CharSequence> c2, List<String> s; <add> // <add> // c2 = s; is allowed and is often used for argument input, for example <add> // see List.addAll(). You can get items from c2 but you cannot add items without <add> // getting a generic type 'is not applicable for the arguments' error. This makes <add> // sense since if you added a StringBuffer to c2 it would break the rules on s. <add> // <add> // c1 = s; not allowed. Since there is no '? extends' to cause the generic <add> // 'is not applicable for the arguments' error when adding (which would pollute <add> // s). <add> <add> ResolvableType objectList = ResolvableType.forField(AssignmentBase.class.getField("listo"), Assignment.class); <add> ResolvableType charSequenceList = ResolvableType.forField(AssignmentBase.class.getField("listc"), Assignment.class); <add> ResolvableType stringList = ResolvableType.forField(AssignmentBase.class.getField("lists"), Assignment.class); <add> ResolvableType extendsObjectList = ResolvableType.forField(AssignmentBase.class.getField("listxo"), Assignment.class); <add> ResolvableType extendsCharSequenceList = ResolvableType.forField(AssignmentBase.class.getField("listxc"), Assignment.class); <add> ResolvableType extendsStringList = ResolvableType.forField(AssignmentBase.class.getField("listxs"), Assignment.class); <add> <add> assertAssignable(objectList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(false, false, false); <add> assertAssignable(charSequenceList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(false, false, false); <add> assertAssignable(stringList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(false, false, false); <add> assertAssignable(extendsObjectList, objectList, charSequenceList, stringList).equalTo(true, true, true); <add> assertAssignable(extendsObjectList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(true, true, true); <add> assertAssignable(extendsCharSequenceList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(false, true, true); <add> assertAssignable(extendsCharSequenceList, objectList, charSequenceList, stringList).equalTo(false, true, true); <add> assertAssignable(extendsStringList, extendsObjectList, extendsCharSequenceList, extendsStringList).equalTo(false, false, true); <add> assertAssignable(extendsStringList, objectList, charSequenceList, stringList).equalTo(false, false, true); <add> } <add> <add> @Test <add> public void isAssignableFromForDifferentClassesWithGenerics() throws Exception { <add> ResolvableType extendsCharSequenceCollection = ResolvableType.forField(AssignmentBase.class.getField("collectionxc"), Assignment.class); <add> ResolvableType charSequenceCollection = ResolvableType.forField(AssignmentBase.class.getField("collectionc"), Assignment.class); <add> ResolvableType charSequenceList = ResolvableType.forField(AssignmentBase.class.getField("listc"), Assignment.class); <add> ResolvableType extendsCharSequenceList = ResolvableType.forField(AssignmentBase.class.getField("listxc"), Assignment.class); <add> ResolvableType extendsStringList = ResolvableType.forField(AssignmentBase.class.getField("listxs"), Assignment.class); <add> <add> assertAssignable(extendsCharSequenceCollection, charSequenceCollection, charSequenceList, extendsCharSequenceList, extendsStringList) <add> .equalTo(true, true, true, true); <add> assertAssignable(charSequenceCollection, charSequenceList, extendsCharSequenceList, extendsStringList) <add> .equalTo(true, false, false); <add> assertAssignable(charSequenceList, extendsCharSequenceCollection, charSequenceCollection) <add> .equalTo(false, false); <add> assertAssignable(extendsCharSequenceList, extendsCharSequenceCollection, charSequenceCollection) <add> .equalTo(false, false); <add> assertAssignable(extendsStringList, charSequenceCollection, charSequenceList, extendsCharSequenceList) <add> .equalTo(false, false, false); <add> } <add> <add> @Test <add> public void isAssignableFromForArrays() throws Exception { <add> ResolvableType object = ResolvableType.forField(AssignmentBase.class.getField("o"), Assignment.class); <add> ResolvableType objectArray = ResolvableType.forField(AssignmentBase.class.getField("oarray"), Assignment.class); <add> ResolvableType charSequenceArray = ResolvableType.forField(AssignmentBase.class.getField("carray"), Assignment.class); <add> ResolvableType stringArray = ResolvableType.forField(AssignmentBase.class.getField("sarray"), Assignment.class); <add> <add> assertAssignable(object, objectArray, charSequenceArray, stringArray). <add> equalTo(true, true, true); <add> assertAssignable(objectArray, object, objectArray, charSequenceArray, stringArray). <add> equalTo(false, true, true, true); <add> assertAssignable(charSequenceArray, object, objectArray, charSequenceArray, stringArray). <add> equalTo(false, false, true, true); <add> assertAssignable(stringArray, object, objectArray, charSequenceArray, stringArray). <add> equalTo(false, false, false, true); <add> } <add> <add> @Test <add> public void isAssignableFromForWildcards() throws Exception { <add> <add> ResolvableType object = ResolvableType.forClass(Object.class); <add> ResolvableType charSequence = ResolvableType.forClass(CharSequence.class); <add> ResolvableType string = ResolvableType.forClass(String.class); <add> ResolvableType extendsObject = ResolvableType.forField(AssignmentBase.class.getField("listxo"), Assignment.class).getGeneric(); <add> ResolvableType extendsCharSequence = ResolvableType.forField(AssignmentBase.class.getField("listxc"), Assignment.class).getGeneric(); <add> ResolvableType extendsString = ResolvableType.forField(AssignmentBase.class.getField("listxs"), Assignment.class).getGeneric(); <add> ResolvableType superObject = ResolvableType.forField(AssignmentBase.class.getField("listso"), Assignment.class).getGeneric(); <add> ResolvableType superCharSequence = ResolvableType.forField(AssignmentBase.class.getField("listsc"), Assignment.class).getGeneric(); <add> ResolvableType superString = ResolvableType.forField(AssignmentBase.class.getField("listss"), Assignment.class).getGeneric(); <add> <add> // Language Spec 4.5.1. Type Arguments and Wildcards <add> <add> // ? extends T <= ? extends S if T <: S <add> assertAssignable(extendsCharSequence, extendsObject, extendsCharSequence, extendsString). <add> equalTo(false, true, true); <add> assertAssignable(extendsCharSequence, object, charSequence, string). <add> equalTo(false, true, true); <add> <add> // ? super T <= ? super S if S <: T <add> assertAssignable(superCharSequence, superObject, superCharSequence, superString). <add> equalTo(true, true, false); <add> assertAssignable(superCharSequence, object, charSequence, string). <add> equalTo(true, true, false); <add> <add> // [Implied] super / extends cannot be mixed <add> assertAssignable(superCharSequence, extendsObject, extendsCharSequence, extendsString). <add> equalTo(false, false, false); <add> assertAssignable(extendsCharSequence, superObject, superCharSequence, superString). <add> equalTo(false, false, false); <add> <add> // T <= T <add> assertAssignable(charSequence, object, charSequence, string). <add> equalTo(false, true, true); <add> <add> // T <= ? extends T <add> assertAssignable(extendsCharSequence, object, charSequence, string). <add> equalTo(false, true, true); <add> assertAssignable(charSequence, extendsObject, extendsCharSequence, extendsString). <add> equalTo(false, false, false); <add> <add> // T <= ? super T <add> assertAssignable(superCharSequence, object, charSequence, string). <add> equalTo(true, true, false); <add> assertAssignable(charSequence, superObject, superCharSequence, superString). <add> equalTo(false, false, false); <add> } <add> <add> @Test <add> public void isAssignableFromForComplexWildcards() throws Exception { <add> ResolvableType complex1 = ResolvableType.forField(AssignmentBase.class.getField("complexWildcard1")); <add> ResolvableType complex2 = ResolvableType.forField(AssignmentBase.class.getField("complexWildcard2")); <add> ResolvableType complex3 = ResolvableType.forField(AssignmentBase.class.getField("complexWildcard3")); <add> ResolvableType complex4 = ResolvableType.forField(AssignmentBase.class.getField("complexWildcard4")); <add> <add> assertAssignable(complex1, complex2).equalTo(true); <add> assertAssignable(complex2, complex1).equalTo(false); <add> assertAssignable(complex3, complex4).equalTo(true); <add> assertAssignable(complex4, complex3).equalTo(false); <add> } <add> <add> @Test <add> public void hashCodeAndEquals() throws Exception { <add> ResolvableType forClass = ResolvableType.forClass(List.class); <add> ResolvableType forFieldDirect = ResolvableType.forField(Fields.class.getDeclaredField("stringList")); <add> ResolvableType forFieldViaType = ResolvableType.forType(Fields.class.getDeclaredField("stringList").getGenericType()); <add> ResolvableType forFieldWithImplementation = ResolvableType.forField(Fields.class.getDeclaredField("stringList"), TypedFields.class); <add> <add> assertThat(forClass, equalTo(forClass)); <add> assertThat(forClass.hashCode(), equalTo(forClass.hashCode())); <add> assertThat(forClass, not(equalTo(forFieldDirect))); <add> assertThat(forClass, not(equalTo(forFieldWithImplementation))); <add> <add> assertThat(forFieldDirect, equalTo(forFieldDirect)); <add> assertThat(forFieldDirect, equalTo(forFieldViaType)); <add> assertThat(forFieldDirect, not(equalTo(forFieldWithImplementation))); <add> } <add> <add> @SuppressWarnings("unused") <add> private HashMap<Integer, List<String>> myMap; <add> <add> @Test <add> public void javaDocSample() throws Exception { <add> ResolvableType t = ResolvableType.forField(getClass().getDeclaredField("myMap")); <add> assertThat(t.getSuperType().toString(), equalTo("java.util.AbstractMap<java.lang.Integer, java.util.List<java.lang.String>>")); <add> assertThat(t.asMap().toString(), equalTo("java.util.Map<java.lang.Integer, java.util.List<java.lang.String>>")); <add> assertThat(t.getGeneric(0).resolve(), equalTo((Class)Integer.class)); <add> assertThat(t.getGeneric(1).resolve(), equalTo((Class)List.class)); <add> assertThat(t.getGeneric(1).toString(), equalTo("java.util.List<java.lang.String>")); <add> assertThat(t.resolveGeneric(1, 0), equalTo((Class) String.class)); <add> } <add> <add> <add> private static AssertAssignbleMatcher assertAssignable(final ResolvableType type, <add> final ResolvableType... fromTypes) { <add> return new AssertAssignbleMatcher() { <add> @Override <add> public void equalTo(boolean... values) { <add> for (int i = 0; i < fromTypes.length; i++) { <add> assertThat(stringDesc(type) + " isAssignableFrom " <add> + stringDesc(fromTypes[i]), <add> type.isAssignableFrom(fromTypes[i]), <add> Matchers.equalTo(values[i])); <add> } <add> } <add> }; <add> } <add> <add> private static String stringDesc(ResolvableType type) { <add> if (type == ResolvableType.NONE) { <add> return "NONE"; <add> } <add> if (type.getType().getClass().equals(Class.class)) { <add> return type.toString(); <add> } <add> return type.getType() + ":" + type; <add> } <add> <add> <add> private static interface AssertAssignbleMatcher { <add> <add> void equalTo(boolean... values); <add> <add> } <add> <add> <add> static class ExtendsList extends ArrayList<CharSequence> { <add> <add> } <add> <add> <add> static class ExtendsMap extends HashMap<String, Integer> { <add> <add> } <add> <add> <add> static class Fields<T> { <add> <add> public List classType; <add> <add> public T typeVariableType; <add> <add> public List<T> parameterizedType; <add> <add> public List[] arrayClassType; <add> <add> public List<String>[] genericArrayType; <add> <add> public List<String>[][][] genericMultiArrayType; <add> <add> public List<? extends Number> wildcardType; <add> <add> public List<? super Number> wildcardSuperType = new ArrayList<Object>(); <add> <add> public List<CharSequence> charSequenceList; <add> <add> public List<String> stringList; <add> <add> public List<List<String>> stringListList; <add> <add> public List<String[]> stringArrayList; <add> <add> public MultiValueMap<String, Integer> stringIntegerMultiValueMap; <add> <add> public VariableNameSwitch<Integer, String> stringIntegerMultiValueMapSwitched; <add> <add> public List<List> listOfListOfUnknown; <add> <add> @SuppressWarnings("unused") <add> private List<String> privateField; <add> <add> public Map<Map<String, Integer>, Map<Byte, Long>> nested; <add> <add> } <add> <add> <add> static class TypedFields extends Fields<String> { <add> <add> } <add> <add> <add> static interface Methods<T> { <add> <add> List<CharSequence> charSequenceReturn(); <add> <add> void charSequenceParameter(List<CharSequence> cs); <add> <add> <R extends CharSequence & Serializable> R boundedTypeVaraibleResult(); <add> <add> void nested(Map<Map<String, Integer>, Map<Byte, Long>> p); <add> <add> void typedParameter(T p); <add> <add> T typedReturn(); <add> <add> } <add> <add> <add> static class AssignmentBase<O, C, S> { <add> <add> public O o; <add> <add> public C c; <add> <add> public S s; <add> <add> public List<O> listo; <add> <add> public List<C> listc; <add> <add> public List<S> lists; <add> <add> public List<? extends O> listxo; <add> <add> public List<? extends C> listxc; <add> <add> public List<? extends S> listxs; <add> <add> public List<? super O> listso; <add> <add> public List<? super C> listsc; <add> <add> public List<? super S> listss; <add> <add> public O[] oarray; <add> <add> public C[] carray; <add> <add> public S[] sarray; <add> <add> public Collection<C> collectionc; <add> <add> public Collection<? extends C> collectionxc; <add> <add> public Map<? super Integer, List<String>> complexWildcard1; <add> <add> public MultiValueMap<Number, String> complexWildcard2; <add> <add> public Collection<? extends Collection<? extends CharSequence>> complexWildcard3; <add> <add> public List<List<String>> complexWildcard4; <add> <add> } <add> <add> <add> static class Assignment extends AssignmentBase<Object, CharSequence, String> { <add> <add> } <add> <add> <add> static interface TypedMethods extends Methods<String> { <add> <add> } <add> <add> <add> static class Constructors<T> { <add> <add> public Constructors(List<CharSequence> p) { <add> } <add> <add> public Constructors(Map<T, Long> p) { <add> } <add> <add> } <add> <add> <add> static class TypedConstructors extends Constructors<String> { <add> <add> public TypedConstructors(List<CharSequence> p) { <add> super(p); <add> } <add> <add> public TypedConstructors(Map<String, Long> p) { <add> super(p); <add> } <add> <add> } <add> <add> <add> public interface MyInterfaceType<T> { <add> <add> } <add> <add> <add> public class MySimpleInterfaceType implements MyInterfaceType<String> { <add> <add> } <add> <add> <add> public class MyCollectionInterfaceType implements MyInterfaceType<Collection<String>> { <add> <add> } <add> <add> <add> public abstract class MySuperclassType<T> { <add> <add> } <add> <add> <add> public class MySimpleSuperclassType extends MySuperclassType<String> { <add> <add> } <add> <add> <add> public class MyCollectionSuperclassType extends MySuperclassType<Collection<String>> { <add> <add> } <add> <add> <add> static interface Wildcard<T extends Number> extends List<T> { <add> <add> } <add> <add> <add> static interface RawExtendsWildcard extends Wildcard { <add> <add> } <add> <add> <add> static interface VariableNameSwitch<V, K> extends MultiValueMap<K, V> { <add> <add> } <add> <add> <add> static interface ListOfGenericArray extends List<List<String>[]> { <add> <add> } <add> <add> <add> static class EnclosedInParameterizedType<T> { <add> <add> static class InnerRaw { <add> } <add> <add> class InnerTyped<Y> { <add> <add> public T field; <add> } <add> <add> } <add> <add> <add> static class TypedEnclosedInParameterizedType extends <add> EnclosedInParameterizedType<Integer> { <add> <add> class TypedInnerTyped extends InnerTyped<Long> { <add> } <add> <add> } <add> <add>}
3
Javascript
Javascript
reduce concurrent memory footprint of pdf2svg.js
0cc173580934c3420ab3f1bf5d2dbe67e8e4599c
<ide><path>examples/node/pdf2svg.js <ide> var pdfPath = process.argv[2] || '../../web/compressed.tracemonkey-pldi-09.pdf'; <ide> var data = new Uint8Array(fs.readFileSync(pdfPath)); <ide> <ide> // Dumps svg outputs to a folder called svgdump <del>function writeToFile(svgdump, pageNum) { <add>function writeToFile(svgdump, pageNum, callback) { <ide> var name = getFileNameFromPath(pdfPath); <ide> fs.mkdir('./svgdump/', function(err) { <ide> if (!err || err.code === 'EEXIST') { <ide> function writeToFile(svgdump, pageNum) { <ide> } else { <ide> console.log('Page: ' + pageNum); <ide> } <add> callback(); <ide> }); <add> } else { <add> callback(); <ide> } <ide> }); <ide> } <ide> pdfjsLib.getDocument({ <ide> svgGfx.embedFonts = true; <ide> return svgGfx.getSVG(opList, viewport).then(function (svg) { <ide> var svgDump = svg.toString(); <del> writeToFile(svgDump, pageNum); <add> return new Promise(function(resolve) { <add> writeToFile(svgDump, pageNum, resolve); <add> }); <ide> }); <ide> }); <ide> })
1
Ruby
Ruby
avoid hash duplication by skipping mutation
1993e2ccbd7c5651278ea30bdc9d8034f5197945
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> class Generator <ide> def initialize(named_route, options, recall, set) <ide> @named_route = named_route <ide> @options = options <del> @recall = recall.dup <add> @recall = recall <ide> @set = set <ide> <ide> normalize_recall! <ide> def current_controller <ide> def use_recall_for(key) <ide> if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key]) <ide> if !named_route_exists? || segment_keys.include?(key) <del> @options[key] = @recall.delete(key) <add> @options[key] = @recall[key] <ide> end <ide> end <ide> end
1
Ruby
Ruby
fix resources ignoring scope options
a7edddf605d2ffbb6669365dcd23d6e4c6c2cf84
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def initialize(*args) #:nodoc: <ide> <ide> def resource(*resources, &block) <ide> options = resources.extract_options! <add> options = (@scope[:options] || {}).merge(options) <ide> <ide> if apply_common_behavior_for(:resource, resources, options, &block) <ide> return self <ide> def resource(*resources, &block) <ide> <ide> def resources(*resources, &block) <ide> options = resources.extract_options! <add> options = (@scope[:options] || {}).merge(options) <ide> <ide> if apply_common_behavior_for(:resources, resources, options, &block) <ide> return self <ide><path>actionpack/test/dispatch/routing_test.rb <ide> def self.matches?(request) <ide> root :to => 'projects#index' <ide> end <ide> <del> resources :products, :constraints => { :id => /\d{4}/ } do <del> root :to => "products#root" <del> get :favorite, :on => :collection <del> resources :images <add> scope :only => [:index, :show] do <add> resources :products, :constraints => { :id => /\d{4}/ } do <add> root :to => "products#root" <add> get :favorite, :on => :collection <add> resources :images <add> end <add> resource :account <ide> end <ide> <ide> resource :dashboard, :constraints => { :ip => /192\.168\.1\.\d{1,3}/ } <ide> def test_resource_new_actions <ide> end <ide> end <ide> <add> def test_resource_merges_options_from_scope <add> with_test_routes do <add> assert_raise(NameError) { new_account_path } <add> <add> get '/account/new' <add> assert_equal 404, status <add> end <add> end <add> <add> def test_resources_merges_options_from_scope <add> with_test_routes do <add> assert_raise(NoMethodError) { edit_product_path('1') } <add> <add> get '/products/1/edit' <add> assert_equal 404, status <add> <add> assert_raise(NoMethodError) { edit_product_image_path('1', '2') } <add> <add> post '/products/1/images/2/edit' <add> assert_equal 404, status <add> end <add> end <add> <ide> private <ide> def with_test_routes <ide> yield
2
PHP
PHP
add missing rawurlencode()
76711c9f7129e09a6da72b930d6d364fbfd14e04
<ide><path>lib/Cake/Routing/Router.php <ide> protected static function _handleNoRoute($url) { <ide> $output = implode('/', $urlOut); <ide> <ide> if (!empty($args)) { <del> $output .= '/' . implode('/', $args); <add> $output .= '/' . implode('/', array_map('rawurlencode', $args)); <ide> } <ide> <ide> if (!empty($named)) { <ide> foreach ($named as $name => $value) { <ide> if (is_array($value)) { <ide> $flattend = Set::flatten($value, ']['); <ide> foreach ($flattend as $namedKey => $namedValue) { <del> $output .= '/' . $name . "[$namedKey]" . self::$_namedConfig['separator'] . $namedValue; <add> $output .= '/' . $name . "[$namedKey]" . self::$_namedConfig['separator'] . rawurlencode($namedValue); <ide> } <ide> } else { <del> $output .= '/' . $name . self::$_namedConfig['separator'] . $value; <add> $output .= '/' . $name . self::$_namedConfig['separator'] . rawurlencode($value); <ide> } <ide> } <ide> } <ide><path>lib/Cake/Test/Case/Routing/RouterTest.php <ide> public function testArrayNamedParameters() { <ide> 'keyed' => 'is an array', <ide> 'test' <ide> ))); <del> $expected = '/tests/index/namedParam[keyed]:is an array/namedParam[0]:test'; <add> $expected = '/tests/index/namedParam[keyed]:is%20an%20array/namedParam[0]:test'; <ide> $this->assertEquals($expected, $result); <ide> } <ide> <ide> public function testPrefixOverride() { <ide> */ <ide> public function testPrefixFalseIgnored() { <ide> Configure::write('Routing.prefixes', array('admin')); <add> Router::reload(); <add> <ide> Router::connect('/cache_css/*', array('admin' => false, 'controller' => 'asset_compress', 'action' => 'get')); <ide> <ide> $url = Router::url(array('controller' => 'asset_compress', 'action' => 'get', 'test'));
2
Javascript
Javascript
default the unit per em size to 1000
fdacb575c5601a205cdfc0c2d050ab57a536e0ef
<ide><path>PDFFont.js <ide> Type1Font.prototype = { <ide> 0x00, 0x00, 0x00, 0x00, // checksumAdjustement <ide> 0x5F, 0x0F, 0x3C, 0xF5, // magicNumber <ide> 0x00, 0x00, // Flags <del> 0x00, 0x40, // unitsPerEM (>= 16 && <=16384) <add> 0x03, 0xE8, // unitsPerEM (>= 16 && <=16384) <ide> 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // created <ide> 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // modified <ide> 0x00, 0x00, // xMin
1
Text
Text
add note about invalid data
c0905b71adb55cbf98816dd993fec2d7c17ebbfe
<ide><path>doc/api/buffer.md <ide> added: v0.1.90 <ide> <ide> Decodes `buf` to a string according to the specified character encoding in <ide> `encoding`. `start` and `end` may be passed to decode only a subset of `buf`. <add>If a byte sequence in the input is not valid in the given `encoding` then <add>it is replaced with the replacement character `U+FFFD`. <ide> <ide> The maximum length of a string instance (in UTF-16 code units) is available <ide> as [`buffer.constants.MAX_STRING_LENGTH`][].
1
Text
Text
add .overlay to the list
dd0bed9bff3e69e428dfcb46ac081b213698e16e
<ide><path>docs/upgrading/upgrading-your-ui-theme.md <ide> Old Selector | New Selector <ide> `.panel-bottom` | `atom-panel[location="bottom"]` <ide> `.panel-left` | `atom-panel[location="left"]` <ide> `.panel-right` | `atom-panel[location="right"]` <add>`.overlay` | `atom-panel[location="modal"]` <ide> <ide> ## Supporting the Shadow DOM <ide>
1
Python
Python
fix beitfeatureextractor postprocessing
36b9a99433b03d9caa8cae48c65348d165bec601
<ide><path>src/transformers/models/beit/feature_extraction_beit.py <ide> def __call__( <ide> <ide> return encoded_inputs <ide> <del> def post_process_semantic_segmentation(self, outputs, target_sizes: Union[TensorType, List[Tuple]] = None): <add> def post_process_semantic_segmentation(self, outputs, target_sizes: List[Tuple] = None): <ide> """ <ide> Converts the output of [`BeitForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch. <ide> <ide> Args: <ide> outputs ([`BeitForSemanticSegmentation`]): <ide> Raw outputs of the model. <del> target_sizes (`torch.Tensor` of shape `(batch_size, 2)` or `List[Tuple]` of length `batch_size`, *optional*): <del> Torch Tensor (or list) corresponding to the requested final size (h, w) of each prediction. If left to <add> target_sizes (`List[Tuple]` of length `batch_size`, *optional*): <add> List of tuples corresponding to the requested final size (height, width) of each prediction. If left to <ide> None, predictions will not be resized. <ide> Returns: <del> semantic_segmentation: `torch.Tensor` of shape `(batch_size, 2)` or `List[torch.Tensor]` of length <del> `batch_size`, where each item is a semantic segmentation map of of the corresponding target_sizes entry (if <del> `target_sizes` is specified). Each entry of each `torch.Tensor` correspond to a semantic class id. <add> semantic_segmentation: `List[torch.Tensor]` of length `batch_size`, where each item is a semantic <add> segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is <add> specified). Each entry of each `torch.Tensor` correspond to a semantic class id. <ide> """ <ide> logits = outputs.logits <ide> <del> if len(logits) != len(target_sizes): <del> raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the logits") <del> <del> if target_sizes is not None and target_sizes.shape[1] != 2: <del> raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch") <del> <del> semantic_segmentation = logits.argmax(dim=1) <del> <del> # Resize semantic segmentation maps <add> # Resize logits and compute semantic segmentation maps <ide> if target_sizes is not None: <add> if len(logits) != len(target_sizes): <add> raise ValueError( <add> "Make sure that you pass in as many target sizes as the batch dimension of the logits" <add> ) <add> <ide> if is_torch_tensor(target_sizes): <ide> target_sizes = target_sizes.numpy() <ide> <del> resized_maps = [] <del> semantic_segmentation = semantic_segmentation.numpy() <add> semantic_segmentation = [] <ide> <del> for idx in range(len(semantic_segmentation)): <del> resized = self.resize(image=semantic_segmentation[idx], size=target_sizes[idx]) <del> resized_maps.append(resized) <del> <del> semantic_segmentation = [torch.Tensor(np.array(image)) for image in resized_maps] <add> for idx in range(len(logits)): <add> resized_logits = torch.nn.functional.interpolate( <add> logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False <add> ) <add> semantic_map = resized_logits[0].argmax(dim=0) <add> semantic_segmentation.append(semantic_map) <add> else: <add> semantic_segmentation = logits.argmax(dim=1) <add> semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])] <ide> <ide> return semantic_segmentation <ide><path>tests/models/beit/test_modeling_beit.py <ide> def test_inference_semantic_segmentation(self): <ide> ) <ide> <ide> self.assertTrue(torch.allclose(logits[0, :3, :3, :3], expected_slice, atol=1e-4)) <add> <add> @slow <add> def test_post_processing_semantic_segmentation(self): <add> model = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640") <add> model = model.to(torch_device) <add> <add> feature_extractor = BeitFeatureExtractor(do_resize=True, size=640, do_center_crop=False) <add> <add> ds = load_dataset("hf-internal-testing/fixtures_ade20k", split="test") <add> image = Image.open(ds[0]["file"]) <add> inputs = feature_extractor(images=image, return_tensors="pt").to(torch_device) <add> <add> # forward pass <add> with torch.no_grad(): <add> outputs = model(**inputs) <add> <add> outputs.logits = outputs.logits.detach().cpu() <add> <add> segmentation = feature_extractor.post_process_semantic_segmentation(outputs=outputs, target_sizes=[(500, 300)]) <add> expected_shape = torch.Size((500, 300)) <add> self.assertEqual(segmentation[0].shape, expected_shape) <add> <add> segmentation = feature_extractor.post_process_semantic_segmentation(outputs=outputs) <add> expected_shape = torch.Size((160, 160)) <add> self.assertEqual(segmentation[0].shape, expected_shape)
2
Text
Text
add note about prefetching
d2dc91c80ce9708aae6055cff1ef6cb9f67bf98a
<ide><path>docs/api-reference/next/link.md <ide> export default Home <ide> - `href` - The path or URL to navigate to. This is the only required prop <ide> - `as` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked <ide> - [`passHref`](#if-the-child-is-a-custom-component-that-wraps-an-a-tag) - Forces `Link` to send the `href` property to its child. Defaults to `false` <del>- `prefetch` - Prefetch the page in the background. Defaults to `true`. Any `<Link />` that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passing `prefetch={false}`. Pages using [Static Generation](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) will preload `JSON` files with the data for faster page transitions <add>- `prefetch` - Prefetch the page in the background. Defaults to `true`. Any `<Link />` that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passing `prefetch={false}`. Pages using [Static Generation](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) will preload `JSON` files with the data for faster page transitions. Prefetching is only enabled in production. <ide> - [`replace`](#replace-the-url-instead-of-push) - Replace the current `history` state instead of adding a new url into the stack. Defaults to `false` <ide> - [`scroll`](#disable-scrolling-to-the-top-of-the-page) - Scroll to the top of the page after a navigation. Defaults to `true` <ide> - [`shallow`](/docs/routing/shallow-routing.md) - Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation), [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) or [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). Defaults to `false`
1
Ruby
Ruby
install etc/var files on postinstall
f951a22beacdae7dd95c94eba67236fe221a3ca0
<ide><path>Library/Homebrew/cmd/postinstall.rb <ide> module Homebrew <ide> module_function <ide> <ide> def postinstall <del> ARGV.resolved_formulae.each { |f| run_post_install(f) if f.post_install_defined? } <add> ARGV.resolved_formulae.each do |f| <add> ohai "Postinstalling #{f}" <add> run_post_install(f) <add> end <ide> end <ide> <ide> def run_post_install(formula) <ide><path>Library/Homebrew/formula.rb <ide> def pour_bottle_check_unsatisfied_reason <ide> # Can be overridden to run commands on both source and bottle installation. <ide> def post_install; end <ide> <del> # @private <del> def post_install_defined? <del> method(:post_install).owner == self.class <del> end <del> <ide> # @private <ide> def run_post_install <ide> @prefix_returns_versioned_prefix = true <ide> def run_post_install <ide> <ide> ENV.clear_sensitive_environment! <ide> <add> Pathname.glob("#{bottle_prefix}/{etc,var}/**/*") do |path| <add> path.extend(InstallRenamed) <add> path.cp_path_sub(bottle_prefix, HOMEBREW_PREFIX) <add> end <add> <ide> with_logging("post_install") do <ide> post_install <ide> end <ide><path>Library/Homebrew/formula_installer.rb <ide> def finish <ide> fix_dynamic_linkage(keg) <ide> end <ide> <del> if formula.post_install_defined? <del> if build_bottle? <del> ohai "Not running post_install as we're building a bottle" <del> puts "You can run it manually using `brew postinstall #{formula.full_name}`" <del> else <del> post_install <del> end <add> if build_bottle? <add> ohai "Not running post_install as we're building a bottle" <add> puts "You can run it manually using `brew postinstall #{formula.full_name}`" <add> else <add> post_install <ide> end <ide> <ide> caveats <ide> def pour <ide> skip_linkage = formula.bottle_specification.skip_relocation? <ide> keg.replace_placeholders_with_locations tab.changed_files, skip_linkage: skip_linkage <ide> <del> Pathname.glob("#{formula.bottle_prefix}/{etc,var}/**/*") do |path| <del> path.extend(InstallRenamed) <del> path.cp_path_sub(formula.bottle_prefix, HOMEBREW_PREFIX) <del> end <del> FileUtils.rm_rf formula.bottle_prefix <del> <ide> tab = Tab.for_keg(keg) <ide> <ide> CxxStdlib.check_compatibility( <ide><path>Library/Homebrew/test/formula_spec.rb <ide> RSpec::Matchers.alias_matcher :have_changed_alias, :be_alias_changed <ide> <ide> RSpec::Matchers.alias_matcher :have_option_defined, :be_option_defined <del>RSpec::Matchers.alias_matcher :have_post_install_defined, :be_post_install_defined <ide> RSpec::Matchers.alias_matcher :have_test_defined, :be_test_defined <ide> RSpec::Matchers.alias_matcher :pour_bottle, :be_pour_bottle <ide> <ide> def options <ide> expect(f.desc).to eq("a formula") <ide> end <ide> <del> specify "#post_install_defined?" do <del> f1 = formula do <del> url "foo-1.0" <del> <del> def post_install <del> # do nothing <del> end <del> end <del> <del> f2 = formula do <del> url "foo-1.0" <del> end <del> <del> expect(f1).to have_post_install_defined <del> expect(f2).not_to have_post_install_defined <del> end <del> <ide> specify "#test_defined?" do <ide> f1 = formula do <ide> url "foo-1.0"
4
Java
Java
fix regression in producesrequestcondition
b5327ef60f7cdd3b82d00d36c0775ba0a324f7be
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/ProducesRequestCondition.java <ide> public ProducesRequestCondition combine(ProducesRequestCondition other) { <ide> @Override <ide> @Nullable <ide> public ProducesRequestCondition getMatchingCondition(ServerWebExchange exchange) { <del> if (isEmpty() || CorsUtils.isPreFlightRequest(exchange.getRequest())) { <add> if (CorsUtils.isPreFlightRequest(exchange.getRequest())) { <ide> return EMPTY_CONDITION; <ide> } <add> if (isEmpty()) { <add> return this; <add> } <ide> Set<ProduceMediaTypeExpression> result = new LinkedHashSet<>(this.expressions); <ide> result.removeIf(expression -> !expression.match(exchange)); <ide> if (!result.isEmpty()) { <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ProducesRequestConditionTests.java <ide> <ide> import org.junit.Test; <ide> <add>import org.springframework.http.MediaType; <ide> import org.springframework.mock.web.test.server.MockServerWebExchange; <add>import org.springframework.web.reactive.accept.RequestedContentTypeResolver; <add>import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <del>import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertNotNull; <del>import static org.junit.Assert.assertNull; <del>import static org.junit.Assert.assertTrue; <del>import static org.junit.Assert.fail; <del>import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; <add>import static org.junit.Assert.*; <add>import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.*; <ide> <ide> /** <ide> * Unit tests for {@link ProducesRequestCondition}. <ide> public void matchWithNegationAndMediaTypeAllWithQualityParameter() { <ide> assertNotNull(condition.getMatchingCondition(exchange)); <ide> } <ide> <add> @Test // gh-22853 <add> public void matchAndCompare() { <add> RequestedContentTypeResolverBuilder builder = new RequestedContentTypeResolverBuilder(); <add> builder.headerResolver(); <add> builder.fixedResolver(MediaType.TEXT_HTML); <add> RequestedContentTypeResolver resolver = builder.build(); <add> <add> ProducesRequestCondition none = new ProducesRequestCondition(new String[0], null, resolver); <add> ProducesRequestCondition html = new ProducesRequestCondition(new String[] {"text/html"}, null, resolver); <add> <add> MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", "*/*")); <add> <add> ProducesRequestCondition noneMatch = none.getMatchingCondition(exchange); <add> ProducesRequestCondition htmlMatch = html.getMatchingCondition(exchange); <add> <add> assertEquals(1, noneMatch.compareTo(htmlMatch, exchange)); <add> } <ide> <ide> @Test <ide> public void compareTo() { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/ProducesRequestCondition.java <ide> public ProducesRequestCondition combine(ProducesRequestCondition other) { <ide> @Override <ide> @Nullable <ide> public ProducesRequestCondition getMatchingCondition(HttpServletRequest request) { <del> if (isEmpty() || CorsUtils.isPreFlightRequest(request)) { <add> if (CorsUtils.isPreFlightRequest(request)) { <ide> return EMPTY_CONDITION; <ide> } <del> <add> if (isEmpty()) { <add> return this; <add> } <ide> List<MediaType> acceptedMediaTypes; <ide> try { <ide> acceptedMediaTypes = getAcceptedMediaTypes(request); <ide> } <ide> catch (HttpMediaTypeException ex) { <ide> return null; <ide> } <del> <ide> Set<ProduceMediaTypeExpression> result = new LinkedHashSet<>(this.expressions); <ide> result.removeIf(expression -> !expression.match(acceptedMediaTypes)); <ide> if (!result.isEmpty()) { <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ProducesRequestConditionTests.java <ide> <ide> import org.junit.Test; <ide> <add>import org.springframework.http.MediaType; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <add>import org.springframework.web.accept.ContentNegotiationManager; <add>import org.springframework.web.accept.FixedContentNegotiationStrategy; <add>import org.springframework.web.accept.HeaderContentNegotiationStrategy; <ide> import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition.ProduceMediaTypeExpression; <ide> <ide> import static org.junit.Assert.*; <ide> public void matchWithNegationAndMediaTypeAllWithQualityParameter() { <ide> assertNotNull(condition.getMatchingCondition(request)); <ide> } <ide> <add> @Test // gh-22853 <add> public void matchAndCompare() { <add> ContentNegotiationManager manager = new ContentNegotiationManager( <add> new HeaderContentNegotiationStrategy(), <add> new FixedContentNegotiationStrategy(MediaType.TEXT_HTML)); <add> <add> ProducesRequestCondition none = new ProducesRequestCondition(new String[0], null, manager); <add> ProducesRequestCondition html = new ProducesRequestCondition(new String[] {"text/html"}, null, manager); <add> <add> MockHttpServletRequest request = new MockHttpServletRequest(); <add> request.addHeader("Accept", "*/*"); <add> <add> ProducesRequestCondition noneMatch = none.getMatchingCondition(request); <add> ProducesRequestCondition htmlMatch = html.getMatchingCondition(request); <add> <add> assertEquals(1, noneMatch.compareTo(htmlMatch, request)); <add> } <add> <ide> @Test <ide> public void compareTo() { <ide> ProducesRequestCondition html = new ProducesRequestCondition("text/html");
4
Javascript
Javascript
remove keymirror in propagationphases
738a9e3ef25db863126cd7ec2b37b9ba0bd1c7c2
<ide><path>src/renderers/shared/stack/event/EventConstants.js <ide> <ide> var keyMirror = require('keyMirror'); <ide> <del>var PropagationPhases = keyMirror({bubbled: null, captured: null}); <add>export type PropagationPhases = 'bubbled' | 'captured'; <ide> <ide> /** <ide> * Types of raw signals from the browser caught at the top level. <ide> var topLevelTypes = keyMirror({ <ide> <ide> var EventConstants = { <ide> topLevelTypes: topLevelTypes, <del> PropagationPhases: PropagationPhases, <ide> }; <ide> <ide> module.exports = EventConstants; <ide><path>src/renderers/shared/stack/event/EventPropagators.js <ide> <ide> 'use strict'; <ide> <del>var EventConstants = require('EventConstants'); <ide> var EventPluginHub = require('EventPluginHub'); <ide> var EventPluginUtils = require('EventPluginUtils'); <ide> <ide> var accumulateInto = require('accumulateInto'); <ide> var forEachAccumulated = require('forEachAccumulated'); <ide> var warning = require('warning'); <ide> <del>var PropagationPhases = EventConstants.PropagationPhases; <add>import type { PropagationPhases } from 'EventConstants'; <add> <ide> var getListener = EventPluginHub.getListener; <ide> <ide> /** <ide> * Some event types have a notion of different registration names for different <ide> * "phases" of propagation. This finds listeners by a given phase. <ide> */ <del>function listenerAtPhase(inst, event, propagationPhase) { <add>function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) { <ide> var registrationName = <ide> event.dispatchConfig.phasedRegistrationNames[propagationPhase]; <ide> return getListener(inst, registrationName); <ide> function accumulateDirectionalDispatches(inst, upwards, event) { <ide> 'Dispatching inst must not be null' <ide> ); <ide> } <del> var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; <add> var phase = upwards ? 'bubbled' : 'captured'; <ide> var listener = listenerAtPhase(inst, event, phase); <ide> if (listener) { <ide> event._dispatchListeners =
2
Ruby
Ruby
remove irrelevant comments
8ae913664ff721e10dfc2c057998a38fd6f76edf
<ide><path>activemodel/lib/active_model/validations/acceptance.rb <ide> def validate_each(record, attribute, value) <ide> end <ide> <ide> def setup(klass) <del> # Note: instance_methods.map(&:to_s) is important for 1.9 compatibility <del> # as instance_methods returns symbols unlike 1.8 which returns strings. <ide> attr_readers = attributes.reject { |name| klass.attribute_method?(name) } <ide> attr_writers = attributes.reject { |name| klass.attribute_method?("#{name}=") } <ide> klass.send(:attr_reader, *attr_readers)
1
Ruby
Ruby
remove useless rescue
13dd7758cedf6152835c4c72b69b1fe631a60733
<ide><path>actionpack/lib/sprockets/helpers/rails_helper.rb <ide> def asset_path(source, default_ext = nil, body = false, protocol = nil) <ide> <ide> private <ide> def debug_assets? <del> begin <del> params[:debug_assets] == '1' || <del> params[:debug_assets] == 'true' <del> rescue NoMethodError <del> false <del> end || Rails.application.config.assets.debug <add> params[:debug_assets] == '1' || <add> params[:debug_assets] == 'true' || <add> Rails.application.config.assets.debug <ide> end <ide> <ide> # Override to specify an alternative prefix for asset path generation. <ide><path>actionpack/test/abstract_unit.rb <ide> def call(env) <ide> end <ide> <ide> class BasicController <del> attr_accessor :request <add> attr_accessor :request, :params <add> <add> def initialize <add> @params = {} <add> end <ide> <ide> def config <ide> @config ||= ActiveSupport::InheritableOptions.new(ActionController::Base.config).tap do |config|
2
Python
Python
create rod_cutting.py (#373)
dc302be505e2ddc3333066dcc50c161981d66cdf
<ide><path>dynamic_programming/rod_cutting.py <add>### PROBLEM ### <add>""" <add>We are given a rod of length n and we are given the array of prices, also of <add>length n. This array contains the price for selling a rod at a certain length. <add>For example, prices[5] shows the price we can sell a rod of length 5. <add>Generalising, prices[x] shows the price a rod of length x can be sold. <add>We are tasked to find the optimal solution to sell the given rod. <add>""" <add> <add>### SOLUTION ### <add>""" <add>Profit(n) = max(1<i<n){Price(n),Price(i)+Profit(n-i)} <add> <add>When we receive a rod, we have two options: <add>a) Don't cut it and sell it as is (receiving prices[length]) <add>b) Cut it and sell it in two parts. The length we cut it and the rod we are <add>left with, which we have to try and sell separately in an efficient way. <add>Choose the maximum price we can get. <add>""" <add> <add>def CutRod(n): <add> if(n == 1): <add> #Cannot cut rod any further <add> return prices[1] <add> <add> noCut = prices[n] #The price you get when you don't cut the rod <add> yesCut = [-1 for x in range(n)] #The prices for the different cutting options <add> <add> for i in range(1,n): <add> if(solutions[i] == -1): <add> #We haven't calulated solution for length i yet. <add> #We know we sell the part of length i so we get prices[i]. <add> #We just need to know how to sell rod of length n-i <add> yesCut[i] = prices[i] + CutRod(n-i) <add> else: <add> #We have calculated solution for length i. <add> #We add the two prices. <add> yesCut[i] = prices[i] + solutions[n-i] <add> <add> #We need to find the highest price in order to sell more efficiently. <add> #We have to choose between noCut and the prices in yesCut. <add> m = noCut #Initialize max to noCut <add> for i in range(n): <add> if(yesCut[i] > m): <add> m = yesCut[i] <add> <add> solutions[n] = m <add> return m <add> <add> <add> <add>### EXAMPLE ### <add>length = 5 <add>#The first price, 0, is for when we have no rod. <add>prices = [0, 1, 3, 7, 9, 11, 13, 17, 21, 21, 30] <add>solutions = [-1 for x in range(length+1)] <add> <add>print(CutRod(length))
1
PHP
PHP
fix filtering of parameters
9902e7d5960c6f3a2ad9a187c142ab6dbb384ed1
<ide><path>src/Illuminate/Routing/Router.php <ide> public function callRouteFilter($filter, $parameters, $route, $request, $respons <ide> <ide> $data = array_merge(array($route, $request, $response), $parameters); <ide> <del> return $this->events->until('router.filter: '.$filter, array_filter($data)); <add> return $this->events->until('router.filter: '.$filter, $this->cleanFilterParameters($data)); <add> } <add> <add> /** <add> * Clean the parameters being passed to a filter callback. <add> * <add> * @param array $parameters <add> * @return array <add> */ <add> protected function cleanFilterParameters(array $parameters) <add> { <add> return array_filter($parameters, function($p) <add> { <add> return ! is_null($p) && $p !== ''; <add> }); <ide> } <ide> <ide> /** <ide><path>tests/Routing/RoutingRouteTest.php <ide> public function testBasicBeforeFilters() <ide> $router->filter('foo', function($route, $request, $age) { return $age; }); <ide> $this->assertEquals('25', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); <ide> <add> $router = $this->getRouter(); <add> $router->get('foo/bar', array('before' => 'foo:0,taylor', function() { return 'hello'; })); <add> $router->filter('foo', function($route, $request, $age, $name) { return $age.$name; }); <add> $this->assertEquals('0taylor', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); <add> <ide> $router = $this->getRouter(); <ide> $router->get('foo/bar', array('before' => 'foo:bar,baz', function() { return 'hello'; })); <ide> $router->filter('foo', function($route, $request, $bar, $baz) { return $bar.$baz; }); <ide> public function testRouteGrouping() <ide> $router->filter('bar', function() {}); <ide> $router->filter('baz', function() { return 'foo!'; }); <ide> $this->assertEquals('foo!', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); <del> <add> <ide> /** <ide> * getPrefix() method <ide> */ <ide> $router = $this->getRouter(); <ide> $router->group(array('prefix' => 'foo'), function() use ($router) <ide> { <ide> $router->get('bar', function() { return 'hello'; }); <del> }); <add> }); <ide> $routes = $router->getRoutes(); <del> $routes = $routes->getRoutes(); <add> $routes = $routes->getRoutes(); <ide> $this->assertEquals('foo', $routes[0]->getPrefix()); <ide> } <ide>
2
Java
Java
remove buffer release used as workaround
bd2c213b471c1a42b17620ff97da1f2d7665dee3
<ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java <ide> public void completed(Integer read, DataBuffer dataBuffer) { <ide> long pos = this.position.addAndGet(read); <ide> dataBuffer.writePosition(read); <ide> this.sink.next(dataBuffer); <del> // It's possible for cancellation to happen right before the push into the sink <add> // onNext may have led to onCancel (e.g. downstream takeUntil) <ide> if (this.disposed.get()) { <del> // TODO: <del> // This is not ideal since we already passed the buffer into the sink and <del> // releasing may cause something reading to fail. Maybe we won't have to <del> // do this after https://github.com/reactor/reactor-core/issues/1634 <del> complete(dataBuffer); <add> complete(); <ide> } <ide> else { <ide> DataBuffer newDataBuffer = this.dataBufferFactory.allocateBuffer(this.bufferSize); <ide> public void completed(Integer read, DataBuffer dataBuffer) { <ide> } <ide> } <ide> else { <del> complete(dataBuffer); <add> release(dataBuffer); <add> complete(); <ide> } <ide> } <ide> <del> private void complete(DataBuffer dataBuffer) { <del> release(dataBuffer); <add> private void complete() { <ide> this.sink.complete(); <ide> closeChannel(this.channel); <ide> }
1
Text
Text
fix bad translation
ebb04604c7cd1b63f6c101c3fd072462df87f052
<ide><path>guide/spanish/c/data-types/index.md <ide> C nos permite elegir entre varias opciones diferentes con nuestros tipos de dato <ide> <ide> ## Tipos de datos enteros <ide> <del>#### Personajes: `char` <add>#### Caracteres: `char` <ide> <del>`char` contiene caracteres, cosas como letras, puntuación y espacios. En una computadora, los caracteres se almacenan como números, por lo que `char` contiene valores enteros que representan caracteres. La traducción real está descrita por el estándar ASCII. [Aquí hay](http://www.asciitable.com/) una mesa útil para buscar eso. <add>`char` contiene caracteres, cosas como letras, puntuación y espacios. En una computadora, los caracteres se almacenan como números, por lo que `char` contiene valores enteros que representan caracteres. La traducción real está descrita por el estándar ASCII. [Aquí hay](http://www.asciitable.com/) una tabla útil para buscar eso. <ide> <ide> El tamaño real, como todos los demás tipos de datos en C, depende del hardware en el que esté trabajando. Como mínimo, es de al menos 8 bits, por lo que tendrá al menos 0 a 127. Alternativamente, puede usar caracteres `signed char` para obtener al menos -128 a 127. <ide> <ide> Un puntero de tipo void \* representa la dirección de un objeto, pero no su tip <ide> * float es el valor básico de punto flotante, almacenando 6 decimales <ide> * El doble toma el doble de memoria y da 15 decimales. <ide> * El doble largo requiere más memoria y da 19 decimales. <del>* Elegir el tipo de datos correcto es importante y le da al programador un gran control sobre el programa en un nivel bajo. <ide>\ No newline at end of file <add>* Elegir el tipo de datos correcto es importante y le da al programador un gran control sobre el programa en un nivel bajo.
1
Go
Go
implement docker exec with standalone client lib
3f9f23114f7cccd9e9972d457f0f1d2502eaa4af
<ide><path>api/client/client.go <ide> import ( <ide> <ide> // apiClient is an interface that clients that talk with a docker server must implement. <ide> type apiClient interface { <del> ContainerAttach(options types.ContainerAttachOptions) (*types.HijackedResponse, error) <add> ContainerAttach(options types.ContainerAttachOptions) (types.HijackedResponse, error) <ide> ContainerCommit(options types.ContainerCommitOptions) (types.ContainerCommitResponse, error) <ide> ContainerCreate(config *runconfig.ContainerConfigWrapper, containerName string) (types.ContainerCreateResponse, error) <ide> ContainerDiff(containerID string) ([]types.ContainerChange, error) <add> ContainerExecAttach(execID string, config runconfig.ExecConfig) (types.HijackedResponse, error) <add> ContainerExecCreate(config runconfig.ExecConfig) (types.ContainerExecCreateResponse, error) <add> ContainerExecInspect(execID string) (types.ContainerExecInspect, error) <add> ContainerExecStart(execID string, config types.ExecStartCheck) error <ide> ContainerExport(containerID string) (io.ReadCloser, error) <ide> ContainerInspect(containerID string) (types.ContainerJSON, error) <ide> ContainerKill(containerID, signal string) error <ide><path>api/client/exec.go <ide> package client <ide> <ide> import ( <del> "encoding/json" <ide> "fmt" <ide> "io" <ide> <ide> func (cli *DockerCli) CmdExec(args ...string) error { <ide> return Cli.StatusError{StatusCode: 1} <ide> } <ide> <del> serverResp, err := cli.call("POST", "/containers/"+execConfig.Container+"/exec", execConfig, nil) <add> response, err := cli.client.ContainerExecCreate(*execConfig) <ide> if err != nil { <ide> return err <ide> } <ide> <del> defer serverResp.body.Close() <del> <del> var response types.ContainerExecCreateResponse <del> if err := json.NewDecoder(serverResp.body).Decode(&response); err != nil { <del> return err <del> } <del> <ide> execID := response.ID <del> <ide> if execID == "" { <ide> fmt.Fprintf(cli.out, "exec ID empty") <ide> return nil <ide> } <ide> <ide> //Temp struct for execStart so that we don't need to transfer all the execConfig <del> execStartCheck := &types.ExecStartCheck{ <del> Detach: execConfig.Detach, <del> Tty: execConfig.Tty, <del> } <del> <ide> if !execConfig.Detach { <ide> if err := cli.CheckTtyInput(execConfig.AttachStdin, execConfig.Tty); err != nil { <ide> return err <ide> } <ide> } else { <del> if _, _, err := readBody(cli.call("POST", "/exec/"+execID+"/start", execStartCheck, nil)); err != nil { <add> execStartCheck := types.ExecStartCheck{ <add> Detach: execConfig.Detach, <add> Tty: execConfig.Tty, <add> } <add> <add> if err := cli.client.ContainerExecStart(execID, execStartCheck); err != nil { <ide> return err <ide> } <ide> // For now don't print this - wait for when we support exec wait() <ide> func (cli *DockerCli) CmdExec(args ...string) error { <ide> var ( <ide> out, stderr io.Writer <ide> in io.ReadCloser <del> hijacked = make(chan io.Closer) <ide> errCh chan error <ide> ) <ide> <del> // Block the return until the chan gets closed <del> defer func() { <del> logrus.Debugf("End of CmdExec(), Waiting for hijack to finish.") <del> if _, ok := <-hijacked; ok { <del> fmt.Fprintln(cli.err, "Hijack did not finish (chan still open)") <del> } <del> }() <del> <ide> if execConfig.AttachStdin { <ide> in = cli.in <ide> } <ide> func (cli *DockerCli) CmdExec(args ...string) error { <ide> stderr = cli.err <ide> } <ide> } <del> errCh = promise.Go(func() error { <del> return cli.hijackWithContentType("POST", "/exec/"+execID+"/start", "application/json", execConfig.Tty, in, out, stderr, hijacked, execConfig) <del> }) <ide> <del> // Acknowledge the hijack before starting <del> select { <del> case closer := <-hijacked: <del> // Make sure that hijack gets closed when returning. (result <del> // in closing hijack chan and freeing server's goroutines. <del> if closer != nil { <del> defer closer.Close() <del> } <del> case err := <-errCh: <del> if err != nil { <del> logrus.Debugf("Error hijack: %s", err) <del> return err <del> } <add> resp, err := cli.client.ContainerExecAttach(execID, *execConfig) <add> if err != nil { <add> return err <ide> } <add> defer resp.Close() <add> errCh = promise.Go(func() error { <add> return cli.holdHijackedConnection(execConfig.Tty, in, out, stderr, resp) <add> }) <ide> <ide> if execConfig.Tty && cli.isTerminalIn { <ide> if err := cli.monitorTtySize(execID, true); err != nil { <ide><path>api/client/hijack.go <ide> import ( <ide> "github.com/docker/docker/pkg/term" <ide> ) <ide> <del>func (cli *DockerCli) holdHijackedConnection(setRawTerminal bool, inputStream io.ReadCloser, outputStream, errorStream io.Writer, resp *types.HijackedResponse) error { <add>func (cli *DockerCli) holdHijackedConnection(setRawTerminal bool, inputStream io.ReadCloser, outputStream, errorStream io.Writer, resp types.HijackedResponse) error { <ide> var ( <ide> err error <ide> oldState *term.State <ide><path>api/client/lib/container_attach.go <ide> import ( <ide> // It returns a types.HijackedConnection with the hijacked connection <ide> // and the a reader to get output. It's up to the called to close <ide> // the hijacked connection by calling types.HijackedResponse.Close. <del>func (cli *Client) ContainerAttach(options types.ContainerAttachOptions) (*types.HijackedResponse, error) { <add>func (cli *Client) ContainerAttach(options types.ContainerAttachOptions) (types.HijackedResponse, error) { <ide> query := url.Values{} <ide> if options.Stream { <ide> query.Set("stream", "1") <ide><path>api/client/lib/exec.go <add>package lib <add> <add>import ( <add> "encoding/json" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/runconfig" <add>) <add> <add>// ContainerExecCreate creates a new exec configuration to run an exec process. <add>func (cli *Client) ContainerExecCreate(config runconfig.ExecConfig) (types.ContainerExecCreateResponse, error) { <add> var response types.ContainerExecCreateResponse <add> resp, err := cli.post("/containers/"+config.Container+"/exec", nil, config, nil) <add> if err != nil { <add> return response, err <add> } <add> defer ensureReaderClosed(resp) <add> err = json.NewDecoder(resp.body).Decode(&response) <add> return response, err <add>} <add> <add>// ContainerExecStart starts an exec process already create in the docker host. <add>func (cli *Client) ContainerExecStart(execID string, config types.ExecStartCheck) error { <add> resp, err := cli.post("/exec/"+execID+"/start", nil, config, nil) <add> ensureReaderClosed(resp) <add> return err <add>} <add> <add>// ContainerExecAttach attaches a connection to an exec process in the server. <add>// It returns a types.HijackedConnection with the hijacked connection <add>// and the a reader to get output. It's up to the called to close <add>// the hijacked connection by calling types.HijackedResponse.Close. <add>func (cli *Client) ContainerExecAttach(execID string, config runconfig.ExecConfig) (types.HijackedResponse, error) { <add> headers := map[string][]string{"Content-Type": {"application/json"}} <add> return cli.postHijacked("/exec/"+execID+"/start", nil, config, headers) <add>} <add> <add>// ContainerExecInspect returns information about a specific exec process on the docker host. <add>func (cli *Client) ContainerExecInspect(execID string) (types.ContainerExecInspect, error) { <add> var response types.ContainerExecInspect <add> resp, err := cli.get("/exec/"+execID+"/json", nil, nil) <add> if err != nil { <add> return response, err <add> } <add> defer ensureReaderClosed(resp) <add> <add> err = json.NewDecoder(resp.body).Decode(&response) <add> return response, err <add>} <ide><path>api/client/lib/hijack.go <ide> import ( <ide> "crypto/tls" <ide> "errors" <ide> "fmt" <del> "io" <ide> "net" <ide> "net/http/httputil" <ide> "net/url" <ide> func (c *tlsClientCon) CloseWrite() error { <ide> } <ide> <ide> // postHijacked sends a POST request and hijacks the connection. <del>func (cli *Client) postHijacked(path string, query url.Values, body io.Reader, headers map[string][]string) (*types.HijackedResponse, error) { <add>func (cli *Client) postHijacked(path string, query url.Values, body interface{}, headers map[string][]string) (types.HijackedResponse, error) { <ide> bodyEncoded, err := encodeData(body) <ide> if err != nil { <del> return nil, err <add> return types.HijackedResponse{}, err <ide> } <ide> <ide> req, err := cli.newRequest("POST", path, query, bodyEncoded, headers) <ide> if err != nil { <del> return nil, err <add> return types.HijackedResponse{}, err <ide> } <ide> req.Host = cli.Addr <ide> <ide> func (cli *Client) postHijacked(path string, query url.Values, body io.Reader, h <ide> conn, err := dial(cli.Proto, cli.Addr, cli.tlsConfig) <ide> if err != nil { <ide> if strings.Contains(err.Error(), "connection refused") { <del> return nil, fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker daemon' running on this host?") <add> return types.HijackedResponse{}, fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker daemon' running on this host?") <ide> } <del> return nil, err <add> return types.HijackedResponse{}, err <ide> } <ide> <ide> // When we set up a TCP connection for hijack, there could be long periods <ide> func (cli *Client) postHijacked(path string, query url.Values, body io.Reader, h <ide> <ide> rwc, br := clientconn.Hijack() <ide> <del> return &types.HijackedResponse{rwc, br}, nil <add> return types.HijackedResponse{rwc, br}, nil <ide> } <ide> <ide> func tlsDial(network, addr string, config *tls.Config) (net.Conn, error) { <ide><path>api/client/utils.go <ide> func getExitCode(cli *DockerCli, containerID string) (bool, int, error) { <ide> // getExecExitCode perform an inspect on the exec command. It returns <ide> // the running state and the exit code. <ide> func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) { <del> serverResp, err := cli.call("GET", "/exec/"+execID+"/json", nil, nil) <add> resp, err := cli.client.ContainerExecInspect(execID) <ide> if err != nil { <ide> // If we can't connect, then the daemon probably died. <del> if err != errConnectionFailed { <add> if err != lib.ErrConnectionFailed { <ide> return false, -1, err <ide> } <ide> return false, -1, nil <ide> } <ide> <del> defer serverResp.body.Close() <del> <del> //TODO: Should we reconsider having a type in api/types? <del> //this is a response to exex/id/json not container <del> var c struct { <del> Running bool <del> ExitCode int <del> } <del> <del> if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil { <del> return false, -1, err <del> } <del> <del> return c.Running, c.ExitCode, nil <add> return resp.Running, resp.ExitCode, nil <ide> } <ide> <ide> func (cli *DockerCli) monitorTtySize(id string, isExec bool) error { <ide><path>api/types/client.go <ide> type ContainerCommitOptions struct { <ide> JSONConfig string <ide> } <ide> <add>// ContainerExecInspect holds information returned by exec inspect. <add>type ContainerExecInspect struct { <add> ExecID string <add> ContainerID string <add> Running bool <add> ExitCode int <add>} <add> <ide> // ContainerListOptions holds parameters to list containers with. <ide> type ContainerListOptions struct { <ide> Quiet bool
8
Ruby
Ruby
fix typo in mime type registering
d41d586e4e00990a8b5e1e62b75857fea0effaf4
<ide><path>actionpack/lib/action_dispatch/http/mime_types.rb <ide> <ide> Mime::Type.register "audio/mpeg", :mp3, [], %w(mp1 mp2 mp3) <ide> Mime::Type.register "audio/ogg", :ogg, [], %w(oga ogg spx opus) <del>Mime::Type.register "audio/aac", :m4a, %( audio/mp4 ), %w(m4a mpg4 aac) <add>Mime::Type.register "audio/aac", :m4a, %w( audio/mp4 ), %w(m4a mpg4 aac) <ide> <ide> Mime::Type.register "video/webm", :webm, [], %w(webm) <ide> Mime::Type.register "video/mp4", :mp4, [], %w(mp4 m4v)
1
Java
Java
improve setdateheader impl in mockservletresponse
088a50c1fbd4fd4d0cc89fb8733c90bff796b611
<ide><path>spring-web/src/test/java/org/springframework/mock/web/test/MockHttpServletResponse.java <ide> import java.io.PrintWriter; <ide> import java.io.UnsupportedEncodingException; <ide> import java.io.Writer; <add>import java.text.SimpleDateFormat; <ide> import java.util.ArrayList; <ide> import java.util.Collection; <ide> import java.util.Collections; <add>import java.util.Date; <ide> import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Map; <add>import java.util.TimeZone; <add> <ide> import javax.servlet.ServletOutputStream; <ide> import javax.servlet.http.Cookie; <ide> import javax.servlet.http.HttpServletResponse; <ide> public class MockHttpServletResponse implements HttpServletResponse { <ide> <ide> private static final String LOCATION_HEADER = "Location"; <ide> <add> private static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz"; <add> <add> private static TimeZone GMT = TimeZone.getTimeZone("GMT"); <add> <ide> <ide> //--------------------------------------------------------------------- <ide> // ServletResponse properties <ide> public String getRedirectedUrl() { <ide> <ide> @Override <ide> public void setDateHeader(String name, long value) { <del> setHeaderValue(name, value); <add> SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US); <add> dateFormat.setTimeZone(GMT); <add> setHeaderValue(name, dateFormat.format(new Date(value))); <ide> } <ide> <ide> @Override <ide> public void addDateHeader(String name, long value) { <del> addHeaderValue(name, value); <add> SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US); <add> dateFormat.setTimeZone(GMT); <add> setHeaderValue(name, dateFormat.format(new Date(value))); <ide> } <ide> <ide> @Override <ide><path>spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestHttpMethodsTests.java <ide> public void checkNotModifiedTimestamp() throws Exception { <ide> assertTrue(request.checkNotModified(epochTime)); <ide> <ide> assertEquals(304, servletResponse.getStatus()); <del> assertEquals("" + epochTime, servletResponse.getHeader("Last-Modified")); <add> assertEquals(dateFormat.format(epochTime), servletResponse.getHeader("Last-Modified")); <ide> } <ide> <ide> @Test <ide> public void checkModifiedTimestamp() { <ide> assertFalse(request.checkNotModified(currentDate.getTime())); <ide> <ide> assertEquals(200, servletResponse.getStatus()); <del> assertEquals("" + currentDate.getTime(), servletResponse.getHeader("Last-Modified")); <add> assertEquals(dateFormat.format(currentDate.getTime()), servletResponse.getHeader("Last-Modified")); <ide> } <ide> <ide> @Test <ide> public void checkNotModifiedETagAndTimestamp() { <ide> <ide> assertEquals(304, servletResponse.getStatus()); <ide> assertEquals(eTag, servletResponse.getHeader("ETag")); <del> assertEquals("" + currentDate.getTime(), servletResponse.getHeader("Last-Modified")); <add> assertEquals(dateFormat.format(currentDate.getTime()), servletResponse.getHeader("Last-Modified")); <ide> } <ide> <ide> @Test <ide> public void checkNotModifiedETagAndModifiedTimestamp() { <ide> <ide> assertEquals(200, servletResponse.getStatus()); <ide> assertEquals(eTag, servletResponse.getHeader("ETag")); <del> assertEquals("" + currentEpoch, servletResponse.getHeader("Last-Modified")); <add> assertEquals(dateFormat.format(currentEpoch), servletResponse.getHeader("Last-Modified")); <ide> } <ide> <ide> @Test <ide> public void checkModifiedETagAndNotModifiedTimestamp() throws Exception { <ide> <ide> assertEquals(200, servletResponse.getStatus()); <ide> assertEquals(currentETag, servletResponse.getHeader("ETag")); <del> assertEquals("" + epochTime, servletResponse.getHeader("Last-Modified")); <add> assertEquals(dateFormat.format(epochTime), servletResponse.getHeader("Last-Modified")); <ide> } <ide> <ide> @Test <ide> public void checkNotModifiedTimestampWithLengthPart() throws Exception { <ide> assertTrue(request.checkNotModified(epochTime)); <ide> <ide> assertEquals(304, servletResponse.getStatus()); <del> assertEquals("" + epochTime, servletResponse.getHeader("Last-Modified")); <add> assertEquals(dateFormat.format(epochTime), servletResponse.getHeader("Last-Modified")); <ide> } <ide> <ide> @Test <ide> public void checkModifiedTimestampWithLengthPart() throws Exception { <ide> assertFalse(request.checkNotModified(epochTime)); <ide> <ide> assertEquals(200, servletResponse.getStatus()); <del> assertEquals("" + epochTime, servletResponse.getHeader("Last-Modified")); <add> assertEquals(dateFormat.format(epochTime), servletResponse.getHeader("Last-Modified")); <ide> } <ide> <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java <ide> public void testLocaleRequest() throws Exception { <ide> MockHttpServletResponse response = new MockHttpServletResponse(); <ide> simpleDispatcherServlet.service(request, response); <ide> assertTrue("Not forwarded", response.getForwardedUrl() == null); <del> assertEquals("1427846400000", response.getHeader("Last-Modified")); <add> assertEquals("Wed, 01 Apr 2015 00:00:00 GMT", response.getHeader("Last-Modified")); <ide> } <ide> <ide> public void testUnknownRequest() throws Exception { <ide> public void testAnotherLocaleRequest() throws Exception { <ide> assertTrue(request.getAttribute("test3") != null); <ide> assertTrue(request.getAttribute("test3x") != null); <ide> assertTrue(request.getAttribute("test3y") != null); <del> assertEquals("1427846401000", response.getHeader("Last-Modified")); <add> assertEquals("Wed, 01 Apr 2015 00:00:01 GMT", response.getHeader("Last-Modified")); <ide> } <ide> <ide> public void testExistingMultipartRequest() throws Exception { <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java <ide> import java.text.SimpleDateFormat; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <del>import java.util.Date; <ide> import java.util.List; <ide> import java.util.Locale; <ide> import java.util.TimeZone; <ide> */ <ide> public class ResourceHttpRequestHandlerTests { <ide> <add> private SimpleDateFormat dateFormat; <add> <ide> private ResourceHttpRequestHandler handler; <ide> <ide> private MockHttpServletRequest request; <ide> public class ResourceHttpRequestHandlerTests { <ide> <ide> @Before <ide> public void setUp() throws Exception { <add> dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); <add> dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); <add> <ide> List<Resource> paths = new ArrayList<>(2); <ide> paths.add(new ClassPathResource("test/", getClass())); <ide> paths.add(new ClassPathResource("testalternatepath/", getClass())); <ide> public void getResource() throws Exception { <ide> assertEquals(17, this.response.getContentLength()); <ide> assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); <ide> assertTrue(this.response.containsHeader("Last-Modified")); <del> assertEquals(headerAsLong("Last-Modified") / 1000, resourceLastModified("test/foo.css") / 1000); <add> assertEquals(this.response.getHeader("Last-Modified"), resourceLastModifiedDate("test/foo.css")); <ide> assertEquals("h1 { color:red; }", this.response.getContentAsString()); <ide> } <ide> <ide> public void getResourceNoCache() throws Exception { <ide> <ide> assertEquals("no-store", this.response.getHeader("Cache-Control")); <ide> assertTrue(this.response.containsHeader("Last-Modified")); <del> assertEquals(headerAsLong("Last-Modified") / 1000, resourceLastModified("test/foo.css") / 1000); <add> assertEquals(this.response.getHeader("Last-Modified"), resourceLastModifiedDate("test/foo.css")); <ide> } <ide> <ide> @Test <ide> public void getResourcePreviousBehaviorCache() throws Exception { <ide> this.handler.handleRequest(this.request, this.response); <ide> <ide> assertEquals("max-age=3600, must-revalidate", this.response.getHeader("Cache-Control")); <del> assertTrue(headerAsLong("Expires") >= System.currentTimeMillis() - 1000 + (3600 * 1000)); <add> assertTrue(dateHeaderAsLong("Expires") >= System.currentTimeMillis() - 1000 + (3600 * 1000)); <ide> assertTrue(this.response.containsHeader("Last-Modified")); <del> assertEquals(headerAsLong("Last-Modified") / 1000, resourceLastModified("test/foo.css") / 1000); <add> assertEquals(this.response.getHeader("Last-Modified"), resourceLastModifiedDate("test/foo.css")); <ide> } <ide> <ide> @Test <ide> public void getResourcePreviousBehaviorNoCache() throws Exception { <ide> <ide> assertEquals("no-cache", this.response.getHeader("Pragma")); <ide> assertThat(this.response.getHeaderValues("Cache-Control"), Matchers.contains("no-cache", "no-store")); <del> assertTrue(headerAsLong("Expires") <= System.currentTimeMillis()); <add> assertTrue(dateHeaderAsLong("Expires") <= System.currentTimeMillis()); <ide> assertTrue(this.response.containsHeader("Last-Modified")); <del> assertEquals(headerAsLong("Last-Modified") / 1000, resourceLastModified("test/foo.css") / 1000); <add> assertEquals(dateHeaderAsLong("Last-Modified") / 1000, resourceLastModified("test/foo.css") / 1000); <ide> } <ide> <ide> @Test <ide> public void getResourceWithHtmlMediaType() throws Exception { <ide> assertEquals("text/html", this.response.getContentType()); <ide> assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); <ide> assertTrue(this.response.containsHeader("Last-Modified")); <del> assertEquals(headerAsLong("Last-Modified") / 1000, resourceLastModified("test/foo.html") / 1000); <add> assertEquals(this.response.getHeader("Last-Modified"), resourceLastModifiedDate("test/foo.html")); <ide> } <ide> <ide> @Test <ide> public void getResourceFromAlternatePath() throws Exception { <ide> assertEquals(17, this.response.getContentLength()); <ide> assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); <ide> assertTrue(this.response.containsHeader("Last-Modified")); <del> assertEquals(headerAsLong("Last-Modified") / 1000, resourceLastModified("testalternatepath/baz.css") / 1000); <add> assertEquals(this.response.getHeader("Last-Modified"), resourceLastModifiedDate("testalternatepath/baz.css")); <ide> assertEquals("h1 { color:red; }", this.response.getContentAsString()); <ide> } <ide> <ide> public void writeContentNotClosingInputStream() throws Exception { <ide> } <ide> <ide> <del> private long headerAsLong(String responseHeaderName) throws Exception { <del> return Long.valueOf(this.response.getHeader(responseHeaderName)); <add> private long dateHeaderAsLong(String responseHeaderName) throws Exception { <add> return dateFormat.parse(this.response.getHeader(responseHeaderName)).getTime(); <ide> } <ide> <ide> private long resourceLastModified(String resourceName) throws IOException { <ide> return new ClassPathResource(resourceName, getClass()).getFile().lastModified(); <ide> } <ide> <add> private String resourceLastModifiedDate(String resourceName) throws IOException { <add> long lastModified = new ClassPathResource(resourceName, getClass()).getFile().lastModified(); <add> return dateFormat.format(lastModified); <add> } <add> <ide> <ide> private static class TestServletContext extends MockServletContext { <ide>
4
Go
Go
fix error handling for bind mount spec parser
ebcef288343698dd86ff307f5b9c58aa52ce9fdd
<ide><path>volume/mounts/linux_parser.go <ide> func (p *linuxParser) validateMountConfigImpl(mnt *mount.Mount, validateBindSour <ide> } <ide> <ide> if validateBindSourceExists { <del> exists, _, _ := currentFileInfoProvider.fileInfo(mnt.Source) <add> exists, _, err := currentFileInfoProvider.fileInfo(mnt.Source) <add> if err != nil { <add> return &errMountConfig{mnt, err} <add> } <ide> if !exists { <ide> return &errMountConfig{mnt, errBindSourceDoesNotExist(mnt.Source)} <ide> } <ide><path>volume/mounts/parser_test.go <ide> package mounts // import "github.com/docker/docker/volume/mounts" <ide> <ide> import ( <add> "errors" <ide> "io/ioutil" <ide> "os" <ide> "runtime" <ide> "strings" <ide> "testing" <ide> <ide> "github.com/docker/docker/api/types/mount" <add> "gotest.tools/assert" <add> "gotest.tools/assert/cmp" <ide> ) <ide> <ide> type parseMountRawTestSet struct { <ide> func TestParseMountSpec(t *testing.T) { <ide> t.Errorf("Expected mount copy data to match. Expected: '%v', Actual: '%v'", c.expected.CopyData, mp.CopyData) <ide> } <ide> } <add> <add>} <add> <add>// always returns the configured error <add>// this is used to test error handling <add>type mockFiProviderWithError struct{ err error } <add> <add>func (m mockFiProviderWithError) fileInfo(path string) (bool, bool, error) { <add> return false, false, m.err <add>} <add> <add>// TestParseMountSpecBindWithFileinfoError makes sure that the parser returns <add>// the error produced by the fileinfo provider. <add>// <add>// Some extra context for the future in case of changes and possible wtf are we <add>// testing this for: <add>// <add>// Currently this "fileInfoProvider" returns (bool, bool, error) <add>// The 1st bool is "does this path exist" <add>// The 2nd bool is "is this path a dir" <add>// Then of course the error is an error. <add>// <add>// The issue is the parser was ignoring the error and only looking at the <add>// "does this path exist" boolean, which is always false if there is an error. <add>// Then the error returned to the caller was a (slightly, maybe) friendlier <add>// error string than what comes from `os.Stat` <add>// So ...the caller was always getting an error saying the path doesn't exist <add>// even if it does exist but got some other error (like a permission error). <add>// This is confusing to users. <add>func TestParseMountSpecBindWithFileinfoError(t *testing.T) { <add> previousProvider := currentFileInfoProvider <add> defer func() { currentFileInfoProvider = previousProvider }() <add> <add> testErr := errors.New("some crazy error") <add> currentFileInfoProvider = &mockFiProviderWithError{err: testErr} <add> <add> p := "/bananas" <add> if runtime.GOOS == "windows" { <add> p = `c:\bananas` <add> } <add> m := mount.Mount{Type: mount.TypeBind, Source: p, Target: p} <add> <add> parser := NewParser(runtime.GOOS) <add> <add> _, err := parser.ParseMountSpec(m) <add> assert.Assert(t, err != nil) <add> assert.Assert(t, cmp.Contains(err.Error(), "some crazy error")) <ide> }
2
Ruby
Ruby
use a name that better reflect the return value
af5b245065acff4a021b160a23c8c89b03635a81
<ide><path>actionview/lib/action_view/helpers/form_helper.rb <ide> def instantiate_builder(record_name, record_object, options) <ide> object_name = model_name_from_record_or_class(object).param_key <ide> end <ide> <del> builder = options[:builder] || build_default_form_builder <add> builder = options[:builder] || default_form_builder_class <ide> builder.new(object_name, object, self, options) <ide> end <ide> <del> def build_default_form_builder <add> def default_form_builder_class <ide> builder = ActionView::Base.default_form_builder <ide> builder.respond_to?(:constantize) ? builder.constantize : builder <ide> end
1
Mixed
Go
add `--limit` option to `docker search`
92f10fe228c1b4b527b87ac47401132322283ea3
<ide><path>api/client/search.go <ide> func (cli *DockerCli) CmdSearch(args ...string) error { <ide> cmd := Cli.Subcmd("search", []string{"TERM"}, Cli.DockerCommands["search"].Description, true) <ide> noTrunc := cmd.Bool([]string{"-no-trunc"}, false, "Don't truncate output") <ide> cmd.Var(&flFilter, []string{"f", "-filter"}, "Filter output based on conditions provided") <add> flLimit := cmd.Int([]string{"-limit"}, registry.DefaultSearchLimit, "Max number of search results") <ide> <ide> // Deprecated since Docker 1.12 in favor of "--filter" <ide> automated := cmd.Bool([]string{"#-automated"}, false, "Only show automated builds - DEPRECATED") <ide> func (cli *DockerCli) CmdSearch(args ...string) error { <ide> RegistryAuth: encodedAuth, <ide> PrivilegeFunc: requestPrivilege, <ide> Filters: filterArgs, <add> Limit: *flLimit, <ide> } <ide> <ide> unorderedResults, err := cli.client.ImageSearch(ctx, name, options) <ide><path>api/server/router/image/backend.go <ide> type importExportBackend interface { <ide> type registryBackend interface { <ide> PullImage(ctx context.Context, image, tag string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error <ide> PushImage(ctx context.Context, image, tag string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error <del> SearchRegistryForImages(ctx context.Context, filtersArgs string, term string, authConfig *types.AuthConfig, metaHeaders map[string][]string) (*registry.SearchResults, error) <add> SearchRegistryForImages(ctx context.Context, filtersArgs string, term string, limit int, authConfig *types.AuthConfig, metaHeaders map[string][]string) (*registry.SearchResults, error) <ide> } <ide><path>api/server/router/image/image_routes.go <ide> import ( <ide> "fmt" <ide> "io" <ide> "net/http" <add> "strconv" <ide> "strings" <ide> <ide> "github.com/docker/docker/api/server/httputils" <ide> "github.com/docker/docker/api/types/backend" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/streamformatter" <add> "github.com/docker/docker/registry" <ide> "github.com/docker/engine-api/types" <ide> "github.com/docker/engine-api/types/container" <ide> "github.com/docker/engine-api/types/versions" <ide> func (s *imageRouter) getImagesSearch(ctx context.Context, w http.ResponseWriter <ide> headers[k] = v <ide> } <ide> } <del> query, err := s.backend.SearchRegistryForImages(ctx, r.Form.Get("filters"), r.Form.Get("term"), config, headers) <add> limit := registry.DefaultSearchLimit <add> if r.Form.Get("limit") != "" { <add> limitValue, err := strconv.Atoi(r.Form.Get("limit")) <add> if err != nil { <add> return err <add> } <add> limit = limitValue <add> } <add> query, err := s.backend.SearchRegistryForImages(ctx, r.Form.Get("filters"), r.Form.Get("term"), limit, config, headers) <ide> if err != nil { <ide> return err <ide> } <ide><path>daemon/search.go <ide> var acceptedSearchFilterTags = map[string]bool{ <ide> <ide> // SearchRegistryForImages queries the registry for images matching <ide> // term. authConfig is used to login. <del>func (daemon *Daemon) SearchRegistryForImages(ctx context.Context, filtersArgs string, term string, <add>func (daemon *Daemon) SearchRegistryForImages(ctx context.Context, filtersArgs string, term string, limit int, <ide> authConfig *types.AuthConfig, <ide> headers map[string][]string) (*registrytypes.SearchResults, error) { <ide> <ide> func (daemon *Daemon) SearchRegistryForImages(ctx context.Context, filtersArgs s <ide> } <ide> } <ide> <del> unfilteredResult, err := daemon.RegistryService.Search(ctx, term, authConfig, dockerversion.DockerUserAgent(ctx), headers) <add> unfilteredResult, err := daemon.RegistryService.Search(ctx, term, limit, authConfig, dockerversion.DockerUserAgent(ctx), headers) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>daemon/search_test.go <ide> type FakeService struct { <ide> results []registrytypes.SearchResult <ide> } <ide> <del>func (s *FakeService) Search(ctx context.Context, term string, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) { <add>func (s *FakeService) Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) { <ide> if s.shouldReturnError { <ide> return nil, fmt.Errorf("Search unknown error") <ide> } <ide> func TestSearchRegistryForImagesErrors(t *testing.T) { <ide> shouldReturnError: e.shouldReturnError, <ide> }, <ide> } <del> _, err := daemon.SearchRegistryForImages(context.Background(), e.filtersArgs, "term", nil, map[string][]string{}) <add> _, err := daemon.SearchRegistryForImages(context.Background(), e.filtersArgs, "term", 25, nil, map[string][]string{}) <ide> if err == nil { <ide> t.Errorf("%d: expected an error, got nothing", index) <ide> } <ide> func TestSearchRegistryForImages(t *testing.T) { <ide> results: s.registryResults, <ide> }, <ide> } <del> results, err := daemon.SearchRegistryForImages(context.Background(), s.filtersArgs, term, nil, map[string][]string{}) <add> results, err := daemon.SearchRegistryForImages(context.Background(), s.filtersArgs, term, 25, nil, map[string][]string{}) <ide> if err != nil { <ide> t.Errorf("%d: %v", index, err) <ide> } <ide><path>docs/reference/api/docker_remote_api.md <ide> This section lists each version from latest to oldest. Each listing includes a <ide> * `GET /images/json` now supports filters `since` and `before`. <ide> * `POST /containers/(id or name)/start` no longer accepts a `HostConfig`. <ide> * `POST /images/(name)/tag` no longer has a `force` query parameter. <add>* `GET /images/search` now supports maximum returned search results `limit`. <ide> <ide> ### v1.23 API changes <ide> <ide><path>docs/reference/api/docker_remote_api_v1.24.md <ide> Search for an image on [Docker Hub](https://hub.docker.com). <ide> Query Parameters: <ide> <ide> - **term** – term to search <add>- **limit** – maximum returned search results <ide> - **filters** – a JSON encoded value of the filters (a map[string][]string) to process on the images list. Available filters: <ide> - `stars=<number>` <ide> - `is-automated=(true|false)` <ide><path>docs/reference/commandline/search.md <ide> parent = "smn_cli" <ide> - is-official=(true|false) <ide> - stars=<number> - image has at least 'number' stars <ide> --help Print usage <add> --limit=25 Maximum returned search results <ide> --no-trunc Don't truncate output <ide> <ide> Search [Docker Hub](https://hub.docker.com) for images <ide> at least 3 stars and the description isn't truncated in the output: <ide> progrium/busybox 50 [OK] <ide> radial/busyboxplus Full-chain, Internet enabled, busybox made from scratch. Comes in git and cURL flavors. 8 [OK] <ide> <add>## Limit search results (--limit) <add> <add>The flag `--limit` is the maximium number of results returned by a search. This value could <add>be in the range between 1 and 100. The default value of `--limit` is 25. <add> <add> <ide> ## Filtering <ide> <ide> The filtering flag (`-f` or `--filter`) format is a `key=value` pair. If there is more <ide><path>integration-cli/docker_cli_search_test.go <ide> package main <ide> <ide> import ( <add> "fmt" <ide> "strings" <ide> <ide> "github.com/docker/docker/pkg/integration/checker" <ide> func (s *DockerSuite) TestSearchOnCentralRegistryWithDash(c *check.C) { <ide> <ide> dockerCmd(c, "search", "ubuntu-") <ide> } <add> <add>// test case for #23055 <add>func (s *DockerSuite) TestSearchWithLimit(c *check.C) { <add> testRequires(c, Network, DaemonIsLinux) <add> <add> limit := 10 <add> out, _, err := dockerCmdWithError("search", fmt.Sprintf("--limit=%d", limit), "docker") <add> c.Assert(err, checker.IsNil) <add> outSlice := strings.Split(out, "\n") <add> c.Assert(outSlice, checker.HasLen, limit+2) // 1 header, 1 carriage return <add> <add> limit = 50 <add> out, _, err = dockerCmdWithError("search", fmt.Sprintf("--limit=%d", limit), "docker") <add> c.Assert(err, checker.IsNil) <add> outSlice = strings.Split(out, "\n") <add> c.Assert(outSlice, checker.HasLen, limit+2) // 1 header, 1 carriage return <add> <add> limit = 100 <add> out, _, err = dockerCmdWithError("search", fmt.Sprintf("--limit=%d", limit), "docker") <add> c.Assert(err, checker.IsNil) <add> outSlice = strings.Split(out, "\n") <add> c.Assert(outSlice, checker.HasLen, limit+2) // 1 header, 1 carriage return <add> <add> limit = 0 <add> out, _, err = dockerCmdWithError("search", fmt.Sprintf("--limit=%d", limit), "docker") <add> c.Assert(err, checker.Not(checker.IsNil)) <add> <add> limit = 200 <add> out, _, err = dockerCmdWithError("search", fmt.Sprintf("--limit=%d", limit), "docker") <add> c.Assert(err, checker.Not(checker.IsNil)) <add>} <ide><path>man/docker-search.1.md <ide> docker-search - Search the Docker Hub for images <ide> **docker search** <ide> [**-f**|**--filter**[=*[]*]] <ide> [**--help**] <add>[**--limit**[=*LIMIT*]] <ide> [**--no-trunc**] <ide> TERM <ide> <ide> of stars awarded, whether the image is official, and whether it is automated. <ide> **--help** <ide> Print usage statement <ide> <add>**--limit**=*LIMIT* <add> Maximum returned search results. The default is 25. <add> <ide> **--no-trunc**=*true*|*false* <ide> Don't truncate output. The default is *false*. <ide> <ide><path>registry/registry_test.go <ide> func TestPushImageJSONIndex(t *testing.T) { <ide> <ide> func TestSearchRepositories(t *testing.T) { <ide> r := spawnTestRegistrySession(t) <del> results, err := r.SearchRepositories("fakequery") <add> results, err := r.SearchRepositories("fakequery", 25) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide><path>registry/service.go <ide> import ( <ide> registrytypes "github.com/docker/engine-api/types/registry" <ide> ) <ide> <add>const ( <add> // DefaultSearchLimit is the default value for maximum number of returned search results. <add> DefaultSearchLimit = 25 <add>) <add> <ide> // Service is the interface defining what a registry service should implement. <ide> type Service interface { <ide> Auth(ctx context.Context, authConfig *types.AuthConfig, userAgent string) (status, token string, err error) <ide> LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) <ide> LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) <ide> ResolveRepository(name reference.Named) (*RepositoryInfo, error) <ide> ResolveIndex(name string) (*registrytypes.IndexInfo, error) <del> Search(ctx context.Context, term string, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) <add> Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) <ide> ServiceConfig() *registrytypes.ServiceConfig <ide> TLSConfig(hostname string) (*tls.Config, error) <ide> } <ide> func splitReposSearchTerm(reposName string) (string, string) { <ide> <ide> // Search queries the public registry for images matching the specified <ide> // search terms, and returns the results. <del>func (s *DefaultService) Search(ctx context.Context, term string, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) { <add>func (s *DefaultService) Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) { <ide> // TODO Use ctx when searching for repositories <ide> if err := validateNoScheme(term); err != nil { <ide> return nil, err <ide> func (s *DefaultService) Search(ctx context.Context, term string, authConfig *ty <ide> localName = strings.SplitN(localName, "/", 2)[1] <ide> } <ide> <del> return r.SearchRepositories(localName) <add> return r.SearchRepositories(localName, limit) <ide> } <del> return r.SearchRepositories(remoteName) <add> return r.SearchRepositories(remoteName, limit) <ide> } <ide> <ide> // ResolveRepository splits a repository name into its components <ide><path>registry/session.go <ide> func shouldRedirect(response *http.Response) bool { <ide> } <ide> <ide> // SearchRepositories performs a search against the remote repository <del>func (r *Session) SearchRepositories(term string) (*registrytypes.SearchResults, error) { <add>func (r *Session) SearchRepositories(term string, limit int) (*registrytypes.SearchResults, error) { <add> if limit < 1 || limit > 100 { <add> return nil, fmt.Errorf("Limit %d is outside the range of [1, 100]", limit) <add> } <ide> logrus.Debugf("Index server: %s", r.indexEndpoint) <del> u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) <add> u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) + "&n=" + url.QueryEscape(fmt.Sprintf("%d", limit)) <ide> <ide> req, err := http.NewRequest("GET", u, nil) <ide> if err != nil {
13
PHP
PHP
use proper assertions.
51c6c8604fb1c0f5a13585cf991a872bf2f242bb
<ide><path>tests/Filesystem/FilesystemAdapterTest.php <ide> public function testDelete() <ide> file_put_contents($this->tempDir.'/file.txt', 'Hello World'); <ide> $filesystemAdapter = new FilesystemAdapter($this->filesystem); <ide> $this->assertTrue($filesystemAdapter->delete('file.txt')); <del> $this->assertFalse(file_exists($this->tempDir.'/file.txt')); <add> $this->assertFileNotExists($this->tempDir.'/file.txt'); <ide> } <ide> <ide> public function testDeleteReturnsFalseWhenFileNotFound() <ide><path>tests/Integration/Database/EloquentCollectionLoadMissingTest.php <ide> public function testLoadMissing() <ide> $this->assertCount(2, \DB::getQueryLog()); <ide> $this->assertTrue($posts[0]->comments[0]->relationLoaded('parent')); <ide> $this->assertTrue($posts[0]->comments[1]->parent->relationLoaded('revisions')); <del> $this->assertFalse(array_key_exists('id', $posts[0]->comments[1]->parent->revisions[0]->getAttributes())); <add> $this->assertArrayNotHasKey('id', $posts[0]->comments[1]->parent->revisions[0]->getAttributes()); <ide> } <ide> <ide> public function testLoadMissingWithClosure() <ide> public function testLoadMissingWithClosure() <ide> <ide> $this->assertCount(1, \DB::getQueryLog()); <ide> $this->assertTrue($posts[0]->comments[0]->relationLoaded('parent')); <del> $this->assertFalse(array_key_exists('post_id', $posts[0]->comments[1]->parent->getAttributes())); <add> $this->assertArrayNotHasKey('post_id', $posts[0]->comments[1]->parent->getAttributes()); <ide> } <ide> } <ide> <ide><path>tests/Integration/Routing/UrlSigningTest.php <ide> public function test_signing_url() <ide> return $request->hasValidSignature() ? 'valid' : 'invalid'; <ide> })->name('foo'); <ide> <del> $this->assertTrue(is_string($url = URL::signedRoute('foo', ['id' => 1]))); <add> $this->assertInternalType('string', $url = URL::signedRoute('foo', ['id' => 1])); <ide> $this->assertEquals('valid', $this->get($url)->original); <ide> } <ide> <ide> public function test_temporary_signed_urls() <ide> })->name('foo'); <ide> <ide> Carbon::setTestNow(Carbon::create(2018, 1, 1)); <del> $this->assertTrue(is_string($url = URL::temporarySignedRoute('foo', now()->addMinutes(5), ['id' => 1]))); <add> $this->assertInternalType('string', $url = URL::temporarySignedRoute('foo', now()->addMinutes(5), ['id' => 1])); <ide> $this->assertEquals('valid', $this->get($url)->original); <ide> <ide> Carbon::setTestNow(Carbon::create(2018, 1, 1)->addMinutes(10)); <ide> public function test_signed_middleware() <ide> })->name('foo')->middleware(ValidateSignature::class); <ide> <ide> Carbon::setTestNow(Carbon::create(2018, 1, 1)); <del> $this->assertTrue(is_string($url = URL::temporarySignedRoute('foo', now()->addMinutes(5), ['id' => 1]))); <add> $this->assertInternalType('string', $url = URL::temporarySignedRoute('foo', now()->addMinutes(5), ['id' => 1])); <ide> $this->assertEquals('valid', $this->get($url)->original); <ide> } <ide> <ide> public function test_signed_middleware_with_invalid_url() <ide> })->name('foo')->middleware(ValidateSignature::class); <ide> <ide> Carbon::setTestNow(Carbon::create(2018, 1, 1)); <del> $this->assertTrue(is_string($url = URL::temporarySignedRoute('foo', now()->addMinutes(5), ['id' => 1]))); <add> $this->assertInternalType('string', $url = URL::temporarySignedRoute('foo', now()->addMinutes(5), ['id' => 1])); <ide> Carbon::setTestNow(Carbon::create(2018, 1, 1)->addMinutes(10)); <ide> <ide> $response = $this->get($url); <ide> public function test_signed_middleware_with_routable_parameter() <ide> return $request->hasValidSignature() ? $routable : 'invalid'; <ide> })->name('foo'); <ide> <del> $this->assertTrue(is_string($url = URL::signedRoute('foo', $model))); <add> $this->assertInternalType('string', $url = URL::signedRoute('foo', $model)); <ide> $this->assertEquals('routable', $this->get($url)->original); <ide> } <ide> } <ide><path>tests/Mail/MailableQueuedTest.php <ide> public function testQueuedMailableWithAttachmentSent() <ide> $mailable = new MailableQueableStub(); <ide> $attachmentOption = ['mime' => 'image/jpeg', 'as' => 'bar.jpg']; <ide> $mailable->attach('foo.jpg', $attachmentOption); <del> $this->assertTrue(is_array($mailable->attachments)); <add> $this->assertInternalType('array', $mailable->attachments); <ide> $this->assertCount(1, $mailable->attachments); <ide> $this->assertEquals($mailable->attachments[0]['options'], $attachmentOption); <ide> $queueFake->assertNothingPushed(); <ide> public function testQueuedMailableWithAttachmentFromDiskSent() <ide> <ide> $mailable->attachFromStorage('/', 'foo.jpg', $attachmentOption); <ide> <del> $this->assertTrue(is_array($mailable->diskAttachments)); <add> $this->assertInternalType('array', $mailable->diskAttachments); <ide> $this->assertCount(1, $mailable->diskAttachments); <ide> $this->assertEquals($mailable->diskAttachments[0]['options'], $attachmentOption); <ide>
4
Java
Java
make stringdecoder use databufferutils.split
a30a134c2397a7482bfd8c895f7ec1dc633e2067
<ide><path>spring-core/src/main/java/org/springframework/core/codec/StringDecoder.java <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferUtils; <del>import org.springframework.core.io.buffer.DefaultDataBufferFactory; <del>import org.springframework.core.io.buffer.PooledDataBuffer; <ide> import org.springframework.core.log.LogFormatUtils; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> */ <ide> public final class StringDecoder extends AbstractDataBufferDecoder<String> { <ide> <del> private static final DataBuffer END_FRAME = new DefaultDataBufferFactory().wrap(new byte[0]); <del> <ide> /** The default charset to use, i.e. "UTF-8". */ <ide> public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; <ide> <ide> public final class StringDecoder extends AbstractDataBufferDecoder<String> { <ide> <ide> private final boolean stripDelimiter; <ide> <del> private final ConcurrentMap<Charset, List<byte[]>> delimitersCache = new ConcurrentHashMap<>(); <add> private final ConcurrentMap<Charset, byte[][]> delimitersCache = new ConcurrentHashMap<>(); <ide> <ide> <ide> private StringDecoder(List<String> delimiters, boolean stripDelimiter, MimeType... mimeTypes) { <ide> public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType <ide> public Flux<String> decode(Publisher<DataBuffer> input, ResolvableType elementType, <ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { <ide> <del> List<byte[]> delimiterBytes = getDelimiterBytes(mimeType); <add> byte[][] delimiterBytes = getDelimiterBytes(mimeType); <ide> <del> Flux<DataBuffer> inputFlux = Flux.from(input) <del> .flatMapIterable(buffer -> splitOnDelimiter(buffer, delimiterBytes)) <del> .bufferUntil(buffer -> buffer == END_FRAME) <del> .map(StringDecoder::joinUntilEndFrame) <del> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release); <add> Flux<DataBuffer> inputFlux = <add> DataBufferUtils.split(input, delimiterBytes, this.stripDelimiter); <ide> <ide> return super.decode(inputFlux, elementType, mimeType, hints); <ide> } <ide> <del> private List<byte[]> getDelimiterBytes(@Nullable MimeType mimeType) { <add> private byte[][] getDelimiterBytes(@Nullable MimeType mimeType) { <ide> return this.delimitersCache.computeIfAbsent(getCharset(mimeType), charset -> { <del> List<byte[]> list = new ArrayList<>(); <del> for (String delimiter : this.delimiters) { <del> byte[] bytes = delimiter.getBytes(charset); <del> list.add(bytes); <add> byte[][] result = new byte[this.delimiters.size()][]; <add> for (int i = 0; i < this.delimiters.size(); i++) { <add> result[i] = this.delimiters.get(i).getBytes(charset); <ide> } <del> return list; <add> return result; <ide> }); <ide> } <ide> <del> /** <del> * Split the given data buffer on delimiter boundaries. <del> * The returned Flux contains an {@link #END_FRAME} buffer after each delimiter. <del> */ <del> private List<DataBuffer> splitOnDelimiter(DataBuffer buffer, List<byte[]> delimiterBytes) { <del> List<DataBuffer> frames = new ArrayList<>(); <del> try { <del> do { <del> int length = Integer.MAX_VALUE; <del> byte[] matchingDelimiter = null; <del> for (byte[] delimiter : delimiterBytes) { <del> int index = indexOf(buffer, delimiter); <del> if (index >= 0 && index < length) { <del> length = index; <del> matchingDelimiter = delimiter; <del> } <del> } <del> DataBuffer frame; <del> int readPosition = buffer.readPosition(); <del> if (matchingDelimiter != null) { <del> frame = this.stripDelimiter ? <del> buffer.slice(readPosition, length) : <del> buffer.slice(readPosition, length + matchingDelimiter.length); <del> buffer.readPosition(readPosition + length + matchingDelimiter.length); <del> frames.add(DataBufferUtils.retain(frame)); <del> frames.add(END_FRAME); <del> } <del> else { <del> frame = buffer.slice(readPosition, buffer.readableByteCount()); <del> buffer.readPosition(readPosition + buffer.readableByteCount()); <del> frames.add(DataBufferUtils.retain(frame)); <del> } <del> } <del> while (buffer.readableByteCount() > 0); <del> } <del> catch (Throwable ex) { <del> for (DataBuffer frame : frames) { <del> DataBufferUtils.release(frame); <del> } <del> throw ex; <del> } <del> finally { <del> DataBufferUtils.release(buffer); <del> } <del> return frames; <del> } <del> <del> /** <del> * Find the given delimiter in the given data buffer. <del> * @return the index of the delimiter, or -1 if not found. <del> */ <del> private static int indexOf(DataBuffer buffer, byte[] delimiter) { <del> for (int i = buffer.readPosition(); i < buffer.writePosition(); i++) { <del> int bufferPos = i; <del> int delimiterPos = 0; <del> while (delimiterPos < delimiter.length) { <del> if (buffer.getByte(bufferPos) != delimiter[delimiterPos]) { <del> break; <del> } <del> else { <del> bufferPos++; <del> boolean endOfBuffer = bufferPos == buffer.writePosition(); <del> boolean endOfDelimiter = delimiterPos == delimiter.length - 1; <del> if (endOfBuffer && !endOfDelimiter) { <del> return -1; <del> } <del> } <del> delimiterPos++; <del> } <del> if (delimiterPos == delimiter.length) { <del> return i - buffer.readPosition(); <del> } <del> } <del> return -1; <del> } <del> <del> /** <del> * Join the given list of buffers into a single buffer. <del> */ <del> private static DataBuffer joinUntilEndFrame(List<DataBuffer> dataBuffers) { <del> if (!dataBuffers.isEmpty()) { <del> int lastIdx = dataBuffers.size() - 1; <del> if (dataBuffers.get(lastIdx) == END_FRAME) { <del> dataBuffers.remove(lastIdx); <del> } <del> } <del> return dataBuffers.get(0).factory().join(dataBuffers); <del> } <del> <ide> @Override <ide> public String decode(DataBuffer dataBuffer, ResolvableType elementType, <ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { <ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java <ide> import java.nio.channels.CompletionHandler; <ide> import java.nio.channels.ReadableByteChannel; <ide> import java.nio.channels.WritableByteChannel; <add>import java.nio.charset.Charset; <ide> import java.nio.file.StandardOpenOption; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.concurrent.atomic.AtomicLong; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> import java.util.function.Consumer; <add>import java.util.function.IntPredicate; <ide> <ide> import org.reactivestreams.Publisher; <ide> import org.reactivestreams.Subscription; <ide> public abstract class DataBufferUtils { <ide> <ide> private static final Consumer<DataBuffer> RELEASE_CONSUMER = DataBufferUtils::release; <ide> <del> private static final DataBuffer END_FRAME = new DefaultDataBufferFactory().wrap(new byte[0]); <del> <ide> <ide> //--------------------------------------------------------------------- <ide> // Reading <ide> public static Flux<DataBuffer> split(Publisher<DataBuffer> dataBuffers, byte[] d <ide> /** <ide> * Splits the given stream of data buffers around the given delimiter. <ide> * The returned flux contains data buffers that are terminated by the given delimiter, <del> * which is included when {@code stripDelimiter} is {@code true}, or stripped off when <del> * {@code false}. <add> * which is included when {@code stripDelimiter} is {@code false}. <ide> * @param dataBuffers the input stream of data buffers <del> * @param delimiter the delimiting byte array <add> * @param delimiter the delimiter bytes <ide> * @param stripDelimiter whether to include the delimiter at the end of each resulting buffer <ide> * @return the flux of data buffers created by splitting the given data buffers around the <ide> * given delimiter <ide> * @since 5.2 <ide> */ <ide> public static Flux<DataBuffer> split(Publisher<DataBuffer> dataBuffers, byte[] delimiter, <ide> boolean stripDelimiter) { <add> <add> return split(dataBuffers, new byte[][]{delimiter}, stripDelimiter); <add> } <add> <add> /** <add> * Splits the given stream of data buffers around the given delimiters. <add> * The returned flux contains data buffers that are terminated by any of the given delimiters, <add> * which are included when {@code stripDelimiter} is {@code false}. <add> * @param dataBuffers the input stream of data buffers <add> * @param delimiters the delimiters, one per element <add> * @param stripDelimiter whether to include the delimiters at the end of each resulting buffer <add> * @return the flux of data buffers created by splitting the given data buffers around the <add> * given delimiters <add> * @since 5.2 <add> */ <add> public static Flux<DataBuffer> split(Publisher<DataBuffer> dataBuffers, byte[][] delimiters, <add> boolean stripDelimiter) { <ide> Assert.notNull(dataBuffers, "DataBuffers must not be null"); <del> Assert.isTrue(delimiter.length > 0, "Delimiter must not be empty"); <add> Assert.isTrue(delimiters.length > 0, "Delimiter must not be empty"); <add> <add> Matcher[] matchers = matchers(delimiters); <ide> <del> Matcher matcher = matcher(delimiter); <ide> return Flux.from(dataBuffers) <del> .flatMap(buffer -> endFrameOnDelimiter(buffer, matcher)) <del> .bufferUntil(buffer -> buffer == END_FRAME) <del> .map(buffers -> joinAndStrip(buffers, delimiter, stripDelimiter)) <add> .flatMap(buffer -> endFrameAfterDelimiter(buffer, matchers)) <add> .bufferUntil(buffer -> buffer instanceof EndFrameBuffer) <add> .map(buffers -> joinAndStrip(buffers, stripDelimiter)) <ide> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release); <ide> } <ide> <del> // Return Flux, because returning List (w/ flatMapIterable) results in memory leaks because <del> // of pre-fetching. <del> private static Flux<DataBuffer> endFrameOnDelimiter(DataBuffer dataBuffer, Matcher matcher) { <add> private static Matcher[] matchers(byte[][] delimiters) { <add> Assert.isTrue(delimiters.length > 0, "Delimiters must not be empty"); <add> Matcher[] result = new Matcher[delimiters.length]; <add> for (int i = 0; i < delimiters.length; i++) { <add> result[i] = matcher(delimiters[i]); <add> } <add> return result; <add> } <add> <add> /** <add> * Finds the {@link Matcher} with the first match and longest delimiter, and inserts a <add> * {@link EndFrameBuffer} just after its match. <add> * <add> * @param dataBuffer the buffer to find delimiters in <add> * @param matchers used to find the first delimiters <add> * @return a flux of buffers, containing {@link EndFrameBuffer} after each delimiter that was <add> * found in {@code dataBuffer}. Returns Flux, because returning List (w/ flatMapIterable) <add> * results in memory leaks due to pre-fetching. <add> */ <add> private static Flux<DataBuffer> endFrameAfterDelimiter(DataBuffer dataBuffer, Matcher[] matchers) { <ide> List<DataBuffer> result = new ArrayList<>(); <ide> do { <del> int endIdx = matcher.match(dataBuffer); <del> int readPosition = dataBuffer.readPosition(); <del> if (endIdx != -1) { <del> int length = endIdx + 1 - readPosition ; <add> int matchedEndIdx = Integer.MAX_VALUE; <add> byte[] matchedDelimiter = new byte[0]; <add> for (Matcher matcher : matchers) { <add> int endIdx = matcher.match(dataBuffer); <add> if (endIdx != -1 && <add> endIdx <= matchedEndIdx && <add> matcher.delimiter().length > matchedDelimiter.length) { <add> matchedEndIdx = endIdx; <add> matchedDelimiter = matcher.delimiter(); <add> } <add> } <add> if (matchedDelimiter.length > 0) { <add> int readPosition = dataBuffer.readPosition(); <add> int length = matchedEndIdx + 1 - readPosition ; <ide> result.add(dataBuffer.retainedSlice(readPosition, length)); <del> result.add(END_FRAME); <del> dataBuffer.readPosition(endIdx + 1); <add> result.add(new EndFrameBuffer(matchedDelimiter)); <add> dataBuffer.readPosition(matchedEndIdx + 1); <add> <add> for (Matcher matcher : matchers) { <add> matcher.reset(); <add> } <ide> } <ide> else { <ide> result.add(retain(dataBuffer)); <ide> private static Flux<DataBuffer> endFrameOnDelimiter(DataBuffer dataBuffer, Match <ide> return Flux.fromIterable(result); <ide> } <ide> <del> private static DataBuffer joinAndStrip(List<DataBuffer> dataBuffers, byte[] delimiter, <add> /** <add> * Joins the given list of buffers. If the list ends with a {@link EndFrameBuffer}, it is <add> * removed. If {@code stripDelimiter} is {@code true} and the resulting buffer ends with <add> * a delimiter, it is removed. <add> * @param dataBuffers the data buffers to join <add> * @param stripDelimiter whether to strip the delimiter <add> * @return <add> */ <add> private static DataBuffer joinAndStrip(List<DataBuffer> dataBuffers, <ide> boolean stripDelimiter) { <ide> <ide> Assert.state(!dataBuffers.isEmpty(), "DataBuffers should not be empty"); <ide> <del> boolean endFrameFound = false; <add> byte[] matchingDelimiter = null; <add> <ide> int lastIdx = dataBuffers.size() - 1; <del> if (dataBuffers.get(lastIdx) == END_FRAME) { <del> endFrameFound = true; <add> DataBuffer lastBuffer = dataBuffers.get(lastIdx); <add> if (lastBuffer instanceof EndFrameBuffer) { <add> matchingDelimiter = ((EndFrameBuffer) lastBuffer).delimiter(); <ide> dataBuffers.remove(lastIdx); <ide> } <ide> <ide> DataBuffer result = dataBuffers.get(0).factory().join(dataBuffers); <del> if (stripDelimiter && endFrameFound) { <del> result.writePosition(result.writePosition() - delimiter.length); <add> <add> if (stripDelimiter && matchingDelimiter != null) { <add> result.writePosition(result.writePosition() - matchingDelimiter.length); <ide> } <ide> return result; <ide> } <ide> public interface Matcher { <ide> */ <ide> byte[] delimiter(); <ide> <add> /** <add> * Resets the state of this matcher. <add> */ <add> void reset(); <add> <ide> } <ide> <ide> <ide> public int match(DataBuffer dataBuffer) { <ide> if (b == this.delimiter[this.matches]) { <ide> this.matches++; <ide> if (this.matches == this.delimiter.length) { <del> this.matches = 0; <add> reset(); <ide> return i; <ide> } <ide> } <ide> public int match(DataBuffer dataBuffer) { <ide> public byte[] delimiter() { <ide> return Arrays.copyOf(this.delimiter, this.delimiter.length); <ide> } <add> <add> @Override <add> public void reset() { <add> this.matches = 0; <add> } <add> } <add> <add> <add> private static class EndFrameBuffer implements DataBuffer { <add> <add> private static final DataBuffer BUFFER = new DefaultDataBufferFactory().wrap(new byte[0]); <add> <add> private byte[] delimiter; <add> <add> <add> public EndFrameBuffer(byte[] delimiter) { <add> this.delimiter = delimiter; <add> } <add> <add> public byte[] delimiter() { <add> return this.delimiter; <add> } <add> <add> @Override <add> public DataBufferFactory factory() { <add> return BUFFER.factory(); <add> } <add> <add> @Override <add> public int indexOf(IntPredicate predicate, int fromIndex) { <add> return BUFFER.indexOf(predicate, fromIndex); <add> } <add> <add> @Override <add> public int lastIndexOf(IntPredicate predicate, int fromIndex) { <add> return BUFFER.lastIndexOf(predicate, fromIndex); <add> } <add> <add> @Override <add> public int readableByteCount() { <add> return BUFFER.readableByteCount(); <add> } <add> <add> @Override <add> public int writableByteCount() { <add> return BUFFER.writableByteCount(); <add> } <add> <add> @Override <add> public int capacity() { <add> return BUFFER.capacity(); <add> } <add> <add> @Override <add> public DataBuffer capacity(int capacity) { <add> return BUFFER.capacity(capacity); <add> } <add> <add> @Override <add> public DataBuffer ensureCapacity(int capacity) { <add> return BUFFER.ensureCapacity(capacity); <add> } <add> <add> @Override <add> public int readPosition() { <add> return BUFFER.readPosition(); <add> } <add> <add> @Override <add> public DataBuffer readPosition(int readPosition) { <add> return BUFFER.readPosition(readPosition); <add> } <add> <add> @Override <add> public int writePosition() { <add> return BUFFER.writePosition(); <add> } <add> <add> @Override <add> public DataBuffer writePosition(int writePosition) { <add> return BUFFER.writePosition(writePosition); <add> } <add> <add> @Override <add> public byte getByte(int index) { <add> return BUFFER.getByte(index); <add> } <add> <add> @Override <add> public byte read() { <add> return BUFFER.read(); <add> } <add> <add> @Override <add> public DataBuffer read(byte[] destination) { <add> return BUFFER.read(destination); <add> } <add> <add> @Override <add> public DataBuffer read(byte[] destination, int offset, int length) { <add> return BUFFER.read(destination, offset, length); <add> } <add> <add> @Override <add> public DataBuffer write(byte b) { <add> return BUFFER.write(b); <add> } <add> <add> @Override <add> public DataBuffer write(byte[] source) { <add> return BUFFER.write(source); <add> } <add> <add> @Override <add> public DataBuffer write(byte[] source, int offset, int length) { <add> return BUFFER.write(source, offset, length); <add> } <add> <add> @Override <add> public DataBuffer write(DataBuffer... buffers) { <add> return BUFFER.write(buffers); <add> } <add> <add> @Override <add> public DataBuffer write(ByteBuffer... buffers) { <add> return BUFFER.write(buffers); <add> } <add> <add> @Override <add> public DataBuffer write(CharSequence charSequence, Charset charset) { <add> return BUFFER.write(charSequence, charset); <add> } <add> <add> @Override <add> public DataBuffer slice(int index, int length) { <add> return BUFFER.slice(index, length); <add> } <add> <add> @Override <add> public DataBuffer retainedSlice(int index, int length) { <add> return BUFFER.retainedSlice(index, length); <add> } <add> <add> @Override <add> public ByteBuffer asByteBuffer() { <add> return BUFFER.asByteBuffer(); <add> } <add> <add> @Override <add> public ByteBuffer asByteBuffer(int index, int length) { <add> return BUFFER.asByteBuffer(index, length); <add> } <add> <add> @Override <add> public InputStream asInputStream() { <add> return BUFFER.asInputStream(); <add> } <add> <add> @Override <add> public InputStream asInputStream(boolean releaseOnClose) { <add> return BUFFER.asInputStream(releaseOnClose); <add> } <add> <add> @Override <add> public OutputStream asOutputStream() { <add> return BUFFER.asOutputStream(); <add> } <ide> } <ide> <ide> } <ide><path>spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java <ide> public void splitIncludeDelimiter() { <ide> .verifyComplete(); <ide> } <ide> <add> @Test <add> public void splitMultipleDelimiters() { <add> Mono<DataBuffer> source = <add> deferStringBuffer("foo␤bar␍␤baz␤"); <add> <add> byte[][] delimiters = new byte[][]{ <add> "␤".getBytes(StandardCharsets.UTF_8), <add> "␍␤".getBytes(StandardCharsets.UTF_8) <add> }; <add> <add> Flux<DataBuffer> result = DataBufferUtils.split(source, delimiters, false); <add> <add> StepVerifier.create(result) <add> .consumeNextWith(stringConsumer("foo␤")) <add> .consumeNextWith(stringConsumer("bar␍␤")) <add> .consumeNextWith(stringConsumer("baz␤")) <add> .verifyComplete(); <add> } <add> <ide> @Test <ide> public void splitErrors() { <ide> Flux<DataBuffer> source = Flux.concat(
3
Python
Python
break reference cycle in npzfile
c4482f56b347760260a695a72f7ccbd26d02756c
<ide><path>numpy/lib/npyio.py <ide> import sys <ide> import itertools <ide> import warnings <add>import weakref <ide> from operator import itemgetter <ide> <ide> from cPickle import load as _cload, loads <ide> class BagObj(object): <ide> <ide> """ <ide> def __init__(self, obj): <del> self._obj = obj <add> # Use weakref to make NpzFile objects collectable by refcount <add> self._obj = weakref.proxy(obj) <ide> def __getattribute__(self, key): <ide> try: <ide> return object.__getattribute__(self, '_obj')[key] <ide> def close(self): <ide> if self.fid is not None: <ide> self.fid.close() <ide> self.fid = None <add> self.f = None # break reference cycle <ide> <ide> def __del__(self): <ide> self.close() <ide><path>numpy/lib/tests/test_io.py <ide> import time <ide> from datetime import datetime <ide> import warnings <add>import gc <ide> from numpy.testing.utils import WarningManager <ide> <ide> import numpy as np <ide> def test_npzfile_dict(): <ide> <ide> assert_('x' in list(z.iterkeys())) <ide> <add>def test_load_refcount(): <add> # Check that objects returned by np.load are directly freed based on <add> # their refcount, rather than needing the gc to collect them. <add> <add> f = StringIO() <add> np.savez(f, [1, 2, 3]) <add> f.seek(0) <add> <add> gc.collect() <add> n_before = len(gc.get_objects()) <add> np.load(f) <add> n_after = len(gc.get_objects()) <add> <add> assert_equal(n_before, n_after) <ide> <ide> if __name__ == "__main__": <ide> run_module_suite()
2
PHP
PHP
add missing methods to entityinterface
beea1121dcdbb694560ef02e63c26dcaf58c13c0
<ide><path>src/Datasource/EntityInterface.php <ide> * Describes the methods that any class representing a data storage should <ide> * comply with. <ide> * <del> * In 4.x the following methods will officially be added to the interface: <del> * <del> * @method $this setHidden(array $properties, $merge = false) <del> * @method array getHidden() <del> * @method $this setVirtual(array $properties, $merge = false) <del> * @method array getVirtual() <del> * @method $this setDirty($property, $isDirty) <del> * @method bool isDirty($property = null) <del> * @method array getErrors() <del> * @method array getError($field) <del> * @method array setErrors(array $fields, $overwrite = false) <del> * @method array setError($field, $errors, $overwrite = false) <del> * @method $this setAccess($property, $set) <del> * @method bool isAccessible($property) <del> * @method $this setSource($source) <del> * @method string getSource() <del> * @method array extractOriginal(array $properties) <del> * @method array extractOriginalChanged(array $properties) <del> * <ide> * @property mixed $id Alias for commonly used primary key. <ide> */ <ide> interface EntityInterface extends ArrayAccess, JsonSerializable <ide> { <ide> <add> /** <add> * Sets hidden properties. <add> * <add> * @param array $properties An array of properties to hide from array exports. <add> * @param bool $merge Merge the new properties with the existing. By default false. <add> * @return $this <add> */ <add> public function setHidden(array $properties, $merge = false); <add> <add> /** <add> * Gets the hidden properties. <add> * <add> * @return array <add> */ <add> public function getHidden(); <add> <add> /** <add> * Sets the virtual properties on this entity. <add> * <add> * @param array $properties An array of properties to treat as virtual. <add> * @param bool $merge Merge the new properties with the existing. By default false. <add> * @return $this <add> */ <add> public function setVirtual(array $properties, $merge = false); <add> <add> /** <add> * Gets the virtual properties on this entity. <add> * <add> * @return array <add> */ <add> public function getVirtual(); <add> <add> /** <add> * Sets the dirty status of a single property. <add> * <add> * @param string $property the field to set or check status for <add> * @param bool $isDirty true means the property was changed, false means <add> * it was not changed <add> * @return $this <add> */ <add> public function setDirty($property, $isDirty); <add> <add> /** <add> * Checks if the entity is dirty or if a single property of it is dirty. <add> * <add> * @param string|null $property The field to check the status for. Null for the whole entity. <add> * @return bool Whether the property was changed or not <add> */ <add> public function isDirty($property = null); <add> <add> /** <add> * Returns all validation errors. <add> * <add> * @return array <add> */ <add> public function getErrors(); <add> <add> /** <add> * Returns validation errors of a field <add> * <add> * @param string $field Field name to get the errors from <add> * @return array <add> */ <add> public function getError($field); <add> <add> /** <add> * Sets error messages to the entity <add> * <add> * @param array $fields The array of errors to set. <add> * @param bool $overwrite Whether or not to overwrite pre-existing errors for $fields <add> * @return $this <add> */ <add> public function setErrors(array $fields, $overwrite = false); <add> <add> /** <add> * Sets errors for a single field <add> * <add> * @param string $field The field to get errors for, or the array of errors to set. <add> * @param string|array $errors The errors to be set for $field <add> * @param bool $overwrite Whether or not to overwrite pre-existing errors for $field <add> * @return $this <add> */ <add> public function setError($field, $errors, $overwrite = false); <add> <add> /** <add> * Stores whether or not a property value can be changed or set in this entity. <add> * <add> * @param string|array $property single or list of properties to change its accessibility <add> * @param bool $set true marks the property as accessible, false will <add> * mark it as protected. <add> * @return $this <add> */ <add> public function setAccess($property, $set); <add> <add> /** <add> * Checks if a property is accessible <add> * <add> * @param string $property Property name to check <add> * @return bool <add> */ <add> public function isAccessible($property); <add> <add> /** <add> * Sets the source alias <add> * <add> * @param string $alias the alias of the repository <add> * @return $this <add> */ <add> public function setSource($alias); <add> <add> /** <add> * Returns the alias of the repository from which this entity came from. <add> * <add> * @return string <add> */ <add> public function getSource(); <add> <add> /** <add> * Returns an array with the requested original properties <add> * stored in this entity, indexed by property name. <add> * <add> * @param array $properties List of properties to be returned <add> * @return array <add> */ <add> public function extractOriginal(array $properties); <add> <add> /** <add> * Returns an array with only the original properties <add> * stored in this entity, indexed by property name. <add> * <add> * @param array $properties List of properties to be returned <add> * @return array <add> */ <add> public function extractOriginalChanged(array $properties); <add> <ide> /** <ide> * Sets one or multiple properties to the specified value <ide> *
1
Text
Text
release notes for 1.2.11
c0c0b2b67461b2c6521ae290fb1a7ea19ff075e8
<ide><path>CHANGELOG.md <add><a name="1.2.11"></a> <add># 1.2.11 cryptocurrency-hyperdeflation (2014-02-03) <add> <add>## Bug Fixes <add> <add>- **$compile:** retain CSS classes added in cloneAttachFn on asynchronous directives <add> ([5ed721b9](https://github.com/angular/angular.js/commit/5ed721b9b5e95ae08450e1ae9d5202e7f3f79295), <add> [#5439](https://github.com/angular/angular.js/issues/5439), [#5617](https://github.com/angular/angular.js/issues/5617)) <add>- **$http:** update httpBackend to use ActiveXObject on IE8 if necessary <add> ([ef210e5e](https://github.com/angular/angular.js/commit/ef210e5e119db4f5bfc9d2428b19f9b335c4f976), <add> [#5677](https://github.com/angular/angular.js/issues/5677), [#5679](https://github.com/angular/angular.js/issues/5679)) <add>- **$q:** make $q.reject support `finally` and `catch` <add> ([074b0675](https://github.com/angular/angular.js/commit/074b0675a1f97dce07f520f1ae6198ed3c604000), <add> [#6048](https://github.com/angular/angular.js/issues/6048), [#6076](https://github.com/angular/angular.js/issues/6076)) <add>- **filterFilter:** don't interpret dots in predicate object fields as paths <add> ([339a1658](https://github.com/angular/angular.js/commit/339a1658cd9bfa5e322a01c45aa0a1df67e3a842), <add> [#6005](https://github.com/angular/angular.js/issues/6005), [#6009](https://github.com/angular/angular.js/issues/6009)) <add>- **mocks:** refactor currentSpec to work w/ Jasmine 2 <add> ([95f0bf9b](https://github.com/angular/angular.js/commit/95f0bf9b526fda8964527c6d4aef1ad50a47f1f3), <add> [#5662](https://github.com/angular/angular.js/issues/5662)) <add>- **ngResource:** don't append number to '$' in url param value when encoding URI <add> ([ce1f1f97](https://github.com/angular/angular.js/commit/ce1f1f97f0ebf77941b2bdaf5e8352d33786524d), <add> [#6003](https://github.com/angular/angular.js/issues/6003), [#6004](https://github.com/angular/angular.js/issues/6004)) <add> <ide> <a name="1.2.10"></a> <ide> # 1.2.10 augmented-serendipity (2014-01-24) <ide>
1
Javascript
Javascript
move some of the sizzle tests to selector
81aa237ee11c731ee92ad6cf7cf958e80f15d057
<ide><path>test/unit/selector.js <ide> test("element - jQuery only", function() { <ide> equal( jQuery("<div id=\"A'B~C.D[E]\"><p>foo</p></div>").find("p").length, 1, "Find where context root is a node and has an ID with CSS3 meta characters" ); <ide> }); <ide> <add>test("id", function() { <add> expect( 26 ); <add> <add> var a; <add> <add> t( "ID Selector", "#body", ["body"] ); <add> t( "ID Selector w/ Element", "body#body", ["body"] ); <add> t( "ID Selector w/ Element", "ul#first", [] ); <add> t( "ID selector with existing ID descendant", "#firstp #simon1", ["simon1"] ); <add> t( "ID selector with non-existant descendant", "#firstp #foobar", [] ); <add> t( "ID selector using UTF8", "#台北Táiběi", ["台北Táiběi"] ); <add> t( "Multiple ID selectors using UTF8", "#台北Táiběi, #台北", ["台北Táiběi","台北"] ); <add> t( "Descendant ID selector using UTF8", "div #台北", ["台北"] ); <add> t( "Child ID selector using UTF8", "form > #台北", ["台北"] ); <add> <add> t( "Escaped ID", "#foo\\:bar", ["foo:bar"] ); <add> t( "Escaped ID", "#test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); <add> t( "Descendant escaped ID", "div #foo\\:bar", ["foo:bar"] ); <add> t( "Descendant escaped ID", "div #test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); <add> t( "Child escaped ID", "form > #foo\\:bar", ["foo:bar"] ); <add> t( "Child escaped ID", "form > #test\\.foo\\[5\\]bar", ["test.foo[5]bar"] ); <add> <add> t( "ID Selector, child ID present", "#form > #radio1", ["radio1"] ); // bug #267 <add> t( "ID Selector, not an ancestor ID", "#form #first", [] ); <add> t( "ID Selector, not a child ID", "#form > #option1a", [] ); <add> <add> t( "All Children of ID", "#foo > *", ["sndp", "en", "sap"] ); <add> t( "All Children of ID with no children", "#firstUL > *", [] ); <add> <add> a = jQuery("<a id='backslash\\foo'></a>").appendTo("#qunit-fixture"); <add> t( "ID Selector contains backslash", "#backslash\\\\foo", ["backslash\\foo"] ); <add> <add> t( "ID Selector on Form with an input that has a name of 'id'", "#lengthtest", ["lengthtest"] ); <add> <add> t( "ID selector with non-existant ancestor", "#asdfasdf #foobar", [] ); // bug #986 <add> <add> t( "Underscore ID", "#types_all", ["types_all"] ); <add> t( "Dash ID", "#qunit-fixture", ["qunit-fixture"] ); <add> <add> t( "ID with weird characters in it", "#name\\+value", ["name+value"] ); <add>}); <add> <ide> test("class - jQuery only", function() { <ide> expect( 4 ); <ide> <ide> test("class - jQuery only", function() { <ide> deepEqual( jQuery("p").find(".blog").get(), q("mark", "simon"), "Finding elements with a context." ); <ide> }); <ide> <add>test("name", function() { <add> expect( 5 ); <add> <add> var form; <add> <add> t( "Name selector", "input[name=action]", ["text1"] ); <add> t( "Name selector with single quotes", "input[name='action']", ["text1"] ); <add> t( "Name selector with double quotes", "input[name=\"action\"]", ["text1"] ); <add> <add> t( "Name selector for grouped input", "input[name='types[]']", ["types_all", "types_anime", "types_movie"] ); <add> <add> form = jQuery("<form><input name='id'/></form>").appendTo("body"); <add> equal( jQuery("input", form[0]).length, 1, "Make sure that rooted queries on forms (with possible expandos) work." ); <add> <add> form.remove(); <add>}); <add> <ide> test("attributes - jQuery only", function() { <ide> expect( 5 ); <ide> <ide> testIframe("selector/sizzle_cache", "Sizzle cache collides with multiple Sizzles <ide> equal( jQuery(".evil a").length, 0, "Select nothing with second sizzle" ); <ide> equal( jQuery(".evil a").length, 0, "Select nothing again with second sizzle" ); <ide> }); <add> <add>asyncTest( "Iframe dispatch should not affect Sizzle, see #13936", 1, function() { <add> var loaded = false, <add> thrown = false, <add> iframe = document.getElementById("iframe"), <add> iframeDoc = iframe.contentDocument || iframe.contentWindow.document; <add> <add> jQuery( iframe ).on( "load", function() { <add> var form; <add> <add> try { <add> iframeDoc = this.contentDocument || this.contentWindow.document; <add> form = jQuery( "#navigate", iframeDoc )[ 0 ]; <add> } catch ( e ) { <add> thrown = e; <add> } <add> <add> if ( loaded ) { <add> strictEqual( thrown, false, "No error thrown from post-reload jQuery call" ); <add> <add> // clean up <add> jQuery( iframe ).off(); <add> <add> start(); <add> } else { <add> loaded = true; <add> form.submit(); <add> } <add> }); <add> <add> iframeDoc.open(); <add> iframeDoc.write("<body><form id='navigate'></form></body>"); <add> iframeDoc.close(); <add>});
1
Python
Python
fix assertion for nested create test (missing id)
8a41d4aa5411560aabc5c198976b7df6580e6143
<ide><path>rest_framework/tests/nested_relations.py <ide> def setUp(self): <ide> def save_serialized_target(self, instance, data): <ide> serializer = ForeignKeyTargetSerializer(instance, data=data) <ide> self.assertTrue(serializer.is_valid()) <del> self.assertEquals(serializer.data, data) <ide> serializer.save() <ide> <ide> def check_serialized_targets(self, data):
1
Javascript
Javascript
fix module preloading when cwd is enoent
2d251e661a8c761e0c1bd809fdc6a29179950c00
<ide><path>lib/module.js <ide> Module._preloadModules = function(requests) { <ide> // in the current working directory. This seeds the search path for <ide> // preloaded modules. <ide> var parent = new Module('internal/preload', null); <del> parent.paths = Module._nodeModulePaths(process.cwd()); <add> try { <add> parent.paths = Module._nodeModulePaths(process.cwd()); <add> } <add> catch (e) { <add> if (e.code !== 'ENOENT') { <add> throw e; <add> } <add> } <ide> requests.forEach(function(request) { <del> Module._load(request, parent, false); <add> parent.require(request); <ide> }); <ide> }; <ide> <ide><path>test/parallel/test-cwd-enoent-preload.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const fs = require('fs'); <add>const spawn = require('child_process').spawn; <add> <add>// Fails with EINVAL on SmartOS, EBUSY on Windows. <add>if (process.platform === 'sunos' || common.isWindows) { <add> console.log('1..0 # Skipped: cannot rmdir current working directory'); <add> return; <add>} <add> <add>const dirname = common.tmpDir + '/cwd-does-not-exist-' + process.pid; <add>const abspathFile = require('path').join(common.fixturesDir, 'a.js'); <add>common.refreshTmpDir(); <add>fs.mkdirSync(dirname); <add>process.chdir(dirname); <add>fs.rmdirSync(dirname); <add> <add> <add>const proc = spawn(process.execPath, ['-r', abspathFile, '-e', '0']); <add>proc.stdout.pipe(process.stdout); <add>proc.stderr.pipe(process.stderr); <add> <add>proc.once('exit', common.mustCall(function(exitCode, signalCode) { <add> assert.strictEqual(exitCode, 0); <add> assert.strictEqual(signalCode, null); <add>}));
2
Go
Go
remove dead code in registry package
962dc622d94a17a30a5926e8155da87a7e39e933
<ide><path>registry/auth.go <ide> import ( <ide> "io/ioutil" <ide> "net/http" <ide> "strings" <del> "sync" <del> "time" <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/cliconfig" <ide> ) <ide> <del>type RequestAuthorization struct { <del> authConfig *cliconfig.AuthConfig <del> registryEndpoint *Endpoint <del> resource string <del> scope string <del> actions []string <del> <del> tokenLock sync.Mutex <del> tokenCache string <del> tokenExpiration time.Time <del>} <del> <del>func NewRequestAuthorization(authConfig *cliconfig.AuthConfig, registryEndpoint *Endpoint, resource, scope string, actions []string) *RequestAuthorization { <del> return &RequestAuthorization{ <del> authConfig: authConfig, <del> registryEndpoint: registryEndpoint, <del> resource: resource, <del> scope: scope, <del> actions: actions, <del> } <del>} <del> <del>func (auth *RequestAuthorization) getToken() (string, error) { <del> auth.tokenLock.Lock() <del> defer auth.tokenLock.Unlock() <del> now := time.Now() <del> if now.Before(auth.tokenExpiration) { <del> logrus.Debugf("Using cached token for %s", auth.authConfig.Username) <del> return auth.tokenCache, nil <del> } <del> <del> for _, challenge := range auth.registryEndpoint.AuthChallenges { <del> switch strings.ToLower(challenge.Scheme) { <del> case "basic": <del> // no token necessary <del> case "bearer": <del> logrus.Debugf("Getting bearer token with %s for %s", challenge.Parameters, auth.authConfig.Username) <del> params := map[string]string{} <del> for k, v := range challenge.Parameters { <del> params[k] = v <del> } <del> params["scope"] = fmt.Sprintf("%s:%s:%s", auth.resource, auth.scope, strings.Join(auth.actions, ",")) <del> token, err := getToken(auth.authConfig.Username, auth.authConfig.Password, params, auth.registryEndpoint) <del> if err != nil { <del> return "", err <del> } <del> auth.tokenCache = token <del> auth.tokenExpiration = now.Add(time.Minute) <del> <del> return token, nil <del> default: <del> logrus.Infof("Unsupported auth scheme: %q", challenge.Scheme) <del> } <del> } <del> <del> // Do not expire cache since there are no challenges which use a token <del> auth.tokenExpiration = time.Now().Add(time.Hour * 24) <del> <del> return "", nil <del>} <del> <del>// Checks that requests to the v2 registry can be authorized. <del>func (auth *RequestAuthorization) CanAuthorizeV2() bool { <del> if len(auth.registryEndpoint.AuthChallenges) == 0 { <del> return true <del> } <del> scope := fmt.Sprintf("%s:%s:%s", auth.resource, auth.scope, strings.Join(auth.actions, ",")) <del> if _, err := loginV2(auth.authConfig, auth.registryEndpoint, scope); err != nil { <del> logrus.Debugf("Cannot authorize against V2 endpoint: %s", auth.registryEndpoint) <del> return false <del> } <del> return true <del>} <del> <del>func (auth *RequestAuthorization) Authorize(req *http.Request) error { <del> token, err := auth.getToken() <del> if err != nil { <del> return err <del> } <del> if token != "" { <del> req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) <del> } else if auth.authConfig.Username != "" && auth.authConfig.Password != "" { <del> req.SetBasicAuth(auth.authConfig.Username, auth.authConfig.Password) <del> } <del> return nil <del>} <del> <ide> // Login tries to register/login to the registry server. <ide> func Login(authConfig *cliconfig.AuthConfig, registryEndpoint *Endpoint) (string, error) { <ide> // Separates the v2 registry login logic from the v1 logic.
1
Javascript
Javascript
add documentation for ember.mixin
a73ba1c2e222f477eb49f33b80203ea776970584
<ide><path>packages/ember-metal/lib/mixin.js <ide> Ember.mixin = function(obj) { <ide> <ide> <ide> /** <del> @constructor <add> @class <add> <add> The `Ember.Mixin` class allows you to create mixins, whose properties can be <add> added to other classes. For instance, <add> <add> App.Editable = Ember.Mixin.create({ <add> edit: function() { <add> console.log('starting to edit'); <add> this.set('isEditing', true); <add> }, <add> isEditing: false <add> }); <add> <add> // Mix mixins into classes by passing them as the first arguments to <add> // .extend or .create. <add> App.CommentView = Ember.View.extend(App.Editable, { <add> template: Ember.Handlebars.compile('{{#if isEditing}}...{{else}}...{{/if}}') <add> }); <add> <add> commentView = App.CommentView.create(); <add> commentView.edit(); // => outputs 'starting to edit' <add> <add> Note that Mixins are created with `Ember.Mixin.create`, not <add> `Ember.Mixin.extend`. <ide> */ <ide> Ember.Mixin = function() { return initMixin(this, arguments); }; <ide>
1
Javascript
Javascript
simplify wording of key warning
547e059f0bc88e76cd738b01b76e777ff1b222a7
<ide><path>packages/react-dom/src/__tests__/ReactFunctionComponent-test.js <ide> describe('ReactFunctionComponent', () => { <ide> } <ide> <ide> expect(() => ReactTestUtils.renderIntoDocument(<Child />)).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.\n\n' + <add> 'Each child in a list should have a unique "key" prop.\n\n' + <ide> 'Check the render method of `Child`.', <ide> ); <ide> }); <ide><path>packages/react-dom/src/__tests__/ReactMultiChildText-test.js <ide> describe('ReactMultiChildText', () => { <ide> ['', 'foo', <div>{true}{<div />}{1.2}{''}</div>, 'foo'], ['', 'foo', <div />, 'foo'], <ide> ]); <ide> }).toWarnDev([ <del> 'Warning: Each child in an array or iterator should have a unique "key" prop.', <del> 'Warning: Each child in an array or iterator should have a unique "key" prop.', <add> 'Warning: Each child in a list should have a unique "key" prop.', <add> 'Warning: Each child in a list should have a unique "key" prop.', <ide> ]); <ide> }); <ide> <ide><path>packages/react-reconciler/src/ReactChildFiber.js <ide> if (__DEV__) { <ide> child._store.validated = true; <ide> <ide> const currentComponentErrorInfo = <del> 'Each child in an array or iterator should have a unique ' + <add> 'Each child in a list should have a unique ' + <ide> '"key" prop. See https://fb.me/react-warning-keys for ' + <ide> 'more information.' + <ide> getCurrentFiberStackInDev(); <ide> if (__DEV__) { <ide> <ide> warning( <ide> false, <del> 'Each child in an array or iterator should have a unique ' + <add> 'Each child in a list should have a unique ' + <ide> '"key" prop. See https://fb.me/react-warning-keys for ' + <ide> 'more information.', <ide> ); <ide><path>packages/react-reconciler/src/__tests__/ReactFragment-test.js <ide> describe('ReactFragment', () => { <ide> <ide> ReactNoop.render(<Foo condition={false} />); <ide> expect(ReactNoop.flush).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.', <add> 'Each child in a list should have a unique "key" prop.', <ide> ); <ide> <ide> expect(ops).toEqual([]); <ide> describe('ReactFragment', () => { <ide> <ide> ReactNoop.render(<Foo condition={true} />); <ide> expect(ReactNoop.flush).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.', <add> 'Each child in a list should have a unique "key" prop.', <ide> ); <ide> <ide> ReactNoop.render(<Foo condition={false} />); <ide> expect(ReactNoop.flush).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.', <add> 'Each child in a list should have a unique "key" prop.', <ide> ); <ide> <ide> expect(ops).toEqual(['Update Stateful']); <ide> expect(ReactNoop.getChildren()).toEqual([span(), div()]); <ide> <ide> ReactNoop.render(<Foo condition={true} />); <ide> expect(ReactNoop.flush).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.', <add> 'Each child in a list should have a unique "key" prop.', <ide> ); <ide> <ide> expect(ops).toEqual(['Update Stateful', 'Update Stateful']); <ide><path>packages/react/src/ReactElementValidator.js <ide> function validateExplicitKey(element, parentType) { <ide> if (__DEV__) { <ide> warning( <ide> false, <del> 'Each child in an array or iterator should have a unique "key" prop.' + <add> 'Each child in a list should have a unique "key" prop.' + <ide> '%s%s See https://fb.me/react-warning-keys for more information.', <ide> currentComponentErrorInfo, <ide> childOwner, <ide><path>packages/react/src/__tests__/ReactChildren-test.js <ide> describe('ReactChildren', () => { <ide> <ide> let instance; <ide> expect(() => (instance = <div>{threeDivIterable}</div>)).toWarnDev( <del> 'Warning: Each child in an array or iterator should have a unique "key" prop.', <add> 'Warning: Each child in a list should have a unique "key" prop.', <ide> ); <ide> <ide> function assertCalls() { <ide> describe('ReactChildren', () => { <ide> ReactTestUtils.renderIntoDocument(<ComponentReturningArray />), <ide> ).toWarnDev( <ide> 'Warning: ' + <del> 'Each child in an array or iterator should have a unique "key" prop.' + <add> 'Each child in a list should have a unique "key" prop.' + <ide> ' See https://fb.me/react-warning-keys for more information.' + <ide> '\n in ComponentReturningArray (at **)', <ide> ); <ide> describe('ReactChildren', () => { <ide> ReactTestUtils.renderIntoDocument([<div />, <div />]), <ide> ).toWarnDev( <ide> 'Warning: ' + <del> 'Each child in an array or iterator should have a unique "key" prop.' + <add> 'Each child in a list should have a unique "key" prop.' + <ide> ' See https://fb.me/react-warning-keys for more information.', <ide> {withoutStack: true}, // There's nothing on the stack <ide> ); <ide><path>packages/react/src/__tests__/ReactElementClone-test.js <ide> describe('ReactElementClone', () => { <ide> it('warns for keys for arrays of elements in rest args', () => { <ide> expect(() => <ide> React.cloneElement(<div />, null, [<div />, <div />]), <del> ).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.', <del> ); <add> ).toWarnDev('Each child in a list should have a unique "key" prop.'); <ide> }); <ide> <ide> it('does not warns for arrays of elements with keys', () => { <ide><path>packages/react/src/__tests__/ReactElementValidator-test.internal.js <ide> describe('ReactElementValidator', () => { <ide> <ide> expect(() => { <ide> Component(null, [Component(), Component()]); <del> }).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.', <del> ); <add> }).toWarnDev('Each child in a list should have a unique "key" prop.'); <ide> }); <ide> <ide> it('warns for keys for arrays of elements with owner info', () => { <ide> describe('ReactElementValidator', () => { <ide> expect(() => { <ide> ReactTestUtils.renderIntoDocument(React.createElement(ComponentWrapper)); <ide> }).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.' + <add> 'Each child in a list should have a unique "key" prop.' + <ide> '\n\nCheck the render method of `InnerClass`. ' + <ide> 'It was passed a child from ComponentWrapper. ', <ide> ); <ide> describe('ReactElementValidator', () => { <ide> expect(() => { <ide> ReactTestUtils.renderIntoDocument(<Anonymous>{divs}</Anonymous>); <ide> }).toWarnDev( <del> 'Warning: Each child in an array or iterator should have a unique ' + <add> 'Warning: Each child in a list should have a unique ' + <ide> '"key" prop. See https://fb.me/react-warning-keys for more information.\n' + <ide> ' in div (at **)', <ide> ); <ide> describe('ReactElementValidator', () => { <ide> expect(() => { <ide> ReactTestUtils.renderIntoDocument(<div>{divs}</div>); <ide> }).toWarnDev( <del> 'Warning: Each child in an array or iterator should have a unique ' + <add> 'Warning: Each child in a list should have a unique ' + <ide> '"key" prop.\n\nCheck the top-level render call using <div>. See ' + <ide> 'https://fb.me/react-warning-keys for more information.\n' + <ide> ' in div (at **)', <ide> describe('ReactElementValidator', () => { <ide> } <ide> <ide> expect(() => ReactTestUtils.renderIntoDocument(<GrandParent />)).toWarnDev( <del> 'Warning: Each child in an array or iterator should have a unique ' + <add> 'Warning: Each child in a list should have a unique ' + <ide> '"key" prop.\n\nCheck the render method of `Component`. See ' + <ide> 'https://fb.me/react-warning-keys for more information.\n' + <ide> ' in div (at **)\n' + <ide> describe('ReactElementValidator', () => { <ide> }; <ide> <ide> expect(() => Component(null, iterable)).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.', <add> 'Each child in a list should have a unique "key" prop.', <ide> ); <ide> }); <ide> <ide><path>packages/react/src/__tests__/ReactJSXElementValidator-test.js <ide> describe('ReactJSXElementValidator', () => { <ide> ReactTestUtils.renderIntoDocument( <ide> <Component>{[<Component />, <Component />]}</Component>, <ide> ), <del> ).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.', <del> ); <add> ).toWarnDev('Each child in a list should have a unique "key" prop.'); <ide> }); <ide> <ide> it('warns for keys for arrays of elements with owner info', () => { <ide> describe('ReactJSXElementValidator', () => { <ide> expect(() => <ide> ReactTestUtils.renderIntoDocument(<ComponentWrapper />), <ide> ).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.' + <add> 'Each child in a list should have a unique "key" prop.' + <ide> '\n\nCheck the render method of `InnerComponent`. ' + <ide> 'It was passed a child from ComponentWrapper. ', <ide> ); <ide> describe('ReactJSXElementValidator', () => { <ide> <ide> expect(() => <ide> ReactTestUtils.renderIntoDocument(<Component>{iterable}</Component>), <del> ).toWarnDev( <del> 'Each child in an array or iterator should have a unique "key" prop.', <del> ); <add> ).toWarnDev('Each child in a list should have a unique "key" prop.'); <ide> }); <ide> <ide> it('does not warn for arrays of elements with keys', () => {
9
Javascript
Javascript
check input and textarea proptypes only in dev
65370ff7520c6daddd729710697873291662dee4
<ide><path>src/renderers/dom/client/wrappers/ReactDOMInput.js <ide> var ReactDOMInput = { <ide> }, <ide> <ide> mountWrapper: function(inst, props) { <del> LinkedValueUtils.checkPropTypes( <del> 'input', <del> props, <del> inst._currentElement._owner <del> ); <add> if (__DEV__) { <add> LinkedValueUtils.checkPropTypes( <add> 'input', <add> props, <add> inst._currentElement._owner <add> ); <add> } <ide> <ide> var defaultValue = props.defaultValue; <ide> inst._wrapperState = { <ide><path>src/renderers/dom/client/wrappers/ReactDOMTextarea.js <ide> var ReactDOMTextarea = { <ide> }, <ide> <ide> mountWrapper: function(inst, props) { <del> LinkedValueUtils.checkPropTypes( <del> 'textarea', <del> props, <del> inst._currentElement._owner <del> ); <add> if (__DEV__) { <add> LinkedValueUtils.checkPropTypes( <add> 'textarea', <add> props, <add> inst._currentElement._owner <add> ); <add> } <ide> <ide> var defaultValue = props.defaultValue; <ide> // TODO (yungsters): Remove support for children content in <textarea>.
2
Javascript
Javascript
change controlleralias to controlleras
400f9360bb2f7553c5bd3b1f256a5f3db175b7bc
<ide><path>src/ng/directive/ngView.js <ide> $routeProvider.when('/Book/:bookId', { <ide> templateUrl: 'book.html', <ide> controller: BookCntl, <del> controllerAlias: 'book' <add> controllerAs: 'book' <ide> }); <ide> $routeProvider.when('/Book/:bookId/ch/:chapterId', { <ide> templateUrl: 'chapter.html', <ide> controller: ChapterCntl, <del> controllerAlias: 'chapter' <add> controllerAs: 'chapter' <ide> }); <ide> <ide> // configure html5 to get links working on jsfiddle <ide> var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$c <ide> if (current.controller) { <ide> locals.$scope = lastScope; <ide> controller = $controller(current.controller, locals); <del> if (current.controllerAlias) { <del> lastScope[current.controllerAlias] = controller; <add> if (current.controllerAs) { <add> lastScope[current.controllerAs] = controller; <ide> } <ide> element.children().data('$ngControllerController', controller); <ide> } <ide><path>src/ng/route.js <ide> function $RouteProvider(){ <ide> * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly <ide> * created scope or the name of a {@link angular.Module#controller registered controller} <ide> * if passed as a string. <del> * - `controllerAlias` – `{string=}` – A controller alias name. If present the controller will be <del> * published to scope under the `controllerAlias` name. <add> * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be <add> * published to scope under the `controllerAs` name. <ide> * - `template` – `{string=|function()=}` – html template as a string or function that returns <ide> * an html template as a string which should be used by {@link ng.directive:ngView ngView} or <ide> * {@link ng.directive:ngInclude ngInclude} directives. <ide><path>test/ng/directive/ngViewSpec.js <ide> describe('ngView', function() { <ide> }; <ide> <ide> module(function($compileProvider, $routeProvider) { <del> $routeProvider.when('/some', {templateUrl: '/tpl.html', controller: Ctrl, controllerAlias: 'ctrl'}); <add> $routeProvider.when('/some', {templateUrl: '/tpl.html', controller: Ctrl, controllerAs: 'ctrl'}); <ide> }); <ide> <ide> inject(function($route, $rootScope, $templateCache, $location) {
3
Java
Java
improve tests for synthesized array of annotations
a9cc7b3edc59d5855dad75ffbf22bb5604162968
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java <ide> void synthesizeNonPublicWithAttributeAliasesFromDifferentPackage() throws Except <ide> } <ide> <ide> @Test <del> void synthesizeWithAttributeAliasesInNestedAnnotations() throws Exception { <add> void synthesizeWithArrayOfAnnotations() throws Exception { <ide> Hierarchy hierarchy = HierarchyClass.class.getAnnotation(Hierarchy.class); <ide> assertThat(hierarchy).isNotNull(); <ide> Hierarchy synthesizedHierarchy = MergedAnnotation.from(hierarchy).synthesize(); <ide> assertThat(synthesizedHierarchy).isInstanceOf(SynthesizedAnnotation.class); <ide> TestConfiguration[] configs = synthesizedHierarchy.value(); <ide> assertThat(configs).isNotNull(); <ide> assertThat(configs).allMatch(SynthesizedAnnotation.class::isInstance); <del> assertThat( <del> Arrays.stream(configs).map(TestConfiguration::location)).containsExactly( <del> "A", "B"); <del> assertThat(Arrays.stream(configs).map(TestConfiguration::value)).containsExactly( <del> "A", "B"); <del> } <add> assertThat(configs).extracting(TestConfiguration::value).containsExactly("A", "B"); <add> assertThat(configs).extracting(TestConfiguration::location).containsExactly("A", "B"); <ide> <del> @Test <del> void synthesizeWithArrayOfAnnotations() throws Exception { <del> Hierarchy hierarchy = HierarchyClass.class.getAnnotation(Hierarchy.class); <del> assertThat(hierarchy).isNotNull(); <del> Hierarchy synthesizedHierarchy = MergedAnnotation.from(hierarchy).synthesize(); <del> assertThat(synthesizedHierarchy).isInstanceOf(SynthesizedAnnotation.class); <del> TestConfiguration contextConfig = TestConfigurationClass.class.getAnnotation( <del> TestConfiguration.class); <add> TestConfiguration contextConfig = TestConfigurationClass.class.getAnnotation(TestConfiguration.class); <ide> assertThat(contextConfig).isNotNull(); <del> TestConfiguration[] configs = synthesizedHierarchy.value(); <del> assertThat( <del> Arrays.stream(configs).map(TestConfiguration::location)).containsExactly( <del> "A", "B"); <ide> // Alter array returned from synthesized annotation <ide> configs[0] = contextConfig; <add> assertThat(configs).extracting(TestConfiguration::value).containsExactly("simple.xml", "B"); <ide> // Re-retrieve the array from the synthesized annotation <ide> configs = synthesizedHierarchy.value(); <del> assertThat( <del> Arrays.stream(configs).map(TestConfiguration::location)).containsExactly( <del> "A", "B"); <add> assertThat(configs).extracting(TestConfiguration::value).containsExactly("A", "B"); <ide> } <ide> <ide> @Test
1
Text
Text
relax type of constant names [ci skip]
fdbeda449e3f20fa5e341f452adc99c70d319aec
<ide><path>guides/source/constant_autoloading_and_reloading.md <ide> end <ide> <ide> First, when the `module` keyword is processed the interpreter creates a new <ide> entry in the constant table of the class object stored in the `Object` constant. <del>Said entry associates the string "Colors" to a newly created module object. <add>Said entry associates the name "Colors" to a newly created module object. <ide> Furthermore, the interpreter sets the name of the new module object to be the <ide> string "Colors". <ide> <ide> Later, when the body of the module definition is interpreted, a new entry is <ide> created in the constant table of the module object stored in the `Colors` <del>constant. That entry maps the string "RED" to the string "0xff0000". <add>constant. That entry maps the name "RED" to the string "0xff0000". <ide> <ide> In particular, `Colors::RED` is totally unrelated to any other `RED` constant <ide> that may live in any other class or module object. If there were any, they <ide> would have separate entries in their respective constant tables. <ide> <ide> Put special attention in the previous paragraphs to the distinction between <del>class and module objects, constant names as strings, and value objects <del>assiociated to them in constant tables. <add>class and module objects, constant names, and value objects assiociated to them <add>in constant tables. <ide> <ide> <ide> autoload_paths
1
PHP
PHP
rename the merge method to collapse
aa58b089b986904cfda8928a1de2da9a371768a0
<ide><path>src/Illuminate/Support/Collection.php <ide> public function flatten() <ide> } <ide> <ide> /** <del> * Merge the collection itmes into a single array. <add> * Collapse the collection items into a single array. <ide> * <ide> * @return \Illuminate\Support\Collection <ide> */ <del> public function merge() <add> public function collapse() <ide> { <ide> $results = array(); <ide> <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testFlatten() <ide> } <ide> <ide> <del> public function testMerge() <add> public function testCollapse() <ide> { <ide> $data = new Collection(array(array($object1 = new StdClass), array($object2 = new StdClass))); <del> $this->assertEquals(array($object1, $object2), $data->merge()->all()); <add> $this->assertEquals(array($object1, $object2), $data->collapse()->all()); <ide> } <ide> <ide>
2
Text
Text
fix typo in docker toolbox upgrade section
1435c9ea21d6c76a923c2501abb840e899b5ed1e
<ide><path>docs/installation/mac.md <ide> The next exercise demonstrates how to do this. <ide> <ide> ## Upgrade Docker Toolbox <ide> <del>To upgrade Docker Toolbox, download an re-run [the Docker Toolbox <add>To upgrade Docker Toolbox, download and re-run [the Docker Toolbox <ide> installer](https://docker.com/toolbox/). <ide> <ide> <ide><path>docs/installation/windows.md <ide> and what it does: <ide> <ide> ## Upgrade Docker Toolbox <ide> <del>To upgrade Docker Toolbox, download an re-run [the Docker Toolbox <add>To upgrade Docker Toolbox, download and re-run [the Docker Toolbox <ide> installer](https://www.docker.com/toolbox). <ide> <ide> ## Container port redirection
2
PHP
PHP
remove dead code
fcca1e8abc02883221870e1c81cecc3c843e0f7c
<ide><path>src/Controller/Component/PaginatorComponent.php <ide> public function implementedEvents() <ide> */ <ide> public function paginate($object, array $settings = []) <ide> { <del> $query = null; <del> if ($object instanceof QueryInterface) { <del> $query = $object; <del> } <del> <ide> $request = $this->_registry->getController()->request; <ide> <ide> try {
1
Javascript
Javascript
remove extraneous assignments in rmdir()
91e0d9bc30948dc58f8675a10a85843e0de65650
<ide><path>lib/fs.js <ide> function rmdir(path, options, callback) { <ide> path = pathModule.toNamespacedPath(getValidatedPath(path)); <ide> <ide> if (options && options.recursive) { <del> options = validateRmOptions( <del> path, <del> { ...options, force: true }, <del> (err, options) => { <del> if (err) { <del> return callback(err); <del> } <del> <del> lazyLoadRimraf(); <del> return rimraf(path, options, callback); <del> }); <add> validateRmOptions(path, { ...options, force: true }, (err, options) => { <add> if (err) { <add> return callback(err); <add> } <ide> <add> lazyLoadRimraf(); <add> return rimraf(path, options, callback); <add> }); <ide> } else { <del> options = validateRmdirOptions(options); <add> validateRmdirOptions(options); <ide> const req = new FSReqCallback(); <ide> req.oncomplete = callback; <ide> return binding.rmdir(path, req);
1
Ruby
Ruby
remove active_support/json/variable was deprecated
6f3e01e8b78eff1b1685a0b35d70819376bfd773
<ide><path>activesupport/lib/active_support/json/encoding.rb <ide> <ide> require 'active_support/core_ext/object/to_json' <ide> require 'active_support/core_ext/module/delegation' <del>require 'active_support/json/variable' <ide> <ide> require 'bigdecimal' <ide> require 'active_support/core_ext/big_decimal/conversions' # for #to_s <ide><path>activesupport/lib/active_support/json/variable.rb <del>require 'active_support/deprecation' <del> <del>module ActiveSupport <del> module JSON <del> # Deprecated: A string that returns itself as its JSON-encoded form. <del> class Variable < String <del> def initialize(*args) <del> message = 'ActiveSupport::JSON::Variable is deprecated and will be removed in Rails 4.1. ' \ <del> 'For your own custom JSON literals, define #as_json and #encode_json yourself.' <del> ActiveSupport::Deprecation.warn message <del> super <del> end <del> <del> def as_json(options = nil) self end #:nodoc: <del> def encode_json(encoder) self end #:nodoc: <del> end <del> end <del>end <ide><path>activesupport/test/json/encoding_test.rb <ide> def sorted_json(json) <ide> end <ide> end <ide> <del> def test_json_variable <del> assert_deprecated do <del> assert_equal ActiveSupport::JSON::Variable.new('foo'), 'foo' <del> assert_equal ActiveSupport::JSON::Variable.new('alert("foo")'), 'alert("foo")' <del> end <del> end <del> <ide> def test_hash_encoding <ide> assert_equal %({\"a\":\"b\"}), ActiveSupport::JSON.encode(:a => :b) <ide> assert_equal %({\"a\":1}), ActiveSupport::JSON.encode('a' => 1)
3
PHP
PHP
remove invalid void
d1ef8a82e5a7e8fa789fef0afe2ac8248e9b900c
<ide><path>src/Auth/FallbackPasswordHasher.php <ide> class FallbackPasswordHasher extends AbstractPasswordHasher <ide> * <ide> * @param array $config configuration options for this object. Requires the <ide> * `hashers` key to be present in the array with a list of other hashers to be <del> * used <del> * @return void <add> * used. <ide> */ <ide> public function __construct(array $config = []) <ide> {
1
Text
Text
extend example contribution guidelines
08e69cfdbb9faa7144f959518aa31e5ab864a019
<ide><path>contributing.md <ide> Below are the steps to add a new link: <ide> <ide> When you add an example to the [examples](examples) directory, please follow these guidelines to ensure high quality examples: <ide> <del>- TypeScript should be leveraged for new examples (no need for separate JavaScript and TypeScript examples) <add>- TypeScript should be leveraged for new examples (no need for separate JavaScript and TypeScript examples, converting old JavaScript examples is preferred) <ide> - Examples should not add custom ESLint configuration (we have specific templates for ESLint) <ide> - If API routes aren't used in an example, they should be omitted <ide> - If an example exists for a certain library and you would like to showcase a specific feature of that library, the existing example should be updated (instead of adding a new example) <ide> - Package manager specific config should not be added (e.g. `resolutions` in `package.json`) <ide> - In `package.json` the version of `next` (and `eslint-config-next`) should be `latest` <ide> - In `package.json` the dependency versions should be up-to-date <add>- Use `export default function` for page components and API Routes instead of `const`/`let` (The exception is if the page has `getInitialProps`, in which case [`NextPage`](https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#typescript) could be useful) <add>- CMS example directories should be prefixed with `cms-` <add>- Example directories should not be prefixed with `with-` <add>- Make sure linting passes (you can run `pnpm lint-fix`) <ide> <ide> Also don’t forget to add a `README.md` file with the following format: <ide>
1
Text
Text
document the removal of deprecated properties
3a25fe29213cbe3f386988609699aab703f856cb
<ide><path>docs/docs/getting-started/v3-migration.md <ide> The following properties and methods were removed: <ide> #### Chart <ide> * `Chart.borderWidth` <ide> * `Chart.chart.chart` <add>* `Chart.Bar`. New charts are created via `new Chart` and providing the appropriate `type` parameter <add>* `Chart.Bubble`. New charts are created via `new Chart` and providing the appropriate `type` parameter <add>* `Chart.Chart` <ide> * `Chart.Controller` <add>* `Chart.Doughnut`. New charts are created via `new Chart` and providing the appropriate `type` parameter <ide> * `Chart.innerRadius` now lives on doughnut, pie, and polarArea controllers <add>* `Chart.Legend` was moved to `Chart.plugins.legend._element` and made private <add>* `Chart.Line`. New charts are created via `new Chart` and providing the appropriate `type` parameter <add>* `Chart.LinearScaleBase` now must be imported and cannot be accessed off the `Chart` object <ide> * `Chart.offsetX` <ide> * `Chart.offsetY` <ide> * `Chart.outerRadius` now lives on doughnut, pie, and polarArea controllers <add>* `Chart.PolarArea`. New charts are created via `new Chart` and providing the appropriate `type` parameter <ide> * `Chart.prototype.generateLegend` <ide> * `Chart.platform`. It only contained `disableCSSInjection`. CSS is never injected in v3. <add>* `Chart.PluginBase` <add>* `Chart.Radar`. New charts are created via `new Chart` and providing the appropriate `type` parameter <ide> * `Chart.radiusLength` <add>* `Chart.Scatter`. New charts are created via `new Chart` and providing the appropriate `type` parameter <ide> * `Chart.types` <add>* `Chart.Title` was moved to `Chart.plugins.title._element` and made private <ide> * `Chart.Tooltip` is now provided by the tooltip plugin. The positioners can be accessed from `tooltipPlugin.positioners` <ide> * `ILayoutItem.minSize` <ide> <ide> The following properties were renamed during v3 development: <ide> <ide> * `Chart.Animation.animationObject` was renamed to `Chart.Animation` <ide> * `Chart.Animation.chartInstance` was renamed to `Chart.Animation.chart` <add>* `Chart.canvasHelpers` was renamed to `Chart.helpers.canvas` <add>* `Chart.layoutService` was renamed to `Chart.layouts` <add>* `Chart.pluginService` was renamed to `Chart.plugins` <ide> * `helpers._decimalPlaces` was renamed to `helpers.math._decimalPlaces` <ide> * `helpers.almostEquals` was renamed to `helpers.math.almostEquals` <ide> * `helpers.almostWhole` was renamed to `helpers.math.almostWhole`
1
Javascript
Javascript
extract emitmixedtypeannotation to parsers-commons
b87d371a3838f7068718fc0e5a1a86afb1dd6c9d
<ide><path>packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js <ide> import {IncorrectlyParameterizedGenericParserError} from '../errors'; <ide> import {assertGenericTypeAnnotationHasExactlyOneTypeParameter} from '../parsers-commons'; <ide> <del>const {wrapNullable, unwrapNullable} = require('../parsers-commons.js'); <add>const { <add> wrapNullable, <add> unwrapNullable, <add> emitMixedTypeAnnotation, <add>} = require('../parsers-commons.js'); <ide> <ide> describe('wrapNullable', () => { <ide> describe('when nullable is true', () => { <ide> describe('assertGenericTypeAnnotationHasExactlyOneTypeParameter', () => { <ide> ).toThrow(IncorrectlyParameterizedGenericParserError); <ide> }); <ide> }); <add> <add>describe('emitMixedTypeAnnotation', () => { <add> describe('when nullable is true', () => { <add> it('returns nullable type annotation', () => { <add> const result = emitMixedTypeAnnotation(true); <add> const expected = { <add> type: 'NullableTypeAnnotation', <add> typeAnnotation: { <add> type: 'MixedTypeAnnotation', <add> }, <add> }; <add> <add> expect(result).toEqual(expected); <add> }); <add> }); <add> describe('when nullable is false', () => { <add> it('returns non nullable type annotation', () => { <add> const result = emitMixedTypeAnnotation(false); <add> const expected = { <add> type: 'MixedTypeAnnotation', <add> }; <add> <add> expect(result).toEqual(expected); <add> }); <add> }); <add>}); <ide><path>packages/react-native-codegen/src/parsers/flow/modules/index.js <ide> const { <ide> unwrapNullable, <ide> wrapNullable, <ide> assertGenericTypeAnnotationHasExactlyOneTypeParameter, <add> emitMixedTypeAnnotation, <ide> } = require('../../parsers-commons'); <ide> const { <ide> emitBoolean, <ide> function translateTypeAnnotation( <ide> } <ide> case 'MixedTypeAnnotation': { <ide> if (cxxOnly) { <del> return wrapNullable(nullable, { <del> type: 'MixedTypeAnnotation', <del> }); <add> return emitMixedTypeAnnotation(nullable); <ide> } <ide> // Fallthrough <ide> } <ide><path>packages/react-native-codegen/src/parsers/parsers-commons.js <ide> import type { <ide> NativeModuleSchema, <ide> NativeModuleTypeAnnotation, <ide> Nullable, <add> NativeModuleMixedTypeAnnotation, <ide> } from '../CodegenSchema.js'; <ide> const {IncorrectlyParameterizedGenericParserError} = require('./errors'); <ide> import type {ParserType} from './errors'; <ide> function assertGenericTypeAnnotationHasExactlyOneTypeParameter( <ide> } <ide> } <ide> <add>function emitMixedTypeAnnotation( <add> nullable: boolean, <add>): Nullable<NativeModuleMixedTypeAnnotation> { <add> return wrapNullable(nullable, { <add> type: 'MixedTypeAnnotation', <add> }); <add>} <add> <ide> module.exports = { <ide> wrapModuleSchema, <ide> unwrapNullable, <ide> wrapNullable, <ide> assertGenericTypeAnnotationHasExactlyOneTypeParameter, <add> emitMixedTypeAnnotation, <ide> }; <ide><path>packages/react-native-codegen/src/parsers/typescript/modules/index.js <ide> const { <ide> unwrapNullable, <ide> wrapNullable, <ide> assertGenericTypeAnnotationHasExactlyOneTypeParameter, <add> emitMixedTypeAnnotation, <ide> } = require('../../parsers-commons'); <ide> const { <ide> emitBoolean, <ide> function translateTypeAnnotation( <ide> } <ide> case 'TSUnknownKeyword': { <ide> if (cxxOnly) { <del> return wrapNullable(nullable, { <del> type: 'MixedTypeAnnotation', <del> }); <add> return emitMixedTypeAnnotation(nullable); <ide> } <ide> // Fallthrough <ide> }
4
Python
Python
use dtype in numeric.indices
0a7f9f5f8bffdcbb4ba94c98d722056b1e6bb133
<ide><path>numpy/core/numeric.py <ide> def indices(dimensions, dtype=int): <ide> tmp = ones(dimensions, dtype) <ide> lst = [] <ide> for i in range(len(dimensions)): <del> lst.append( add.accumulate(tmp, i, )-1 ) <del> return array(lst, dtype) <add> lst.append( add.accumulate(tmp, i, dtype)-1 ) <add> return array(lst) <ide> <ide> def fromfunction(function, dimensions, **kwargs): <ide> """fromfunction(function, dimensions) returns an array constructed by
1
PHP
PHP
remove `static` return types
ecec6ca33280f3d9e93e294824cf5bd04424c255
<ide><path>src/Illuminate/Database/Eloquent/SoftDeletes.php <ide> namespace Illuminate\Database\Eloquent; <ide> <ide> /** <del> * @method static static|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder withTrashed(bool $withTrashed = true) <del> * @method static static|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder onlyTrashed() <del> * @method static static|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder withoutTrashed() <add> * @method static \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder withTrashed(bool $withTrashed = true) <add> * @method static \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder onlyTrashed() <add> * @method static \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder withoutTrashed() <ide> */ <ide> trait SoftDeletes <ide> {
1
Python
Python
fix checkpoint for vit config
f4b7420dfe419fe653908f091976517635a119e6
<ide><path>src/transformers/models/vit/configuration_vit.py <ide> logger = logging.get_logger(__name__) <ide> <ide> VIT_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "nielsr/vit-base-patch16-224": "https://huggingface.co/vit-base-patch16-224/resolve/main/config.json", <add> "google/vit-base-patch16-224": "https://huggingface.co/vit-base-patch16-224/resolve/main/config.json", <ide> # See all ViT models at https://huggingface.co/models?filter=vit <ide> } <ide>
1
Text
Text
release notes for 3.1.3
bc778732bf956966b28dc3e6a425bf29eb9a23de
<ide><path>docs/topics/release-notes.md <ide> You can determine your currently installed version using `pip freeze`: <ide> <ide> ## 3.1.x series <ide> <add>### 3.1.3 <add> <add>**Date**: [4th June 2015][3.1.3-milestone]. <add> <add>* Add `DurationField`. ([#2481][gh2481], [#2989][gh2989]) <add>* Add `format` argument to `UUIDField`. ([#2788][gh2788], [#3000][gh3000]) <add>* `MultipleChoiceField` empties incorrectly on a partial update using multipart/form-data ([#2993][gh2993], [#2894][gh2894]) <add>* Fix a bug in options related to read-only `RelatedField`. ([#2981][gh2981], [#2811][gh2811]) <add>* Fix nested serializers with `unique_together` relations. ([#2975][gh2975]) <add>* Allow unexpected values for `ChoiceField`/`MultipleChoiceField` representations. ([#2839][gh2839], [#2940][gh2940]) <add>* Rollback the transaction on error if `ATOMIC_REQUESTS` is set. ([#2887][gh2887], [#2034][gh2034]) <add>* Set the action on a view when override_method regardless of its None-ness. ([#2933][gh2933]) <add>* `DecimalField` accepts `2E+2` as 200 and validates decimal place correctly. ([#2948][gh2948], [#2947][gh2947]) <add>* Support basic authentication with custom `UserModel` that change `username`. ([#2952][gh2952]) <add>* `IPAddressField` improvements. ([#2747][gh2747]) <add> <add> <ide> ### 3.1.2 <ide> <ide> **Date**: [13rd May 2015][3.1.2-milestone]. <ide> For older release notes, [please see the version 2.x documentation][old-release- <ide> [3.1.0-milestone]: https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.1.0+Release%22 <ide> [3.1.1-milestone]: https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.1.1+Release%22 <ide> [3.1.2-milestone]: https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.1.2+Release%22 <add>[3.1.3-milestone]: https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.1.3+Release%22 <ide> <ide> <!-- 3.0.1 --> <ide> [gh2013]: https://github.com/tomchristie/django-rest-framework/issues/2013 <ide> For older release notes, [please see the version 2.x documentation][old-release- <ide> [gh2863]: https://github.com/tomchristie/django-rest-framework/issues/2863 <ide> [gh2868]: https://github.com/tomchristie/django-rest-framework/issues/2868 <ide> [gh2905]: https://github.com/tomchristie/django-rest-framework/issues/2905 <add><!-- 3.1.3 --> <add>[gh2481]: https://github.com/tomchristie/django-rest-framework/issues/2481 <add>[gh2989]: https://github.com/tomchristie/django-rest-framework/issues/2989 <add>[gh2788]: https://github.com/tomchristie/django-rest-framework/issues/2788 <add>[gh3000]: https://github.com/tomchristie/django-rest-framework/issues/3000 <add>[gh2993]: https://github.com/tomchristie/django-rest-framework/issues/2993 <add>[gh2894]: https://github.com/tomchristie/django-rest-framework/issues/2894 <add>[gh2981]: https://github.com/tomchristie/django-rest-framework/issues/2981 <add>[gh2811]: https://github.com/tomchristie/django-rest-framework/issues/2811 <add>[gh2975]: https://github.com/tomchristie/django-rest-framework/issues/2975 <add>[gh2839]: https://github.com/tomchristie/django-rest-framework/issues/2839 <add>[gh2940]: https://github.com/tomchristie/django-rest-framework/issues/2940 <add>[gh2887]: https://github.com/tomchristie/django-rest-framework/issues/2887 <add>[gh2034]: https://github.com/tomchristie/django-rest-framework/issues/2034 <add>[gh2933]: https://github.com/tomchristie/django-rest-framework/issues/2933 <add>[gh2948]: https://github.com/tomchristie/django-rest-framework/issues/2948 <add>[gh2947]: https://github.com/tomchristie/django-rest-framework/issues/2947 <add>[gh2952]: https://github.com/tomchristie/django-rest-framework/issues/2952 <add>[gh2747]: https://github.com/tomchristie/django-rest-framework/issues/2747
1
PHP
PHP
add a test for
acc11336a3292d64f36c43a581c1a04c0d9ccf1f
<ide><path>tests/TestCase/Routing/Route/RedirectRouteTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Routing\Route; <ide> <add>use Cake\Http\ServerRequest; <ide> use Cake\Routing\Router; <ide> use Cake\Routing\Route\RedirectRoute; <ide> use Cake\TestSuite\TestCase; <ide> public function testParsePersist() <ide> $route->parse('/posts/2'); <ide> } <ide> <add> /** <add> * test redirecting with persist and a base directory <add> * <add> * @return void <add> */ <add> public function testParsePersistBaseDirectory() <add> { <add> $request = new ServerRequest([ <add> 'base' => '/basedir', <add> 'url' => '/posts/2' <add> ]); <add> Router::pushRequest($request); <add> <add> $this->expectException(\Cake\Routing\Exception\RedirectException::class); <add> $this->expectExceptionMessage('http://localhost/basedir/posts/view/2'); <add> $this->expectExceptionCode(301); <add> $route = new RedirectRoute('/posts/*', ['controller' => 'posts', 'action' => 'view'], ['persist' => true]); <add> $route->parse('/posts/2'); <add> } <add> <ide> /** <ide> * test redirecting with persist and string target URLs <ide> *
1
Javascript
Javascript
fix 95% of windowedlistview jumpiness
5e91a2a3124a76e5216975497e63c04e012aa0d1
<ide><path>Libraries/Experimental/IncrementalGroup.js <ide> const Incremental = require('Incremental'); <ide> const React = require('React'); <ide> <add>const infoLog = require('infoLog'); <add> <ide> let _groupCounter = -1; <ide> const DEBUG = false; <ide> <ide> import type {Props, Context} from 'Incremental'; <ide> * See Incremental.js for more info. <ide> */ <ide> class IncrementalGroup extends React.Component { <del> props: Props; <add> props: Props & {disabled?: boolean}; <ide> context: Context; <ide> _groupInc: string; <ide> componentWillMount() { <ide> this._groupInc = `g${++_groupCounter}-`; <del> DEBUG && console.log( <add> DEBUG && infoLog( <ide> 'create IncrementalGroup with id ' + this.getGroupId() <ide> ); <ide> } <ide><path>Libraries/Experimental/ViewabilityHelper.js <ide> const ViewabilityHelper = { <ide> computeViewableRows( <ide> viewablePercentThreshold: number, <del> rowFrames: Array<Object>, <add> rowFrames: {[key: string]: Object}, <add> data: Array<{rowKey: string, rowData: any}>, <ide> scrollOffsetY: number, <ide> viewportHeight: number <ide> ): Array<number> { <del> var viewableRows = []; <del> var firstVisible = -1; <del> for (var idx = 0; idx < rowFrames.length; idx++) { <del> var frame = rowFrames[idx]; <add> const viewableRows = []; <add> let firstVisible = -1; <add> for (let idx = 0; idx < data.length; idx++) { <add> const frame = rowFrames[data[idx].rowKey]; <ide> if (!frame) { <ide> continue; <ide> } <del> var top = frame.y - scrollOffsetY; <del> var bottom = top + frame.height; <add> const top = frame.y - scrollOffsetY; <add> const bottom = top + frame.height; <ide> if ((top < viewportHeight) && (bottom > 0)) { <ide> firstVisible = idx; <ide> if (_isViewable( <ide> function _getPercentOccupied( <ide> bottom: number, <ide> viewportHeight: number <ide> ): number { <del> var visibleHeight = Math.min(bottom, viewportHeight) - Math.max(top, 0); <add> let visibleHeight = Math.min(bottom, viewportHeight) - Math.max(top, 0); <ide> visibleHeight = Math.max(0, visibleHeight); <ide> return Math.max(0, visibleHeight * 100 / viewportHeight); <ide> } <ide><path>Libraries/Experimental/WindowedListView.js <ide> type Props = { <ide> * A simple array of data blobs that are passed to the renderRow function in <ide> * order. Note there is no dataSource like in the standard `ListView`. <ide> */ <del> data: Array<any>; <add> data: Array<{rowKey: string, rowData: any}>; <ide> /** <ide> * Takes a data blob from the `data` array prop plus some meta info and should <ide> * return a row. <ide> */ <ide> renderRow: ( <del> data: any, sectionIdx: number, rowIdx: number, key?: string <add> rowData: any, sectionIdx: number, rowIdx: number, rowKey: string <ide> ) => ?ReactElement; <ide> /** <ide> * Rendered when the list is scrolled faster than rows can be rendered. <ide> type Props = { <ide> * determine how many rows to render above the viewport. <ide> */ <ide> numToRenderAhead: number; <del> /** <del> * Super dangerous and experimental - rows and all their decendents must be <del> * fully stateless otherwise recycling their instances may introduce nasty <del> * bugs. Some apps may see an improvement in perf, but sometimes perf and <del> * memory usage can actually get worse with this. <del> */ <del> enableDangerousRecycling: boolean; <ide> /** <ide> * Used to log perf events for async row rendering. <ide> */ <ide> class WindowedListView extends React.Component { <ide> _scrollOffsetY: number = 0; <ide> _isScrolling: boolean = false; <ide> _frameHeight: number = 0; <del> _rowFrames: Array<Object> = []; <add> _rowFrames: {[key: string]: Object} = {}; <add> _rowRenderMode: {[key: string]: null | 'async' | 'sync'} = {}; <ide> _rowFramesDirty: boolean = false; <ide> _hasCalledOnEndReached: boolean = false; <ide> _willComputeRowsToRender: boolean = false; <ide> _timeoutHandle: number = 0; <ide> _incrementPending: boolean = false; <ide> _viewableRows: Array<number> = []; <del> _cellsInProgress: Set<number> = new Set(); <add> _cellsInProgress: Set<string> = new Set(); <ide> _scrollRef: ?Object; <ide> <ide> static defaultProps = { <del> enableDangerousRecycling: false, <ide> initialNumToRender: 10, <ide> maxNumToRender: 30, <ide> numToRenderAhead: 10, <ide> class WindowedListView extends React.Component { <ide> componentWillReceiveProps(newProps: Object) { <ide> // This has to happen immediately otherwise we could crash, e.g. if the data <ide> // array has gotten shorter. <del> if (newProps.data.length < this._rowFrames.length) { <del> this._rowFrames = this._rowFrames.splice(0, newProps.data.length); <del> } <ide> this._computeRowsToRender(newProps); <ide> } <ide> _onMomentumScrollEnd = (e: Object) => { <ide> class WindowedListView extends React.Component { <ide> if (this._cellsInProgress.size === 0) { <ide> this._enqueueComputeRowsToRender(); <ide> } <del> if (this.props.onViewableRowsChanged && this._rowFrames.length) { <add> if (this.props.onViewableRowsChanged && Object.keys(this._rowFrames).length) { <ide> const viewableRows = ViewabilityHelper.computeViewableRows( <ide> this.props.viewablePercentThreshold, <ide> this._rowFrames, <add> this.props.data, <ide> e.nativeEvent.contentOffset.y, <ide> e.nativeEvent.layoutMeasurement.height <ide> ); <ide> class WindowedListView extends React.Component { <ide> this.props.onScroll && this.props.onScroll(e); <ide> }; <ide> // Caller does the diffing so we don't have to. <del> _onNewLayout = (params: {rowIndex: number, layout: Object}) => { <del> const {rowIndex, layout} = params; <add> _onNewLayout = (params: {rowKey: string, layout: Object}) => { <add> const {rowKey, layout} = params; <ide> if (DEBUG) { <del> const layoutPrev = this._rowFrames[rowIndex] || {}; <add> const layoutPrev = this._rowFrames[rowKey] || {}; <ide> infoLog( <ide> 'record layout for row: ', <del> {i: rowIndex, h: layout.height, y: layout.y, x: layout.x, hp: layoutPrev.height, yp: layoutPrev.y} <add> {k: rowKey, h: layout.height, y: layout.y, x: layout.x, hp: layoutPrev.height, yp: layoutPrev.y} <ide> ); <ide> } <del> this._rowFrames[rowIndex] = {...layout, offscreenLayoutDone: true}; <add> if (this._rowFrames[rowKey]) { <add> const deltaY = Math.abs(this._rowFrames[rowKey].y - layout.y); <add> const deltaH = Math.abs(this._rowFrames[rowKey].height - layout.height); <add> if (deltaY > 2 || deltaH > 2) { <add> const dataEntry = this.props.data.find((datum) => datum.rowKey === rowKey); <add> console.warn('layout jump: ', {dataEntry, prevLayout: this._rowFrames[rowKey], newLayout: layout}); <add> } <add> } <add> this._rowFrames[rowKey] = {...layout, offscreenLayoutDone: true}; <ide> this._rowFramesDirty = true; <ide> if (this._cellsInProgress.size === 0) { <ide> this._enqueueComputeRowsToRender(); <ide> } <ide> }; <del> _onWillUnmountCell = (rowIndex: number) => { <del> if (this._rowFrames[rowIndex]) { <del> this._rowFrames[rowIndex].offscreenLayoutDone = false; <add> _onWillUnmountCell = (rowKey: string) => { <add> if (this._rowFrames[rowKey]) { <add> this._rowFrames[rowKey].offscreenLayoutDone = false; <add> this._rowRenderMode[rowKey] = null; <ide> } <ide> }; <ide> /** <ide> * This is used to keep track of cells that are in the process of rendering. If any cells are in progress, then <ide> * other updates are skipped because they will just be wasted work. <ide> */ <del> _onProgressChange = ({rowIndex, inProgress}: {rowIndex: number, inProgress: boolean}) => { <add> _onProgressChange = ({rowKey, inProgress}: {rowKey: string, inProgress: boolean}) => { <ide> if (inProgress) { <del> this._cellsInProgress.add(rowIndex); <add> this._cellsInProgress.add(rowKey); <ide> } else { <del> this._cellsInProgress.delete(rowIndex); <add> this._cellsInProgress.delete(rowKey); <ide> } <ide> }; <ide> /** <ide> class WindowedListView extends React.Component { <ide> const rowFrames = this._rowFrames; <ide> let firstVisible = -1; <ide> let lastVisible = 0; <add> let lastRow = this.state.lastRow; <ide> const top = this._scrollOffsetY; <ide> const bottom = top + this._frameHeight; <del> for (let idx = 0; idx < rowFrames.length; idx++) { <del> const frame = rowFrames[idx]; <add> for (let idx = 0; idx < lastRow; idx++) { <add> const frame = rowFrames[props.data[idx].rowKey]; <ide> if (!frame) { <ide> // No frame - sometimes happens when they come out of order, so just wait for the rest. <ide> return; <ide> class WindowedListView extends React.Component { <ide> // Unfortuantely, we can't use <Incremental> to simplify our increment logic in this function because we need to <ide> // make sure that cells are rendered in the right order one at a time when scrolling back up. <ide> <del> const numRendered = this.state.lastRow - this.state.firstRow + 1; <add> const numRendered = lastRow - this.state.firstRow + 1; <ide> // Our last row target that we will approach incrementally <ide> const targetLastRow = clamp( <ide> numRendered - 1, // Don't reduce numRendered when scrolling back up <ide> lastVisible + props.numToRenderAhead, // Primary goal <ide> totalRows - 1, // Don't render past the end <ide> ); <del> let lastRow = this.state.lastRow; <ide> // Increment the last row one at a time per JS event loop <ide> if (!this._incrementPending) { <ide> if (targetLastRow > this.state.lastRow) { <ide> class WindowedListView extends React.Component { <ide> const rowsShouldChange = firstRow !== this.state.firstRow || lastRow !== this.state.lastRow; <ide> if (this._rowFramesDirty || rowsShouldChange) { <ide> if (rowsShouldChange) { <del> this.props.onMountedRowsWillChange && this.props.onMountedRowsWillChange(firstRow, lastRow - firstRow + 1); <add> props.onMountedRowsWillChange && props.onMountedRowsWillChange(firstRow, lastRow - firstRow + 1); <ide> infoLog( <ide> 'WLV: row render range will change:', <ide> {firstRow, firstVis: this._firstVisible, lastVis: this._lastVisible, lastRow}, <ide> class WindowedListView extends React.Component { <ide> const rowFrames = this._rowFrames; <ide> const rows = []; <ide> let spacerHeight = 0; <add> // Incremental rendering is a tradeoff between throughput and responsiveness. When we have plenty of buffer (say 50% <add> // of the target), we render incrementally to keep the app responsive. If we are dangerously low on buffer (say <add> // below 25%) we always disable incremental to try to catch up as fast as possible. In the middle, we only disable <add> // incremental while scrolling since it's unlikely the user will try to press a button while scrolling. We also <add> // ignore the "buffer" size when we are bumped up against the edge of the available data. <add> const firstBuffer = firstRow === 0 ? Infinity : this._firstVisible - firstRow; <add> const lastBuffer = lastRow === this.props.data.length - 1 ? Infinity : lastRow - this._lastVisible; <add> const minBuffer = Math.min(firstBuffer, lastBuffer); <add> const disableIncrementalRendering = this.props.disableIncrementalRendering || <add> (this._isScrolling && minBuffer < this.props.numToRenderAhead * 0.5) || <add> (minBuffer < this.props.numToRenderAhead * 0.25); <add> // Render mode is sticky while the component is mounted. <add> for (let ii = firstRow; ii <= lastRow; ii++) { <add> const rowKey = this.props.data[ii].rowKey; <add> if (this._rowRenderMode[rowKey] === 'sync' || (disableIncrementalRendering && this._rowRenderMode[rowKey] !== 'async')) { <add> this._rowRenderMode[rowKey] = 'sync'; <add> } else { <add> this._rowRenderMode[rowKey] = 'async'; <add> } <add> } <ide> for (let ii = firstRow; ii <= lastRow; ii++) { <del> if (!rowFrames[ii]) { <add> const rowKey = this.props.data[ii].rowKey; <add> if (!rowFrames[rowKey]) { <ide> break; // if rowFrame missing, no following ones will exist so quit early <ide> } <del> // Look for the first row where offscreen layout is done (only true for mounted rows) and set the spacer height <del> // such that it will offset all the unmounted rows before that one using the saved frame data. <del> if (rowFrames[ii].offscreenLayoutDone) { <del> const frame = rowFrames[ii - 1]; <del> spacerHeight = frame ? frame.y + frame.height : 0; <add> // Look for the first row where offscreen layout is done (only true for mounted rows) or it will be rendered <add> // synchronously and set the spacer height such that it will offset all the unmounted rows before that one using <add> // the saved frame data. <add> if (rowFrames[rowKey].offscreenLayoutDone || this._rowRenderMode[rowKey] === 'sync') { <add> if (ii > 0) { <add> const prevRowKey = this.props.data[ii - 1].rowKey; <add> const frame = rowFrames[prevRowKey]; <add> spacerHeight = frame ? frame.y + frame.height : 0; <add> } <ide> break; <ide> } <ide> } <ide> class WindowedListView extends React.Component { <ide> </View> <ide> ); <ide> } <del> // Incremental rendering is a tradeoff between throughput and responsiveness. When we have plenty of buffer (say 50% <del> // of the target), we render incrementally to keep the app responsive. If we are dangerously low on buffer (say <del> // below 25%) we always disable incremental to try to catch up as fast as possible. In the middle, we only disable <del> // incremental while scrolling since it's unlikely the user will try to press a button while scrolling. We also <del> // ignore the "buffer" size when we are bumped up against the edge of the available data. <del> const firstBuffer = firstRow === 0 ? Infinity : this._firstVisible - firstRow; <del> const lastBuffer = lastRow === this.props.data.length - 1 ? Infinity : lastRow - this._lastVisible; <del> const minBuffer = Math.min(firstBuffer, lastBuffer); <del> const disableIncrementalRendering = this.props.disableIncrementalRendering || <del> (this._isScrolling && minBuffer < this.props.numToRenderAhead * 0.5) || <del> (minBuffer < this.props.numToRenderAhead * 0.25); <ide> for (let idx = firstRow; idx <= lastRow; idx++) { <del> const key = '' + (this.props.enableDangerousRecycling ? (idx % this.props.maxNumToRender) : idx); <add> const rowKey = this.props.data[idx].rowKey; <add> const includeInLayout = this._rowRenderMode[rowKey] === 'sync' || <add> (this._rowFrames[rowKey] && this._rowFrames[rowKey].offscreenLayoutDone); <ide> rows.push( <ide> <CellRenderer <del> key={key} <del> recyclingKey={key} <add> key={rowKey} <add> rowKey={rowKey} <ide> rowIndex={idx} <ide> onNewLayout={this._onNewLayout} <ide> onWillUnmount={this._onWillUnmountCell} <del> includeInLayout={disableIncrementalRendering || <del> (this._rowFrames[idx] && this._rowFrames[idx].offscreenLayoutDone)} <add> includeInLayout={includeInLayout} <ide> onProgressChange={this._onProgressChange} <ide> asyncRowPerfEventName={this.props.asyncRowPerfEventName} <del> data={this.props.data[idx]} <add> rowData={this.props.data[idx].rowData} <ide> renderRow={this.props.renderRow} <ide> /> <ide> ); <ide> } <del> const showFooter = this._rowFrames[lastRow] && <del> this._rowFrames[lastRow].offscreenLayoutDone && <add> const lastRowKey = this.props.data[lastRow].rowKey; <add> const showFooter = this._rowFrames[lastRowKey] && <add> this._rowFrames[lastRowKey].offscreenLayoutDone && <ide> lastRow === this.props.data.length - 1; <ide> if (this.props.renderFooter) { <ide> rows.push( <ide> class WindowedListView extends React.Component { <ide> // Prevent user from scrolling into empty space of unmounted rows. <ide> const contentInset = {top: firstRow === 0 ? 0 : -spacerHeight}; <ide> return ( <del> <IncrementalGroup name="WLV" disabled={this.props.disableIncrementalRendering}> <del> {this.props.renderScrollComponent({ <del> scrollEventThrottle: 50, <del> removeClippedSubviews: true, <del> ...this.props, <del> contentInset, <del> ref: (ref) => { this._scrollRef = ref; }, <del> onScroll: this._onScroll, <del> onMomentumScrollEnd: this._onMomentumScrollEnd, <del> children: rows, <del> })} <del> </IncrementalGroup> <add> this.props.renderScrollComponent({ <add> scrollEventThrottle: 50, <add> removeClippedSubviews: true, <add> ...this.props, <add> contentInset, <add> ref: (ref) => { this._scrollRef = ref; }, <add> onScroll: this._onScroll, <add> onMomentumScrollEnd: this._onMomentumScrollEnd, <add> children: rows, <add> }) <ide> ); <ide> } <ide> } <ide> type CellProps = { <ide> /** <ide> * Row-specific data passed to renderRow and used in shouldComponentUpdate with === <ide> */ <del> data: mixed; <add> rowData: mixed; <add> rowKey: string; <ide> /** <ide> * Renders the actual row contents. <ide> */ <del> renderRow: (data: mixed, sectionIdx: number, rowIdx: number) => ?ReactElement; <add> renderRow: ( <add> rowData: mixed, sectionIdx: number, rowIdx: number, rowKey: string <add> ) => ?ReactElement; <ide> /** <ide> * Index of the row, passed through to other callbacks. <ide> */ <ide> type CellProps = { <ide> * Updates the parent with the latest layout. Only called when incremental rendering is done and triggers the parent <ide> * to re-render this row with includeInLayout true. <ide> */ <del> onNewLayout: (params: {rowIndex: number, layout: Object}) => void; <add> onNewLayout: (params: {rowKey: string, layout: Object}) => void; <ide> /** <ide> * Used to track when rendering is in progress so the parent can avoid wastedful re-renders that are just going to be <ide> * invalidated once the cell finishes. <ide> */ <del> onProgressChange: (progress: {rowIndex: number; inProgress: boolean}) => void; <add> onProgressChange: (progress: {rowKey: string; inProgress: boolean}) => void; <ide> /** <ide> * Used to invalidate the layout so the parent knows it needs to compensate for the height in the placeholder size. <ide> */ <del> onWillUnmount: (rowIndex: number) => void; <add> onWillUnmount: (rowKey: string) => void; <ide> }; <ide> class CellRenderer extends React.Component { <ide> props: CellProps; <ide> class CellRenderer extends React.Component { <ide> if (this.props.includeInLayout) { <ide> this._includeInLayoutLatch = true; <ide> } <del> this.props.onProgressChange({rowIndex: this.props.rowIndex, inProgress: true}); <add> this.props.onProgressChange({rowKey: this.props.rowKey, inProgress: true}); <ide> } <ide> _onLayout = (e) => { <ide> const layout = e.nativeEvent.layout; <ide> class CellRenderer extends React.Component { <ide> return; // Don't send premature or duplicate updates <ide> } <ide> this.props.onNewLayout({ <del> rowIndex: this.props.rowIndex, <add> rowKey: this.props.rowKey, <ide> layout, <ide> }); <ide> }; <ide> class CellRenderer extends React.Component { <ide> <ide> // If this is not called before calling onNewLayout, the number of inProgress cells will remain non-zero, <ide> // and thus the onNewLayout call will not fire the needed state change update. <del> this.props.onProgressChange({rowIndex: this.props.rowIndex, inProgress: false}); <add> this.props.onProgressChange({rowKey: this.props.rowKey, inProgress: false}); <ide> <ide> // If an onLayout event hasn't come in yet, then we skip here and assume it will come in later. This happens <ide> // when Incremental is disabled and _onOffscreenRenderDone is called faster than layout can happen. <del> this._lastLayout && this.props.onNewLayout({rowIndex: this.props.rowIndex, layout: this._lastLayout}); <add> this._lastLayout && this.props.onNewLayout({rowKey: this.props.rowKey, layout: this._lastLayout}); <ide> <ide> DEBUG && infoLog('\n >>>>> display row ' + this.props.rowIndex + '\n\n\n'); <ide> if (this.props.asyncRowPerfEventName) { <ide> class CellRenderer extends React.Component { <ide> }; <ide> componentWillUnmount() { <ide> clearTimeout(this._timeout); <del> this.props.onProgressChange({rowIndex: this.props.rowIndex, inProgress: false}); <del> this.props.onWillUnmount(this.props.rowIndex); <add> this.props.onProgressChange({rowKey: this.props.rowKey, inProgress: false}); <add> this.props.onWillUnmount(this.props.rowKey); <ide> } <ide> componentWillReceiveProps(newProps) { <ide> if (newProps.includeInLayout && !this.props.includeInLayout) { <ide> class CellRenderer extends React.Component { <ide> this._containerRef.setNativeProps({style: styles.include}); <ide> } <ide> } <del> shouldComponentUpdate(newProps) { <del> return newProps.data !== this.props.data; <add> shouldComponentUpdate(newProps: CellProps) { <add> return newProps.rowData !== this.props.rowData; <ide> } <ide> _setRef = (ref) => { <ide> this._containerRef = ref; <ide> class CellRenderer extends React.Component { <ide> const style = this._includeInLayoutLatch ? styles.include : styles.remove; <ide> return ( <ide> <IncrementalGroup <del> disable={this._includeInLayoutLatch} <add> disabled={this._includeInLayoutLatch} <ide> onDone={this._onOffscreenRenderDone} <ide> name={`WLVCell_${this.props.rowIndex}`}> <ide> <View <ide> ref={this._setRef} <ide> style={style} <ide> onLayout={this._onLayout}> <ide> {debug} <del> {this.props.renderRow(this.props.data, 0, this.props.rowIndex)} <add> {this.props.renderRow(this.props.rowData, 0, this.props.rowIndex, this.props.rowKey)} <ide> {debug} <ide> </View> <ide> </IncrementalGroup>
3
Go
Go
fix duplicate mount release
2732fe527f9258561c7310c128914b4b456c8404
<ide><path>builder/builder-next/adapters/snapshot/snapshot.go <ide> func (s *snapshotter) Close() error { <ide> } <ide> <ide> type mountable struct { <del> mu sync.Mutex <del> mounts []mount.Mount <del> acquire func() ([]mount.Mount, error) <del> release func() error <add> mu sync.Mutex <add> mounts []mount.Mount <add> acquire func() ([]mount.Mount, error) <add> release func() error <add> refCount int <ide> } <ide> <ide> func (m *mountable) Mount() ([]mount.Mount, error) { <ide> m.mu.Lock() <ide> defer m.mu.Unlock() <ide> <ide> if m.mounts != nil { <add> m.refCount++ <ide> return m.mounts, nil <ide> } <ide> <ide> func (m *mountable) Mount() ([]mount.Mount, error) { <ide> return nil, err <ide> } <ide> m.mounts = mounts <add> m.refCount = 1 <ide> <ide> return m.mounts, nil <ide> } <ide> <ide> func (m *mountable) Release() error { <ide> m.mu.Lock() <ide> defer m.mu.Unlock() <add> <add> if m.refCount > 1 { <add> m.refCount-- <add> return nil <add> } <add> <add> m.refCount = 0 <ide> if m.release == nil { <ide> return nil <ide> }
1
Javascript
Javascript
log validation errors to the console
cee956dbb7c67dedb276272327905567560aa2c6
<ide><path>lib/webpack.js <ide> function webpack(options, callback) { <ide> } else if(typeof options === "object") { <ide> var webpackOptionsValidationErrors = validateWebpackOptions(options); <ide> if(webpackOptionsValidationErrors.length) { <add> console.log("'options' validation errors:", webpackOptionsValidationErrors); <ide> throw new Error("Passed 'options' object does not look like a valid webpack configuration"); <ide> } <ide> new WebpackOptionsDefaulter().process(options);
1
Ruby
Ruby
fix typo in `brew doctor`
74ee65466cb321ba60db5ac6c1c568bcc9db56d3
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_for_config_scripts <ide> def check_for_dyld_vars <ide> if ENV['DYLD_LIBRARY_PATH'] <ide> puts <<-EOS.undent <del> Setting DYLD_LIBARY_PATH can break dynamic linking. <add> Setting DYLD_LIBRARY_PATH can break dynamic linking. <ide> You should probably unset it. <ide> <ide> EOS
1
Javascript
Javascript
improve typing of animated component wrappers
64720ab14a68fba7ae5ac3100499365e3c84ba85
<ide><path>Libraries/Animated/src/components/AnimatedFlatList.js <ide> import * as React from 'react'; <ide> <ide> const FlatList = require('../../../Lists/FlatList'); <del> <ide> const createAnimatedComponent = require('../createAnimatedComponent'); <ide> <add>import type {AnimatedComponentType} from '../createAnimatedComponent'; <add> <ide> /** <ide> * @see https://github.com/facebook/react-native/commit/b8c8562 <ide> */ <ide> const FlatListWithEventThrottle = React.forwardRef((props, ref) => ( <ide> <ide> module.exports = (createAnimatedComponent( <ide> FlatListWithEventThrottle, <del>): $FlowFixMe); <add>): AnimatedComponentType< <add> React.ElementConfig<typeof FlatList>, <add> React.ElementRef<typeof FlatList>, <add>>); <ide><path>Libraries/Animated/src/components/AnimatedImage.js <ide> <ide> 'use strict'; <ide> <del>const Image = require('../../../Image/Image'); <add>import * as React from 'react'; <ide> <add>const Image = require('../../../Image/Image'); <ide> const createAnimatedComponent = require('../createAnimatedComponent'); <ide> <del>module.exports = (createAnimatedComponent(Image): $FlowFixMe); <add>import type {AnimatedComponentType} from '../createAnimatedComponent'; <add> <add>module.exports = (createAnimatedComponent( <add> (Image: $FlowFixMe), <add>): AnimatedComponentType< <add> React.ElementConfig<typeof Image>, <add> React.ElementRef<typeof Image>, <add>>); <ide><path>Libraries/Animated/src/components/AnimatedScrollView.js <ide> import * as React from 'react'; <ide> <ide> const ScrollView = require('../../../Components/ScrollView/ScrollView'); <del> <ide> const createAnimatedComponent = require('../createAnimatedComponent'); <ide> <add>import type {AnimatedComponentType} from '../createAnimatedComponent'; <add> <ide> /** <ide> * @see https://github.com/facebook/react-native/commit/b8c8562 <ide> */ <ide> const ScrollViewWithEventThrottle = React.forwardRef((props, ref) => ( <ide> <ide> module.exports = (createAnimatedComponent( <ide> ScrollViewWithEventThrottle, <del>): $FlowFixMe); <add>): AnimatedComponentType< <add> React.ElementConfig<typeof ScrollView>, <add> React.ElementRef<typeof ScrollView>, <add>>); <ide><path>Libraries/Animated/src/components/AnimatedSectionList.js <ide> import * as React from 'react'; <ide> <ide> const SectionList = require('../../../Lists/SectionList'); <del> <ide> const createAnimatedComponent = require('../createAnimatedComponent'); <ide> <add>import type {AnimatedComponentType} from '../createAnimatedComponent'; <add> <ide> /** <ide> * @see https://github.com/facebook/react-native/commit/b8c8562 <ide> */ <ide> const SectionListWithEventThrottle = React.forwardRef((props, ref) => ( <ide> <ide> module.exports = (createAnimatedComponent( <ide> SectionListWithEventThrottle, <del>): $FlowFixMe); <add>): AnimatedComponentType< <add> React.ElementConfig<typeof SectionList>, <add> React.ElementRef<typeof SectionList>, <add>>); <ide><path>Libraries/Animated/src/components/AnimatedText.js <ide> <ide> 'use strict'; <ide> <del>const Text = require('../../../Text/Text'); <add>import * as React from 'react'; <ide> <add>const Text = require('../../../Text/Text'); <ide> const createAnimatedComponent = require('../createAnimatedComponent'); <ide> <del>module.exports = (createAnimatedComponent(Text): $FlowFixMe); <add>import type {AnimatedComponentType} from '../createAnimatedComponent'; <add> <add>module.exports = (createAnimatedComponent( <add> (Text: $FlowFixMe), <add>): AnimatedComponentType< <add> React.ElementConfig<typeof Text>, <add> React.ElementRef<typeof Text>, <add>>); <ide><path>Libraries/Animated/src/components/AnimatedView.js <ide> <ide> 'use strict'; <ide> <del>const View = require('../../../Components/View/View'); <add>import * as React from 'react'; <ide> <add>const View = require('../../../Components/View/View'); <ide> const createAnimatedComponent = require('../createAnimatedComponent'); <ide> <del>const React = require('react'); <del> <ide> import type {AnimatedComponentType} from '../createAnimatedComponent'; <ide> <ide> module.exports = (createAnimatedComponent(View): AnimatedComponentType<
6
Ruby
Ruby
fix argumenterror on ruby 3.0
d2642762885d79b330930ea473357f965a0b5581
<ide><path>actioncable/lib/action_cable/remote_connections.rb <ide> def initialize(server, ids) <ide> <ide> # Uses the internal channel to disconnect the connection. <ide> def disconnect <del> server.broadcast internal_channel, type: "disconnect" <add> server.broadcast internal_channel, { type: "disconnect" } <ide> end <ide> <ide> # Returns all the identifiers that were applied to this connection.
1
Go
Go
remove unwanted return variable name
a31be2512136444ce473235a35d6fd47634e3f13
<ide><path>registry/token.go <ide> type tokenResponse struct { <ide> Token string `json:"token"` <ide> } <ide> <del>func getToken(username, password string, params map[string]string, registryEndpoint *Endpoint) (token string, err error) { <add>func getToken(username, password string, params map[string]string, registryEndpoint *Endpoint) (string, error) { <ide> realm, ok := params["realm"] <ide> if !ok { <ide> return "", errors.New("no realm specified for token auth challenge")
1
Javascript
Javascript
add resolve_config log
1388c6897ef99b94b313b49bdf901efed84db571
<ide><path>packages/next/build/webpack.js <ide> export default async function getBaseWebpackConfig (dir: string, {dev = false, i <ide> } <ide> } <ide> <add> console.log('RESOLVE_CONFIG', resolveConfig) <add> <ide> const webpackMode = dev ? 'development' : 'production' <ide> <ide> let webpackConfig = {
1
Ruby
Ruby
use newer configure syntax as make template
5dd37087687fa837b990a50107aaf10d231a75ad
<ide><path>Library/Homebrew/brew.h.rb <ide> class #{Formula.class $1} <Formula <ide> cmake end <ide> cmake <ide> def install <del> autotools system "./configure --prefix='\#{prefix}' --disable-debug --disable-dependency-tracking" <add> autotools system "./configure", "--prefix=#{prefix}", "--disable-debug", "--disable-dependency-tracking" <ide> cmake system "cmake . \#{cmake_std_parameters}" <ide> system "make install" <ide> end
1
Python
Python
add http 308 permanent redirect
0d0e7c3ae092e1b98f4826ccf356a87cb9aa2b56
<ide><path>rest_framework/status.py <ide> def is_server_error(code): <ide> HTTP_305_USE_PROXY = 305 <ide> HTTP_306_RESERVED = 306 <ide> HTTP_307_TEMPORARY_REDIRECT = 307 <add>HTTP_308_PERMANENT_REDIRECT = 308 <ide> HTTP_400_BAD_REQUEST = 400 <ide> HTTP_401_UNAUTHORIZED = 401 <ide> HTTP_402_PAYMENT_REQUIRED = 402
1
Javascript
Javascript
explain the possibilty of refactor unused argument
9d2125e3bfeaa36692ded547a50c9579ddc39e20
<ide><path>lib/_http_incoming.js <ide> IncomingMessage.prototype.setTimeout = function setTimeout(msecs, callback) { <ide> // argument adaptor frame creation inside V8 in case that number of actual <ide> // arguments is different from expected arguments. <ide> // Ref: https://bugs.chromium.org/p/v8/issues/detail?id=10201 <add>// NOTE: Argument adapt frame issue might be solved in V8 engine v8.9. <add>// Refactoring `n` out might be possible when V8 is upgraded to that <add>// version. <add>// Ref: https://v8.dev/blog/v8-release-89 <ide> IncomingMessage.prototype._read = function _read(n) { <ide> if (!this._consuming) { <ide> this._readableState.readingMore = false;
1
Python
Python
fix spelling in celeryexecutor
b78632704124930eaf883142a0045a1ed348911c
<ide><path>airflow/executors/celery_executor.py <ide> def execute_command(command_to_exec: CommandType) -> None: <ide> log.info("Executing command in Celery: %s", command_to_exec) <ide> <ide> if settings.EXECUTE_TASKS_NEW_PYTHON_INTERPRETER: <del> _execute_in_subprocees(command_to_exec) <add> _execute_in_subprocess(command_to_exec) <ide> else: <ide> _execute_in_fork(command_to_exec) <ide> <ide> def _execute_in_fork(command_to_exec: CommandType) -> None: <ide> os._exit(ret) # pylint: disable=protected-access <ide> <ide> <del>def _execute_in_subprocees(command_to_exec: CommandType) -> None: <add>def _execute_in_subprocess(command_to_exec: CommandType) -> None: <ide> env = os.environ.copy() <ide> try: <ide> # pylint: disable=unexpected-keyword-arg <ide><path>tests/executors/test_celery_executor.py <ide> def test_gauge_executor_metrics(self, mock_stats_gauge, mock_trigger_tasks, mock <ide> )) <ide> def test_command_validation(self, command, expected_exception): <ide> # Check that we validate _on the receiving_ side, not just sending side <del> with mock.patch('airflow.executors.celery_executor._execute_in_subprocees') as mock_subproc, \ <add> with mock.patch('airflow.executors.celery_executor._execute_in_subprocess') as mock_subproc, \ <ide> mock.patch('airflow.executors.celery_executor._execute_in_fork') as mock_fork: <ide> if expected_exception: <ide> with pytest.raises(expected_exception): <ide><path>tests/utils/test_dag_processing.py <ide> def test_handle_failure_callback_with_zombies_are_correctly_passed_to_dag_file_p <ide> session.add(local_job) <ide> session.commit() <ide> <del> # TODO: If there was an actual Relationshop between TI and Job <add> # TODO: If there was an actual Relationship between TI and Job <ide> # we wouldn't need this extra commit <ide> session.add(ti) <ide> ti.job_id = local_job.id
3