content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
fix error with more case-sensitive databases
3c48552f81f486b8fd7bd9d3dabf9788f9b26018
<ide><path>lib/Cake/Model/Behavior/TranslateBehavior.php <ide> public function beforeFind($model, $query) { <ide> ); <ide> $conditionFields = $this->_checkConditions($model, $query); <ide> foreach ($conditionFields as $field) { <del> $query = $this->_addJoin($model, $query, $field, $locale); <add> $query = $this->_addJoin($model, $query, $field, $field, $locale); <ide> } <ide> unset($this->_joinTable, $this->_runtimeModel); <ide> return $query; <ide> public function beforeFind($model, $query) { <ide> unset($query['fields'][$key]); <ide> } <ide> } <del> $query = $this->_addJoin($model, $query, $field, $locale); <add> $query = $this->_addJoin($model, $query, $field, $aliasField, $locale); <ide> } <ide> } <ide> $this->runtime[$model->alias]['beforeFind'] = $addFields; <ide> protected function _checkConditions(Model $model, $query) { <ide> * @param object $joinTable The jointable object. <ide> * @param array $query The query array to append a join to. <ide> * @param string $field The field name being joined. <add> * @param string $aliasField The aliased field name being joined. <ide> * @param mixed $locale The locale(s) having joins added. <ide> * @param boolean $addField Whether or not to add a field. <ide> * @return array The modfied query <ide> */ <del> protected function _addJoin(Model $model, $query, $field, $locale, $addField = false) { <add> protected function _addJoin(Model $model, $query, $field, $aliasField, $locale, $addField = false) { <ide> $db = ConnectionManager::getDataSource($model->useDbConfig); <ide> <ide> $RuntimeModel = $this->_runtimeModel; <ide> protected function _addJoin(Model $model, $query, $field, $locale, $addField = f <ide> 'conditions' => array( <ide> $model->alias . '.' . $model->primaryKey => $db->identifier("I18n__{$field}__{$_locale}.foreign_key"), <ide> 'I18n__'.$field.'__'.$_locale.'.model' => $model->name, <del> 'I18n__'.$field.'__'.$_locale.'.'.$RuntimeModel->displayField => $field, <add> 'I18n__'.$field.'__'.$_locale.'.'.$RuntimeModel->displayField => $aliasField, <ide> 'I18n__'.$field.'__'.$_locale.'.locale' => $_locale <ide> ) <ide> ); <ide> protected function _addJoin(Model $model, $query, $field, $locale, $addField = f <ide> 'conditions' => array( <ide> $model->alias . '.' . $model->primaryKey => $db->identifier("I18n__{$field}.foreign_key"), <ide> 'I18n__'.$field.'.model' => $model->name, <del> 'I18n__'.$field.'.'.$RuntimeModel->displayField => $field, <add> 'I18n__'.$field.'.'.$RuntimeModel->displayField => $aliasField, <ide> 'I18n__'.$field.'.locale' => $locale <ide> ) <ide> );
1
Python
Python
prepare 1.0.6 release
892d9fae846b2e15e73de075e7290a8bfcfeb145
<ide><path>keras/__init__.py <ide> from . import optimizers <ide> from . import regularizers <ide> <del>__version__ = '1.0.5' <add>__version__ = '1.0.6' <ide><path>setup.py <ide> <ide> <ide> setup(name='Keras', <del> version='1.0.5', <add> version='1.0.6', <ide> description='Deep Learning for Python', <ide> author='Francois Chollet', <ide> author_email='[email protected]', <ide> url='https://github.com/fchollet/keras', <del> download_url='https://github.com/fchollet/keras/tarball/1.0.5', <add> download_url='https://github.com/fchollet/keras/tarball/1.0.6', <ide> license='MIT', <ide> install_requires=['theano', 'pyyaml', 'six'], <ide> extras_require={
2
Text
Text
add missing directory slashes [ci skip]
67e6deea1ccb0ff6264ff0796264ec90c190e35a
<ide><path>guides/source/getting_started.md <ide> of the files and folders that Rails created by default: <ide> <ide> | File/Folder | Purpose | <ide> | ----------- | ------- | <del>|app|Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.| <del>|bin|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.| <add>|app/|Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.| <add>|bin/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.| <ide> |config/|Configure your application's routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html).| <ide> |config.ru|Rack configuration for Rack based servers used to start the application.| <del>|db|Contains your current database schema, as well as the database migrations.| <add>|db/|Contains your current database schema, as well as the database migrations.| <ide> |Gemfile<br>Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see [the Bundler website](http://gembundler.com).| <del>|lib|Extended modules for your application.| <del>|log|Application log files.| <del>|public|The only folder seen by the world as-is. Contains static files and compiled assets.| <add>|lib/|Extended modules for your application.| <add>|log/|Application log files.| <add>|public/|The only folder seen by the world as-is. Contains static files and compiled assets.| <ide> |Rakefile|This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.| <ide> |README.rdoc|This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.| <del>|test|Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications](testing.html).| <del>|tmp|Temporary files (like cache, pid, and session files).| <del>|vendor|A place for all third-party code. In a typical Rails application this includes vendored gems.| <add>|test/|Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications](testing.html).| <add>|tmp/|Temporary files (like cache, pid, and session files).| <add>|vendor/|A place for all third-party code. In a typical Rails application this includes vendored gems.| <ide> <ide> Hello, Rails! <ide> -------------
1
Go
Go
implement docker kill with standalone client lib
c57e62d00e209288e4f2734d32a3184b4abf4248
<ide><path>api/client/kill.go <ide> func (cli *DockerCli) CmdKill(args ...string) error { <ide> <ide> var errNames []string <ide> for _, name := range cmd.Args() { <del> if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", name, *signal), nil, nil)); err != nil { <add> if err := cli.client.ContainerKill(name, *signal); err != nil { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> errNames = append(errNames, name) <ide> } else { <ide><path>api/client/lib/kill.go <add>package lib <add> <add>import "net/url" <add> <add>// ContainerKill terminates the container process but does not remove the container from the docker host. <add>func (cli *Client) ContainerKill(containerID, signal string) error { <add> var query url.Values <add> query.Set("signal", signal) <add> <add> _, err := cli.POST("/containers/"+containerID+"/kill", query, nil, nil) <add> return err <add>} <ide><path>api/client/start.go <ide> func (cli *DockerCli) forwardAllSignals(cid string) chan os.Signal { <ide> fmt.Fprintf(cli.err, "Unsupported signal: %v. Discarding.\n", s) <ide> continue <ide> } <del> if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", cid, sig), nil, nil)); err != nil { <add> <add> if err := cli.client.ContainerKill(cid, sig); err != nil { <ide> logrus.Debugf("Error sending signal: %s", err) <ide> } <ide> }
3
Text
Text
add v4.6.0-beta.1 to changelog
5a77a4312accd672f29b48b73db2b78745335ae7
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v4.6.0-beta.1 (June 13, 2022) <add> <add>No new external changes. <add> <ide> ### v4.5.0 (June 13, 2022) <ide> <ide> - [#20052](https://github.com/emberjs/ember.js/pull/20052) / [#20055](https://github.com/emberjs/ember.js/pull/20055) [FEATURE] Add the default helper manager to implement [RFC #0756](https://github.com/emberjs/rfcs/blob/master/text/0756-helper-default-manager.md).
1
Ruby
Ruby
replace drop sql statement to drop_table method
cb8b4167641484a9f7fe5757c872216e945bb1fb
<ide><path>activerecord/test/cases/associations/required_test.rb <ide> class Child < ActiveRecord::Base <ide> end <ide> <ide> teardown do <del> @connection.execute("DROP TABLE parents") if @connection.table_exists? 'parents' <del> @connection.execute("DROP TABLE children") if @connection.table_exists? 'children' <add> @connection.drop_table 'parents' if @connection.table_exists? 'parents' <add> @connection.drop_table 'children' if @connection.table_exists? 'children' <ide> end <ide> <ide> test "belongs_to associations are not required by default" do <ide><path>activerecord/test/cases/attribute_decorators_test.rb <ide> def type_cast_from_user(value) <ide> <ide> teardown do <ide> return unless @connection <del> @connection.execute 'DROP TABLE attribute_decorators_model' if @connection.table_exists? 'attribute_decorators_model' <add> @connection.drop_table 'attribute_decorators_model' if @connection.table_exists? 'attribute_decorators_model' <ide> Model.attribute_type_decorations.clear <ide> Model.reset_column_information <ide> end <ide><path>activerecord/test/cases/migration/foreign_key_test.rb <ide> class Astronaut < ActiveRecord::Base <ide> <ide> teardown do <ide> if defined?(@connection) <del> @connection.execute "DROP TABLE astronauts" if @connection.table_exists? 'astronauts' <del> @connection.execute "DROP TABLE rockets" if @connection.table_exists? 'rockets' <add> @connection.drop_table "astronauts" if @connection.table_exists? 'astronauts' <add> @connection.drop_table "rockets" if @connection.table_exists? 'rockets' <ide> end <ide> end <ide>
3
Javascript
Javascript
add angular-route.js to karma docs suite
6b12432729848d3b34689f62a6bcd1766fd29720
<ide><path>karma-docs.conf.js <ide> files = [ <ide> 'build/angular-resource.js', <ide> 'build/angular-mobile.js', <ide> 'build/angular-sanitize.js', <add> 'build/angular-route.js', <ide> <ide> 'build/docs/components/lib/lunr.js/lunr.js', <ide> 'build/docs/components/lib/google-code-prettify/src/prettify.js',
1
Text
Text
fix typo in building.md
ed5e5395c730a27b4e86ff6a4efbd36044cf93f5
<ide><path>BUILDING.md <ide> to execute JavaScript tests independently of the C++ test suite: <ide> $ make coverage-run-js <ide> ``` <ide> <del>If you are updating tests and want to collect coverrage for a single test file <add>If you are updating tests and want to collect coverage for a single test file <ide> (e.g. `test/parallel/test-stream2-transform.js`): <ide> <ide> ```text
1
PHP
PHP
fix cs errors
2a73fcc271a9564315bae793a29df865d785bb37
<ide><path>src/Mailer/Mailer.php <ide> abstract class Mailer implements EventListenerInterface <ide> * <ide> * @var string <ide> */ <del> static public $name; <add> public static $name; <ide> <ide> /** <ide> * Email instance. <ide><path>tests/TestCase/Cache/Engine/ApcuEngineTest.php <ide> class ApcuEngineTest extends TestCase <ide> * <ide> * @var bool <ide> */ <del> static protected $useRequestTime = null; <add> protected static $useRequestTime = null; <ide> <ide> /** <ide> * Ensure use_request_time is turned off <ide><path>tests/TestCase/Console/CommandRunnerTest.php <ide> public function testRunValidCommandSubcommandName() <ide> { <ide> $app = $this->makeAppWithCommands([ <ide> 'tool build' => DemoCommand::class, <del> 'tool' => AbortCommand::class <add> 'tool' => AbortCommand::class, <ide> ]); <ide> $output = new ConsoleOutput(); <ide> <ide> public function testRunValidCommandNestedName() <ide> { <ide> $app = $this->makeAppWithCommands([ <ide> 'tool build assets' => DemoCommand::class, <del> 'tool' => AbortCommand::class <add> 'tool' => AbortCommand::class, <ide> ]); <ide> $output = new ConsoleOutput(); <ide>
3
Javascript
Javascript
name anonymous function in tls.js
07c514ce29ffb1875b62ad5cbf056b33b7fdc9e5
<ide><path>lib/tls.js <ide> function convertProtocols(protocols) { <ide> return buff; <ide> } <ide> <del>exports.convertALPNProtocols = function(protocols, out) { <add>exports.convertALPNProtocols = function convertALPNProtocols(protocols, out) { <ide> // If protocols is Array - translate it into buffer <ide> if (Array.isArray(protocols)) { <ide> out.ALPNProtocols = convertProtocols(protocols);
1
PHP
PHP
unify other log types as well
8141dd2d5d2fe3792c2ca3df258d1a7a0da2465e
<ide><path>lib/Cake/Console/Shell.php <ide> protected function _useLogger($enable = true) { <ide> return; <ide> } <ide> CakeLog::config('stdout', array( <del> 'engine' => 'ConsoleLog', <add> 'engine' => 'Console', <ide> 'types' => array('notice', 'info'), <ide> 'stream' => $this->stdout, <ide> )); <ide> CakeLog::config('stderr', array( <del> 'engine' => 'ConsoleLog', <add> 'engine' => 'Console', <ide> 'types' => array('emergency', 'alert', 'critical', 'error', 'warning', 'debug'), <ide> 'stream' => $this->stderr, <ide> )); <ide><path>lib/Cake/Log/Engine/SyslogLog.php <ide> class SyslogLog extends BaseLog { <ide> * <ide> * {{{ <ide> * CakeLog::config('error', array( <del> * 'engine' => 'SyslogLog', <add> * 'engine' => 'Syslog', <ide> * 'types' => array('emergency', 'alert', 'critical', 'error'), <ide> * 'format' => "%s: My-App - %s", <ide> * 'prefix' => 'Web Server 01' <ide><path>lib/Cake/Test/Case/Console/ShellTest.php <ide> public function testFileAndConsoleLogging() { <ide> array('types' => 'error'), <ide> )); <ide> TestCakeLog::config('console', array( <del> 'engine' => 'ConsoleLog', <add> 'engine' => 'Console', <ide> 'stream' => 'php://stderr', <ide> )); <ide> TestCakeLog::replace('console', $mock); <ide><path>lib/Cake/Test/Case/Log/Engine/ConsoleLogTest.php <ide> public function tearDown() { <ide> */ <ide> public function testConsoleOutputWrites() { <ide> TestCakeLog::config('test_console_log', array( <del> 'engine' => 'TestConsoleLog', <add> 'engine' => 'TestConsole', <ide> )); <ide> <ide> $mock = $this->getMock('TestConsoleLog', array('write'), array( <ide> public function testConsoleOutputWrites() { <ide> */ <ide> public function testCombinedLogWriting() { <ide> TestCakeLog::config('test_console_log', array( <del> 'engine' => 'TestConsoleLog', <add> 'engine' => 'TestConsole', <ide> )); <ide> $mock = $this->getMock('TestConsoleLog', array('write'), array( <ide> array('types' => 'error'), <ide> public function testCombinedLogWriting() { <ide> */ <ide> public function testDefaultOutputAs() { <ide> TestCakeLog::config('test_console_log', array( <del> 'engine' => 'TestConsoleLog', <add> 'engine' => 'TestConsole', <ide> )); <ide> if (DS === '\\' && !(bool)env('ANSICON')) { <ide> $expected = ConsoleOutput::PLAIN;
4
PHP
PHP
create "auth" helper
46203676c748ac3cdb4849e75e711ca9cb1ca118
<ide><path>src/Illuminate/Foundation/helpers.php <ide> function asset($path, $secure = null) <ide> } <ide> } <ide> <add>if ( ! function_exists('auth')) <add>{ <add> /** <add> * Get the available auth instance. <add> * <add> * @return \Illuminate\Contracts\Auth\Guard <add> */ <add> function auth() <add> { <add> return app('Illuminate\Contracts\Auth\Guard'); <add> } <add>} <add> <ide> if ( ! function_exists('base_path')) <ide> { <ide> /**
1
Python
Python
fix initialization of index_array
595d67ad7d919b44f3c4cabcf68c756c35b14c9c
<ide><path>keras/preprocessing/image.py <ide> def reset(self): <ide> self.batch_index = 0 <ide> <ide> def _flow_index(self, N, batch_size=32, shuffle=False, seed=None): <add> # ensure self.batch_index is 0 <add> self.reset() <add> <ide> while 1: <del> index_array = np.arange(N) <ide> if self.batch_index == 0: <add> index_array = np.arange(N) <ide> if shuffle: <ide> if seed is not None: <ide> np.random.seed(seed + self.total_batches_seen)
1
Java
Java
add support for ping and pong websocket messages
1f897329f9b8617a84fab10fee5f3ad9269160b3
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/BinaryMessage.java <ide> public final class BinaryMessage extends WebSocketMessage<ByteBuffer> { <ide> <ide> /** <ide> * Create a new {@link BinaryMessage} instance. <del> * @param payload a non-null payload <add> * @param payload the non-null payload <ide> */ <ide> public BinaryMessage(ByteBuffer payload) { <ide> this(payload, true); <ide> } <ide> <ide> /** <ide> * Create a new {@link BinaryMessage} instance. <del> * @param payload a non-null payload <add> * @param payload the non-null payload <ide> * @param isLast if the message is the last of a series of partial messages <ide> */ <ide> public BinaryMessage(ByteBuffer payload, boolean isLast) { <ide> public BinaryMessage(ByteBuffer payload, boolean isLast) { <ide> <ide> /** <ide> * Create a new {@link BinaryMessage} instance. <del> * @param payload a non-null payload <add> * @param payload the non-null payload <ide> */ <ide> public BinaryMessage(byte[] payload) { <ide> this(payload, 0, (payload == null ? 0 : payload.length), true); <ide> } <ide> <ide> /** <ide> * Create a new {@link BinaryMessage} instance. <del> * @param payload a non-null payload <add> * @param payload the non-null payload <ide> * @param isLast if the message is the last of a series of partial messages <ide> */ <ide> public BinaryMessage(byte[] payload, boolean isLast) { <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/PingMessage.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.web.socket; <add> <add>import java.nio.ByteBuffer; <add> <add>/** <add> * A WebSocket ping message. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public final class PingMessage extends WebSocketMessage<ByteBuffer> { <add> <add> <add> public PingMessage(ByteBuffer payload) { <add> super(payload); <add> } <add> <add> @Override <add> protected int getPayloadSize() { <add> return (getPayload() != null) ? getPayload().remaining() : 0; <add> } <add> <add> @Override <add> protected String toStringPayload() { <add> return (getPayload() != null) ? getPayload().toString() : null; <add> } <add> <add>} <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/PongMessage.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.web.socket; <add> <add>import java.nio.ByteBuffer; <add> <add>/** <add> * A WebSocket pong message. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public final class PongMessage extends WebSocketMessage<ByteBuffer> { <add> <add> <add> public PongMessage(ByteBuffer payload) { <add> super(payload); <add> } <add> <add> @Override <add> protected int getPayloadSize() { <add> return (getPayload() != null) ? getPayload().remaining() : 0; <add> } <add> <add> @Override <add> protected String toStringPayload() { <add> return (getPayload() != null) ? getPayload().toString() : null; <add> } <add> <add>} <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/TextMessage.java <ide> public final class TextMessage extends WebSocketMessage<String> { <ide> <ide> /** <ide> * Create a new {@link TextMessage} instance. <del> * @param payload the payload <add> * @param payload the non-null payload <ide> */ <ide> public TextMessage(CharSequence payload) { <ide> super(payload.toString(), true); <ide> } <ide> <ide> /** <ide> * Create a new {@link TextMessage} instance. <del> * @param payload the payload <add> * @param payload the non-null payload <ide> * @param isLast whether this the last part of a message received or transmitted in parts <ide> */ <ide> public TextMessage(CharSequence payload, boolean isLast) { <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/WebSocketMessage.java <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <del> * @see BinaryMessage <del> * @see TextMessage <ide> */ <ide> public abstract class WebSocketMessage<T> { <ide> <ide> private final boolean last; <ide> <ide> <add> /** <add> * Create a new {@link WebSocketMessage} instance with the given payload. <add> */ <add> WebSocketMessage(T payload) { <add> this(payload, true); <add> } <add> <ide> /** <ide> * Create a new {@link WebSocketMessage} instance with the given payload. <ide> * @param payload a non-null payload <ide> */ <ide> WebSocketMessage(T payload, boolean isLast) { <del> Assert.notNull(payload, "Payload must not be null"); <add> Assert.notNull(payload, "payload is required"); <ide> this.payload = payload; <ide> this.last = isLast; <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/AbstractWebSocketSesssion.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.socket.BinaryMessage; <ide> import org.springframework.web.socket.CloseStatus; <add>import org.springframework.web.socket.PingMessage; <add>import org.springframework.web.socket.PongMessage; <ide> import org.springframework.web.socket.TextMessage; <ide> import org.springframework.web.socket.WebSocketMessage; <ide> import org.springframework.web.socket.WebSocketSession; <ide> public final void sendMessage(WebSocketMessage message) throws IOException { <ide> else if (message instanceof BinaryMessage) { <ide> sendBinaryMessage((BinaryMessage) message); <ide> } <add> else if (message instanceof PingMessage) { <add> sendPingMessage((PingMessage) message); <add> } <add> else if (message instanceof PongMessage) { <add> sendPongMessage((PongMessage) message); <add> } <ide> else { <ide> throw new IllegalStateException("Unexpected WebSocketMessage type: " + message); <ide> } <ide> } <ide> <del> protected abstract void sendTextMessage(TextMessage message) throws IOException ; <add> protected abstract void sendTextMessage(TextMessage message) throws IOException; <add> <add> protected abstract void sendBinaryMessage(BinaryMessage message) throws IOException; <ide> <del> protected abstract void sendBinaryMessage(BinaryMessage message) throws IOException ; <add> protected abstract void sendPingMessage(PingMessage message) throws IOException; <ide> <add> protected abstract void sendPongMessage(PongMessage message) throws IOException; <ide> <ide> @Override <ide> public final void close() throws IOException { <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/JettyWebSocketSession.java <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.web.socket.BinaryMessage; <ide> import org.springframework.web.socket.CloseStatus; <add>import org.springframework.web.socket.PingMessage; <add>import org.springframework.web.socket.PongMessage; <ide> import org.springframework.web.socket.TextMessage; <ide> import org.springframework.web.socket.WebSocketSession; <ide> <ide> protected void sendBinaryMessage(BinaryMessage message) throws IOException { <ide> getNativeSession().getRemote().sendBytes(message.getPayload()); <ide> } <ide> <add> @Override <add> protected void sendPingMessage(PingMessage message) throws IOException { <add> getNativeSession().getRemote().sendPing(message.getPayload()); <add> } <add> <add> @Override <add> protected void sendPongMessage(PongMessage message) throws IOException { <add> getNativeSession().getRemote().sendPong(message.getPayload()); <add> } <add> <ide> @Override <ide> protected void closeInternal(CloseStatus status) throws IOException { <ide> getNativeSession().close(status.getCode(), status.getReason()); <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/StandardWebSocketHandlerAdapter.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.socket.BinaryMessage; <ide> import org.springframework.web.socket.CloseStatus; <add>import org.springframework.web.socket.PongMessage; <ide> import org.springframework.web.socket.TextMessage; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.support.ExceptionWebSocketHandlerDecorator; <ide> public void onMessage(ByteBuffer message) { <ide> }); <ide> } <ide> <add> session.addMessageHandler(new MessageHandler.Whole<javax.websocket.PongMessage>() { <add> @Override <add> public void onMessage(javax.websocket.PongMessage message) { <add> handlePongMessage(session, message.getApplicationData()); <add> } <add> }); <add> <ide> try { <ide> this.handler.afterConnectionEstablished(this.wsSession); <ide> } <ide> private void handleBinaryMessage(javax.websocket.Session session, ByteBuffer pay <ide> } <ide> } <ide> <add> private void handlePongMessage(javax.websocket.Session session, ByteBuffer payload) { <add> PongMessage pongMessage = new PongMessage(payload); <add> try { <add> this.handler.handleMessage(this.wsSession, pongMessage); <add> } <add> catch (Throwable t) { <add> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, t, logger); <add> } <add> } <add> <ide> @Override <ide> public void onClose(javax.websocket.Session session, CloseReason reason) { <ide> CloseStatus closeStatus = new CloseStatus(reason.getCloseCode().getCode(), reason.getReasonPhrase()); <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/StandardWebSocketSession.java <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.socket.BinaryMessage; <ide> import org.springframework.web.socket.CloseStatus; <add>import org.springframework.web.socket.PingMessage; <add>import org.springframework.web.socket.PongMessage; <ide> import org.springframework.web.socket.TextMessage; <ide> import org.springframework.web.socket.WebSocketSession; <ide> <ide> protected void sendBinaryMessage(BinaryMessage message) throws IOException { <ide> getNativeSession().getBasicRemote().sendBinary(message.getPayload(), message.isLast()); <ide> } <ide> <add> @Override <add> protected void sendPingMessage(PingMessage message) throws IOException { <add> getNativeSession().getBasicRemote().sendPing(message.getPayload()); <add> } <add> <add> @Override <add> protected void sendPongMessage(PongMessage message) throws IOException { <add> getNativeSession().getBasicRemote().sendPong(message.getPayload()); <add> } <add> <ide> @Override <ide> protected void closeInternal(CloseStatus status) throws IOException { <ide> getNativeSession().close(new CloseReason(CloseCodes.getCloseCode(status.getCode()), status.getReason())); <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/WebSocketHandlerAdapter.java <ide> <ide> import org.springframework.web.socket.BinaryMessage; <ide> import org.springframework.web.socket.CloseStatus; <add>import org.springframework.web.socket.PongMessage; <ide> import org.springframework.web.socket.TextMessage; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.WebSocketMessage; <ide> */ <ide> public class WebSocketHandlerAdapter implements WebSocketHandler { <ide> <add> <ide> @Override <ide> public void afterConnectionEstablished(WebSocketSession session) throws Exception { <ide> } <ide> public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) <ide> else if (message instanceof BinaryMessage) { <ide> handleBinaryMessage(session, (BinaryMessage) message); <ide> } <add> else if (message instanceof PongMessage) { <add> handlePongMessage(session, (PongMessage) message); <add> } <ide> else { <ide> throw new IllegalStateException("Unexpected WebSocket message type: " + message); <ide> } <ide> protected void handleTextMessage(WebSocketSession session, TextMessage message) <ide> protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception { <ide> } <ide> <add> protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception { <add> } <add> <ide> @Override <ide> public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { <ide> }
10
Go
Go
improve error output for `docker stats ...`
32de162fc9a18f7f2d702ce488e73b5eca0199ce
<ide><path>cli/command/container/stats.go <ide> func runStats(dockerCli *command.DockerCli, opts *statsOptions) error { <ide> var errs []string <ide> cStats.mu.Lock() <ide> for _, c := range cStats.cs { <del> cErr := c.GetError() <del> if cErr != nil { <del> errs = append(errs, fmt.Sprintf("%s: %v", c.Name, cErr)) <add> if err := c.GetError(); err != nil { <add> errs = append(errs, err.Error()) <ide> } <ide> } <ide> cStats.mu.Unlock() <ide> if len(errs) > 0 { <del> return fmt.Errorf("%s", strings.Join(errs, ", ")) <add> return fmt.Errorf("%s", strings.Join(errs, "\n")) <ide> } <ide> } <ide>
1
Ruby
Ruby
add ability to reference casks from brew reinstall
d1004c81430d6b893ff487a32b9c4fe70131a943
<ide><path>Library/Homebrew/cmd/reinstall.rb <ide> require "reinstall" <ide> require "cli/parser" <ide> require "cleanup" <add>require "cask/all" <ide> <ide> module Homebrew <ide> module_function <ide> def reinstall <ide> <ide> Install.perform_preinstall_checks <ide> <del> args.resolved_formulae.each do |f| <add> resolved_formulae, possible_casks = args.resolved_formulae_and_unknowns <add> resolved_formulae.each do |f| <ide> if f.pinned? <ide> onoe "#{f.full_name} is pinned. You must unpin it to reinstall." <ide> next <ide> def reinstall <ide> Cleanup.install_formula_clean!(f) <ide> end <ide> Homebrew.messages.display_messages <add> <add> possible_casks.each do |name| <add> reinstall_cmd = Cask::Cmd::Reinstall.new(name) <add> reinstall_cmd.verbose = args.verbose? <add> reinstall_cmd.force = args.force? <add> reinstall_cmd.run <add> rescue Cask::CaskUnavailableError <add> ofail "No installed keg or cask with the name \"#{name}\"" <add> end <ide> end <ide> end
1
Text
Text
update deployment documentation.
26ddf32f53f24dd4a56b10ee2b668aebe17cb6b1
<ide><path>docs/deployment.md <ide> --- <del>description: Deploy your Next.js app to production with Vercel and other hosting options. <add>description: Learn how to deploy your Next.js app to production, either managed or self-hosted. <ide> --- <ide> <ide> # Deployment <ide> <del>## Vercel (Recommended) <add>Congratulations, you are ready to deploy your Next.js application to production. This document will show how to deploy either managed or self-hosted using the [Next.js Build API](#nextjs-build-api). <ide> <del>The easiest way to deploy Next.js to production is to use the **[Vercel platform](https://vercel.com)** from the creators of Next.js. [Vercel](https://vercel.com) is a cloud platform for static sites, hybrid apps, and Serverless Functions. <add>## Next.js Build API <ide> <del>### Getting started <add>`next build` generates an optimized version of your application for production. This standard output includes: <ide> <del>If you haven’t already done so, push your Next.js app to a Git provider of your choice: [GitHub](https://github.com/), [GitLab](https://gitlab.com/), or [BitBucket](https://bitbucket.org/). Your repository can be private or public. <add>- HTML files for pages using `getStaticProps` or [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) <add>- CSS files for global styles or for individually scoped styles <add>- JavaScript for pre-rendering dynamic content from the Next.js server <add>- JavaScript for interactivity on the client-side through React <ide> <del>Then, follow these steps: <add>This output is generated inside the `.next` folder: <ide> <del>1. [Sign up to Vercel](https://vercel.com/signup) (no credit card is required). <del>2. After signing up, you’ll arrive on the [“Import Project”](https://vercel.com/new) page. Under “From Git Repository”, choose the Git provider you use and set up an integration. (Instructions: [GitHub](https://vercel.com/docs/git/vercel-for-github) / [GitLab](https://vercel.com/docs/git/vercel-for-gitlab) / [BitBucket](https://vercel.com/docs/git/vercel-for-bitbucket)). <del>3. Once that’s set up, click “Import Project From …” and import your Next.js app. It auto-detects that your app is using Next.js and sets up the build configuration for you. No need to change anything — everything should work fine! <del>4. After importing, it’ll deploy your Next.js app and provide you with a deployment URL. Click “Visit” to see your app in production. <add>- `.next/static/chunks/pages` – Each JavaScript file inside this folder relates to the route with the same name. For example, `.next/static/chunks/pages/about.js` would be the JavaScript file loaded when viewing the `/about` route in your application <add>- `.next/static/media` – Statically imported images from `next/image` are hashed and copied here <add>- `.next/static/css` – Global CSS files for all pages in your application <add>- `.next/server/pages` – The HTML and JavaScript entry points prerendered from the server. The `.nft.json` files are created when [Output File Tracing](/docs/advanced-features/output-file-tracing.md) is enabled and contain all the file paths that depend on a given page. <add>- `.next/server/chunks` – Shared JavaScript chunks used in multiple places throughout your application <add>- `.next/cache` – Output for the build cache and cached images, responses, and pages from the Next.js server. Using a cache helps decrease build times and improve performance of loading images <ide> <del>Congratulations! You’ve deployed your Next.js app! If you have questions, take a look at the [Vercel documentation](https://vercel.com/docs). <add>All JavaScript code inside `.next` has been **compiled** and browser bundles have been **minified** to help achieve the best performance and support [all modern browsers](/docs/basic-features/supported-browsers-features.md). <ide> <del>> If you’re using a [custom server](/docs/advanced-features/custom-server.md), we strongly recommend migrating away from it (for example, by using [dynamic routing](/docs/routing/dynamic-routes.md)). If you cannot migrate, consider [other hosting options](#other-hosting-options). <add>## Managed Next.js with Vercel <ide> <del>### DPS: Develop, Preview, Ship <add>[Vercel](https://vercel.com/) is a frontend cloud platform from the creators of Next.js. It's the fastest way to deploy your managed Next.js application with zero configuration. <ide> <del>Let’s talk about the workflow we recommend using. [Vercel](https://vercel.com) supports what we call the **DPS** workflow: **D**evelop, **P**review, and **S**hip: <add>When deploying to Vercel, the platform automatically detects Next.js, runs `next build`, and optimizes the build output for you, including: <ide> <del>- **Develop:** Write code in Next.js. Keep the development server running and take advantage of [React Fast Refresh](https://nextjs.org/blog/next-9-4#fast-refresh). <del>- **Preview:** Every time you push changes to a branch on GitHub / GitLab / BitBucket, Vercel automatically creates a new deployment with a unique URL. You can view them on GitHub when you open a pull request, or under “Preview Deployments” on your project page on Vercel. [Learn more about it here](https://vercel.com/features/deployment-previews). <del>- **Ship:** When you’re ready to ship, merge the pull request to your default branch (e.g. `main`). Vercel will automatically create a production deployment. <add>- Persisting cached assets across deployments if unchanged <add>- [Immutable deployments](https://vercel.com/features/previews) with a unique URL for every commit <add>- [Pages](/docs/basic-features/pages.md) are automatically statically optimized, if possible <add>- Assets (JavaScript, CSS, images, fonts) are compressed and served from a [Global Edge Network](https://vercel.com/features/infrastructure) <add>- [API Routes](/docs/api-routes/introduction.md) are automatically optimized as isolated [Serverless Functions](https://vercel.com/features/infrastructure) that can scale infinitely <add>- [Middleware](/docs/middleware.md) are automatically optimized as [Edge Functions](https://vercel.com/features/edge-functions) that have zero cold starts and boot instantly <ide> <del>By using the DPS workflow, in addition to doing _code reviews_, you can do _deployment previews_. Each deployment creates a unique URL that can be shared or used for integration tests. <add>In addition, Vercel provides features like: <ide> <del>### Optimized for Next.js <add>- Automatic performance monitoring with [Next.js Analytics](/analytics) <add>- Automatic HTTPS and SSL certificates <add>- Automatic CI/CD (through GitHub, GitLab, Bitbucket, etc.) <add>- Support for [Environment Variables](https://vercel.com/docs/environment-variables) <add>- Support for [Custom Domains](https://vercel.com/docs/custom-domains) <add>- Support for [Image Optimization](/docs/basic-features/image-optimization.md) with `next/image` <add>- Instant global deployments via `git push` <ide> <del>[Vercel](https://vercel.com) is made by the creators of Next.js and has first-class support for Next.js. <add>You can start using Vercel (for free) through a personal hobby account, or create a team to start the next big thing. Learn more about [Next.js on Vercel](https://vercel.com/solutions/nextjs) or read the [Vercel Documentation](https://vercel.com/docs). <ide> <del>For example, the [hybrid pages](/docs/basic-features/pages.md) approach is fully supported out of the box. <add>[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/hello-world&project-name=hello-world&repository-name=hello-world&utm_source=github.com&utm_medium=referral&utm_campaign=deployment) <ide> <del>- Every page can either use [Static Generation](/docs/basic-features/pages.md#static-generation) or [Server-Side Rendering](/docs/basic-features/pages.md#server-side-rendering). <del>- Pages that use [Static Generation](/docs/basic-features/pages.md#static-generation) and assets (JS, CSS, images, fonts, etc) will automatically be served from [Vercel's Edge Network](https://vercel.com/docs/edge-network/overview), which is blazingly fast. <del>- Pages that use [Server-Side Rendering](/docs/basic-features/pages.md#server-side-rendering) and [API routes](/docs/api-routes/introduction.md) will automatically become isolated Serverless Functions. This allows page rendering and API requests to scale infinitely. <add>## Self-Hosting <ide> <del>### Custom Domains, Environment Variables, Automatic HTTPS, and more <del> <del>- **Custom Domains:** Once deployed on [Vercel](https://vercel.com), you can assign a custom domain to your Next.js app. Take a look at [our documentation here](https://vercel.com/docs/custom-domains). <del>- **Environment Variables:** You can also set environment variables on Vercel. Take a look at [our documentation here](https://vercel.com/docs/environment-variables). You can then [use those environment variables](/docs/api-reference/next.config.js/environment-variables.md) in your Next.js app. <del>- **Automatic HTTPS:** HTTPS is enabled by default (including custom domains) and doesn't require extra configuration. We auto-renew SSL certificates. <del>- **More:** [Read our documentation](https://vercel.com/docs) to learn more about the Vercel platform. <del> <del>## Automatic Updates <del> <del>When you deploy your Next.js application, you want to see the latest version without needing to reload. <del> <del>Next.js will automatically load the latest version of your application in the background when routing. For client-side navigation, `next/link` will temporarily function as a normal `<a>` tag. <del> <del>**Note:** If a new page (with an old version) has already been prefetched by `next/link`, Next.js will use the old version. Then, after either a full page refresh or multiple client-side page transitions, Next.js will show the latest version. <del> <del>## Other hosting options <add>You can self-host Next.js with support for all features using Node.js or Docker. You can also do a Static HTML Export, which [has some limitations](/docs/advanced-features/static-html-export.md). <ide> <ide> ### Node.js Server <ide> <del>Next.js can be deployed to any hosting provider that supports Node.js. Make sure your `package.json` has the `"build"` and `"start"` scripts: <add>Next.js can be deployed to any hosting provider that supports Node.js. For example, [AWS EC2](https://aws.amazon.com/ec2/) or a [DigitalOcean Droplet](https://www.digitalocean.com/products/droplets/). <add> <add>First, ensure your `package.json` has the `"build"` and `"start"` scripts: <ide> <ide> ```json <ide> { <ide> Next.js can be deployed to any hosting provider that supports Node.js. Make sure <ide> } <ide> ``` <ide> <del>`next build` builds the production application in the `.next` folder. After building, `next start` starts a Node.js server that supports [hybrid pages](/docs/basic-features/pages.md), serving both statically generated and server-side rendered pages. <add>Then, run `next build` to build your application. Finally, run `next start` to start the Node.js server. This server supports all features of Next.js. <ide> <del>If you are using [`next/image`](/docs/basic-features/image-optimization.md), consider adding `sharp` for more performant [Image Optimization](/docs/basic-features/image-optimization.md) in your production environment by running `npm install sharp` in your project directory. On Linux platforms, `sharp` may require [additional configuration](https://sharp.pixelplumbing.com/install#linux-memory-allocator) to prevent excessive memory usage. <add>> If you are using [`next/image`](/docs/basic-features/image-optimization.md), consider adding `sharp` for more performant [Image Optimization](/docs/basic-features/image-optimization.md) in your production environment by running `npm install sharp` in your project directory. On Linux platforms, `sharp` may require [additional configuration](https://sharp.pixelplumbing.com/install#linux-memory-allocator) to prevent excessive memory usage. <ide> <ide> ### Docker Image <ide> <del><details open> <del> <summary><b>Examples</b></summary> <del> <ul> <del> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-docker">with-docker</a></li> <del> </ul> <del></details> <del> <ide> Next.js can be deployed to any hosting provider that supports [Docker](https://www.docker.com/) containers. You can use this approach when deploying to container orchestrators such as [Kubernetes](https://kubernetes.io/) or [HashiCorp Nomad](https://www.nomadproject.io/), or when running inside a single node in any cloud provider. <ide> <del>Here is a multi-stage `Dockerfile` using `node:alpine` that you can use: <del> <del>```Dockerfile <del># Install dependencies only when needed <del>FROM node:alpine AS deps <del># Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed. <del>RUN apk add --no-cache libc6-compat <del>WORKDIR /app <del>COPY package.json yarn.lock ./ <del>RUN yarn install --frozen-lockfile <add>1. [Install Docker](https://docs.docker.com/get-docker/) on your machine <add>1. Clone the [with-docker](https://github.com/vercel/next.js/tree/canary/examples/with-docker) example <add>1. Build your container: `docker build -t nextjs-docker .` <add>1. Run your container: `docker run -p 3000:3000 nextjs-docker` <ide> <del># Rebuild the source code only when needed <del>FROM node:alpine AS builder <del>WORKDIR /app <del>COPY . . <del>COPY --from=deps /app/node_modules ./node_modules <del>RUN yarn build && yarn install --production --ignore-scripts --prefer-offline <del> <del># Production image, copy all the files and run next <del>FROM node:alpine AS runner <del>WORKDIR /app <del> <del>ENV NODE_ENV production <del> <del>RUN addgroup -g 1001 -S nodejs <del>RUN adduser -S nextjs -u 1001 <del> <del># You only need to copy next.config.js if you are NOT using the default configuration <del># COPY --from=builder /app/next.config.js ./ <del>COPY --from=builder /app/public ./public <del>COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next <del>COPY --from=builder /app/node_modules ./node_modules <del>COPY --from=builder /app/package.json ./package.json <del> <del>USER nextjs <add>### Static HTML Export <ide> <del>EXPOSE 3000 <add>If you’d like to do a static HTML export of your Next.js app, follow the directions on our [Static HTML Export documentation](/docs/advanced-features/static-html-export.md). <ide> <del>ENV PORT 3000 <add>## Automatic Updates <ide> <del># Next.js collects completely anonymous telemetry data about general usage. <del># Learn more here: https://nextjs.org/telemetry <del># Uncomment the following line in case you want to disable telemetry. <del># ENV NEXT_TELEMETRY_DISABLED 1 <add>When you deploy your Next.js application, you want to see the latest version without needing to reload. <ide> <del>CMD ["node_modules/.bin/next", "start"] <del>``` <add>Next.js will automatically load the latest version of your application in the background when routing. For client-side navigations, `next/link` will temporarily function as a normal `<a>` tag. <ide> <del>Make sure to place this Dockerfile in the root folder of your project. <add>**Note:** If a new page (with an old version) has already been prefetched by `next/link`, Next.js will use the old version. Navigating to a page that has _not_ been prefetched (and is not cached at the CDN level) will load the latest version. <ide> <del>You can build your container with `docker build . -t my-next-js-app` and run it with `docker run -p 3000:3000 my-next-js-app`. <add>## Related <ide> <del>### Static HTML Export <add>For more information on what to do next, we recommend the following sections: <ide> <del>If you’d like to do a static HTML export of your Next.js app, follow the directions on [our documentation](/docs/advanced-features/static-html-export.md). <add><div class="card"> <add> <a href="/docs/going-to-production.md"> <add> <b>Going to Production:</b> <add> <small>Ensure the best performance and user experience.</small> <add> </a> <add></div>
1
Go
Go
prevent panic on network attach
651e694508563e6fb3e8f5d7037641cc136b2c44
<ide><path>daemon/container_operations.go <ide> func (daemon *Daemon) buildSandboxOptions(container *container.Container) ([]lib <ide> <ide> func (daemon *Daemon) updateNetworkSettings(container *container.Container, n libnetwork.Network, endpointConfig *networktypes.EndpointSettings) error { <ide> if container.NetworkSettings == nil { <del> container.NetworkSettings = &network.Settings{Networks: make(map[string]*network.EndpointSettings)} <add> container.NetworkSettings = &network.Settings{} <add> } <add> if container.NetworkSettings.Networks == nil { <add> container.NetworkSettings.Networks = make(map[string]*network.EndpointSettings) <ide> } <ide> <ide> if !container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
1
Python
Python
fix typo in docstring
7f09d45efb7d0d0e8f43b9c2975caa6be0fda00d
<ide><path>keras/engine/topology.py <ide> def Input(shape=None, batch_shape=None, <ide> attributes that allow us to build a Keras model <ide> just by knowing the inputs and outputs of the model. <ide> <del> For instance, if a, b and c and Keras tensors, <add> For instance, if a, b and c are Keras tensors, <ide> it becomes possible to do: <ide> `model = Model(input=[a, b], output=c)` <ide>
1
Text
Text
fix typos in n-api, tls and worker_threads
0c6ac2deb3f3e11e9d36740107564286a5cbe6a6
<ide><path>doc/api/n-api.md <ide> the native addon will also need to have a C/C++ toolchain installed. <ide> <ide> For Linux developers, the necessary C/C++ toolchain packages are readily <ide> available. [GCC][] is widely used in the Node.js community to build and <del>test across a variety of plarforms. For many developers, the [LLVM][] <add>test across a variety of platforms. For many developers, the [LLVM][] <ide> compiler infrastructure is also a good choice. <ide> <ide> For Mac developers, [Xcode][] offers all the required compiler tools. <ide><path>doc/api/tls.md <ide> all sessions). Methods implementing this technique are called "ephemeral". <ide> Currently two methods are commonly used to achieve perfect forward secrecy (note <ide> the character "E" appended to the traditional abbreviations): <ide> <del>* [DHE][]: An ephemeral version of the Diffie Hellman key-agreement protocol. <del>* [ECDHE][]: An ephemeral version of the Elliptic Curve Diffie Hellman <add>* [DHE][]: An ephemeral version of the Diffie-Hellman key-agreement protocol. <add>* [ECDHE][]: An ephemeral version of the Elliptic Curve Diffie-Hellman <ide> key-agreement protocol. <ide> <ide> Ephemeral methods may have some performance drawbacks, because key generation <ide> changes: <ide> client certificate. <ide> * `crl` {string|string[]|Buffer|Buffer[]} PEM formatted CRLs (Certificate <ide> Revocation Lists). <del> * `dhparam` {string|Buffer} Diffie Hellman parameters, required for <add> * `dhparam` {string|Buffer} Diffie-Hellman parameters, required for <ide> [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters. <ide> The key length must be greater than or equal to 1024 bits or else an error <ide> will be thrown. Although 1024 bits is permissible, use 2048 bits or larger <ide><path>doc/api/worker_threads.md <ide> const { port1 } = new MessageChannel(); <ide> port1.postMessage(typedArray1, [ typedArray1.buffer ]); <ide> <ide> // The following line prints the contents of typedArray1 -- it still owns its <del>// memory and has been cloned, not transfered. Without `markAsUntransferable()`, <add>// memory and has been cloned, not transferred. Without `markAsUntransferable()`, <ide> // this would print an empty Uint8Array. typedArray2 is intact as well. <ide> console.log(typedArray1); <ide> console.log(typedArray2);
3
Javascript
Javascript
improve sample app
03cb5aca3f5b8594287608265d4bde7104f07b87
<ide><path>template/App.js <ide> import { <ide> ReloadInstructions, <ide> } from 'react-native/Libraries/NewAppScreen'; <ide> <del>/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's <del> * LTI update could not be added via codemod */ <del>const Section = ({children, title}): Node => { <add>const styles = StyleSheet.create({ <add> sectionContainer: { <add> marginTop: 32, <add> paddingHorizontal: 24, <add> }, <add> sectionTitle: { <add> fontSize: 24, <add> fontWeight: '600', <add> }, <add> sectionDescription: { <add> marginTop: 8, <add> fontSize: 18, <add> fontWeight: '400', <add> }, <add> highlight: { <add> fontWeight: '700', <add> }, <add>}); <add> <add>type SectionProps = { <add> title: string, <add> children: Node, <add>}; <add> <add>function Section({children, title}: SectionProps): Node { <ide> const isDarkMode = useColorScheme() === 'dark'; <ide> return ( <ide> <View style={styles.sectionContainer}> <ide> const Section = ({children, title}): Node => { <ide> </Text> <ide> </View> <ide> ); <del>}; <add>} <ide> <del>const App: () => Node = () => { <add>export default function App(): Node { <ide> const isDarkMode = useColorScheme() === 'dark'; <ide> <ide> const backgroundStyle = { <ide> const App: () => Node = () => { <ide> </ScrollView> <ide> </SafeAreaView> <ide> ); <del>}; <del> <del>const styles = StyleSheet.create({ <del> sectionContainer: { <del> marginTop: 32, <del> paddingHorizontal: 24, <del> }, <del> sectionTitle: { <del> fontSize: 24, <del> fontWeight: '600', <del> }, <del> sectionDescription: { <del> marginTop: 8, <del> fontSize: 18, <del> fontWeight: '400', <del> }, <del> highlight: { <del> fontWeight: '700', <del> }, <del>}); <del> <del>export default App; <add>}
1
Javascript
Javascript
pass jslint, 2 missing semicolons
d28922bc03ea03dd7f02bbc4abc8061ea4c7305b
<ide><path>src/attributes.js <ide> jQuery.extend({ <ide> name = jQuery.attrFix[ name ] || name; <ide> <ide> if ( jQuery.support.getSetAttribute ) { <del> elem.removeAttribute( name ) <add> elem.removeAttribute( name ); <ide> } else { <ide> // set property to null if getSetAttribute not supported (IE6-7) <ide> // setting className to null makes the class "null" <ide> if ( name === "className" ) { <del> elem.className = "" <add> elem.className = ""; <ide> } else { <ide> elem.setAttribute( name, null ); <ide> }
1
Mixed
Java
add support for shadowcolor on android (api >= 28)
cfa42605989eee5a9de42bdb1259fb7f4d9451fb
<ide><path>Libraries/StyleSheet/StyleSheetTypes.js <ide> type ____TransformStyle_Internal = $ReadOnly<{| <ide> * Because they are dynamically generated, they may cause performance regressions. Static <ide> * shadow image asset may be a better way to go for optimal performance. <ide> * <del> * These properties are iOS only - for similar functionality on Android, use the [`elevation` <del> * property](docs/viewstyleproptypes.html#elevation). <add> * Shadow-related properties are not fully supported on Android. <add> * To add a drop shadow to a view use the [`elevation` property](docs/viewstyleproptypes.html#elevation) (Android 5.0+). <add> * To customize the color use the [`shadowColor` property](docs/shadow-props.html#shadowColor) (Android 9.0+). <ide> */ <ide> export type ____ShadowStyle_Internal = $ReadOnly<{| <ide> /** <ide><path>RNTester/js/examples/BoxShadow/BoxShadowExample.js <ide> const styles = StyleSheet.create({ <ide> margin: 8, <ide> backgroundColor: 'red', <ide> }, <add> <add> elevation1: { <add> elevation: 1, <add> }, <add> elevation2: { <add> elevation: 3, <add> }, <add> elevation3: { <add> elevation: 10, <add> }, <add> shadowColor1: { <add> shadowColor: 'red', <add> }, <add> shadowColor2: { <add> shadowColor: 'blue', <add> }, <add> shadowColor3: { <add> shadowColor: '#00FF0080', <add> }, <add> border: { <add> borderWidth: 5, <add> borderColor: '#EEE', <add> }, <ide> }); <ide> <ide> exports.title = 'Box Shadow'; <ide> exports.examples = [ <ide> ); <ide> }, <ide> }, <add> <add> { <add> title: 'Basic elevation', <add> description: 'elevation: 1, 3, 6', <add> platform: 'android', <add> render() { <add> return ( <add> <View style={styles.wrapper}> <add> <View style={[styles.box, styles.elevation1]} /> <add> <View style={[styles.box, styles.elevation2]} /> <add> <View style={[styles.box, styles.elevation3]} /> <add> </View> <add> ); <add> }, <add> }, <add> { <add> title: 'Fractional elevation', <add> description: 'elevation: 0.1, 0.5, 1.5', <add> platform: 'android', <add> render() { <add> return ( <add> <View style={styles.wrapper}> <add> <View style={[styles.box, {elevation: 0.1}]} /> <add> <View style={[styles.box, {elevation: 0.5}]} /> <add> <View style={[styles.box, {elevation: 1.5}]} /> <add> </View> <add> ); <add> }, <add> }, <add> { <add> title: 'Colored shadow', <add> description: "shadowColor: 'red', 'blue', '#00FF0080'", <add> platform: 'android', <add> render() { <add> return ( <add> <View style={styles.wrapper}> <add> <View style={[styles.box, styles.elevation1, styles.shadowColor1]} /> <add> <View style={[styles.box, styles.elevation2, styles.shadowColor2]} /> <add> <View style={[styles.box, styles.elevation3, styles.shadowColor3]} /> <add> </View> <add> ); <add> }, <add> }, <add> { <add> title: 'Shaped shadow', <add> description: 'borderRadius: 50', <add> platform: 'android', <add> render() { <add> return ( <add> <View style={styles.wrapper}> <add> <View style={[styles.box, styles.elevation1, styles.shadowShaped]} /> <add> <View style={[styles.box, styles.elevation2, styles.shadowShaped]} /> <add> <View style={[styles.box, styles.elevation3, styles.shadowShaped]} /> <add> </View> <add> ); <add> }, <add> }, <add> { <add> title: 'Borders', <add> description: 'borderWidth: 5', <add> platform: 'android', <add> render() { <add> return ( <add> <View style={styles.wrapper}> <add> <View style={[styles.box, styles.elevation1, styles.border]} /> <add> <View style={[styles.box, styles.elevation2, styles.border]} /> <add> <View style={[styles.box, styles.elevation3, styles.border]} /> <add> </View> <add> ); <add> }, <add> }, <ide> ]; <ide><path>RNTester/js/utils/RNTesterList.android.js <ide> const APIExamples: Array<RNTesterExample> = [ <ide> key: 'BorderExample', <ide> module: require('../examples/Border/BorderExample'), <ide> }, <add> { <add> key: 'BoxShadowExample', <add> module: require('../examples/BoxShadow/BoxShadowExample'), <add> }, <ide> { <ide> key: 'ClipboardExample', <ide> module: require('../examples/Clipboard/ClipboardExample'), <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java <ide> public void setElevation(@NonNull T view, float elevation) { <ide> ViewCompat.setElevation(view, PixelUtil.toPixelFromDIP(elevation)); <ide> } <ide> <add> @Override <add> @ReactProp(name = ViewProps.SHADOW_COLOR, defaultInt = Color.BLACK, customType = "Color") <add> public void setShadowColor(@NonNull T view, int shadowColor) { <add> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { <add> view.setOutlineAmbientShadowColor(shadowColor); <add> view.setOutlineSpotShadowColor(shadowColor); <add> } <add> } <add> <ide> @Override <ide> @ReactProp(name = ViewProps.Z_INDEX) <ide> public void setZIndex(@NonNull T view, float zIndex) { <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManagerAdapter.java <ide> public void setBorderTopRightRadius(@NonNull T view, float borderRadius) {} <ide> @Override <ide> public void setElevation(@NonNull T view, float elevation) {} <ide> <add> @Override <add> public void setShadowColor(@NonNull T view, int shadowColor) {} <add> <ide> @Override <ide> public void setImportantForAccessibility( <ide> @NonNull T view, @Nullable String importantForAccessibility) {} <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManagerDelegate.java <ide> public void setProperty(T view, String propName, @Nullable Object value) { <ide> case ViewProps.ELEVATION: <ide> mViewManager.setElevation(view, value == null ? 0.0f : ((Double) value).floatValue()); <ide> break; <add> case ViewProps.SHADOW_COLOR: <add> mViewManager.setShadowColor( <add> view, value == null ? 0 : ColorPropConverter.getColor(value, view.getContext())); <add> break; <ide> case ViewProps.IMPORTANT_FOR_ACCESSIBILITY: <ide> mViewManager.setImportantForAccessibility(view, (String) value); <ide> break; <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManagerInterface.java <ide> <ide> void setElevation(T view, float elevation); <ide> <add> void setShadowColor(T view, int shadowColor); <add> <ide> void setImportantForAccessibility(T view, @Nullable String importantForAccessibility); <ide> <ide> void setNativeId(T view, @Nullable String nativeId); <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java <ide> public class ViewProps { <ide> <ide> public static final String TRANSFORM = "transform"; <ide> public static final String ELEVATION = "elevation"; <add> public static final String SHADOW_COLOR = "shadowColor"; <ide> public static final String Z_INDEX = "zIndex"; <ide> public static final String RENDER_TO_HARDWARE_TEXTURE = "renderToHardwareTextureAndroid"; <ide> public static final String ACCESSIBILITY_LABEL = "accessibilityLabel";
8
Text
Text
add links to newer faq entries
23976f491c1dd1d60530eaff17133b6ee05e2b17
<ide><path>docs/FAQ.md <ide> ## Table of Contents <ide> <ide> - **General** <add> - [When should I learn Redux?](/docs/faq/General.md#general-when-to-learn) <ide> - [When should I use Redux?](/docs/faq/General.md#general-when-to-use) <ide> - [Can Redux only be used with React?](/docs/faq/General.md#general-only-react) <ide> - [Do I need to have a particular build tool to use Redux?](/docs/faq/General.md#general-build-tools) <ide> - **Code Structure** <ide> - [What should my file structure look like? How should I group my action creators and reducers in my project? Where should my selectors go?](/docs/faq/CodeStructure.md#structure-file-structure) <ide> - [How should I split my logic between reducers and action creators? Where should my “business logic” go?](/docs/faq/CodeStructure.md#structure-business-logic) <add> - [Why should I use action creators?](/docs/faq/CodeStructure.md#structure-action-creators) <ide> - **Performance** <ide> - [How well does Redux “scale” in terms of performance and architecture?](/docs/faq/Performance.md#performance-scaling) <ide> - [Won't calling “all my reducers” for each action be slow?](/docs/faq/Performance.md#performance-all-reducers) <ide> - [Do I have to deep-clone my state in a reducer? Isn't copying my state going to be slow?](/docs/faq/Performance.md#performance-clone-state) <ide> - [How can I reduce the number of store update events?](/docs/faq/Performance.md#performance-update-events) <ide> - [Will having “one state tree” cause memory problems? Will dispatching many actions take up memory?](/docs/faq/Performance.md#performance-state-memory) <add> - [Will caching remote data cause memory problems?](/docs/faq/Performance.md#performance-cache-memory) <ide> - **Design Decisions** <ide> - [Why doesn't Redux pass the state and action to subscribers?](/docs/faq/DesignDecisions.md#does-not-pass-state-action-to-subscribers) <ide> - [Why doesn't Redux support using classes for actions and reducers?](/docs/faq/DesignDecisions.md#does-not-support-classes)
1
Text
Text
remove extra space on threadpool usage
50329ae22d5bad64ae01902e00fca43b2aff6379
<ide><path>doc/api/fs.md <ide> try { <ide> <ide> ### Threadpool usage <ide> <del>All callback and promise-based file system APIs ( with the exception of <add>All callback and promise-based file system APIs (with the exception of <ide> `fs.FSWatcher()`) use libuv's threadpool. This can have surprising and negative <ide> performance implications for some applications. See the <ide> [`UV_THREADPOOL_SIZE`][] documentation for more information.
1
Text
Text
improve buf.fill() documentation
4545cc17b9b95d20d98e7f4fd851d8a987ca9a9c
<ide><path>doc/api/buffer.md <ide> changes: <ide> description: The `encoding` parameter is supported now. <ide> --> <ide> <del>* `value` {string|Buffer|integer} The value to fill `buf` with. <del>* `offset` {integer} Number of bytes to skip before starting to fill `buf`. **Default:** `0`. <del>* `end` {integer} Where to stop filling `buf` (not inclusive). **Default:** [`buf.length`]. <del>* `encoding` {string} If `value` is a string, this is its encoding. <add>* `value` {string|Buffer|integer} The value with which to fill `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to fill `buf`. <add> **Default:** `0`. <add>* `end` {integer} Where to stop filling `buf` (not inclusive). **Default:** <add> [`buf.length`]. <add>* `encoding` {string} The encoding for `value` if `value` is a string. <ide> **Default:** `'utf8'`. <ide> * Returns: {Buffer} A reference to `buf`. <ide> <ide> Fills `buf` with the specified `value`. If the `offset` and `end` are not given, <del>the entire `buf` will be filled. This is meant to be a small simplification to <del>allow the creation and filling of a `Buffer` to be done on a single line. <add>the entire `buf` will be filled: <ide> <ide> ```js <ide> // Fill a `Buffer` with the ASCII character 'h'. <ide> console.log(b.toString()); <ide> // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh <ide> ``` <ide> <del>`value` is coerced to a `uint32` value if it is not a String or Integer. <add>`value` is coerced to a `uint32` value if it is not a string or integer. <ide> <ide> If the final write of a `fill()` operation falls on a multi-byte character, <del>then only the first bytes of that character that fit into `buf` are written. <add>then only the bytes of that character that fit into `buf` are written: <ide> <ide> ```js <ide> // Fill a `Buffer` with a two-byte character.
1
Python
Python
check trigger_rule syntax
6ed96d6a362aa7d3bec6df19a101279b06cdbfc7
<ide><path>airflow/models.py <ide> def __init__( <ide> logging.warning( <ide> "start_date for {} isn't datetime.datetime".format(self)) <ide> self.end_date = end_date <add> # could add "not callable(attr) " <add> all_triggers = [getattr(TriggerRule, attr) \ <add> for attr in dir(TriggerRule) if not attr.startswith("__")] <add> if trigger_rule not in all_triggers: <add> raise AirflowException( <add> "The trigger_rule must be one of {all_triggers}," <add> "'{d}.{t}'; received '{tr}'.".format(all_triggers=all_triggers, <add> d=dag.dag_id, t=task_id, tr = trigger_rule)) <add> <ide> self.trigger_rule = trigger_rule <ide> self.depends_on_past = depends_on_past <ide> self.wait_for_downstream = wait_for_downstream
1
Ruby
Ruby
allow whitelisting of versioned kibana
4b2eb86bbf5bb0ae76619e67be1bc99e8b68ee40
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_text <ide> problem "\"Formula.factory(name)\" is deprecated in favor of \"Formula[name]\"" <ide> end <ide> <del> if text =~ /system "npm", "install"/ && text !~ %r[opt_libexec\}/npm/bin] && formula.name != "kibana" <add> if text =~ /system "npm", "install"/ && text !~ %r[opt_libexec\}/npm/bin] && formula.name !~ /^kibana(\d{2})?$/ <ide> need_npm = "\#{Formula[\"node\"].opt_libexec\}/npm/bin" <ide> problem <<-EOS.undent <ide> Please add ENV.prepend_path \"PATH\", \"#{need_npm}"\ to def install
1
Python
Python
fix documentation for adamweightdecayconfig
d062cab59e376efc18d25d838cfdb385d1a5cd73
<ide><path>official/modeling/optimization/configs/optimizer_config.py <ide> class AdamWeightDecayConfig(BaseOptimizerConfig): <ide> weight_decay_rate: float. Weight decay rate. Default to 0. <ide> include_in_weight_decay: list[str], or None. List of weight names to include <ide> in weight decay. <del> include_in_weight_decay: list[str], or None. List of weight names to not <add> exclude_from_weight_decay: list[str], or None. List of weight names to not <ide> include in weight decay. <add> gradient_clip_norm: A positive float. Clips the gradients to this maximum <add> L2-norm. Default to 1.0. <ide> """ <ide> name: str = "AdamWeightDecay" <ide> beta_1: float = 0.9
1
PHP
PHP
add test case
e33653a8d7f5910782577ae6bc7518e172938a4c
<ide><path>lib/Cake/Test/Case/Controller/Component/CookieComponentTest.php <ide> public function testReadEmpty() { <ide> $_COOKIE['CakeTestCookie'] = array( <ide> 'JSON' => '{"name":"value"}', <ide> 'Empty' => '', <del> 'String' => '{"somewhat:"broken"}' <add> 'String' => '{"somewhat:"broken"}', <add> 'Array' => '{}' <ide> ); <ide> $this->assertEquals(array('name' => 'value'), $this->Cookie->read('JSON')); <ide> $this->assertEquals('value', $this->Cookie->read('JSON.name')); <ide> $this->assertEquals('', $this->Cookie->read('Empty')); <ide> $this->assertEquals('{"somewhat:"broken"}', $this->Cookie->read('String')); <add> $this->assertEquals(array(), $this->Cookie->read('Array')); <ide> } <ide> <ide> /**
1
Javascript
Javascript
capture onlyhandlers in jquery.event.istrigger
3f05afbd8d9bbc75d30b68e720324d1ed984a315
<ide><path>src/event.js <ide> jQuery.event = { <ide> event : <ide> new jQuery.Event( type, typeof event === "object" && event ); <ide> <del> event.isTrigger = true; <add> // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) <add> event.isTrigger = onlyHandlers ? 2 : 3; <ide> event.namespace = namespaces.join("."); <ide> event.namespace_re = event.namespace ? <ide> new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : <ide><path>test/unit/event.js <ide> test("jQuery.Event( type, props )", function() { <ide> <ide> }); <ide> <del>test("jQuery.Event.currentTarget", function(){ <del> expect(2); <add>test("jQuery.Event properties", function(){ <add> expect(12); <ide> <del> jQuery("<div><p><button>shiny</button></p></div>") <del> .on( "click", "p", function( e ){ <del> equal( e.currentTarget, this, "Check delegated currentTarget on event" ); <del> }) <del> .find( "button" ) <del> .on( "click", function( e ){ <del> equal( e.currentTarget, this, "Check currentTarget on event" ); <del> }) <del> .trigger("click") <del> .off( "click" ) <del> .end() <del> .off( "click" ); <add> var handler, <add> $structure = jQuery("<div id='ancestor'><p id='delegate'><span id='target'>shiny</span></p></div>"), <add> $target = $structure.find("#target"); <add> <add> handler = function( e ) { <add> strictEqual( e.currentTarget, this, "currentTarget at " + this.id ); <add> equal( e.isTrigger, 3, "trigger at " + this.id ); <add> }; <add> $structure.one( "click", handler ); <add> $structure.one( "click", "p", handler ); <add> $target.one( "click", handler ); <add> $target[0].onclick = function( e ) { <add> strictEqual( e.currentTarget, this, "currentTarget at target (native handler)" ); <add> equal( e.isTrigger, 3, "trigger at target (native handler)" ); <add> }; <add> $target.trigger("click"); <add> <add> $target.one( "click", function( e ) { <add> equal( e.isTrigger, 2, "triggerHandler at target" ); <add> }); <add> $target[0].onclick = function( e ) { <add> equal( e.isTrigger, 2, "triggerHandler at target (native handler)" ); <add> }; <add> $target.triggerHandler("click"); <add> <add> handler = function( e ) { <add> strictEqual( e.isTrigger, undefined, "native event at " + this.id ); <add> }; <add> $target.one( "click", handler ); <add> $target[0].onclick = function( e ) { <add> strictEqual( e.isTrigger, undefined, "native event at target (native handler)" ); <add> }; <add> fireNative( $target[0], "click" ); <ide> }); <ide> <ide> test(".delegate()/.undelegate()", function() {
2
Ruby
Ruby
add missing # [ci skip]
26e89c7f95f8a99c3174dc2d1f43aa05397dc719
<ide><path>actionview/lib/action_view/helpers/tag_helper.rb <ide> def method_missing(called, *args, **options, &block) <ide> # # => <input type="text" aria-label="Search"> <ide> # <ide> # <button <%= tag.attributes id: "call-to-action", disabled: false, aria: { expanded: false } %> class="primary">Get Started!</button> <del> # => <button id="call-to-action" aria-expanded="false" class="primary">Get Started!</button> <add> # # => <button id="call-to-action" aria-expanded="false" class="primary">Get Started!</button> <ide> # <ide> # === Legacy syntax <ide> #
1
Ruby
Ruby
remove obsolete comment about download_strategy
62d25f9c8bb8f0471394bc6dad5d82abb163e1cb
<ide><path>Library/Homebrew/formula.rb <ide> def build; self.class.build; end <ide> <ide> def opt_prefix; HOMEBREW_PREFIX/:opt/name end <ide> <del> # Use the @active_spec to detect the download strategy. <del> # Can be overriden to force a custom download strategy <ide> def download_strategy <ide> @active_spec.download_strategy <ide> end
1
Text
Text
correct a typo in readme
7627b8b6d9ef6e57dbd20a55b946bd1991c1223e
<ide><path>README.md <ide> Following are some commands that can be used there: <ide> * `Ctrl + Alt + M` - automerge as much as possible <ide> * `b` - jump to next merge conflict <ide> * `s` - change the order of the conflicted lines <del>* `u` - undo an merge <add>* `u` - undo a merge <ide> * `left mouse button` - mark a block to be the winner <ide> * `middle mouse button` - mark a line to be the winner <ide> * `Ctrl + S` - save
1
Javascript
Javascript
remove extra returns tag
c2c60ab49af22381e77641d61151563785e97a97
<ide><path>docs/collect.js <ide> var TAG = { <ide> 'function': valueTag, <ide> description: markdownTag, <ide> TODO: markdownTag, <del> returns: markdownTag, <ide> paramDescription: markdownTag, <ide> exampleDescription: markdownTag, <ide> element: valueTag,
1
Go
Go
use a regular "defer" to log container event
952902efbcea04a619c4d8c763eecf7fbfeecd85
<ide><path>daemon/stop.go <ide> func (daemon *Daemon) ContainerStop(name string, timeout *int) error { <ide> } <ide> <ide> // containerStop sends a stop signal, waits, sends a kill signal. <del>func (daemon *Daemon) containerStop(ctr *container.Container, seconds *int) error { <add>func (daemon *Daemon) containerStop(ctr *container.Container, seconds *int) (retErr error) { <ide> // TODO propagate a context down to this function <ide> ctx := context.TODO() <ide> if !ctr.IsRunning() { <ide> func (daemon *Daemon) containerStop(ctr *container.Container, seconds *int) erro <ide> if stopTimeout >= 0 { <ide> wait = time.Duration(stopTimeout) * time.Second <ide> } <del> success := func() error { <del> daemon.LogContainerEvent(ctr, "stop") <del> return nil <del> } <add> defer func() { <add> if retErr == nil { <add> daemon.LogContainerEvent(ctr, "stop") <add> } <add> }() <ide> <ide> // 1. Send a stop signal <ide> err := daemon.killPossiblyDeadProcess(ctr, stopSignal) <ide> func (daemon *Daemon) containerStop(ctr *container.Container, seconds *int) erro <ide> <ide> if status := <-ctr.Wait(subCtx, container.WaitConditionNotRunning); status.Err() == nil { <ide> // container did exit, so ignore any previous errors and return <del> return success() <add> return nil <ide> } <ide> <ide> if err != nil { <ide> func (daemon *Daemon) containerStop(ctr *container.Container, seconds *int) erro <ide> } <ide> <ide> logrus.WithField("container", ctr.ID).Infof("Container failed to exit within %s of signal %d - using the force", wait, stopSignal) <del> // Stop either failed or container didnt exit, so fallback to kill. <add> <add> // Stop either failed or container didn't exit, so fallback to kill. <ide> if err := daemon.Kill(ctr); err != nil { <ide> // got a kill error, but give container 2 more seconds to exit just in case <ide> subCtx, cancel := context.WithTimeout(ctx, 2*time.Second) <ide> defer cancel() <del> if status := <-ctr.Wait(subCtx, container.WaitConditionNotRunning); status.Err() == nil { <del> // container did exit, so ignore error and return <del> return success() <add> status := <-ctr.Wait(subCtx, container.WaitConditionNotRunning) <add> if status.Err() != nil { <add> logrus.WithError(err).WithField("container", ctr.ID).Errorf("error killing container: %v", status.Err()) <add> return err <ide> } <del> logrus.WithError(err).WithField("container", ctr.ID).Error("Error killing the container") <del> return err <add> // container did exit, so ignore previous errors and continue <ide> } <ide> <del> return success() <add> return nil <ide> }
1
Python
Python
add problem 31 solution
683474c64b4ad4c423aafcb967ac3897046a46bf
<ide><path>Project Euler/Problem 31/sol1.py <add># -*- coding: utf-8 -*- <add>from __future__ import print_function <add>try: <add> raw_input # Python 2 <add>except NameError: <add> raw_input = input # Python 3 <add>''' <add>Coin sums <add>Problem 31 <add>In England the currency is made up of pound, £, and pence, p, and there are <add>eight coins in general circulation: <add> <add>1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). <add>It is possible to make £2 in the following way: <add> <add>1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p <add>How many different ways can £2 be made using any number of coins? <add>''' <add> <add> <add>def one_pence(): <add> return 1 <add> <add> <add>def two_pence(x): <add> return 0 if x < 0 else two_pence(x - 2) + one_pence() <add> <add> <add>def five_pence(x): <add> return 0 if x < 0 else five_pence(x - 5) + two_pence(x) <add> <add> <add>def ten_pence(x): <add> return 0 if x < 0 else ten_pence(x - 10) + five_pence(x) <add> <add> <add>def twenty_pence(x): <add> return 0 if x < 0 else twenty_pence(x - 20) + ten_pence(x) <add> <add> <add>def fifty_pence(x): <add> return 0 if x < 0 else fifty_pence(x - 50) + twenty_pence(x) <add> <add> <add>def one_pound(x): <add> return 0 if x < 0 else one_pound(x - 100) + fifty_pence(x) <add> <add> <add>def two_pound(x): <add> return 0 if x < 0 else two_pound(x - 200) + one_pound(x) <add> <add> <add>print(two_pound(200))
1
Java
Java
register runtime hints for activeprofilesresolvers
a68d4ae25ca3225c1c236718330964fe116dddf6
<ide><path>spring-test/src/main/java/org/springframework/test/context/aot/hint/StandardTestRuntimeHints.java <ide> import java.util.List; <ide> <ide> import org.springframework.aot.hint.RuntimeHints; <add>import org.springframework.core.annotation.MergedAnnotations; <add>import org.springframework.test.context.ActiveProfiles; <add>import org.springframework.test.context.ActiveProfilesResolver; <ide> import org.springframework.test.context.ContextLoader; <ide> import org.springframework.test.context.MergedContextConfiguration; <add>import org.springframework.test.context.TestContextAnnotationUtils; <ide> import org.springframework.test.context.aot.TestRuntimeHintsRegistrar; <ide> import org.springframework.test.context.web.WebMergedContextConfiguration; <ide> <ide> import static org.springframework.aot.hint.MemberCategory.INVOKE_DECLARED_CONSTRUCTORS; <add>import static org.springframework.core.annotation.MergedAnnotations.SearchStrategy.TYPE_HIERARCHY; <ide> import static org.springframework.util.ResourceUtils.CLASSPATH_URL_PREFIX; <ide> <ide> /** <ide> public void registerHints(RuntimeHints runtimeHints, MergedContextConfiguration <ide> List<Class<?>> testClasses, ClassLoader classLoader) { <ide> <ide> registerHintsForMergedContextConfiguration(runtimeHints, mergedConfig); <add> testClasses.forEach(testClass -> registerHintsForActiveProfilesResolvers(runtimeHints, testClass)); <ide> } <ide> <ide> private void registerHintsForMergedContextConfiguration( <ide> private void registerHintsForMergedContextConfiguration( <ide> } <ide> } <ide> <add> private void registerHintsForActiveProfilesResolvers(RuntimeHints runtimeHints, Class<?> testClass) { <add> // @ActiveProfiles(resolver = ...) <add> MergedAnnotations.search(TYPE_HIERARCHY) <add> .withEnclosingClasses(TestContextAnnotationUtils::searchEnclosingClass) <add> .from(testClass) <add> .stream(ActiveProfiles.class) <add> .map(mergedAnnotation -> mergedAnnotation.getClass("resolver")) <add> .filter(type -> type != ActiveProfilesResolver.class) <add> .forEach(resolverClass -> registerDeclaredConstructors(runtimeHints, resolverClass)); <add> } <add> <ide> private void registerDeclaredConstructors(RuntimeHints runtimeHints, Class<?> type) { <ide> runtimeHints.reflection().registerType(type, INVOKE_DECLARED_CONSTRUCTORS); <ide> } <ide><path>spring-test/src/test/java/org/springframework/test/context/aot/TestContextAotGeneratorTests.java <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.ApplicationContextInitializer; <ide> import org.springframework.context.ConfigurableApplicationContext; <add>import org.springframework.core.env.Profiles; <ide> import org.springframework.javapoet.ClassName; <ide> import org.springframework.test.context.MergedContextConfiguration; <ide> import org.springframework.test.context.aot.samples.basic.BasicSpringJupiterSharedConfigTests; <ide> private static void assertRuntimeHints(RuntimeHints runtimeHints) { <ide> Stream.of( <ide> // @BootstrapWith <ide> org.springframework.test.context.aot.samples.basic.BasicSpringVintageTests.CustomXmlBootstrapper.class, <del> // @ContextConfiguration(initializers=...) <add> // @ContextConfiguration(initializers = ...) <ide> org.springframework.test.context.aot.samples.basic.BasicSpringTestNGTests.CustomInitializer.class, <del> // @ContextConfiguration(loader=...) <del> org.springframework.test.context.support.AnnotationConfigContextLoader.class <add> // @ContextConfiguration(loader = ...) <add> org.springframework.test.context.support.AnnotationConfigContextLoader.class, <add> // @ActiveProfiles(resolver = ...) <add> org.springframework.test.context.aot.samples.basic.SpanishActiveProfilesResolver.class <ide> ).forEach(type -> assertReflectionRegistered(runtimeHints, type, INVOKE_DECLARED_CONSTRUCTORS)); <ide> <del> // @ContextConfiguration(locations=...) <add> // @ContextConfiguration(locations = ...) <ide> assertThat(resource().forResource("/org/springframework/test/context/aot/samples/xml/test-config.xml")) <ide> .accepts(runtimeHints); <ide> <ide> private void assertContextForBasicTests(ApplicationContext context) { <ide> assertThat(context.getEnvironment().getProperty("test.engine")).as("Environment").isNotNull(); <ide> <ide> MessageService messageService = context.getBean(MessageService.class); <del> assertThat(messageService.generateMessage()).isEqualTo("Hello, AOT!"); <add> ConfigurableApplicationContext cac = (ConfigurableApplicationContext) context; <add> String expectedMessage = cac.getEnvironment().acceptsProfiles(Profiles.of("spanish")) ? <add> "¡Hola, AOT!" : "Hello, AOT!"; <add> assertThat(messageService.generateMessage()).isEqualTo(expectedMessage); <ide> } <ide> <ide> private void assertContextForBasicWebTests(WebApplicationContext wac) throws Exception { <ide><path>spring-test/src/test/java/org/springframework/test/context/aot/samples/basic/BasicSpringJupiterTests.java <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.beans.factory.annotation.Value; <ide> import org.springframework.context.ApplicationContext; <add>import org.springframework.test.context.ActiveProfiles; <ide> import org.springframework.test.context.TestExecutionListeners; <ide> import org.springframework.test.context.TestPropertySource; <ide> import org.springframework.test.context.aot.samples.basic.BasicSpringJupiterTests.DummyExtension; <ide> void test(@Autowired ApplicationContext context, @Autowired MessageService messa <ide> <ide> @Nested <ide> @TestPropertySource(properties = "foo=bar") <add> @ActiveProfiles(resolver = SpanishActiveProfilesResolver.class) <ide> public class NestedTests { <ide> <ide> @org.junit.jupiter.api.Test <ide> void test(@Autowired ApplicationContext context, @Autowired MessageService messageService, <ide> @Value("${test.engine}") String testEngine, @Value("${foo}") String foo) { <del> assertThat(messageService.generateMessage()).isEqualTo("Hello, AOT!"); <add> assertThat(messageService.generateMessage()).isEqualTo("¡Hola, AOT!"); <ide> assertThat(foo).isEqualTo("bar"); <ide> assertThat(testEngine).isEqualTo("jupiter"); <ide> assertThat(context.getEnvironment().getProperty("test.engine")) <ide><path>spring-test/src/test/java/org/springframework/test/context/aot/samples/basic/BasicTestConfiguration.java <ide> <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <add>import org.springframework.context.annotation.Profile; <ide> import org.springframework.test.context.aot.samples.common.DefaultMessageService; <ide> import org.springframework.test.context.aot.samples.common.MessageService; <add>import org.springframework.test.context.aot.samples.common.SpanishMessageService; <ide> <ide> /** <ide> * @author Sam Brannen <ide> class BasicTestConfiguration { <ide> <ide> @Bean <del> MessageService messageService() { <add> @Profile("default") <add> MessageService defaultMessageService() { <ide> return new DefaultMessageService(); <ide> } <ide> <add> @Bean <add> @Profile("spanish") <add> MessageService spanishMessageService() { <add> return new SpanishMessageService(); <add> } <add> <ide> } <ide><path>spring-test/src/test/java/org/springframework/test/context/aot/samples/basic/SpanishActiveProfilesResolver.java <add>/* <add> * Copyright 2002-2022 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> * https://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.test.context.aot.samples.basic; <add> <add>import org.springframework.test.context.ActiveProfilesResolver; <add> <add>/** <add> * @author Sam Brannen <add> * @since 6.0 <add> */ <add>public class SpanishActiveProfilesResolver implements ActiveProfilesResolver { <add> <add> @Override <add> public String[] resolve(Class<?> testClass) { <add> return new String[] { "spanish" }; <add> } <add> <add>} <ide><path>spring-test/src/test/java/org/springframework/test/context/aot/samples/common/SpanishMessageService.java <add>/* <add> * Copyright 2002-2022 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> * https://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.test.context.aot.samples.common; <add> <add>/** <add> * @author Sam Brannen <add> * @since 6.0 <add> */ <add>public class SpanishMessageService implements MessageService { <add> <add> @Override <add> public String generateMessage() { <add> return "¡Hola, AOT!"; <add> } <add> <add>}
6
Text
Text
add documentation link in sequential model.
0b2c044d48a335e97ffef4b6c76031fa12627ec9
<ide><path>docs/templates/getting-started/sequential-model-guide.md <ide> model.compile(optimizer='rmsprop', <ide> <ide> ## Training <ide> <del>Keras models are trained on Numpy arrays of input data and labels. For training a model, you will typically use the `fit` function. [Read its documentation here](/models/sequential). <add>Keras models are trained on Numpy arrays of input data and labels. For training a model, you will typically use the `fit` function. [Read its documentation here](/models/sequential). <ide> <ide> ```python <ide> # for a single-input model with 2 classes (binary): <ide> model.fit([data_1, data_2], labels, epochs=10, batch_size=32) <ide> <ide> Here are a few examples to get you started! <ide> <del>In the examples folder, you will also find example models for real datasets: <add>In the [examples folder](https://github.com/fchollet/keras/tree/master/examples), you will also find example models for real datasets: <ide> <ide> - CIFAR10 small images classification: Convolutional Neural Network (CNN) with realtime data augmentation <ide> - IMDB movie review sentiment classification: LSTM over sequences of words
1
Text
Text
add varenc/ffmpeg to list of interesting taps
e295570f00536f65375b74ef732a28b9c76d3997
<ide><path>docs/Interesting-Taps-and-Forks.md <ide> Homebrew has the capability to add (and remove) multiple taps to your local inst <ide> Your taps are Git repositories located at `$(brew --repository)/Library/Taps`. <ide> <ide> ## Unsupported interesting taps <add>* [varenc/ffmpeg](https://github.com/varenc/homebrew-ffmpeg): A tap for FFmpeg with additional options, including nonfree additions. <ide> <ide> * [denji/nginx](https://github.com/denji/homebrew-nginx): A tap for NGINX modules, intended for its `nginx-full` formula which includes more module options. <ide>
1
Javascript
Javascript
allow shared reused dgram sockets
c7be08cec18b0591381126e149cac96a05125966
<ide><path>lib/cluster.js <ide> Worker.prototype.isConnected = function isConnected() { <ide> <ide> // Master/worker specific methods are defined in the *Init() functions. <ide> <del>function SharedHandle(key, address, port, addressType, backlog, fd) { <add>function SharedHandle(key, address, port, addressType, backlog, fd, flags) { <ide> this.key = key; <ide> this.workers = []; <ide> this.handle = null; <ide> function SharedHandle(key, address, port, addressType, backlog, fd) { <ide> // FIXME(bnoordhuis) Polymorphic return type for lack of a better solution. <ide> var rval; <ide> if (addressType === 'udp4' || addressType === 'udp6') <del> rval = dgram._createSocketHandle(address, port, addressType, fd); <add> rval = dgram._createSocketHandle(address, port, addressType, fd, flags); <ide> else <ide> rval = net._createServerHandle(address, port, addressType, fd); <ide> <ide> function masterInit() { <ide> var args = [message.address, <ide> message.port, <ide> message.addressType, <del> message.fd]; <add> message.fd, <add> message.index]; <ide> var key = args.join(':'); <ide> var handle = handles[key]; <ide> if (handle === undefined) { <ide> function masterInit() { <ide> message.port, <ide> message.addressType, <ide> message.backlog, <del> message.fd); <add> message.fd, <add> message.flags); <ide> } <ide> if (!handle.data) handle.data = message.data; <ide> <ide> function masterInit() { <ide> cluster.emit('listening', worker, info); <ide> } <ide> <del> // Round-robin only. Server in worker is closing, remove from list. <add> // Server in worker is closing, remove from list. <ide> function close(worker, message) { <ide> var key = message.key; <ide> var handle = handles[key]; <ide> function masterInit() { <ide> <ide> function workerInit() { <ide> var handles = {}; <add> var indexes = {}; <ide> <ide> // Called from src/node.js <ide> cluster._setupWorker = function() { <ide> function workerInit() { <ide> }; <ide> <ide> // obj is a net#Server or a dgram#Socket object. <del> cluster._getServer = function(obj, address, port, addressType, fd, cb) { <del> var message = { <del> addressType: addressType, <del> address: address, <del> port: port, <add> cluster._getServer = function(obj, options, cb) { <add> const key = [ options.address, <add> options.port, <add> options.addressType, <add> options.fd ].join(':'); <add> if (indexes[key] === undefined) <add> indexes[key] = 0; <add> else <add> indexes[key]++; <add> <add> const message = util._extend({ <ide> act: 'queryServer', <del> fd: fd, <add> index: indexes[key], <ide> data: null <del> }; <add> }, options); <add> <ide> // Set custom data on handle (i.e. tls tickets key) <ide> if (obj._getServerData) message.data = obj._getServerData(); <ide> send(message, function(reply, handle) { <ide> function workerInit() { <ide> }); <ide> obj.once('listening', function() { <ide> cluster.worker.state = 'listening'; <del> var address = obj.address(); <add> const address = obj.address(); <ide> message.act = 'listening'; <del> message.port = address && address.port || port; <add> message.port = address && address.port || options.port; <ide> send(message); <ide> }); <ide> }; <ide> function workerInit() { <ide> // closed. Avoids resource leaks when the handle is short-lived. <ide> var close = handle.close; <ide> handle.close = function() { <add> send({ act: 'close', key: key }); <ide> delete handles[key]; <ide> return close.apply(this, arguments); <ide> }; <ide><path>lib/dgram.js <ide> function newHandle(type) { <ide> } <ide> <ide> <del>exports._createSocketHandle = function(address, port, addressType, fd) { <add>exports._createSocketHandle = function(address, port, addressType, fd, flags) { <ide> // Opening an existing fd is not supported for UDP handles. <ide> assert(typeof fd !== 'number' || fd < 0); <ide> <ide> var handle = newHandle(addressType); <ide> <ide> if (port || address) { <del> var err = handle.bind(address, port || 0, 0); <add> var err = handle.bind(address, port || 0, flags); <ide> if (err) { <ide> handle.close(); <ide> return err; <ide> Socket.prototype.bind = function(port /*, address, callback*/) { <ide> if (!cluster) <ide> cluster = require('cluster'); <ide> <add> var flags = 0; <add> if (self._reuseAddr) <add> flags |= constants.UV_UDP_REUSEADDR; <add> <ide> if (cluster.isWorker && !exclusive) { <del> cluster._getServer(self, ip, port, self.type, -1, function(err, handle) { <add> function onHandle(err, handle) { <ide> if (err) { <ide> var ex = exceptionWithHostPort(err, 'bind', ip, port); <ide> self.emit('error', ex); <ide> Socket.prototype.bind = function(port /*, address, callback*/) { <ide> <ide> replaceHandle(self, handle); <ide> startListening(self); <del> }); <add> } <add> cluster._getServer(self, { <add> address: ip, <add> port: port, <add> addressType: self.type, <add> fd: -1, <add> flags: flags <add> }, onHandle); <ide> <ide> } else { <ide> if (!self._handle) <ide> return; // handle has been closed in the mean time <ide> <del> var flags = 0; <del> if (self._reuseAddr) <del> flags |= constants.UV_UDP_REUSEADDR; <del> <ide> var err = self._handle.bind(ip, port || 0, flags); <ide> if (err) { <ide> var ex = exceptionWithHostPort(err, 'bind', ip, port); <ide><path>lib/net.js <ide> function listen(self, address, port, addressType, backlog, fd, exclusive) { <ide> return; <ide> } <ide> <del> cluster._getServer(self, address, port, addressType, fd, cb); <add> cluster._getServer(self, { <add> address: address, <add> port: port, <add> addressType: addressType, <add> fd: fd, <add> flags: 0 <add> }, cb); <ide> <ide> function cb(err, handle) { <ide> // EADDRINUSE may not be reported until we call listen(). To complicate <ide><path>test/parallel/test-cluster-dgram-reuse.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const cluster = require('cluster'); <add>const dgram = require('dgram'); <add> <add>if (common.isWindows) { <add> console.log('1..0 # Skipped: dgram clustering is currently not supported ' + <add> 'on windows.'); <add> return; <add>} <add> <add>if (cluster.isMaster) { <add> cluster.fork().on('exit', function(code) { <add> assert.equal(code, 0); <add> }); <add> return; <add>} <add> <add>const sockets = []; <add>function next() { <add> sockets.push(this); <add> if (sockets.length !== 2) <add> return; <add> <add> // Work around health check issue <add> process.nextTick(function() { <add> for (var i = 0; i < sockets.length; i++) <add> sockets[i].close(close); <add> }); <add>} <add> <add>var waiting = 2; <add>function close() { <add> if (--waiting === 0) <add> cluster.worker.disconnect(); <add>} <add> <add>for (var i = 0; i < 2; i++) <add> dgram.createSocket({ type: 'udp4', reuseAddr: true }).bind(common.PORT, next);
4
Python
Python
update the importing logic for cpuinfo and psutil.
03781c74b9decb69e9270edccfac26c92263ab70
<ide><path>official/utils/logging/logger.py <ide> import numbers <ide> import os <ide> <del># pylint: disable=g-bad-import-order <del># Note: cpuinfo and psutil are not installed in the TensorFlow OSS tree. <del># They are installable via pip. <del>import cpuinfo <del>import psutil <del># pylint: enable=g-bad-import-order <del> <ide> import tensorflow as tf <ide> from tensorflow.python.client import device_lib <ide> <ide> def _collect_cpu_info(run_info): <ide> <ide> cpu_info["num_cores"] = multiprocessing.cpu_count() <ide> <add> # Note: cpuinfo is not installed in the TensorFlow OSS tree. <add> # It is installable via pip. <add> import cpuinfo # pylint: disable=g-import-not-at-top <add> <ide> info = cpuinfo.get_cpu_info() <ide> cpu_info["cpu_info"] = info["brand"] <ide> cpu_info["mhz_per_cpu"] = info["hz_advertised_raw"][0] / 1.0e6 <ide> def _collect_gpu_info(run_info): <ide> <ide> <ide> def _collect_memory_info(run_info): <add> # Note: psutil is not installed in the TensorFlow OSS tree. <add> # It is installable via pip. <add> import psutil # pylint: disable=g-import-not-at-top <ide> vmem = psutil.virtual_memory() <ide> run_info["memory_total"] = vmem.total <ide> run_info["memory_available"] = vmem.available
1
Javascript
Javascript
measure callback timeout relative to current time
71c8759cebfadd09cf58748eb1963fe23ec11e4f
<ide><path>packages/react-reconciler/src/ReactFiberScheduler.js <ide> let interruptedBy: Fiber | null = null; <ide> // In other words, because expiration times determine how updates are batched, <ide> // we want all updates of like priority that occur within the same event to <ide> // receive the same expiration time. Otherwise we get tearing. <del>let initialTimeMs: number = now(); <ide> let currentEventTime: ExpirationTime = NoWork; <ide> <ide> export function requestCurrentTime() { <ide> if (workPhase === RenderPhase || workPhase === CommitPhase) { <ide> // We're inside React, so it's fine to read the actual time. <del> return msToExpirationTime(now() - initialTimeMs); <add> return msToExpirationTime(now()); <ide> } <ide> // We're not inside React, so we may be in the middle of a browser event. <ide> if (currentEventTime !== NoWork) { <ide> // Use the same start time for all updates until we enter React again. <ide> return currentEventTime; <ide> } <ide> // This is the first update since React yielded. Compute a new start time. <del> currentEventTime = msToExpirationTime(now() - initialTimeMs); <add> currentEventTime = msToExpirationTime(now()); <ide> return currentEventTime; <ide> } <ide> <ide> function scheduleCallbackForRoot( <ide> cancelCallback(existingCallbackNode); <ide> } <ide> root.callbackExpirationTime = expirationTime; <del> const options = <del> expirationTime === Sync <del> ? null <del> : {timeout: expirationTimeToMs(expirationTime)}; <add> <add> let options = null; <add> if (expirationTime !== Sync && expirationTime !== Never) { <add> let timeout = expirationTimeToMs(expirationTime) - now(); <add> if (timeout > 5000) { <add> // Sanity check. Should never take longer than 5 seconds. <add> // TODO: Add internal warning? <add> timeout = 5000; <add> } <add> options = {timeout}; <add> } <add> <ide> root.callbackNode = scheduleCallback( <ide> priorityLevel, <ide> runRootCallback.bind( <ide> function inferTimeFromExpirationTime(expirationTime: ExpirationTime): number { <ide> // We don't know exactly when the update was scheduled, but we can infer an <ide> // approximate start time from the expiration time. <ide> const earliestExpirationTimeMs = expirationTimeToMs(expirationTime); <del> return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION + initialTimeMs; <add> return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; <ide> } <ide> <ide> function workLoopSync() { <ide> function computeMsUntilTimeout( <ide> <ide> // Compute the time until this render pass would expire. <ide> const timeUntilExpirationMs = <del> expirationTimeToMs(committedExpirationTime) + initialTimeMs - currentTimeMs; <add> expirationTimeToMs(committedExpirationTime) - currentTimeMs; <ide> <ide> // Clamp the timeout to the expiration time. <ide> // TODO: Once the event time is exact instead of inferred from expiration time <ide><path>packages/react-reconciler/src/SchedulerWithReactIntegration.js <ide> export const IdlePriority: ReactPriorityLevel = 95; <ide> // NoPriority is the absence of priority. Also React-only. <ide> export const NoPriority: ReactPriorityLevel = 90; <ide> <del>export const now = Scheduler_now; <ide> export const shouldYield = disableYielding <ide> ? () => false // Never yield when `disableYielding` is on <ide> : Scheduler_shouldYield; <ide> <ide> let immediateQueue: Array<SchedulerCallback> | null = null; <ide> let immediateQueueCallbackNode: mixed | null = null; <ide> let isFlushingImmediate: boolean = false; <add>let initialTimeMs: number = Scheduler_now(); <add> <add>// If the initial timestamp is reasonably small, use Scheduler's `now` directly. <add>// This will be the case for modern browsers that support `performance.now`. In <add>// older browsers, Scheduler falls back to `Date.now`, which returns a Unix <add>// timestamp. In that case, subtract the module initialization time to simulate <add>// the behavior of performance.now and keep our times small enough to fit <add>// within 32 bits. <add>// TODO: Consider lifting this into Scheduler. <add>export const now = <add> initialTimeMs < 10000 ? Scheduler_now : () => Scheduler_now() - initialTimeMs; <ide> <ide> export function getCurrentPriorityLevel(): ReactPriorityLevel { <ide> switch (Scheduler_getCurrentPriorityLevel()) { <ide><path>packages/react-reconciler/src/__tests__/ReactExpiration-test.internal.js <ide> describe('ReactExpiration', () => { <ide> expect(Scheduler).toFlushExpired([]); <ide> expect(ReactNoop).toMatchRenderedOutput('Hi'); <ide> }); <add> <add> it('should measure callback timeout relative to current time, not start-up time', () => { <add> // Corresponds to a bugfix: https://github.com/facebook/react/pull/15479 <add> // The bug wasn't caught by other tests because we use virtual times that <add> // default to 0, and most tests don't advance time. <add> <add> // Before scheduling an update, advance the current time. <add> Scheduler.advanceTime(10000); <add> <add> ReactNoop.render('Hi'); <add> expect(Scheduler).toFlushExpired([]); <add> expect(ReactNoop).toMatchRenderedOutput(null); <add> <add> // Advancing by ~5 seconds should be sufficient to expire the update. (I <add> // used a slightly larger number to allow for possible rounding.) <add> Scheduler.advanceTime(6000); <add> <add> ReactNoop.render('Hi'); <add> expect(Scheduler).toFlushExpired([]); <add> expect(ReactNoop).toMatchRenderedOutput('Hi'); <add> }); <ide> });
3
Javascript
Javascript
remove socket interface from buildbundle command
bc81cc4073812812276981cd91747243d9ae89af
<ide><path>local-cli/bundle/buildBundle.js <ide> const log = require('../util/log').out('bundle'); <ide> const outputBundle = require('./output/bundle'); <ide> const Promise = require('promise'); <del>const ReactPackager = require('../../packager/react-packager'); <ide> const saveAssets = require('./saveAssets'); <add>const Server = require('../../packager/react-packager/src/Server'); <ide> <ide> function saveBundle(output, bundle, args) { <ide> return Promise.resolve( <ide> function buildBundle(args, config, output = outputBundle, packagerInstance) { <ide> blacklistRE: config.getBlacklistRE(args.platform), <ide> getTransformOptionsModulePath: config.getTransformOptionsModulePath, <ide> transformModulePath: args.transformer, <del> verbose: args.verbose, <add> nonPersistent: true, <ide> }; <ide> <ide> const requestOpts = { <ide> function buildBundle(args, config, output = outputBundle, packagerInstance) { <ide> platform: args.platform, <ide> }; <ide> <del> var bundlePromise; <del> if (packagerInstance) { <del> bundlePromise = output.build(packagerInstance, requestOpts) <del> .then(bundle => saveBundle(output, bundle, args)); <del> } else { <del> const clientPromise = ReactPackager.createClientFor(options); <del> <del> // Build and save the bundle <del> bundlePromise = clientPromise <del> .then(client => { <del> log('Created ReactPackager'); <del> return output.build(client, requestOpts); <del> }) <del> .then(bundle => saveBundle(output, bundle, args)); <del> <del> // When we're done bundling, close the client <del> Promise.all([clientPromise, bundlePromise]) <del> .then(([client]) => { <del> log('Closing client'); <del> client.close(); <del> }); <add> // If a packager instance was not provided, then just create one for this <add> // bundle command and close it down afterwards. <add> var shouldClosePackager = false; <add> if (!packagerInstance) { <add> packagerInstance = new Server(options); <add> shouldClosePackager = true; <ide> } <ide> <add> const bundlePromise = output.build(packagerInstance, requestOpts) <add> .then(bundle => { <add> if (shouldClosePackager) { <add> packagerInstance.end(); <add> } <add> return saveBundle(output, bundle, args); <add> }); <add> <ide> // Save the assets of the bundle <ide> const assets = bundlePromise <ide> .then(bundle => bundle.getAssets())
1
Go
Go
modify several fun notes in fsnotify.go
ff2c898652de37f70cd2774a208e61b112d06e1b
<ide><path>pkg/filenotify/fsnotify.go <ide> package filenotify <ide> <ide> import "gopkg.in/fsnotify.v1" <ide> <del>// fsNotify wraps the fsnotify package to satisfy the FileNotifer interface <add>// fsNotifyWatcher wraps the fsnotify package to satisfy the FileNotifer interface <ide> type fsNotifyWatcher struct { <ide> *fsnotify.Watcher <ide> } <ide> <del>// GetEvents returns the fsnotify event channel receiver <add>// Events returns the fsnotify event channel receiver <ide> func (w *fsNotifyWatcher) Events() <-chan fsnotify.Event { <ide> return w.Watcher.Events <ide> } <ide> <del>// GetErrors returns the fsnotify error channel receiver <add>// Errors returns the fsnotify error channel receiver <ide> func (w *fsNotifyWatcher) Errors() <-chan error { <ide> return w.Watcher.Errors <ide> }
1
Python
Python
fix typo in flask shell help
5bfe236fb531045497396bc85ee5026c6c9c68eb
<ide><path>src/flask/cli.py <ide> def run_command( <ide> def shell_command(): <ide> """Run an interactive Python shell in the context of a given <ide> Flask application. The application will populate the default <del> namespace of this shell according to it's configuration. <add> namespace of this shell according to its configuration. <ide> <ide> This is useful for executing small snippets of management code <ide> without having to manually configure the application.
1
Javascript
Javascript
fix regression of virtualizedlist jumpy header
e4fd9babe03d82fcf39ba6a46376f746a8a3e960
<ide><path>Libraries/Lists/VirtualizedList.js <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> if (stickyIndicesFromProps.has(ii + stickyOffset)) { <ide> const initBlock = this._getFrameMetricsApprox(lastInitialIndex); <ide> const stickyBlock = this._getFrameMetricsApprox(ii); <del> const leadSpace = stickyBlock.offset - initBlock.offset; <add> const leadSpace = <add> stickyBlock.offset - <add> initBlock.offset - <add> (this.props.initialScrollIndex ? 0 : initBlock.length); <ide> cells.push( <ide> <View key="$sticky_lead" style={{[spacerKey]: leadSpace}} />, <ide> );
1
Text
Text
fix script name for dlrm model
66264b2353aeeca3d4b340908a9590571495d5a6
<ide><path>official/recommendation/ranking/README.md <ide> Training on GPUs are similar to TPU training. Only distribution strategy needs <ide> to be updated and number of GPUs provided (for 4 GPUs): <ide> <ide> ```shell <del>python3 official/recommendation/ranking/main.py --mode=train_and_eval \ <add>python3 official/recommendation/ranking/train.py --mode=train_and_eval \ <ide> --model_dir=${BUCKET_NAME}/model_dirs/${EXPERIMENT_NAME} --params_override=" <ide> runtime: <ide> distribution_strategy: 'mirrored'
1
Python
Python
improve celery command to use base.command
b8402e30ab325f5d99becc1c5de3b3e5266b9637
<ide><path>celery/__main__.py <add>from __future__ import absolute_import <add> <add>from celery import current_app <add> <add>current_app.start() <ide><path>celery/bin/base.py <ide> def execute_from_commandline(self, argv=None): <ide> prog_name = os.path.basename(argv[0]) <ide> return self.handle_argv(prog_name, argv[1:]) <ide> <del> def usage(self): <add> def usage(self, command): <ide> """Returns the command-line usage string for this app.""" <ide> return "%%prog [options] %s" % (self.args, ) <ide> <ide> def handle_argv(self, prog_name, argv): <ide> and ``argv`` contains positional arguments. <ide> <ide> """ <add> options, args = self.prepare_args(*self.parse_options(prog_name, argv)) <add> return self.run(*args, **options) <ide> <del> options, args = self.parse_options(prog_name, argv) <del> options = dict((k, self.expanduser(v)) <del> for k, v in vars(options).iteritems() <del> if not k.startswith('_')) <del> argv = map(self.expanduser, argv) <add> def prepare_args(self, options, args): <add> if options: <add> options = dict((k, self.expanduser(v)) <add> for k, v in vars(options).iteritems() <add> if not k.startswith('_')) <add> args = map(self.expanduser, args) <ide> self.check_args(args) <del> return self.run(*args, **options) <add> return options, args <ide> <ide> def check_args(self, args): <ide> if not self.supports_args and args: <ide> def parse_options(self, prog_name, arguments): <ide> parser = self.create_parser(prog_name) <ide> return parser.parse_args(arguments) <ide> <del> def create_parser(self, prog_name): <add> def create_parser(self, prog_name, command=None): <ide> return self.prepare_parser(self.Parser(prog=prog_name, <del> usage=self.usage(), <add> usage=self.usage(command), <ide> version=self.version, <ide> option_list=(self.preload_options + <ide> self.get_options()))) <ide><path>celery/bin/celery.py <ide> def command(fun, name=None): <ide> return fun <ide> <ide> <del>class Command(object): <add>class Command(BaseCommand): <ide> help = "" <ide> args = "" <ide> version = __version__ <ide> prog_name = "celery" <ide> <del> option_list = BaseCommand.preload_options + ( <add> option_list = ( <ide> Option("--quiet", "-q", action="store_true"), <ide> Option("--no-color", "-C", action="store_true"), <ide> ) <ide> <ide> def __init__(self, app=None, no_color=False, stdout=sys.stdout, <ide> stderr=sys.stderr): <del> self.app = app_or_default(app) <add> super(Command, self).__init__(app=app) <ide> self.colored = term.colored(enabled=not no_color) <ide> self.stdout = stdout <ide> self.stderr = stderr <ide> def out(self, s, fh=None): <ide> s += "\n" <ide> (fh or self.stdout).write(s) <ide> <del> def create_parser(self, prog_name, command): <del> return OptionParser(prog=prog_name, <del> usage=self.usage(command), <del> version=self.version, <del> option_list=self.get_options()) <del> <del> def get_options(self): <del> return self.option_list <del> <ide> def run_from_argv(self, prog_name, argv): <ide> self.prog_name = prog_name <ide> self.command = argv[0] <ide> self.arglist = argv[1:] <ide> self.parser = self.create_parser(self.prog_name, self.command) <del> options, args = self.parser.parse_args(self.arglist) <del> self.colored = term.colored(enabled=not options.no_color) <del> return self(*args, **options.__dict__) <del> <del> def run(self, *args, **kwargs): <del> raise NotImplementedError() <add> options, args = self.prepare_args( <add> *self.parser.parse_args(self.arglist)) <add> self.colored = term.colored(enabled=not options["no_color"]) <add> return self(*args, **options) <ide> <ide> def usage(self, command): <ide> return "%%prog %s [options] %s" % (command, self.args) <ide> def __init__(self, *args, **kwargs): <ide> def get_options(self): <ide> return self.option_list + self.target.get_options() <ide> <add> def create_parser(self, prog_name, command): <add> parser = super(Delegate, self).create_parser(prog_name, command) <add> return self.target.prepare_parser(parser) <add> <ide> def run(self, *args, **kwargs): <ide> self.target.check_args(args) <ide> return self.target.run(*args, **kwargs) <ide> def remove_options_at_beginning(self, argv, index=0): <ide> def handle_argv(self, prog_name, argv): <ide> self.prog_name = prog_name <ide> argv = self.remove_options_at_beginning(argv) <add> _, argv = self.prepare_args(None, argv) <ide> try: <ide> command = argv[0] <ide> except IndexError:
3
PHP
PHP
fix doc blocks
4a160d8d219b8da18b211809cc0d6ae7fb1c2aa6
<ide><path>src/Illuminate/Auth/Reminders/DatabaseReminderRepository.php <ide> public function __construct(Connection $connection, $table, $hashKey, $expires = <ide> /** <ide> * Create a new reminder record and token. <ide> * <del> * @param \Illuminate\Auth\RemindableInterface $user <add> * @param \Illuminate\Auth\Reminders\RemindableInterface $user <ide> * @return string <ide> */ <ide> public function create(RemindableInterface $user) <ide> protected function getPayload($email, $token) <ide> /** <ide> * Determine if a reminder record exists and is valid. <ide> * <del> * @param \Illuminate\Auth\RemindableInterface $user <add> * @param \Illuminate\Auth\Reminders\RemindableInterface $user <ide> * @param string $token <ide> * @return bool <ide> */ <ide> public function deleteExpired() <ide> /** <ide> * Create a new token for the user. <ide> * <del> * @param \Illuminate\Auth\RemindableInterface $user <add> * @param \Illuminate\Auth\Reminders\RemindableInterface $user <ide> * @return string <ide> */ <ide> public function createNewToken(RemindableInterface $user) <ide><path>src/Illuminate/Auth/Reminders/PasswordBroker.php <ide> public function reset(array $credentials, Closure $callback) <ide> * Validate a password reset for the given credentials. <ide> * <ide> * @param array $credentials <del> * @return \Illuminate\Auth\RemindableInterface <add> * @return \Illuminate\Auth\Reminders\RemindableInterface <ide> */ <ide> protected function validateReset(array $credentials) <ide> { <ide><path>src/Illuminate/Auth/Reminders/ReminderRepositoryInterface.php <ide> interface ReminderRepositoryInterface { <ide> /** <ide> * Create a new reminder record and token. <ide> * <del> * @param \Illuminate\Auth\RemindableInterface $user <add> * @param \Illuminate\Auth\Reminders\RemindableInterface $user <ide> * @return string <ide> */ <ide> public function create(RemindableInterface $user); <ide> <ide> /** <ide> * Determine if a reminder record exists and is valid. <ide> * <del> * @param \Illuminate\Auth\RemindableInterface $user <add> * @param \Illuminate\Auth\Reminders\RemindableInterface $user <ide> * @param string $token <ide> * @return bool <ide> */ <ide><path>src/Illuminate/Database/Connection.php <ide> class Connection implements ConnectionInterface { <ide> /** <ide> * The cache manager instance. <ide> * <del> * @var \Illuminate\Cache\CacheManger <add> * @var \Illuminate\Cache\CacheManager <ide> */ <ide> protected $cache; <ide> <ide><path>src/Illuminate/Database/Connectors/ConnectorInterface.php <ide> interface ConnectorInterface { <ide> * Establish a database connection. <ide> * <ide> * @param array $config <del> * @return PDO <add> * @return \PDO <ide> */ <ide> public function connect(array $config); <ide> <ide><path>src/Illuminate/Database/Connectors/MySqlConnector.php <ide> class MySqlConnector extends Connector implements ConnectorInterface { <ide> * Establish a database connection. <ide> * <ide> * @param array $config <del> * @return PDO <add> * @return \PDO <ide> */ <ide> public function connect(array $config) <ide> { <ide><path>src/Illuminate/Database/Connectors/SQLiteConnector.php <ide> class SQLiteConnector extends Connector implements ConnectorInterface { <ide> * Establish a database connection. <ide> * <ide> * @param array $config <del> * @return PDO <add> * @return \PDO <ide> * <ide> * @throws \InvalidArgumentException <ide> */ <ide><path>src/Illuminate/Database/Console/Migrations/InstallCommand.php <ide> class InstallCommand extends Command { <ide> /** <ide> * The repository instance. <ide> * <del> * @var \Illuminate\Database\Console\Migrations\MigrationRepositoryInterface <add> * @var \Illuminate\Database\Migrations\MigrationRepositoryInterface <ide> */ <ide> protected $repository; <ide> <ide> /** <ide> * Create a new migration install command instance. <ide> * <del> * @param \Illuminate\Database\Console\Migrations\MigrationRepositoryInterface $repository <add> * @param \Illuminate\Database\Migrations\MigrationRepositoryInterface $repository <ide> * @return void <ide> */ <ide> public function __construct(MigrationRepositoryInterface $repository) <ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function newCollection(array $models = array()) <ide> * @param array $attributes <ide> * @param string $table <ide> * @param bool $exists <del> * @return \Illuminate\Database\Eloquent\Relation\Pivot <add> * @return \Illuminate\Database\Eloquent\Relations\Pivot <ide> */ <ide> public function newPivot(Model $parent, array $attributes, $table, $exists) <ide> { <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php <ide> public function newPivotStatementForId($id) <ide> * <ide> * @param array $attributes <ide> * @param bool $exists <del> * @return \Illuminate\Database\Eloquent\Relation\Pivot <add> * @return \Illuminate\Database\Eloquent\Relations\Pivot <ide> */ <ide> public function newPivot(array $attributes = array(), $exists = false) <ide> { <ide><path>src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php <ide> public function getRelationCountQuery(Builder $query, Builder $parent) <ide> /** <ide> * Set the join clause on the query. <ide> * <del> * @param \Illuminate\Databaes\Eloquent\Builder|null $query <add> * @param \Illuminate\Database\Eloquent\Builder|null $query <ide> * @return void <ide> */ <ide> protected function setJoin(Builder $query = null) <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphToMany.php <ide> protected function newPivotQuery() <ide> * <ide> * @param array $attributes <ide> * @param bool $exists <del> * @return \Illuminate\Database\Eloquent\Relation\Pivot <add> * @return \Illuminate\Database\Eloquent\Relations\Pivot <ide> */ <ide> public function newPivot(array $attributes = array(), $exists = false) <ide> { <ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function orWhere($column, $operator = null, $value = null) <ide> * Determine if the given operator and value combination is legal. <ide> * <ide> * @param string $operator <del> * @param mxied $value <add> * @param mixed $value <ide> * @return bool <ide> */ <ide> protected function invalidOperatorAndValue($operator, $value) <ide><path>src/Illuminate/Exception/Handler.php <ide> protected function isFatal($type) <ide> /** <ide> * Handle a console exception. <ide> * <del> * @param Exception $exception <add> * @param \Exception $exception <ide> * @return void <ide> */ <ide> public function handleConsole($exception) <ide> public function handleConsole($exception) <ide> /** <ide> * Handle the given exception. <ide> * <del> * @param Exception $exception <add> * @param \Exception $exception <ide> * @param bool $fromConsole <ide> * @return void <ide> */ <ide> protected function displayException($exception) <ide> * Determine if the given handler handles this exception. <ide> * <ide> * @param Closure $handler <del> * @param Exception $exception <add> * @param \Exception $exception <ide> * @return bool <ide> */ <ide> protected function handlesException(Closure $handler, $exception) <ide> protected function handlesException(Closure $handler, $exception) <ide> * Determine if the given handler type hints the exception. <ide> * <ide> * @param ReflectionFunction $reflection <del> * @param Exception $exception <add> * @param \Exception $exception <ide> * @return bool <ide> */ <ide> protected function hints(ReflectionFunction $reflection, $exception) <ide> protected function hints(ReflectionFunction $reflection, $exception) <ide> /** <ide> * Format an exception thrown by a handler. <ide> * <del> * @param Exception $e <add> * @param \Exception $e <ide> * @return string <ide> */ <ide> protected function formatException(\Exception $e) <ide><path>src/Illuminate/Exception/PlainDisplayer.php <ide> class PlainDisplayer implements ExceptionDisplayerInterface { <ide> * Display the given exception to the user. <ide> * <ide> * @param \Exception $exception <add> * @return \Symfony\Component\HttpFoundation\Response <ide> */ <ide> public function display(Exception $exception) <ide> { <ide><path>src/Illuminate/Exception/WhoopsDisplayer.php <ide> public function __construct(Run $whoops, $runningInConsole) <ide> * Display the given exception to the user. <ide> * <ide> * @param \Exception $exception <add> * @return \Symfony\Component\HttpFoundation\Response <ide> */ <ide> public function display(Exception $exception) <ide> { <ide><path>src/Illuminate/Foundation/Testing/TestCase.php <ide> protected function refreshApplication() <ide> * <ide> * Needs to be implemented by subclasses. <ide> * <del> * @return Symfony\Component\HttpKernel\HttpKernelInterface <add> * @return \Symfony\Component\HttpKernel\HttpKernelInterface <ide> */ <ide> abstract public function createApplication(); <ide> <ide><path>src/Illuminate/Html/FormBuilder.php <ide> protected function checkable($type, $name, $value, $checked, $options) <ide> * @param string $name <ide> * @param mixed $value <ide> * @param bool $checked <del> * @return void <add> * @return bool <ide> */ <ide> protected function getCheckedState($type, $name, $value, $checked) <ide> { <ide><path>src/Illuminate/Log/Writer.php <ide> class Writer { <ide> /** <ide> * The event dispatcher instance. <ide> * <del> * @var \Illuminate\Events\Dispacher <add> * @var \Illuminate\Events\Dispatcher <ide> */ <ide> protected $dispatcher; <ide> <ide><path>src/Illuminate/Mail/Mailer.php <ide> class Mailer { <ide> /** <ide> * The IoC container instance. <ide> * <del> * @var \Illuminate\Container <add> * @var \Illuminate\Container\Container <ide> */ <ide> protected $container; <ide> <ide><path>src/Illuminate/Queue/IronQueue.php <ide> public function recreate($payload, $queue = null, $delay) <ide> * <ide> * @param \DateTime|int $delay <ide> * @param string $job <del> * @param mixed data <add> * @param mixed $data <ide> * @param string $queue <ide> * @return mixed <ide> */ <ide><path>src/Illuminate/Queue/Jobs/RedisJob.php <ide> class RedisJob extends Job { <ide> * Create a new job instance. <ide> * <ide> * @param \Illuminate\Container\Container $container <del> * @param \Illuminate\Redis\Queue $redis <add> * @param \Illuminate\Queue\RedisQueue $redis <ide> * @param string $job <ide> * @param string $queue <ide> * @return void <ide><path>src/Illuminate/Queue/QueueInterface.php <ide> public function later($delay, $job, $data = '', $queue = null); <ide> * Pop the next job off of the queue. <ide> * <ide> * @param string $queue <del> * @return \Illuminate\Queue\Jobs\Job|nul <add> * @return \Illuminate\Queue\Jobs\Job|null <ide> */ <ide> public function pop($queue = null); <ide> <ide><path>src/Illuminate/Routing/ControllerDispatcher.php <ide> protected function getAssignableAfter($filter) <ide> * @param array $filter <ide> * @param \Illuminate\Http\Request $request <ide> * @param string $method <add> * @return bool <ide> */ <ide> protected function filterApplies($filter, $request, $method) <ide> { <ide> protected function filterApplies($filter, $request, $method) <ide> * @param array $filter <ide> * @param \Illuminate\Http\Request $request <ide> * @param string $method <add> * @return bool <ide> */ <ide> protected function filterFailsOnly($filter, $request, $method) <ide> { <ide> protected function filterFailsOnly($filter, $request, $method) <ide> * @param array $filter <ide> * @param \Illuminate\Http\Request $request <ide> * @param string $method <add> * @return bool <ide> */ <ide> protected function filterFailsExcept($filter, $request, $method) <ide> { <ide> protected function filterFailsExcept($filter, $request, $method) <ide> * @param array $filter <ide> * @param \Illuminate\Http\Request $request <ide> * @param string $method <add> * @return bool <ide> */ <ide> protected function filterFailsOn($filter, $request, $method) <ide> { <ide><path>src/Illuminate/Routing/Router.php <ide> protected function getLastGroupPrefix() <ide> * @param array|string $methods <ide> * @param string $uri <ide> * @param \Closure|array|string $action <add> * @return \Illuminate\Routing\Route <ide> */ <ide> protected function addRoute($methods, $uri, $action) <ide> { <ide><path>src/Illuminate/Session/CacheBasedSessionHandler.php <ide> class CacheBasedSessionHandler implements \SessionHandlerInterface { <ide> /** <ide> * Create a new cache driven handler instance. <ide> * <del> * @param Illuminate\Cache\Repository $cache <add> * @param \Illuminate\Cache\Repository $cache <ide> * @param int $minutes <ide> * @return void <ide> */ <ide><path>src/Illuminate/Support/Facades/Response.php <ide> public static function json($data = array(), $status = 200, array $headers = arr <ide> /** <ide> * Return a new streamed response from the application. <ide> * <del> * @param Closure $callback <add> * @param \Closure $callback <ide> * @param int $status <ide> * @param array $headers <ide> * @return \Symfony\Component\HttpFoundation\StreamedResponse <ide> public static function stream($callback, $status = 200, array $headers = array() <ide> /** <ide> * Create a new file download response. <ide> * <del> * @param SplFileInfo|string $file <add> * @param \SplFileInfo|string $file <ide> * @param string $name <ide> * @param array $headers <ide> * @return \Symfony\Component\HttpFoundation\BinaryFileResponse <ide><path>src/Illuminate/Validation/Factory.php <ide> class Factory { <ide> /** <ide> * The Translator implementation. <ide> * <del> * @var \Symfony\Component\Translator\TranslatorInterface <add> * @var \Symfony\Component\Translation\TranslatorInterface <ide> */ <ide> protected $translator; <ide> <ide><path>src/Illuminate/View/Engines/CompilerEngine.php <ide> public function get($path, array $data = array()) <ide> /** <ide> * Handle a view exception. <ide> * <del> * @param Exception $e <add> * @param \Exception $e <ide> * @return void <ide> * <ide> * @throws $e <ide><path>src/Illuminate/View/Engines/PhpEngine.php <ide> protected function evaluatePath($__path, $__data) <ide> /** <ide> * Handle a view exception. <ide> * <del> * @param Exception $e <add> * @param \Exception $e <ide> * @return void <ide> * <ide> * @throws $e <ide><path>src/Illuminate/View/Environment.php <ide> class Environment { <ide> /** <ide> * The IoC container instance. <ide> * <del> * @var \Illuminate\Container <add> * @var \Illuminate\Container\Container <ide> */ <ide> protected $container; <ide> <ide><path>src/Illuminate/Workbench/PackageCreator.php <ide> class PackageCreator { <ide> /** <ide> * The filesystem instance. <ide> * <del> * @var \Illuminate\Filesystem <add> * @var \Illuminate\Filesystem\Filesystem <ide> */ <ide> protected $files; <ide> <ide> class PackageCreator { <ide> /** <ide> * Create a new package creator instance. <ide> * <del> * @param \Illuminate\Filesystem $files <add> * @param \Illuminate\Filesystem\Filesystem $files <ide> * @return void <ide> */ <ide> public function __construct(Filesystem $files)
32
Javascript
Javascript
fix a failing test and count ids from one
9cebc2663888573b4b993a4a9096f7fac8c6a5a3
<ide><path>src/isomorphic/devtools/__tests__/ReactNativeOperationHistoryDevtool-test.js <ide> describe('ReactNativeOperationHistoryDevtool', () => { <ide> }]); <ide> }); <ide> <del> it('gets recorded for composite roots that return null', () => { <add> it('gets ignored for composite roots that return null', () => { <ide> function Foo() { <ide> return null; <ide> } <ide> var node = document.createElement('div'); <ide> ReactDOM.render(<Foo />, node); <del> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild); <ide> <del> if (ReactDOMFeatureFlags.useCreateElement) { <del> // Empty DOM components should be invisible to devtools. <del> assertHistoryMatches([]); <del> } else { <del> assertHistoryMatches([{ <del> instanceID: inst._debugID, <del> type: 'mount', <del> payload: '<!-- react-empty: 1 -->', <del> }]); <del> } <add> // Empty DOM components should be invisible to devtools. <add> assertHistoryMatches([]); <ide> }); <ide> <ide> it('gets recorded when a native is mounted deeply instead of null', () => { <ide><path>src/test/ReactTestUtils.js <ide> ReactShallowRenderer.prototype.getMountedInstance = function() { <ide> return this._instance ? this._instance._instance : null; <ide> }; <ide> <del>var nextDebugID = 0; <add>var nextDebugID = 1; <ide> <ide> var NoopInternalComponent = function(element) { <ide> this._renderedOutput = element;
2
Javascript
Javascript
add geolocation api jest mock
6a1e0516e9f9276723479d8393c9e036ed511f17
<ide><path>jest/setup.js <ide> const mockNativeModules = { <ide> addListener: jest.fn(), <ide> removeListeners: jest.fn(), <ide> }, <add> LocationObserver: { <add> getCurrentPosition: jest.fn(), <add> startObserving: jest.fn(), <add> stopObserving: jest.fn(), <add> }, <ide> ModalFullscreenViewManager: {}, <ide> Networking: { <ide> sendRequest: jest.fn(),
1
Ruby
Ruby
prevent deprecation warning in the tests
8b6870cfae8d50a2ffd4f024d33d51aadaa6a6f7
<ide><path>railties/test/secret_key_generation_test.rb <ide> def setup <ide> end <ide> <ide> def test_secret_key_generation <del> assert @generator.generate_secret.length >= SECRET_KEY_MIN_LENGTH <add> assert_deprecated /ActiveSupport::SecureRandom\.hex\(64\)/ do <add> assert @generator.generate_secret.length >= SECRET_KEY_MIN_LENGTH <add> end <ide> end <ide> end
1
Text
Text
fix 404 links in module.md
3b40893815c2e85350f0ea651ac124cb377051e0
<ide><path>doc/api/module.md <ide> # Modules: `module` API <ide> <del><!--introduced_in=v0.3.7--> <add><!--introduced_in=v12.20.0--> <add><!-- YAML <add>added: v0.3.7 <add>--> <ide> <ide> ## The `Module` object <ide>
1
Ruby
Ruby
keep onsubmit around for form_remote_for
06a731e365011715759f46a09cb726b9f0350d00
<ide><path>actionpack/lib/action_view/helpers/prototype_helper.rb <ide> def form_remote_tag(options = {}) <ide> options[:form] = true <ide> <ide> options[:html] ||= {} <del> options[:html][:onsubmit] = "#{remote_function(options)}; return false;" <add> options[:html][:onsubmit] = <add> (options[:html][:onsubmit] ? options[:html][:onsubmit] + "; " : "") + <add> "#{remote_function(options)}; return false;" <ide> <ide> form_tag(options[:html].delete(:action) || url_for(options[:url]), options[:html]) <ide> end <ide> def remote_function(options) <ide> javascript_options = options_for_ajax(options) <ide> <ide> update = '' <del> if options[:update] and options[:update].is_a?Hash <add> if options[:update] && options[:update].is_a?(Hash) <ide> update = [] <ide> update << "success:'#{options[:update][:success]}'" if options[:update][:success] <ide> update << "failure:'#{options[:update][:failure]}'" if options[:update][:failure] <ide> def remote_function(options) <ide> "new Ajax.Updater(#{update}, " <ide> <ide> url_options = options[:url] <del> url_options = url_options.merge(:escape => false) if url_options.is_a? Hash <add> url_options = url_options.merge(:escape => false) if url_options.is_a?(Hash) <ide> function << "'#{url_for(url_options)}'" <ide> function << ", #{javascript_options})" <ide>
1
Javascript
Javascript
cover path.basename when path and ext are the same
824f16c8610b31ce06e4b6ff6927eb0df2da1953
<ide><path>test/parallel/test-path-basename.js <ide> assert.strictEqual(path.basename('/aaa/'), 'aaa'); <ide> assert.strictEqual(path.basename('/aaa/b'), 'b'); <ide> assert.strictEqual(path.basename('/a/b'), 'b'); <ide> assert.strictEqual(path.basename('//a'), 'a'); <add>assert.strictEqual(path.basename('a', 'a'), ''); <ide> <ide> // On Windows a backslash acts as a path separator. <ide> assert.strictEqual(path.win32.basename('\\dir\\basename.ext'), 'basename.ext'); <ide> assert.strictEqual(path.win32.basename('C:basename.ext\\'), 'basename.ext'); <ide> assert.strictEqual(path.win32.basename('C:basename.ext\\\\'), 'basename.ext'); <ide> assert.strictEqual(path.win32.basename('C:foo'), 'foo'); <ide> assert.strictEqual(path.win32.basename('file:stream'), 'file:stream'); <add>assert.strictEqual(path.win32.basename('a', 'a'), ''); <ide> <ide> // On unix a backslash is just treated as any other character. <ide> assert.strictEqual(path.posix.basename('\\dir\\basename.ext'),
1
Java
Java
polish uribuilderfactory and implementation
4db0d999af9a6d5ca9ee09df1b8c08bcaf9cf5dd
<ide><path>spring-web/src/main/java/org/springframework/web/client/RestTemplate.java <ide> else if (this.uriTemplateHandler instanceof org.springframework.web.util.Abstrac <ide> } <ide> <ide> /** <del> * Configure the {@link UriTemplateHandler} to use to expand URI templates. <del> * By default the {@link DefaultUriBuilderFactory} is used which relies on <del> * Spring's URI template support and exposes several useful properties that <del> * customize its behavior for encoding and for pre-pending a common base URL. <del> * An alternative implementation may be used to plug an external URI <del> * template library. <del> * <p><strong>Note:</strong> if switching from <add> * Customize how URI templates are expanded into URI instances. <add> * <p>By default {@link DefaultUriBuilderFactory} with default settings is <add> * used. You can supply a {@code DefaultUriBuilderFactory} configured <add> * differently, or an entirely different implementation, for example that <add> * plugs in a 3rd party URI template library. <add> * <p><strong>Note:</strong> in 5.0 the switch from <ide> * {@link org.springframework.web.util.DefaultUriTemplateHandler <del> * DefaultUriTemplateHandler} (deprecated in 4.3) to <del> * {@link DefaultUriBuilderFactory} keep in mind that the <del> * {@link DefaultUriBuilderFactory} has a different default for the <del> * {@code parsePath} property (from false to true). <add> * DefaultUriTemplateHandler} (deprecated in 4.3), as the default to use, to <add> * {@link DefaultUriBuilderFactory} brings in a different default for the <add> * {@code parsePath} property (switching from false to true). <ide> * @param handler the URI template handler to use <ide> */ <ide> public void setUriTemplateHandler(UriTemplateHandler handler) { <ide><path>spring-web/src/main/java/org/springframework/web/util/DefaultUriBuilderFactory.java <ide> package org.springframework.web.util; <ide> <ide> import java.net.URI; <add>import java.nio.charset.Charset; <ide> import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import org.springframework.util.ObjectUtils; <ide> <ide> /** <del> * Default implementation of {@link UriBuilderFactory} providing options to <del> * pre-configure all {@link UriBuilder} instances with common properties <del> * such as a base URI, encoding mode, and default URI variables. <add> * {@code UriBuilderFactory} that relies on {@link UriComponentsBuilder} for <add> * the actual building of the URI. <add> * <add> * <p>Provides options to create {@link UriBuilder} instances with a common <add> * base URI, alternative encoding mode strategies, among others. <ide> * <del> * <p>Uses {@link UriComponentsBuilder} for URI building. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 5.0 <ide> * @see UriComponentsBuilder <ide> */ <ide> public class DefaultUriBuilderFactory implements UriBuilderFactory { <ide> <del> public enum EncodingMode {URI_COMPONENT, VALUES_ONLY, NONE} <add> <add> /** <add> * Constants that represent different URI encoding strategies. <add> * @see #setEncodingMode <add> */ <add> public enum EncodingMode { <add> <add> /** <add> * The default way of encoding that {@link UriComponents} supports: <add> * <ol> <add> * <li>Expand URI variables. <add> * <li>Encode individual URI components as described in <add> * {@link UriComponents#encode(Charset)}. <add> * </ol> <add> * <p>This mode <strong>does not</strong> encode all characters with <add> * reserved meaning but only the ones that are illegal within a given <add> * URI component as defined in RFC 396. This matches the way the <add> * multi-argument {@link URI} constructor does encoding. <add> */ <add> URI_COMPONENT, <add> <add> /** <add> * Comprehensive encoding of URI variable values prior to expanding: <add> * <ol> <add> * <li>Apply {@link UriUtils#encode(String, Charset)} to each URI variable value. <add> * <li>Expand URI variable values. <add> * </ol> <add> * <p>This mode encodes all characters with reserved meaning, therefore <add> * ensuring that expanded URI variable do not have any impact on the <add> * structure or meaning of the URI. <add> */ <add> VALUES_ONLY, <add> <add> /** <add> * No encoding should be applied. <add> */ <add> NONE } <ide> <ide> <ide> private final UriComponentsBuilder baseUri; <ide> public void setDefaultUriVariables(@Nullable Map<String, ?> defaultUriVariables) <ide> } <ide> <ide> /** <del> * Specify the encoding mode to use when building URIs: <del> * <ul> <del> * <li>URI_COMPONENT -- expand the URI variables first and then encode all URI <del> * component (e.g. host, path, query, etc) according to the encoding rules <del> * for each individual component. <del> * <li>VALUES_ONLY -- encode URI variable values only, prior to expanding <del> * them, using a "strict" encoding mode, i.e. encoding all characters <del> * outside the unreserved set as defined in <del> * <a href="https://tools.ietf.org/html/rfc3986#section-2">RFC 3986 Section 2</a>. <del> * This ensures a URI variable value will not contain any characters with a <del> * reserved purpose. <del> * <li>NONE -- in this mode no encoding is performed. <del> * </ul> <del> * <p>By default this is set to {@code "URI_COMPONENT"}. <add> * Specify the {@link EncodingMode EncodingMode} to use when building URIs. <add> * <p>By default set to <add> * {@link EncodingMode#URI_COMPONENT EncodingMode.URI_COMPONENT}. <ide> * @param encodingMode the encoding mode to use <ide> */ <ide> public void setEncodingMode(EncodingMode encodingMode) { <ide><path>spring-web/src/main/java/org/springframework/web/util/UriBuilderFactory.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> package org.springframework.web.util; <ide> <ide> /** <del> * Factory to create {@link UriBuilder} instances pre-configured in a specific <del> * way such as sharing a common base URI across all builders. <add> * Factory to create {@link UriBuilder} instances with shared configuration <add> * such as a base URI, an encoding mode strategy, and others across all URI <add> * builder instances created through a factory. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 5.0 <ide> */ <ide> public interface UriBuilderFactory extends UriTemplateHandler { <ide> <ide> /** <del> * Create a builder from the given URI template string. <del> * Implementations may further combine the URI template with a base URI. <add> * Initialize a builder with the given URI template. <ide> * @param uriTemplate the URI template to use <del> * @return the builder instance <add> * @return the URI builder instance <ide> */ <ide> UriBuilder uriString(String uriTemplate); <ide> <ide> /** <del> * Create a builder with default settings. <add> * Create a URI builder with default settings. <ide> * @return the builder instance <ide> */ <ide> UriBuilder builder(); <ide><path>spring-web/src/main/java/org/springframework/web/util/UriTemplateHandler.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.util.Map; <ide> <ide> /** <del> * Strategy for expanding a URI template. <del> * <del> * <p>Supported as a property on the {@code RestTemplate} as well as the <del> * {@code AsyncRestTemplate}. <add> * Defines methods for expanding a URI template with variables. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.2 <del> * @see DefaultUriBuilderFactory <add> * @see org.springframework.web.client.RestTemplate#setUriTemplateHandler(UriTemplateHandler) <ide> */ <ide> public interface UriTemplateHandler { <ide> <ide> /** <del> * Expand the given URI template from a map of URI variables. <del> * @param uriTemplate the URI template string <del> * @param uriVariables the URI variables <del> * @return the resulting URI <add> * Expand the given URI template with a map of URI variables. <add> * @param uriTemplate the URI template <add> * @param uriVariables variable values <add> * @return the created URI instance <ide> */ <ide> URI expand(String uriTemplate, Map<String, ?> uriVariables); <ide> <ide> /** <del> * Expand the given URI template from an array of URI variables. <del> * @param uriTemplate the URI template string <del> * @param uriVariables the URI variable values <del> * @return the resulting URI <add> * Expand the given URI template with an array of URI variables. <add> * @param uriTemplate the URI template <add> * @param uriVariables variable values <add> * @return the created URI instance <ide> */ <ide> URI expand(String uriTemplate, Object... uriVariables); <ide>
4
Text
Text
fix a minor typo
8df0b12d821d5a57051e9a92bc8687ac893deb3f
<ide><path>docs/sources/userguide/dockervolumes.md <ide> page_keywords: Examples, Usage, volume, docker, documentation, user guide, data, <ide> <ide> # Managing Data in Containers <ide> <del>So far we've been introduced some [basic Docker <add>So far we've been introduced to some [basic Docker <ide> concepts](/userguide/usingdocker/), seen how to work with [Docker <ide> images](/userguide/dockerimages/) as well as learned about [networking <ide> and links between containers](/userguide/dockerlinks/). In this section
1
Text
Text
add mutliclass field to default zero shot example
fbcddb85442c41cd1d2d60c40171fc8cc22ee9bb
<ide><path>model_cards/facebook/bart-large-mnli/README.md <ide> pipeline_tag: zero-shot-classification <ide> widget: <ide> - text: "Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app." <ide> labels: "mobile, website, billing, account access" <add> multiclass: true <ide> ---
1
Python
Python
adjust number of warmup loops
5be198eca885fd967426ad5551c8374f1c3e889e
<ide><path>research/tensorrt/tensorrt.py <ide> from official.resnet import imagenet_preprocessing # pylint: disable=g-bad-import-order <ide> <ide> _GPU_MEM_FRACTION = 0.50 <del>_WARMUP_NUM_LOOPS = 50 <add>_WARMUP_NUM_LOOPS = 5 <ide> _LOG_FILE = "log.txt" <ide> _LABELS_FILE = "labellist.json" <ide> _GRAPH_FILE = "frozen_graph.pb"
1
Go
Go
fix volumes-from mount references
3d029c3bf335bc2867d1efc803096d2912b81799
<ide><path>daemon/volumes.go <ide> func (daemon *Daemon) registerMountPoints(container *Container, hostConfig *runc <ide> } <ide> <ide> for _, m := range c.MountPoints { <del> cp := m <del> cp.RW = m.RW && mode != "ro" <add> cp := &mountPoint{ <add> Name: m.Name, <add> Source: m.Source, <add> RW: m.RW && mode != "ro", <add> Driver: m.Driver, <add> Destination: m.Destination, <add> } <ide> <del> if len(m.Source) == 0 { <del> v, err := createVolume(m.Name, m.Driver) <add> if len(cp.Source) == 0 { <add> v, err := createVolume(cp.Name, cp.Driver) <ide> if err != nil { <ide> return err <ide> } <ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) { <ide> c.Fatalf("expected output ok received %s", actual) <ide> } <ide> } <add> <add>// https://github.com/docker/docker/pull/14498 <add>func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) { <add> dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true") <add> dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true") <add> dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true") <add> <add> testRO, err := inspectFieldMap("test-volumes-1", ".VolumesRW", "/test") <add> c.Assert(err, check.IsNil) <add> if testRO != "false" { <add> c.Fatalf("Expected RO volume was RW") <add> } <add> testRW, err := inspectFieldMap("test-volumes-2", ".VolumesRW", "/test") <add> c.Assert(err, check.IsNil) <add> if testRW != "true" { <add> c.Fatalf("Expected RW volume was RO") <add> } <add>}
2
Ruby
Ruby
simplify arg parameterization
b9efc74f9e63e76f121204a96073d2f5582f66e6
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def optimize_routes_generation?(t) <ide> end <ide> <ide> def parameterize_args(args) <del> [].tap do |parameterized_args| <del> @required_parts.zip(args) do |part, arg| <del> parameterized_arg = arg.to_param <del> parameterized_args << [part, parameterized_arg] <del> end <del> end <add> @required_parts.zip(args.map(&:to_param)) <ide> end <ide> <ide> def missing_keys(args)
1
Ruby
Ruby
add annotation to haml and slim template
8f61df0bcd0e84f26c6c41b98eeb2f7bb8d5ca4b
<ide><path>railties/lib/rails/source_annotation_extractor.rb <ide> def find_in(dir) <ide> results.update(extract_annotations_from(item, /#\s*(#{tag}):?\s*(.*)$/)) <ide> elsif item =~ /\.erb$/ <ide> results.update(extract_annotations_from(item, /<%\s*#\s*(#{tag}):?\s*(.*?)\s*%>/)) <add> elsif item =~ /\.haml$/ <add> results.update(extract_annotations_from(item, /-\s*#\s*(#{tag}):?\s*(.*)$/)) <add> elsif item =~ /\.slim$/ <add> results.update(extract_annotations_from(item, /\/\s*\s*(#{tag}):?\s*(.*)$/)) <ide> end <ide> end <ide> <ide><path>railties/test/railties/rake_tasks_test.rb <add>require "isolation/abstract_unit" <add> <add>module RailtiesTest <add> class RakeNotesTest < Test::Unit::TestCase <add> def setup <add> build_app <add> require "rails/all" <add> end <add> <add> def teardown <add> teardown_app <add> end <add> <add> test 'notes' do <add> app_file "app/views/home/index.html.erb", "<% # TODO: note in erb %>" <add> app_file "app/views/home/index.html.haml", "-# TODO: note in haml" <add> app_file "app/views/home/index.html.slim", "/ TODO: note in slim" <add> <add> boot_rails <add> require 'rake' <add> require 'rdoc/task' <add> require 'rake/testtask' <add> <add> Rails.application.load_tasks <add> <add> Dir.chdir(app_path) do <add> output = `bundle exec rake notes` <add> <add> assert_match /note in erb/, output <add> assert_match /note in haml/, output <add> assert_match /note in slim/, output <add> end <add> <add> end <add> <add> private <add> def boot_rails <add> super <add> require "#{app_path}/config/environment" <add> end <add> end <add>end
2
Ruby
Ruby
pass the join type to the join_constraints method
bae5e02cf33311318be9c7272852bbaef976bd7e
<ide><path>activerecord/lib/active_record/associations/join_dependency.rb <ide> def instantiate(result_set, aliases) <ide> <ide> def make_joins(node) <ide> node.children.flat_map { |child| <del> child.join_constraints(node, child.tables, child.reflection.chain) <add> chain = child.reflection.chain <add> child.join_constraints(node, child.join_type, child.tables, chain) <ide> .concat make_joins(child) <ide> } <ide> end <ide><path>activerecord/lib/active_record/associations/join_dependency/join_association.rb <ide> def match?(other) <ide> super && reflection == other.reflection <ide> end <ide> <del> def join_constraints(parent, tables, chain) <add> def join_constraints(parent, join_type, tables, chain) <ide> joins = [] <ide> tables = tables.reverse <ide>
2
Text
Text
use code markup/markdown in headers
f6b67010506ec83ab9e60b2876f168e88864653a
<ide><path>doc/api/crypto.md <ide> try { <ide> } <ide> ``` <ide> <del>## Class: Certificate <add>## Class: `Certificate` <ide> <!-- YAML <ide> added: v0.11.8 <ide> --> <ide> The `crypto` module provides the `Certificate` class for working with SPKAC <ide> data. The most common usage is handling output generated by the HTML5 <ide> `<keygen>` element. Node.js uses [OpenSSL's SPKAC implementation][] internally. <ide> <del>### Certificate.exportChallenge(spkac) <add>### `Certificate.exportChallenge(spkac)` <ide> <!-- YAML <ide> added: v9.0.0 <ide> --> <ide> console.log(challenge.toString('utf8')); <ide> // Prints: the challenge as a UTF8 string <ide> ``` <ide> <del>### Certificate.exportPublicKey(spkac\[, encoding\]) <add>### `Certificate.exportPublicKey(spkac[, encoding])` <ide> <!-- YAML <ide> added: v9.0.0 <ide> --> <ide> console.log(publicKey); <ide> // Prints: the public key as <Buffer ...> <ide> ``` <ide> <del>### Certificate.verifySpkac(spkac) <add>### `Certificate.verifySpkac(spkac)` <ide> <!-- YAML <ide> added: v9.0.0 <ide> --> <ide> As a still supported legacy interface, it is possible (but not recommended) to <ide> create new instances of the `crypto.Certificate` class as illustrated in the <ide> examples below. <ide> <del>#### new crypto.Certificate() <add>#### `new crypto.Certificate()` <ide> <ide> Instances of the `Certificate` class can be created using the `new` keyword <ide> or by calling `crypto.Certificate()` as a function: <ide> const cert1 = new crypto.Certificate(); <ide> const cert2 = crypto.Certificate(); <ide> ``` <ide> <del>#### certificate.exportChallenge(spkac) <add>#### `certificate.exportChallenge(spkac)` <ide> <!-- YAML <ide> added: v0.11.8 <ide> --> <ide> console.log(challenge.toString('utf8')); <ide> // Prints: the challenge as a UTF8 string <ide> ``` <ide> <del>#### certificate.exportPublicKey(spkac) <add>#### `certificate.exportPublicKey(spkac)` <ide> <!-- YAML <ide> added: v0.11.8 <ide> --> <ide> console.log(publicKey); <ide> // Prints: the public key as <Buffer ...> <ide> ``` <ide> <del>#### certificate.verifySpkac(spkac) <add>#### `certificate.verifySpkac(spkac)` <ide> <!-- YAML <ide> added: v0.11.8 <ide> --> <ide> console.log(cert.verifySpkac(Buffer.from(spkac))); <ide> // Prints: true or false <ide> ``` <ide> <del>## Class: Cipher <add>## Class: `Cipher` <ide> <!-- YAML <ide> added: v0.1.94 <ide> --> <ide> console.log(encrypted); <ide> // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa <ide> ``` <ide> <del>### cipher.final(\[outputEncoding\]) <add>### `cipher.final([outputEncoding])` <ide> <!-- YAML <ide> added: v0.1.94 <ide> --> <ide> Once the `cipher.final()` method has been called, the `Cipher` object can no <ide> longer be used to encrypt data. Attempts to call `cipher.final()` more than <ide> once will result in an error being thrown. <ide> <del>### cipher.setAAD(buffer\[, options\]) <add>### `cipher.setAAD(buffer[, options])` <ide> <!-- YAML <ide> added: v1.0.0 <ide> --> <ide> of the plaintext in bytes. See [CCM mode][]. <ide> <ide> The `cipher.setAAD()` method must be called before [`cipher.update()`][]. <ide> <del>### cipher.getAuthTag() <add>### `cipher.getAuthTag()` <ide> <!-- YAML <ide> added: v1.0.0 <ide> --> <ide> added: v1.0.0 <ide> The `cipher.getAuthTag()` method should only be called after encryption has <ide> been completed using the [`cipher.final()`][] method. <ide> <del>### cipher.setAutoPadding(\[autoPadding\]) <add>### `cipher.setAutoPadding([autoPadding])` <ide> <!-- YAML <ide> added: v0.7.1 <ide> --> <ide> using `0x0` instead of PKCS padding. <ide> The `cipher.setAutoPadding()` method must be called before <ide> [`cipher.final()`][]. <ide> <del>### cipher.update(data\[, inputEncoding\]\[, outputEncoding\]) <add>### `cipher.update(data[, inputEncoding][, outputEncoding])` <ide> <!-- YAML <ide> added: v0.1.94 <ide> changes: <ide> The `cipher.update()` method can be called multiple times with new data until <ide> [`cipher.final()`][] is called. Calling `cipher.update()` after <ide> [`cipher.final()`][] will result in an error being thrown. <ide> <del>## Class: Decipher <add>## Class: `Decipher` <ide> <!-- YAML <ide> added: v0.1.94 <ide> --> <ide> console.log(decrypted); <ide> // Prints: some clear text data <ide> ``` <ide> <del>### decipher.final(\[outputEncoding\]) <add>### `decipher.final([outputEncoding])` <ide> <!-- YAML <ide> added: v0.1.94 <ide> --> <ide> Once the `decipher.final()` method has been called, the `Decipher` object can <ide> no longer be used to decrypt data. Attempts to call `decipher.final()` more <ide> than once will result in an error being thrown. <ide> <del>### decipher.setAAD(buffer\[, options\]) <add>### `decipher.setAAD(buffer[, options])` <ide> <!-- YAML <ide> added: v1.0.0 <ide> changes: <ide> of the plaintext in bytes. See [CCM mode][]. <ide> <ide> The `decipher.setAAD()` method must be called before [`decipher.update()`][]. <ide> <del>### decipher.setAuthTag(buffer) <add>### `decipher.setAuthTag(buffer)` <ide> <!-- YAML <ide> added: v1.0.0 <ide> changes: <ide> is invalid according to [NIST SP 800-38D][] or does not match the value of the <ide> The `decipher.setAuthTag()` method must be called before <ide> [`decipher.final()`][] and can only be called once. <ide> <del>### decipher.setAutoPadding(\[autoPadding\]) <add>### `decipher.setAutoPadding([autoPadding])` <ide> <!-- YAML <ide> added: v0.7.1 <ide> --> <ide> multiple of the ciphers block size. <ide> The `decipher.setAutoPadding()` method must be called before <ide> [`decipher.final()`][]. <ide> <del>### decipher.update(data\[, inputEncoding\]\[, outputEncoding\]) <add>### `decipher.update(data[, inputEncoding][, outputEncoding])` <ide> <!-- YAML <ide> added: v0.1.94 <ide> changes: <ide> The `decipher.update()` method can be called multiple times with new data until <ide> [`decipher.final()`][] is called. Calling `decipher.update()` after <ide> [`decipher.final()`][] will result in an error being thrown. <ide> <del>## Class: DiffieHellman <add>## Class: `DiffieHellman` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> const bobSecret = bob.computeSecret(aliceKey); <ide> assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); <ide> ``` <ide> <del>### diffieHellman.computeSecret(otherPublicKey\[, inputEncoding\]\[, outputEncoding\]) <add>### `diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> provided, `otherPublicKey` is expected to be a [`Buffer`][], <ide> If `outputEncoding` is given a string is returned; otherwise, a <ide> [`Buffer`][] is returned. <ide> <del>### diffieHellman.generateKeys(\[encoding\]) <add>### `diffieHellman.generateKeys([encoding])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> transferred to the other party. <ide> If `encoding` is provided a string is returned; otherwise a <ide> [`Buffer`][] is returned. <ide> <del>### diffieHellman.getGenerator(\[encoding\]) <add>### `diffieHellman.getGenerator([encoding])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> Returns the Diffie-Hellman generator in the specified `encoding`. <ide> If `encoding` is provided a string is <ide> returned; otherwise a [`Buffer`][] is returned. <ide> <del>### diffieHellman.getPrime(\[encoding\]) <add>### `diffieHellman.getPrime([encoding])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> Returns the Diffie-Hellman prime in the specified `encoding`. <ide> If `encoding` is provided a string is <ide> returned; otherwise a [`Buffer`][] is returned. <ide> <del>### diffieHellman.getPrivateKey(\[encoding\]) <add>### `diffieHellman.getPrivateKey([encoding])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> Returns the Diffie-Hellman private key in the specified `encoding`. <ide> If `encoding` is provided a <ide> string is returned; otherwise a [`Buffer`][] is returned. <ide> <del>### diffieHellman.getPublicKey(\[encoding\]) <add>### `diffieHellman.getPublicKey([encoding])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> Returns the Diffie-Hellman public key in the specified `encoding`. <ide> If `encoding` is provided a <ide> string is returned; otherwise a [`Buffer`][] is returned. <ide> <del>### diffieHellman.setPrivateKey(privateKey\[, encoding\]) <add>### `diffieHellman.setPrivateKey(privateKey[, encoding])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> Sets the Diffie-Hellman private key. If the `encoding` argument is provided, <ide> to be a string. If no `encoding` is provided, `privateKey` is expected <ide> to be a [`Buffer`][], `TypedArray`, or `DataView`. <ide> <del>### diffieHellman.setPublicKey(publicKey\[, encoding\]) <add>### `diffieHellman.setPublicKey(publicKey[, encoding])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> Sets the Diffie-Hellman public key. If the `encoding` argument is provided, <ide> to be a string. If no `encoding` is provided, `publicKey` is expected <ide> to be a [`Buffer`][], `TypedArray`, or `DataView`. <ide> <del>### diffieHellman.verifyError <add>### `diffieHellman.verifyError` <ide> <!-- YAML <ide> added: v0.11.12 <ide> --> <ide> module): <ide> * `DH_UNABLE_TO_CHECK_GENERATOR` <ide> * `DH_NOT_SUITABLE_GENERATOR` <ide> <del>## Class: DiffieHellmanGroup <add>## Class: `DiffieHellmanGroup` <ide> <!-- YAML <ide> added: v0.7.5 <ide> --> <ide> modp17 <ide> modp18 <ide> ``` <ide> <del>## Class: ECDH <add>## Class: `ECDH` <ide> <!-- YAML <ide> added: v0.11.14 <ide> --> <ide> assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); <ide> // OK <ide> ``` <ide> <del>### Class Method: ECDH.convertKey(key, curve\[, inputEncoding\[, outputEncoding\[, format\]\]\]) <add>### Class Method: `ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])` <ide> <!-- YAML <ide> added: v10.0.0 <ide> --> <ide> const uncompressedKey = ECDH.convertKey(compressedKey, <ide> console.log(uncompressedKey === ecdh.getPublicKey('hex')); <ide> ``` <ide> <del>### ecdh.computeSecret(otherPublicKey\[, inputEncoding\]\[, outputEncoding\]) <add>### `ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])` <ide> <!-- YAML <ide> added: v0.11.14 <ide> changes: <ide> lies outside of the elliptic curve. Since `otherPublicKey` is <ide> usually supplied from a remote user over an insecure network, <ide> its recommended for developers to handle this exception accordingly. <ide> <del>### ecdh.generateKeys(\[encoding\[, format\]\]) <add>### `ecdh.generateKeys([encoding[, format]])` <ide> <!-- YAML <ide> added: v0.11.14 <ide> --> <ide> The `format` argument specifies point encoding and can be `'compressed'` or <ide> If `encoding` is provided a string is returned; otherwise a [`Buffer`][] <ide> is returned. <ide> <del>### ecdh.getPrivateKey(\[encoding\]) <add>### `ecdh.getPrivateKey([encoding])` <ide> <!-- YAML <ide> added: v0.11.14 <ide> --> <ide> added: v0.11.14 <ide> If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is <ide> returned. <ide> <del>### ecdh.getPublicKey(\[encoding\]\[, format\]) <add>### `ecdh.getPublicKey([encoding][, format])` <ide> <!-- YAML <ide> added: v0.11.14 <ide> --> <ide> The `format` argument specifies point encoding and can be `'compressed'` or <ide> If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is <ide> returned. <ide> <del>### ecdh.setPrivateKey(privateKey\[, encoding\]) <add>### `ecdh.setPrivateKey(privateKey[, encoding])` <ide> <!-- YAML <ide> added: v0.11.14 <ide> --> <ide> If `privateKey` is not valid for the curve specified when the `ECDH` object was <ide> created, an error is thrown. Upon setting the private key, the associated <ide> public point (key) is also generated and set in the `ECDH` object. <ide> <del>### ecdh.setPublicKey(publicKey\[, encoding\]) <add>### `ecdh.setPublicKey(publicKey[, encoding])` <ide> <!-- YAML <ide> added: v0.11.14 <ide> deprecated: v5.2.0 <ide> const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); <ide> console.log(aliceSecret === bobSecret); <ide> ``` <ide> <del>## Class: Hash <add>## Class: `Hash` <ide> <!-- YAML <ide> added: v0.1.92 <ide> --> <ide> console.log(hash.digest('hex')); <ide> // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 <ide> ``` <ide> <del>### hash.copy(\[options\]) <add>### `hash.copy([options])` <ide> <!-- YAML <ide> added: v13.1.0 <ide> --> <ide> console.log(hash.copy().digest('hex')); <ide> // Etc. <ide> ``` <ide> <del>### hash.digest(\[encoding\]) <add>### `hash.digest([encoding])` <ide> <!-- YAML <ide> added: v0.1.92 <ide> --> <ide> a [`Buffer`][] is returned. <ide> The `Hash` object can not be used again after `hash.digest()` method has been <ide> called. Multiple calls will cause an error to be thrown. <ide> <del>### hash.update(data\[, inputEncoding\]) <add>### `hash.update(data[, inputEncoding])` <ide> <!-- YAML <ide> added: v0.1.92 <ide> changes: <ide> encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or <ide> <ide> This can be called many times with new data as it is streamed. <ide> <del>## Class: Hmac <add>## Class: `Hmac` <ide> <!-- YAML <ide> added: v0.1.94 <ide> --> <ide> console.log(hmac.digest('hex')); <ide> // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e <ide> ``` <ide> <del>### hmac.digest(\[encoding\]) <add>### `hmac.digest([encoding])` <ide> <!-- YAML <ide> added: v0.1.94 <ide> --> <ide> provided a string is returned; otherwise a [`Buffer`][] is returned; <ide> The `Hmac` object can not be used again after `hmac.digest()` has been <ide> called. Multiple calls to `hmac.digest()` will result in an error being thrown. <ide> <del>### hmac.update(data\[, inputEncoding\]) <add>### `hmac.update(data[, inputEncoding])` <ide> <!-- YAML <ide> added: v0.1.94 <ide> changes: <ide> encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or <ide> <ide> This can be called many times with new data as it is streamed. <ide> <del>## Class: KeyObject <add>## Class: `KeyObject` <ide> <!-- YAML <ide> added: v11.6.0 <ide> changes: <ide> keyword. <ide> Most applications should consider using the new `KeyObject` API instead of <ide> passing keys as strings or `Buffer`s due to improved security features. <ide> <del>### keyObject.asymmetricKeyType <add>### `keyObject.asymmetricKeyType` <ide> <!-- YAML <ide> added: v11.6.0 <ide> changes: <ide> types are: <ide> This property is `undefined` for unrecognized `KeyObject` types and symmetric <ide> keys. <ide> <del>### keyObject.export(\[options\]) <add>### `keyObject.export([options])` <ide> <!-- YAML <ide> added: v11.6.0 <ide> --> <ide> encryption mechanism, PEM-level encryption is not supported when encrypting <ide> a PKCS#8 key. See [RFC 5208][] for PKCS#8 encryption and [RFC 1421][] for <ide> PKCS#1 and SEC1 encryption. <ide> <del>### keyObject.symmetricKeySize <add>### `keyObject.symmetricKeySize` <ide> <!-- YAML <ide> added: v11.6.0 <ide> --> <ide> added: v11.6.0 <ide> For secret keys, this property represents the size of the key in bytes. This <ide> property is `undefined` for asymmetric keys. <ide> <del>### keyObject.type <add>### `keyObject.type` <ide> <!-- YAML <ide> added: v11.6.0 <ide> --> <ide> Depending on the type of this `KeyObject`, this property is either <ide> `'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys <ide> or `'private'` for private (asymmetric) keys. <ide> <del>## Class: Sign <add>## Class: `Sign` <ide> <!-- YAML <ide> added: v0.1.92 <ide> --> <ide> console.log(verify.verify(publicKey, signature)); <ide> // Prints: true <ide> ``` <ide> <del>### sign.sign(privateKey\[, outputEncoding\]) <add>### `sign.sign(privateKey[, outputEncoding])` <ide> <!-- YAML <ide> added: v0.1.92 <ide> changes: <ide> is returned. <ide> The `Sign` object can not be again used after `sign.sign()` method has been <ide> called. Multiple calls to `sign.sign()` will result in an error being thrown. <ide> <del>### sign.update(data\[, inputEncoding\]) <add>### `sign.update(data[, inputEncoding])` <ide> <!-- YAML <ide> added: v0.1.92 <ide> changes: <ide> encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or <ide> <ide> This can be called many times with new data as it is streamed. <ide> <del>## Class: Verify <add>## Class: `Verify` <ide> <!-- YAML <ide> added: v0.1.92 <ide> --> <ide> The [`crypto.createVerify()`][] method is used to create `Verify` instances. <ide> <ide> See [`Sign`][] for examples. <ide> <del>### verify.update(data\[, inputEncoding\]) <add>### `verify.update(data[, inputEncoding])` <ide> <!-- YAML <ide> added: v0.1.92 <ide> changes: <ide> encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or <ide> <ide> This can be called many times with new data as it is streamed. <ide> <del>### verify.verify(object, signature\[, signatureEncoding\]) <add>### `verify.verify(object, signature[, signatureEncoding])` <ide> <!-- YAML <ide> added: v0.1.92 <ide> changes: <ide> be passed instead of a public key. <ide> <ide> ## `crypto` module methods and properties <ide> <del>### crypto.constants <add>### `crypto.constants` <ide> <!-- YAML <ide> added: v6.3.0 <ide> --> <ide> added: v6.3.0 <ide> security related operations. The specific constants currently defined are <ide> described in [Crypto Constants][]. <ide> <del>### crypto.DEFAULT_ENCODING <add>### `crypto.DEFAULT_ENCODING` <ide> <!-- YAML <ide> added: v0.9.3 <ide> deprecated: v10.0.0 <ide> New applications should expect the default to be `'buffer'`. <ide> <ide> This property is deprecated. <ide> <del>### crypto.fips <add>### `crypto.fips` <ide> <!-- YAML <ide> added: v6.0.0 <ide> deprecated: v10.0.0 <ide> is currently in use. Setting to true requires a FIPS build of Node.js. <ide> This property is deprecated. Please use `crypto.setFips()` and <ide> `crypto.getFips()` instead. <ide> <del>### crypto.createCipher(algorithm, password\[, options\]) <add>### `crypto.createCipher(algorithm, password[, options])` <ide> <!-- YAML <ide> added: v0.1.94 <ide> deprecated: v10.0.0 <ide> they are used in order to avoid the risk of IV reuse that causes <ide> vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting <ide> Adversaries][] for details. <ide> <del>### crypto.createCipheriv(algorithm, key, iv\[, options\]) <add>### `crypto.createCipheriv(algorithm, key, iv[, options])` <ide> <!-- YAML <ide> added: v0.1.94 <ide> changes: <ide> something has to be unpredictable and unique, but does not have to be secret; <ide> remember that an attacker must not be able to predict ahead of time what a <ide> given IV will be. <ide> <del>### crypto.createDecipher(algorithm, password\[, options\]) <add>### `crypto.createDecipher(algorithm, password[, options])` <ide> <!-- YAML <ide> added: v0.1.94 <ide> deprecated: v10.0.0 <ide> In line with OpenSSL's recommendation to use a more modern algorithm instead of <ide> their own using [`crypto.scrypt()`][] and to use [`crypto.createDecipheriv()`][] <ide> to create the `Decipher` object. <ide> <del>### crypto.createDecipheriv(algorithm, key, iv\[, options\]) <add>### `crypto.createDecipheriv(algorithm, key, iv[, options])` <ide> <!-- YAML <ide> added: v0.1.94 <ide> changes: <ide> something has to be unpredictable and unique, but does not have to be secret; <ide> remember that an attacker must not be able to predict ahead of time what a given <ide> IV will be. <ide> <del>### crypto.createDiffieHellman(prime\[, primeEncoding\]\[, generator\]\[, generatorEncoding\]) <add>### `crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])` <ide> <!-- YAML <ide> added: v0.11.12 <ide> changes: <ide> a [`Buffer`][], `TypedArray`, or `DataView` is expected. <ide> If `generatorEncoding` is specified, `generator` is expected to be a string; <ide> otherwise a number, [`Buffer`][], `TypedArray`, or `DataView` is expected. <ide> <del>### crypto.createDiffieHellman(primeLength\[, generator\]) <add>### `crypto.createDiffieHellman(primeLength[, generator])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> Creates a `DiffieHellman` key exchange object and generates a prime of <ide> `primeLength` bits using an optional specific numeric `generator`. <ide> If `generator` is not specified, the value `2` is used. <ide> <del>### crypto.createDiffieHellmanGroup(name) <add>### `crypto.createDiffieHellmanGroup(name)` <ide> <!-- YAML <ide> added: v0.9.3 <ide> --> <ide> added: v0.9.3 <ide> <ide> An alias for [`crypto.getDiffieHellman()`][] <ide> <del>### crypto.createECDH(curveName) <add>### `crypto.createECDH(curveName)` <ide> <!-- YAML <ide> added: v0.11.14 <ide> --> <ide> predefined curve specified by the `curveName` string. Use <ide> OpenSSL releases, `openssl ecparam -list_curves` will also display the name <ide> and description of each available elliptic curve. <ide> <del>### crypto.createHash(algorithm\[, options\]) <add>### `crypto.createHash(algorithm[, options])` <ide> <!-- YAML <ide> added: v0.1.92 <ide> changes: <ide> input.on('readable', () => { <ide> }); <ide> ``` <ide> <del>### crypto.createHmac(algorithm, key\[, options\]) <add>### `crypto.createHmac(algorithm, key[, options])` <ide> <!-- YAML <ide> added: v0.1.94 <ide> changes: <ide> input.on('readable', () => { <ide> }); <ide> ``` <ide> <del>### crypto.createPrivateKey(key) <add>### `crypto.createPrivateKey(key)` <ide> <!-- YAML <ide> added: v11.6.0 <ide> --> <ide> must be an object with the properties described above. <ide> If the private key is encrypted, a `passphrase` must be specified. The length <ide> of the passphrase is limited to 1024 bytes. <ide> <del>### crypto.createPublicKey(key) <add>### `crypto.createPublicKey(key)` <ide> <!-- YAML <ide> added: v11.6.0 <ide> changes: <ide> extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type <ide> `'private'` is given, a new `KeyObject` with type `'public'` will be returned <ide> and it will be impossible to extract the private key from the returned object. <ide> <del>### crypto.createSecretKey(key) <add>### `crypto.createSecretKey(key)` <ide> <!-- YAML <ide> added: v11.6.0 <ide> --> <ide> added: v11.6.0 <ide> Creates and returns a new key object containing a secret key for symmetric <ide> encryption or `Hmac`. <ide> <del>### crypto.createSign(algorithm\[, options\]) <add>### `crypto.createSign(algorithm[, options])` <ide> <!-- YAML <ide> added: v0.1.92 <ide> --> <ide> the corresponding digest algorithm. This does not work for all signature <ide> algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest <ide> algorithm names. <ide> <del>### crypto.createVerify(algorithm\[, options\]) <add>### `crypto.createVerify(algorithm[, options])` <ide> <!-- YAML <ide> added: v0.1.92 <ide> --> <ide> the corresponding digest algorithm. This does not work for all signature <ide> algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest <ide> algorithm names. <ide> <del>### crypto.generateKeyPair(type, options, callback) <add>### `crypto.generateKeyPair(type, options, callback)` <ide> <!-- YAML <ide> added: v10.12.0 <ide> changes: <ide> On completion, `callback` will be called with `err` set to `undefined` and <ide> If this method is invoked as its [`util.promisify()`][]ed version, it returns <ide> a `Promise` for an `Object` with `publicKey` and `privateKey` properties. <ide> <del>### crypto.generateKeyPairSync(type, options) <add>### `crypto.generateKeyPairSync(type, options)` <ide> <!-- YAML <ide> added: v10.12.0 <ide> changes: <ide> The return value `{ publicKey, privateKey }` represents the generated key pair. <ide> When PEM encoding was selected, the respective key will be a string, otherwise <ide> it will be a buffer containing the data encoded as DER. <ide> <del>### crypto.getCiphers() <add>### `crypto.getCiphers()` <ide> <!-- YAML <ide> added: v0.9.3 <ide> --> <ide> const ciphers = crypto.getCiphers(); <ide> console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...] <ide> ``` <ide> <del>### crypto.getCurves() <add>### `crypto.getCurves()` <ide> <!-- YAML <ide> added: v2.3.0 <ide> --> <ide> const curves = crypto.getCurves(); <ide> console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] <ide> ``` <ide> <del>### crypto.getDiffieHellman(groupName) <add>### `crypto.getDiffieHellman(groupName)` <ide> <!-- YAML <ide> added: v0.7.5 <ide> --> <ide> const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); <ide> console.log(aliceSecret === bobSecret); <ide> ``` <ide> <del>### crypto.getFips() <add>### `crypto.getFips()` <ide> <!-- YAML <ide> added: v10.0.0 <ide> --> <ide> <ide> * Returns: {boolean} `true` if and only if a FIPS compliant crypto provider is <ide> currently in use. <ide> <del>### crypto.getHashes() <add>### `crypto.getHashes()` <ide> <!-- YAML <ide> added: v0.9.3 <ide> --> <ide> const hashes = crypto.getHashes(); <ide> console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] <ide> ``` <ide> <del>### crypto.pbkdf2(password, salt, iterations, keylen, digest, callback) <add>### `crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> This API uses libuv's threadpool, which can have surprising and <ide> negative performance implications for some applications; see the <ide> [`UV_THREADPOOL_SIZE`][] documentation for more information. <ide> <del>### crypto.pbkdf2Sync(password, salt, iterations, keylen, digest) <add>### `crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)` <ide> <!-- YAML <ide> added: v0.9.3 <ide> changes: <ide> console.log(key); // '3745e48...aa39b34' <ide> An array of supported digest functions can be retrieved using <ide> [`crypto.getHashes()`][]. <ide> <del>### crypto.privateDecrypt(privateKey, buffer) <add>### `crypto.privateDecrypt(privateKey, buffer)` <ide> <!-- YAML <ide> added: v0.11.14 <ide> changes: <ide> If `privateKey` is not a [`KeyObject`][], this function behaves as if <ide> object, the `padding` property can be passed. Otherwise, this function uses <ide> `RSA_PKCS1_OAEP_PADDING`. <ide> <del>### crypto.privateEncrypt(privateKey, buffer) <add>### `crypto.privateEncrypt(privateKey, buffer)` <ide> <!-- YAML <ide> added: v1.1.0 <ide> changes: <ide> If `privateKey` is not a [`KeyObject`][], this function behaves as if <ide> object, the `padding` property can be passed. Otherwise, this function uses <ide> `RSA_PKCS1_PADDING`. <ide> <del>### crypto.publicDecrypt(key, buffer) <add>### `crypto.publicDecrypt(key, buffer)` <ide> <!-- YAML <ide> added: v1.1.0 <ide> changes: <ide> object, the `padding` property can be passed. Otherwise, this function uses <ide> Because RSA public keys can be derived from private keys, a private key may <ide> be passed instead of a public key. <ide> <del>### crypto.publicEncrypt(key, buffer) <add>### `crypto.publicEncrypt(key, buffer)` <ide> <!-- YAML <ide> added: v0.11.14 <ide> changes: <ide> object, the `padding` property can be passed. Otherwise, this function uses <ide> Because RSA public keys can be derived from private keys, a private key may <ide> be passed instead of a public key. <ide> <del>### crypto.randomBytes(size\[, callback\]) <add>### `crypto.randomBytes(size[, callback])` <ide> <!-- YAML <ide> added: v0.5.8 <ide> changes: <ide> threadpool request. To minimize threadpool task length variation, partition <ide> large `randomBytes` requests when doing so as part of fulfilling a client <ide> request. <ide> <del>### crypto.randomFillSync(buffer\[, offset\]\[, size\]) <add>### `crypto.randomFillSync(buffer[, offset][, size])` <ide> <!-- YAML <ide> added: <ide> - v7.10.0 <ide> console.log(Buffer.from(crypto.randomFillSync(c).buffer, <ide> c.byteOffset, c.byteLength).toString('hex')); <ide> ``` <ide> <del>### crypto.randomFill(buffer\[, offset\]\[, size\], callback) <add>### `crypto.randomFill(buffer[, offset][, size], callback)` <ide> <!-- YAML <ide> added: <ide> - v7.10.0 <ide> threadpool request. To minimize threadpool task length variation, partition <ide> large `randomFill` requests when doing so as part of fulfilling a client <ide> request. <ide> <del>### crypto.scrypt(password, salt, keylen\[, options\], callback) <add>### `crypto.scrypt(password, salt, keylen[, options], callback)` <ide> <!-- YAML <ide> added: v10.5.0 <ide> changes: <ide> crypto.scrypt('secret', 'salt', 64, { N: 1024 }, (err, derivedKey) => { <ide> }); <ide> ``` <ide> <del>### crypto.scryptSync(password, salt, keylen\[, options\]) <add>### `crypto.scryptSync(password, salt, keylen[, options])` <ide> <!-- YAML <ide> added: v10.5.0 <ide> changes: <ide> const key2 = crypto.scryptSync('secret', 'salt', 64, { N: 1024 }); <ide> console.log(key2.toString('hex')); // '3745e48...aa39b34' <ide> ``` <ide> <del>### crypto.setEngine(engine\[, flags\]) <add>### `crypto.setEngine(engine[, flags])` <ide> <!-- YAML <ide> added: v0.11.11 <ide> --> <ide> The flags below are deprecated in OpenSSL-1.1.0. <ide> * `crypto.constants.ENGINE_METHOD_ECDSA` <ide> * `crypto.constants.ENGINE_METHOD_STORE` <ide> <del>### crypto.setFips(bool) <add>### `crypto.setFips(bool)` <ide> <!-- YAML <ide> added: v10.0.0 <ide> --> <ide> added: v10.0.0 <ide> Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. <ide> Throws an error if FIPS mode is not available. <ide> <del>### crypto.sign(algorithm, data, key) <add>### `crypto.sign(algorithm, data, key)` <ide> <!-- YAML <ide> added: v12.0.0 <ide> --> <ide> additional properties can be passed: <ide> size, `crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN` (default) sets it to the <ide> maximum permissible value. <ide> <del>### crypto.timingSafeEqual(a, b) <add>### `crypto.timingSafeEqual(a, b)` <ide> <!-- YAML <ide> added: v6.6.0 <ide> --> <ide> Use of `crypto.timingSafeEqual` does not guarantee that the *surrounding* code <ide> is timing-safe. Care should be taken to ensure that the surrounding code does <ide> not introduce timing vulnerabilities. <ide> <del>### crypto.verify(algorithm, data, key, signature) <add>### `crypto.verify(algorithm, data, key, signature)` <ide> <!-- YAML <ide> added: v12.0.0 <ide> -->
1
Python
Python
remove old unused tests and conftest files
f8803808ce5604dbde4b6f0c4b0f1f0e1e199859
<ide><path>setup.py <ide> 'spacy.munge', <ide> 'spacy.tests', <ide> 'spacy.tests.matcher', <del> 'spacy.tests.morphology', <ide> 'spacy.tests.munge', <ide> 'spacy.tests.parser', <ide> 'spacy.tests.serialize', <ide><path>spacy/tests/morphology/test_morphology_pickle.py <del>import pytest <del> <del>import pickle <del>import io <del> <del> <del>from spacy.morphology import Morphology <del>from spacy.lemmatizer import Lemmatizer <del>from spacy.strings import StringStore <del> <del>@pytest.mark.xfail <del>def test_pickle(): <del> morphology = Morphology(StringStore(), {}, Lemmatizer({}, {}, {})) <del> <del> file_ = io.BytesIO() <del> pickle.dump(morphology, file_) <del> <ide><path>spacy/tests/test_matcher.py <ide> def test_phrase_matcher(): <ide> matcher = PhraseMatcher(vocab, [Doc(vocab, words='Google Now'.split())]) <ide> doc = Doc(vocab, words=['I', 'like', 'Google', 'Now', 'best']) <ide> assert len(matcher(doc)) == 1 <del> <del> <del>#@pytest.mark.models <del>#def test_match_preserved(EN): <del># patterns = { <del># 'JS': ['PRODUCT', {}, [[{'ORTH': 'JavaScript'}]]], <del># 'GoogleNow': ['PRODUCT', {}, [[{'ORTH': 'Google'}, {'ORTH': 'Now'}]]], <del># 'Java': ['PRODUCT', {}, [[{'LOWER': 'java'}]]], <del># } <del># matcher = Matcher(EN.vocab, patterns) <del># doc = EN.tokenizer('I like java.') <del># EN.tagger(doc) <del># assert len(doc.ents) == 0 <del># doc = EN.tokenizer('I like java.') <del># doc.ents += tuple(matcher(doc)) <del># assert len(doc.ents) == 1 <del># EN.tagger(doc) <del># EN.entity(doc) <del># assert len(doc.ents) == 1 <ide><path>spacy/tests/vocab/conftest.py <del>import pytest <del> <del> <del>@pytest.fixture(scope="session") <del>def en_vocab(EN): <del> return EN.vocab
4
Javascript
Javascript
add deprecation warnings to reactnative.addons
0b534d1c3da9e3520bfd9b85bdd669db4d8c3b9f
<ide><path>Libraries/react-native/react-native.js <ide> */ <ide> 'use strict'; <ide> <add>var warning = require('fbjs/lib/warning'); <add> <add>if (__DEV__) { <add> var warningDedupe = {}; <add> var addonWarn = function addonWarn(prevName, newPackageName) { <add> warning( <add> warningDedupe[prevName], <add> 'React.addons.' + prevName + ' is deprecated. Please import the "' + <add> newPackageName + '" package instead.' <add> ); <add> warningDedupe[prevName] = true; <add> }; <add>} <add> <ide> // Export React, plus some native additions. <ide> var ReactNative = { <ide> // Components <ide> var ReactNative = { <ide> <ide> // See http://facebook.github.io/react/docs/addons.html <ide> addons: { <del> get LinkedStateMixin() { return require('LinkedStateMixin'); }, <add> get LinkedStateMixin() { <add> if (__DEV__) { <add> addonWarn('LinkedStateMixin', 'react-addons-linked-state-mixin'); <add> } <add> return require('LinkedStateMixin'); <add> }, <ide> Perf: undefined, <del> get PureRenderMixin() { return require('ReactComponentWithPureRenderMixin'); }, <del> get TestModule() { return require('NativeModules').TestModule; }, <add> get PureRenderMixin() { <add> if (__DEV__) { <add> addonWarn('PureRenderMixin', 'react-addons-pure-render-mixin'); <add> } <add> return require('ReactComponentWithPureRenderMixin'); <add> }, <add> get TestModule() { <add> if (__DEV__) { <add> warning( <add> warningDedupe.TestModule, <add> 'React.addons.TestModule is deprecated. ' + <add> 'Use ReactNative.NativeModules.TestModule instead.' <add> ); <add> warningDedupe.TestModule = true; <add> } <add> return require('NativeModules').TestModule; <add> }, <ide> TestUtils: undefined, <del> get batchedUpdates() { return require('ReactUpdates').batchedUpdates; }, <del> get cloneWithProps() { return require('cloneWithProps'); }, <del> get createFragment() { return require('ReactFragment').create; }, <del> get update() { return require('update'); }, <add> get batchedUpdates() { <add> if (__DEV__) { <add> warning( <add> warningDedupe.batchedUpdates, <add> 'React.addons.batchedUpdates is deprecated. ' + <add> 'Use ReactNative.unstable_batchedUpdates instead.' <add> ); <add> warningDedupe.batchedUpdates = true; <add> } <add> return require('ReactUpdates').batchedUpdates; <add> }, <add> get cloneWithProps() { <add> if (__DEV__) { <add> addonWarn('cloneWithProps', 'react-addons-clone-with-props'); <add> } <add> return require('cloneWithProps'); <add> }, <add> get createFragment() { <add> if (__DEV__) { <add> addonWarn('createFragment', 'react-addons-create-fragment'); <add> } <add> return require('ReactFragment').create; <add> }, <add> get update() { <add> if (__DEV__) { <add> addonWarn('update', 'react-addons-update'); <add> } <add> return require('update'); <add> }, <ide> }, <ide> }; <ide> <ide> for (var key in ReactNativeInternal) { <ide> if (__DEV__) { <ide> Object.defineProperty(ReactNative.addons, 'Perf', { <ide> enumerable: true, <del> get: () => require('ReactDefaultPerf'), <add> get: () => { <add> if (__DEV__) { <add> addonWarn('Perf', 'react-addons-perf'); <add> } <add> return require('ReactDefaultPerf'); <add> } <ide> }); <ide> Object.defineProperty(ReactNative.addons, 'TestUtils', { <ide> enumerable: true, <del> get: () => require('ReactTestUtils'), <add> get: () => { <add> if (__DEV__) { <add> addonWarn('update', 'react-addons-test-utils'); <add> } <add> return require('ReactTestUtils'); <add> } <ide> }); <ide> } <ide>
1
Javascript
Javascript
add test for ignored normal modules
eae28fa56b54b7bcaf38ae77eb6f0c4e117b70d0
<ide><path>test/configCases/ignore/only-resource/ignored-module.js <add>module.exports = "ignored"; <ide><path>test/configCases/ignore/only-resource/normal-module.js <add>module.exports = "normal"; <ide><path>test/configCases/ignore/only-resource/test.js <add>/* globals it */ <add>"use strict"; <add> <add>it("should ignore ignored resources", function() { <add> (function() { <add> require("./ignored-module"); <add> }).should.throw(); <add>}); <add>it("should not ignore resources that do not match", function() { <add> (function() { <add> require("./normal-module"); <add> }).should.not.throw(); <add>}); <ide><path>test/configCases/ignore/only-resource/webpack.config.js <add>"use strict"; <add> <add>const IgnorePlugin = require("../../../../lib/IgnorePlugin"); <add> <add>module.exports = { <add> entry: "./test.js", <add> plugins: [ <add> new IgnorePlugin(/ignored-module/) <add> ], <add>}; <ide><path>test/configCases/ignore/resource-and-context/folder-a/ignored-module.js <add>module.exports = "ignored"; <ide><path>test/configCases/ignore/resource-and-context/folder-a/normal-module.js <add>module.exports = require("./normal-module"); <ide><path>test/configCases/ignore/resource-and-context/folder-b/ignored-module.js <add>module.exports = "ignored"; <ide><path>test/configCases/ignore/resource-and-context/folder-b/normal-module.js <add>module.exports = require("./ignored-module"); <ide><path>test/configCases/ignore/resource-and-context/folder-b/only-context-match-require.js <add>module.exports = "should be fine"; <ide><path>test/configCases/ignore/resource-and-context/folder-b/only-context-match.js <add>module.exports = require("./only-context-match-require"); <ide><path>test/configCases/ignore/resource-and-context/test.js <add>/* globals it */ <add>"use strict"; <add> <add>it("should ignore resources that match resource regex and context", function() { <add> (function() { <add> require("./folder-b/normal-module"); <add> }).should.throw(); <add>}); <add> <add>it("should not ignore resources that match resource but not context", function() { <add> (function() { <add> require("./folder-a/normal-module"); <add> }).should.not.throw(); <add>}); <add> <add>it("should not ignore resources that do not match resource but do match context", function() { <add> (function() { <add> require("./folder-b/only-context-match"); <add> }).should.not.throw(); <add>}); <ide><path>test/configCases/ignore/resource-and-context/webpack.config.js <add>"use strict"; <add> <add>const IgnorePlugin = require("../../../../lib/IgnorePlugin"); <add> <add>module.exports = { <add> entry: "./test.js", <add> plugins: [ <add> new IgnorePlugin(/ignored-module/, /folder-b/) <add> ], <add>};
12
Javascript
Javascript
add additional test
32cfbd6d671dc2827562e39c5d3cd7c7565550d1
<ide><path>test/unit/manipulation.js <ide> test( "Index for function argument should be received (#13094)", 2, function() { <ide> jQuery("<div/><div/>").before(function( index ) { <ide> equal( index, i++, "Index should be correct" ); <ide> }); <add> <ide> });
1
Python
Python
fix fine_tune when optimizer is none
1c5c256e5882d58b53050eb8f1ba1f3741c3c955
<ide><path>spacy/_ml.py <ide> def fine_tune_bwd(d_output, sgd=None): <ide> model.d_mix[1] += flat_vecs.dot(flat_grad.T).sum() <ide> <ide> bp_vecs([d_o * model.mix[1] for d_o in d_output], sgd=sgd) <del> sgd(model._mem.weights, model._mem.gradient, key=model.id) <add> if sgd is not None: <add> sgd(model._mem.weights, model._mem.gradient, key=model.id) <ide> return [d_o * model.mix[0] for d_o in d_output] <ide> return output, fine_tune_bwd <ide>
1
Ruby
Ruby
remove unused to_date_tag. closes [danger]
d7f84f61a28ff308b0403ec9940dadc6e2894b41
<ide><path>actionpack/lib/action_view/helpers/form_helper.rb <ide> class InstanceTag #:nodoc: <ide> DEFAULT_FIELD_OPTIONS = { "size" => 30 }.freeze unless const_defined?(:DEFAULT_FIELD_OPTIONS) <ide> DEFAULT_RADIO_OPTIONS = { }.freeze unless const_defined?(:DEFAULT_RADIO_OPTIONS) <ide> DEFAULT_TEXT_AREA_OPTIONS = { "cols" => 40, "rows" => 20 }.freeze unless const_defined?(:DEFAULT_TEXT_AREA_OPTIONS) <del> DEFAULT_DATE_OPTIONS = { :discard_type => true }.freeze unless const_defined?(:DEFAULT_DATE_OPTIONS) <ide> <ide> def initialize(object_name, method_name, template_object, local_binding = nil, object = nil) <ide> @object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup <ide> def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0") <ide> tag("input", options) << tag("input", "name" => options["name"], "type" => "hidden", "value" => options['disabled'] && checked ? checked_value : unchecked_value) <ide> end <ide> <del> def to_date_tag() <del> defaults = DEFAULT_DATE_OPTIONS.dup <del> date = value(object) || Date.today <del> options = Proc.new { |position| defaults.merge(:prefix => "#{@object_name}[#{@method_name}(#{position}i)]") } <del> html_day_select(date, options.call(3)) + <del> html_month_select(date, options.call(2)) + <del> html_year_select(date, options.call(1)) <del> end <del> <ide> def to_boolean_select_tag(options = {}) <ide> options = options.stringify_keys <ide> add_default_name_and_id(options)
1
Javascript
Javascript
add missing jsdoc comment
350894ae9e87dc76468e655fd067d488f46fae89
<ide><path>lib/dependencies/HarmonyImportSideEffectDependency.js <ide> makeSerializable( <ide> ); <ide> <ide> HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends HarmonyImportDependency.Template { <add> /** <add> * @param {Dependency} dependency the dependency for which the template should be applied <add> * @param {ReplaceSource} source the current replace source which can be modified <add> * @param {DependencyTemplateContext} templateContext the context object <add> * @returns {void} <add> */ <ide> apply(dependency, source, templateContext) { <ide> const dep = /** @type {HarmonyImportSideEffectDependency} */ (dependency); <ide> const { moduleGraph } = templateContext;
1
Ruby
Ruby
fix typo in api document formhelper#fields
523f296557231e3ab77f36b5a7ce9fe11f070596
<ide><path>actionview/lib/action_view/helpers/form_helper.rb <ide> def fields_for(record_name, record_object = nil, options = {}, &block) <ide> # <%= fields :comment do |fields| %> <ide> # <%= fields.text_field :body %> <ide> # <% end %> <del> # # => <input type="text" name="comment[body]> <add> # # => <input type="text" name="comment[body]"> <ide> # <ide> # # Using a model infers the scope and assigns field values: <del> # <%= fields model: Comment.new(body: "full bodied") do |fields| %< <add> # <%= fields model: Comment.new(body: "full bodied") do |fields| %> <ide> # <%= fields.text_field :body %> <ide> # <% end %> <del> # # => <del> # <input type="text" name="comment[body] value="full bodied"> <add> # # => <input type="text" name="comment[body]" value="full bodied"> <ide> # <ide> # # Using +fields+ with +form_with+: <ide> # <%= form_with model: @post do |form| %>
1
Python
Python
run pyflakes and pep8 on numpy/ma/tests/*
b733a10a9cc806f4772728015ec1bd9e63322858
<ide><path>numpy/ma/tests/test_core.py <ide> __author__ = "Pierre GF Gerard-Marchant" <ide> <ide> import warnings <del>import sys <ide> import pickle <del>from functools import reduce <ide> import operator <del> <del>from nose.tools import assert_raises <add>from functools import reduce <ide> <ide> import numpy as np <ide> import numpy.ma.core <ide> import numpy.core.fromnumeric as fromnumeric <add>import numpy.core.umath as umath <add>from numpy.testing import TestCase, run_module_suite, assert_raises <ide> from numpy import ndarray <del>from numpy.ma.testutils import * <del>from numpy.ma.core import * <ide> from numpy.compat import asbytes, asbytes_nested <add>from numpy.ma.testutils import ( <add> assert_, assert_array_equal, assert_equal, assert_almost_equal, <add> assert_equal_records, fail_if_equal, assert_not_equal, <add> assert_mask_equal, <add> ) <add>from numpy.ma.core import ( <add> MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, <add> allclose, allequal, alltrue, angle, anom, arange, arccos, arctan2, <add> arcsin, arctan, argsort, array, asarray, choose, concatenate, <add> conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, <add> empty_like, equal, exp, flatten_mask, filled, fix_invalid, <add> flatten_structured_array, fromflex, getmask, getmaskarray, greater, <add> greater_equal, identity, inner, isMaskedArray, less, less_equal, log, <add> log10, make_mask, make_mask_descr, mask_or, masked, masked_array, <add> masked_equal, masked_greater, masked_greater_equal, masked_inside, <add> masked_less, masked_less_equal, masked_not_equal, masked_outside, <add> masked_print_option, masked_values, masked_where, max, maximum, <add> maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, <add> mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, <add> ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, <add> subtract, sum, take, tan, tanh, transpose, where, zeros, <add> ) <ide> <ide> pi = np.pi <ide> <ide> <del>#.............................................................................. <ide> class TestMaskedArray(TestCase): <ide> # Base test class for MaskedArrays. <ide> <ide> def test_basic2d(self): <ide> xm.shape = s <ide> ym.shape = s <ide> xf.shape = s <del> # <add> <ide> self.assertTrue(not isMaskedArray(x)) <ide> self.assertTrue(isMaskedArray(xm)) <ide> assert_equal(shape(xm), s) <ide> def test_concatenate_alongaxis(self): <ide> xmym = concatenate((xm, ym), 1) <ide> assert_equal(np.concatenate((x, y), 1), xmym) <ide> assert_equal(np.concatenate((xm.mask, ym.mask), 1), xmym._mask) <del> # <add> <ide> x = zeros(2) <ide> y = array(ones(2), mask=[False, True]) <ide> z = concatenate((x, y)) <ide> def test_concatenate_flexible(self): <ide> data = masked_array(list(zip(np.random.rand(10), <ide> np.arange(10))), <ide> dtype=[('a', float), ('b', int)]) <del> # <add> <ide> test = concatenate([data[:5], data[5:]]) <ide> assert_equal_records(test, data) <ide> <ide> def test_creation_with_list_of_maskedarrays(self): <ide> data = array((x, x[::-1])) <ide> assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]]) <ide> assert_equal(data._mask, [[1, 0, 0, 0, 0], [0, 0, 0, 0, 1]]) <del> # <add> <ide> x.mask = nomask <ide> data = array((x, x[::-1])) <ide> assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]]) <ide> def test_set_element_as_object(self): <ide> a[0] = x <ide> assert_equal(a[0], x) <ide> self.assertTrue(a[0] is x) <del> # <add> <ide> import datetime <ide> dt = datetime.datetime.now() <ide> a[0] = dt <ide> def test_indexing(self): <ide> x3 = array(x1, mask=[0, 1, 0, 1]) <ide> x4 = array(x1) <ide> # test conversion to strings <del> junk, garbage = str(x2), repr(x2) <add> str(x2) # raises? <add> repr(x2) # raises? <ide> assert_equal(np.sort(x1), sort(x2, endwith=False)) <ide> # tests of indexing <ide> assert_(type(x2[1]) is type(x1[1])) <ide> def test_matrix_indexing(self): <ide> x3 = array(x1, mask=[[0, 1, 0], [1, 0, 0]]) <ide> x4 = array(x1) <ide> # test conversion to strings <del> junk, garbage = str(x2), repr(x2) <del> # assert_equal(np.sort(x1), sort(x2, endwith=False)) <add> str(x2) # raises? <add> repr(x2) # raises? <ide> # tests of indexing <ide> assert_(type(x2[1, 0]) is type(x1[1, 0])) <ide> assert_(x1[1, 0] == x2[1, 0]) <ide> def test_copy(self): <ide> y9 = x4.copy() <ide> assert_equal(y9._data, x4._data) <ide> assert_equal(y9._mask, x4._mask) <del> # <add> <ide> x = masked_array([1, 2, 3], mask=[0, 1, 0]) <ide> # Copy is False by default <ide> y = masked_array(x) <ide> def test_deepcopy(self): <ide> copied = deepcopy(a) <ide> assert_equal(copied.mask, a.mask) <ide> assert_not_equal(id(a._mask), id(copied._mask)) <del> # <add> <ide> copied[1] = 1 <ide> assert_equal(copied.mask, [0, 0, 0]) <ide> assert_equal(a.mask, [0, 1, 0]) <del> # <add> <ide> copied = deepcopy(a) <ide> assert_equal(copied.mask, a.mask) <ide> copied.mask[1] = False <ide> def test_topython(self): <ide> assert_equal(1, int(array([[[1]]]))) <ide> assert_equal(1.0, float(array([[1]]))) <ide> self.assertRaises(TypeError, float, array([1, 1])) <del> # <add> <ide> with warnings.catch_warnings(): <ide> warnings.simplefilter('ignore', UserWarning) <ide> assert_(np.isnan(float(array([1], mask=[1])))) <del> # <add> <ide> a = array([1, 2, 3], mask=[1, 0, 0]) <ide> self.assertRaises(TypeError, lambda:float(a)) <ide> assert_equal(float(a[-1]), 3.) <ide> def test_oddfeatures_1(self): <ide> assert_equal(z.imag, 10 * x) <ide> assert_equal((z * conjugate(z)).real, 101 * x * x) <ide> z.imag[...] = 0.0 <del> # <add> <ide> x = arange(10) <ide> x[3] = masked <ide> assert_(str(x[3]) == str(masked)) <ide> c = x >= 8 <ide> assert_(count(where(c, masked, masked)) == 0) <ide> assert_(shape(where(c, masked, masked)) == c.shape) <del> # <add> <ide> z = masked_where(c, x) <ide> assert_(z.dtype is x.dtype) <ide> assert_(z[3] is masked) <ide> def test_filled_w_nested_dtype(self): <ide> test = a.filled(0) <ide> control = np.array([(1, (0, 1)), (2, (2, 0))], dtype=ndtype) <ide> assert_equal(test, control) <del> # <add> <ide> test = a['B'].filled(0) <ide> control = np.array([(0, 1), (2, 0)], dtype=a['B'].dtype) <ide> assert_equal(test, control) <ide> def test_void0d(self): <ide> a = np.array([(1, 2,)], dtype=ndtype)[0] <ide> f = mvoid(a) <ide> assert_(isinstance(f, mvoid)) <del> # <add> <ide> a = masked_array([(1, 2)], mask=[(1, 0)], dtype=ndtype)[0] <ide> assert_(isinstance(a, mvoid)) <del> # <add> <ide> a = masked_array([(1, 2), (1, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype) <ide> f = mvoid(a._data[0], a._mask[0]) <ide> assert_(isinstance(f, mvoid)) <ide> def test_object_with_array(self): <ide> assert mx2[0] == 0. <ide> <ide> <del>#------------------------------------------------------------------------------ <ide> class TestMaskedArrayArithmetic(TestCase): <ide> # Base test class for MaskedArrays. <ide> <ide> def test_divide_on_different_shapes(self): <ide> x = arange(6, dtype=float) <ide> x.shape = (2, 3) <ide> y = arange(3, dtype=float) <del> # <add> <ide> z = x / y <ide> assert_equal(z, [[-1., 1., 1.], [-1., 4., 2.5]]) <ide> assert_equal(z.mask, [[1, 0, 0], [1, 0, 0]]) <del> # <add> <ide> z = x / y[None,:] <ide> assert_equal(z, [[-1., 1., 1.], [-1., 4., 2.5]]) <ide> assert_equal(z.mask, [[1, 0, 0], [1, 0, 0]]) <del> # <add> <ide> y = arange(2, dtype=float) <ide> z = x / y[:, None] <ide> assert_equal(z, [[-1., -1., -1.], [3., 4., 5.]]) <ide> def test_count_func(self): <ide> assert_equal([1, 2], res) <ide> assert_(getmask(res) is nomask) <ide> <del> ott= array([0., 1., 2., 3.]) <add> ott = array([0., 1., 2., 3.]) <ide> res = count(ott, 0) <ide> assert_(isinstance(res, ndarray)) <ide> assert_(res.dtype.type is np.intp) <ide> def test_minmax_func(self): <ide> # following are true because of careful selection of data <ide> assert_equal(max(xr), maximum(xmr)) <ide> assert_equal(min(xr), minimum(xmr)) <del> # <add> <ide> assert_equal(minimum([1, 2, 3], [4, 0, 9]), [1, 0, 3]) <ide> assert_equal(maximum([1, 2, 3], [4, 0, 9]), [4, 2, 9]) <ide> x = arange(5) <ide> def test_minmax_func(self): <ide> assert_equal(maximum(x, y), where(greater(x, y), x, y)) <ide> assert_(minimum(x) == 0) <ide> assert_(maximum(x) == 4) <del> # <add> <ide> x = arange(4).reshape(2, 2) <ide> x[-1, -1] = masked <ide> assert_equal(maximum(x), 2) <ide> def test_minimummaximum_func(self): <ide> aminimum = minimum(a, a) <ide> self.assertTrue(isinstance(aminimum, MaskedArray)) <ide> assert_equal(aminimum, np.minimum(a, a)) <del> # <add> <ide> aminimum = minimum.outer(a, a) <ide> self.assertTrue(isinstance(aminimum, MaskedArray)) <ide> assert_equal(aminimum, np.minimum.outer(a, a)) <del> # <add> <ide> amaximum = maximum(a, a) <ide> self.assertTrue(isinstance(amaximum, MaskedArray)) <ide> assert_equal(amaximum, np.maximum(a, a)) <del> # <add> <ide> amaximum = maximum.outer(a, a) <ide> self.assertTrue(isinstance(amaximum, MaskedArray)) <ide> assert_equal(amaximum, np.maximum.outer(a, a)) <ide> def test_minmax_methods(self): <ide> self.assertTrue(xm[0].ptp() is masked) <ide> self.assertTrue(xm[0].ptp(0) is masked) <ide> self.assertTrue(xm[0].ptp(-1) is masked) <del> # <add> <ide> x = array([1, 2, 3], mask=True) <ide> self.assertTrue(x.min() is masked) <ide> self.assertTrue(x.max() is masked) <ide> def test_binops_d2D(self): <ide> # Test binary operations on 2D data <ide> a = array([[1.], [2.], [3.]], mask=[[False], [True], [True]]) <ide> b = array([[2., 3.], [4., 5.], [6., 7.]]) <del> # <add> <ide> test = a * b <ide> control = array([[2., 3.], [2., 2.], [3., 3.]], <ide> mask=[[0, 0], [1, 1], [1, 1]]) <ide> assert_equal(test, control) <ide> assert_equal(test.data, control.data) <ide> assert_equal(test.mask, control.mask) <del> # <add> <ide> test = b * a <ide> control = array([[2., 3.], [4., 5.], [6., 7.]], <ide> mask=[[0, 0], [1, 1], [1, 1]]) <ide> assert_equal(test, control) <ide> assert_equal(test.data, control.data) <ide> assert_equal(test.mask, control.mask) <del> # <add> <ide> a = array([[1.], [2.], [3.]]) <ide> b = array([[2., 3.], [4., 5.], [6., 7.]], <ide> mask=[[0, 0], [0, 0], [0, 1]]) <ide> def test_binops_d2D(self): <ide> assert_equal(test, control) <ide> assert_equal(test.data, control.data) <ide> assert_equal(test.mask, control.mask) <del> # <add> <ide> test = b * a <ide> control = array([[2, 3], [8, 10], [18, 7]], <ide> mask=[[0, 0], [0, 0], [0, 1]]) <ide> def test_domained_binops_d2D(self): <ide> # Test domained binary operations on 2D data <ide> a = array([[1.], [2.], [3.]], mask=[[False], [True], [True]]) <ide> b = array([[2., 3.], [4., 5.], [6., 7.]]) <del> # <add> <ide> test = a / b <ide> control = array([[1. / 2., 1. / 3.], [2., 2.], [3., 3.]], <ide> mask=[[0, 0], [1, 1], [1, 1]]) <ide> assert_equal(test, control) <ide> assert_equal(test.data, control.data) <ide> assert_equal(test.mask, control.mask) <del> # <add> <ide> test = b / a <ide> control = array([[2. / 1., 3. / 1.], [4., 5.], [6., 7.]], <ide> mask=[[0, 0], [1, 1], [1, 1]]) <ide> assert_equal(test, control) <ide> assert_equal(test.data, control.data) <ide> assert_equal(test.mask, control.mask) <del> # <add> <ide> a = array([[1.], [2.], [3.]]) <ide> b = array([[2., 3.], [4., 5.], [6., 7.]], <ide> mask=[[0, 0], [0, 0], [0, 1]]) <ide> def test_domained_binops_d2D(self): <ide> assert_equal(test, control) <ide> assert_equal(test.data, control.data) <ide> assert_equal(test.mask, control.mask) <del> # <add> <ide> test = b / a <ide> control = array([[2 / 1., 3 / 1.], [4 / 2., 5 / 2.], [6 / 3., 7]], <ide> mask=[[0, 0], [0, 0], [0, 1]]) <ide> def test_imag_real(self): <ide> def test_methods_with_output(self): <ide> xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4) <ide> xm[:, 0] = xm[0] = xm[-1, -1] = masked <del> # <add> <ide> funclist = ('sum', 'prod', 'var', 'std', 'max', 'min', 'ptp', 'mean',) <del> # <add> <ide> for funcname in funclist: <ide> npfunc = getattr(np, funcname) <ide> xmmeth = getattr(xm, funcname) <ide> def test_methods_with_output(self): <ide> # ... the result should be the given output <ide> assert_(result is output) <ide> assert_equal(result, xmmeth(axis=0, out=output)) <del> # <add> <ide> output = empty(4, dtype=int) <ide> result = xmmeth(axis=0, out=output) <ide> assert_(result is output) <ide> def test_ne_on_structured(self): <ide> assert_equal(test.mask, [False, False]) <ide> <ide> def test_eq_w_None(self): <del> # Really, comparisons with None should not be done, but <del> # check them anyway <add> # Really, comparisons with None should not be done, but check them <add> # anyway. Note that pep8 will flag these tests. <add> <ide> # With partial mask <ide> a = array([1, 2], mask=[0, 1]) <ide> assert_equal(a == None, False) <ide> def test_numpyarithmetics(self): <ide> a = masked_array([-1, 0, 1, 2, 3], mask=[0, 0, 0, 0, 1]) <ide> control = masked_array([np.nan, np.nan, 0, np.log(2), -1], <ide> mask=[1, 1, 0, 0, 1]) <del> # <add> <ide> test = log(a) <ide> assert_equal(test, control) <ide> assert_equal(test.mask, control.mask) <ide> assert_equal(a.mask, [0, 0, 0, 0, 1]) <del> # <add> <ide> test = np.log(a) <ide> assert_equal(test, control) <ide> assert_equal(test.mask, control.mask) <ide> assert_equal(a.mask, [0, 0, 0, 0, 1]) <ide> <ide> <del>#------------------------------------------------------------------------------ <ide> class TestMaskedArrayAttributes(TestCase): <ide> <ide> def test_keepmask(self): <ide> def test_hardmask(self): <ide> xh[filled(xh > 1, False)] = 5 <ide> assert_equal(xh._data, [0, 1, 2, 5, 5]) <ide> assert_equal(xh._mask, [1, 1, 1, 0, 0]) <del> # <add> <ide> xh = array([[1, 2], [3, 4]], mask=[[1, 0], [0, 0]], hard_mask=True) <ide> xh[0] = 0 <ide> assert_equal(xh._data, [[1, 0], [3, 4]]) <ide> def test_assign_dtype(self): <ide> <ide> m = np.ma.array(a) <ide> m.dtype = np.dtype('f4') <del> repr(m) # raises? <add> repr(m) # raises? <ide> assert_equal(m.dtype, np.dtype('f4')) <ide> <ide> # check that dtype changes that change shape of mask too much <ide> def assign(): <ide> m.dtype = np.dtype('f8') <ide> assert_raises(ValueError, assign) <ide> <del> b = a.view(dtype='f4', type=np.ma.MaskedArray) # raises? <add> b = a.view(dtype='f4', type=np.ma.MaskedArray) # raises? <ide> assert_equal(b.dtype, np.dtype('f4')) <ide> <ide> # check that nomask is preserved <ide> def assign(): <ide> assert_equal(m._mask, np.ma.nomask) <ide> <ide> <del>#------------------------------------------------------------------------------ <ide> class TestFillingValues(TestCase): <ide> <ide> def test_check_on_scalar(self): <ide> # Test _check_fill_value set to valid and invalid values <ide> _check_fill_value = np.ma.core._check_fill_value <del> # <add> <ide> fval = _check_fill_value(0, int) <ide> assert_equal(fval, 0) <ide> fval = _check_fill_value(None, int) <ide> assert_equal(fval, default_fill_value(0)) <del> # <add> <ide> fval = _check_fill_value(0, "|S3") <ide> assert_equal(fval, asbytes("0")) <ide> fval = _check_fill_value(None, "|S3") <ide> def test_fillvalue_conversion(self): <ide> # properly dealt with <ide> a = array(asbytes_nested(['3', '4', '5'])) <ide> a._optinfo.update({'comment':"updated!"}) <del> # <add> <ide> b = array(a, dtype=int) <ide> assert_equal(b._data, [3, 4, 5]) <ide> assert_equal(b.fill_value, default_fill_value(0)) <del> # <add> <ide> b = array(a, dtype=float) <ide> assert_equal(b._data, [3, 4, 5]) <ide> assert_equal(b.fill_value, default_fill_value(0.)) <del> # <add> <ide> b = a.astype(int) <ide> assert_equal(b._data, [3, 4, 5]) <ide> assert_equal(b.fill_value, default_fill_value(0)) <ide> assert_equal(b._optinfo['comment'], "updated!") <del> # <add> <ide> b = a.astype([('a', '|S3')]) <ide> assert_equal(b['a']._data, a._data) <ide> assert_equal(b['a'].fill_value, a.fill_value) <ide> def test_fillvalue(self): <ide> data = masked_array([1, 2, 3], fill_value=-999) <ide> series = data[[0, 2, 1]] <ide> assert_equal(series._fill_value, data._fill_value) <del> # <add> <ide> mtype = [('f', float), ('s', '|S3')] <ide> x = array([(1, 'a'), (2, 'b'), (pi, 'pi')], dtype=mtype) <ide> x.fill_value = 999 <ide> assert_equal(x.fill_value.item(), [999., asbytes('999')]) <ide> assert_equal(x['f'].fill_value, 999) <ide> assert_equal(x['s'].fill_value, asbytes('999')) <del> # <add> <ide> x.fill_value = (9, '???') <ide> assert_equal(x.fill_value.item(), (9, asbytes('???'))) <ide> assert_equal(x['f'].fill_value, 9) <ide> assert_equal(x['s'].fill_value, asbytes('???')) <del> # <add> <ide> x = array([1, 2, 3.1]) <ide> x.fill_value = 999 <ide> assert_equal(np.asarray(x.fill_value).dtype, float) <ide> def test_fillvalue_exotic_dtype(self): <ide> assert_equal(_check_fill_value(None, ndtype), control) <ide> control = np.array((0,), dtype=[('f0', float)]).astype(ndtype) <ide> assert_equal(_check_fill_value(0, ndtype), control) <del> # <add> <ide> ndtype = np.dtype("int, (2,3)float, float") <ide> control = np.array((default_fill_value(0), <ide> default_fill_value(0.), <ide> def test_extremum_fill_value(self): <ide> assert_equal(test['A'], default_fill_value(a['A'])) <ide> assert_equal(test['B']['BA'], default_fill_value(a['B']['BA'])) <ide> assert_equal(test['B']['BB'], default_fill_value(a['B']['BB'])) <del> # <add> <ide> test = minimum_fill_value(a) <ide> assert_equal(test[0], minimum_fill_value(a['A'])) <ide> assert_equal(test[1][0], minimum_fill_value(a['B']['BA'])) <ide> assert_equal(test[1][1], minimum_fill_value(a['B']['BB'])) <ide> assert_equal(test[1], minimum_fill_value(a['B'])) <del> # <add> <ide> test = maximum_fill_value(a) <ide> assert_equal(test[0], maximum_fill_value(a['A'])) <ide> assert_equal(test[1][0], maximum_fill_value(a['B']['BA'])) <ide> def test_fillvalue_as_arguments(self): <ide> # Test adding a fill_value parameter to empty/ones/zeros <ide> a = empty(3, fill_value=999.) <ide> assert_equal(a.fill_value, 999.) <del> # <add> <ide> a = ones(3, fill_value=999., dtype=float) <ide> assert_equal(a.fill_value, 999.) <del> # <add> <ide> a = zeros(3, fill_value=0., dtype=complex) <ide> assert_equal(a.fill_value, 0.) <del> # <add> <ide> a = identity(3, fill_value=0., dtype=complex) <ide> assert_equal(a.fill_value, 0.) <ide> <ide> def test_fillvalue_in_view(self): <ide> assert_(y.fill_value == 999999) <ide> <ide> <del>#------------------------------------------------------------------------------ <ide> class TestUfuncs(TestCase): <ide> # Test class for the application of ufuncs on MaskedArrays. <ide> <ide> def __rdiv__(self, other): <ide> assert_(a / me_too == "Me2rdiv") <ide> <ide> <del>#------------------------------------------------------------------------------ <ide> class TestMaskedArrayInPlaceArithmetics(TestCase): <ide> # Test MaskedArray Arithmetics <ide> <ide> def test_inplace_addition_scalar(self): <ide> assert_equal(x, y + 1) <ide> xm += 1 <ide> assert_equal(xm, y + 1) <del> # <add> <ide> (x, _, xm) = self.floatdata <ide> id1 = x.data.ctypes._data <ide> x += 1. <ide> def test_inplace_division_array_float(self): <ide> assert_equal(xm.mask, mask_or(mask_or(m, a.mask), (a == 0))) <ide> <ide> def test_inplace_division_misc(self): <del> # <add> <ide> x = [1., 1., 1., -2., pi / 2., 4., 5., -10., 10., 1., 2., 3.] <ide> y = [5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.] <ide> m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] <ide> m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1] <ide> xm = masked_array(x, mask=m1) <ide> ym = masked_array(y, mask=m2) <del> # <add> <ide> z = xm / ym <ide> assert_equal(z._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1]) <ide> assert_equal(z._data, <ide> [1., 1., 1., -1., -pi / 2., 4., 5., 1., 1., 1., 2., 3.]) <ide> #assert_equal(z._data, [0.2,1.,1./3.,-1.,-pi/2.,-1.,5.,1.,1.,1.,2.,1.]) <del> # <add> <ide> xm = xm.copy() <ide> xm /= ym <ide> assert_equal(xm._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1]) <ide> def test_datafriendly_add_arrays(self): <ide> assert_equal(a, [[2, 2], [4, 4]]) <ide> if a.mask is not nomask: <ide> assert_equal(a.mask, [[0, 0], [0, 0]]) <del> # <add> <ide> a = array([[1, 1], [3, 3]]) <ide> b = array([1, 1], mask=[0, 1]) <ide> a += b <ide> def test_datafriendly_sub_arrays(self): <ide> assert_equal(a, [[0, 0], [2, 2]]) <ide> if a.mask is not nomask: <ide> assert_equal(a.mask, [[0, 0], [0, 0]]) <del> # <add> <ide> a = array([[1, 1], [3, 3]]) <ide> b = array([1, 1], mask=[0, 1]) <ide> a -= b <ide> def test_datafriendly_mul_arrays(self): <ide> assert_equal(a, [[1, 1], [3, 3]]) <ide> if a.mask is not nomask: <ide> assert_equal(a.mask, [[0, 0], [0, 0]]) <del> # <add> <ide> a = array([[1, 1], [3, 3]]) <ide> b = array([1, 1], mask=[0, 1]) <ide> a *= b <ide> def test_inplace_subtraction_scalar_type(self): <ide> <ide> assert_equal(len(w), 0, "Failed on type=%s." % t) <ide> <del> <ide> def test_inplace_subtraction_array_type(self): <ide> # Test of inplace subtractions <ide> for t in self.othertypes: <ide> def test_inplace_pow_type(self): <ide> assert_equal(len(w), 0, "Failed on type=%s." % t) <ide> <ide> <del>#------------------------------------------------------------------------------ <ide> class TestMaskedArrayMethods(TestCase): <ide> # Test class for miscellaneous MaskedArrays methods. <ide> def setUp(self): <ide> def test_generic_methods(self): <ide> assert_equal(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])) <ide> assert_equal(a.conj(), a._data.conj()) <ide> assert_equal(a.conjugate(), a._data.conjugate()) <del> # <add> <ide> m = array([[1, 2], [3, 4]]) <ide> assert_equal(m.diagonal(), m._data.diagonal()) <ide> assert_equal(a.sum(), a._data.sum()) <ide> def test_allany(self): <ide> mx = masked_array(x, mask=m) <ide> mxbig = (mx > 0.5) <ide> mxsmall = (mx < 0.5) <del> # <add> <ide> self.assertFalse(mxbig.all()) <ide> self.assertTrue(mxbig.any()) <ide> assert_equal(mxbig.all(0), [False, False, True]) <ide> assert_equal(mxbig.all(1), [False, False, True]) <ide> assert_equal(mxbig.any(0), [False, False, True]) <ide> assert_equal(mxbig.any(1), [True, True, True]) <del> # <add> <ide> self.assertFalse(mxsmall.all()) <ide> self.assertTrue(mxsmall.any()) <ide> assert_equal(mxsmall.all(0), [True, True, False]) <ide> def test_allany_onmatrices(self): <ide> mX = masked_array(X, mask=m) <ide> mXbig = (mX > 0.5) <ide> mXsmall = (mX < 0.5) <del> # <add> <ide> self.assertFalse(mXbig.all()) <ide> self.assertTrue(mXbig.any()) <ide> assert_equal(mXbig.all(0), np.matrix([False, False, True])) <ide> assert_equal(mXbig.all(1), np.matrix([False, False, True]).T) <ide> assert_equal(mXbig.any(0), np.matrix([False, False, True])) <ide> assert_equal(mXbig.any(1), np.matrix([True, True, True]).T) <del> # <add> <ide> self.assertFalse(mXsmall.all()) <ide> self.assertTrue(mXsmall.any()) <ide> assert_equal(mXsmall.all(0), np.matrix([True, True, False])) <ide> def test_allany_oddities(self): <ide> # Some fun with all and any <ide> store = empty((), dtype=bool) <ide> full = array([1, 2, 3], mask=True) <del> # <add> <ide> self.assertTrue(full.all() is masked) <ide> full.all(out=store) <ide> self.assertTrue(store) <ide> self.assertTrue(store._mask, True) <ide> self.assertTrue(store is not masked) <del> # <add> <ide> store = empty((), dtype=bool) <ide> self.assertTrue(full.any() is masked) <ide> full.any(out=store) <ide> def test_allany_oddities(self): <ide> def test_argmax_argmin(self): <ide> # Tests argmin & argmax on MaskedArrays. <ide> (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d <del> # <add> <ide> assert_equal(mx.argmin(), 35) <ide> assert_equal(mX.argmin(), 35) <ide> assert_equal(m2x.argmin(), 4) <ide> def test_argmax_argmin(self): <ide> assert_equal(mX.argmax(), 28) <ide> assert_equal(m2x.argmax(), 31) <ide> assert_equal(m2X.argmax(), 31) <del> # <add> <ide> assert_equal(mX.argmin(0), [2, 2, 2, 5, 0, 5]) <ide> assert_equal(m2X.argmin(0), [2, 2, 4, 5, 0, 4]) <ide> assert_equal(mX.argmax(0), [0, 5, 0, 5, 4, 0]) <ide> assert_equal(m2X.argmax(0), [5, 5, 0, 5, 1, 0]) <del> # <add> <ide> assert_equal(mX.argmin(1), [4, 1, 0, 0, 5, 5, ]) <ide> assert_equal(m2X.argmin(1), [4, 4, 0, 0, 5, 3]) <ide> assert_equal(mX.argmax(1), [2, 4, 1, 1, 4, 1]) <ide> def test_compress(self): <ide> a = masked_array([1., 2., 3., 4., 5.], fill_value=9999) <ide> condition = (a > 1.5) & (a < 3.5) <ide> assert_equal(a.compress(condition), [2., 3.]) <del> # <add> <ide> a[[2, 3]] = masked <ide> b = a.compress(condition) <ide> assert_equal(b._data, [2., 3.]) <ide> assert_equal(b._mask, [0, 1]) <ide> assert_equal(b.fill_value, 9999) <ide> assert_equal(b, a[condition]) <del> # <add> <ide> condition = (a < 4.) <ide> b = a.compress(condition) <ide> assert_equal(b._data, [1., 2., 3.]) <ide> assert_equal(b._mask, [0, 0, 1]) <ide> assert_equal(b.fill_value, 9999) <ide> assert_equal(b, a[condition]) <del> # <add> <ide> a = masked_array([[10, 20, 30], [40, 50, 60]], <ide> mask=[[0, 0, 1], [1, 0, 0]]) <ide> b = a.compress(a.ravel() >= 22) <ide> assert_equal(b._data, [30, 40, 50, 60]) <ide> assert_equal(b._mask, [1, 1, 0, 0]) <del> # <add> <ide> x = np.array([3, 1, 2]) <ide> b = a.compress(x >= 2, axis=1) <ide> assert_equal(b._data, [[10, 30], [40, 60]]) <ide> def test_compressed(self): <ide> a[0] = masked <ide> b = a.compressed() <ide> assert_equal(b, [2, 3, 4]) <del> # <add> <ide> a = array(np.matrix([1, 2, 3, 4]), mask=[0, 0, 0, 0]) <ide> b = a.compressed() <ide> assert_equal(b, a) <ide> def test_empty(self): <ide> a = masked_array([(1, 1.1, '1.1'), (2, 2.2, '2.2'), (3, 3.3, '3.3')], <ide> dtype=datatype) <ide> assert_equal(len(a.fill_value.item()), len(datatype)) <del> # <add> <ide> b = empty_like(a) <ide> assert_equal(b.shape, a.shape) <ide> assert_equal(b.fill_value, a.fill_value) <del> # <add> <ide> b = empty(len(a), dtype=datatype) <ide> assert_equal(b.shape, a.shape) <ide> assert_equal(b.fill_value, a.fill_value) <ide> def test_put(self): <ide> self.assertTrue(x[3] is masked) <ide> self.assertTrue(x[4] is not masked) <ide> assert_equal(x, [0, 10, 2, -1, 40]) <del> # <add> <ide> x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2) <ide> i = [0, 2, 4, 6] <ide> x.put(i, [6, 4, 2, 0]) <ide> def test_put(self): <ide> x.put(i, masked_array([0, 2, 4, 6], [1, 0, 1, 0])) <ide> assert_array_equal(x, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ]) <ide> assert_equal(x.mask, [1, 0, 0, 0, 1, 1, 0, 0, 0, 0]) <del> # <add> <ide> x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2) <ide> put(x, i, [6, 4, 2, 0]) <ide> assert_equal(x, asarray([6, 1, 4, 3, 2, 5, 0, 7, 8, 9, ])) <ide> def test_reshape(self): <ide> def test_sort(self): <ide> # Test sort <ide> x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8) <del> # <add> <ide> sortedx = sort(x) <ide> assert_equal(sortedx._data, [1, 2, 3, 4]) <ide> assert_equal(sortedx._mask, [0, 0, 0, 1]) <del> # <add> <ide> sortedx = sort(x, endwith=False) <ide> assert_equal(sortedx._data, [4, 1, 2, 3]) <ide> assert_equal(sortedx._mask, [1, 0, 0, 0]) <del> # <add> <ide> x.sort() <ide> assert_equal(x._data, [1, 2, 3, 4]) <ide> assert_equal(x._mask, [0, 0, 0, 1]) <del> # <add> <ide> x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8) <ide> x.sort(endwith=False) <ide> assert_equal(x._data, [4, 1, 2, 3]) <ide> assert_equal(x._mask, [1, 0, 0, 0]) <del> # <add> <ide> x = [1, 4, 2, 3] <ide> sortedx = sort(x) <ide> self.assertTrue(not isinstance(sorted, MaskedArray)) <del> # <add> <ide> x = array([0, 1, -1, -2, 2], mask=nomask, dtype=np.int8) <ide> sortedx = sort(x, endwith=False) <ide> assert_equal(sortedx._data, [-2, -1, 0, 1, 2]) <ide> def test_sort_flexible(self): <ide> data=[(3, 3), (3, 2), (2, 2), (2, 1), (1, 0), (1, 1), (1, 2)], <ide> mask=[(0, 0), (0, 1), (0, 0), (0, 0), (1, 0), (0, 0), (0, 0)], <ide> dtype=[('A', int), ('B', int)]) <del> # <add> <ide> test = sort(a) <ide> b = array( <ide> data=[(1, 1), (1, 2), (2, 1), (2, 2), (3, 3), (3, 2), (1, 0)], <ide> mask=[(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (1, 0)], <ide> dtype=[('A', int), ('B', int)]) <ide> assert_equal(test, b) <ide> assert_equal(test.mask, b.mask) <del> # <add> <ide> test = sort(a, endwith=False) <ide> b = array( <ide> data=[(1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (3, 2), (3, 3), ], <ide> def test_swapaxes(self): <ide> 0, 0, 1, 0, 1, 0]) <ide> mX = array(x, mask=m).reshape(6, 6) <ide> mXX = mX.reshape(3, 2, 2, 3) <del> # <add> <ide> mXswapped = mX.swapaxes(0, 1) <ide> assert_equal(mXswapped[-1], mX[:, -1]) <ide> <ide> def test_take(self): <ide> assert_equal(x.take([0, 0, 3]), x[[0, 0, 3]]) <ide> assert_equal(x.take([[0, 1], [0, 1]]), <ide> masked_array([[10, 20], [10, 20]], [[0, 1], [0, 1]])) <del> # <add> <ide> x = array([[10, 20, 30], [40, 50, 60]], mask=[[0, 0, 1], [1, 0, 0, ]]) <ide> assert_equal(x.take([0, 2], axis=1), <ide> array([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]])) <ide> def test_toflex(self): <ide> record = data.toflex() <ide> assert_equal(record['_data'], data._data) <ide> assert_equal(record['_mask'], data._mask) <del> # <add> <ide> data[[0, 1, 2, -1]] = masked <ide> record = data.toflex() <ide> assert_equal(record['_data'], data._data) <ide> assert_equal(record['_mask'], data._mask) <del> # <add> <ide> ndtype = [('i', int), ('s', '|S3'), ('f', float)] <ide> data = array([(i, s, f) for (i, s, f) in zip(np.arange(10), <ide> 'ABCDEFGHIJKLM', <ide> def test_toflex(self): <ide> record = data.toflex() <ide> assert_equal(record['_data'], data._data) <ide> assert_equal(record['_mask'], data._mask) <del> # <add> <ide> ndtype = np.dtype("int, (2,3)float, float") <ide> data = array([(i, f, ff) for (i, f, ff) in zip(np.arange(10), <ide> np.random.rand(10), <ide> def test_fromflex(self): <ide> test = fromflex(a.toflex()) <ide> assert_equal(test, a) <ide> assert_equal(test.mask, a.mask) <del> # <add> <ide> a = array([1, 2, 3], mask=[0, 0, 1]) <ide> test = fromflex(a.toflex()) <ide> assert_equal(test, a) <ide> assert_equal(test.mask, a.mask) <del> # <add> <ide> a = array([(1, 1.), (2, 2.), (3, 3.)], mask=[(1, 0), (0, 0), (0, 1)], <ide> dtype=[('A', int), ('B', float)]) <ide> test = fromflex(a.toflex()) <ide> def test_arraymethod(self): <ide> mask=[0, 0, 1, 0, 0]) <ide> assert_equal(marray.T, control) <ide> assert_equal(marray.transpose(), control) <del> # <add> <ide> assert_equal(MaskedArray.cumsum(marray.T, 0), control.cumsum(0)) <ide> <ide> <del>#------------------------------------------------------------------------------ <ide> class TestMaskedArrayMathMethods(TestCase): <ide> <ide> def setUp(self): <ide> def test_cumsumprod(self): <ide> assert_equal(mXcp._data, mX.filled(0).cumsum(0)) <ide> mXcp = mX.cumsum(1) <ide> assert_equal(mXcp._data, mX.filled(0).cumsum(1)) <del> # <add> <ide> mXcp = mX.cumprod(0) <ide> assert_equal(mXcp._data, mX.filled(1).cumprod(0)) <ide> mXcp = mX.cumprod(1) <ide> def test_cumsumprod_with_output(self): <ide> # Tests cumsum/cumprod w/ output <ide> xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4) <ide> xm[:, 0] = xm[0] = xm[-1, -1] = masked <del> # <add> <ide> for funcname in ('cumsum', 'cumprod'): <ide> npfunc = getattr(np, funcname) <ide> xmmeth = getattr(xm, funcname) <ide> def test_cumsumprod_with_output(self): <ide> # ... the result should be the given output <ide> self.assertTrue(result is output) <ide> assert_equal(result, xmmeth(axis=0, out=output)) <del> # <add> <ide> output = empty((3, 4), dtype=int) <ide> result = xmmeth(axis=0, out=output) <ide> self.assertTrue(result is output) <ide> def test_ptp(self): <ide> assert_equal(mX.ptp(1), rows) <ide> <ide> def test_add_object(self): <del> x = masked_array(['a', 'b'], mask = [1, 0], dtype=object) <add> x = masked_array(['a', 'b'], mask=[1, 0], dtype=object) <ide> y = x + 'x' <ide> assert_equal(y[1], 'bx') <ide> assert_(y.mask[0]) <ide> def test_varstd_specialcases(self): <ide> # Test a special case for var <ide> nout = np.array(-1, dtype=float) <ide> mout = array(-1, dtype=float) <del> # <add> <ide> x = array(arange(10), mask=True) <ide> for methodname in ('var', 'std'): <ide> method = getattr(x, methodname) <ide> def test_varstd_specialcases(self): <ide> # Using a masked array as explicit output <ide> with warnings.catch_warnings(): <ide> warnings.simplefilter('ignore') <del> _ = method(out=mout) <add> method(out=mout) <ide> self.assertTrue(mout is not masked) <ide> assert_equal(mout.mask, True) <ide> # Using a ndarray as explicit output <ide> with warnings.catch_warnings(): <ide> warnings.simplefilter('ignore') <del> _ = method(out=nout) <add> method(out=nout) <ide> self.assertTrue(np.isnan(nout)) <del> # <add> <ide> x = array(arange(10), mask=True) <ide> x[-1] = 9 <ide> for methodname in ('var', 'std'): <ide> def test_diag(self): <ide> def test_axis_methods_nomask(self): <ide> # Test the combination nomask & methods w/ axis <ide> a = array([[1, 2, 3], [4, 5, 6]]) <del> # <add> <ide> assert_equal(a.sum(0), [5, 7, 9]) <ide> assert_equal(a.sum(-1), [6, 15]) <ide> assert_equal(a.sum(1), [6, 15]) <del> # <add> <ide> assert_equal(a.prod(0), [4, 10, 18]) <ide> assert_equal(a.prod(-1), [6, 120]) <ide> assert_equal(a.prod(1), [6, 120]) <del> # <add> <ide> assert_equal(a.min(0), [1, 2, 3]) <ide> assert_equal(a.min(-1), [1, 4]) <ide> assert_equal(a.min(1), [1, 4]) <del> # <add> <ide> assert_equal(a.max(0), [4, 5, 6]) <ide> assert_equal(a.max(-1), [3, 6]) <ide> assert_equal(a.max(1), [3, 6]) <ide> <ide> <del>#------------------------------------------------------------------------------ <ide> class TestMaskedArrayMathMethodsComplex(TestCase): <ide> # Test class for miscellaneous MaskedArrays methods. <ide> def setUp(self): <ide> def test_varstd(self): <ide> mX[:, k].compressed().std()) <ide> <ide> <del>#------------------------------------------------------------------------------ <ide> class TestMaskedArrayFunctions(TestCase): <ide> # Test class for miscellaneous functions. <ide> <ide> def test_masked_where_structured(self): <ide> # test that masked_where on a structured array sets a structured <ide> # mask (see issue #2972) <ide> a = np.zeros(10, dtype=[("A", "<f2"), ("B", "<f4")]) <del> am = np.ma.masked_where(a["A"]<5, a) <add> am = np.ma.masked_where(a["A"] < 5, a) <ide> assert_equal(am.mask.dtype.names, am.dtype.names) <ide> assert_equal(am["A"], <ide> np.ma.masked_array(np.zeros(10), np.ones(10))) <ide> def test_round_with_output(self): <ide> # ... the result should be the given output <ide> self.assertTrue(result is output) <ide> assert_equal(result, xm.round(decimals=2, out=output)) <del> # <add> <ide> output = empty((3, 4), dtype=float) <ide> result = xm.round(decimals=2, out=output) <ide> self.assertTrue(result is output) <ide> def test_power_w_broadcasting(self): <ide> b1 = np.array([2, 4, 3]) <ide> b2 = np.array([b1, b1]) <ide> b2m = array(b2, mask=[[0, 1, 0], [0, 1, 0]]) <del> # <add> <ide> ctrl = array([[1 ** 2, 2 ** 4, 3 ** 3], [4 ** 2, 5 ** 4, 6 ** 3]], <ide> mask=[[1, 1, 0], [0, 1, 1]]) <ide> # No broadcasting, base & exp w/ mask <ide> def test_power_w_broadcasting(self): <ide> test = a2 ** b2m <ide> assert_equal(test, ctrl) <ide> assert_equal(test.mask, b2m.mask) <del> # <add> <ide> ctrl = array([[2 ** 2, 4 ** 4, 3 ** 3], [2 ** 2, 4 ** 4, 3 ** 3]], <ide> mask=[[0, 1, 0], [0, 1, 0]]) <ide> test = b1 ** b2m <ide> def test_where(self): <ide> xm = masked_array(x, mask=m1) <ide> ym = masked_array(y, mask=m2) <ide> xm.set_fill_value(1e+20) <del> # <add> <ide> d = where(xm > 2, xm, -9) <ide> assert_equal(d, [-9., -9., -9., -9., -9., 4., <ide> -9., -9., 10., -9., -9., 3.]) <ide> def test_where(self): <ide> tmp = xm._mask.copy() <ide> tmp[(xm <= 2).filled(True)] = True <ide> assert_equal(d._mask, tmp) <del> # <add> <ide> ixm = xm.astype(int) <ide> d = where(ixm > 2, ixm, masked) <ide> assert_equal(d, [-9, -9, -9, -9, -9, 4, -9, -9, 10, -9, -9, 3]) <ide> def test_where_with_masked_condition(self): <ide> assert_(z[0] is masked) <ide> assert_(z[1] is not masked) <ide> assert_(z[2] is masked) <del> # <add> <ide> x = arange(1, 6) <ide> x[-1] = masked <ide> y = arange(1, 6) * 10 <ide> def test_reshape(self): <ide> b = a.reshape(5, 2, order='F') <ide> assert_equal(b.shape, (5, 2)) <ide> self.assertTrue(b.flags['F']) <del> # <add> <ide> c = np.reshape(a, (2, 5)) <ide> self.assertTrue(isinstance(c, MaskedArray)) <ide> assert_equal(c.shape, (2, 5)) <ide> def test_compressed(self): <ide> a = np.ma.array([1, 2]) <ide> test = np.ma.compressed(a) <ide> assert_(type(test) is np.ndarray) <add> <ide> # Test case when input data is ndarray subclass <ide> class A(np.ndarray): <ide> pass <add> <ide> a = np.ma.array(A(shape=0)) <ide> test = np.ma.compressed(a) <ide> assert_(type(test) is A) <add> <ide> # Test that compress flattens <ide> test = np.ma.compressed([[1],[2]]) <ide> assert_equal(test.ndim, 1) <ide> test = np.ma.compressed([[[[[1]]]]]) <ide> assert_equal(test.ndim, 1) <add> <ide> # Test case when input is MaskedArray subclass <ide> class M(MaskedArray): <ide> pass <add> <ide> test = np.ma.compressed(M(shape=(0,1,2))) <ide> assert_equal(test.ndim, 1) <add> <ide> # with .compessed() overriden <ide> class M(MaskedArray): <ide> def compressed(self): <ide> return 42 <add> <ide> test = np.ma.compressed(M(shape=(0,1,2))) <ide> assert_equal(test, 42) <ide> <del>#------------------------------------------------------------------------------ <add> <ide> class TestMaskedFields(TestCase): <del> # <add> <ide> def setUp(self): <ide> ilist = [1, 2, 3, 4, 5] <ide> flist = [1.1, 2.2, 3.3, 4.4, 5.5] <ide> def test_set_record_slice(self): <ide> def test_mask_element(self): <ide> "Check record access" <ide> base = self.data['base'] <del> (base_a, base_b, base_c) = (base['a'], base['b'], base['c']) <ide> base[0] = masked <del> # <add> <ide> for n in ('a', 'b', 'c'): <ide> assert_equal(base[n].mask, [1, 1, 0, 0, 1]) <ide> assert_equal(base[n]._data, base._data[n]) <ide> def test_view(self): <ide> test = a.view((float, 2)) <ide> assert_equal(test, data) <ide> assert_equal(test.mask, controlmask.reshape(-1, 2)) <del> # <add> <ide> test = a.view((float, 2), np.matrix) <ide> assert_equal(test, data) <ide> self.assertTrue(isinstance(test, np.matrix)) <ide> def test_element_len(self): <ide> assert_equal(len(rec), len(self.data['ddtype'])) <ide> <ide> <del>#------------------------------------------------------------------------------ <ide> class TestMaskedView(TestCase): <del> # <add> <ide> def setUp(self): <ide> iterator = list(zip(np.arange(10), np.random.rand(10))) <ide> data = np.array(iterator) <ide> def test_view_to_simple_dtype(self): <ide> <ide> def test_view_to_flexible_dtype(self): <ide> (data, a, controlmask) = self.data <del> # <add> <ide> test = a.view([('A', float), ('B', float)]) <ide> assert_equal(test.mask.dtype.names, ('A', 'B')) <ide> assert_equal(test['A'], a['a']) <ide> assert_equal(test['B'], a['b']) <del> # <add> <ide> test = a[0].view([('A', float), ('B', float)]) <ide> self.assertTrue(isinstance(test, MaskedArray)) <ide> assert_equal(test.mask.dtype.names, ('A', 'B')) <ide> assert_equal(test['A'], a['a'][0]) <ide> assert_equal(test['B'], a['b'][0]) <del> # <add> <ide> test = a[-1].view([('A', float), ('B', float)]) <ide> self.assertTrue(isinstance(test, MaskedArray)) <ide> assert_equal(test.dtype.names, ('A', 'B')) <ide> def test_view_to_subdtype(self): <ide> <ide> def test_view_to_dtype_and_type(self): <ide> (data, a, controlmask) = self.data <del> # <add> <ide> test = a.view((float, 2), np.matrix) <ide> assert_equal(test, data) <ide> self.assertTrue(isinstance(test, np.matrix)) <ide> def test_append_masked_array_along_axis(): <ide> assert_array_equal(result.mask, expected.mask) <ide> <ide> <del>############################################################################### <ide> if __name__ == "__main__": <ide> run_module_suite() <ide><path>numpy/ma/tests/test_extras.py <ide> """ <ide> from __future__ import division, absolute_import, print_function <ide> <del>__author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" <del>__version__ = '1.0' <del>__revision__ = "$Revision: 3473 $" <del>__date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' <del> <ide> import warnings <ide> <ide> import numpy as np <del>from numpy.testing import (TestCase, run_module_suite, assert_warns, <del> assert_raises, clear_and_catch_warnings) <del>from numpy.ma.testutils import (rand, assert_, assert_array_equal, <del> assert_equal, assert_almost_equal) <del>from numpy.ma.core import (array, arange, masked, MaskedArray, masked_array, <del> getmaskarray, shape, nomask, ones, zeros, count) <del>import numpy.ma.extras as mae <add>from numpy.testing import ( <add> TestCase, run_module_suite, assert_warns, clear_and_catch_warnings <add> ) <add>from numpy.ma.testutils import ( <add> assert_, assert_array_equal, assert_equal, assert_almost_equal <add> ) <add>from numpy.ma.core import ( <add> array, arange, masked, MaskedArray, masked_array, getmaskarray, shape, <add> nomask, ones, zeros, count <add> ) <ide> from numpy.ma.extras import ( <del> atleast_2d, mr_, dot, polyfit, <del> cov, corrcoef, median, average, <del> unique, setxor1d, setdiff1d, union1d, intersect1d, in1d, ediff1d, <del> apply_over_axes, apply_along_axis, <del> compress_nd, compress_rowcols, mask_rowcols, <del> clump_masked, clump_unmasked, <del> flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges, <del> masked_all, masked_all_like) <add> atleast_2d, mr_, dot, polyfit, cov, corrcoef, median, average, unique, <add> setxor1d, setdiff1d, union1d, intersect1d, in1d, ediff1d, <add> apply_over_axes, apply_along_axis, compress_nd, compress_rowcols, <add> mask_rowcols, clump_masked, clump_unmasked, flatnotmasked_contiguous, <add> notmasked_contiguous, notmasked_edges, masked_all, masked_all_like <add> ) <add>import numpy.ma.extras as mae <ide> <ide> <ide> class TestGeneric(TestCase): <ide> def test_1d(self): <ide> <ide> def test_2d(self): <ide> # Tests mr_ on 2D arrays. <del> a_1 = rand(5, 5) <del> a_2 = rand(5, 5) <del> m_1 = np.round_(rand(5, 5), 0) <del> m_2 = np.round_(rand(5, 5), 0) <add> a_1 = np.random.rand(5, 5) <add> a_2 = np.random.rand(5, 5) <add> m_1 = np.round_(np.random.rand(5, 5), 0) <add> m_2 = np.round_(np.random.rand(5, 5), 0) <ide> b_1 = masked_array(a_1, mask=m_1) <ide> b_2 = masked_array(a_2, mask=m_2) <ide> # append columns <ide> def test_compress_nd(self): <ide> <ide> # axis=None <ide> a = compress_nd(x) <del> assert_equal(a, [[[ 0, 2, 3 , 4], <add> assert_equal(a, [[[ 0, 2, 3, 4], <ide> [10, 12, 13, 14], <ide> [15, 17, 18, 19]], <ide> [[40, 42, 43, 44], <ide> [50, 52, 53, 54], <ide> [55, 57, 58, 59]]]) <del> <add> <ide> # axis=0 <ide> a = compress_nd(x, 0) <ide> assert_equal(a, [[[ 0, 1, 2, 3, 4], <ide> def test_compress_nd(self): <ide> <ide> # axis=(0, 2) <ide> a = compress_nd(x, (0, 2)) <del> assert_equal(a, [[[ 0, 2, 3, 4], <del> [ 5, 7, 8, 9], <add> assert_equal(a, [[[ 0, 2, 3, 4], <add> [ 5, 7, 8, 9], <ide> [10, 12, 13, 14], <ide> [15, 17, 18, 19]], <ide> [[40, 42, 43, 44], <ide> def myfunc(b): <ide> xa = apply_along_axis(myfunc, 2, a) <ide> assert_equal(xa, [[1, 4], [7, 10]]) <ide> <del> # Tests kwargs functions <add> # Tests kwargs functions <ide> def test_3d_kwargs(self): <ide> a = arange(12).reshape(2, 2, 3) <ide> <ide> def test_setdiff1d_char_array(self): <ide> <ide> <ide> class TestShapeBase(TestCase): <del> # <add> <ide> def test_atleast2d(self): <ide> # Test atleast_2d <ide> a = masked_array([0, 1, 2], mask=[0, 1, 0]) <ide> def test_atleast2d(self): <ide> assert_equal(a.mask.shape, a.data.shape) <ide> <ide> <del>############################################################################### <del>#------------------------------------------------------------------------------ <ide> if __name__ == "__main__": <ide> run_module_suite() <ide><path>numpy/ma/tests/test_mrecords.py <ide> import numpy as np <ide> import numpy.ma as ma <ide> from numpy import recarray <del>from numpy.core.records import (fromrecords as recfromrecords, <del> fromarrays as recfromarrays) <del> <ide> from numpy.compat import asbytes, asbytes_nested <del>from numpy.ma.testutils import * <ide> from numpy.ma import masked, nomask <del>from numpy.ma.mrecords import (MaskedRecords, mrecarray, fromarrays, <del> fromtextfile, fromrecords, addfield) <del> <del> <del>__author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" <del>__revision__ = "$Revision: 3473 $" <del>__date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' <add>from numpy.testing import TestCase, run_module_suite <add>from numpy.core.records import ( <add> fromrecords as recfromrecords, fromarrays as recfromarrays <add> ) <add>from numpy.ma.mrecords import ( <add> MaskedRecords, mrecarray, fromarrays, fromtextfile, fromrecords, <add> addfield <add> ) <add>from numpy.ma.testutils import ( <add> assert_, assert_equal, <add> assert_equal_records, <add> ) <ide> <ide> <del>#.............................................................................. <ide> class TestMRecords(TestCase): <ide> # Base test class for MaskedArrays. <ide> def __init__(self, *args, **kwds): <ide> def test_set_fields(self): <ide> data = ma.array([('a', 1), ('b', 2), ('c', 3)], dtype=ndtype) <ide> rdata = data.view(MaskedRecords) <ide> val = ma.array([10, 20, 30], mask=[1, 0, 0]) <del> # <add> <ide> with warnings.catch_warnings(): <ide> warnings.simplefilter("ignore") <ide> rdata['num'] = val <ide> def test_set_mask_fromarray(self): <ide> <ide> def test_set_mask_fromfields(self): <ide> mbase = self.base.copy().view(mrecarray) <del> # <add> <ide> nmask = np.array( <ide> [(0, 1, 0), (0, 1, 0), (1, 0, 1), (1, 0, 1), (0, 0, 0)], <ide> dtype=[('a', bool), ('b', bool), ('c', bool)]) <ide> def test_set_elements(self): <ide> assert_equal(mbase.c._data, <ide> asbytes_nested(['5', '5', 'three', 'four', 'five'])) <ide> assert_equal(mbase.b._mask, [0, 0, 0, 0, 1]) <del> # <add> <ide> mbase = base.view(mrecarray).copy() <ide> mbase[:2] = masked <ide> assert_equal(mbase.a._data, [1, 2, 3, 4, 5]) <ide> def test_tolist(self): <ide> ddtype = [('a', int), ('b', float), ('c', '|S8')] <ide> mrec = fromarrays([_a, _b, _c], dtype=ddtype, <ide> fill_value=(99999, 99999., 'N/A')) <del> # <add> <ide> assert_equal(mrec.tolist(), <ide> [(1, 1.1, None), (2, 2.2, asbytes('two')), <ide> (None, None, asbytes('three'))]) <ide> def test_exotic_formats(self): <ide> easy = mrecarray(1, dtype=[('i', int), ('s', '|S8'), ('f', float)]) <ide> easy[0] = masked <ide> assert_equal(easy.filled(1).item(), (1, asbytes('1'), 1.)) <del> # <add> <ide> solo = mrecarray(1, dtype=[('f0', '<f8', (2, 2))]) <ide> solo[0] = masked <ide> assert_equal(solo.filled(1).item(), <ide> np.array((1,), dtype=solo.dtype).item()) <del> # <add> <ide> mult = mrecarray(2, dtype="i4, (2,3)float, float") <ide> mult[0] = masked <ide> mult[1] = (1, 1, 1) <ide> def test_exotic_formats(self): <ide> <ide> <ide> class TestView(TestCase): <del> # <add> <ide> def setUp(self): <ide> (a, b) = (np.arange(10), np.random.rand(10)) <ide> ndtype = [('a', np.float), ('b', np.float)] <ide> def test_view_flexible_type(self): <ide> self.assertTrue(test._fill_value is None) <ide> <ide> <del>############################################################################### <add>############################################################################## <ide> class TestMRecordsImport(TestCase): <ide> # Base test class for MaskedArrays. <ide> def __init__(self, *args, **kwds): <ide> def test_fromrecords(self): <ide> assert_equal(_mrec.dtype, mrec.dtype) <ide> for field in _mrec.dtype.names: <ide> assert_equal(getattr(_mrec, field), getattr(mrec._data, field)) <del> # <add> <ide> _mrec = fromrecords(nrec.tolist(), names='c1,c2,c3') <ide> assert_equal(_mrec.dtype, [('c1', int), ('c2', float), ('c3', '|S5')]) <ide> for (f, n) in zip(('c1', 'c2', 'c3'), ('a', 'b', 'c')): <ide> assert_equal(getattr(_mrec, f), getattr(mrec._data, n)) <del> # <add> <ide> _mrec = fromrecords(mrec) <ide> assert_equal(_mrec.dtype, mrec.dtype) <ide> assert_equal_records(_mrec._data, mrec.filled()) <ide> def test_fromrecords(self): <ide> def test_fromrecords_wmask(self): <ide> # Tests construction from records w/ mask. <ide> (mrec, nrec, ddtype) = self.data <del> # <add> <ide> _mrec = fromrecords(nrec.tolist(), dtype=ddtype, mask=[0, 1, 0,]) <ide> assert_equal_records(_mrec._data, mrec._data) <ide> assert_equal(_mrec._mask.tolist(), [(0, 0, 0), (1, 1, 1), (0, 0, 0)]) <del> # <add> <ide> _mrec = fromrecords(nrec.tolist(), dtype=ddtype, mask=True) <ide> assert_equal_records(_mrec._data, mrec._data) <ide> assert_equal(_mrec._mask.tolist(), [(1, 1, 1), (1, 1, 1), (1, 1, 1)]) <del> # <add> <ide> _mrec = fromrecords(nrec.tolist(), dtype=ddtype, mask=mrec._mask) <ide> assert_equal_records(_mrec._data, mrec._data) <ide> assert_equal(_mrec._mask.tolist(), mrec._mask.tolist()) <del> # <add> <ide> _mrec = fromrecords(nrec.tolist(), dtype=ddtype, <ide> mask=mrec._mask.tolist()) <ide> assert_equal_records(_mrec._data, mrec._data) <ide> assert_equal(_mrec._mask.tolist(), mrec._mask.tolist()) <ide> <ide> def test_fromtextfile(self): <ide> # Tests reading from a text file. <del> fcontent = asbytes("""# <add> fcontent = asbytes( <add>"""# <ide> 'One (S)','Two (I)','Three (F)','Four (M)','Five (-)','Six (C)' <ide> 'strings',1,1.0,'mixed column',,1 <ide> 'with embedded "double quotes"',2,2.0,1.0,,1 <ide> def test_fromtextfile(self): <ide> os.close(tmp_fd) <ide> mrectxt = fromtextfile(tmp_fl, delimitor=',', varnames='ABCDEFG') <ide> os.remove(tmp_fl) <del> # <add> <ide> self.assertTrue(isinstance(mrectxt, MaskedRecords)) <ide> assert_equal(mrectxt.F, [1, 1, 1, 1]) <ide> assert_equal(mrectxt.E._mask, [1, 1, 1, 1]) <ide> def test_record_array_with_object_field(): <ide> y[1] <ide> <ide> <del>############################################################################### <del>#------------------------------------------------------------------------------ <ide> if __name__ == "__main__": <ide> run_module_suite() <ide><path>numpy/ma/tests/test_old_ma.py <ide> from __future__ import division, absolute_import, print_function <ide> <del>import sys <ide> from functools import reduce <ide> <ide> import numpy as np <del>from numpy.ma import * <del>from numpy.core.numerictypes import float32 <del>from numpy.ma.core import umath <del>from numpy.testing import * <add>import numpy.core.umath as umath <add>import numpy.core.fromnumeric as fromnumeric <add>from numpy.testing import TestCase, run_module_suite, assert_ <add>from numpy.ma.testutils import assert_array_equal <add>from numpy.ma import ( <add> MaskType, MaskedArray, absolute, add, all, allclose, allequal, alltrue, <add> arange, arccos, arcsin, arctan, arctan2, array, average, choose, <add> concatenate, conjugate, cos, cosh, count, divide, equal, exp, filled, <add> getmask, greater, greater_equal, inner, isMaskedArray, less, <add> less_equal, log, log10, make_mask, masked, masked_array, masked_equal, <add> masked_greater, masked_greater_equal, masked_inside, masked_less, <add> masked_less_equal, masked_not_equal, masked_outside, <add> masked_print_option, masked_values, masked_where, maximum, minimum, <add> multiply, nomask, nonzero, not_equal, ones, outer, product, put, ravel, <add> repeat, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, <add> take, tan, tanh, transpose, where, zeros, <add> ) <ide> <ide> pi = np.pi <ide> <ide> <ide> def eq(v, w, msg=''): <ide> result = allclose(v, w) <ide> if not result: <del> print("""Not eq:%s <del>%s <del>---- <del>%s""" % (msg, str(v), str(w))) <add> print("Not eq:%s\n%s\n----%s" % (msg, str(v), str(w))) <ide> return result <ide> <ide> <ide> def test_testCI(self): <ide> x2 = array(x1, mask=[1, 0, 0, 0]) <ide> x3 = array(x1, mask=[0, 1, 0, 1]) <ide> x4 = array(x1) <del> # test conversion to strings <del> junk, garbage = str(x2), repr(x2) <add> # test conversion to strings <add> str(x2) # raises? <add> repr(x2) # raises? <ide> assert_(eq(np.sort(x1), sort(x2, fill_value=0))) <del> # tests of indexing <add> # tests of indexing <ide> assert_(type(x2[1]) is type(x1[1])) <ide> assert_(x1[1] == x2[1]) <ide> assert_(x2[0] is masked) <ide> def test_testOddFeatures(self): <ide> [1, 0, 1, 0, 1])) <ide> assert_(eq(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]), <ide> [99, 99, 3, 4, 5])) <del> atest = ones((10, 10, 10), dtype=float32) <add> atest = ones((10, 10, 10), dtype=np.float32) <ide> btest = zeros(atest.shape, MaskType) <ide> ctest = masked_where(btest, atest) <ide> assert_(eq(atest, ctest)) <ide> def test_testInplace(self): <ide> xm /= arange(10) <ide> assert_(eq(xm, ones((10,)))) <ide> <del> x = arange(10).astype(float32) <add> x = arange(10).astype(np.float32) <ide> xm = arange(10) <ide> xm[2] = masked <ide> x += 1. <ide><path>numpy/ma/tests/test_subclassing.py <ide> """ <ide> from __future__ import division, absolute_import, print_function <ide> <del>__author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" <del>__version__ = '1.0' <del>__revision__ = "$Revision: 3473 $" <del>__date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' <del> <ide> import numpy as np <del>from numpy.testing import * <del>from numpy.ma.testutils import * <del>from numpy.ma.core import * <add>from numpy.testing import TestCase, run_module_suite, assert_raises <add>from numpy.ma.testutils import assert_equal <add>from numpy.ma.core import ( <add> array, arange, masked, MaskedArray, masked_array, log, add, hypot, <add> divide, asarray, asanyarray, nomask <add> ) <add># from numpy.ma.core import ( <ide> <ide> <ide> class SubArray(np.ndarray): <ide><path>numpy/ma/testutils.py <ide> import numpy.testing.utils as utils <ide> from .core import mask_or, getmask, masked_array, nomask, masked, filled <ide> <del>__all__ = [ <add>__all__masked = [ <ide> 'almost', 'approx', 'assert_almost_equal', 'assert_array_almost_equal', <ide> 'assert_array_approx_equal', 'assert_array_compare', <ide> 'assert_array_equal', 'assert_array_less', 'assert_close', <ide> 'assert_equal', 'assert_equal_records', 'assert_mask_equal', <ide> 'assert_not_equal', 'fail_if_array_equal', <ide> ] <ide> <add># Include some normal test functions to avoid breaking other projects who <add># have mistakenly included them from this file. SciPy is one. That was a <add># bad idea, as some of these functions are not intended to work with masked <add># arrays, but there was no way to tell before. <add>__all__from_testing = [ <add> 'TestCase', 'assert_', 'assert_allclose', <add> 'assert_array_almost_equal_nulp', 'assert_raises', 'run_modules_suite', <add> ] <add> <add>__all__ = __all__masked <add> <add> <ide> def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8): <ide> """ <ide> Returns true if all components of a and b are equal to given tolerances.
6
Javascript
Javascript
define constants with const
86eda173b16b6ece9712e066661a0ac5db6795e8
<ide><path>lib/fs.js <ide> var FSReqWrap = binding.FSReqWrap; <ide> var Readable = Stream.Readable; <ide> var Writable = Stream.Writable; <ide> <del>var kMinPoolSpace = 128; <del>var kMaxLength = require('smalloc').kMaxLength; <del> <del>var O_APPEND = constants.O_APPEND || 0; <del>var O_CREAT = constants.O_CREAT || 0; <del>var O_EXCL = constants.O_EXCL || 0; <del>var O_RDONLY = constants.O_RDONLY || 0; <del>var O_RDWR = constants.O_RDWR || 0; <del>var O_SYNC = constants.O_SYNC || 0; <del>var O_TRUNC = constants.O_TRUNC || 0; <del>var O_WRONLY = constants.O_WRONLY || 0; <del>var F_OK = constants.F_OK || 0; <del>var R_OK = constants.R_OK || 0; <del>var W_OK = constants.W_OK || 0; <del>var X_OK = constants.X_OK || 0; <add>const kMinPoolSpace = 128; <add>const kMaxLength = require('smalloc').kMaxLength; <add> <add>const O_APPEND = constants.O_APPEND || 0; <add>const O_CREAT = constants.O_CREAT || 0; <add>const O_EXCL = constants.O_EXCL || 0; <add>const O_RDONLY = constants.O_RDONLY || 0; <add>const O_RDWR = constants.O_RDWR || 0; <add>const O_SYNC = constants.O_SYNC || 0; <add>const O_TRUNC = constants.O_TRUNC || 0; <add>const O_WRONLY = constants.O_WRONLY || 0; <add>const F_OK = constants.F_OK || 0; <add>const R_OK = constants.R_OK || 0; <add>const W_OK = constants.W_OK || 0; <add>const X_OK = constants.X_OK || 0; <ide> <ide> var isWindows = process.platform === 'win32'; <ide>
1
Javascript
Javascript
use attribute for media, srcset and sizes
942d358acea51cb93c172f01a2ab8094bc661808
<ide><path>src/browser/ui/dom/HTMLDOMPropertyConfig.js <ide> var HTMLDOMPropertyConfig = { <ide> loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, <ide> max: null, <ide> maxLength: MUST_USE_ATTRIBUTE, <del> media: null, <add> media: MUST_USE_ATTRIBUTE, <ide> mediaGroup: null, <ide> method: null, <ide> min: null, <ide> var HTMLDOMPropertyConfig = { <ide> selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, <ide> shape: null, <ide> size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, <del> sizes: null, <add> sizes: MUST_USE_ATTRIBUTE, <ide> span: HAS_POSITIVE_NUMERIC_VALUE, <ide> spellCheck: null, <ide> src: null, <ide> srcDoc: MUST_USE_PROPERTY, <del> srcSet: null, <add> srcSet: MUST_USE_ATTRIBUTE, <ide> start: HAS_NUMERIC_VALUE, <ide> step: null, <ide> style: null,
1
Ruby
Ruby
extract installer setup to prelude method
4c0db19538d69cc2d00f8455b94c85d75c9a4203
<ide><path>Library/Homebrew/cmd/install.rb <ide> def perform_preinstall_checks <ide> <ide> def install_formula f <ide> fi = FormulaInstaller.new(f) <add> fi.prelude <ide> fi.install <ide> fi.caveats <ide> fi.finish <ide><path>Library/Homebrew/cmd/upgrade.rb <ide> def upgrade_formula f <ide> installer = FormulaInstaller.new(f) <ide> installer.options |= Tab.for_formula(f).used_options <ide> installer.show_header = false <add> installer.prelude <ide> <ide> oh1 "Upgrading #{f.name}" <ide> <ide><path>Library/Homebrew/formula_installer.rb <ide> def initialize ff <ide> <ide> @poured_bottle = false <ide> @pour_failed = false <del> <del> verify_deps_exist unless ignore_deps <del> lock <del> check_install_sanity <ide> end <ide> <ide> def pour_bottle? install_bottle_options={:warn=>false} <ide> return false if @pour_failed <ide> options.empty? && install_bottle?(f, install_bottle_options) <ide> end <ide> <add> def prelude <add> verify_deps_exist unless ignore_deps <add> lock <add> check_install_sanity <add> end <add> <ide> def verify_deps_exist <ide> f.recursive_dependencies.map(&:to_formula) <ide> rescue TapFormulaUnavailableError => e <ide> def install_dependency(dep, inherited_options) <ide> fi.ignore_deps = true <ide> fi.only_deps = false <ide> fi.show_header = false <add> fi.prelude <ide> oh1 "Installing #{f} dependency: #{Tty.green}#{dep.name}#{Tty.reset}" <ide> outdated_keg.unlink if outdated_keg <ide> fi.install
3
Ruby
Ruby
test the correct object
1396b05e5a36859a9730e7a4a56abba02c41c0d6
<ide><path>actionpack/test/controller/parameters/parameters_permit_test.rb <ide> def walk_permitted(params) <ide> params = ActionController::Parameters.new(crab: "Senjougahara Hitagi") <ide> <ide> assert params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess <del> assert_not @params.to_h.is_a? ActionController::Parameters <add> assert_not params.to_h.is_a? ActionController::Parameters <ide> assert_equal({ "crab" => "Senjougahara Hitagi" }, params.to_h) <ide> ensure <ide> ActionController::Parameters.permit_all_parameters = false
1
Text
Text
add changelog entry for
4c1c2e650155fd17ceeb41580650da67b684fb34
<ide><path>activerecord/CHANGELOG.md <add>* Load fixtures from linked folders. <add> <add> *Kassio Borges* <add> <ide> * Create a directory for sqlite3 file if not present on the system. <ide> <ide> *Richard Schneeman*
1
Java
Java
notify viewmanagers when a view is deleted
7b82df287d36e39073d29e3ae3adbe82cf424055
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java <ide> public void removeViewAt(final int tag, final int parentTag, final int index) { <ide> } <ide> <ide> throw new IllegalStateException( <del> "Tried to delete view [" <add> "Tried to remove view [" <ide> + tag <ide> + "] of parent [" <ide> + parentTag <ide> public void deleteView(int reactTag) { <ide> // Additionally, as documented in `dropView`, we cannot always trust a <ide> // view's children to be up-to-date. <ide> mTagToViewState.remove(reactTag); <add> <add> // For non-root views we notify viewmanager with {@link ViewManager#onDropInstance} <add> ViewManager viewManager = viewState.mViewManager; <add> if (!viewState.mIsRoot && viewManager != null) { <add> viewManager.onDropViewInstance(viewState.mView); <add> } <ide> } <ide> <ide> @UiThread
1
Ruby
Ruby
support index.length for mysql 8.0.0-dmr
32fc0331227ab9b14c875837ea66be8ee70ab96b
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def indexes(table_name, name = nil) #:nodoc: <ide> end <ide> <ide> indexes.last.columns << row[:Column_name] <del> indexes.last.lengths.merge!(row[:Column_name] => row[:Sub_part]) if row[:Sub_part] <add> indexes.last.lengths.merge!(row[:Column_name] => row[:Sub_part].to_i) if row[:Sub_part] <ide> end <ide> end <ide>
1
Javascript
Javascript
add bailout effecttag for react devtools
a37012a6b5fb5a1c0c19c962737189aeaebe3684
<ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js <ide> var { <ide> Fragment, <ide> } = ReactTypeOfWork; <ide> var {NoWork, OffscreenPriority} = require('ReactPriorityLevel'); <del>var {Placement, ContentReset, Err, Ref} = require('ReactTypeOfSideEffect'); <add>var { <add> PerformedWork, <add> Placement, <add> ContentReset, <add> Err, <add> Ref, <add>} = require('ReactTypeOfSideEffect'); <ide> var ReactFiberClassComponent = require('ReactFiberClassComponent'); <ide> var {ReactCurrentOwner} = require('ReactGlobalSharedState'); <ide> var invariant = require('fbjs/lib/invariant'); <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> } else { <ide> nextChildren = fn(nextProps, context); <ide> } <add> // React DevTools reads this flag. <add> workInProgress.effectTag |= PerformedWork; <ide> reconcileChildren(current, workInProgress, nextChildren); <ide> memoizeProps(workInProgress, nextProps); <ide> return workInProgress.child; <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> } else { <ide> nextChildren = instance.render(); <ide> } <add> // React DevTools reads this flag. <add> workInProgress.effectTag |= PerformedWork; <ide> reconcileChildren(current, workInProgress, nextChildren); <ide> // Memoize props and state using the values we just used to render. <ide> // TODO: Restructure so we never read values from the instance. <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> } else { <ide> value = fn(props, context); <ide> } <add> // React DevTools reads this flag. <add> workInProgress.effectTag |= PerformedWork; <ide> <ide> if ( <ide> typeof value === 'object' && <ide><path>src/renderers/shared/fiber/ReactFiberScheduler.js <ide> var { <ide> var {AsyncUpdates} = require('ReactTypeOfInternalContext'); <ide> <ide> var { <del> NoEffect, <add> PerformedWork, <ide> Placement, <ide> Update, <ide> PlacementAndUpdate, <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> // updates, and deletions. To avoid needing to add a case for every <ide> // possible bitmap value, we remove the secondary effects from the <ide> // effect tag and switch on that value. <del> let primaryEffectTag = effectTag & ~(Callback | Err | ContentReset | Ref); <add> let primaryEffectTag = <add> effectTag & ~(Callback | Err | ContentReset | Ref | PerformedWork); <ide> switch (primaryEffectTag) { <ide> case Placement: { <ide> commitPlacement(nextEffect); <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> priorityContext = TaskPriority; <ide> <ide> let firstEffect; <del> if (finishedWork.effectTag !== NoEffect) { <add> if (finishedWork.effectTag > PerformedWork) { <ide> // A fiber's effect list consists only of its children, not itself. So if <ide> // the root has an effect, we need to add it to the end of the list. The <ide> // resulting list is the set that would belong to the root's parent, if <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> // to schedule our own side-effect on our own list because if end up <ide> // reusing children we'll schedule this effect onto itself since we're <ide> // at the end. <del> if (workInProgress.effectTag !== NoEffect) { <add> const effectTag = workInProgress.effectTag; <add> // Skip both NoWork and PerformedWork tags when creating the effect list. <add> // PerformedWork effect is read by React DevTools but shouldn't be committed. <add> if (effectTag > PerformedWork) { <ide> if (returnFiber.lastEffect !== null) { <ide> returnFiber.lastEffect.nextEffect = workInProgress; <ide> } else { <ide><path>src/renderers/shared/fiber/ReactTypeOfSideEffect.js <ide> export type TypeOfSideEffect = number; <ide> <ide> module.exports = { <del> NoEffect: 0, // 0b0000000 <del> Placement: 1, // 0b0000001 <del> Update: 2, // 0b0000010 <del> PlacementAndUpdate: 3, // 0b0000011 <del> Deletion: 4, // 0b0000100 <del> ContentReset: 8, // 0b0001000 <del> Callback: 16, // 0b0010000 <del> Err: 32, // 0b0100000 <del> Ref: 64, // 0b1000000 <add> // Don't change these two values: <add> NoEffect: 0, // 0b00000000 <add> PerformedWork: 1, // 0b00000001 <add> // You can change the rest (and add more). <add> Placement: 2, // 0b00000010 <add> Update: 4, // 0b00000100 <add> PlacementAndUpdate: 6, // 0b00000110 <add> Deletion: 8, // 0b00001000 <add> ContentReset: 16, // 0b00010000 <add> Callback: 32, // 0b00100000 <add> Err: 64, // 0b01000000 <add> Ref: 128, // 0b10000000 <ide> };
3
Mixed
Ruby
add support to libvips in the image analyzer
82fdf45fe5dd74a6dfd962715dd611e03571f896
<ide><path>activestorage/CHANGELOG.md <add>* Use libvips instead of ImageMagick to analyze images when `active_storage.variant_processor = vips` <add> <add> *Breno Gazzola* <add> <ide> * Add metadata value for presence of video channel in video blobs <ide> <ide> The `metadata` attribute of video blobs has a new boolean key named `video` that is set to <ide><path>activestorage/lib/active_storage/analyzer.rb <ide> <ide> module ActiveStorage <ide> # This is an abstract base class for analyzers, which extract metadata from blobs. See <del> # ActiveStorage::Analyzer::ImageAnalyzer for an example of a concrete subclass. <add> # ActiveStorage::Analyzer::VideoAnalyzer for an example of a concrete subclass. <ide> class Analyzer <ide> attr_reader :blob <ide> <ide><path>activestorage/lib/active_storage/analyzer/image_analyzer.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> # Extracts width and height in pixels from an image blob. <add> # This is an abstract base class for image analyzers, which extract width and height from an image blob. <ide> # <ide> # If the image contains EXIF data indicating its angle is 90 or 270 degrees, its width and height are swapped for convenience. <ide> # <ide> # Example: <ide> # <del> # ActiveStorage::Analyzer::ImageAnalyzer.new(blob).metadata <add> # ActiveStorage::Analyzer::ImageAnalyzer::ImageMagick.new(blob).metadata <ide> # # => { width: 4104, height: 2736 } <del> # <del> # This analyzer relies on the third-party {MiniMagick}[https://github.com/minimagick/minimagick] gem. MiniMagick requires <del> # the {ImageMagick}[http://www.imagemagick.org] system library. <ide> class Analyzer::ImageAnalyzer < Analyzer <ide> def self.accept?(blob) <ide> blob.image? <ide> def metadata <ide> end <ide> end <ide> end <del> <del> private <del> def read_image <del> download_blob_to_tempfile do |file| <del> require "mini_magick" <del> image = MiniMagick::Image.new(file.path) <del> <del> if image.valid? <del> yield image <del> else <del> logger.info "Skipping image analysis because ImageMagick doesn't support the file" <del> {} <del> end <del> end <del> rescue LoadError <del> logger.info "Skipping image analysis because the mini_magick gem isn't installed" <del> {} <del> rescue MiniMagick::Error => error <del> logger.error "Skipping image analysis due to an ImageMagick error: #{error.message}" <del> {} <del> end <del> <del> def rotated_image?(image) <del> %w[ RightTop LeftBottom ].include?(image["%[orientation]"]) <del> end <ide> end <ide> end <ide><path>activestorage/lib/active_storage/analyzer/image_analyzer/image_magick.rb <add># frozen_string_literal: true <add> <add>module ActiveStorage <add> # This analyzer relies on the third-party {MiniMagick}[https://github.com/minimagick/minimagick] gem. MiniMagick requires <add> # the {ImageMagick}[http://www.imagemagick.org] system library. <add> class Analyzer::ImageAnalyzer::ImageMagick < Analyzer::ImageAnalyzer <add> def self.accept?(blob) <add> super && ActiveStorage.variant_processor == :mini_magick <add> end <add> <add> private <add> def read_image <add> download_blob_to_tempfile do |file| <add> require "mini_magick" <add> image = MiniMagick::Image.new(file.path) <add> <add> if image.valid? <add> yield image <add> else <add> logger.info "Skipping image analysis because ImageMagick doesn't support the file" <add> {} <add> end <add> end <add> rescue LoadError <add> logger.info "Skipping image analysis because the mini_magick gem isn't installed" <add> {} <add> rescue MiniMagick::Error => error <add> logger.error "Skipping image analysis due to an ImageMagick error: #{error.message}" <add> {} <add> end <add> <add> def rotated_image?(image) <add> %w[ RightTop LeftBottom TopRight BottomLeft ].include?(image["%[orientation]"]) <add> end <add> end <add>end <ide><path>activestorage/lib/active_storage/analyzer/image_analyzer/vips.rb <add># frozen_string_literal: true <add> <add>module ActiveStorage <add> # This analyzer relies on the third-party {ruby-vips}[https://github.com/libvips/ruby-vips] gem. Ruby-vips requires <add> # the {libvips}[https://libvips.github.io/libvips/] system library. <add> class Analyzer::ImageAnalyzer::Vips < Analyzer::ImageAnalyzer <add> def self.accept?(blob) <add> super && ActiveStorage.variant_processor == :vips <add> end <add> <add> private <add> def read_image <add> download_blob_to_tempfile do |file| <add> require "ruby-vips" <add> image = ::Vips::Image.new_from_file(file.path, access: :sequential) <add> <add> if valid_image?(image) <add> yield image <add> else <add> logger.info "Skipping image analysis because Vips doesn't support the file" <add> {} <add> end <add> end <add> rescue LoadError <add> logger.info "Skipping image analysis because the ruby-vips gem isn't installed" <add> {} <add> rescue ::Vips::Error => error <add> logger.error "Skipping image analysis due to an Vips error: #{error.message}" <add> {} <add> end <add> <add> ROTATIONS = /Right-top|Left-bottom|Top-right|Bottom-left/ <add> def rotated_image?(image) <add> ROTATIONS === image.get("exif-ifd0-Orientation") <add> rescue ::Vips::Error <add> false <add> end <add> <add> def valid_image?(image) <add> image.avg <add> true <add> rescue ::Vips::Error <add> false <add> end <add> end <add>end <ide><path>activestorage/lib/active_storage/engine.rb <ide> require "active_storage/previewer/video_previewer" <ide> <ide> require "active_storage/analyzer/image_analyzer" <add>require "active_storage/analyzer/image_analyzer/image_magick" <add>require "active_storage/analyzer/image_analyzer/vips" <ide> require "active_storage/analyzer/video_analyzer" <ide> require "active_storage/analyzer/audio_analyzer" <ide> <ide> class Engine < Rails::Engine # :nodoc: <ide> <ide> config.active_storage = ActiveSupport::OrderedOptions.new <ide> config.active_storage.previewers = [ ActiveStorage::Previewer::PopplerPDFPreviewer, ActiveStorage::Previewer::MuPDFPreviewer, ActiveStorage::Previewer::VideoPreviewer ] <del> config.active_storage.analyzers = [ ActiveStorage::Analyzer::ImageAnalyzer, ActiveStorage::Analyzer::VideoAnalyzer, ActiveStorage::Analyzer::AudioAnalyzer ] <add> config.active_storage.analyzers = [ ActiveStorage::Analyzer::ImageAnalyzer::Vips, ActiveStorage::Analyzer::ImageAnalyzer::ImageMagick, ActiveStorage::Analyzer::VideoAnalyzer, ActiveStorage::Analyzer::AudioAnalyzer ] <ide> config.active_storage.paths = ActiveSupport::OrderedOptions.new <ide> config.active_storage.queues = ActiveSupport::InheritableOptions.new <ide> <ide><path>activestorage/test/analyzer/image_analyzer/image_magick_test.rb <add># frozen_string_literal: true <add> <add>require "test_helper" <add>require "database/setup" <add> <add>require "active_storage/analyzer/image_analyzer" <add> <add>class ActiveStorage::Analyzer::ImageAnalyzer::ImageMagickTest < ActiveSupport::TestCase <add> test "analyzing a JPEG image" do <add> analyze_with_image_magick do <add> blob = create_file_blob(filename: "racecar.jpg", content_type: "image/jpeg") <add> metadata = extract_metadata_from(blob) <add> <add> assert_equal 4104, metadata[:width] <add> assert_equal 2736, metadata[:height] <add> end <add> end <add> <add> test "analyzing a rotated JPEG image" do <add> analyze_with_image_magick do <add> blob = create_file_blob(filename: "racecar_rotated.jpg", content_type: "image/jpeg") <add> metadata = extract_metadata_from(blob) <add> <add> assert_equal 2736, metadata[:width] <add> assert_equal 4104, metadata[:height] <add> end <add> end <add> <add> test "analyzing an SVG image without an XML declaration" do <add> analyze_with_image_magick do <add> blob = create_file_blob(filename: "icon.svg", content_type: "image/svg+xml") <add> metadata = extract_metadata_from(blob) <add> <add> assert_equal 792, metadata[:width] <add> assert_equal 584, metadata[:height] <add> end <add> end <add> <add> test "analyzing an unsupported image type" do <add> analyze_with_image_magick do <add> blob = create_blob(data: "bad", filename: "bad_file.bad", content_type: "image/bad_type") <add> metadata = extract_metadata_from(blob) <add> <add> assert_nil metadata[:width] <add> assert_nil metadata[:height] <add> end <add> end <add> <add> private <add> def analyze_with_image_magick <add> previous_processor, ActiveStorage.variant_processor = ActiveStorage.variant_processor, :mini_magick <add> require "mini_magick" <add> <add> yield <add> rescue LoadError <add> ENV["CI"] ? raise : skip("Variant processor image_magick is not installed") <add> ensure <add> ActiveStorage.variant_processor = previous_processor <add> end <add>end <ide><path>activestorage/test/analyzer/image_analyzer/vips_test.rb <add># frozen_string_literal: true <add> <add>require "test_helper" <add>require "database/setup" <add> <add>require "active_storage/analyzer/image_analyzer" <add> <add>class ActiveStorage::Analyzer::ImageAnalyzer::VipsTest < ActiveSupport::TestCase <add> test "analyzing a JPEG image" do <add> analyze_with_vips do <add> blob = create_file_blob(filename: "racecar.jpg", content_type: "image/jpeg") <add> metadata = extract_metadata_from(blob) <add> <add> assert_equal 4104, metadata[:width] <add> assert_equal 2736, metadata[:height] <add> end <add> end <add> <add> test "analyzing a rotated JPEG image" do <add> analyze_with_vips do <add> blob = create_file_blob(filename: "racecar_rotated.jpg", content_type: "image/jpeg") <add> metadata = extract_metadata_from(blob) <add> <add> assert_equal 2736, metadata[:width] <add> assert_equal 4104, metadata[:height] <add> end <add> end <add> <add> test "analyzing an SVG image without an XML declaration" do <add> analyze_with_vips do <add> blob = create_file_blob(filename: "icon.svg", content_type: "image/svg+xml") <add> metadata = extract_metadata_from(blob) <add> <add> assert_equal 792, metadata[:width] <add> assert_equal 584, metadata[:height] <add> end <add> end <add> <add> test "analyzing an unsupported image type" do <add> analyze_with_vips do <add> blob = create_blob(data: "bad", filename: "bad_file.bad", content_type: "image/bad_type") <add> metadata = extract_metadata_from(blob) <add> <add> assert_nil metadata[:width] <add> assert_nil metadata[:height] <add> end <add> end <add> <add> private <add> def analyze_with_vips <add> previous_processor, ActiveStorage.variant_processor = ActiveStorage.variant_processor, :vips <add> require "ruby-vips" <add> <add> yield <add> rescue LoadError <add> ENV["CI"] ? raise : skip("Variant processor vips is not installed") <add> ensure <add> ActiveStorage.variant_processor = previous_processor <add> end <add>end <ide><path>activestorage/test/analyzer/image_analyzer_test.rb <del># frozen_string_literal: true <del> <del>require "test_helper" <del>require "database/setup" <del> <del>require "active_storage/analyzer/image_analyzer" <del> <del>class ActiveStorage::Analyzer::ImageAnalyzerTest < ActiveSupport::TestCase <del> test "analyzing a JPEG image" do <del> blob = create_file_blob(filename: "racecar.jpg", content_type: "image/jpeg") <del> metadata = extract_metadata_from(blob) <del> <del> assert_equal 4104, metadata[:width] <del> assert_equal 2736, metadata[:height] <del> end <del> <del> test "analyzing a rotated JPEG image" do <del> blob = create_file_blob(filename: "racecar_rotated.jpg", content_type: "image/jpeg") <del> metadata = extract_metadata_from(blob) <del> <del> assert_equal 2736, metadata[:width] <del> assert_equal 4104, metadata[:height] <del> end <del> <del> test "analyzing an SVG image without an XML declaration" do <del> blob = create_file_blob(filename: "icon.svg", content_type: "image/svg+xml") <del> metadata = extract_metadata_from(blob) <del> <del> assert_equal 792, metadata[:width] <del> assert_equal 584, metadata[:height] <del> end <del> <del> test "analyzing an unsupported image type" do <del> blob = create_blob(data: "bad", filename: "bad_file.bad", content_type: "image/bad_type") <del> metadata = extract_metadata_from(blob) <del> <del> assert_nil metadata[:width] <del> assert_nil metadata[:height] <del> end <del>end <ide><path>activestorage/test/models/variant_test.rb <ide> def process_variants_with(processor) <ide> previous_processor, ActiveStorage.variant_processor = ActiveStorage.variant_processor, processor <ide> yield <ide> rescue LoadError <del> skip "Variant processor #{processor.inspect} is not installed" <add> ENV["CI"] ? raise : skip("Variant processor #{processor.inspect} is not installed") <ide> ensure <ide> ActiveStorage.variant_processor = previous_processor <ide> end <ide><path>guides/source/configuring.md <ide> You can find more detailed configuration options in the <ide> <ide> `config.active_storage` provides the following configuration options: <ide> <del>* `config.active_storage.variant_processor` accepts a symbol `:mini_magick` or `:vips`, specifying whether variant transformations will be performed with MiniMagick or ruby-vips. The default is `:mini_magick`. <add>* `config.active_storage.variant_processor` accepts a symbol `:mini_magick` or `:vips`, specifying whether variant transformations and blob analysis will be performed with MiniMagick or ruby-vips. The default is `:mini_magick`. <ide> <del>* `config.active_storage.analyzers` accepts an array of classes indicating the analyzers available for Active Storage blobs. The default is `[ActiveStorage::Analyzer::ImageAnalyzer, ActiveStorage::Analyzer::VideoAnalyzer, ActiveStorage::Analyzer::AudioAnalyzer]`. The image analyzer can extract width and height of an image blob; the video analyzer can extract width, height, duration, angle, aspect ratio and presence/absence of video/audio channels of a video blob; the audio analyzer can extract duration and bit rate of an audio blob. <add>* `config.active_storage.analyzers` accepts an array of classes indicating the analyzers available for Active Storage blobs. The default is `[ActiveStorage::Analyzer::ImageAnalyzer::Vips, ActiveStorage::Analyzer::ImageAnalyzer::ImageMagick, ActiveStorage::Analyzer::VideoAnalyzer, ActiveStorage::Analyzer::AudioAnalyzer]`. The image analyzers can extract width and height of an image blob; the video analyzer can extract width, height, duration, angle, aspect ratio and presence/absence of video/audio channels of a video blob; the audio analyzer can extract duration and bit rate of an audio blob. <ide> <ide> * `config.active_storage.previewers` accepts an array of classes indicating the image previewers available in Active Storage blobs. The default is `[ActiveStorage::Previewer::PopplerPDFPreviewer, ActiveStorage::Previewer::MuPDFPreviewer, ActiveStorage::Previewer::VideoPreviewer]`. `PopplerPDFPreviewer` and `MuPDFPreviewer` can generate a thumbnail from the first page of a PDF blob; `VideoPreviewer` from the relevant frame of a video blob. <ide>
11
Javascript
Javascript
add cross method to vector2
ceef48eedc496698a2f92106bd01070983c13112
<ide><path>src/math/Vector2.js <ide> Object.assign( Vector2.prototype, { <ide> <ide> }, <ide> <add> cross: function ( v ) { <add> <add> return this.x * v.y - this.y * v.x; <add> <add> }, <add> <ide> lengthSq: function () { <ide> <ide> return this.x * this.x + this.y * this.y;
1
Javascript
Javascript
add test for pdfdocumentproxy_getpageindex
c547f17ee5eb086fa759472a441c1e97a8801f52
<ide><path>test/unit/api_spec.js <ide> describe('api', function() { <ide> expect(true).toEqual(true); <ide> }); <ide> }); <add> it('gets page index', function() { <add> // reference to second page <add> var ref = {num: 17, gen: 0}; <add> var promise = doc.getPageIndex(ref); <add> waitsForPromise(promise, function(pageIndex) { <add> expect(pageIndex).toEqual(1); <add> }); <add> }); <ide> it('gets destinations', function() { <ide> var promise = doc.getDestinations(); <ide> waitsForPromise(promise, function(data) {
1
Javascript
Javascript
remove duplicate fixture components
52a1ee492aa87f794320cfa4eeb921deddf7d7b1
<ide><path>fixtures/src/components/RangeInputs.js <del>const React = window.React; <del> <del>const RangeInputs = React.createClass({ <del> getInitialState() { <del> return { value: 0.5 }; <del> }, <del> onChange(event) { <del> this.setState({ value: event.target.value }); <del> }, <del> render() { <del> return ( <del> <form> <del> <fieldset> <del> <legend>Controlled</legend> <del> <input type="range" value={this.state.value} onChange={this.onChange.bind(this)} /> <del> <span className="hint">Value: {this.state.value}</span> <del> </fieldset> <del> <del> <fieldset> <del> <legend>Uncontrolled</legend> <del> <input type="range" defaultValue={0.5} /> <del> </fieldset> <del> </form> <del> ); <del> }, <del>}); <del> <del>export default RangeInputs; <ide><path>fixtures/src/components/TextInputs.js <del>const React = window.React; <del>import '../styles/TextInputs.css'; <del> <del>const TextInputFixtures = React.createClass({ <del> getInitialState() { <del> return { <del> color: '#ffaaee', <del> }; <del> }, <del> <del> renderControlled(type) { <del> let id = `controlled_${type}`; <del> <del> let onChange = e => { <del> let value = e.target.value; <del> if (type === 'number') { <del> value = value === '' ? '' : parseFloat(value, 10) || 0 <del> } <del> this.setState({ <del> [type] : value, <del> }); <del> }; <del> <del> let state = this.state[type] || ''; <del> <del> return ( <del> <div key={type} className="field"> <del> <label htmlFor={id}>{type}</label> <del> <input id={id} type={type} value={state} onChange={onChange} /> <del> &nbsp; &rarr; {JSON.stringify(state)} <del> </div> <del> ); <del> }, <del> <del> renderUncontrolled(type) { <del> let id = `uncontrolled_${type}`; <del> return ( <del> <div key={type} className="field"> <del> <label htmlFor={id}>{type}</label> <del> <input id={id} type={type} /> <del> </div> <del> ); <del> }, <del> <del> render() { <del> // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input <del> let types = [ <del> 'text', 'email', 'number', 'url', 'tel', <del> 'color', 'date', 'datetime-local', <del> 'time', 'month', 'week', 'range', 'password', <del> ]; <del> return ( <del> <form onSubmit={event => event.preventDefault()}> <del> <fieldset> <del> <legend>Controlled</legend> <del> {types.map(this.renderControlled)} <del> </fieldset> <del> <fieldset> <del> <legend>Uncontrolled</legend> <del> {types.map(this.renderUncontrolled)} <del> </fieldset> <del> </form> <del> ); <del> }, <del>}); <del> <del>module.exports = TextInputFixtures;
2
Python
Python
fix mnist sklearn wrapper example
48e1e8458e772758420efba93508de9c03cdf915
<ide><path>examples/mnist_sklearn_wrapper.py <ide> def make_model(dense_layer_sizes, filters, kernel_size, pool_size): <ide> model.add(Flatten()) <ide> for layer_size in dense_layer_sizes: <ide> model.add(Dense(layer_size)) <del> model.add(Activation('relu')) <add> model.add(Activation('relu')) <ide> model.add(Dropout(0.5)) <ide> model.add(Dense(num_classes)) <ide> model.add(Activation('softmax'))
1
Java
Java
discover controllers based on type @requestmapping
f61f4a960e1b28e96abe8912a137720fcd0690f5
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java <ide> public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi <ide> private boolean useSuffixPatternMatch = true; <ide> <ide> private boolean useTrailingSlashMatch = true; <del> <add> <ide> /** <ide> * Whether to use suffix pattern match (".*") when matching patterns to <ide> * requests. If enabled a method mapped to "/users" also matches to "/users.*". <ide> public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi <ide> public void setUseSuffixPatternMatch(boolean useSuffixPatternMatch) { <ide> this.useSuffixPatternMatch = useSuffixPatternMatch; <ide> } <del> <add> <ide> /** <ide> * Whether to match to URLs irrespective of the presence of a trailing slash. <ide> * If enabled a method mapped to "/users" also matches to "/users/". <ide> public boolean useTrailingSlashMatch() { <ide> */ <ide> @Override <ide> protected boolean isHandler(Class<?> beanType) { <del> return AnnotationUtils.findAnnotation(beanType, Controller.class) != null; <add> return ((AnnotationUtils.findAnnotation(beanType, Controller.class) != null) || <add> (AnnotationUtils.findAnnotation(beanType, RequestMapping.class) != null)); <ide> } <ide> <ide> /** <ide> protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handler <ide> protected RequestCondition<?> getCustomMethodCondition(Method method) { <ide> return null; <ide> } <del> <add> <ide> /** <ide> * Provide a custom type-level request condition. <ide> * The custom {@link RequestCondition} can be of any type so long as the <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HandlerMethodAnnotationDetectionTests.java <ide> import org.springframework.web.servlet.ModelAndView; <ide> <ide> /** <del> * Test various scenarios for detecting method-level and method parameter annotations depending <del> * on where they are located -- on interfaces, parent classes, in parameterized methods, or in <add> * Test various scenarios for detecting method-level and method parameter annotations depending <add> * on where they are located -- on interfaces, parent classes, in parameterized methods, or in <ide> * combination with proxies. <del> * <add> * <ide> * @author Rossen Stoyanchev <ide> */ <ide> @RunWith(Parameterized.class) <ide> public class HandlerMethodAnnotationDetectionTests { <del> <add> <ide> @Parameters <ide> public static Collection<Object[]> handlerTypes() { <ide> Object[][] array = new Object[12][2]; <ide> <ide> array[0] = new Object[] { SimpleController.class, true}; // CGLib proxy <ide> array[1] = new Object[] { SimpleController.class, false}; <del> <add> <ide> array[2] = new Object[] { AbstractClassController.class, true }; // CGLib proxy <ide> array[3] = new Object[] { AbstractClassController.class, false }; <del> <del> array[4] = new Object[] { ParameterizedAbstractClassController.class, false}; // CGLib proxy <del> array[5] = new Object[] { ParameterizedAbstractClassController.class, false}; <del> <add> <add> array[4] = new Object[] { ParameterizedAbstractClassController.class, false}; // CGLib proxy <add> array[5] = new Object[] { ParameterizedAbstractClassController.class, false}; <add> <ide> array[6] = new Object[] { InterfaceController.class, true }; // JDK dynamic proxy <del> array[7] = new Object[] { InterfaceController.class, false }; <del> <del> array[8] = new Object[] { ParameterizedInterfaceController.class, false}; // no AOP <del> array[9] = new Object[] { ParameterizedInterfaceController.class, false}; <del> <add> array[7] = new Object[] { InterfaceController.class, false }; <add> <add> array[8] = new Object[] { ParameterizedInterfaceController.class, false}; // no AOP <add> array[9] = new Object[] { ParameterizedInterfaceController.class, false}; <add> <ide> array[10] = new Object[] { SupportClassController.class, true}; // CGLib proxy <ide> array[11] = new Object[] { SupportClassController.class, false}; <del> <add> <ide> return Arrays.asList(array); <ide> } <ide> <ide> public HandlerMethodAnnotationDetectionTests(Class<?> controllerType, boolean us <ide> context.getBeanFactory().registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor())); <ide> } <ide> context.refresh(); <del> <add> <ide> handlerMapping.setApplicationContext(context); <ide> handlerAdapter.afterPropertiesSet(); <ide> exceptionResolver.afterPropertiesSet(); <ide> public void testRequestMappingMethod() throws Exception { <ide> SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); <ide> String dateA = "11:01:2011"; <ide> String dateB = "11:02:2011"; <del> <add> <ide> MockHttpServletRequest request = new MockHttpServletRequest("POST", "/path1/path2"); <ide> request.setParameter("datePattern", datePattern); <ide> request.addHeader("header1", dateA); <ide> request.addHeader("header2", dateB); <del> <add> <ide> HandlerExecutionChain chain = handlerMapping.getHandler(request); <ide> assertNotNull(chain); <ide> <ide> public void testRequestMappingMethod() throws Exception { <ide> assertEquals("failure", response.getContentAsString()); <ide> } <ide> <del> <add> <ide> /** <ide> * SIMPLE CASE <ide> */ <ide> public void initModel(@RequestHeader("header1") Date date, Model model) { <ide> public Date handle(@RequestHeader("header2") Date date) throws Exception { <ide> return date; <ide> } <del> <add> <ide> @ExceptionHandler(Exception.class) <ide> @ResponseBody <ide> public String handleException(Exception exception) { <ide> return exception.getMessage(); <ide> } <del> } <add> } <add> <ide> <del> <ide> @Controller <ide> static abstract class MappingAbstractClass { <ide> <ide> static abstract class MappingAbstractClass { <ide> @RequestMapping(value="/path1/path2", method=RequestMethod.POST) <ide> @ModelAttribute("attr2") <ide> public abstract Date handle(Date date, Model model) throws Exception; <del> <add> <ide> @ExceptionHandler(Exception.class) <ide> @ResponseBody <ide> public abstract String handleException(Exception exception); <del> } <add> } <ide> <ide> /** <ide> * CONTROLLER WITH ABSTRACT CLASS <del> * <add> * <ide> * <p>All annotations can be on methods in the abstract class except parameter annotations. <ide> */ <ide> static class AbstractClassController extends MappingAbstractClass { <ide> public void initModel(@RequestHeader("header1") Date date, Model model) { <ide> public Date handle(@RequestHeader("header2") Date date, Model model) throws Exception { <ide> return date; <ide> } <del> <add> <ide> public String handleException(Exception exception) { <ide> return exception.getMessage(); <ide> } <ide> } <del> <del> <del> @Controller <add> <add> // SPR-9374 <add> <add> @RequestMapping <ide> static interface MappingInterface { <ide> <ide> @InitBinder <ide> static interface MappingInterface { <ide> @RequestMapping(value="/path1/path2", method=RequestMethod.POST) <ide> @ModelAttribute("attr2") <ide> Date handle(@RequestHeader("header2") Date date, Model model) throws Exception; <del> <add> <ide> @ExceptionHandler(Exception.class) <ide> @ResponseBody <ide> String handleException(Exception exception); <del> } <add> } <ide> <ide> /** <ide> * CONTROLLER WITH INTERFACE <del> * <add> * <ide> * No AOP: <ide> * All annotations can be on interface methods except parameter annotations. <ide> * <ide> public void initModel(@RequestHeader("header1") Date date, Model model) { <ide> public Date handle(@RequestHeader("header2") Date date, Model model) throws Exception { <ide> return date; <ide> } <del> <add> <ide> public String handleException(Exception exception) { <ide> return exception.getMessage(); <ide> } <ide> public String handleException(Exception exception) { <ide> @RequestMapping(value="/path1/path2", method=RequestMethod.POST) <ide> @ModelAttribute("attr2") <ide> public abstract Date handle(C date, Model model) throws Exception; <del> <add> <ide> @ExceptionHandler(Exception.class) <ide> @ResponseBody <ide> public abstract String handleException(Exception exception); <del> } <add> } <ide> <ide> /** <ide> * CONTROLLER WITH PARAMETERIZED BASE CLASS <del> * <add> * <ide> * <p>All annotations can be on methods in the abstract class except parameter annotations. <ide> */ <ide> static class ParameterizedAbstractClassController extends MappingParameterizedAbstractClass<String, Date, Date> { <ide> public void initModel(@RequestHeader("header1") Date date, Model model) { <ide> public Date handle(@RequestHeader("header2") Date date, Model model) throws Exception { <ide> return date; <ide> } <del> <add> <ide> public String handleException(Exception exception) { <ide> return exception.getMessage(); <ide> } <ide> } <ide> <del> <del> @Controller <add> @RequestMapping <ide> static interface MappingParameterizedInterface<A, B, C> { <ide> <ide> @InitBinder <ide> public String handleException(Exception exception) { <ide> @RequestMapping(value="/path1/path2", method=RequestMethod.POST) <ide> @ModelAttribute("attr2") <ide> Date handle(C date, Model model) throws Exception; <del> <add> <ide> @ExceptionHandler(Exception.class) <ide> @ResponseBody <ide> String handleException(Exception exception); <del> } <add> } <ide> <ide> /** <ide> * CONTROLLER WITH PARAMETERIZED INTERFACE <del> * <add> * <ide> * <p>All annotations can be on interface except parameter annotations. <del> * <add> * <ide> * <p>Cannot be used as JDK dynamic proxy since parameterized interface does not contain type information. <ide> */ <ide> static class ParameterizedInterfaceController implements MappingParameterizedInterface<String, Date, Date> { <ide> public void initModel(@RequestHeader("header1") Date date, Model model) { <ide> public Date handle(@RequestHeader("header2") Date date, Model model) throws Exception { <ide> return date; <ide> } <del> <add> <ide> @ExceptionHandler(Exception.class) <ide> @ResponseBody <ide> public String handleException(Exception exception) { <ide> return exception.getMessage(); <ide> } <del> } <del> <del> <add> } <add> <add> <ide> /** <ide> * SPR-8248 <del> * <add> * <ide> * <p>Support class contains all annotations. Subclass has type-level @{@link RequestMapping}. <ide> */ <ide> @Controller <ide> public void initModel(@RequestHeader("header1") Date date, Model model) { <ide> public Date handle(@RequestHeader("header2") Date date, Model model) throws Exception { <ide> return date; <ide> } <del> <add> <ide> @ExceptionHandler(Exception.class) <ide> @ResponseBody <ide> public String handleException(Exception exception) { <ide> return exception.getMessage(); <ide> } <del> } <add> } <ide> <ide> @Controller <ide> @RequestMapping("/path1") <ide> static class SupportClassController extends MappingSupportClass { <del> } <add> } <ide> <ide> }
2
Ruby
Ruby
fix sorbet errors
4c1b2630dcf99793e8ecfed60c441dd080418401
<ide><path>Library/Homebrew/cache_store.rb <ide> def self.use(type) <ide> return_value <ide> end <ide> <add> # Creates a CacheStoreDatabase. <add> # <add> # @param [Symbol] type <add> # @return [nil] <add> def initialize(type) <add> @type = type <add> @dirty = false <add> end <add> <ide> # Sets a value in the underlying database (and creates it if necessary). <ide> def set(key, value) <ide> dirty! <ide> def db <ide> @db ||= {} <ide> end <ide> <del> # Creates a CacheStoreDatabase. <del> # <del> # @param [Symbol] type <del> # @return [nil] <del> def initialize(type) <del> @type = type <del> @dirty = false <del> end <del> <ide> # The path where the database resides in the `HOMEBREW_CACHE` for the given <ide> # `@type`. <ide> # <ide><path>Library/Homebrew/utils/spdx.rb <ide> def download_latest_license_data!(to: DATA_PATH) <ide> end <ide> <ide> def parse_license_expression(license_expression) <del> licenses = [] <del> exceptions = [] <add> licenses = T.let([], T::Array[T.any(String, Symbol)]) <add> exceptions = T.let([], T::Array[String]) <ide> <ide> case license_expression <ide> when String, Symbol
2
Python
Python
add radix2 fft
a41a14f9d89b665178f08535f128ba14652ce449
<ide><path>maths/radix2_fft.py <add>""" <add>Fast Polynomial Multiplication using radix-2 fast Fourier Transform. <add>""" <add> <add>import mpmath # for roots of unity <add>import numpy as np <add> <add> <add>class FFT: <add> """ <add> Fast Polynomial Multiplication using radix-2 fast Fourier Transform. <add> <add> Reference: <add> https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case <add> <add> For polynomials of degree m and n the algorithms has complexity <add> O(n*logn + m*logm) <add> <add> The main part of the algorithm is split in two parts: <add> 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a <add> bottom-up dynamic approach - <add> 2) __multiply: Once we obtain the DFT of A*B, we can similarly <add> invert it to obtain A*B <add> <add> The class FFT takes two polynomials A and B with complex coefficients as arguments; <add> The two polynomials should be represented as a sequence of coefficients starting <add> from the free term. Thus, for instance x + 2*x^3 could be represented as <add> [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the <add> polynomials have the same length which is a power of 2 at least the length of <add> their product. <add> <add> Example: <add> <add> Create two polynomials as sequences <add> >>> A = [0, 1, 0, 2] # x+2x^3 <add> >>> B = (2, 3, 4, 0) # 2+3x+4x^2 <add> <add> Create an FFT object with them <add> >>> x = FFT(A, B) <add> <add> Print product <add> >>> print(x.product) # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5 <add> [(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)] <add> <add> __str__ test <add> >>> print(x) <add> A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2 <add> B = 0*x^2 + 1*x^3 + 2*x^4 <add> A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j) <add> """ <add> <add> def __init__(self, polyA=[0], polyB=[0]): <add> # Input as list <add> self.polyA = list(polyA)[:] <add> self.polyB = list(polyB)[:] <add> <add> # Remove leading zero coefficients <add> while self.polyA[-1] == 0: <add> self.polyA.pop() <add> self.len_A = len(self.polyA) <add> <add> while self.polyB[-1] == 0: <add> self.polyB.pop() <add> self.len_B = len(self.polyB) <add> <add> # Add 0 to make lengths equal a power of 2 <add> self.C_max_length = int( <add> 2 <add> ** np.ceil( <add> np.log2( <add> len(self.polyA) + len(self.polyB) - 1 <add> ) <add> ) <add> ) <add> <add> while len(self.polyA) < self.C_max_length: <add> self.polyA.append(0) <add> while len(self.polyB) < self.C_max_length: <add> self.polyB.append(0) <add> # A complex root used for the fourier transform <add> self.root = complex( <add> mpmath.root(x=1, n=self.C_max_length, k=1) <add> ) <add> <add> # The product <add> self.product = self.__multiply() <add> <add> # Discrete fourier transform of A and B <add> def __DFT(self, which): <add> if which == "A": <add> dft = [[x] for x in self.polyA] <add> else: <add> dft = [[x] for x in self.polyB] <add> # Corner case <add> if len(dft) <= 1: <add> return dft[0] <add> # <add> next_ncol = self.C_max_length // 2 <add> while next_ncol > 0: <add> new_dft = [[] for i in range(next_ncol)] <add> root = self.root ** next_ncol <add> <add> # First half of next step <add> current_root = 1 <add> for j in range( <add> self.C_max_length // (next_ncol * 2) <add> ): <add> for i in range(next_ncol): <add> new_dft[i].append( <add> dft[i][j] <add> + current_root <add> * dft[i + next_ncol][j] <add> ) <add> current_root *= root <add> # Second half of next step <add> current_root = 1 <add> for j in range( <add> self.C_max_length // (next_ncol * 2) <add> ): <add> for i in range(next_ncol): <add> new_dft[i].append( <add> dft[i][j] <add> - current_root <add> * dft[i + next_ncol][j] <add> ) <add> current_root *= root <add> # Update <add> dft = new_dft <add> next_ncol = next_ncol // 2 <add> return dft[0] <add> <add> # multiply the DFTs of A and B and find A*B <add> def __multiply(self): <add> dftA = self.__DFT("A") <add> dftB = self.__DFT("B") <add> inverseC = [ <add> [ <add> dftA[i] * dftB[i] <add> for i in range(self.C_max_length) <add> ] <add> ] <add> del dftA <add> del dftB <add> <add> # Corner Case <add> if len(inverseC[0]) <= 1: <add> return inverseC[0] <add> # Inverse DFT <add> next_ncol = 2 <add> while next_ncol <= self.C_max_length: <add> new_inverseC = [[] for i in range(next_ncol)] <add> root = self.root ** (next_ncol // 2) <add> current_root = 1 <add> # First half of next step <add> for j in range(self.C_max_length // next_ncol): <add> for i in range(next_ncol // 2): <add> # Even positions <add> new_inverseC[i].append( <add> ( <add> inverseC[i][j] <add> + inverseC[i][ <add> j <add> + self.C_max_length <add> // next_ncol <add> ] <add> ) <add> / 2 <add> ) <add> # Odd positions <add> new_inverseC[i + next_ncol // 2].append( <add> ( <add> inverseC[i][j] <add> - inverseC[i][ <add> j <add> + self.C_max_length <add> // next_ncol <add> ] <add> ) <add> / (2 * current_root) <add> ) <add> current_root *= root <add> # Update <add> inverseC = new_inverseC <add> next_ncol *= 2 <add> # Unpack <add> inverseC = [ <add> round(x[0].real, 8) + round(x[0].imag, 8) * 1j <add> for x in inverseC <add> ] <add> <add> # Remove leading 0's <add> while inverseC[-1] == 0: <add> inverseC.pop() <add> return inverseC <add> <add> # Overwrite __str__ for print(); Shows A, B and A*B <add> def __str__(self): <add> A = "A = " + " + ".join( <add> f"{coef}*x^{i}" <add> for coef, i in enumerate( <add> self.polyA[: self.len_A] <add> ) <add> ) <add> B = "B = " + " + ".join( <add> f"{coef}*x^{i}" <add> for coef, i in enumerate( <add> self.polyB[: self.len_B] <add> ) <add> ) <add> C = "A*B = " + " + ".join( <add> f"{coef}*x^{i}" <add> for coef, i in enumerate(self.product) <add> ) <add> <add> return "\n".join((A, B, C)) <add> <add> <add># Unit tests <add>if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod()
1
Go
Go
remove unnescessary conversion (unconvert)
3a16c7246a0b3e2cc7896f8ed4fb732dbd88a1ad
<ide><path>pkg/signal/signal_test.go <ide> func TestValidSignalForPlatform(t *testing.T) { <ide> assert.Check(t, is.Equal(false, isValidSignal)) <ide> <ide> for _, sigN := range SignalMap { <del> isValidSignal = ValidSignalForPlatform(syscall.Signal(sigN)) <add> isValidSignal = ValidSignalForPlatform(sigN) <ide> assert.Check(t, is.Equal(true, isValidSignal)) <ide> } <ide> }
1
Javascript
Javascript
move common tls connect setup into fixtures
99b0c2e7a7b299e127234334e5bd23cf600902d9
<ide><path>test/fixtures/tls-connect.js <add>// One shot call to connect a TLS client and server based on options to <add>// tls.createServer() and tls.connect(), so assertions can be made on both ends <add>// of the connection. <add>'use strict'; <add> <add>const common = require('../common'); <add>const fs = require('fs'); <add>const join = require('path').join; <add>const tls = require('tls'); <add>const util = require('util'); <add> <add>module.exports = exports = checkCrypto; <add> <add>function checkCrypto() { <add> if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> process.exit(0); <add> } <add> return exports; <add>} <add> <add>exports.assert = require('assert'); <add>exports.debug = util.debuglog('test'); <add>exports.tls = tls; <add> <add>// Pre-load keys from common fixtures for ease of use by tests. <add>const keys = exports.keys = { <add> agent1: load('agent1', 'ca1'), <add> agent2: load('agent2', 'agent2'), <add> agent3: load('agent3', 'ca2'), <add> agent4: load('agent4', 'ca2'), <add> agent5: load('agent5', 'ca2'), <add> agent6: load('agent6', 'ca1'), <add> agent7: load('agent7', 'fake-cnnic-root'), <add> ec: load('ec', 'ec'), <add>}; <add> <add>function load(cert, issuer) { <add> issuer = issuer || cert; // Assume self-signed if no issuer <add> const id = { <add> key: read(cert + '-key.pem'), <add> cert: read(cert + '-cert.pem'), <add> ca: read(issuer + '-cert.pem'), <add> }; <add> return id; <add>} <add> <add>function read(file) { <add> return fs.readFileSync(join(common.fixturesDir, 'keys', file), 'binary'); <add>} <add> <add>exports.connect = function connect(options, callback) { <add> callback = common.mustCall(callback); <add> <add> const server = {}; <add> const client = {}; <add> const pair = { <add> server: server, <add> client: client, <add> }; <add> <add> tls.createServer(options.server, function(conn) { <add> server.conn = conn; <add> conn.pipe(conn); <add> maybeCallback() <add> }).listen(0, function() { <add> server.server = this; <add> <add> const optClient = util._extend({ <add> port: this.address().port, <add> }, options.client); <add> <add> tls.connect(optClient) <add> .on('secureConnect', function() { <add> client.conn = this; <add> maybeCallback(); <add> }) <add> .on('error', function(err) { <add> client.err = err; <add> client.conn = this; <add> maybeCallback(); <add> }); <add> }); <add> <add> function maybeCallback() { <add> if (!callback) <add> return; <add> if (server.conn && (client.conn || client.err)) { <add> const err = pair.client.err || pair.server.err; <add> callback(err, pair, cleanup); <add> callback = null; <add> <add> function cleanup() { <add> if (server.server) <add> server.server.close(); <add> if (client.conn) <add> client.conn.end(); <add> } <add> } <add> } <add>} <ide><path>test/parallel/test-tls-addca.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const fs = require('fs'); <ide> <del>if (!common.hasCrypto) { <del> common.skip('missing crypto'); <del> return; <del>} <del>const tls = require('tls'); <del> <del>function filenamePEM(n) { <del> return require('path').join(common.fixturesDir, 'keys', n + '.pem'); <del>} <add>// Adding a CA certificate to contextWithCert should not also add it to <add>// contextWithoutCert. This is tested by trying to connect to a server that <add>// depends on that CA using contextWithoutCert. <ide> <del>function loadPEM(n) { <del> return fs.readFileSync(filenamePEM(n)); <del>} <add>const join = require('path').join; <add>const { <add> assert, connect, keys, tls <add>} = require(join(common.fixturesDir, 'tls-connect'))(); <ide> <del>const caCert = loadPEM('ca1-cert'); <ide> const contextWithoutCert = tls.createSecureContext({}); <ide> const contextWithCert = tls.createSecureContext({}); <del>// Adding a CA certificate to contextWithCert should not also add it to <del>// contextWithoutCert. This is tested by trying to connect to a server that <del>// depends on that CA using contextWithoutCert. <del>contextWithCert.context.addCACert(caCert); <add>contextWithCert.context.addCACert(keys.agent1.ca); <ide> <ide> const serverOptions = { <del> key: loadPEM('agent1-key'), <del> cert: loadPEM('agent1-cert'), <add> key: keys.agent1.key, <add> cert: keys.agent1.cert, <ide> }; <del>const server = tls.createServer(serverOptions, function() {}); <ide> <ide> const clientOptions = { <del> port: undefined, <del> ca: [caCert], <add> ca: [keys.agent1.ca], <ide> servername: 'agent1', <ide> rejectUnauthorized: true, <ide> }; <ide> <del>function startTest() { <del> // This client should fail to connect because it doesn't trust the CA <add>// This client should fail to connect because it doesn't trust the CA <add>// certificate. <add>clientOptions.secureContext = contextWithoutCert; <add> <add>connect({ <add> client: clientOptions, <add> server: serverOptions, <add>}, function(err, pair, cleanup) { <add> assert(err); <add> assert.strictEqual(err.message, 'unable to verify the first certificate'); <add> cleanup(); <add> <add> // This time it should connect because contextWithCert includes the needed CA <ide> // certificate. <del> clientOptions.secureContext = contextWithoutCert; <del> clientOptions.port = server.address().port; <del> const client = tls.connect(clientOptions, common.fail); <del> client.on('error', common.mustCall(() => { <del> client.destroy(); <del> <del> // This time it should connect because contextWithCert includes the needed <del> // CA certificate. <del> clientOptions.secureContext = contextWithCert; <del> const client2 = tls.connect(clientOptions, common.mustCall(() => { <del> client2.destroy(); <del> server.close(); <del> })); <del> client2.on('error', (e) => { <del> console.log(e); <del> }); <del> })); <del>} <del> <del>server.listen(0, startTest); <add> clientOptions.secureContext = contextWithCert; <add> connect({ <add> client: clientOptions, <add> server: serverOptions, <add> }, function(err, pair, cleanup) { <add> assert.ifError(err); <add> cleanup(); <add> }); <add>}); <ide><path>test/parallel/test-tls-connect-secure-context.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> <del>if (!common.hasCrypto) { <del> common.skip('missing crypto'); <del> return; <del>} <del>const tls = require('tls'); <add>// Verify connection with explicitly created client SecureContext. <ide> <del>const fs = require('fs'); <del>const path = require('path'); <add>const join = require('path').join; <add>const { <add> assert, connect, keys, tls <add>} = require(join(common.fixturesDir, 'tls-connect'))(); <ide> <del>const keysDir = path.join(common.fixturesDir, 'keys'); <del> <del>const ca = fs.readFileSync(path.join(keysDir, 'ca1-cert.pem')); <del>const cert = fs.readFileSync(path.join(keysDir, 'agent1-cert.pem')); <del>const key = fs.readFileSync(path.join(keysDir, 'agent1-key.pem')); <del> <del>const server = tls.createServer({ <del> cert: cert, <del> key: key <del>}, function(c) { <del> c.end(); <del>}).listen(0, function() { <del> const secureContext = tls.createSecureContext({ <del> ca: ca <del> }); <del> <del> const socket = tls.connect({ <del> secureContext: secureContext, <add>connect({ <add> client: { <ide> servername: 'agent1', <del> port: this.address().port <del> }, common.mustCall(function() { <del> server.close(); <del> socket.end(); <del> })); <add> secureContext: tls.createSecureContext({ <add> ca: keys.agent1.ca, <add> }), <add> }, <add> server: { <add> cert: keys.agent1.cert, <add> key: keys.agent1.key, <add> }, <add>}, function(err, pair, cleanup) { <add> assert.ifError(err); <add> return cleanup(); <ide> }); <ide><path>test/parallel/test-tls-peer-certificate.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> <del>if (!common.hasCrypto) { <del> common.skip('missing crypto'); <del> return; <del>} <del>const tls = require('tls'); <add>// Verify that detailed getPeerCertificate() return value has all certs. <ide> <del>const fs = require('fs'); <del>const util = require('util'); <ide> const join = require('path').join; <add>const { <add> assert, connect, debug, keys <add>} = require(join(common.fixturesDir, 'tls-connect'))(); <ide> <del>const options = { <del> key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-key.pem')), <del> cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-cert.pem')), <del> ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca1-cert.pem')) ] <del>}; <add>connect({ <add> client: {rejectUnauthorized: false}, <add> server: keys.agent1, <add>}, function(err, pair, cleanup) { <add> assert.ifError(err); <add> const socket = pair.client.conn; <add> let peerCert = socket.getPeerCertificate(); <add> assert.ok(!peerCert.issuerCertificate); <ide> <del>const server = tls.createServer(options, function(cleartext) { <del> cleartext.end('World'); <del>}); <del>server.listen(0, common.mustCall(function() { <del> const socket = tls.connect({ <del> port: this.address().port, <del> rejectUnauthorized: false <del> }, common.mustCall(function() { <del> let peerCert = socket.getPeerCertificate(); <del> assert.ok(!peerCert.issuerCertificate); <add> peerCert = socket.getPeerCertificate(true); <add> debug('peerCert:\n', peerCert); <ide> <del> // Verify that detailed return value has all certs <del> peerCert = socket.getPeerCertificate(true); <del> assert.ok(peerCert.issuerCertificate); <add> assert.ok(peerCert.issuerCertificate); <add> assert.strictEqual(peerCert.subject.emailAddress, '[email protected]'); <add> assert.strictEqual(peerCert.serialNumber, '9A84ABCFB8A72AC0'); <add> assert.strictEqual(peerCert.exponent, '0x10001'); <add> assert.strictEqual( <add> peerCert.fingerprint, <add> '8D:06:3A:B3:E5:8B:85:29:72:4F:7D:1B:54:CD:95:19:3C:EF:6F:AA' <add> ); <add> assert.deepStrictEqual(peerCert.infoAccess['OCSP - URI'], <add> [ 'http://ocsp.nodejs.org/' ]); <ide> <del> console.error(util.inspect(peerCert)); <del> assert.strictEqual(peerCert.subject.emailAddress, '[email protected]'); <del> assert.strictEqual(peerCert.serialNumber, '9A84ABCFB8A72AC0'); <del> assert.strictEqual(peerCert.exponent, '0x10001'); <del> assert.strictEqual( <del> peerCert.fingerprint, <del> '8D:06:3A:B3:E5:8B:85:29:72:4F:7D:1B:54:CD:95:19:3C:EF:6F:AA' <del> ); <del> assert.deepStrictEqual(peerCert.infoAccess['OCSP - URI'], <del> [ 'http://ocsp.nodejs.org/' ]); <add> const issuer = peerCert.issuerCertificate; <add> assert.strictEqual(issuer.issuerCertificate, issuer); <add> assert.strictEqual(issuer.serialNumber, '8DF21C01468AF393'); <ide> <del> const issuer = peerCert.issuerCertificate; <del> assert.strictEqual(issuer.issuerCertificate, issuer); <del> assert.strictEqual(issuer.serialNumber, '8DF21C01468AF393'); <del> server.close(); <del> })); <del> socket.end('Hello'); <del>})); <add> return cleanup(); <add>});
4
Text
Text
add link to master docs
4374d3bc81cf47866bd3f5c240307915931084cf
<ide><path>README.md <ide> Want to run Docker from a master build? You can download <ide> master builds at [master.dockerproject.com](https://master.dockerproject.com). <ide> They are updated with each commit merged into the master branch. <ide> <add>Don't know how to use that super cool new feature in the master build? Check <add>out the master docs at <add>[docs.master.dockerproject.com](http://docs.master.dockerproject.com). <add> <ide> ### Legal <ide> <ide> *Brought to you courtesy of our legal counsel. For more context,
1
Text
Text
update license year to 2016
5a2c8ff9622b2359011f1aa297c3d28c04ef103f
<ide><path>LICENSE.md <del>Copyright (c) 2015 GitHub Inc. <add>Copyright (c) 2016 GitHub Inc. <ide> <ide> Permission is hereby granted, free of charge, to any person obtaining <ide> a copy of this software and associated documentation files (the
1
Python
Python
change copyright scipy to numpy
eb231979b90cfe7f434bd598aefe4196df74b32e
<ide><path>doc/source/conf.py <ide> class PyTypeObject(ctypes.Structure): <ide> <ide> # General substitutions. <ide> project = 'NumPy' <del>copyright = '2008-2021, The SciPy community' <add>copyright = '2008-2021, The NumPy community' <ide> <ide> # The default replacements for |version| and |release|, also used in various <ide> # other places throughout the built documents.
1
Ruby
Ruby
fix bad format [ci skip]
0631b2631601b30d8fedaefb7388da8b42c83977
<ide><path>activemodel/lib/active_model/model.rb <ide> module ActiveModel <ide> <ide> # == Active Model Basic Model <ide> # <del> # Includes the required interface for an object to interact with +ActionPack+, <del> # using different +ActiveModel+ modules. It includes model name introspections, <add> # Includes the required interface for an object to interact with <tt>ActionPack</tt>, <add> # using different <tt>ActiveModel</tt> modules. It includes model name introspections, <ide> # conversions, translations and validations. Besides that, it allows you to <ide> # initialize the object with a hash of attributes, pretty much like <del> # +ActiveRecord+ does. <add> # <tt>ActiveRecord</tt> does. <ide> # <ide> # A minimal implementation could be: <ide> # <ide> module ActiveModel <ide> # person.name # => 'bob' <ide> # person.age # => 18 <ide> # <del> # Note that, by default, +ActiveModel::Model+ implements +persisted?+ to <del> # return +false+, which is the most common case. You may want to override it <add> # Note that, by default, <tt>ActiveModel::Model</tt> implements <tt>persisted?</tt> to <add> # return <tt>false</tt>, which is the most common case. You may want to override it <ide> # in your class to simulate a different scenario: <ide> # <ide> # class Person <ide> module ActiveModel <ide> # person = Person.new(:id => 1, :name => 'bob') <ide> # person.persisted? # => true <ide> # <del> # Also, if for some reason you need to run code on +initialize+, make sure you <add> # Also, if for some reason you need to run code on <tt>initialize</tt>, make sure you <ide> # call super if you want the attributes hash initialization to happen. <ide> # <ide> # class Person <ide> module ActiveModel <ide> # person.omg # => true <ide> # <ide> # For more detailed information on other functionalities available, please refer <del> # to the specific modules included in +ActiveModel::Model+ (see below). <add> # to the specific modules included in <tt>ActiveModel::Model</tt> (see below). <ide> module Model <ide> def self.included(base) <ide> base.class_eval do
1
Go
Go
simplify function signature
445620f231ccd2a99e5ebb8fc004dcb254cc2c4b
<ide><path>daemon/graphdriver/driver.go <ide> func getBuiltinDriver(name, home string, options []string, uidMaps, gidMaps []id <ide> } <ide> <ide> // New creates the driver and initializes it at the specified root. <del>func New(root string, name string, options []string, uidMaps, gidMaps []idtools.IDMap, pg plugingetter.PluginGetter) (Driver, error) { <add>func New(root, name string, options []string, uidMaps, gidMaps []idtools.IDMap, pg plugingetter.PluginGetter) (Driver, error) { <ide> if name != "" { <ide> logrus.Debugf("[graphdriver] trying provided driver: %s", name) // so the logs show specified driver <ide> return GetDriver(name, root, options, uidMaps, gidMaps, pg)
1
Ruby
Ruby
make all references to engines lowercase in docs
2373eedc88661a11c1ac58d8e98a9cb5b6c7dba1
<ide><path>railties/lib/rails/engine.rb <ide> module Rails <ide> # Rails::Engine allows you to wrap a specific Rails application and share it across <ide> # different applications. Since Rails 3.0, every <tt>Rails::Application</tt> is nothing <del> # more than an <tt>Engine</tt>, allowing you to share it very easily. <add> # more than an engine, allowing you to share it very easily. <ide> # <ide> # Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same methods <del> # (like <tt>rake_tasks</tt> and <tt>generators</tt>) and configuration available in the <add> # (like <tt>rake_tasks</tt> and +generators+) and configuration available in the <ide> # latter can also be used in the former. <ide> # <ide> # == Creating an Engine <ide> # <del> # In Rails versions prior to 3.0, your gems automatically behaved as Engines, however, <add> # In Rails versions prior to 3.0, your gems automatically behaved as engines, however, <ide> # this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically <del> # behave as an <tt>Engine</tt>, you have to specify an <tt>Engine</tt> for it somewhere <del> # inside your plugin's <tt>lib</tt> folder (similar to how we specify a <tt>Railtie</tt>): <add> # behave as an engine, you have to specify an +Engine+ for it somewhere inside <add> # your plugin's +lib+ folder (similar to how we specify a +Railtie+): <ide> # <ide> # # lib/my_engine.rb <ide> # module MyEngine <ide> module Rails <ide> # end <ide> # <ide> # Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt> <del> # (or in your <tt>Gemfile</tt>) and it will automatically load models, controllers and helpers <del> # inside <tt>app</tt>, load routes at <tt>config/routes.rb</tt>, load locales at <add> # (or in your +Gemfile+) and it will automatically load models, controllers and helpers <add> # inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at <ide> # <tt>config/locales/*</tt>, and load tasks at <tt>lib/tasks/*</tt>. <ide> # <ide> # == Configuration <ide> # <del> # Besides the <tt>Railtie</tt> configuration which is shared across the application, in a <add> # Besides the +Railtie+ configuration which is shared across the application, in a <ide> # <tt>Rails::Engine</tt> you can access <tt>autoload_paths</tt>, <tt>eager_load_paths</tt> <ide> # and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to <del> # the current <tt>Engine</tt>. <add> # the current engine. <ide> # <ide> # Example: <ide> # <ide> module Rails <ide> # <ide> # == Generators <ide> # <del> # You can set up generators for Engines with <tt>config.generators</tt> method: <add> # You can set up generators for engines with <tt>config.generators</tt> method: <ide> # <ide> # class MyEngine < Rails::Engine <ide> # config.generators do |g| <ide> module Rails <ide> # end <ide> # end <ide> # <del> # You can also set generators for application by using <tt>config.app_generators</tt>: <add> # You can also set generators for an application by using <tt>config.app_generators</tt>: <ide> # <ide> # class MyEngine < Rails::Engine <ide> # # note that you can also pass block to app_generators in the same way you <ide> module Rails <ide> # <ide> # == Paths <ide> # <del> # Since Rails 3.0, both your Application and Engines do not have hardcoded paths. <add> # Since Rails 3.0, both your application and engines do not have hardcoded paths. <ide> # This means that you are not required to place your controllers at <tt>app/controllers</tt>, <ide> # but in any place which you find convenient. <ide> # <del> # For example, let's suppose you want to place your controllers in <tt>lib/controllers. <add> # For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>. <ide> # All you would need to do is: <ide> # <ide> # class MyEngine < Rails::Engine <ide> module Rails <ide> # paths["app/controllers"] << "lib/controllers" <ide> # end <ide> # <del> # The available paths in an Engine are: <add> # The available paths in an engine are: <ide> # <ide> # class MyEngine < Rails::Engine <ide> # paths["app"] #=> ["app"] <ide> module Rails <ide> # paths["config/routes"] #=> ["config/routes.rb"] <ide> # end <ide> # <del> # Your <tt>Application</tt> class adds a couple more paths to this set. And as in your <del> # <tt>Application</tt>,all folders under <tt>app</tt> are automatically added to the load path. <add> # Your <tt>Application</tt> class adds a couple more paths to this set. And as in your <add> # <tt>Application</tt>,all folders under +app+ are automatically added to the load path. <ide> # So if you have <tt>app/observers</tt>, it's added by default. <ide> # <ide> # == Endpoint <ide> # <del> # An Engine can be also a rack application. It can be useful if you have a rack application that <del> # you would like to wrap with Engine and provide some of the Engine's features. <add> # An engine can be also a rack application. It can be useful if you have a rack application that <add> # you would like to wrap with +Engine+ and provide some of the +Engine+'s features. <ide> # <del> # To do that, use the <tt>endpoint</tt> method: <add> # To do that, use the +endpoint+ method: <ide> # <ide> # module MyEngine <ide> # class Engine < Rails::Engine <ide> # endpoint MyRackApplication <ide> # end <ide> # end <ide> # <del> # Now you can mount your <tt>Engine</tt> in application's routes just like that: <add> # Now you can mount your engine in application's routes just like that: <ide> # <ide> # MyRailsApp::Application.routes.draw do <ide> # mount MyEngine::Engine => "/engine" <ide> # end <ide> # <ide> # == Middleware stack <ide> # <del> # As <tt>Engine</tt> can now be rack endpoint, it can also have a middleware stack. The usage is exactly <add> # As an engine can now be rack endpoint, it can also have a middleware stack. The usage is exactly <ide> # the same as in <tt>Application</tt>: <ide> # <ide> # module MyEngine <ide> module Rails <ide> # <ide> # == Routes <ide> # <del> # If you don't specify endpoint, routes will be used as default endpoint. You can use them <del> # just like you use application's routes: <add> # If you don't specify an endpoint, routes will be used as the default endpoint. You can use them <add> # just like you use an application's routes: <ide> # <ide> # # ENGINE/config/routes.rb <ide> # MyEngine::Engine.routes.draw do <ide> module Rails <ide> # match "/blog/omg" => "main#omg" <ide> # end <ide> # <del> # <tt>MyEngine</tT> is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's <del> # controller. In such a situation, requests to <tt>/blog/omg</tt> will go through <tt>MyEngine</tt>, <del> # and if there is no such route in Engine's routes, it will be dispatched to <tt>main#omg</tt>. <add> # +MyEngine+ is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's <add> # controller. In such a situation, requests to <tt>/blog/omg</tt> will go through +MyEngine+, <add> # and if there is no such route in +Engine+'s routes, it will be dispatched to <tt>main#omg</tt>. <ide> # It's much better to swap that: <ide> # <ide> # MyRailsApp::Application.routes.draw do <ide> # match "/blog/omg" => "main#omg" <ide> # mount MyEngine::Engine => "/blog" <ide> # end <ide> # <del> # Now, </tt>Engine</tt> will get only requests that were not handled by <tt>Application</tt>. <add> # Now, +Engine+ will get only requests that were not handled by +Application+. <ide> # <ide> # == Asset path <ide> # <del> # When you use <tt>Engine</tt> with its own public directory, you will probably want to copy or symlink it <add> # When you use +Engine+ with its own public directory, you will probably want to copy or symlink it <ide> # to application's public directory. To simplify generating paths for assets, you can set <tt>asset_path</tt> <del> # for an <tt>Engine</tt>: <add> # for an engine: <ide> # <ide> # module MyEngine <ide> # class Engine < Rails::Engine <ide> # config.asset_path = "/my_engine/%s" <ide> # end <ide> # end <ide> # <del> # With such a config, asset paths will be automatically modified inside <tt>Engine</tt>: <add> # With such a config, asset paths will be automatically modified inside +Engine+: <ide> # <ide> # image_path("foo.jpg") #=> "/my_engine/images/foo.jpg" <ide> # <ide> # == Serving static files <ide> # <ide> # By default, Rails uses <tt>ActionDispatch::Static</tt> to serve static files in development mode. This is ok <del> # while you develop your application, but when you want to deploy it, assets from engine will not be <add> # while you develop your application, but when you want to deploy it, assets from an engine will not be <ide> # served by default. You should choose one of the two following strategies: <ide> # <ide> # * enable serving static files by setting config.serve_static_assets to true <ide> module Rails <ide> # end <ide> # end <ide> # <del> # With such an Engine, everything that is inside the +MyEngine+ module will be isolated from <add> # With such an engine, everything that is inside the +MyEngine+ module will be isolated from <ide> # the application. <ide> # <ide> # Consider such controller: <ide> module Rails <ide> # end <ide> # end <ide> # <del> # If engine is marked as isolated, +FooController+ has access only to helpers from engine and <add> # If an engine is marked as isolated, +FooController+ has access only to helpers from +Engine+ and <ide> # <tt>url_helpers</tt> from <tt>MyEngine::Engine.routes</tt>. <ide> # <ide> # The next thing that changes in isolated engines is the behaviour of routes. Normally, when you namespace <ide> module Rails <ide> # <ide> # == Using Engine's routes outside Engine <ide> # <del> # Since you can now mount engine inside application's routes, you do not have direct access to engine's <del> # <tt>url_helpers</tt> inside application. When you mount Engine in application's routes, a special helper is <add> # Since you can now mount an engine inside application's routes, you do not have direct access to +Engine+'s <add> # <tt>url_helpers</tt> inside +Application+. When you mount an engine in an application's routes, a special helper is <ide> # created to allow you to do that. Consider such a scenario: <ide> # <ide> # # APP/config/routes.rb <ide> module Rails <ide> # Note that the <tt>:as</tt> option given to mount takes the <tt>engine_name</tT> as default, so most of the time <ide> # you can simply omit it. <ide> # <del> # Finally, if you want to generate a url to engine's route using <tt>polymorphic_url</tt>, you also need <add> # Finally, if you want to generate a url to an engine's route using <tt>polymorphic_url</tt>, you also need <ide> # to pass the engine helper. Let's say that you want to create a form pointing to one of the <ide> # engine's routes. All you need to do is pass the helper as the first element in array with <ide> # attributes for url:
1
Text
Text
remove reference to globalize gem
46b8d343d3a2f1b647c8543d486a3bdf6636ad04
<ide><path>guides/source/i18n.md <ide> The I18n API described in this guide is primarily intended for translating inter <ide> <ide> Several gems can help with this: <ide> <del>* [Globalize](https://github.com/globalize/globalize): Store translations on separate translation tables, one for each translated model <ide> * [Mobility](https://github.com/shioyama/mobility): Provides support for storing translations in many formats, including translation tables, json columns (PostgreSQL), etc. <ide> * [Traco](https://github.com/barsoom/traco): Translatable columns stored in the model table itself <ide>
1
Python
Python
expand mapped tasks at dagrun.veriy_integrity
91832a42d8124b040073481fd93c54e9e64c2609
<ide><path>airflow/models/dagrun.py <ide> import warnings <ide> from collections import defaultdict <ide> from datetime import datetime <del>from typing import TYPE_CHECKING, Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, Union <add>from typing import ( <add> TYPE_CHECKING, <add> Any, <add> Dict, <add> Generator, <add> Iterable, <add> List, <add> NamedTuple, <add> Optional, <add> Sequence, <add> Tuple, <add> Union, <add> cast, <add>) <ide> <ide> from sqlalchemy import ( <ide> Boolean, <ide> def verify_integrity(self, session: Session = NEW_SESSION): <ide> task = None <ide> try: <ide> task = dag.get_task(ti.task_id) <add> <add> should_restore_task = (task is not None) and ti.state == State.REMOVED <add> if should_restore_task: <add> self.log.info("Restoring task '%s' which was previously removed from DAG '%s'", ti, dag) <add> Stats.incr(f"task_restored_to_dag.{dag.dag_id}", 1, 1) <add> ti.state = State.NONE <ide> except AirflowException: <ide> if ti.state == State.REMOVED: <ide> pass # ti has already been removed, just ignore it <ide> elif self.state != State.RUNNING and not dag.partial: <ide> self.log.warning("Failed to get task '%s' for dag '%s'. Marking it as removed.", ti, dag) <ide> Stats.incr(f"task_removed_from_dag.{dag.dag_id}", 1, 1) <ide> ti.state = State.REMOVED <add> continue <ide> <del> should_restore_task = (task is not None) and ti.state == State.REMOVED <del> if should_restore_task: <del> self.log.info("Restoring task '%s' which was previously removed from DAG '%s'", ti, dag) <del> Stats.incr(f"task_restored_to_dag.{dag.dag_id}", 1, 1) <del> ti.state = State.NONE <del> session.merge(ti) <add> if task.is_mapped: <add> task = cast("MappedOperator", task) <add> num_mapped_tis = task.parse_time_mapped_ti_count <add> # Check if the number of mapped literals has changed and we need to mark this TI as removed <add> if not num_mapped_tis or ti.map_index >= num_mapped_tis: <add> ti.state = State.REMOVED <add> elif ti.map_index < 0: <add> ti.state = State.REMOVED <ide> <ide> def task_filter(task: "Operator") -> bool: <ide> return task.task_id not in task_ids and ( <ide> def task_filter(task: "Operator") -> bool: <ide> <ide> if hook_is_noop: <ide> <del> def create_ti_mapping(task: "Operator") -> dict: <add> def create_ti_mapping(task: "Operator", indexes: Tuple[int, ...]) -> Generator: <ide> created_counts[task.task_type] += 1 <del> return TI.insert_mapping(self.run_id, task, map_index=-1) <add> for map_index in indexes: <add> yield TI.insert_mapping(self.run_id, task, map_index=map_index) <add> <add> creator = create_ti_mapping <ide> <ide> else: <ide> <del> def create_ti(task: "Operator") -> TI: <del> ti = TI(task, run_id=self.run_id) <del> task_instance_mutation_hook(ti) <del> created_counts[ti.operator] += 1 <del> return ti <add> def create_ti(task: "Operator", indexes: Tuple[int, ...]) -> Generator: <add> for map_index in indexes: <add> ti = TI(task, run_id=self.run_id, map_index=map_index) <add> task_instance_mutation_hook(ti) <add> created_counts[ti.operator] += 1 <add> yield ti <add> <add> creator = create_ti <add> <add> # Create missing tasks -- and expand any MappedOperator that _only_ have literals as input <add> def expand_mapped_literals(task: "Operator") -> Tuple["Operator", Sequence[int]]: <add> if not task.is_mapped: <add> return (task, (-1,)) <add> task = cast("MappedOperator", task) <add> count = task.parse_time_mapped_ti_count <add> if not count: <add> return (task, (-1,)) <add> return (task, range(count)) <add> <add> tasks_and_map_idxs = map(expand_mapped_literals, filter(task_filter, dag.task_dict.values())) <add> tasks = itertools.chain.from_iterable(itertools.starmap(creator, tasks_and_map_idxs)) <ide> <del> # Create missing tasks <del> tasks = list(filter(task_filter, dag.task_dict.values())) <ide> try: <ide> if hook_is_noop: <del> session.bulk_insert_mappings(TI, map(create_ti_mapping, tasks)) <add> session.bulk_insert_mappings(TI, tasks) <ide> else: <del> session.bulk_save_objects(map(create_ti, tasks)) <add> session.bulk_save_objects(tasks) <ide> <ide> for task_type, count in created_counts.items(): <ide> Stats.incr(f"task_instance_created-{task_type}", count) <ide><path>airflow/models/mappedoperator.py <ide> from sqlalchemy import func, or_ <ide> from sqlalchemy.orm.session import Session <ide> <del>from airflow.compat.functools import cache <add>from airflow.compat.functools import cache, cached_property <ide> from airflow.exceptions import UnmappableOperator <ide> from airflow.models.abstractoperator import ( <ide> DEFAULT_OWNER, <ide> # any mapping since we need the value to be ordered). <ide> Mappable = Union[XComArg, Sequence, dict] <ide> <del>ValidationSource = Union[Literal["map"], Literal["partial"]] <add>ValidationSource = Union[Literal["expand"], Literal["partial"]] <add> <add> <add>MAPPABLE_LITERAL_TYPES = (dict, list) <ide> <ide> <ide> # For isinstance() check. <ide> @cache <ide> def get_mappable_types() -> Tuple[type, ...]: <ide> from airflow.models.xcom_arg import XComArg <ide> <del> return (XComArg, dict, list) <add> return (XComArg,) + MAPPABLE_LITERAL_TYPES <ide> <ide> <ide> def validate_mapping_kwargs(op: Type["BaseOperator"], func: ValidationSource, value: Dict[str, Any]) -> None: <ide> def _find_index_for_this_field(index: int) -> int: <ide> if i == found_index: <ide> return k, v <ide> raise IndexError(f"index {map_index} is over mapped length") <add> <add> @cached_property <add> def parse_time_mapped_ti_count(self) -> Optional[int]: <add> """ <add> Number of mapped TaskInstances that can be created at DagRun create time. <add> <add> :return: None if non-literal mapped arg encountered, or else total number of mapped TIs this task <add> should have <add> """ <add> total = 0 <add> <add> for value in self._get_expansion_kwargs().values(): <add> if not isinstance(value, MAPPABLE_LITERAL_TYPES): <add> # None literal type encountered, so give up <add> return None <add> total += len(value) <add> return total <ide><path>tests/models/test_dagrun.py <ide> <ide> from airflow import settings <ide> from airflow.callbacks.callback_requests import DagCallbackRequest <add>from airflow.decorators import task <ide> from airflow.models import DAG, DagBag, DagModel, DagRun, TaskInstance as TI, clear_task_instances <ide> from airflow.models.baseoperator import BaseOperator <ide> from airflow.models.taskmap import TaskMap <ide> def test_verify_integrity_task_start_and_end_date(Stats_incr, session, run_type, <ide> Stats_incr.assert_called_with('task_instance_created-DummyOperator', expected_tis) <ide> <ide> <del>@pytest.mark.xfail(reason="TODO: Expand mapped literals at verify_integrity time!") <del>def test_expand_mapped_task_instance(dag_maker, session): <del> literal = [1, 2, {'a': 'b'}] <add>@pytest.mark.parametrize('is_noop', [True, False]) <add>def test_expand_mapped_task_instance_at_create(is_noop, dag_maker, session): <add> with mock.patch('airflow.settings.task_instance_mutation_hook') as mock_mut: <add> mock_mut.is_noop = is_noop <add> literal = [1, 2, 3, 4] <add> with dag_maker(session=session, dag_id='test_dag'): <add> mapped = MockOperator.partial(task_id='task_2').expand(arg2=literal) <add> <add> dr = dag_maker.create_dagrun() <add> indices = ( <add> session.query(TI.map_index) <add> .filter_by(task_id=mapped.task_id, dag_id=mapped.dag_id, run_id=dr.run_id) <add> .order_by(TI.map_index) <add> .all() <add> ) <add> assert indices == [(0,), (1,), (2,), (3,)] <add> <add> <add>@pytest.mark.need_serialized_dag <add>@pytest.mark.parametrize('is_noop', [True, False]) <add>def test_expand_mapped_task_instance_task_decorator(is_noop, dag_maker, session): <add> with mock.patch('airflow.settings.task_instance_mutation_hook') as mock_mut: <add> mock_mut.is_noop = is_noop <add> <add> @task <add> def mynameis(arg): <add> print(arg) <add> <add> literal = [1, 2, 3, 4] <add> with dag_maker(session=session, dag_id='test_dag'): <add> mynameis.expand(arg=literal) <add> <add> dr = dag_maker.create_dagrun() <add> indices = ( <add> session.query(TI.map_index) <add> .filter_by(task_id='mynameis', dag_id=dr.dag_id, run_id=dr.run_id) <add> .order_by(TI.map_index) <add> .all() <add> ) <add> assert indices == [(0,), (1,), (2,), (3,)] <add> <add> <add>def test_mapped_literal_verify_integrity(dag_maker, session): <add> """Test that when the length of a mapped literal changes we remove extra TIs""" <add> <add> with dag_maker(session=session) as dag: <add> <add> @task <add> def task_2(arg2): <add> ... <add> <add> task_2.expand(arg2=[1, 2, 3, 4]) <add> <add> dr = dag_maker.create_dagrun() <add> <add> # Now "change" the DAG and we should see verify_integrity REMOVE some TIs <add> dag._remove_task('task_2') <add> <add> with dag: <add> mapped = task_2.expand(arg2=[1, 2]).operator <add> <add> # At this point, we need to test that the change works on the serialized <add> # DAG (which is what the scheduler operates on) <add> serialized_dag = SerializedDAG.from_dict(SerializedDAG.to_dict(dag)) <add> <add> dr.dag = serialized_dag <add> dr.verify_integrity() <add> <add> indices = ( <add> session.query(TI.map_index, TI.state) <add> .filter_by(task_id=mapped.task_id, dag_id=mapped.dag_id, run_id=dr.run_id) <add> .order_by(TI.map_index) <add> .all() <add> ) <add> <add> assert indices == [(0, None), (1, None), (2, TaskInstanceState.REMOVED), (3, TaskInstanceState.REMOVED)] <add> <add> <add>def test_mapped_literal_to_xcom_arg_verify_integrity(dag_maker, session): <add> """Test that when we change from literal to a XComArg the TIs are removed""" <add> <add> with dag_maker(session=session) as dag: <add> t1 = BaseOperator(task_id='task_1') <add> <add> @task <add> def task_2(arg2): <add> ... <add> <add> task_2.expand(arg2=[1, 2, 3, 4]) <add> <add> dr = dag_maker.create_dagrun() <add> <add> # Now "change" the DAG and we should see verify_integrity REMOVE some TIs <add> dag._remove_task('task_2') <add> <add> with dag: <add> mapped = task_2.expand(arg2=XComArg(t1)).operator <add> <add> # At this point, we need to test that the change works on the serialized <add> # DAG (which is what the scheduler operates on) <add> serialized_dag = SerializedDAG.from_dict(SerializedDAG.to_dict(dag)) <add> <add> dr.dag = serialized_dag <add> dr.verify_integrity() <add> <add> indices = ( <add> session.query(TI.map_index, TI.state) <add> .filter_by(task_id=mapped.task_id, dag_id=mapped.dag_id, run_id=dr.run_id) <add> .order_by(TI.map_index) <add> .all() <add> ) <add> <add> assert indices == [ <add> (0, TaskInstanceState.REMOVED), <add> (1, TaskInstanceState.REMOVED), <add> (2, TaskInstanceState.REMOVED), <add> (3, TaskInstanceState.REMOVED), <add> ] <add> <add> <add>@pytest.mark.need_serialized_dag <add>def test_mapped_mixed__literal_not_expanded_at_create(dag_maker, session): <add> literal = [1, 2, 3, 4] <ide> with dag_maker(session=session): <del> mapped = MockOperator(task_id='task_2').expand(arg2=literal) <add> task = BaseOperator(task_id='task_1') <add> mapped = MockOperator.partial(task_id='task_2').expand(arg1=literal, arg2=XComArg(task)) <ide> <ide> dr = dag_maker.create_dagrun() <ide> indices = ( <ide> def test_expand_mapped_task_instance(dag_maker, session): <ide> .all() <ide> ) <ide> <del> assert indices == [0, 1, 2] <add> assert indices == [(-1,)] <ide> <ide> <ide> def test_ti_scheduling_mapped_zero_length(dag_maker, session): <ide><path>tests/models/test_taskinstance.py <ide> def show(value): <ide> <ide> dag_run = dag_maker.create_dagrun() <ide> show_task = dag.get_task("show") <del> mapped_tis = show_task.expand_mapped_task(dag_run.run_id, session=session) <add> mapped_tis = ( <add> session.query(TI) <add> .filter_by(task_id='show', dag_id=dag_run.dag_id, run_id=dag_run.run_id) <add> .order_by(TI.map_index) <add> .all() <add> ) <ide> assert len(mapped_tis) == len(literal) <ide> <ide> for ti in sorted(mapped_tis, key=operator.attrgetter("map_index")):
4