content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Ruby
Ruby
improve documentation for hash#slice!
4fa6a5c4e02bf6c511ecda9db4fd61e51634fe06
<ide><path>activesupport/lib/active_support/core_ext/hash/slice.rb <ide> def slice(*keys) <ide> # Replaces the hash with only the given keys. <ide> # Returns a hash containing the removed key/value pairs. <ide> # <del> # { a: 1, b: 2, c: 3, d: 4 }.slice!(:a, :b) <del> # # => {:c=>3, :d=>4} <add> # hash = { a: 1, b: 2, c: 3, d: 4 } <add> # hash.slice!(:a, :b) # => {:c=>3, :d=>4 } <add> # hash # => {:a=>1, :b=>2 } <ide> def slice!(*keys) <ide> omit = slice(*self.keys - keys) <ide> hash = slice(*keys)
1
Text
Text
add small note about aufs layer limitation
d91d381856b7c91fa992c3cd1943f27c269219f2
<ide><path>docs/sources/userguide/dockerimages.md <ide> instructions have executed we're left with the `324104cde6ad` image <ide> (also helpfully tagged as `ouruser/sinatra:v2`) and all intermediate <ide> containers will get removed to clean things up. <ide> <add>> **Note:** <add>> Due to a AUFS limitation, an image can't have more than 127 layers <add>> (see [this PR](https://github.com/dotcloud/docker/pull/2897)). <add>> This means that a Dockerfile can't create more than 127 containers <add>> during a build (each RUN command creates a new container). <add>> An image flatten strategy is discussed [here](https://github.com/dotcloud/docker/issues/332). <add> <ide> We can then create a container from our new image. <ide> <ide> $ sudo docker run -t -i ouruser/sinatra:v2 /bin/bash
1
Ruby
Ruby
add test case for the 's default order contract
673cf4f13b08438bd1bd751420da778c38145df3
<ide><path>activerecord/test/cases/finder_test.rb <ide> def test_first_have_primary_key_order_by_default <ide> expected = topics(:first) <ide> expected.touch # PostgreSQL changes the default order if no order clause is used <ide> assert_equal expected, Topic.first <add> assert_equal expected, Topic.limit(5).first <ide> end <ide> <ide> def test_model_class_responds_to_first_bang <ide> def test_second_have_primary_key_order_by_default <ide> expected = topics(:second) <ide> expected.touch # PostgreSQL changes the default order if no order clause is used <ide> assert_equal expected, Topic.second <add> assert_equal expected, Topic.limit(5).second <ide> end <ide> <ide> def test_model_class_responds_to_second_bang <ide> def test_third_have_primary_key_order_by_default <ide> expected = topics(:third) <ide> expected.touch # PostgreSQL changes the default order if no order clause is used <ide> assert_equal expected, Topic.third <add> assert_equal expected, Topic.limit(5).third <ide> end <ide> <ide> def test_model_class_responds_to_third_bang <ide> def test_fourth_have_primary_key_order_by_default <ide> expected = topics(:fourth) <ide> expected.touch # PostgreSQL changes the default order if no order clause is used <ide> assert_equal expected, Topic.fourth <add> assert_equal expected, Topic.limit(5).fourth <ide> end <ide> <ide> def test_model_class_responds_to_fourth_bang <ide> def test_fifth_have_primary_key_order_by_default <ide> expected = topics(:fifth) <ide> expected.touch # PostgreSQL changes the default order if no order clause is used <ide> assert_equal expected, Topic.fifth <add> assert_equal expected, Topic.limit(5).fifth <ide> end <ide> <ide> def test_model_class_responds_to_fifth_bang <ide> def test_first_on_relation_with_limit_and_offset <ide> assert_equal comments.limit(2).to_a.first(3), comments.limit(2).first(3) <ide> end <ide> <add> def test_first_have_determined_order_by_default <add> expected = [companies(:second_client), companies(:another_client)] <add> clients = Client.where(name: expected.map(&:name)) <add> <add> assert_equal expected, clients.first(2) <add> assert_equal expected, clients.limit(5).first(2) <add> end <add> <ide> def test_take_and_first_and_last_with_integer_should_return_an_array <ide> assert_kind_of Array, Topic.take(5) <ide> assert_kind_of Array, Topic.first(5)
1
Text
Text
add license to the root directory
2d31404d0782ba809b39a49e4c45797ef1adde12
<ide><path>license.md <add>The MIT License (MIT) <add> <add>Copyright (c) 2016-present Zeit, Inc. <add> <add>Permission is hereby granted, free of charge, to any person obtaining a copy <add>of this software and associated documentation files (the "Software"), to deal <add>in the Software without restriction, including without limitation the rights <add>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell <add>copies of the Software, and to permit persons to whom the Software is <add>furnished to do so, subject to the following conditions: <add> <add>The above copyright notice and this permission notice shall be included in all <add>copies or substantial portions of the Software. <add> <add>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR <add>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <add>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE <add>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER <add>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, <add>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE <add>SOFTWARE.
1
Python
Python
remove unused methods
3fea8482d4dce98b36350a0ac3f98fdd3c02e379
<ide><path>libcloud/compute/drivers/azure.py <ide> def _update_management_header(self, request): <ide> <ide> return request.headers <ide> <del> def send_request_headers(self, connection, request_headers): <del> # TODO - unused, remove <del> for name, value in request_headers: <del> if value: <del> connection.putheader(name, value) <del> <del> connection.putheader('User-Agent', _USER_AGENT_STRING) <del> connection.endheaders() <del> <del> def send_request_body(self, connection, request_body): <del> # TODO - unused, remove <del> if request_body: <del> assert isinstance(request_body, bytes) <del> connection.send(request_body) <del> elif (not isinstance(connection, HTTPSConnection) and <del> not isinstance(connection, httplib.HTTPConnection)): <del> connection.send(None) <del> <ide> def _parse_response(self, response, return_type): <ide> """ <ide> Parse the HTTPResponse's body and fill all the data into a class of
1
Text
Text
add missing types
28e18cfff0d491e14889935a64395cbbb5b666a6
<ide><path>doc/api/stream.md <ide> Return the value of `highWaterMark` passed when constructing this <ide> added: v9.4.0 <ide> --> <ide> <add>* {number} <add> <ide> This property contains the number of bytes (or objects) in the queue <ide> ready to be written. The value provides introspection data regarding <ide> the status of the `highWaterMark`. <ide> the status of the `highWaterMark`. <ide> added: v12.3.0 <ide> --> <ide> <add>* {boolean} <add> <ide> Getter for the property `objectMode` of a given `Writable` stream. <ide> <ide> ##### writable.write(chunk[, encoding][, callback]) <ide> the status of the `highWaterMark`. <ide> added: v12.3.0 <ide> --> <ide> <add>* {boolean} <add> <ide> Getter for the property `objectMode` of a given `Readable` stream. <ide> <ide> ##### readable.resume()
1
Text
Text
update docs to point to new update task
3174b5f92a43e4bfdf4f833389b1ac819ac2cdc5
<ide><path>guides/source/upgrading_ruby_on_rails.md <ide> Rails generally stays close to the latest released Ruby version when it's releas <ide> <ide> TIP: Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition has these fixed since the release of 1.8.7-2010.02. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x, jump straight to 1.9.3 for smooth sailing. <ide> <del>### The Rake Task <add>### The Task <ide> <del>Rails provides the `app:update` rake task. After updating the Rails version <add>Rails provides the `rails:update` rake task. After updating the Rails version <ide> in the Gemfile, run this rake task. <ide> This will help you with the creation of new files and changes of old files in an <ide> interactive session. <ide> <ide> ```bash <del>$ rails app:update <add>$ rails rails:update <ide> identical config/boot.rb <ide> exist config <ide> conflict config/routes.rb
1
Python
Python
fix batch normalization
0debec1c11803f0f7b6f2c75e2c6762bfdc4a468
<ide><path>keras/layers/normalization.py <ide> def set_weights(self, weights): <ide> def get_output(self, train): <ide> X = self.get_input(train) <ide> if self.mode == 0: <del> m = K.mean(X, axis=0) <del> std = K.mean(K.square(X - m) + self.epsilon, axis=0) <del> std = K.sqrt(std) <del> mean_update = self.momentum * self.running_mean + (1-self.momentum) * m <del> std_update = self.momentum * self.running_std + (1-self.momentum) * std <del> self.updates = [(self.running_mean, mean_update), <del> (self.running_std, std_update)] <del> X_normed = ((X - self.running_mean) / <del> (self.running_std + self.epsilon)) <add> if train: <add> m = K.mean(X, axis=0) <add> std = K.mean(K.square(X - m) + self.epsilon, axis=0) <add> std = K.sqrt(std) <add> mean_update = self.momentum * self.running_mean + (1-self.momentum) * m <add> std_update = self.momentum * self.running_std + (1-self.momentum) * std <add> self.updates = [(self.running_mean, mean_update), <add> (self.running_std, std_update)] <add> X_normed = (X - m) / (std + self.epsilon) <add> else: <add> X_normed = ((X - self.running_mean) / <add> (self.running_std + self.epsilon)) <ide> elif self.mode == 1: <ide> m = K.mean(X, axis=-1, keepdims=True) <ide> std = K.std(X, axis=-1, keepdims=True)
1
PHP
PHP
remove unused use statements
96e64ef66c69cc8e0c7960ea0c973b7f8b400db2
<ide><path>app/Console/Commands/Inspire.php <ide> <ide> use Illuminate\Console\Command; <ide> use Illuminate\Foundation\Inspiring; <del>use Symfony\Component\Console\Input\InputOption; <del>use Symfony\Component\Console\Input\InputArgument; <ide> <ide> class Inspire extends Command { <ide>
1
PHP
PHP
remove useless setup() method.
36c0af67504504a2df5398aeffce0da9ec58b1a8
<ide><path>tests/Integration/Mail/SendingMailWithLocaleTest.php <ide> protected function getEnvironmentSetUp($app) <ide> ]); <ide> } <ide> <del> protected function setUp(): void <del> { <del> parent::setUp(); <del> } <del> <ide> public function testMailIsSentWithDefaultLocale() <ide> { <ide> Mail::to('test@mail.com')->send(new TestMail);
1
Python
Python
add client standalone mode and retry mechanism
3ece6f6dcb6ab14249c493c3b1a16ce1c848c29a
<ide><path>airflow/contrib/hooks/spark_submit_hook.py <ide> def _process_spark_submit_log(self, itr): <ide> """ <ide> Processes the log files and extracts useful information out of it. <ide> <add> If the deploy-mode is 'client', log the output of the submit command as those <add> are the output logs of the Spark worker directly. <add> <ide> Remark: If the driver needs to be tracked for its status, the log-level of the <ide> spark deploy needs to be at least INFO (log4j.logger.org.apache.spark.deploy=INFO) <ide> <ide> def _process_spark_submit_log(self, itr): <ide> <ide> # If we run Kubernetes cluster mode, we want to extract the driver pod id <ide> # from the logs so we can kill the application when we stop it unexpectedly <del> if self._is_kubernetes: <add> elif self._is_kubernetes: <ide> match = re.search('\s*pod name: ((.+?)-([a-z0-9]+)-driver)', line) <ide> if match: <ide> self._kubernetes_driver_pod = match.groups()[0] <ide> def _process_spark_submit_log(self, itr): <ide> # if we run in standalone cluster mode and we want to track the driver status <ide> # we need to extract the driver id from the logs. This allows us to poll for <ide> # the status using the driver id. Also, we can kill the driver when needed. <del> if self._should_track_driver_status and not self._driver_id: <add> elif self._should_track_driver_status and not self._driver_id: <ide> match_driver_id = re.search('(driver-[0-9\-]+)', line) <ide> if match_driver_id: <ide> self._driver_id = match_driver_id.groups()[0] <ide> self.log.info("identified spark driver id: {}" <ide> .format(self._driver_id)) <ide> <add> else: <add> self.log.info(line) <add> <ide> self.log.debug("spark submit log: {}".format(line)) <ide> <ide> def _process_spark_status_log(self, itr): <ide> def _start_driver_status_tracking(self): <ide> ERROR: Unable to run or restart due to an unrecoverable error <ide> (e.g. missing jar file) <ide> """ <add> <add> # When your Spark Standalone cluster is not performing well <add> # due to misconfiguration or heavy loads. <add> # it is possible that the polling request will timeout. <add> # Therefore we use a simple retry mechanism. <add> missed_job_status_reports = 0 <add> max_missed_job_status_reports = 10 <add> <ide> # Keep polling as long as the driver is processing <ide> while self._driver_status not in ["FINISHED", "UNKNOWN", <ide> "KILLED", "FAILED", "ERROR"]: <ide> def _start_driver_status_tracking(self): <ide> returncode = status_process.wait() <ide> <ide> if returncode: <del> raise AirflowException( <del> "Failed to poll for the driver status: returncode = {}" <del> .format(returncode) <del> ) <add> if missed_job_status_reports < max_missed_job_status_reports: <add> missed_job_status_reports = missed_job_status_reports + 1 <add> else: <add> raise AirflowException( <add> "Failed to poll for the driver status {} times: returncode = {}" <add> .format(max_missed_job_status_reports, returncode) <add> ) <ide> <ide> def _build_spark_driver_kill_command(self): <ide> """
1
Javascript
Javascript
fix comment typo
0955aae47a8cb5ea39255b9beef6f01cd939c653
<ide><path>test/inspector-cli/test-inspector-cli-address.js <ide> function launchTarget(...args) { <ide> const childProc = spawn(process.execPath, args); <ide> return new Promise((resolve, reject) => { <ide> const onExit = () => { <del> reject(new Error('Child process exits unexpectly')); <add> reject(new Error('Child process exits unexpectedly')); <ide> }; <ide> childProc.on('exit', onExit); <ide> childProc.stderr.setEncoding('utf8');
1
Javascript
Javascript
add www.freecodecamp.org to trusted list
9c14e5846da7ec0497ba4f0b5bba644b46283bf1
<ide><path>server/server.js <ide> var trusted = [ <ide> 'https://freecodecamp.com', <ide> 'https://freecodecamp.org', <ide> '*.freecodecamp.org', <add> // NOTE(berks): add the following as the blob above was not covering www <add> 'http://www.freecodecamp.org', <ide> 'ws://freecodecamp.com/', <ide> 'ws://www.freecodecamp.com/', <ide> '*.gstatic.com',
1
Ruby
Ruby
fix trailing whitespace
abc042cf9e350a67e855370705586e2744b815e2
<ide><path>actioncable/lib/rails/generators/channel/channel_generator.rb <ide> def create_channel_javascript_file <ide> end <ide> <ide> def import_channels_in_javascript_entrypoint <del> append_to_file "app/javascript/application.js", <add> append_to_file "app/javascript/application.js", <ide> using_node? ? %(import "./channels"\n) : %(import "channels"\n) <ide> end <ide> <ide> def import_channel_in_javascript_entrypoint <ide> append_to_file "app/javascript/channels/index.js", <del> using_node? ? %(import "./#{file_name}_channel"\n) : %(import "channels/#{file_name}_channel"\n) <add> using_node? ? %(import "./#{file_name}_channel"\n) : %(import "channels/#{file_name}_channel"\n) <ide> end <ide> <ide> def install_javascript_dependencies
1
Python
Python
make parameter value more generic and adaptable
9ccb66226642ae8304d8b1a7a375d024e93db1bc
<ide><path>research/object_detection/exporter.py <ide> def freeze_graph_with_def_protos( <ide> if optimize_graph: <ide> logging.info('Graph Rewriter optimizations enabled') <ide> rewrite_options = rewriter_config_pb2.RewriterConfig( <del> layout_optimizer=1) <add> layout_optimizer=rewriter_config_pb2.RewriterConfig.ON) <ide> rewrite_options.optimizers.append('pruning') <ide> rewrite_options.optimizers.append('constfold') <ide> rewrite_options.optimizers.append('layout')
1
PHP
PHP
remove use of routerexception
bae8a9b43a71e80f02b64dfedb6b65776c1388dc
<ide><path>lib/Cake/Routing/Router.php <ide> <?php <ide> /** <del> * Parses the request URL into controller, action, and parameters. <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> class Router { <ide> * <ide> * @param string $routeClass to set as default <ide> * @return mixed void|string <del> * @throws RouterException <add> * @throws Cake\Error\Exception <ide> */ <ide> public static function defaultRouteClass($routeClass = null) { <ide> if (is_null($routeClass)) { <ide> public static function defaultRouteClass($routeClass = null) { <ide> * <ide> * @param $routeClass <ide> * @return string <del> * @throws RouterException <add> * @throws Cake\Error\Exception <ide> */ <ide> protected static function _validateRouteClass($routeClass) { <ide> if (!class_exists($routeClass) || !is_subclass_of($routeClass, 'Cake\Routing\Route\Route')) { <del> throw new Error\RouterException(__d('cake_dev', 'Route classes must extend Cake\Routing\Route\Route')); <add> throw new Error\Exception(__d('cake_dev', 'Route classes must extend Cake\Routing\Route\Route')); <ide> } <ide> return $routeClass; <ide> } <ide> protected static function _setPrefixes() { <ide> } <ide> <ide> /** <del> * Gets the named route elements for use in app/Config/routes.php <add> * Gets the named route patterns for use in app/Config/routes.php <ide> * <ide> * @return array Named route elements <ide> * @see Router::$_namedExpressions <ide> public static function getNamedExpressions() { <ide> /** <ide> * Resource map getter & setter. <ide> * <add> * Allows you to define the default route configuration for REST routing and <add> * Router::mapResources() <add> * <ide> * @param array $resourceMap Resource map <ide> * @return mixed <ide> * @see Router::$_resourceMap <ide> public static function resourceMap($resourceMap = null) { <ide> * custom routing class. <ide> * @see routes <ide> * @return void <del> * @throws RouterException <add> * @throws Cake\Error\Exception <ide> */ <ide> public static function connect($route, $defaults = array(), $options = array()) { <ide> if (!empty($defaults['prefix'])) { <ide> public static function redirect($route, $url, $options = array()) { <ide> } <ide> <ide> /** <del> * Creates REST resource routes for the given controller(s). When creating resource routes <del> * for a plugin, by default the prefix will be changed to the lower_underscore version of the plugin <del> * name. By providing a prefix you can override this behavior. <add> * Creates REST resource routes for the given controller(s). <add> * <add> * ### Usage <add> * <add> * Connect resource routes for an app controller: <add> * <add> * {{{ <add> * Router::mapResources('Posts'); <add> * }}} <add> * <add> * Connect resource routes for the Comment controller in the <add> * Comments plugin: <add> * <add> * {{{ <add> * Router::mapResources('Comments.Comment'); <add> * }}} <add> * <add> * Plugins will create lower_case underscored resource routes. e.g <add> * `/comments/comment` <add> * <add> * Connect resource routes for the Posts controller in the <add> * Admin prefix: <add> * <add> * {{{ <add> * Router::mapResources('Posts', ['prefix' => 'admin']); <add> * }}} <add> * <add> * Prefixes will create lower_case underscored resource routes. e.g <add> * `/admin/posts` <ide> * <ide> * ### Options: <ide> * <ide> public static function mapResources($controller, $options = array()) { <ide> 'id' => static::ID . '|' . static::UUID <ide> ), $options); <ide> <del> <ide> foreach ((array)$controller as $name) { <ide> list($plugin, $name) = pluginSplit($name); <ide> $urlName = Inflector::underscore($name); <ide> public static function url($url = null, $options = array()) { <ide> $hasLeadingSlash = isset($url[0]) ? $url[0] === '/' : false; <ide> } <ide> <del> // TODO refactor so there is less overhead <del> // incurred on each URL generated. <ide> $request = static::getRequest(true); <ide> if ($request) { <ide> $params = $request->params; <ide> public static function url($url = null, $options = array()) { <ide> * This will strip out 'autoRender', 'bare', 'requested', and 'return' param names as those <ide> * are used for CakePHP internals and should not normally be part of an output url. <ide> * <del> * @param Cake\Network\Request|array $params The params array or Cake\Network\Request object that needs to be reversed. <del> * @param boolean $full Set to true to include the full url including the protocol when reversing <del> * the url. <add> * @param Cake\Network\Request|array $params The params array or <add> * Cake\Network\Request object that needs to be reversed. <add> * @param boolean $full Set to true to include the full url including the <add> * protocol when reversing the url. <ide> * @return string The string that is the reversed result of the array <ide> */ <ide> public static function reverse($params, $full = false) {
1
Javascript
Javascript
allow three.box3 as an input of boxhelper
5d892789529562f2ab8f8f540ab6ca481aabe172
<ide><path>src/extras/helpers/BoxHelper.js <ide> THREE.BoxHelper.prototype.update = ( function () { <ide> <ide> return function ( object ) { <ide> <del> box.setFromObject( object ); <add> if ( object instanceof THREE.Box3 ) { <add> <add> box.copy( object ); <add> <add> } else { <add> <add> box.setFromObject( object ); <add> <add> } <ide> <ide> if ( box.isEmpty() ) return; <ide>
1
Go
Go
fix bridge and br_netfilter modules loading
0c2293e0a07f85ce7a2e934b0a2f36b3937f2dd4
<ide><path>libnetwork/drivers/bridge/bridge.go <ide> import ( <ide> "fmt" <ide> "io/ioutil" <ide> "net" <add> "os" <ide> "os/exec" <ide> "path/filepath" <ide> "strconv" <add> "strings" <ide> "sync" <ide> "syscall" <ide> <ide> func newDriver() driverapi.Driver { <ide> <ide> // Init registers a new instance of bridge driver <ide> func Init(dc driverapi.DriverCallback) error { <del> // try to modprobe bridge first <del> // see gh#12177 <del> if out, err := exec.Command("modprobe", "-va", "bridge", "nf_nat", "br_netfilter").CombinedOutput(); err != nil { <del> logrus.Warnf("Running modprobe bridge nf_nat br_netfilter failed with message: %s, error: %v", out, err) <add> if _, err := os.Stat("/proc/sys/net/bridge"); err != nil { <add> if out, err := exec.Command("modprobe", "-va", "bridge", "br_netfilter").CombinedOutput(); err != nil { <add> logrus.Warnf("Running modprobe bridge br_netfilter failed with message: %s, error: %v", out, err) <add> } <add> } <add> if out, err := exec.Command("modprobe", "-va", "nf_nat").CombinedOutput(); err != nil { <add> logrus.Warnf("Running modprobe nf_nat failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err) <ide> } <ide> if err := iptables.FirewalldInit(); err != nil { <ide> logrus.Debugf("Fail to initialize firewalld: %v, using raw iptables instead", err)
1
PHP
PHP
guess hasone or hasmany relationship
7d78de0b214398d5c34c34fd840eee7812fa22ca
<ide><path>src/Illuminate/Database/Eloquent/Factories/Factory.php <ide> public function has(self $factory, $relationship = null) <ide> { <ide> return $this->newInstance([ <ide> 'has' => $this->has->concat([new Relationship( <del> $factory, $relationship ?: Str::camel(Str::plural(class_basename($factory->modelName()))) <add> $factory, $relationship ?: $this->guessRelationship($factory->modelName()) <ide> )]), <ide> ]); <ide> } <ide> <add> /** <add> * Guess relation name between the model and the related. <add> * <add> * @param string $related <add> * @return string <add> */ <add> protected function guessRelationship(string $related) <add> { <add> $guess = Str::camel(Str::plural(class_basename($related))); <add> <add> return method_exists($this->modelName(), $guess) ? $guess : Str::singular($guess); <add> } <add> <ide> /** <ide> * Define an attached relationship for the model. <ide> *
1
Python
Python
append build c libraries as dependencies of
2d596da7383cc30092e5812a103eb50b0fb9b16c
<ide><path>numpy/distutils/command/build_ext.py <ide> def run(self): <ide> ' overwriting build_info\n%s... \nwith\n%s...' \ <ide> % (libname, `clibs[libname]`[:300], `build_info`[:300])) <ide> clibs[libname] = build_info <add> local_clibs = clibs.copy() <ide> # .. and distribution libraries: <ide> for libname,build_info in self.distribution.libraries or []: <ide> if clibs.has_key(libname): <ide> def run(self): <ide> c_lib_dirs = [] <ide> macros = [] <ide> for libname in ext.libraries: <del> if clibs.has_key(libname): <add> if libname in clibs: <ide> binfo = clibs[libname] <ide> c_libs += binfo.get('libraries',[]) <ide> c_lib_dirs += binfo.get('library_dirs',[]) <ide> for m in binfo.get('macros',[]): <ide> if m not in macros: <ide> macros.append(m) <add> if libname in local_clibs: <add> c = self.compiler <add> outname = c.library_filename(libname, <add> output_dir=self.build_temp) <add> ext.depends.append(outname) <ide> for l in clibs.get(libname,{}).get('source_languages',[]): <ide> ext_languages.add(l) <ide> if c_libs:
1
Text
Text
add changelog entry for [ci skip]
fe8239e35ad025fa833a9e8307d4f2b9f7d2978e
<ide><path>actionpack/CHANGELOG.md <add>* Add request headers in the payload of the `start_processing.action_controller` <add> and `process_action.action_controller` notifications. <add> <add> *Gareth du Plooy* <add> <ide> * Add `action_dispatch_integration_test` load hook. The hook can be used to <ide> extend `ActionDispatch::IntegrationTest` once it has been loaded. <ide>
1
Text
Text
realign a different indentation
c606946c5c5cf856b1c737b5f528f39e0966ec56
<ide><path>guide/english/java/arraylist/index.md <ide> Since ArrayList implements *List*, an ArrayList can be created using the followi <ide> ``` <ide> <ide> **Modify/update element at specified index** <del> ```java <del> variable_name.set(index_number, element); <add> <add> ```java <add> variable_name.set(index_number,element); <ide> ``` <ide> <ide> **Get the size of the list** <del> ```java <del> variable_name.size(); <add> <add> ```java <add> variable_name.size(); <ide> ``` <ide> <ide> **Get a sublist of the list** <del> ```java <del> variable_name.subList(int fromIndex, int toIndex); <add> <add> ```java <add> variable_name.subList(int fromIndex, int toIndex); <ide> ``` <ide> <ide> **Reverse elements in list** <ide> Since ArrayList implements *List*, an ArrayList can be created using the followi <ide> ``` <ide> <ide> **Sort elements in ascending order** <del>```java <add> ```java <ide> Collections.sort(variable_name); <ide> ``` <ide> <ide> **Sort elements in descending order** <del> ```java <del> Collections.sort(variable_name, Collections.reverseOrder()); <del> ``` <ide> <add> ```java <add> Collections.sort(variable_name, Collections.reverseOrder()); <add> ``` <ide> <ide> **Creating Array from ArrayList** <ide> <ide> for(Object obj : arr) { <ide> } <ide> ``` <ide> <del> An ArrayList allows us to randomly access elements. ArrayList is similar to *Vector* in a lot of ways, but it is faster than Vectors. The main thing to note is that - Vectors are faster than arrays but ArrayLists are not. <del> <add>An ArrayList allows us to randomly access elements. ArrayList is similar to *Vector* in a lot of ways, but it is faster than Vectors. The main thing to note is that - Vectors are faster than arrays but ArrayLists are not. <ide> <del> So when it comes down to choosing between the two - if speed is critical then Vectors should be considered, otherwise ArrayLists are better when it comes to storing large number of elements and accessing them efficiently. <add>So when it comes down to choosing between the two - if speed is critical then Vectors should be considered, otherwise ArrayLists are better when it comes to storing large number of elements and accessing them efficiently. <ide> <ide> ## Basic Big O for ArrayList Methods: <ide>
1
Text
Text
enclose a value of variable in back quote
4dbb8b307c57f6b82b42f47c6c79880b6f00bb2f
<ide><path>docs/docs/08-working-with-the-browser.md <ide> React provides lifecycle methods that you can specify to hook into this process. <ide> ### Updating <ide> <ide> * `componentWillReceiveProps(object nextProps)` is invoked when a mounted component receives new props. This method should be used to compare `this.props` and `nextProps` to perform state transitions using `this.setState()`. <del>* `shouldComponentUpdate(object nextProps, object nextState): boolean` is invoked when a component decides whether any changes warrant an update to the DOM. Implement this as an optimization to compare `this.props` with `nextProps` and `this.state` with `nextState` and return false if React should skip updating. <add>* `shouldComponentUpdate(object nextProps, object nextState): boolean` is invoked when a component decides whether any changes warrant an update to the DOM. Implement this as an optimization to compare `this.props` with `nextProps` and `this.state` with `nextState` and return `false` if React should skip updating. <ide> * `componentWillUpdate(object nextProps, object nextState)` is invoked immediately before updating occurs. You cannot call `this.setState()` here. <ide> * `componentDidUpdate(object prevProps, object prevState)` is invoked immediately after updating occurs. <ide>
1
Text
Text
fix typos in docs
130ffa5fbf8751de4eeb4bfd2463f46242ecc50d
<ide><path>website/docs/api/data-formats.md <ide> process that are used when you run [`spacy train`](/api/cli#train). <ide> | `raw_text` | Optional path to a jsonl file with unlabelled text documents for a [rehearsal](/api/language#rehearse) step. Defaults to variable `${paths.raw}`. ~~Optional[str]~~ | <ide> | `score_weights` | Score names shown in metrics mapped to their weight towards the final weighted score. See [here](/usage/training#metrics) for details. Defaults to `{}`. ~~Dict[str, float]~~ | <ide> | `seed` | The random seed. Defaults to variable `${system.seed}`. ~~int~~ | <del>| `corpus` | Dot notation of the config location defining the train corpus. Defaults to `corpora.train`. ~~str~~ | <add>| `train_corpus` | Dot notation of the config location defining the train corpus. Defaults to `corpora.train`. ~~str~~ | <ide> | `vectors` | Name or path of pipeline containing pretrained word vectors to use, e.g. created with [`init vocab`](/api/cli#init-vocab). Defaults to `null`. ~~Optional[str]~~ | <ide> <ide> ### pretraining {#config-pretraining tag="section,optional"} <ide> used when you run [`spacy pretrain`](/api/cli#pretrain). <ide> | `n_save_every` | Saving frequency. Defaults to `null`. ~~Optional[int]~~ | <ide> | `objective` | The pretraining objective. Defaults to `{"type": "characters", "n_characters": 4}`. ~~Dict[str, Any]~~ | <ide> | `optimizer` | The optimizer. Defaults to [`Adam`](https://thinc.ai/docs/api-optimizers#adam). ~~Optimizer~~ | <del>| `corpus` | Dot notation of the config location defining the train corpus. Defaults to `corpora.train`. ~~str~~ | <add>| `corpus` | Dot notation of the config location defining the train corpus. Defaults to `corpora.pretrain`. ~~str~~ | <ide> | `batcher` | Batcher for the training data. ~~Callable[[Iterator[Doc], Iterator[List[Doc]]]]~~ | <ide> | `component` | Component to find the layer to pretrain. Defaults to `"tok2vec"`. ~~str~~ | <ide> | `layer` | The layer to pretrain. If empty, the whole component model will be used. ~~str~~ |
1
Go
Go
remove obsolete comments
59d58352dfb66a12000d4b65f6c337c7936326e3
<ide><path>graph/graph.go <ide> func (graph *Graph) Get(name string) (*image.Image, error) { <ide> if err != nil { <ide> return nil, err <ide> } <del> // FIXME: return nil when the image doesn't exist, instead of an error <ide> img, err := image.LoadImage(graph.ImageRoot(id)) <ide> if err != nil { <ide> return nil, err
1
Python
Python
use tf.compat.v2 when accessing policies
a6f9945ac4352774f3219e379865720f7533ddd3
<ide><path>official/transformer/v2/transformer_main.py <ide> def __init__(self, flags_obj): <ide> # this. <ide> loss_scale = flags_core.get_loss_scale(flags_obj, <ide> default_for_fp16="dynamic") <del> policy = tf.keras.mixed_precision.experimental.Policy( <add> policy = tf.compat.v2.keras.mixed_precision.experimental.Policy( <ide> "mixed_float16", loss_scale=loss_scale) <del> tf.keras.mixed_precision.experimental.set_policy(policy) <add> tf.compat.v2.keras.mixed_precision.experimental.set_policy(policy) <ide> <ide> self.distribution_strategy = distribution_utils.get_distribution_strategy( <ide> distribution_strategy=flags_obj.distribution_strategy, <ide> def _create_optimizer(self): <ide> opt, loss_scale=flags_core.get_loss_scale(self.flags_obj, <ide> default_for_fp16="dynamic")) <ide> if self.flags_obj.fp16_implementation == "graph_rewrite": <del> # Note: when flags_obj.fp16_implementation == "graph_rewrite", <del> # dtype as determined by flags_core.get_tf_dtype(flags_obj) would be 'float32' <del> # which will ensure tf.keras.mixed_precision and tf.train.experimental.enable_mixed_precision_graph_rewrite <del> # do not double up. <add> # Note: when flags_obj.fp16_implementation == "graph_rewrite", dtype as <add> # determined by flags_core.get_tf_dtype(flags_obj) would be 'float32' <add> # which will ensure tf.compat.v2.keras.mixed_precision and <add> # tf.train.experimental.enable_mixed_precision_graph_rewrite do not double <add> # up. <ide> opt = tf.train.experimental.enable_mixed_precision_graph_rewrite(opt) <ide> <ide> return opt <ide><path>official/transformer/v2/transformer_main_test.py <ide> def setUp(self): <ide> self.vocab_size = misc.get_model_params(FLAGS.param_set, 0)['vocab_size'] <ide> self.bleu_source = os.path.join(temp_dir, 'bleu_source') <ide> self.bleu_ref = os.path.join(temp_dir, 'bleu_ref') <del> self.orig_policy = tf.keras.mixed_precision.experimental.global_policy() <add> self.orig_policy = ( <add> tf.compat.v2.keras.mixed_precision.experimental.global_policy()) <ide> <ide> def tearDown(self): <del> tf.keras.mixed_precision.experimental.set_policy(self.orig_policy) <add> tf.compat.v2.keras.mixed_precision.experimental.set_policy(self.orig_policy) <ide> <ide> def _assert_exists(self, filepath): <ide> self.assertTrue(os.path.exists(filepath)) <ide><path>official/vision/image_classification/resnet_imagenet_main.py <ide> def run(flags_obj): <ide> dtype = flags_core.get_tf_dtype(flags_obj) <ide> if dtype == 'float16': <ide> loss_scale = flags_core.get_loss_scale(flags_obj, default_for_fp16=128) <del> policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16', <del> loss_scale=loss_scale) <del> tf.keras.mixed_precision.experimental.set_policy(policy) <add> policy = tf.compat.v2.keras.mixed_precision.experimental.Policy( <add> 'mixed_float16', loss_scale=loss_scale) <add> tf.compat.v2.keras.mixed_precision.experimental.set_policy(policy) <ide> if not keras_utils.is_v2_0(): <ide> raise ValueError('--dtype=fp16 is not supported in TensorFlow 1.') <ide> <ide> def run(flags_obj): <ide> with strategy_scope: <ide> optimizer = common.get_optimizer(lr_schedule) <ide> if flags_obj.fp16_implementation == "graph_rewrite": <del> # Note: when flags_obj.fp16_implementation == "graph_rewrite", <del> # dtype as determined by flags_core.get_tf_dtype(flags_obj) would be 'float32' <del> # which will ensure tf.keras.mixed_precision and tf.train.experimental.enable_mixed_precision_graph_rewrite <del> # do not double up. <del> optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite(optimizer) <add> # Note: when flags_obj.fp16_implementation == "graph_rewrite", dtype as <add> # determined by flags_core.get_tf_dtype(flags_obj) would be 'float32' <add> # which will ensure tf.compat.v2.keras.mixed_precision and <add> # tf.train.experimental.enable_mixed_precision_graph_rewrite do not double <add> # up. <add> optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite( <add> optimizer) <ide> <ide> # TODO(hongkuny): Remove trivial model usage and move it to benchmark. <ide> if flags_obj.use_trivial_model:
3
Python
Python
fix syntax error
f156db84444562a67491a6fd21e722bd5f8e88f4
<ide><path>libcloud/interface.py <ide> def __call__(id, name, driver): <ide> Set values for ivars, including any other requisite kwargs <ide> """ <ide> <del>class INodeLocation(Interface) <add>class INodeLocation(Interface): <ide> """ <ide> Physical Location of a node <ide> """
1
Text
Text
update changelog for 1.3.0-beta.2
44b940e88ddc6483baf1907496510d1d7fba8530
<ide><path>CHANGELOG.md <add><a name="1.3.0-beta.2"></a> <add># 1.3.0-beta.2 silent-ventriloquism (2014-03-14) <add> <add> <add>## Bug Fixes <add> <add>- **$$rAF:** always fallback to a $timeout in case native rAF isn't supported <add> ([7b5e0199](https://github.com/angular/angular.js/commit/7b5e019981f352add88be2984de68e553d1bfa93), <add> [#6654](https://github.com/angular/angular.js/issues/6654)) <add>- **$http:** don't convert 0 status codes to 404 for non-file protocols <add> ([56e73ea3](https://github.com/angular/angular.js/commit/56e73ea355c851fdfd574d6d2a9e2fcb75677945), <add> [#6074](https://github.com/angular/angular.js/issues/6074), [#6155](https://github.com/angular/angular.js/issues/6155)) <add>- **ngAnimate:** setting classNameFilter disables animation inside ng-if <add> ([129e2e02](https://github.com/angular/angular.js/commit/129e2e021ab1d773874428cd1fb329eae72797c4), <add> [#6539](https://github.com/angular/angular.js/issues/6539)) <add> <add> <add>## Features <add> <add>- whitelist blob urls for sanitization of data-bound image urls <add> ([47ab8df4](https://github.com/angular/angular.js/commit/47ab8df455df1f1391b760e1fbcc5c21645512b8), <add> [#4623](https://github.com/angular/angular.js/issues/4623)) <add> <add> <add> <ide> <a name="1.3.0-beta.1"></a> <ide> # 1.3.0-beta.1 retractable-eyebrow (2014-03-07) <ide>
1
Javascript
Javascript
allow chaining of whens and otherwise
15ecc6f3668885ebc5c7130dd34e00059ddf79ae
<ide><path>src/ng/route.js <ide> function $RouteProvider(){ <ide> * If the option is set to `false` and url in the browser changes, then <ide> * `$routeUpdate` event is broadcasted on the root scope. <ide> * <del> * @returns {Object} route object <add> * @returns {Object} self <ide> * <ide> * @description <ide> * Adds a new route definition to the `$route` service. <ide> */ <ide> this.when = function(path, route) { <del> var routeDef = routes[path]; <del> if (!routeDef) routeDef = routes[path] = {reloadOnSearch: true}; <del> if (route) extend(routeDef, route); // TODO(im): what the heck? merge two route definitions? <add> routes[path] = extend({reloadOnSearch: true}, route); <ide> <ide> // create redirection for trailing slashes <ide> if (path) { <ide> function $RouteProvider(){ <ide> routes[redirectPath] = {redirectTo: path}; <ide> } <ide> <del> return routeDef; <add> return this; <ide> }; <ide> <ide> /** <ide> function $RouteProvider(){ <ide> * is matched. <ide> * <ide> * @param {Object} params Mapping information to be assigned to `$route.current`. <add> * @returns {Object} self <ide> */ <ide> this.otherwise = function(params) { <ide> this.when(null, params); <add> return this; <ide> }; <ide> <ide> <ide><path>test/ng/routeParamsSpec.js <ide> describe('$routeParams', function() { <ide> it('should publish the params into a service', function() { <ide> module(function($routeProvider) { <del> $routeProvider.when('/foo'); <del> $routeProvider.when('/bar/:barId'); <add> $routeProvider.when('/foo', {}); <add> $routeProvider.when('/bar/:barId', {}); <ide> }); <ide> <ide> inject(function($rootScope, $route, $location, $routeParams) { <ide><path>test/ng/routeSpec.js <ide> describe('$route', function() { <ide> module(function($routeProvider) { <ide> $routeProvider.when('/Book/:book/Chapter/:chapter', <ide> {controller: noop, template: 'Chapter.html'}); <del> $routeProvider.when('/Blank'); <add> $routeProvider.when('/Blank', {}); <ide> }); <ide> inject(function($route, $location, $rootScope) { <ide> $rootScope.$on('$beforeRouteChange', function(event, next, current) { <ide> describe('$route', function() { <ide> }); <ide> <ide> <add> it('should chain whens and otherwise', function() { <add> module(function($routeProvider){ <add> $routeProvider.when('/foo', {template: 'foo.html'}). <add> otherwise({template: 'bar.html'}). <add> when('/baz', {template: 'baz.html'}); <add> }); <add> <add> inject(function($route, $location, $rootScope) { <add> $rootScope.$digest(); <add> expect($route.current.template).toBe('bar.html'); <add> <add> $location.url('/baz'); <add> $rootScope.$digest(); <add> expect($route.current.template).toBe('baz.html'); <add> }); <add> }); <add> <add> <ide> it('should not fire $after/beforeRouteChange during bootstrap (if no route)', function() { <ide> var routeChangeSpy = jasmine.createSpy('route change'); <ide>
3
Ruby
Ruby
move cellar checks to module
91c5c15a488ad46bf111c7c97c68574a59ac6fac
<ide><path>Library/Homebrew/formula_cellar_checks.rb <add>module FormulaCellarChecks <add> def check_PATH bin <add> # warn the user if stuff was installed outside of their PATH <add> return unless bin.directory? <add> return unless bin.children.length > 0 <add> <add> bin = (HOMEBREW_PREFIX/bin.basename).realpath <add> return if ORIGINAL_PATHS.include? bin <add> <add> ["#{bin} is not in your PATH", <add> "You can amend this by altering your ~/.bashrc file"] <add> end <add> <add> def check_manpages <add> # Check for man pages that aren't in share/man <add> return unless (f.prefix+'man').directory? <add> <add> ['A top-level "man" directory was found.', <add> <<-EOS.undent <add> Homebrew requires that man pages live under share. <add> This can often be fixed by passing "--mandir=#{man}" to configure. <add> EOS <add> ] <add> end <add> <add> def check_infopages <add> # Check for info pages that aren't in share/info <add> return unless (f.prefix+'info').directory? <add> <add> ['A top-level "info" directory was found.', <add> <<-EOS.undent <add> Homebrew suggests that info pages live under share. <add> This can often be fixed by passing "--infodir=#{info}" to configure. <add> EOS <add> ] <add> end <add> <add> def check_jars <add> return unless f.lib.directory? <add> <add> jars = f.lib.children.select{|g| g.to_s =~ /\.jar$/} <add> return if jars.empty? <add> <add> ['JARs were installed to "lib".', <add> <<-EOS.undent <add> Installing JARs to "lib" can cause conflicts between packages. <add> For Java software, it is typically better for the formula to <add> install to "libexec" and then symlink or wrap binaries into "bin". <add> "See "activemq", "jruby", etc. for examples." <add> "The offending files are:" <add> #{jars} <add> EOS <add> ] <add> end <add> <add> def check_non_libraries <add> return unless f.lib.directory? <add> <add> valid_extensions = %w(.a .dylib .framework .jnilib .la .o .so <add> .jar .prl .pm .sh) <add> non_libraries = f.lib.children.select do |g| <add> next if g.directory? <add> not valid_extensions.include? g.extname <add> end <add> return if non_libraries.empty? <add> <add> ['Non-libraries were installed to "lib".', <add> <<-EOS.undent <add> Installing non-libraries to "lib" is bad practice. <add> The offending files are: <add> #{non_libraries} <add> EOS <add> ] <add> end <add> <add> def check_non_executables bin <add> return unless bin.directory? <add> <add> non_exes = bin.children.select { |g| g.directory? or not g.executable? } <add> return if non_exes.empty? <add> <add> ["Non-executables were installed to \"#{bin}\".", <add> <<-EOS.undent <add> The offending files are: <add> #{non_exes}" <add> EOS <add> ] <add> end <add>end <ide><path>Library/Homebrew/formula_installer.rb <ide> require 'bottles' <ide> require 'caveats' <ide> require 'cleaner' <add>require 'formula_cellar_checks' <ide> <ide> class FormulaInstaller <add> include FormulaCellarChecks <add> <ide> attr_reader :f <ide> attr_accessor :tab, :options, :ignore_deps <ide> attr_accessor :show_summary_heading, :show_header <ide> def pour <ide> <ide> ## checks <ide> <del> def check_PATH bin <del> # warn the user if stuff was installed outside of their PATH <del> if bin.directory? and bin.children.length > 0 <del> bin = (HOMEBREW_PREFIX/bin.basename).realpath <del> unless ORIGINAL_PATHS.include? bin <del> opoo "#{bin} is not in your PATH" <del> puts "You can amend this by altering your ~/.bashrc file" <del> @show_summary_heading = true <del> end <del> end <del> end <del> <del> def check_manpages <del> # Check for man pages that aren't in share/man <del> if (f.prefix+'man').directory? <del> opoo 'A top-level "man" directory was found.' <del> puts "Homebrew requires that man pages live under share." <del> puts 'This can often be fixed by passing "--mandir=#{man}" to configure.' <del> @show_summary_heading = true <del> Homebrew.failed = true # fatal to Brew Bot <del> end <del> end <del> <del> def check_infopages <del> # Check for info pages that aren't in share/info <del> if (f.prefix+'info').directory? <del> opoo 'A top-level "info" directory was found.' <del> puts "Homebrew suggests that info pages live under share." <del> puts 'This can often be fixed by passing "--infodir=#{info}" to configure.' <del> @show_summary_heading = true <del> end <del> end <del> <del> def check_jars <del> return unless f.lib.directory? <del> <del> jars = f.lib.children.select{|g| g.to_s =~ /\.jar$/} <del> unless jars.empty? <del> opoo 'JARs were installed to "lib".' <del> puts "Installing JARs to \"lib\" can cause conflicts between packages." <del> puts "For Java software, it is typically better for the formula to" <del> puts "install to \"libexec\" and then symlink or wrap binaries into \"bin\"." <del> puts "See \"activemq\", \"jruby\", etc. for examples." <del> puts "The offending files are:" <del> puts jars <del> @show_summary_heading = true <del> end <del> end <del> <del> def check_non_libraries <del> return unless f.lib.directory? <del> <del> valid_extensions = %w(.a .dylib .framework .jnilib .la .o .so <del> .jar .prl .pm .sh) <del> non_libraries = f.lib.children.select do |g| <del> next if g.directory? <del> not valid_extensions.include? g.extname <del> end <del> <del> unless non_libraries.empty? <del> opoo 'Non-libraries were installed to "lib".' <del> puts "Installing non-libraries to \"lib\" is bad practice." <del> puts "The offending files are:" <del> puts non_libraries <del> @show_summary_heading = true <del> end <del> end <del> <del> def check_non_executables bin <del> non_exes = bin.children.select { |g| g.directory? or not g.executable? } <del> <del> unless non_exes.empty? <del> opoo 'Non-executables were installed to "bin".' <del> puts "Installing non-executables to \"bin\" is bad practice." <del> puts "The offending files are:" <del> puts non_exes <del> @show_summary_heading = true <del> Homebrew.failed = true # fatal to Brew Bot <del> end <add> def print_check_output warning_and_description <add> return unless warning_and_description <add> warning, description = *warning_and_description <add> opoo warning <add> puts description <add> @show_summary_heading = true <ide> end <ide> <ide> def audit_bin <ide> return unless f.bin.directory? <del> check_PATH f.bin unless f.keg_only? <del> check_non_executables f.bin <add> print_check_output(check_PATH(f.bin)) unless f.keg_only? <add> print_check_output(check_non_executables(f.bin)) <ide> end <ide> <ide> def audit_sbin <ide> return unless f.sbin.directory? <del> check_PATH f.sbin unless f.keg_only? <del> check_non_executables f.sbin <add> print_check_output(check_PATH(f.sbin)) unless f.keg_only? <add> print_check_output(check_non_executables(f.sbin)) <ide> end <ide> <ide> def audit_lib <del> check_jars <del> check_non_libraries <add> print_check_output(check_jars) <add> print_check_output(check_non_libraries) <ide> end <ide> <ide> def audit_man <del> check_manpages <add> print_check_output(check_manpages) <ide> end <ide> <ide> def audit_info <del> check_infopages <add> print_check_output(check_infopages) <ide> end <ide> <ide> private
2
Python
Python
unify dot behavior in tf and theano
75bef59016a8a230823a04836e1ab6e5bf0079dc
<ide><path>keras/backend/tensorflow_backend.py <ide> def int_shape(x): <ide> <ide> <ide> def ndim(x): <del> return len(x.get_shape()) <add> dims = x.get_shape()._dims <add> if dims is not None: <add> return len(dims) <add> return None <ide> <ide> <ide> def dtype(x): <ide> def cast(x, dtype): <ide> # LINEAR ALGEBRA <ide> <ide> def dot(x, y): <del> return tf.matmul(x, y) <add> '''Multiplies 2 tensors. <add> When attempting to multiply a 2D tensor <add> with a 3D tensor, reproduces the Theano behavior <add> (e.g. (2, 3).(4, 3, 5) = (2, 4, 5)) <add> ''' <add> if ndim(x) == 2 and ndim(y) == 3: <add> slices = [] <add> for i in range(int_shape(y)[0]): <add> slice_i = tf.matmul(x, y[i, :, :]) <add> slice_i = expand_dims(slice_i, 1) <add> slices.append(slice_i) <add> out = tf.concat(1, slices) <add> return out <add> out = tf.matmul(x, y) <add> return out <ide> <ide> <ide> def batch_dot(x, y, axes=None):
1
Javascript
Javascript
use stat.st_size only to read regular files
a6af70948924625566c48bfb381ce7a804f98520
<ide><path>lib/fs.js <ide> function readFileAfterStat(err, st) { <ide> if (err) <ide> return context.close(err); <ide> <del> var size = context.size = st.size; <add> var size = context.size = st.isFile() ? st.size : 0; <ide> <ide> if (size === 0) { <ide> context.buffers = []; <ide> fs.readFileSync = function(path, options) { <ide> var flag = options.flag || 'r'; <ide> var fd = fs.openSync(path, flag, 0o666); <ide> <add> var st; <ide> var size; <ide> var threw = true; <ide> try { <del> size = fs.fstatSync(fd).size; <add> st = fs.fstatSync(fd); <add> size = st.isFile() ? st.size : 0; <ide> threw = false; <ide> } finally { <ide> if (threw) fs.closeSync(fd);
1
Javascript
Javascript
tweak the rules for the showcase
50e0d8e171b1d5e780eb870d10f402ea59670f2b
<ide><path>website/src/react-native/showcase.js <ide> /* <ide> Thousands of applications use React Native, so we can't list all of them <ide> in our showcase. To be useful to someone looking through the showcase, <del>either the app must be something that most readers would recognize, or the makers of the application must have posted useful technical content about the making of the app. It also must be useful considering that the majority of readers only speak English. So, each app in the showcase should link to either: <add>either the app must be something that most readers would recognize, or the makers of the application must have <add>posted useful technical content about the making of the app. It also must be useful considering that the majority <add>of readers only speak English. So, each app in the showcase should link to either: <ide> <ide> 1/ An English-language news article discussing the app, built either by a funded startup or for a public company <del>2/ An English-language technical blog post by the app creators specifically discussing React Native <add>2/ An English-language technical post on a funded startup or public company blog discussing React Native <ide> <ide> For each app in the showcase, use infoLink and infoTitle to reference this content. <ide> */
1
Javascript
Javascript
remove reference to three in modules
cdf0bba21a8b3a264f21dcea59dbca28b39905a5
<ide><path>examples/jsm/controls/MapControls.js <ide> var MapControls = function ( object, domElement ) { <ide> }; <ide> <ide> MapControls.prototype = Object.create( EventDispatcher.prototype ); <del>MapControls.prototype.constructor = THREE.MapControls; <add>MapControls.prototype.constructor = MapControls; <ide> <ide> Object.defineProperties( MapControls.prototype, { <ide> <ide><path>examples/jsm/controls/OrbitControls.js <ide> var OrbitControls = function ( object, domElement ) { <ide> }; <ide> <ide> OrbitControls.prototype = Object.create( EventDispatcher.prototype ); <del>OrbitControls.prototype.constructor = THREE.OrbitControls; <add>OrbitControls.prototype.constructor = OrbitControls; <ide> <ide> Object.defineProperties( OrbitControls.prototype, { <ide> <ide><path>examples/jsm/controls/TrackballControls.js <ide> var TrackballControls = function ( object, domElement ) { <ide> }; <ide> <ide> TrackballControls.prototype = Object.create( EventDispatcher.prototype ); <del>TrackballControls.prototype.constructor = THREE.TrackballControls; <add>TrackballControls.prototype.constructor = TrackballControls; <ide> <ide> export { TrackballControls };
3
Text
Text
add agent conference to conferences docs
09ce083c4cad39714208c36f84cf7cfcff0f691d
<ide><path>docs/community/conferences.md <ide> redirect_from: "docs/conferences.html" <ide> <ide> ## Upcoming Conferences <ide> <add>### Agent Conference 2017 <add>January 20-21 in Dornbirn, Austria <add> <add>[Website](http://agent.sh/) <add> <ide> ### ReactEurope 2017 <ide> May 18th & 19th in Paris, France <ide>
1
Text
Text
fix pr-url in repl.md
4ba1ddb046ed79118f357a9d47458bdf158dfa06
<ide><path>doc/api/repl.md <ide> Returns `true` if `keyword` is a valid keyword, otherwise `false`. <ide> added: v0.1.91 <ide> changes: <ide> - version: v10.0.0 <del> pr-url: https://github.com/nodejs/node/pull/v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/19187 <ide> description: The `REPL_MAGIC_MODE` `replMode` was removed. <ide> - version: v5.8.0 <ide> pr-url: https://github.com/nodejs/node/pull/5388
1
Go
Go
move responsibility of ls/inspect to volume driver
d3eca4451d264aac564594fe46b8c097bd85a5cc
<ide><path>api/client/volume.go <ide> func (cli *DockerCli) CmdVolumeLs(args ...string) error { <ide> <ide> w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) <ide> if !*quiet { <add> for _, warn := range volumes.Warnings { <add> fmt.Fprintln(cli.err, warn) <add> } <ide> fmt.Fprintf(w, "DRIVER \tVOLUME NAME") <ide> fmt.Fprintf(w, "\n") <ide> } <ide> func (cli *DockerCli) CmdVolumeInspect(args ...string) error { <ide> return cli.inspectElements(*tmplStr, cmd.Args(), inspectSearcher) <ide> } <ide> <del>// CmdVolumeCreate creates a new container from a given image. <add>// CmdVolumeCreate creates a new volume. <ide> // <ide> // Usage: docker volume create [OPTIONS] <ide> func (cli *DockerCli) CmdVolumeCreate(args ...string) error { <ide> func (cli *DockerCli) CmdVolumeCreate(args ...string) error { <ide> return nil <ide> } <ide> <del>// CmdVolumeRm removes one or more containers. <add>// CmdVolumeRm removes one or more volumes. <ide> // <ide> // Usage: docker volume rm VOLUME [VOLUME...] <ide> func (cli *DockerCli) CmdVolumeRm(args ...string) error { <ide> func (cli *DockerCli) CmdVolumeRm(args ...string) error { <ide> cmd.ParseFlags(args, true) <ide> <ide> var status = 0 <add> <ide> for _, name := range cmd.Args() { <ide> if err := cli.client.VolumeRemove(name); err != nil { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide><path>api/server/router/volume/backend.go <ide> import ( <ide> // Backend is the methods that need to be implemented to provide <ide> // volume specific functionality <ide> type Backend interface { <del> Volumes(filter string) ([]*types.Volume, error) <add> Volumes(filter string) ([]*types.Volume, []string, error) <ide> VolumeInspect(name string) (*types.Volume, error) <ide> VolumeCreate(name, driverName string, <ide> opts map[string]string) (*types.Volume, error) <ide><path>api/server/router/volume/volume_routes.go <ide> func (v *volumeRouter) getVolumesList(ctx context.Context, w http.ResponseWriter <ide> return err <ide> } <ide> <del> volumes, err := v.backend.Volumes(r.Form.Get("filters")) <add> volumes, warnings, err := v.backend.Volumes(r.Form.Get("filters")) <ide> if err != nil { <ide> return err <ide> } <del> return httputils.WriteJSON(w, http.StatusOK, &types.VolumesListResponse{Volumes: volumes}) <add> return httputils.WriteJSON(w, http.StatusOK, &types.VolumesListResponse{Volumes: volumes, Warnings: warnings}) <ide> } <ide> <ide> func (v *volumeRouter) getVolumeByName(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide><path>api/types/types.go <ide> type Volume struct { <ide> // VolumesListResponse contains the response for the remote API: <ide> // GET "/volumes" <ide> type VolumesListResponse struct { <del> Volumes []*Volume // Volumes is the list of volumes being returned <add> Volumes []*Volume // Volumes is the list of volumes being returned <add> Warnings []string // Warnings is a list of warnings that occurred when getting the list from the volume drivers <ide> } <ide> <ide> // VolumeCreateRequest contains the response for the remote API: <ide><path>daemon/create.go <ide> import ( <ide> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/stringid" <del> "github.com/docker/docker/volume" <add> volumestore "github.com/docker/docker/volume/store" <ide> "github.com/opencontainers/runc/libcontainer/label" <ide> ) <ide> <ide> func (daemon *Daemon) VolumeCreate(name, driverName string, opts map[string]stri <ide> <ide> v, err := daemon.volumes.Create(name, driverName, opts) <ide> if err != nil { <add> if volumestore.IsNameConflict(err) { <add> return nil, derr.ErrorVolumeNameTaken.WithArgs(name) <add> } <ide> return nil, err <ide> } <ide> <del> // keep "docker run -v existing_volume:/foo --volume-driver other_driver" work <del> if (driverName != "" && v.DriverName() != driverName) || (driverName == "" && v.DriverName() != volume.DefaultDriverName) { <del> return nil, derr.ErrorVolumeNameTaken.WithArgs(name, v.DriverName()) <del> } <del> <del> if driverName == "" { <del> driverName = volume.DefaultDriverName <del> } <del> daemon.LogVolumeEvent(name, "create", map[string]string{"driver": driverName}) <add> daemon.LogVolumeEvent(v.Name(), "create", map[string]string{"driver": v.DriverName()}) <ide> return volumeToAPIType(v), nil <ide> } <ide><path>daemon/create_unix.go <ide> func (daemon *Daemon) createContainerPlatformSpecificSettings(container *contain <ide> } <ide> } <ide> <del> v, err := daemon.createVolume(name, volumeDriver, nil) <add> v, err := daemon.volumes.CreateWithRef(name, volumeDriver, container.ID, nil) <ide> if err != nil { <ide> return err <ide> } <ide><path>daemon/create_windows.go <ide> func (daemon *Daemon) createContainerPlatformSpecificSettings(container *contain <ide> <ide> // Create the volume in the volume driver. If it doesn't exist, <ide> // a new one will be created. <del> v, err := daemon.createVolume(mp.Name, volumeDriver, nil) <add> v, err := daemon.volumes.CreateWithRef(mp.Name, volumeDriver, container.ID, nil) <ide> if err != nil { <ide> return err <ide> } <ide><path>daemon/daemon.go <ide> func configureVolumes(config *Config, rootUID, rootGID int) (*store.VolumeStore, <ide> } <ide> <ide> volumedrivers.Register(volumesDriver, volumesDriver.Name()) <del> s := store.New() <del> s.AddAll(volumesDriver.List()) <del> <del> return s, nil <add> return store.New(), nil <ide> } <ide> <ide> // AuthenticateToRegistry checks the validity of credentials in authConfig <ide><path>daemon/delete.go <ide> func (daemon *Daemon) VolumeRm(name string) error { <ide> if err != nil { <ide> return err <ide> } <add> <ide> if err := daemon.volumes.Remove(v); err != nil { <ide> if volumestore.IsInUse(err) { <ide> return derr.ErrorCodeRmVolumeInUse.WithArgs(err) <ide><path>daemon/list.go <ide> func (daemon *Daemon) transformContainer(container *container.Container, ctx *li <ide> <ide> // Volumes lists known volumes, using the filter to restrict the range <ide> // of volumes returned. <del>func (daemon *Daemon) Volumes(filter string) ([]*types.Volume, error) { <add>func (daemon *Daemon) Volumes(filter string) ([]*types.Volume, []string, error) { <ide> var volumesOut []*types.Volume <ide> volFilters, err := filters.FromParam(filter) <ide> if err != nil { <del> return nil, err <add> return nil, nil, err <ide> } <ide> <ide> filterUsed := volFilters.Include("dangling") && <ide> (volFilters.ExactMatch("dangling", "true") || volFilters.ExactMatch("dangling", "1")) <ide> <del> volumes := daemon.volumes.List() <add> volumes, warnings, err := daemon.volumes.List() <add> if err != nil { <add> return nil, nil, err <add> } <add> if filterUsed { <add> volumes = daemon.volumes.FilterByUsed(volumes) <add> } <ide> for _, v := range volumes { <del> if filterUsed && daemon.volumes.Count(v) > 0 { <del> continue <del> } <ide> volumesOut = append(volumesOut, volumeToAPIType(v)) <ide> } <del> return volumesOut, nil <add> return volumesOut, warnings, nil <ide> } <ide> <ide> func populateImageFilterByParents(ancestorMap map[image.ID]bool, imageID image.ID, getChildren func(image.ID) []image.ID) { <ide><path>daemon/mounts.go <ide> import ( <ide> func (daemon *Daemon) prepareMountPoints(container *container.Container) error { <ide> for _, config := range container.MountPoints { <ide> if len(config.Driver) > 0 { <del> v, err := daemon.createVolume(config.Name, config.Driver, nil) <add> v, err := daemon.volumes.GetWithRef(config.Name, config.Driver, container.ID) <ide> if err != nil { <ide> return err <ide> } <add> <ide> config.Volume = v <ide> } <ide> } <ide> func (daemon *Daemon) removeMountPoints(container *container.Container, rm bool) <ide> if m.Volume == nil { <ide> continue <ide> } <del> daemon.volumes.Decrement(m.Volume) <add> daemon.volumes.Dereference(m.Volume, container.ID) <ide> if rm { <ide> err := daemon.volumes.Remove(m.Volume) <del> // ErrVolumeInUse is ignored because having this <add> // Ignore volume in use errors because having this <ide> // volume being referenced by other container is <ide> // not an error, but an implementation detail. <ide> // This prevents docker from logging "ERROR: Volume in use" <ide><path>daemon/volumes.go <ide> func volumeToAPIType(v volume.Volume) *types.Volume { <ide> } <ide> } <ide> <del>// createVolume creates a volume. <del>func (daemon *Daemon) createVolume(name, driverName string, opts map[string]string) (volume.Volume, error) { <del> v, err := daemon.volumes.Create(name, driverName, opts) <del> if err != nil { <del> return nil, err <del> } <del> daemon.volumes.Increment(v) <del> return v, nil <del>} <del> <ide> // Len returns the number of mounts. Used in sorting. <ide> func (m mounts) Len() int { <ide> return len(m) <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> } <ide> <ide> if len(cp.Source) == 0 { <del> v, err := daemon.createVolume(cp.Name, cp.Driver, nil) <add> v, err := daemon.volumes.GetWithRef(cp.Name, cp.Driver, container.ID) <ide> if err != nil { <ide> return err <ide> } <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> <ide> if len(bind.Name) > 0 && len(bind.Driver) > 0 { <ide> // create the volume <del> v, err := daemon.createVolume(bind.Name, bind.Driver, nil) <add> v, err := daemon.volumes.CreateWithRef(bind.Name, bind.Driver, container.ID, nil) <ide> if err != nil { <ide> return err <ide> } <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> for _, m := range mountPoints { <ide> if m.BackwardsCompatible() { <ide> if mp, exists := container.MountPoints[m.Destination]; exists && mp.Volume != nil { <del> daemon.volumes.Decrement(mp.Volume) <add> daemon.volumes.Dereference(mp.Volume, container.ID) <ide> } <ide> } <ide> } <ide><path>errors/daemon.go <ide> var ( <ide> // trying to create a volume that has existed using different driver. <ide> ErrorVolumeNameTaken = errcode.Register(errGroup, errcode.ErrorDescriptor{ <ide> Value: "VOLUME_NAME_TAKEN", <del> Message: "A volume named %q already exists with the %q driver. Choose a different volume name.", <add> Message: "A volume named %s already exists. Choose a different volume name.", <ide> Description: "An attempt to create a volume using a driver but the volume already exists with a different driver", <ide> HTTPStatusCode: http.StatusInternalServerError, <ide> }) <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestDaemonRestartRmVolumeInUse(c *check.C) { <ide> c.Assert(s.d.Restart(), check.IsNil) <ide> <ide> out, err = s.d.Cmd("volume", "rm", "test") <del> c.Assert(err, check.Not(check.IsNil), check.Commentf("should not be able to remove in use volume after daemon restart")) <del> c.Assert(strings.Contains(out, "in use"), check.Equals, true) <add> c.Assert(err, check.NotNil, check.Commentf("should not be able to remove in use volume after daemon restart")) <add> c.Assert(out, checker.Contains, "in use") <ide> } <ide> <ide> func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *check.C) { <ide><path>integration-cli/docker_cli_start_volume_driver_unix_test.go <ide> type eventCounter struct { <ide> mounts int <ide> unmounts int <ide> paths int <add> lists int <add> gets int <ide> } <ide> <ide> type DockerExternalVolumeSuite struct { <ide> func (s *DockerExternalVolumeSuite) SetUpSuite(c *check.C) { <ide> Err string `json:",omitempty"` <ide> } <ide> <add> type vol struct { <add> Name string <add> Mountpoint string <add> } <add> var volList []vol <add> <ide> read := func(b io.ReadCloser) (pluginRequest, error) { <ide> defer b.Close() <ide> var pr pluginRequest <ide> func (s *DockerExternalVolumeSuite) SetUpSuite(c *check.C) { <ide> <ide> mux.HandleFunc("/VolumeDriver.Create", func(w http.ResponseWriter, r *http.Request) { <ide> s.ec.creations++ <add> pr, err := read(r.Body) <add> if err != nil { <add> send(w, err) <add> return <add> } <add> volList = append(volList, vol{Name: pr.Name}) <add> send(w, nil) <add> }) <ide> <del> _, err := read(r.Body) <add> mux.HandleFunc("/VolumeDriver.List", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.lists++ <add> send(w, map[string][]vol{"Volumes": volList}) <add> }) <add> <add> mux.HandleFunc("/VolumeDriver.Get", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.gets++ <add> pr, err := read(r.Body) <ide> if err != nil { <ide> send(w, err) <ide> return <ide> } <ide> <del> send(w, nil) <add> for _, v := range volList { <add> if v.Name == pr.Name { <add> v.Mountpoint = hostVolumePath(pr.Name) <add> send(w, map[string]vol{"Volume": v}) <add> return <add> } <add> } <add> send(w, `{"Err": "no such volume"}`) <ide> }) <ide> <ide> mux.HandleFunc("/VolumeDriver.Remove", func(w http.ResponseWriter, r *http.Request) { <ide> s.ec.removals++ <del> <ide> pr, err := read(r.Body) <ide> if err != nil { <ide> send(w, err) <ide> return <ide> } <add> <ide> if err := os.RemoveAll(hostVolumePath(pr.Name)); err != nil { <ide> send(w, &pluginResp{Err: err.Error()}) <ide> return <ide> } <ide> <add> for i, v := range volList { <add> if v.Name == pr.Name { <add> if err := os.RemoveAll(hostVolumePath(v.Name)); err != nil { <add> send(w, fmt.Sprintf(`{"Err": "%v"}`, err)) <add> return <add> } <add> volList = append(volList[:i], volList[i+1:]...) <add> break <add> } <add> } <ide> send(w, nil) <ide> }) <ide> <ide> func (s *DockerExternalVolumeSuite) SetUpSuite(c *check.C) { <ide> return <ide> } <ide> p := hostVolumePath(pr.Name) <del> <del> fmt.Fprintln(w, fmt.Sprintf("{\"Mountpoint\": \"%s\"}", p)) <add> send(w, &pluginResp{Mountpoint: p}) <ide> }) <ide> <ide> mux.HandleFunc("/VolumeDriver.Mount", func(w http.ResponseWriter, r *http.Request) { <ide> func (s *DockerExternalVolumeSuite) SetUpSuite(c *check.C) { <ide> return <ide> } <ide> <del> fmt.Fprintln(w, nil) <add> send(w, nil) <ide> }) <ide> <ide> err := os.MkdirAll("/etc/docker/plugins", 0755) <ide> func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverNamedCheckBindLocalV <ide> // Make sure a request to use a down driver doesn't block other requests <ide> func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverLookupNotBlocked(c *check.C) { <ide> specPath := "/etc/docker/plugins/down-driver.spec" <del> err := ioutil.WriteFile("/etc/docker/plugins/down-driver.spec", []byte("tcp://127.0.0.7:9999"), 0644) <del> c.Assert(err, checker.IsNil) <add> err := ioutil.WriteFile(specPath, []byte("tcp://127.0.0.7:9999"), 0644) <add> c.Assert(err, check.IsNil) <ide> defer os.RemoveAll(specPath) <ide> <ide> chCmd1 := make(chan struct{}) <ide> func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverLookupNotBlocked(c * <ide> case err := <-chCmd2: <ide> c.Assert(err, checker.IsNil) <ide> case <-time.After(5 * time.Second): <del> c.Fatal("volume creates are blocked by previous create requests when previous driver is down") <ide> cmd2.Process.Kill() <add> c.Fatal("volume creates are blocked by previous create requests when previous driver is down") <ide> } <ide> } <add> <ide> func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverRetryNotImmediatelyExists(c *check.C) { <ide> err := s.d.StartWithBusybox() <ide> c.Assert(err, checker.IsNil) <ide> func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverBindExternalVolume(c <ide> c.Assert(mounts[0].Name, checker.Equals, "foo") <ide> c.Assert(mounts[0].Driver, checker.Equals, "test-external-volume-driver") <ide> } <add> <add>func (s *DockerExternalVolumeSuite) TestStartExternalVolumeDriverList(c *check.C) { <add> dockerCmd(c, "volume", "create", "-d", "test-external-volume-driver", "--name", "abc") <add> out, _ := dockerCmd(c, "volume", "ls") <add> ls := strings.Split(strings.TrimSpace(out), "\n") <add> c.Assert(len(ls), check.Equals, 2, check.Commentf("\n%s", out)) <add> <add> vol := strings.Fields(ls[len(ls)-1]) <add> c.Assert(len(vol), check.Equals, 2, check.Commentf("%v", vol)) <add> c.Assert(vol[0], check.Equals, "test-external-volume-driver") <add> c.Assert(vol[1], check.Equals, "abc") <add> <add> c.Assert(s.ec.lists, check.Equals, 1) <add>} <add> <add>func (s *DockerExternalVolumeSuite) TestStartExternalVolumeDriverGet(c *check.C) { <add> out, _, err := dockerCmdWithError("volume", "inspect", "dummy") <add> c.Assert(err, check.NotNil, check.Commentf(out)) <add> c.Assert(s.ec.gets, check.Equals, 1) <add> c.Assert(out, checker.Contains, "No such volume") <add>} <ide><path>integration-cli/docker_cli_volume_test.go <ide> import ( <ide> "os/exec" <ide> "strings" <ide> <del> derr "github.com/docker/docker/errors" <ide> "github.com/docker/docker/pkg/integration/checker" <del> "github.com/docker/docker/volume" <ide> "github.com/go-check/check" <ide> ) <ide> <ide> func (s *DockerSuite) TestVolumeCliCreateOptionConflict(c *check.C) { <ide> dockerCmd(c, "volume", "create", "--name=test") <ide> out, _, err := dockerCmdWithError("volume", "create", "--name", "test", "--driver", "nosuchdriver") <ide> c.Assert(err, check.NotNil, check.Commentf("volume create exception name already in use with another driver")) <del> stderr := derr.ErrorVolumeNameTaken.WithArgs("test", volume.DefaultDriverName).Error() <del> c.Assert(strings.Contains(out, strings.TrimPrefix(stderr, "volume name taken: ")), check.Equals, true) <add> c.Assert(out, checker.Contains, "A volume named test already exists") <ide> <ide> out, _ = dockerCmd(c, "volume", "inspect", "--format='{{ .Driver }}'", "test") <ide> _, _, err = dockerCmdWithError("volume", "create", "--name", "test", "--driver", strings.TrimSpace(out)) <ide><path>pkg/plugins/discovery.go <ide> func newLocalRegistry() localRegistry { <ide> return localRegistry{} <ide> } <ide> <add>// Scan scans all the plugin paths and returns all the names it found <add>func Scan() ([]string, error) { <add> var names []string <add> if err := filepath.Walk(socketsPath, func(path string, fi os.FileInfo, err error) error { <add> if err != nil { <add> return nil <add> } <add> <add> if fi.Mode()&os.ModeSocket != 0 { <add> name := strings.TrimSuffix(fi.Name(), filepath.Ext(fi.Name())) <add> names = append(names, name) <add> } <add> return nil <add> }); err != nil { <add> return nil, err <add> } <add> <add> for _, path := range specsPaths { <add> if err := filepath.Walk(path, func(p string, fi os.FileInfo, err error) error { <add> if err != nil || fi.IsDir() { <add> return nil <add> } <add> name := strings.TrimSuffix(fi.Name(), filepath.Ext(fi.Name())) <add> names = append(names, name) <add> return nil <add> }); err != nil { <add> return nil, err <add> } <add> } <add> return names, nil <add>} <add> <ide> // Plugin returns the plugin registered with the given name (or returns an error). <ide> func (l *localRegistry) Plugin(name string) (*Plugin, error) { <ide> socketpaths := pluginPaths(socketsPath, name, ".sock") <ide><path>pkg/plugins/plugins.go <ide> func (p *Plugin) activateWithLock() error { <ide> return nil <ide> } <ide> <add>func (p *Plugin) implements(kind string) bool { <add> for _, driver := range p.Manifest.Implements { <add> if driver == kind { <add> return true <add> } <add> } <add> return false <add>} <add> <ide> func load(name string) (*Plugin, error) { <ide> return loadWithRetry(name, true) <ide> } <ide> func Get(name, imp string) (*Plugin, error) { <ide> if err != nil { <ide> return nil, err <ide> } <del> for _, driver := range pl.Manifest.Implements { <del> logrus.Debugf("%s implements: %s", name, driver) <del> if driver == imp { <del> return pl, nil <del> } <add> if pl.implements(imp) { <add> logrus.Debugf("%s implements: %s", name, imp) <add> return pl, nil <ide> } <ide> return nil, ErrNotImplements <ide> } <ide> func Get(name, imp string) (*Plugin, error) { <ide> func Handle(iface string, fn func(string, *Client)) { <ide> extpointHandlers[iface] = fn <ide> } <add> <add>// GetAll returns all the plugins for the specified implementation <add>func GetAll(imp string) ([]*Plugin, error) { <add> pluginNames, err := Scan() <add> if err != nil { <add> return nil, err <add> } <add> <add> type plLoad struct { <add> pl *Plugin <add> err error <add> } <add> <add> chPl := make(chan plLoad, len(pluginNames)) <add> for _, name := range pluginNames { <add> go func(name string) { <add> pl, err := loadWithRetry(name, false) <add> chPl <- plLoad{pl, err} <add> }(name) <add> } <add> <add> var out []*Plugin <add> for i := 0; i < len(pluginNames); i++ { <add> pl := <-chPl <add> if pl.err != nil { <add> logrus.Error(err) <add> continue <add> } <add> if pl.pl.implements(imp) { <add> out = append(out, pl.pl) <add> } <add> } <add> return out, nil <add>} <ide><path>volume/drivers/adapter.go <ide> func (a *volumeDriverAdapter) Remove(v volume.Volume) error { <ide> return a.proxy.Remove(v.Name()) <ide> } <ide> <add>func (a *volumeDriverAdapter) List() ([]volume.Volume, error) { <add> ls, err := a.proxy.List() <add> if err != nil { <add> return nil, err <add> } <add> <add> var out []volume.Volume <add> for _, vp := range ls { <add> out = append(out, &volumeAdapter{ <add> proxy: a.proxy, <add> name: vp.Name, <add> driverName: a.name, <add> eMount: vp.Mountpoint, <add> }) <add> } <add> return out, nil <add>} <add> <add>func (a *volumeDriverAdapter) Get(name string) (volume.Volume, error) { <add> v, err := a.proxy.Get(name) <add> if err != nil { <add> return nil, err <add> } <add> <add> return &volumeAdapter{ <add> proxy: a.proxy, <add> name: v.Name, <add> driverName: a.Name(), <add> eMount: v.Mountpoint, <add> }, nil <add>} <add> <ide> type volumeAdapter struct { <ide> proxy *volumeDriverProxy <ide> name string <ide><path>volume/drivers/extpoint.go <ide> import ( <ide> <ide> var drivers = &driverExtpoint{extensions: make(map[string]volume.Driver)} <ide> <add>const extName = "VolumeDriver" <add> <ide> // NewVolumeDriver returns a driver has the given name mapped on the given client. <ide> func NewVolumeDriver(name string, c client) volume.Driver { <ide> proxy := &volumeDriverProxy{c} <ide> return &volumeDriverAdapter{name, proxy} <ide> } <ide> <ide> type opts map[string]string <add>type list []*proxyVolume <ide> <ide> // volumeDriver defines the available functions that volume plugins must implement. <ide> // This interface is only defined to generate the proxy objects. <ide> type volumeDriver interface { <ide> Mount(name string) (mountpoint string, err error) <ide> // Unmount the given volume <ide> Unmount(name string) (err error) <add> // List lists all the volumes known to the driver <add> List() (volumes list, err error) <add> // Get retreives the volume with the requested name <add> Get(name string) (volume *proxyVolume, err error) <ide> } <ide> <ide> type driverExtpoint struct { <ide> func Lookup(name string) (volume.Driver, error) { <ide> if ok { <ide> return ext, nil <ide> } <del> pl, err := plugins.Get(name, "VolumeDriver") <add> pl, err := plugins.Get(name, extName) <ide> if err != nil { <ide> return nil, fmt.Errorf("Error looking up volume plugin %s: %v", name, err) <ide> } <ide> func GetDriverList() []string { <ide> } <ide> return driverList <ide> } <add> <add>// GetAllDrivers lists all the registered drivers <add>func GetAllDrivers() ([]volume.Driver, error) { <add> plugins, err := plugins.GetAll(extName) <add> if err != nil { <add> return nil, err <add> } <add> var ds []volume.Driver <add> <add> drivers.Lock() <add> defer drivers.Unlock() <add> <add> for _, d := range drivers.extensions { <add> ds = append(ds, d) <add> } <add> <add> for _, p := range plugins { <add> ext, ok := drivers.extensions[p.Name] <add> if ok { <add> continue <add> } <add> ext = NewVolumeDriver(p.Name, p.Client) <add> drivers.extensions[p.Name] = ext <add> ds = append(ds, ext) <add> } <add> return ds, nil <add>} <ide><path>volume/drivers/extpoint_test.go <ide> func TestGetDriver(t *testing.T) { <ide> if err == nil { <ide> t.Fatal("Expected error, was nil") <ide> } <del> Register(volumetestutils.FakeDriver{}, "fake") <add> <add> Register(volumetestutils.NewFakeDriver("fake"), "fake") <ide> d, err := GetDriver("fake") <ide> if err != nil { <ide> t.Fatal(err) <ide><path>volume/drivers/proxy.go <ide> func (pp *volumeDriverProxy) Unmount(name string) (err error) { <ide> <ide> return <ide> } <add> <add>type volumeDriverProxyListRequest struct { <add>} <add> <add>type volumeDriverProxyListResponse struct { <add> Volumes list <add> Err string <add>} <add> <add>func (pp *volumeDriverProxy) List() (volumes list, err error) { <add> var ( <add> req volumeDriverProxyListRequest <add> ret volumeDriverProxyListResponse <add> ) <add> <add> if err = pp.Call("VolumeDriver.List", req, &ret); err != nil { <add> return <add> } <add> <add> volumes = ret.Volumes <add> <add> if ret.Err != "" { <add> err = errors.New(ret.Err) <add> } <add> <add> return <add>} <add> <add>type volumeDriverProxyGetRequest struct { <add> Name string <add>} <add> <add>type volumeDriverProxyGetResponse struct { <add> Volume *proxyVolume <add> Err string <add>} <add> <add>func (pp *volumeDriverProxy) Get(name string) (volume *proxyVolume, err error) { <add> var ( <add> req volumeDriverProxyGetRequest <add> ret volumeDriverProxyGetResponse <add> ) <add> <add> req.Name = name <add> if err = pp.Call("VolumeDriver.Get", req, &ret); err != nil { <add> return <add> } <add> <add> volume = ret.Volume <add> <add> if ret.Err != "" { <add> err = errors.New(ret.Err) <add> } <add> <add> return <add>} <ide><path>volume/drivers/proxy_test.go <ide> func TestVolumeRequestError(t *testing.T) { <ide> fmt.Fprintln(w, `{"Err": "Unknown volume"}`) <ide> }) <ide> <add> mux.HandleFunc("/VolumeDriver.List", func(w http.ResponseWriter, r *http.Request) { <add> w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") <add> fmt.Fprintln(w, `{"Err": "Cannot list volumes"}`) <add> }) <add> <add> mux.HandleFunc("/VolumeDriver.Get", func(w http.ResponseWriter, r *http.Request) { <add> w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") <add> fmt.Fprintln(w, `{"Err": "Cannot get volume"}`) <add> }) <add> <ide> u, _ := url.Parse(server.URL) <ide> client, err := plugins.NewClient("tcp://"+u.Host, tlsconfig.Options{InsecureSkipVerify: true}) <ide> if err != nil { <ide> func TestVolumeRequestError(t *testing.T) { <ide> if !strings.Contains(err.Error(), "Unknown volume") { <ide> t.Fatalf("Unexpected error: %v\n", err) <ide> } <add> <add> _, err = driver.List() <add> if err == nil { <add> t.Fatal("Expected error, was nil") <add> } <add> if !strings.Contains(err.Error(), "Cannot list volumes") { <add> t.Fatalf("Unexpected error: %v\n", err) <add> } <add> <add> _, err = driver.Get("volume") <add> if err == nil { <add> t.Fatal("Expected error, was nil") <add> } <add> if !strings.Contains(err.Error(), "Cannot get volume") { <add> t.Fatalf("Unexpected error: %v\n", err) <add> } <ide> } <ide><path>volume/local/local.go <ide> type Root struct { <ide> } <ide> <ide> // List lists all the volumes <del>func (r *Root) List() []volume.Volume { <add>func (r *Root) List() ([]volume.Volume, error) { <ide> var ls []volume.Volume <ide> for _, v := range r.volumes { <ide> ls = append(ls, v) <ide> } <del> return ls <add> return ls, nil <ide> } <ide> <ide> // DataPath returns the constructed path of this volume. <ide><path>volume/local/local_test.go <ide> func TestRemove(t *testing.T) { <ide> t.Fatal("volume dir not removed") <ide> } <ide> <del> if len(r.List()) != 0 { <add> if l, _ := r.List(); len(l) != 0 { <ide> t.Fatal("expected there to be no volumes") <ide> } <ide> } <ide><path>volume/store/errors.go <ide> package store <ide> <del>import "errors" <add>import ( <add> "errors" <add> "strings" <add>) <ide> <ide> var ( <ide> // errVolumeInUse is a typed error returned when trying to remove a volume that is currently in use by a container <ide> var ( <ide> errNoSuchVolume = errors.New("no such volume") <ide> // errInvalidName is a typed error returned when creating a volume with a name that is not valid on the platform <ide> errInvalidName = errors.New("volume name is not valid on this platform") <add> // errNameConflict is a typed error returned on create when a volume exists with the given name, but for a different driver <add> errNameConflict = errors.New("conflict: volume name must be unique") <ide> ) <ide> <ide> // OpErr is the error type returned by functions in the store package. It describes <ide> type OpErr struct { <ide> Op string <ide> // Name is the name of the resource being requested for this op, typically the volume name or the driver name. <ide> Name string <add> // Refs is the list of references associated with the resource. <add> Refs []string <ide> } <ide> <ide> // Error satisfies the built-in error interface type. <ide> func (e *OpErr) Error() string { <ide> } <ide> <ide> s = s + ": " + e.Err.Error() <add> if len(e.Refs) > 0 { <add> s = s + " - " + "[" + strings.Join(e.Refs, ", ") + "]" <add> } <ide> return s <ide> } <ide> <ide> func IsNotExist(err error) bool { <ide> return isErr(err, errNoSuchVolume) <ide> } <ide> <add>// IsNameConflict returns a boolean indicating whether the error indicates that a <add>// volume name is already taken <add>func IsNameConflict(err error) bool { <add> return isErr(err, errNameConflict) <add>} <add> <ide> func isErr(err error, expected error) bool { <ide> switch pe := err.(type) { <ide> case nil: <ide><path>volume/store/store.go <ide> import ( <ide> // reference counting of volumes in the system. <ide> func New() *VolumeStore { <ide> return &VolumeStore{ <del> vols: make(map[string]*volumeCounter), <ide> locks: &locker.Locker{}, <add> names: make(map[string]string), <add> refs: make(map[string][]string), <ide> } <ide> } <ide> <del>func (s *VolumeStore) get(name string) (*volumeCounter, bool) { <add>func (s *VolumeStore) getNamed(name string) (string, bool) { <ide> s.globalLock.Lock() <del> vc, exists := s.vols[name] <add> driverName, exists := s.names[name] <ide> s.globalLock.Unlock() <del> return vc, exists <add> return driverName, exists <ide> } <ide> <del>func (s *VolumeStore) set(name string, vc *volumeCounter) { <add>func (s *VolumeStore) setNamed(name, driver, ref string) { <ide> s.globalLock.Lock() <del> s.vols[name] = vc <add> s.names[name] = driver <add> if len(ref) > 0 { <add> s.refs[name] = append(s.refs[name], ref) <add> } <ide> s.globalLock.Unlock() <ide> } <ide> <del>func (s *VolumeStore) remove(name string) { <add>func (s *VolumeStore) purge(name string) { <ide> s.globalLock.Lock() <del> delete(s.vols, name) <add> delete(s.names, name) <add> delete(s.refs, name) <ide> s.globalLock.Unlock() <ide> } <ide> <ide> // VolumeStore is a struct that stores the list of volumes available and keeps track of their usage counts <ide> type VolumeStore struct { <del> vols map[string]*volumeCounter <ide> locks *locker.Locker <ide> globalLock sync.Mutex <add> // names stores the volume name -> driver name relationship. <add> // This is used for making lookups faster so we don't have to probe all drivers <add> names map[string]string <add> // refs stores the volume name and the list of things referencing it <add> refs map[string][]string <ide> } <ide> <del>// volumeCounter keeps track of references to a volume <del>type volumeCounter struct { <del> volume.Volume <del> count uint <del>} <add>// List proxies to all registered volume drivers to get the full list of volumes <add>// If a driver returns a volume that has name which conflicts with a another volume from a different driver, <add>// the first volume is chosen and the conflicting volume is dropped. <add>func (s *VolumeStore) List() ([]volume.Volume, []string, error) { <add> vols, warnings, err := s.list() <add> if err != nil { <add> return nil, nil, &OpErr{Err: err, Op: "list"} <add> } <add> var out []volume.Volume <ide> <del>// AddAll adds a list of volumes to the store <del>func (s *VolumeStore) AddAll(vols []volume.Volume) { <ide> for _, v := range vols { <del> s.vols[normaliseVolumeName(v.Name())] = &volumeCounter{v, 0} <add> name := normaliseVolumeName(v.Name()) <add> <add> s.locks.Lock(name) <add> driverName, exists := s.getNamed(name) <add> if !exists { <add> s.setNamed(name, v.DriverName(), "") <add> } <add> if exists && driverName != v.DriverName() { <add> logrus.Warnf("Volume name %s already exists for driver %s, not including volume returned by %s", v.Name(), driverName, v.DriverName()) <add> s.locks.Unlock(v.Name()) <add> continue <add> } <add> <add> out = append(out, v) <add> s.locks.Unlock(v.Name()) <ide> } <add> return out, warnings, nil <ide> } <ide> <del>// Create tries to find an existing volume with the given name or create a new one from the passed in driver <del>func (s *VolumeStore) Create(name, driverName string, opts map[string]string) (volume.Volume, error) { <add>// list goes through each volume driver and asks for its list of volumes. <add>func (s *VolumeStore) list() ([]volume.Volume, []string, error) { <add> drivers, err := volumedrivers.GetAllDrivers() <add> if err != nil { <add> return nil, nil, err <add> } <add> var ( <add> ls []volume.Volume <add> warnings []string <add> ) <add> <add> type vols struct { <add> vols []volume.Volume <add> err error <add> } <add> chVols := make(chan vols, len(drivers)) <add> <add> for _, vd := range drivers { <add> go func(d volume.Driver) { <add> vs, err := d.List() <add> if err != nil { <add> chVols <- vols{err: &OpErr{Err: err, Name: d.Name(), Op: "list"}} <add> return <add> } <add> chVols <- vols{vols: vs} <add> }(vd) <add> } <add> <add> for i := 0; i < len(drivers); i++ { <add> vs := <-chVols <add> <add> if vs.err != nil { <add> warnings = append(warnings, vs.err.Error()) <add> logrus.Warn(vs.err) <add> continue <add> } <add> ls = append(ls, vs.vols...) <add> } <add> return ls, warnings, nil <add>} <add> <add>// CreateWithRef creates a volume with the given name and driver and stores the ref <add>// This is just like Create() except we store the reference while holding the lock. <add>// This ensures there's no race between creating a volume and then storing a reference. <add>func (s *VolumeStore) CreateWithRef(name, driverName, ref string, opts map[string]string) (volume.Volume, error) { <ide> name = normaliseVolumeName(name) <ide> s.locks.Lock(name) <ide> defer s.locks.Unlock(name) <ide> <del> if vc, exists := s.get(name); exists { <del> v := vc.Volume <del> return v, nil <add> v, err := s.create(name, driverName, opts) <add> if err != nil { <add> return nil, &OpErr{Err: err, Name: name, Op: "create"} <ide> } <ide> <del> vd, err := volumedrivers.GetDriver(driverName) <add> s.setNamed(name, v.DriverName(), ref) <add> return v, nil <add>} <add> <add>// Create creates a volume with the given name and driver. <add>func (s *VolumeStore) Create(name, driverName string, opts map[string]string) (volume.Volume, error) { <add> name = normaliseVolumeName(name) <add> s.locks.Lock(name) <add> defer s.locks.Unlock(name) <add> <add> v, err := s.create(name, driverName, opts) <ide> if err != nil { <del> return nil, &OpErr{Err: err, Name: driverName, Op: "create"} <add> return nil, &OpErr{Err: err, Name: name, Op: "create"} <ide> } <add> s.setNamed(name, v.DriverName(), "") <add> return v, nil <add>} <ide> <add>// create asks the given driver to create a volume with the name/opts. <add>// If a volume with the name is already known, it will ask the stored driver for the volume. <add>// If the passed in driver name does not match the driver name which is stored for the given volume name, an error is returned. <add>// It is expected that callers of this function hold any neccessary locks. <add>func (s *VolumeStore) create(name, driverName string, opts map[string]string) (volume.Volume, error) { <ide> // Validate the name in a platform-specific manner <ide> valid, err := volume.IsVolumeNameValid(name) <ide> if err != nil { <ide> func (s *VolumeStore) Create(name, driverName string, opts map[string]string) (v <ide> return nil, &OpErr{Err: errInvalidName, Name: name, Op: "create"} <ide> } <ide> <del> v, err := vd.Create(name, opts) <add> vdName, exists := s.getNamed(name) <add> if exists { <add> if vdName != driverName && driverName != "" && driverName != volume.DefaultDriverName { <add> return nil, errNameConflict <add> } <add> driverName = vdName <add> } <add> <add> logrus.Debugf("Registering new volume reference: driver %s, name %s", driverName, name) <add> vd, err := volumedrivers.GetDriver(driverName) <ide> if err != nil { <ide> return nil, &OpErr{Op: "create", Name: name, Err: err} <ide> } <ide> <del> s.set(name, &volumeCounter{v, 0}) <del> return v, nil <add> if v, err := vd.Get(name); err == nil { <add> return v, nil <add> } <add> return vd.Create(name, opts) <ide> } <ide> <del>// Get looks if a volume with the given name exists and returns it if so <del>func (s *VolumeStore) Get(name string) (volume.Volume, error) { <add>// GetWithRef gets a volume with the given name from the passed in driver and stores the ref <add>// This is just like Get(), but we store the reference while holding the lock. <add>// This makes sure there are no races between checking for the existance of a volume and adding a reference for it <add>func (s *VolumeStore) GetWithRef(name, driverName, ref string) (volume.Volume, error) { <ide> name = normaliseVolumeName(name) <ide> s.locks.Lock(name) <ide> defer s.locks.Unlock(name) <ide> <del> vc, exists := s.get(name) <del> if !exists { <del> return nil, &OpErr{Err: errNoSuchVolume, Name: name, Op: "get"} <add> vd, err := volumedrivers.GetDriver(driverName) <add> if err != nil { <add> return nil, &OpErr{Err: err, Name: name, Op: "get"} <add> } <add> <add> v, err := vd.Get(name) <add> if err != nil { <add> return nil, &OpErr{Err: err, Name: name, Op: "get"} <ide> } <del> return vc.Volume, nil <add> <add> s.setNamed(name, v.DriverName(), ref) <add> return v, nil <ide> } <ide> <del>// Remove removes the requested volume. A volume is not removed if the usage count is > 0 <del>func (s *VolumeStore) Remove(v volume.Volume) error { <del> name := normaliseVolumeName(v.Name()) <add>// Get looks if a volume with the given name exists and returns it if so <add>func (s *VolumeStore) Get(name string) (volume.Volume, error) { <add> name = normaliseVolumeName(name) <ide> s.locks.Lock(name) <ide> defer s.locks.Unlock(name) <ide> <del> logrus.Debugf("Removing volume reference: driver %s, name %s", v.DriverName(), name) <del> vc, exists := s.get(name) <del> if !exists { <del> return &OpErr{Err: errNoSuchVolume, Name: name, Op: "remove"} <add> v, err := s.getVolume(name) <add> if err != nil { <add> return nil, &OpErr{Err: err, Name: name, Op: "get"} <ide> } <add> return v, nil <add>} <ide> <del> if vc.count > 0 { <del> return &OpErr{Err: errVolumeInUse, Name: name, Op: "remove"} <add>// get requests the volume, if the driver info is stored it just access that driver, <add>// if the driver is unknown it probes all drivers until it finds the first volume with that name. <add>// it is expected that callers of this function hold any neccessary locks <add>func (s *VolumeStore) getVolume(name string) (volume.Volume, error) { <add> logrus.Debugf("Getting volume reference for name: %s", name) <add> if vdName, exists := s.names[name]; exists { <add> vd, err := volumedrivers.GetDriver(vdName) <add> if err != nil { <add> return nil, err <add> } <add> return vd.Get(name) <ide> } <ide> <del> vd, err := volumedrivers.GetDriver(vc.DriverName()) <add> logrus.Debugf("Probing all drivers for volume with name: %s", name) <add> drivers, err := volumedrivers.GetAllDrivers() <ide> if err != nil { <del> return &OpErr{Err: err, Name: vc.DriverName(), Op: "remove"} <del> } <del> if err := vd.Remove(vc.Volume); err != nil { <del> return &OpErr{Err: err, Name: name, Op: "remove"} <add> return nil, err <ide> } <ide> <del> s.remove(name) <del> return nil <add> for _, d := range drivers { <add> v, err := d.Get(name) <add> if err != nil { <add> continue <add> } <add> return v, nil <add> } <add> return nil, errNoSuchVolume <ide> } <ide> <del>// Increment increments the usage count of the passed in volume by 1 <del>func (s *VolumeStore) Increment(v volume.Volume) { <add>// Remove removes the requested volume. A volume is not removed if it has any refs <add>func (s *VolumeStore) Remove(v volume.Volume) error { <ide> name := normaliseVolumeName(v.Name()) <ide> s.locks.Lock(name) <ide> defer s.locks.Unlock(name) <ide> <del> logrus.Debugf("Incrementing volume reference: driver %s, name %s", v.DriverName(), v.Name()) <del> vc, exists := s.get(name) <del> if !exists { <del> s.set(name, &volumeCounter{v, 1}) <del> return <add> if refs, exists := s.refs[name]; exists && len(refs) > 0 { <add> return &OpErr{Err: errVolumeInUse, Name: v.Name(), Op: "remove", Refs: refs} <ide> } <del> vc.count++ <del>} <ide> <del>// Decrement decrements the usage count of the passed in volume by 1 <del>func (s *VolumeStore) Decrement(v volume.Volume) { <del> name := normaliseVolumeName(v.Name()) <del> s.locks.Lock(name) <del> defer s.locks.Unlock(name) <del> logrus.Debugf("Decrementing volume reference: driver %s, name %s", v.DriverName(), v.Name()) <del> <del> vc, exists := s.get(name) <del> if !exists { <del> return <add> vd, err := volumedrivers.GetDriver(v.DriverName()) <add> if err != nil { <add> return &OpErr{Err: err, Name: vd.Name(), Op: "remove"} <ide> } <del> if vc.count == 0 { <del> return <add> <add> logrus.Debugf("Removing volume reference: driver %s, name %s", v.DriverName(), name) <add> if err := vd.Remove(v); err != nil { <add> return &OpErr{Err: err, Name: name, Op: "remove"} <ide> } <del> vc.count-- <add> <add> s.purge(name) <add> return nil <ide> } <ide> <del>// Count returns the usage count of the passed in volume <del>func (s *VolumeStore) Count(v volume.Volume) uint { <del> name := normaliseVolumeName(v.Name()) <del> s.locks.Lock(name) <del> defer s.locks.Unlock(name) <add>// Dereference removes the specified reference to the volume <add>func (s *VolumeStore) Dereference(v volume.Volume, ref string) { <add> s.locks.Lock(v.Name()) <add> defer s.locks.Unlock(v.Name()) <ide> <del> vc, exists := s.get(name) <add> s.globalLock.Lock() <add> refs, exists := s.refs[v.Name()] <ide> if !exists { <del> return 0 <add> return <ide> } <del> return vc.count <del>} <ide> <del>// List returns all the available volumes <del>func (s *VolumeStore) List() []volume.Volume { <del> s.globalLock.Lock() <del> defer s.globalLock.Unlock() <del> var ls []volume.Volume <del> for _, vc := range s.vols { <del> ls = append(ls, vc.Volume) <add> for i, r := range refs { <add> if r == ref { <add> s.refs[v.Name()] = append(s.refs[v.Name()][:i], s.refs[v.Name()][i+1:]...) <add> } <ide> } <del> return ls <add> s.globalLock.Unlock() <ide> } <ide> <ide> // FilterByDriver returns the available volumes filtered by driver name <del>func (s *VolumeStore) FilterByDriver(name string) []volume.Volume { <del> return s.filter(byDriver(name)) <add>func (s *VolumeStore) FilterByDriver(name string) ([]volume.Volume, error) { <add> vd, err := volumedrivers.GetDriver(name) <add> if err != nil { <add> return nil, &OpErr{Err: err, Name: name, Op: "list"} <add> } <add> ls, err := vd.List() <add> if err != nil { <add> return nil, &OpErr{Err: err, Name: name, Op: "list"} <add> } <add> return ls, nil <add>} <add> <add>// FilterByUsed returns the available volumes filtered by if they are not in use <add>func (s *VolumeStore) FilterByUsed(vols []volume.Volume) []volume.Volume { <add> return s.filter(vols, func(v volume.Volume) bool { <add> s.locks.Lock(v.Name()) <add> defer s.locks.Unlock(v.Name()) <add> return len(s.refs[v.Name()]) == 0 <add> }) <ide> } <ide> <ide> // filterFunc defines a function to allow filter volumes in the store <ide> type filterFunc func(vol volume.Volume) bool <ide> <del>// byDriver generates a filterFunc to filter volumes by their driver name <del>func byDriver(name string) filterFunc { <del> return func(vol volume.Volume) bool { <del> return vol.DriverName() == name <del> } <del>} <del> <ide> // filter returns the available volumes filtered by a filterFunc function <del>func (s *VolumeStore) filter(f filterFunc) []volume.Volume { <del> s.globalLock.Lock() <del> defer s.globalLock.Unlock() <add>func (s *VolumeStore) filter(vols []volume.Volume, f filterFunc) []volume.Volume { <ide> var ls []volume.Volume <del> for _, vc := range s.vols { <del> if f(vc.Volume) { <del> ls = append(ls, vc.Volume) <add> for _, v := range vols { <add> if f(v) { <add> ls = append(ls, v) <ide> } <ide> } <ide> return ls <ide><path>volume/store/store_test.go <ide> package store <ide> <ide> import ( <ide> "errors" <add> "strings" <ide> "testing" <ide> <del> "github.com/docker/docker/volume" <ide> "github.com/docker/docker/volume/drivers" <ide> vt "github.com/docker/docker/volume/testutils" <ide> ) <ide> <del>func TestList(t *testing.T) { <del> volumedrivers.Register(vt.FakeDriver{}, "fake") <del> s := New() <del> s.AddAll([]volume.Volume{vt.NewFakeVolume("fake1"), vt.NewFakeVolume("fake2")}) <del> l := s.List() <del> if len(l) != 2 { <del> t.Fatalf("Expected 2 volumes in the store, got %v: %v", len(l), l) <del> } <del>} <del> <del>func TestGet(t *testing.T) { <del> volumedrivers.Register(vt.FakeDriver{}, "fake") <del> s := New() <del> s.AddAll([]volume.Volume{vt.NewFakeVolume("fake1"), vt.NewFakeVolume("fake2")}) <del> v, err := s.Get("fake1") <del> if err != nil { <del> t.Fatal(err) <del> } <del> if v.Name() != "fake1" { <del> t.Fatalf("Expected fake1 volume, got %v", v) <del> } <del> <del> if _, err := s.Get("fake4"); !IsNotExist(err) { <del> t.Fatalf("Expected IsNotExist error, got %v", err) <del> } <del>} <del> <ide> func TestCreate(t *testing.T) { <del> volumedrivers.Register(vt.FakeDriver{}, "fake") <add> volumedrivers.Register(vt.NewFakeDriver("fake"), "fake") <add> defer volumedrivers.Unregister("fake") <ide> s := New() <ide> v, err := s.Create("fake1", "fake", nil) <ide> if err != nil { <ide> func TestCreate(t *testing.T) { <ide> if v.Name() != "fake1" { <ide> t.Fatalf("Expected fake1 volume, got %v", v) <ide> } <del> if l := s.List(); len(l) != 1 { <add> if l, _, _ := s.List(); len(l) != 1 { <ide> t.Fatalf("Expected 1 volume in the store, got %v: %v", len(l), l) <ide> } <ide> <ide> func TestCreate(t *testing.T) { <ide> } <ide> <ide> func TestRemove(t *testing.T) { <del> volumedrivers.Register(vt.FakeDriver{}, "fake") <add> volumedrivers.Register(vt.NewFakeDriver("fake"), "fake") <add> volumedrivers.Register(vt.NewFakeDriver("noop"), "noop") <add> defer volumedrivers.Unregister("fake") <add> defer volumedrivers.Unregister("noop") <ide> s := New() <del> if err := s.Remove(vt.NoopVolume{}); !IsNotExist(err) { <del> t.Fatalf("Expected IsNotExist error, got %v", err) <add> <add> // doing string compare here since this error comes directly from the driver <add> expected := "no such volume" <add> if err := s.Remove(vt.NoopVolume{}); err == nil || !strings.Contains(err.Error(), expected) { <add> t.Fatalf("Expected error %q, got %v", expected, err) <ide> } <del> v, err := s.Create("fake1", "fake", nil) <add> <add> v, err := s.CreateWithRef("fake1", "fake", "fake", nil) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> s.Increment(v) <add> <ide> if err := s.Remove(v); !IsInUse(err) { <del> t.Fatalf("Expected IsInUse error, got %v", err) <add> t.Fatalf("Expected ErrVolumeInUse error, got %v", err) <ide> } <del> s.Decrement(v) <add> s.Dereference(v, "fake") <ide> if err := s.Remove(v); err != nil { <ide> t.Fatal(err) <ide> } <del> if l := s.List(); len(l) != 0 { <add> if l, _, _ := s.List(); len(l) != 0 { <ide> t.Fatalf("Expected 0 volumes in the store, got %v, %v", len(l), l) <ide> } <ide> } <ide> <del>func TestIncrement(t *testing.T) { <add>func TestList(t *testing.T) { <add> volumedrivers.Register(vt.NewFakeDriver("fake"), "fake") <add> volumedrivers.Register(vt.NewFakeDriver("fake2"), "fake2") <add> defer volumedrivers.Unregister("fake") <add> defer volumedrivers.Unregister("fake2") <add> <ide> s := New() <del> v := vt.NewFakeVolume("fake1") <del> s.Increment(v) <del> if l := s.List(); len(l) != 1 { <del> t.Fatalf("Expected 1 volume, got %v, %v", len(l), l) <add> if _, err := s.Create("test", "fake", nil); err != nil { <add> t.Fatal(err) <ide> } <del> if c := s.Count(v); c != 1 { <del> t.Fatalf("Expected 1 counter, got %v", c) <add> if _, err := s.Create("test2", "fake2", nil); err != nil { <add> t.Fatal(err) <ide> } <ide> <del> s.Increment(v) <del> if l := s.List(); len(l) != 1 { <del> t.Fatalf("Expected 1 volume, got %v, %v", len(l), l) <add> ls, _, err := s.List() <add> if err != nil { <add> t.Fatal(err) <ide> } <del> if c := s.Count(v); c != 2 { <del> t.Fatalf("Expected 2 counter, got %v", c) <add> if len(ls) != 2 { <add> t.Fatalf("expected 2 volumes, got: %d", len(ls)) <ide> } <ide> <del> v2 := vt.NewFakeVolume("fake2") <del> s.Increment(v2) <del> if l := s.List(); len(l) != 2 { <del> t.Fatalf("Expected 2 volume, got %v, %v", len(l), l) <add> // and again with a new store <add> s = New() <add> ls, _, err = s.List() <add> if err != nil { <add> t.Fatal(err) <add> } <add> if len(ls) != 2 { <add> t.Fatalf("expected 2 volumes, got: %d", len(ls)) <ide> } <ide> } <ide> <del>func TestDecrement(t *testing.T) { <add>func TestFilterByDriver(t *testing.T) { <add> volumedrivers.Register(vt.NewFakeDriver("fake"), "fake") <add> volumedrivers.Register(vt.NewFakeDriver("noop"), "noop") <add> defer volumedrivers.Unregister("fake") <add> defer volumedrivers.Unregister("noop") <ide> s := New() <del> v := vt.NoopVolume{} <del> s.Decrement(v) <del> if c := s.Count(v); c != 0 { <del> t.Fatalf("Expected 0 volumes, got %v", c) <del> } <ide> <del> s.Increment(v) <del> s.Increment(v) <del> s.Decrement(v) <del> if c := s.Count(v); c != 1 { <del> t.Fatalf("Expected 1 volume, got %v", c) <add> if _, err := s.Create("fake1", "fake", nil); err != nil { <add> t.Fatal(err) <ide> } <del> <del> s.Decrement(v) <del> if c := s.Count(v); c != 0 { <del> t.Fatalf("Expected 0 volumes, got %v", c) <add> if _, err := s.Create("fake2", "fake", nil); err != nil { <add> t.Fatal(err) <ide> } <del> <del> // Test counter cannot be negative. <del> s.Decrement(v) <del> if c := s.Count(v); c != 0 { <del> t.Fatalf("Expected 0 volumes, got %v", c) <add> if _, err := s.Create("fake3", "noop", nil); err != nil { <add> t.Fatal(err) <ide> } <del>} <del> <del>func TestFilterByDriver(t *testing.T) { <del> s := New() <del> <del> s.Increment(vt.NewFakeVolume("fake1")) <del> s.Increment(vt.NewFakeVolume("fake2")) <del> s.Increment(vt.NoopVolume{}) <ide> <del> if l := s.FilterByDriver("fake"); len(l) != 2 { <add> if l, _ := s.FilterByDriver("fake"); len(l) != 2 { <ide> t.Fatalf("Expected 2 volumes, got %v, %v", len(l), l) <ide> } <ide> <del> if l := s.FilterByDriver("noop"); len(l) != 1 { <add> if l, _ := s.FilterByDriver("noop"); len(l) != 1 { <ide> t.Fatalf("Expected 1 volume, got %v, %v", len(l), l) <ide> } <ide> } <ide><path>volume/testutils/testutils.go <ide> func (FakeVolume) Mount() (string, error) { return "fake", nil } <ide> func (FakeVolume) Unmount() error { return nil } <ide> <ide> // FakeDriver is a driver that generates fake volumes <del>type FakeDriver struct{} <add>type FakeDriver struct { <add> name string <add> vols map[string]volume.Volume <add>} <add> <add>// NewFakeDriver creates a new FakeDriver with the specified name <add>func NewFakeDriver(name string) volume.Driver { <add> return &FakeDriver{ <add> name: name, <add> vols: make(map[string]volume.Volume), <add> } <add>} <ide> <ide> // Name is the name of the driver <del>func (FakeDriver) Name() string { return "fake" } <add>func (d *FakeDriver) Name() string { return d.name } <ide> <ide> // Create initializes a fake volume. <ide> // It returns an error if the options include an "error" key with a message <del>func (FakeDriver) Create(name string, opts map[string]string) (volume.Volume, error) { <add>func (d *FakeDriver) Create(name string, opts map[string]string) (volume.Volume, error) { <ide> if opts != nil && opts["error"] != "" { <ide> return nil, fmt.Errorf(opts["error"]) <ide> } <del> return NewFakeVolume(name), nil <add> v := NewFakeVolume(name) <add> d.vols[name] = v <add> return v, nil <ide> } <ide> <ide> // Remove deletes a volume. <del>func (FakeDriver) Remove(v volume.Volume) error { return nil } <add>func (d *FakeDriver) Remove(v volume.Volume) error { <add> if _, exists := d.vols[v.Name()]; !exists { <add> return fmt.Errorf("no such volume") <add> } <add> delete(d.vols, v.Name()) <add> return nil <add>} <add> <add>// List lists the volumes <add>func (d *FakeDriver) List() ([]volume.Volume, error) { <add> var vols []volume.Volume <add> for _, v := range d.vols { <add> vols = append(vols, v) <add> } <add> return vols, nil <add>} <add> <add>// Get gets the volume <add>func (d *FakeDriver) Get(name string) (volume.Volume, error) { <add> if v, exists := d.vols[name]; exists { <add> return v, nil <add> } <add> return nil, fmt.Errorf("no such volume") <add>} <ide><path>volume/volume.go <ide> type Driver interface { <ide> // Create makes a new volume with the given id. <ide> Create(name string, opts map[string]string) (Volume, error) <ide> // Remove deletes the volume. <del> Remove(Volume) error <add> Remove(vol Volume) (err error) <add> // List lists all the volumes the driver has <add> List() ([]Volume, error) <add> // Get retreives the volume with the requested name <add> Get(name string) (Volume, error) <ide> } <ide> <ide> // Volume is a place to store data. It is backed by a specific driver, and can be mounted.
30
Text
Text
put the needed import in one example
a5506610ad7b497dadbab1ccde471b3d13c614ff
<ide><path>docs/api-guide/versioning.md <ide> How you vary the API behavior is up to you, but one example you might typically <ide> <ide> The `reverse` function included by REST framework ties in with the versioning scheme. You need to make sure to include the current `request` as a keyword argument, like so. <ide> <add> from rest_framework.reverse import reverse <add> <ide> reverse('bookings-list', request=request) <ide> <ide> The above function will apply any URL transformations appropriate to the request version. For example:
1
Text
Text
remove an extra period
fe077b50c9ce65c4ac1cc718c34dda45cd24c6fe
<ide><path>guides/source/api_documentation_guidelines.md <ide> Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite databa <ide> English <ide> ------- <ide> <del>Please use American English (<em>color</em>, <em>center</em>, <em>modularize</em>, etc).. See [a list of American and British English spelling differences here](http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences). <add>Please use American English (<em>color</em>, <em>center</em>, <em>modularize</em>, etc). See [a list of American and British English spelling differences here](http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences). <ide> <ide> Example Code <ide> ------------
1
Text
Text
use correct filename in example
6707819986796cbfeaafb7ac31e6f12cd3735b1e
<ide><path>README.md <ide> This is a web notification channel that allows you to trigger client-side web no <ide> streams: <ide> <ide> ```ruby <del># app/channels/web_notifications.rb <add># app/channels/web_notifications_channel.rb <ide> class WebNotificationsChannel < ApplicationCable::Channel <ide> def subscribed <ide> stream_from "web_notifications_#{current_user.id}"
1
Python
Python
add a test for activity regulrisation
cf49d59aff3766c2cf78d17a78e2b821db902228
<ide><path>test/test_activity_reg.py <add>__author__ = 'mccolgan' <add> <add> <add>from keras.datasets import mnist <add>from keras.models import Sequential <add>from keras.layers.convolutional import Convolution2D <add>from keras.layers.core import Dense, Flatten, ActivityRegularization <add>from keras.utils import np_utils <add>from keras.regularizers import l2, activity_l1 <add> <add>import numpy as np <add> <add>np.random.seed(1337) <add> <add>max_train_samples = 128*8 <add>max_test_samples = 1000 <add> <add>(X_train, y_train), (X_test, y_test) = mnist.load_data() <add> <add>X_train = X_train.reshape((-1,28*28)) <add>X_test = X_test.reshape((-1,28*28)) <add> <add>nb_classes = len(np.unique(y_train)) <add>Y_train = np_utils.to_categorical(y_train, nb_classes)[:max_train_samples] <add>Y_test = np_utils.to_categorical(y_test, nb_classes)[:max_test_samples] <add> <add>model_noreg = Sequential() <add>model_noreg.add(Flatten()) <add>model_noreg.add(Dense(28*28, 20, activation='sigmoid')) <add>model_noreg.add(Dense(20, 10, activation='sigmoid')) <add> <add>model_noreg.compile(loss='categorical_crossentropy', optimizer='rmsprop') <add>model_noreg.fit(X_train, Y_train) <add> <add>score_noreg = model_noreg.evaluate(X_test, Y_test) <add>score_train_noreg = model_noreg.evaluate(X_train, Y_train) <add> <add>model_reg = Sequential() <add>model_reg.add(Flatten()) <add>model_reg.add(Dense(28*28, 20, activation='sigmoid')) <add>model_reg.add(ActivityRegularization(activity_l1(0.015))) <add>model_reg.add(Dense(20, 10, activation='sigmoid')) <add> <add>model_reg.compile(loss='categorical_crossentropy', optimizer='rmsprop') <add>model_reg.fit(X_train, Y_train) <add> <add>score_reg = model_reg.evaluate(X_test, Y_test) <add>score_train_reg = model_reg.evaluate(X_train, Y_train) <add> <add>print <add>print <add>print "Overfitting without regularisation: %f - %f = %f" % ( score_noreg , score_train_noreg , score_noreg-score_train_noreg) <add>print "Overfitting with regularisation: %f - %f = %f" % ( score_reg , score_train_reg , score_reg-score_train_reg)
1
Ruby
Ruby
improve test coverage for `#in` and `#not_in`
fefac0178c2d4815a2ceeebc2b7c4fea9ab6ed46
<ide><path>test/attributes/test_attribute.rb <ide> module Attributes <ide> end <ide> <ide> describe '#in' do <add> it 'can be constructed with a subquery' do <add> relation = Table.new(:users) <add> mgr = relation.project relation[:id] <add> mgr.where relation[:name].does_not_match_all(['%chunky%','%bacon%']) <add> attribute = Attribute.new nil, nil <add> <add> node = attribute.in(mgr) <add> <add> node.must_equal Nodes::In.new(attribute, mgr.ast) <add> end <add> <add> describe 'with a range' do <add> it 'can be constructed with a standard range' do <add> attribute = Attribute.new nil, nil <add> node = attribute.in(1..3) <add> <add> node.must_equal Nodes::Between.new( <add> attribute, <add> Nodes::And.new([ <add> Nodes::Casted.new(1, attribute), <add> Nodes::Casted.new(3, attribute) <add> ]) <add> ) <add> end <add> <add> it 'can be constructed with a range starting from -Infinity' do <add> attribute = Attribute.new nil, nil <add> node = attribute.in(-::Float::INFINITY..3) <add> <add> node.must_equal Nodes::LessThanOrEqual.new( <add> attribute, <add> Nodes::Casted.new(3, attribute) <add> ) <add> end <add> <add> it 'can be constructed with an exclusive range starting from -Infinity' do <add> attribute = Attribute.new nil, nil <add> node = attribute.in(-::Float::INFINITY...3) <add> <add> node.must_equal Nodes::LessThan.new( <add> attribute, <add> Nodes::Casted.new(3, attribute) <add> ) <add> end <add> <add> it 'can be constructed with an infinite range' do <add> attribute = Attribute.new nil, nil <add> node = attribute.in(-::Float::INFINITY..::Float::INFINITY) <add> <add> node.must_equal Nodes::NotIn.new(attribute, []) <add> end <add> <add> it 'can be constructed with a range ending at Infinity' do <add> attribute = Attribute.new nil, nil <add> node = attribute.in(0..::Float::INFINITY) <add> <add> node.must_equal Nodes::GreaterThanOrEqual.new( <add> attribute, <add> Nodes::Casted.new(0, attribute) <add> ) <add> end <add> <add> it 'can be constructed with an exclusive range' do <add> attribute = Attribute.new nil, nil <add> node = attribute.in(0...3) <add> <add> node.must_equal Nodes::And.new([ <add> Nodes::GreaterThanOrEqual.new( <add> attribute, <add> Nodes::Casted.new(0, attribute) <add> ), <add> Nodes::LessThan.new( <add> attribute, <add> Nodes::Casted.new(3, attribute) <add> ) <add> ]) <add> end <add> end <add> <ide> it 'can be constructed with a list' do <add> attribute = Attribute.new nil, nil <add> node = attribute.in([1, 2, 3]) <add> <add> node.must_equal Nodes::In.new( <add> attribute, <add> [ <add> Nodes::Casted.new(1, attribute), <add> Nodes::Casted.new(2, attribute), <add> Nodes::Casted.new(3, attribute), <add> ] <add> ) <ide> end <ide> <del> it 'should return an in node' do <add> it 'can be constructed with a random object' do <ide> attribute = Attribute.new nil, nil <del> node = Nodes::In.new attribute, [1,2,3] <del> node.left.must_equal attribute <del> node.right.must_equal [1, 2, 3] <add> random_object = Object.new <add> node = attribute.in(random_object) <add> <add> node.must_equal Nodes::In.new( <add> attribute, <add> Nodes::Casted.new(random_object, attribute) <add> ) <ide> end <ide> <ide> it 'should generate IN in sql' do <ide> module Attributes <ide> end <ide> <ide> describe '#not_in' do <add> it 'can be constructed with a subquery' do <add> relation = Table.new(:users) <add> mgr = relation.project relation[:id] <add> mgr.where relation[:name].does_not_match_all(['%chunky%','%bacon%']) <add> attribute = Attribute.new nil, nil <ide> <del> it 'should return a NotIn node' do <add> node = attribute.not_in(mgr) <add> <add> node.must_equal Nodes::NotIn.new(attribute, mgr.ast) <add> end <add> <add> describe 'with a range' do <add> it 'can be constructed with a standard range' do <add> attribute = Attribute.new nil, nil <add> node = attribute.not_in(1..3) <add> <add> node.must_equal Nodes::Or.new( <add> Nodes::LessThan.new( <add> attribute, <add> Nodes::Casted.new(1, attribute) <add> ), <add> Nodes::GreaterThan.new( <add> attribute, <add> Nodes::Casted.new(3, attribute) <add> ) <add> ) <add> end <add> <add> it 'can be constructed with a range starting from -Infinity' do <add> attribute = Attribute.new nil, nil <add> node = attribute.not_in(-::Float::INFINITY..3) <add> <add> node.must_equal Nodes::GreaterThan.new( <add> attribute, <add> Nodes::Casted.new(3, attribute) <add> ) <add> end <add> <add> it 'can be constructed with an exclusive range starting from -Infinity' do <add> attribute = Attribute.new nil, nil <add> node = attribute.not_in(-::Float::INFINITY...3) <add> <add> node.must_equal Nodes::GreaterThanOrEqual.new( <add> attribute, <add> Nodes::Casted.new(3, attribute) <add> ) <add> end <add> <add> it 'can be constructed with an infinite range' do <add> attribute = Attribute.new nil, nil <add> node = attribute.not_in(-::Float::INFINITY..::Float::INFINITY) <add> <add> node.must_equal Nodes::In.new(attribute, []) <add> end <add> <add> it 'can be constructed with a range ending at Infinity' do <add> attribute = Attribute.new nil, nil <add> node = attribute.not_in(0..::Float::INFINITY) <add> <add> node.must_equal Nodes::LessThan.new( <add> attribute, <add> Nodes::Casted.new(0, attribute) <add> ) <add> end <add> <add> it 'can be constructed with an exclusive range' do <add> attribute = Attribute.new nil, nil <add> node = attribute.not_in(0...3) <add> <add> node.must_equal Nodes::Or.new( <add> Nodes::LessThan.new( <add> attribute, <add> Nodes::Casted.new(0, attribute) <add> ), <add> Nodes::GreaterThanOrEqual.new( <add> attribute, <add> Nodes::Casted.new(3, attribute) <add> ) <add> ) <add> end <add> end <add> <add> it 'can be constructed with a list' do <ide> attribute = Attribute.new nil, nil <del> node = Nodes::NotIn.new attribute, [1,2,3] <del> node.left.must_equal attribute <del> node.right.must_equal [1, 2, 3] <add> node = attribute.not_in([1, 2, 3]) <add> <add> node.must_equal Nodes::NotIn.new( <add> attribute, <add> [ <add> Nodes::Casted.new(1, attribute), <add> Nodes::Casted.new(2, attribute), <add> Nodes::Casted.new(3, attribute), <add> ] <add> ) <add> end <add> <add> it 'can be constructed with a random object' do <add> attribute = Attribute.new nil, nil <add> random_object = Object.new <add> node = attribute.not_in(random_object) <add> <add> node.must_equal Nodes::NotIn.new( <add> attribute, <add> Nodes::Casted.new(random_object, attribute) <add> ) <ide> end <ide> <ide> it 'should generate NOT IN in sql' do
1
Python
Python
add get_cosine util function
bd20ec0a6adc8a8c267ee316815d727981c04fcb
<ide><path>spacy/tests/util.py <ide> from ..tokens import Doc <ide> from ..attrs import ORTH, POS, HEAD, DEP <ide> <add>import numpy <add> <ide> <ide> def get_doc(vocab, words=[], pos=None, heads=None, deps=None, tags=None, ents=None): <ide> """Create Doc object from given vocab, words and annotations.""" <ide> def apply_transition_sequence(parser, doc, sequence): <ide> with parser.step_through(doc) as stepwise: <ide> for transition in sequence: <ide> stepwise.transition(transition) <add> <add> <add>def get_cosine(vec1, vec2): <add> """Get cosine for two given vectors""" <add> return numpy.dot(vec1, vec2) / (numpy.linalg.norm(vec1) * numpy.linalg.norm(vec2))
1
Javascript
Javascript
add abort test for backtrace validation
64edd064b880ff8ce3bcc85d68e0100c8d987fa0
<ide><path>test/abort/test-abort-backtrace.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const cp = require('child_process'); <add> <add>if (common.isWindows) { <add> common.skip('Backtraces unimplemented on Windows.'); <add> return; <add>} <add> <add>if (process.argv[2] === 'child') { <add> process.abort(); <add>} else { <add> const child = cp.spawnSync(`${process.execPath}`, [`${__filename}`, 'child']); <add> const frames = <add> child.stderr.toString().trimRight().split('\n').map((s) => s.trim()); <add> <add> assert.strictEqual(child.stdout.toString(), ''); <add> assert.ok(frames.length > 0); <add> // All frames should start with a frame number. <add> assert.ok(frames.every((frame, index) => frame.startsWith(`${index + 1}:`))); <add> // At least some of the frames should include the binary name. <add> assert.ok(frames.some((frame) => frame.includes(`[${process.execPath}]`))); <add>}
1
Text
Text
translate tips 05..10
0b3fe6f47ec11b2e0e2c9b36b8e30ba55a01fb4e
<ide><path>docs/tips/05-maximum-number-of-jsx-root-nodes.ko-KR.md <add>--- <add>id: maximum-number-of-jsx-root-nodes-ko-KR <add>title: JSX 루트 노드의 최대 갯수 <add>layout: tips <add>permalink: maximum-number-of-jsx-root-nodes-ko-KR.html <add>prev: self-closing-tag-ko-KR.html <add>next: style-props-value-px-ko-KR.html <add>--- <add> <add>현재 컴포넌트의 `render`는 한 노드만 리턴할 수 있습니다. 만약 `div` 배열을 리턴하려면, `div`, `span`과 같은 다른 컴포넌트로 한 번 더 싸주어야 합니다. <add> <add>JSX는 일반 JS로 컴파일 함을 잊지말아야 합니다. 두개의 함수를 리턴하는 것은 문법적으로 맞지 않습니다. 이와 마찬가지로, 한 삼항 연산자 안에 한개 이상의 자식 컴포넌트를 넣으면 안됩니다. <ide>\ No newline at end of file <ide><path>docs/tips/06-style-props-value-px.ko-KR.md <add>--- <add>id: style-props-value-px-ko-KR <add>title: 스타일 속성에서 특정 픽셀 값 넣는 간단한 방법 <add>layout: tips <add>permalink: style-props-value-px-ko-KR.html <add>prev: maximum-number-of-jsx-root-nodes-ko-KR.html <add>next: children-props-type-ko-KR.html <add>--- <add> <add>인라인 `style` prop에서 픽셀 값을 넣을때, React가 자동으로 숫자뒤에 "px"를 붙여줍니다. 다음과 같이 동작합니다: <add> <add>```js <add>var divStyle = {height: 10}; // "height:10px" 로 렌더링 됩니다. <add>React.render(<div style={divStyle}>Hello World!</div>, mountNode); <add>``` <add> <add>더 자세한 이야기는 [Inline Styles](/react/tips/inline-styles-ko-KR.html)를 참고해 주시기 바랍니다. <add> <add>개발 하다보면 CSS 속성들이 단위 없이 그대로 유지되어야 할 때가 있을 겁니다. 아래의 프로퍼티들은 자동으로 "px"가 붙지 않는 속성 리스트 입니다: <add> <add>- `columnCount` <add>- `fillOpacity` <add>- `flex` <add>- `flexGrow` <add>- `flexShrink` <add>- `fontWeight` <add>- `lineClamp` <add>- `lineHeight` <add>- `opacity` <add>- `order` <add>- `orphans` <add>- `strokeOpacity` <add>- `widows` <add>- `zIndex` <add>- `zoom` <ide><path>docs/tips/07-children-props-type.ko-KR.md <add>--- <add>id: children-props-type-ko-KR <add>title: 자식 속성들의 타입 <add>layout: tips <add>permalink: children-props-type-ko-KR.html <add>prev: style-props-value-px-ko-KR.html <add>next: controlled-input-null-value-ko-KR.html <add>--- <add> <add>컴포넌트의 자식들(`this.props.children`)은 대부분 컴포넌트의 배열로 들어갑니다: <add> <add>```js <add>var GenericWrapper = React.createClass({ <add> componentDidMount: function() { <add> console.log(Array.isArray(this.props.children)); // => true <add> }, <add> <add> render: function() { <add> return <div />; <add> } <add>}); <add> <add>React.render( <add> <GenericWrapper><span/><span/><span/></GenericWrapper>, <add> mountNode <add>); <add>``` <add> <add>하지만 자식이 하나만 있는 경우, `this.props.children`는 _배열 래퍼(wrapper)없이_ 싱글 자식 컴포넌트가 됩니다. 이렇게 함으로써 배열 할당을 줄일 수 있습니다. <add> <add>```js <add>var GenericWrapper = React.createClass({ <add> componentDidMount: function() { <add> console.log(Array.isArray(this.props.children)); // => false <add> <add> // 경고 : 산출된 5 값은 'hello' 스트링의 길이 입니다. 존재하지 않는 배열 래퍼의 길이인 1이 아닙니다! <add> <add> console.log(this.props.children.length); <add> }, <add> <add> render: function() { <add> return <div />; <add> } <add>}); <add> <add>React.render(<GenericWrapper>hello</GenericWrapper>, mountNode); <add>``` <add> <add>`this.props.children`을 쉽게 다룰 수 있도록 [React.Children utilities](/react/docs/top-level-api-ko-KR.html#react.children)를 제공하고 있습니다. <ide><path>docs/tips/08-controlled-input-null-value.ko-KR.md <add>--- <add>id: controlled-input-null-value-ko-KR <add>title: 제어되는 input 내의 null 값 <add>layout: tips <add>permalink: controlled-input-null-value-ko-KR.html <add>prev: children-props-type-ko-KR.html <add>next: componentWillReceiveProps-not-triggered-after-mounting-ko-KR.html <add>--- <add> <add>[제어되는 컴포넌트들](/react/docs/forms-ko-KR.html)의 `value` 속성 값을 지정하면 유저에 의해 입력값을 바꿀 수 없습니다. <add> <add>`value`가 정해져 있는데도 입력값을 변경할 수 있는 문제를 겪고 있다면 실수로 `value`를 `undefined`나 `null`로 설정한 것일 수 있습니다. <add> <add>아래 짧은 예제가 있습니다; 렌더링 후, 잠시 뒤에 텍스트를 고칠 수 있는 상태가 되는 것을 확인 하실 수 있습니다. <add> <add>```js <add>React.render(<input value="hi" />, mountNode); <add> <add>setTimeout(function() { <add> React.render(<input value={null} />, mountNode); <add>}, 1000); <add>``` <ide><path>docs/tips/09-componentWillReceiveProps-not-triggered-after-mounting.ko-KR.md <add>--- <add>id: componentWillReceiveProps-not-triggered-after-mounting-ko-KR <add>title: 마운트 후에는 componentWillReceiveProps가 실행되지 않음. <add>layout: tips <add>permalink: componentWillReceiveProps-not-triggered-after-mounting-ko-KR.html <add>prev: controlled-input-null-value-ko-KR.html <add>next: props-in-getInitialState-as-anti-pattern-ko-KR.html <add>--- <add> <add>`componentWillReceiveProps`는 노드가 더해진 후엔 실행되지 않습니다. 이는 설계에 의한 것입니다. [다른 생명주기 메소드](/react/docs/component-specs-ko-KR.html)에서 요구사항에 적합한 것을 찾아보세요. <add> <add>이러한 이유는 `componentWillReceiveProps`에 종종 예전 props와 액션의 차이를 비교하는 로직이 들어가기 때문입니다. 마운트할 때 트리거되지 않으면, (예전 props가 없다고 해도) 메소드의 형태를 구별하는 데 도움이 됩니다. <add> <ide><path>docs/tips/10-props-in-getInitialState-as-anti-pattern.ko-KR.md <add>--- <add>id: props-in-getInitialState-as-anti-pattern-ko-KR <add>title: getInitialState의 Props는 안티패턴 <add>layout: tips <add>permalink: props-in-getInitialState-as-anti-pattern-ko-KR.html <add>prev: componentWillReceiveProps-not-triggered-after-mounting-ko-KR.html <add>next: dom-event-listeners-ko-KR.html <add>--- <add> <add>> 주의 : <add>> <add>> 이것은 React에만 국한된 팁이 아니고 안티패턴은 평범한 코드 속 에서도 종종 발생합니다. 이 글에서는 React로 간단하게 설명해 보겠습니다. <add> <add>부모로부터 받은 props를 이용하여 `getInitialState`에서 state를 생성할 때 종종 "진실의 소스", 예를 들어 진짜 데이터가 있는 곳을 중복으로 만들 때가 있습니다. 가능하던 안하던, 나중에 싱크되지 않는 확실한 값을 계산하고 또한 유지보수에도 문제를 야기합니다. <add> <add>**나쁜 예제:** <add> <add>```js <add>var MessageBox = React.createClass({ <add> getInitialState: function() { <add> return {nameWithQualifier: 'Mr. ' + this.props.name}; <add> }, <add> <add> render: function() { <add> return <div>{this.state.nameWithQualifier}</div>; <add> } <add>}); <add> <add>React.render(<MessageBox name="Rogers"/>, mountNode); <add>``` <add> <add>더 나은 코드: <add> <add>```js <add>var MessageBox = React.createClass({ <add> render: function() { <add> return <div>{'Mr. ' + this.props.name}</div>; <add> } <add>}); <add> <add>React.render(<MessageBox name="Rogers"/>, mountNode); <add>``` <add> <add>(복잡한 로직이라, 메소드에서 계산하는 부분만 떼어 왔습니다.) <add> <add>하지만 여기서 싱크를 맞출 목적이 아님을 명확히 할 수 있다면, 이것은 안티 패턴이 **아닙니다.** <add> <add> <add> <add>```js <add>var Counter = React.createClass({ <add> getInitialState: function() { <add> // initial로 시작하는 메소드는 내부에서 받은 어떠한 값을 초기화 할 목적이 있다는 것을 나타냅니다. <add> return {count: this.props.initialCount}; <add> }, <add> <add> handleClick: function() { <add> this.setState({count: this.state.count + 1}); <add> }, <add> <add> render: function() { <add> return <div onClick={this.handleClick}>{this.state.count}</div>; <add> } <add>}); <add> <add>React.render(<Counter initialCount={7}/>, mountNode); <add>```
6
Ruby
Ruby
maintain return value for recreate_database
78db16d440c610edeb8b2bb37233a5991caf4a29
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def empty_insert_statement_value <ide> # and creates it again using the provided +options+. <ide> def recreate_database(name, options = {}) <ide> drop_database(name) <del> create_database(name, options) <add> sql = create_database(name, options) <ide> reconnect! <add> sql <ide> end <ide> <ide> # Create a new MySQL database with optional <tt>:charset</tt> and <tt>:collation</tt>.
1
PHP
PHP
apply fixes from styleci
2d150b59250f018bfe03d8d4a7acd4a58cc1c9d6
<ide><path>src/Illuminate/Console/GeneratorCommand.php <ide> public function handle() <ide> protected function qualifyClass($name) <ide> { <ide> $name = ltrim($name, '\\/'); <del> <add> <ide> $rootNamespace = $this->rootNamespace(); <ide> <ide> if (Str::startsWith($name, $rootNamespace)) { <ide><path>src/Illuminate/Foundation/Http/FormRequest.php <ide> public function validated() <ide> { <ide> $rules = $this->container->call([$this, 'rules']); <ide> <del> return $this->only(collect($rules)->keys()->map(function($rule){ <add> return $this->only(collect($rules)->keys()->map(function ($rule) { <ide> return str_contains($rule, '.') ? explode('.', $rule)[0] : $rule; <ide> })->unique()->toArray()); <ide> } <ide><path>src/Illuminate/Foundation/Providers/FoundationServiceProvider.php <ide> public function registerRequestValidate() <ide> Request::macro('validate', function (array $rules, ...$params) { <ide> validator()->validate($this->all(), $rules, ...$params); <ide> <del> <del> return $this->only(collect($rules)->keys()->map(function($rule){ <add> return $this->only(collect($rules)->keys()->map(function ($rule) { <ide> return str_contains($rule, '.') ? explode('.', $rule)[0] : $rule; <ide> })->unique()->toArray()); <ide> }); <ide><path>src/Illuminate/Foundation/Validation/ValidatesRequests.php <ide> public function validateWith($validator, Request $request = null) <ide> <ide> $validator->validate(); <ide> <del> return $request->only(collect($validator->getRules())->keys()->map(function($rule){ <del> return str_contains($rule, '.') ? explode('.', $rule)[0] : $rule; <del> })->unique()->toArray()); <add> return $request->only(collect($validator->getRules())->keys()->map(function ($rule) { <add> return str_contains($rule, '.') ? explode('.', $rule)[0] : $rule; <add> })->unique()->toArray()); <ide> } <ide> <ide> /** <ide> public function validate(Request $request, array $rules, <ide> ->make($request->all(), $rules, $messages, $customAttributes) <ide> ->validate(); <ide> <del> return $request->only(collect($rules)->keys()->map(function($rule){ <add> return $request->only(collect($rules)->keys()->map(function ($rule) { <ide> return str_contains($rule, '.') ? explode('.', $rule)[0] : $rule; <ide> })->unique()->toArray()); <ide> } <ide><path>tests/Integration/Http/ResourceTest.php <ide> <ide> namespace Illuminate\Tests\Integration\Http; <ide> <del>use Illuminate\Tests\Integration\Http\Fixtures\Author; <ide> use Orchestra\Testbench\TestCase; <ide> use Illuminate\Support\Facades\Route; <ide> use Illuminate\Pagination\LengthAwarePaginator; <ide> use Illuminate\Tests\Integration\Http\Fixtures\Post; <add>use Illuminate\Tests\Integration\Http\Fixtures\Author; <ide> use Illuminate\Tests\Integration\Http\Fixtures\PostResource; <ide> use Illuminate\Tests\Integration\Http\Fixtures\Subscription; <ide> use Illuminate\Tests\Integration\Http\Fixtures\PostCollectionResource; <ide> public function test_resources_may_load_optional_relationships() <ide> $response->assertExactJson([ <ide> 'data' => [ <ide> 'id' => 5, <del> 'author' => ['name' => 'jrrmartin'] <add> 'author' => ['name' => 'jrrmartin'], <ide> ], <ide> ]); <ide> } <ide> public function test_resources_may_shows_null_for_loaded_relationship_with_value <ide> $response->assertExactJson([ <ide> 'data' => [ <ide> 'id' => 5, <del> 'author' => null <add> 'author' => null, <ide> ], <ide> ]); <ide> } <ide><path>tests/Routing/RoutingRouteTest.php <ide> public function testMacro() <ide> $this->assertEquals('OK', $router->dispatch(Request::create('webhook', 'GET'))->getContent()); <ide> $this->assertEquals('OK', $router->dispatch(Request::create('webhook', 'POST'))->getContent()); <ide> } <del> <add> <ide> public function testRouteMacro() <ide> { <ide> $router = $this->getRouter(); <del> <add> <ide> Route::macro('breadcrumb', function ($breadcrumb) { <ide> $this->action['breadcrumb'] = $breadcrumb; <del> <add> <ide> return $this; <ide> }); <del> <add> <ide> $router->get('foo', function () { <ide> return 'bar'; <ide> })->breadcrumb('fooBreadcrumb')->name('foo'); <del> <add> <ide> $router->getRoutes()->refreshNameLookups(); <del> <add> <ide> $this->assertEquals('fooBreadcrumb', $router->getRoutes()->getByName('foo')->getAction()['breadcrumb']); <ide> } <ide>
6
Ruby
Ruby
add specs for simple in memory joins
d2bf57135f7293a1998a25bd828b0c470cf6b85c
<ide><path>spec/relations/join_spec.rb <add>require 'spec_helper' <add> <add>describe "Arel" do <add> before :all do <add> @owner = Arel::Model.build do |r| <add> r.engine Arel::Testing::Engine.new <add> <add> r.attribute :id, Arel::Attributes::Integer <add> end <add> <add> @thing = Arel::Model.build do |r| <add> r.engine Arel::Testing::Engine.new <add> <add> r.attribute :id, Arel::Attributes::Integer <add> r.attribute :owner_id, Arel::Attributes::Integer <add> r.attribute :age, Arel::Attributes::Integer <add> end <add> end <add> <add> describe "Join" do <add> before :all do <add> @relation = @thing.join(@owner).on(@thing[:owner_id].eq(@owner[:id])) <add> @expected = [] <add> <add> 3.times do |owner_id| <add> @owner.insert([owner_id]) <add> <add> 8.times do |i| <add> thing_id = owner_id * 8 + i <add> age = 2 * thing_id <add> <add> @thing.insert([thing_id, owner_id, age]) <add> @expected << Arel::Row.new(@relation, [thing_id, owner_id, age, owner_id]) <add> end <add> end <add> end <add> <add> it_should_behave_like 'A Relation' <add> end <add>end <ide>\ No newline at end of file
1
Javascript
Javascript
remove async from void functions in page-loader
72a0c5578e249b5b4c8c76aebb02ebe9e9a1a7ec
<ide><path>packages/next/client/page-loader.js <ide> const relPrefetch = <ide> <ide> const hasNoModule = 'noModule' in document.createElement('script') <ide> <add>function normalizeRoute(route) { <add> if (route[0] !== '/') { <add> throw new Error(`Route name should start with a "/", got "${route}"`) <add> } <add> route = route.replace(/\/index$/, '/') <add> <add> if (route === '/') return route <add> return route.replace(/\/$/, '') <add>} <add> <ide> function appendLink(href, rel, as) { <ide> return new Promise((res, rej, link) => { <ide> link = document.createElement('link') <ide> export default class PageLoader { <ide> ) <ide> } <ide> <del> normalizeRoute(route) { <del> if (route[0] !== '/') { <del> throw new Error(`Route name should start with a "/", got "${route}"`) <del> } <del> route = route.replace(/\/index$/, '/') <del> <del> if (route === '/') return route <del> return route.replace(/\/$/, '') <del> } <del> <ide> loadPage(route) { <ide> return this.loadPageScript(route).then(v => v.page) <ide> } <ide> <ide> loadPageScript(route) { <del> route = this.normalizeRoute(route) <add> route = normalizeRoute(route) <ide> <ide> return new Promise((resolve, reject) => { <ide> const fire = ({ error, page, mod }) => { <ide> export default class PageLoader { <ide> }) <ide> } <ide> <del> async loadRoute(route) { <del> route = this.normalizeRoute(route) <add> loadRoute(route) { <add> route = normalizeRoute(route) <ide> let scriptRoute = route === '/' ? '/index.js' : `${route}.js` <ide> <ide> const url = `${this.assetPrefix}/_next/static/${encodeURIComponent( <ide> export default class PageLoader { <ide> register() <ide> } <ide> <del> async prefetch(route, isDependency) { <add> prefetch(route, isDependency) { <ide> // https://github.com/GoogleChromeLabs/quicklink/blob/453a661fa1fa940e2d2e044452398e38c67a98fb/src/index.mjs#L115-L118 <ide> // License: Apache 2.0 <ide> let cn <ide> if ((cn = navigator.connection)) { <ide> // Don't prefetch if using 2G or if Save-Data is enabled. <del> if (cn.saveData || /2g/.test(cn.effectiveType)) return <add> if (cn.saveData || /2g/.test(cn.effectiveType)) return Promise.resolve() <ide> } <ide> <ide> let url = this.assetPrefix <ide> if (isDependency) { <ide> url += route <ide> } else { <del> route = this.normalizeRoute(route) <add> route = normalizeRoute(route) <ide> this.prefetched[route] = true <ide> <ide> let scriptRoute = `${route === '/' ? '/index' : route}.js` <ide> export default class PageLoader { <ide> )}/pages${encodeURI(scriptRoute)}` <ide> } <ide> <del> if ( <add> return Promise.all( <ide> document.querySelector( <ide> `link[rel="${relPrefetch}"][href^="${url}"], script[data-next-page="${route}"]` <ide> ) <del> ) { <del> return <del> } <del> <del> return Promise.all([ <del> appendLink(url, relPrefetch, url.match(/\.css$/) ? 'style' : 'script'), <del> process.env.__NEXT_GRANULAR_CHUNKS && <del> !isDependency && <del> this.getDependencies(route).then(urls => <del> Promise.all(urls.map(url => this.prefetch(url, true))) <del> ), <del> ]).then( <add> ? [] <add> : [ <add> appendLink( <add> url, <add> relPrefetch, <add> url.match(/\.css$/) ? 'style' : 'script' <add> ), <add> process.env.__NEXT_GRANULAR_CHUNKS && <add> !isDependency && <add> this.getDependencies(route).then(urls => <add> Promise.all(urls.map(url => this.prefetch(url, true))) <add> ), <add> ] <add> ).then( <ide> // do not return any data <ide> () => {}, <ide> // swallow prefetch errors <ide><path>test/integration/size-limit/test/index.test.js <ide> describe('Production response size', () => { <ide> ) <ide> <ide> // These numbers are without gzip compression! <del> const delta = responseSizeKilobytes - 199 <add> const delta = responseSizeKilobytes - 198 <ide> expect(delta).toBeLessThanOrEqual(0) // don't increase size <ide> expect(delta).toBeGreaterThanOrEqual(-1) // don't decrease size without updating target <ide> })
2
Go
Go
remove restart canceled error
fc2e2234c614379d21c16e32c1b82e7819fc3eac
<ide><path>libcontainerd/container_linux.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> containerd "github.com/docker/containerd/api/grpc/types" <add> "github.com/docker/docker/restartmanager" <ide> "github.com/opencontainers/specs/specs-go" <ide> "golang.org/x/net/context" <ide> ) <ide> func (ctr *container) handleEvent(e *containerd.Event) error { <ide> logrus.Error(err) <ide> } <ide> }) <del> logrus.Error(err) <add> if err != restartmanager.ErrRestartCanceled { <add> logrus.Error(err) <add> } <ide> } else { <ide> ctr.start() <ide> } <ide><path>restartmanager/restartmanager.go <ide> package restartmanager <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "sync" <ide> "time" <ide> const ( <ide> defaultTimeout = 100 * time.Millisecond <ide> ) <ide> <add>// ErrRestartCanceled is returned when the restart manager has been <add>// canceled and will no longer restart the container. <add>var ErrRestartCanceled = errors.New("restart canceled") <add> <ide> // RestartManager defines object that controls container restarting rules. <ide> type RestartManager interface { <ide> Cancel() error <ide> func (rm *restartManager) ShouldRestart(exitCode uint32, hasBeenManuallyStopped <ide> }() <ide> <ide> if rm.canceled { <del> return false, nil, fmt.Errorf("restartmanager canceled") <add> return false, nil, ErrRestartCanceled <ide> } <ide> <ide> if rm.active { <ide> func (rm *restartManager) ShouldRestart(exitCode uint32, hasBeenManuallyStopped <ide> go func() { <ide> select { <ide> case <-rm.cancel: <del> ch <- fmt.Errorf("restartmanager canceled") <add> ch <- ErrRestartCanceled <ide> close(ch) <ide> case <-time.After(rm.timeout): <ide> rm.Lock()
2
Javascript
Javascript
remove leb128 opt
b310b9b45c7e8a60c40d13dae967f74e712ec224
<ide><path>lib/wasm/WebAssemblyGenerator.js <ide> const Template = require("../Template"); <ide> const WebAssemblyUtils = require("./WebAssemblyUtils"); <ide> const { RawSource } = require("webpack-sources"); <ide> <del>const { shrinkPaddedLEB128 } = require("@webassemblyjs/wasm-opt"); <ide> const { editWithAST, addWithAST } = require("@webassemblyjs/wasm-edit"); <ide> const { decode } = require("@webassemblyjs/wasm-parser"); <ide> const t = require("@webassemblyjs/ast"); <ide> const WebAssemblyExportImportedDependency = require("../dependencies/WebAssembly <ide> * @typedef {(ArrayBuffer) => ArrayBuffer} ArrayBufferTransform <ide> */ <ide> <del>/** <del> * Run some preprocessing on the binary before wasm-edit <del> * <del> * @param {ArrayBuffer} ab - original binary <del> * @returns {ArrayBufferTransform} transform <del> */ <del>const preprocess = ab => { <del> const optBin = shrinkPaddedLEB128(new Uint8Array(ab)); <del> return optBin.buffer; <del>}; <del> <ide> /** <ide> * @template T <ide> * @param {Function[]} fns transforms <ide> class WebAssemblyGenerator extends Generator { <ide> <ide> generate(module) { <ide> let bin = module.originalSource().source(); <del> bin = preprocess(bin); <ide> <ide> const initFuncId = t.identifier( <ide> Array.isArray(module.usedExports)
1
Text
Text
add cla for suchow
85603f5b6a780f948acd11ce347764750c0e4247
<ide><path>contributors/suchow.md <add>Syllogism Contributor Agreement <add>=============================== <add> <add>This Syllogism Contributor Agreement (“SCA”) is based on the Oracle Contributor <add>Agreement. The SCA applies to any contribution that you make to any product or <add>project managed by us (the “project”), and sets out the intellectual property <add>rights you grant to us in the contributed materials. The term “us” shall mean <add>Syllogism Co. The term "you" shall mean the person or entity identified below. <add>If you agree to be bound by these terms, fill in the information requested below <add>and include the filled-in version with your first pull-request, under the file <add>contrbutors/. The name of the file should be your GitHub username, with the <add>extension .md. For example, the user example_user would create the file <add>spaCy/contributors/example_user.md . <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>1. The term 'contribution' or ‘contributed materials’ means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, documentation, <add>or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and registrations, <add>in your contribution: <add> * you hereby assign to us joint ownership, and to the extent that such assignment <add> is or becomes invalid, ineffective or unenforceable, you hereby grant to us a perpetual, <add> irrevocable, non-exclusive, worldwide, no-charge, royalty-free, unrestricted license <add> to exercise all rights under those copyrights. This includes, at our option, the <add> right to sublicense these same rights to third parties through multiple levels of <add> sublicensees or other licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your contribution <add> as if each of us were the sole owners, and if one of us makes a derivative work <add> of your contribution, the one who makes the derivative work (or has it made) will <add> be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution against <add> us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and exercise <add> all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the consent <add> of, pay or render an accounting to the other for any use or distribution of your <add> contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, non-exclusive, <add>worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer your <add> contribution in whole or in part, alone or in combination with <add> or included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through multiple <add> levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective on <add>the date you first submitted a contribution to us, even if your submission took <add>place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of authorship <add> and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any third <add> party's copyrights, trademarks, patents, or other intellectual property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and other <add> applicable export and import laws. You agree to notify us if you become aware of <add> any circumstance which would make any of the foregoing representations inaccurate <add> in any respect. Syllogism Co. may publicly disclose your participation in the project, <add> including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable U.S. <add> Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add>x___ I am signing on behalf of myself as an individual and no other person or entity, including my employer, has or will have rights with respect my contributions. <add> <add>____ I am signing on behalf of my employer or a legal entity and I have the actual authority to contractually bind that entity. <add> <add>| Field | Entry | <add>|------------------------------- | -------------------- | <add>| Name | Jordan Suchow | <add>| Company's name (if applicable) | | <add>| Title or Role (if applicable) | | <add>| Date | 2015-04-19 | <add>| GitHub username | suchow | <add>| Website (optional) | http://suchow.io | <add>
1
Python
Python
make more args keyword-only
3d56a3f286485a9f1741286476f8872d8e3be1c8
<ide><path>spacy/language.py <ide> class Language: <ide> def __init__( <ide> self, <ide> vocab: Union[Vocab, bool] = True, <add> *, <ide> max_length: int = 10 ** 6, <ide> meta: Dict[str, Any] = {}, <ide> create_tokenizer: Optional[Callable[["Language"], Callable[[str], Doc]]] = None, <ide> def _link_components(self) -> None: <ide> def from_config( <ide> cls, <ide> config: Union[Dict[str, Any], Config] = {}, <add> *, <ide> disable: Iterable[str] = tuple(), <ide> overrides: Dict[str, Any] = {}, <ide> auto_fill: bool = True,
1
Python
Python
add jsonp support inside of jsonify
cb24646948a8c00c5b39f0d76bf75e153ac502b1
<ide><path>flask/helpers.py <ide> def get_current_user(): <ide> information about this, have a look at :ref:`json-security`. <ide> <ide> .. versionadded:: 0.2 <add> <add> .. versionadded:: 0.9 <add> If the argument ``padded`` true than the json object will pad for <add> JSONP calls like from jquery. The response mimetype will also change <add> to ``text/javascript``. <add> <add> The json object will pad as javascript function with the function name <add> from the request argument ``callback`` or ``jsonp``. If the argument <add> ``padded`` a string jsonify will look for the function name in the <add> request argument with the name which is equal to ``padded``. Is there <add> no function name it will fallback and use ``jsonp`` as function name. <ide> """ <ide> if __debug__: <ide> _assert_have_json() <add> if 'padded' in kwargs: <add> if isinstance(kwargs['padded'], str): <add> callback = request.args.get(kwargs['padded']) or 'jsonp' <add> else: <add> callback = request.args.get('callback') or \ <add> request.args.get('jsonp') or 'jsonp' <add> del kwargs['padded'] <add> json_str = json.dumps(dict(*args, **kwargs), indent=None) <add> content = str(callback) + "(" + json_str + ")" <add> return current_app.response_class(content, mimetype='text/javascript') <ide> return current_app.response_class(json.dumps(dict(*args, **kwargs), <ide> indent=None if request.is_xhr else 2), mimetype='application/json') <ide> <ide><path>flask/testsuite/helpers.py <ide> def return_kwargs(): <ide> @app.route('/dict') <ide> def return_dict(): <ide> return flask.jsonify(d) <add> @app.route("/padded") <add> def return_padded_json(): <add> return flask.jsonify(d, padded=True) <add> @app.route("/padded_custom") <add> def return_padded_json_custom_callback(): <add> return flask.jsonify(d, padded='my_func_name') <ide> c = app.test_client() <ide> for url in '/kw', '/dict': <ide> rv = c.get(url) <ide> self.assert_equal(rv.mimetype, 'application/json') <ide> self.assert_equal(flask.json.loads(rv.data), d) <add> for get_arg in 'callback=funcName', 'jsonp=funcName': <add> rv = c.get('/padded?' + get_arg) <add> self.assert_( rv.data.startswith("funcName(") ) <add> self.assert_( rv.data.endswith(")") ) <add> rv_json = rv.data.split('(')[1].split(')')[0] <add> self.assert_equal(flask.json.loads(rv_json), d) <add> rv = c.get('/padded_custom?my_func_name=funcName') <add> self.assert_( rv.data.startswith("funcName(") ) <ide> <ide> def test_json_attr(self): <ide> app = flask.Flask(__name__)
2
Ruby
Ruby
add xcode 4.5 to standardcompilers map
50efa98638db1484f21f10af3d4a05c568d3896c
<ide><path>Library/Homebrew/macos.rb <ide> def prefer_64_bit? <ide> "4.3.2" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318}, <ide> "4.3.3" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318}, <ide> "4.4" => {:llvm_build_version=>2336, :clang_version=>"4.0", :clang_build_version=>421}, <del> "4.4.1" => {:llvm_build_version=>2336, :clang_version=>"4.0", :clang_build_version=>421} <add> "4.4.1" => {:llvm_build_version=>2336, :clang_version=>"4.0", :clang_build_version=>421}, <add> "4.5" => {:llvm_build_version=>2336, :clang_version=>"4.1", :clang_build_version=>421} <ide> } <ide> <ide> def compilers_standard?
1
Javascript
Javascript
improve error message for requiring system modules
7ddf1f569a809c746874d85527915ac68bc0510c
<ide><path>src/node.js <ide> node.Module.cache = {}; <ide> if (fullPath) { <ide> retrieveFromCache(loadPromise, fullPath, parent); <ide> } else { <del> loadPromise.emitError(); <add> loadPromise.emitError(new Error("Cannot find module '" + requestedPath + "'")); <ide> } <ide> }); <ide> <ide> node.Module.prototype.loadObject = function (loadPromise) { <ide> node.dlopen(self.filename, self.target); // FIXME synchronus <ide> loadPromise.emitSuccess(self.target); <ide> } else { <del> node.stdio.writeError("Error reading " + self.filename + "\n"); <del> loadPromise.emitError(); <add> node.error("Error reading " + self.filename + "\n"); <add> loadPromise.emitError(new Error("Error reading " + self.filename)); <ide> node.exit(1); <ide> } <ide> }); <ide> node.Module.prototype.loadScript = function (loadPromise) { <ide> var catPromise = node.cat(self.filename); <ide> <ide> catPromise.addErrback(function () { <del> loadPromise.emitError(new Error("Error reading " + self.filename + "\n")); <add> loadPromise.emitError(new Error("Error reading " + self.filename)); <add> node.exit(1); <ide> }); <ide> <ide> catPromise.addCallback(function (content) {
1
Python
Python
apply setupmethod consistently
a406c297aafa28074d11ec6fd27c246c70418cb4
<ide><path>src/flask/app.py <ide> def __init__( <ide> # the app's commands to another CLI tool. <ide> self.cli.name = self.name <ide> <del> def _is_setup_finished(self) -> bool: <del> return self.debug and self._got_first_request <add> def _check_setup_finished(self, f_name: str) -> None: <add> if self._got_first_request: <add> raise AssertionError( <add> f"The setup method '{f_name}' can no longer be called" <add> " on the application. It has already handled its first" <add> " request, any changes will not be applied" <add> " consistently.\n" <add> "Make sure all imports, decorators, functions, etc." <add> " needed to set up the application are done before" <add> " running it." <add> ) <ide> <ide> @locked_cached_property <ide> def name(self) -> str: # type: ignore <ide><path>src/flask/blueprints.py <ide> from .scaffold import _endpoint_from_view_func <ide> from .scaffold import _sentinel <ide> from .scaffold import Scaffold <add>from .scaffold import setupmethod <ide> from .typing import AfterRequestCallable <ide> from .typing import BeforeFirstRequestCallable <ide> from .typing import BeforeRequestCallable <ide> def __init__( <ide> self.cli_group = cli_group <ide> self._blueprints: t.List[t.Tuple["Blueprint", dict]] = [] <ide> <del> def _is_setup_finished(self) -> bool: <del> return self._got_registered_once <add> def _check_setup_finished(self, f_name: str) -> None: <add> if self._got_registered_once: <add> import warnings <add> <add> warnings.warn( <add> f"The setup method '{f_name}' can no longer be called on" <add> f" the blueprint '{self.name}'. It has already been" <add> " registered at least once, any changes will not be" <add> " applied consistently.\n" <add> "Make sure all imports, decorators, functions, etc." <add> " needed to set up the blueprint are done before" <add> " registering it.\n" <add> "This warning will become an exception in Flask 2.3.", <add> UserWarning, <add> stacklevel=3, <add> ) <ide> <add> @setupmethod <ide> def record(self, func: t.Callable) -> None: <ide> """Registers a function that is called when the blueprint is <ide> registered on the application. This function is called with the <ide> state as argument as returned by the :meth:`make_setup_state` <ide> method. <ide> """ <del> if self._got_registered_once: <del> # TODO: Upgrade this to an error and unify it setupmethod in 2.3 <del> from warnings import warn <del> <del> warn( <del> Warning( <del> "The blueprint was already registered once but is" <del> " getting modified now. These changes will not show" <del> " up.\n This warning will be become an exception in 2.3." <del> ) <del> ) <ide> self.deferred_functions.append(func) <ide> <add> @setupmethod <ide> def record_once(self, func: t.Callable) -> None: <ide> """Works like :meth:`record` but wraps the function in another <ide> function that will ensure the function is only called once. If the <ide> def make_setup_state( <ide> """ <ide> return BlueprintSetupState(self, app, options, first_registration) <ide> <add> @setupmethod <ide> def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None: <ide> """Register a :class:`~flask.Blueprint` on this blueprint. Keyword <ide> arguments passed to this method will override the defaults set <ide> def extend(bp_dict, parent_dict): <ide> bp_options["name_prefix"] = name <ide> blueprint.register(app, bp_options) <ide> <add> @setupmethod <ide> def add_url_rule( <ide> self, <ide> rule: str, <ide> def add_url_rule( <ide> ) <ide> ) <ide> <add> @setupmethod <ide> def app_template_filter( <ide> self, name: t.Optional[str] = None <ide> ) -> t.Callable[[TemplateFilterCallable], TemplateFilterCallable]: <ide> def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable: <ide> <ide> return decorator <ide> <add> @setupmethod <ide> def add_app_template_filter( <ide> self, f: TemplateFilterCallable, name: t.Optional[str] = None <ide> ) -> None: <ide> def register_template(state: BlueprintSetupState) -> None: <ide> <ide> self.record_once(register_template) <ide> <add> @setupmethod <ide> def app_template_test( <ide> self, name: t.Optional[str] = None <ide> ) -> t.Callable[[TemplateTestCallable], TemplateTestCallable]: <ide> def decorator(f: TemplateTestCallable) -> TemplateTestCallable: <ide> <ide> return decorator <ide> <add> @setupmethod <ide> def add_app_template_test( <ide> self, f: TemplateTestCallable, name: t.Optional[str] = None <ide> ) -> None: <ide> def register_template(state: BlueprintSetupState) -> None: <ide> <ide> self.record_once(register_template) <ide> <add> @setupmethod <ide> def app_template_global( <ide> self, name: t.Optional[str] = None <ide> ) -> t.Callable[[TemplateGlobalCallable], TemplateGlobalCallable]: <ide> def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable: <ide> <ide> return decorator <ide> <add> @setupmethod <ide> def add_app_template_global( <ide> self, f: TemplateGlobalCallable, name: t.Optional[str] = None <ide> ) -> None: <ide> def register_template(state: BlueprintSetupState) -> None: <ide> <ide> self.record_once(register_template) <ide> <add> @setupmethod <ide> def before_app_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable: <ide> """Like :meth:`Flask.before_request`. Such a function is executed <ide> before each request, even if outside of a blueprint. <ide> def before_app_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable: <ide> ) <ide> return f <ide> <add> @setupmethod <ide> def before_app_first_request( <ide> self, f: BeforeFirstRequestCallable <ide> ) -> BeforeFirstRequestCallable: <ide> def after_app_request(self, f: AfterRequestCallable) -> AfterRequestCallable: <ide> ) <ide> return f <ide> <add> @setupmethod <ide> def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable: <ide> """Like :meth:`Flask.teardown_request` but for a blueprint. Such a <ide> function is executed when tearing down each request, even if outside of <ide> def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable: <ide> ) <ide> return f <ide> <add> @setupmethod <ide> def app_context_processor( <ide> self, f: TemplateContextProcessorCallable <ide> ) -> TemplateContextProcessorCallable: <ide> def app_context_processor( <ide> ) <ide> return f <ide> <add> @setupmethod <ide> def app_errorhandler(self, code: t.Union[t.Type[Exception], int]) -> t.Callable: <ide> """Like :meth:`Flask.errorhandler` but for a blueprint. This <ide> handler is used for all requests, even if outside of the blueprint. <ide> def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable": <ide> <ide> return decorator <ide> <add> @setupmethod <ide> def app_url_value_preprocessor( <ide> self, f: URLValuePreprocessorCallable <ide> ) -> URLValuePreprocessorCallable: <ide> def app_url_value_preprocessor( <ide> ) <ide> return f <ide> <add> @setupmethod <ide> def app_url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable: <ide> """Same as :meth:`url_defaults` but application wide.""" <ide> self.record_once( <ide><path>src/flask/scaffold.py <ide> <ide> <ide> def setupmethod(f: F) -> F: <del> """Wraps a method so that it performs a check in debug mode if the <del> first request was already handled. <del> """ <add> f_name = f.__name__ <ide> <ide> def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any: <del> if self._is_setup_finished(): <del> raise AssertionError( <del> "A setup function was called after the first request " <del> "was handled. This usually indicates a bug in the" <del> " application where a module was not imported and" <del> " decorators or other functionality was called too" <del> " late.\nTo fix this make sure to import all your view" <del> " modules, database models, and everything related at a" <del> " central place before the application starts serving" <del> " requests." <del> ) <add> self._check_setup_finished(f_name) <ide> return f(self, *args, **kwargs) <ide> <ide> return t.cast(F, update_wrapper(wrapper_func, f)) <ide> def __init__( <ide> def __repr__(self) -> str: <ide> return f"<{type(self).__name__} {self.name!r}>" <ide> <del> def _is_setup_finished(self) -> bool: <add> def _check_setup_finished(self, f_name: str) -> None: <ide> raise NotImplementedError <ide> <ide> @property <ide> def _method_route( <ide> <ide> return self.route(rule, methods=[method], **options) <ide> <add> @setupmethod <ide> def get(self, rule: str, **options: t.Any) -> t.Callable[[F], F]: <ide> """Shortcut for :meth:`route` with ``methods=["GET"]``. <ide> <ide> .. versionadded:: 2.0 <ide> """ <ide> return self._method_route("GET", rule, options) <ide> <add> @setupmethod <ide> def post(self, rule: str, **options: t.Any) -> t.Callable[[F], F]: <ide> """Shortcut for :meth:`route` with ``methods=["POST"]``. <ide> <ide> .. versionadded:: 2.0 <ide> """ <ide> return self._method_route("POST", rule, options) <ide> <add> @setupmethod <ide> def put(self, rule: str, **options: t.Any) -> t.Callable[[F], F]: <ide> """Shortcut for :meth:`route` with ``methods=["PUT"]``. <ide> <ide> .. versionadded:: 2.0 <ide> """ <ide> return self._method_route("PUT", rule, options) <ide> <add> @setupmethod <ide> def delete(self, rule: str, **options: t.Any) -> t.Callable[[F], F]: <ide> """Shortcut for :meth:`route` with ``methods=["DELETE"]``. <ide> <ide> .. versionadded:: 2.0 <ide> """ <ide> return self._method_route("DELETE", rule, options) <ide> <add> @setupmethod <ide> def patch(self, rule: str, **options: t.Any) -> t.Callable[[F], F]: <ide> """Shortcut for :meth:`route` with ``methods=["PATCH"]``. <ide>
3
Ruby
Ruby
fix ruby 2.7 warnings on `middlewarestackproxy`
fedde239dcee256b417dc9bcfe5fef603bf0d952
<ide><path>actionpack/lib/action_dispatch/middleware/stack.rb <ide> def [](i) <ide> end <ide> <ide> def unshift(klass, *args, &block) <del> middlewares.unshift(build_middleware(klass, args, block)) <add> middlewares.unshift( <add> build_middleware(klass, args, block) do |app| <add> klass.new(app, *args, &block) <add> end <add> ) <ide> end <add> ruby2_keywords(:unshift) if respond_to?(:ruby2_keywords, true) <ide> <ide> def initialize_copy(other) <ide> self.middlewares = other.middlewares.dup <ide> end <ide> <ide> def insert(index, klass, *args, &block) <ide> index = assert_index(index, :before) <del> middlewares.insert(index, build_middleware(klass, args, block)) <add> middlewares.insert( <add> index, <add> build_middleware(klass, args, block) do |app| <add> klass.new(app, *args, &block) <add> end <add> ) <ide> end <add> ruby2_keywords(:insert) if respond_to?(:ruby2_keywords, true) <ide> <ide> alias_method :insert_before, :insert <ide> <ide> def insert_after(index, *args, &block) <ide> index = assert_index(index, :after) <ide> insert(index + 1, *args, &block) <ide> end <add> ruby2_keywords(:insert_after) if respond_to?(:ruby2_keywords, true) <ide> <ide> def swap(target, *args, &block) <ide> index = assert_index(target, :before) <ide> insert(index, *args, &block) <ide> middlewares.delete_at(index + 1) <ide> end <add> ruby2_keywords(:swap) if respond_to?(:ruby2_keywords, true) <ide> <ide> def delete(target) <ide> middlewares.delete_if { |m| m.klass == target } <ide><path>railties/lib/rails/configuration.rb <ide> def initialize(operations = [], delete_operations = []) <ide> end <ide> <ide> def insert_before(*args, &block) <del> @operations << [__method__, args, block] <add> @operations << -> middleware { middleware.send(__method__, *args, &block) } <ide> end <add> ruby2_keywords(:insert_before) if respond_to?(:ruby2_keywords, true) <ide> <ide> alias :insert :insert_before <ide> <ide> def insert_after(*args, &block) <del> @operations << [__method__, args, block] <add> @operations << -> middleware { middleware.send(__method__, *args, &block) } <ide> end <add> ruby2_keywords(:insert_after) if respond_to?(:ruby2_keywords, true) <ide> <ide> def swap(*args, &block) <del> @operations << [__method__, args, block] <add> @operations << -> middleware { middleware.send(__method__, *args, &block) } <ide> end <add> ruby2_keywords(:swap) if respond_to?(:ruby2_keywords, true) <ide> <ide> def use(*args, &block) <del> @operations << [__method__, args, block] <add> @operations << -> middleware { middleware.send(__method__, *args, &block) } <ide> end <add> ruby2_keywords(:use) if respond_to?(:ruby2_keywords, true) <ide> <ide> def delete(*args, &block) <del> @delete_operations << [__method__, args, block] <add> @delete_operations << -> middleware { middleware.send(__method__, *args, &block) } <ide> end <ide> <ide> def unshift(*args, &block) <del> @operations << [__method__, args, block] <add> @operations << -> middleware { middleware.send(__method__, *args, &block) } <ide> end <add> ruby2_keywords(:unshift) if respond_to?(:ruby2_keywords, true) <ide> <ide> def merge_into(other) #:nodoc: <del> (@operations + @delete_operations).each do |operation, args, block| <del> other.send(operation, *args, &block) <add> (@operations + @delete_operations).each do |operation| <add> operation.call(other) <ide> end <ide> <ide> other
2
Go
Go
add bytessize in pkg/units
ae4689f14d59ece06bbd2a08a9687dc075e42d6d
<ide><path>pkg/units/size.go <ide> var ( <ide> sizeRegex = regexp.MustCompile(`^(\d+)([kKmMgGtTpP])?[bB]?$`) <ide> ) <ide> <del>var unitAbbrs = [...]string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} <add>var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} <add>var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} <ide> <ide> // HumanSize returns a human-readable approximation of a size <ide> // using SI standard (eg. "44kB", "17MB") <ide> func HumanSize(size int64) string { <add> return intToString(float64(size), 1000.0, decimapAbbrs) <add>} <add> <add>func BytesSize(size float64) string { <add> return intToString(size, 1024.0, binaryAbbrs) <add>} <add> <add>func intToString(size, unit float64, _map []string) string { <ide> i := 0 <del> sizef := float64(size) <del> for sizef >= 1000.0 { <del> sizef = sizef / 1000.0 <add> for size >= unit { <add> size = size / unit <ide> i++ <ide> } <del> return fmt.Sprintf("%.4g %s", sizef, unitAbbrs[i]) <add> return fmt.Sprintf("%.4g %s", size, _map[i]) <ide> } <ide> <ide> // FromHumanSize returns an integer from a human-readable specification of a <ide><path>pkg/units/size_test.go <ide> import ( <ide> "testing" <ide> ) <ide> <add>func TestBytesSize(t *testing.T) { <add> assertEquals(t, "1 KiB", BytesSize(1024)) <add> assertEquals(t, "1 MiB", BytesSize(1024*1024)) <add> assertEquals(t, "1 MiB", BytesSize(1048576)) <add> assertEquals(t, "2 MiB", BytesSize(2*MiB)) <add> assertEquals(t, "3.42 GiB", BytesSize(3.42*GiB)) <add> assertEquals(t, "5.372 TiB", BytesSize(5.372*TiB)) <add> assertEquals(t, "2.22 PiB", BytesSize(2.22*PiB)) <add>} <add> <ide> func TestHumanSize(t *testing.T) { <ide> assertEquals(t, "1 kB", HumanSize(1000)) <ide> assertEquals(t, "1.024 kB", HumanSize(1024))
2
Go
Go
fix lint issue from rebase
83af60e6237b4227126dad1ef2f8a2016984ee90
<ide><path>api/types/types.go <ide> type ContainerProcessList struct { <ide> Titles []string <ide> } <ide> <del>// Info contains response of Remote API: <add>// Ping contains response of Remote API: <ide> // GET "/_ping" <ide> type Ping struct { <ide> APIVersion string
1
Text
Text
add changelog entry
1d48e5028493b7b628b9e7df0b74a40b44fc1b67
<ide><path>activesupport/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* Make Module#delegate stop using `send` - can no longer delegate to private methods. *dasch* <add> <ide> * AS::Callbacks: deprecate `:rescuable` option. *Bogdan Gusiev* <ide> <ide> * Adds Integer#ordinal to get the ordinal suffix string of an integer. *Tim Gildea*
1
Ruby
Ruby
improve bottle commit writing
d83ed0d793210bd692fe72830b8f3c0b0f41f5ab
<ide><path>Library/Homebrew/cmd/bottle.rb <ide> def merge <ide> <ide> if ARGV.include? '--write' <ide> f = Formula.factory formula_name <del> has_bottle_block = f.class.bottle.checksums.any? <add> update_or_add = nil <ide> <ide> inreplace f.path do |s| <del> if has_bottle_block <del> s.sub!(/ bottle do.+?end\n/m, output) <add> if s.include? 'bottle do' <add> update_or_add = 'add' <add> string = s.sub!(/ bottle do.+?end\n/m, output) <add> odie 'Bottle block replacement failed!' unless string <ide> else <del> s.sub!(/( (url|sha1|sha256|head|version) '\S*'\n+)+/m, '\0' + output + "\n") <add> update_or_add = 'update' <add> string = s.sub!(/( (url|sha1|sha256|head|version) '\S*'\n+)+/m, '\0' + output + "\n") <add> odie 'Bottle block addition failed!' unless string <ide> end <ide> end <ide> <del> update_or_add = has_bottle_block ? 'update' : 'add' <del> <del> system 'git', 'diff' <ide> safe_system 'git', 'commit', '--no-edit', '--verbose', <ide> "--message=#{f.name}: #{update_or_add} #{f.version} bottle.", <ide> '--', f.path
1
Java
Java
improve readability of body[inserters|extractors]
d77797f42c2da26286d5bb9681d6f2a0018792ce
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyExtractors.java <ide> import org.springframework.core.ParameterizedTypeReference; <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.io.buffer.DataBuffer; <del>import org.springframework.http.HttpMessage; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.ReactiveHttpInputMessage; <ide> import org.springframework.http.codec.HttpMessageReader; <ide> import org.springframework.http.codec.multipart.Part; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <del>import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.util.MultiValueMap; <ide> <ide> /** <del> * Implementations of {@link BodyExtractor} that read various bodies, such a reactive streams. <add> * Static factory methods for {@link BodyExtractor} implementations. <ide> * <ide> * @author Arjen Poutsma <ide> * @author Sebastien Deleuze <add> * @author Rossen Stoyanchev <ide> * @since 5.0 <ide> */ <ide> public abstract class BodyExtractors { <ide> <del> private static final ResolvableType FORM_MAP_TYPE = <add> private static final ResolvableType FORM_DATA_TYPE = <ide> ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class); <ide> <del> private static final ResolvableType MULTIPART_MAP_TYPE = ResolvableType.forClassWithGenerics( <add> private static final ResolvableType MULTIPART_DATA_TYPE = ResolvableType.forClassWithGenerics( <ide> MultiValueMap.class, String.class, Part.class); <ide> <ide> private static final ResolvableType PART_TYPE = ResolvableType.forClass(Part.class); <ide> <ide> private static final ResolvableType VOID_TYPE = ResolvableType.forClass(Void.class); <ide> <add> <ide> /** <del> * Return a {@code BodyExtractor} that reads into a Reactor {@link Mono}. <del> * @param elementClass the class of element in the {@code Mono} <del> * @param <T> the element type <del> * @return a {@code BodyExtractor} that reads a mono <add> * Extractor to decode the input content into {@code Mono<T>}. <add> * @param elementClass the class of the element type to decode to <add> * @param <T> the element type to decode to <add> * @return {@code BodyExtractor} for {@code Mono<T>} <ide> */ <ide> public static <T> BodyExtractor<Mono<T>, ReactiveHttpInputMessage> toMono(Class<? extends T> elementClass) { <ide> return toMono(ResolvableType.forClass(elementClass)); <ide> } <ide> <ide> /** <del> * Return a {@code BodyExtractor} that reads into a Reactor {@link Mono}. <del> * The given {@link ParameterizedTypeReference} is used to pass generic type information, for <del> * instance when using the {@link org.springframework.web.reactive.function.client.WebClient WebClient} <del> * <pre class="code"> <del> * Mono&lt;Map&lt;String, String&gt;&gt; body = this.webClient <del> * .get() <del> * .uri("http://example.com") <del> * .exchange() <del> * .flatMap(r -> r.body(toMono(new ParameterizedTypeReference&lt;Map&lt;String,String&gt;&gt;() {}))); <del> * </pre> <del> * @param typeReference a reference to the type of element in the {@code Mono} <del> * @param <T> the element type <del> * @return a {@code BodyExtractor} that reads a mono <add> * Variant of {@link #toMono(Class)} for type information with generics. <add> * @param typeRef the type reference for the type to decode to <add> * @param <T> the element type to decode to <add> * @return {@code BodyExtractor} for {@code Mono<T>} <ide> */ <del> public static <T> BodyExtractor<Mono<T>, ReactiveHttpInputMessage> toMono( <del> ParameterizedTypeReference<T> typeReference) { <del> <del> return toMono(ResolvableType.forType(typeReference.getType())); <add> public static <T> BodyExtractor<Mono<T>, ReactiveHttpInputMessage> toMono(ParameterizedTypeReference<T> typeRef) { <add> return toMono(ResolvableType.forType(typeRef.getType())); <ide> } <ide> <del> static <T> BodyExtractor<Mono<T>, ReactiveHttpInputMessage> toMono(ResolvableType elementType) { <del> return (inputMessage, context) -> readWithMessageReaders(inputMessage, context, <del> elementType, <del> (HttpMessageReader<T> reader) -> { <del> Optional<ServerHttpResponse> serverResponse = context.serverResponse(); <del> if (serverResponse.isPresent() && inputMessage instanceof ServerHttpRequest) { <del> return reader.readMono(elementType, elementType, (ServerHttpRequest) inputMessage, <del> serverResponse.get(), context.hints()); <del> } <del> else { <del> return reader.readMono(elementType, inputMessage, context.hints()); <del> } <del> }, <del> ex -> (inputMessage.getHeaders().getContentType() == null) ? <del> Mono.from(permitEmptyOrFail(inputMessage, ex)) : Mono.error(ex), <del> Mono::empty); <add> private static <T> BodyExtractor<Mono<T>, ReactiveHttpInputMessage> toMono(ResolvableType elementType) { <add> return (inputMessage, context) -> <add> readWithMessageReaders(inputMessage, context, elementType, <add> (HttpMessageReader<T> reader) -> readToMono(inputMessage, context, elementType, reader), <add> ex -> Mono.from(unsupportedErrorHandler(inputMessage, ex)), <add> Mono::empty); <ide> } <ide> <ide> /** <del> * Return a {@code BodyExtractor} that reads into a Reactor {@link Flux}. <del> * @param elementClass the class of element in the {@code Flux} <del> * @param <T> the element type <del> * @return a {@code BodyExtractor} that reads a flux <add> * Extractor to decode the input content into {@code Flux<T>}. <add> * @param elementClass the class of the element type to decode to <add> * @param <T> the element type to decode to <add> * @return {@code BodyExtractor} for {@code Flux<T>} <ide> */ <ide> public static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(Class<? extends T> elementClass) { <ide> return toFlux(ResolvableType.forClass(elementClass)); <ide> } <ide> <ide> /** <del> * Return a {@code BodyExtractor} that reads into a Reactor {@link Flux}. <del> * The given {@link ParameterizedTypeReference} is used to pass generic type information, for <del> * instance when using the {@link org.springframework.web.reactive.function.client.WebClient WebClient} <del> * <pre class="code"> <del> * Flux&lt;ServerSentEvent&lt;String&gt;&gt; body = this.webClient <del> * .get() <del> * .uri("http://example.com") <del> * .exchange() <del> * .flatMap(r -> r.body(toFlux(new ParameterizedTypeReference&lt;ServerSentEvent&lt;String&gt;&gt;() {}))); <del> * </pre> <del> * @param typeReference a reference to the type of element in the {@code Flux} <del> * @param <T> the element type <del> * @return a {@code BodyExtractor} that reads a flux <add> * Variant of {@link #toFlux(Class)} for type information with generics. <add> * @param typeRef the type reference for the type to decode to <add> * @param <T> the element type to decode to <add> * @return {@code BodyExtractor} for {@code Flux<T>} <ide> */ <del> public static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux( <del> ParameterizedTypeReference<T> typeReference) { <del> <del> return toFlux(ResolvableType.forType(typeReference.getType())); <add> public static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(ParameterizedTypeReference<T> typeRef) { <add> return toFlux(ResolvableType.forType(typeRef.getType())); <ide> } <ide> <ide> @SuppressWarnings("unchecked") <del> static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(ResolvableType elementType) { <del> return (inputMessage, context) -> readWithMessageReaders(inputMessage, context, <del> elementType, <del> (HttpMessageReader<T> reader) -> { <del> Optional<ServerHttpResponse> serverResponse = context.serverResponse(); <del> if (serverResponse.isPresent() && inputMessage instanceof ServerHttpRequest) { <del> return reader.read(elementType, elementType, (ServerHttpRequest) inputMessage, <del> serverResponse.get(), context.hints()); <del> } <del> else { <del> return reader.read(elementType, inputMessage, context.hints()); <del> } <del> }, <del> ex -> (inputMessage.getHeaders().getContentType() == null) ? <del> permitEmptyOrFail(inputMessage, ex) : Flux.error(ex), <del> Flux::empty); <add> private static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(ResolvableType elementType) { <add> return (inputMessage, context) -> <add> readWithMessageReaders(inputMessage, context, elementType, <add> (HttpMessageReader<T> reader) -> readToFlux(inputMessage, context, elementType, reader), <add> ex -> unsupportedErrorHandler(inputMessage, ex), <add> Flux::empty); <ide> } <ide> <del> @SuppressWarnings("unchecked") <del> private static <T> Flux<T> permitEmptyOrFail(ReactiveHttpInputMessage message, UnsupportedMediaTypeException ex) { <del> return message.getBody().doOnNext(buffer -> { <del> throw ex; <del> }).map(o -> (T) o); <del> } <add> <add> // Extractors for specific content .. <ide> <ide> /** <del> * Return a {@code BodyExtractor} that reads form data into a {@link MultiValueMap}. <add> * Extractor to read form data into {@code MultiValueMap<String, String>}. <ide> * <p>As of 5.1 this method can also be used on the client side to read form <ide> * data from a server response (e.g. OAuth). <del> * @return a {@code BodyExtractor} that reads form data <add> * @return {@code BodyExtractor} for form data <ide> */ <ide> public static BodyExtractor<Mono<MultiValueMap<String, String>>, ReactiveHttpInputMessage> toFormData() { <ide> return (message, context) -> { <del> ResolvableType type = FORM_MAP_TYPE; <del> HttpMessageReader<MultiValueMap<String, String>> reader = <del> messageReader(type, MediaType.APPLICATION_FORM_URLENCODED, context); <del> Optional<ServerHttpResponse> response = context.serverResponse(); <del> if (response.isPresent() && message instanceof ServerHttpRequest) { <del> return reader.readMono(type, type, (ServerHttpRequest) message, response.get(), context.hints()); <del> } <del> else { <del> return reader.readMono(type, message, context.hints()); <del> } <add> ResolvableType elementType = FORM_DATA_TYPE; <add> MediaType mediaType = MediaType.APPLICATION_FORM_URLENCODED; <add> HttpMessageReader<MultiValueMap<String, String>> reader = findReader(elementType, mediaType, context); <add> return readToMono(message, context, elementType, reader); <ide> }; <ide> } <ide> <ide> /** <del> * Return a {@code BodyExtractor} that reads multipart (i.e. file upload) form data into a <del> * {@link MultiValueMap}. <del> * @return a {@code BodyExtractor} that reads multipart data <add> * Extractor to read multipart data into a {@code MultiValueMap<String, Part>}. <add> * @return {@code BodyExtractor} for multipart data <ide> */ <del> // Note that the returned BodyExtractor is parameterized to ServerHttpRequest, not <del> // ReactiveHttpInputMessage like other methods, since reading form data only typically happens on <del> // the server-side <add> // Parameterized for server-side use <ide> public static BodyExtractor<Mono<MultiValueMap<String, Part>>, ServerHttpRequest> toMultipartData() { <ide> return (serverRequest, context) -> { <del> ResolvableType type = MULTIPART_MAP_TYPE; <del> HttpMessageReader<MultiValueMap<String, Part>> reader = <del> messageReader(type, MediaType.MULTIPART_FORM_DATA, context); <del> return context.serverResponse() <del> .map(response -> reader.readMono(type, type, serverRequest, response, context.hints())) <del> .orElseGet(() -> reader.readMono(type, serverRequest, context.hints())); <add> ResolvableType elementType = MULTIPART_DATA_TYPE; <add> MediaType mediaType = MediaType.MULTIPART_FORM_DATA; <add> HttpMessageReader<MultiValueMap<String, Part>> reader = findReader(elementType, mediaType, context); <add> return readToMono(serverRequest, context, elementType, reader); <ide> }; <ide> } <ide> <ide> /** <del> * Return a {@code BodyExtractor} that reads multipart (i.e. file upload) form data into a <del> * {@link MultiValueMap}. <del> * @return a {@code BodyExtractor} that reads multipart data <add> * Extractor to read multipart data into {@code Flux<Part>}. <add> * @return {@code BodyExtractor} for multipart request parts <ide> */ <del> // Note that the returned BodyExtractor is parameterized to ServerHttpRequest, not <del> // ReactiveHttpInputMessage like other methods, since reading form data only typically happens on <del> // the server-side <add> // Parameterized for server-side use <ide> public static BodyExtractor<Flux<Part>, ServerHttpRequest> toParts() { <ide> return (serverRequest, context) -> { <del> ResolvableType type = PART_TYPE; <del> HttpMessageReader<Part> reader = messageReader(type, MediaType.MULTIPART_FORM_DATA, context); <del> return context.serverResponse() <del> .map(response -> reader.read(type, type, serverRequest, response, context.hints())) <del> .orElseGet(() -> reader.read(type, serverRequest, context.hints())); <add> ResolvableType elementType = PART_TYPE; <add> MediaType mediaType = MediaType.MULTIPART_FORM_DATA; <add> HttpMessageReader<Part> reader = findReader(elementType, mediaType, context); <add> return readToFlux(serverRequest, context, elementType, reader); <ide> }; <ide> } <ide> <ide> /** <del> * Return a {@code BodyExtractor} that returns the body of the message as a {@link Flux} of <del> * {@link DataBuffer}s. <del> * <p><strong>Note</strong> that the returned buffers should be released after usage by calling <del> * {@link org.springframework.core.io.buffer.DataBufferUtils#release(DataBuffer)} <del> * @return a {@code BodyExtractor} that returns the body <del> * @see ReactiveHttpInputMessage#getBody() <add> * Extractor that returns the raw {@link DataBuffer}s. <add> * <p><strong>Note:</strong> the data buffers should be <add> * {@link org.springframework.core.io.buffer.DataBufferUtils#release(DataBuffer) <add> * released} after being used. <add> * @return {@code BodyExtractor} for data buffers <ide> */ <ide> public static BodyExtractor<Flux<DataBuffer>, ReactiveHttpInputMessage> toDataBuffers() { <ide> return (inputMessage, context) -> inputMessage.getBody(); <ide> } <ide> <ide> <add> // Private support methods <add> <ide> private static <T, S extends Publisher<T>> S readWithMessageReaders( <del> ReactiveHttpInputMessage inputMessage, BodyExtractor.Context context, ResolvableType elementType, <add> ReactiveHttpInputMessage message, BodyExtractor.Context context, ResolvableType elementType, <ide> Function<HttpMessageReader<T>, S> readerFunction, <del> Function<UnsupportedMediaTypeException, S> unsupportedError, <del> Supplier<S> empty) { <add> Function<UnsupportedMediaTypeException, S> errorFunction, <add> Supplier<S> emptySupplier) { <ide> <ide> if (VOID_TYPE.equals(elementType)) { <del> return empty.get(); <add> return emptySupplier.get(); <ide> } <del> MediaType contentType = contentType(inputMessage); <del> List<HttpMessageReader<?>> messageReaders = context.messageReaders(); <del> return messageReaders.stream() <del> .filter(r -> r.canRead(elementType, contentType)) <add> <add> MediaType contentType = Optional.ofNullable(message.getHeaders().getContentType()) <add> .orElse(MediaType.APPLICATION_OCTET_STREAM); <add> <add> return context.messageReaders().stream() <add> .filter(reader -> reader.canRead(elementType, contentType)) <ide> .findFirst() <ide> .map(BodyExtractors::<T>cast) <ide> .map(readerFunction) <del> .orElseGet(() -> { <del> List<MediaType> supportedMediaTypes = messageReaders.stream() <del> .flatMap(reader -> reader.getReadableMediaTypes().stream()) <del> .collect(Collectors.toList()); <del> UnsupportedMediaTypeException error = <del> new UnsupportedMediaTypeException(contentType, supportedMediaTypes, elementType); <del> return unsupportedError.apply(error); <del> }); <add> .orElseGet(() -> errorFunction.apply(unsupportedError(context, elementType, contentType))); <add> } <add> <add> private static UnsupportedMediaTypeException unsupportedError(BodyExtractor.Context context, <add> ResolvableType elementType, MediaType contentType) { <add> <add> List<MediaType> supportedMediaTypes = context.messageReaders().stream() <add> .flatMap(reader -> reader.getReadableMediaTypes().stream()) <add> .collect(Collectors.toList()); <add> <add> return new UnsupportedMediaTypeException(contentType, supportedMediaTypes, elementType); <ide> } <ide> <del> private static <T> HttpMessageReader<T> messageReader(ResolvableType elementType, <del> MediaType mediaType, BodyExtractor.Context context) { <add> private static <T> Mono<T> readToMono(ReactiveHttpInputMessage message, BodyExtractor.Context context, <add> ResolvableType type, HttpMessageReader<T> reader) { <add> <add> return context.serverResponse() <add> .map(response -> reader.readMono(type, type, (ServerHttpRequest) message, response, context.hints())) <add> .orElseGet(() -> reader.readMono(type, message, context.hints())); <add> } <add> <add> private static <T> Flux<T> readToFlux(ReactiveHttpInputMessage message, BodyExtractor.Context context, <add> ResolvableType type, HttpMessageReader<T> reader) { <add> <add> return context.serverResponse() <add> .map(response -> reader.read(type, type, (ServerHttpRequest) message, response, context.hints())) <add> .orElseGet(() -> reader.read(type, message, context.hints())); <add> } <add> <add> private static <T> Flux<T> unsupportedErrorHandler( <add> ReactiveHttpInputMessage inputMessage, UnsupportedMediaTypeException ex) { <add> <add> if (inputMessage.getHeaders().getContentType() == null) { <add> // Empty body with no content type is ok <add> return inputMessage.getBody().map(o -> { <add> throw ex; <add> }); <add> } <add> else { <add> return Flux.error(ex); <add> } <add> } <add> <add> private static <T> HttpMessageReader<T> findReader( <add> ResolvableType elementType, MediaType mediaType, BodyExtractor.Context context) { <add> <ide> return context.messageReaders().stream() <ide> .filter(messageReader -> messageReader.canRead(elementType, mediaType)) <ide> .findFirst() <ide> .map(BodyExtractors::<T>cast) <ide> .orElseThrow(() -> new IllegalStateException( <del> "Could not find HttpMessageReader that supports \"" + mediaType + <del> "\" and \"" + elementType + "\"")); <del> } <del> <del> private static MediaType contentType(HttpMessage message) { <del> MediaType result = message.getHeaders().getContentType(); <del> return result != null ? result : MediaType.APPLICATION_OCTET_STREAM; <add> "No HttpMessageReader for \"" + mediaType + "\" and \"" + elementType + "\"")); <ide> } <ide> <ide> @SuppressWarnings("unchecked") <del> private static <T> HttpMessageReader<T> cast(HttpMessageReader<?> messageReader) { <del> return (HttpMessageReader<T>) messageReader; <add> private static <T> HttpMessageReader<T> cast(HttpMessageReader<?> reader) { <add> return (HttpMessageReader<T>) reader; <ide> } <ide> <ide> } <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java <ide> package org.springframework.web.reactive.function; <ide> <ide> import java.util.List; <del>import java.util.Optional; <ide> import java.util.stream.Collectors; <ide> <ide> import org.reactivestreams.Publisher; <ide> import org.springframework.http.client.reactive.ClientHttpRequest; <ide> import org.springframework.http.codec.HttpMessageWriter; <ide> import org.springframework.http.codec.ServerSentEvent; <del>import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> * server-sent events, resources, etc. <ide> * <ide> * @author Arjen Poutsma <add> * @author Rossen Stoyanchev <ide> * @since 5.0 <ide> */ <ide> public abstract class BodyInserters { <ide> <del> private static final ResolvableType RESOURCE_TYPE = <del> ResolvableType.forClass(Resource.class); <add> private static final ResolvableType RESOURCE_TYPE = ResolvableType.forClass(Resource.class); <ide> <del> private static final ResolvableType SERVER_SIDE_EVENT_TYPE = <del> ResolvableType.forClass(ServerSentEvent.class); <add> private static final ResolvableType SSE_TYPE = ResolvableType.forClass(ServerSentEvent.class); <ide> <del> private static final ResolvableType FORM_TYPE = <add> private static final ResolvableType FORM_DATA_TYPE = <ide> ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class); <ide> <del> private static final ResolvableType MULTIPART_VALUE_TYPE = ResolvableType.forClassWithGenerics( <add> private static final ResolvableType MULTIPART_DATA_TYPE = ResolvableType.forClassWithGenerics( <ide> MultiValueMap.class, String.class, Object.class); <ide> <del> private static final BodyInserter<Void, ReactiveHttpOutputMessage> EMPTY = <del> (response, context) -> response.setComplete(); <add> private static final BodyInserter<Void, ReactiveHttpOutputMessage> EMPTY_INSERTER = <add> (response, context) -> response.setComplete(); <ide> <ide> <ide> /** <del> * Return an empty {@code BodyInserter} that writes nothing. <del> * @return an empty {@code BodyInserter} <add> * Inserter that does not write. <add> * @return the inserter <ide> */ <ide> @SuppressWarnings("unchecked") <ide> public static <T> BodyInserter<T, ReactiveHttpOutputMessage> empty() { <del> return (BodyInserter<T, ReactiveHttpOutputMessage>)EMPTY; <add> return (BodyInserter<T, ReactiveHttpOutputMessage>) EMPTY_INSERTER; <ide> } <ide> <ide> /** <del> * Return a {@code BodyInserter} that writes the given single object. <del> * <p>Note also that <add> * Inserter to write the given object. <add> * <p>Alternatively, consider using the {@code syncBody(Object)} shortcuts on <ide> * {@link org.springframework.web.reactive.function.client.WebClient WebClient} and <del> * {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse} <del> * each offer a {@code syncBody(Object)} shortcut for providing an Object <del> * as the body. <del> * @param body the body of the response <del> * @return a {@code BodyInserter} that writes a single object <add> * {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse}. <add> * @param body the body to write to the response <add> * @param <T> the type of the body <add> * @return the inserter to write a single object <ide> */ <ide> public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromObject(T body) { <del> return bodyInserterFor(Mono.just(body), ResolvableType.forInstance(body)); <add> return (message, context) -> <add> writeWithMessageWriters(message, context, Mono.just(body), ResolvableType.forInstance(body)); <ide> } <ide> <ide> /** <del> * Return a {@code BodyInserter} that writes the given {@link Publisher}. <del> * <p>Note also that <add> * Inserter to write the given {@link Publisher}. <add> * <p>Alternatively, consider using the {@code body} shortcuts on <ide> * {@link org.springframework.web.reactive.function.client.WebClient WebClient} and <del> * {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse} <del> * each offer {@code body} shortcut methods for providing a Publisher as the body. <del> * @param publisher the publisher to stream to the response body <del> * @param elementClass the class of elements contained in the publisher <add> * {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse}. <add> * @param publisher the publisher to write with <add> * @param elementClass the type of elements in the publisher <ide> * @param <T> the type of the elements contained in the publisher <del> * @param <P> the type of the {@code Publisher} <del> * @return a {@code BodyInserter} that writes a {@code Publisher} <add> * @param <P> the {@code Publisher} type <add> * @return the inserter to write a {@code Publisher} <ide> */ <ide> public static <T, P extends Publisher<T>> BodyInserter<P, ReactiveHttpOutputMessage> fromPublisher( <ide> P publisher, Class<T> elementClass) { <ide> <del> return bodyInserterFor(publisher, ResolvableType.forClass(elementClass)); <add> return (message, context) -> <add> writeWithMessageWriters(message, context, publisher, ResolvableType.forClass(elementClass)); <ide> } <ide> <ide> /** <del> * Return a {@code BodyInserter} that writes the given {@link Publisher}. <del> * <p>Note also that <add> * Inserter to write the given {@link Publisher}. <add> * <p>Alternatively, consider using the {@code body} shortcuts on <ide> * {@link org.springframework.web.reactive.function.client.WebClient WebClient} and <del> * {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse} <del> * each offer {@code body} shortcut methods for providing a Publisher as the body. <del> * @param publisher the publisher to stream to the response body <del> * @param typeReference the type of elements contained in the publisher <add> * {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse}. <add> * @param publisher the publisher to write with <add> * @param typeRef the type of elements contained in the publisher <ide> * @param <T> the type of the elements contained in the publisher <del> * @param <P> the type of the {@code Publisher} <del> * @return a {@code BodyInserter} that writes a {@code Publisher} <add> * @param <P> the {@code Publisher} type <add> * @return the inserter to write a {@code Publisher} <ide> */ <ide> public static <T, P extends Publisher<T>> BodyInserter<P, ReactiveHttpOutputMessage> fromPublisher( <del> P publisher, ParameterizedTypeReference<T> typeReference) { <add> P publisher, ParameterizedTypeReference<T> typeRef) { <ide> <del> return bodyInserterFor(publisher, ResolvableType.forType(typeReference.getType())); <add> return (message, context) -> <add> writeWithMessageWriters(message, context, publisher, ResolvableType.forType(typeRef.getType())); <ide> } <ide> <ide> /** <del> * Return a {@code BodyInserter} that writes the given {@code Resource}. <add> * Inserter to write the given {@code Resource}. <ide> * <p>If the resource can be resolved to a {@linkplain Resource#getFile() file}, it will <ide> * be copied using <a href="https://en.wikipedia.org/wiki/Zero-copy">zero-copy</a>. <ide> * @param resource the resource to write to the output message <ide> * @param <T> the type of the {@code Resource} <del> * @return a {@code BodyInserter} that writes a {@code Publisher} <add> * @return the inserter to write a {@code Publisher} <ide> */ <ide> public static <T extends Resource> BodyInserter<T, ReactiveHttpOutputMessage> fromResource(T resource) { <ide> return (outputMessage, context) -> { <del> Mono<T> inputStream = Mono.just(resource); <del> HttpMessageWriter<Resource> messageWriter = resourceHttpMessageWriter(context); <del> Optional<ServerHttpRequest> serverRequest = context.serverRequest(); <del> if (serverRequest.isPresent() && outputMessage instanceof ServerHttpResponse) { <del> return messageWriter.write(inputStream, RESOURCE_TYPE, RESOURCE_TYPE, null, <del> serverRequest.get(), (ServerHttpResponse) outputMessage, context.hints()); <del> } <del> else { <del> return messageWriter.write(inputStream, RESOURCE_TYPE, null, outputMessage, context.hints()); <del> } <add> ResolvableType elementType = RESOURCE_TYPE; <add> HttpMessageWriter<Resource> writer = findWriter(context, elementType, null); <add> return write(Mono.just(resource), elementType, null, outputMessage, context, writer); <ide> }; <ide> } <ide> <del> private static HttpMessageWriter<Resource> resourceHttpMessageWriter(BodyInserter.Context context) { <del> return context.messageWriters().stream() <del> .filter(messageWriter -> messageWriter.canWrite(RESOURCE_TYPE, null)) <del> .findFirst() <del> .map(BodyInserters::<Resource>cast) <del> .orElseThrow(() -> new IllegalStateException( <del> "Could not find HttpMessageWriter that supports Resource objects")); <del> } <del> <ide> /** <del> * Return a {@code BodyInserter} that writes the given {@code ServerSentEvent} publisher. <del> * <p>Note that a SSE {@code BodyInserter} can also be obtained by passing a stream of strings <del> * or POJOs (to be encoded as JSON) to {@link #fromPublisher(Publisher, Class)}, and specifying a <del> * {@link MediaType#TEXT_EVENT_STREAM text/event-stream} Content-Type. <add> * Inserter to write the given {@code ServerSentEvent} publisher. <add> * <p>Alternatively, you can provide event data objects via <add> * {@link #fromPublisher(Publisher, Class)}, and set the "Content-Type" to <add> * {@link MediaType#TEXT_EVENT_STREAM text/event-stream}. <ide> * @param eventsPublisher the {@code ServerSentEvent} publisher to write to the response body <del> * @param <T> the type of the elements contained in the {@link ServerSentEvent} <del> * @return a {@code BodyInserter} that writes a {@code ServerSentEvent} publisher <add> * @param <T> the type of the data elements in the {@link ServerSentEvent} <add> * @return the inserter to write a {@code ServerSentEvent} publisher <ide> * @see <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events W3C recommendation</a> <ide> */ <del> // Note that the returned BodyInserter is parameterized to ServerHttpResponse, not <del> // ReactiveHttpOutputMessage like other methods, since sending SSEs only typically happens on <del> // the server-side <add> // Parameterized for server-side use <ide> public static <T, S extends Publisher<ServerSentEvent<T>>> BodyInserter<S, ServerHttpResponse> fromServerSentEvents( <ide> S eventsPublisher) { <ide> <ide> return (serverResponse, context) -> { <del> HttpMessageWriter<ServerSentEvent<T>> messageWriter = <del> findMessageWriter(context, SERVER_SIDE_EVENT_TYPE, MediaType.TEXT_EVENT_STREAM); <del> return context.serverRequest() <del> .map(serverRequest -> messageWriter.write(eventsPublisher, SERVER_SIDE_EVENT_TYPE, <del> SERVER_SIDE_EVENT_TYPE, MediaType.TEXT_EVENT_STREAM, serverRequest, <del> serverResponse, context.hints())) <del> .orElseGet(() -> messageWriter.write(eventsPublisher, SERVER_SIDE_EVENT_TYPE, <del> MediaType.TEXT_EVENT_STREAM, serverResponse, context.hints())); <add> ResolvableType elmentType = SSE_TYPE; <add> MediaType mediaType = MediaType.TEXT_EVENT_STREAM; <add> HttpMessageWriter<ServerSentEvent<T>> writer = findWriter(context, elmentType, mediaType); <add> return write(eventsPublisher, elmentType, mediaType, serverResponse, context, writer); <ide> }; <ide> } <ide> <ide> /** <del> * Return a {@link FormInserter} that writes the given {@code MultiValueMap} <add> * Return a {@link FormInserter} to write the given {@code MultiValueMap} <ide> * as URL-encoded form data. The returned inserter allows for additional <ide> * entries to be added via {@link FormInserter#with(String, Object)}. <ide> * <ide> public static FormInserter<String> fromFormData(MultiValueMap<String, String> fo <ide> } <ide> <ide> /** <del> * Return a {@link FormInserter} that writes the given key-value pair as <add> * Return a {@link FormInserter} to write the given key-value pair as <ide> * URL-encoded form data. The returned inserter allows for additional <ide> * entries to be added via {@link FormInserter#with(String, Object)}. <ide> * @param name the key to add to the form <ide> public static FormInserter<String> fromFormData(String name, String value) { <ide> } <ide> <ide> /** <del> * Return a {@link MultipartInserter} that writes the given <add> * Return a {@link MultipartInserter} to write the given <ide> * {@code MultiValueMap} as multipart data. Values in the map can be an <ide> * Object or an {@link HttpEntity}. <ide> * <p>Note that you can also build the multipart data externally with <ide> public static MultipartInserter fromMultipartData(MultiValueMap<String, ?> multi <ide> } <ide> <ide> /** <del> * Return a {@link MultipartInserter} that writes the given parts, <add> * Return a {@link MultipartInserter} to write the given parts, <ide> * as multipart data. Values in the map can be an Object or an <ide> * {@link HttpEntity}. <ide> * <p>Note that you can also build the multipart data externally with <ide> public static MultipartInserter fromMultipartData(String name, Object value) { <ide> } <ide> <ide> /** <del> * Return a {@link MultipartInserter} that writes the given asynchronous parts, <add> * Return a {@link MultipartInserter} to write the given asynchronous parts, <ide> * as multipart data. <ide> * <p>Note that you can also build the multipart data externally with <ide> * {@link MultipartBodyBuilder}, and pass the resulting map directly to the <ide> public static <T, P extends Publisher<T>> MultipartInserter fromMultipartAsyncDa <ide> } <ide> <ide> /** <del> * Return a {@code BodyInserter} that writes the given <add> * Inserter to write the given <ide> * {@code Publisher<DataBuffer>} to the body. <ide> * @param publisher the data buffer publisher to write <ide> * @param <T> the type of the publisher <del> * @return a {@code BodyInserter} that writes directly to the body <add> * @return the inserter to write directly to the body <ide> * @see ReactiveHttpOutputMessage#writeWith(Publisher) <ide> */ <ide> public static <T extends Publisher<DataBuffer>> BodyInserter<T, ReactiveHttpOutputMessage> fromDataBuffers( <ide> public static <T extends Publisher<DataBuffer>> BodyInserter<T, ReactiveHttpOutp <ide> } <ide> <ide> <del> private static <T, P extends Publisher<?>, M extends ReactiveHttpOutputMessage> BodyInserter<T, M> bodyInserterFor( <del> P body, ResolvableType bodyType) { <add> private static <P extends Publisher<?>, M extends ReactiveHttpOutputMessage> Mono<Void> writeWithMessageWriters( <add> M outputMessage, BodyInserter.Context context, P body, ResolvableType bodyType) { <ide> <del> return (outputMessage, context) -> { <del> MediaType contentType = outputMessage.getHeaders().getContentType(); <del> List<HttpMessageWriter<?>> messageWriters = context.messageWriters(); <del> return messageWriters.stream() <del> .filter(messageWriter -> messageWriter.canWrite(bodyType, contentType)) <del> .findFirst() <del> .map(BodyInserters::cast) <del> .map(messageWriter -> { <del> Optional<ServerHttpRequest> serverRequest = context.serverRequest(); <del> if (serverRequest.isPresent() && outputMessage instanceof ServerHttpResponse) { <del> return messageWriter.write(body, bodyType, bodyType, contentType, <del> serverRequest.get(), (ServerHttpResponse) outputMessage, <del> context.hints()); <del> } <del> else { <del> return messageWriter.write(body, bodyType, contentType, outputMessage, context.hints()); <del> } <del> }) <del> .orElseGet(() -> { <del> List<MediaType> supportedMediaTypes = messageWriters.stream() <del> .flatMap(reader -> reader.getWritableMediaTypes().stream()) <del> .collect(Collectors.toList()); <del> UnsupportedMediaTypeException error = <del> new UnsupportedMediaTypeException(contentType, supportedMediaTypes, bodyType); <del> return Mono.error(error); <del> }); <del> }; <add> MediaType mediaType = outputMessage.getHeaders().getContentType(); <add> return context.messageWriters().stream() <add> .filter(messageWriter -> messageWriter.canWrite(bodyType, mediaType)) <add> .findFirst() <add> .map(BodyInserters::cast) <add> .map(writer -> write(body, bodyType, mediaType, outputMessage, context, writer)) <add> .orElseGet(() -> Mono.error(unsupportedError(bodyType, context, mediaType))); <add> } <add> <add> private static UnsupportedMediaTypeException unsupportedError(ResolvableType bodyType, <add> BodyInserter.Context context, @Nullable MediaType mediaType) { <add> <add> List<MediaType> supportedMediaTypes = context.messageWriters().stream() <add> .flatMap(reader -> reader.getWritableMediaTypes().stream()) <add> .collect(Collectors.toList()); <add> <add> return new UnsupportedMediaTypeException(mediaType, supportedMediaTypes, bodyType); <add> } <add> <add> private static <T> Mono<Void> write(Publisher<? extends T> input, ResolvableType type, <add> @Nullable MediaType mediaType, ReactiveHttpOutputMessage message, <add> BodyInserter.Context context, HttpMessageWriter<T> writer) { <add> <add> return context.serverRequest() <add> .map(request -> { <add> ServerHttpResponse response = (ServerHttpResponse) message; <add> return writer.write(input, type, type, mediaType, request, response, context.hints()); <add> }) <add> .orElseGet(() -> writer.write(input, type, mediaType, message, context.hints())); <ide> } <ide> <del> private static <T> HttpMessageWriter<T> findMessageWriter( <del> BodyInserter.Context context, ResolvableType type, MediaType mediaType) { <add> private static <T> HttpMessageWriter<T> findWriter( <add> BodyInserter.Context context, ResolvableType elementType, @Nullable MediaType mediaType) { <ide> <ide> return context.messageWriters().stream() <del> .filter(messageWriter -> messageWriter.canWrite(type, mediaType)) <add> .filter(messageWriter -> messageWriter.canWrite(elementType, mediaType)) <ide> .findFirst() <ide> .map(BodyInserters::<T>cast) <ide> .orElseThrow(() -> new IllegalStateException( <del> "Could not find HttpMessageWriter that supports " + mediaType)); <add> "No HttpMessageWriter for \"" + mediaType + "\" and \"" + elementType + "\"")); <ide> } <ide> <ide> @SuppressWarnings("unchecked") <ide> public FormInserter<String> with(MultiValueMap<String, String> values) { <ide> @Override <ide> public Mono<Void> insert(ClientHttpRequest outputMessage, Context context) { <ide> HttpMessageWriter<MultiValueMap<String, String>> messageWriter = <del> findMessageWriter(context, FORM_TYPE, MediaType.APPLICATION_FORM_URLENCODED); <del> return messageWriter.write(Mono.just(this.data), FORM_TYPE, <add> findWriter(context, FORM_DATA_TYPE, MediaType.APPLICATION_FORM_URLENCODED); <add> return messageWriter.write(Mono.just(this.data), FORM_DATA_TYPE, <ide> MediaType.APPLICATION_FORM_URLENCODED, <ide> outputMessage, context.hints()); <ide> } <ide> public <T, P extends Publisher<T>> MultipartInserter withPublisher( <ide> @Override <ide> public Mono<Void> insert(ClientHttpRequest outputMessage, Context context) { <ide> HttpMessageWriter<MultiValueMap<String, HttpEntity<?>>> messageWriter = <del> findMessageWriter(context, MULTIPART_VALUE_TYPE, MediaType.MULTIPART_FORM_DATA); <add> findWriter(context, MULTIPART_DATA_TYPE, MediaType.MULTIPART_FORM_DATA); <ide> MultiValueMap<String, HttpEntity<?>> body = this.builder.build(); <del> return messageWriter.write(Mono.just(body), MULTIPART_VALUE_TYPE, <add> return messageWriter.write(Mono.just(body), MULTIPART_DATA_TYPE, <ide> MediaType.MULTIPART_FORM_DATA, <ide> outputMessage, context.hints()); <ide> }
2
Ruby
Ruby
remove an unused connection handler in a test
3c3eb40f8e1fb492c220ef5c5af3e67378a9e14c
<ide><path>activerecord/test/cases/connection_adapters/connection_handlers_multi_pool_config_test.rb <ide> class ConnectionHandlersMultiPoolConfigTest < ActiveRecord::TestCase <ide> <ide> def setup <ide> @handlers = { writing: ConnectionHandler.new } <del> @rw_handler = @handlers[:writing] <ide> @spec_name = "primary" <del> @writing_handler = ActiveRecord::Base.connection_handlers[:writing] <add> @writing_handler = @handlers[:writing] <ide> end <ide> <ide> def teardown
1
Java
Java
improve @sessionattributes support during redirect
ea05e0b1add86317c13997678aa01bfb73476487
<ide><path>spring-web/src/main/java/org/springframework/web/method/annotation/ModelFactory.java <ide> public static String getNameForReturnValue(Object returnValue, MethodParameter r <ide> * @throws Exception if creating BindingResult attributes fails <ide> */ <ide> public void updateModel(NativeWebRequest request, ModelAndViewContainer mavContainer) throws Exception { <add> ModelMap defaultModel = mavContainer.getDefaultModel(); <ide> if (mavContainer.getSessionStatus().isComplete()){ <ide> this.sessionAttributesHandler.cleanupAttributes(request); <ide> } <ide> else { <del> this.sessionAttributesHandler.storeAttributes(request, mavContainer.getModel()); <add> this.sessionAttributesHandler.storeAttributes(request, defaultModel); <ide> } <del> if (!mavContainer.isRequestHandled()) { <del> updateBindingResult(request, mavContainer.getModel()); <add> if (!mavContainer.isRequestHandled() && mavContainer.getModel() == defaultModel) { <add> updateBindingResult(request, defaultModel); <ide> } <ide> } <ide> <ide><path>spring-web/src/main/java/org/springframework/web/method/support/ModelAndViewContainer.java <ide> private boolean useDefaultModel() { <ide> return (!this.redirectModelScenario || (this.redirectModel == null && !this.ignoreDefaultModelOnRedirect)); <ide> } <ide> <add> /** <add> * Return the "default" model created at instantiation. <add> * <p>In general it is recommended to use {@link #getModel()} instead which <add> * returns either the "default" model (template rendering) or the "redirect" <add> * model (redirect URL preparation). Use of this method may be needed for <add> * advanced cases when access to the "default" model is needed regardless, <add> * e.g. to save model attributes specified via {@code @SessionAttributes}. <add> * @return the default model, never {@code null} <add> */ <add> public ModelMap getDefaultModel() { <add> return this.defaultModel; <add> } <add> <ide> /** <ide> * Provide a separate model instance to use in a redirect scenario. <ide> * The provided additional model however is not used used unless <ide><path>spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java <ide> public void updateModelSessionAttributesRemoved() throws Exception { <ide> assertNull(this.sessionAttributeStore.retrieveAttribute(this.webRequest, attributeName)); <ide> } <ide> <add> // SPR-12542 <add> <add> @Test <add> public void updateModelWhenRedirecting() throws Exception { <add> String attributeName = "sessionAttr"; <add> String attribute = "value"; <add> ModelAndViewContainer container = new ModelAndViewContainer(); <add> container.addAttribute(attributeName, attribute); <add> <add> String queryParam = "123"; <add> String queryParamName = "q"; <add> container.setRedirectModel(new ModelMap(queryParamName, queryParam)); <add> container.setRedirectModelScenario(true); <add> <add> WebDataBinder dataBinder = new WebDataBinder(attribute, attributeName); <add> WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class); <add> given(binderFactory.createBinder(this.webRequest, attribute, attributeName)).willReturn(dataBinder); <add> <add> ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.sessionAttrsHandler); <add> modelFactory.updateModel(this.webRequest, container); <add> <add> assertEquals(queryParam, container.getModel().get(queryParamName)); <add> assertEquals(1, container.getModel().size()); <add> assertEquals(attribute, this.sessionAttributeStore.retrieveAttribute(this.webRequest, attributeName)); <add> } <add> <ide> <ide> private String bindingResultKey(String key) { <ide> return BindingResult.MODEL_KEY_PREFIX + key;
3
Javascript
Javascript
add process no deprecation
6ae6383fdc40c1fe799a8ff600e60ed58366f798
<ide><path>test/parallel/test-child-process-no-deprecation.js <add>'use strict'; <add>const common = require('../common'); <add>process.noDeprecation = true; <add> <add>if (process.argv[2] === 'child') { <add> process.emitWarning('Something else is deprecated.', 'DeprecationWarning'); <add>} else { <add> // parent process <add> const spawn = require('child_process').spawn; <add> <add> // spawn self as child <add> const child = spawn(process.execPath, [process.argv[1], 'child']); <add> <add> child.stderr.on('data', common.mustNotCall()); <add>}
1
Python
Python
remove unnecessary comprehension
0eb5020fda46a6eceaa3652846598cb4ba34493b
<ide><path>airflow/executors/celery_executor.py <ide> def update_task_state(self, key: TaskInstanceKey, state: str, info: Any) -> None <ide> <ide> def end(self, synchronous: bool = False) -> None: <ide> if synchronous: <del> while any([task.state not in celery_states.READY_STATES for task in self.tasks.values()]): <add> while any(task.state not in celery_states.READY_STATES for task in self.tasks.values()): <ide> time.sleep(5) <ide> self.sync() <ide> <ide><path>airflow/models/baseoperator.py <ide> def resolve_template_files(self) -> None: <ide> if content is None: # pylint: disable=no-else-continue <ide> continue <ide> elif isinstance(content, str) and \ <del> any([content.endswith(ext) for ext in self.template_ext]): <add> any(content.endswith(ext) for ext in self.template_ext): <ide> env = self.get_template_env() <ide> try: <ide> setattr(self, field, env.loader.get_source(env, content)[0]) <ide> def resolve_template_files(self) -> None: <ide> env = self.dag.get_template_env() <ide> for i in range(len(content)): # pylint: disable=consider-using-enumerate <ide> if isinstance(content[i], str) and \ <del> any([content[i].endswith(ext) for ext in self.template_ext]): <add> any(content[i].endswith(ext) for ext in self.template_ext): <ide> try: <ide> content[i] = env.loader.get_source(env, content[i])[0] <ide> except Exception as e: # pylint: disable=broad-except <ide><path>airflow/operators/sql.py <ide> def execute(self, context=None): <ide> self.log.info("Record: %s", records) <ide> if not records: <ide> raise AirflowException("The query returned None") <del> elif not all([bool(r) for r in records]): <add> elif not all(bool(r) for r in records): <ide> raise AirflowException( <ide> "Test failed.\nQuery:\n{query}\nResults:\n{records!s}".format( <ide> query=self.sql, records=records <ide><path>airflow/utils/file.py <ide> def might_contain_dag(file_path: str, safe_mode: bool, zip_file: Optional[zipfil <ide> return True <ide> with open(file_path, 'rb') as dag_file: <ide> content = dag_file.read() <del> return all([s in content for s in (b'DAG', b'airflow')]) <add> return all(s in content for s in (b'DAG', b'airflow')) <ide><path>airflow/www/security.py <ide> def _has_role(self, role_name_or_list): <ide> if not isinstance(role_name_or_list, list): <ide> role_name_or_list = [role_name_or_list] <ide> return any( <del> [r.name in role_name_or_list for r in self.get_user_roles()]) <add> r.name in role_name_or_list for r in self.get_user_roles()) <ide> <ide> def _has_perm(self, permission_name, view_menu_name): <ide> """ <ide><path>backport_packages/import_all_provider_classes.py <ide> def import_all_provider_classes(source_path: str, <ide> imported_classes = [] <ide> tracebacks = [] <ide> for root, _, files in os.walk(source_path): <del> if all([not root.startswith(prefix_provider_path) <del> for prefix_provider_path in prefixed_provider_paths]) or root.endswith("__pycache__"): <add> if all(not root.startswith(prefix_provider_path) <add> for prefix_provider_path in prefixed_provider_paths) or root.endswith("__pycache__"): <ide> # Skip loading module if it is not in the list of providers that we are looking for <ide> continue <ide> package_name = root[len(source_path) + 1:].replace("/", ".") <ide><path>tests/jobs/test_backfill_job.py <ide> def test_backfill_max_limit_check_within_limit(self): <ide> <ide> dagruns = DagRun.find(dag_id=dag.dag_id) <ide> self.assertEqual(2, len(dagruns)) <del> self.assertTrue(all([run.state == State.SUCCESS for run in dagruns])) <add> self.assertTrue(all(run.state == State.SUCCESS for run in dagruns)) <ide> <ide> def test_backfill_max_limit_check(self): <ide> dag_id = 'test_backfill_max_limit_check' <ide> def test_backfill_run_backwards(self): <ide> <ide> queued_times = [ti.queued_dttm for ti in tis] <ide> self.assertTrue(queued_times == sorted(queued_times, reverse=True)) <del> self.assertTrue(all([ti.state == State.SUCCESS for ti in tis])) <add> self.assertTrue(all(ti.state == State.SUCCESS for ti in tis)) <ide> <ide> dag.clear() <ide> session.close() <ide><path>tests/models/test_taskinstance.py <ide> def test_check_task_dependencies(self, trigger_rule, successes, skipped, <ide> done=done, <ide> flag_upstream_failed=flag_upstream_failed, <ide> ) <del> completed = all([dep.passed for dep in dep_results]) <add> completed = all(dep.passed for dep in dep_results) <ide> <ide> self.assertEqual(completed, expect_completed) <ide> self.assertEqual(ti.state, expect_state)
8
Python
Python
fix broken tests
44b5d6120341c5fb90a0b3022d09f9ad78d9f836
<ide><path>djangorestframework/tests/parsers.py <ide> def setUp(self): <ide> <ide> def test_parse(self): <ide> """ Make sure the `QueryDict` works OK """ <del> parser = FormParser(None) <add> parser = FormParser() <ide> <ide> stream = StringIO(self.string) <ide> (data, files) = parser.parse(stream, {}, []) <ide> def setUp(self): <ide> } <ide> <ide> def test_parse(self): <del> parser = XMLParser(None) <del> (data, files) = parser.parse(self._input) <add> parser = XMLParser() <add> (data, files) = parser.parse(self._input, {}, []) <ide> self.assertEqual(data, self._data) <ide> <ide> def test_complex_data_parse(self): <del> parser = XMLParser(None) <del> (data, files) = parser.parse(self._complex_data_input) <add> parser = XMLParser() <add> (data, files) = parser.parse(self._complex_data_input, {}, []) <ide> self.assertEqual(data, self._complex_data) <ide><path>djangorestframework/tests/renderers.py <ide> def test_render_and_parse_complex_data(self): <ide> renderer = XMLRenderer(None) <ide> content = StringIO(renderer.render(self._complex_data, 'application/xml')) <ide> <del> parser = XMLParser(None) <del> complex_data_out, dummy = parser.parse(content) <add> parser = XMLParser() <add> complex_data_out, dummy = parser.parse(content, {}, []) <ide> error_msg = "complex data differs!IN:\n %s \n\n OUT:\n %s" % (repr(self._complex_data), repr(complex_data_out)) <ide> self.assertEqual(self._complex_data, complex_data_out, error_msg) <ide> <ide><path>djangorestframework/tests/request.py <ide> def test_overloaded_behaviour_allows_content_tunnelling(self): <ide> request = factory.post('/', data, parsers=parsers) <ide> self.assertEqual(request.DATA, content) <ide> <del> def test_accessing_post_after_data_form(self): <del> """ <del> Ensures request.POST can be accessed after request.DATA in <del> form request. <del> """ <del> data = {'qwerty': 'uiop'} <del> request = factory.post('/', data=data) <del> self.assertEqual(request.DATA.items(), data.items()) <del> self.assertEqual(request.POST.items(), data.items()) <del> <del> def test_accessing_post_after_data_for_json(self): <del> """ <del> Ensures request.POST can be accessed after request.DATA in <del> json request. <del> """ <del> data = {'qwerty': 'uiop'} <del> content = json.dumps(data) <del> content_type = 'application/json' <del> parsers = (JSONParser, ) <del> <del> request = factory.post('/', content, content_type=content_type, <del> parsers=parsers) <del> self.assertEqual(request.DATA.items(), data.items()) <del> self.assertEqual(request.POST.items(), []) <del> <del> def test_accessing_post_after_data_for_overloaded_json(self): <del> """ <del> Ensures request.POST can be accessed after request.DATA in overloaded <del> json request. <del> """ <del> data = {'qwerty': 'uiop'} <del> content = json.dumps(data) <del> content_type = 'application/json' <del> parsers = (JSONParser, ) <del> form_data = {Request._CONTENT_PARAM: content, <del> Request._CONTENTTYPE_PARAM: content_type} <del> <del> request = factory.post('/', form_data, parsers=parsers) <del> self.assertEqual(request.DATA.items(), data.items()) <del> self.assertEqual(request.POST.items(), form_data.items()) <del> <del> def test_accessing_data_after_post_form(self): <del> """ <del> Ensures request.DATA can be accessed after request.POST in <del> form request. <del> """ <del> data = {'qwerty': 'uiop'} <del> parsers = (FormParser, MultiPartParser) <del> request = factory.post('/', data, parsers=parsers) <del> <del> self.assertEqual(request.POST.items(), data.items()) <del> self.assertEqual(request.DATA.items(), data.items()) <del> <del> def test_accessing_data_after_post_for_json(self): <del> """ <del> Ensures request.DATA can be accessed after request.POST in <del> json request. <del> """ <del> data = {'qwerty': 'uiop'} <del> content = json.dumps(data) <del> content_type = 'application/json' <del> parsers = (JSONParser, ) <del> request = factory.post('/', content, content_type=content_type, <del> parsers=parsers) <del> self.assertEqual(request.POST.items(), []) <del> self.assertEqual(request.DATA.items(), data.items()) <del> <del> def test_accessing_data_after_post_for_overloaded_json(self): <del> """ <del> Ensures request.DATA can be accessed after request.POST in overloaded <del> json request <del> """ <del> data = {'qwerty': 'uiop'} <del> content = json.dumps(data) <del> content_type = 'application/json' <del> parsers = (JSONParser, ) <del> form_data = {Request._CONTENT_PARAM: content, <del> Request._CONTENTTYPE_PARAM: content_type} <del> <del> request = factory.post('/', form_data, parsers=parsers) <del> self.assertEqual(request.POST.items(), form_data.items()) <del> self.assertEqual(request.DATA.items(), data.items()) <add> # def test_accessing_post_after_data_form(self): <add> # """ <add> # Ensures request.POST can be accessed after request.DATA in <add> # form request. <add> # """ <add> # data = {'qwerty': 'uiop'} <add> # request = factory.post('/', data=data) <add> # self.assertEqual(request.DATA.items(), data.items()) <add> # self.assertEqual(request.POST.items(), data.items()) <add> <add> # def test_accessing_post_after_data_for_json(self): <add> # """ <add> # Ensures request.POST can be accessed after request.DATA in <add> # json request. <add> # """ <add> # data = {'qwerty': 'uiop'} <add> # content = json.dumps(data) <add> # content_type = 'application/json' <add> # parsers = (JSONParser, ) <add> <add> # request = factory.post('/', content, content_type=content_type, <add> # parsers=parsers) <add> # self.assertEqual(request.DATA.items(), data.items()) <add> # self.assertEqual(request.POST.items(), []) <add> <add> # def test_accessing_post_after_data_for_overloaded_json(self): <add> # """ <add> # Ensures request.POST can be accessed after request.DATA in overloaded <add> # json request. <add> # """ <add> # data = {'qwerty': 'uiop'} <add> # content = json.dumps(data) <add> # content_type = 'application/json' <add> # parsers = (JSONParser, ) <add> # form_data = {Request._CONTENT_PARAM: content, <add> # Request._CONTENTTYPE_PARAM: content_type} <add> <add> # request = factory.post('/', form_data, parsers=parsers) <add> # self.assertEqual(request.DATA.items(), data.items()) <add> # self.assertEqual(request.POST.items(), form_data.items()) <add> <add> # def test_accessing_data_after_post_form(self): <add> # """ <add> # Ensures request.DATA can be accessed after request.POST in <add> # form request. <add> # """ <add> # data = {'qwerty': 'uiop'} <add> # parsers = (FormParser, MultiPartParser) <add> # request = factory.post('/', data, parsers=parsers) <add> <add> # self.assertEqual(request.POST.items(), data.items()) <add> # self.assertEqual(request.DATA.items(), data.items()) <add> <add> # def test_accessing_data_after_post_for_json(self): <add> # """ <add> # Ensures request.DATA can be accessed after request.POST in <add> # json request. <add> # """ <add> # data = {'qwerty': 'uiop'} <add> # content = json.dumps(data) <add> # content_type = 'application/json' <add> # parsers = (JSONParser, ) <add> # request = factory.post('/', content, content_type=content_type, <add> # parsers=parsers) <add> # self.assertEqual(request.POST.items(), []) <add> # self.assertEqual(request.DATA.items(), data.items()) <add> <add> # def test_accessing_data_after_post_for_overloaded_json(self): <add> # """ <add> # Ensures request.DATA can be accessed after request.POST in overloaded <add> # json request <add> # """ <add> # data = {'qwerty': 'uiop'} <add> # content = json.dumps(data) <add> # content_type = 'application/json' <add> # parsers = (JSONParser, ) <add> # form_data = {Request._CONTENT_PARAM: content, <add> # Request._CONTENTTYPE_PARAM: content_type} <add> <add> # request = factory.post('/', form_data, parsers=parsers) <add> # self.assertEqual(request.POST.items(), form_data.items()) <add> # self.assertEqual(request.DATA.items(), data.items()) <ide> <ide> <ide> class MockView(View): <ide><path>djangorestframework/tests/response.py <ide> from django.conf.urls.defaults import patterns, url, include <ide> from django.test import TestCase <ide> <del>from djangorestframework.response import Response, ImmediateResponse <add>from djangorestframework.response import Response, NotAcceptable <ide> from djangorestframework.views import View <ide> from djangorestframework.compat import RequestFactory <ide> from djangorestframework import status <ide> ) <ide> <ide> <add>class MockPickleRenderer(BaseRenderer): <add> media_type = 'application/pickle' <add> <add> <add>class MockJsonRenderer(BaseRenderer): <add> media_type = 'application/json' <add> <add> <ide> class TestResponseDetermineRenderer(TestCase): <ide> <ide> def get_response(self, url='', accept_list=[], renderers=[]): <ide> def get_response(self, url='', accept_list=[], renderers=[]): <ide> request = RequestFactory().get(url, **kwargs) <ide> return Response(request=request, renderers=renderers) <ide> <del> def get_renderer_mock(self, media_type): <del> return type('RendererMock', (BaseRenderer,), { <del> 'media_type': media_type, <del> })() <del> <ide> def test_determine_accept_list_accept_header(self): <ide> """ <ide> Test that determine_accept_list takes the Accept header. <ide> def test_determine_renderer(self): <ide> Test that right renderer is chosen, in the order of Accept list. <ide> """ <ide> accept_list = ['application/pickle', 'application/json'] <del> prenderer = self.get_renderer_mock('application/pickle') <del> jrenderer = self.get_renderer_mock('application/json') <del> <del> response = self.get_response(accept_list=accept_list, renderers=(prenderer, jrenderer)) <add> renderers = (MockPickleRenderer, MockJsonRenderer) <add> response = self.get_response(accept_list=accept_list, renderers=renderers) <ide> renderer, media_type = response._determine_renderer() <ide> self.assertEqual(media_type, 'application/pickle') <del> self.assertTrue(renderer, prenderer) <add> self.assertTrue(isinstance(renderer, MockPickleRenderer)) <ide> <del> response = self.get_response(accept_list=accept_list, renderers=(jrenderer,)) <add> renderers = (MockJsonRenderer, ) <add> response = self.get_response(accept_list=accept_list, renderers=renderers) <ide> renderer, media_type = response._determine_renderer() <ide> self.assertEqual(media_type, 'application/json') <del> self.assertTrue(renderer, jrenderer) <add> self.assertTrue(isinstance(renderer, MockJsonRenderer)) <ide> <ide> def test_determine_renderer_default(self): <ide> """ <ide> Test determine renderer when Accept was not specified. <ide> """ <del> prenderer = self.get_renderer_mock('application/pickle') <del> <del> response = self.get_response(accept_list=None, renderers=(prenderer,)) <add> renderers = (MockPickleRenderer, ) <add> response = self.get_response(accept_list=None, renderers=renderers) <ide> renderer, media_type = response._determine_renderer() <ide> self.assertEqual(media_type, '*/*') <del> self.assertTrue(renderer, prenderer) <add> self.assertTrue(isinstance(renderer, MockPickleRenderer)) <ide> <ide> def test_determine_renderer_no_renderer(self): <ide> """ <ide> Test determine renderer when no renderer can satisfy the Accept list. <ide> """ <ide> accept_list = ['application/json'] <del> prenderer = self.get_renderer_mock('application/pickle') <del> <del> response = self.get_response(accept_list=accept_list, renderers=(prenderer,)) <del> self.assertRaises(ImmediateResponse, response._determine_renderer) <add> renderers = (MockPickleRenderer, ) <add> response = self.get_response(accept_list=accept_list, renderers=renderers) <add> self.assertRaises(NotAcceptable, response._determine_renderer) <ide> <ide> <ide> class TestResponseRenderContent(TestCase): <ide> <ide> def get_response(self, url='', accept_list=[], content=None): <ide> request = RequestFactory().get(url, HTTP_ACCEPT=','.join(accept_list)) <del> return Response(request=request, content=content, renderers=[r() for r in DEFAULT_RENDERERS]) <add> return Response(request=request, content=content, renderers=DEFAULT_RENDERERS) <ide> <ide> def test_render(self): <ide> """ <ide><path>djangorestframework/tests/validators.py <ide> class MockView(View): <ide> content = {'field1': 'example1', 'field2': 'example2'} <ide> try: <ide> MockResource(view).validate_request(content, None) <del> except ImmediateResponse, response: <add> except ImmediateResponse, exc: <add> response = exc.response <ide> self.assertEqual(response.raw_content, {'errors': [MockForm.ERROR_TEXT]}) <ide> else: <ide> self.fail('ImmediateResponse was not raised') <ide> def validation_failed_due_to_no_content_returns_appropriate_message(self, valida <ide> content = {} <ide> try: <ide> validator.validate_request(content, None) <del> except ImmediateResponse, response: <add> except ImmediateResponse, exc: <add> response = exc.response <ide> self.assertEqual(response.raw_content, {'field_errors': {'qwerty': ['This field is required.']}}) <ide> else: <ide> self.fail('ResourceException was not raised') <ide> def validation_failed_due_to_field_error_returns_appropriate_message(self, valid <ide> content = {'qwerty': ''} <ide> try: <ide> validator.validate_request(content, None) <del> except ImmediateResponse, response: <add> except ImmediateResponse, exc: <add> response = exc.response <ide> self.assertEqual(response.raw_content, {'field_errors': {'qwerty': ['This field is required.']}}) <ide> else: <ide> self.fail('ResourceException was not raised') <ide> def validation_failed_due_to_invalid_field_returns_appropriate_message(self, val <ide> content = {'qwerty': 'uiop', 'extra': 'extra'} <ide> try: <ide> validator.validate_request(content, None) <del> except ImmediateResponse, response: <add> except ImmediateResponse, exc: <add> response = exc.response <ide> self.assertEqual(response.raw_content, {'field_errors': {'extra': ['This field does not exist.']}}) <ide> else: <ide> self.fail('ResourceException was not raised') <ide> def validation_failed_due_to_multiple_errors_returns_appropriate_message(self, v <ide> content = {'qwerty': '', 'extra': 'extra'} <ide> try: <ide> validator.validate_request(content, None) <del> except ImmediateResponse, response: <add> except ImmediateResponse, exc: <add> response = exc.response <ide> self.assertEqual(response.raw_content, {'field_errors': {'qwerty': ['This field is required.'], <ide> 'extra': ['This field does not exist.']}}) <ide> else:
5
Python
Python
add not empty check to linalg.qr
1802219aa005d64520f0892fa9ee223f57cfb1ec
<ide><path>numpy/linalg/linalg.py <ide> def qr(a, mode='full'): <ide> """ <ide> a, wrap = _makearray(a) <ide> _assertRank2(a) <add> _assertNonEmpty(a) <ide> m, n = a.shape <ide> t, result_t = _commonType(a) <ide> a = _fastCopyAndTranspose(t, a)
1
Ruby
Ruby
use encode_with for marshalling
441118458d57011ee1b1f1dcfea558de462c6da9
<ide><path>activerecord/lib/active_record/base.rb <ide> def before_remove_const #:nodoc: <ide> reset_scoped_methods <ide> end <ide> <add> # Specifies how the record is loaded by +Marshal+. <add> # <add> # +_load+ sets an instance variable for each key in the hash it takes as input. <add> # Override this method if you require more complex marshalling. <add> def _load(data) <add> record = allocate <add> record.init_with(Marshal.load(data)) <add> record <add> end <add> <ide> private <ide> <ide> def relation #:nodoc: <ide> def init_with(coder) <ide> _run_initialize_callbacks <ide> end <ide> <add> # Specifies how the record is dumped by +Marshal+. <add> # <add> # +_dump+ emits a marshalled hash which has been passed to +encode_with+. Override this <add> # method if you require more complex marshalling. <add> def _dump(level) <add> dump = {} <add> encode_with(dump) <add> Marshal.dump(dump) <add> end <add> <ide> # Returns a String, which Action Pack uses for constructing an URL to this <ide> # object. The default implementation returns this record's id as a String, <ide> # or nil if this record's unsaved. <ide><path>activerecord/test/cases/base_test.rb <ide> def test_default_scope_is_reset <ide> ensure <ide> Object.class_eval{ remove_const :UnloadablePost } if defined?(UnloadablePost) <ide> end <add> <add> def test_marshal_round_trip <add> expected = posts(:welcome) <add> actual = Marshal.load(Marshal.dump(expected)) <add> <add> assert_equal expected.attributes, actual.attributes <add> end <ide> end
2
Text
Text
create model card
c4bcb019062117216e34991ab257b33bd2b91ac8
<ide><path>model_cards/mrm8488/spanbert-large-finetuned-squadv1/README.md <add>--- <add>language: english <add>thumbnail: <add>--- <add> <add># SpanBERT large fine-tuned on SQuAD v1 <add> <add>[SpanBERT](https://github.com/facebookresearch/SpanBERT) created by [Facebook Research](https://github.com/facebookresearch) and fine-tuned on [SQuAD 1.1](https://rajpurkar.github.io/SQuAD-explorer/explore/1.1/dev/) for **Q&A** downstream task ([by them](https://github.com/facebookresearch/SpanBERT#finetuned-models-squad-1120-relation-extraction-coreference-resolution)). <add> <add>## Details of SpanBERT <add> <add>[SpanBERT: Improving Pre-training by Representing and Predicting Spans](https://arxiv.org/abs/1907.10529) <add> <add>## Details of the downstream task (Q&A) - Dataset 📚 🧐 ❓ <add> <add>[SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) <add> <add>## Model fine-tuning 🏋️‍ <add> <add>You can get the fine-tuning script [here](https://github.com/facebookresearch/SpanBERT) <add> <add>```bash <add>python code/run_squad.py \ <add> --do_train \ <add> --do_eval \ <add> --model spanbert-large-cased \ <add> --train_file train-v1.1.json \ <add> --dev_file dev-v1.1.json \ <add> --train_batch_size 32 \ <add> --eval_batch_size 32 \ <add> --learning_rate 2e-5 \ <add> --num_train_epochs 4 \ <add> --max_seq_length 512 \ <add> --doc_stride 128 \ <add> --eval_metric f1 \ <add> --output_dir squad_output \ <add> --fp16 <add>``` <add> <add>## Results Comparison 📝 <add> <add>| | SQuAD 1.1 | SQuAD 2.0 | Coref | TACRED | <add>| ---------------------- | ------------- | --------- | ------- | ------ | <add>| | F1 | F1 | avg. F1 | F1 | <add>| BERT (base) | 88.5* | 76.5* | 73.1 | 67.7 | <add>| SpanBERT (base) | [92.4*](https://huggingface.co/mrm8488/spanbert-base-finetuned-squadv1) | [83.6*](https://huggingface.co/mrm8488/spanbert-base-finetuned-squadv2) | 77.4 | [68.2](https://huggingface.co/mrm8488/spanbert-base-finetuned-tacred) | <add>| BERT (large) | 91.3 | 83.3 | 77.1 | 66.4 | <add>| SpanBERT (large) | **94.6** (this) | [88.7](https://huggingface.co/mrm8488/spanbert-large-finetuned-squadv2) | 79.6 | [70.8](https://huggingface.co/mrm8488/spanbert-large-finetuned-tacred) | <add> <add> <add>Note: The numbers marked as * are evaluated on the development sets becaus those models were not submitted to the official SQuAD leaderboard. All the other numbers are test numbers. <add> <add>## Model in action <add> <add>Fast usage with **pipelines**: <add> <add>```python <add>from transformers import pipeline <add> <add>qa_pipeline = pipeline( <add> "question-answering", <add> model="mrm8488/spanbert-large-finetuned-squadv1", <add> tokenizer="SpanBERT/spanbert-large-cased" <add>) <add> <add>qa_pipeline({ <add> 'context': "Manuel Romero has been working very hard in the repository hugginface/transformers lately", <add> 'question': "How has been working Manuel Romero lately?" <add> <add>}) <add> <add># Output: {'answer': 'very hard in the repository hugginface/transformers', <add> 'end': 82, <add> 'score': 0.327230326857725, <add> 'start': 31} <add>``` <add> <add>> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) <add> <add>> Made with <span style="color: #e25555;">&hearts;</span> in Spain
1
Javascript
Javascript
remove this.type assignment
92a4d59c3221ada339177ca860570893766a6429
<ide><path>src/event.js <ide> jQuery.Event = function( src ) { <ide> } <ide> } <ide> <del> if ( !this.type ) { <del> this.type = src.type; <del> } <del> <ide> // Events bubbling up the document may have been marked as prevented <ide> // by a handler lower down the tree; reflect the correct value. <ide> this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
1
Text
Text
delete some space and unused char
61f1fd4bbb905990312962ceb589f0ede49f3d29
<ide><path>guide/english/android-development/core-components/index.md <del>--- <del>title: Android Core Components <del>--- <del>## Android core components <del>Core components are the essential elements contained in an Android app. Each of them has its own purpose and lifecycle, but not all of them are independent. The Android Core Components are: <del> <del>- Activities <del>- Services <del>- Broadcast receivers <del>- Content providers <del> <del>### [Activities](https://developer.android.com/guide/components/activities/) <del>An _activity_ is a component that has a user interface and represents a single screen in an Android app. An app can have multiple activities, each of which can be an entry point to the application itself for the user or the system (an app's activity that wants to open another activity that belongs to the same application or to a different one). <del> <del>#### [Activity Lifecycle](https://developer.android.com/guide/components/activities/activity-lifecycle) <del>![Activity Lifecycle](https://developer.android.com/images/activity_lifecycle.png) <del> <del>* onCreate(): <del> <del>> Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart(). <del> <del>* onRestart(): <del> <del>> Called after your activity has been stopped, prior to it being started again. Always followed by onStart(). <del> <del>* onStart(): <del> <del>> Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden. <del> <del>* onResume(): <del> <del>> Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause(). <del> <del>* onPause(): <del> <del>> Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). Take for example, an Android app with two activities A and B, in which activity A is currently in the foreground and is the only activity on the app activity stack. When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here. <del> <del>* onStop(): <del> <del>> Called when an activity is no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on subsequent user activity. <del> <del>>Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called. <del> <del>* onDestroy(): <del> <del>> The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method. This call is often used when the user hits the back button, or closes the instance of the app. <del> <del>#### Sample code to understand Activity Lifecycle <del>``` java <del>import android.app.Activity; <del>import android.os.Bundle; <del>import android.util.Log; <del>public class MainActivity extends Activity { <del> String tag = "LifeCycleEvents"; <del> /** Called when the activity is first created. */ <del> @Override <del> public void onCreate(Bundle savedInstanceState) { <del> super.onCreate(savedInstanceState); <del> setContentView(R.layout.main); <del> Log.d(tag, "In the onCreate() event"); <del> } <del> public void onStart() <del> { <del> super.onStart(); <del> Log.d(tag, "In the onStart() event"); <del> } <del> public void onRestart() <del> { <del> super.onRestart(); <del> Log.d(tag, "In the onRestart() event"); <del> } <del> public void onResume() <del> { <del> super.onResume(); <del> Log.d(tag, "In the onResume() event"); <del> } <del> public void onPause() <del> { <del> super.onPause(); <del> Log.d(tag, "In the onPause() event"); <del> } <del> public void onStop() <del> { <del> super.onStop(); <del> Log.d(tag, "In the onStop() event"); <del> } <del> public void onDestroy() <del> { <del> super.onDestroy(); <del> Log.d(tag, "In the onDestroy() event"); <del> } <del>} <del>``` <del> <del> <del>### [Services](https://developer.android.com/guide/components/services) <del>A _service_ is a component without a user interface, and is used to perform long-running operations in the background. <del>There are three kinds of services: <del> <del>- _foreground_ services: they are strictly related to user's interaction (for example music playback), so it's harder for the system to kill them. <del>- _background_ services: they are not directly related to user's activities, so they can be killed if more RAM is needed. <del>- _bound_ services: they are offers a client-server interface that allows components to interact with the service, send requests, receive results, and even do so across processes with interprocess communication (IPC). <del> <del>### [Broadcast receivers](https://developer.android.com/guide/components/broadcasts) <del>A _broadcast receiver_ is another component without user interface (except an optional status bar notification) that provides a gateway for the system to deliver events from/to the app, even when the latter hasn't been previously launched. <del> <del>### [Content providers](https://developer.android.com/guide/topics/providers/content-providers) <del>A _content provider_ is a component used to manage a set of app data to share with other applications. Each item saved in the content provider is identified by a URI scheme. <del> <del>For detailed information about the topic, see the official [Android fundamentals](https://developer.android.com/guide/components/fundamentals) documentation. <del> <del>### Advanced Android Development <del>To learn advanced Android programming concepts, see Google's [Advanced Android Development](https://developers.google.com/training/courses/android-advanced) course. <del> <add>--- <add>title: Android Core Components <add>--- <add>## Android core components <add>Core components are the essential elements contained in an Android app. Each of them has its own purpose and lifecycle, but not all of them are independent. The Android Core Components are: <add> <add>- Activities <add>- Services <add>- Broadcast receivers <add>- Content providers <add> <add>### [Activities](https://developer.android.com/guide/components/activities/) <add>An _activity_ is a component that has a user interface and represents a single screen in an Android app. An app can have multiple activities, each of which can be an entry point to the application itself for the user or the system (an app's activity that wants to open another activity that belongs to the same application or to a different one). <add> <add>#### [Activity Lifecycle](https://developer.android.com/guide/components/activities/activity-lifecycle) <add>![Activity Lifecycle](https://developer.android.com/images/activity_lifecycle.png) <add> <add>* onCreate(): <add> <add>> Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart(). <add> <add>* onRestart(): <add> <add>> Called after your activity has been stopped, prior to it being started again. Always followed by onStart(). <add> <add>* onStart(): <add> <add>> Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden. <add> <add>* onResume(): <add> <add>> Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause(). <add> <add>* onPause(): <add> <add>> Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). Take for example, an Android app with two activities A and B, in which activity A is currently in the foreground and is the only activity on the app activity stack. When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here. <add> <add>* onStop(): <add> <add>> Called when an activity is no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on subsequent user activity. <add> <add>>Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called. <add> <add>* onDestroy(): <add> <add>> The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method. <add>This call is often used when the user hits the back button, or closes the instance of the app. <add> <add>#### Sample code to understand Activity Lifecycle <add>``` java <add>import android.app.Activity; <add>import android.os.Bundle; <add>import android.util.Log; <add>public class MainActivity extends Activity { <add> String tag = "LifeCycleEvents"; <add> /** Called when the activity is first created. */ <add> @Override <add> public void onCreate(Bundle savedInstanceState) { <add> super.onCreate(savedInstanceState); <add> setContentView(R.layout.main); <add> Log.d(tag, "In the onCreate() event"); <add> } <add> public void onStart() <add> { <add> super.onStart(); <add> Log.d(tag, "In the onStart() event"); <add> } <add> public void onRestart() <add> { <add> super.onRestart(); <add> Log.d(tag, "In the onRestart() event"); <add> } <add> public void onResume() <add> { <add> super.onResume(); <add> Log.d(tag, "In the onResume() event"); <add> } <add> public void onPause() <add> { <add> super.onPause(); <add> Log.d(tag, "In the onPause() event"); <add> } <add> public void onStop() <add> { <add> super.onStop(); <add> Log.d(tag, "In the onStop() event"); <add> } <add> public void onDestroy() <add> { <add> super.onDestroy(); <add> Log.d(tag, "In the onDestroy() event"); <add> } <add>} <add>``` <add> <add> <add>### [Services](https://developer.android.com/guide/components/services) <add>A _service_ is a component without a user interface, and is used to perform long-running operations in the background. <add>There are three kinds of services: <add> <add>- _foreground_ services: they are strictly related to user's interaction (for example music playback), so it's harder for the system to kill them. <add>- _background_ services: they are not directly related to user's activities, so they can be killed if more RAM is needed. <add>- _bound_ services: they are offers a client-server interface that allows components to interact with the service, send requests, receive results, and even do so across processes with interprocess communication (IPC). <add> <add>### [Broadcast receivers](https://developer.android.com/guide/components/broadcasts) <add>A _broadcast receiver_ is another component without user interface (except an optional status bar notification) that provides a gateway for the system to deliver events from/to the app, even when the latter hasn't been previously launched. <add> <add>### [Content providers](https://developer.android.com/guide/topics/providers/content-providers) <add>A _content provider_ is a component used to manage a set of app data to share with other applications. Each item saved in the content provider is identified by a URI scheme. <add> <add>For detailed information about the topic, see the official [Android fundamentals](https://developer.android.com/guide/components/fundamentals) documentation. <add> <add>### Advanced Android Development <add>To learn advanced Android programming concepts, see Google's [Advanced Android Development](https://developers.google.com/training/courses/android-advanced) course. <add>
1
Python
Python
use a better method to detect complex arrays
7c1435c11d8bc0d1a3a380bc541a46f75749dc52
<ide><path>numpy/polynomial/chebyshev.py <ide> def chebfit(x, y, deg, rcond=None, full=False, w=None): <ide> rcond = len(x)*np.finfo(x.dtype).eps <ide> <ide> # Determine the norms of the design matrix columns. <del> if lhs.dtype.char in np.typecodes['Complex']: <add> if issubclass(lhs.dtype.type, np.complexfloating): <ide> scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) <ide> else: <ide> scl = np.sqrt(np.square(lhs).sum(1)) <ide><path>numpy/polynomial/hermite.py <ide> def hermfit(x, y, deg, rcond=None, full=False, w=None): <ide> rcond = len(x)*np.finfo(x.dtype).eps <ide> <ide> # Determine the norms of the design matrix columns. <del> if lhs.dtype.char in np.typecodes['Complex']: <add> if issubclass(lhs.dtype.type, np.complexfloating): <ide> scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) <ide> else: <ide> scl = np.sqrt(np.square(lhs).sum(1)) <ide><path>numpy/polynomial/hermite_e.py <ide> def hermefit(x, y, deg, rcond=None, full=False, w=None): <ide> rcond = len(x)*np.finfo(x.dtype).eps <ide> <ide> # Determine the norms of the design matrix columns. <del> if lhs.dtype.char in np.typecodes['Complex']: <add> if issubclass(lhs.dtype.type, np.complexfloating): <ide> scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) <ide> else: <ide> scl = np.sqrt(np.square(lhs).sum(1)) <ide><path>numpy/polynomial/laguerre.py <ide> def lagfit(x, y, deg, rcond=None, full=False, w=None): <ide> rcond = len(x)*np.finfo(x.dtype).eps <ide> <ide> # Determine the norms of the design matrix columns. <del> if lhs.dtype.char in np.typecodes['Complex']: <add> if issubclass(lhs.dtype.type, np.complexfloating): <ide> scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) <ide> else: <ide> scl = np.sqrt(np.square(lhs).sum(1)) <ide><path>numpy/polynomial/legendre.py <ide> def legfit(x, y, deg, rcond=None, full=False, w=None): <ide> rcond = len(x)*np.finfo(x.dtype).eps <ide> <ide> # Determine the norms of the design matrix columns. <del> if lhs.dtype.char in np.typecodes['Complex']: <add> if issubclass(lhs.dtype.type, np.complexfloating): <ide> scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) <ide> else: <ide> scl = np.sqrt(np.square(lhs).sum(1)) <ide><path>numpy/polynomial/polynomial.py <ide> def polyfit(x, y, deg, rcond=None, full=False, w=None): <ide> rcond = len(x)*np.finfo(x.dtype).eps <ide> <ide> # Determine the norms of the design matrix columns. <del> if lhs.dtype.char in np.typecodes['Complex']: <add> if issubclass(lhs.dtype.type, np.complexfloating): <ide> scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) <ide> else: <ide> scl = np.sqrt(np.square(lhs).sum(1))
6
Java
Java
introduce computeattribute() in attributeaccessor
1292947f7837c2716d6e0335698af450d4f12732
<ide><path>spring-core/src/main/java/org/springframework/core/AttributeAccessor.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2020 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> <ide> package org.springframework.core; <ide> <add>import java.util.function.Function; <add> <ide> import org.springframework.lang.Nullable; <add>import org.springframework.util.Assert; <ide> <ide> /** <ide> * Interface defining a generic contract for attaching and accessing metadata <ide> * to/from arbitrary objects. <ide> * <ide> * @author Rob Harrop <add> * @author Sam Brannen <ide> * @since 2.0 <ide> */ <ide> public interface AttributeAccessor { <ide> <ide> /** <ide> * Set the attribute defined by {@code name} to the supplied {@code value}. <del> * If {@code value} is {@code null}, the attribute is {@link #removeAttribute removed}. <add> * <p>If {@code value} is {@code null}, the attribute is {@link #removeAttribute removed}. <ide> * <p>In general, users should take care to prevent overlaps with other <ide> * metadata attributes by using fully-qualified names, perhaps using <ide> * class or package names as prefix. <ide> public interface AttributeAccessor { <ide> <ide> /** <ide> * Get the value of the attribute identified by {@code name}. <del> * Return {@code null} if the attribute doesn't exist. <add> * <p>Return {@code null} if the attribute doesn't exist. <ide> * @param name the unique attribute key <ide> * @return the current value of the attribute, if any <ide> */ <ide> @Nullable <ide> Object getAttribute(String name); <ide> <add> /** <add> * Compute a new value for the attribute identified by {@code name} if <add> * necessary and {@linkplain #setAttribute set} the new value in this <add> * {@code AttributeAccessor}. <add> * <p>If a value for the attribute identified by {@code name} already exists <add> * in this {@code AttributeAccessor}, the existing value will be returned <add> * without applying the supplied compute function. <add> * <p>The default implementation of this method is not thread safe but can <add> * overridden by concrete implementations of this interface. <add> * @param <T> the type of the attribute value <add> * @param name the unique attribute key <add> * @param computeFunction a function that computes a new value for the attribute <add> * name; the function must not return a {@code null} value <add> * @return the existing value or newly computed value for the named attribute <add> * @see #getAttribute(String) <add> * @see #setAttribute(String, Object) <add> * @since 5.3.3 <add> */ <add> @SuppressWarnings("unchecked") <add> default <T> T computeAttribute(String name, Function<String, T> computeFunction) { <add> Assert.notNull(name, "Name must not be null"); <add> Assert.notNull(computeFunction, "Compute function must not be null"); <add> Object value = getAttribute(name); <add> if (value == null) { <add> value = computeFunction.apply(name); <add> Assert.state(value != null, <add> () -> String.format("Compute function must not return null for attribute named '%s'", name)); <add> setAttribute(name, value); <add> } <add> return (T) value; <add> } <add> <ide> /** <ide> * Remove the attribute identified by {@code name} and return its value. <del> * Return {@code null} if no attribute under {@code name} is found. <add> * <p>Return {@code null} if no attribute under {@code name} is found. <ide> * @param name the unique attribute key <ide> * @return the last value of the attribute, if any <ide> */ <ide> public interface AttributeAccessor { <ide> <ide> /** <ide> * Return {@code true} if the attribute identified by {@code name} exists. <del> * Otherwise return {@code false}. <add> * <p>Otherwise return {@code false}. <ide> * @param name the unique attribute key <ide> */ <ide> boolean hasAttribute(String name); <ide><path>spring-core/src/main/java/org/springframework/core/AttributeAccessorSupport.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2020 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.io.Serializable; <ide> import java.util.LinkedHashMap; <ide> import java.util.Map; <add>import java.util.function.Function; <ide> <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> * <ide> * @author Rob Harrop <ide> * @author Juergen Hoeller <add> * @author Sam Brannen <ide> * @since 2.0 <ide> */ <ide> @SuppressWarnings("serial") <ide> public Object getAttribute(String name) { <ide> return this.attributes.get(name); <ide> } <ide> <add> @Override <add> @SuppressWarnings("unchecked") <add> public <T> T computeAttribute(String name, Function<String, T> computeFunction) { <add> Assert.notNull(name, "Name must not be null"); <add> Assert.notNull(computeFunction, "Compute function must not be null"); <add> Object value = this.attributes.computeIfAbsent(name, computeFunction); <add> Assert.state(value != null, <add> () -> String.format("Compute function must not return null for attribute named '%s'", name)); <add> return (T) value; <add> } <add> <ide> @Override <ide> @Nullable <ide> public Object removeAttribute(String name) { <ide><path>spring-core/src/test/java/org/springframework/core/AttributeAccessorSupportTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 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.core; <ide> <ide> import java.util.Arrays; <add>import java.util.concurrent.atomic.AtomicInteger; <add>import java.util.function.Function; <ide> <ide> import org.junit.jupiter.api.Test; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> <ide> /** <add> * Unit tests for {@link AttributeAccessorSupport}. <add> * <ide> * @author Rob Harrop <ide> * @author Sam Brannen <ide> * @since 2.0 <ide> */ <ide> class AttributeAccessorSupportTests { <ide> <del> private static final String NAME = "foo"; <add> private static final String NAME = "name"; <add> <add> private static final String VALUE = "value"; <ide> <del> private static final String VALUE = "bar"; <add> private final AttributeAccessor attributeAccessor = new SimpleAttributeAccessorSupport(); <ide> <del> private AttributeAccessor attributeAccessor = new SimpleAttributeAccessorSupport(); <ide> <ide> @Test <del> void setAndGet() throws Exception { <add> void setAndGet() { <ide> this.attributeAccessor.setAttribute(NAME, VALUE); <ide> assertThat(this.attributeAccessor.getAttribute(NAME)).isEqualTo(VALUE); <ide> } <ide> <ide> @Test <del> void setAndHas() throws Exception { <add> void setAndHas() { <ide> assertThat(this.attributeAccessor.hasAttribute(NAME)).isFalse(); <ide> this.attributeAccessor.setAttribute(NAME, VALUE); <ide> assertThat(this.attributeAccessor.hasAttribute(NAME)).isTrue(); <ide> } <ide> <ide> @Test <del> void remove() throws Exception { <add> void computeAttribute() { <add> AtomicInteger atomicInteger = new AtomicInteger(); <add> Function<String, String> computeFunction = name -> "computed-" + atomicInteger.incrementAndGet(); <add> <add> assertThat(this.attributeAccessor.hasAttribute(NAME)).isFalse(); <add> this.attributeAccessor.computeAttribute(NAME, computeFunction); <add> assertThat(this.attributeAccessor.getAttribute(NAME)).isEqualTo("computed-1"); <add> this.attributeAccessor.computeAttribute(NAME, computeFunction); <add> assertThat(this.attributeAccessor.getAttribute(NAME)).isEqualTo("computed-1"); <add> <add> this.attributeAccessor.removeAttribute(NAME); <add> assertThat(this.attributeAccessor.hasAttribute(NAME)).isFalse(); <add> this.attributeAccessor.computeAttribute(NAME, computeFunction); <add> assertThat(this.attributeAccessor.getAttribute(NAME)).isEqualTo("computed-2"); <add> } <add> <add> @Test <add> void remove() { <ide> assertThat(this.attributeAccessor.hasAttribute(NAME)).isFalse(); <ide> this.attributeAccessor.setAttribute(NAME, VALUE); <ide> assertThat(this.attributeAccessor.removeAttribute(NAME)).isEqualTo(VALUE); <ide> assertThat(this.attributeAccessor.hasAttribute(NAME)).isFalse(); <ide> } <ide> <ide> @Test <del> void attributeNames() throws Exception { <add> void attributeNames() { <ide> this.attributeAccessor.setAttribute(NAME, VALUE); <ide> this.attributeAccessor.setAttribute("abc", "123"); <ide> String[] attributeNames = this.attributeAccessor.attributeNames(); <ide> Arrays.sort(attributeNames); <del> assertThat(Arrays.binarySearch(attributeNames, NAME) > -1).isTrue(); <del> assertThat(Arrays.binarySearch(attributeNames, "abc") > -1).isTrue(); <add> assertThat(Arrays.binarySearch(attributeNames, "abc")).isEqualTo(0); <add> assertThat(Arrays.binarySearch(attributeNames, NAME)).isEqualTo(1); <ide> } <ide> <ide> @SuppressWarnings("serial") <ide><path>spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 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.lang.reflect.Method; <ide> import java.util.Map; <ide> import java.util.concurrent.ConcurrentHashMap; <add>import java.util.function.Function; <ide> <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.ConfigurableApplicationContext; <ide> public Object getAttribute(String name) { <ide> return this.attributes.get(name); <ide> } <ide> <add> @Override <add> @SuppressWarnings("unchecked") <add> public <T> T computeAttribute(String name, Function<String, T> computeFunction) { <add> Assert.notNull(name, "Name must not be null"); <add> Assert.notNull(computeFunction, "Compute function must not be null"); <add> Object value = this.attributes.computeIfAbsent(name, computeFunction); <add> Assert.state(value != null, <add> () -> String.format("Compute function must not return null for attribute named '%s'", name)); <add> return (T) value; <add> } <add> <ide> @Override <ide> @Nullable <ide> public Object removeAttribute(String name) {
4
Ruby
Ruby
fix indentation and newlines in generated engine
f0f978a4f31930777d402965cad55086ebaa46ba
<ide><path>railties/lib/rails/generators/named_base.rb <ide> def indent(content, multiplier = 2) <ide> end <ide> <ide> def wrap_with_namespace(content) <del> content = indent(content) <add> content = indent(content).chomp <ide> "module #{namespace.name}\n#{content}\nend\n" <ide> end <ide> <ide><path>railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb <ide> module <%= camelized %> <ide> class Engine < Rails::Engine <ide> <% if mountable? -%> <del> isolate_namespace <%= camelized %> <add> isolate_namespace <%= camelized %> <ide> <% end -%> <ide> end <ide> end
2
PHP
PHP
rename another trait
51a354f620fd89b667b62623bb9af6dee828a83c
<ide><path>lib/Cake/Model/Datasource/Database/Dialect/PostgresDialectTrait.php <ide> <ide> use Cake\Model\Datasource\Database\Expression\UnaryExpression; <ide> use Cake\Model\Datasource\Database\Query; <add>use Cake\Model\Datasource\Database\SqlDialectTrait; <ide> <del>trait PostgresDialectTrait { <add>trait PostgresDialectTrait extends SqlDialectTrait { <ide> <ide> protected function _selectQueryTranslator($query) { <ide> $limit = $query->clause('limit'); <ide><path>lib/Cake/Model/Datasource/Database/Driver.php <ide> */ <ide> namespace Cake\Model\Datasource\Database; <ide> <del>use \Cake\Model\Datasource\Database\SqlDialect; <add>use \Cake\Model\Datasource\Database\SqlDialectTrait; <ide> <ide> /** <ide> * Represents a database diver containing all specificities for <ide> **/ <ide> abstract class Driver { <ide> <del> use SqlDialect; <add> use SqlDialectTrait; <ide> <ide> /** <ide> * Establishes a connection to the database server <add><path>lib/Cake/Model/Datasource/Database/SqlDialectTrait.php <del><path>lib/Cake/Model/Datasource/Database/SqlDialect.php <ide> */ <ide> namespace Cake\Model\Datasource\Database; <ide> <del>trait SqlDialect { <add>trait SqlDialectTrait { <ide> <ide> /** <ide> * String used to start a database identifier quoting to make it safe
3
Text
Text
add debugging guide to list of guides
f9c975bba73d5498ed61b44a1dff515ed37f72d2
<ide><path>docs/index.md <ide> * [Converting a TextMate Bundle](converting-a-text-mate-bundle.md) <ide> * [Converting a TextMate Theme](converting-a-text-mate-theme.md) <ide> * [Contributing](contributing.md) <add>* [Debugging](debugging.md) <ide> <ide> ### Advanced Topics <ide>
1
Javascript
Javascript
correct the order of the assertions
00d7b13a18dcf39cb7e7ace87c5c7b43d8024f41
<ide><path>lib/module.js <ide> Module.prototype.load = function(filename) { <ide> // Loads a module at the given file path. Returns that module's <ide> // `exports` property. <ide> Module.prototype.require = function(path) { <del> assert(util.isString(path), 'path must be a string'); <ide> assert(path, 'missing path'); <add> assert(util.isString(path), 'path must be a string'); <ide> return Module._load(path, this); <ide> }; <ide> <ide><path>test/simple/test-module-loading-error.js <ide> try { <ide> } catch (e) { <ide> assert.notEqual(e.toString().indexOf(dlerror_msg), -1); <ide> } <add> <add>try { <add> require(); <add>} catch (e) { <add> assert.notEqual(e.toString().indexOf('missing path'), -1); <add>} <add> <add>try { <add> require({}); <add>} catch (e) { <add> assert.notEqual(e.toString().indexOf('path must be a string'), -1); <add>}
2
Ruby
Ruby
add xcode 7.2.1
e84539135969e84a1b451f524a43f58ff42b6d37
<ide><path>Library/Homebrew/os/mac.rb <ide> def preferred_arch <ide> "7.1" => { :clang => "7.0", :clang_build => 700 }, <ide> "7.1.1" => { :clang => "7.0", :clang_build => 700 }, <ide> "7.2" => { :clang => "7.0", :clang_build => 700 }, <add> "7.2.1" => { :clang => "7.0", :clang_build => 700 }, <ide> } <ide> <ide> def compilers_standard?
1
Javascript
Javascript
add unit tests utils
bb6a1aaafaf366a300178e93bd274f38252dbaa2
<ide><path>test/unit/SmartComparer.js <add>// Smart comparison of three.js objects. <add>// Identifies significant differences between two objects. <add>// Performs deep comparison. <add>// Comparison stops after the first difference is found. <add>// Provides an explanation for the failure. <add>function SmartComparer() { <add> 'use strict'; <add> <add> // Diagnostic message, when comparison fails. <add> var message; <add> <add> return { <add> <add> areEqual: areEqual, <add> <add> getDiagnostic: function() { <add> <add> return message; <add> <add> } <add> <add> }; <add> <add> <add> // val1 - first value to compare (typically the actual value) <add> // val2 - other value to compare (typically the expected value) <add> function areEqual( val1, val2 ) { <add> <add> // Values are strictly equal. <add> if ( val1 === val2 ) return true; <add> <add> // Null or undefined values. <add> /* jshint eqnull:true */ <add> if ( val1 == null || val2 == null ) { <add> <add> if ( val1 != val2 ) { <add> <add> return makeFail( 'One value is undefined or null', val1, val2 ); <add> <add> } <add> <add> // Both null / undefined. <add> return true; <add> } <add> <add> // Don't compare functions. <add> if ( isFunction( val1 ) && isFunction( val2 ) ) return true; <add> <add> // Array comparison. <add> var arrCmp = compareArrays( val1, val2 ); <add> if ( arrCmp !== undefined ) return arrCmp; <add> <add> // Has custom equality comparer. <add> if ( val1.equals ) { <add> <add> if ( val1.equals( val2 ) ) return true; <add> <add> return makeFail( 'Comparison with .equals method returned false' ); <add> <add> } <add> <add> // Object comparison. <add> var objCmp = compareObjects( val1, val2 ); <add> if ( objCmp !== undefined ) return objCmp; <add> <add> // if (JSON.stringify( val1 ) == JSON.stringify( val2 ) ) return true; <add> <add> // Object differs (unknown reason). <add> return makeFail( 'Values differ', val1, val2 ); <add> } <add> <add> function isFunction(value) { <add> <add> // The use of `Object#toString` avoids issues with the `typeof` operator <add> // in Safari 8 which returns 'object' for typed array constructors, and <add> // PhantomJS 1.9 which returns 'function' for `NodeList` instances. <add> var tag = isObject(value) ? Object.prototype.toString.call(value) : ''; <add> <add> return tag == '[object Function]' || tag == '[object GeneratorFunction]'; <add> <add> } <add> <add> function isObject(value) { <add> <add> // Avoid a V8 JIT bug in Chrome 19-20. <add> // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. <add> var type = typeof value; <add> <add> return !!value && (type == 'object' || type == 'function'); <add> <add> } <add> <add> function compareArrays( val1, val2 ) { <add> <add> var isArr1 = Array.isArray( val1 ); <add> var isArr2 = Array.isArray( val2 ); <add> <add> // Compare type. <add> if ( isArr1 !== isArr2 ) return makeFail( 'Values are not both arrays' ); <add> <add> // Not arrays. Continue. <add> if ( !isArr1 ) return undefined; <add> <add> // Compare length. <add> var N1 = val1.length; <add> var N2 = val2.length; <add> if ( N1 !== val2.length ) return makeFail( 'Array length differs', N1, N2 ); <add> <add> // Compare content at each index. <add> for ( var i = 0; i < N1; i ++ ) { <add> <add> var cmp = areEqual( val1[ i ], val2[ i ] ); <add> if ( !cmp ) return addContext( 'array index "' + i + '"' ); <add> <add> } <add> <add> // Arrays are equal. <add> return true; <add> } <add> <add> <add> function compareObjects( val1, val2 ) { <add> <add> var isObj1 = isObject( val1 ); <add> var isObj2 = isObject( val2 ); <add> <add> // Compare type. <add> if ( isObj1 !== isObj2 ) return makeFail( 'Values are not both objects' ); <add> <add> // Not objects. Continue. <add> if ( !isObj1 ) return undefined; <add> <add> // Compare keys. <add> var keys1 = Object.keys( val1 ); <add> var keys2 = Object.keys( val2 ); <add> <add> for ( var i = 0, l = keys1.length; i < l; i++ ) { <add> <add> if (keys2.indexOf(keys1[ i ]) < 0) { <add> <add> return makeFail( 'Property "' + keys1[ i ] + '" is unexpected.' ); <add> <add> } <add> <add> } <add> <add> for ( var i = 0, l = keys2.length; i < l; i++ ) { <add> <add> if (keys1.indexOf(keys2[ i ]) < 0) { <add> <add> return makeFail( 'Property "' + keys2[ i ] + '" is missing.' ); <add> <add> } <add> <add> } <add> <add> // Keys are the same. For each key, compare content until a difference is found. <add> var hadDifference = false; <add> <add> for ( var i = 0, l = keys1.length; i < l; i++ ) { <add> <add> var key = keys1[ i ]; <add> <add> if (key === "uuid" || key === "id") { <add> <add> continue; <add> <add> } <add> <add> var prop1 = val1[ key ]; <add> var prop2 = val2[ key ]; <add> <add> // Compare property content. <add> var eq = areEqual( prop1, prop2 ); <add> <add> // In case of failure, an message should already be set. <add> // Add context to low level message. <add> if ( !eq ) { <add> <add> addContext( 'property "' + key + '"' ); <add> hadDifference = true; <add> <add> } <add> } <add> <add> return ! hadDifference; <add> <add> } <add> <add> <add> function makeFail( msg, val1, val2 ) { <add> <add> message = msg; <add> if ( arguments.length > 1) message += " (" + val1 + " vs " + val2 + ")"; <add> <add> return false; <add> <add> } <add> <add> function addContext( msg ) { <add> <add> // There should already be a validation message. Add more context to it. <add> message = message || "Error"; <add> message += ", at " + msg; <add> <add> return false; <add> <add> } <add> <add>} <ide><path>test/unit/qunit-utils.js <add>// <add>// Custom QUnit assertions. <add>// <add> <add>QUnit.assert.success = function ( message ) { <add> <add> // Equivalent to assert( true, message ); <add> this.pushResult( { <add> result: true, <add> actual: undefined, <add> expected: undefined, <add> message: message <add> } ); <add> <add>}; <add> <add>QUnit.assert.fail = function ( message ) { <add> <add> // Equivalent to assert( false, message ); <add> this.pushResult( { <add> result: false, <add> actual: undefined, <add> expected: undefined, <add> message: message <add> } ); <add> <add>}; <add> <add>QUnit.assert.numEqual = function ( actual, expected, message ) { <add> <add> var diff = Math.abs( actual - expected ); <add> message = message || ( actual + " should be equal to " + expected ); <add> this.pushResult( { <add> result: diff < 0.1, <add> actual: actual, <add> expected: expected, <add> message: message <add> } ); <add> <add>}; <add> <add>QUnit.assert.equalKey = function ( obj, ref, key ) { <add> <add> var actual = obj[ key ]; <add> var expected = ref[ key ]; <add> var message = actual + ' should be equal to ' + expected + ' for key "' + key + '"'; <add> this.pushResult( { <add> result: actual == expected, <add> actual: actual, <add> expected: expected, <add> message: message <add> } ); <add> <add>}; <add> <add>QUnit.assert.smartEqual = function ( actual, expected, message ) { <add> <add> var cmp = new SmartComparer(); <add> <add> var same = cmp.areEqual( actual, expected ); <add> var msg = cmp.getDiagnostic() || message; <add> <add> this.pushResult( { <add> result: same, <add> actual: actual, <add> expected: expected, <add> message: msg <add> } ); <add> <add>}; <add> <add>// <add>// GEOMETRY TEST HELPERS <add>// <add> <add>function checkGeometryClone( geom ) { <add> <add> // Clone <add> var copy = geom.clone(); <add> QUnit.assert.notEqual( copy.uuid, geom.uuid, "clone uuid should differ from original" ); <add> QUnit.assert.notEqual( copy.id, geom.id, "clone id should differ from original" ); <add> <add> var excludedProperties = [ 'parameters', 'widthSegments', 'heightSegments', 'depthSegments' ]; <add> <add> var differingProp = getDifferingProp( geom, copy, excludedProperties ); <add> QUnit.assert.ok( differingProp === undefined, 'properties are equal' ); <add> <add> differingProp = getDifferingProp( copy, geom, excludedProperties ); <add> QUnit.assert.ok( differingProp === undefined, 'properties are equal' ); <add> <add> // json round trip with clone <add> checkGeometryJsonRoundtrip( copy ); <add> <add>} <add> <add>function getDifferingProp( geometryA, geometryB, excludedProperties ) { <add> <add> excludedProperties = excludedProperties || []; <add> <add> var geometryKeys = Object.keys( geometryA ); <add> var cloneKeys = Object.keys( geometryB ); <add> <add> var differingProp = undefined; <add> <add> for ( var i = 0, l = geometryKeys.length; i < l; i ++ ) { <add> <add> var key = geometryKeys[ i ]; <add> <add> if ( excludedProperties.indexOf( key ) >= 0 ) continue; <add> <add> if ( cloneKeys.indexOf( key ) < 0 ) { <add> <add> differingProp = key; <add> break; <add> <add> } <add> <add> } <add> <add> return differingProp; <add> <add>} <add> <add>// Compare json file with its source geometry. <add>function checkGeometryJsonWriting( geom, json ) { <add> <add> QUnit.assert.equal( json.metadata.version, "4.5", "check metadata version" ); <add> QUnit.assert.equalKey( geom, json, 'type' ); <add> QUnit.assert.equalKey( geom, json, 'uuid' ); <add> QUnit.assert.equal( json.id, undefined, "should not persist id" ); <add> <add> var params = geom.parameters; <add> if ( ! params ) { <add> <add> return; <add> <add> } <add> <add> // All parameters from geometry should be persisted. <add> var keys = Object.keys( params ); <add> for ( var i = 0, l = keys.length; i < l; i ++ ) { <add> <add> QUnit.assert.equalKey( params, json, keys[ i ] ); <add> <add> } <add> <add> // All parameters from json should be transfered to the geometry. <add> // json is flat. Ignore first level json properties that are not parameters. <add> var notParameters = [ "metadata", "uuid", "type" ]; <add> var keys = Object.keys( json ); <add> for ( var i = 0, l = keys.length; i < l; i ++ ) { <add> <add> var key = keys[ i ]; <add> if ( notParameters.indexOf( key ) === - 1 ) QUnit.assert.equalKey( params, json, key ); <add> <add> } <add> <add>} <add> <add>// Check parsing and reconstruction of json geometry <add>function checkGeometryJsonReading( json, geom ) { <add> <add> var wrap = [ json ]; <add> <add> var loader = new THREE.ObjectLoader(); <add> var output = loader.parseGeometries( wrap ); <add> <add> QUnit.assert.ok( output[ geom.uuid ], 'geometry matching source uuid not in output' ); <add> // QUnit.assert.smartEqual( output[ geom.uuid ], geom, 'Reconstruct geometry from ObjectLoader' ); <add> <add> var differing = getDifferingProp( output[ geom.uuid ], geom, [ 'bones' ] ); <add> if ( differing ) console.log( differing ); <add> <add> var excludedProperties = [ 'bones' ]; <add> <add> var differingProp = getDifferingProp( output[ geom.uuid ], geom, excludedProperties ); <add> QUnit.assert.ok( differingProp === undefined, 'properties are equal' ); <add> <add> differingProp = getDifferingProp( geom, output[ geom.uuid ], excludedProperties ); <add> QUnit.assert.ok( differingProp === undefined, 'properties are equal' ); <add> <add>} <add> <add>// Verify geom -> json -> geom <add>function checkGeometryJsonRoundtrip( geom ) { <add> <add> var json = geom.toJSON(); <add> checkGeometryJsonWriting( geom, json ); <add> checkGeometryJsonReading( json, geom ); <add> <add>} <add> <add>// Look for undefined and NaN values in numerical fieds. <add>function checkFinite( geom ) { <add> <add> var allVerticesAreFinite = true; <add> <add> var vertices = geom.vertices || []; <add> <add> for ( var i = 0, l = vertices.length; i < l; i ++ ) { <add> <add> var v = geom.vertices[ i ]; <add> <add> if ( ! ( isFinite( v.x ) || isFinite( v.y ) || isFinite( v.z ) ) ) { <add> <add> allVerticesAreFinite = false; <add> break; <add> <add> } <add> <add> } <add> <add> // TODO Buffers, normal, etc. <add> <add> QUnit.assert.ok( allVerticesAreFinite, "contains only finite coordinates" ); <add> <add>} <add> <add>// Run common geometry tests. <add>function runStdGeometryTests( assert, geometries ) { <add> <add> for ( var i = 0, l = geometries.length; i < l; i ++ ) { <add> <add> var geom = geometries[ i ]; <add> <add> checkFinite( geom ); <add> <add> // Clone <add> checkGeometryClone( geom ); <add> <add> // json round trip <add> checkGeometryJsonRoundtrip( geom ); <add> <add> } <add> <add>} <add> <add>// <add>// LIGHT TEST HELPERS <add>// <add> <add>// Run common light tests. <add>function runStdLightTests( lights ) { <add> <add> for ( var i = 0, l = lights.length; i < l; i ++ ) { <add> <add> var light = lights[ i ]; <add> <add> // copy and clone <add> checkLightCopyClone( light ); <add> <add> // THREE.Light doesn't get parsed by ObjectLoader as it's only <add> // used as an abstract base class - so we skip the JSON tests <add> if ( light.type !== "Light" ) { <add> <add> // json round trip <add> checkLightJsonRoundtrip( light ); <add> <add> } <add> <add> } <add> <add>} <add> <add>function checkLightCopyClone( light ) { <add> <add> // copy <add> var newLight = new light.constructor( 0xc0ffee ); <add> newLight.copy( light ); <add> <add> QUnit.assert.notEqual( newLight.uuid, light.uuid, "Copied light's UUID differs from original" ); <add> QUnit.assert.notEqual( newLight.id, light.id, "Copied light's id differs from original" ); <add> QUnit.assert.smartEqual( newLight, light, "Copied light is equal to original" ); <add> <add> // real copy? <add> newLight.color.setHex( 0xc0ffee ); <add> QUnit.assert.notStrictEqual( <add> newLight.color.getHex(), light.color.getHex(), "Copied light is independent from original" <add> ); <add> <add> // Clone <add> var clone = light.clone(); // better get a new var <add> QUnit.assert.notEqual( clone.uuid, light.uuid, "Cloned light's UUID differs from original" ); <add> QUnit.assert.notEqual( clone.id, light.id, "Clone light's id differs from original" ); <add> QUnit.assert.smartEqual( clone, light, "Clone light is equal to original" ); <add> <add> // real clone? <add> clone.color.setHex( 0xc0ffee ); <add> QUnit.assert.notStrictEqual( <add> clone.color.getHex(), light.color.getHex(), "Clone light is independent from original" <add> ); <add> <add> if ( light.type !== "Light" ) { <add> <add> // json round trip with clone <add> checkLightJsonRoundtrip( clone ); <add> <add> } <add> <add>} <add> <add>// Compare json file with its source Light. <add>function checkLightJsonWriting( light, json ) { <add> <add> QUnit.assert.equal( json.metadata.version, "4.5", "check metadata version" ); <add> <add> var object = json.object; <add> QUnit.assert.equalKey( light, object, 'type' ); <add> QUnit.assert.equalKey( light, object, 'uuid' ); <add> QUnit.assert.equal( object.id, undefined, "should not persist id" ); <add> <add>} <add> <add>// Check parsing and reconstruction of json Light <add>function checkLightJsonReading( json, light ) { <add> <add> var loader = new THREE.ObjectLoader(); <add> var outputLight = loader.parse( json ); <add> <add> QUnit.assert.smartEqual( outputLight, light, 'Reconstruct Light from ObjectLoader' ); <add> <add>} <add> <add>// Verify light -> json -> light <add>function checkLightJsonRoundtrip( light ) { <add> <add> var json = light.toJSON(); <add> checkLightJsonWriting( light, json ); <add> checkLightJsonReading( json, light ); <add> <add>}
2
Python
Python
remove xfail on test #910
040751ad17c96a6e6bf2c0d70e7e789cbd8dd7d6
<ide><path>spacy/tests/regression/test_issue910.py <ide> def temp_save_model(model): <ide> <ide> <ide> <del>@pytest.mark.xfail <ide> @pytest.mark.models <ide> def test_issue910(train_data, additional_entity_types): <ide> '''Test that adding entities and resuming training works passably OK. <ide> def test_issue910(train_data, additional_entity_types): <ide> ents_before_train = [(ent.label_, ent.text) for ent in doc.ents] <ide> # Fine tune the ner model <ide> for entity_type in additional_entity_types: <del> if entity_type not in nlp.entity.cfg['actions']['1']: <del> nlp.entity.add_label(entity_type) <add> nlp.entity.add_label(entity_type) <ide> <del> nlp.entity.learn_rate = 0.001 <del> for itn in range(4): <add> nlp.entity.model.learn_rate = 0.001 <add> for itn in range(10): <ide> random.shuffle(train_data) <ide> for raw_text, entity_offsets in train_data: <ide> doc = nlp.make_doc(raw_text) <ide> def test_issue910(train_data, additional_entity_types): <ide> # Load the fine tuned model <ide> loaded_ner = EntityRecognizer.load(model_dir, nlp.vocab) <ide> <del> for entity_type in additional_entity_types: <del> if entity_type not in loaded_ner.cfg['actions']['1']: <del> loaded_ner.add_label(entity_type) <del> <del> doc = nlp(u"I am looking for a restaurant in Berlin", entity=False) <del> nlp.tagger(doc) <del> loaded_ner(doc) <del> <del> ents_after_train = [(ent.label_, ent.text) for ent in doc.ents] <del> assert ents_before_train == ents_after_train <add> for raw_text, entity_offsets in train_data: <add> doc = nlp.make_doc(raw_text) <add> nlp.tagger(doc) <add> loaded_ner(doc) <add> ents = {(ent.start_char, ent.end_char): ent.label_ for ent in doc.ents} <add> for start, end, label in entity_offsets: <add> if (start, end) not in ents: <add> print(ents) <add> assert ents[(start, end)] == label
1
Mixed
Ruby
ignore config.eager_load=true for rake
9cac69c602f57e397fe01d866cb24ce1781606d4
<ide><path>railties/CHANGELOG.md <add>* Fix `rake environment` to do not eager load modules <add> <add> *Paul Nikitochkin* <add> <ide> * Fix `rake notes` to look into `*.sass` files <ide> <ide> *Yuri Artemev* <ide><path>railties/lib/rails/application.rb <ide> def run_tasks_blocks(app) #:nodoc: <ide> require "rails/tasks" <ide> config = self.config <ide> task :environment do <del> config.eager_load = false <add> ActiveSupport.on_load(:before_initialize) { config.eager_load = false } <add> <ide> require_environment! <ide> end <ide> end <ide><path>railties/test/application/assets_test.rb <ide> def test_precompile_does_not_hit_the_database <ide> class UsersController < ApplicationController; end <ide> eoruby <ide> app_file "app/models/user.rb", <<-eoruby <del> class User < ActiveRecord::Base; end <add> class User < ActiveRecord::Base; raise 'should not be reached'; end <ide> eoruby <ide> <ide> ENV['RAILS_ENV'] = 'production' <ide><path>railties/test/application/rake_test.rb <ide> class RakeTest < ActiveSupport::TestCase <ide> def setup <ide> build_app <ide> boot_rails <del> FileUtils.rm_rf("#{app_path}/config/environments") <ide> end <ide> <ide> def teardown <ide> def test_initializers_are_executed_in_rake_tasks <ide> assert_match "Doing something...", output <ide> end <ide> <del> def test_does_not_explode_when_accessing_a_model_with_eager_load <add> def test_does_not_explode_when_accessing_a_model <ide> add_to_config <<-RUBY <del> config.eager_load = true <del> <ide> rake_tasks do <ide> task do_nothing: :environment do <ide> Hello.new.world <ide> end <ide> end <ide> RUBY <ide> <del> app_file "app/models/hello.rb", <<-RUBY <del> class Hello <del> def world <del> puts "Hello world" <add> app_file 'app/models/hello.rb', <<-RUBY <add> class Hello <add> def world <add> puts 'Hello world' <add> end <ide> end <del> end <ide> RUBY <ide> <del> output = Dir.chdir(app_path){ `rake do_nothing` } <del> assert_match "Hello world", output <add> output = Dir.chdir(app_path) { `rake do_nothing` } <add> assert_match 'Hello world', output <ide> end <ide> <del> def test_should_not_eager_load_model_path_for_rake <add> def test_should_not_eager_load_model_for_rake <ide> add_to_config <<-RUBY <del> config.eager_load = true <del> <ide> rake_tasks do <ide> task do_nothing: :environment do <ide> end <ide> end <ide> RUBY <ide> <del> app_file "app/models/hello.rb", <<-RUBY <del> raise 'should not be pre-required for rake even `eager_load=true`' <add> add_to_env_config 'production', <<-RUBY <add> config.eager_load = true <add> RUBY <add> <add> app_file 'app/models/hello.rb', <<-RUBY <add> raise 'should not be pre-required for rake even eager_load=true' <ide> RUBY <ide> <del> Dir.chdir(app_path){ `rake do_nothing` } <add> Dir.chdir(app_path) do <add> assert system('rake do_nothing RAILS_ENV=production'), <add> 'should not be pre-required for rake even eager_load=true' <add> end <ide> end <ide> <ide> def test_code_statistics_sanity
4
Javascript
Javascript
fix a small issue with the 'name' table
1037fdf2ada515ee46c6f63fe4e9d8f7a4df0a28
<ide><path>fonts.js <ide> var Font = (function Font() { <ide> var nameTable = <ide> "\x00\x00" + // format <ide> string16(namesRecordCount) + // Number of names Record <del> string16(namesRecordCount * 12 + 6); // Storage <add> string16(namesRecordCount * 12 + 6); // Offset to start of storage <ide> <ide> // Build the name records field <ide> var strOffset = 0; <ide> var Font = (function Font() { <ide> platforms[i] + // platform ID <ide> encodings[i] + // encoding ID <ide> languages[i] + // language ID <del> string16(i) + // name ID <add> string16(j) + // name ID <ide> string16(str.length) + <ide> string16(strOffset); <ide> nameTable += nameRecord; <ide> strOffset += str.length; <ide> } <ide> } <ide> <del> nameTable += strings.join("") + stringsUnicode.join(""); <add> nameTable += strings.join("") + stringsUnicode.join(""); <ide> return nameTable; <del> } <add> }; <ide> <ide> function isFixedPitch(glyphs) { <ide> for (var i = 0; i < glyphs.length - 1; i++) {
1
Javascript
Javascript
remove trailing white spaces from all source files
805e083c243655bfaed3c5431dc0f402cb27fcb4
<ide><path>example/personalLog/test/personalLogSpec.js <ide> describe('example.personalLog.LogCtrl', function() { <ide> beforeEach(function() { <ide> logCtrl = createNotesCtrl(); <ide> }); <del> <add> <ide> <ide> it('should initialize notes with an empty array', function() { <ide> expect(logCtrl.logs).toEqual([]); <ide> describe('example.personalLog.LogCtrl', function() { <ide> it('should add newMsg to logs as a log entry', function() { <ide> logCtrl.newMsg = 'first log message'; <ide> logCtrl.addLog(); <del> <add> <ide> expect(logCtrl.logs.length).toBe(1); <ide> expect(logCtrl.logs[0].msg).toBe('first log message'); <ide> <ide><path>scenario/datastore-scenarios.js <ide> angular.scenarioDef.datastore = { <ide> $before:[ <del> {Given:"dataset", <add> {Given:"dataset", <ide> dataset:{ <del> Book:[{$id:'moby', name:"Moby Dick"}, <add> Book:[{$id:'moby', name:"Moby Dick"}, <ide> {$id:'gadsby', name:'Great Gadsby'}] <ide> } <ide> }, <ide> {Given:"browser", at:"datastore.html#book=moby"}, <ide> ], <ide> checkLoadBook:[ <ide> {Then:"drainRequestQueue"}, <del> <add> <ide> {Then:"text", at:"{{book.$id}}", should_be:"moby"}, <ide> {Then:"text", at:"li[$index=0] {{book.name}}", should_be:"Great Gahdsby"}, <ide> {Then:"text", at:"li[$index=0] {{book.name}}", should_be:"Moby Dick"}, <del> <add> <ide> ] <ide> }; <ide><path>src/widgets.js <ide> angularWidget('a', function() { <ide> * <ide> * @description <ide> * The `ng:repeat` widget instantiates a template once per item from a collection. The collection is <del> * enumerated with the `ng:repeat-index` attribute, starting from 0. Each template instance gets <del> * its own scope, where the given loop variable is set to the current collection item, and `$index` <add> * enumerated with the `ng:repeat-index` attribute, starting from 0. Each template instance gets <add> * its own scope, where the given loop variable is set to the current collection item, and `$index` <ide> * is set to the item index or key. <ide> * <ide> * Special properties are exposed on the local scope of each template instance, including: <ide> * <ide> * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) <del> * * `$position` – `{string}` – position of the repeated element in the iterator. One of: <add> * * `$position` – `{string}` – position of the repeated element in the iterator. One of: <ide> * * `'first'`, <del> * * `'middle'` <add> * * `'middle'` <ide> * * `'last'` <ide> * <ide> * Note: Although `ng:repeat` looks like a directive, it is actually an attribute widget. <ide><path>test/BrowserSpecs.js <ide> describe('browser', function(){ <ide> expect(code).toEqual(202); <ide> expect(response).toEqual('RESPONSE'); <ide> }); <del> <add> <ide> it('should not set Content-type header for GET requests', function() { <ide> browser.xhr('GET', 'URL', 'POST-DATA', function(c, r) {}); <ide>
4
Python
Python
add lowercase lemma to tokenizer exceptions
1d237664af28dd1685acdd11e94c9d1aa8cd1714
<ide><path>spacy/en/tokenizer_exceptions.py <ide> for word in ["who", "what", "when", "where", "why", "how", "there", "that"]: <ide> for orth in [word, word.title()]: <ide> EXC[orth + "'s"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "'s"} <ide> ] <ide> <ide> EXC[orth + "s"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "s"} <ide> ] <ide> <ide> EXC[orth + "'ll"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "'ll", LEMMA: "will", TAG: "MD"} <ide> ] <ide> <ide> EXC[orth + "ll"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "ll", LEMMA: "will", TAG: "MD"} <ide> ] <ide> <ide> EXC[orth + "'ll've"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "ll", LEMMA: "will", TAG: "MD"}, <ide> {ORTH: "ve", LEMMA: "have", TAG: "VB"} <ide> ] <ide> <ide> EXC[orth + "llve"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "ll", LEMMA: "will", TAG: "MD"}, <ide> {ORTH: "ve", LEMMA: "have", TAG: "VB"} <ide> ] <ide> <ide> EXC[orth + "'re"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "'re", LEMMA: "be", NORM: "are"} <ide> ] <ide> <ide> EXC[orth + "re"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "re", LEMMA: "be", NORM: "are"} <ide> ] <ide> <ide> ] <ide> <ide> EXC[orth + "ve"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "'ve", LEMMA: "have", TAG: "VB"} <ide> ] <ide> <ide> EXC[orth + "'d"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "'d"} <ide> ] <ide> <ide> EXC[orth + "d"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "d"} <ide> ] <ide> <ide> EXC[orth + "'d've"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "'d", LEMMA: "would", TAG: "MD"}, <ide> {ORTH: "'ve", LEMMA: "have", TAG: "VB"} <ide> ] <ide> <ide> EXC[orth + "dve"] = [ <del> {ORTH: orth}, <add> {ORTH: orth, LEMMA: word}, <ide> {ORTH: "d", LEMMA: "would", TAG: "MD"}, <ide> {ORTH: "ve", LEMMA: "have", TAG: "VB"} <ide> ]
1
Javascript
Javascript
use performconcurrentworkonroot for "sync default"
ef37d55b68ddc45d465b84ea2ce30e8328297b2d
<ide><path>packages/react-reconciler/src/ReactFiberLane.new.js <ide> export function getNextLanes(root: FiberRoot, wipLanes: Lanes): Lanes { <ide> // Default priority updates should not interrupt transition updates. The <ide> // only difference between default updates and transition updates is that <ide> // default updates do not support refresh transitions. <add> // TODO: This applies to sync default updates, too. Which is probably what <add> // we want for default priority events, but not for continuous priority <add> // events like hover. <ide> (nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) <ide> ) { <ide> // Keep working on the existing in-progress tree. Do not interrupt. <ide><path>packages/react-reconciler/src/ReactFiberLane.old.js <ide> export function getNextLanes(root: FiberRoot, wipLanes: Lanes): Lanes { <ide> // Default priority updates should not interrupt transition updates. The <ide> // only difference between default updates and transition updates is that <ide> // default updates do not support refresh transitions. <add> // TODO: This applies to sync default updates, too. Which is probably what <add> // we want for default priority events, but not for continuous priority <add> // events like hover. <ide> (nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) <ide> ) { <ide> // Keep working on the existing in-progress tree. Do not interrupt. <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) { <ide> <ide> // Schedule a new callback. <ide> let newCallbackNode; <del> if ( <del> enableSyncDefaultUpdates && <del> (newCallbackPriority === DefaultLane || <del> newCallbackPriority === DefaultHydrationLane) <del> ) { <del> newCallbackNode = scheduleCallback( <del> ImmediateSchedulerPriority, <del> performSyncWorkOnRoot.bind(null, root), <del> ); <del> } else if (newCallbackPriority === SyncLane) { <add> if (newCallbackPriority === SyncLane) { <ide> // Special case: Sync React callbacks are scheduled on a special <ide> // internal queue <ide> scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); <ide> function performConcurrentWorkOnRoot(root, didTimeout) { <ide> return null; <ide> } <ide> <del> let exitStatus = renderRootConcurrent(root, lanes); <add> let exitStatus = <add> enableSyncDefaultUpdates && <add> (includesSomeLane(lanes, DefaultLane) || <add> includesSomeLane(lanes, DefaultHydrationLane)) <add> ? // Time slicing is disabled for default updates in this root. <add> renderRootSync(root, lanes) <add> : renderRootConcurrent(root, lanes); <ide> if (exitStatus !== RootIncomplete) { <ide> if (exitStatus === RootErrored) { <ide> executionContext |= RetryAfterError; <ide> function performSyncWorkOnRoot(root) { <ide> // rendering it before rendering the rest of the expired work. <ide> lanes = workInProgressRootRenderLanes; <ide> } <del> } else if ( <del> !( <del> enableSyncDefaultUpdates && <del> (includesSomeLane(lanes, DefaultLane) || <del> includesSomeLane(lanes, DefaultHydrationLane)) <del> ) <del> ) { <add> } else { <ide> // There's no remaining sync work left. <ide> ensureRootIsScheduled(root, now()); <ide> return null; <ide> function performSyncWorkOnRoot(root) { <ide> const finishedWork: Fiber = (root.current.alternate: any); <ide> root.finishedWork = finishedWork; <ide> root.finishedLanes = lanes; <del> if ( <del> enableSyncDefaultUpdates && <del> (includesSomeLane(lanes, DefaultLane) || <del> includesSomeLane(lanes, DefaultHydrationLane)) <del> ) { <del> finishConcurrentRender(root, exitStatus, lanes); <del> } else { <del> commitRoot(root); <del> } <add> commitRoot(root); <ide> <ide> // Before exiting, make sure there's a callback scheduled for the next <ide> // pending level. <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js <ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) { <ide> <ide> // Schedule a new callback. <ide> let newCallbackNode; <del> if ( <del> enableSyncDefaultUpdates && <del> (newCallbackPriority === DefaultLane || <del> newCallbackPriority === DefaultHydrationLane) <del> ) { <del> newCallbackNode = scheduleCallback( <del> ImmediateSchedulerPriority, <del> performSyncWorkOnRoot.bind(null, root), <del> ); <del> } else if (newCallbackPriority === SyncLane) { <add> if (newCallbackPriority === SyncLane) { <ide> // Special case: Sync React callbacks are scheduled on a special <ide> // internal queue <ide> scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); <ide> function performConcurrentWorkOnRoot(root, didTimeout) { <ide> return null; <ide> } <ide> <del> let exitStatus = renderRootConcurrent(root, lanes); <add> let exitStatus = <add> enableSyncDefaultUpdates && <add> (includesSomeLane(lanes, DefaultLane) || <add> includesSomeLane(lanes, DefaultHydrationLane)) <add> ? // Time slicing is disabled for default updates in this root. <add> renderRootSync(root, lanes) <add> : renderRootConcurrent(root, lanes); <ide> if (exitStatus !== RootIncomplete) { <ide> if (exitStatus === RootErrored) { <ide> executionContext |= RetryAfterError; <ide> function performSyncWorkOnRoot(root) { <ide> // rendering it before rendering the rest of the expired work. <ide> lanes = workInProgressRootRenderLanes; <ide> } <del> } else if ( <del> !( <del> enableSyncDefaultUpdates && <del> (includesSomeLane(lanes, DefaultLane) || <del> includesSomeLane(lanes, DefaultHydrationLane)) <del> ) <del> ) { <add> } else { <ide> // There's no remaining sync work left. <ide> ensureRootIsScheduled(root, now()); <ide> return null; <ide> function performSyncWorkOnRoot(root) { <ide> const finishedWork: Fiber = (root.current.alternate: any); <ide> root.finishedWork = finishedWork; <ide> root.finishedLanes = lanes; <del> if ( <del> enableSyncDefaultUpdates && <del> (includesSomeLane(lanes, DefaultLane) || <del> includesSomeLane(lanes, DefaultHydrationLane)) <del> ) { <del> finishConcurrentRender(root, exitStatus, lanes); <del> } else { <del> commitRoot(root); <del> } <add> commitRoot(root); <ide> <ide> // Before exiting, make sure there's a callback scheduled for the next <ide> // pending level. <ide><path>packages/react-reconciler/src/__tests__/ReactExpiration-test.js <ide> describe('ReactExpiration', () => { <ide> flushNextRenderIfExpired(); <ide> expect(Scheduler).toHaveYielded([]); <ide> <del> if (gate(flags => flags.enableSyncDefaultUpdates)) { <del> // TODO: Why is this flushed? <del> expect(ReactNoop).toMatchRenderedOutput('Hi'); <del> } else { <del> expect(ReactNoop).toMatchRenderedOutput(null); <del> } <add> expect(ReactNoop).toMatchRenderedOutput(null); <ide> <ide> // Advance the time some more to expire the update. <ide> Scheduler.unstable_advanceTime(10000); <ide> describe('ReactExpiration', () => { <ide> // Advancing by ~5 seconds should be sufficient to expire the update. (I <ide> // used a slightly larger number to allow for possible rounding.) <ide> Scheduler.unstable_advanceTime(6000); <del> <del> ReactNoop.render('Hi'); <ide> flushNextRenderIfExpired(); <ide> expect(Scheduler).toHaveYielded([]); <ide> expect(ReactNoop).toMatchRenderedOutput('Hi'); <ide><path>packages/react-reconciler/src/__tests__/ReactFlushSync-test.js <ide> describe('ReactFlushSync', () => { <ide> // The passive effect will schedule a sync update and a normal update. <ide> // They should commit in two separate batches. First the sync one. <ide> expect(() => { <del> if (gate(flags => flags.enableSyncDefaultUpdates)) { <del> expect(Scheduler).toFlushUntilNextPaint(['1, 0', '1, 1']); <del> } else { <del> expect(Scheduler).toFlushUntilNextPaint(['1, 0']); <del> } <add> expect(Scheduler).toFlushUntilNextPaint(['1, 0']); <ide> }).toErrorDev('flushSync was called from inside a lifecycle method'); <ide> <ide> // The remaining update is not sync <ide> ReactNoop.flushSync(); <ide> expect(Scheduler).toHaveYielded([]); <ide> <ide> // Now flush it. <del> if (gate(flags => flags.enableSyncDefaultUpdates)) { <del> // With sync default updates, passive effects are synchronously flushed. <del> expect(Scheduler).toHaveYielded([]); <del> } else { <del> expect(Scheduler).toFlushUntilNextPaint(['1, 1']); <del> } <add> expect(Scheduler).toFlushUntilNextPaint(['1, 1']); <ide> }); <ide> expect(root).toMatchRenderedOutput('1, 1'); <ide> }); <ide><path>packages/react-reconciler/src/__tests__/ReactHooksWithNoopRenderer-test.js <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> setParentState(false); <ide> }); <ide> if (gate(flags => flags.enableSyncDefaultUpdates)) { <add> // TODO: Default updates do not interrupt transition updates, to <add> // prevent starvation. However, when sync default updates are enabled, <add> // continuous updates are treated like default updates. In this case, <add> // we probably don't want this behavior; continuous should be allowed <add> // to interrupt. <ide> expect(Scheduler).toFlushUntilNextPaint([ <del> // TODO: why do the children render and fire effects? <ide> 'Child two render', <ide> 'Child one commit', <ide> 'Child two commit', <del> 'Parent false render', <del> 'Parent false commit', <del> ]); <del> } else { <del> expect(Scheduler).toFlushUntilNextPaint([ <del> 'Parent false render', <del> 'Parent false commit', <ide> ]); <ide> } <add> expect(Scheduler).toFlushUntilNextPaint([ <add> 'Parent false render', <add> 'Parent false commit', <add> ]); <ide> <ide> // Schedule updates for children too (which should be ignored) <ide> setChildStates.forEach(setChildState => setChildState(2)); <ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalUpdates-test.js <ide> describe('ReactIncrementalUpdates', () => { <ide> ReactNoop.render(<Foo />); <ide> expect(Scheduler).toFlushAndYieldThrough(['commit']); <ide> <del> if (gate(flags => flags.enableSyncDefaultUpdates)) { <del> // TODO: should deferredUpdates flush sync with the default update? <del> expect(state).toEqual({a: 'a', b: 'b', c: 'c'}); <del> expect(Scheduler).toFlushWithoutYielding(); <del> } else { <del> expect(state).toEqual({a: 'a'}); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(state).toEqual({a: 'a', b: 'b', c: 'c'}); <del> } <add> expect(state).toEqual({a: 'a'}); <add> expect(Scheduler).toFlushWithoutYielding(); <add> expect(state).toEqual({a: 'a', b: 'b', c: 'c'}); <ide> }); <ide> <ide> it('applies updates with equal priority in insertion order', () => { <ide><path>packages/react-reconciler/src/__tests__/useMutableSource-test.internal.js <ide> describe('useMutableSource', () => { <ide> mutateB('b0'); <ide> }); <ide> // Finish the current render <del> if (gate(flags => flags.enableSyncDefaultUpdates)) { <del> // Default sync will flush both without yielding <del> expect(Scheduler).toFlushUntilNextPaint(['c', 'a0']); <del> } else { <del> expect(Scheduler).toFlushUntilNextPaint(['c']); <del> // a0 will re-render because of the mutation update. But it should show <del> // the latest value, not the intermediate one, to avoid tearing with b. <del> expect(Scheduler).toFlushUntilNextPaint(['a0']); <del> } <add> expect(Scheduler).toFlushUntilNextPaint(['c']); <add> // a0 will re-render because of the mutation update. But it should show <add> // the latest value, not the intermediate one, to avoid tearing with b. <add> expect(Scheduler).toFlushUntilNextPaint(['a0']); <ide> <ide> expect(root).toMatchRenderedOutput('a0b0c'); <ide> // We should be done.
9
Javascript
Javascript
intercept property changes instead of sets
27a6c57b0d15766b65a8ae1f74e1ab37e3493add
<ide><path>packages/ember-htmlbars/tests/integration/select_in_template_test.js <ide> function testValueBinding(templateString) { <ide> equal(selectEl.selectedIndex, 1, "The DOM is updated to reflect the new selection"); <ide> } <ide> <del>QUnit.skip("select element should correctly initialize and update selectedIndex and bound properties when using valueBinding [DEPRECATED]", function() { <add>QUnit.test("select element should correctly initialize and update selectedIndex and bound properties when using valueBinding [DEPRECATED]", function() { <ide> expectDeprecation(`You're using legacy binding syntax: valueBinding="view.val" @ 1:176 in (inline). Please replace with value=view.val`); <ide> <ide> testValueBinding( <ide> QUnit.skip("select element should correctly initialize and update selectedIndex <ide> ); <ide> }); <ide> <del>QUnit.skip("select element should correctly initialize and update selectedIndex and bound properties when using valueBinding", function() { <add>QUnit.test("select element should correctly initialize and update selectedIndex and bound properties when using valueBinding", function() { <ide> testValueBinding( <ide> '{{view view.selectView viewName="select"' + <ide> ' content=view.collection' + <ide><path>packages/ember-metal/lib/property_events.js <ide> import { <ide> accumulateListeners <ide> } from "ember-metal/events"; <ide> import ObserverSet from "ember-metal/observer_set"; <add>import { symbol } from "ember-metal/utils"; <add> <add>export let PROPERTY_DID_CHANGE = symbol("PROPERTY_DID_CHANGE"); <ide> <ide> var beforeObserverSet = new ObserverSet(); <ide> var observerSet = new ObserverSet(); <ide> function propertyDidChange(obj, keyName) { <ide> desc.didChange(obj, keyName); <ide> } <ide> <add> if (obj[PROPERTY_DID_CHANGE]) { <add> obj[PROPERTY_DID_CHANGE](keyName); <add> } <add> <ide> if (!watching && keyName !== 'length') { <ide> return; <ide> } <ide><path>packages/ember-metal/lib/property_set.js <ide> import Ember from "ember-metal/core"; <ide> import { _getPath as getPath } from "ember-metal/property_get"; <ide> import { <add> PROPERTY_DID_CHANGE, <ide> propertyWillChange, <ide> propertyDidChange <ide> } from "ember-metal/property_events"; <ide> export function set(obj, keyName, value, tolerant) { <ide> } <ide> } else { <ide> obj[keyName] = value; <add> if (obj[PROPERTY_DID_CHANGE]) { <add> obj[PROPERTY_DID_CHANGE](keyName); <add> } <ide> } <ide> } <ide> return value; <ide><path>packages/ember-views/lib/compat/attrs-proxy.js <ide> import { Mixin } from "ember-metal/mixin"; <ide> import { on } from "ember-metal/events"; <ide> import { symbol } from "ember-metal/utils"; <ide> import objectKeys from "ember-metal/keys"; <del>import { INTERCEPT_SET, UNHANDLED_SET } from 'ember-metal/property_set'; <add>import { PROPERTY_DID_CHANGE } from "ember-metal/property_events"; <ide> //import run from "ember-metal/run_loop"; <ide> <ide> export function deprecation(key) { <ide> let AttrsProxyMixin = { <ide> //} <ide> }; <ide> <del>AttrsProxyMixin[INTERCEPT_SET] = function(obj, key, value) { <del> let attrs = obj.attrs; <add>AttrsProxyMixin[PROPERTY_DID_CHANGE] = function(key) { <add> let attrs = this.attrs; <ide> <del> if (key === 'attrs') { return UNHANDLED_SET; } <del> if (!attrs || !(key in attrs)) { <del> return UNHANDLED_SET; <del> } <del> <del> let possibleCell = attrs[key]; <del> <del> if (!possibleCell[MUTABLE_CELL]) { <del> return UNHANDLED_SET; <del> // This would ideally be an error, but there are cases where immutable <del> // data from attrs is copied into local state, setting that <del> // state is legitimate. <del> //throw new Error(`You cannot set ${key} because attrs.${key} is not mutable`); <del> } <add> if (attrs && key in attrs) { <add> let possibleCell = attrs[key]; <ide> <del> possibleCell.update(value); <del> <del> if (key in obj) { <del> return UNHANDLED_SET; <add> if (possibleCell[MUTABLE_CELL]) { <add> possibleCell.update(get(this, key)); <add> } <ide> } <del> <del> return value; <ide> }; <ide> <ide> export default Mixin.create(AttrsProxyMixin); <ide><path>packages/ember-views/tests/views/view_test.js <ide> QUnit.test("propagates dependent-key invalidated sets upstream", function() { <ide> equal(view.get('parentProp'), 'new-value', 'new value is propagated across template'); <ide> }); <ide> <del>QUnit.skip("propagates dependent-key invalidated bindings upstream", function() { <add>QUnit.test("propagates dependent-key invalidated bindings upstream", function() { <ide> view = EmberView.create({ <ide> parentProp: 'parent-value', <ide> template: compile("{{view view.childView childProp=view.parentProp}}"), <ide> QUnit.skip("propagates dependent-key invalidated bindings upstream", function() <ide> <ide> equal(view.get('parentProp'), 'parent-value', 'precond - parent value is there'); <ide> var childView = view.get('childView'); <del> childView.set('dependencyProp', 'new-value'); <add> run(() => childView.set('dependencyProp', 'new-value')); <ide> equal(childView.get('childProp'), 'new-value', 'pre-cond - new value is propagated to CP'); <ide> equal(view.get('parentProp'), 'new-value', 'new value is propagated across template'); <ide> });
5
PHP
PHP
apply fixes from styleci
f49ea906ac371dc343c6d878f13796f08561cfb0
<ide><path>src/Illuminate/Session/DatabaseSessionHandler.php <ide> public function read($sessionId) <ide> */ <ide> protected function expired($session) <ide> { <del> return (isset($session->last_activity) && <del> $session->last_activity < Carbon::now()->subMinutes($this->minutes)->getTimestamp()); <add> return isset($session->last_activity) && <add> $session->last_activity < Carbon::now()->subMinutes($this->minutes)->getTimestamp(); <ide> } <ide> <ide> /** <ide> protected function getDefaultPayload($data) <ide> { <ide> $payload = [ <ide> 'payload' => base64_encode($data), <del> 'last_activity' => Carbon::now()->getTimestamp() <add> 'last_activity' => Carbon::now()->getTimestamp(), <ide> ]; <ide> <ide> if (! $this->container) {
1
Javascript
Javascript
combine ng-bind-html and ng-bind-html-unsafe
dae694739b9581bea5dbc53522ec00d87b26ae55
<ide><path>Gruntfile.js <ide> module.exports = function(grunt) { <ide> dest: 'build/angular-sanitize.js', <ide> src: util.wrap([ <ide> 'src/ngSanitize/sanitize.js', <del> 'src/ngSanitize/directive/ngBindHtml.js', <ide> 'src/ngSanitize/filter/linky.js' <ide> ], 'module') <ide> }, <ide><path>angularFiles.js <ide> angularFiles = { <ide> 'src/ngRoute/routeParams.js', <ide> 'src/ngRoute/directive/ngView.js', <ide> 'src/ngSanitize/sanitize.js', <del> 'src/ngSanitize/directive/ngBindHtml.js', <ide> 'src/ngSanitize/filter/linky.js', <ide> 'src/ngMock/angular-mocks.js', <ide> 'src/ngMobile/mobile.js', <ide><path>src/AngularPublic.js <ide> function publishExternalAPI(angular){ <ide> style: styleDirective, <ide> option: optionDirective, <ide> ngBind: ngBindDirective, <del> ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective, <add> ngBindHtml: ngBindHtmlDirective, <ide> ngBindTemplate: ngBindTemplateDirective, <ide> ngClass: ngClassDirective, <ide> ngClassEven: ngClassEvenDirective, <ide><path>src/ng/directive/ngBind.js <ide> var ngBindTemplateDirective = ['$interpolate', function($interpolate) { <ide> <ide> /** <ide> * @ngdoc directive <del> * @name ng.directive:ngBindHtmlUnsafe <add> * @name ng.directive:ngBindHtml <ide> * <ide> * @description <ide> * Creates a binding that will innerHTML the result of evaluating the `expression` into the current <del> * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if <del> * {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too <del> * restrictive and when you absolutely trust the source of the content you are binding to. <add> * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link <add> * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` <add> * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in <add> * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to <add> * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example <add> * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}. <ide> * <del> * See {@link ngSanitize.$sanitize $sanitize} docs for examples. <add> * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you <add> * will have an exception (instead of an exploit.) <ide> * <ide> * @element ANY <del> * @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate. <add> * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. <ide> */ <del>var ngBindHtmlUnsafeDirective = ['$sce', function($sce) { <add>var ngBindHtmlDirective = ['$sce', function($sce) { <ide> return function(scope, element, attr) { <del> element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe); <del> scope.$watch($sce.parseAsHtml(attr.ngBindHtmlUnsafe), function ngBindHtmlUnsafeWatchAction(value) { <add> element.addClass('ng-binding').data('$binding', attr.ngBindHtml); <add> scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function ngBindHtmlWatchAction(value) { <ide> element.html(value || ''); <ide> }); <ide> }; <ide><path>src/ng/sce.js <ide> function $SceDelegateProvider() { <ide> (documentProtocol === "http:" && resourceProtocol === "https:")); <ide> } <ide> <del> this.$get = ['$log', '$document', '$$urlUtils', function( <del> $log, $document, $$urlUtils) { <add> this.$get = ['$log', '$document', '$injector', '$$urlUtils', function( <add> $log, $document, $injector, $$urlUtils) { <add> <add> var htmlSanitizer = function htmlSanitizer(html) { <add> throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); <add> }; <add> <add> if ($injector.has('$sanitize')) { <add> htmlSanitizer = $injector.get('$sanitize'); <add> } <add> <ide> <ide> function matchUrl(matcher, parsedUrl) { <ide> if (matcher === 'self') { <ide> function $SceDelegateProvider() { <ide> if (constructor && maybeTrusted instanceof constructor) { <ide> return maybeTrusted.$$unwrapTrustedValue(); <ide> } <add> // If we get here, then we may only take one of two actions. <add> // 1. sanitize the value for the requested type, or <add> // 2. throw an exception. <ide> if (type === SCE_CONTEXTS.RESOURCE_URL) { <ide> if (isResourceUrlAllowedByPolicy(maybeTrusted)) { <ide> return maybeTrusted; <ide> function $SceDelegateProvider() { <ide> 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', maybeTrusted.toString()); <ide> return; <ide> } <add> } else if (type === SCE_CONTEXTS.HTML) { <add> return htmlSanitizer(maybeTrusted); <ide> } <ide> throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); <ide> } <ide> function $SceDelegateProvider() { <ide> * <ide> * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain <ide> * contexts to result in a value that is marked as safe to use for that context One example of such <del> * a context is binding arbitrary html controlled by the user via `ng-bind-html-unsafe`. We refer <del> * to these contexts as privileged or SCE contexts. <add> * a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer to these <add> * contexts as privileged or SCE contexts. <ide> * <ide> * As of version 1.2, Angular ships with SCE enabled by default. <ide> * <ide> function $SceDelegateProvider() { <ide> * <ide> * <pre class="prettyprint"> <ide> * <input ng-model="userHtml"> <del> * <div ng-bind-html-unsafe="{{userHtml}}"> <add> * <div ng-bind-html="{{userHtml}}"> <ide> * </pre> <ide> * <del> * Notice that `ng-bind-html-unsafe` is bound to `{{userHtml}}` controlled by the user. With SCE <add> * Notice that `ng-bind-html` is bound to `{{userHtml}}` controlled by the user. With SCE <ide> * disabled, this application allows the user to render arbitrary HTML into the DIV. <ide> * In a more realistic example, one may be rendering user comments, blog articles, etc. via <ide> * bindings. (HTML is just one example of a context where rendering user controlled input creates <ide> function $SceDelegateProvider() { <ide> * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the <ide> * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. <ide> * <del> * As an example, {@link ng.directive:ngBindHtmlUnsafe ngBindHtmlUnsafe} uses {@link <add> * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link <ide> * ng.$sce#parseHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly <ide> * simplified): <ide> * <ide> * <pre class="prettyprint"> <del> * var ngBindHtmlUnsafeDirective = ['$sce', function($sce) { <add> * var ngBindHtmlDirective = ['$sce', function($sce) { <ide> * return function(scope, element, attr) { <del> * scope.$watch($sce.parseAsHtml(attr.ngBindHtmlUnsafe), function(value) { <add> * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { <ide> * element.html(value || ''); <ide> * }); <ide> * }; <ide> function $SceDelegateProvider() { <ide> * <ide> * | Context | Notes | <ide> * |=====================|================| <del> * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtmlUnsafe ngBindHtmlUnsafe} directive uses this context for bindings. | <add> * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. | <ide> * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | <ide> * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't consititute an SCE context. | <ide> * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contens are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | <ide> function $SceDelegateProvider() { <ide> <example module="mySceApp"> <ide> <file name="index.html"> <ide> <div ng-controller="myAppController as myCtrl"> <del> <button ng-click="myCtrl.fetchUserComments()" id="fetchBtn">Fetch Comments</button> <del> <div ng-show="myCtrl.errorMsg">Error: {{myCtrl.errorMsg}}</div> <del> <div ng-repeat="userComment in myCtrl.userComments"> <del> <hr> <del> <b>{{userComment.name}}</b>: <del> <span ng-bind-html-unsafe="userComment.htmlComment" class="htmlComment"></span> <add> <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br> <add> <b>User comments</b><br> <add> By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when $sanitize is available. If $sanitize isn't available, this results in an error instead of an exploit. <add> <div class="well"> <add> <div ng-repeat="userComment in myCtrl.userComments"> <add> <b>{{userComment.name}}</b>: <add> <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span> <add> <br> <add> </div> <ide> </div> <del> <div ng-bind-html-unsafe="myCtrl.someHtml" id="someHtml"></div> <ide> </div> <ide> </file> <ide> <ide> <file name="script.js"> <del> // These types of functions would be in the data access layer of your application code. <del> function fetchUserCommentsFromServer($http, $q, $templateCache, $sce) { <del> var deferred = $q.defer(); <del> $http({method: "GET", url: "test_data.json", cache: $templateCache}). <del> success(function(userComments, status) { <del> // The comments coming from the server have been sanitized by the server and can be <del> // trusted. <del> angular.forEach(userComments, function(userComment) { <del> userComment.htmlComment = $sce.trustAsHtml(userComment.htmlComment); <del> }); <del> deferred.resolve(userComments); <del> }). <del> error(function (data, status) { <del> deferred.reject("HTTP status code " + status + ": " + data); <del> }); <del> return deferred.promise; <del> }; <del> <del> var mySceApp = angular.module('mySceApp', []); <add> var mySceApp = angular.module('mySceApp', ['ngSanitize']); <ide> <del> mySceApp.controller("myAppController", function myAppController($injector) { <add> mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) { <ide> var self = this; <del> <del> self.someHtml = "This might have been any binding including an input element " + <del> "controlled by the user."; <del> <del> self.fetchUserComments = function() { <del> $injector.invoke(fetchUserCommentsFromServer).then( <del> function onSuccess(userComments) { <del> self.errorMsg = null; <del> self.userComments = userComments; <del> }, <del> function onFailure(errorMsg) { <del> self.errorMsg = errorMsg; <del> }); <del> } <add> $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { <add> self.userComments = userComments; <add> }); <add> self.explicitlyTrustedHtml = $sce.trustAsHtml( <add> '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' + <add> 'sanitization.&quot;">Hover over this text.</span>'); <ide> }); <ide> </file> <ide> <ide> <file name="test_data.json"> <ide> [ <ide> { "name": "Alice", <del> "htmlComment": "Is <i>anyone</i> reading this?" <add> "htmlComment": "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>" <ide> }, <ide> { "name": "Bob", <ide> "htmlComment": "<i>Yes!</i> Am I the only other one?" <ide> function $SceDelegateProvider() { <ide> </file> <ide> <ide> <file name="scenario.js"> <del> describe('SCE doc demo', function() { <del> it('should bind trusted values', function() { <del> element('#fetchBtn').click(); <del> expect(element('.htmlComment').html()).toBe('Is <i>anyone</i> reading this?'); <del> }); <del> it('should NOT bind arbitrary values', function() { <del> expect(element('#someHtml').html()).toBe(''); <del> }); <add> describe('SCE doc demo', function() { <add> it('should sanitize untrusted values', function() { <add> expect(element('.htmlComment').html()).toBe('<span>Is <i>anyone</i> reading this?</span>'); <add> }); <add> it('should NOT sanitize explicitly trusted values', function() { <add> expect(element('#explicitlyTrustedHtml').html()).toBe( <add> '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' + <add> 'sanitization.&quot;">Hover over this text.</span>'); <add> }); <ide> }); <ide> </file> <ide> </example> <ide><path>src/ngSanitize/directive/ngBindHtml.js <del>'use strict'; <del> <del> <del>/** <del> * @ngdoc directive <del> * @name ngSanitize.directive:ngBindHtml <del> * <del> * @description <del> * Creates a binding that will sanitize the result of evaluating the `expression` with the <del> * {@link ngSanitize.$sanitize $sanitize} service and innerHTML the result into the current element. <del> * <del> * See {@link ngSanitize.$sanitize $sanitize} docs for examples. <del> * <del> * @element ANY <del> * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. <del> */ <del>angular.module('ngSanitize').directive('ngBindHtml', ['$sanitize', function($sanitize) { <del> return function(scope, element, attr) { <del> element.addClass('ng-binding').data('$binding', attr.ngBindHtml); <del> scope.$watch(attr.ngBindHtml, function ngBindHtmlWatchAction(value) { <del> value = $sanitize(value); <del> element.html(value || ''); <del> }); <del> }; <del>}]); <ide><path>src/ngSanitize/sanitize.js <ide> var ngSanitizeMinErr = angular.$$minErr('ngSanitize'); <ide> '<p style="color:blue">an html\n' + <ide> '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + <ide> 'snippet</p>'; <del> // ng-bind-html-unsafe requires a $sce trusted value of type $sce.HTML. <del> $scope.getSceSnippet = function() { <add> $scope.deliberatelyTrustDangerousSnippet = function() { <ide> return $sce.trustAsHtml($scope.snippet); <ide> }; <ide> } <ide> var ngSanitizeMinErr = angular.$$minErr('ngSanitize'); <ide> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <ide> <table> <ide> <tr> <del> <td>Filter</td> <add> <td>Directive</td> <add> <td>How</td> <ide> <td>Source</td> <ide> <td>Rendered</td> <ide> </tr> <del> <tr id="html-filter"> <del> <td>html filter</td> <del> <td> <del> <pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre> <del> </td> <del> <td> <del> <div ng-bind-html="snippet"></div> <del> </td> <add> <tr id="bind-html-with-sanitize"> <add> <td>ng-bind-html</td> <add> <td>Automatically uses $sanitize</td> <add> <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <add> <td><div ng-bind-html="snippet"></div></td> <ide> </tr> <del> <tr id="escaped-html"> <del> <td>no filter</td> <add> <tr id="bind-html-with-trust"> <add> <td>ng-bind-html</td> <add> <td>Bypass $sanitize by explicitly trusting the dangerous value</td> <add> <td><pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt;<br/>&lt;/div&gt;</pre></td> <add> <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td> <add> </tr> <add> <tr id="bind-default"> <add> <td>ng-bind</td> <add> <td>Automatically escapes</td> <ide> <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <ide> <td><div ng-bind="snippet"></div></td> <ide> </tr> <del> <tr id="html-unsafe-filter"> <del> <td>unsafe html filter</td> <del> <td><pre>&lt;div ng-bind-html-unsafe="getSceSnippet()"&gt;<br/>&lt;/div&gt;</pre></td> <del> <td><div ng-bind-html-unsafe="getSceSnippet()"></div></td> <del> </tr> <ide> </table> <ide> </div> <ide> </doc:source> <ide> <doc:scenario> <del> it('should sanitize the html snippet ', function() { <del> expect(using('#html-filter').element('div').html()). <add> it('should sanitize the html snippet by default', function() { <add> expect(using('#bind-html-with-sanitize').element('div').html()). <ide> toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); <ide> }); <ide> <add> it('should inline raw snippet if bound to a trusted value', function() { <add> expect(using('#bind-html-with-trust').element("div").html()). <add> toBe("<p style=\"color:blue\">an html\n" + <add> "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + <add> "snippet</p>"); <add> }); <add> <ide> it('should escape snippet without any filter', function() { <del> expect(using('#escaped-html').element('div').html()). <add> expect(using('#bind-default').element('div').html()). <ide> toBe("&lt;p style=\"color:blue\"&gt;an html\n" + <ide> "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + <ide> "snippet&lt;/p&gt;"); <ide> }); <ide> <del> it('should inline raw snippet if filtered as unsafe', function() { <del> expect(using('#html-unsafe-filter').element("div").html()). <del> toBe("<p style=\"color:blue\">an html\n" + <del> "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + <del> "snippet</p>"); <del> }); <del> <del> it('should update', function($sce) { <del> input('snippet').enter('new <b>text</b>'); <del> expect(using('#html-filter').binding('snippet')).toBe('new <b>text</b>'); <del> expect(using('#escaped-html').element('div').html()).toBe("new &lt;b&gt;text&lt;/b&gt;"); <del> expect(using('#html-unsafe-filter').element('div').html()).toBe('new <b>text</b>'); <add> it('should update', function() { <add> input('snippet').enter('new <b onclick="alert(1)">text</b>'); <add> expect(using('#bind-html-with-sanitize').element('div').html()).toBe('new <b>text</b>'); <add> expect(using('#bind-html-with-trust').element('div').html()).toBe('new <b onclick="alert(1)">text</b>'); <add> expect(using('#bind-default').element('div').html()).toBe("new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;"); <ide> }); <ide> </doc:scenario> <ide> </doc:example> <ide><path>test/ng/directive/ngBindSpec.js <ide> describe('ngBind*', function() { <ide> }); <ide> <ide> <del> describe('ngBindHtmlUnsafe', function() { <del> <del> function configureSce(enabled) { <del> module(function($provide, $sceProvider) { <del> $sceProvider.enabled(enabled); <del> }); <del> }; <del> <add> describe('ngBindHtml', function() { <ide> describe('SCE disabled', function() { <del> beforeEach(function() {configureSce(false)}); <add> beforeEach(function() { <add> module(function($sceProvider) { $sceProvider.enabled(false); }); <add> }); <ide> <del> it('should set unsafe html', inject(function($rootScope, $compile) { <del> element = $compile('<div ng-bind-html-unsafe="html"></div>')($rootScope); <add> it('should set html', inject(function($rootScope, $compile) { <add> element = $compile('<div ng-bind-html="html"></div>')($rootScope); <ide> $rootScope.html = '<div onclick="">hello</div>'; <ide> $rootScope.$digest(); <ide> expect(angular.lowercase(element.html())).toEqual('<div onclick="">hello</div>'); <ide> describe('ngBind*', function() { <ide> <ide> <ide> describe('SCE enabled', function() { <del> beforeEach(function() {configureSce(true)}); <del> <del> it('should NOT set unsafe html for untrusted values', inject(function($rootScope, $compile) { <del> element = $compile('<div ng-bind-html-unsafe="html"></div>')($rootScope); <add> it('should NOT set html for untrusted values', inject(function($rootScope, $compile) { <add> element = $compile('<div ng-bind-html="html"></div>')($rootScope); <ide> $rootScope.html = '<div onclick="">hello</div>'; <ide> expect($rootScope.$digest).toThrow(); <ide> })); <ide> <del> it('should NOT set unsafe html for wrongly typed values', inject(function($rootScope, $compile, $sce) { <del> element = $compile('<div ng-bind-html-unsafe="html"></div>')($rootScope); <add> it('should NOT set html for wrongly typed values', inject(function($rootScope, $compile, $sce) { <add> element = $compile('<div ng-bind-html="html"></div>')($rootScope); <ide> $rootScope.html = $sce.trustAsCss('<div onclick="">hello</div>'); <ide> expect($rootScope.$digest).toThrow(); <ide> })); <ide> <del> it('should set unsafe html for trusted values', inject(function($rootScope, $compile, $sce) { <del> element = $compile('<div ng-bind-html-unsafe="html"></div>')($rootScope); <add> it('should set html for trusted values', inject(function($rootScope, $compile, $sce) { <add> element = $compile('<div ng-bind-html="html"></div>')($rootScope); <ide> $rootScope.html = $sce.trustAsHtml('<div onclick="">hello</div>'); <ide> $rootScope.$digest(); <ide> expect(angular.lowercase(element.html())).toEqual('<div onclick="">hello</div>'); <ide> })); <ide> <add> describe('when $sanitize is available', function() { <add> beforeEach(function() { module('ngSanitize'); }); <add> <add> it('should sanitize untrusted html', inject(function($rootScope, $compile) { <add> element = $compile('<div ng-bind-html="html"></div>')($rootScope); <add> $rootScope.html = '<div onclick="">hello</div>'; <add> $rootScope.$digest(); <add> expect(angular.lowercase(element.html())).toEqual('<div>hello</div>'); <add> })); <add> }); <ide> }); <ide> <ide> }); <ide><path>test/ng/sceSpecs.js <ide> describe('SCE', function() { <ide> expect(function() { $sce.getTrustedResourceUrl('open_redirect'); }).toThrow( <ide> '[$sce:isecrurl] Blocked loading resource from url not allowed by $sceDelegate policy. URL: open_redirect'); <ide> })); <add> }); <add> <add> describe('sanitizing html', function() { <add> describe('when $sanitize is NOT available', function() { <add> it('should throw an exception for getTrusted(string) values', inject(function($sce) { <add> expect(function() { $sce.getTrustedHtml('<b></b>'); }).toThrow( <add> '[$sce:unsafe] Attempting to use an unsafe value in a safe context.'); <add> })); <add> }); <ide> <add> describe('when $sanitize is available', function() { <add> beforeEach(function() { module('ngSanitize'); }); <add> it('should sanitize html using $sanitize', inject(function($sce) { <add> expect($sce.getTrustedHtml('a<xxx><B>b</B></xxx>c')).toBe('a<b>b</b>c'); <add> })); <add> }); <ide> }); <ide> }); <ide>
9
Python
Python
add possible solution for field validation error
2250ab6418d3cf99719ea7c5e3b3a861afa850bd
<ide><path>rest_framework/serializers.py <ide> def perform_validation(self, attrs): <ide> Run `validate_<fieldname>()` and `validate()` methods on the serializer <ide> """ <ide> for field_name, field in self.fields.items(): <del> try: <del> validate_method = getattr(self, 'validate_%s' % field_name, None) <del> if validate_method: <del> source = field.source or field_name <del> attrs = validate_method(attrs, source) <del> except ValidationError as err: <del> self._errors[field_name] = self._errors.get(field_name, []) + list(err.messages) <add> if field_name not in self._errors: <add> try: <add> validate_method = getattr(self, 'validate_%s' % field_name, None) <add> if validate_method: <add> source = field.source or field_name <add> attrs = validate_method(attrs, source) <add> except ValidationError as err: <add> self._errors[field_name] = self._errors.get(field_name, []) + list(err.messages) <ide> <ide> # If there are already errors, we don't run .validate() because <ide> # field-validation failed and thus `attrs` may not be complete.
1
Javascript
Javascript
replace erroneous comma with semicolon
3c649703c714f9654f8b6f47ecaa7f93c05a38f8
<ide><path>lib/cluster.js <ide> function workerInit() { <ide> cluster.worker.state = 'listening'; <ide> var address = obj.address(); <ide> message.act = 'listening'; <del> message.port = address && address.port || port, <add> message.port = address && address.port || port; <ide> send(message); <ide> }); <ide> };
1
Ruby
Ruby
pass second tag as import
b14ff8d16395c2691bda2852afe5fbbdada54398
<ide><path>Library/Homebrew/dependency_collector.rb <ide> def parse_string_spec(spec, tags) <ide> if tags.empty? <ide> Dependency.new(spec, tags) <ide> elsif (tag = tags.first) && LANGUAGE_MODULES.include?(tag) <del> LanguageModuleDependency.new(tag, spec) <add> LanguageModuleDependency.new(tag, spec, tags[1]) <ide> elsif HOMEBREW_TAP_FORMULA_REGEX === spec <ide> TapDependency.new(spec, tags) <ide> else
1
Ruby
Ruby
fix syntax error
e9468e3971b9c38dd6584fcaa25b3acc6d2ab630
<ide><path>activestorage/lib/active_storage/service/s3_service.rb <ide> def exist?(key) <ide> end <ide> end <ide> <del> def url(key, expires_in:, disposition:, filename:, disposition:, content_type:) <add> def url(key, expires_in:, filename:, disposition:, content_type:) <ide> instrument :url, key do |payload| <ide> generated_url = object_for(key).presigned_url :get, expires_in: expires_in, <ide> response_content_disposition: disposition,
1
PHP
PHP
refactor the package class
e3785ee7ff9a85132fc7595b6c1cca24144b4035
<ide><path>system/package.php <ide> public static function load($packages) <ide> { <ide> foreach ((array) $packages as $package) <ide> { <del> if (file_exists($bootstrap = PACKAGE_PATH.$package.'/bootstrap'.EXT)) require_once $bootstrap; <add> if (file_exists($bootstrap = PACKAGE_PATH.$package.'/bootstrap'.EXT)) <add> { <add> require_once $bootstrap; <add> } <ide> <del> static::$loaded[] = $package; <add> static::$loaded[] = $package; <ide> } <ide> } <ide>
1
Ruby
Ruby
use module#prepend instead of alias_method_chain
d5bddc1b2d3d794b2eddcb7309f41f87a8d665c1
<ide><path>activesupport/lib/active_support/core_ext/marshal.rb <del>require 'active_support/core_ext/module/aliasing' <del> <del>module Marshal <del> class << self <del> def load_with_autoloading(source) <del> load_without_autoloading(source) <add>module ActiveSupport <add> module MarshalWithAutoloading <add> def load(source) <add> super(source) <ide> rescue ArgumentError, NameError => exc <ide> if exc.message.match(%r|undefined class/module (.+)|) <ide> # try loading the class/module <ide> def load_with_autoloading(source) <ide> raise exc <ide> end <ide> end <del> <del> alias_method_chain :load, :autoloading <ide> end <ide> end <add> <add>Marshal.singleton_class.prepend(ActiveSupport::MarshalWithAutoloading) <ide><path>activesupport/lib/active_support/core_ext/object/json.rb <ide> require 'active_support/core_ext/time/conversions' <ide> require 'active_support/core_ext/date_time/conversions' <ide> require 'active_support/core_ext/date/conversions' <del>require 'active_support/core_ext/module/aliasing' <ide> <ide> # The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting <ide> # their default behavior. That said, we need to define the basic to_json method in all of them, <ide> # bypassed completely. This means that as_json won't be invoked and the JSON gem will simply <ide> # ignore any options it does not natively understand. This also means that ::JSON.{generate,dump} <ide> # should give exactly the same results with or without active support. <del>[Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass, Enumerable].each do |klass| <del> klass.class_eval do <del> def to_json_with_active_support_encoder(options = nil) <del> if options.is_a?(::JSON::State) <del> # Called from JSON.{generate,dump}, forward it to JSON gem's to_json <del> self.to_json_without_active_support_encoder(options) <del> else <del> # to_json is being invoked directly, use ActiveSupport's encoder <del> ActiveSupport::JSON.encode(self, options) <add> <add>module ActiveSupport <add> module CoreExt <add> module ToJsonWithActiveSupportEncoder <add> def to_json(options = nil) <add> if options.is_a?(::JSON::State) <add> # Called from JSON.{generate,dump}, forward it to JSON gem's to_json <add> super(options) <add> else <add> # to_json is being invoked directly, use ActiveSupport's encoder <add> ActiveSupport::JSON.encode(self, options) <add> end <ide> end <ide> end <del> <del> alias_method_chain :to_json, :active_support_encoder <ide> end <ide> end <ide> <add>[Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass, Enumerable].reverse_each do |klass| <add> klass.prepend(ActiveSupport::CoreExt::ToJsonWithActiveSupportEncoder) <add>end <add> <ide> class Object <ide> def as_json(options = nil) #:nodoc: <ide> if respond_to?(:to_hash) <ide><path>activesupport/test/core_ext/marshal_test.rb <ide> def teardown <ide> sanity_data = ["test", [1, 2, 3], {a: [1, 2, 3]}, ActiveSupport::TestCase] <ide> sanity_data.each do |obj| <ide> dumped = Marshal.dump(obj) <del> assert_equal Marshal.load_without_autoloading(dumped), Marshal.load(dumped) <add> assert_equal Marshal.method(:load).super_method.call(dumped), Marshal.load(dumped) <ide> end <ide> end <ide> <ide> class SomeClass <ide> end <ide> end <ide> end <del>end <ide>\ No newline at end of file <add>end
3
Text
Text
add typescript docs for ssg
b13892e0070993e4d014a70f6b424302fe583635
<ide><path>docs/api-reference/data-fetching/getInitialProps.md <ide> description: Enable Server-Side Rendering in a page and do initial data populati <ide> <ide> # getInitialProps <ide> <add>## Recommended: Use `getStaticProps` or `getServerSideProps` instead <add> <add>If you're using Next.js 9.3 or newer, you should use `getStaticProps` or `getServerSideProps` instead of `getInitialProps`. <add> <add>Learn more on the [Pages documentation](/docs/basic-features/pages.md) and the [Data fetching documentation](/docs/basic-features/data-fetching.md): <add> <add>## `getInitialProps` (for older versions of Next.js) <add> <ide> <details> <ide> <summary><b>Examples</b></summary> <ide> <ul> <ide> For the initial page load, `getInitialProps` will execute on the server only. `g <ide> - `getInitialProps` can **not** be used in children components, only in the default export of every page <ide> - If you are using server-side only modules inside `getInitialProps`, make sure to [import them properly](https://arunoda.me/blog/ssr-and-server-only-modules), otherwise it'll slow down your app <ide> <add>## TypeScript <add> <add>If you're using TypeScript, you can use the `NextPage` type for functional components: <add> <add>```jsx <add>import { NextPage } from 'next' <add> <add>interface Props { <add> userAgent?: string; <add>} <add> <add>const Page: NextPage<Props> = ({ userAgent }) => ( <add> <main>Your user agent: {userAgent}</main> <add>) <add> <add>Page.getInitialProps = async ({ req }) => { <add> const userAgent = req ? req.headers['user-agent'] : navigator.userAgent <add> return { userAgent } <add>} <add> <add>export default Page <add>``` <add> <add>And for `React.Component`, you can use `NextPageContext`: <add> <add>```jsx <add>import React from 'react' <add>import { NextPageContext } from 'next' <add> <add>interface Props { <add> userAgent?: string; <add>} <add> <add>export default class Page extends React.Component<Props> { <add> static async getInitialProps({ req }: NextPageContext) { <add> const userAgent = req ? req.headers['user-agent'] : navigator.userAgent <add> return { userAgent } <add> } <add> <add> render() { <add> const { userAgent } = this.props <add> return <main>Your user agent: {userAgent}</main> <add> } <add>} <add>``` <add> <ide> ## Related <ide> <ide> For more information on what to do next, we recommend the following sections: <ide><path>docs/basic-features/data-fetching.md <ide> You should use `getStaticProps` if: <ide> - The data can be publicly cached (not user-specific). <ide> - The page must be pre-rendered (for SEO) and be very fast — `getStaticProps` generates HTML and JSON files, both of which can be cached by a CDN for performance. <ide> <add>### TypeScript: Use `GetStaticProps` <add> <add>For TypeScript, you can use the `GetStaticProps` type from `next`: <add> <add>```ts <add>import { GetStaticProps } from 'next' <add> <add>export const getStaticProps: GetStaticProps = async context => { <add> // ... <add>} <add>``` <add> <ide> ### Technical details <ide> <ide> #### Only runs at build time <ide> This ensures that users always have a fast experience while preserving fast buil <ide> <ide> You should use `getStaticPaths` if you’re statically pre-rendering pages that use dynamic routes. <ide> <add>### TypeScript: Use `GetStaticPaths` <add> <add>For TypeScript, you can use the `GetStaticPaths` type from `next`: <add> <add>```ts <add>import { GetStaticPaths } from 'next' <add> <add>export const getStaticPaths: GetStaticPaths = async () => { <add> // ... <add>} <add>``` <add> <ide> ### Technical details <ide> <ide> #### Use together with `getStaticProps` <ide> You should use `getServerSideProps` only if you need to pre-render a page whose <ide> <ide> If you don’t need to pre-render the data, then you should consider fetching data on the client side. [Click here to learn more](#fetching-data-on-the-client-side). <ide> <add>### TypeScript: Use `GetServerSideProps` <add> <add>For TypeScript, you can use the `GetServerSideProps` type from `next`: <add> <add>```ts <add>import { GetServerSideProps } from 'next' <add> <add>export const getServerSideProps: GetServerSideProps = async context => { <add> // ... <add>} <add>``` <add> <ide> ### Technical details <ide> <ide> #### Only runs on server-side <ide><path>docs/basic-features/typescript.md <ide> By default, Next.js reports TypeScript errors during development for pages you a <ide> <ide> If you want to silence the error reports, refer to the documentation for [Ignoring TypeScript errors](/docs/api-reference/next.config.js/ignoring-typescript-errors.md). <ide> <del>## Pages <add>## Static Generation and Server-side Rendering <ide> <del>For function components the `NextPage` type is exported, here's how to use it: <add>For `getStaticProps`, `getStaticPaths`, and `getServerSideProps`, you can use the `GetStaticProps`, `GetStaticPaths`, and `GetServerSideProps` types respectively: <ide> <del>```jsx <del>import { NextPage } from 'next' <del> <del>interface Props { <del> userAgent?: string; <del>} <del> <del>const Page: NextPage<Props> = ({ userAgent }) => ( <del> <main>Your user agent: {userAgent}</main> <del>) <add>```ts <add>import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next' <ide> <del>Page.getInitialProps = async ({ req }) => { <del> const userAgent = req ? req.headers['user-agent'] : navigator.userAgent <del> return { userAgent } <add>export const getStaticProps: GetStaticProps = async context => { <add> // ... <ide> } <ide> <del>export default Page <del>``` <del> <del>And for `React.Component` you can use `NextPageContext`: <del> <del>```jsx <del>import React from 'react' <del>import { NextPageContext } from 'next' <del> <del>interface Props { <del> userAgent?: string; <add>export const getStaticPaths: GetStaticPaths = async () => { <add> // ... <ide> } <ide> <del>export default class Page extends React.Component<Props> { <del> static async getInitialProps({ req }: NextPageContext) { <del> const userAgent = req ? req.headers['user-agent'] : navigator.userAgent <del> return { userAgent } <del> } <del> <del> render() { <del> const { userAgent } = this.props <del> return <main>Your user agent: {userAgent}</main> <del> } <add>export const getServerSideProps: GetServerSideProps = async context => { <add> // ... <ide> } <ide> ``` <ide> <add>> If you're using `getInitialProps`, you can [follow the directions on this page](/docs/api-reference/data-fetching/getInitialProps.md#typescript). <add> <ide> ## API Routes <ide> <ide> The following is an example of how to use the built-in types for API routes:
3
Ruby
Ruby
install bundler gems if necessary
323fec503201eb66bf981f8fab034238db428aae
<ide><path>Library/Homebrew/utils/bottles.rb <ide> def formula_contents(bottle_file, <ide> end <ide> <ide> def add_bottle_stanza!(formula_contents, bottle_output) <add> Homebrew.install_bundler_gems! <ide> require "rubocop-ast" <ide> <ide> ruby_version = Version.new(HOMEBREW_REQUIRED_RUBY_VERSION).major_minor.to_f
1
Python
Python
add example for isscalar on strings
ae17d2c93dfac88cca9859d8b49490deb3991f41
<ide><path>numpy/core/numeric.py <ide> def isscalar(num): <ide> False <ide> >>> np.isscalar(False) <ide> True <add> >>> np.isscalar('numpy') <add> True <ide> <ide> """ <ide> if isinstance(num, generic):
1
Text
Text
add belugadb to airflow users
7ca45b252bbeeb2de223a835b8fa8b6b6200423c
<ide><path>README.md <ide> Currently **officially** using Airflow: <ide> 1. [Azri Solutions](http://www.azrisolutions.com/) [[@userimack](https://github.com/userimack)] <ide> 1. [BandwidthX](http://www.bandwidthx.com) [[@dineshdsharma](https://github.com/dineshdsharma)] <ide> 1. [Bellhops](https://github.com/bellhops) <add>1. [BelugaDB](https://belugadb.com) [[@fabio-nukui](https://github.com/fabio-nukui) & [@joao-sallaberry](http://github.com/joao-sallaberry) & [@lucianoviola](https://github.com/lucianoviola) & [@tmatuki](https://github.com/tmatuki)] <ide> 1. [BlaBlaCar](https://www.blablacar.com) [[@puckel](https://github.com/puckel) & [@wmorin](https://github.com/wmorin)] <ide> 1. [Bloc](https://www.bloc.io) [[@dpaola2](https://github.com/dpaola2)] <ide> 1. [BlueApron](https://www.blueapron.com) [[@jasonjho](https://github.com/jasonjho) & [@matthewdavidhauser](https://github.com/matthewdavidhauser)]
1