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
Text
Text
add updated links to anaconda resources
6c2c4f546eacd6c438b21241d3a4a020d4e37c68
<ide><path>guide/english/python/anaconda/index.md <ide> title: Anaconda <ide> --- <ide> <del>![alt text](https://www.anaconda.com/wp-content/themes/anaconda/images/logo-dark.png) <add># Anaconda <add> <add>**Anaconda** is a package manager, environment manager and Python distribution with a collection of over [1,500 open source packages](https://docs.anaconda.com/anaconda/packages/pkg-docs/), and it offers [free community support](https://groups.google.com/a/anaconda.com/forum/?fromgroups#!forum/anaconda). Anaconda is platform-agnostic, so you can use it whether you are on Windows, macOS or Linux. <ide> <del>**Anaconda** is a package manager, environment manager and Python distribution software with a collection of numerous packages. Anaconda is platform-agnostic, so you can use it whether you are on Windows, macOS or Linux. <ide> Anaconda easily creates, saves, loads and switches between environments on your system. It was initially created for Python programs, but it can package and distribute software for any language. <add> <ide> Anaconda, as a package manager, helps you find and install packages. If you need a package that requires a different version of Python, you do not need to switch to a different environment manager, because Anaconda is also an environment manager. With just a few commands, you can set up a totally separate environment to run that different version of Python, while continuing to run your usual version of Python in your normal environment. <ide> <add>To try Anaconda get the [Anaconda Cheat Sheet](https://docs.anaconda.com/_downloads/Anaconda-Starter-Guide-Cheat-Sheet.pdf) and [download Anaconda](https://www.anaconda.com/downloads). <add> <ide> ## Overview <ide> <del>The quickest way to start using conda is to go through the <del>20-minute [Getting started with conda](https://conda.io/docs/user-guide/getting-started.html) guide. <add>To use the Anaconda prompt (or Terminal on Linux or macOS), instead of a graphical user interface (GUI), then do so along with conda. You can also switch between them. <add> <add>The quickest ways to start using conda are to take the [30-minute conda test drive](http://conda.pydata.org/docs/test-drive.html), download the [conda cheat sheet](http://conda.pydata.org/docs/_downloads/conda-cheatsheet.pdf) and visit [Using conda](http://conda.pydata.org/docs/using) for creative/fun things to do with conda. <ide> <ide> The ``conda`` command is the primary interface for managing <ide> installations of various packages. It can: <ide> For full usage of each command, including abbreviations, see <ide> You can also type ``conda`` or ``conda help`` to access the list of commands and help text for each command available. <ide> <ide> <add>## Packages Available in Anaconda <add>- Over [200 packages](https://docs.anaconda.com/anaconda/packages/pkg-docs/) are automaticlly installed with Anaconda. <add>- Over 1,500 additional packages can be installed a la carte from the Anaconda repository using the ``conda install`` command. <add>- Thousands of more packages are available on [Anaconda Cloud](https://anaconda.org/). <add>- The ability to install other packages is possible using the ``pip install`` command that is installed with Anaconda. [Pip Packages](https://conda.io/docs/user-guide/tasks/manage-pkgs.html#installing-non-conda-packages) offer many of the same features as conda packages. Ideally, using the conda package, if available, is preferred. <add>- Anaconda allows for the development of your own [custom packages](http://conda.pydata.org/docs/building/build.html) via the ``conda build`` command. You can then share the packages on [Anaconda Cloud](http://anaconda.org/), PyPi, and more repositories. <add> <ide> ### Sources <ide> 1. [Anaconda Documentation](https://docs.anaconda.com/) <ide> 2. [Conda Documentation](https://conda.io/docs/)
1
Python
Python
fix maximum doc length in ud_train script
da7650e84ba8cd75775144c1d37cd0badb7805d1
<ide><path>spacy/cli/ud_train.py <ide> def main(ud_dir, parses_dir, config, corpus, limit=0, use_gpu=-1, vectors_dir=No <ide> nlp = load_nlp(paths.lang, config, vectors=vectors_dir) <ide> <ide> docs, golds = read_data(nlp, paths.train.conllu.open(), paths.train.text.open(), <del> max_doc_length=3, limit=limit) <add> max_doc_length=config.max_doc_length, <add> limit=limit) <ide> <ide> optimizer = initialize_pipeline(nlp, docs, golds, config, use_gpu) <ide>
1
Text
Text
add example to #recipes
68f7e20477160dcf8cf58869f4ce77a74a57abc7
<ide><path>readme.md <ide> For the production deployment, you can use the [path alias](https://zeit.co/docs <ide> <ide> - [Setting up 301 redirects](https://www.raygesualdo.com/posts/301-redirects-with-nextjs/) <ide> - [Dealing with SSR and server only modules](https://arunoda.me/blog/ssr-and-server-only-modules) <add>- [Building with React-Material-UI-Next-Express-Mongoose-Mongodb](https://github.com/builderbook/builderbook) <ide> <ide> ## FAQ <ide>
1
Text
Text
fix typo in "the rails initialization process"
4c9afc79a1357036697a95512f863f1490619ce3
<ide><path>guides/source/initialization.md <ide> on your needs. <ide> <ide> ### `Rails::Server#start` <ide> <del>After `congif/application` is loaded, `server.start` is called. This method is defined like this: <add>After `config/application` is loaded, `server.start` is called. This method is defined like this: <ide> <ide> ```ruby <ide> def start
1
Text
Text
change http links to https in linux.md
b18ba63f5482814d97ef1b5e4064762f9d02d2c8
<ide><path>docs/build-instructions/linux.md <del>See the [Hacking on Atom Core](http://flight-manual.atom.io/hacking-atom/sections/hacking-on-atom-core/#platform-linux) section in the [Atom Flight Manual](http://flight-manual.atom.io). <add>See the [Hacking on Atom Core](https://flight-manual.atom.io/hacking-atom/sections/hacking-on-atom-core/#platform-linux) section in the [Atom Flight Manual](https://flight-manual.atom.io).
1
Ruby
Ruby
combine attr declarations
32315c93480edea8cdf02c97876ffca6b1d99b32
<ide><path>Library/Homebrew/software_spec.rb <ide> require 'version' <ide> <ide> class SoftwareSpec <del> attr_reader :checksum, :mirrors, :specs <del> attr_reader :using # for auditing <add> attr_reader :checksum, :mirrors, :specs, :using <ide> <ide> def initialize url=nil, version=nil <ide> @url = url
1
PHP
PHP
refactor some method names
294c006288ee182eeddf3c6deb23a35032a9219d
<ide><path>src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php <ide> public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', C <ide> ); <ide> } <ide> <add> /** <add> * Get the "has relation" base query instance. <add> * <add> * @param string $relation <add> * @return \Illuminate\Database\Eloquent\Relations\Relation <add> */ <add> protected function getHasRelationQuery($relation) <add> { <add> return Relation::noConstraints(function () use ($relation) { <add> return $this->getModel()->{$relation}(); <add> }); <add> } <add> <ide> /** <ide> * Add nested relationship count / exists conditions to the query. <ide> * <ide> public function mergeModelDefinedRelationConstraints(Builder $relation) <ide> $relationQuery->wheres, $whereBindings <ide> ); <ide> } <del> <del> /** <del> * Get the "has relation" base query instance. <del> * <del> * @param string $relation <del> * @return \Illuminate\Database\Eloquent\Relations\Relation <del> */ <del> protected function getHasRelationQuery($relation) <del> { <del> return Relation::noConstraints(function () use ($relation) { <del> return $this->getModel()->$relation(); <del> }); <del> } <ide> } <ide><path>src/Illuminate/Database/Eloquent/Relations/HasOne.php <ide> protected function getDefaultFor(Model $model) <ide> } <ide> <ide> $instance = $this->related->newInstance()->setAttribute( <del> $this->getPlainForeignKey(), $model->getAttribute($this->localKey) <add> $this->getForeignKeyName(), $model->getAttribute($this->localKey) <ide> ); <ide> <ide> if (is_callable($this->withDefault)) { <ide><path>src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php <ide> public function addConstraints() <ide> } <ide> } <ide> <del> /** <del> * Add the constraints for a relationship query. <del> * <del> * @param \Illuminate\Database\Eloquent\Builder $query <del> * @param \Illuminate\Database\Eloquent\Builder $parent <del> * @param array|mixed $columns <del> * @return \Illuminate\Database\Eloquent\Builder <del> */ <del> public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*']) <del> { <del> if ($parent->getQuery()->from == $query->getQuery()->from) { <del> return $this->getRelationQueryForSelfRelation($query, $parent, $columns); <del> } <del> <del> return parent::getRelationQuery($query, $parent, $columns); <del> } <del> <del> /** <del> * Add the constraints for a relationship query on the same table. <del> * <del> * @param \Illuminate\Database\Eloquent\Builder $query <del> * @param \Illuminate\Database\Eloquent\Builder $parent <del> * @param array|mixed $columns <del> * @return \Illuminate\Database\Eloquent\Builder <del> */ <del> public function getRelationQueryForSelfRelation(Builder $query, Builder $parent, $columns = ['*']) <del> { <del> $query->select($columns); <del> <del> $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash()); <del> <del> $query->getModel()->setTable($hash); <del> <del> $key = $this->wrap($this->getQualifiedParentKeyName()); <del> <del> return $query->where($hash.'.'.$this->getPlainForeignKey(), '=', new Expression($key)); <del> } <del> <del> /** <del> * Get a relationship join table hash. <del> * <del> * @return string <del> */ <del> public function getRelationCountHash() <del> { <del> return 'laravel_reserved_'.static::$selfJoinCount++; <del> } <del> <ide> /** <ide> * Set the constraints for an eager load of the relation. <ide> * <ide> public function getRelationCountHash() <ide> */ <ide> public function addEagerConstraints(array $models) <ide> { <del> $this->query->whereIn($this->foreignKey, $this->getKeys($models, $this->localKey)); <add> $this->query->whereIn( <add> $this->foreignKey, $this->getKeys($models, $this->localKey) <add> ); <ide> } <ide> <ide> /** <ide> protected function matchOneOrMany(array $models, Collection $results, $relation, <ide> // link them up with their children using the keyed dictionary to make the <ide> // matching very convenient and easy work. Then we'll just return them. <ide> foreach ($models as $model) { <del> $key = $model->getAttribute($this->localKey); <del> <del> if (isset($dictionary[$key])) { <del> $value = $this->getRelationValue($dictionary, $key, $type); <del> <del> $model->setRelation($relation, $value); <add> if (isset($dictionary[$key = $model->getAttribute($this->localKey)])) { <add> $model->setRelation( <add> $relation, $this->getRelationValue($dictionary, $key, $type) <add> ); <ide> } <ide> } <ide> <ide> protected function buildDictionary(Collection $results) <ide> { <ide> $dictionary = []; <ide> <del> $foreign = $this->getPlainForeignKey(); <add> $foreign = $this->getForeignKeyName(); <ide> <ide> // First we will create a dictionary of models keyed by the foreign key of the <ide> // relationship as this will allow us to quickly access all of the related <ide> protected function buildDictionary(Collection $results) <ide> return $dictionary; <ide> } <ide> <del> /** <del> * Attach a model instance to the parent model. <del> * <del> * @param \Illuminate\Database\Eloquent\Model $model <del> * @return \Illuminate\Database\Eloquent\Model <del> */ <del> public function save(Model $model) <del> { <del> $model->setAttribute($this->getPlainForeignKey(), $this->getParentKey()); <del> <del> return $model->save() ? $model : false; <del> } <del> <del> /** <del> * Attach a collection of models to the parent instance. <del> * <del> * @param \Traversable|array $models <del> * @return \Traversable|array <del> */ <del> public function saveMany($models) <del> { <del> foreach ($models as $model) { <del> $this->save($model); <del> } <del> <del> return $models; <del> } <del> <ide> /** <ide> * Find a model by its primary key or return new instance of the related model. <ide> * <ide> public function findOrNew($id, $columns = ['*']) <ide> if (is_null($instance = $this->find($id, $columns))) { <ide> $instance = $this->related->newInstance(); <ide> <del> $instance->setAttribute($this->getPlainForeignKey(), $this->getParentKey()); <add> $instance->setAttribute($this->getForeignKeyName(), $this->getParentKey()); <ide> } <ide> <ide> return $instance; <ide> public function firstOrNew(array $attributes) <ide> if (is_null($instance = $this->where($attributes)->first())) { <ide> $instance = $this->related->newInstance($attributes); <ide> <del> $instance->setAttribute($this->getPlainForeignKey(), $this->getParentKey()); <add> $instance->setAttribute($this->getForeignKeyName(), $this->getParentKey()); <ide> } <ide> <ide> return $instance; <ide> public function firstOrCreate(array $attributes) <ide> */ <ide> public function updateOrCreate(array $attributes, array $values = []) <ide> { <del> $instance = $this->firstOrNew($attributes); <add> return tap($this->firstOrNew($attributes), function ($instance) use ($values) { <add> $instance->fill($values); <add> <add> $instance->save(); <add> }); <add> } <add> <add> /** <add> * Attach a model instance to the parent model. <add> * <add> * @param \Illuminate\Database\Eloquent\Model $model <add> * @return \Illuminate\Database\Eloquent\Model <add> */ <add> public function save(Model $model) <add> { <add> $model->setAttribute($this->getForeignKeyName(), $this->getParentKey()); <ide> <del> $instance->fill($values); <add> return $model->save() ? $model : false; <add> } <ide> <del> $instance->save(); <add> /** <add> * Attach a collection of models to the parent instance. <add> * <add> * @param \Traversable|array $models <add> * @return \Traversable|array <add> */ <add> public function saveMany($models) <add> { <add> foreach ($models as $model) { <add> $this->save($model); <add> } <ide> <del> return $instance; <add> return $models; <ide> } <ide> <ide> /** <ide> public function create(array $attributes) <ide> // Here we will set the raw attributes to avoid hitting the "fill" method so <ide> // that we do not have to worry about a mass accessor rules blocking sets <ide> // on the models. Otherwise, some of these attributes will not get set. <del> $instance = $this->related->newInstance($attributes); <del> <del> $instance->setAttribute($this->getPlainForeignKey(), $this->getParentKey()); <add> return tap($this->related->newInstance($attributes), function ($instance) use ($attributes) { <add> $instance->setAttribute($this->getForeignKeyName(), $this->getParentKey()); <ide> <del> $instance->save(); <del> <del> return $instance; <add> $instance->save(); <add> }); <ide> } <ide> <ide> /** <ide> public function update(array $attributes) <ide> } <ide> <ide> /** <del> * Get the key for comparing against the parent key in "has" query. <add> * Add the constraints for a relationship query. <ide> * <del> * @return string <add> * @param \Illuminate\Database\Eloquent\Builder $query <add> * @param \Illuminate\Database\Eloquent\Builder $parent <add> * @param array|mixed $columns <add> * @return \Illuminate\Database\Eloquent\Builder <ide> */ <del> public function getHasCompareKey() <add> public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*']) <ide> { <del> return $this->getForeignKey(); <add> if ($parent->getQuery()->from == $query->getQuery()->from) { <add> return $this->getRelationQueryForSelfRelation($query, $parent, $columns); <add> } <add> <add> return parent::getRelationQuery($query, $parent, $columns); <ide> } <ide> <ide> /** <del> * Get the foreign key for the relationship. <add> * Add the constraints for a relationship query on the same table. <ide> * <del> * @return string <add> * @param \Illuminate\Database\Eloquent\Builder $query <add> * @param \Illuminate\Database\Eloquent\Builder $parent <add> * @param array|mixed $columns <add> * @return \Illuminate\Database\Eloquent\Builder <ide> */ <del> public function getForeignKey() <add> public function getRelationQueryForSelfRelation(Builder $query, Builder $parent, $columns = ['*']) <ide> { <del> return $this->foreignKey; <add> $query->select($columns); <add> <add> $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash()); <add> <add> $query->getModel()->setTable($hash); <add> <add> $key = $this->wrap($this->getQualifiedParentKeyName()); <add> <add> return $query->where($hash.'.'.$this->getForeignKeyName(), '=', new Expression($key)); <ide> } <ide> <ide> /** <del> * Get the plain foreign key. <add> * Get a relationship join table hash. <ide> * <ide> * @return string <ide> */ <del> public function getPlainForeignKey() <add> public function getRelationCountHash() <ide> { <del> $segments = explode('.', $this->getForeignKey()); <add> return 'laravel_reserved_'.static::$selfJoinCount++; <add> } <ide> <del> return $segments[count($segments) - 1]; <add> /** <add> * Get the key for comparing against the parent key in "has" query. <add> * <add> * @return string <add> */ <add> public function getHasCompareKey() <add> { <add> return $this->getQualifiedForeignKeyName(); <ide> } <ide> <ide> /** <ide> public function getQualifiedParentKeyName() <ide> { <ide> return $this->parent->getTable().'.'.$this->localKey; <ide> } <add> <add> /** <add> * Get the plain foreign key. <add> * <add> * @return string <add> */ <add> public function getForeignKeyName() <add> { <add> $segments = explode('.', $this->getQualifiedForeignKeyName()); <add> <add> return $segments[count($segments) - 1]; <add> } <add> <add> /** <add> * Get the foreign key for the relationship. <add> * <add> * @return string <add> */ <add> public function getQualifiedForeignKeyName() <add> { <add> return $this->foreignKey; <add> } <ide> } <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php <ide> public function create(array $attributes) <ide> */ <ide> protected function setForeignAttributesForCreate(Model $model) <ide> { <del> $model->{$this->getPlainForeignKey()} = $this->getParentKey(); <add> $model->{$this->getForeignKeyName()} = $this->getParentKey(); <ide> <ide> $model->{last(explode('.', $this->morphType))} = $this->morphClass; <ide> } <ide><path>src/Illuminate/Database/Eloquent/Relations/Relation.php <ide> public function getRelationCountQuery(Builder $query, Builder $parent) <ide> */ <ide> public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*']) <ide> { <del> $query->select($columns); <del> <del> $key = $this->wrap($this->getQualifiedParentKeyName()); <del> <del> return $query->where($this->getHasCompareKey(), '=', new Expression($key)); <add> return $query->select($columns)->where( <add> $this->getHasCompareKey(), '=', <add> new Expression($this->wrap($this->getQualifiedParentKeyName())) <add> ); <ide> } <ide> <ide> /** <ide> public static function noConstraints(Closure $callback) <ide> // off of the bindings, leaving only the constraints that the developers put <ide> // as "extra" on the relationships, and not original relation constraints. <ide> try { <del> $results = call_user_func($callback); <add> return call_user_func($callback); <ide> } finally { <ide> static::$constraints = $previous; <ide> } <del> <del> return $results; <ide> } <ide> <ide> /** <ide> public static function noConstraints(Closure $callback) <ide> */ <ide> protected function getKeys(array $models, $key = null) <ide> { <del> return array_unique(array_values(array_map(function ($value) use ($key) { <add> return collect($models)->map(function ($value) use ($key) { <ide> return $key ? $value->getAttribute($key) : $value->getKey(); <del> }, $models))); <add> })->values()->unique()->all(); <ide> } <ide> <ide> /** <ide> public function relatedUpdatedAt() <ide> */ <ide> public function wrap($value) <ide> { <del> return $this->parent->newQueryWithoutScopes()->getQuery()->getGrammar()->wrap($value); <add> return $this->parent->newQueryWithoutScopes() <add> ->getQuery()->getGrammar()->wrap($value); <ide> } <ide> <ide> /** <ide> protected static function buildMorphMapFromModels(array $models = null) <ide> return $models; <ide> } <ide> <del> $tables = array_map(function ($model) { <add> return array_combine(array_map(function ($model) { <ide> return (new $model)->getTable(); <del> }, $models); <del> <del> return array_combine($tables, $models); <add> }, $models), $models); <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseEloquentHasOneTest.php <ide> public function testRelationCountQueryCanBeBuilt() <ide> $builder->shouldReceive('getQuery')->once()->andReturn($baseQuery); <ide> $builder->shouldReceive('getQuery')->once()->andReturn($parentQuery); <ide> <del> $builder->shouldReceive('select')->once()->with(m::type('Illuminate\Database\Query\Expression')); <add> $builder->shouldReceive('select')->once()->with(m::type('Illuminate\Database\Query\Expression'))->andReturnSelf(); <ide> $relation->getParent()->shouldReceive('getTable')->andReturn('table'); <ide> $builder->shouldReceive('where')->once()->with('table.foreign_key', '=', m::type('Illuminate\Database\Query\Expression')); <ide> $relation->getQuery()->shouldReceive('getQuery')->andReturn($parentQuery = m::mock('StdClass')); <ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testHasOneCreatesProperRelation() <ide> $model = new EloquentModelStub; <ide> $this->addMockConnection($model); <ide> $relation = $model->hasOne('EloquentModelSaveStub'); <del> $this->assertEquals('save_stub.eloquent_model_stub_id', $relation->getForeignKey()); <add> $this->assertEquals('save_stub.eloquent_model_stub_id', $relation->getQualifiedForeignKeyName()); <ide> <ide> $model = new EloquentModelStub; <ide> $this->addMockConnection($model); <ide> $relation = $model->hasOne('EloquentModelSaveStub', 'foo'); <del> $this->assertEquals('save_stub.foo', $relation->getForeignKey()); <add> $this->assertEquals('save_stub.foo', $relation->getQualifiedForeignKeyName()); <ide> $this->assertSame($model, $relation->getParent()); <ide> $this->assertInstanceOf('EloquentModelSaveStub', $relation->getQuery()->getModel()); <ide> } <ide> public function testMorphOneCreatesProperRelation() <ide> $model = new EloquentModelStub; <ide> $this->addMockConnection($model); <ide> $relation = $model->morphOne('EloquentModelSaveStub', 'morph'); <del> $this->assertEquals('save_stub.morph_id', $relation->getForeignKey()); <add> $this->assertEquals('save_stub.morph_id', $relation->getQualifiedForeignKeyName()); <ide> $this->assertEquals('save_stub.morph_type', $relation->getMorphType()); <ide> $this->assertEquals('EloquentModelStub', $relation->getMorphClass()); <ide> } <ide> public function testHasManyCreatesProperRelation() <ide> $model = new EloquentModelStub; <ide> $this->addMockConnection($model); <ide> $relation = $model->hasMany('EloquentModelSaveStub'); <del> $this->assertEquals('save_stub.eloquent_model_stub_id', $relation->getForeignKey()); <add> $this->assertEquals('save_stub.eloquent_model_stub_id', $relation->getQualifiedForeignKeyName()); <ide> <ide> $model = new EloquentModelStub; <ide> $this->addMockConnection($model); <ide> $relation = $model->hasMany('EloquentModelSaveStub', 'foo'); <del> $this->assertEquals('save_stub.foo', $relation->getForeignKey()); <add> $this->assertEquals('save_stub.foo', $relation->getQualifiedForeignKeyName()); <ide> $this->assertSame($model, $relation->getParent()); <ide> $this->assertInstanceOf('EloquentModelSaveStub', $relation->getQuery()->getModel()); <ide> } <ide> public function testMorphManyCreatesProperRelation() <ide> $model = new EloquentModelStub; <ide> $this->addMockConnection($model); <ide> $relation = $model->morphMany('EloquentModelSaveStub', 'morph'); <del> $this->assertEquals('save_stub.morph_id', $relation->getForeignKey()); <add> $this->assertEquals('save_stub.morph_id', $relation->getQualifiedForeignKeyName()); <ide> $this->assertEquals('save_stub.morph_type', $relation->getMorphType()); <ide> $this->assertEquals('EloquentModelStub', $relation->getMorphClass()); <ide> }
7
Text
Text
remove key from session by using session.delete
80cbf19453bb3fe22e8d038a9631b8436320788b
<ide><path>guides/source/action_controller_overview.md <ide> class LoginsController < ApplicationController <ide> # "Delete" a login, aka "log the user out" <ide> def destroy <ide> # Remove the user id from the session <del> @_current_user = session[:current_user_id] = nil <add> session.delete(:current_user_id) <add> # Clear the memoized current user <add> @_current_user = nil <ide> redirect_to root_url <ide> end <ide> end
1
Javascript
Javascript
add listener for non-value animated node
68a5ceef312c7e3ac74d616b960c1cfde46a109d
<ide><path>Libraries/Animated/src/__tests__/Animated-test.js <ide> describe('Animated tests', () => { <ide> expect(value1.__getValue()).toBe(1492); <ide> }); <ide> <add> it('should get updates for derived animated nodes', () => { <add> const value1 = new Animated.Value(40); <add> const value2 = new Animated.Value(50); <add> const value3 = new Animated.Value(0); <add> const value4 = Animated.add(value3, Animated.multiply(value1, value2)); <add> const callback = jest.fn(); <add> const view = new Animated.__PropsOnlyForTests( <add> { <add> style: { <add> transform: [ <add> { <add> translateX: value4, <add> }, <add> ], <add> }, <add> }, <add> callback, <add> ); <add> const listener = jest.fn(); <add> const id = value4.addListener(listener); <add> value3.setValue(137); <add> expect(listener.mock.calls.length).toBe(1); <add> expect(listener).toBeCalledWith({value: 2137}); <add> value1.setValue(0); <add> expect(listener.mock.calls.length).toBe(2); <add> expect(listener).toBeCalledWith({value: 137}); <add> expect(view.__getValue()).toEqual({ <add> style: { <add> transform: [ <add> { <add> translateX: 137, <add> }, <add> ], <add> }, <add> }); <add> value4.removeListener(id); <add> value1.setValue(40); <add> expect(listener.mock.calls.length).toBe(2); <add> expect(value4.__getValue()).toBe(2137); <add> }); <add> <ide> it('should removeAll', () => { <ide> const value1 = new Animated.Value(0); <ide> const listener = jest.fn(); <ide><path>Libraries/Animated/src/nodes/AnimatedNode.js <ide> <ide> const NativeAnimatedHelper = require('../NativeAnimatedHelper'); <ide> <add>const NativeAnimatedAPI = NativeAnimatedHelper.API; <ide> const invariant = require('invariant'); <ide> <add>type ValueListenerCallback = (state: {value: number}) => mixed; <add> <add>let _uniqueId = 1; <add> <ide> // Note(vjeux): this would be better as an interface but flow doesn't <ide> // support them yet <ide> class AnimatedNode { <add> _listeners: {[key: string]: ValueListenerCallback}; <add> __nativeAnimatedValueListener: ?any; <ide> __attach(): void {} <ide> __detach(): void { <ide> if (this.__isNative && this.__nativeTag != null) { <ide> class AnimatedNode { <ide> /* Methods and props used by native Animated impl */ <ide> __isNative: boolean; <ide> __nativeTag: ?number; <add> <add> constructor() { <add> this._listeners = {}; <add> } <add> <ide> __makeNative() { <ide> if (!this.__isNative) { <ide> throw new Error('This node cannot be made a "native" animated node'); <ide> } <add> <add> if (this.hasListeners()) { <add> this._startListeningToNativeValueUpdates(); <add> } <ide> } <add> <add> /** <add> * Adds an asynchronous listener to the value so you can observe updates from <add> * animations. This is useful because there is no way to <add> * synchronously read the value because it might be driven natively. <add> * <add> * See http://facebook.github.io/react-native/docs/animatedvalue.html#addlistener <add> */ <add> addListener(callback: (value: any) => mixed): string { <add> const id = String(_uniqueId++); <add> this._listeners[id] = callback; <add> if (this.__isNative) { <add> this._startListeningToNativeValueUpdates(); <add> } <add> return id; <add> } <add> <add> /** <add> * Unregister a listener. The `id` param shall match the identifier <add> * previously returned by `addListener()`. <add> * <add> * See http://facebook.github.io/react-native/docs/animatedvalue.html#removelistener <add> */ <add> removeListener(id: string): void { <add> delete this._listeners[id]; <add> if (this.__isNative && !this.hasListeners()) { <add> this._stopListeningForNativeValueUpdates(); <add> } <add> } <add> <add> /** <add> * Remove all registered listeners. <add> * <add> * See http://facebook.github.io/react-native/docs/animatedvalue.html#removealllisteners <add> */ <add> removeAllListeners(): void { <add> this._listeners = {}; <add> if (this.__isNative) { <add> this._stopListeningForNativeValueUpdates(); <add> } <add> } <add> <add> hasListeners(): boolean { <add> return !!Object.keys(this._listeners).length; <add> } <add> <add> _startListeningToNativeValueUpdates() { <add> if (this.__nativeAnimatedValueListener) { <add> return; <add> } <add> <add> NativeAnimatedAPI.startListeningToAnimatedNodeValue(this.__getNativeTag()); <add> this.__nativeAnimatedValueListener = NativeAnimatedHelper.nativeEventEmitter.addListener( <add> 'onAnimatedValueUpdate', <add> data => { <add> if (data.tag !== this.__getNativeTag()) { <add> return; <add> } <add> this._onAnimatedValueUpdateReceived(data.value); <add> }, <add> ); <add> } <add> <add> _onAnimatedValueUpdateReceived(value: number) { <add> this.__callListeners(value); <add> } <add> <add> __callListeners(value: number): void { <add> for (const key in this._listeners) { <add> this._listeners[key]({value}); <add> } <add> } <add> <add> _stopListeningForNativeValueUpdates() { <add> if (!this.__nativeAnimatedValueListener) { <add> return; <add> } <add> <add> this.__nativeAnimatedValueListener.remove(); <add> this.__nativeAnimatedValueListener = null; <add> NativeAnimatedAPI.stopListeningToAnimatedNodeValue(this.__getNativeTag()); <add> } <add> <ide> __getNativeTag(): ?number { <ide> NativeAnimatedHelper.assertNativeAnimatedModule(); <ide> invariant( <ide><path>Libraries/Animated/src/nodes/AnimatedValue.js <ide> import type AnimatedTracking from './AnimatedTracking'; <ide> <ide> const NativeAnimatedAPI = NativeAnimatedHelper.API; <ide> <del>type ValueListenerCallback = (state: {value: number}) => void; <del> <del>let _uniqueId = 1; <del> <ide> /** <ide> * Animated works by building a directed acyclic graph of dependencies <ide> * transparently when you render your Animated components. <ide> class AnimatedValue extends AnimatedWithChildren { <ide> _offset: number; <ide> _animation: ?Animation; <ide> _tracking: ?AnimatedTracking; <del> _listeners: {[key: string]: ValueListenerCallback}; <del> __nativeAnimatedValueListener: ?any; <ide> <ide> constructor(value: number) { <ide> super(); <ide> this._startingValue = this._value = value; <ide> this._offset = 0; <ide> this._animation = null; <del> this._listeners = {}; <ide> } <ide> <ide> __detach() { <ide> class AnimatedValue extends AnimatedWithChildren { <ide> return this._value + this._offset; <ide> } <ide> <del> __makeNative() { <del> super.__makeNative(); <del> <del> if (Object.keys(this._listeners).length) { <del> this._startListeningToNativeValueUpdates(); <del> } <del> } <del> <ide> /** <ide> * Directly set the value. This will stop any animations running on the value <ide> * and update all the bound properties. <ide> class AnimatedValue extends AnimatedWithChildren { <ide> } <ide> } <ide> <del> /** <del> * Adds an asynchronous listener to the value so you can observe updates from <del> * animations. This is useful because there is no way to <del> * synchronously read the value because it might be driven natively. <del> * <del> * See http://facebook.github.io/react-native/docs/animatedvalue.html#addlistener <del> */ <del> addListener(callback: ValueListenerCallback): string { <del> const id = String(_uniqueId++); <del> this._listeners[id] = callback; <del> if (this.__isNative) { <del> this._startListeningToNativeValueUpdates(); <del> } <del> return id; <del> } <del> <del> /** <del> * Unregister a listener. The `id` param shall match the identifier <del> * previously returned by `addListener()`. <del> * <del> * See http://facebook.github.io/react-native/docs/animatedvalue.html#removelistener <del> */ <del> removeListener(id: string): void { <del> delete this._listeners[id]; <del> if (this.__isNative && Object.keys(this._listeners).length === 0) { <del> this._stopListeningForNativeValueUpdates(); <del> } <del> } <del> <del> /** <del> * Remove all registered listeners. <del> * <del> * See http://facebook.github.io/react-native/docs/animatedvalue.html#removealllisteners <del> */ <del> removeAllListeners(): void { <del> this._listeners = {}; <del> if (this.__isNative) { <del> this._stopListeningForNativeValueUpdates(); <del> } <del> } <del> <del> _startListeningToNativeValueUpdates() { <del> if (this.__nativeAnimatedValueListener) { <del> return; <del> } <del> <del> NativeAnimatedAPI.startListeningToAnimatedNodeValue(this.__getNativeTag()); <del> this.__nativeAnimatedValueListener = NativeAnimatedHelper.nativeEventEmitter.addListener( <del> 'onAnimatedValueUpdate', <del> data => { <del> if (data.tag !== this.__getNativeTag()) { <del> return; <del> } <del> this._updateValue(data.value, false /* flush */); <del> }, <del> ); <del> } <del> <del> _stopListeningForNativeValueUpdates() { <del> if (!this.__nativeAnimatedValueListener) { <del> return; <del> } <del> <del> this.__nativeAnimatedValueListener.remove(); <del> this.__nativeAnimatedValueListener = null; <del> NativeAnimatedAPI.stopListeningToAnimatedNodeValue(this.__getNativeTag()); <del> } <del> <ide> /** <ide> * Stops any running animation or tracking. `callback` is invoked with the <ide> * final value after stopping the animation, which is useful for updating <ide> class AnimatedValue extends AnimatedWithChildren { <ide> this._value = this._startingValue; <ide> } <ide> <add> _onAnimatedValueUpdateReceived(value: number): void { <add> this._updateValue(value, false /*flush*/); <add> } <add> <ide> /** <ide> * Interpolates the value before updating the property, e.g. mapping 0-1 to <ide> * 0-10. <ide> class AnimatedValue extends AnimatedWithChildren { <ide> if (flush) { <ide> _flush(this); <ide> } <del> for (const key in this._listeners) { <del> this._listeners[key]({value: this.__getValue()}); <del> } <add> super.__callListeners(this.__getValue()); <ide> } <ide> <ide> __getNativeConfig(): Object { <ide><path>Libraries/Animated/src/nodes/AnimatedValueXY.js <ide> const AnimatedWithChildren = require('./AnimatedWithChildren'); <ide> <ide> const invariant = require('invariant'); <ide> <del>type ValueXYListenerCallback = (value: {x: number, y: number}) => void; <add>type ValueXYListenerCallback = (value: {x: number, y: number}) => mixed; <ide> <ide> let _uniqueId = 1; <ide> <ide><path>Libraries/Animated/src/nodes/AnimatedWithChildren.js <ide> class AnimatedWithChildren extends AnimatedNode { <ide> ); <ide> } <ide> } <add> super.__makeNative(); <ide> } <ide> <ide> __addChild(child: AnimatedNode): void { <ide> class AnimatedWithChildren extends AnimatedNode { <ide> __getChildren(): Array<AnimatedNode> { <ide> return this._children; <ide> } <add> <add> __callListeners(value: number): void { <add> super.__callListeners(value); <add> if (!this.__isNative) { <add> for (const child of this._children) { <add> if (child.__getValue) { <add> child.__callListeners(child.__getValue()); <add> } <add> } <add> } <add> } <ide> } <ide> <ide> module.exports = AnimatedWithChildren;
5
Python
Python
add pypi classifier for python 3. closes
cdac1209a517bf0808f12340d21ac9d334f69485
<ide><path>setup.py <ide> License :: OSI Approved <ide> Programming Language :: C <ide> Programming Language :: Python <add>Programming Language :: Python :: 3 <ide> Topic :: Software Development <ide> Topic :: Scientific/Engineering <ide> Operating System :: Microsoft :: Windows
1
Text
Text
clarify implementation of tick() in lifecycle docs
bd915caaf7b5ec2b34d433f118fa1ef138f6be6a
<ide><path>docs/docs/state-and-lifecycle.md <ide> We will tear down the timer in the `componentWillUnmount()` lifecycle hook: <ide> } <ide> ``` <ide> <del>Finally, we will implement the `tick()` method that runs every second. <add>Finally, we will implement a method called `tick()` that the `Clock` component will run every second. <ide> <ide> It will use `this.setState()` to schedule updates to the component local state: <ide> <ide> Let's quickly recap what's going on and the order in which the methods are calle <ide> <ide> 2) React then calls the `Clock` component's `render()` method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the `Clock`'s render output. <ide> <del>3) When the `Clock` output is inserted in the DOM, React calls the `componentDidMount()` lifecycle hook. Inside it, the `Clock` component asks the browser to set up a timer to call `tick()` once a second. <add>3) When the `Clock` output is inserted in the DOM, React calls the `componentDidMount()` lifecycle hook. Inside it, the `Clock` component asks the browser to set up a timer to call the component's `tick()` method once a second. <ide> <ide> 4) Every second the browser calls the `tick()` method. Inside it, the `Clock` component schedules a UI update by calling `setState()` with an object containing the current time. Thanks to the `setState()` call, React knows the state has changed, and calls `render()` method again to learn what should be on the screen. This time, `this.state.date` in the `render()` method will be different, and so the render output will include the updated time. React updates the DOM accordingly. <ide>
1
Ruby
Ruby
add lidarr to github_prerelease_allowlist
249088038c1bc410068ce53d8d0b804d38289bda
<ide><path>Library/Homebrew/utils/shared_audits.rb <ide> def github_release_data(user, repo, tag) <ide> "freetube" => :all, <ide> "gitless" => "0.8.8", <ide> "home-assistant" => :all, <add> "lidarr" => :all, <ide> "nuclear" => :all, <ide> "pock" => :all, <ide> "riff" => "0.5.0",
1
Javascript
Javascript
add tests for preventparsing and applynoparserule
3812c101b16a70e315ec349f216884d5fe15706f
<ide><path>lib/NormalModule.js <ide> class NormalModule extends Module { <ide> this._source = new RawSource("throw new Error(" + JSON.stringify(this.error.message) + ");"); <ide> } <ide> <del> applyNoParseRule(rule, request) { <add> applyNoParseRule(rule, content) { <ide> // must start with "rule" if rule is a string <ide> if(typeof rule === "string") { <del> return request.indexOf(rule) === 0; <add> return content.indexOf(rule) === 0; <ide> } <ide> // we assume rule is a regexp <del> return rule.test(request); <add> return rule.test(content); <ide> } <ide> <ide> // check if module should not be parsed <ide><path>test/NormalModule.test.js <ide> describe("NormalModule", function() { <ide> }); <ide> }); <ide> }); <add> <add> describe("#applyNoParseRule", function() { <add> let rule; <add> let content; <add> describe("given a string as rule", function() { <add> beforeEach(function() { <add> rule = "some-rule"; <add> }); <add> describe("and the content starting with the string specified in rule", function() { <add> beforeEach(function() { <add> content = rule + "some-content"; <add> }); <add> it("returns true", function() { <add> normalModule.preventParsing(rule, content).should.eql(true); <add> }); <add> }); <add> describe("and the content does not start with the string specified in rule", function() { <add> beforeEach(function() { <add> content = "some-content"; <add> }); <add> it("returns false", function() { <add> normalModule.preventParsing(rule, content).should.eql(false); <add> }); <add> }); <add> }); <add> describe("given a regex as rule", function() { <add> beforeEach(function() { <add> rule = /some-rule/; <add> }); <add> describe("and the content matches the rule", function() { <add> beforeEach(function() { <add> content = rule + "some-content"; <add> }); <add> it("returns true", function() { <add> normalModule.preventParsing(rule, content).should.eql(true); <add> }); <add> }); <add> describe("and the content does not match the rule", function() { <add> beforeEach(function() { <add> content = "some-content"; <add> }); <add> it("returns false", function() { <add> normalModule.preventParsing(rule, content).should.eql(false); <add> }); <add> }); <add> }); <add> }); <add> <add> describe("#preventParsing", function() { <add> let applyNoParseRuleSpy; <add> beforeEach(function() { <add> applyNoParseRuleSpy = sinon.stub(); <add> normalModule.applyNoParseRule = applyNoParseRuleSpy; <add> }); <add> describe("given no noParseRule", function() { <add> it("returns false", function() { <add> normalModule.preventParsing().should.eql(false); <add> applyNoParseRuleSpy.callCount.should.eql(0); <add> }); <add> }); <add> describe("given a noParseRule", function() { <add> let returnValOfSpy; <add> beforeEach(function() { <add> returnValOfSpy = Math.random() >= 0.5 ? true : false; <add> applyNoParseRuleSpy.returns(returnValOfSpy); <add> }); <add> describe("that is a string", function() { <add> it("calls and returns whatever applyNoParseRule returns", function() { <add> normalModule.preventParsing("some rule").should.eql(returnValOfSpy); <add> applyNoParseRuleSpy.callCount.should.eql(1); <add> }); <add> }); <add> describe("that is a regex", function() { <add> it("calls and returns whatever applyNoParseRule returns", function() { <add> normalModule.preventParsing("some rule").should.eql(returnValOfSpy); <add> applyNoParseRuleSpy.callCount.should.eql(1); <add> }); <add> }); <add> describe("that is an array", function() { <add> describe("of strings and or regexs", function() { <add> let someRules; <add> beforeEach(function() { <add> someRules = [ <add> Math.random() >= 0.5 ? "some rule" : /some rule/, <add> Math.random() >= 0.5 ? "some rule1" : /some rule1/, <add> Math.random() >= 0.5 ? "some rule2" : /some rule2/, <add> ]; <add> }); <add> describe("and none of them match", function() { <add> beforeEach(function() { <add> returnValOfSpy = false; <add> applyNoParseRuleSpy.returns(returnValOfSpy); <add> }); <add> it("returns false", function() { <add> normalModule.preventParsing(someRules).should.eql(returnValOfSpy); <add> applyNoParseRuleSpy.callCount.should.eql(3); <add> }); <add> }); <add> describe("and the first of them matches", function() { <add> beforeEach(function() { <add> returnValOfSpy = true; <add> applyNoParseRuleSpy.returns(returnValOfSpy); <add> }); <add> it("returns true", function() { <add> normalModule.preventParsing(someRules).should.eql(returnValOfSpy); <add> applyNoParseRuleSpy.callCount.should.eql(1); <add> }); <add> }); <add> describe("and the last of them matches", function() { <add> beforeEach(function() { <add> returnValOfSpy = true; <add> applyNoParseRuleSpy.onCall(0).returns(false); <add> applyNoParseRuleSpy.onCall(1).returns(false); <add> applyNoParseRuleSpy.onCall(2).returns(true); <add> }); <add> it("returns true", function() { <add> normalModule.preventParsing(someRules).should.eql(returnValOfSpy); <add> applyNoParseRuleSpy.callCount.should.eql(3); <add> }); <add> }); <add> }); <add> }); <add> }); <add> }); <ide> });
2
Python
Python
add tapas mlm-only models
5642a555ae89ae489d77c4871911dabe68daf699
<ide><path>src/transformers/__init__.py <ide> "TapasForSequenceClassification", <ide> "TapasModel", <ide> "TapasPreTrainedModel", <add> "load_tf_weights_in_tapas", <ide> ] <ide> ) <ide> _import_structure["models.transfo_xl"].extend( <ide> TapasForSequenceClassification, <ide> TapasModel, <ide> TapasPreTrainedModel, <add> load_tf_weights_in_tapas, <ide> ) <ide> from .models.transfo_xl import ( <ide> TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, <ide><path>src/transformers/models/tapas/__init__.py <ide> "TapasForSequenceClassification", <ide> "TapasModel", <ide> "TapasPreTrainedModel", <add> "load_tf_weights_in_tapas", <ide> ] <ide> <ide> <ide> TapasForSequenceClassification, <ide> TapasModel, <ide> TapasPreTrainedModel, <add> load_tf_weights_in_tapas, <ide> ) <ide> <ide> else: <ide><path>src/transformers/models/tapas/convert_tapas_original_tf_checkpoint_to_pytorch.py <ide> def convert_tf_checkpoint_to_pytorch( <ide> model = TapasForMaskedLM(config=config) <ide> elif task == "INTERMEDIATE_PRETRAINING": <ide> model = TapasModel(config=config) <add> else: <add> raise ValueError(f"Task {task} not supported.") <ide> <ide> print(f"Building PyTorch model from configuration: {config}") <del> <ide> # Load weights from tf checkpoint <ide> load_tf_weights_in_tapas(model, config, tf_checkpoint_path) <ide> <ide> # Save pytorch-model (weights and configuration) <ide> print(f"Save PyTorch model to {pytorch_dump_path}") <del> model.save_pretrained(pytorch_dump_path[:-17]) <add> model.save_pretrained(pytorch_dump_path) <ide> <ide> # Save tokenizer files <del> dir_name = r"C:\Users\niels.rogge\Documents\Python projecten\tensorflow\Tensorflow models\SQA\Base\tapas_sqa_inter_masklm_base_reset" <del> tokenizer = TapasTokenizer(vocab_file=dir_name + r"\vocab.txt", model_max_length=512) <del> <ide> print(f"Save tokenizer files to {pytorch_dump_path}") <del> tokenizer.save_pretrained(pytorch_dump_path[:-17]) <add> tokenizer = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + "vocab.txt", model_max_length=512) <add> tokenizer.save_pretrained(pytorch_dump_path) <ide> <ide> print("Used relative position embeddings:", model.config.reset_position_index_per_cell) <ide> <ide><path>src/transformers/models/tapas/modeling_tapas.py <ide> def load_tf_weights_in_tapas(model, config, tf_checkpoint_path): <ide> if any(n in ["output_bias", "output_weights", "output_bias_cls", "output_weights_cls"] for n in name): <ide> logger.info(f"Skipping {'/'.join(name)}") <ide> continue <add> # in case the model is TapasForMaskedLM, we skip the pooler <add> if isinstance(model, TapasForMaskedLM): <add> if any(n in ["pooler"] for n in name): <add> logger.info(f"Skipping {'/'.join(name)}") <add> continue <ide> # if first scope name starts with "bert", change it to "tapas" <ide> if name[0] == "bert": <ide> name[0] = "tapas" <ide> def load_tf_weights_in_tapas(model, config, tf_checkpoint_path): <ide> pointer = getattr(pointer, "bias") <ide> # cell selection heads <ide> elif scope_names[0] == "output_bias": <del> pointer = getattr(pointer, "output_bias") <add> if not isinstance(model, TapasForMaskedLM): <add> pointer = getattr(pointer, "output_bias") <add> else: <add> pointer = getattr(pointer, "bias") <ide> elif scope_names[0] == "output_weights": <ide> pointer = getattr(pointer, "output_weights") <ide> elif scope_names[0] == "column_output_bias": <ide> def forward(self, hidden_states): <ide> return pooled_output <ide> <ide> <add># Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->Tapas <add>class TapasPredictionHeadTransform(nn.Module): <add> def __init__(self, config): <add> super().__init__() <add> self.dense = nn.Linear(config.hidden_size, config.hidden_size) <add> if isinstance(config.hidden_act, str): <add> self.transform_act_fn = ACT2FN[config.hidden_act] <add> else: <add> self.transform_act_fn = config.hidden_act <add> self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) <add> <add> def forward(self, hidden_states): <add> hidden_states = self.dense(hidden_states) <add> hidden_states = self.transform_act_fn(hidden_states) <add> hidden_states = self.LayerNorm(hidden_states) <add> return hidden_states <add> <add> <add># Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Tapas <add>class TapasLMPredictionHead(nn.Module): <add> def __init__(self, config): <add> super().__init__() <add> self.transform = TapasPredictionHeadTransform(config) <add> <add> # The output weights are the same as the input embeddings, but there is <add> # an output-only bias for each token. <add> self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) <add> <add> self.bias = nn.Parameter(torch.zeros(config.vocab_size)) <add> <add> # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` <add> self.decoder.bias = self.bias <add> <add> def forward(self, hidden_states): <add> hidden_states = self.transform(hidden_states) <add> hidden_states = self.decoder(hidden_states) <add> return hidden_states <add> <add> <add># Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Tapas <add>class TapasOnlyMLMHead(nn.Module): <add> def __init__(self, config): <add> super().__init__() <add> self.predictions = TapasLMPredictionHead(config) <add> <add> def forward(self, sequence_output): <add> prediction_scores = self.predictions(sequence_output) <add> return prediction_scores <add> <add> <ide> class TapasPreTrainedModel(PreTrainedModel): <ide> """ <ide> An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained <ide> def __init__(self, config): <ide> super().__init__(config) <ide> <ide> self.tapas = TapasModel(config, add_pooling_layer=False) <del> self.lm_head = nn.Linear(config.hidden_size, config.vocab_size) <add> self.cls = TapasOnlyMLMHead(config) <ide> <ide> self.init_weights() <ide> <ide> def get_output_embeddings(self): <del> return self.lm_head <add> return self.cls.predictions.decoder <ide> <del> def set_output_embeddings(self, word_embeddings): <del> self.lm_head = word_embeddings <add> def set_output_embeddings(self, new_embeddings): <add> self.cls.predictions.decoder = new_embeddings <ide> <ide> @add_start_docstrings_to_model_forward(TAPAS_INPUTS_DOCSTRING.format("batch_size, sequence_length")) <ide> @replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> ) <ide> <ide> sequence_output = outputs[0] <del> prediction_scores = self.lm_head(sequence_output) <add> prediction_scores = self.cls(sequence_output) <ide> <ide> masked_lm_loss = None <ide> if labels is not None: <ide><path>src/transformers/utils/dummy_pt_objects.py <ide> def from_pretrained(cls, *args, **kwargs): <ide> requires_backends(cls, ["torch"]) <ide> <ide> <add>def load_tf_weights_in_tapas(*args, **kwargs): <add> requires_backends(load_tf_weights_in_tapas, ["torch"]) <add> <add> <ide> TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST = None <ide> <ide>
5
Javascript
Javascript
extract a variable
1102fc5c1190b08ad5032333975ec57d9a0b5254
<ide><path>src/devtools/views/Components/TreeContext.js <ide> function reduceSearchState(store: Store, state: State, action: Action): State { <ide> didRequestSearch = true; <ide> } <ide> if (searchText !== prevSearchText) { <del> if (searchResults.indexOf(selectedElementID) === -1) { <add> const newSearchIndex = searchResults.indexOf(selectedElementID); <add> if (newSearchIndex === -1) { <ide> // Only move the selection if the new query <ide> // doesn't match the current selection anymore. <ide> didRequestSearch = true; <ide> } else { <ide> // Selected item still matches the new search query. <ide> // Adjust the index to reflect its position in new results. <del> searchIndex = searchResults.indexOf(selectedElementID); <add> searchIndex = newSearchIndex; <ide> } <ide> } <ide> if (didRequestSearch) {
1
PHP
PHP
fix paginator options when disabled
dc41a1ff56a4ea07836874883c8abde5cb79de36
<ide><path>lib/Cake/Test/Case/View/Helper/PaginatorHelperTest.php <ide> public function testPagingLinks() { <ide> ) <ide> ); <ide> <add> $result = $this->Paginator->prev('<i class="fa fa-angle-left"></i>', array('escape' => false), null, array('class' => 'prev disabled')); <add> $expected = array( <add> 'span' => array('class' => 'prev disabled'), <add> 'a' => array('href' => '/', 'rel' => 'prev'), <add> 'i' => array('class' => 'fa fa-angle-left'), <add> '/i', <add> '/a', <add> '/span' <add> ); <add> $this->assertTags($result, $expected); <add> <ide> $result = $this->Paginator->prev('<< Previous', null, '<strong>Disabled</strong>'); <ide> $expected = array( <ide> 'span' => array('class' => 'prev'), <ide><path>lib/Cake/View/Helper/PaginatorHelper.php <ide> protected function _pagingLink($which, $title = null, $options = array(), $disab <ide> if (!empty($disabledTitle) && $disabledTitle !== true) { <ide> $title = $disabledTitle; <ide> } <del> $options = (array)$disabledOptions + $_defaults; <add> $options = (array)$disabledOptions + $options + $_defaults; <ide> } elseif (!$this->{$check}($options['model'])) { <ide> return ''; <ide> }
2
PHP
PHP
use methods that exist on requestinterface
edd7109b6cd186004ca32ad0578294d504649364
<ide><path>src/Http/Cookie/CookieCollection.php <ide> public function getIterator() <ide> public function addToRequest(RequestInterface $request) <ide> { <ide> $uri = $request->getUri(); <del> $path = $uri->getPath(); <del> $host = $uri->getHost(); <del> $scheme = $uri->getScheme(); <del> $cookies = $this->findMatchingCookies($scheme, $host, $path); <del> $cookies = array_merge($request->getCookieParams(), $cookies); <del> <del> return $request->withCookieParams($cookies); <add> $cookies = $this->findMatchingCookies( <add> $uri->getScheme(), <add> $uri->getHost(), <add> $uri->getPath() <add> ); <add> $cookiePairs = []; <add> foreach ($cookies as $key => $value) { <add> $cookiePairs[] = sprintf("%s=%s", urlencode($key), urlencode($value)); <add> } <add> return $request->withAddedHeader('Cookie', implode('; ', $cookiePairs)); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Http/Cookie/CookieCollectionTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Http\Cookie; <ide> <add>use Cake\Http\Client\Request as ClientRequest; <ide> use Cake\Http\Client\Response as ClientResponse; <ide> use Cake\Http\Cookie\Cookie; <ide> use Cake\Http\Cookie\CookieCollection; <ide> public function testAddToRequest() <ide> ->add(new Cookie('api', 'A', null, '/api', 'example.com')) <ide> ->add(new Cookie('blog', 'b', null, '/blog', 'blog.example.com')) <ide> ->add(new Cookie('expired', 'ex', new DateTime('-2 seconds'), '/', 'example.com')); <del> $request = new ServerRequest([ <del> 'environment' => [ <del> 'HTTP_HOST' => 'example.com', <del> 'REQUEST_URI' => '/api' <del> ] <del> ]); <add> $request = new ClientRequest('http://example.com/api'); <ide> $request = $collection->addToRequest($request); <del> $this->assertCount(1, $request->getCookieParams()); <del> $this->assertSame(['api' => 'A'], $request->getCookieParams()); <add> $this->assertSame('api=A', $request->getHeaderLine('Cookie')); <ide> <del> $request = new ServerRequest([ <del> 'environment' => [ <del> 'HTTP_HOST' => 'example.com', <del> 'REQUEST_URI' => '/' <del> ] <del> ]); <add> $request = new ClientRequest('http://example.com/'); <ide> $request = $collection->addToRequest($request); <del> $this->assertCount(0, $request->getCookieParams()); <add> $this->assertSame('', $request->getHeaderLine('')); <ide> <del> $request = new ServerRequest([ <del> 'environment' => [ <del> 'HTTP_HOST' => 'example.com', <del> 'REQUEST_URI' => '/blog' <del> ] <del> ]); <add> $request = new ClientRequest('http://example.com/blog'); <ide> $request = $collection->addToRequest($request); <del> $this->assertCount(0, $request->getCookieParams(), 'domain matching should apply'); <add> $this->assertSame('', $request->getHeaderLine('Cookie'), 'domain matching should apply'); <ide> <del> $request = new ServerRequest([ <del> 'environment' => [ <del> 'HTTP_HOST' => 'foo.blog.example.com', <del> 'REQUEST_URI' => '/blog' <del> ] <del> ]); <add> $request = new ClientRequest('http://foo.blog.example.com/blog'); <ide> $request = $collection->addToRequest($request); <del> $this->assertCount(1, $request->getCookieParams(), 'domain matching should apply'); <del> $this->assertSame(['blog' => 'b'], $request->getCookieParams()); <add> $this->assertSame('blog=b', $request->getHeaderLine('Cookie')); <ide> } <ide> <ide> /** <ide> public function testAddToRequestLeadingDot() <ide> $collection = new CookieCollection(); <ide> $collection = $collection <ide> ->add(new Cookie('public', 'b', null, '/', '.example.com')); <del> $request = new ServerRequest([ <del> 'environment' => [ <del> 'HTTP_HOST' => 'example.com', <del> 'REQUEST_URI' => '/blog' <del> ] <del> ]); <add> $request = new ClientRequest('http://example.com/blog'); <ide> $request = $collection->addToRequest($request); <del> $this->assertSame(['public' => 'b'], $request->getCookieParams()); <add> $this->assertSame('public=b', $request->getHeaderLine('Cookie')); <ide> } <ide> <ide> /** <ide> public function testAddToRequestSecureCrumb() <ide> $collection = $collection <ide> ->add(new Cookie('secret', 'A', null, '/', 'example.com', true)) <ide> ->add(new Cookie('public', 'b', null, '/', '.example.com', false)); <del> $request = new ServerRequest([ <del> 'environment' => [ <del> 'HTTPS' => 'on', <del> 'HTTP_HOST' => 'example.com', <del> 'REQUEST_URI' => '/api' <del> ] <del> ]); <add> $request = new ClientRequest('https://example.com/api'); <ide> $request = $collection->addToRequest($request); <del> $this->assertSame(['secret' => 'A', 'public' => 'b'], $request->getCookieParams()); <add> $this->assertSame('secret=A; public=b', $request->getHeaderLine('Cookie')); <ide> <ide> // no HTTPS set. <del> $request = new ServerRequest([ <del> 'environment' => [ <del> 'HTTP_HOST' => 'example.com', <del> 'REQUEST_URI' => '/api' <del> ] <del> ]); <add> $request = new ClientRequest('http://example.com/api'); <ide> $request = $collection->addToRequest($request); <del> $this->assertSame(['public' => 'b'], $request->getCookieParams()); <add> $this->assertSame('public=b', $request->getHeaderLine('Cookie')); <ide> } <ide> }
2
Text
Text
fix several typos in the documentation
3c6aa163a3fd04c344a2072ab379f0778734b269
<ide><path>docs/installation/mac.md <ide> The `ACTIVE` machine, in this case `default`, is the one your environment is poi <ide> ![Bad Address](images/bad_host.png) <ide> <ide> This didn't work. The reason it doesn't work is your `DOCKER_HOST` address is <del> not the localhost address (0.0.0.0) but is instead the address of the <del> your Docker VM. <add> not the localhost address (0.0.0.0) but is instead the address of your Docker VM. <ide> <ide> 5. Get the address of the `default` VM. <ide> <ide><path>docs/security/trust/content_trust.md <ide> ability to use digital signatures for data sent to and received from remote <ide> Docker registries. These signatures allow client-side verification of the <ide> integrity and publisher of specific image tags. <ide> <del>Currently, content trust is disabled by default. You must enabled it by setting <add>Currently, content trust is disabled by default. You must enable it by setting <ide> the `DOCKER_CONTENT_TRUST` environment variable. Refer to the <ide> [environment variables](../../reference/commandline/cli.md#environment-variables) <ide> and [Notary](../../reference/commandline/cli.md#notary) configuration
2
Python
Python
fix flaky test in preprocessing
42b3d37a54545882699283b5764cf3c997f8d9cd
<ide><path>tests/keras/preprocessing/test_sequence.py <ide> def test_skipgrams(): <ide> couples, labels = skipgrams(np.arange(5), vocabulary_size=5, window_size=1, <ide> categorical=True) <ide> for couple in couples: <del> assert couple[0] - couple[1] < 3 <add> assert couple[0] - couple[1] <= 3 <ide> for l in labels: <ide> assert len(l) == 2 <ide>
1
Java
Java
improve precondition checks in testclassscanner
feb2a30910fe6410ffa2912fe547883de3add6c6
<ide><path>spring-test/src/main/java/org/springframework/test/context/aot/TestClassScanner.java <ide> package org.springframework.test.context.aot; <ide> <ide> import java.lang.annotation.Annotation; <add>import java.nio.file.Files; <ide> import java.nio.file.Path; <ide> import java.util.Arrays; <ide> import java.util.Comparator; <ide> class TestClassScanner { <ide> * @param classpathRoots the classpath roots to scan <ide> */ <ide> TestClassScanner(Set<Path> classpathRoots) { <del> Assert.notEmpty(classpathRoots, "'classpathRoots' must not be null or empty"); <del> Assert.noNullElements(classpathRoots, "'classpathRoots' must not contain null elements"); <del> this.classpathRoots = classpathRoots; <add> this.classpathRoots = assertPreconditions(classpathRoots); <ide> } <ide> <ide> <ide> private static boolean isGenericSpringTestClass(Class<?> clazz) { <ide> mergedAnnotations.isPresent(BootstrapWith.class)); <ide> } <ide> <add> <add> private static Set<Path> assertPreconditions(Set<Path> classpathRoots) { <add> Assert.notEmpty(classpathRoots, "'classpathRoots' must not be null or empty"); <add> Assert.noNullElements(classpathRoots, "'classpathRoots' must not contain null elements"); <add> classpathRoots.forEach(classpathRoot -> Assert.isTrue(Files.exists(classpathRoot), <add> () -> "Classpath root [%s] does not exist".formatted(classpathRoot))); <add> return classpathRoots; <add> } <add> <ide> }
1
PHP
PHP
return the used traits from setuptraits
4586bb74015791dffda1ae6275c94db8a651f498
<ide><path>src/Illuminate/Foundation/Testing/TestCase.php <ide> protected function refreshApplication() <ide> /** <ide> * Boot the testing helper traits. <ide> * <del> * @return void <add> * @return array <ide> */ <ide> protected function setUpTraits() <ide> { <ide> protected function setUpTraits() <ide> if (isset($uses[WithoutEvents::class])) { <ide> $this->disableEventsForAllTests(); <ide> } <add> <add> return $uses; <ide> } <ide> <ide> /**
1
Python
Python
remove print statements from test
376c5813a75e4ecb6770bf62aa6c7cbbe3f9387a
<ide><path>spacy/tests/doc/test_doc_api.py <ide> def test_doc_api_runtime_error(en_tokenizer): <ide> if len(np) > 1: <ide> nps.append((np.start_char, np.end_char, np.root.tag_, np.text, np.root.ent_type_)) <ide> for np in nps: <del> print(np) <del> for word in doc: <del> print(word.idx, word.text, word.head.i, word.head.text) <ide> doc.merge(*np) <ide> <ide>
1
Text
Text
update the attribute table
ffe8546c7d76fc961ad02a61b7d5145b34147489
<ide><path>fixtures/attribute-behavior/AttributeTableSnapshot.md <ide> ## `capture` (on `<input>` inside `<div>`) <ide> | Test Case | Flags | Result | <ide> | --- | --- | --- | <del>| `capture=(string)`| (changed)| `<empty string>` | <del>| `capture=(empty string)`| (initial)| `<null>` | <del>| `capture=(array with string)`| (changed)| `<empty string>` | <add>| `capture=(string)`| (changed)| `"environment"` | <add>| `capture=(empty string)`| (changed)| `<empty string>` | <add>| `capture=(array with string)`| (changed)| `"environment"` | <ide> | `capture=(empty array)`| (changed)| `<empty string>` | <del>| `capture=(object)`| (changed)| `<empty string>` | <del>| `capture=(numeric string)`| (changed)| `<empty string>` | <del>| `capture=(-1)`| (changed)| `<empty string>` | <del>| `capture=(0)`| (initial)| `<null>` | <del>| `capture=(integer)`| (changed)| `<empty string>` | <del>| `capture=(NaN)`| (initial, warning)| `<null>` | <del>| `capture=(float)`| (changed)| `<empty string>` | <add>| `capture=(object)`| (changed)| `"result of toString()"` | <add>| `capture=(numeric string)`| (changed)| `"42"` | <add>| `capture=(-1)`| (changed)| `"-1"` | <add>| `capture=(0)`| (changed)| `"0"` | <add>| `capture=(integer)`| (changed)| `"1"` | <add>| `capture=(NaN)`| (changed, warning)| `"NaN"` | <add>| `capture=(float)`| (changed)| `"99.99"` | <ide> | `capture=(true)`| (changed)| `<empty string>` | <ide> | `capture=(false)`| (initial)| `<null>` | <del>| `capture=(string 'true')`| (changed)| `<empty string>` | <del>| `capture=(string 'false')`| (changed)| `<empty string>` | <del>| `capture=(string 'on')`| (changed)| `<empty string>` | <del>| `capture=(string 'off')`| (changed)| `<empty string>` | <del>| `capture=(symbol)`| (initial, warning, ssr mismatch)| `<null>` | <add>| `capture=(string 'true')`| (changed)| `"true"` | <add>| `capture=(string 'false')`| (changed)| `"false"` | <add>| `capture=(string 'on')`| (changed)| `"on"` | <add>| `capture=(string 'off')`| (changed)| `"off"` | <add>| `capture=(symbol)`| (initial, warning, ssr error, ssr mismatch)| `<null>` | <ide> | `capture=(function)`| (initial, warning, ssr mismatch)| `<null>` | <ide> | `capture=(null)`| (initial)| `<null>` | <ide> | `capture=(undefined)`| (initial)| `<null>` | <ide> | `defaultValue=(string 'false')`| (changed)| `"false"` | <ide> | `defaultValue=(string 'on')`| (changed)| `"on"` | <ide> | `defaultValue=(string 'off')`| (changed)| `"off"` | <del>| `defaultValue=(symbol)`| (initial, ssr error, ssr mismatch)| `<empty string>` | <del>| `defaultValue=(function)`| (initial, ssr mismatch)| `<empty string>` | <add>| `defaultValue=(symbol)`| (changed, error, warning, ssr error)| `` | <add>| `defaultValue=(function)`| (changed, ssr warning)| `"function f() {}"` | <ide> | `defaultValue=(null)`| (initial, ssr warning)| `<empty string>` | <ide> | `defaultValue=(undefined)`| (initial)| `<empty string>` | <ide> <ide> | `value=(string 'false')`| (changed)| `"false"` | <ide> | `value=(string 'on')`| (changed)| `"on"` | <ide> | `value=(string 'off')`| (changed)| `"off"` | <del>| `value=(symbol)`| (initial, warning, ssr error, ssr mismatch)| `<empty string>` | <del>| `value=(function)`| (initial, warning, ssr mismatch)| `<empty string>` | <add>| `value=(symbol)`| (changed, error, warning, ssr error)| `` | <add>| `value=(function)`| (changed, warning, ssr warning)| `"function f() {}"` | <ide> | `value=(null)`| (initial, warning, ssr warning)| `<empty string>` | <ide> | `value=(undefined)`| (initial)| `<empty string>` | <ide> <ide> | `value=(string 'false')`| (changed)| `"false"` | <ide> | `value=(string 'on')`| (changed)| `"on"` | <ide> | `value=(string 'off')`| (changed)| `"off"` | <del>| `value=(symbol)`| (initial, warning, ssr error, ssr mismatch)| `<empty string>` | <del>| `value=(function)`| (initial, warning, ssr mismatch)| `<empty string>` | <add>| `value=(symbol)`| (changed, error, warning, ssr error)| `` | <add>| `value=(function)`| (changed, warning)| `"function f() {}"` | <ide> | `value=(null)`| (initial, warning, ssr warning)| `<empty string>` | <ide> | `value=(undefined)`| (initial)| `<empty string>` | <ide> <ide> | `value=(string 'false')`| (initial)| `<empty string>` | <ide> | `value=(string 'on')`| (initial)| `<empty string>` | <ide> | `value=(string 'off')`| (initial)| `<empty string>` | <del>| `value=(symbol)`| (initial, warning, ssr error, ssr mismatch)| `<empty string>` | <add>| `value=(symbol)`| (changed, error, warning, ssr error)| `` | <ide> | `value=(function)`| (initial, warning)| `<empty string>` | <ide> | `value=(null)`| (initial, warning, ssr warning)| `<empty string>` | <ide> | `value=(undefined)`| (initial)| `<empty string>` |
1
Mixed
Text
add recommended videos
fde956ea24fea1f30f5fe0c801a6b8c3750eb54e
<ide><path>docs/tutorials/videos.md <add>--- <add>id: videos <add>title: 'Videos' <add>sidebar_label: 'Videos' <add>description: 'The official Fundamentals tutorial for Redux: learn the fundamentals of using Redux' <add>hide_title: true <add>--- <add> <add>import { DetailedExplanation } from '../components/DetailedExplanation' <add>import LiteYouTubeEmbed from 'react-lite-youtube-embed'; <add>import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css' <add> <add># Recommended Videos <add> <add>## Redux Toolkit Complete Tutorial with Dave Gray <add> <add>This React Redux Full Course for Beginners is a complete tutorial full of 4 hours of React and Redux Toolkit code and instruction to help you learn state management with Redux. Think of this React Redux full course tutorial as a video textbook with 7 clearly defined chapters. <add> <add><LiteYouTubeEmbed <add> id="NqzdVN2tyvQ" <add> title="React Redux Full Course for Beginners | Redux Toolkit Complete Tutorial" <add>/> <add> <add>## Modern Redux with Redux Toolkit (RTK) and TypeScript with Jamund Ferguson <add> <add>[https://app.egghead.io/lessons/react-intro-to-modern-redux-with-rtk-and-typescript?pl=modern-redux-with-redux-toolkit-rtk-and-typescript-64f243c8](https://app.egghead.io/lessons/react-intro-to-modern-redux-with-rtk-and-typescript?pl=modern-redux-with-redux-toolkit-rtk-and-typescript-64f243c8) <add> <add>In this course we take a basic shopping cart application built with React and fully power it with Redux and RTK using TypeScript. For those of you familiar with Redux Hooks, we use those here, but the emphasis is more on how the Redux Toolkit simplifies the process of setting up your redux application including building slices, reducers, selectors and thunks. Everything we do in the course is typed with TypeScript to make your application development process as smooth and powerful as possible. <add> <add>## Modernizing a Legacy Redux Application with React Hooks with Jamund Ferguson <add> <add>[https://app.egghead.io/lessons/react-setup-the-currency-conversion-calculator?pl=modernizing-a-legacy-redux-application-with-react-hooks-c528](https://app.egghead.io/lessons/react-setup-the-currency-conversion-calculator?pl=modernizing-a-legacy-redux-application-with-react-hooks-c528) <add> <add>Many engineers working with redux have felt burdened by large amounts of boilerplate code and confusing indirection. These apps often rely on legacy patterns that are no longer recommended, but are still commonly found in production code bases. If you are are an engineer working on such an application, this course is for you. <add> <add>## Confidently Testing Redux Applications with Jest & TypeScript with Jamund Ferguson <add> <add>[https://app.egghead.io/lessons/jest-intro-to-confidently-testing-redux-applications-with-jest-typescript?pl=confidently-testing-redux-applications-with-jest-typescript-16e17d9b](https://app.egghead.io/lessons/jest-intro-to-confidently-testing-redux-applications-with-jest-typescript?pl=confidently-testing-redux-applications-with-jest-typescript-16e17d9b) <add> <add>Best practices for building & testing redux applications have changed dramatically over time. This course aims to be a comprehensive and up-to-date resource for those seeking to confidently test their redux apps. Whether you're just getting started or want to improve on your existing testing strategy, there will be something in this course for you. <ide><path>docs/tutorials/videos/dave-grays-rtk-complete-tutorial.md <del>--- <del>id: dave-grays-rtk-complete-tutorial <del>title: 'Redux Toolkit Complete Tutorial' <del>sidebar_label: "Dave Gray's Redux Toolkit Complete Tutorial" <del>description: 'The official Fundamentals tutorial for Redux: learn the fundamentals of using Redux' <del>hide_title: true <del>--- <del> <del>import { DetailedExplanation } from '../../components/DetailedExplanation' <del>import LiteYouTubeEmbed from 'react-lite-youtube-embed'; <del>import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css' <del> <del># Dave Gray's Redux Toolkit Complete Tutorial <del> <del><LiteYouTubeEmbed <del> id="NqzdVN2tyvQ" <del> title="React Redux Full Course for Beginners | Redux Toolkit Complete Tutorial" <del>/> <del> <del>## Details <del> <del>This React Redux Full Course for Beginners is a complete tutorial full of 4 hours of React and Redux Toolkit code and instruction to help you learn state management with Redux. Think of this React Redux full course tutorial as a video textbook with 7 clearly defined chapters. <del> <del>:::info Course Summary <del> <del>- Introduction <del>- Chapter 1: Redux Toolkit Intro <del>- Chapter 2: App Structure & Data Flow <del>- Chapter 3: Async Logic & Thunks <del>- Chapter 4: Blog Project <del>- Chapter 5: Performance Optimizations <del>- Chapter 6: RTK Query Intro Project <del>- Chapter 7: Advanced Redux & RTK Query <del> <del>::: <ide><path>website/sidebars.js <ide> module.exports = { <ide> 'tutorials/fundamentals/part-8-modern-redux' <ide> ] <ide> }, <del> { <del> type: 'category', <del> label: 'Videos', <del> items: [ <del> 'tutorials/videos/dave-grays-rtk-complete-tutorial', <del> { <del> type: 'link', <del> label: 'Modern Redux with RTK and TS', <del> href: <del> 'https://app.egghead.io/lessons/react-intro-to-modern-redux-with-rtk-and-typescript?pl=modern-redux-with-redux-toolkit-rtk-and-typescript-64f243c8' // The external URL <del> }, <del> { <del> type: 'link', <del> label: 'Modernizing Legacy Redux Apps', <del> href: <del> 'https://app.egghead.io/courses/modernizing-a-legacy-redux-application-with-react-hooks-c528' // The external URL <del> }, <del> { <del> type: 'link', <del> label: 'Testing Redux Apps with Jest', <del> href: <del> 'https://app.egghead.io/lessons/jest-intro-to-confidently-testing-redux-applications-with-jest-typescript?pl=confidently-testing-redux-applications-with-jest-typescript-16e17d9b' // The external URL <del> } <del> ] <del> } <add> 'tutorials/videos' <add> <ide> ], <ide> 'Using Redux': [ <ide> 'usage/index',
3
Ruby
Ruby
add missing comment out [ci skip]
ec3933e14c8b0df3fc306c59d63e3f10c51cb1e1
<ide><path>activesupport/lib/active_support/core_ext/array/access.rb <ide> def to(position) <ide> # <ide> # people = ["David", "Rafael", "Aaron", "Todd"] <ide> # people.without "Aaron", "Todd" <del> # => ["David", "Rafael"] <add> # # => ["David", "Rafael"] <ide> # <ide> # Note: This is an optimization of `Enumerable#without` that uses `Array#-` <ide> # instead of `Array#reject` for performance reasons.
1
Javascript
Javascript
remove unused module alias
4c32dd96b7f910a1640390c35be6e60997afb9eb
<ide><path>server/build/babel/preset.js <ide> module.exports = { <ide> 'next/head': require.resolve('../../../lib/head'), <ide> 'next/document': require.resolve('../../../server/document'), <ide> 'next/router': require.resolve('../../../lib/router'), <del> 'styled-jsx/style': require.resolve('styled-jsx/style'), <del> 'ansi-html': require.resolve('ansi-html') <add> 'styled-jsx/style': require.resolve('styled-jsx/style') <ide> } <ide> } <ide> ]
1
Java
Java
add additional test for daylight savings glitch
6914aff825bfbf58291fa39a131471f312eafe04
<ide><path>spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java <ide> public CronTriggerTests(Date date, TimeZone timeZone) { <ide> @Parameters <ide> public static List<Object[]> getParameters() { <ide> List<Object[]> list = new ArrayList<Object[]>(); <del> list.add(new Object[] { new Date(), TimeZone.getDefault() }); <add> list.add(new Object[] { new Date(), TimeZone.getTimeZone("PST") }); <ide> list.add(new Object[] { new Date(), TimeZone.getTimeZone("CET") }); <ide> return list; <ide> } <ide> public void testMonthSequence() throws Exception { <ide> assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context3)); <ide> } <ide> <add> @Test <add> public void testDaylightSavingMissingHour() throws Exception { <add> // This trigger has to be somewhere in between 2am and 3am <add> CronTrigger trigger = new CronTrigger("0 10 2 * * *", timeZone); <add> calendar.set(Calendar.DAY_OF_MONTH, 31); <add> calendar.set(Calendar.MONTH, Calendar.MARCH); <add> calendar.set(Calendar.YEAR, 2013); <add> calendar.set(Calendar.HOUR_OF_DAY, 1); <add> calendar.set(Calendar.SECOND, 54); <add> Date date = calendar.getTime(); <add> TriggerContext context1 = getTriggerContext(date); <add> if (timeZone.equals(TimeZone.getTimeZone("CET"))) { <add> // Clocks go forward an hour so 2am doesn't exist in CET for this date <add> calendar.add(Calendar.DAY_OF_MONTH, 1); <add> } <add> calendar.add(Calendar.HOUR_OF_DAY, 1); <add> calendar.set(Calendar.MINUTE, 10); <add> calendar.set(Calendar.SECOND, 0); <add> assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); <add> } <ide> <ide> private void assertMatchesNextSecond(CronTrigger trigger, Calendar calendar) { <ide> Date date = calendar.getTime();
1
Text
Text
add shirtstarter to examples of production apps
6485e219563c1cf7e4e871ed0699937a2c824990
<ide><path>docs/docs/examples.md <ide> prev: complementary-tools.html <ide> * **[Instagram.com](http://instagram.com/)** Is 100% built on React. <ide> * **[Facebook.com](http://www.facebook.com/)** 's commenting interface, ads creation flows, and page insights. <ide> * **[Khan Academy](http://khanacademy.org/)** Uses React for most new JS development. <add>* **[Shirtstarter](https://www.shirtstarter.com/)** Is 100% built on React. <ide> <ide> <ide> ### Sample Code
1
Ruby
Ruby
fix regression in numericality validations
9c330798b0a77762b72a833519e10b01738cf79c
<ide><path>activemodel/lib/active_model/validations/numericality.rb <ide> def validate_each(record, attr_name, value) <ide> return <ide> end <ide> <add> if raw_value.is_a?(String) <add> value = parse_raw_value_as_a_number(raw_value) <add> end <add> <ide> options.slice(*CHECKS.keys).each do |option, option_value| <ide> case option <ide> when :odd, :even <ide> def validate_each(record, attr_name, value) <ide> protected <ide> <ide> def is_number?(raw_value) <del> parsed_value = Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/ <del> !parsed_value.nil? <add> !parse_raw_value_as_a_number(raw_value).nil? <ide> rescue ArgumentError, TypeError <ide> false <ide> end <ide> <add> def parse_raw_value_as_a_number(raw_value) <add> Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/ <add> end <add> <ide> def is_integer?(raw_value) <ide> /\A[+-]?\d+\z/ === raw_value.to_s <ide> end
1
Text
Text
fix some translation bug
bea24ca944a7f3bdf814af3ae2802a4f7d976349
<ide><path>docs/docs/02-displaying-data.zh-CN.md <ide> --- <ide> id: displaying-data-zh-CN <del>title: 显示数据 Displaying Data <add>title: 显示数据 <ide> layout: docs <ide> permalink: displaying-data-zh-CN.html <ide> prev: why-react-zh-CN.html <ide> setInterval(function() { <ide> }, 500); <ide> ``` <ide> <del>## Reactive Updates <add>## 被动更新 (Reactive Updates) <ide> <ide> 在浏览器中打开 `hello-react.html` ,在输入框输入你的名字。你会发现 React 在用户界面中只改变了时间, 任何你在输入框输入的内容一直保留着,即使你没有写任何代码来完成这个功能。React 为你解决了这个问题,做了正确的事。 <ide> <del>我们想到的方法是除非不得不操作 DOM ,React 是不会去操作 DOM 的。**它用一种更快的内置仿造的 DOM 来操作差异,为你计算出出效率最高的 DOM 改变** <add>我们想到的方法是除非不得不操作 DOM ,React 是不会去操作 DOM 的。**它用一种更快的内置仿造的 DOM 来操作差异,为你计算出出效率最高的 DOM 改变**。 <ide> <del>对这个组件的输入称为 `props` - "properties"的缩写。得益于 JSX 语法,它们通过参数传递。你必须知道在组件里,这些属性是不可改变的,也就是说 **`this.props` 是只读的** <add>对这个组件的输入称为 `props` - "properties"的缩写。得益于 JSX 语法,它们通过参数传递。你必须知道在组件里,这些属性是不可改变的,也就是说 **`this.props` 是只读的**。 <ide> <ide> ## 组件就像是函数 <ide>
1
PHP
PHP
update bootstrap version
25559cdc14066566658d6c9a7efd8a0e1d0ffccd
<ide><path>src/Illuminate/Foundation/Console/Presets/Bootstrap.php <ide> public static function install() <ide> protected static function updatePackageArray(array $packages) <ide> { <ide> return [ <del> 'bootstrap' => '^4.0.0-beta.3', <add> 'bootstrap' => '^4.0.0', <ide> 'jquery' => '^3.2', <ide> 'popper.js' => '^1.12', <ide> ] + $packages;
1
Ruby
Ruby
fix tests for deprecating sha1
28b4923dad7a421f6f6d2598a5661a147268a4c7
<ide><path>Library/Homebrew/test/test_checksum.rb <ide> <ide> class ChecksumTests < Homebrew::TestCase <ide> def test_empty? <del> assert_empty Checksum.new(:sha1, "") <add> assert_empty Checksum.new(:sha256, "") <ide> end <ide> <ide> def test_equality <del> a = Checksum.new(:sha1, TEST_SHA1) <del> b = Checksum.new(:sha1, TEST_SHA1) <add> a = Checksum.new(:sha256, TEST_SHA256) <add> b = Checksum.new(:sha256, TEST_SHA256) <ide> assert_equal a, b <ide> <del> a = Checksum.new(:sha1, TEST_SHA1) <del> b = Checksum.new(:sha1, TEST_SHA1.reverse) <add> a = Checksum.new(:sha256, TEST_SHA256) <add> b = Checksum.new(:sha256, TEST_SHA256.reverse) <ide> refute_equal a, b <ide> <ide> a = Checksum.new(:sha1, TEST_SHA1) <ide><path>Library/Homebrew/test/test_checksum_verification.rb <ide> def teardown <ide> @_f.clear_cache <ide> end <ide> <del> def test_good_sha1 <del> formula do <del> sha1 TESTBALL_SHA1 <del> end <del> <del> assert_checksum_good <del> end <del> <del> def test_bad_sha1 <del> formula do <del> sha1 "7ea8a98acb8f918df723c2ae73fe67d5664bfd7e" <del> end <del> <del> assert_checksum_bad <del> end <del> <ide> def test_good_sha256 <ide> formula do <ide> sha256 TESTBALL_SHA256 <ide><path>Library/Homebrew/test/test_formula.rb <ide> def test_formula_spec_integration <ide> homepage "http://example.com" <ide> url "http://example.com/test-0.1.tbz" <ide> mirror "http://example.org/test-0.1.tbz" <del> sha1 TEST_SHA1 <add> sha256 TEST_SHA256 <ide> <ide> head "http://example.com/test.git", :tag => "foo" <ide> <ide><path>Library/Homebrew/test/test_formula_spec_selection.rb <ide> def test_selects_head_when_exclusive <ide> <ide> def test_incomplete_spec_not_selected <ide> f = formula { <del> sha1 TEST_SHA1 <add> sha256 TEST_SHA256 <ide> version "1.0" <ide> head "foo" <ide> } <ide> def test_incomplete_spec_not_selected <ide> <ide> def test_incomplete_stable_not_set <ide> f = formula { <del> sha1 TEST_SHA1 <add> sha256 TEST_SHA256 <ide> devel { url "foo-1.1a" } <ide> head "foo" <ide> } <ide><path>Library/Homebrew/test/test_resource.rb <ide> def test_mirrors <ide> <ide> def test_checksum_setters <ide> assert_nil @resource.checksum <del> @resource.sha1(TEST_SHA1) <del> assert_equal Checksum.new(:sha1, TEST_SHA1), @resource.checksum <ide> @resource.sha256(TEST_SHA256) <ide> assert_equal Checksum.new(:sha256, TEST_SHA256), @resource.checksum <ide> end <ide> def test_verify_download_integrity_missing <ide> <ide> def test_verify_download_integrity_mismatch <ide> fn = stub(:file? => true) <del> checksum = @resource.sha1(TEST_SHA1) <add> checksum = @resource.sha256(TEST_SHA256) <ide> <ide> fn.expects(:verify_checksum).with(checksum). <ide> raises(ChecksumMismatchError.new(fn, checksum, Object.new)) <ide><path>Library/Homebrew/test/test_software_spec.rb <ide> def setup <ide> <ide> def test_checksum_setters <ide> checksums = { <del> :snow_leopard_32 => "deadbeef"*5, <del> :snow_leopard => "faceb00c"*5, <del> :lion => "baadf00d"*5, <del> :mountain_lion => "8badf00d"*5 <add> :snow_leopard_32 => "deadbeef"*8, <add> :snow_leopard => "faceb00c"*8, <add> :lion => "baadf00d"*8, <add> :mountain_lion => "8badf00d"*8 <ide> } <ide> <del> checksums.each_pair do |cat, sha1| <del> @spec.sha1(sha1 => cat) <add> checksums.each_pair do |cat, digest| <add> @spec.sha256(digest => cat) <ide> end <ide> <del> checksums.each_pair do |cat, sha1| <add> checksums.each_pair do |cat, digest| <ide> checksum, = @spec.checksum_for(cat) <del> assert_equal Checksum.new(:sha1, sha1), checksum <add> assert_equal Checksum.new(:sha256, digest), checksum <ide> end <ide> end <ide>
6
Javascript
Javascript
add more tests for sizzle attributes
8084ab24bc269af22e0cfd4af77a7a17eb39729a
<ide><path>test/unit/selector.js <ide> test("name", function() { <ide> form.remove(); <ide> }); <ide> <del>test( "comma selectors", function() { <add>test( "selectors with comma", function() { <ide> expect( 4 ); <ide> <ide> var fixture = jQuery( "<div><h2><span/></h2><div><p><span/></p><p/></div></div>" ); <ide> test( "comma selectors", function() { <ide> equal( fixture.find( "h2 , div p" ).filter( "h2" ).length, 1, "has to find one <h2>" ); <ide> }); <ide> <add>test("attributes", function() { <add> expect( 54 ); <ide> <del>test("attributes - jQuery only", function() { <del> expect( 5 ); <add> var opt, input, attrbad, div, withScript; <ide> <ide> t( "Find elements with a tabindex attribute", "[tabindex]", ["listWithTabIndex", "foodWithNegativeTabIndex", "linkWithTabIndex", "linkWithNegativeTabIndex", "linkWithNoHrefWithTabIndex", "linkWithNoHrefWithNegativeTabIndex"] ); <ide> <add> t( "Attribute Exists", "#qunit-fixture a[title]", ["google"] ); <add> t( "Attribute Exists (case-insensitive)", "#qunit-fixture a[TITLE]", ["google"] ); <add> t( "Attribute Exists", "#qunit-fixture *[title]", ["google"] ); <add> t( "Attribute Exists", "#qunit-fixture [title]", ["google"] ); <add> t( "Attribute Exists", "#qunit-fixture a[ title ]", ["google"] ); <add> <add> t( "Boolean attribute exists", "#select2 option[selected]", ["option2d"]); <add> t( "Boolean attribute equals", "#select2 option[selected='selected']", ["option2d"]); <add> <add> t( "Attribute Equals", "#qunit-fixture a[rel='bookmark']", ["simon1"] ); <add> t( "Attribute Equals", "#qunit-fixture a[rel='bookmark']", ["simon1"] ); <add> t( "Attribute Equals", "#qunit-fixture a[rel=bookmark]", ["simon1"] ); <add> t( "Attribute Equals", "#qunit-fixture a[href='http://www.google.com/']", ["google"] ); <add> t( "Attribute Equals", "#qunit-fixture a[ rel = 'bookmark' ]", ["simon1"] ); <add> t( "Attribute Equals Number", "#qunit-fixture option[value=1]", ["option1b","option2b","option3b","option4b","option5c"] ); <add> t( "Attribute Equals Number", "#qunit-fixture li[tabIndex=-1]", ["foodWithNegativeTabIndex"] ); <add> <add> document.getElementById("anchor2").href = "#2"; <add> t( "href Attribute", "p a[href^=#]", ["anchor2"] ); <add> t( "href Attribute", "p a[href*=#]", ["simon1", "anchor2"] ); <add> <add> t( "for Attribute", "form label[for]", ["label-for"] ); <add> t( "for Attribute in form", "#form [for=action]", ["label-for"] ); <add> <add> t( "Attribute containing []", "input[name^='foo[']", ["hidden2"] ); <add> t( "Attribute containing []", "input[name^='foo[bar]']", ["hidden2"] ); <add> t( "Attribute containing []", "input[name*='[bar]']", ["hidden2"] ); <add> t( "Attribute containing []", "input[name$='bar]']", ["hidden2"] ); <add> t( "Attribute containing []", "input[name$='[bar]']", ["hidden2"] ); <add> t( "Attribute containing []", "input[name$='foo[bar]']", ["hidden2"] ); <add> t( "Attribute containing []", "input[name*='foo[bar]']", ["hidden2"] ); <add> <add> t( "Multiple Attribute Equals", "#form input[type='radio'], #form input[type='hidden']", ["radio1", "radio2", "hidden1"] ); <add> t( "Multiple Attribute Equals", "#form input[type='radio'], #form input[type=\"hidden\"]", ["radio1", "radio2", "hidden1"] ); <add> t( "Multiple Attribute Equals", "#form input[type='radio'], #form input[type=hidden]", ["radio1", "radio2", "hidden1"] ); <add> <add> t( "Attribute selector using UTF8", "span[lang=中文]", ["台北"] ); <add> <add> t( "Attribute Begins With", "a[href ^= 'http://www']", ["google","yahoo"] ); <add> t( "Attribute Ends With", "a[href $= 'org/']", ["mark"] ); <add> t( "Attribute Contains", "a[href *= 'google']", ["google","groups"] ); <add> t( "Attribute Is Not Equal", "#ap a[hreflang!='en']", ["google","groups","anchor1"] ); <add> <add> t( "Empty values", "#select1 option[value='']", ["option1a"] ); <add> t( "Empty values", "#select1 option[value!='']", ["option1b","option1c","option1d"] ); <add> <add> t( "Select options via :selected", "#select1 option:selected", ["option1a"] ); <add> t( "Select options via :selected", "#select2 option:selected", ["option2d"] ); <add> t( "Select options via :selected", "#select3 option:selected", ["option3b", "option3c"] ); <add> t( "Select options via :selected", "select[name='select2'] option:selected", ["option2d"] ); <add> <add> t( "Grouped Form Elements", "input[name='foo[bar]']", ["hidden2"] ); <add> <add> // Make sure attribute value quoting works correctly. See jQuery #6093; #6428; #13894 <add> // Use seeded results to bypass querySelectorAll optimizations <add> attrbad = jQuery( <add> "<input type='hidden' id='attrbad_space' name='foo bar'/>" + <add> "<input type='hidden' id='attrbad_dot' value='2' name='foo.baz'/>" + <add> "<input type='hidden' id='attrbad_brackets' value='2' name='foo[baz]'/>" + <add> "<input type='hidden' id='attrbad_injection' data-attr='foo_baz&#39;]'/>" + <add> "<input type='hidden' id='attrbad_quote' data-attr='&#39;'/>" + <add> "<input type='hidden' id='attrbad_backslash' data-attr='&#92;'/>" + <add> "<input type='hidden' id='attrbad_backslash_quote' data-attr='&#92;&#39;'/>" + <add> "<input type='hidden' id='attrbad_backslash_backslash' data-attr='&#92;&#92;'/>" + <add> "<input type='hidden' id='attrbad_unicode' data-attr='&#x4e00;'/>" <add> ).appendTo("#qunit-fixture").get(); <add> <add> t( "Underscores don't need escaping", "input[id=types_all]", ["types_all"] ); <add> <add> t( "input[type=text]", "#form input[type=text]", ["text1", "text2", "hidden2", "name"] ); <add> t( "input[type=search]", "#form input[type=search]", ["search"] ); <add> <add> withScript = supportjQuery( "<div><span><script src=''/></span></div>" ); <add> ok( withScript.find( "#moretests script[src]" ).has( "script" ), "script[src] (jQuery #13777)" ); <add> <add> div = document.getElementById("foo"); <add> t( "Object.prototype property \"constructor\" (negative)", "[constructor]", [] ); <add> t( "Gecko Object.prototype property \"watch\" (negative)", "[watch]", [] ); <add> div.setAttribute( "constructor", "foo" ); <add> div.setAttribute( "watch", "bar" ); <add> t( "Object.prototype property \"constructor\"", "[constructor='foo']", ["foo"] ); <add> t( "Gecko Object.prototype property \"watch\"", "[watch='bar']", ["foo"] ); <add> <add> t( "Value attribute is retrieved correctly", "input[value=Test]", ["text1", "text2"] ); <add> <ide> // #12600 <ide> ok( <ide> jQuery("<select value='12600'><option value='option' selected='selected'></option><option value=''></option></select>")
1
Python
Python
fix naming conflict and formatting
bea863acd255407887806d1089c1f63896cdf084
<ide><path>spacy/lang/zh/__init__.py <ide> def to_bytes(self, **kwargs): <ide> return util.to_bytes(serializers, []) <ide> <ide> def from_bytes(self, data, **kwargs): <del> data = {"features_b": b"", "weights_b": b"", "processors_data": None} <del> # pkuseg_features_b = b"" <del> # pkuseg_weights_b = b"" <del> # pkuseg_processors_data = None <add> pkuseg_data = {"features_b": b"", "weights_b": b"", "processors_data": None} <ide> <ide> def deserialize_pkuseg_features(b): <del> data["features_b"] = b <add> pkuseg_data["features_b"] = b <ide> <ide> def deserialize_pkuseg_weights(b): <del> data["weights_b"] = b <add> pkuseg_data["weights_b"] = b <ide> <ide> def deserialize_pkuseg_processors(b): <del> data["processors_data"] = srsly.msgpack_loads(b) <add> pkuseg_data["processors_data"] = srsly.msgpack_loads(b) <ide> <ide> deserializers = OrderedDict( <ide> ( <ide> def deserialize_pkuseg_processors(b): <ide> ) <ide> util.from_bytes(data, deserializers, []) <ide> <del> if data["features_b"] and data["weights_b"]: <add> if pkuseg_data["features_b"] and pkuseg_data["weights_b"]: <ide> with tempfile.TemporaryDirectory() as tempdir: <ide> tempdir = Path(tempdir) <ide> with open(tempdir / "features.pkl", "wb") as fileh: <del> fileh.write(data["features_b"]) <add> fileh.write(pkuseg_data["features_b"]) <ide> with open(tempdir / "weights.npz", "wb") as fileh: <del> fileh.write(data["weights_b"]) <add> fileh.write(pkuseg_data["weights_b"]) <ide> try: <ide> import pkuseg <ide> except ImportError: <ide> def deserialize_pkuseg_processors(b): <ide> + _PKUSEG_INSTALL_MSG <ide> ) <ide> self.pkuseg_seg = pkuseg.pkuseg(str(tempdir)) <del> if data["processors_data"]: <del> (user_dict, do_process, common_words, other_words) = data[ <del> "processors_data" <del> ] <add> if pkuseg_data["processors_data"]: <add> processors_data = pkuseg_data["processors_data"] <add> (user_dict, do_process, common_words, other_words) = processors_data <ide> self.pkuseg_seg.preprocesser = pkuseg.Preprocesser(user_dict) <ide> self.pkuseg_seg.postprocesser.do_process = do_process <ide> self.pkuseg_seg.postprocesser.common_words = set(common_words)
1
Text
Text
clarify link to above section
6bcb3bd3678f3975e79a4688a1766ad940b5cfc4
<ide><path>docs/Homebrew-brew-Maintainer-Guide.md <ide> There are many checks that run on every PR. The following is a quick list of the <ide> any new/changed dependencies. See [Type Checking With Sorbet](Typechecking.md) for more information about RBI files <ide> and typechecking. <ide> - `Triage / review`: This verifies that the PR has been open for long enough. <del> See [above](#automatic-approvals) for more information about automatic approvals. <add> See the ["Automatic approvals" section above](#automatic-approvals) for more information about automatic approvals. <ide> - `codecov/patch` and `codecov/project`: These show the Codecov report for the PR. <ide> See the ["`brew tests` and Codecov" section below](#brew-tests-and-codecov) for more info about Codecov. <ide> - `CI / vendored gems (Linux)`: This checks whether there was a change to the vendored gems on Linux that needs to be
1
Text
Text
add translation for titles [portuguese]
c1c0b3b33fe9ec78fa4b10f80e6844b4468ac1fb
<ide><path>curriculum/challenges/portuguese/03-front-end-libraries/jquery/remove-an-element-using-jquery.portuguese.md <ide> videoUrl: '' <ide> localeTitle: Remover um elemento usando jQuery <ide> --- <ide> <del>## Description <del><section id="description"> Agora vamos remover um elemento HTML da sua página usando jQuery. jQuery tem uma função chamada <code>.remove()</code> que remove um elemento HTML inteiramente Remove o elemento <code>target4</code> da página usando a função <code>.remove()</code> . </section> <add>## Descrição <add><section id="description"> Agora vamos remover um elemento HTML da sua página usando jQuery. jQuery tem uma função chamada <code>.remove()</code> que remove um elemento HTML inteiramente. Remova o elemento <code>target4</code> da página usando a função <code>.remove()</code>.</section> <ide> <del>## Instructions <add>## Instruções <ide> <section id="instructions"> <ide> </section> <ide> <del>## Tests <add>## Testes <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <ide> <ide> </section> <ide> <del>## Challenge Seed <add>## Desafio <ide> <section id='challengeSeed'> <ide> <ide> <div id='html-seed'> <ide> tests: <ide> }); <ide> </script> <ide> <del><!-- Only change code above this line. --> <add><!-- Apenas altere o código acima dessa linha. --> <ide> <ide> <div class="container-fluid"> <ide> <h3 class="text-primary text-center">jQuery Playground</h3> <ide> tests: <ide> <ide> </section> <ide> <del>## Solution <add>## Solução <ide> <section id='solution'> <ide> <ide> ```js
1
Python
Python
run tests for __init__.pxd
586bc6002b66624ff17db4213381e985cea80cf2
<ide><path>numpy/core/setup.py <ide> def generate_umath_c(ext, build_dir): <ide> <ide> config.add_subpackage('tests') <ide> config.add_data_dir('tests/data') <add> config.add_data_dir('tests/examples') <ide> <ide> config.make_svn_version_py() <ide> <ide><path>numpy/core/tests/test_cython.py <ide> def install_temp(request, tmp_path): <ide> ext_dir = os.path.join(here, "examples") <ide> <ide> #assert False <del> tmp_path = tmp_path._str#str(tmp_path) <add> tmp_path = tmp_path._str # str(tmp_path) <ide> cytest = os.path.join(tmp_path, "cytest") <ide> <ide> shutil.copytree(ext_dir, cytest) <ide> # build the examples and "install" them into a temporary directory <ide> <ide> build_dir = os.path.join(tmp_path, "examples") <add> install_log = os.path.join(tmp_path, "tmp_install_log.txt") <ide> subprocess.check_call([sys.executable, "setup.py", "build", "install", <ide> "--prefix", os.path.join(tmp_path, "installdir"), <ide> "--single-version-externally-managed", <del> "--record", os.path.join(tmp_path, "tmp_install_log.txt"), <add> "--record", install_log, <ide> ], <ide> cwd=cytest, <ide> ) <del> sys.path.append(cytest) <add> <add> # In order to import the built module, we need its path to sys.path <add> # so parse that out of the record <add> with open(install_log) as fid: <add> for line in fid: <add> if 'checks' in line: <add> sys.path.append(os.path.dirname(line)) <add> break <add> else: <add> raise RuntimeError(f'could not parse "{install_log}"') <ide> <ide> <ide> def test_is_timedelta64_object(install_temp): <ide> def test_get_datetime64_value(install_temp): <ide> def test_get_timedelta64_value(install_temp): <ide> import checks <ide> <del> td64 = np.timedelta(12345, "h") <add> td64 = np.timedelta64(12345, "h") <ide> <del> result = checks.get_td64_value(dt64) <add> result = checks.get_td64_value(td64) <ide> expected = td64.view("i8") <ide> <ide> assert result == expected <ide> def test_get_datetime64_unit(install_temp): <ide> expected = 11 <ide> assert result == expected <ide> <del> td64 = np.timedelta(12345, "h") <add> td64 = np.timedelta64(12345, "h") <ide> result = checks.get_dt64_unit(dt64) <ide> expected = 5 <ide> assert result == expected
2
Java
Java
add sealing assertion in fabric
93b568cc510c09ffa03b86a0c7605885580c852c
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java <ide> private void applyUpdatesRecursive(ReactShadowNode node, float absoluteX, float <ide> } <ide> <ide> int tag = node.getReactTag(); <del> if (mRootShadowNodeRegistry.getNode(tag) == null) { <add> if (getRootNode(tag) == null) { <ide> boolean frameDidChange = <ide> node.dispatchUpdates(absoluteX, absoluteY, mUIViewOperationQueue, null); <ide> // Notify JS about layout event if requested <ide> public void onSizeChanged(final int width, final int height, int oldW, int oldH) <ide> <ide> @Override <ide> @DoNotStrip <del> public void updateRootLayoutSpecs(int rootViewTag, int widthMeasureSpec, int heightMeasureSpec) { <del> ReactShadowNode rootNode = mRootShadowNodeRegistry.getNode(rootViewTag); <add> public synchronized void updateRootLayoutSpecs(int rootViewTag, int widthMeasureSpec, int heightMeasureSpec) { <add> ReactShadowNode rootNode = getRootNode(rootViewTag); <ide> if (rootNode == null) { <ide> FLog.w(ReactConstants.TAG, "Tried to update non-existent root tag: " + rootViewTag); <ide> return; <ide> } <del> updateRootView(rootNode, widthMeasureSpec, heightMeasureSpec); <add> <add> ReactShadowNode newRootNode = rootNode.mutableCopy(rootNode.getInstanceHandle()); <add> updateRootView(newRootNode, widthMeasureSpec, heightMeasureSpec); <add> mRootShadowNodeRegistry.replaceNode(newRootNode); <ide> } <ide> <ide> /** <ide> public void updateRootLayoutSpecs(int rootViewTag, int widthMeasureSpec, int hei <ide> * //TODO: change synchronization to integrate with new #render loop. <ide> */ <ide> private synchronized void updateRootSize(int rootTag, int newWidth, int newHeight) { <del> ReactShadowNode rootNode = mRootShadowNodeRegistry.getNode(rootTag); <add> ReactShadowNode rootNode = getRootNode(rootTag); <ide> if (rootNode == null) { <ide> FLog.w( <ide> ReactConstants.TAG, <ide> "Tried to update size of non-existent tag: " + rootTag); <ide> return; <ide> } <add> <add> ReactShadowNode newRootNode = rootNode.mutableCopy(rootNode.getInstanceHandle()); <ide> int newWidthSpec = View.MeasureSpec.makeMeasureSpec(newWidth, View.MeasureSpec.EXACTLY); <ide> int newHeightSpec = View.MeasureSpec.makeMeasureSpec(newHeight, View.MeasureSpec.EXACTLY); <del> updateRootView(rootNode, newWidthSpec, newHeightSpec); <add> updateRootView(newRootNode, newWidthSpec, newHeightSpec); <ide> <del> completeRoot(rootTag, rootNode.getChildrenList()); <add> completeRoot(rootTag, newRootNode.getChildrenList()); <ide> } <ide> <ide> public void removeRootView(int rootTag) { <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNodeImpl.java <ide> public final boolean hasUpdates() { <ide> <ide> @Override <ide> public final void markUpdateSeen() { <add> assertNotSealed(); <ide> mNodeUpdated = false; <ide> if (hasNewLayout()) { <ide> markLayoutSeen(); <ide> public final boolean hasUnseenUpdates() { <ide> <ide> @Override <ide> public void dirty() { <add> assertNotSealed(); <ide> if (!isVirtual()) { <ide> mYogaNode.dirty(); <ide> } <ide> public final boolean isDirty() { <ide> <ide> @Override <ide> public void addChildAt(ReactShadowNodeImpl child, int i) { <add> assertNotSealed(); <ide> if (mChildren == null) { <ide> mChildren = new ArrayList<>(4); <ide> } <ide> public void addChildAt(ReactShadowNodeImpl child, int i) { <ide> <ide> @Override <ide> public ReactShadowNodeImpl removeChildAt(int i) { <add> assertNotSealed(); <ide> if (mChildren == null) { <ide> throw new ArrayIndexOutOfBoundsException( <ide> "Index " + i + " out of bounds: node has no children"); <ide> public final int getReactTag() { <ide> <ide> @Override <ide> public void setReactTag(int reactTag) { <add> assertNotSealed(); <ide> mReactTag = reactTag; <ide> } <ide> <ide> public final int getRootTag() { <ide> <ide> @Override <ide> public final void setRootTag(int rootTag) { <add> assertNotSealed(); <ide> mRootTag = rootTag; <ide> } <ide> <ide> @Override <ide> public final void setViewClassName(String viewClassName) { <add> assertNotSealed(); <ide> mViewClassName = viewClassName; <ide> } <ide> <ide> public final boolean hasNewLayout() { <ide> <ide> @Override <ide> public final void markLayoutSeen() { <add> assertNotSealed(); <ide> if (mYogaNode != null) { <ide> mYogaNode.markLayoutSeen(); <ide> } <ide> public final void markLayoutSeen() { <ide> */ <ide> @Override <ide> public final void addNativeChildAt(ReactShadowNodeImpl child, int nativeIndex) { <add> assertNotSealed(); <ide> Assertions.assertCondition(!mIsLayoutOnly); <ide> Assertions.assertCondition(!child.mIsLayoutOnly); <ide> <ide> public final int indexOfNativeChild(ReactShadowNodeImpl nativeChild) { <ide> */ <ide> @Override <ide> public final void setIsLayoutOnly(boolean isLayoutOnly) { <add> assertNotSealed(); <ide> Assertions.assertCondition(getParent() == null, "Must remove from no opt parent first"); <ide> Assertions.assertCondition(mNativeParent == null, "Must remove from native parent first"); <ide> Assertions.assertCondition(getNativeChildCount() == 0, "Must remove all native children first"); <ide> public final YogaDirection getLayoutDirection() { <ide> <ide> @Override <ide> public void setLayoutDirection(YogaDirection direction) { <add> assertNotSealed(); <ide> mYogaNode.setDirection(direction); <ide> } <ide> <ide> public final YogaValue getStyleWidth() { <ide> <ide> @Override <ide> public void setStyleWidth(float widthPx) { <add> assertNotSealed(); <ide> mYogaNode.setWidth(widthPx); <ide> } <ide> <ide> @Override <ide> public void setStyleWidthPercent(float percent) { <add> assertNotSealed(); <ide> mYogaNode.setWidthPercent(percent); <ide> } <ide> <ide> @Override <ide> public void setStyleWidthAuto() { <add> assertNotSealed(); <ide> mYogaNode.setWidthAuto(); <ide> } <ide> <ide> @Override <ide> public void setStyleMinWidth(float widthPx) { <add> assertNotSealed(); <ide> mYogaNode.setMinWidth(widthPx); <ide> } <ide> <ide> @Override <ide> public void setStyleMinWidthPercent(float percent) { <add> assertNotSealed(); <ide> mYogaNode.setMinWidthPercent(percent); <ide> } <ide> <ide> @Override <ide> public void setStyleMaxWidth(float widthPx) { <add> assertNotSealed(); <ide> mYogaNode.setMaxWidth(widthPx); <ide> } <ide> <ide> @Override <ide> public void setStyleMaxWidthPercent(float percent) { <add> assertNotSealed(); <ide> mYogaNode.setMaxWidthPercent(percent); <ide> } <ide> <ide> public final YogaValue getStyleHeight() { <ide> <ide> @Override <ide> public void setStyleHeight(float heightPx) { <add> assertNotSealed(); <ide> mYogaNode.setHeight(heightPx); <ide> } <ide> <ide> @Override <ide> public void setStyleHeightPercent(float percent) { <add> assertNotSealed(); <ide> mYogaNode.setHeightPercent(percent); <ide> } <ide> <ide> @Override <ide> public void setStyleHeightAuto() { <add> assertNotSealed(); <ide> mYogaNode.setHeightAuto(); <ide> } <ide> <ide> @Override <ide> public void setStyleMinHeight(float widthPx) { <add> assertNotSealed(); <ide> mYogaNode.setMinHeight(widthPx); <ide> } <ide> <ide> @Override <ide> public void setStyleMinHeightPercent(float percent) { <add> assertNotSealed(); <ide> mYogaNode.setMinHeightPercent(percent); <ide> } <ide> <ide> @Override <ide> public void setStyleMaxHeight(float widthPx) { <add> assertNotSealed(); <ide> mYogaNode.setMaxHeight(widthPx); <ide> } <ide> <ide> @Override <ide> public void setStyleMaxHeightPercent(float percent) { <add> assertNotSealed(); <ide> mYogaNode.setMaxHeightPercent(percent); <ide> } <ide> <ide> @Override <ide> public void setFlex(float flex) { <add> assertNotSealed(); <ide> mYogaNode.setFlex(flex); <ide> } <ide> <ide> @Override <ide> public void setFlexGrow(float flexGrow) { <add> assertNotSealed(); <ide> mYogaNode.setFlexGrow(flexGrow); <ide> } <ide> <ide> @Override <ide> public void setFlexShrink(float flexShrink) { <add> assertNotSealed(); <ide> mYogaNode.setFlexShrink(flexShrink); <ide> } <ide> <ide> @Override <ide> public void setFlexBasis(float flexBasis) { <add> assertNotSealed(); <ide> mYogaNode.setFlexBasis(flexBasis); <ide> } <ide> <ide> @Override <ide> public void setFlexBasisAuto() { <add> assertNotSealed(); <ide> mYogaNode.setFlexBasisAuto(); <ide> } <ide> <ide> @Override <ide> public void setFlexBasisPercent(float percent) { <add> assertNotSealed(); <ide> mYogaNode.setFlexBasisPercent(percent); <ide> } <ide> <ide> @Override <ide> public void setStyleAspectRatio(float aspectRatio) { <add> assertNotSealed(); <ide> mYogaNode.setAspectRatio(aspectRatio); <ide> } <ide> <ide> @Override <ide> public void setFlexDirection(YogaFlexDirection flexDirection) { <add> assertNotSealed(); <ide> mYogaNode.setFlexDirection(flexDirection); <ide> } <ide> <ide> @Override <ide> public void setFlexWrap(YogaWrap wrap) { <add> assertNotSealed(); <ide> mYogaNode.setWrap(wrap); <ide> } <ide> <ide> @Override <ide> public void setAlignSelf(YogaAlign alignSelf) { <add> assertNotSealed(); <ide> mYogaNode.setAlignSelf(alignSelf); <ide> } <ide> <ide> @Override <ide> public void setAlignItems(YogaAlign alignItems) { <add> assertNotSealed(); <ide> mYogaNode.setAlignItems(alignItems); <ide> } <ide> <ide> @Override <ide> public void setAlignContent(YogaAlign alignContent) { <add> assertNotSealed(); <ide> mYogaNode.setAlignContent(alignContent); <ide> } <ide> <ide> @Override <ide> public void setJustifyContent(YogaJustify justifyContent) { <add> assertNotSealed(); <ide> mYogaNode.setJustifyContent(justifyContent); <ide> } <ide> <ide> @Override <ide> public void setOverflow(YogaOverflow overflow) { <add> assertNotSealed(); <ide> mYogaNode.setOverflow(overflow); <ide> } <ide> <ide> @Override <ide> public void setDisplay(YogaDisplay display) { <add> assertNotSealed(); <ide> mYogaNode.setDisplay(display); <ide> } <ide> <ide> @Override <ide> public void setMargin(int spacingType, float margin) { <add> assertNotSealed(); <ide> mYogaNode.setMargin(YogaEdge.fromInt(spacingType), margin); <ide> } <ide> <ide> @Override <ide> public void setMarginPercent(int spacingType, float percent) { <add> assertNotSealed(); <ide> mYogaNode.setMarginPercent(YogaEdge.fromInt(spacingType), percent); <ide> } <ide> <ide> @Override <ide> public void setMarginAuto(int spacingType) { <add> assertNotSealed(); <ide> mYogaNode.setMarginAuto(YogaEdge.fromInt(spacingType)); <ide> } <ide> <ide> public final YogaValue getStylePadding(int spacingType) { <ide> <ide> @Override <ide> public void setDefaultPadding(int spacingType, float padding) { <add> assertNotSealed(); <ide> mDefaultPadding.set(spacingType, padding); <ide> updatePadding(); <ide> } <ide> <ide> @Override <ide> public void setPadding(int spacingType, float padding) { <add> assertNotSealed(); <ide> mPadding[spacingType] = padding; <ide> mPaddingIsPercent[spacingType] = false; <ide> updatePadding(); <ide> } <ide> <ide> @Override <ide> public void setPaddingPercent(int spacingType, float percent) { <add> assertNotSealed(); <ide> mPadding[spacingType] = percent; <ide> mPaddingIsPercent[spacingType] = !YogaConstants.isUndefined(percent); <ide> updatePadding(); <ide> } <ide> <ide> private void updatePadding() { <add> assertNotSealed(); <ide> for (int spacingType = Spacing.LEFT; spacingType <= Spacing.ALL; spacingType++) { <ide> if (spacingType == Spacing.LEFT <ide> || spacingType == Spacing.RIGHT <ide> private void updatePadding() { <ide> <ide> @Override <ide> public void setBorder(int spacingType, float borderWidth) { <add> assertNotSealed(); <ide> mYogaNode.setBorder(YogaEdge.fromInt(spacingType), borderWidth); <ide> } <ide> <ide> @Override <ide> public void setPosition(int spacingType, float position) { <add> assertNotSealed(); <ide> mYogaNode.setPosition(YogaEdge.fromInt(spacingType), position); <ide> } <ide> <ide> @Override <ide> public void setPositionPercent(int spacingType, float percent) { <add> assertNotSealed(); <ide> mYogaNode.setPositionPercent(YogaEdge.fromInt(spacingType), percent); <ide> } <ide> <ide> @Override <ide> public void setPositionType(YogaPositionType positionType) { <add> assertNotSealed(); <ide> mYogaNode.setPositionType(positionType); <ide> } <ide> <ide> @Override <ide> public void setShouldNotifyOnLayout(boolean shouldNotifyOnLayout) { <add> assertNotSealed(); <ide> mShouldNotifyOnLayout = shouldNotifyOnLayout; <ide> } <ide> <ide> @Override <ide> public void setBaselineFunction(YogaBaselineFunction baselineFunction) { <add> assertNotSealed(); <ide> mYogaNode.setBaselineFunction(baselineFunction); <ide> } <ide> <ide> @Override <ide> public void setMeasureFunction(YogaMeasureFunction measureFunction) { <add> assertNotSealed(); <ide> mYogaNode.setMeasureFunction(measureFunction); <ide> } <ide> <ide> public long getInstanceHandle() { <ide> <ide> @Override <ide> public void setInstanceHandle(long instanceHandle) { <add> assertNotSealed(); <ide> mInstanceHandle = instanceHandle; <ide> } <ide> <ide> public void markAsSealed() { <ide> public boolean isSealed() { <ide> return mIsSealed; <ide> } <add> <add> private void assertNotSealed() { <add> if (mIsSealed) { <add> throw new IllegalStateException("Can not modify sealed node " + toString()); <add> } <add> } <ide> }
2
Python
Python
return uniquenesstogethermodel to previous state
aa7ed316d842c06d7eb6907d4481d72c747991d7
<ide><path>tests/test_validators.py <ide> def test_doesnt_pollute_model(self): <ide> # ----------------------------------- <ide> <ide> class UniquenessTogetherModel(models.Model): <del> race_name = models.CharField(max_length=100, null=True) <del> position = models.IntegerField(null=True) <add> race_name = models.CharField(max_length=100) <add> position = models.IntegerField() <ide> <ide> class Meta: <ide> unique_together = ('race_name', 'position') <ide> def test_repr(self): <ide> expected = dedent(""" <ide> UniquenessTogetherSerializer(): <ide> id = IntegerField(label='ID', read_only=True) <del> race_name = CharField(allow_null=True, max_length=100, required=True) <del> position = IntegerField(allow_null=True, required=True) <add> race_name = CharField(max_length=100, required=True) <add> position = IntegerField(required=True) <ide> class Meta: <ide> validators = [<UniqueTogetherValidator(queryset=UniquenessTogetherModel.objects.all(), fields=('race_name', 'position'))>] <ide> """) <ide> class Meta: <ide> expected = dedent(""" <ide> ExcludedFieldSerializer(): <ide> id = IntegerField(label='ID', read_only=True) <del> race_name = CharField(allow_null=True, max_length=100, required=False) <add> race_name = CharField(max_length=100) <ide> """) <ide> assert repr(serializer) == expected <ide>
1
PHP
PHP
remove extra whitespace
256da430900442bc077fd02a5f20b49fa13a848d
<ide><path>src/View/Helper/FormHelper.php <ide> public function submit($caption = null, array $options = []) <ide> $caption = __d('cake', 'Submit'); <ide> } <ide> $options += [ <del> 'type' => 'submit', <add> 'type' => 'submit', <ide> 'secure' => false, <ide> 'templateVars' => [] <ide> ];
1
Ruby
Ruby
raise exception when building invalid mime type
b5e8942c95078945ff09a83b2fc03a0ae7e35953
<ide><path>actionpack/lib/action_dispatch/http/mime_type.rb <ide> def register(string, symbol, mime_type_synonyms = [], extension_synonyms = [], s <ide> def parse(accept_header) <ide> if !accept_header.include?(",") <ide> accept_header = accept_header.split(PARAMETER_SEPARATOR_REGEXP).first <add> return [] unless accept_header <ide> parse_trailing_star(accept_header) || [Mime::Type.lookup(accept_header)].compact <ide> else <ide> list, index = [], 0 <ide> def unregister(symbol) <ide> <ide> attr_reader :hash <ide> <add> MIME_NAME = "[a-zA-Z0-9][a-zA-Z0-9#{Regexp.escape('!#$&-^_.+')}]{0,126}" <add> MIME_REGEXP = /\A(?:\*\/\*|#{MIME_NAME}\/(?:\*|#{MIME_NAME}))\z/ <add> <add> class InvalidMimeType < StandardError; end <add> <ide> def initialize(string, symbol = nil, synonyms = []) <add> unless MIME_REGEXP.match?(string) <add> raise InvalidMimeType, "#{string.inspect} is not a valid MIME type" <add> end <ide> @symbol, @synonyms = symbol, synonyms <ide> @string = string <ide> @hash = [@string, @synonyms, @symbol].hash <ide><path>actionpack/lib/action_dispatch/testing/request_encoder.rb <ide> def encode_params(params) <ide> end <ide> <ide> def self.parser(content_type) <del> mime = Mime::Type.lookup(content_type) <del> encoder(mime ? mime.ref : nil).response_parser <add> type = Mime::Type.lookup(content_type).ref if content_type <add> encoder(type).response_parser <ide> end <ide> <ide> def self.encoder(name) <ide><path>actionpack/test/dispatch/mime_type_test.rb <ide> class MimeTypeTest < ActiveSupport::TestCase <ide> assert_not (Mime[:js] !~ "application/javascript") <ide> assert Mime[:html] =~ "application/xhtml+xml" <ide> end <add> <add> test "can be initialized with wildcards" do <add> assert_equal "*/*", Mime::Type.new("*/*").to_s <add> assert_equal "text/*", Mime::Type.new("text/*").to_s <add> assert_equal "video/*", Mime::Type.new("video/*").to_s <add> end <add> <add> test "invalid mime types raise error" do <add> assert_raises Mime::Type::InvalidMimeType do <add> Mime::Type.new("too/many/slash") <add> end <add> <add> assert_raises Mime::Type::InvalidMimeType do <add> Mime::Type.new("missingslash") <add> end <add> <add> assert_raises Mime::Type::InvalidMimeType do <add> Mime::Type.new("text/html, text/plain") <add> end <add> <add> assert_raises Mime::Type::InvalidMimeType do <add> Mime::Type.new("*/html") <add> end <add> <add> assert_raises Mime::Type::InvalidMimeType do <add> Mime::Type.new("") <add> end <add> <add> assert_raises Mime::Type::InvalidMimeType do <add> Mime::Type.new(nil) <add> end <add> end <ide> end <ide><path>actionview/test/template/html_test.rb <ide> class HTMLTest < ActiveSupport::TestCase <ide> end <ide> <ide> test "formats returns string for recognized MIME type when MIME does not have symbol" do <del> foo = Mime::Type.lookup("foo") <add> foo = Mime::Type.lookup("text/foo") <ide> assert_nil foo.to_sym <del> assert_equal "foo", ActionView::Template::HTML.new("", foo).format <add> assert_equal "text/foo", ActionView::Template::HTML.new("", foo).format <ide> end <ide> <ide> test "formats returns string for unknown MIME type" do
4
Ruby
Ruby
remove hack required for ruby 1.8.7
13488183bd3fe9d0f8e84d66075c9c7d4cdc931d
<ide><path>Library/Homebrew/emoji.rb <ide> module Emoji <ide> class << self <del> def tick <del> # necessary for 1.8.7 unicode handling since many installs are on 1.8.7 <del> @tick ||= ["2714".hex].pack("U*") <del> end <del> <del> def cross <del> # necessary for 1.8.7 unicode handling since many installs are on 1.8.7 <del> @cross ||= ["2718".hex].pack("U*") <del> end <del> <ide> def install_badge <del> ENV["HOMEBREW_INSTALL_BADGE"] || "\xf0\x9f\x8d\xba" <add> ENV["HOMEBREW_INSTALL_BADGE"] || "🍺" <ide> end <ide> <ide> def enabled? <ide><path>Library/Homebrew/utils.rb <ide> def pretty_installed(f) <ide> if !$stdout.tty? <ide> f.to_s <ide> elsif Emoji.enabled? <del> "#{Tty.bold}#{f} #{Formatter.success(Emoji.tick)}#{Tty.reset}" <add> "#{Tty.bold}#{f} #{Formatter.success("✔")}#{Tty.reset}" <ide> else <ide> Formatter.success("#{Tty.bold}#{f} (installed)#{Tty.reset}") <ide> end <ide> def pretty_uninstalled(f) <ide> if !$stdout.tty? <ide> f.to_s <ide> elsif Emoji.enabled? <del> "#{Tty.bold}#{f} #{Formatter.error(Emoji.cross)}#{Tty.reset}" <add> "#{Tty.bold}#{f} #{Formatter.error("✘")}#{Tty.reset}" <ide> else <ide> Formatter.error("#{Tty.bold}#{f} (uninstalled)#{Tty.reset}") <ide> end
2
Text
Text
add gitter badge to readme
da5bb3774501d0edaa6bd6958b8cab5980ea336b
<ide><path>README.md <add>[![Join the chat at https://gitter.im/moment/moment](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/moment/moment?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) <add> <ide> [![NPM version][npm-version-image]][npm-url] [![NPM downloads][npm-downloads-image]][npm-url] [![MIT License][license-image]][license-url] [![Build Status][travis-image]][travis-url] <ide> <ide> A lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.
1
Java
Java
add explicit error message if e.getmessage is null
c6614f117f19a2c689e5e606adc10440fe75fb0a
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java <ide> public void onFailure(Call call, IOException e) { <ide> return; <ide> } <ide> removeRequest(requestId); <del> ResponseUtil.onRequestError(eventEmitter, requestId, e.getMessage(), e); <add> String errorMessage = e.getMessage() != null <add> ? e.getMessage() <add> : "Error while executing request: " + e.getClass().getSimpleName(); <add> ResponseUtil.onRequestError(eventEmitter, requestId, errorMessage, e); <ide> } <ide> <ide> @Override
1
Javascript
Javascript
use async/await in test-debugger-sb-before-load
6355cd8542ddef8c2620f48bebdfecb6545cf7a7
<ide><path>test/sequential/test-debugger-sb-before-load.js <ide> const assert = require('assert'); <ide> const path = require('path'); <ide> <ide> // Using sb before loading file. <del>{ <del> const scriptFullPath = fixtures.path('debugger', 'cjs', 'index.js'); <del> const script = path.relative(process.cwd(), scriptFullPath); <del> <del> const otherScriptFullPath = fixtures.path('debugger', 'cjs', 'other.js'); <del> const otherScript = path.relative(process.cwd(), otherScriptFullPath); <del> <del> const cli = startCLI([script]); <del> <del> function onFatal(error) { <del> cli.quit(); <del> throw error; <del> } <del> <del> cli.waitForInitialBreak() <del> .then(() => cli.waitForPrompt()) <del> .then(() => cli.command('sb("other.js", 2)')) <del> .then(() => { <del> assert.match( <del> cli.output, <del> /not loaded yet/, <del> 'warns that the script was not loaded yet'); <del> }) <del> .then(() => cli.stepCommand('cont')) <del> .then(() => { <del> assert.ok( <del> cli.output.includes(`break in ${otherScript}:2`), <del> 'found breakpoint in file that was not loaded yet'); <del> }) <del> .then(() => cli.quit()) <del> .then(null, onFatal); <del>} <add> <add>const scriptFullPath = fixtures.path('debugger', 'cjs', 'index.js'); <add>const script = path.relative(process.cwd(), scriptFullPath); <add> <add>const otherScriptFullPath = fixtures.path('debugger', 'cjs', 'other.js'); <add>const otherScript = path.relative(process.cwd(), otherScriptFullPath); <add> <add>const cli = startCLI([script]); <add> <add>(async () => { <add> await cli.waitForInitialBreak(); <add> await cli.waitForPrompt(); <add> await cli.command('sb("other.js", 2)'); <add> assert.match(cli.output, /not loaded yet/, <add> 'warns that the script was not loaded yet'); <add> await cli.stepCommand('cont'); <add> assert.ok(cli.output.includes(`break in ${otherScript}:2`), <add> 'found breakpoint in file that was not loaded yet'); <add>})() <add>.then(common.mustCall()) <add>.finally(() => cli.quit());
1
Ruby
Ruby
invoke non interactive shell from brew edit
fe32e6343d25df14012378ddecd8e84d84adc7ec
<ide><path>Library/Homebrew/utils.rb <ide> def exec_editor *args <ide> # Invoke bash to evaluate env vars in $EDITOR <ide> # This also gets us proper argument quoting. <ide> # See: https://github.com/mxcl/homebrew/issues/5123 <del> system "bash", "-c", which_editor + ' "$@"', "--", *args <add> system "bash", "-i", "-c", which_editor + ' "$@"', "--", *args <ide> end <ide> <ide> # GZips the given paths, and returns the gzipped paths
1
Javascript
Javascript
add example to the view#disconnectoutlet docs
8008c82cae5910586f2c5747ae79ea6152dcd05e
<ide><path>packages/ember-routing/lib/ext/view.js <ide> Ember.View.reopen({ <ide> Allows you to connect a unique view as the parent <ide> view's `{{outlet}}`. <ide> <add> Example <add> <ide> ```javascript <add> var MyView = Ember.View.extend({ <add> template: Ember.Handlebars.compile('Child view: {{outlet "main"}} ') <add> }); <add> var myView = MyView.create(); <add> myView.appendTo('body'); <add> // The html for myView now looks like: <add> // <div id="ember228" class="ember-view">Child view: </div> <add> <ide> myView.connectOutlet('main', Ember.View.extend({ <ide> template: Ember.Handlebars.compile('<h1>Foo</h1> ') <ide> })); <add> // The html for myView now looks like: <add> // <div id="ember228" class="ember-view">Child view: <add> // <div id="ember234" class="ember-view"><h1>Foo</h1> </div> <add> // </div> <ide> ``` <ide> @method connectOutlet <ide> @param {String} outletName A unique name for the outlet <ide> Ember.View.reopen({ <ide> /** <ide> Removes an outlet from the current view. <ide> <add> Example <add> <add> ```javascript <add> var MyView = Ember.View.extend({ <add> template: Ember.Handlebars.compile('Child view: {{outlet "main"}} ') <add> }); <add> var myView = MyView.create(); <add> myView.appendTo('body'); <add> // myView's html: <add> // <div id="ember228" class="ember-view">Child view: </div> <add> <add> myView.connectOutlet('main', Ember.View.extend({ <add> template: Ember.Handlebars.compile('<h1>Foo</h1> ') <add> })); <add> // myView's html: <add> // <div id="ember228" class="ember-view">Child view: <add> // <div id="ember234" class="ember-view"><h1>Foo</h1> </div> <add> // </div> <add> <add> myView.disconnectOutlet('main'); <add> // myView's html: <add> // <div id="ember228" class="ember-view">Child view: </div> <add> ``` <add> <ide> @method disconnectOutlet <ide> @param {String} outletName The name of the outlet to be removed <ide> */
1
Python
Python
fix the tests on 1.3 and head
9c007a6197ca5125bed774cf3089de7759e755d1
<ide><path>djangorestframework/tests/request.py <ide> from django.conf.urls.defaults import patterns <ide> from django.contrib.auth.models import User <ide> from django.test import TestCase, Client <del>from django.test.client import MULTIPART_CONTENT, BOUNDARY, encode_multipart <ide> <ide> from djangorestframework import status <ide> from djangorestframework.authentication import SessionAuthentication <ide> def test_standard_behaviour_determines_form_content_PUT(self): <ide> """ <ide> data = {'qwerty': 'uiop'} <ide> parsers = (FormParser, MultiPartParser) <del> request = factory.put('/', encode_multipart(BOUNDARY, data), parsers=parsers, <del> content_type=MULTIPART_CONTENT) <add> <add> from django import VERSION <add> <add> if VERSION >= (1, 5): <add> from django.test.client import MULTIPART_CONTENT, BOUNDARY, encode_multipart <add> request = factory.put('/', encode_multipart(BOUNDARY, data), parsers=parsers, <add> content_type=MULTIPART_CONTENT) <add> else: <add> request = factory.put('/', data, parsers=parsers) <add> <ide> self.assertEqual(request.DATA.items(), data.items()) <ide> <ide> def test_standard_behaviour_determines_non_form_content_PUT(self):
1
Javascript
Javascript
handle immediate synthetic transforms properly
8acb416ad0532d249a0342f39103dd09fbbeeb2e
<ide><path>lib/_stream_passthrough.js <ide> function PassThrough(options) { <ide> } <ide> <ide> PassThrough.prototype._transform = function(chunk, output, cb) { <del> output(chunk); <del> cb(); <add> cb(null, chunk); <ide> }; <ide><path>lib/_stream_readable.js <ide> var StringDecoder; <ide> <ide> util.inherits(Readable, Stream); <ide> <del>function ReadableState(options, stream) { <add>function ReadableState(options) { <ide> options = options || {}; <ide> <ide> this.bufferSize = options.bufferSize || 16 * 1024; <ide> function ReadableState(options, stream) { <ide> this.flowing = false; <ide> this.ended = false; <ide> this.endEmitted = false; <del> this.stream = stream; <ide> this.reading = false; <ide> <ide> // whenever we return null, then we set a flag to say <ide> Readable.prototype.setEncoding = function(enc) { <ide> this._readableState.decoder = new StringDecoder(enc); <ide> }; <ide> <del>// you can override either this method, or _read(n, cb) below. <del>Readable.prototype.read = function(n) { <del> var state = this._readableState; <ide> <del> if (state.length === 0 && state.ended) { <del> endReadable(this); <del> return null; <del> } <add>function howMuchToRead(n, state) { <add> if (state.length === 0 && state.ended) <add> return 0; <add> <add> if (isNaN(n)) <add> return state.length; <ide> <del> if (isNaN(n) || n <= 0) <del> n = state.length <add> if (n <= 0) <add> return 0; <ide> <del> // XXX: controversial. <ide> // don't have that much. return null, unless we've ended. <del> // However, if the low water mark is lower than the number of bytes, <del> // then we still need to return what we have, or else it won't kick <del> // off another _read() call. For example, <del> // lwm=5 <del> // len=9 <del> // read(10) <del> // We don't have that many bytes, so it'd be tempting to return null, <del> // but then it won't ever cause _read to be called, so in that case, <del> // we just return what we have, and let the programmer deal with it. <ide> if (n > state.length) { <del> if (!state.ended && state.length <= state.lowWaterMark) { <add> if (!state.ended) { <ide> state.needReadable = true; <del> n = 0; <add> return 0; <ide> } else <del> n = state.length; <add> return state.length; <ide> } <ide> <add> return n; <add>} <ide> <del> var ret; <del> if (n > 0) <del> ret = fromList(n, state.buffer, state.length, !!state.decoder); <del> else <del> ret = null; <add>// you can override either this method, or _read(n, cb) below. <add>Readable.prototype.read = function(n) { <add> var state = this._readableState; <add> var nOrig = n; <ide> <del> if (ret === null || ret.length === 0) <del> state.needReadable = true; <add> n = howMuchToRead(n, state); <ide> <del> state.length -= n; <add> // if we've ended, and we're now clear, then finish it up. <add> if (n === 0 && state.ended) { <add> endReadable(this); <add> return null; <add> } <ide> <del> if (!state.ended && <del> state.length <= state.lowWaterMark && <del> !state.reading) { <add> // All the actual chunk generation logic needs to be <add> // *below* the call to _read. The reason is that in certain <add> // synthetic stream cases, such as passthrough streams, _read <add> // may be a completely synchronous operation which may change <add> // the state of the read buffer, providing enough data when <add> // before there was *not* enough. <add> // <add> // So, the steps are: <add> // 1. Figure out what the state of things will be after we do <add> // a read from the buffer. <add> // <add> // 2. If that resulting state will trigger a _read, then call _read. <add> // Note that this may be asynchronous, or synchronous. Yes, it is <add> // deeply ugly to write APIs this way, but that still doesn't mean <add> // that the Readable class should behave improperly, as streams are <add> // designed to be sync/async agnostic. <add> // Take note if the _read call is sync or async (ie, if the read call <add> // has returned yet), so that we know whether or not it's safe to emit <add> // 'readable' etc. <add> // <add> // 3. Actually pull the requested chunks out of the buffer and return. <add> <add> // if we need a readable event, then we need to do some reading. <add> var doRead = state.needReadable; <add> // if we currently have less than the lowWaterMark, then also read some <add> if (state.length - n <= state.lowWaterMark) <add> doRead = true; <add> // however, if we've ended, then there's no point, and if we're already <add> // reading, then it's unnecessary. <add> if (state.ended || state.reading) <add> doRead = false; <add> <add> if (doRead) { <add> var sync = true; <ide> state.reading = true; <ide> // call internal read method <ide> this._read(state.bufferSize, function onread(er, chunk) { <ide> Readable.prototype.read = function(n) { <ide> return this.emit('error', er); <ide> <ide> if (!chunk || !chunk.length) { <add> // eof <ide> state.ended = true; <ide> // if we've ended and we have some data left, then emit <ide> // 'readable' now to make sure it gets picked up. <del> if (state.length > 0) <del> this.emit('readable'); <del> else <del> endReadable(this); <add> if (!sync) { <add> if (state.length > 0) <add> this.emit('readable'); <add> else <add> endReadable(this); <add> } <ide> return; <ide> } <ide> <ide> if (state.decoder) <ide> chunk = state.decoder.write(chunk); <ide> <del> state.length += chunk.length; <del> state.buffer.push(chunk); <add> // update the buffer info. <add> if (chunk) { <add> state.length += chunk.length; <add> state.buffer.push(chunk); <add> } <ide> <ide> // if we haven't gotten enough to pass the lowWaterMark, <ide> // and we haven't ended, then don't bother telling the user <ide> Readable.prototype.read = function(n) { <ide> return; <ide> } <ide> <del> // now we have something to call this.read() to get. <del> if (state.needReadable) { <add> if (state.needReadable && !sync) { <ide> state.needReadable = false; <ide> this.emit('readable'); <ide> } <ide> }.bind(this)); <add> sync = false; <ide> } <ide> <add> // If _read called its callback synchronously, then `reading` <add> // will be false, and we need to re-evaluate how much data we <add> // can return to the user. <add> if (doRead && !state.reading) <add> n = howMuchToRead(nOrig, state); <add> <add> var ret; <add> if (n > 0) <add> ret = fromList(n, state.buffer, state.length, !!state.decoder); <add> else <add> ret = null; <add> <add> if (ret === null || ret.length === 0) { <add> state.needReadable = true; <add> n = 0; <add> } <add> <add> state.length -= n; <add> <ide> return ret; <ide> }; <ide> <ide><path>lib/_stream_transform.js <ide> Transform.prototype._write = function(chunk, cb) { <ide> if (ts.pendingReadCb) { <ide> var readcb = ts.pendingReadCb; <ide> ts.pendingReadCb = null; <del> this._read(-1, readcb); <add> this._read(0, readcb); <ide> } <ide> <ide> // if we weren't waiting for it, but nothing is queued up, then <ide> // still kick off a transform, just so it's there when the user asks. <del> if (rs.length === 0) { <del> var ret = this.read(); <add> var doRead = rs.needReadable || rs.length <= rs.lowWaterMark; <add> if (doRead && !rs.reading) { <add> var ret = this.read(0); <ide> if (ret !== null) <ide> return cb(new Error('invalid stream transform state')); <ide> }
3
Python
Python
remove resnext networks (bug) and add tests
99ebe7759fd317aedae734865f68dd4387100081
<ide><path>keras/applications/__init__.py <ide> def wrapper(*args, **kwargs): <ide> from .nasnet import NASNetMobile, NASNetLarge <ide> from .resnet import ResNet101, ResNet152 <ide> from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2 <del>from .resnext import ResNeXt50, ResNeXt101 <ide><path>tests/integration_tests/applications_test.py <ide> <ide> MODEL_LIST = [ <ide> (applications.ResNet50, 2048), <add> (applications.ResNet101, 2048), <add> (applications.ResNet152, 2048), <add> (applications.ResNet50V2, 2048), <add> (applications.ResNet101V2, 2048), <add> (applications.ResNet152V2, 2048), <ide> (applications.VGG16, 512), <ide> (applications.VGG19, 512), <ide> (applications.Xception, 2048),
2
Text
Text
add example links in python for formula authors
491bb469e75c772d897c29645453a0988a1c7a4a
<ide><path>docs/Python-for-Formula-Authors.md <ide> <ide> This document explains how to successfully use Python in a Homebrew formula. <ide> <del>Homebrew draws a distinction between Python **applications** and Python **libraries**. The difference is that users generally do not care that applications are written in Python; it is unusual that a user would expect to be able to `import foo` after installing an application. Examples of applications are `ansible` and `jrnl`. <add>Homebrew draws a distinction between Python **applications** and Python **libraries**. The difference is that users generally do not care that applications are written in Python; it is unusual that a user would expect to be able to `import foo` after installing an application. Examples of applications are [`ansible`](https://github.com/Homebrew/homebrew-core/blob/master/Formula/ansible.rb) and [`jrnl`](https://github.com/Homebrew/homebrew-core/blob/master/Formula/jrnl.rb). <ide> <del>Python libraries exist to be imported by other Python modules; they are often dependencies of Python applications. They are usually no more than incidentally useful from a Terminal.app command line. Examples of libraries are `py2cairo` and the bindings that are installed by `protobuf --with-python`. <add>Python libraries exist to be imported by other Python modules; they are often dependencies of Python applications. They are usually no more than incidentally useful from a Terminal.app command line. Examples of libraries are [`py2cairo`](https://github.com/Homebrew/homebrew-core/blob/master/Formula/py2cairo.rb) and the bindings that are installed by [`protobuf --with-python`](https://github.com/Homebrew/homebrew-core/blob/master/Formula/protobuf.rb). <ide> <ide> Bindings are a special case of libraries that allow Python code to interact with a library or application implemented in another language. <ide> <del>Homebrew is happy to accept applications that are built in Python, whether the apps are available from PyPI or not. Homebrew generally won't accept libraries that can be installed correctly with `pip install foo`. Libraries that can be `pip`-installed but have several Homebrew dependencies may be appropriate for the [homebrew/python](https://github.com/Homebrew/homebrew-python) tap. Bindings may be installed for packages that provide them, especially if equivalent functionality isn't available through pip. <add>Homebrew is happy to accept applications that are built in Python, whether the apps are available from PyPI or not. Homebrew generally won't accept libraries that can be installed correctly with `pip install foo`. Bindings may be installed for packages that provide them, especially if equivalent functionality isn't available through pip. <ide> <ide> ## Running `setup.py` <ide> <ide> If you submit a formula with this syntax to core, you may be asked to rewrite it <ide> <ide> ## Applications <ide> <del>`ansible.rb` and `jrnl.rb` are good examples of applications that follow this advice. <del> <ide> ### Python declarations <ide> <ide> Applications that are compatible with Python 2 **should** use the Apple-provided system Python in `/usr/bin` on systems that provide Python 2.7. To do this, declare:
1
Ruby
Ruby
use the doc conventions for arguments in all cases
18792069ab7beec08abaa34eb8c80fad8836b25f
<ide><path>actionpack/lib/action_view/helpers/date_helper.rb <ide> def select_time(datetime = Time.current, options = {}, html_options = {}) <ide> end <ide> <ide> # Returns a select tag with options for each of the seconds 0 through 59 with the current second selected. <del> # The <tt>second</tt> can also be substituted for a second number. <add> # The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer. <ide> # Override the field name using the <tt>:field_name</tt> option, 'second' by default. <ide> # <ide> # ==== Examples <ide> def select_second(datetime, options = {}, html_options = {}) <ide> <ide> # Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected. <ide> # Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute <del> # selected. The <tt>date</tt> can also be substituted for a minute number. <add> # selected. The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer. <ide> # Override the field name using the <tt>:field_name</tt> option, 'minute' by default. <ide> # <ide> # ==== Examples <ide> def select_minute(datetime, options = {}, html_options = {}) <ide> end <ide> <ide> # Returns a select tag with options for each of the hours 0 through 23 with the current hour selected. <del> # The <tt>date</tt> can also be substituted for a hour number. <add> # The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer. <ide> # Override the field name using the <tt>:field_name</tt> option, 'hour' by default. <ide> # <ide> # ==== Examples
1
Javascript
Javascript
fix incorrect logic
8c261180d36bf1400503f0b9ed0905b8d7b38659
<ide><path>client/commonFramework/step-challenge.js <ide> window.common = (function({ $, common = { init: [] }}) { <ide> } <ide> <ide> common.init.push(function($) { <del> if (common.challengeType === '7') { <add> if (common.challengeType !== '7') { <ide> return null; <ide> } <ide>
1
Ruby
Ruby
add focus support
0b69ca85f763bb0db210384ba2c4a93049bb7b35
<ide><path>Library/Homebrew/test/spec_helper.rb <ide> RSpec.configure do |config| <ide> config.order = :random <ide> <add> config.filter_run_when_matching :focus <add> <ide> config.include(Test::Helper::Shutup) <ide> config.include(Test::Helper::Fixtures) <ide> config.include(Test::Helper::Formula)
1
Text
Text
add prerequisits to contributing.md (#40)
27b65b94a7c81499edc94be41a0e4873ff6408ee
<ide><path>packages/learn/CONTRIBUTING.md <ide> # Contributing <ide> <add>Prerequistits| Minimum Version <add>|---|---| <add>node | ^8.11.x <add>[yarn](https://yarnpkg.com/en/) | ^1.3.0 <add> <add> <ide> 1. Fork the repo <ide> 2. clone locally <ide> 3. `yarn install` <ide> 4. `git branch -b <your-branch-name>` <ide> 5. `yarn develop` <add>5. Make your changes <ide> 6. Make a PR <ide> 7. Bask in the glory of your accomplishments <del>
1
Javascript
Javascript
fix auth0 example
5014362a7a6359fac8fc1bb8a02eae6736805d7f
<ide><path>examples/auth0/pages/advanced/ssr-profile.js <ide> export async function getServerSideProps({ req, res }) { <ide> // Here you can check authentication status directly before rendering the page, <ide> // however the page would be a serverless function, which is more expensive and <ide> // slower than a static page with client side authentication <del> const session = await auth0.getSession(req) <add> const session = await auth0.getSession(req, res) <ide> <ide> if (!session || !session.user) { <ide> res.writeHead(302, {
1
Go
Go
add nice error message
cee62a95a2086dace52f2492de781aa333abca3b
<ide><path>api/server/server.go <ide> func postImagesPush(eng *engine.Engine, version version.Version, w http.Response <ide> } else { <ide> // the old format is supported for compatibility if there was no authConfig header <ide> if err := json.NewDecoder(r.Body).Decode(authConfig); err != nil { <del> return err <add> return fmt.Errorf("Bad parameters and missing X-Registry-Auth: %v", err) <ide> } <ide> } <ide>
1
Javascript
Javascript
allow console.warn from tests
673c630ee01d1709322d75c94c3b37ec6cc20b03
<ide><path>test/load.js <ide> require("./XMLHttpRequest"); <ide> module.exports = function() { <ide> var files = [].slice.call(arguments).map(function(d) { return "src/" + d; }), <ide> expression = "d3", <del> sandbox = {Date: Date}; // so we can use deepEqual in tests <add> sandbox = {console: console, Date: Date}; // so we can use deepEqual in tests <ide> <ide> files.unshift("src/start"); <ide> files.push("src/end");
1
Text
Text
remove spurious new line in changelog_v6.md
dabac8a2fb285ae838cd30d5bdbdb42d2d345706
<ide><path>doc/changelogs/CHANGELOG_V6.md <ide> October 2016. <ide> <ide> <a id="6.3.1"></a> <del> <ide> ## 2016-07-21, Version 6.3.1 (Current), @evanlucas <ide> <ide> ### Notable changes
1
Python
Python
fix failing test in linode driver
bcc45a65c6832ea2cac748914fdb0ff65bdcf53a
<ide><path>test/test_linode.py <ide> def test_list_nodes(self): <ide> nodes = self.driver.list_nodes() <ide> self.assertEqual(len(nodes), 1) <ide> node = nodes[0] <del> self.assertEqual(node.id, 8098) <add> self.assertEqual(node.id, "8098") <ide> self.assertEqual(node.name, 'api-node3') <ide> self.assertTrue('75.127.96.245' in node.public_ip) <ide> self.assertEqual(node.private_ip, []) <ide> def _linode_delete(self, method, url, body, headers): <ide> body = '{"ERRORARRAY":[],"ACTION":"linode.delete","DATA":{"LinodeID":8098}}' <ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) <ide> <add> def _linode_update(self, method, url, body, headers): <add> body = '{"ERRORARRAY":[],"ACTION":"linode.update","DATA":{"LinodeID":8098}}' <add> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) <add> <ide> def _linode_reboot(self, method, url, body, headers): <ide> body = '{"ERRORARRAY":[],"ACTION":"linode.reboot","DATA":{"JobID":1305}}' <ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
1
Text
Text
add missing closing quote
d92e75cb30cc1f31a7ba8132e94686d6aca58d24
<ide><path>docs/advanced-features/react-18.md <ide> You can then import other server or client components from any server component. <ide> ```jsx <ide> // pages/home.server.js <ide> <del>import React, { Suspense } from 'react <add>import React, { Suspense } from 'react' <ide> <ide> import Profile from '../components/profile.server' <ide> import Content from '../components/content.client'
1
Python
Python
remove change from other issue
1800a1ebbb95bd761ae4ed005a726e2e82f2957a
<ide><path>libcloud/compute/drivers/gce.py <ide> def ex_list_project_images(self, ex_project=None, ex_include_deprecated=False): <ide> new_request_path = save_request_path.replace(self.project, proj) <ide> self.connection.request_path = new_request_path <ide> try: <del> self.connection.gce_params = {'maxResults': 1500} <ide> response = self.connection.request(request, method="GET").object <ide> except Exception: <ide> raise
1
Javascript
Javascript
show 0.8.0 even after 0.8.1 ships
37bdd36d70e86e3a3644bc73349e2f6f18909ea0
<ide><path>tools/blog/generate.js <ide> function buildFeeds(data) { <ide> } <ide> <ide> // filter non-latest release notices out of main feeds. <add> // still show the first stable release of the family, since <add> // it usually is an important milestone with benchmarks and stuff. <ide> var main = posts.filter(function(post) { <del> if (post.version && post.family && post !== releases[post.family][0]) { <del> return false; <add> if (post.version && post.family) { <add> var ver = semver.parse(post.version) <add> if (+ver[2] % 2 === 0 && +ver[3] === 0) { <add> // 0.x.0, where x is event <add> return true; <add> } <add> if (post.version && post.family && post !== releases[post.family][0]) { <add> return false; <add> } <ide> } <ide> return true; <ide> });
1
Javascript
Javascript
use native driver even if gestures are enabled
cbc413ba87caffc40ae67040ce85340908f8bc07
<ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCardStack.js <ide> */ <ide> 'use strict'; <ide> <add>const NativeAnimatedModule = require('NativeModules').NativeAnimatedModule; <ide> const NavigationCard = require('NavigationCard'); <ide> const NavigationCardStackPanResponder = require('NavigationCardStackPanResponder'); <ide> const NavigationCardStackStyleInterpolator = require('NavigationCardStackStyleInterpolator'); <ide> class NavigationCardStack extends React.Component<DefaultProps, Props, void> { <ide> _configureTransition = () => { <ide> const isVertical = this.props.direction === 'vertical'; <ide> const animationConfig = {}; <del> if (NavigationCardStackStyleInterpolator.canUseNativeDriver(isVertical)) { <add> if ( <add> !!NativeAnimatedModule <add> <add> // Gestures do not work with the current iteration of native animation <add> // driving. When gestures are disabled, we can drive natively. <add> && !this.props.enableGestures <add> <add> // Native animation support also depends on the transforms used: <add> && NavigationCardStackStyleInterpolator.canUseNativeDriver(isVertical) <add> ) { <ide> animationConfig.useNativeDriver = true; <ide> } <ide> return animationConfig;
1
Javascript
Javascript
add a missing test for jqlite#text
3cbc8e5563d0f272838a65636989544519873492
<ide><path>test/jqLiteSpec.js <ide> describe('jqLite', function() { <ide> expect(element.text('xyz') == element).toBeTruthy(); <ide> expect(element.text()).toEqual('xyzxyz'); <ide> }); <add> <add> it('should return text only for element or text nodes', function() { <add> expect(jqLite('<div>foo</div>').text()).toBe('foo'); <add> expect(jqLite('<div>foo</div>').contents().eq(0).text()).toBe('foo'); <add> expect(jqLite(document.createComment('foo')).text()).toBe(''); <add> }); <ide> }); <ide> <ide>
1
Ruby
Ruby
reduce object allocations in utc_offset
365aa654d8bbe2889b75df2f5147bc25c54fa751
<ide><path>activesupport/lib/active_support/values/time_zone.rb <ide> def utc_offset <ide> if @utc_offset <ide> @utc_offset <ide> else <del> @current_period ||= tzinfo.try(:current_period) <del> @current_period.try(:utc_offset) <add> @current_period ||= tzinfo.current_period if tzinfo <add> @current_period.utc_offset if @current_period <ide> end <ide> end <ide>
1
Text
Text
add response to swarm/init example (fixes
a2a0a03e2b801545b2e3fb9e8476c76370da9175
<ide><path>docs/reference/api/docker_remote_api_v1.24.md <ide> Inspect swarm <ide> <ide> `POST /swarm/init` <ide> <del>Initialize a new swarm <add>Initialize a new swarm. The body of the HTTP response includes the node ID. <ide> <ide> **Example request**: <ide> <ide> Initialize a new swarm <ide> **Example response**: <ide> <ide> HTTP/1.1 200 OK <del> Content-Length: 0 <del> Content-Type: text/plain; charset=utf-8 <add> Content-Length: 28 <add> Content-Type: application/json <add> Date: Thu, 01 Sep 2016 21:49:13 GMT <add> Server: Docker/1.12.0 (linux) <add> <add> "7v2t30z9blmxuhnyo6s4cpenp" <ide> <ide> **Status codes**: <ide>
1
Text
Text
add french translation
bd8a2b9b140108e38a9c6844c53ab8ac669b5177
<ide><path>threejs/lessons/fr/threejs-scenegraph.md <del>Title: Graphique de scène de Three.js <del>Description: Qu'est-ce qu'un graphique de scène ? <del>TOC: Graphique de scène <add>Title: Graphe de scène Three.js <add>Description: What's a scene graph? <add>TOC: Scenegraph <ide> <ide> Cet article fait partie d'une série consacrée à Three.js. <ide> Le premier article s'intitule [Principes de base](threejs-fundamentals.html). <ide> Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là. <ide> <del>Le coeurs de Three.js est sans aucun doute son graphique de scène. Un graphique de scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local. <add>Le coeurs de Three.js est sans aucun doute son objet scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local. <ide> <ide> <img src="resources/images/scenegraph-generic.svg" align="center"> <ide> <ide> objects.push(earthMesh); <ide> +moonOrbit.add(moonMesh); <ide> +objects.push(moonMesh); <ide> ``` <add>XXXXXXXXXXXXXXXX <ide> <del>Ajoutons à nouveau d'autres noeuds à notre scène. D'abord, un `Object3D` appelé `earthOrbit` <del>ensuite ajoutons-lui un `earthMesh` et un `moonOrbit`. Finalement, ajoutons un `moonMesh` <del>au `moonOrbit`. Notre scène devrait ressembler à ceci : <add> <add>Again we added more invisible scene graph nodes. The first, an `Object3D` called `earthOrbit` <add>and added both the `earthMesh` and the `moonOrbit` to it, also new. We then added the `moonMesh` <add>to the `moonOrbit`. The new scene graph looks like this. <ide> <ide> <img src="resources/images/scenegraph-sun-earth-moon.svg" align="center"> <ide> <del>et à ça : <add>and here's that <ide> <ide> {{{example url="../threejs-scenegraph-sun-earth-moon.html" }}} <ide> <del>Vous pouvez voir que la lune suit le modèle de spirographe indiqué en haut de cet article, mais nous n'avons pas eu à le calculer manuellement. Nous venons de configurer notre graphe de scène pour le faire pour nous. <add>You can see the moon follows the spirograph pattern shown at the top <add>of this article but we didn't have to manually compute it. We just <add>setup our scene graph to do it for us. <ide> <del>Il est souvent utile de dessiner quelque chose pour visualiser les nœuds dans le graphe de scène. <del>Three.js dispose pour cela de Helpers. <add>It is often useful to draw something to visualize the nodes in the scene graph. <add>Three.js has some helpful ummmm, helpers to ummm, ... help with this. <ide> <del>L'un d'entre eux s'appelle `AxesHelper`. Il dessine trois lignes représentant les axes <add>One is called an `AxesHelper`. It draws 3 lines representing the local <ide> <span style="color:red">X</span>, <del><span style="color:green">Y</span>, et <del><span style="color:blue">Z</span>. Ajoutons-en un à chacun de nos noeuds. <add><span style="color:green">Y</span>, and <add><span style="color:blue">Z</span> axes. Let's add one to every node we <add>created. <ide> <ide> ```js <ide> // add an AxesHelper to each node <ide> objects.forEach((node) => { <ide> }); <ide> ``` <ide> <del>Dans notre cas, nous voulons que les axes apparaissent même s'ils sont à l'intérieur des sphères. <del>Pour cela, nous définissons le `depthTest` de material à false, pour ne pas vérifier s'ils dessinent derrière quelque chose. Nous définissons également leur `renderOrder` sur 1 (la valeur par défaut est 0) afin qu'ils soient dessinés après toutes les sphères. Sinon, une sphère pourrait les recouvrir et les recouvrir. <add>On our case we want the axes to appear even though they are inside the spheres. <add>To do this we set their material's `depthTest` to false which means they will <add>not check to see if they are drawing behind something else. We also <add>set their `renderOrder` to 1 (the default is 0) so that they get drawn after <add>all the spheres. Otherwise a sphere might draw over them and cover them up. <ide> <ide> {{{example url="../threejs-scenegraph-sun-earth-moon-axes.html" }}} <ide> <del>Vous pouvez voir les axes <del><span style="color:red">x (rouge)</span> et <del><span style="color:blue">z (bleu)</span>. Comme nous regardons vers le bas et que chacun de nos objets tourne autour de son axe y, nous ne voyons pas bien l'axe <span style="color:green">y (verte)</span>. <add>We can see the <add><span style="color:red">x (red)</span> and <add><span style="color:blue">z (blue)</span> axes. Since we are looking <add>straight down and each of our objects is only rotating around its <add>y axis we don't see much of the <span style="color:green">y (green)</span> axes. <ide> <del>Il peut être difficile de voir certains d'entre eux car il y a 2 paires d'axes qui se chevauchent. Le `sunMesh` et le `solarSystem` sont tous les deux à la même position. De même, `earthMesh` et `earthOrbit` sont à la même position. Ajoutons quelques contrôles simples pour nous permettre de les activer/désactiver pour chaque nœud. Pendant que nous y sommes, ajoutons également un autre assistant appelé `GridHelper`. Il crée une grille 2D sur le plan X,Z. Par défaut, la grille est de 10x10 unités. <add>It might be hard to see some of them as there are 2 pairs of overlapping axes. Both the `sunMesh` <add>and the `solarSystem` are at the same position. Similarly the `earthMesh` and <add>`earthOrbit` are at the same position. Let's add some simple controls to allow us <add>to turn them on/off for each node. <add>While we're at it let's also add another helper called the `GridHelper`. It <add>makes a 2D grid on the X,Z plane. By default the grid is 10x10 units. <ide> <del>Nous allons également utiliser [dat.GUI](https://github.com/dataarts/dat.gui), une librairie d'interface utilisateur très populaire pour les projets Three.js. dat.GUI prend un objet et un nom de propriété sur cet objet et, en fonction du type de la propriété, crée automatiquement une interface utilisateur pour manipuler cette propriété. <add>We're also going to use [dat.GUI](https://github.com/dataarts/dat.gui) which is <add>a UI library that is very popular with three.js projects. dat.GUI takes an <add>object and a property name on that object and based on the type of the property <add>automatically makes a UI to manipulate that property. <ide> <del>Nous voulons créer à la fois un `GridHelper` et un `AxesHelper` pour chaque nœud. Nous avons besoin d'un label pour chaque nœud, nous allons donc nous débarrasser de l'ancienne boucle et faire appel à une fonction pour ajouter les helpers pour chaque nœud. <add>We want to make both a `GridHelper` and an `AxesHelper` for each node. We need <add>a label for each node so we'll get rid of the old loop and switch to calling <add>some function to add the helpers for each node <ide> <ide> ```js <ide> -// add an AxesHelper to each node <ide> Nous voulons créer à la fois un `GridHelper` et un `AxesHelper` pour chaque n <ide> +makeAxisGrid(moonOrbit, 'moonOrbit'); <ide> +makeAxisGrid(moonMesh, 'moonMesh'); <ide> ``` <del>`makeAxisGrid` crée un `AxisGridHelper` qui est une classe que nous allons créer pour rendre dat.GUI heureux. Comme il est dit ci-dessus, dat.GUI créera automatiquement une interface utilisateur qui manipule la propriété nommée d'un objet. Cela créera une interface utilisateur différente selon le type de propriété. Nous voulons qu'il crée une case à cocher, nous devons donc spécifier une propriété bool. Mais, nous voulons que les axes et la grille apparaissent/disparaissent en fonction d'une seule propriété, nous allons donc créer une classe qui a un getter et un setter pour une propriété. De cette façon, nous pouvons laisser dat.GUI penser qu'il manipule une seule propriété, mais en interne, nous pouvons définir la propriété visible de `AxesHelper` et `GridHelper` pour un nœud. <add> <add>`makeAxisGrid` makes an `AxisGridHelper` which is a class we'll create <add>to make dat.GUI happy. Like it says above dat.GUI <add>will automagically make a UI that manipulates the named property <add>of some object. It will create a different UI depending on the type <add>of property. We want it to create a checkbox so we need to specify <add>a `bool` property. But, we want both the axes and the grid <add>to appear/disappear based on a single property so we'll make a class <add>that has a getter and setter for a property. That way we can let dat.GUI <add>think it's manipulating a single property but internally we can set <add>the visible property of both the `AxesHelper` and `GridHelper` for a node. <ide> <ide> ```js <del>// Activer/désactiver les axes et la grille dat.GUI <del>// nécessite une propriété qui renvoie un bool <del>// pour décider de faire une case à cocher <del>// afin que nous créions un setter et un getter pour `visible` <del>// que nous pouvons dire à dat.GUI de regarder. <add>// Turns both axes and grid visible on/off <add>// dat.GUI requires a property that returns a bool <add>// to decide to make a checkbox so we make a setter <add>// and getter for `visible` which we can tell dat.GUI <add>// to look at. <ide> class AxisGridHelper { <ide> constructor(node, units = 10) { <ide> const axes = new THREE.AxesHelper(); <ide> class AxisGridHelper { <ide> } <ide> ``` <ide> <del>Une chose à noter est que nous définissons le `renderOrder` de l'`AxesHelper` sur 2 et pour le `GridHelper` sur 1 afin que les axes soient dessinés après la grille. Sinon, la grille pourrait écraser les axes. <add>One thing to notice is we set the `renderOrder` of the `AxesHelper` <add>to 2 and for the `GridHelper` to 1 so that the axes get drawn after the grid. <add>Otherwise the grid might overwrite the axes. <ide> <ide> {{{example url="../threejs-scenegraph-sun-earth-moon-axes-grids.html" }}} <ide> <del>Cliquez sur `solarSystem` et vous verrez que la terre est exactement à 10 unités du centre, comme nous l'avons défini ci-dessus. Vous pouvez voir que la terre est dans l'espace local du `solarSystem`. De même, si vous cliquez sur `earthOrbit`, vous verrez que la lune est exactement à 2 unités du centre de *l'espace local* de `earthOrbit`. <add>Turn on the `solarSystem` and you'll see how the earth is exactly 10 <add>units out from the center just like we set above. You can see how the <add>earth is in the *local space* of the `solarSystem`. Similarly if you <add>turn on the `earthOrbit` you'll see how the moon is exactly 2 units <add>from the center of the *local space* of the `earthOrbit`. <ide> <del>Un autre exemple de scène. Une automobile dans un jeu simple pourrait avoir un graphique de scène comme celui-ci <add>A few more examples of scene graphs. An automobile in a simple game world might have a scene graph like this <ide> <ide> <img src="resources/images/scenegraph-car.svg" align="center"> <ide> <del>Si vous déplacez la carrosserie de la voiture, toutes les roues bougeront avec elle. Si vous vouliez que le corps rebondisse séparément des roues, vous pouvez lier le corps et les roues à un nœud "cadre" qui représente le cadre de la voiture. <add>If you move the car's body all the wheels will move with it. If you wanted the body <add>to bounce separate from the wheels you might parent the body and the wheels to a "frame" node <add>that represents the car's frame. <ide> <del>Un autre exemple avec un humain dans un jeu vidéo. <add>Another example is a human in a game world. <ide> <ide> <img src="resources/images/scenegraph-human.svg" align="center"> <ide> <del>Vous pouvez voir que le graphique de la scène devient assez complexe pour un humain. En fait, le graphe ci-dessus est simplifié. Par exemple, vous pouvez l'étendre pour couvrir chaque doigt (au moins 28 autres nœuds) et chaque orteil (encore 28 nœuds) plus ceux pour le visage et la mâchoire, les yeux et peut-être plus. <del> <del>Faisons un graphe semi-complexe. On va faire un char. Il aura 6 roues et une tourelle. Il pourra suivre un chemin. Il y aura une sphère qui se déplacera et le char ciblera la sphère. <add>You can see the scene graph gets pretty complex for a human. In fact <add>that scene graph above is simplified. For example you might extend it <add>to cover every finger (at least another 28 nodes) and every toe <add>(yet another 28 nodes) plus ones for the face and jaw, the eyes and maybe more. <ide> <ide> Let's make one semi-complex scene graph. We'll make a tank. The tank will have <ide> 6 wheels and a turret. The tank will follow a path. There will be a sphere that <ide> moves around and the tank will target the sphere. <ide> <del>Voici le graphique de la scène. Les maillages sont colorés en vert, les `Object3D` en bleu, les lumières en or et les caméras en violet. Une caméra n'a pas été ajoutée au graphique de la scène. <add>Here's the scene graph. The meshes are colored in green, the `Object3D`s in blue, <add>the lights in gold, and the cameras in purple. One camera has not been added <add>to the scene graph. <ide> <ide> <div class="threejs_center"><img src="resources/images/scenegraph-tank.svg" style="width: 800px;"></div> <ide> <del>Regardez dans le code pour voir la configuration de tous ces nœuds. <add>Look in the code to see the setup of all of these nodes. <ide> <del>Pour la cible, la chose que le char vise, il y a une `targetOrbit` (Object3D) qui tourne juste de la même manière que la `earthOrbit` ci-dessus. Une `targetElevation` (Object3D) qui est un enfant de `targetOrbit` fournit un décalage par rapport à `targetOrbit` et une élévation de base. Un autre `Object3D` appelé `targetBob` qui monte et descend par rapport à la `targetElevation`. Enfin, il y a le `targetMesh` qui est juste un cube que nous faisons pivoter et changeons ses couleurs. <add>For the target, the thing the tank is aiming at, there is a `targetOrbit` <add>(`Object3D`) which just rotates similar to the `earthOrbit` above. A <add>`targetElevation` (`Object3D`) which is a child of the `targetOrbit` provides an <add>offset from the `targetOrbit` and a base elevation. Childed to that is another <add>`Object3D` called `targetBob` which just bobs up and down relative to the <add>`targetElevation`. Finally there's the `targetMesh` which is just a cube we <add>rotate and change its colors <ide> <ide> ```js <del>// mettre en mouvement la cible <add>// move target <ide> targetOrbit.rotation.y = time * .27; <ide> targetBob.position.y = Math.sin(time * 2) * 4; <ide> targetMesh.rotation.x = time * 7; <ide> targetMaterial.emissive.setHSL(time * 10 % 1, 1, .25); <ide> targetMaterial.color.setHSL(time * 10 % 1, 1, .25); <ide> ``` <ide> <del>Pour le char, il y a un `Object3D` appelé `tank` qui est utilisé pour déplacer tout ce qui se trouve en dessous. Le code utilise une `SplineCurve` à laquelle il peut demander des positions le long de cette courbe. 0.0 est le début de la courbe. 1,0 est la fin de la courbe. Il demande la position actuelle où il met le réservoir. Il demande ensuite une position légèrement plus bas dans la courbe et l'utilise pour pointer le réservoir dans cette direction à l'aide de `Object3D.lookAt`. <add>For the tank there's an `Object3D` called `tank` which is used to move everything <add>below it around. The code uses a `SplineCurve` which it can ask for positions <add>along that curve. 0.0 is the start of the curve. 1.0 is the end of the curve. It <add>asks for the current position where it puts the tank. It then asks for a <add>position slightly further down the curve and uses that to point the tank in that <add>direction using `Object3D.lookAt`. <ide> <ide> ```js <ide> const tankPosition = new THREE.Vector2(); <ide> const tankTarget = new THREE.Vector2(); <ide> <ide> ... <ide> <del>// mettre en mouvement le char <add>// move tank <ide> const tankTime = time * .05; <ide> curve.getPointAt(tankTime % 1, tankPosition); <ide> curve.getPointAt((tankTime + 0.01) % 1, tankTarget); <ide> tank.position.set(tankPosition.x, 0, tankPosition.y); <ide> tank.lookAt(tankTarget.x, 0, tankTarget.y); <ide> ``` <ide> <del>La tourelle sur le dessus du char est déplacée automatiquement en tant qu'enfant du char. Pour le pointer sur la cible, nous demandons simplement la position de la cible, puis utilisons à nouveau `Object3D.lookAt`. <add>The turret on top of the tank is moved automatically by being a child <add>of the tank. To point it at the target we just ask for the target's world position <add>and then again use `Object3D.lookAt` <ide> <ide> ```js <ide> const targetPosition = new THREE.Vector3(); <ide> <ide> ... <ide> <del>// tourelle face à la cible <add>// face turret at target <ide> targetMesh.getWorldPosition(targetPosition); <ide> turretPivot.lookAt(targetPosition); <ide> ``` <del>Il y a une `tourretCamera` qui est un enfant de `turretMesh` donc il se déplacera de haut en bas et tournera avec la tourelle. On la fait viser la cible. <add> <add>There's a `turretCamera` which is a child of the `turretMesh` so <add>it will move up and down and rotate with the turret. We make that <add>aim at the target. <ide> <ide> ```js <del>// la turretCamera regarde la cible <add>// make the turretCamera look at target <ide> turretCamera.lookAt(targetPosition); <ide> ``` <del>Il y a aussi un `targetCameraPivot` qui est un enfant de `targetBob` donc il flotte <del>autour de la cible. Nous le pointons vers le char. Son but est de permettre à la <del>`targetCamera` d'être décalé par rapport à la cible elle-même. Si nous faisions de la caméra <del>un enfant de `targetBob`, elle serait à l'intérieur de la cible. <add> <add>There is also a `targetCameraPivot` which is a child of `targetBob` so it floats <add>around with the target. We aim that back at the tank. Its purpose is to allow the <add>`targetCamera` to be offset from the target itself. If we instead made the camera <add>a child of `targetBob` and just aimed the camera itself it would be inside the <add>target. <ide> <ide> ```js <del>// faire en sorte que la cibleCameraPivot regarde le char <add>// make the targetCameraPivot look at the tank <ide> tank.getWorldPosition(targetPosition); <ide> targetCameraPivot.lookAt(targetPosition); <ide> ``` <ide> <del>Enfin on fait tourner toutes les roues <add>Finally we rotate all the wheels <ide> <ide> ```js <ide> wheelMeshes.forEach((obj) => { <ide> obj.rotation.x = time * 3; <ide> }); <ide> ``` <ide> <del>Pour les caméras, nous avons configuré un ensemble de 4 caméras au moment de l'initialisation avec des descriptions. <add>For the cameras we setup an array of all 4 cameras at init time with descriptions. <ide> <ide> ```js <ide> const cameras = [ <ide> const cameras = [ <ide> const infoElem = document.querySelector('#info'); <ide> ``` <ide> <del>et nous parcourons chaque camera au moment du rendu <add>and cycle through our cameras at render time. <ide> <ide> ```js <ide> const camera = cameras[time * .25 % cameras.length | 0]; <ide> infoElem.textContent = camera.desc; <ide> <ide> {{{example url="../threejs-scenegraph-tank.html"}}} <ide> <del>J'espère que cela donne une idée du fonctionnement des graphiques de scène et de la façon dont vous pouvez les utiliser. <del>Faire des nœuds « Object3D » et leur attacher des choses est une étape importante pour utiliser <del>un moteur 3D comme Three.js bien. Souvent, on pourrait penser que des mathématiques complexes soient nécessaires <del>pour faire bouger quelque chose et faire pivoter comme vous le souhaitez. Par exemple sans graphique de scène <del>calculer le mouvement de la lune, savoir où placer les roues de la voiture par rapport à son <del>corps serait très compliqué, mais en utilisant un graphique de scène, cela devient beaucoup plus facile. <add>I hope this gives some idea of how scene graphs work and how you might use them. <add>Making `Object3D` nodes and parenting things to them is an important step to using <add>a 3D engine like three.js well. Often it might seem like some complex math is necessary <add>to make something move and rotate the way you want. For example without a scene graph <add>computing the motion of the moon or where to put the wheels of the car relative to its <add>body would be very complicated but using a scene graph it becomes much easier. <ide> <del>[Passons maintenant en revue les materials](threejs-materials.html). <add>[Next up we'll go over materials](threejs-materials.html).
1
Text
Text
fix broken link in rails 3.0 release_notes
4b802bc4f1a3bd35b15d80d1d62280d96114aef5
<ide><path>guides/source/3_0_release_notes.md <ide> More Information: <ide> <ide> Major re-write was done in the Action View helpers, implementing Unobtrusive JavaScript (UJS) hooks and removing the old inline AJAX commands. This enables Rails to use any compliant UJS driver to implement the UJS hooks in the helpers. <ide> <del>What this means is that all previous `remote_<method>` helpers have been removed from Rails core and put into the [Prototype Legacy Helper](http://github.com/rails/prototype_legacy_helper.) To get UJS hooks into your HTML, you now pass `:remote => true` instead. For example: <add>What this means is that all previous `remote_<method>` helpers have been removed from Rails core and put into the [Prototype Legacy Helper](http://github.com/rails/prototype_legacy_helper) To get UJS hooks into your HTML, you now pass `:remote => true` instead. For example: <ide> <ide> ```ruby <ide> form_for @post, :remote => true
1
Ruby
Ruby
initialize git when generating plugins
8541ad319a6546d87bf8f5b758e8bad4fb1ec5b4
<ide><path>railties/lib/rails/generators/rails/plugin/plugin_generator.rb <ide> def gemfile_entry <ide> append_file gemfile_in_app_path, entry <ide> end <ide> end <add> <add> def version_control <add> if !options[:skip_git] && !options[:pretend] <add> run "git init", capture: options[:quiet], abort_on_failure: false <add> end <add> end <ide> end <ide> <ide> module Generators <ide> def create_root_files <ide> build(:license) <ide> build(:gitignore) unless options[:skip_git] <ide> build(:gemfile) unless options[:skip_gemfile] <add> build(:version_control) <ide> end <ide> <ide> def create_app_files <ide><path>railties/test/generators/plugin_generator_test.rb <ide> def test_correct_file_in_lib_folder_of_camelcase_plugin_name <ide> end <ide> <ide> def test_generating_without_options <del> run_generator <add> output = run_generator <ide> assert_file "README.md", /Bukkits/ <ide> assert_no_file "config/routes.rb" <ide> assert_no_file "app/assets/config/bukkits_manifest.js" <ide> def test_generating_without_options <ide> assert_file "test/bukkits_test.rb", /assert_kind_of Module, Bukkits/ <ide> assert_file "bin/test" <ide> assert_no_file "bin/rails" <add> assert_match(/run git init/, output) <ide> end <ide> <ide> def test_generating_in_full_mode_with_almost_of_all_skip_options
2
Ruby
Ruby
make path instead of symlink for lib/r
3a535ed36b346694ab9f2143ef5f28e314318520
<ide><path>Library/Homebrew/keg.rb <ide> def link(mode = OpenStruct.new) <ide> when /^perl5/ then :mkpath <ide> when "php" then :mkpath <ide> when /^python[23]\.\d/ then :mkpath <add> when /^R/ then :mkpath <ide> when /^ruby/ then :mkpath <ide> # Everything else is symlinked to the cellar <ide> else :link
1
PHP
PHP
raise exceptions on missing elements
4e49b63140ef78712e26922269ae80b052bdf0df
<ide><path>src/View/Error/MissingElementException.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://book.cakephp.org/2.0/en/development/testing.html <add> * @since 3.0.0 <add> * @license http://www.opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\View\Error; <add> <add>use Cake\Error\Exception; <add> <add>/** <add> * Used when an element file cannot be found. <add> */ <add>class MissingElementException extends Exception { <add> <add>/** <add> * Message template <add> * <add> * @var string <add> */ <add> protected $_messageTemplate = 'Element file "%s" is missing.'; <add> <add>} <ide><path>src/View/View.php <ide> public function __construct(Request $request = null, Response $response = null, <ide> * - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_` <ide> * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element. <ide> * Defaults to false. <del> * - `ignoreMissing` - Used to allow missing elements. Set to true to not trigger notices. <add> * - `ignoreMissing` - Used to allow missing elements. Set to true to not throw exceptions. <ide> * @return string Rendered Element <add> * @throws <ide> */ <ide> public function element($name, array $data = array(), array $options = array()) { <ide> $file = $plugin = null; <ide> public function element($name, array $data = array(), array $options = array()) <ide> list ($plugin, $name) = pluginSplit($name, true); <ide> $name = str_replace('/', DS, $name); <ide> $file = $plugin . 'Element' . DS . $name . $this->_ext; <del> trigger_error(sprintf('Element Not Found: %s', $file), E_USER_NOTICE); <add> throw new Error\MissingElementException($file); <ide> } <ide> } <ide> <ide><path>tests/TestCase/View/ViewTest.php <ide> public function index() { <ide> */ <ide> class TestThemeView extends View { <ide> <del>/** <del> * renderElement method <del> * <del> * @param string $name Element name. <del> * @param array $params Params list. <del> * @return string The given name <del> */ <del> public function renderElement($name, $params = array()) { <del> return $name; <del> } <del> <ide> /** <ide> * getViewFileName method <ide> * <ide> public function testElement() { <ide> /** <ide> * Test elementInexistent method <ide> * <del> * @expectedException PHPUnit_Framework_Error_Notice <add> * @expectedException Cake\View\Error\MissingElementException <ide> * @return void <ide> */ <ide> public function testElementInexistent() { <ide> public function testElementInexistent() { <ide> /** <ide> * Test elementInexistent3 method <ide> * <del> * @expectedException PHPUnit_Framework_Error_Notice <add> * @expectedException Cake\View\Error\MissingElementException <ide> * @return void <ide> */ <ide> public function testElementInexistent3() {
3
Text
Text
fix minor punctuation issue in path.md
35d82af78c1bbd05baa783b3b25f2eb7b48d1848
<ide><path>doc/api/path.md <ide> For instance, given the sequence of path segments: `/foo`, `/bar`, `baz`, <ide> calling `path.resolve('/foo', '/bar', 'baz')` would return `/bar/baz` <ide> because `'baz'` is not an absolute path but `'/bar' + '/' + 'baz'` is. <ide> <del>If after processing all given `path` segments an absolute path has not yet <add>If, after processing all given `path` segments, an absolute path has not yet <ide> been generated, the current working directory is used. <ide> <ide> The resulting path is normalized and trailing slashes are removed unless the
1
PHP
PHP
fix bug in model names
d67977bba04cd04e6c55de4206e3632f9c34a8d1
<ide><path>cake/scripts/bake.php <ide> function __bakeViews($controllerName, $controllerPath, $admin= null, $admin_url <ide> <ide> //-------------------------[INDEX]-------------------------// <ide> $indexView = null; <del> if(!empty($modelObj->alias)) { <del> foreach ($modelObj->alias as $key => $value) { <del> $alias[] = $key; <del> } <del> } <ide> $indexView .= "<div class=\"{$pluralName}\">\n"; <ide> $indexView .= "<h2>List " . $pluralHumanName . "</h2>\n\n"; <ide> $indexView .= "<table cellpadding=\"0\" cellspacing=\"0\">\n"; <ide> function __bakeViews($controllerName, $controllerPath, $admin= null, $admin_url <ide> $otherControllerPath = $this->__controllerPath($otherControllerName); <ide> if(is_object($otherModelObj)) { <ide> $displayField = $otherModelObj->getDisplayField(); <del> $indexView .= "\t<td>&nbsp;<?php echo \$html->link(\$".$singularName."['{$alias[$count]}']['{$displayField}'], '{$admin_url}/" . $otherControllerPath . "/view/' .\$".$singularName."['{$alias[$count]}']['{$otherModelObj->primaryKey}'])?></td>\n"; <add> $indexView .= "\t<td>&nbsp;<?php echo \$html->link(\$".$singularName."['{$otherModelName}']['{$displayField}'], '{$admin_url}/" . $otherControllerPath . "/view/' .\$".$singularName."['{$otherModelName}']['{$otherModelObj->primaryKey}'])?></td>\n"; <ide> } else { <ide> $indexView .= "\t<td><?php echo \$".$singularName."['{$modelObj->name}']['{$field}']; ?></td>\n"; <ide> } <ide> function __bakeViews($controllerName, $controllerPath, $admin= null, $admin_url <ide> $viewView .= "<dl>\n"; <ide> $count = 0; <ide> foreach($fieldNames as $field => $value) { <del> $viewView .= "\t<dt>" . $value['prompt'] . "</dt>\n"; <add> $viewView .= "\t<dt>" . $value['label'] . "</dt>\n"; <ide> if(isset($value['foreignKey'])) { <ide> $otherModelName = $this->__modelName($value['model']); <ide> $otherModelKey = Inflector::underscore($value['modelKey']); <ide> $otherModelObj =& ClassRegistry::getObject($value['modelKey']); <ide> $otherControllerName = $this->__controllerName($value['modelKey']); <ide> $otherControllerPath = $this->__controllerPath($otherControllerName); <ide> $displayField = $otherModelObj->getDisplayField(); <del> $viewView .= "\t<dd>&nbsp;<?php echo \$html->link(\$".$singularName."['{$alias[$count]}']['{$displayField}'], '{$admin_url}/" . $otherControllerPath . "/view/' .\$".$singularName."['{$alias[$count]}']['{$otherModelObj->primaryKey}'])?></dd>\n"; <add> $viewView .= "\t<dd>&nbsp;<?php echo \$html->link(\$".$singularName."['{$otherModelName}']['{$displayField}'], '{$admin_url}/" . $otherControllerPath . "/view/' .\$".$singularName."['{$otherModelName}']['{$otherModelObj->primaryKey}'])?></dd>\n"; <ide> $count++; <ide> } else { <ide> $viewView .= "\t<dd>&nbsp;<?php echo \$".$singularName."['{$modelObj->name}']['{$field}']?></dd>\n";
1
Javascript
Javascript
require project completion to claim certs
1f65b3b7eb026a5cdc9e0b39fd7f1ddaabdac57d
<ide><path>curriculum/getChallenges.js <ide> ${getFullPath('english')} <ide> // while the auditing is ongoing, we default to English for un-audited certs <ide> // once that's complete, we can revert to using isEnglishChallenge(fullPath) <ide> const useEnglish = lang === 'english' || !isAuditedCert(lang, superBlock); <del> const isCert = path.extname(filePath) === 'markdown'; <add> const isCert = path.extname(filePath) === '.markdown'; <ide> let challenge; <ide> <ide> if (isCert) { <add> // TODO: this uses the old parser to handle certifcates, but Markdown is a <add> // clunky way to store data, consider converting to YAML and removing the <add> // old parser. <ide> challenge = await (useEnglish <ide> ? parseMarkdown(getFullPath('english')) <ide> : parseTranslation(
1
PHP
PHP
move tests for http\client
0b156617b500857654ac48155434bdc71c69e1c2
<add><path>tests/TestCase/Http/Client/Adapter/StreamTest.php <del><path>tests/TestCase/Network/Http/Adapter/StreamTest.php <ide> * @since 3.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Network\Http\Adapter; <add>namespace Cake\Test\TestCase\Http\Client\Adapter; <ide> <ide> use Cake\Http\Client\Adapter\Stream; <ide> use Cake\Http\Client\Request; <add><path>tests/TestCase/Http/Client/Auth/DigestTest.php <del><path>tests/TestCase/Network/Http/Auth/DigestTest.php <ide> * @since 3.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Network\Http\Auth; <add>namespace Cake\Test\TestCase\Http\Client\Auth; <ide> <ide> use Cake\Http\Client; <ide> use Cake\Http\Client\Auth\Digest; <add><path>tests/TestCase/Http/Client/Auth/OauthTest.php <del><path>tests/TestCase/Network/Http/Auth/OauthTest.php <ide> * @since 3.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Network\Http\Auth; <add>namespace Cake\Test\TestCase\Http\Client\Auth; <ide> <ide> use Cake\Http\Client\Auth\Oauth; <ide> use Cake\Http\Client\Request; <add><path>tests/TestCase/Http/Client/CookieCollectionTest.php <del><path>tests/TestCase/Network/Http/CookieCollectionTest.php <ide> * @since 3.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Network\Http; <add>namespace Cake\Test\TestCase\Http\Client; <ide> <ide> use Cake\Http\Client\CookieCollection; <ide> use Cake\Http\Client\Response; <add><path>tests/TestCase/Http/Client/FormDataTest.php <del><path>tests/TestCase/Network/Http/FormDataTest.php <ide> * @since 3.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Network\Http; <add>namespace Cake\Test\TestCase\Http\Client; <ide> <ide> use Cake\Http\Client\FormData; <ide> use Cake\TestSuite\TestCase; <add><path>tests/TestCase/Http/Client/RequestTest.php <del><path>tests/TestCase/Network/Http/RequestTest.php <ide> * @since 3.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Network\Http; <add>namespace Cake\Test\TestCase\Http\Client; <ide> <ide> use Cake\Http\Client\Request; <ide> use Cake\TestSuite\TestCase; <add><path>tests/TestCase/Http/Client/ResponseTest.php <del><path>tests/TestCase/Network/Http/ResponseTest.php <ide> * @since 3.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Network\Http; <add>namespace Cake\Test\TestCase\Http\Client; <ide> <ide> use Cake\Http\Client\Response; <ide> use Cake\TestSuite\TestCase; <add><path>tests/TestCase/Http/ClientTest.php <del><path>tests/TestCase/Network/Http/ClientTest.php <ide> * @since 3.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Network\Http; <add>namespace Cake\Test\TestCase\Http; <ide> <ide> use Cake\Core\Configure; <ide> use Cake\Http\Client;
8
PHP
PHP
apply fixes from styleci
16156447e4a0e47b4b46ade43731296f4b033f04
<ide><path>src/Illuminate/Foundation/Console/PolicyMakeCommand.php <ide> namespace Illuminate\Foundation\Console; <ide> <ide> use Illuminate\Console\GeneratorCommand; <del>use Illuminate\Contracts\Auth\Access\Authorizable; <ide> use Illuminate\Support\Str; <ide> use Symfony\Component\Console\Input\InputOption; <ide> <ide> protected function userProviderModel() <ide> $guard = $this->option('guard') ?: $config->get('auth.defaults.guard'); <ide> <ide> return $config->get( <del> "auth.providers.".$config->get('auth.guards.'.$guard.'.provider').".model" <add> 'auth.providers.'.$config->get('auth.guards.'.$guard.'.provider').'.model' <ide> ); <ide> } <ide>
1
Java
Java
fix layout animation crash
9fb31d15381647c7c7a28ebe28f8a8676d65eb19
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java <ide> public synchronized void manageChildren( <ide> arrayContains(tagsToDelete, viewToRemove.getId())) { <ide> // The view will be removed and dropped by the 'delete' layout animation <ide> // instead, so do nothing <del> } else { <add> } else if (viewToManage != null) { <ide> viewManager.removeViewAt(viewToManage, normalizedIndexToRemove); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutAnimationController.java <ide> public void reset() { <ide> } <ide> <ide> public boolean shouldAnimateLayout(View viewToAnimate) { <del> // if view parent is null, skip animation: view have been clipped, we don't want animation to <del> // resume when view is re-attached to parent, which is the standard android animation behavior. <del> // If there's a layout handling animation going on, it should be animated nonetheless since the <del> // ongoing animation needs to be updated. <add> // if view is null or the view parent is null, skip animation: view have been clipped, <add> // we don't want animation to resume when view is re-attached to parent, which is the <add> // standard android animation behavior. If there's a layout handling animation going on, <add> // it should be animated nonetheless since the ongoing animation needs to be updated. <add> <add> if (viewToAnimate == null) { <add> return false; <add> } <ide> return (mShouldAnimateLayout && viewToAnimate.getParent() != null) <ide> || mLayoutHandlers.get(viewToAnimate.getId()) != null; <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java <ide> public void removeViewAt(int index) { <ide> mDrawingOrderHelper.handleRemoveView(getChildAt(index)); <ide> setChildrenDrawingOrderEnabled(mDrawingOrderHelper.shouldEnableCustomDrawingOrder()); <ide> <del> super.removeViewAt(index); <add> if (getChildAt(index) != null) { <add> super.removeViewAt(index); <add> } <ide> } <ide> <ide> @Override
3
Ruby
Ruby
use a set to track failed downloads
3a96a1a594d688225675d0b9bd7f90fd4669b7a5
<ide><path>Library/Homebrew/cmd/fetch.rb <ide> def fetch_patch p <ide> private <ide> <ide> def retry_fetch? f <del> @fetch_failed ||= {} <del> already_failed = @fetch_failed.fetch(f.name, false) <del> <del> if already_failed || !ARGV.include?("--retry") <add> @fetch_failed ||= Set.new <add> if ARGV.include?("--retry") && @fetch_failed.add?(f.name) <add> ohai "Retrying download" <add> f.clear_cache <add> true <add> else <ide> Homebrew.failed = true <del> return false <add> false <ide> end <del> <del> ohai "Retrying download" <del> <del> f.clear_cache <del> @fetch_failed[f.name] = true <del> true <ide> end <ide> <ide> def fetch_fetchable f
1
Ruby
Ruby
fix subversion remote check logic
bbf71921eb2b2cce5072bb615fac3a2bc96fcfc7
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_urls <ide> elsif strategy <= SubversionDownloadStrategy <ide> next unless DevelopmentTools.subversion_handles_most_https_certificates? <ide> next unless Utils.svn_available? <del> if Utils.svn_remote_exists url <add> unless Utils.svn_remote_exists url <ide> problem "The URL #{url} is not a valid svn URL" <ide> end <ide> end
1
Text
Text
update changelog for 1.5.0-beta.2
3bcd9bdca42b1398322a9f14588248ff7b870a2b
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add> <add>### Ember 1.5.0-beta.2 (February 23, 2014) <add> <add>* [SECURITY] Ensure that `ember-routing-auto-location` cannot be forced to redirect to another domain. <add>* [BUGFIX beta] Handle ES6 transpiler errors. <add>* [BUGFIX beta] Ensure namespaces are cleaned up. <add>* Many documentation updates. <add> <ide> ### Ember 1.5.0-beta.1 (February 14, 2014) <ide> <ide> * [FEATURE ember-handlebars-log-primitives]
1
PHP
PHP
fix failing tests and errors in php72
8d896ac6e503d497b243665c8f74b4d5316efec4
<ide><path>src/Console/ConsoleOptionParser.php <ide> public function help(?string $subcommand = null, string $format = 'text', int $w <ide> $message = sprintf( <ide> 'Unable to find the `%s %s` subcommand. See `bin/%s %s --help`.', <ide> $rootCommand, <del> $command, <add> $subcommand, <ide> $this->rootName, <ide> $rootCommand <ide> ); <ide> throw new InvalidOptionException( <ide> $message, <del> $command, <del> array_keys((array)$this->subcommands()), <add> $subcommand, <add> array_keys((array)$this->subcommands()) <ide> ); <ide> } <ide> <ide><path>src/Console/Shell.php <ide> public function runCommand(array $argv, bool $autoMethod = false, array $extra = <ide> } <ide> <ide> $this->err('No subcommand provided. Choose one of the available subcommands.', 2); <del> $this->_io->err($this->OptionParser->help($command)); <add> try { <add> $this->_io->err($this->OptionParser->help($command)); <add> } catch (ConsoleException $e) { <add> $this->err('Error: ' . $e->getMessage()); <add> } <ide> <ide> return false; <ide> } <ide><path>tests/TestCase/Console/ConsoleOptionParserTest.php <ide> public function testHelpUnknownSubcommand() <ide> ->addOption('test', ['help' => 'A test option.']) <ide> ->addSubcommand('unstash'); <ide> <del> $result = $parser->help('unknown'); <del> $expected = <<<TEXT <del>Unable to find the `mycommand unknown` subcommand. See `bin/cake mycommand --help`. <del> <del>Did you mean : `mycommand unstash` ? <del> <del>Available subcommands for the `mycommand` command are : <del> <del> - method <del> - unstash <del>TEXT; <del> $this->assertTextEquals($expected, $result, 'Help is not correct.'); <add> try { <add> $result = $parser->help('unknown'); <add> } catch (InvalidOptionException $e) { <add> $result = $e->getFullMessage(); <add> $this->assertStringContainsString( <add> "Unable to find the `mycommand unknown` subcommand. See `bin/cake mycommand --help`.\n" . <add> "\n" . <add> "Other valid choices:\n" . <add> "\n" . <add> "- method", <add> $result, <add> ); <add> } <ide> } <ide> <ide> /**
3
Python
Python
update the small nanmedian threshold
3b31fa130959bbc5544e7b5fa5226076466d6d88
<ide><path>numpy/lib/nanfunctions.py <ide> def _nanmedian(a, axis=None, out=None, overwrite_input=False): <ide> else: <ide> # for small medians use sort + indexing which is still faster than <ide> # apply_along_axis <del> if a.shape[axis] < 400: <add> if a.shape[axis] < 1000: <ide> return _nanmedian_small(a, axis, out, overwrite_input) <ide> result = np.apply_along_axis(_nanmedian1d, axis, a, overwrite_input) <ide> if out is not None:
1
PHP
PHP
use implicit null instead of explicit
3435710575ad1aa9a302cbd3ac7b7a93946bb8c0
<ide><path>database/factories/ModelFactory.php <ide> */ <ide> <ide> $factory->define(App\User::class, function (Faker\Generator $faker) { <del> static $password = null; <add> static $password; <ide> <ide> return [ <ide> 'name' => $faker->name,
1
Mixed
Text
fix broken references
048b3de22d843a8dd3d00b00b702205ca90dbf58
<ide><path>doc/api/crypto.md <ide> the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. <ide> [`hmac.update()`]: #crypto_hmac_update_data_input_encoding <ide> [`sign.sign()`]: #crypto_sign_sign_private_key_output_format <ide> [`sign.update()`]: #crypto_sign_update_data_input_encoding <del>[`tls.createSecureContext()`]: tls.html#tls_tls_createsecurecontext_details <add>[`tls.createSecureContext()`]: tls.html#tls_tls_createsecurecontext_options <ide> [`verify.update()`]: #crypto_verifier_update_data_input_encoding <ide> [`verify.verify()`]: #crypto_verifier_verify_object_signature_signature_format <ide> [Caveats]: #crypto_support_for_weak_or_compromised_algorithms <ide><path>doc/api/net.md <ide> Returns true if input is a version 6 IP address, otherwise returns false. <ide> [`connect()`]: #net_socket_connect_options_connectlistener <ide> [`destroy()`]: #net_socket_destroy <ide> [`dns.lookup()`]: dns.html#dns_dns_lookup_hostname_options_callback <del>[`dns.lookup()` hints]: #dns_supported_getaddrinfo_flags <add>[`dns.lookup()` hints]: dns.html#dns_supported_getaddrinfo_flags <ide> [`end()`]: #net_socket_end_data_encoding <ide> [`EventEmitter`]: events.html#events_class_eventemitter <ide> [`net.Socket`]: #net_class_net_socket <ide><path>doc/topics/domain-postmortem.md <ide> handle. More on this in _Resource Cleanup on Exception_. <ide> <ide> ### Resource Cleanup on Exception <ide> <del>The script [`domain-resource-cleanup.js`](domain-resource-cleanup.js) <add>The script [`domain-resource-cleanup-example.js`][] <ide> contains a more complex example of properly cleaning up in a small resource <ide> dependency tree in the case that an exception occurs in a given connection or <ide> any of its dependencies. Breaking down the script into its basic operations: <ide> this writing there is ongoing work building out the `AsyncWrap` API and a <ide> proposal for Zones being prepared for the TC39. At such time there is suitable <ide> functionality to replace domains it will undergo the full deprecation cycle and <ide> eventually be removed from core. <add> <add>[domain-resource-cleanup-example.js]: ./domain-resource-cleanup-example.js <ide><path>tools/doc/type-parser.js <ide> const typeMap = { <ide> 'cluster.Worker': 'cluster.html#cluster_class_worker', <ide> 'dgram.Socket': 'dgram.html#dgram_class_dgram_socket', <ide> 'net.Socket': 'net.html#net_class_net_socket', <del> 'EventEmitter': 'events.html#events_class_events_eventemitter', <add> 'EventEmitter': 'events.html#events_class_eventemitter', <ide> 'Timer': 'timers.html#timers_timers' <ide> }; <ide>
4
Javascript
Javascript
add w3cpointerevent example to rntester android
50070ec7c64b4d9ad087606c2a4eee5eb80b9ca9
<ide><path>packages/rn-tester/js/examples/Experimental/W3CPointerEventsExample.js <add>/** <add> * Copyright (c) Meta Platforms, Inc. and affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @format <add> * @flow <add> */ <add> <add>import {Button, Switch, StyleSheet, ScrollView, View, Text} from 'react-native'; <add>import * as React from 'react'; <add>import type {ViewProps} from 'react-native/Libraries/Components/View/ViewPropTypes'; <add> <add>function EventfulView(props: {| <add> name: string, <add> log: string => void, <add> ...ViewProps, <add>|}) { <add> const ref = React.useRef<?React.ElementRef<typeof View>>(); <add> React.useEffect(() => { <add> // $FlowFixMe[prop-missing] Using private property <add> setTag(ref.current?._nativeTag); <add> }, [ref]); <add> const [lastEvent, setLastEvent] = React.useState(''); <add> const [listen, setListen] = React.useState(false); <add> const [tag, setTag] = React.useState(''); <add> <add> const {log, name, children, ...restProps} = props; <add> <add> const eventLog = eventName => event => { <add> // $FlowFixMe[prop-missing] Using private property <add> log(`${name} - ${eventName} - target: ${event.target._nativeTag}`); <add> setLastEvent(eventName); <add> }; <add> <add> const listeners = listen <add> ? { <add> onPointerUp: eventLog('up'), <add> onPointerDown: eventLog('down'), <add> onPointerLeave2: eventLog('leave'), <add> onPointerEnter2: eventLog('enter'), <add> } <add> : Object.freeze({}); <add> <add> return ( <add> <View ref={ref} {...listeners} {...restProps}> <add> <View style={styles.row}> <add> <Text> <add> {props.name}, {tag}, last event: {lastEvent} <add> </Text> <add> <Switch value={listen} onValueChange={() => setListen(l => !l)} /> <add> </View> <add> {props.children} <add> </View> <add> ); <add>} <add> <add>function RelativeChildExample() { <add> const [eventsLog, setEventsLog] = React.useState(''); <add> const clear = () => setEventsLog(''); <add> const log = eventStr => { <add> setEventsLog(currentEventsLog => `${currentEventsLog}\n${eventStr}`); <add> }; <add> return ( <add> <ScrollView> <add> <View> <add> <EventfulView <add> log={log} <add> collapsable={false} <add> style={StyleSheet.compose(styles.eventfulView, styles.parent)} <add> name="parent"> <add> <EventfulView <add> log={log} <add> style={StyleSheet.compose( <add> styles.eventfulView, <add> styles.relativeChild, <add> )} <add> name="childA"> <add> <EventfulView <add> log={log} <add> style={StyleSheet.compose( <add> styles.eventfulView, <add> styles.relativeChild, <add> )} <add> name="childB" <add> /> <add> </EventfulView> <add> </EventfulView> <add> </View> <add> <View> <add> <View style={styles.row}> <add> <Text>Events Log</Text> <add> <Button onPress={clear} title="Clear" /> <add> </View> <add> <Text>{eventsLog}</Text> <add> </View> <add> </ScrollView> <add> ); <add>} <add> <add>const styles = StyleSheet.create({ <add> absoluteChild: { <add> position: 'absolute', <add> top: 400, <add> left: 40, <add> height: 100, <add> width: 200, <add> borderWidth: 1, <add> borderColor: 'red', <add> }, <add> eventfulView: { <add> paddingBottom: 40, <add> }, <add> relativeChild: {borderWidth: 1, margin: 10}, <add> parent: { <add> margin: 20, <add> borderWidth: 1, <add> }, <add> row: { <add> flexDirection: 'row', <add> justifyContent: 'center', <add> alignItems: 'center', <add> }, <add>}); <add> <add>exports.title = 'W3C PointerEvents experiment'; <add>exports.category = 'Experimental'; <add>exports.description = 'Demonstrate pointer events'; <add>exports.examples = [ <add> { <add> title: 'Relative Child', <add> render(): React.Node { <add> return <RelativeChildExample />; <add> }, <add> }, <add>]; <ide><path>packages/rn-tester/js/utils/RNTesterList.android.js <ide> const APIs: Array<RNTesterModuleInfo> = [ <ide> category: 'UI', <ide> module: require('../examples/Dimensions/DimensionsExample'), <ide> }, <add> { <add> key: 'W3C PointerEvents', <add> category: 'Experimental', <add> module: require('../examples/Experimental/W3CPointerEventsExample'), <add> }, <ide> { <ide> key: 'LayoutEventsExample', <ide> category: 'UI',
2
Javascript
Javascript
move getsafepropertyname to utils
b1e12fb0d57f99f80cbf93d18a6c3ee3bba0b4d4
<ide><path>packages/react-native-codegen/src/generators/modules/ObjCppUtils/GenerateStructs.js <ide> 'use strict'; <ide> <ide> import type {ObjectParamTypeAnnotation} from '../../../CodegenSchema'; <del>const {flatObjects, capitalizeFirstLetter} = require('./Utils'); <add>const { <add> flatObjects, <add> capitalizeFirstLetter, <add> getSafePropertyName, <add>} = require('./Utils'); <ide> const {generateStructsForConstants} = require('./GenerateStructsForConstants'); <ide> <ide> const template = ` <ide> inline ::_RETURN_TYPE_::JS::Native::_MODULE_NAME_::::Spec::_STRUCT_NAME_::::::_P <ide> } <ide> `; <ide> <del>function getSafePropertyName(name: string) { <del> if (name === 'id') { <del> return `${name}_`; <del> } <del> return name; <del>} <del> <del>function getNamespacedStructName(structName: string, propertyName: string) { <add>function getNamespacedStructName( <add> structName: string, <add> property: ObjectParamTypeAnnotation, <add>) { <ide> return `JS::Native::_MODULE_NAME_::::Spec${structName}${capitalizeFirstLetter( <del> getSafePropertyName(propertyName), <add> getSafePropertyName(property), <ide> )}`; <ide> } <ide> <ide> function getElementTypeForArray( <ide> case 'Int32TypeAnnotation': <ide> return 'double'; <ide> case 'ObjectTypeAnnotation': <del> return getNamespacedStructName(name, property.name) + 'Element'; <add> return getNamespacedStructName(name, property) + 'Element'; <ide> case 'GenericObjectTypeAnnotation': <ide> // TODO(T67565166): Generic objects are not type safe and should be disallowed in the schema. This case should throw an error once it is disallowed in schema. <ide> console.error( <ide> function getInlineMethodSignature( <ide> console.error( <ide> `Warning: Unsafe type found (see '${property.name}' in ${moduleName}'s ${name})`, <ide> ); <del> return `id<NSObject> ${getSafePropertyName(property.name)}() const;`; <add> return `id<NSObject> ${getSafePropertyName(property)}() const;`; <ide> } <ide> <ide> switch (typeAnnotation.type) { <ide> case 'ReservedFunctionValueTypeAnnotation': <ide> switch (typeAnnotation.name) { <ide> case 'RootTag': <del> return `double ${getSafePropertyName(property.name)}() const;`; <add> return `double ${getSafePropertyName(property)}() const;`; <ide> default: <ide> (typeAnnotation.name: empty); <ide> throw new Error(`Unknown prop type, found: ${typeAnnotation.name}"`); <ide> } <ide> case 'StringTypeAnnotation': <del> return `NSString *${getSafePropertyName(property.name)}() const;`; <add> return `NSString *${getSafePropertyName(property)}() const;`; <ide> case 'NumberTypeAnnotation': <ide> case 'FloatTypeAnnotation': <ide> case 'Int32TypeAnnotation': <ide> return `${markOptionalTypeIfNecessary('double')} ${getSafePropertyName( <del> property.name, <add> property, <ide> )}() const;`; <ide> case 'BooleanTypeAnnotation': <ide> return `${markOptionalTypeIfNecessary('bool')} ${getSafePropertyName( <del> property.name, <add> property, <ide> )}() const;`; <ide> case 'ObjectTypeAnnotation': <ide> return ( <del> markOptionalTypeIfNecessary( <del> getNamespacedStructName(name, property.name), <del> ) + ` ${getSafePropertyName(property.name)}() const;` <add> markOptionalTypeIfNecessary(getNamespacedStructName(name, property)) + <add> ` ${getSafePropertyName(property)}() const;` <ide> ); <ide> case 'GenericObjectTypeAnnotation': <ide> case 'AnyTypeAnnotation': <ide> return `id<NSObject> ${ <ide> property.optional ? '_Nullable ' : ' ' <del> }${getSafePropertyName(property.name)}() const;`; <add> }${getSafePropertyName(property)}() const;`; <ide> case 'ArrayTypeAnnotation': <ide> return `${markOptionalTypeIfNecessary( <ide> `facebook::react::LazyVector<${getElementTypeForArray( <ide> property, <ide> name, <ide> moduleName, <ide> )}>`, <del> )} ${getSafePropertyName(property.name)}() const;`; <add> )} ${getSafePropertyName(property)}() const;`; <ide> case 'FunctionTypeAnnotation': <ide> default: <ide> throw new Error(`Unknown prop type, found: ${typeAnnotation.type}"`); <ide> function getInlineMethodImplementation( <ide> case 'BooleanTypeAnnotation': <ide> return `RCTBridgingToBool(${element})`; <ide> case 'ObjectTypeAnnotation': <del> return `${getNamespacedStructName( <del> name, <del> property.name, <del> )}Element(${element})`; <add> return `${getNamespacedStructName(name, property)}Element(${element})`; <ide> case 'GenericObjectTypeAnnotation': <ide> return element; <ide> case 'AnyObjectTypeAnnotation': <ide> function getInlineMethodImplementation( <ide> return inlineTemplate <ide> .replace( <ide> /::_RETURN_TYPE_::/, <del> markOptionalTypeIfNecessary( <del> getNamespacedStructName(name, property.name), <del> ), <add> markOptionalTypeIfNecessary(getNamespacedStructName(name, property)), <ide> ) <ide> .replace( <ide> /::_RETURN_VALUE_::/, <ide> property.optional <ide> ? `(p == nil ? folly::none : folly::make_optional(${getNamespacedStructName( <ide> name, <del> property.name, <add> property, <ide> )}(p)))` <del> : `${getNamespacedStructName(name, property.name)}(p)`, <add> : `${getNamespacedStructName(name, property)}(p)`, <ide> ); <ide> case 'ArrayTypeAnnotation': <ide> return inlineTemplate <ide> function translateObjectsForStructs( <ide> acc.concat( <ide> object.properties.map(property => <ide> getInlineMethodImplementation(property, object.name, moduleName) <del> .replace( <del> /::_PROPERTY_NAME_::/g, <del> getSafePropertyName(property.name), <del> ) <add> .replace(/::_PROPERTY_NAME_::/g, getSafePropertyName(property)) <ide> .replace(/::_STRUCT_NAME_::/g, object.name), <ide> ), <ide> ), <ide><path>packages/react-native-codegen/src/generators/modules/ObjCppUtils/Utils.js <ide> function flatObjects( <ide> <ide> return flattenObjects; <ide> } <add> <add>function getSafePropertyName(property: ObjectParamTypeAnnotation): string { <add> if (property.name === 'id') { <add> return `${property.name}_`; <add> } <add> return property.name; <add>} <add> <ide> module.exports = { <ide> flatObjects, <ide> capitalizeFirstLetter, <add> getSafePropertyName, <ide> };
2
Text
Text
update http urls to https in governance.md
7f446f0fb20d53d68f5745f22852aafae7bd2922
<ide><path>GOVERNANCE.md <ide> The TSC follows a [Consensus Seeking][] decision making model as described by <ide> the [TSC Charter][]. <ide> <ide> [TSC Charter]: https://github.com/nodejs/TSC/blob/master/TSC-Charter.md <del>[Consensus Seeking]: http://en.wikipedia.org/wiki/Consensus-seeking_decision-making <add>[Consensus Seeking]: https://en.wikipedia.org/wiki/Consensus-seeking_decision-making
1
Java
Java
reintroduce suppression of deprecation warning
802763d26f4aa263df2d474746f3963912f8660b
<ide><path>spring-test/src/main/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.java <ide> protected Class<? extends Throwable> getExpectedException(FrameworkMethod framew <ide> * @see #getJUnitTimeout(FrameworkMethod) <ide> */ <ide> @Override <add> // Retain the following warning suppression for deprecation (even if Eclipse <add> // states it is unnecessary) since withPotentialTimeout(FrameworkMethod,Object,Statement) <add> // in BlockJUnit4ClassRunner has been deprecated. <add> @SuppressWarnings("deprecation") <ide> protected Statement withPotentialTimeout(FrameworkMethod frameworkMethod, Object testInstance, Statement next) { <ide> Statement statement = null; <ide> long springTimeout = getSpringTimeout(frameworkMethod);
1
Ruby
Ruby
move jscoverage to the boneyard
099954499ffbea9e74ea1482cb03fa4da943373a
<ide><path>Library/Homebrew/tap_migrations.rb <ide> 'aimage' => 'homebrew/boneyard', <ide> 'cmucl' => 'homebrew/binary', <ide> 'lmutil' => 'homebrew/binary', <add> 'jscoverage' => 'homebrew/boneyard', <ide> }
1
Javascript
Javascript
rewrite angular-bootstrap.js to use $script
e40f8d829f10de3d73aa1026591fe014fe54eca9
<ide><path>src/angular-bootstrap.js <ide> * (c) Dustin Diaz, Jacob Thornton 2011 <ide> * License: MIT <ide> */ <del>(function(a,b){typeof module!="undefined"?module.exports=b():typeof define=="function"&&define.amd?define(a,b):this[a]=b()})("$script",function(){function q(a,b,c){for(c=0,j=a.length;c<j;++c)if(!b(a[c]))return k;return 1}function r(a,b){q(a,function(a){return!b(a)})}function s(a,b,i){function o(a){return a.call?a():d[a]}function p(){if(!--n){d[m]=1,k&&k();for(var a in f)q(a.split("|"),o)&&!r(f[a],o)&&(f[a]=[])}}a=a[l]?a:[a];var j=b&&b.call,k=j?b:i,m=j?a.join(""):b,n=a.length;return setTimeout(function(){r(a,function(a){if(h[a])return m&&(e[m]=1),h[a]==2&&p();h[a]=1,m&&(e[m]=1),t(!c.test(a)&&g?g+a+".js":a,p)})},0),s}function t(c,d){var e=a.createElement("script"),f=k;e.onload=e.onerror=e[p]=function(){if(e[n]&&!/^c|loade/.test(e[n])||f)return;e.onload=e[p]=null,f=1,h[c]=2,d()},e.async=1,e.src=c,b.insertBefore(e,b.firstChild)}var a=document,b=a.getElementsByTagName("head")[0],c=/^https?:\/\//,d={},e={},f={},g,h={},i="string",k=!1,l="push",m="DOMContentLoaded",n="readyState",o="addEventListener",p="onreadystatechange";return!a[n]&&a[o]&&(a[o](m,function u(){a.removeEventListener(m,u,k),a[n]="complete"},k),a[n]="loading"),s.get=t,s.order=function(a,b,c){(function d(e){e=a.shift(),a.length?s(e,d):s(e,b,c)})()},s.path=function(a){g=a},s.ready=function(a,b,c){a=a[l]?a:[a];var e=[];return!r(a,function(a){d[a]||e[l](a)})&&q(a,function(a){return d[a]})?b():!function(a){f[a]=f[a]||[],f[a][l](b),c&&c(e)}(a.join("|")),s},s}); <add>(function (name, definition, context) { <add> if (typeof context['module'] != 'undefined' && context['module']['exports']) context['module']['exports'] = definition() <add> else if (typeof context['define'] != 'undefined' && context['define'] == 'function' && context['define']['amd']) define(name, definition) <add> else context[name] = definition() <add>})('$script', function () { <add> var doc = document <add> , head = doc.getElementsByTagName('head')[0] <add> , validBase = /^https?:\/\// <add> , list = {}, ids = {}, delay = {}, scriptpath <add> , scripts = {}, s = 'string', f = false <add> , push = 'push', domContentLoaded = 'DOMContentLoaded', readyState = 'readyState' <add> , addEventListener = 'addEventListener', onreadystatechange = 'onreadystatechange' <add> <add> function every(ar, fn) { <add> for (var i = 0, j = ar.length; i < j; ++i) if (!fn(ar[i])) return f <add> return 1 <add> } <add> function each(ar, fn) { <add> every(ar, function(el) { <add> return !fn(el) <add> }) <add> } <add> <add> if (!doc[readyState] && doc[addEventListener]) { <add> doc[addEventListener](domContentLoaded, function fn() { <add> doc.removeEventListener(domContentLoaded, fn, f) <add> doc[readyState] = 'complete' <add> }, f) <add> doc[readyState] = 'loading' <add> } <add> <add> function $script(paths, idOrDone, optDone) { <add> paths = paths[push] ? paths : [paths] <add> var idOrDoneIsDone = idOrDone && idOrDone.call <add> , done = idOrDoneIsDone ? idOrDone : optDone <add> , id = idOrDoneIsDone ? paths.join('') : idOrDone <add> , queue = paths.length <add> function loopFn(item) { <add> return item.call ? item() : list[item] <add> } <add> function callback() { <add> if (!--queue) { <add> list[id] = 1 <add> done && done() <add> for (var dset in delay) { <add> every(dset.split('|'), loopFn) && !each(delay[dset], loopFn) && (delay[dset] = []) <add> } <add> } <add> } <add> setTimeout(function () { <add> each(paths, function (path) { <add> if (scripts[path]) { <add> id && (ids[id] = 1) <add> return scripts[path] == 2 && callback() <add> } <add> scripts[path] = 1 <add> id && (ids[id] = 1) <add> create(!validBase.test(path) && scriptpath ? scriptpath + path + '.js' : path, callback) <add> }) <add> }, 0) <add> return $script <add> } <add> <add> function create(path, fn) { <add> var el = doc.createElement('script') <add> , loaded = f <add> el.onload = el.onerror = el[onreadystatechange] = function () { <add> if ((el[readyState] && !(/^c|loade/.test(el[readyState]))) || loaded) return; <add> el.onload = el[onreadystatechange] = null <add> loaded = 1 <add> scripts[path] = 2 <add> fn() <add> } <add> el.async = 1 <add> el.src = path <add> head.insertBefore(el, head.firstChild) <add> } <add> <add> $script.get = create <add> <add> $script.order = function (scripts, id, done) { <add> (function callback(s) { <add> s = scripts.shift() <add> if (!scripts.length) $script(s, id, done) <add> else $script(s, callback) <add> }()) <add> } <add> <add> $script.path = function (p) { <add> scriptpath = p <add> } <add> $script.ready = function (deps, ready, req) { <add> deps = deps[push] ? deps : [deps] <add> var missing = []; <add> !each(deps, function (dep) { <add> list[dep] || missing[push](dep); <add> }) && every(deps, function (dep) {return list[dep]}) ? <add> ready() : !function (key) { <add> delay[key] = delay[key] || [] <add> delay[key][push](ready) <add> req && req(missing) <add> }(deps.join('|')) <add> return $script <add> } <add> return $script <add>}, this); <add> <ide> <ide> /** <ide> * @license AngularJS <ide> match, <ide> globalVars = {}, <ide> IGNORE = { <add> innerHeight: true, innerWidth: true, <ide> onkeyup: true, onkeydown: true, onresize: true, <ide> event: true, frames: true, external: true, <ide> sessionStorage: true, clipboardData: true, localStorage: true}; <ide> <ide> (function next() { <ide> if (index < scripts.length) { <del> var file = scripts[index++]; <add> var file = scripts[index++], <add> last = index == scripts.length, <add> name = last ? 'angular' : file; <ide> <del> $script(file.replace(/\.js$/, ''), function() { <add> $script(file.replace(/\.js$/, ''), name, function() { <ide> angularClobberTest(file); <ide> next(); <ide> });
1
PHP
PHP
remove initialize() call
8483f9d45605b793f46daf7c53410431c3d9efe5
<ide><path>lib/Cake/Test/TestCase/Controller/Component/SecurityComponentTest.php <ide> public function testConstructorSettingProperties() { <ide> 'requireGet' => array('index'), <ide> 'validatePost' => false, <ide> ); <del> $event = new Event('Controller.initialize'); <ide> $Security = new SecurityComponent($this->Controller->Components, $settings); <del> $this->Controller->Security->initialize($event, $this->Controller, $settings); <ide> $this->assertEquals($Security->requirePost, $settings['requirePost']); <ide> $this->assertEquals($Security->requireSecure, $settings['requireSecure']); <ide> $this->assertEquals($Security->requireGet, $settings['requireGet']);
1
Java
Java
replace relevant code with lambda
4b1478d830f3cdbc4eb0d50d84f152d7900f30c3
<ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/DeclareParentsAdvisor.java <ide> private DeclareParentsAdvisor(Class<?> interfaceType, String typePattern, Class< <ide> ClassFilter typePatternFilter = new TypePatternClassFilter(typePattern); <ide> <ide> // Excludes methods implemented. <del> ClassFilter exclusion = new ClassFilter() { <del> @Override <del> public boolean matches(Class<?> clazz) { <del> return !(introducedInterface.isAssignableFrom(clazz)); <del> } <del> }; <add> ClassFilter exclusion = clazz -> !(introducedInterface.isAssignableFrom(clazz)); <ide> <ide> this.typePatternClassFilter = ClassFilters.intersection(typePatternFilter, exclusion); <ide> this.advice = advice; <ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java <ide> public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto <ide> Comparator<Method> adviceKindComparator = new ConvertingComparator<>( <ide> new InstanceComparator<>( <ide> Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class), <del> new Converter<Method, Annotation>() { <del> @Override <del> public Annotation convert(Method method) { <del> AspectJAnnotation<?> annotation = <del> AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(method); <del> return (annotation != null ? annotation.getAnnotation() : null); <del> } <del> }); <del> Comparator<Method> methodNameComparator = new ConvertingComparator<>( <del> new Converter<Method, String>() { <del> @Override <del> public String convert(Method method) { <del> return method.getName(); <del> } <add> (Converter<Method, Annotation>) method -> { <add> AspectJAnnotation<?> annotation = <add> AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(method); <add> return (annotation != null ? annotation.getAnnotation() : null); <ide> }); <add> Comparator<Method> methodNameComparator = new ConvertingComparator<>(Method::getName); <ide> METHOD_COMPARATOR = adviceKindComparator.thenComparing(methodNameComparator); <ide> } <ide> <ide> public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstan <ide> <ide> private List<Method> getAdvisorMethods(Class<?> aspectClass) { <ide> final List<Method> methods = new LinkedList<>(); <del> ReflectionUtils.doWithMethods(aspectClass, new ReflectionUtils.MethodCallback() { <del> @Override <del> public void doWith(Method method) throws IllegalArgumentException { <del> // Exclude pointcuts <del> if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) { <del> methods.add(method); <del> } <add> ReflectionUtils.doWithMethods(aspectClass, method -> { <add> // Exclude pointcuts <add> if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) { <add> methods.add(method); <ide> } <ide> }); <ide> Collections.sort(methods, METHOD_COMPARATOR); <ide><path>spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java <ide> protected Executor getDefaultExecutor(@Nullable BeanFactory beanFactory) { <ide> @Nullable <ide> protected Object doSubmit(Callable<Object> task, AsyncTaskExecutor executor, Class<?> returnType) { <ide> if (CompletableFuture.class.isAssignableFrom(returnType)) { <del> return CompletableFuture.supplyAsync(new Supplier<Object>() { <del> @Override <del> public Object get() { <del> try { <del> return task.call(); <del> } <del> catch (Throwable ex) { <del> throw new CompletionException(ex); <del> } <add> return CompletableFuture.supplyAsync(() -> { <add> try { <add> return task.call(); <add> } <add> catch (Throwable ex) { <add> throw new CompletionException(ex); <ide> } <ide> }, executor); <ide> } <ide><path>spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java <ide> public Object invoke(final MethodInvocation invocation) throws Throwable { <ide> "No executor specified and no default executor set on AsyncExecutionInterceptor either"); <ide> } <ide> <del> Callable<Object> task = new Callable<Object>() { <del> @Override <del> public Object call() throws Exception { <del> try { <del> Object result = invocation.proceed(); <del> if (result instanceof Future) { <del> return ((Future<?>) result).get(); <del> } <add> Callable<Object> task = () -> { <add> try { <add> Object result = invocation.proceed(); <add> if (result instanceof Future) { <add> return ((Future<?>) result).get(); <ide> } <del> catch (ExecutionException ex) { <del> handleError(ex.getCause(), userDeclaredMethod, invocation.getArguments()); <del> } <del> catch (Throwable ex) { <del> handleError(ex, userDeclaredMethod, invocation.getArguments()); <del> } <del> return null; <ide> } <add> catch (ExecutionException ex) { <add> handleError(ex.getCause(), userDeclaredMethod, invocation.getArguments()); <add> } <add> catch (Throwable ex) { <add> handleError(ex, userDeclaredMethod, invocation.getArguments()); <add> } <add> return null; <ide> }; <ide> <ide> return doSubmit(task, executor, invocation.getMethod().getReturnType()); <ide><path>spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java <ide> private List<Method> findCandidateWriteMethods(MethodDescriptor[] methodDescript <ide> // Sort non-void returning write methods to guard against the ill effects of <ide> // non-deterministic sorting of methods returned from Class#getDeclaredMethods <ide> // under JDK 7. See http://bugs.sun.com/view_bug.do?bug_id=7023180 <del> Collections.sort(matches, new Comparator<Method>() { <del> @Override <del> public int compare(Method m1, Method m2) { <del> return m2.toString().compareTo(m1.toString()); <del> } <del> }); <add> Collections.sort(matches, (m1, m2) -> m2.toString().compareTo(m1.toString())); <ide> return matches; <ide> } <ide> <ide><path>spring-beans/src/main/java/org/springframework/beans/PropertyMatches.java <ide> public FieldPropertyMatches(String propertyName, Class<?> beanClass, int maxDist <ide> <ide> private static String[] calculateMatches(final String propertyName, Class<?> beanClass, final int maxDistance) { <ide> final List<String> candidates = new ArrayList<>(); <del> ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() { <del> @Override <del> public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { <del> String possibleAlternative = field.getName(); <del> if (calculateStringDistance(propertyName, possibleAlternative) <= maxDistance) { <del> candidates.add(possibleAlternative); <del> } <add> ReflectionUtils.doWithFields(beanClass, field -> { <add> String possibleAlternative = field.getName(); <add> if (calculateStringDistance(propertyName, possibleAlternative) <= maxDistance) { <add> candidates.add(possibleAlternative); <ide> } <ide> }); <ide> Collections.sort(candidates); <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java <ide> public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final <ide> // Let's check for lookup methods here.. <ide> if (!this.lookupMethodsChecked.contains(beanName)) { <ide> try { <del> ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() { <del> @Override <del> public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { <del> Lookup lookup = method.getAnnotation(Lookup.class); <del> if (lookup != null) { <del> LookupOverride override = new LookupOverride(method, lookup.value()); <del> try { <del> RootBeanDefinition mbd = (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName); <del> mbd.getMethodOverrides().addOverride(override); <del> } <del> catch (NoSuchBeanDefinitionException ex) { <del> throw new BeanCreationException(beanName, <del> "Cannot apply @Lookup to beans without corresponding bean definition"); <del> } <add> ReflectionUtils.doWithMethods(beanClass, method -> { <add> Lookup lookup = method.getAnnotation(Lookup.class); <add> if (lookup != null) { <add> LookupOverride override = new LookupOverride(method, lookup.value()); <add> try { <add> RootBeanDefinition mbd = (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName); <add> mbd.getMethodOverrides().addOverride(override); <add> } <add> catch (NoSuchBeanDefinitionException ex) { <add> throw new BeanCreationException(beanName, <add> "Cannot apply @Lookup to beans without corresponding bean definition"); <ide> } <ide> } <ide> }); <ide> private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) { <ide> do { <ide> final LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<>(); <ide> <del> ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() { <del> @Override <del> public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { <del> AnnotationAttributes ann = findAutowiredAnnotation(field); <del> if (ann != null) { <del> if (Modifier.isStatic(field.getModifiers())) { <del> if (logger.isWarnEnabled()) { <del> logger.warn("Autowired annotation is not supported on static fields: " + field); <del> } <del> return; <del> } <del> boolean required = determineRequiredStatus(ann); <del> currElements.add(new AutowiredFieldElement(field, required)); <del> } <del> } <del> }); <del> <del> ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() { <del> @Override <del> public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { <del> Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); <del> if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { <del> return; <del> } <del> AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod); <del> if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { <del> if (Modifier.isStatic(method.getModifiers())) { <del> if (logger.isWarnEnabled()) { <del> logger.warn("Autowired annotation is not supported on static methods: " + method); <del> } <del> return; <del> } <del> if (method.getParameterCount() == 0) { <del> if (logger.isWarnEnabled()) { <del> logger.warn("Autowired annotation should only be used on methods with parameters: " + <del> method); <del> } <del> } <del> boolean required = determineRequiredStatus(ann); <del> PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); <del> currElements.add(new AutowiredMethodElement(method, required, pd)); <del> } <del> } <del> }); <add> ReflectionUtils.doWithLocalFields(targetClass, field -> { <add> AnnotationAttributes ann = findAutowiredAnnotation(field); <add> if (ann != null) { <add> if (Modifier.isStatic(field.getModifiers())) { <add> if (logger.isWarnEnabled()) { <add> logger.warn("Autowired annotation is not supported on static fields: " + field); <add> } <add> return; <add> } <add> boolean required = determineRequiredStatus(ann); <add> currElements.add(new AutowiredFieldElement(field, required)); <add> } <add> }); <add> <add> ReflectionUtils.doWithLocalMethods(targetClass, method -> { <add> Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); <add> if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { <add> return; <add> } <add> AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod); <add> if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { <add> if (Modifier.isStatic(method.getModifiers())) { <add> if (logger.isWarnEnabled()) { <add> logger.warn("Autowired annotation is not supported on static methods: " + method); <add> } <add> return; <add> } <add> if (method.getParameterCount() == 0) { <add> if (logger.isWarnEnabled()) { <add> logger.warn("Autowired annotation should only be used on methods with parameters: " + <add> method); <add> } <add> } <add> boolean required = determineRequiredStatus(ann); <add> PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); <add> currElements.add(new AutowiredMethodElement(method, required, pd)); <add> } <add> }); <ide> <ide> elements.addAll(0, currElements); <ide> targetClass = targetClass.getSuperclass(); <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java <ide> private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) { <ide> final LinkedList<LifecycleElement> currInitMethods = new LinkedList<>(); <ide> final LinkedList<LifecycleElement> currDestroyMethods = new LinkedList<>(); <ide> <del> ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() { <del> @Override <del> public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { <del> if (initAnnotationType != null) { <del> if (method.getAnnotation(initAnnotationType) != null) { <del> LifecycleElement element = new LifecycleElement(method); <del> currInitMethods.add(element); <del> if (debug) { <del> logger.debug("Found init method on class [" + clazz.getName() + "]: " + method); <del> } <add> ReflectionUtils.doWithLocalMethods(targetClass, method -> { <add> if (initAnnotationType != null) { <add> if (method.getAnnotation(initAnnotationType) != null) { <add> LifecycleElement element = new LifecycleElement(method); <add> currInitMethods.add(element); <add> if (debug) { <add> logger.debug("Found init method on class [" + clazz.getName() + "]: " + method); <ide> } <ide> } <del> if (destroyAnnotationType != null) { <del> if (method.getAnnotation(destroyAnnotationType) != null) { <del> currDestroyMethods.add(new LifecycleElement(method)); <del> if (debug) { <del> logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method); <del> } <add> } <add> if (destroyAnnotationType != null) { <add> if (method.getAnnotation(destroyAnnotationType) != null) { <add> currDestroyMethods.add(new LifecycleElement(method)); <add> if (debug) { <add> logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method); <ide> } <ide> } <ide> } <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java <ide> class Holder { Class<?> value = null; } <ide> <ide> // Find the given factory method, taking into account that in the case of <ide> // @Bean methods, there may be parameters present. <del> ReflectionUtils.doWithMethods(fbClass, <del> new ReflectionUtils.MethodCallback() { <del> @Override <del> public void doWith(Method method) { <del> if (method.getName().equals(factoryMethodName) && <del> FactoryBean.class.isAssignableFrom(method.getReturnType())) { <del> Class<?> currentType = GenericTypeResolver.resolveReturnTypeArgument( <del> method, FactoryBean.class); <del> if (currentType != null) { <del> objectType.value = ClassUtils.determineCommonAncestor(currentType, objectType.value); <del> } <del> } <del> } <del> }); <add> ReflectionUtils.doWithMethods(fbClass, method -> { <add> if (method.getName().equals(factoryMethodName) && <add> FactoryBean.class.isAssignableFrom(method.getReturnType())) { <add> Class<?> currentType = GenericTypeResolver.resolveReturnTypeArgument(method, FactoryBean.class); <add> if (currentType != null) { <add> objectType.value = ClassUtils.determineCommonAncestor(currentType, objectType.value); <add> } <add> } <add> }); <ide> <ide> return (objectType.value != null && Object.class != objectType.value ? objectType.value : null); <ide> } <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/JCacheInterceptor.java <ide> public class JCacheInterceptor extends JCacheAspectSupport implements MethodInte <ide> public Object invoke(final MethodInvocation invocation) throws Throwable { <ide> Method method = invocation.getMethod(); <ide> <del> CacheOperationInvoker aopAllianceInvoker = new CacheOperationInvoker() { <del> @Override <del> public Object invoke() { <del> try { <del> return invocation.proceed(); <del> } <del> catch (Throwable ex) { <del> throw new ThrowableWrapper(ex); <del> } <add> CacheOperationInvoker aopAllianceInvoker = () -> { <add> try { <add> return invocation.proceed(); <add> } <add> catch (Throwable ex) { <add> throw new CacheOperationInvoker.ThrowableWrapper(ex); <ide> } <ide> }; <ide> <ide><path>spring-context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java <ide> public AnnotationCacheOperationSource(Set<CacheAnnotationParser> annotationParse <ide> <ide> @Override <ide> protected Collection<CacheOperation> findCacheOperations(final Class<?> clazz) { <del> return determineCacheOperations(new CacheOperationProvider() { <del> @Override <del> public Collection<CacheOperation> getCacheOperations(CacheAnnotationParser parser) { <del> return parser.parseCacheAnnotations(clazz); <del> } <del> }); <del> <add> return determineCacheOperations(parser -> parser.parseCacheAnnotations(clazz)); <ide> } <ide> <ide> @Override <ide> protected Collection<CacheOperation> findCacheOperations(final Method method) { <del> return determineCacheOperations(new CacheOperationProvider() { <del> @Override <del> public Collection<CacheOperation> getCacheOperations(CacheAnnotationParser parser) { <del> return parser.parseCacheAnnotations(method); <del> } <del> }); <add> return determineCacheOperations(parser -> parser.parseCacheAnnotations(method)); <ide> } <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheInterceptor.java <ide> public class CacheInterceptor extends CacheAspectSupport implements MethodInterc <ide> public Object invoke(final MethodInvocation invocation) throws Throwable { <ide> Method method = invocation.getMethod(); <ide> <del> CacheOperationInvoker aopAllianceInvoker = new CacheOperationInvoker() { <del> @Override <del> public Object invoke() { <del> try { <del> return invocation.proceed(); <del> } <del> catch (Throwable ex) { <del> throw new ThrowableWrapper(ex); <del> } <add> CacheOperationInvoker aopAllianceInvoker = () -> { <add> try { <add> return invocation.proceed(); <add> } <add> catch (Throwable ex) { <add> throw new CacheOperationInvoker.ThrowableWrapper(ex); <ide> } <ide> }; <ide> <ide><path>spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java <ide> private InjectionMetadata buildResourceMetadata(final Class<?> clazz) { <ide> final LinkedList<InjectionMetadata.InjectedElement> currElements = <ide> new LinkedList<>(); <ide> <del> ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() { <del> @Override <del> public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { <del> if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) { <del> if (Modifier.isStatic(field.getModifiers())) { <del> throw new IllegalStateException("@WebServiceRef annotation is not supported on static fields"); <del> } <del> currElements.add(new WebServiceRefElement(field, field, null)); <add> ReflectionUtils.doWithLocalFields(targetClass, field -> { <add> if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) { <add> if (Modifier.isStatic(field.getModifiers())) { <add> throw new IllegalStateException("@WebServiceRef annotation is not supported on static fields"); <ide> } <del> else if (ejbRefClass != null && field.isAnnotationPresent(ejbRefClass)) { <del> if (Modifier.isStatic(field.getModifiers())) { <del> throw new IllegalStateException("@EJB annotation is not supported on static fields"); <del> } <del> currElements.add(new EjbRefElement(field, field, null)); <add> currElements.add(new WebServiceRefElement(field, field, null)); <add> } <add> else if (ejbRefClass != null && field.isAnnotationPresent(ejbRefClass)) { <add> if (Modifier.isStatic(field.getModifiers())) { <add> throw new IllegalStateException("@EJB annotation is not supported on static fields"); <ide> } <del> else if (field.isAnnotationPresent(Resource.class)) { <del> if (Modifier.isStatic(field.getModifiers())) { <del> throw new IllegalStateException("@Resource annotation is not supported on static fields"); <del> } <del> if (!ignoredResourceTypes.contains(field.getType().getName())) { <del> currElements.add(new ResourceElement(field, field, null)); <del> } <add> currElements.add(new EjbRefElement(field, field, null)); <add> } <add> else if (field.isAnnotationPresent(Resource.class)) { <add> if (Modifier.isStatic(field.getModifiers())) { <add> throw new IllegalStateException("@Resource annotation is not supported on static fields"); <add> } <add> if (!ignoredResourceTypes.contains(field.getType().getName())) { <add> currElements.add(new ResourceElement(field, field, null)); <ide> } <ide> } <ide> }); <ide> <del> ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() { <del> @Override <del> public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { <del> Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); <del> if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { <del> return; <add> ReflectionUtils.doWithLocalMethods(targetClass, method -> { <add> Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); <add> if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { <add> return; <add> } <add> if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { <add> if (webServiceRefClass != null && bridgedMethod.isAnnotationPresent(webServiceRefClass)) { <add> if (Modifier.isStatic(method.getModifiers())) { <add> throw new IllegalStateException("@WebServiceRef annotation is not supported on static methods"); <add> } <add> if (method.getParameterCount() != 1) { <add> throw new IllegalStateException("@WebServiceRef annotation requires a single-arg method: " + method); <add> } <add> PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); <add> currElements.add(new WebServiceRefElement(method, bridgedMethod, pd)); <ide> } <del> if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { <del> if (webServiceRefClass != null && bridgedMethod.isAnnotationPresent(webServiceRefClass)) { <del> if (Modifier.isStatic(method.getModifiers())) { <del> throw new IllegalStateException("@WebServiceRef annotation is not supported on static methods"); <del> } <del> if (method.getParameterCount() != 1) { <del> throw new IllegalStateException("@WebServiceRef annotation requires a single-arg method: " + method); <del> } <del> PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); <del> currElements.add(new WebServiceRefElement(method, bridgedMethod, pd)); <add> else if (ejbRefClass != null && bridgedMethod.isAnnotationPresent(ejbRefClass)) { <add> if (Modifier.isStatic(method.getModifiers())) { <add> throw new IllegalStateException("@EJB annotation is not supported on static methods"); <ide> } <del> else if (ejbRefClass != null && bridgedMethod.isAnnotationPresent(ejbRefClass)) { <del> if (Modifier.isStatic(method.getModifiers())) { <del> throw new IllegalStateException("@EJB annotation is not supported on static methods"); <del> } <del> if (method.getParameterCount() != 1) { <del> throw new IllegalStateException("@EJB annotation requires a single-arg method: " + method); <del> } <del> PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); <del> currElements.add(new EjbRefElement(method, bridgedMethod, pd)); <add> if (method.getParameterCount() != 1) { <add> throw new IllegalStateException("@EJB annotation requires a single-arg method: " + method); <ide> } <del> else if (bridgedMethod.isAnnotationPresent(Resource.class)) { <del> if (Modifier.isStatic(method.getModifiers())) { <del> throw new IllegalStateException("@Resource annotation is not supported on static methods"); <del> } <del> Class<?>[] paramTypes = method.getParameterTypes(); <del> if (paramTypes.length != 1) { <del> throw new IllegalStateException("@Resource annotation requires a single-arg method: " + method); <del> } <del> if (!ignoredResourceTypes.contains(paramTypes[0].getName())) { <del> PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); <del> currElements.add(new ResourceElement(method, bridgedMethod, pd)); <del> } <add> PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); <add> currElements.add(new EjbRefElement(method, bridgedMethod, pd)); <add> } <add> else if (bridgedMethod.isAnnotationPresent(Resource.class)) { <add> if (Modifier.isStatic(method.getModifiers())) { <add> throw new IllegalStateException("@Resource annotation is not supported on static methods"); <add> } <add> Class<?>[] paramTypes = method.getParameterTypes(); <add> if (paramTypes.length != 1) { <add> throw new IllegalStateException("@Resource annotation requires a single-arg method: " + method); <add> } <add> if (!ignoredResourceTypes.contains(paramTypes[0].getName())) { <add> PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); <add> currElements.add(new ResourceElement(method, bridgedMethod, pd)); <ide> } <ide> } <ide> } <ide><path>spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java <ide> else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this. <ide> } <ide> <ide> // Sort by previously determined @Order value, if applicable <del> Collections.sort(configCandidates, new Comparator<BeanDefinitionHolder>() { <del> @Override <del> public int compare(BeanDefinitionHolder bd1, BeanDefinitionHolder bd2) { <del> int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition()); <del> int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition()); <del> return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0; <del> } <add> Collections.sort(configCandidates, (bd1, bd2) -> { <add> int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition()); <add> int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition()); <add> return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0; <ide> }); <ide> <ide> // Detect any custom bean name generation strategy supplied through the enclosing application context <ide><path>spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java <ide> private void doStop(Map<String, ? extends Lifecycle> lifecycleBeans, final Strin <ide> logger.debug("Asking bean '" + beanName + "' of type [" + bean.getClass() + "] to stop"); <ide> } <ide> countDownBeanNames.add(beanName); <del> ((SmartLifecycle) bean).stop(new Runnable() { <del> @Override <del> public void run() { <del> latch.countDown(); <del> countDownBeanNames.remove(beanName); <del> if (logger.isDebugEnabled()) { <del> logger.debug("Bean '" + beanName + "' completed its stop procedure"); <del> } <add> ((SmartLifecycle) bean).stop(() -> { <add> latch.countDown(); <add> countDownBeanNames.remove(beanName); <add> if (logger.isDebugEnabled()) { <add> logger.debug("Bean '" + beanName + "' completed its stop procedure"); <ide> } <ide> }); <ide> } <ide><path>spring-context/src/main/java/org/springframework/jmx/export/MBeanExporter.java <ide> private ModelMBeanInfo getMBeanInfo(Object managedBean, String beanKey) throws J <ide> * certain internal classes from being registered automatically. <ide> */ <ide> private void autodetectBeans(final AutodetectCapableMBeanInfoAssembler assembler) { <del> autodetect(new AutodetectCallback() { <del> @Override <del> public boolean include(Class<?> beanClass, String beanName) { <del> return assembler.includeBean(beanClass, beanName); <del> } <del> }); <add> autodetect((beanClass, beanName) -> assembler.includeBean(beanClass, beanName)); <ide> } <ide> <ide> /** <ide> * Attempts to detect any beans defined in the {@code ApplicationContext} that are <ide> * valid MBeans and registers them automatically with the {@code MBeanServer}. <ide> */ <ide> private void autodetectMBeans() { <del> autodetect(new AutodetectCallback() { <del> @Override <del> public boolean include(Class<?> beanClass, String beanName) { <del> return isMBean(beanClass); <del> } <del> }); <add> autodetect((beanClass, beanName) -> isMBean(beanClass)); <ide> } <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/core/convert/converter/ConvertingComparator.java <ide> public int compare(S o1, S o2) { <ide> * @return a new {@link ConvertingComparator} instance <ide> */ <ide> public static <K, V> ConvertingComparator<Map.Entry<K, V>, K> mapEntryKeys(Comparator<K> comparator) { <del> return new ConvertingComparator<>(comparator, new Converter<Map.Entry<K, V>, K>() { <del> @Override <del> public K convert(Map.Entry<K, V> source) { <del> return source.getKey(); <del> } <del> }); <add> return new ConvertingComparator<>(comparator, source -> source.getKey()); <ide> } <ide> <ide> /** <ide> public K convert(Map.Entry<K, V> source) { <ide> * @return a new {@link ConvertingComparator} instance <ide> */ <ide> public static <K, V> ConvertingComparator<Map.Entry<K, V>, V> mapEntryValues(Comparator<V> comparator) { <del> return new ConvertingComparator<>(comparator, new Converter<Map.Entry<K, V>, V>() { <del> @Override <del> public V convert(Map.Entry<K, V> source) { <del> return source.getValue(); <del> } <del> }); <add> return new ConvertingComparator<>(comparator, source -> source.getValue()); <ide> } <ide> <ide> <ide><path>spring-core/src/main/java/org/springframework/core/env/AbstractPropertyResolver.java <ide> private PropertyPlaceholderHelper createPlaceholderHelper(boolean ignoreUnresolv <ide> } <ide> <ide> private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) { <del> return helper.replacePlaceholders(text, new PropertyPlaceholderHelper.PlaceholderResolver() { <del> @Override <del> public String resolvePlaceholder(String placeholderName) { <del> return getPropertyAsRawString(placeholderName); <del> } <del> }); <add> return helper.replacePlaceholders(text, placeholderName -> getPropertyAsRawString(placeholderName)); <ide> } <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.java <ide> public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuf <ide> */ <ide> public String replacePlaceholders(String value, final Properties properties) { <ide> Assert.notNull(properties, "'properties' must not be null"); <del> return replacePlaceholders(value, new PlaceholderResolver() { <del> @Override <del> public String resolvePlaceholder(String placeholderName) { <del> return properties.getProperty(placeholderName); <del> } <del> }); <add> return replacePlaceholders(value, placeholderName -> properties.getProperty(placeholderName)); <ide> } <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/ReflectionUtils.java <ide> */ <ide> public abstract class ReflectionUtils { <ide> <add> /** <add> * Pre-built FieldFilter that matches all non-static, non-final fields. <add> */ <add> public static final FieldFilter COPYABLE_FIELDS = <add> field -> !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())); <add> <ide> /** <ide> * Naming prefix for CGLIB-renamed methods. <ide> * @see #isCglibRenamedMethod <ide> public interface FieldFilter { <ide> } <ide> <ide> <del> /** <del> * Pre-built FieldFilter that matches all non-static, non-final fields. <del> */ <del> public static final FieldFilter COPYABLE_FIELDS = new FieldFilter() { <del> <del> @Override <del> public boolean matches(Field field) { <del> return !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())); <del> } <del> }; <del> <del> <ide> /** <ide> * Pre-built MethodFilter that matches all non-bridge methods. <ide> */ <ide><path>spring-core/src/main/java/org/springframework/util/concurrent/CompletableToListenableFutureAdapter.java <ide> public CompletableToListenableFutureAdapter(CompletionStage<T> completionStage) <ide> */ <ide> public CompletableToListenableFutureAdapter(CompletableFuture<T> completableFuture) { <ide> this.completableFuture = completableFuture; <del> this.completableFuture.handle(new BiFunction<T, Throwable, Object>() { <del> @Override <del> @Nullable <del> public Object apply(T result, @Nullable Throwable ex) { <del> if (ex != null) { <del> callbacks.failure(ex); <del> } <del> else { <del> callbacks.success(result); <del> } <del> return null; <add> this.completableFuture.handle((result, exception) -> { <add> if (exception != null) { <add> callbacks.failure(exception); <ide> } <add> else { <add> callbacks.success(result); <add> } <add> return null; <ide> }); <ide> } <ide> <ide><path>spring-core/src/main/java/org/springframework/util/concurrent/SettableListenableFuture.java <ide> */ <ide> public class SettableListenableFuture<T> implements ListenableFuture<T> { <ide> <del> private static final Callable<Object> DUMMY_CALLABLE = new Callable<Object>() { <del> @Override <del> public Object call() throws Exception { <del> throw new IllegalStateException("Should never be called"); <del> } <add> private static final Callable<Object> DUMMY_CALLABLE = () -> { <add> throw new IllegalStateException("Should never be called"); <ide> }; <ide> <ide> <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/InlineList.java <ide> public void generateCode(MethodVisitor mv, CodeFlow codeflow) { <ide> final String constantFieldName = "inlineList$" + codeflow.nextFieldId(); <ide> final String className = codeflow.getClassName(); <ide> <del> codeflow.registerNewField(new CodeFlow.FieldAdder() { <del> public void generateField(ClassWriter cw, CodeFlow codeflow) { <del> cw.visitField(ACC_PRIVATE|ACC_STATIC|ACC_FINAL, constantFieldName, "Ljava/util/List;", null, null); <del> } <del> }); <add> codeflow.registerNewField((cw, codeflow1) <add> -> cw.visitField(ACC_PRIVATE|ACC_STATIC|ACC_FINAL, constantFieldName, "Ljava/util/List;", null, null)); <ide> <del> codeflow.registerNewClinit(new CodeFlow.ClinitAdder() { <del> public void generateCode(MethodVisitor mv, CodeFlow codeflow) { <del> generateClinitCode(className, constantFieldName, mv, codeflow, false); <del> } <del> }); <add> codeflow.registerNewClinit((mv1, codeflow12) -> generateClinitCode(className, constantFieldName, mv1, codeflow12, false)); <ide> <ide> mv.visitFieldInsn(GETSTATIC, className, constantFieldName, "Ljava/util/List;"); <ide> codeflow.pushDescriptor("Ljava/util/List"); <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodResolver.java <ide> public MethodExecutor resolve(EvaluationContext context, Object targetObject, St <ide> <ide> // Sort methods into a sensible order <ide> if (methods.size() > 1) { <del> Collections.sort(methods, new Comparator<Method>() { <del> @Override <del> public int compare(Method m1, Method m2) { <del> int m1pl = m1.getParameterCount(); <del> int m2pl = m2.getParameterCount(); <del> // varargs methods go last <del> if (m1pl == m2pl) { <del> if (!m1.isVarArgs() && m2.isVarArgs()) { <del> return -1; <del> } <del> else if (m1.isVarArgs() && !m2.isVarArgs()) { <del> return 1; <del> } <del> else { <del> return 0; <del> } <add> Collections.sort(methods, (m1, m2) -> { <add> int m1pl = m1.getParameterCount(); <add> int m2pl = m2.getParameterCount(); <add> // varargs methods go last <add> if (m1pl == m2pl) { <add> if (!m1.isVarArgs() && m2.isVarArgs()) { <add> return -1; <add> } <add> else if (m1.isVarArgs() && !m2.isVarArgs()) { <add> return 1; <add> } <add> else { <add> return 0; <ide> } <del> return (m1pl < m2pl ? -1 : (m1pl > m2pl ? 1 : 0)); <ide> } <add> return (m1pl < m2pl ? -1 : (m1pl > m2pl ? 1 : 0)); <ide> }); <ide> } <ide> <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java <ide> private Method findMethodForProperty(String[] methodSuffixes, String prefix, Cla <ide> */ <ide> private Method[] getSortedClassMethods(Class<?> clazz) { <ide> Method[] methods = clazz.getMethods(); <del> Arrays.sort(methods, new Comparator<Method>() { <del> @Override <del> public int compare(Method o1, Method o2) { <del> return (o1.isBridge() == o2.isBridge()) ? 0 : (o1.isBridge() ? 1 : -1); <del> } <del> }); <add> Arrays.sort(methods, (o1, o2) -> (o1.isBridge() == o2.isBridge()) ? 0 : (o1.isBridge() ? 1 : -1)); <ide> return methods; <ide> } <ide> <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/config/SortedResourcesFactoryBean.java <ide> protected Resource[] createInstance() throws Exception { <ide> for (String location : this.locations) { <ide> List<Resource> resources = new ArrayList<>( <ide> Arrays.asList(this.resourcePatternResolver.getResources(location))); <del> Collections.sort(resources, new Comparator<Resource>() { <del> @Override <del> public int compare(Resource r1, Resource r2) { <del> try { <del> return r1.getURL().toString().compareTo(r2.getURL().toString()); <del> } <del> catch (IOException ex) { <del> return 0; <del> } <add> Collections.sort(resources, (r1, r2) -> { <add> try { <add> return r1.getURL().toString().compareTo(r2.getURL().toString()); <add> } <add> catch (IOException ex) { <add> return 0; <ide> } <ide> }); <ide> for (Resource resource : resources) { <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReader.java <ide> public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { <ide> public void loadBeanDefinitions(String sql) { <ide> Assert.notNull(this.jdbcTemplate, "Not fully configured - specify DataSource or JdbcTemplate"); <ide> final Properties props = new Properties(); <del> this.jdbcTemplate.query(sql, new RowCallbackHandler() { <del> @Override <del> public void processRow(ResultSet rs) throws SQLException { <del> String beanName = rs.getString(1); <del> String property = rs.getString(2); <del> String value = rs.getString(3); <del> // Make a properties entry by combining bean name and property. <del> props.setProperty(beanName + '.' + property, value); <del> } <add> this.jdbcTemplate.query(sql, resultSet -> { <add> String beanName = resultSet.getString(1); <add> String property = resultSet.getString(2); <add> String value = resultSet.getString(3); <add> // Make a properties entry by combining bean name and property. <add> props.setProperty(beanName + '.' + property, value); <ide> }); <ide> this.propReader.registerBeanDefinitions(props); <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandler.java <ide> protected SimpMessageMappingInfo getMatchingMapping(SimpMessageMappingInfo mappi <ide> <ide> @Override <ide> protected Comparator<SimpMessageMappingInfo> getMappingComparator(final Message<?> message) { <del> return new Comparator<SimpMessageMappingInfo>() { <del> @Override <del> public int compare(SimpMessageMappingInfo info1, SimpMessageMappingInfo info2) { <del> return info1.compareTo(info2, message); <del> } <del> }; <add> return (info1, info2) -> info1.compareTo(info2, message); <ide> } <ide> <ide> @Override <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/DefaultStompSession.java <ide> private void initReceiptHandling() { <ide> Assert.notNull(getTaskScheduler(), "To track receipts, a TaskScheduler must be configured"); <ide> DefaultStompSession.this.receiptHandlers.put(this.receiptId, this); <ide> Date startTime = new Date(System.currentTimeMillis() + getReceiptTimeLimit()); <del> this.future = getTaskScheduler().schedule(new Runnable() { <del> @Override <del> public void run() { <del> handleReceiptNotReceived(); <del> } <del> }, startTime); <add> this.future = getTaskScheduler().schedule(this::handleReceiptNotReceived, startTime); <ide> } <ide> <ide> @Override <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java <ide> public void afterConnected(TcpConnection<byte[]> connection) { <ide> logger.debug("TCP connection opened in session=" + getSessionId()); <ide> } <ide> this.tcpConnection = connection; <del> this.tcpConnection.onReadInactivity(new Runnable() { <del> @Override <del> public void run() { <del> if (tcpConnection != null && !isStompConnected) { <del> handleTcpConnectionFailure("No CONNECTED frame received in " + <del> MAX_TIME_TO_CONNECTED_FRAME + " ms.", null); <del> } <add> this.tcpConnection.onReadInactivity(() -> { <add> if (tcpConnection != null && !isStompConnected) { <add> handleTcpConnectionFailure("No CONNECTED frame received in " + <add> MAX_TIME_TO_CONNECTED_FRAME + " ms.", null); <ide> } <ide> }, MAX_TIME_TO_CONNECTED_FRAME); <ide> connection.send(MessageBuilder.createMessage(EMPTY_PAYLOAD, this.connectHeaders.getMessageHeaders())); <ide> private void initHeartbeats(StompHeaderAccessor connectedHeaders) { <ide> <ide> if (clientSendInterval > 0 && serverReceiveInterval > 0) { <ide> long interval = Math.max(clientSendInterval, serverReceiveInterval); <del> this.tcpConnection.onWriteInactivity(new Runnable() { <del> @Override <del> public void run() { <del> TcpConnection<byte[]> conn = tcpConnection; <del> if (conn != null) { <del> conn.send(HEARTBEAT_MESSAGE).addCallback( <del> new ListenableFutureCallback<Void>() { <del> public void onSuccess(Void result) { <del> } <del> public void onFailure(Throwable ex) { <del> handleTcpConnectionFailure( <del> "Failed to forward heartbeat: " + ex.getMessage(), ex); <del> } <del> }); <del> } <add> this.tcpConnection.onWriteInactivity(() -> { <add> TcpConnection<byte[]> conn = tcpConnection; <add> if (conn != null) { <add> conn.send(HEARTBEAT_MESSAGE).addCallback( <add> new ListenableFutureCallback<Void>() { <add> public void onSuccess(Void result) { <add> } <add> public void onFailure(Throwable ex) { <add> handleTcpConnectionFailure("Failed to forward heartbeat: " + ex.getMessage(), ex); <add> } <add> }); <ide> } <ide> }, interval); <ide> } <ide> if (clientReceiveInterval > 0 && serverSendInterval > 0) { <ide> final long interval = Math.max(clientReceiveInterval, serverSendInterval) * HEARTBEAT_MULTIPLIER; <del> this.tcpConnection.onReadInactivity(new Runnable() { <del> @Override <del> public void run() { <del> handleTcpConnectionFailure("No messages received in " + interval + " ms.", null); <del> } <del> }, interval); <add> this.tcpConnection.onReadInactivity(() <add> -> handleTcpConnectionFailure("No messages received in " + interval + " ms.", null), interval); <ide> } <ide> } <ide> <ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/LocalSessionFactoryBuilder.java <ide> private class BootstrapSessionFactoryInvocationHandler implements InvocationHand <ide> private final Future<SessionFactory> sessionFactoryFuture; <ide> <ide> public BootstrapSessionFactoryInvocationHandler(AsyncTaskExecutor bootstrapExecutor) { <del> this.sessionFactoryFuture = bootstrapExecutor.submit(new Callable<SessionFactory>() { <del> @Override <del> public SessionFactory call() throws Exception { <del> return buildSessionFactory(); <del> } <del> }); <add> this.sessionFactoryFuture = bootstrapExecutor.submit( <add> (Callable<SessionFactory>) LocalSessionFactoryBuilder.this::buildSessionFactory); <ide> } <ide> <ide> @Override <ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java <ide> public final void afterPropertiesSet() throws PersistenceException { <ide> } <ide> <ide> if (this.bootstrapExecutor != null) { <del> this.nativeEntityManagerFactoryFuture = this.bootstrapExecutor.submit(new Callable<EntityManagerFactory>() { <del> @Override <del> public EntityManagerFactory call() { <del> return buildNativeEntityManagerFactory(); <del> } <del> }); <add> this.nativeEntityManagerFactoryFuture = this.bootstrapExecutor.submit(this::buildNativeEntityManagerFactory); <ide> } <ide> else { <ide> this.nativeEntityManagerFactory = buildNativeEntityManagerFactory(); <ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.java <ide> private InjectionMetadata buildPersistenceMetadata(final Class<?> clazz) { <ide> final LinkedList<InjectionMetadata.InjectedElement> currElements = <ide> new LinkedList<>(); <ide> <del> ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() { <del> @Override <del> public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { <del> if (field.isAnnotationPresent(PersistenceContext.class) || <del> field.isAnnotationPresent(PersistenceUnit.class)) { <del> if (Modifier.isStatic(field.getModifiers())) { <del> throw new IllegalStateException("Persistence annotations are not supported on static fields"); <del> } <del> currElements.add(new PersistenceElement(field, field, null)); <add> ReflectionUtils.doWithLocalFields(targetClass, field -> { <add> if (field.isAnnotationPresent(PersistenceContext.class) || <add> field.isAnnotationPresent(PersistenceUnit.class)) { <add> if (Modifier.isStatic(field.getModifiers())) { <add> throw new IllegalStateException("Persistence annotations are not supported on static fields"); <ide> } <add> currElements.add(new PersistenceElement(field, field, null)); <ide> } <ide> }); <ide> <del> ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() { <del> @Override <del> public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { <del> Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); <del> if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { <del> return; <add> ReflectionUtils.doWithLocalMethods(targetClass, method -> { <add> Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); <add> if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { <add> return; <add> } <add> if ((bridgedMethod.isAnnotationPresent(PersistenceContext.class) || <add> bridgedMethod.isAnnotationPresent(PersistenceUnit.class)) && <add> method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { <add> if (Modifier.isStatic(method.getModifiers())) { <add> throw new IllegalStateException("Persistence annotations are not supported on static methods"); <ide> } <del> if ((bridgedMethod.isAnnotationPresent(PersistenceContext.class) || <del> bridgedMethod.isAnnotationPresent(PersistenceUnit.class)) && <del> method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { <del> if (Modifier.isStatic(method.getModifiers())) { <del> throw new IllegalStateException("Persistence annotations are not supported on static methods"); <del> } <del> if (method.getParameterCount() != 1) { <del> throw new IllegalStateException("Persistence annotation requires a single-arg method: " + method); <del> } <del> PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); <del> currElements.add(new PersistenceElement(method, bridgedMethod, pd)); <add> if (method.getParameterCount() != 1) { <add> throw new IllegalStateException("Persistence annotation requires a single-arg method: " + method); <ide> } <add> PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); <add> currElements.add(new PersistenceElement(method, bridgedMethod, pd)); <ide> } <ide> }); <ide> <ide><path>spring-test/src/main/java/org/springframework/test/web/client/match/ContentRequestMatchers.java <ide> public RequestMatcher contentType(String expectedContentType) { <ide> * Assert the request content type as a {@link MediaType}. <ide> */ <ide> public RequestMatcher contentType(final MediaType expectedContentType) { <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) throws IOException, AssertionError { <del> MediaType actualContentType = request.getHeaders().getContentType(); <del> assertTrue("Content type not set", actualContentType != null); <del> assertEquals("Content type", expectedContentType, actualContentType); <del> } <add> return request -> { <add> MediaType actualContentType = request.getHeaders().getContentType(); <add> assertTrue("Content type not set", actualContentType != null); <add> assertEquals("Content type", expectedContentType, actualContentType); <ide> }; <ide> } <ide> <ide> public RequestMatcher contentTypeCompatibleWith(String contentType) { <ide> * content type as defined by {@link MediaType#isCompatibleWith(MediaType)}. <ide> */ <ide> public RequestMatcher contentTypeCompatibleWith(final MediaType contentType) { <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) throws IOException, AssertionError { <del> MediaType actualContentType = request.getHeaders().getContentType(); <del> assertTrue("Content type not set", actualContentType != null); <del> if (actualContentType != null) { <del> assertTrue("Content type [" + actualContentType + "] is not compatible with [" + contentType + "]", <del> actualContentType.isCompatibleWith(contentType)); <del> } <add> return request -> { <add> MediaType actualContentType = request.getHeaders().getContentType(); <add> assertTrue("Content type not set", actualContentType != null); <add> if (actualContentType != null) { <add> assertTrue("Content type [" + actualContentType + "] is not compatible with [" + contentType + "]", <add> actualContentType.isCompatibleWith(contentType)); <ide> } <ide> }; <ide> } <ide> public void match(ClientHttpRequest request) throws IOException, AssertionError <ide> * Get the body of the request as a UTF-8 string and appply the given {@link Matcher}. <ide> */ <ide> public RequestMatcher string(final Matcher<? super String> matcher) { <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) throws IOException, AssertionError { <del> MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; <del> assertThat("Request content", mockRequest.getBodyAsString(), matcher); <del> } <add> return request -> { <add> MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; <add> assertThat("Request content", mockRequest.getBodyAsString(), matcher); <ide> }; <ide> } <ide> <ide> /** <ide> * Get the body of the request as a UTF-8 string and compare it to the given String. <ide> */ <ide> public RequestMatcher string(final String expectedContent) { <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) throws IOException, AssertionError { <del> MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; <del> assertEquals("Request content", expectedContent, mockRequest.getBodyAsString()); <del> } <add> return request -> { <add> MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; <add> assertEquals("Request content", expectedContent, mockRequest.getBodyAsString()); <ide> }; <ide> } <ide> <ide> /** <ide> * Compare the body of the request to the given byte array. <ide> */ <ide> public RequestMatcher bytes(final byte[] expectedContent) { <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) throws IOException, AssertionError { <del> MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; <del> assertEquals("Request content", expectedContent, mockRequest.getBodyAsBytes()); <del> } <add> return request -> { <add> MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; <add> assertEquals("Request content", expectedContent, mockRequest.getBodyAsBytes()); <ide> }; <ide> } <ide> <ide> public void match(ClientHttpRequest request) throws IOException, AssertionError <ide> * @since 4.3 <ide> */ <ide> public RequestMatcher formData(final MultiValueMap<String, String> expectedContent) { <del> return new RequestMatcher() { <del> @Override <del> public void match(final ClientHttpRequest request) throws IOException, AssertionError { <del> HttpInputMessage inputMessage = new HttpInputMessage() { <del> @Override <del> public InputStream getBody() throws IOException { <del> MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; <del> return new ByteArrayInputStream(mockRequest.getBodyAsBytes()); <del> } <del> @Override <del> public HttpHeaders getHeaders() { <del> return request.getHeaders(); <del> } <del> }; <del> FormHttpMessageConverter converter = new FormHttpMessageConverter(); <del> assertEquals("Request content", expectedContent, converter.read(null, inputMessage)); <del> } <add> return request -> { <add> HttpInputMessage inputMessage = new HttpInputMessage() { <add> @Override <add> public InputStream getBody() throws IOException { <add> MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; <add> return new ByteArrayInputStream(mockRequest.getBodyAsBytes()); <add> } <add> @Override <add> public HttpHeaders getHeaders() { <add> return request.getHeaders(); <add> } <add> }; <add> FormHttpMessageConverter converter = new FormHttpMessageConverter(); <add> assertEquals("Request content", expectedContent, converter.read(null, inputMessage)); <ide> }; <ide> } <ide> <ide><path>spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java <ide> <ide> package org.springframework.test.web.client.match; <ide> <del>import java.io.IOException; <ide> import java.net.URI; <ide> import java.util.List; <ide> import java.util.Map; <ide> public abstract class MockRestRequestMatchers { <ide> * Match to any request. <ide> */ <ide> public static RequestMatcher anything() { <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) throws AssertionError { <del> } <del> }; <add> return request -> {}; <ide> } <ide> <ide> /** <ide> public void match(ClientHttpRequest request) throws AssertionError { <ide> */ <ide> public static RequestMatcher method(final HttpMethod method) { <ide> Assert.notNull(method, "'method' must not be null"); <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) throws AssertionError { <del> AssertionErrors.assertEquals("Unexpected HttpMethod", method, request.getMethod()); <del> } <del> }; <add> return request -> assertEquals("Unexpected HttpMethod", method, request.getMethod()); <ide> } <ide> <ide> /** <ide> public void match(ClientHttpRequest request) throws AssertionError { <ide> */ <ide> public static RequestMatcher requestTo(final Matcher<String> matcher) { <ide> Assert.notNull(matcher, "'matcher' must not be null"); <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) throws IOException, AssertionError { <del> assertThat("Request URI", request.getURI().toString(), matcher); <del> } <del> }; <add> return request -> assertThat("Request URI", request.getURI().toString(), matcher); <ide> } <ide> <ide> /** <ide> public void match(ClientHttpRequest request) throws IOException, AssertionError <ide> */ <ide> public static RequestMatcher requestTo(final String expectedUri) { <ide> Assert.notNull(expectedUri, "'uri' must not be null"); <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) throws IOException, AssertionError { <del> assertEquals("Request URI", expectedUri, request.getURI().toString()); <del> } <del> }; <add> return request -> assertEquals("Request URI", expectedUri, request.getURI().toString()); <ide> } <ide> <ide> /** <ide> public void match(ClientHttpRequest request) throws IOException, AssertionError <ide> */ <ide> public static RequestMatcher requestTo(final URI uri) { <ide> Assert.notNull(uri, "'uri' must not be null"); <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) throws IOException, AssertionError { <del> AssertionErrors.assertEquals("Unexpected request", uri, request.getURI()); <del> } <del> }; <add> return request -> assertEquals("Unexpected request", uri, request.getURI()); <ide> } <ide> <ide> /** <ide> * Assert request query parameter values with the given Hamcrest matcher. <ide> */ <ide> @SafeVarargs <ide> public static RequestMatcher queryParam(final String name, final Matcher<? super String>... matchers) { <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) { <del> MultiValueMap<String, String> params = getQueryParams(request); <del> assertValueCount("query param", name, params, matchers.length); <del> for (int i = 0 ; i < matchers.length; i++) { <del> assertThat("Query param", params.get(name).get(i), matchers[i]); <del> } <add> return request -> { <add> MultiValueMap<String, String> params = getQueryParams(request); <add> assertValueCount("query param", name, params, matchers.length); <add> for (int i = 0 ; i < matchers.length; i++) { <add> assertThat("Query param", params.get(name).get(i), matchers[i]); <ide> } <ide> }; <ide> } <ide> public void match(ClientHttpRequest request) { <ide> * Assert request query parameter values. <ide> */ <ide> public static RequestMatcher queryParam(final String name, final String... expectedValues) { <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) { <del> MultiValueMap<String, String> params = getQueryParams(request); <del> assertValueCount("query param", name, params, expectedValues.length); <del> for (int i = 0 ; i < expectedValues.length; i++) { <del> assertEquals("Query param + [" + name + "]", expectedValues[i], params.get(name).get(i)); <del> } <add> return request -> { <add> MultiValueMap<String, String> params = getQueryParams(request); <add> assertValueCount("query param", name, params, expectedValues.length); <add> for (int i = 0 ; i < expectedValues.length; i++) { <add> assertEquals("Query param + [" + name + "]", expectedValues[i], params.get(name).get(i)); <ide> } <ide> }; <ide> } <ide> private static void assertValueCount(String valueType, final String name, <ide> */ <ide> @SafeVarargs <ide> public static RequestMatcher header(final String name, final Matcher<? super String>... matchers) { <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) { <add> return request-> { <ide> assertValueCount("header", name, request.getHeaders(), matchers.length); <ide> List<String> headerValues = request.getHeaders().get(name); <del> Assert.state(headerValues != null, "No header values"); <del> for (int i = 0; i < matchers.length; i++) { <del> assertThat("Request header [" + name + "]", headerValues.get(i), matchers[i]); <del> } <add> Assert.state(headerValues != null, "No header values");for (int i = 0 ; i < matchers.length; i++) { <add> assertThat("Request header["+name+ "]", headerValues.get(i), matchers[i]); <add> <ide> } <ide> }; <ide> } <ide> public void match(ClientHttpRequest request) { <ide> * Assert request header values. <ide> */ <ide> public static RequestMatcher header(final String name, final String... expectedValues) { <del> return new RequestMatcher() { <del> @Override <del> public void match(ClientHttpRequest request) { <add> return request-> { <ide> assertValueCount("header", name, request.getHeaders(), expectedValues.length); <ide> List<String> headerValues = request.getHeaders().get(name); <del> Assert.state(headerValues != null, "No header values"); <del> for (int i = 0 ; i < expectedValues.length; i++) { <del> assertEquals("Request header [" + name + "]", expectedValues[i], headerValues.get(i)); <del> } <add> Assert.state(headerValues != null, "No header values");for (int i = 0 ; i < expectedValues.length; i++) { <add> assertEquals("Request header [" + name + "]", <add> expectedValues[i], headerValues.get(i)); <add> <ide> } <ide> }; <ide> } <ide><path>spring-tx/src/main/java/org/springframework/jca/cci/core/CciTemplate.java <ide> public <T> T execute(ConnectionCallback<T> action) throws DataAccessException { <ide> @Override <ide> public <T> T execute(final InteractionCallback<T> action) throws DataAccessException { <ide> Assert.notNull(action, "Callback object must not be null"); <del> return execute(new ConnectionCallback<T>() { <del> @Override <del> public T doInConnection(Connection connection, ConnectionFactory connectionFactory) <del> throws ResourceException, SQLException, DataAccessException { <del> Interaction interaction = connection.createInteraction(); <del> try { <del> return action.doInInteraction(interaction, connectionFactory); <del> } <del> finally { <del> closeInteraction(interaction); <del> } <add> return execute((ConnectionCallback<T>) (connection, connectionFactory) -> { <add> Interaction interaction = connection.createInteraction(); <add> try { <add> return action.doInInteraction(interaction, connectionFactory); <add> } <add> finally { <add> closeInteraction(interaction); <ide> } <ide> }); <ide> } <ide><path>spring-tx/src/main/java/org/springframework/jca/context/ResourceAdapterApplicationContext.java <ide> protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactor <ide> beanFactory.registerResolvableDependency(BootstrapContext.class, this.bootstrapContext); <ide> <ide> // JCA WorkManager resolved lazily - may not be available. <del> beanFactory.registerResolvableDependency(WorkManager.class, new ObjectFactory<WorkManager>() { <del> @Override <del> public WorkManager getObject() { <del> return bootstrapContext.getWorkManager(); <del> } <del> }); <add> beanFactory.registerResolvableDependency(WorkManager.class, (ObjectFactory<WorkManager>) bootstrapContext::getWorkManager); <ide> } <ide> <ide> } <ide><path>spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java <ide> protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targe <ide> else { <ide> // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in. <ide> try { <del> Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr, <del> new TransactionCallback<Object>() { <del> @Override <del> public Object doInTransaction(TransactionStatus status) { <del> TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status); <del> try { <del> return invocation.proceedWithInvocation(); <del> } <del> catch (Throwable ex) { <del> if (txAttr.rollbackOn(ex)) { <del> // A RuntimeException: will lead to a rollback. <del> if (ex instanceof RuntimeException) { <del> throw (RuntimeException) ex; <del> } <del> else { <del> throw new ThrowableHolderException(ex); <del> } <del> } <del> else { <del> // A normal return value: will lead to a commit. <del> return new ThrowableHolder(ex); <del> } <del> } <del> finally { <del> cleanupTransactionInfo(txInfo); <del> } <add> Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr, status -> { <add> TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status); <add> try { <add> return invocation.proceedWithInvocation(); <add> } catch (Throwable ex) { <add> if (txAttr.rollbackOn(ex)) { <add> // A RuntimeException: will lead to a rollback. <add> if (ex instanceof RuntimeException) { <add> throw (RuntimeException) ex; <add> } else { <add> throw new ThrowableHolderException(ex); <ide> } <del> }); <add> } else { <add> // A normal return value: will lead to a commit. <add> return new ThrowableHolder(ex); <add> } <add> } finally { <add> cleanupTransactionInfo(txInfo); <add> } <add> }); <ide> <ide> // Check result: It might indicate a Throwable to rethrow. <ide> if (result instanceof ThrowableHolder) { <ide><path>spring-web/src/main/java/org/springframework/http/MediaType.java <ide> public class MediaType extends MimeType implements Serializable { <ide> */ <ide> public final static String APPLICATION_PROBLEM_XML_VALUE = "application/problem+xml"; <ide> <add> /** <add> * Comparator used by {@link #sortByQualityValue(List)}. <add> */ <add> public static final Comparator<MediaType> QUALITY_VALUE_COMPARATOR = (mediaType1, mediaType2) -> { <add> double quality1 = mediaType1.getQualityValue(); <add> double quality2 = mediaType2.getQualityValue(); <add> int qualityComparison = Double.compare(quality2, quality1); <add> if (qualityComparison != 0) { <add> return qualityComparison; // audio/*;q=0.7 < audio/*;q=0.3 <add> } <add> else if (mediaType1.isWildcardType() && !mediaType2.isWildcardType()) { // */* < audio/* <add> return 1; <add> } <add> else if (mediaType2.isWildcardType() && !mediaType1.isWildcardType()) { // audio/* > */* <add> return -1; <add> } <add> else if (!mediaType1.getType().equals(mediaType2.getType())) { // audio/basic == text/html <add> return 0; <add> } <add> else { // mediaType1.getType().equals(mediaType2.getType()) <add> if (mediaType1.isWildcardSubtype() && !mediaType2.isWildcardSubtype()) { // audio/* < audio/basic <add> return 1; <add> } <add> else if (mediaType2.isWildcardSubtype() && !mediaType1.isWildcardSubtype()) { // audio/basic > audio/* <add> return -1; <add> } <add> else if (!mediaType1.getSubtype().equals(mediaType2.getSubtype())) { // audio/basic == audio/wave <add> return 0; <add> } <add> else { <add> int paramsSize1 = mediaType1.getParameters().size(); <add> int paramsSize2 = mediaType2.getParameters().size(); <add> return (paramsSize2 < paramsSize1 ? -1 : (paramsSize2 == paramsSize1 ? 0 : 1)); // audio/basic;level=1 < audio/basic <add> } <add> } <add> }; <add> <ide> private static final String PARAM_QUALITY_FACTOR = "q"; <ide> <ide> <ide> public static void sortBySpecificityAndQuality(List<MediaType> mediaTypes) { <ide> } <ide> <ide> <del> /** <del> * Comparator used by {@link #sortByQualityValue(List)}. <del> */ <del> public static final Comparator<MediaType> QUALITY_VALUE_COMPARATOR = new Comparator<MediaType>() { <del> <del> @Override <del> public int compare(MediaType mediaType1, MediaType mediaType2) { <del> double quality1 = mediaType1.getQualityValue(); <del> double quality2 = mediaType2.getQualityValue(); <del> int qualityComparison = Double.compare(quality2, quality1); <del> if (qualityComparison != 0) { <del> return qualityComparison; // audio/*;q=0.7 < audio/*;q=0.3 <del> } <del> else if (mediaType1.isWildcardType() && !mediaType2.isWildcardType()) { // */* < audio/* <del> return 1; <del> } <del> else if (mediaType2.isWildcardType() && !mediaType1.isWildcardType()) { // audio/* > */* <del> return -1; <del> } <del> else if (!mediaType1.getType().equals(mediaType2.getType())) { // audio/basic == text/html <del> return 0; <del> } <del> else { // mediaType1.getType().equals(mediaType2.getType()) <del> if (mediaType1.isWildcardSubtype() && !mediaType2.isWildcardSubtype()) { // audio/* < audio/basic <del> return 1; <del> } <del> else if (mediaType2.isWildcardSubtype() && !mediaType1.isWildcardSubtype()) { // audio/basic > audio/* <del> return -1; <del> } <del> else if (!mediaType1.getSubtype().equals(mediaType2.getSubtype())) { // audio/basic == audio/wave <del> return 0; <del> } <del> else { <del> int paramsSize1 = mediaType1.getParameters().size(); <del> int paramsSize2 = mediaType2.getParameters().size(); <del> return (paramsSize2 < paramsSize1 ? -1 : (paramsSize2 == paramsSize1 ? 0 : 1)); // audio/basic;level=1 < audio/basic <del> } <del> } <del> } <del> }; <del> <del> <ide> /** <ide> * Comparator used by {@link #sortBySpecificity(List)}. <ide> */ <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java <ide> public final class WebAsyncManager { <ide> public void setAsyncWebRequest(final AsyncWebRequest asyncWebRequest) { <ide> Assert.notNull(asyncWebRequest, "AsyncWebRequest must not be null"); <ide> this.asyncWebRequest = asyncWebRequest; <del> this.asyncWebRequest.addCompletionHandler(new Runnable() { <del> @Override <del> public void run() { <del> asyncWebRequest.removeAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); <del> } <del> }); <add> this.asyncWebRequest.addCompletionHandler(() <add> -> asyncWebRequest.removeAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST)); <ide> } <ide> <ide> /** <ide> public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object.. <ide> final Callable<?> callable = webAsyncTask.getCallable(); <ide> final CallableInterceptorChain interceptorChain = new CallableInterceptorChain(interceptors); <ide> <del> this.asyncWebRequest.addTimeoutHandler(new Runnable() { <del> @Override <del> public void run() { <del> logger.debug("Processing timeout"); <del> Object result = interceptorChain.triggerAfterTimeout(asyncWebRequest, callable); <del> if (result != CallableProcessingInterceptor.RESULT_NONE) { <del> setConcurrentResultAndDispatch(result); <del> } <add> this.asyncWebRequest.addTimeoutHandler(() -> { <add> logger.debug("Processing timeout"); <add> Object result = interceptorChain.triggerAfterTimeout(asyncWebRequest, callable); <add> if (result != CallableProcessingInterceptor.RESULT_NONE) { <add> setConcurrentResultAndDispatch(result); <ide> } <ide> }); <ide> <del> this.asyncWebRequest.addCompletionHandler(new Runnable() { <del> @Override <del> public void run() { <del> interceptorChain.triggerAfterCompletion(asyncWebRequest, callable); <del> } <del> }); <add> this.asyncWebRequest.addCompletionHandler(() -> interceptorChain.triggerAfterCompletion(asyncWebRequest, callable)); <ide> <ide> interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, callable); <ide> startAsyncProcessing(processingContext); <ide> try { <del> this.taskExecutor.submit(new Runnable() { <del> @Override <del> public void run() { <del> Object result = null; <del> try { <del> interceptorChain.applyPreProcess(asyncWebRequest, callable); <del> result = callable.call(); <del> } <del> catch (Throwable ex) { <del> result = ex; <del> } <del> finally { <del> result = interceptorChain.applyPostProcess(asyncWebRequest, callable, result); <del> } <del> setConcurrentResultAndDispatch(result); <add> this.taskExecutor.submit(() -> { <add> Object result = null; <add> try { <add> interceptorChain.applyPreProcess(asyncWebRequest, callable); <add> result = callable.call(); <add> } <add> catch (Throwable ex) { <add> result = ex; <add> } <add> finally { <add> result = interceptorChain.applyPostProcess(asyncWebRequest, callable, result); <ide> } <add> setConcurrentResultAndDispatch(result); <ide> }); <ide> } <ide> catch (RejectedExecutionException ex) { <ide> public void startDeferredResultProcessing( <ide> <ide> final DeferredResultInterceptorChain interceptorChain = new DeferredResultInterceptorChain(interceptors); <ide> <del> this.asyncWebRequest.addTimeoutHandler(new Runnable() { <del> @Override <del> public void run() { <del> try { <del> interceptorChain.triggerAfterTimeout(asyncWebRequest, deferredResult); <del> } <del> catch (Throwable ex) { <del> setConcurrentResultAndDispatch(ex); <del> } <add> this.asyncWebRequest.addTimeoutHandler(() -> { <add> try { <add> interceptorChain.triggerAfterTimeout(asyncWebRequest, deferredResult); <ide> } <del> }); <del> <del> this.asyncWebRequest.addCompletionHandler(new Runnable() { <del> @Override <del> public void run() { <del> interceptorChain.triggerAfterCompletion(asyncWebRequest, deferredResult); <add> catch (Throwable ex) { <add> setConcurrentResultAndDispatch(ex); <ide> } <ide> }); <ide> <add> this.asyncWebRequest.addCompletionHandler(() <add> -> interceptorChain.triggerAfterCompletion(asyncWebRequest, deferredResult)); <add> <ide> interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, deferredResult); <ide> startAsyncProcessing(processingContext); <ide> <ide> try { <ide> interceptorChain.applyPreProcess(this.asyncWebRequest, deferredResult); <del> deferredResult.setResultHandler(new DeferredResultHandler() { <del> @Override <del> public void handleResult(Object result) { <del> result = interceptorChain.applyPostProcess(asyncWebRequest, deferredResult, result); <del> setConcurrentResultAndDispatch(result); <del> } <add> deferredResult.setResultHandler(result -> { <add> result = interceptorChain.applyPostProcess(asyncWebRequest, deferredResult, result); <add> setConcurrentResultAndDispatch(result); <ide> }); <ide> } <ide> catch (Throwable ex) { <ide><path>spring-web/src/main/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolver.java <ide> public class ExceptionHandlerMethodResolver { <ide> /** <ide> * A filter for selecting {@code @ExceptionHandler} methods. <ide> */ <del> public static final MethodFilter EXCEPTION_HANDLER_METHODS = new MethodFilter() { <del> @Override <del> public boolean matches(Method method) { <del> return (AnnotationUtils.findAnnotation(method, ExceptionHandler.class) != null); <del> } <del> }; <add> public static final MethodFilter EXCEPTION_HANDLER_METHODS = <add> method -> (AnnotationUtils.findAnnotation(method, ExceptionHandler.class) != null); <ide> <ide> /** <ide> * Arbitrary {@link Method} reference, indicating no method found in the cache. <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java <ide> private static String getMethodRequestMapping(Method method) { <ide> } <ide> <ide> private static Method getMethod(Class<?> controllerType, final String methodName, final Object... args) { <del> MethodFilter selector = new MethodFilter() { <del> @Override <del> public boolean matches(Method method) { <del> String name = method.getName(); <del> int argLength = method.getParameterCount(); <del> return (name.equals(methodName) && argLength == args.length); <del> } <add> MethodFilter selector = method -> { <add> String name = method.getName(); <add> int argLength = method.getParameterCount(); <add> return (name.equals(methodName) && argLength == args.length); <ide> }; <ide> Set<Method> methods = MethodIntrospector.selectMethods(controllerType, selector); <ide> if (methods.size() == 1) { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java <ide> public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter <ide> implements BeanFactoryAware, InitializingBean { <ide> <add> /** <add> * MethodFilter that matches {@link InitBinder @InitBinder} methods. <add> */ <add> public static final MethodFilter INIT_BINDER_METHODS = <add> method -> AnnotationUtils.findAnnotation(method, InitBinder.class) != null; <add> <add> /** <add> * MethodFilter that matches {@link ModelAttribute @ModelAttribute} methods. <add> */ <add> public static final MethodFilter MODEL_ATTRIBUTE_METHODS = <add> method -> ((AnnotationUtils.findAnnotation(method, RequestMapping.class) == null) <add> && (AnnotationUtils.findAnnotation(method, ModelAttribute.class) != null)); <add> <ide> private List<HandlerMethodArgumentResolver> customArgumentResolvers; <ide> <ide> private HandlerMethodArgumentResolverComposite argumentResolvers; <ide> private ModelAndView getModelAndView(ModelAndViewContainer mavContainer, <ide> return mav; <ide> } <ide> <del> <del> /** <del> * MethodFilter that matches {@link InitBinder @InitBinder} methods. <del> */ <del> public static final MethodFilter INIT_BINDER_METHODS = new MethodFilter() { <del> @Override <del> public boolean matches(Method method) { <del> return AnnotationUtils.findAnnotation(method, InitBinder.class) != null; <del> } <del> }; <del> <del> /** <del> * MethodFilter that matches {@link ModelAttribute @ModelAttribute} methods. <del> */ <del> public static final MethodFilter MODEL_ATTRIBUTE_METHODS = new MethodFilter() { <del> @Override <del> public boolean matches(Method method) { <del> return ((AnnotationUtils.findAnnotation(method, RequestMapping.class) == null) && <del> (AnnotationUtils.findAnnotation(method, ModelAttribute.class) != null)); <del> } <del> }; <del> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/jetty/JettyWebSocketClient.java <ide> public ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler w <ide> final JettyWebSocketSession wsSession = new JettyWebSocketSession(attributes, user); <ide> final JettyWebSocketHandlerAdapter listener = new JettyWebSocketHandlerAdapter(wsHandler, wsSession); <ide> <del> Callable<WebSocketSession> connectTask = new Callable<WebSocketSession>() { <del> @Override <del> public WebSocketSession call() throws Exception { <del> Future<Session> future = client.connect(listener, uri, request); <del> future.get(); <del> return wsSession; <del> } <add> Callable<WebSocketSession> connectTask = () -> { <add> Future<Session> future = client.connect(listener, uri, request); <add> future.get(); <add> return wsSession; <ide> }; <ide> <ide> if (this.taskExecutor != null) { <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/standard/AnnotatedEndpointConnectionManager.java <ide> public TaskExecutor getTaskExecutor() { <ide> <ide> @Override <ide> protected void openConnection() { <del> this.taskExecutor.execute(new Runnable() { <del> @Override <del> public void run() { <del> try { <del> if (logger.isInfoEnabled()) { <del> logger.info("Connecting to WebSocket at " + getUri()); <del> } <del> Object endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler(); <del> session = webSocketContainer.connectToServer(endpointToUse, getUri()); <del> logger.info("Successfully connected to WebSocket"); <del> } <del> catch (Throwable ex) { <del> logger.error("Failed to connect to WebSocket", ex); <add> this.taskExecutor.execute(() -> { <add> try { <add> if (logger.isInfoEnabled()) { <add> logger.info("Connecting to WebSocket at " + getUri()); <ide> } <add> Object endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler(); <add> session = webSocketContainer.connectToServer(endpointToUse, getUri()); <add> logger.info("Successfully connected to WebSocket"); <add> } <add> catch (Throwable ex) { <add> logger.error("Failed to connect to WebSocket", ex); <ide> } <ide> }); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/standard/EndpointConnectionManager.java <ide> public TaskExecutor getTaskExecutor() { <ide> <ide> @Override <ide> protected void openConnection() { <del> this.taskExecutor.execute(new Runnable() { <del> @Override <del> public void run() { <del> try { <del> if (logger.isInfoEnabled()) { <del> logger.info("Connecting to WebSocket at " + getUri()); <del> } <del> Endpoint endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler(); <del> ClientEndpointConfig endpointConfig = configBuilder.build(); <del> session = getWebSocketContainer().connectToServer(endpointToUse, endpointConfig, getUri()); <del> logger.info("Successfully connected to WebSocket"); <del> } <del> catch (Throwable ex) { <del> logger.error("Failed to connect to WebSocket", ex); <add> this.taskExecutor.execute(() -> { <add> try { <add> if (logger.isInfoEnabled()) { <add> logger.info("Connecting to WebSocket at " + getUri()); <ide> } <add> Endpoint endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler(); <add> ClientEndpointConfig endpointConfig = configBuilder.build(); <add> session = getWebSocketContainer().connectToServer(endpointToUse, endpointConfig, getUri()); <add> logger.info("Successfully connected to WebSocket"); <add> } <add> catch (Throwable ex) { <add> logger.error("Failed to connect to WebSocket", ex); <ide> } <ide> }); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/standard/StandardWebSocketClient.java <ide> protected ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandle <ide> <ide> final Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session); <ide> <del> Callable<WebSocketSession> connectTask = new Callable<WebSocketSession>() { <del> @Override <del> public WebSocketSession call() throws Exception { <del> webSocketContainer.connectToServer(endpoint, endpointConfig, uri); <del> return session; <del> } <add> Callable<WebSocketSession> connectTask = () -> { <add> webSocketContainer.connectToServer(endpoint, endpointConfig, uri); <add> return session; <ide> }; <ide> <ide> if (this.taskExecutor != null) { <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketMessageBrokerStats.java <ide> public void setSockJsTaskScheduler(ThreadPoolTaskScheduler sockJsTaskScheduler) <ide> @Nullable <ide> private ScheduledFuture<?> initLoggingTask(long initialDelay) { <ide> if (logger.isInfoEnabled() && this.loggingPeriod > 0) { <del> return this.sockJsTaskScheduler.scheduleAtFixedRate(new Runnable() { <del> @Override <del> public void run() { <del> logger.info(WebSocketMessageBrokerStats.this.toString()); <del> } <del> }, initialDelay, this.loggingPeriod, TimeUnit.MILLISECONDS); <add> return this.sockJsTaskScheduler.scheduleAtFixedRate(() <add> -> logger.info(WebSocketMessageBrokerStats.this.toString()), <add> initialDelay, this.loggingPeriod, TimeUnit.MILLISECONDS); <ide> } <ide> return null; <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/WebSocketStompClient.java <ide> private void updateLastWriteTime() { <ide> public void onReadInactivity(final Runnable runnable, final long duration) { <ide> Assert.state(getTaskScheduler() != null, "No TaskScheduler configured"); <ide> this.lastReadTime = System.currentTimeMillis(); <del> this.inactivityTasks.add(getTaskScheduler().scheduleWithFixedDelay(new Runnable() { <del> @Override <del> public void run() { <del> if (System.currentTimeMillis() - lastReadTime > duration) { <del> try { <del> runnable.run(); <del> } <del> catch (Throwable ex) { <del> if (logger.isDebugEnabled()) { <del> logger.debug("ReadInactivityTask failure", ex); <del> } <del> } <del> } <del> } <del> }, duration / 2)); <add> this.inactivityTasks.add(getTaskScheduler().scheduleWithFixedDelay(() -> { <add> if (System.currentTimeMillis() - lastReadTime > duration) { <add> try { <add> runnable.run(); <add> } <add> catch (Throwable ex) { <add> if (logger.isDebugEnabled()) { <add> logger.debug("ReadInactivityTask failure", ex); <add> } <add> } <add> } <add> }, duration / 2)); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/AbstractClientSockJsSession.java <ide> public WebSocketHandler getWebSocketHandler() { <ide> * request. <ide> */ <ide> Runnable getTimeoutTask() { <del> return new Runnable() { <del> @Override <del> public void run() { <del> closeInternal(new CloseStatus(2007, "Transport timed out")); <del> } <del> }; <add> return () -> closeInternal(new CloseStatus(2007, "Transport timed out")); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransport.java <ide> protected void connectInternal(final TransportRequest transportRequest, final We <ide> final URI receiveUrl, final HttpHeaders handshakeHeaders, final XhrClientSockJsSession session, <ide> final SettableListenableFuture<WebSocketSession> connectFuture) { <ide> <del> getTaskExecutor().execute(new Runnable() { <del> @Override <del> public void run() { <del> HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders(); <del> XhrRequestCallback requestCallback = new XhrRequestCallback(handshakeHeaders); <del> XhrRequestCallback requestCallbackAfterHandshake = new XhrRequestCallback(httpHeaders); <del> XhrReceiveExtractor responseExtractor = new XhrReceiveExtractor(session); <del> while (true) { <del> if (session.isDisconnected()) { <del> session.afterTransportClosed(null); <del> break; <add> getTaskExecutor().execute(() -> { <add> HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders(); <add> XhrRequestCallback requestCallback = new XhrRequestCallback(handshakeHeaders); <add> XhrRequestCallback requestCallbackAfterHandshake = new XhrRequestCallback(httpHeaders); <add> XhrReceiveExtractor responseExtractor = new XhrReceiveExtractor(session); <add> while (true) { <add> if (session.isDisconnected()) { <add> session.afterTransportClosed(null); <add> break; <add> } <add> try { <add> if (logger.isTraceEnabled()) { <add> logger.trace("Starting XHR receive request, url=" + receiveUrl); <ide> } <del> try { <del> if (logger.isTraceEnabled()) { <del> logger.trace("Starting XHR receive request, url=" + receiveUrl); <del> } <del> getRestTemplate().execute(receiveUrl, HttpMethod.POST, requestCallback, responseExtractor); <del> requestCallback = requestCallbackAfterHandshake; <add> getRestTemplate().execute(receiveUrl, HttpMethod.POST, requestCallback, responseExtractor); <add> requestCallback = requestCallbackAfterHandshake; <add> } <add> catch (Throwable ex) { <add> if (!connectFuture.isDone()) { <add> connectFuture.setException(ex); <ide> } <del> catch (Throwable ex) { <del> if (!connectFuture.isDone()) { <del> connectFuture.setException(ex); <del> } <del> else { <del> session.handleTransportError(ex); <del> session.afterTransportClosed(new CloseStatus(1006, ex.getMessage())); <del> } <del> break; <add> else { <add> session.handleTransportError(ex); <add> session.afterTransportClosed(new CloseStatus(1006, ex.getMessage())); <ide> } <add> break; <ide> } <ide> } <ide> }); <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java <ide> private void scheduleSessionTask() { <ide> if (this.sessionCleanupTask != null) { <ide> return; <ide> } <del> this.sessionCleanupTask = getTaskScheduler().scheduleAtFixedRate(new Runnable() { <del> @Override <del> public void run() { <del> List<String> removedIds = new ArrayList<>(); <del> for (SockJsSession session : sessions.values()) { <del> try { <del> if (session.getTimeSinceLastActive() > getDisconnectDelay()) { <del> sessions.remove(session.getId()); <del> removedIds.add(session.getId()); <del> session.close(); <del> } <del> } <del> catch (Throwable ex) { <del> // Could be part of normal workflow (e.g. browser tab closed) <del> logger.debug("Failed to close " + session, ex); <add> this.sessionCleanupTask = getTaskScheduler().scheduleAtFixedRate(() -> { <add> List<String> removedIds = new ArrayList<>(); <add> for (SockJsSession session : sessions.values()) { <add> try { <add> if (session.getTimeSinceLastActive() > getDisconnectDelay()) { <add> sessions.remove(session.getId()); <add> removedIds.add(session.getId()); <add> session.close(); <ide> } <ide> } <del> if (logger.isDebugEnabled() && !removedIds.isEmpty()) { <del> logger.debug("Closed " + removedIds.size() + " sessions: " + removedIds); <add> catch (Throwable ex) { <add> // Could be part of normal workflow (e.g. browser tab closed) <add> logger.debug("Failed to close " + session, ex); <ide> } <ide> } <add> if (logger.isDebugEnabled() && !removedIds.isEmpty()) { <add> logger.debug("Closed " + removedIds.size() + " sessions: " + removedIds); <add> } <ide> }, getDisconnectDelay()); <ide> } <ide> }
52
Text
Text
add guides for chinese contributors
f7148650ce27f336e7f9caa958b1ec2da5d588f1
<ide><path>docs/chinese-guides/news-translations.md <add># freeCodeCamp 文章翻译计划 <add> <add>freeCodeCamp 英文社区的成员发布了大量[优质文章](https://www.freecodecamp.org/news/),分享前端、后端、 Android、iOS、产品、设计、区块链、人工智能等领域的内容,以及学习编程的经历和求职经验。我们一起把这些文章翻译成中文,分享给更多读者。 <add> <add>## 参与翻译计划你会获得 <add>- 持续提升你的英文水平和多人协作的经验 <add>- 快速提高你的 Git 操作熟练度 <add>- 收获 GitHub 认可的 contributions <add>- 受邀成为 freeCodeCamp 社区作者,文章发表在[官网](https://chinese.freecodecamp.org/news/) <add>- 有机会受邀参与 freeCodeCamp 城市社区举办的技术交流活动 <add>- 在社区中结识优秀的小伙伴,拥抱更多技术成长与职业发展的可能性 <add> <add>## 参与翻译 <add>请在认领翻译前阅读这两篇: <add>- [图文详解如何参与翻译](./Contributing.md) <add>- [翻译技巧](https://github.com/freeCodeCamp/news-translation/wiki/%E7%BF%BB%E8%AF%91%E6%8A%80%E5%B7%A7) <add> <add>在校对了好多篇文章之后,我们发现不少文章有一些类似的小问题,在这里特别提醒一下: <add>- 在翻译 you 这个单词的时候,不需要使用敬语”您“,使用”你“即可 <add>- 中英文之间需要加一个空格(这点在翻译技巧中有写) <add>- 翻译好之后可以自己读一遍,看是否流畅,是否符合中文的表达习惯 <add> <add>## 参与校对 <add>每一篇翻译好的文章,我们会有一位贡献者对其进行校对。如果你希望参与校对,请在 [Review-awaiting](https://github.com/freeCodeCamp/news-translation/issues?q=is%3Aissue+is%3Aopen+label%3AReview-awaiting) 列表选取文章并留言“认领校对”,我们会邀请你成为 collaborator。 <add> <add>## 发布文章 <add>我们会和译者一同确认校对意见,形成终稿,即校对完毕。翻译及校对完毕的文章将以翻译者的姓名(或昵称)发布在 [freeCodeCamp 官网](https://chinese.freecodecamp.org/news/)(我们会邀请译者在官网注册作者账号;同时发布在 freeCodeCamp 微信公众号,在公众号发布时将在文章中同时注明翻译者和校对者的姓名(或昵称)。此外,我们还会在其他相关站点的 freeCodeCamp 专栏发布译文,链接到官网。 <ide><path>docs/chinese-guides/video-translations.md <add># freeCodeCamp 视频翻译计划 <add> <add>[freeCodeCamp's YouTube Channel](https://www.youtube.com/freecodecamp) 发布了大量优质视频教程,涵盖 HTML&CSS、JavaScript、Python、数据科学、机器学习等内容,我们一起把这些视频翻译成中文,发布在 [bilibili](https://space.bilibili.com/335505768),分享给更多学员。 <add> <add>## 参与翻译你会获得 <add> <add>- 持续提升你的英文水平和多人协作的经验 <add>- 成为 freeCodeCamp 社区贡献者(我们将在翻译后的视频介绍中记录译者的姓名或昵称) <add>- 有机会受邀参与 freeCodeCamp 城市社区的技术交流活动 <add>- 在社区中结识优秀的小伙伴,拥抱更多技术成长与职业发展的可能性 <add> <add>## 协作流程 <add>我们翻译的第一个视频是[零基础学 JavaScript(全套教程)](https://www.bilibili.com/video/av61884749/),从这个过程中总结出协作流程的最佳实践如下(稍后我们可能对此进行优化): <add>- **认领翻译:** 我们会先将 [freeCodeCamp's YouTube Channel](https://www.youtube.com/freecodecamp) 的原视频上传到 [bilibili](https://space.bilibili.com/335505768),这样那些英语水平不错的人们可以先行观看学习。然后我们逐步为视频添加中文字幕。如果你有意参与翻译,请加微信好友(Hello_MrT)或发送邮件至 miya@freecodecamp.org,作简要的自我介绍,然后我们会把你想要翻译的视频的英文字幕文档发给你,并帮助你详细了解翻译过程中需要注意的地方。 <add>- **语言水平要求:** 总的来说,英文字幕没有复杂的语法结构,没有生僻单词,对译者来说,英语四级的水平足够了。如果你之前有翻译经历或者用英语交流的经历,那就更棒啦!并且,你可以随时在协作群里和大家讨论,所以你真的真的不用太担心自己的英语水平。 <add>- **技术水平要求:** 我们的视频教程有的是面向新手的,比如零基础学 JavaScript、零基础学 Python,这就不需要你有技术背景。而且当你遇到问题的时候,我们的开发者同学会为你解答,你可以在翻译过程中学习技术知识,逐渐掌握一门新技能。当然,有的视频教程是进阶性的,欢迎有技术背景的贡献者认领。 <add>- **提交译文:** 翻译完成后,请将 .srt 格式的译文发至邮箱 miya@freecodecamp.org,注明译者姓名(或昵称),随后我们会在视频介绍中记录所有译者的姓名(或昵称)。 <add>- **时间轴:** 在翻译过程中,译者不需要调整时间轴,也不要删除时间轴,我们会在上传的时候统一调整。 <add>- **上传字幕:** 我们逐步将译文上传为外挂字幕,比如某个视频的一半的字幕已经翻译完毕,那么就先上传这一半的字幕。在完全上传并且校对无误之后,我们会下载包含时间轴的字幕终稿,并上传至 [freeCodeCamp's YouTube Channel](https://www.youtube.com/freecodecamp) 的视频。有大量中文用户在 YouTube 观看我们的视频教程,所以我们翻译的中文字幕也将帮助他们学习。特别感谢 [Chengjun.L](https://github.com/Raman0716) 编写脚本方便我们下载字幕终稿。 <add>- **校对字幕:** 我们在上传字幕的时候同步进行校对。 <add> <add>## 翻译原则 <add>结合翻译[零基础学 JavaScript(全套教程)](https://www.bilibili.com/video/av61884749/)的经验,我们简要总结翻译原则如下(稍后我们可能对此进行优化): <add>- 句末不要加标点符号。 <add>- 单句不宜过长,观众需要一眼就能看懂中文字幕。 <add>- 灵活调整语序,比如英语里的 if 条件状语从句有时候是放在后部分,而中文翻译为“如果......”的时候,则需要放在前部分。 <add>- 特别提醒没有技术背景的译者,当你遇到一些单词,拿不定主意,也许它是一个专业术语(比如,variable 变量,function 函数),这时候你可以直接在协作群里提出来讨论。 <add>- 我们没有 deadline,请结合你自己的实际情况合理安排翻译时间,希望你享受协作的过程:D 不过,如果你在认领翻译之后发现自己短期内没时间翻译,请直接告诉我们,以便协调进度。 <add> <add>## 视频翻译进度 <add>在选择你想翻译哪个视频之前,请在[这里](https://github.com/freeCodeCamp/videos-translation/wiki/%E8%A7%86%E9%A2%91%E7%BF%BB%E8%AF%91%E8%BF%9B%E5%BA%A6)查看其他贡献者已经翻译了哪些视频,避免重复翻译。 <ide><path>docs/components/sidebar.md <ide> - [How to work on the news theme](/how-to-work-on-the-news-theme.md) <ide> - [How to work on the docs theme](/how-to-work-on-the-docs-theme.md) <ide> - [How to catch outgoing emails locally](/how-to-catch-outgoing-emails-locally.md) <add>- **<i class="fad fa-language"></i> Chinese Community Contribution Guides** (中文社区贡献指南) <add> - [Translate news articles (文章翻译计划)](/chinese-guides/news-translations.md) <add> - [Translate videos (视频翻译计划)](/chinese-guides/video-translations.md) <ide> - **<i class="fad fa-laptop-code"></i> DevOps Guides** <ide> - [How we build, test and deploy](/devops.md) <ide> - **<i class="fad fa-plane-alt"></i> Flight Manuals** (for Staff & Mods)
3
Mixed
Javascript
add writeearlyhints function to serverresponse
58ab0e28210b4107f50a419ae24c97b376d1ff18
<ide><path>doc/api/http.md <ide> buffer. Returns `false` if all or part of the data was queued in user memory. <ide> added: v0.3.0 <ide> --> <ide> <del>Sends a HTTP/1.1 100 Continue message to the client, indicating that <add>Sends an HTTP/1.1 100 Continue message to the client, indicating that <ide> the request body should be sent. See the [`'checkContinue'`][] event on <ide> `Server`. <ide> <add>### `response.writeEarlyHints(links[, callback])` <add> <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* `links` {string|Array} <add>* `callback` {Function} <add> <add>Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, <add>indicating that the user agent can preload/preconnect the linked resources. <add>The `links` can be a string or an array of strings containing the values <add>of the `Link` header. The optional `callback` argument will be called when <add>the response message has been written. <add> <add>**Example** <add> <add>```js <add>const earlyHintsLink = '</styles.css>; rel=preload; as=style'; <add>response.writeEarlyHints(earlyHintsLink); <add> <add>const earlyHintsLinks = [ <add> '</styles.css>; rel=preload; as=style', <add> '</scripts.js>; rel=preload; as=script', <add>]; <add>response.writeEarlyHints(earlyHintsLinks); <add> <add>const earlyHintsCallback = () => console.log('early hints message sent'); <add>response.writeEarlyHints(earlyHintsLinks, earlyHintsCallback); <add>``` <add> <ide> ### `response.writeHead(statusCode[, statusMessage][, headers])` <ide> <ide> <!-- YAML <ide><path>doc/api/http2.md <ide> Sends a status `100 Continue` to the client, indicating that the request body <ide> should be sent. See the [`'checkContinue'`][] event on `Http2Server` and <ide> `Http2SecureServer`. <ide> <add>### `response.writeEarlyHints(links)` <add> <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* `links` {string|Array} <add> <add>Sends a status `103 Early Hints` to the client with a Link header, <add>indicating that the user agent can preload/preconnect the linked resources. <add>The `links` can be a string or an array of strings containing the values <add>of the `Link` header. <add> <add>**Example** <add> <add>```js <add>const earlyHintsLink = '</styles.css>; rel=preload; as=style'; <add>response.writeEarlyHints(earlyHintsLink); <add> <add>const earlyHintsLinks = [ <add> '</styles.css>; rel=preload; as=style', <add> '</scripts.js>; rel=preload; as=script', <add>]; <add>response.writeEarlyHints(earlyHintsLinks); <add>``` <add> <ide> #### `response.writeHead(statusCode[, statusMessage][, headers])` <ide> <ide> <!-- YAML <ide><path>lib/_http_server.js <ide> const { <ide> } = codes; <ide> const { <ide> validateInteger, <del> validateBoolean <add> validateBoolean, <add> validateLinkHeaderValue <ide> } = require('internal/validators'); <ide> const Buffer = require('buffer').Buffer; <ide> const { setInterval, clearInterval } = require('timers'); <ide> ServerResponse.prototype.writeProcessing = function writeProcessing(cb) { <ide> this._writeRaw('HTTP/1.1 102 Processing\r\n\r\n', 'ascii', cb); <ide> }; <ide> <add>ServerResponse.prototype.writeEarlyHints = function writeEarlyHints(links, cb) { <add> let head = 'HTTP/1.1 103 Early Hints\r\n'; <add> <add> if (typeof links === 'string') { <add> validateLinkHeaderValue(links, 'links'); <add> head += 'Link: ' + links + '\r\n'; <add> } else if (ArrayIsArray(links)) { <add> if (!links.length) { <add> return; <add> } <add> <add> head += 'Link: '; <add> <add> for (let i = 0; i < links.length; i++) { <add> const link = links[i]; <add> validateLinkHeaderValue(link, 'links'); <add> head += link; <add> <add> if (i !== links.length - 1) { <add> head += ', '; <add> } <add> } <add> <add> head += '\r\n'; <add> } else { <add> throw new ERR_INVALID_ARG_VALUE( <add> 'links', <add> links, <add> 'must be an array or string of format "</styles.css>; rel=preload; as=style"' <add> ); <add> } <add> <add> head += '\r\n'; <add> <add> this._writeRaw(head, 'ascii', cb); <add>}; <add> <ide> ServerResponse.prototype._implicitHeader = function _implicitHeader() { <ide> this.writeHead(this.statusCode); <ide> }; <ide><path>lib/internal/http2/compat.js <ide> const { <ide> HTTP2_HEADER_STATUS, <ide> <ide> HTTP_STATUS_CONTINUE, <add> HTTP_STATUS_EARLY_HINTS, <ide> HTTP_STATUS_EXPECTATION_FAILED, <ide> HTTP_STATUS_METHOD_NOT_ALLOWED, <ide> HTTP_STATUS_OK <ide> const { <ide> const { <ide> validateFunction, <ide> validateString, <add> validateLinkHeaderValue, <ide> } = require('internal/validators'); <ide> const { <ide> kSocket, <ide> class Http2ServerResponse extends Stream { <ide> }); <ide> return true; <ide> } <add> <add> writeEarlyHints(links) { <add> let linkHeaderValue = ''; <add> <add> if (typeof links === 'string') { <add> validateLinkHeaderValue(links, 'links'); <add> linkHeaderValue += links; <add> } else if (ArrayIsArray(links)) { <add> if (!links.length) { <add> return; <add> } <add> <add> linkHeaderValue += ''; <add> <add> for (let i = 0; i < links.length; i++) { <add> const link = links[i]; <add> validateLinkHeaderValue(link, 'links'); <add> linkHeaderValue += link; <add> <add> if (i !== links.length - 1) { <add> linkHeaderValue += ', '; <add> } <add> } <add> } else { <add> throw new ERR_INVALID_ARG_VALUE( <add> 'links', <add> links, <add> 'must be an array or string of format "</styles.css>; rel=preload; as=style"' <add> ); <add> } <add> <add> const stream = this[kStream]; <add> <add> if (stream.headersSent || this[kState].closed) <add> return false; <add> <add> stream.additionalHeaders({ <add> [HTTP2_HEADER_STATUS]: HTTP_STATUS_EARLY_HINTS, <add> 'Link': linkHeaderValue <add> }); <add> <add> return true; <add> } <ide> } <ide> <ide> function onServerStream(ServerRequest, ServerResponse, <ide><path>lib/internal/validators.js <ide> function validateUnion(value, name, union) { <ide> } <ide> } <ide> <add>function validateLinkHeaderValue(value, name) { <add> const linkValueRegExp = /^(?:<[^>]*>;)\s*(?:rel=(")?[^;"]*\1;?)\s*(?:(?:as|anchor|title)=(")?[^;"]*\2)?$/; <add> <add> if ( <add> typeof value === 'undefined' || <add> !RegExpPrototypeExec(linkValueRegExp, value) <add> ) { <add> throw new ERR_INVALID_ARG_VALUE( <add> name, <add> value, <add> 'must be an array or string of format "</styles.css>; rel=preload; as=style"' <add> ); <add> } <add>} <add> <ide> module.exports = { <ide> isInt32, <ide> isUint32, <ide> module.exports = { <ide> validateUndefined, <ide> validateUnion, <ide> validateAbortSignal, <add> validateLinkHeaderValue <ide> }; <ide><path>test/parallel/test-http-early-hints-invalid-argument-type.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('node:assert'); <add>const http = require('node:http'); <add>const debug = require('node:util').debuglog('test'); <add> <add>const testResBody = 'response content\n'; <add> <add>const server = http.createServer(common.mustCall((req, res) => { <add> debug('Server sending early hints...'); <add> res.writeEarlyHints({ links: 'bad argument object' }); <add> <add> debug('Server sending full response...'); <add> res.end(testResBody); <add>})); <add> <add>server.listen(0, common.mustCall(() => { <add> const req = http.request({ <add> port: server.address().port, path: '/' <add> }); <add> <add> req.end(); <add> debug('Client sending request...'); <add> <add> req.on('information', common.mustNotCall()); <add> <add> process.on('uncaughtException', (err) => { <add> debug(`Caught an exception: ${JSON.stringify(err)}`); <add> if (err.name === 'AssertionError') throw err; <add> assert.strictEqual(err.code, 'ERR_INVALID_ARG_VALUE'); <add> process.exit(0); <add> }); <add>})); <ide><path>test/parallel/test-http-early-hints-invalid-argument.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('node:assert'); <add>const http = require('node:http'); <add>const debug = require('node:util').debuglog('test'); <add> <add>const testResBody = 'response content\n'; <add> <add>const server = http.createServer(common.mustCall((req, res) => { <add> debug('Server sending early hints...'); <add> res.writeEarlyHints('bad argument value'); <add> <add> debug('Server sending full response...'); <add> res.end(testResBody); <add>})); <add> <add>server.listen(0, common.mustCall(() => { <add> const req = http.request({ <add> port: server.address().port, path: '/' <add> }); <add> <add> req.end(); <add> debug('Client sending request...'); <add> <add> req.on('information', common.mustNotCall()); <add> <add> process.on('uncaughtException', (err) => { <add> debug(`Caught an exception: ${JSON.stringify(err)}`); <add> if (err.name === 'AssertionError') throw err; <add> assert.strictEqual(err.code, 'ERR_INVALID_ARG_VALUE'); <add> process.exit(0); <add> }); <add>})); <ide><path>test/parallel/test-http-early-hints.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('node:assert'); <add>const http = require('node:http'); <add>const debug = require('node:util').debuglog('test'); <add> <add>const testResBody = 'response content\n'; <add> <add>{ <add> // Happy flow - string argument <add> <add> const server = http.createServer(common.mustCall((req, res) => { <add> debug('Server sending early hints...'); <add> res.writeEarlyHints('</styles.css>; rel=preload; as=style'); <add> <add> debug('Server sending full response...'); <add> res.end(testResBody); <add> })); <add> <add> server.listen(0, common.mustCall(() => { <add> const req = http.request({ <add> port: server.address().port, path: '/' <add> }); <add> <add> debug('Client sending request...'); <add> <add> req.on('information', common.mustCall((res) => { <add> assert.strictEqual(res.headers.link, '</styles.css>; rel=preload; as=style'); <add> })); <add> <add> req.on('response', common.mustCall((res) => { <add> let body = ''; <add> <add> assert.strictEqual(res.statusCode, 200, `Final status code was ${res.statusCode}, not 200.`); <add> <add> res.on('data', (chunk) => { <add> body += chunk; <add> }); <add> <add> res.on('end', common.mustCall(() => { <add> debug('Got full response.'); <add> assert.strictEqual(body, testResBody); <add> server.close(); <add> })); <add> })); <add> <add> req.end(); <add> })); <add>} <add> <add>{ <add> // Happy flow - array argument <add> <add> const server = http.createServer(common.mustCall((req, res) => { <add> debug('Server sending early hints...'); <add> res.writeEarlyHints([ <add> '</styles.css>; rel=preload; as=style', <add> '</scripts.js>; rel=preload; as=script', <add> ]); <add> <add> debug('Server sending full response...'); <add> res.end(testResBody); <add> })); <add> <add> server.listen(0, common.mustCall(() => { <add> const req = http.request({ <add> port: server.address().port, path: '/' <add> }); <add> debug('Client sending request...'); <add> <add> req.on('information', common.mustCall((res) => { <add> assert.strictEqual( <add> res.headers.link, <add> '</styles.css>; rel=preload; as=style, </scripts.js>; rel=preload; as=script' <add> ); <add> })); <add> <add> req.on('response', common.mustCall((res) => { <add> let body = ''; <add> <add> assert.strictEqual(res.statusCode, 200, `Final status code was ${res.statusCode}, not 200.`); <add> <add> res.on('data', (chunk) => { <add> body += chunk; <add> }); <add> <add> res.on('end', common.mustCall(() => { <add> debug('Got full response.'); <add> assert.strictEqual(body, testResBody); <add> server.close(); <add> })); <add> })); <add> <add> req.end(); <add> })); <add>} <add> <add>{ <add> // Happy flow - empty array <add> <add> const server = http.createServer(common.mustCall((req, res) => { <add> debug('Server sending early hints...'); <add> res.writeEarlyHints([]); <add> <add> debug('Server sending full response...'); <add> res.end(testResBody); <add> })); <add> <add> server.listen(0, common.mustCall(() => { <add> const req = http.request({ <add> port: server.address().port, path: '/' <add> }); <add> debug('Client sending request...'); <add> <add> req.on('information', common.mustNotCall()); <add> <add> req.on('response', common.mustCall((res) => { <add> let body = ''; <add> <add> assert.strictEqual(res.statusCode, 200, `Final status code was ${res.statusCode}, not 200.`); <add> <add> res.on('data', (chunk) => { <add> body += chunk; <add> }); <add> <add> res.on('end', common.mustCall(() => { <add> debug('Got full response.'); <add> assert.strictEqual(body, testResBody); <add> server.close(); <add> })); <add> })); <add> <add> req.end(); <add> })); <add>} <ide><path>test/parallel/test-http2-compat-write-early-hints-invalid-argument-type.js <add>'use strict'; <add> <add>const common = require('../common'); <add>if (!common.hasCrypto) common.skip('missing crypto'); <add> <add>const assert = require('node:assert'); <add>const http2 = require('node:http2'); <add>const debug = require('node:util').debuglog('test'); <add> <add>const testResBody = 'response content'; <add> <add>const server = http2.createServer(); <add> <add>server.on('request', common.mustCall((req, res) => { <add> debug('Server sending early hints...'); <add> res.writeEarlyHints({ links: 'bad argument object' }); <add> <add> debug('Server sending full response...'); <add> res.end(testResBody); <add>})); <add> <add>server.listen(0); <add> <add>server.on('listening', common.mustCall(() => { <add> const client = http2.connect(`http://localhost:${server.address().port}`); <add> const req = client.request(); <add> <add> debug('Client sending request...'); <add> <add> req.on('headers', common.mustNotCall()); <add> <add> process.on('uncaughtException', (err) => { <add> debug(`Caught an exception: ${JSON.stringify(err)}`); <add> if (err.name === 'AssertionError') throw err; <add> assert.strictEqual(err.code, 'ERR_INVALID_ARG_VALUE'); <add> process.exit(0); <add> }); <add>})); <ide><path>test/parallel/test-http2-compat-write-early-hints-invalid-argument.js <add>'use strict'; <add> <add>const common = require('../common'); <add>if (!common.hasCrypto) common.skip('missing crypto'); <add> <add>const assert = require('node:assert'); <add>const http2 = require('node:http2'); <add>const debug = require('node:util').debuglog('test'); <add> <add>const testResBody = 'response content'; <add> <add>const server = http2.createServer(); <add> <add>server.on('request', common.mustCall((req, res) => { <add> debug('Server sending early hints...'); <add> res.writeEarlyHints('bad argument value'); <add> <add> debug('Server sending full response...'); <add> res.end(testResBody); <add>})); <add> <add>server.listen(0); <add> <add>server.on('listening', common.mustCall(() => { <add> const client = http2.connect(`http://localhost:${server.address().port}`); <add> const req = client.request(); <add> <add> debug('Client sending request...'); <add> <add> req.on('headers', common.mustNotCall()); <add> <add> process.on('uncaughtException', (err) => { <add> debug(`Caught an exception: ${JSON.stringify(err)}`); <add> if (err.name === 'AssertionError') throw err; <add> assert.strictEqual(err.code, 'ERR_INVALID_ARG_VALUE'); <add> process.exit(0); <add> }); <add>})); <ide><path>test/parallel/test-http2-compat-write-early-hints.js <add>'use strict'; <add> <add>const common = require('../common'); <add>if (!common.hasCrypto) common.skip('missing crypto'); <add> <add>const assert = require('node:assert'); <add>const http2 = require('node:http2'); <add>const debug = require('node:util').debuglog('test'); <add> <add>const testResBody = 'response content'; <add> <add>{ <add> // Happy flow - string argument <add> <add> const server = http2.createServer(); <add> <add> server.on('request', common.mustCall((req, res) => { <add> debug('Server sending early hints...'); <add> res.writeEarlyHints('</styles.css>; rel=preload; as=style'); <add> <add> debug('Server sending full response...'); <add> res.end(testResBody); <add> })); <add> <add> server.listen(0); <add> <add> server.on('listening', common.mustCall(() => { <add> const client = http2.connect(`http://localhost:${server.address().port}`); <add> const req = client.request(); <add> <add> debug('Client sending request...'); <add> <add> req.on('headers', common.mustCall((headers) => { <add> assert.notStrictEqual(headers, undefined); <add> assert.strictEqual(headers[':status'], 103); <add> assert.strictEqual(headers.link, '</styles.css>; rel=preload; as=style'); <add> })); <add> <add> req.on('response', common.mustCall((headers) => { <add> assert.strictEqual(headers[':status'], 200); <add> })); <add> <add> let data = ''; <add> req.on('data', common.mustCallAtLeast((d) => data += d)); <add> <add> req.on('end', common.mustCall(() => { <add> debug('Got full response.'); <add> assert.strictEqual(data, testResBody); <add> client.close(); <add> server.close(); <add> })); <add> })); <add>} <add> <add>{ <add> // Happy flow - array argument <add> <add> const server = http2.createServer(); <add> <add> server.on('request', common.mustCall((req, res) => { <add> debug('Server sending early hints...'); <add> res.writeEarlyHints([ <add> '</styles.css>; rel=preload; as=style', <add> '</scripts.js>; rel=preload; as=script', <add> ]); <add> <add> debug('Server sending full response...'); <add> res.end(testResBody); <add> })); <add> <add> server.listen(0); <add> <add> server.on('listening', common.mustCall(() => { <add> const client = http2.connect(`http://localhost:${server.address().port}`); <add> const req = client.request(); <add> <add> debug('Client sending request...'); <add> <add> req.on('headers', common.mustCall((headers) => { <add> assert.notStrictEqual(headers, undefined); <add> assert.strictEqual(headers[':status'], 103); <add> assert.strictEqual( <add> headers.link, <add> '</styles.css>; rel=preload; as=style, </scripts.js>; rel=preload; as=script' <add> ); <add> })); <add> <add> req.on('response', common.mustCall((headers) => { <add> assert.strictEqual(headers[':status'], 200); <add> })); <add> <add> let data = ''; <add> req.on('data', common.mustCallAtLeast((d) => data += d)); <add> <add> req.on('end', common.mustCall(() => { <add> debug('Got full response.'); <add> assert.strictEqual(data, testResBody); <add> client.close(); <add> server.close(); <add> })); <add> })); <add>} <add> <add>{ <add> // Happy flow - empty array <add> <add> const server = http2.createServer(); <add> <add> server.on('request', common.mustCall((req, res) => { <add> debug('Server sending early hints...'); <add> res.writeEarlyHints([]); <add> <add> debug('Server sending full response...'); <add> res.end(testResBody); <add> })); <add> <add> server.listen(0); <add> <add> server.on('listening', common.mustCall(() => { <add> const client = http2.connect(`http://localhost:${server.address().port}`); <add> const req = client.request(); <add> <add> debug('Client sending request...'); <add> <add> req.on('headers', common.mustNotCall()); <add> <add> req.on('response', common.mustCall((headers) => { <add> assert.strictEqual(headers[':status'], 200); <add> })); <add> <add> let data = ''; <add> req.on('data', common.mustCallAtLeast((d) => data += d)); <add> <add> req.on('end', common.mustCall(() => { <add> debug('Got full response.'); <add> assert.strictEqual(data, testResBody); <add> client.close(); <add> server.close(); <add> })); <add> })); <add>}
11
Mixed
Ruby
raise nodatabaseerror when db does not exist
f0311c24876f78ed2054fb1e5a24d38a4d0db4ac
<ide><path>activerecord/CHANGELOG.md <ide> <ide> *Carlos Antonio da Silva* <ide> <del>* When connecting to a non-existant postgresql database, the error: <add>* When connecting to a non-existant database, the error: <ide> `ActiveRecord::NoDatabaseError` will now be raised. When being used with Rails <ide> the error message will include information on how to create a database: <del> `rake db:create` <add> `rake db:create`. Supported adapters: postgresql, mysql, mysql2, sqlite3 <ide> <ide> *Richard Schneeman* <ide> <ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb <ide> def mysql2_connection(config) <ide> client = Mysql2::Client.new(config) <ide> options = [config[:host], config[:username], config[:password], config[:database], config[:port], config[:socket], 0] <ide> ConnectionAdapters::Mysql2Adapter.new(client, logger, options, config) <add> rescue Mysql2::Error => error <add> if error.message.include?("Unknown database") <add> raise ActiveRecord::NoDatabaseError.new(error.message) <add> else <add> raise error <add> end <ide> end <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb <ide> def mysql_connection(config) <ide> default_flags |= Mysql::CLIENT_FOUND_ROWS if Mysql.const_defined?(:CLIENT_FOUND_ROWS) <ide> options = [host, username, password, database, port, socket, default_flags] <ide> ConnectionAdapters::MysqlAdapter.new(mysql, logger, options, config) <add> rescue Mysql::Error => error <add> if error.message.include?("Unknown database") <add> raise ActiveRecord::NoDatabaseError.new(error.message) <add> else <add> raise error <add> end <ide> end <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def sqlite3_connection(config) <ide> db.busy_timeout(ConnectionAdapters::SQLite3Adapter.type_cast_config_to_integer(config[:timeout])) if config[:timeout] <ide> <ide> ConnectionAdapters::SQLite3Adapter.new(db, logger, config) <add> rescue Errno::ENOENT => error <add> if error.message.include?("No such file or directory") <add> raise ActiveRecord::NoDatabaseError.new(error.message) <add> else <add> raise error <add> end <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb <ide> def setup <ide> eosql <ide> end <ide> <add> def test_bad_connection_mysql <add> assert_raise ActiveRecord::NoDatabaseError do <add> connection = ActiveRecord::Base.mysql_connection(adapter: "mysql", database: "should_not_exist-cinco-dog-db") <add> connection.exec_query('drop table if exists ex') <add> end <add> end <add> <add> def test_bad_connection_mysql2 <add> assert_raise ActiveRecord::NoDatabaseError do <add> connection = ActiveRecord::Base.mysql2_connection(adapter: "mysql2", database: "should_not_exist-cinco-dog-db") <add> connection.exec_query('drop table if exists ex') <add> end <add> end <add> <ide> def test_valid_column <ide> column = @conn.columns('ex').find { |col| col.name == 'id' } <ide> assert @conn.valid_type?(column.type) <ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb <ide> def setup <ide> ActiveSupport::Notifications.subscribe('sql.active_record', @subscriber) <ide> end <ide> <add> def test_bad_connection <add> assert_raise ActiveRecord::NoDatabaseError do <add> connection = ActiveRecord::Base.sqlite3_connection(adapter: "sqlite3", database: "/tmp/should/_not/_exist/-cinco-dog.db") <add> connection.exec_query('drop table if exists ex') <add> end <add> end <add> <ide> def test_connect_with_url <ide> original_connection = ActiveRecord::Base.remove_connection <ide> tf = Tempfile.open 'whatever'
6
Go
Go
add some documentation to pkg/system
e94a48ffc8fa287c4b1b441c5308999693c58b75
<ide><path>pkg/system/lstat.go <ide> import ( <ide> "syscall" <ide> ) <ide> <add>// Lstat takes a path to a file and returns <add>// a system.Stat_t type pertaining to that file. <add>// <add>// Throws an error if the file does not exist <ide> func Lstat(path string) (*Stat_t, error) { <ide> s := &syscall.Stat_t{} <ide> err := syscall.Lstat(path, s) <ide><path>pkg/system/lstat_test.go <ide> import ( <ide> "testing" <ide> ) <ide> <add>// TestLstat tests Lstat for existing and non existing files <ide> func TestLstat(t *testing.T) { <ide> file, invalid, _, dir := prepareFiles(t) <ide> defer os.RemoveAll(dir) <ide><path>pkg/system/meminfo_linux.go <ide> var ( <ide> ErrMalformed = errors.New("malformed file") <ide> ) <ide> <del>// Retrieve memory statistics of the host system and parse them into a MemInfo <del>// type. <add>// ReadMemInfo retrieves memory statistics of the host system and returns a <add>// MemInfo type. <ide> func ReadMemInfo() (*MemInfo, error) { <ide> file, err := os.Open("/proc/meminfo") <ide> if err != nil { <ide> func ReadMemInfo() (*MemInfo, error) { <ide> return parseMemInfo(file) <ide> } <ide> <add>// parseMemInfo parses the /proc/meminfo file into <add>// a MemInfo object given a io.Reader to the file. <add>// <add>// Throws error if there are problems reading from the file <ide> func parseMemInfo(reader io.Reader) (*MemInfo, error) { <ide> meminfo := &MemInfo{} <ide> scanner := bufio.NewScanner(reader) <ide><path>pkg/system/meminfo_linux_test.go <ide> import ( <ide> "github.com/docker/docker/pkg/units" <ide> ) <ide> <add>// TestMemInfo tests parseMemInfo with a static meminfo string <ide> func TestMemInfo(t *testing.T) { <ide> const input = ` <ide> MemTotal: 1 kB <ide><path>pkg/system/mknod.go <ide> import ( <ide> "syscall" <ide> ) <ide> <add>// Mknod creates a filesystem node (file, device special file or named pipe) named path <add>// with attributes specified by mode and dev <ide> func Mknod(path string, mode uint32, dev int) error { <ide> return syscall.Mknod(path, mode, dev) <ide> } <ide><path>pkg/system/stat.go <ide> import ( <ide> "syscall" <ide> ) <ide> <add>// Stat_t type contains status of a file. It contains metadata <add>// like permission, owner, group, size, etc about a file <ide> type Stat_t struct { <ide> mode uint32 <ide> uid uint32 <ide><path>pkg/system/stat_linux.go <ide> import ( <ide> "syscall" <ide> ) <ide> <add>// fromStatT converts a syscall.Stat_t type to a system.Stat_t type <ide> func fromStatT(s *syscall.Stat_t) (*Stat_t, error) { <ide> return &Stat_t{size: s.Size, <ide> mode: s.Mode, <ide> func fromStatT(s *syscall.Stat_t) (*Stat_t, error) { <ide> mtim: s.Mtim}, nil <ide> } <ide> <add>// Stat takes a path to a file and returns <add>// a system.Stat_t type pertaining to that file. <add>// <add>// Throws an error if the file does not exist <ide> func Stat(path string) (*Stat_t, error) { <ide> s := &syscall.Stat_t{} <ide> err := syscall.Stat(path, s) <ide><path>pkg/system/stat_test.go <ide> import ( <ide> "testing" <ide> ) <ide> <add>// TestFromStatT tests fromStatT for a tempfile <ide> func TestFromStatT(t *testing.T) { <ide> file, _, _, dir := prepareFiles(t) <ide> defer os.RemoveAll(dir) <ide><path>pkg/system/stat_unsupported.go <ide> import ( <ide> "syscall" <ide> ) <ide> <add>// fromStatT creates a system.Stat_t type from a syscall.Stat_t type <ide> func fromStatT(s *syscall.Stat_t) (*Stat_t, error) { <ide> return &Stat_t{size: s.Size, <ide> mode: uint32(s.Mode), <ide><path>pkg/system/utimes_test.go <ide> import ( <ide> "testing" <ide> ) <ide> <add>// prepareFiles creates files for testing in the temp directory <ide> func prepareFiles(t *testing.T) (string, string, string, string) { <ide> dir, err := ioutil.TempDir("", "docker-system-test") <ide> if err != nil {
10
Ruby
Ruby
make digest cache work in development
40f79da8f22d301f87873669d7355346049eccf2
<ide><path>actionview/lib/action_view/digestor.rb <ide> class Digestor <ide> @@cache = ThreadSafe::Cache.new <ide> @@digest_monitor = Monitor.new <ide> <add> class PerRequestDigestCacheExpiry < Struct.new(:app) # :nodoc: <add> def call(env) <add> ActionView::Digestor.cache.clear <add> app.call(env) <add> end <add> end <add> <ide> class << self <ide> # Supported options: <ide> # <ide> def compute_and_store_digest(cache_key, options) # called under @@digest_monitor <ide> Digestor <ide> end <ide> <del> digest = klass.new(options).digest <del> # Store the actual digest if config.cache_template_loading is true <del> @@cache[cache_key] = stored_digest = digest if ActionView::Resolver.caching? <del> digest <add> @@cache[cache_key] = stored_digest = klass.new(options).digest <ide> ensure <ide> # something went wrong or ActionView::Resolver.caching? is false, make sure not to corrupt the @@cache <ide> @@cache.delete_pair(cache_key, false) if pre_stored && !stored_digest <ide><path>actionview/lib/action_view/railtie.rb <ide> class Railtie < Rails::Railtie # :nodoc: <ide> end <ide> end <ide> <add> initializer "action_view.per_request_digest_cache" do |app| <add> ActiveSupport.on_load(:action_view) do <add> if app.config.consider_all_requests_local <add> app.middleware.use ActionView::Digestor::PerRequestDigestCacheExpiry <add> end <add> end <add> end <add> <ide> initializer "action_view.setup_action_pack" do |app| <ide> ActiveSupport.on_load(:action_controller) do <ide> ActionView::RoutingUrlFor.include(ActionDispatch::Routing::UrlFor) <ide><path>actionview/test/template/digestor_test.rb <ide> def test_dependencies_via_options_results_in_different_digest <ide> assert_not_equal digest_phone, digest_fridge_phone <ide> end <ide> <del> def test_cache_template_loading <del> resolver_before = ActionView::Resolver.caching <del> ActionView::Resolver.caching = false <del> assert_digest_difference("messages/edit", true) do <del> change_template("comments/_comment") <del> end <del> ensure <del> ActionView::Resolver.caching = resolver_before <del> end <del> <ide> def test_digest_cache_cleanup_with_recursion <ide> first_digest = digest("level/_recursion") <ide> second_digest = digest("level/_recursion") <ide><path>railties/test/application/per_request_digest_cache_test.rb <add>require 'isolation/abstract_unit' <add>require 'rack/test' <add>require 'minitest/mock' <add> <add>require 'action_view' <add>require 'active_support/testing/method_call_assertions' <add> <add>class PerRequestDigestCacheTest < ActiveSupport::TestCase <add> include ActiveSupport::Testing::Isolation <add> include ActiveSupport::Testing::MethodCallAssertions <add> include Rack::Test::Methods <add> <add> setup do <add> build_app <add> add_to_config 'config.consider_all_requests_local = true' <add> <add> app_file 'app/models/customer.rb', <<-RUBY <add> class Customer < Struct.new(:name, :id) <add> extend ActiveModel::Naming <add> include ActiveModel::Conversion <add> end <add> RUBY <add> <add> app_file 'config/routes.rb', <<-RUBY <add> Rails.application.routes.draw do <add> resources :customers, only: :index <add> end <add> RUBY <add> <add> app_file 'app/controllers/customers_controller.rb', <<-RUBY <add> class CustomersController < ApplicationController <add> def index <add> render [ Customer.new('david', 1), Customer.new('dingus', 2) ] <add> end <add> end <add> RUBY <add> <add> app_file 'app/views/customers/_customer.html.erb', <<-RUBY <add> <% cache customer do %> <add> <%= customer.name %> <add> <% end %> <add> RUBY <add> <add> require "#{app_path}/config/environment" <add> end <add> <add> teardown :teardown_app <add> <add> test "digests are reused when rendering the same template twice" do <add> get '/customers' <add> assert_equal 200, last_response.status <add> <add> assert_equal [ '8ba099b7749542fe765ff34a6824d548' ], ActionView::Digestor.cache.values <add> assert_equal %w(david dingus), last_response.body.split.map(&:strip) <add> end <add> <add> test "template digests are cleared before a request" do <add> assert_called(ActionView::Digestor.cache, :clear) do <add> get '/customers' <add> assert_equal 200, last_response.status <add> end <add> end <add>end
4
Javascript
Javascript
use regex to hide hikes
c7de26f3d9f877bb47807937d8239cb2db09f8e4
<ide><path>index.js <ide> destroy() <ide> challenge.order = order; <ide> challenge.suborder = index + 1; <ide> challenge.block = block; <del> challenge.superBlock = superBlock; <ide> challenge.isBeta = challenge.isBeta || isBeta; <ide> challenge.time = challengeSpec.time; <add> challenge.superBlock = superBlock <add> .split('-') <add> .map(function(word) { <add> return _.capitalize(word); <add> }) <add> .join(' '); <ide> <ide> return challenge; <ide> });
1
Python
Python
use consistent test names
89525ef345a39ccb0d1c5ca986bd5c1c71ea89c5
<ide><path>spacy/tests/tagger/test_morph_exceptions.py <ide> import pytest <ide> <ide> <del>def test_load_exc(en_tokenizer): <add>def test_tagger_load_morph_exc(en_tokenizer): <ide> text = "I like his style." <ide> tags = ['PRP', 'VBP', 'PRP$', 'NN', '.'] <ide> morph_exc = {'PRP$': {'his': {'L': '-PRP-', 'person': 3, 'case': 2}}}
1