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
Go
Go
normalize comment formatting
a567ae3c31c4d3b71ab34dac4dc70314c5de65ac
<ide><path>client/image_import.go <ide> import ( <ide> // It returns the JSON content in the response body. <ide> func (cli *Client) ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { <ide> if ref != "" { <del> //Check if the given image name can be resolved <add> // Check if the given image name can be resolved <ide> if _, err := reference.ParseNormalizedNamed(ref); err != nil { <ide> return nil, err <ide> }
1
Python
Python
fix bug in pt speech-encoder-decoder
60ba48205e4ec070780e8cb8d461421b77432bad
<ide><path>src/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py <ide> def forward( <ide> argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_") <ide> } <ide> <del> if encoder_outputs is None and inputs is None: <del> if input_values is not None and input_features is not None: <del> raise ValueError("You cannot specify both input_values and input_features at the same time") <del> elif input_values is not None: <del> inputs = input_values <del> elif input_features is not None: <del> inputs = input_features <del> else: <del> raise ValueError("You have to specify either input_values or input_features") <add> if encoder_outputs is None: <add> if inputs is None: <add> if input_values is not None and input_features is not None: <add> raise ValueError("You cannot specify both input_values and input_features at the same time") <add> elif input_values is not None: <add> inputs = input_values <add> elif input_features is not None: <add> inputs = input_features <add> else: <add> raise ValueError("You have to specify either input_values or input_features") <ide> <ide> encoder_outputs = self.encoder( <ide> inputs, <ide><path>tests/test_modeling_speech_encoder_decoder.py <ide> def check_encoder_decoder_model( <ide> outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) <ide> ) <ide> <add> def check_encoder_decoder_model_with_inputs( <add> self, <add> config, <add> attention_mask, <add> decoder_config, <add> decoder_input_ids, <add> decoder_attention_mask, <add> input_values=None, <add> input_features=None, <add> **kwargs <add> ): <add> inputs = input_values if input_features is None else input_features <add> encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) <add> enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) <add> enc_dec_model.to(torch_device) <add> <add> outputs_encoder_decoder = enc_dec_model( <add> inputs, <add> decoder_input_ids=decoder_input_ids, <add> attention_mask=attention_mask, <add> decoder_attention_mask=decoder_attention_mask, <add> output_hidden_states=True, <add> ) <add> self.assertEqual( <add> outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) <add> ) <add> outputs_encoder_decoder_kwarg = enc_dec_model( <add> inputs=inputs, <add> decoder_input_ids=decoder_input_ids, <add> attention_mask=attention_mask, <add> decoder_attention_mask=decoder_attention_mask, <add> output_hidden_states=True, <add> ) <add> self.assertEqual( <add> outputs_encoder_decoder_kwarg["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) <add> ) <add> <ide> def check_encoder_decoder_model_from_pretrained( <ide> self, <ide> config, <ide> def test_encoder_decoder_model(self): <ide> input_ids_dict = self.prepare_config_and_inputs() <ide> self.check_encoder_decoder_model(**input_ids_dict) <ide> <add> def test_encoder_decoder_model_with_inputs(self): <add> input_ids_dict = self.prepare_config_and_inputs() <add> self.check_encoder_decoder_model_with_inputs(**input_ids_dict) <add> <ide> def test_encoder_decoder_model_from_pretrained_configs(self): <ide> input_ids_dict = self.prepare_config_and_inputs() <ide> self.check_encoder_decoder_model_from_pretrained_configs(**input_ids_dict)
2
Javascript
Javascript
update response data types
fd0b1ebfc71f9092e950f62359317a061c7840b3
<ide><path>src/ngMock/angular-mocks.js <ide> function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) { <ide> * order to change how a matched request is handled. <ide> * <ide> * - respond – <del> * `{function([status,] data[, headers, statusText]) <del> * | function(function(method, url, data, headers, params)}` <add> * ```js <add> * {function([status,] data[, headers, statusText]) <add> * | function(function(method, url, data, headers, params)} <add> * ``` <ide> * – The respond method takes a set of static data to be returned or a function that can <del> * return an array containing response status (number), response data (string), response <del> * headers (Object), and the text for the status (string). The respond method returns the <del> * `requestHandler` object for possible overrides. <add> * return an array containing response status (number), response data (Array|Object|string), <add> * response headers (Object), and the text for the status (string). The respond method returns <add> * the `requestHandler` object for possible overrides. <ide> */ <ide> $httpBackend.when = function(method, url, data, headers, keys) { <ide> var definition = new MockHttpExpectation(method, url, data, headers, keys), <ide> function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) { <ide> * order to change how a matched request is handled. <ide> * <ide> * - respond – <del> * `{function([status,] data[, headers, statusText]) <del> * | function(function(method, url, data, headers, params)}` <add> * ``` <add> * { function([status,] data[, headers, statusText]) <add> * | function(function(method, url, data, headers, params)} <add> * ``` <ide> * – The respond method takes a set of static data to be returned or a function that can <del> * return an array containing response status (number), response data (string), response <del> * headers (Object), and the text for the status (string). The respond method returns the <del> * `requestHandler` object for possible overrides. <add> * return an array containing response status (number), response data (Array|Object|string), <add> * response headers (Object), and the text for the status (string). The respond method returns <add> * the `requestHandler` object for possible overrides. <ide> */ <ide> $httpBackend.expect = function(method, url, data, headers, keys) { <ide> var expectation = new MockHttpExpectation(method, url, data, headers, keys), <ide> angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) { <ide> * `respond` or `passThrough` again in order to change how a matched request is handled. <ide> * <ide> * - respond – <del> * `{function([status,] data[, headers, statusText]) <del> * | function(function(method, url, data, headers, params)}` <add> * ``` <add> * { function([status,] data[, headers, statusText]) <add> * | function(function(method, url, data, headers, params)} <add> * ``` <ide> * – The respond method takes a set of static data to be returned or a function that can return <del> * an array containing response status (number), response data (string), response headers <del> * (Object), and the text for the status (string). <add> * an array containing response status (number), response data (Array|Object|string), response <add> * headers (Object), and the text for the status (string). <ide> * - passThrough – `{function()}` – Any request matching a backend definition with <ide> * `passThrough` handler will be passed through to the real backend (an XHR request will be made <ide> * to the server.)
1
Text
Text
add docs for named build stages
877ac98e44f2b1d9af6319ca07d232a3cd929d39
<ide><path>docs/reference/builder.md <ide> the first pattern, followed by one or more `!` exception patterns. <ide> <ide> ## FROM <ide> <del> FROM <image> <add> FROM <image> [AS <name>] <ide> <ide> Or <ide> <del> FROM <image>:<tag> <add> FROM <image>[:<tag>] [AS <name>] <ide> <ide> Or <ide> <del> FROM <image>@<digest> <add> FROM <image>[@<digest>] [AS <name>] <ide> <del>The `FROM` instruction sets the [*Base Image*](glossary.md#base-image) <del>for subsequent instructions. As such, a valid `Dockerfile` must have `FROM` as <del>its first instruction. The image can be any valid image – it is especially easy <del>to start by **pulling an image** from the [*Public Repositories*](https://docs.docker.com/engine/tutorials/dockerrepos/). <add>The `FROM` instruction initializes a new build stage and sets the <add>[*Base Image*](glossary.md#base-image) for subsequent instructions. As such, a <add>valid `Dockerfile` must have `FROM` as its first instruction. The image can be <add>any valid image – it is especially easy to start by **pulling an image** from <add>the [*Public Repositories*](https://docs.docker.com/engine/tutorials/dockerrepos/). <ide> <ide> - `FROM` must be the first non-comment instruction in the `Dockerfile`. <ide> <del>- `FROM` can appear multiple times within a single `Dockerfile` in order to create <del>multiple images. Simply make a note of the last image ID output by the commit <del>before each new `FROM` command. <add>- `FROM` can appear multiple times within a single `Dockerfile` in order to <add>create multiple images or use one build stage as a dependency for another. <add>Simply make a note of the last image ID output by the commit before each new <add>`FROM` command. Each `FROM` command resets all the previous commands. <ide> <del>- The `tag` or `digest` values are optional. If you omit either of them, the builder <del>assumes a `latest` by default. The builder returns an error if it cannot match <del>the `tag` value. <add>- Optionally a name can be given to a new build stage. That name can be then <add>used in subsequent `FROM` and `COPY --from=<name|index>` commands to refer back <add>to the image built in this stage. <add> <add>- The `tag` or `digest` values are optional. If you omit either of them, the <add>builder assumes a `latest` tag by default. The builder returns an error if it <add>cannot match the `tag` value. <ide> <ide> ## RUN <ide> <ide> All new files and directories are created with a UID and GID of 0. <ide> > If you build using STDIN (`docker build - < somefile`), there is no <ide> > build context, so `COPY` can't be used. <ide> <add>Optionally `COPY` accepts a flag `--from=<name|index>` that can be used to set <add>the source location to a previous build stage (created with `FROM .. AS <name>`) <add>that will be used instead of a build context sent by the user. The flag also <add>accepts a numeric index assigned for all previous build stages started with <add>`FROM` command. In case a build stage with a specified name can't be found an <add>image with the same name is attempted to be used instead. <add> <ide> `COPY` obeys the following rules: <ide> <ide> - The `<src>` path must be inside the *context* of the build;
1
Ruby
Ruby
update route globbing documention in rdoc
4cbf55344d07d552b00e1522b4e208bcaaf46504
<ide><path>actionpack/lib/action_controller/routing.rb <ide> module ActionController <ide> # <ide> # map.connect '*path' , :controller => 'blog' , :action => 'unrecognized?' <ide> # <del> # will glob all remaining parts of the route that were not recognized earlier. This idiom <del> # must appear at the end of the path. The globbed values are in <tt>params[:path]</tt> in <del> # this case. <add> # will glob all remaining parts of the route that were not recognized earlier. <add> # The globbed values are in <tt>params[:path]</tt> as an array of path segments. <add> # Originally this parameter had to be at the end of the route definition, <add> # however as of Rails 2.0 this is no longer the case. <ide> # <ide> # == Route conditions <ide> #
1
PHP
PHP
implement the basic builder methods
e85364195c60cf062ed4acb1a9e2eeb822581287
<ide><path>src/View/ViewBuilder.php <ide> class ViewBuilder <ide> */ <ide> protected $options = []; <ide> <add> /** <add> * The helpers to use <add> * <add> * @var array <add> */ <add> protected $helpers = []; <add> <ide> /** <ide> * Get/set path for view files. <ide> * <del> * @param string $path Path for view files. If null returns current path. <add> * @param string|null $path Path for view files. If null returns current path. <ide> * @return string|$this <ide> */ <ide> public function viewPath($path = null) <ide> public function viewPath($path = null) <ide> /** <ide> * Get/set path for layout files. <ide> * <del> * @param string $path Path for layout files. If null returns current path. <add> * @param string|null $path Path for layout files. If null returns current path. <ide> * @return string|void <ide> */ <ide> public function layoutPath($path = null) <ide> public function layoutPath($path = null) <ide> * On by default. Setting to off means that layouts will not be <ide> * automatically applied to rendered views. <ide> * <del> * @param bool $autoLayout Boolean to turn on/off. If null returns current value. <add> * @param bool|ull $autoLayout Boolean to turn on/off. If null returns current value. <ide> * @return bool|$this <ide> */ <ide> public function autoLayout($autoLayout = null) <ide> public function autoLayout($autoLayout = null) <ide> /** <ide> * The plugin name to use <ide> * <del> * @param string $theme Plugin name. If null returns current plugin. <add> * @param string|null $name Plugin name. If null returns current plugin. <ide> * @return string|$this <ide> */ <del> public function plugin($theme = null) <add> public function plugin($name = null) <ide> { <add> if ($name === null) { <add> return $this->plugin; <add> } <add> <add> $this->plugin = $name; <add> return $this; <ide> } <ide> <ide> /** <ide> * The helpers to use <ide> * <del> * @param array $helpers Helpers to use. <add> * @param array|null $helpers Helpers to use. <ide> * @return array|$this <ide> */ <del> public function helpers($helpers = null) <add> public function helpers(array $helpers = null) <ide> { <add> if ($helpers === null) { <add> return $this->helpers; <add> } <add> <add> $this->helpers = array_merge($this->helpers, $helpers); <add> return $this; <ide> } <ide> <ide> /** <ide> * The view theme to use. <ide> * <del> * @param string $theme Theme name. If null returns current theme. <add> * @param string|null $theme Theme name. If null returns current theme. <ide> * @return string|$this <ide> */ <ide> public function theme($theme = null) <ide> public function theme($theme = null) <ide> * Get/set the name of the view file to render. The name specified is the <ide> * filename in /app/Template/<SubFolder> without the .ctp extension. <ide> * <del> * @param string $name View file name to set. If null returns current name. <add> * @param string|null $name View file name to set. If null returns current name. <ide> * @return string|$this <ide> */ <ide> public function view($name = null) <ide> public function view($name = null) <ide> * The name specified is the filename of the layout in /app/Template/Layout <ide> * without the .ctp extension. <ide> * <del> * @param string $name Layout file name to set. If null returns current name. <add> * @param string|null $name Layout file name to set. If null returns current name. <ide> * @return string|$this <ide> */ <ide> public function layout($name = null) <ide> public function layout($name = null) <ide> * @param array|null $options Either an array of options or null to get current options. <ide> * @return array|$this <ide> */ <del> public function options($options = null) <add> public function options(array $options = null) <ide> { <add> if ($options === null) { <add> return $this->options; <add> } <add> $this->options = array_merge($this->options, $options); <add> return $this; <ide> } <ide> <ide> /** <ide> * Get/set the view name <ide> * <add> * @param string|null $name The name of the view <ide> * @return array|$this <ide> */ <del> public function name($vars = null) <add> public function name($name = null) <ide> { <add> if ($name === null) { <add> return $this->name; <add> } <add> $this->name = $name; <add> return $this; <ide> } <ide> <ide> /** <ide> * Get/set the view classname <ide> * <add> * @param string|null $name The class name for the view. Can <add> * be a plugin.class name reference, a short alias, or a fully <add> * namespaced name. <ide> * @return array|$this <ide> */ <ide> public function className($name = null) <ide> { <add> if ($name === null) { <add> return $this->className; <add> } <add> $this->className = $name; <add> return $this; <ide> } <ide> <ide> /**
1
Python
Python
add keyword allow_zero 2nd
dc82b3ee7eb7c4134f86a83eb465a21e1b620609
<ide><path>keras/layers/local.py <ide> def __init__(self, <ide> super(LocallyConnected2D, self).__init__(**kwargs) <ide> self.filters = filters <ide> self.kernel_size = conv_utils.normalize_tuple(kernel_size, 2, 'kernel_size') <del> self.strides = conv_utils.normalize_tuple(strides, 2, 'strides', True) <add> self.strides = conv_utils.normalize_tuple(strides, 2, 'strides', allow_zero=True) <ide> self.padding = conv_utils.normalize_padding(padding) <ide> if self.padding != 'valid' and implementation == 1: <ide> raise ValueError('Invalid border mode for LocallyConnected2D '
1
Ruby
Ruby
ensure that using correct alias tracker
135437cbb660ec0db5dc2cca1c78c6ad985ec807
<ide><path>activerecord/test/models/membership.rb <ide> class Membership < ActiveRecord::Base <add> enum type: %i(Membership CurrentMembership SuperMembership SelectedMembership TenantMembership) <ide> belongs_to :member <ide> belongs_to :club <ide> end <ide><path>activerecord/test/schema/schema.rb <ide> t.datetime :joined_on <ide> t.integer :club_id, :member_id <ide> t.boolean :favourite, default: false <del> t.string :type <add> t.integer :type <ide> end <ide> <ide> create_table :member_types, force: true do |t|
2
Go
Go
fix a panic where run [] would be supplied
39343b86182b4e997dc991645729ae130bd0f5f2
<ide><path>builder/internals.go <ide> func (b *Builder) create() (*daemon.Container, error) { <ide> b.TmpContainers[c.ID] = struct{}{} <ide> fmt.Fprintf(b.OutStream, " ---> Running in %s\n", utils.TruncateID(c.ID)) <ide> <del> // override the entry point that may have been picked up from the base image <del> c.Path = config.Cmd[0] <del> c.Args = config.Cmd[1:] <add> if config.Cmd != nil { <add> // override the entry point that may have been picked up from the base image <add> c.Path = config.Cmd[0] <add> c.Args = config.Cmd[1:] <add> } else { <add> config.Cmd = []string{} <add> } <ide> <ide> return c, nil <ide> } <ide><path>integration-cli/docker_cli_build_test.go <ide> import ( <ide> "github.com/docker/docker/pkg/archive" <ide> ) <ide> <add>func TestBuildJSONEmptyRun(t *testing.T) { <add> name := "testbuildjsonemptyrun" <add> defer deleteImages(name) <add> <add> _, err := buildImage( <add> name, <add> ` <add> FROM busybox <add> RUN [] <add> `, <add> true) <add> <add> if err != nil { <add> t.Fatal("error when dealing with a RUN statement with empty JSON array") <add> } <add> <add> logDone("build - RUN with an empty array should not panic") <add>} <add> <ide> func TestBuildEmptyWhitespace(t *testing.T) { <ide> name := "testbuildemptywhitespace" <ide> defer deleteImages(name)
2
Text
Text
fix typo in readme
97a6a62a6be874c4c6caa66cb6a0778011f8bfbd
<ide><path>examples/with-asset-imports/README.md <ide> now <ide> <ide> ## The idea behind the example <ide> <del>This example shows how to enable the impors of assets (images, videos, etc.) and get a URL pointing to `/static`. <add>This example shows how to enable the imports of assets (images, videos, etc.) and get a URL pointing to `/static`. <ide> <ide> This is also configurable to point to a CDN changing the `baseUri` to the CDN domain, something similar to this: <ide>
1
Ruby
Ruby
clarify desc calculation
b554c8bcca3042f7e3664f7a892c285201cfbd39
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_desc <ide> # Make sure the formula name plus description is no longer than 80 characters <ide> linelength = formula.full_name.length + ": ".length + desc.length <ide> if linelength > 80 <del> problem "Description is too long. \"name: desc\" should be less than 80 characters (currently #{linelength})." <add> problem <<-EOS.undent <add> Description is too long. \"name: desc\" should be less than 80 characters. <add> Length is calculated as #{formula.full_name} + desc. (currently #{linelength}) <add> EOS <ide> end <ide> <ide> if desc =~ %r[[Cc]ommandline]
1
Javascript
Javascript
fix jshint complaint about negation
fcfe4fd2e146c24d7ed4426d63ded907137bce9d
<ide><path>packages/ember-metal/lib/watching.js <ide> Wp.copy = function(obj) { <ide> var ret = new ChainNode(null, null, obj, this._separator); <ide> var paths = this._paths, path; <ide> for(path in paths) { <del> if (!(paths[path] > 0)) continue; // this check will also catch non-number vals. <add> if (paths[path] <= 0) continue; // this check will also catch non-number vals. <ide> ret.add(path); <ide> } <ide> return ret; <ide><path>packages/ember-runtime/tests/suites/enumerable/find.js <ide> suite.test('every should stop invoking when you return true', function() { <ide> exp = cnt, <ide> found = [], result; <ide> <del> result = obj.find(function(i) { found.push(i); return !(--cnt>0); }); <add> result = obj.find(function(i) { found.push(i); return --cnt >= 0; }); <ide> equal(result, ary[exp-1], 'return value of obj.find'); <ide> equal(found.length, exp, 'should invoke proper number of times'); <ide> deepEqual(found, ary.slice(0,-2), 'items passed during find() should match'); <ide><path>packages/ember-runtime/tests/suites/enumerable/some.js <ide> suite.test('every should stop invoking when you return true', function() { <ide> exp = cnt, <ide> found = [], result; <ide> <del> result = obj.some(function(i) { found.push(i); return !(--cnt>0); }); <add> result = obj.some(function(i) { found.push(i); return --cnt <= 0; }); <ide> equal(result, true, 'return value of obj.some'); <ide> equal(found.length, exp, 'should invoke proper number of times'); <ide> deepEqual(found, ary.slice(0,-2), 'items passed during some() should match');
3
PHP
PHP
remove constraint support for sqlite
b3c383d1a86b7d80b6d67a20cc7a7f21ac776ab7
<ide><path>src/Database/Connection.php <ide> public function enableForeignKeys() <ide> $this->execute($this->_driver->enableForeignKeySql())->closeCursor(); <ide> } <ide> <add> /** <add> * Returns whether the driver supports adding or dropping constraints <add> * to already created tables. <add> * <add> * @return bool true if driver supports dynamic constraints <add> */ <add> public function supportsDynamicConstraints() <add> { <add> return $this->_driver->supportsDynamicConstraints(); <add> } <add> <ide> /** <ide> * {@inheritDoc} <ide> * <ide><path>src/Database/Driver.php <ide> abstract public function disableForeignKeySQL(); <ide> */ <ide> abstract public function enableForeignKeySQL(); <ide> <add> /** <add> * Returns whether the driver supports adding or dropping constraints <add> * to already created tables. <add> * <add> * @return bool true if driver supports dynamic constraints <add> */ <add> abstract public function supportsDynamicConstraints(); <add> <ide> /** <ide> * Returns whether this driver supports save points for nested transactions <ide> * <ide><path>src/Database/Driver/Mysql.php <ide> public function prepare($query) <ide> } <ide> return $result; <ide> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public function supportsDynamicConstraints() <add> { <add> return true; <add> } <ide> } <ide><path>src/Database/Driver/Postgres.php <ide> public function setSchema($schema) <ide> $this->connect(); <ide> $this->_connection->exec('SET search_path TO ' . $this->_connection->quote($schema)); <ide> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public function supportsDynamicConstraints() <add> { <add> return true; <add> } <ide> } <ide><path>src/Database/Driver/Sqlite.php <ide> public function prepare($query) <ide> } <ide> return $result; <ide> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public function supportsDynamicConstraints() <add> { <add> return false; <add> } <ide> } <ide><path>src/Database/Driver/Sqlserver.php <ide> public function prepare($query) <ide> $statement = $this->_connection->prepare($isObject ? $query->sql() : $query, $options); <ide> return new SqlserverStatement($statement, $this); <ide> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public function supportsDynamicConstraints() <add> { <add> return true; <add> } <ide> } <ide><path>src/Database/Schema/SqliteSchema.php <ide> */ <ide> namespace Cake\Database\Schema; <ide> <add>use Cake\Core\Configure; <ide> use Cake\Database\Exception; <add>use RuntimeException; <ide> <ide> /** <ide> * Schema management/reflection features for Sqlite <ide> public function constraintSql(Table $table, $name) <ide> <ide> /** <ide> * {@inheritDoc} <add> * <add> * SQLite can not properly handle adding a constraint to an existing table. <add> * This method is no-op <ide> */ <ide> public function addConstraintSql(Table $table) <ide> { <del> $tmpTableName = $this->_driver->quoteIdentifier('tmp_' . $table->name()); <del> $tableName = $this->_driver->quoteIdentifier($table->name()); <del> <del> $columns = $indexes = $constraints = []; <del> foreach ($table->columns() as $column) { <del> $columns[] = $this->columnSql($table, $column); <del> } <del> <del> foreach ($table->constraints() as $constraint) { <del> $constraints[] = $this->constraintSql($table, $constraint); <del> } <del> <del> foreach ($table->indexes() as $index) { <del> $indexes[] = $this->indexSql($table, $index); <del> } <del> $createSql = $this->createTableSql($table, $columns, $constraints, $indexes); <del> <del> $columnsList = implode(', ', $table->columns()); <del> $copySql = sprintf( <del> 'INSERT INTO %s(%s) SELECT %s FROM %s', <del> $tableName, <del> $columnsList, <del> $columnsList, <del> $tmpTableName <del> ); <del> <del> $dropSql = sprintf('DROP TABLE IF EXISTS %s', $tmpTableName); <del> <del> $sql = [ <del> $dropSql, <del> sprintf('ALTER TABLE %s RENAME TO %s', $tableName, $tmpTableName), <del> $createSql[0], <del> $copySql, <del> $dropSql <del> ]; <del> <del> return $sql; <add> return []; <ide> } <ide> <ide> /** <ide> * {@inheritDoc} <add> * <add> * SQLite can not properly handle dropping a constraint to an existing table. <add> * This method is no-op <ide> */ <ide> public function dropConstraintSql(Table $table) <ide> { <del> $tmpTableName = $this->_driver->quoteIdentifier('tmp_' . $table->name()); <del> $tableName = $this->_driver->quoteIdentifier($table->name()); <del> <del> $columns = []; <del> foreach ($table->columns() as $column) { <del> $columns[$column] = $this->columnSql($table, $column); <del> } <del> <del> $indexes = []; <del> foreach ($table->indexes() as $index) { <del> $indexes[$index] = $this->indexSql($table, $index); <del> } <del> <del> $constraints = []; <del> foreach ($table->constraints() as $constraint) { <del> $constraintDefinition = $table->constraint($constraint); <del> if ($constraintDefinition['type'] == Table::CONSTRAINT_FOREIGN) { <del> $table->dropConstraint($constraint); <del> } else { <del> $constraints[$constraint] = $this->constraintSql($table, $constraint); <del> } <del> } <del> $createSql = $this->createTableSql($table, $columns, $constraints, $indexes); <del> <del> $columnsList = implode(', ', $table->columns()); <del> $copySql = sprintf( <del> 'INSERT INTO %s(%s) SELECT %s FROM %s', <del> $tableName, <del> $columnsList, <del> $columnsList, <del> $tmpTableName <del> ); <del> <del> $dropSql = sprintf('DROP TABLE IF EXISTS %s', $tmpTableName); <del> $sql = [ <del> $dropSql, <del> sprintf('ALTER TABLE %s RENAME TO %s', $tableName, $tmpTableName), <del> $createSql[0], <del> $copySql, <del> $dropSql <del> ]; <del> <del> return $sql; <add> return []; <ide> } <ide> <ide> /** <ide><path>src/TestSuite/Fixture/TestFixture.php <ide> namespace Cake\TestSuite\Fixture; <ide> <ide> use Cake\Core\Exception\Exception as CakeException; <add>use Cake\Database\Driver\Sqlite; <ide> use Cake\Database\Schema\Table; <ide> use Cake\Datasource\ConnectionInterface; <ide> use Cake\Datasource\ConnectionManager; <ide> public function init() <ide> */ <ide> protected function _schemaFromFields() <ide> { <add> $connection = ConnectionManager::get($this->connection()); <ide> $this->_schema = new Table($this->table); <ide> foreach ($this->fields as $field => $data) { <ide> if ($field === '_constraints' || $field === '_indexes' || $field === '_options') { <ide> protected function _schemaFromFields() <ide> } <ide> if (!empty($this->fields['_constraints'])) { <ide> foreach ($this->fields['_constraints'] as $name => $data) { <del> if ($data['type'] !== Table::CONSTRAINT_FOREIGN) { <add> if (!$connection->supportsDynamicConstraints() || $data['type'] !== Table::CONSTRAINT_FOREIGN) { <ide> $this->_schema->addConstraint($name, $data); <ide> } else { <ide> $this->_constraints[$name] = $data; <ide> public function createConstraints(ConnectionInterface $db) <ide> return true; <ide> } <ide> <del> $db->disableForeignKeys(); <ide> try { <ide> foreach ($sql as $stmt) { <ide> $db->execute($stmt)->closeCursor(); <ide> public function dropConstraints(ConnectionInterface $db) <ide> return true; <ide> } <ide> <del> $db->disableForeignKeys(); <ide> try { <ide> foreach ($sql as $stmt) { <ide> $db->execute($stmt)->closeCursor(); <ide><path>tests/Fixture/OrdersFixture.php <ide> class OrdersFixture extends TestFixture <ide> 'primary' => [ <ide> 'type' => 'primary', 'columns' => ['id'] <ide> ], <del> 'product_id_fk' => [ <add> 'product_category_fk' => [ <ide> 'type' => 'foreign', <ide> 'columns' => ['product_category', 'product_id'], <ide> 'references' => ['products', ['category', 'id']], <ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php <ide> public function testAddConstraintSql() <ide> $connection->expects($this->any())->method('driver') <ide> ->will($this->returnValue($driver)); <ide> <del> $table = (new Table('posts')) <del> ->addColumn('author_id', [ <del> 'type' => 'integer', <del> 'null' => false <del> ]) <del> ->addColumn('category_id', [ <del> 'type' => 'integer', <del> 'null' => false <del> ]) <del> ->addColumn('category_name', [ <del> 'type' => 'integer', <del> 'null' => false <del> ]) <del> ->addConstraint('author_fk', [ <del> 'type' => 'foreign', <del> 'columns' => ['author_id'], <del> 'references' => ['authors', 'id'], <del> 'update' => 'cascade', <del> 'delete' => 'cascade' <del> ]) <del> ->addConstraint('category_fk', [ <del> 'type' => 'foreign', <del> 'columns' => ['category_id', 'category_name'], <del> 'references' => ['categories', ['id', 'name']], <del> 'update' => 'cascade', <del> 'delete' => 'cascade' <del> ]); <add> $table = new Table('posts'); <ide> <del> $expected = [ <del> 'DROP TABLE IF EXISTS "tmp_posts"', <del> 'ALTER TABLE "posts" RENAME TO "tmp_posts"', <del> 'CREATE TABLE "posts" ( <del>"author_id" INTEGER NOT NULL, <del>"category_id" INTEGER NOT NULL, <del>"category_name" INTEGER NOT NULL, <del>CONSTRAINT "author_fk" FOREIGN KEY ("author_id") REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE CASCADE, <del>CONSTRAINT "category_fk" FOREIGN KEY ("category_id", "category_name") REFERENCES "categories" ("id", "name") ON UPDATE CASCADE ON DELETE CASCADE <del>)', <del> 'INSERT INTO "posts"(author_id, category_id, category_name) SELECT author_id, category_id, category_name FROM "tmp_posts"', <del> 'DROP TABLE IF EXISTS "tmp_posts"' <del> ]; <ide> $result = $table->addConstraintSql($connection); <del> $this->assertCount(5, $result); <del> $this->assertTextEquals($expected, $result); <add> $this->assertEmpty($result); <ide> } <ide> <ide> /** <ide> public function testDropConstraintSql() <ide> $connection->expects($this->any())->method('driver') <ide> ->will($this->returnValue($driver)); <ide> <del> $table = (new Table('posts')) <del> ->addColumn('author_id', [ <del> 'type' => 'integer', <del> 'null' => false <del> ]) <del> ->addColumn('category_id', [ <del> 'type' => 'integer', <del> 'null' => false <del> ]) <del> ->addColumn('category_name', [ <del> 'type' => 'integer', <del> 'null' => false <del> ]) <del> ->addConstraint('author_fk', [ <del> 'type' => 'foreign', <del> 'columns' => ['author_id'], <del> 'references' => ['authors', 'id'], <del> 'update' => 'cascade', <del> 'delete' => 'cascade' <del> ]) <del> ->addConstraint('category_fk', [ <del> 'type' => 'foreign', <del> 'columns' => ['category_id', 'category_name'], <del> 'references' => ['categories', ['id', 'name']], <del> 'update' => 'cascade', <del> 'delete' => 'cascade' <del> ]); <del> <del> $expected = [ <del> 'DROP TABLE IF EXISTS "tmp_posts"', <del> 'ALTER TABLE "posts" RENAME TO "tmp_posts"', <del> 'CREATE TABLE "posts" ( <del>"author_id" INTEGER NOT NULL, <del>"category_id" INTEGER NOT NULL, <del>"category_name" INTEGER NOT NULL <del>)', <del> 'INSERT INTO "posts"(author_id, category_id, category_name) SELECT author_id, category_id, category_name FROM "tmp_posts"', <del> 'DROP TABLE IF EXISTS "tmp_posts"' <del> ]; <add> $table = new Table('posts'); <ide> $result = $table->dropConstraintSql($connection); <del> $this->assertCount(5, $result); <del> $this->assertTextEquals($expected, $result); <add> $this->assertEmpty($result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Database/Schema/TableTest.php <ide> public function testConstraintForeignKey() <ide> public function testConstraintForeignKeyTwoColumns() <ide> { <ide> $table = TableRegistry::get('Orders'); <del> $compositeConstraint = $table->schema()->constraint('product_id_fk'); <add> $compositeConstraint = $table->schema()->constraint('product_category_fk'); <ide> $expected = [ <ide> 'type' => 'foreign', <ide> 'columns' => [ <ide> public function testConstraintForeignKeyTwoColumns() <ide> <ide> $this->assertEquals($expected, $compositeConstraint); <ide> <del> $expectedSubstring = 'CONSTRAINT <product_id_fk> FOREIGN KEY \(<product_category>, <product_id>\)' . <add> $expectedSubstring = 'CONSTRAINT <product_category_fk> FOREIGN KEY \(<product_category>, <product_id>\)' . <ide> ' REFERENCES <products> \(<category>, <id>\)'; <ide> <ide> $this->assertQuotedQuery($expectedSubstring, $table->schema()->createSql(ConnectionManager::get('test'))[0]);
11
Text
Text
update doc with go_backwards option
f8b0c7e2e3e24f8aeb66745da510d89a4ece24b6
<ide><path>docs/sources/layers/recurrent.md <ide> Fully connected RNN where output is to fed back to input. <ide> - __return_sequences__: Boolean. Whether to return the last output in the output sequence, or the full sequence. <ide> - __input_dim__: dimensionality of the input (integer). This argument (or alternatively, the keyword argument `input_shape`) is required when using this layer as the first layer in a model. <ide> - __input_length__: Length of input sequences, when it is constant. This argument is required if you are going to connect `Flatten` then `Dense` layers upstream (without it, the shape of the dense outputs cannot be computed). <add> - __go_backwards__: Boolean (Default False). Process the input sequence backwards. <ide> <ide> --- <ide> <ide> Not a particularly useful model, included for demonstration purposes. <ide> - __return_sequences__: Boolean. Whether to return the last output in the output sequence, or the full sequence. <ide> - __input_dim__: dimensionality of the input (integer). This argument (or alternatively, the keyword argument `input_shape`) is required when using this layer as the first layer in a model. <ide> - __input_length__: Length of input sequences, when it is constant. This argument is required if you are going to connect `Flatten` then `Dense` layers upstream (without it, the shape of the dense outputs cannot be computed). <add> - __go_backwards__: Boolean (Default False). Process the input sequence backwards. <ide> <ide> <ide> --- <ide> Gated Recurrent Unit - Cho et al. 2014. <ide> - __return_sequences__: Boolean. Whether to return the last output in the output sequence, or the full sequence. <ide> - __input_dim__: dimensionality of the input (integer). This argument (or alternatively, the keyword argument `input_shape`) is required when using this layer as the first layer in a model. <ide> - __input_length__: Length of input sequences, when it is constant. This argument is required if you are going to connect `Flatten` then `Dense` layers upstream (without it, the shape of the dense outputs cannot be computed). <add> - __go_backwards__: Boolean (Default False). Process the input sequence backwards. <ide> <ide> - __References__: <ide> - [On the Properties of Neural Machine Translation: Encoder–Decoder Approaches](http://www.aclweb.org/anthology/W14-4012) <ide> Long-Short Term Memory unit - Hochreiter 1997. <ide> - __return_sequences__: Boolean. Whether to return the last output in the output sequence, or the full sequence. <ide> - __input_dim__: dimensionality of the input (integer). This argument (or alternatively, the keyword argument `input_shape`) is required when using this layer as the first layer in a model. <ide> - __input_length__: Length of input sequences, when it is constant. This argument is required if you are going to connect `Flatten` then `Dense` layers upstream (without it, the shape of the dense outputs cannot be computed). <add> - __go_backwards__: Boolean (Default False). Process the input sequence backwards. <ide> <ide> - __References__: <ide> - [Long short-term memory](http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf) (original 1997 paper) <ide> Top 3 RNN architectures evolved from the evaluation of thousands of models. Serv <ide> - __return_sequences__: Boolean. Whether to return the last output in the output sequence, or the full sequence. <ide> - __input_dim__: dimensionality of the input (integer). This argument (or alternatively, the keyword argument `input_shape`) is required when using this layer as the first layer in a model. <ide> - __input_length__: Length of input sequences, when it is constant. This argument is required if you are going to connect `Flatten` then `Dense` layers upstream (without it, the shape of the dense outputs cannot be computed). <add> - __go_backwards__: Boolean (Default False). Process the input sequence backwards. <ide> <ide> - __References__: <ide> - [An Empirical Exploration of Recurrent Network Architectures](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)
1
Python
Python
update swivel code to work with python 3
d4131c9a4e218dc59fd9b15c1e5b149b90b98ceb
<ide><path>swivel/swivel.py <ide> <ide> """ <ide> <add>from __future__ import print_function <ide> import argparse <ide> import glob <ide> import math <ide> def write_embeddings_to_disk(config, model, sess): <ide> # Row Embedding <ide> row_vocab_path = config.input_base_path + '/row_vocab.txt' <ide> row_embedding_output_path = config.output_base_path + '/row_embedding.tsv' <del> print 'Writing row embeddings to:', row_embedding_output_path <add> print('Writing row embeddings to:', row_embedding_output_path) <ide> sys.stdout.flush() <ide> write_embedding_tensor_to_disk(row_vocab_path, row_embedding_output_path, <ide> sess, model.row_embedding) <ide> <ide> # Column Embedding <ide> col_vocab_path = config.input_base_path + '/col_vocab.txt' <ide> col_embedding_output_path = config.output_base_path + '/col_embedding.tsv' <del> print 'Writing column embeddings to:', col_embedding_output_path <add> print('Writing column embeddings to:', col_embedding_output_path) <ide> sys.stdout.flush() <ide> write_embedding_tensor_to_disk(col_vocab_path, col_embedding_output_path, <ide> sess, model.col_embedding) <ide> def __init__(self, config): <ide> self._config = config <ide> <ide> # Create paths to input data files <del> print 'Reading model from:', config.input_base_path <add> print('Reading model from:', config.input_base_path) <ide> sys.stdout.flush() <ide> count_matrix_files = glob.glob(config.input_base_path + '/shard-*.pb') <ide> row_sums_path = config.input_base_path + '/row_sums.txt' <ide> def __init__(self, config): <ide> <ide> self.n_rows = len(row_sums) <ide> self.n_cols = len(col_sums) <del> print 'Matrix dim: (%d,%d) SubMatrix dim: (%d,%d) ' % ( <del> self.n_rows, self.n_cols, config.submatrix_rows, config.submatrix_cols) <add> print('Matrix dim: (%d,%d) SubMatrix dim: (%d,%d) ' % ( <add> self.n_rows, self.n_cols, config.submatrix_rows, config.submatrix_cols)) <ide> sys.stdout.flush() <ide> self.n_submatrices = (self.n_rows * self.n_cols / <ide> (config.submatrix_rows * config.submatrix_cols)) <del> print 'n_submatrices: %d' % (self.n_submatrices) <add> print('n_submatrices: %d' % (self.n_submatrices)) <ide> sys.stdout.flush() <ide> <ide> # ===== CREATE VARIABLES ====== <ide> def main(_): <ide> t0 = [time.time()] <ide> <ide> def TrainingFn(): <del> for _ in range(n_steps_per_thread): <add> for _ in range(int(n_steps_per_thread)): <ide> _, global_step = sess.run([model.train_op, model.global_step]) <ide> n_steps_between_status_updates = 100 <ide> if (global_step % n_steps_between_status_updates) == 0: <ide> elapsed = float(time.time() - t0[0]) <del> print '%d/%d submatrices trained (%.1f%%), %.1f submatrices/sec' % ( <add> print('%d/%d submatrices trained (%.1f%%), %.1f submatrices/sec' % ( <ide> global_step, n_submatrices_to_train, <ide> 100.0 * global_step / n_submatrices_to_train, <del> n_steps_between_status_updates / elapsed) <add> n_steps_between_status_updates / elapsed)) <ide> sys.stdout.flush() <ide> t0[0] = time.time() <ide>
1
Ruby
Ruby
reduce test noise
0bb8429e71662aedc36ed232748d62442e74a154
<ide><path>activerecord/test/cases/timestamp_test.rb <ide> def setup <ide> @previously_updated_at = @developer.updated_at <ide> end <ide> <del> def test_load_infinity_and_beyond <del> unless current_adapter?(:PostgreSQLAdapter) <del> return skip("only tested on postgresql") <add> if current_adapter?(:PostgreSQLAdapter) <add> def test_load_infinity_and_beyond <add> d = Developer.find_by_sql("select 'infinity'::timestamp as updated_at") <add> assert d.first.updated_at.infinite?, 'timestamp should be infinite' <add> <add> d = Developer.find_by_sql("select '-infinity'::timestamp as updated_at") <add> time = d.first.updated_at <add> assert time.infinite?, 'timestamp should be infinite' <add> assert_operator time, :<, 0 <ide> end <ide> <del> d = Developer.find_by_sql("select 'infinity'::timestamp as updated_at") <del> assert d.first.updated_at.infinite?, 'timestamp should be infinite' <add> def test_save_infinity_and_beyond <add> d = Developer.create!(:name => 'aaron', :updated_at => 1.0 / 0.0) <add> assert_equal(1.0 / 0.0, d.updated_at) <ide> <del> d = Developer.find_by_sql("select '-infinity'::timestamp as updated_at") <del> time = d.first.updated_at <del> assert time.infinite?, 'timestamp should be infinite' <del> assert_operator time, :<, 0 <del> end <del> <del> def test_save_infinity_and_beyond <del> unless current_adapter?(:PostgreSQLAdapter) <del> return skip("only tested on postgresql") <add> d = Developer.create!(:name => 'aaron', :updated_at => -1.0 / 0.0) <add> assert_equal(-1.0 / 0.0, d.updated_at) <ide> end <del> <del> d = Developer.create!(:name => 'aaron', :updated_at => 1.0 / 0.0) <del> assert_equal(1.0 / 0.0, d.updated_at) <del> <del> d = Developer.create!(:name => 'aaron', :updated_at => -1.0 / 0.0) <del> assert_equal(-1.0 / 0.0, d.updated_at) <ide> end <ide> <ide> def test_saving_a_changed_record_updates_its_timestamp
1
Java
Java
improve support for generics in jackson codecs
992e75303d598a4f3ef7ab912de588f9748961ac
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Decoder.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public Object decode(DataBuffer dataBuffer, ResolvableType targetType, <ide> <ide> private ObjectReader getObjectReader(ResolvableType elementType, @Nullable Map<String, Object> hints) { <ide> Assert.notNull(elementType, "'elementType' must not be null"); <del> MethodParameter param = getParameter(elementType); <del> Class<?> contextClass = (param != null ? param.getContainingClass() : null); <add> Class<?> contextClass = getContextClass(elementType); <add> if (contextClass == null && hints != null) { <add> contextClass = getContextClass((ResolvableType) hints.get(ACTUAL_TYPE_HINT)); <add> } <ide> JavaType javaType = getJavaType(elementType.getType(), contextClass); <ide> Class<?> jsonView = (hints != null ? (Class<?>) hints.get(Jackson2CodecSupport.JSON_VIEW_HINT) : null); <ide> return jsonView != null ? <ide> getObjectMapper().readerWithView(jsonView).forType(javaType) : <ide> getObjectMapper().readerFor(javaType); <ide> } <ide> <add> @Nullable <add> private Class<?> getContextClass(@Nullable ResolvableType elementType) { <add> MethodParameter param = (elementType != null ? getParameter(elementType) : null); <add> return (param != null ? param.getContainingClass() : null); <add> } <add> <ide> private void logValue(@Nullable Object value, @Nullable Map<String, Object> hints) { <ide> if (!Hints.isLoggingSuppressed(hints)) { <ide> LogFormatUtils.traceDebug(logger, traceOn -> { <ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2CodecSupport.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.lang.reflect.Type; <ide> import java.util.Arrays; <ide> import java.util.Collections; <add>import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.codec.Hints; <ide> import org.springframework.http.HttpLogging; <add>import org.springframework.http.server.reactive.ServerHttpRequest; <add>import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.MimeType; <ide> public abstract class Jackson2CodecSupport { <ide> */ <ide> public static final String JSON_VIEW_HINT = Jackson2CodecSupport.class.getName() + ".jsonView"; <ide> <add> /** <add> * The key for the hint to access the actual ResolvableType passed into <add> * {@link org.springframework.http.codec.HttpMessageReader#read(ResolvableType, ResolvableType, ServerHttpRequest, ServerHttpResponse, Map)} <add> * (server-side only). Currently set when the method argument has generics because <add> * in case of reactive types, use of {@code ResolvableType.getGeneric()} means no <add> * MethodParameter source and no knowledge of the containing class. <add> */ <add> static final String ACTUAL_TYPE_HINT = Jackson2CodecSupport.class.getName() + ".actualType"; <add> <ide> private static final String JSON_VIEW_HINT_ERROR = <ide> "@JsonView only supported for write hints with exactly 1 class argument: "; <ide> <ide> protected JavaType getJavaType(Type type, @Nullable Class<?> contextClass) { <ide> protected Map<String, Object> getHints(ResolvableType resolvableType) { <ide> MethodParameter param = getParameter(resolvableType); <ide> if (param != null) { <add> Map<String, Object> hints = null; <add> if (resolvableType.hasGenerics()) { <add> hints = new HashMap<>(2); <add> hints.put(ACTUAL_TYPE_HINT, resolvableType); <add> } <ide> JsonView annotation = getAnnotation(param, JsonView.class); <ide> if (annotation != null) { <ide> Class<?>[] classes = annotation.value(); <ide> Assert.isTrue(classes.length == 1, JSON_VIEW_HINT_ERROR + param); <del> return Hints.from(JSON_VIEW_HINT, classes[0]); <add> hints = (hints != null ? hints : new HashMap<>(1)); <add> hints.put(JSON_VIEW_HINT, classes[0]); <add> } <add> if (hints != null) { <add> return hints; <ide> } <ide> } <ide> return Hints.none(); <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.Maybe; <del>import org.junit.jupiter.api.Disabled; <ide> import org.reactivestreams.Publisher; <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> public void personCreateWithFlowableXml(HttpServer httpServer) throws Exception <ide> assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(2); <ide> } <ide> <del> @Disabled <ide> @ParameterizedHttpServerTest // gh-23791 <ide> public void personCreateViaDefaultMethodWithGenerics(HttpServer httpServer) throws Exception { <ide> startServer(httpServer);
3
Ruby
Ruby
fix failing tests on active storage
5d818806707c24785d47d956226cbee98322c00a
<ide><path>activestorage/test/controllers/direct_uploads_controller_test.rb <ide> if SERVICE_CONFIGURATIONS[:s3] && SERVICE_CONFIGURATIONS[:s3][:access_key_id].present? <ide> class ActiveStorage::S3DirectUploadsControllerTest < ActionDispatch::IntegrationTest <ide> setup do <add> Rails.configuration.active_storage.service = "s3" <ide> @old_service = ActiveStorage::Blob.service <ide> ActiveStorage::Blob.service = ActiveStorage::Service.configure(:s3, SERVICE_CONFIGURATIONS) <ide> end <ide> <ide> teardown do <ide> ActiveStorage::Blob.service = @old_service <add> Rails.configuration.active_storage.service = "local" <ide> end <ide> <ide> test "creating new direct upload" do <ide><path>activestorage/test/test_helper.rb <ide> <ide> require "tmpdir" <ide> <del>Rails.configuration.active_storage.service_configurations = { <add>Rails.configuration.active_storage.service_configurations = SERVICE_CONFIGURATIONS.deep_stringify_keys.merge( <ide> "local" => { "service" => "Disk", "root" => Dir.mktmpdir("active_storage_tests") }, <ide> "disk_mirror_1" => { "service" => "Disk", "root" => Dir.mktmpdir("active_storage_tests_1") }, <ide> "disk_mirror_2" => { "service" => "Disk", "root" => Dir.mktmpdir("active_storage_tests_2") }, <ide> "disk_mirror_3" => { "service" => "Disk", "root" => Dir.mktmpdir("active_storage_tests_3") }, <ide> "mirror" => { "service" => "Mirror", "primary" => "local", "mirrors" => ["disk_mirror_1", "disk_mirror_2", "disk_mirror_3"] } <del>} <add>) <ide> <ide> Rails.configuration.active_storage.service = "local" <ide>
2
Text
Text
add historical information about v1 spec
1d17542f80d1a961224c762cec7628293f81465e
<ide><path>image/spec/README.md <add># Docker Image Specification v1. <add> <add>This directory contains documents about Docker Image Specification v1.X. <add> <add>The v1 file layout and manifests are no longer used in Moby and Docker, except in `docker save` and `docker load`. <add> <add>However, v1 Image JSON (`application/vnd.docker.container.image.v1+json`) has been still widely <add>used and officially adopted in [V2 manifest](https://github.com/docker/distribution/blob/master/docs/spec/manifest-v2-2.md) <add>and in [OCI Image Format Specification](https://github.com/opencontainers/image-spec). <add> <add>## v1.X rough Changelog <add> <add>All 1.X versions are compatible with older ones. <add> <add>### [v1.2](v1.2.md) <add> <add>* Implemented in Docker v1.12 (July, 2016) <add>* The official spec document was written in August 2016 ([#25750](https://github.com/moby/moby/pull/25750)) <add> <add>Changes: <add> <add>* `Healthcheck` struct was added to Image JSON <add> <add>### [v1.1](v1.1.md) <add> <add>* Implemented in Docker v1.10 (February, 2016) <add>* The official spec document was written in April 2016 ([#22264](https://github.com/moby/moby/pull/22264)) <add> <add>Changes: <add> <add>* IDs were made into SHA256 digest values rather than random values <add>* Layer directory names were made into deterministic values rather than random ID values <add>* `manifest.json` was added <add> <add>### [v1](v1.md) <add> <add>* The initial revision <add>* The official spec document was written in late 2014 ([#9560](https://github.com/moby/moby/pull/9560)), but actual implementations had existed even earlier <add> <add> <add>## Related specifications <add> <add>* [Open Containers Initiative (OCI) Image Format Specification v1.0.0](https://github.com/opencontainers/image-spec/tree/v1.0.0) <add>* [Docker Image Manifest Version 2, Schema 2](https://github.com/docker/distribution/blob/master/docs/spec/manifest-v2-2.md) <add>* [Docker Image Manifest Version 2, Schema 1](https://github.com/docker/distribution/blob/master/docs/spec/manifest-v2-1.md) (*DEPRECATED*) <add>* [Docker Registry HTTP API V2](https://docs.docker.com/registry/spec/api/)
1
PHP
PHP
rename some traits to be less stupid
96d80ee2bff037fc4eb58e144c9aa0e177ce355f
<add><path>src/Illuminate/Auth/Authenticates.php <del><path>src/Illuminate/Auth/UserTrait.php <ide> <?php namespace Illuminate\Auth; <ide> <del>trait UserTrait { <add>trait Authenticates { <ide> <ide> /** <ide> * Get the unique identifier for the user. <add><path>src/Illuminate/Auth/Passwords/ResetsPassword.php <del><path>src/Illuminate/Auth/Passwords/CanResetPasswordTrait.php <ide> <?php namespace Illuminate\Auth\Passwords; <ide> <del>trait CanResetPasswordTrait { <add>trait ResetsPassword { <ide> <ide> /** <ide> * Get the e-mail address where password reset links are sent. <add><path>src/Illuminate/Database/Eloquent/SoftDeletes.php <del><path>src/Illuminate/Database/Eloquent/SoftDeletingTrait.php <ide> <?php namespace Illuminate\Database\Eloquent; <ide> <del>trait SoftDeletingTrait { <add>trait SoftDeletes { <ide> <ide> /** <ide> * Indicates if the model is currently force deleting. <ide> trait SoftDeletingTrait { <ide> * <ide> * @return void <ide> */ <del> public static function bootSoftDeletingTrait() <add> public static function bootSoftDeletes() <ide> { <ide> static::addGlobalScope(new SoftDeletingScope); <ide> } <ide><path>tests/Database/DatabaseEloquentBuilderTest.php <ide> public function scopeApproved($query) <ide> } <ide> <ide> class EloquentBuilderTestWithTrashedStub extends Illuminate\Database\Eloquent\Model { <del> use Illuminate\Database\Eloquent\SoftDeletingTrait; <add> use Illuminate\Database\Eloquent\SoftDeletes; <ide> protected $table = 'table'; <ide> public function getKeyName() { return 'foo'; } <ide> } <ide> <ide> class EloquentBuilderTestNestedStub extends Illuminate\Database\Eloquent\Model { <ide> protected $table = 'table'; <del> use Illuminate\Database\Eloquent\SoftDeletingTrait; <add> use Illuminate\Database\Eloquent\SoftDeletes; <ide> } <ide> <ide> class EloquentBuilderTestListsStub { <ide><path>tests/Database/DatabaseSoftDeletingTraitTest.php <ide> public function testRestoreCancel() <ide> <ide> <ide> class DatabaseSoftDeletingTraitStub { <del> use Illuminate\Database\Eloquent\SoftDeletingTrait; <add> use Illuminate\Database\Eloquent\SoftDeletes; <ide> public $deleted_at; <ide> public function newQuery() <ide> {
5
Text
Text
fix chatrelayjob definition in testing guide
66ff8b14398b4264bb6a3dd3486572ff6fdddf53
<ide><path>guides/source/testing.md <ide> If you want to test the broadcasting made with `Channel.broadcast_to`, you shoul <ide> ```ruby <ide> # app/jobs/chat_relay_job.rb <ide> class ChatRelayJob < ApplicationJob <del> def perform_later(room, message) <add> def perform(room, message) <ide> ChatChannel.broadcast_to room, text: message <ide> end <ide> end
1
Ruby
Ruby
decorate deps to show installed status?
8939857600c58e6e2134fad51cc4de2d69fd6dc3
<ide><path>Library/Homebrew/cmd/info.rb <ide> def info_formula f <ide> ohai "Dependencies" <ide> %w{build required recommended optional}.map do |type| <ide> deps = f.deps.send(type) <del> puts "#{type.capitalize}: #{deps*', '}" unless deps.empty? <add> puts "#{type.capitalize}: #{decorate_dependencies deps}" unless deps.empty? <ide> end <ide> end <ide> <ide> def info_formula f <ide> ohai 'Caveats', c.caveats unless c.empty? <ide> end <ide> <add> def decorate_dependencies dependencies <add> # necessary for 1.8.7 unicode handling since many installs are on 1.8.7 <add> tick = Tty.green + ["2714".hex].pack("U*") + Tty.reset <add> cross = Tty.red + ["2718".hex].pack("U*") + Tty.reset <add> <add> deps_status = dependencies.collect do |dep| <add> if ENV['HOMEBREW_NO_EMOJI'] <add> "%s%s%s" % [(dep.installed? ? Tty.green : Tty.red), dep, Tty.reset] <add> else <add> "%s %s" % [dep, (dep.installed? ? tick : cross)] <add> end <add> end <add> deps_status * ", " <add> end <add> <ide> private <ide> <ide> def valid_url u
1
Ruby
Ruby
improve error wording
dd46cc40c7b3c45d3ceb632ca8d9dba20bc230f7
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit <ide> end <ide> <ide> if audit_formulae.empty? && audit_casks.empty? <del> ofail "No audits to perform" <add> ofail "No matching formulae or casks to audit!" <ide> return <ide> end <ide>
1
Text
Text
fix typos and formatting
d6c839cf0f04f30ba95e2b032a4e686dea2eb0d0
<ide><path>image/spec/v1.md <ide> This specification uses the following terms: <ide> Image JSON <ide> </dt> <ide> <dd> <del> Each layer has an associated A JSON structure which describes some <add> Each layer has an associated JSON structure which describes some <ide> basic information about the image such as date created, author, and the <ide> ID of its parent image as well as execution/runtime configuration like <ide> its entry point, default arguments, CPU/memory shares, networking, and <ide> This specification uses the following terms: <ide> times of any entries differ. For this reason, image checksums are <ide> generated using the TarSum algorithm which produces a cryptographic <ide> hash of file contents and selected headers only. Details of this <del> algorithm are described in the separate [TarSum specification](https://github.com/docker/docker/blob/master/pkg/tarsum/tarsum_spec.md). <add> algorithm are described in the separate <a href="https://github.com/docker/docker/blob/master/pkg/tarsum/tarsum_spec.md">TarSum specification</a>. <ide> </dd> <ide> <dt> <ide> Tag <ide> Changeset tar archives. <ide> There is also a format for a single archive which contains complete information <ide> about an image, including: <ide> <del> - repository names/tags <del> - all image layer JSON files <del> - all tar archives of each layer filesystem changesets <add> - repository names/tags <add> - all image layer JSON files <add> - all tar archives of each layer filesystem changesets <ide> <ide> For example, here's what the full archive of `library/busybox` is (displayed in <ide> `tree` format): <ide> For example, here's what the full archive of `library/busybox` is (displayed in <ide> There are one or more directories named with the ID for each layer in a full <ide> image. Each of these directories contains 3 files: <ide> <del> * `VERSION` - The schema version of the `json` file <del> * `json` - The JSON metadata for an image layer <del> * `layer.tar` - The Tar archive of the filesystem changeset for an image <del> layer. <add> * `VERSION` - The schema version of the `json` file <add> * `json` - The JSON metadata for an image layer <add> * `layer.tar` - The Tar archive of the filesystem changeset for an image <add> layer. <ide> <ide> The content of the `VERSION` files is simply the semantic version of the JSON <ide> metadata schema:
1
Python
Python
avoid signed overflow in histogram
b581aade6891662e37931b04bba29262cd6057de
<ide><path>numpy/lib/histograms.py <ide> def _get_outer_edges(a, range): <ide> return first_edge, last_edge <ide> <ide> <add>def _unsigned_subtract(a, b): <add> """ <add> Subtract two values where a >= b, and produce an unsigned result <add> <add> This is needed when finding the difference between the upper and lower <add> bound of an int16 histogram <add> """ <add> # coerce to a single type <add> signed_to_unsigned = { <add> np.byte: np.ubyte, <add> np.short: np.ushort, <add> np.intc: np.uintc, <add> np.int_: np.uint, <add> np.longlong: np.ulonglong <add> } <add> dt = np.result_type(a, b) <add> try: <add> dt = signed_to_unsigned[dt.type] <add> except KeyError: <add> return np.subtract(a, b, dtype=dt) <add> else: <add> # we know the inputs are integers, and we are deliberately casting <add> # signed to unsigned <add> return np.subtract(a, b, casting='unsafe', dtype=dt) <add> <add> <ide> def _get_bin_edges(a, bins, range, weights): <ide> """ <ide> Computes the bins used internally by `histogram`. <ide> def _get_bin_edges(a, bins, range, weights): <ide> # Do not call selectors on empty arrays <ide> width = _hist_bin_selectors[bin_name](a) <ide> if width: <del> n_equal_bins = int(np.ceil((last_edge - first_edge) / width)) <add> n_equal_bins = int(np.ceil(_unsigned_subtract(last_edge, first_edge) / width)) <ide> else: <ide> # Width can be zero for some estimators, e.g. FD when <ide> # the IQR of the data is zero. <ide> def histogram(a, bins=10, range=None, normed=False, weights=None, <ide> n = np.zeros(n_equal_bins, ntype) <ide> <ide> # Pre-compute histogram scaling factor <del> norm = n_equal_bins / (last_edge - first_edge) <add> norm = n_equal_bins / _unsigned_subtract(last_edge, first_edge) <ide> <ide> # We iterate over blocks here for two reasons: the first is that for <ide> # large arrays, it is actually faster (for example for a 10^8 array it <ide> def histogram(a, bins=10, range=None, normed=False, weights=None, <ide> <ide> # Compute the bin indices, and for values that lie exactly on <ide> # last_edge we need to subtract one <del> f_indices = (tmp_a - first_edge) * norm <add> f_indices = _unsigned_subtract(tmp_a, first_edge) * norm <ide> indices = f_indices.astype(np.intp) <ide> indices[indices == n_equal_bins] -= 1 <ide> <ide><path>numpy/lib/tests/test_histograms.py <ide> def test_datetime(self): <ide> assert_equal(d_edge.dtype, dates.dtype) <ide> assert_equal(t_edge.dtype, td) <ide> <add> def do_signed_overflow_bounds(self, dtype): <add> exponent = 8 * np.dtype(dtype).itemsize - 1 <add> arr = np.array([-2**exponent + 4, 2**exponent - 4], dtype=dtype) <add> hist, e = histogram(arr, bins=2) <add> assert_equal(e, [-2**exponent + 4, 0, 2**exponent - 4]) <add> assert_equal(hist, [1, 1]) <add> <add> def test_signed_overflow_bounds(self): <add> self.do_signed_overflow_bounds(np.byte) <add> self.do_signed_overflow_bounds(np.short) <add> self.do_signed_overflow_bounds(np.intc) <add> self.do_signed_overflow_bounds(np.int_) <add> self.do_signed_overflow_bounds(np.longlong) <add> <ide> def do_precision_lower_bound(self, float_small, float_large): <ide> eps = np.finfo(float_large).eps <ide>
2
Text
Text
add notes to http.get options
e1161a37188600ce23bef3bcab2ed44fbd645860
<ide><path>doc/api/http.md <ide> added: v0.3.6 <ide> <ide> * `options` {Object | string} Accepts the same `options` as <ide> [`http.request()`][], with the `method` always set to `GET`. <add> Properties that are inherited from the prototype are ignored. <ide> * `callback` {Function} <ide> * Returns: {http.ClientRequest} <ide>
1
Python
Python
pass overrides to subcommands in workflows
1e9b4b55ee5a423f4dfed447daa38a250ce85eb8
<ide><path>spacy/cli/project/run.py <ide> def project_run( <ide> <ide> project_dir (Path): Path to project directory. <ide> subcommand (str): Name of command to run. <add> overrides (Dict[str, Any]): Optional config overrides. <ide> force (bool): Force re-running, even if nothing changed. <ide> dry (bool): Perform a dry run and don't execute commands. <ide> capture (bool): Whether to capture the output and errors of individual commands. <ide> def project_run( <ide> if subcommand in workflows: <ide> msg.info(f"Running workflow '{subcommand}'") <ide> for cmd in workflows[subcommand]: <del> project_run(project_dir, cmd, force=force, dry=dry, capture=capture) <add> project_run(project_dir, cmd, overrides=overrides, force=force, dry=dry, capture=capture) <ide> else: <ide> cmd = commands[subcommand] <ide> for dep in cmd.get("deps", []):
1
Java
Java
apply new responsestatusexception hierarchy
6b7360fed1741bd9f7208f993f1df0036e2137d6
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/HandlerNotFoundException.java <del>/* <del> * Copyright 2002-2015 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del>package org.springframework.web.reactive; <del> <del>import org.springframework.core.NestedRuntimeException; <del> <del>/** <del> * @author Rossen Stoyanchev <del> */ <del>public class HandlerNotFoundException extends NestedRuntimeException { <del> <del> <del> public HandlerNotFoundException() { <del> super("No handler found."); <del> } <del> <del>} <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/accept/AbstractMappingContentTypeResolver.java <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.StringUtils; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <ide> /** <ide> protected List<MediaType> getMediaTypes() { <ide> <ide> @Override <ide> public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) <del> throws HttpMediaTypeNotAcceptableException { <add> throws NotAcceptableStatusException { <ide> <ide> String key = extractKey(exchange); <ide> return resolveMediaTypes(key); <ide> public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) <ide> * An overloaded resolve method with a pre-resolved lookup key. <ide> * @param key the key for looking up media types <ide> * @return a list of resolved media types or an empty list <del> * @throws HttpMediaTypeNotAcceptableException <add> * @throws NotAcceptableStatusException <ide> */ <del> public List<MediaType> resolveMediaTypes(String key) <del> throws HttpMediaTypeNotAcceptableException { <del> <add> public List<MediaType> resolveMediaTypes(String key) throws NotAcceptableStatusException { <ide> if (StringUtils.hasText(key)) { <ide> MediaType mediaType = getMediaType(key); <ide> if (mediaType != null) { <ide> protected void handleMatch(String key, MediaType mediaType) { <ide> * this method it will be added to the mappings. <ide> */ <ide> @SuppressWarnings("UnusedParameters") <del> protected MediaType handleNoMatch(String key) throws HttpMediaTypeNotAcceptableException { <add> protected MediaType handleNoMatch(String key) throws NotAcceptableStatusException { <ide> return null; <ide> } <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/accept/CompositeContentTypeResolver.java <ide> <ide> import org.springframework.http.MediaType; <ide> import org.springframework.util.Assert; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <ide> /** <ide> public <T extends ContentTypeResolver> T findResolver(Class<T> resolverType) { <ide> <ide> <ide> @Override <del> public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws HttpMediaTypeNotAcceptableException { <add> public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException { <ide> for (ContentTypeResolver resolver : this.resolvers) { <ide> List<MediaType> mediaTypes = resolver.resolveMediaTypes(exchange); <ide> if (mediaTypes.isEmpty() || (mediaTypes.size() == 1 && mediaTypes.contains(MediaType.ALL))) { <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/accept/ContentTypeResolver.java <ide> import java.util.List; <ide> <ide> import org.springframework.http.MediaType; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <ide> /** <ide> public interface ContentTypeResolver { <ide> * @param exchange the current exchange <ide> * @return the requested media types or an empty list <ide> * <del> * @throws HttpMediaTypeNotAcceptableException if the requested media <del> * types cannot be parsed <add> * @throws NotAcceptableStatusException if the requested media types is invalid <ide> */ <del> List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws HttpMediaTypeNotAcceptableException; <add> List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException; <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/accept/HeaderContentTypeResolver.java <ide> <ide> import org.springframework.http.InvalidMediaTypeException; <ide> import org.springframework.http.MediaType; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <ide> /** <ide> public class HeaderContentTypeResolver implements ContentTypeResolver { <ide> <ide> @Override <del> public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) <del> throws HttpMediaTypeNotAcceptableException { <del> <add> public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException { <ide> try { <ide> List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept(); <ide> MediaType.sortBySpecificityAndQuality(mediaTypes); <ide> return mediaTypes; <ide> } <ide> catch (InvalidMediaTypeException ex) { <ide> String value = exchange.getRequest().getHeaders().getFirst("Accept"); <del> throw new HttpMediaTypeNotAcceptableException( <add> throw new NotAcceptableStatusException( <ide> "Could not parse 'Accept' header [" + value + "]: " + ex.getMessage()); <ide> } <ide> } <add> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/accept/ParameterContentTypeResolver.java <ide> <ide> import org.springframework.http.MediaType; <ide> import org.springframework.util.Assert; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <ide> /** <ide> protected void handleMatch(String mediaTypeKey, MediaType mediaType) { <ide> } <ide> <ide> @Override <del> protected MediaType handleNoMatch(String key) throws HttpMediaTypeNotAcceptableException { <del> throw new HttpMediaTypeNotAcceptableException(getMediaTypes()); <add> protected MediaType handleNoMatch(String key) throws NotAcceptableStatusException { <add> throw new NotAcceptableStatusException(getMediaTypes()); <ide> } <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/accept/PathExtensionContentTypeResolver.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.util.StringUtils; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <del>import org.springframework.web.accept.PathExtensionContentNegotiationStrategy; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.util.WebUtils; <ide> <ide> */ <ide> public class PathExtensionContentTypeResolver extends AbstractMappingContentTypeResolver { <ide> <del> private static final Log logger = LogFactory.getLog(PathExtensionContentNegotiationStrategy.class); <add> private static final Log logger = LogFactory.getLog(PathExtensionContentTypeResolver.class); <ide> <del> private static final boolean JAF_PRESENT = ClassUtils.isPresent( <del> "javax.activation.FileTypeMap", <del> PathExtensionContentNegotiationStrategy.class.getClassLoader()); <add> private static final boolean JAF_PRESENT = ClassUtils.isPresent("javax.activation.FileTypeMap", <add> PathExtensionContentTypeResolver.class.getClassLoader()); <ide> <ide> <ide> private boolean useJaf = true; <ide> protected String extractKey(ServerWebExchange exchange) { <ide> } <ide> <ide> @Override <del> protected MediaType handleNoMatch(String key) throws HttpMediaTypeNotAcceptableException { <add> protected MediaType handleNoMatch(String key) throws NotAcceptableStatusException { <ide> if (this.useJaf && JAF_PRESENT) { <ide> MediaType mediaType = JafMediaTypeFactory.getMediaType("file." + key); <ide> if (mediaType != null && !MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) { <ide> return mediaType; <ide> } <ide> } <ide> if (!this.ignoreUnknownExtensions) { <del> throw new HttpMediaTypeNotAcceptableException(getMediaTypes()); <add> throw new NotAcceptableStatusException(getMediaTypes()); <ide> } <ide> return null; <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/condition/AbstractMediaTypeExpression.java <ide> import org.apache.commons.logging.LogFactory; <ide> <ide> import org.springframework.http.MediaType; <del>import org.springframework.web.HttpMediaTypeException; <ide> import org.springframework.web.bind.annotation.RequestMapping; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <add>import org.springframework.web.server.UnsupportedMediaTypeStatusException; <ide> <ide> /** <ide> * Supports media type expressions as described in: <ide> public final boolean match(ServerWebExchange exchange) { <ide> boolean match = matchMediaType(exchange); <ide> return (!this.isNegated == match); <ide> } <del> catch (HttpMediaTypeException ex) { <add> catch (NotAcceptableStatusException ex) { <add> return false; <add> } <add> catch (UnsupportedMediaTypeStatusException ex) { <ide> return false; <ide> } <ide> } <ide> <del> protected abstract boolean matchMediaType(ServerWebExchange exchange) throws HttpMediaTypeException; <add> protected abstract boolean matchMediaType(ServerWebExchange exchange) <add> throws NotAcceptableStatusException, UnsupportedMediaTypeStatusException; <ide> <ide> <ide> @Override <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/condition/ConsumesRequestCondition.java <ide> <ide> import org.springframework.http.InvalidMediaTypeException; <ide> import org.springframework.http.MediaType; <del>import org.springframework.web.HttpMediaTypeNotSupportedException; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.server.ServerWebExchange; <add>import org.springframework.web.server.UnsupportedMediaTypeStatusException; <ide> <ide> /** <ide> * A logical disjunction (' || ') request condition to match a request's <ide> static class ConsumeMediaTypeExpression extends AbstractMediaTypeExpression { <ide> } <ide> <ide> @Override <del> protected boolean matchMediaType(ServerWebExchange exchange) throws HttpMediaTypeNotSupportedException { <add> protected boolean matchMediaType(ServerWebExchange exchange) throws UnsupportedMediaTypeStatusException { <ide> try { <ide> MediaType contentType = exchange.getRequest().getHeaders().getContentType(); <ide> contentType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM); <ide> return getMediaType().includes(contentType); <ide> } <ide> catch (InvalidMediaTypeException ex) { <del> throw new HttpMediaTypeNotSupportedException("Can't parse Content-Type [" + <add> throw new UnsupportedMediaTypeStatusException("Can't parse Content-Type [" + <ide> exchange.getRequest().getHeaders().getFirst("Content-Type") + <ide> "]: " + ex.getMessage()); <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/condition/ProducesRequestCondition.java <ide> import java.util.Set; <ide> <ide> import org.springframework.http.MediaType; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <ide> import org.springframework.web.accept.ContentNegotiationManager; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.reactive.accept.CompositeContentTypeResolverBuilder; <ide> import org.springframework.web.reactive.accept.ContentTypeResolver; <ide> import org.springframework.web.reactive.accept.HeaderContentTypeResolver; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <ide> /** <ide> public int compareTo(ProducesRequestCondition other, ServerWebExchange exchange) <ide> } <ide> return 0; <ide> } <del> catch (HttpMediaTypeNotAcceptableException ex) { <add> catch (NotAcceptableStatusException ex) { <ide> // should never happen <ide> throw new IllegalStateException("Cannot compare without having any requested media types", ex); <ide> } <ide> } <ide> <ide> private List<MediaType> getAcceptedMediaTypes(ServerWebExchange exchange) <del> throws HttpMediaTypeNotAcceptableException { <add> throws NotAcceptableStatusException { <ide> <ide> List<MediaType> mediaTypes = this.contentTypeResolver.resolveMediaTypes(exchange); <ide> return mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes; <ide> class ProduceMediaTypeExpression extends AbstractMediaTypeExpression { <ide> } <ide> <ide> @Override <del> protected boolean matchMediaType(ServerWebExchange exchange) throws HttpMediaTypeNotAcceptableException { <add> protected boolean matchMediaType(ServerWebExchange exchange) throws NotAcceptableStatusException { <ide> List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(exchange); <ide> for (MediaType acceptedMediaType : acceptedMediaTypes) { <ide> if (getMediaType().isCompatibleWith(acceptedMediaType)) { <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMapping.java <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.util.CollectionUtils; <ide> import org.springframework.util.MultiValueMap; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <del>import org.springframework.web.HttpMediaTypeNotSupportedException; <del>import org.springframework.web.HttpRequestMethodNotSupportedException; <del>import org.springframework.web.bind.UnsatisfiedServletRequestParameterException; <ide> import org.springframework.web.bind.annotation.RequestMethod; <ide> import org.springframework.web.method.HandlerMethod; <ide> import org.springframework.web.reactive.HandlerMapping; <ide> import org.springframework.web.reactive.result.condition.NameValueExpression; <ide> import org.springframework.web.reactive.result.condition.ParamsRequestCondition; <add>import org.springframework.web.server.BadRequestStatusException; <add>import org.springframework.web.server.MethodNotAllowedException; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <add>import org.springframework.web.server.UnsupportedMediaTypeStatusException; <ide> import org.springframework.web.util.WebUtils; <ide> <ide> /** <ide> private Map<String, MultiValueMap<String, String>> extractMatrixVariables( <ide> /** <ide> * Iterate all RequestMappingInfos once again, look if any match by URL at <ide> * least and raise exceptions accordingly. <del> * @throws HttpRequestMethodNotSupportedException if there are matches by URL <del> * but not by HTTP method <del> * @throws HttpMediaTypeNotAcceptableException if there are matches by URL <del> * but not by consumable/producible media types <add> * @throws MethodNotAllowedException for matches by URL but not by HTTP method <add> * @throws UnsupportedMediaTypeStatusException if there are matches by URL <add> * and HTTP method but not by consumable media types <add> * @throws NotAcceptableStatusException if there are matches by URL and HTTP <add> * method but not by producible media types <add> * @throws BadRequestStatusException if there are matches by URL and HTTP <add> * method but not by query parameter conditions <ide> */ <ide> @Override <ide> protected HandlerMethod handleNoMatch(Set<RequestMappingInfo> requestMappingInfos, <ide> else if (patternAndMethodMatches.isEmpty()) { <ide> return new HandlerMethod(handler, HTTP_OPTIONS_HANDLE_METHOD); <ide> } <ide> else if (!allowedMethods.isEmpty()) { <del> throw new HttpRequestMethodNotSupportedException(httpMethod.name(), allowedMethods); <add> throw new MethodNotAllowedException(httpMethod.name(), allowedMethods); <ide> } <ide> } <ide> <ide> else if (!allowedMethods.isEmpty()) { <ide> contentType = request.getHeaders().getContentType(); <ide> } <ide> catch (InvalidMediaTypeException ex) { <del> throw new HttpMediaTypeNotSupportedException(ex.getMessage()); <add> throw new UnsupportedMediaTypeStatusException(ex.getMessage()); <ide> } <del> throw new HttpMediaTypeNotSupportedException(contentType, new ArrayList<>(consumableMediaTypes)); <add> throw new UnsupportedMediaTypeStatusException(contentType, new ArrayList<>(consumableMediaTypes)); <ide> } <ide> else if (!producibleMediaTypes.isEmpty()) { <del> throw new HttpMediaTypeNotAcceptableException(new ArrayList<>(producibleMediaTypes)); <add> throw new NotAcceptableStatusException(new ArrayList<>(producibleMediaTypes)); <ide> } <ide> else { <ide> if (!CollectionUtils.isEmpty(paramConditions)) { <ide> Map<String, String[]> params = request.getQueryParams().entrySet().stream() <ide> .collect(Collectors.toMap(Entry::getKey, <ide> entry -> entry.getValue().toArray(new String[entry.getValue().size()])) <ide> ); <del> throw new UnsatisfiedServletRequestParameterException(paramConditions, params); <add> throw new BadRequestStatusException("Unsatisfied query parameter conditions: " + <add> paramConditions + ", actual: " + params); <ide> } <ide> else { <ide> return null; <ide> public HttpOptionsHandler(Set<String> declaredMethods) { <ide> } <ide> <ide> private static Set<HttpMethod> initAllowedHttpMethods(Set<String> declaredMethods) { <del> Set<HttpMethod> result = new LinkedHashSet<HttpMethod>(declaredMethods.size()); <add> Set<HttpMethod> result = new LinkedHashSet<>(declaredMethods.size()); <ide> if (declaredMethods.isEmpty()) { <ide> for (HttpMethod method : HttpMethod.values()) { <ide> if (!HttpMethod.TRACE.equals(method)) { <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandler.java <ide> import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.MimeType; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <ide> import org.springframework.web.bind.annotation.ResponseBody; <ide> import org.springframework.web.method.HandlerMethod; <ide> import org.springframework.web.reactive.HandlerResult; <ide> import org.springframework.web.reactive.HandlerResultHandler; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <ide> <ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) <ide> } <ide> } <ide> if (compatibleMediaTypes.isEmpty()) { <del> return Mono.error(new HttpMediaTypeNotAcceptableException(producibleMediaTypes)); <add> return Mono.error(new NotAcceptableStatusException(producibleMediaTypes)); <ide> } <ide> <ide> List<MediaType> mediaTypes = new ArrayList<>(compatibleMediaTypes); <ide> else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICAT <ide> } <ide> } <ide> <del> return Mono.error(new HttpMediaTypeNotAcceptableException(this.allMediaTypes)); <add> return Mono.error(new NotAcceptableStatusException(this.allMediaTypes)); <ide> } <ide> <ide> private List<MediaType> getAcceptableMediaTypes(ServerHttpRequest request) { <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java <ide> import org.springframework.http.server.reactive.MockServerHttpRequest; <ide> import org.springframework.http.server.reactive.MockServerHttpResponse; <ide> import org.springframework.stereotype.Controller; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <del>import org.springframework.web.server.ResponseStatusException; <ide> import org.springframework.web.bind.annotation.RequestBody; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.annotation.ResponseBody; <ide> import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter; <ide> import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping; <ide> import org.springframework.web.reactive.result.method.annotation.ResponseBodyResultHandler; <add>import org.springframework.web.server.NotAcceptableStatusException; <add>import org.springframework.web.server.ResponseStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.WebExceptionHandler; <ide> import org.springframework.web.server.WebFilter; <ide> import org.springframework.web.server.session.WebSessionManager; <ide> <ide> import static org.hamcrest.CoreMatchers.startsWith; <del>import static org.junit.Assert.*; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertSame; <add>import static org.junit.Assert.assertThat; <ide> import static org.mockito.Mockito.mock; <ide> <ide> /** <ide> public void noHandler() throws Exception { <ide> Throwable ex = awaitErrorSignal(publisher); <ide> <ide> assertEquals(ResponseStatusException.class, ex.getClass()); <del> assertNotNull(ex.getCause()); <del> assertEquals(HandlerNotFoundException.class, ex.getCause().getClass()); <add> assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) ex).getStatus()); <ide> } <ide> <ide> @Test <ide> public void notAcceptable() throws Exception { <ide> Mono<Void> publisher = this.dispatcherHandler.handle(this.exchange); <ide> Throwable ex = awaitErrorSignal(publisher); <ide> <del> assertEquals(ResponseStatusException.class, ex.getClass()); <del> assertNotNull(ex.getCause()); <del> assertEquals(HttpMediaTypeNotAcceptableException.class, ex.getCause().getClass()); <add> assertEquals(NotAcceptableStatusException.class, ex.getClass()); <ide> } <ide> <ide> @Test <ide> public void requestBodyError() throws Exception { <ide> <ide> ex.printStackTrace(); <ide> assertSame(EXCEPTION, ex); <del> <ide> } <ide> <ide> @Test <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/ResponseStatusExceptionHandlerTests.java <ide> import static org.mockito.Mockito.mock; <ide> <ide> /** <add> * Unit tests for {@link ResponseStatusExceptionHandler}. <add> * <ide> * @author Rossen Stoyanchev <ide> */ <ide> public class ResponseStatusExceptionHandlerTests { <ide> public void setUp() throws Exception { <ide> <ide> @Test <ide> public void handleException() throws Exception { <del> Throwable ex = new ResponseStatusException(HttpStatus.BAD_REQUEST); <add> Throwable ex = new ResponseStatusException(HttpStatus.BAD_REQUEST, ""); <ide> Mono<Void> publisher = this.handler.handle(this.exchange, ex); <ide> <ide> publisher.get(); <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/accept/CompositeContentTypeResolverBuilderTests.java <ide> import org.springframework.http.server.reactive.MockServerHttpRequest; <ide> import org.springframework.http.server.reactive.MockServerHttpResponse; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.adapter.DefaultServerWebExchange; <ide> import org.springframework.web.server.session.WebSessionManager; <ide> public void favorPathWithJafTurnedOff() throws Exception { <ide> assertEquals(Collections.emptyList(), resolver.resolveMediaTypes(exchange)); <ide> } <ide> <del> @Test(expected = HttpMediaTypeNotAcceptableException.class) // SPR-10170 <add> @Test(expected = NotAcceptableStatusException.class) // SPR-10170 <ide> public void favorPathWithIgnoreUnknownPathExtensionTurnedOff() throws Exception { <ide> CompositeContentTypeResolver resolver = new CompositeContentTypeResolverBuilder() <ide> .favorPathExtension(true) <ide> public void favorParameter() throws Exception { <ide> resolver.resolveMediaTypes(exchange)); <ide> } <ide> <del> @Test(expected = HttpMediaTypeNotAcceptableException.class) // SPR-10170 <add> @Test(expected = NotAcceptableStatusException.class) // SPR-10170 <ide> public void favorParameterWithUnknownMediaType() throws Exception { <ide> CompositeContentTypeResolver resolver = new CompositeContentTypeResolverBuilder() <ide> .favorParameter(true) <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/accept/HeaderContentTypeResolverTests.java <ide> import org.springframework.http.server.reactive.MockServerHttpRequest; <ide> import org.springframework.http.server.reactive.MockServerHttpResponse; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.adapter.DefaultServerWebExchange; <ide> import org.springframework.web.server.session.WebSessionManager; <ide> public void resolveMediaTypes() throws Exception { <ide> assertEquals("text/plain;q=0.5", mediaTypes.get(3).toString()); <ide> } <ide> <del> @Test(expected=HttpMediaTypeNotAcceptableException.class) <add> @Test(expected=NotAcceptableStatusException.class) <ide> public void resolveMediaTypesParseError() throws Exception { <ide> ServerWebExchange exchange = createExchange("textplain; q=0.5"); <ide> this.resolver.resolveMediaTypes(exchange); <add><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/accept/PathExtensionContentTypeResolverTests.java <del><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/accept/PathExtensionContentNegotiationStrategyTests.java <ide> import org.springframework.http.server.reactive.MockServerHttpRequest; <ide> import org.springframework.http.server.reactive.MockServerHttpResponse; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.adapter.DefaultServerWebExchange; <ide> import org.springframework.web.server.session.WebSessionManager; <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <del>public class PathExtensionContentNegotiationStrategyTests { <add>public class PathExtensionContentTypeResolverTests { <ide> <ide> @Test <ide> public void resolveMediaTypesFromMapping() throws Exception { <ide> public void resolveMediaTypesIgnoreUnknownExtension() throws Exception { <ide> assertEquals(Collections.<MediaType>emptyList(), mediaTypes); <ide> } <ide> <del> @Test(expected = HttpMediaTypeNotAcceptableException.class) <add> @Test(expected = NotAcceptableStatusException.class) <ide> public void resolveMediaTypesDoNotIgnoreUnknownExtension() throws Exception { <ide> ServerWebExchange exchange = createExchange("test.xyz"); <ide> PathExtensionContentTypeResolver resolver = new PathExtensionContentTypeResolver(); <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMappingTests.java <ide> import java.util.Arrays; <ide> import java.util.Collections; <ide> import java.util.HashSet; <del>import java.util.List; <ide> import java.util.Map; <ide> import java.util.Optional; <ide> import java.util.Set; <ide> import java.util.function.Consumer; <ide> <add>import org.hamcrest.Matchers; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import reactor.core.publisher.Mono; <ide> import org.springframework.ui.ExtendedModelMap; <ide> import org.springframework.ui.ModelMap; <ide> import org.springframework.util.MultiValueMap; <del>import org.springframework.web.HttpMediaTypeNotAcceptableException; <del>import org.springframework.web.HttpMediaTypeNotSupportedException; <del>import org.springframework.web.HttpRequestMethodNotSupportedException; <del>import org.springframework.web.bind.UnsatisfiedServletRequestParameterException; <ide> import org.springframework.web.bind.annotation.RequestBody; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.annotation.RequestMethod; <ide> import org.springframework.web.method.HandlerMethod; <ide> import org.springframework.web.reactive.HandlerMapping; <ide> import org.springframework.web.reactive.HandlerResult; <ide> import org.springframework.web.reactive.result.method.RequestMappingInfo.BuilderConfiguration; <add>import org.springframework.web.server.BadRequestStatusException; <add>import org.springframework.web.server.MethodNotAllowedException; <add>import org.springframework.web.server.NotAcceptableStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <add>import org.springframework.web.server.UnsupportedMediaTypeStatusException; <ide> import org.springframework.web.server.adapter.DefaultServerWebExchange; <ide> import org.springframework.web.server.session.WebSessionManager; <ide> import org.springframework.web.util.HttpRequestPathHelper; <ide> <del>import static org.hamcrest.Matchers.containsInAnyOrder; <del>import static org.junit.Assert.assertArrayEquals; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertNotNull; <ide> import static org.junit.Assert.assertNull; <del>import static org.junit.Assert.assertThat; <ide> import static org.junit.Assert.assertTrue; <ide> import static org.mockito.Mockito.mock; <ide> <ide> public void getHandlerBestMatch() throws Exception { <ide> public void getHandlerRequestMethodNotAllowed() throws Exception { <ide> ServerWebExchange exchange = createExchange(HttpMethod.POST, "/bar"); <ide> Mono<Object> mono = this.handlerMapping.getHandler(exchange); <del> assertError(mono, HttpRequestMethodNotSupportedException.class, <del> ex -> assertArrayEquals(new String[]{"GET", "HEAD"}, ex.getSupportedMethods())); <add> assertError(mono, MethodNotAllowedException.class, <add> ex -> assertEquals(new HashSet<>(Arrays.asList("GET", "HEAD")), ex.getSupportedMethods())); <ide> } <ide> <ide> // SPR-9603 <ide> public void getHandlerRequestMethodMatchFalsePositive() throws Exception { <ide> <ide> TestSubscriber<Object> subscriber = new TestSubscriber<>(); <ide> mono.subscribeWith(subscriber); <del> subscriber.assertError(HttpMediaTypeNotAcceptableException.class); <add> subscriber.assertError(NotAcceptableStatusException.class); <ide> } <ide> <ide> // SPR-8462 <ide> public void getHandlerTestInvalidContentType() throws Exception { <ide> ServerWebExchange exchange = createExchange(HttpMethod.PUT, "/person/1"); <ide> exchange.getRequest().getHeaders().add("Content-Type", "bogus"); <ide> Mono<Object> mono = this.handlerMapping.getHandler(exchange); <del> assertError(mono, HttpMediaTypeNotSupportedException.class, <del> ex -> assertEquals("Invalid mime type \"bogus\": does not contain '/'", ex.getMessage())); <add> assertError(mono, UnsupportedMediaTypeStatusException.class, <add> ex -> assertEquals("Request failure [status: 415, " + <add> "reason: \"Invalid mime type \"bogus\": does not contain '/'\"]", <add> ex.getMessage())); <ide> } <ide> <ide> // SPR-8462 <ide> public void getHandlerMediaTypeNotAccepted() throws Exception { <ide> public void getHandlerUnsatisfiedServletRequestParameterException() throws Exception { <ide> ServerWebExchange exchange = createExchange(HttpMethod.GET, "/params"); <ide> Mono<Object> mono = this.handlerMapping.getHandler(exchange); <del> assertError(mono, UnsatisfiedServletRequestParameterException.class, ex -> { <del> List<String[]> groups = ex.getParamConditionGroups(); <del> assertEquals(2, groups.size()); <del> assertThat(Arrays.asList("foo=bar", "bar=baz"), <del> containsInAnyOrder(groups.get(0)[0], groups.get(1)[0])); <add> assertError(mono, BadRequestStatusException.class, ex -> { <add> assertThat(ex.getReason(), Matchers.startsWith("Unsatisfied query parameter conditions:")); <ide> }); <ide> } <ide> <ide> private void testHttpMediaTypeNotSupportedException(String url) throws Exception <ide> exchange.getRequest().getHeaders().setContentType(MediaType.APPLICATION_JSON); <ide> Mono<Object> mono = this.handlerMapping.getHandler(exchange); <ide> <del> assertError(mono, HttpMediaTypeNotSupportedException.class, ex -> <add> assertError(mono, UnsupportedMediaTypeStatusException.class, ex -> <ide> assertEquals("Invalid supported consumable media types", <ide> Collections.singletonList(new MediaType("application", "xml")), <del> ex.getSupportedMediaTypes())); <add> ex.getSupportedContentTypes())); <ide> } <ide> <ide> private void testHttpOptions(String requestURI, String allowHeader) throws Exception { <ide> private void testHttpMediaTypeNotAcceptableException(String url) throws Exceptio <ide> exchange.getRequest().getHeaders().setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); <ide> Mono<Object> mono = this.handlerMapping.getHandler(exchange); <ide> <del> assertError(mono, HttpMediaTypeNotAcceptableException.class, ex -> <add> assertError(mono, NotAcceptableStatusException.class, ex -> <ide> assertEquals("Invalid supported producible media types", <ide> Collections.singletonList(new MediaType("application", "xml")), <ide> ex.getSupportedMediaTypes()));
18
Javascript
Javascript
add a bolder warning when missing .env
f5ccaf971b7a7dce66978461e5ee8969c4ed56ac
<ide><path>config/read-env.js <ide> const envPath = path.resolve(__dirname, '../.env'); <ide> const { error } = require('dotenv').config({ path: envPath }); <ide> <ide> if (error) { <del> if (process.env.FREECODECAMP_NODE_ENV === 'development') { <del> console.warn('.env not found, please copy sample.env to .env'); <del> } else { <del> console.warn(`.env not found. If env vars are not being set another way, <del>this could be a problem.`); <del> } <add> console.warn(` <add> ---------------------------------------------------- <add> Warning: .env file not found. <add> ---------------------------------------------------- <add> Please copy sample.env to .env <add> <add> You can ignore this warning if using a different way <add> to setup this environment. <add> ---------------------------------------------------- <add> `); <ide> } <ide> <ide> const {
1
Javascript
Javascript
add a loading bar when loading split bundles
d974793b5952fe9c5ead7411a860eef04038529e
<ide><path>Libraries/Utilities/HMRClient.js <ide> Error: ${e.message}`; <ide> <ide> client.on('update-start', () => { <ide> if (isFastRefreshActive()) { <del> LoadingView.showMessage('Refreshing...'); <add> LoadingView.showMessage('Refreshing...', 'refresh'); <ide> } <ide> }); <ide> <ide><path>Libraries/Utilities/LoadingView.android.js <ide> const TOAST_SHORT_DELAY = 2000; <ide> let isVisible = false; <ide> <ide> module.exports = { <del> showMessage(message: string) { <add> showMessage(message: string, type: 'load' | 'refresh') { <ide> if (!isVisible) { <ide> ToastAndroid.show(message, ToastAndroid.SHORT); <ide> isVisible = true; <ide><path>Libraries/Utilities/LoadingView.ios.js <ide> import processColor from '../StyleSheet/processColor'; <ide> import NativeDevLoadingView from './NativeDevLoadingView'; <ide> <ide> module.exports = { <del> showMessage(message: string) { <add> showMessage(message: string, type: 'load' | 'refresh') { <ide> if (NativeDevLoadingView) { <ide> NativeDevLoadingView.showMessage( <ide> message, <ide> // Use same colors as iOS "Personal Hotspot" bar. <ide> processColor('#ffffff'), <del> processColor('#2584e8'), <add> type && type === 'load' <add> ? processColor('#275714') <add> : processColor('#2584e8'), <ide> ); <ide> } <ide> }, <ide><path>Libraries/Utilities/LoadingView.js <ide> 'use strict'; <ide> <ide> module.exports = { <del> showMessage(message: string) {}, <add> showMessage(message: string, type: 'load' | 'refresh') {}, <ide> hide() {}, <ide> };
4
Python
Python
fix move when the two cache folders exist
6ed7e32f7cbef032ca8c5b805c5501227b4358ee
<ide><path>src/transformers/file_utils.py <ide> # Onetime move from the old location to the new one if no ENV variable has been set. <ide> if ( <ide> os.path.isdir(old_default_cache_path) <add> and not os.path.isdir(default_cache_path) <ide> and "PYTORCH_PRETRAINED_BERT_CACHE" not in os.environ <ide> and "PYTORCH_TRANSFORMERS_CACHE" not in os.environ <ide> and "TRANSFORMERS_CACHE" not in os.environ
1
Go
Go
fix a unit test broken by pull request #703
bb4b35a8920bcba8b60784297650ced5b2e01e47
<ide><path>runtime_test.go <ide> func init() { <ide> registry: registry.NewRegistry(runtime.root), <ide> } <ide> // Retrieve the Image <del> if err := srv.ImagePull(unitTestImageName, "", "", os.Stdout); err != nil { <add> if err := srv.ImagePull(unitTestImageName, "", "", os.Stdout, false); err != nil { <ide> panic(err) <ide> } <ide> } <ide> <add>// FIXME: test that ImagePull(json=true) send correct json output <add> <ide> func newTestRuntime() (*Runtime, error) { <ide> root, err := ioutil.TempDir("", "docker-test") <ide> if err != nil {
1
Python
Python
fix inplace test
2bf5fa1363944408857e368341c4299b121f928c
<ide><path>numpy/ma/tests/test_core.py <ide> class TestNoMask(NumpyTestCase): <ide> def test_no_inplace(self): <ide> x = nomask <del> def iadd(x): <del> x += 1 <del> self.failUnlessRaises(ValueError,iadd,x) <add> y = x <add> x += 1 <add> assert x != y <ide> <ide> def test_no_copy(self): <ide> x = nomask
1
Text
Text
add links to jump to sections
5e179e32b6104ca7b1586b8daa489ea7a699eef0
<ide><path>docs/testing.md <ide> description: Learn how to set up Next.js with three commonly used testing tools <ide> </ul> <ide> </details> <ide> <del>Learn how to set up Next.js with three commonly used testing tools: [Cypress](https://www.cypress.io/blog/2021/04/06/cypress-component-testing-react/), [Jest](https://jestjs.io/docs/tutorial-react), and [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/). <add>Learn how to set up Next.js with commonly used testing tools: [Cypress](https://nextjs.org/docs/testing#cypress), [Playwright](https://nextjs.org/docs/testing#playwright), and [Jest with React Testing Library](https://nextjs.org/docs/testing#jest-and-react-testing-library). <ide> <ide> ## Cypress <ide>
1
Go
Go
add minor stylistic fixes
1c89c6ea2f34f51a05215279c9cdefca30bb13b1
<ide><path>builder/internals.go <ide> func (b *Builder) run(c *daemon.Container) error { <ide> <ide> // Wait for it to finish <ide> if ret, _ := c.WaitStop(-1 * time.Second); ret != 0 { <del> err := &jsonmessage.JSONError{ <add> return &jsonmessage.JSONError{ <ide> Message: fmt.Sprintf("The command %v returned a non-zero code: %d", b.Config.Cmd, ret), <ide> Code: ret, <ide> } <del> return err <ide> } <ide> <ide> return nil <ide><path>daemon/networkdriver/bridge/driver.go <ide> func setupIPTables(addr net.Addr, icc, ipmasq bool) error { <ide> "-t", string(iptables.Nat), "-I", "POSTROUTING"}, natArgs...)...); err != nil { <ide> return fmt.Errorf("Unable to enable network bridge NAT: %s", err) <ide> } else if len(output) != 0 { <del> return &iptables.ChainError{Chain: "POSTROUTING", Output: output} <add> return iptables.ChainError{Chain: "POSTROUTING", Output: output} <ide> } <ide> } <ide> } <ide> func setupIPTables(addr net.Addr, icc, ipmasq bool) error { <ide> if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, outgoingArgs...)...); err != nil { <ide> return fmt.Errorf("Unable to allow outgoing packets: %s", err) <ide> } else if len(output) != 0 { <del> return &iptables.ChainError{Chain: "FORWARD outgoing", Output: output} <add> return iptables.ChainError{Chain: "FORWARD outgoing", Output: output} <ide> } <ide> } <ide> <ide> func setupIPTables(addr net.Addr, icc, ipmasq bool) error { <ide> if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, existingArgs...)...); err != nil { <ide> return fmt.Errorf("Unable to allow incoming packets: %s", err) <ide> } else if len(output) != 0 { <del> return &iptables.ChainError{Chain: "FORWARD incoming", Output: output} <add> return iptables.ChainError{Chain: "FORWARD incoming", Output: output} <ide> } <ide> } <ide> return nil <ide><path>pkg/iptables/iptables.go <ide> type ChainError struct { <ide> Output []byte <ide> } <ide> <del>func (e *ChainError) Error() string { <add>func (e ChainError) Error() string { <ide> return fmt.Sprintf("Error iptables %s: %s", e.Chain, string(e.Output)) <ide> } <ide> <ide> func (c *Chain) Forward(action Action, ip net.IP, port int, proto, destAddr stri <ide> "--to-destination", net.JoinHostPort(destAddr, strconv.Itoa(destPort))); err != nil { <ide> return err <ide> } else if len(output) != 0 { <del> return &ChainError{Chain: "FORWARD", Output: output} <add> return ChainError{Chain: "FORWARD", Output: output} <ide> } <ide> <ide> if output, err := Raw("-t", string(Filter), string(action), c.Name, <ide> func (c *Chain) Forward(action Action, ip net.IP, port int, proto, destAddr stri <ide> "-j", "ACCEPT"); err != nil { <ide> return err <ide> } else if len(output) != 0 { <del> return &ChainError{Chain: "FORWARD", Output: output} <add> return ChainError{Chain: "FORWARD", Output: output} <ide> } <ide> <ide> if output, err := Raw("-t", string(Nat), string(action), "POSTROUTING", <ide> func (c *Chain) Forward(action Action, ip net.IP, port int, proto, destAddr stri <ide> "-j", "MASQUERADE"); err != nil { <ide> return err <ide> } else if len(output) != 0 { <del> return &ChainError{Chain: "FORWARD", Output: output} <add> return ChainError{Chain: "FORWARD", Output: output} <ide> } <ide> <ide> return nil <ide> func (c *Chain) Prerouting(action Action, args ...string) error { <ide> if output, err := Raw(append(a, "-j", c.Name)...); err != nil { <ide> return err <ide> } else if len(output) != 0 { <del> return &ChainError{Chain: "PREROUTING", Output: output} <add> return ChainError{Chain: "PREROUTING", Output: output} <ide> } <ide> return nil <ide> } <ide> func (c *Chain) Output(action Action, args ...string) error { <ide> if output, err := Raw(append(a, "-j", c.Name)...); err != nil { <ide> return err <ide> } else if len(output) != 0 { <del> return &ChainError{Chain: "OUTPUT", Output: output} <add> return ChainError{Chain: "OUTPUT", Output: output} <ide> } <ide> return nil <ide> } <ide><path>pkg/streamformatter/streamformatter.go <ide> package streamformatter <ide> import ( <ide> "encoding/json" <ide> "fmt" <del> "github.com/docker/docker/pkg/jsonmessage" <ide> "io" <add> <add> "github.com/docker/docker/pkg/jsonmessage" <ide> ) <ide> <ide> type StreamFormatter struct { <ide><path>pkg/streamformatter/streamformatter_test.go <ide> package streamformatter <ide> import ( <ide> "encoding/json" <ide> "errors" <del> "github.com/docker/docker/pkg/jsonmessage" <ide> "reflect" <ide> "testing" <add> <add> "github.com/docker/docker/pkg/jsonmessage" <ide> ) <ide> <ide> func TestFormatStream(t *testing.T) {
5
Javascript
Javascript
avoid duplicate serialization
6fce46ebd831a2890beee225432273d9656b3085
<ide><path>lib/dependencies/NullDependency.js <ide> class NullDependency extends Dependency { <ide> get type() { <ide> return "null"; <ide> } <del> <del> serialize({ write }) { <del> write(this.loc); <del> } <del> <del> deserialize({ read }) { <del> this.loc = read(); <del> } <ide> } <ide> <ide> NullDependency.Template = class NullDependencyTemplate extends (
1
Go
Go
add case for exec closestdin
8e25f4ff6d89888a1bcd578f3f8f7aab89dce24d
<ide><path>integration/container/exec_test.go <ide> import ( <ide> "context" <ide> "io/ioutil" <ide> "testing" <add> "time" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/strslice" <ide> import ( <ide> "gotest.tools/skip" <ide> ) <ide> <add>// TestExecWithCloseStdin adds case for moby#37870 issue. <add>func TestExecWithCloseStdin(t *testing.T) { <add> skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.39"), "broken in earlier versions") <add> defer setupTest(t)() <add> <add> ctx := context.Background() <add> client := request.NewAPIClient(t) <add> <add> // run top with detached mode <add> cID := container.Run(t, ctx, client) <add> <add> expected := "closeIO" <add> execResp, err := client.ContainerExecCreate(ctx, cID, <add> types.ExecConfig{ <add> AttachStdin: true, <add> AttachStdout: true, <add> Cmd: strslice.StrSlice([]string{"sh", "-c", "cat && echo " + expected}), <add> }, <add> ) <add> assert.NilError(t, err) <add> <add> resp, err := client.ContainerExecAttach(ctx, execResp.ID, <add> types.ExecStartCheck{ <add> Detach: false, <add> Tty: false, <add> }, <add> ) <add> assert.NilError(t, err) <add> defer resp.Close() <add> <add> // close stdin to send EOF to cat <add> assert.NilError(t, resp.CloseWrite()) <add> <add> var ( <add> waitCh = make(chan struct{}) <add> resCh = make(chan struct { <add> content string <add> err error <add> }) <add> ) <add> <add> go func() { <add> close(waitCh) <add> defer close(resCh) <add> r, err := ioutil.ReadAll(resp.Reader) <add> <add> resCh <- struct { <add> content string <add> err error <add> }{ <add> content: string(r), <add> err: err, <add> } <add> }() <add> <add> <-waitCh <add> select { <add> case <-time.After(3 * time.Second): <add> t.Fatal("failed to read the content in time") <add> case got := <-resCh: <add> assert.NilError(t, got.err) <add> <add> // NOTE: using Contains because no-tty's stream contains UX information <add> // like size, stream type. <add> assert.Assert(t, is.Contains(got.content, expected)) <add> } <add>} <add> <ide> func TestExec(t *testing.T) { <ide> skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.35"), "broken in earlier versions") <ide> skip.If(t, testEnv.OSType == "windows", "FIXME. Probably needs to wait for container to be in running state.")
1
Text
Text
improve translation for russioan locale
9631152f1e510aad6c2fcbfc3fb5a26298db5ded
<ide><path>curriculum/challenges/russian/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.russian.md <ide> id: 587d7b8f367417b2b2512b62 <ide> title: Implement map on a Prototype <ide> challengeType: 1 <ide> videoUrl: '' <del>localeTitle: Реализовать карту на прототипе <add>localeTitle: Реализовать map на прототипе <ide> --- <ide> <del>## Description <del><section id="description"> Как вы видели из применения <code>Array.prototype.map()</code> или просто <code>map()</code> ранее, метод <code>map</code> возвращает массив той же длины, что и тот, на который он был вызван. Он также не изменяет исходный массив, если его функция обратного вызова не работает. Другими словами, <code>map</code> является чистой функцией, и ее выход зависит исключительно от ее входов. Кроме того, в качестве аргумента требуется другая функция. Это научит нас много о <code>map</code> чтобы попытаться реализовать версию, которая ведет себя точно так же, как <code>Array.prototype.map()</code> с циклом <code>for</code> или <code>Array.prototype.forEach()</code> . Примечание. Чистая функция позволяет изменять локальные переменные, определенные в пределах ее области действия, хотя предпочтительно избегать этого. </section> <add>## Описание <add><section id="description"> Как вы видели из применения <code>Array.prototype.map()</code> или просто <code>map()</code> ранее, метод <code>map</code> возвращает массив той же длины, что и тот, на котором он был вызван. Он также не изменяет исходный массив, если его функция обратного вызова не отработает. Другими словами, <code>map</code> является чистой функцией, и результат еевыполнения зависит исключительно от ее аргументов. Кроме того, в качестве аргумента требуется другая функция. Это достаточно описало <code>map</code> чтобы попытаться реализовать версию, которая ведет себя точно так же, как <code>Array.prototype.map()</code> с помощью цикла <code>for</code> или <code>Array.prototype.forEach()</code> . Примечание. Чистая функция позволяет изменять локальные переменные, определенные в пределах ее области действия, хотя предпочтительно избегать этого. </section> <ide> <del>## Instructions <add>## Указания <ide> <section id="instructions"> Напишите свой собственный <code>Array.prototype.myMap()</code> , который должен вести себя точно так же, как <code>Array.prototype.map()</code> . Вы можете использовать цикл <code>for</code> или метод <code>forEach</code> . </section> <ide> <del>## Tests <add>## Тесты <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <ide> <ide> </section> <ide> <del>## Challenge Seed <add>## Исходные данные <ide> <section id='challengeSeed'> <ide> <ide> <div id='js-seed'> <ide> var new_s = s.myMap(function(item){ <ide> <ide> </section> <ide> <del>## Solution <add>## Решение <ide> <section id='solution'> <ide> <ide> ```js
1
PHP
PHP
improve output of console error messages
8b27726bbec07a10cbce5cb071702d270e7e8831
<ide><path>src/Error/Renderer/ConsoleErrorRenderer.php <ide> */ <ide> namespace Cake\Error\Renderer; <ide> <add>use Cake\Console\ConsoleOutput; <ide> use Cake\Error\ErrorRendererInterface; <ide> use Cake\Error\PhpError; <ide> <ide> /** <ide> * Plain text error rendering with a stack trace. <ide> * <del> * Writes to STDERR for console environments <add> * Writes to STDERR via a Cake\Console\ConsoleOutput instance for console environments <ide> */ <ide> class ConsoleErrorRenderer implements ErrorRendererInterface <ide> { <add> /** <add> * @var \Cake\Console\ConsoleOutput <add> */ <add> private $output; <add> <add> /** <add> * Constructor. <add> * <add> * @param array $config Error handling configuration. <add> */ <add> public function __construct(array $config) <add> { <add> $this->output = $config['stderr'] ?? new ConsoleOutput('php://stderr'); <add> } <add> <ide> /** <ide> * @inheritDoc <ide> */ <ide> public function write(string $out): void <ide> { <del> // Write to stderr which is useful in console environments. <del> fwrite(STDERR, $out); <add> $this->output->write($out); <ide> } <ide> <ide> /** <ide> public function write(string $out): void <ide> public function render(PhpError $error, bool $debug): string <ide> { <ide> return sprintf( <del> "%s: %s :: %s on line %s of %s\nTrace:\n%s", <add> "<error>%s: %s :: %s</error> on line %s of %s\n<info>Trace:</info>\n%s", <ide> $error->getLabel(), <ide> $error->getCode(), <ide> $error->getMessage(),
1
Ruby
Ruby
prevent error pipe object from being finalized
c2f05cfb711401a498d494e9dcc90016e9b168a7
<ide><path>Library/Homebrew/build.rb <ide> # the whole of everything must be run in at_exit because the formula has to <ide> # be the run script as __END__ must work for *that* formula. <ide> <add> error_pipe = nil <add> <ide> begin <ide> raise $! if $! # an exception was already thrown when parsing the formula <ide> <ide> # question altogether. <ide> if ENV['HOMEBREW_ERROR_PIPE'] <ide> require 'fcntl' <del> IO.new(ENV['HOMEBREW_ERROR_PIPE'].to_i, 'w').fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) <add> error_pipe = IO.new(ENV['HOMEBREW_ERROR_PIPE'].to_i, 'w') <add> error_pipe.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) <ide> end <ide> <ide> install(Formula.factory($0)) <ide> rescue Exception => e <del> if ENV['HOMEBREW_ERROR_PIPE'] <del> pipe = IO.new(ENV['HOMEBREW_ERROR_PIPE'].to_i, 'w') <del> Marshal.dump(e, pipe) <del> pipe.close <add> unless error_pipe.nil? <add> Marshal.dump(e, error_pipe) <add> error_pipe.close <ide> exit! 1 <ide> else <ide> onoe e
1
Python
Python
update affected tests and add some news ones
9dca00889c8601fd3181466e2bd069dcfdb70272
<ide><path>libcloud/test/compute/test_ssh_client.py <ide> def setUp(self): <ide> <ide> @patch('paramiko.SSHClient', Mock) <ide> def test_create_with_password(self): <del> """ <del> Initialize object with password. <del> <del> Just to have better coverage, initialize the object <del> with the 'password' value instead of the 'key'. <del> """ <ide> conn_params = {'hostname': 'dummy.host.org', <ide> 'username': 'ubuntu', <ide> 'password': 'ubuntu'} <ide> def test_create_with_password(self): <ide> <ide> expected_conn = {'username': 'ubuntu', <ide> 'password': 'ubuntu', <del> 'allow_agent': False, <add> 'allow_agent': True, <ide> 'hostname': 'dummy.host.org', <del> 'look_for_keys': False, <add> 'look_for_keys': True, <add> 'port': 22} <add> mock.client.connect.assert_called_once_with(**expected_conn) <add> self.assertLogMsg('Connecting to server') <add> <add> @patch('paramiko.SSHClient', Mock) <add> def test_create_with_key(self): <add> conn_params = {'hostname': 'dummy.host.org', <add> 'username': 'ubuntu', <add> 'key': 'id_rsa'} <add> mock = ParamikoSSHClient(**conn_params) <add> mock.connect() <add> <add> expected_conn = {'username': 'ubuntu', <add> 'allow_agent': True, <add> 'hostname': 'dummy.host.org', <add> 'look_for_keys': True, <add> 'key_filename': 'id_rsa', <add> 'port': 22} <add> mock.client.connect.assert_called_once_with(**expected_conn) <add> self.assertLogMsg('Connecting to server') <add> <add> @patch('paramiko.SSHClient', Mock) <add> def test_create_with_password_and_key(self): <add> conn_params = {'hostname': 'dummy.host.org', <add> 'username': 'ubuntu', <add> 'password': 'ubuntu', <add> 'key': 'id_rsa'} <add> mock = ParamikoSSHClient(**conn_params) <add> mock.connect() <add> <add> expected_conn = {'username': 'ubuntu', <add> 'password': 'ubuntu', <add> 'allow_agent': True, <add> 'hostname': 'dummy.host.org', <add> 'look_for_keys': True, <add> 'key_filename': 'id_rsa', <ide> 'port': 22} <ide> mock.client.connect.assert_called_once_with(**expected_conn) <ide> self.assertLogMsg('Connecting to server') <ide> def test_basic_usage_absolute_path(self): <ide> mock_cli = mock.client # The actual mocked object: SSHClient <ide> expected_conn = {'username': 'ubuntu', <ide> 'key_filename': '~/.ssh/ubuntu_ssh', <del> 'allow_agent': False, <add> 'allow_agent': True, <ide> 'hostname': 'dummy.host.org', <del> 'look_for_keys': False, <add> 'look_for_keys': True, <ide> 'timeout': '600', <ide> 'port': 8822} <ide> mock_cli.connect.assert_called_once_with(**expected_conn)
1
Text
Text
add v4.5.0-beta.2 to changelog
75cd214c1165ad9c7bec274031eecb6404658225
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v4.5.0-beta.2 (June 6, 2022) <add> <add>- [#20082](https://github.com/emberjs/ember.js/pull/20082) [BUGFIX] Fix blueprint generation <add> <ide> ### v4.4.1 (May 31, 2022) <ide> <ide> - [#20082](https://github.com/emberjs/ember.js/pull/20082) [BUGFIX] Fix blueprints publication
1
Ruby
Ruby
fix eagerloadpolyassocstest setup
834f5414c3b879a3a50c5cac128c9d9b007fa569
<ide><path>activerecord/test/cases/associations/eager_load_nested_include_test.rb <ide> def remember; self.class.remembered << self; end <ide> end <ide> <ide> module ClassMethods <del> def remembered; @@remembered ||= []; end <del> def sample; @@remembered.sample; end <add> def remembered; @remembered ||= []; end <add> def sample; remembered.sample; end <ide> end <ide> end <ide>
1
Python
Python
handle text type correctly across python 2/3
e5263a8ad0542c477806096740b0ad5a14dec195
<ide><path>unitest-restful.py <ide> <ide> import requests <ide> <add>try: <add> text_type = str <add>except NameError: <add> text_type = unicode <add> <ide> SERVER_PORT = 61234 <ide> URL = "http://localhost:%s/api/2" % SERVER_PORT <ide> pid = None <ide> def test_003_plugins(self): <ide> req = requests.get("%s/%s" % (URL, p)) <ide> self.assertTrue(req.ok) <ide> if p in ('uptime', 'now'): <del> self.assertIsInstance(req.json(), unicode) <add> self.assertIsInstance(req.json(), text_type) <ide> elif p in ('fs', 'monitor', 'percpu', 'sensors', 'alert', 'processlist', <ide> 'diskio', 'hddtemp', 'batpercent', 'network'): <ide> self.assertIsInstance(req.json(), list)
1
Javascript
Javascript
fix side effects in router-is-ready tests
cce82cd7bcbf9c9fa61df4a808ac862aaace2b39
<ide><path>test/integration/router-is-ready/pages/auto-export/[slug].js <ide> import { useRouter } from 'next/router' <add>import { useLayoutEffect } from 'react' <ide> <ide> export default function Page(props) { <ide> const router = useRouter() <ide> <ide> if (typeof window !== 'undefined') { <del> if (!window.isReadyValues) { <del> window.isReadyValues = [] <del> } <del> window.isReadyValues.push(router.isReady) <add> // eslint-disable-next-line react-hooks/rules-of-hooks <add> useLayoutEffect(() => { <add> if (!window.isReadyValues) { <add> window.isReadyValues = [] <add> } <add> window.isReadyValues.push(router.isReady) <add> }, [router]) <ide> } <ide> <ide> return ( <ide><path>test/integration/router-is-ready/pages/auto-export/index.js <ide> import { useRouter } from 'next/router' <add>import { useLayoutEffect } from 'react' <ide> <ide> export default function Page(props) { <ide> const router = useRouter() <ide> <ide> if (typeof window !== 'undefined') { <del> if (!window.isReadyValues) { <del> window.isReadyValues = [] <del> } <del> window.isReadyValues.push(router.isReady) <add> // eslint-disable-next-line react-hooks/rules-of-hooks <add> useLayoutEffect(() => { <add> if (!window.isReadyValues) { <add> window.isReadyValues = [] <add> } <add> window.isReadyValues.push(router.isReady) <add> }, [router]) <ide> } <ide> <ide> return ( <ide><path>test/integration/router-is-ready/pages/gip.js <ide> import { useRouter } from 'next/router' <add>import { useLayoutEffect } from 'react' <ide> <ide> export default function Page(props) { <ide> const router = useRouter() <ide> <ide> if (typeof window !== 'undefined') { <del> if (!window.isReadyValues) { <del> window.isReadyValues = [] <del> } <del> window.isReadyValues.push(router.isReady) <add> // eslint-disable-next-line react-hooks/rules-of-hooks <add> useLayoutEffect(() => { <add> if (!window.isReadyValues) { <add> window.isReadyValues = [] <add> } <add> window.isReadyValues.push(router.isReady) <add> }, [router]) <ide> } <ide> <ide> return ( <ide><path>test/integration/router-is-ready/pages/gsp.js <ide> import { useRouter } from 'next/router' <add>import { useLayoutEffect } from 'react' <ide> <ide> export default function Page(props) { <ide> const router = useRouter() <ide> <ide> if (typeof window !== 'undefined') { <del> if (!window.isReadyValues) { <del> window.isReadyValues = [] <del> } <del> window.isReadyValues.push(router.isReady) <add> // eslint-disable-next-line react-hooks/rules-of-hooks <add> useLayoutEffect(() => { <add> if (!window.isReadyValues) { <add> window.isReadyValues = [] <add> } <add> window.isReadyValues.push(router.isReady) <add> }, [router]) <ide> } <ide> <ide> return ( <ide><path>test/integration/router-is-ready/pages/gssp.js <ide> import { useRouter } from 'next/router' <add>import { useLayoutEffect } from 'react' <ide> <ide> export default function Page(props) { <ide> const router = useRouter() <ide> <ide> if (typeof window !== 'undefined') { <del> if (!window.isReadyValues) { <del> window.isReadyValues = [] <del> } <del> window.isReadyValues.push(router.isReady) <add> // eslint-disable-next-line react-hooks/rules-of-hooks <add> useLayoutEffect(() => { <add> if (!window.isReadyValues) { <add> window.isReadyValues = [] <add> } <add> window.isReadyValues.push(router.isReady) <add> }, [router]) <ide> } <ide> <ide> return (
5
Mixed
Javascript
fix modal resizing on keyboard show
404b7cc069471cc8e0277d398751305665f0d3e1
<ide><path>Libraries/Modal/Modal.js <ide> const Platform = require('Platform'); <ide> const PropTypes = require('react/lib/ReactPropTypes'); <ide> const React = require('React'); <ide> const StyleSheet = require('StyleSheet'); <del>const UIManager = require('UIManager'); <ide> const View = require('View'); <del>const deprecatedPropType = require('deprecatedPropType'); <ide> <add>const deprecatedPropType = require('deprecatedPropType'); <ide> const requireNativeComponent = require('requireNativeComponent'); <ide> const RCTModalHostView = requireNativeComponent('RCTModalHostView', null); <ide> <ide> class Modal extends React.Component { <ide> <ide> const containerStyles = { <ide> backgroundColor: this.props.transparent ? 'transparent' : 'white', <del> top: Platform.OS === 'android' && Platform.Version >= 19 ? UIManager.RCTModalHostView.Constants.StatusBarHeight : 0, <ide> }; <ide> <ide> let animationType = this.props.animationType; <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.java <ide> import android.app.Dialog; <ide> import android.content.Context; <ide> import android.content.DialogInterface; <del>import android.graphics.Point; <ide> import android.view.KeyEvent; <ide> import android.view.MotionEvent; <ide> import android.view.View; <ide> import android.view.ViewGroup; <ide> import android.view.WindowManager; <ide> import android.view.accessibility.AccessibilityEvent; <add>import android.widget.FrameLayout; <ide> <ide> import com.facebook.infer.annotation.Assertions; <ide> import com.facebook.react.R; <ide> protected void showOrUpdate() { <ide> } <ide> mDialog = new Dialog(getContext(), theme); <ide> <del> mDialog.setContentView(mHostView); <add> mDialog.setContentView(getContentView()); <ide> updateProperties(); <ide> <ide> mDialog.setOnShowListener(mOnShowListener); <ide> public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { <ide> } <ide> }); <ide> <add> mDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); <ide> mDialog.show(); <ide> } <ide> <add> /** <add> * Returns the view that will be the root view of the dialog. We are wrapping this in a <add> * FrameLayout because this is the system's way of notifying us that the dialog size has changed. <add> * This has the pleasant side-effect of us not having to preface all Modals with <add> * "top: statusBarHeight", since that margin will be included in the FrameLayout. <add> */ <add> private View getContentView() { <add> FrameLayout frameLayout = new FrameLayout(getContext()); <add> frameLayout.addView(mHostView); <add> frameLayout.setFitsSystemWindows(true); <add> return frameLayout; <add> } <add> <ide> /** <ide> * updateProperties will update the properties that do not require us to recreate the dialog <ide> * Properties that do require us to recreate the dialog should set mPropertyRequiresNewDialog to <ide> protected void onSizeChanged(final int w, final int h, int oldw, int oldh) { <ide> new Runnable() { <ide> @Override <ide> public void run() { <del> Point modalSize = ModalHostHelper.getModalHostSize(getContext()); <ide> ((ReactContext) getContext()).getNativeModule(UIManagerModule.class) <del> .updateNodeSize(getChildAt(0).getId(), modalSize.x, modalSize.y); <add> .updateNodeSize(getChildAt(0).getId(), w, h); <ide> } <ide> }); <ide> }
2
Go
Go
update api_test.go to reflect new api.go
b99446831f576d626f78be7baea09af8520d125b
<ide><path>api_test.go <ide> func TestGetAuth(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> body, err := postAuth(srv, r, req, nil) <del> if err != nil { <add> if err := postAuth(srv, r, req, nil); err != nil { <ide> t.Fatal(err) <ide> } <del> if body == nil { <del> t.Fatalf("No body received\n") <del> } <ide> if r.Code != http.StatusOK && r.Code != 0 { <ide> t.Fatalf("%d OK or 0 expected, received %d\n", http.StatusOK, r.Code) <ide> } <ide> func TestGetVersion(t *testing.T) { <ide> <ide> srv := &Server{runtime: runtime} <ide> <del> body, err := getVersion(srv, nil, nil, nil) <del> if err != nil { <add> r := httptest.NewRecorder() <add> <add> if err := getVersion(srv, r, nil, nil); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> v := &ApiVersion{} <del> <del> err = json.Unmarshal(body, v) <del> if err != nil { <add> if err = json.Unmarshal(r.Body.Bytes(), v); err != nil { <ide> t.Fatal(err) <ide> } <ide> if v.Version != VERSION { <ide> func TestGetInfo(t *testing.T) { <ide> <ide> srv := &Server{runtime: runtime} <ide> <del> body, err := getInfo(srv, nil, nil, nil) <del> if err != nil { <add> r := httptest.NewRecorder() <add> <add> if err := getInfo(srv, r, nil, nil); err != nil { <ide> t.Fatal(err) <ide> } <add> <ide> infos := &ApiInfo{} <del> err = json.Unmarshal(body, infos) <add> err = json.Unmarshal(r.Body.Bytes(), infos) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestGetImagesJson(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> body, err := getImagesJson(srv, nil, req, nil) <del> if err != nil { <add> r := httptest.NewRecorder() <add> <add> if err := getImagesJson(srv, r, req, nil); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> images := []ApiImages{} <del> err = json.Unmarshal(body, &images) <del> if err != nil { <add> if err := json.Unmarshal(r.Body.Bytes(), &images); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestGetImagesJson(t *testing.T) { <ide> t.Errorf("Excepted image %s, %s found", unitTestImageName, images[0].Repository) <ide> } <ide> <add> r2 := httptest.NewRecorder() <add> <ide> // only_ids=1&all=1 <ide> req2, err := http.NewRequest("GET", "/images/json?only_ids=1&all=1", nil) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> body2, err := getImagesJson(srv, nil, req2, nil) <del> if err != nil { <add> if err := getImagesJson(srv, r2, req2, nil); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> images2 := []ApiImages{} <del> err = json.Unmarshal(body2, &images2) <del> if err != nil { <add> if err := json.Unmarshal(r2.Body.Bytes(), &images2); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestGetImagesJson(t *testing.T) { <ide> t.Errorf("Retrieved image Id differs, expected %s, received %s", GetTestImage(runtime).ShortId(), images2[0].Id) <ide> } <ide> <add> r3 := httptest.NewRecorder() <add> <ide> // filter=a <ide> req3, err := http.NewRequest("GET", "/images/json?filter=a", nil) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> body3, err := getImagesJson(srv, nil, req3, nil) <del> if err != nil { <add> if err := getImagesJson(srv, r3, req3, nil); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> images3 := []ApiImages{} <del> err = json.Unmarshal(body3, &images3) <del> if err != nil { <add> if err := json.Unmarshal(r3.Body.Bytes(), &images3); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestGetImagesViz(t *testing.T) { <ide> srv := &Server{runtime: runtime} <ide> <ide> r := httptest.NewRecorder() <del> <del> _, err = getImagesViz(srv, r, nil, nil) <del> if err != nil { <add> if err := getImagesViz(srv, r, nil, nil); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestGetImagesSearch(t *testing.T) { <ide> <ide> srv := &Server{runtime: runtime} <ide> <add> r := httptest.NewRecorder() <add> <ide> req, err := http.NewRequest("GET", "/images/search?term=redis", nil) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> body, err := getImagesSearch(srv, nil, req, nil) <del> if err != nil { <add> if err := getImagesSearch(srv, r, req, nil); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> results := []ApiSearch{} <del> err = json.Unmarshal(body, &results) <del> if err != nil { <add> if err := json.Unmarshal(r.Body.Bytes(), &results); err != nil { <ide> t.Fatal(err) <ide> } <ide> if len(results) < 2 { <ide> func TestGetImagesHistory(t *testing.T) { <ide> <ide> srv := &Server{runtime: runtime} <ide> <del> body, err := getImagesHistory(srv, nil, nil, map[string]string{"name": unitTestImageName}) <del> if err != nil { <add> r := httptest.NewRecorder() <add> <add> if err := getImagesHistory(srv, r, nil, map[string]string{"name": unitTestImageName}); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> history := []ApiHistory{} <del> err = json.Unmarshal(body, &history) <del> if err != nil { <add> if err := json.Unmarshal(r.Body.Bytes(), &history); err != nil { <ide> t.Fatal(err) <ide> } <ide> if len(history) != 1 { <ide> func TestGetImagesByName(t *testing.T) { <ide> <ide> srv := &Server{runtime: runtime} <ide> <del> body, err := getImagesByName(srv, nil, nil, map[string]string{"name": unitTestImageName}) <del> if err != nil { <add> r := httptest.NewRecorder() <add> if err := getImagesByName(srv, r, nil, map[string]string{"name": unitTestImageName}); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> img := &Image{} <del> <del> err = json.Unmarshal(body, img) <del> if err != nil { <add> if err := json.Unmarshal(r.Body.Bytes(), img); err != nil { <ide> t.Fatal(err) <ide> } <ide> if img.Id != GetTestImage(runtime).Id || img.Comment != "Imported from http://get.docker.io/images/busybox" { <ide> func TestGetContainersPs(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> body, err := getContainersPs(srv, nil, req, nil) <del> if err != nil { <add> r := httptest.NewRecorder() <add> if err := getContainersPs(srv, r, req, nil); err != nil { <ide> t.Fatal(err) <ide> } <ide> containers := []ApiContainers{} <del> err = json.Unmarshal(body, &containers) <del> if err != nil { <add> if err := json.Unmarshal(r.Body.Bytes(), &containers); err != nil { <ide> t.Fatal(err) <ide> } <ide> if len(containers) != 1 { <ide> func TestGetContainersExport(t *testing.T) { <ide> } <ide> <ide> r := httptest.NewRecorder() <del> <del> _, err = getContainersExport(srv, r, nil, map[string]string{"name": container.Id}) <del> if err != nil { <add> if err = getContainersExport(srv, r, nil, map[string]string{"name": container.Id}); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestGetContainersChanges(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> body, err := getContainersChanges(srv, nil, nil, map[string]string{"name": container.Id}) <del> if err != nil { <add> r := httptest.NewRecorder() <add> if err := getContainersChanges(srv, r, nil, map[string]string{"name": container.Id}); err != nil { <ide> t.Fatal(err) <ide> } <ide> changes := []Change{} <del> if err := json.Unmarshal(body, &changes); err != nil { <add> if err := json.Unmarshal(r.Body.Bytes(), &changes); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestGetContainersByName(t *testing.T) { <ide> } <ide> defer runtime.Destroy(container) <ide> <del> body, err := getContainersByName(srv, nil, nil, map[string]string{"name": container.Id}) <del> if err != nil { <add> r := httptest.NewRecorder() <add> if err := getContainersByName(srv, r, nil, map[string]string{"name": container.Id}); err != nil { <ide> t.Fatal(err) <ide> } <ide> outContainer := &Container{} <del> if err := json.Unmarshal(body, outContainer); err != nil { <add> if err := json.Unmarshal(r.Body.Bytes(), outContainer); err != nil { <ide> t.Fatal(err) <ide> } <ide> if outContainer.Id != container.Id { <ide> func TestPostAuth(t *testing.T) { <ide> } <ide> runtime.authConfig = authConfigOrig <ide> <del> body, err := getAuth(srv, nil, nil, nil) <del> if err != nil { <add> r := httptest.NewRecorder() <add> if err := getAuth(srv, r, nil, nil); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> authConfig := &auth.AuthConfig{} <del> err = json.Unmarshal(body, authConfig) <del> if err != nil { <add> if err := json.Unmarshal(r.Body.Bytes(), authConfig); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestPostCommit(t *testing.T) { <ide> <ide> srv := &Server{runtime: runtime} <ide> <del> r := httptest.NewRecorder() <del> <ide> builder := NewBuilder(runtime) <ide> <ide> // Create a container and remove a file <ide> func TestPostCommit(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> body, err := postCommit(srv, r, req, nil) <del> if err != nil { <add> r := httptest.NewRecorder() <add> if err := postCommit(srv, r, req, nil); err != nil { <ide> t.Fatal(err) <ide> } <ide> if r.Code != http.StatusCreated { <ide> t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code) <ide> } <ide> <ide> apiId := &ApiId{} <del> if err := json.Unmarshal(body, apiId); err != nil { <add> if err := json.Unmarshal(r.Body.Bytes(), apiId); err != nil { <ide> t.Fatal(err) <ide> } <ide> if _, err := runtime.graph.Get(apiId.Id); err != nil { <ide> func TestPostBuild(t *testing.T) { <ide> <ide> c1 := make(chan struct{}) <ide> go func() { <add> defer close(c1) <ide> r := &hijackTester{ <ide> ResponseRecorder: httptest.NewRecorder(), <ide> in: stdin, <ide> out: stdoutPipe, <ide> } <ide> <del> body, err := postBuild(srv, r, nil, nil) <del> close(c1) <del> if err != nil { <add> if err := postBuild(srv, r, nil, nil); err != nil { <ide> t.Fatal(err) <ide> } <del> if body != nil { <del> t.Fatalf("No body expected, received: %s\n", body) <del> } <ide> }() <ide> <ide> // Acknowledge hijack <ide> func TestPostContainersCreate(t *testing.T) { <ide> <ide> srv := &Server{runtime: runtime} <ide> <del> r := httptest.NewRecorder() <del> <ide> configJson, err := json.Marshal(&Config{ <ide> Image: GetTestImage(runtime).Id, <ide> Memory: 33554432, <ide> func TestPostContainersCreate(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> body, err := postContainersCreate(srv, r, req, nil) <del> if err != nil { <add> r := httptest.NewRecorder() <add> if err := postContainersCreate(srv, r, req, nil); err != nil { <ide> t.Fatal(err) <ide> } <ide> if r.Code != http.StatusCreated { <ide> t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code) <ide> } <ide> <ide> apiRun := &ApiRun{} <del> if err := json.Unmarshal(body, apiRun); err != nil { <add> if err := json.Unmarshal(r.Body.Bytes(), apiRun); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestPostContainersKill(t *testing.T) { <ide> } <ide> <ide> r := httptest.NewRecorder() <del> <del> body, err := postContainersKill(srv, r, nil, map[string]string{"name": container.Id}) <del> if err != nil { <add> if err := postContainersKill(srv, r, nil, map[string]string{"name": container.Id}); err != nil { <ide> t.Fatal(err) <ide> } <del> if body != nil { <del> t.Fatalf("No body expected, received: %s\n", body) <del> } <ide> if r.Code != http.StatusNoContent { <ide> t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code) <ide> } <ide> func TestPostContainersRestart(t *testing.T) { <ide> t.Errorf("Container should be running") <ide> } <ide> <del> r := httptest.NewRecorder() <del> <ide> req, err := http.NewRequest("POST", "/containers/"+container.Id+"/restart?t=1", bytes.NewReader([]byte{})) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> body, err := postContainersRestart(srv, r, req, map[string]string{"name": container.Id}) <del> if err != nil { <add> r := httptest.NewRecorder() <add> if err := postContainersRestart(srv, r, req, map[string]string{"name": container.Id}); err != nil { <ide> t.Fatal(err) <ide> } <del> if body != nil { <del> t.Fatalf("No body expected, received: %s\n", body) <del> } <ide> if r.Code != http.StatusNoContent { <ide> t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code) <ide> } <ide> func TestPostContainersStart(t *testing.T) { <ide> defer runtime.Destroy(container) <ide> <ide> r := httptest.NewRecorder() <del> <del> body, err := postContainersStart(srv, r, nil, map[string]string{"name": container.Id}) <del> if err != nil { <add> if err := postContainersStart(srv, r, nil, map[string]string{"name": container.Id}); err != nil { <ide> t.Fatal(err) <ide> } <del> if body != nil { <del> t.Fatalf("No body expected, received: %s\n", body) <del> } <ide> if r.Code != http.StatusNoContent { <ide> t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code) <ide> } <ide> func TestPostContainersStart(t *testing.T) { <ide> t.Errorf("Container should be running") <ide> } <ide> <del> if _, err = postContainersStart(srv, r, nil, map[string]string{"name": container.Id}); err == nil { <add> r = httptest.NewRecorder() <add> if err = postContainersStart(srv, r, nil, map[string]string{"name": container.Id}); err == nil { <ide> t.Fatalf("A running containter should be able to be started") <ide> } <ide> <ide> func TestPostContainersStop(t *testing.T) { <ide> t.Errorf("Container should be running") <ide> } <ide> <del> r := httptest.NewRecorder() <del> <ide> // Note: as it is a POST request, it requires a body. <ide> req, err := http.NewRequest("POST", "/containers/"+container.Id+"/stop?t=1", bytes.NewReader([]byte{})) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> body, err := postContainersStop(srv, r, req, map[string]string{"name": container.Id}) <del> if err != nil { <add> r := httptest.NewRecorder() <add> if err := postContainersStop(srv, r, req, map[string]string{"name": container.Id}); err != nil { <ide> t.Fatal(err) <ide> } <del> if body != nil { <del> t.Fatalf("No body expected, received: %s\n", body) <del> } <ide> if r.Code != http.StatusNoContent { <ide> t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code) <ide> } <ide> func TestPostContainersWait(t *testing.T) { <ide> } <ide> <ide> setTimeout(t, "Wait timed out", 3*time.Second, func() { <del> body, err := postContainersWait(srv, nil, nil, map[string]string{"name": container.Id}) <del> if err != nil { <add> r := httptest.NewRecorder() <add> if err := postContainersWait(srv, r, nil, map[string]string{"name": container.Id}); err != nil { <ide> t.Fatal(err) <ide> } <ide> apiWait := &ApiWait{} <del> if err := json.Unmarshal(body, apiWait); err != nil { <add> if err := json.Unmarshal(r.Body.Bytes(), apiWait); err != nil { <ide> t.Fatal(err) <ide> } <ide> if apiWait.StatusCode != 0 { <ide> func TestPostContainersAttach(t *testing.T) { <ide> // Attach to it <ide> c1 := make(chan struct{}) <ide> go func() { <del> // We're simulating a disconnect so the return value doesn't matter. What matters is the <del> // fact that CmdAttach returns. <add> defer close(c1) <ide> <ide> r := &hijackTester{ <ide> ResponseRecorder: httptest.NewRecorder(), <ide> func TestPostContainersAttach(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> body, err := postContainersAttach(srv, r, req, map[string]string{"name": container.Id}) <del> close(c1) <del> if err != nil { <add> if err := postContainersAttach(srv, r, req, map[string]string{"name": container.Id}); err != nil { <ide> t.Fatal(err) <ide> } <del> if body != nil { <del> t.Fatalf("No body expected, received: %s\n", body) <del> } <ide> }() <ide> <ide> // Acknowledge hijack <ide> func TestDeleteContainers(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> r := httptest.NewRecorder() <del> <ide> req, err := http.NewRequest("DELETE", "/containers/"+container.Id, nil) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> <del> body, err := deleteContainers(srv, r, req, map[string]string{"name": container.Id}) <del> if err != nil { <add> r := httptest.NewRecorder() <add> if err := deleteContainers(srv, r, req, map[string]string{"name": container.Id}); err != nil { <ide> t.Fatal(err) <ide> } <del> if body != nil { <del> t.Fatalf("No body expected, received: %s\n", body) <del> } <ide> if r.Code != http.StatusNoContent { <ide> t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code) <ide> } <ide> func TestDeleteContainers(t *testing.T) { <ide> <ide> func TestDeleteImages(t *testing.T) { <ide> //FIXME: Implement this test <del> t.Log("Test not implemented") <add> t.Skip("Test not implemented") <ide> } <ide> <ide> // Mocked types for tests
1
Go
Go
remove migration code from docker 1.11 to 1.12
0f3b94a5c7efa3032203dcaf0dc41570c900fd7e
<ide><path>daemon/daemon.go <ide> func (daemon *Daemon) restore() error { <ide> mapLock.Unlock() <ide> return <ide> } <del> <del> // The LogConfig.Type is empty if the container was created before docker 1.12 with default log driver. <del> // We should rewrite it to use the daemon defaults. <del> // Fixes https://github.com/docker/docker/issues/22536 <del> if c.HostConfig.LogConfig.Type == "" { <del> if err := daemon.mergeAndVerifyLogConfig(&c.HostConfig.LogConfig); err != nil { <del> log.WithError(err).Error("failed to verify log config for container") <del> } <del> } <ide> }(c) <ide> } <ide> group.Wait()
1
Mixed
Ruby
make salt argument required for message verifier
48c703b055a6b287100f3c0fbc18f1294d7c7af4
<ide><path>railties/CHANGELOG.md <ide> <ide> This verifier can be used to generate and verify signed messages in the application. <ide> <del> message = Rails.application.message_verifier.generate('my sensible data') <del> Rails.application.message_verifier.verify(message) <add> message = Rails.application.message_verifier('salt').generate('my sensible data') <add> Rails.application.message_verifier('salt').verify(message) <ide> # => 'my sensible data' <ide> <ide> It is recommended not to use the same verifier for different things, so you can get different <ide><path>railties/lib/rails/application.rb <ide> def key_generator <ide> # <ide> # ==== Parameters <ide> # <del> # * +verifier_name+ - the name of verifier you want to get. <add> # * +salt+ - the salt that will be used to generate the secret key of the verifier. <ide> # <ide> # ==== Examples <ide> # <del> # message = Rails.application.message_verifier.generate('my sensible data') <del> # Rails.application.message_verifier.verify(message) <add> # message = Rails.application.message_verifier('salt').generate('my sensible data') <add> # Rails.application.message_verifier('salt').verify(message) <ide> # # => 'my sensible data' <ide> # <ide> # See the +ActiveSupport::MessageVerifier+ documentation for more information. <del> def message_verifier(verifier_name = 'default') <del> @message_verifiers[verifier_name] ||= begin <del> secret = key_generator.generate_key(verifier_name) <add> def message_verifier(salt) <add> @message_verifiers[salt] ||= begin <add> secret = key_generator.generate_key(salt) <ide> ActiveSupport::MessageVerifier.new(secret) <ide> end <ide> end <ide><path>railties/test/application/configuration_test.rb <ide> def index <ide> app.config.session_store :disabled <ide> end <ide> <del> message = app.message_verifier.generate("some_value") <add> message = app.message_verifier('salt').generate("some_value") <ide> <del> assert_equal 'some_value', Rails.application.message_verifier.verify(message) <add> assert_equal 'some_value', Rails.application.message_verifier('salt').verify(message) <ide> <del> secret = app.key_generator.generate_key('default') <add> secret = app.key_generator.generate_key('salt') <ide> verifier = ActiveSupport::MessageVerifier.new(secret) <ide> assert_equal 'some_value', verifier.verify(message) <ide> end <ide> def index <ide> app.config.session_store :disabled <ide> end <ide> <del> default_verifier = app.message_verifier <add> default_verifier = app.message_verifier('salt') <ide> text_verifier = app.message_verifier('text') <ide> <ide> message = text_verifier.generate('some_value') <ide> def index <ide> default_verifier.verify(message) <ide> end <ide> <del> assert_equal default_verifier.object_id, app.message_verifier.object_id <add> assert_equal default_verifier.object_id, app.message_verifier('salt').object_id <ide> assert_not_equal default_verifier.object_id, text_verifier.object_id <ide> end <ide>
3
Ruby
Ruby
fix a rubocop offence for `lint/erbnewarguments`
c03933af23557945dd7d5d1359779d2ea461542c
<ide><path>tasks/release.rb <ide> def rc? <ide> require "erb" <ide> template = File.read("../tasks/release_announcement_draft.erb") <ide> <del> if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+ <del> puts ERB.new(template, trim_mode: "<>").result(binding) <del> else <del> puts ERB.new(template, nil, "<>").result(binding) <del> end <add> puts ERB.new(template, trim_mode: "<>").result(binding) <ide> end <ide> end
1
Python
Python
fix code example
08816de16aef6a85c187c599a6779d292c376f83
<ide><path>src/transformers/models/encoder_decoder/modeling_encoder_decoder.py <ide> def forward( <ide> >>> model.config.pad_token_id = tokenizer.pad_token_id <ide> >>> model.config.vocab_size = model.config.decoder.vocab_size <ide> <del> >>> input_ids = tokenizer("Hello, my dog is cute", return_tensors="pt").input_ids <del> >>> labels = tokenizer("Salut, mon chien est mignon", return_tensors="pt").input_ids <add> >>> input_ids = tokenizer("This is a really long text", return_tensors="pt").input_ids <add> >>> labels = tokenizer("This is the corresponding summary", return_tensors="pt").input_ids <ide> >>> outputs = model(input_ids=input_ids, labels=input_ids) <ide> >>> loss, logits = outputs.loss, outputs.logits <ide> <ide> def forward( <ide> >>> model = EncoderDecoderModel.from_pretrained("bert2bert") <ide> <ide> >>> # generation <del> >>> generated = model.generate(input_ids, decoder_start_token_id=model.config.decoder.pad_token_id) <add> >>> generated = model.generate(input_ids) <ide> <ide> """ <ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1
Ruby
Ruby
convert path to string before call `length`
1d26c86b8611bb37f5641d4f3e3e94d8675eba1d
<ide><path>railties/lib/rails/engine.rb <ide> def load_generators(app = self) <ide> def eager_load! <ide> config.eager_load_paths.each do |load_path| <ide> # Starts after load_path plus a slash, ends before ".rb". <del> relname_range = (load_path.length + 1)...-3 <add> relname_range = (load_path.to_s.length + 1)...-3 <ide> Dir.glob("#{load_path}/**/*.rb").sort.each do |file| <ide> require_dependency file[relname_range] <ide> end
1
Javascript
Javascript
improve pipe-test. still not working
393f0071e4cabc05d083a43e8da76f166b9d0f0a
<ide><path>test/disabled/pipe-test.js <del>/* <del> * try with <del> * curl -d @/usr/share/dict/words http://localhost:8000/123 <add>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <add>var net = require('net'); <add> <add>var listenCount = 0; <add>var gotThanks = false; <add>var tcpLengthSeen; <add> <add> <add>/* <add> * 5MB of random buffer. <ide> */ <add>var buffer = Buffer(1024 * 1024 * 5); <add>for (var i = 0; i < buffer.length; i++) { <add> buffer[i] = parseInt(Math.random()*10000); <add>} <ide> <del>http = require('http'); <ide> <del>s = http.Server(function (req, res) { <add>var web = http.Server(function (req, res) { <add> web.close(); <add> <ide> console.log(req.headers); <ide> <del> req.pipe(process.stdout, { end: false }); <add> var socket = net.Stream(); <add> socket.connect(tcpPort); <add> <add> req.pipe(socket); <ide> <ide> req.on('end', function () { <ide> res.writeHead(200); <ide> res.write("thanks"); <ide> res.end(); <ide> }); <ide> }); <add>var webPort = common.PORT <add>web.listen(webPort, startClient); <add> <add> <add> <add>var tcp = net.Server(function (socket) { <add> tcp.close(); <add> <add> var i = 0; <add> <add> socket.on('data', function (d) { <add> for (var j = 0; j < d.length; j++) { <add> assert.equal(i % 256, d[i]); <add> i++; <add> } <add> }); <add> <add> socket.on('end', function () { <add> tcpLengthSeen = i; <add> socket.end(); <add> }); <add>}); <add>var tcpPort = webPort + 1; <add>tcp.listen(tcpPort, startClient); <add> <add> <add>function startClient () { <add> listenCount++; <add> console.log("listenCount %d" , listenCount); <add> if (listenCount < 2) { <add> console.log("dont start client %d" , listenCount); <add> return; <add> } <add> <add> console.log("start client"); <add> <add> var client = http.createClient(common.PORT); <add> var req = client.request('GET', '/'); <add> req.write(buffer); <add> req.end(); <add> <add> req.on('response', function (res) { <add> res.setEncoding('utf8'); <add> res.on('data', function (s) { <add> assert.equal("thanks", s); <add> gotThanks = true; <add> }); <add> }); <add>} <add> <add>process.on('exit', function () { <add> assert.ok(gotThanks); <add> assert.equal(1024*1024*5, tcpLengthSeen); <add>}); <ide> <del>s.listen(8000);
1
PHP
PHP
remove duplicate parameter doc string
b539959e0e7f3204ad4b91d519309641333de478
<ide><path>src/ORM/Table.php <ide> public function validateUnique($value, array $options, array $context = []) { <ide> * @param \Cake\Datasource\EntityInterface $entity The entity to check for validity. <ide> * @param string $operation The operation being run. Either 'create', 'update' or 'delete'. <ide> * @param \ArrayObject|array $options The options To be passed to the rules. <del> * @param string $operation Either 'create, 'update' or 'delete'. <ide> * @return bool <ide> */ <ide> public function checkRules(EntityInterface $entity, $operation = RulesChecker::CREATE, $options = null) {
1
Javascript
Javascript
suggest course of action
2fe82af05d27014a922afbf360d37217f981604a
<ide><path>lib/WebpackOptionsValidationError.js <ide> class WebpackOptionsValidationError extends Error { <ide> else <ide> return `${dataPath} ${err.message}`; <ide> } else if(err.keyword === "absolutePath") { <del> return `${dataPath}: ${err.message}`; <add> const baseMessage = `${dataPath}: ${err.message}`; <add> if(dataPath === "configuration.output.filename") { <add> return `${baseMessage}\n` + <add> "Please use output.path to specify absolute path and output.filename for the file name."; <add> } <add> return baseMessage; <ide> } else { <ide> // eslint-disable-line no-fallthrough <ide> return `${dataPath} ${err.message} (${JSON.stringify(err, 0, 2)}).\n${getSchemaPartText(err.parentSchema)}`; <ide><path>test/Validation.test.js <ide> describe("Validation", () => { <ide> }, <ide> message: [ <ide> " - configuration.output.filename: A relative path is expected. However the provided value \"/bar\" is an absolute path!", <add> " Please use output.path to specify absolute path and output.filename for the file name." <ide> ] <ide> }, { <ide> name: "absolute path",
2
Text
Text
add patreon badge
0271e76f08f122b4b6dde90f7e49066696072953
<ide><path>README.md <ide> Documentation is under the [Creative Commons Attribution license](https://creati <ide> ## Donations <ide> Homebrew is a non-profit project run entirely by unpaid volunteers. We need your funds to pay for software, hardware and hosting around continuous integration and future improvements to the project. Every donation will be spent on making Homebrew better for our users. <ide> <del>Homebrew is a member of the [Software Freedom Conservancy](http://sfconservancy.org) which provides us with an ability to receive tax-deductible, Homebrew earmarked donations (and [many other services](http://sfconservancy.org/members/services/)). Software Freedom Conservancy, Inc. is a 501(c)(3) organization incorporated in New York, and donations made to it are fully tax-deductible to the extent permitted by law. <del> <del>- [Donate with PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=V6ZE57MJRYC8L) <del>- Donate by USA $ check from a USA bank: <del> - Make check payable to "Software Freedom Conservancy, Inc." and place "Directed donation: Homebrew" in the memo field. Checks should then be mailed to: <del> - Software Freedom Conservancy, Inc. <del> 137 Montague ST STE 380 <del> BROOKLYN, NY 11201 USA <del>- Donate by wire transfer: contact [email protected] for wire transfer details. <del>- Donate with Flattr or PayPal Giving Fund: coming soon. <add>Please consider a regular donation through Patreon: <add>[![Donate with Patreon](https://img.shields.io/badge/patreon-donate-green.svg)](https://www.patreon.com/homebrew) <ide> <ide> ## Sponsors <ide> Our CI infrastructure was paid for by [our Kickstarter supporters](https://github.com/Homebrew/brew/blob/master/docs/Kickstarter-Supporters.md).
1
Java
Java
relax constraints in messageheaders for subclasses
1eee339c152a3de2f2a37525899be28bb0bfaf0a
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/MessageHeaders.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * <b>IMPORTANT</b>: This class is immutable. Any mutating operation such as <ide> * {@code put(..)}, {@code putAll(..)} and others will throw <ide> * {@link UnsupportedOperationException}. <add> * <p>Subclasses do have access to the raw headers, however, via {@link #getRawHeaders()}. <ide> * <p> <ide> * One way to create message headers is to use the <ide> * {@link org.springframework.messaging.support.MessageBuilder MessageBuilder}: <ide> * @see org.springframework.messaging.support.MessageBuilder <ide> * @see org.springframework.messaging.support.MessageHeaderAccessor <ide> */ <del>public final class MessageHeaders implements Map<String, Object>, Serializable { <add>public class MessageHeaders implements Map<String, Object>, Serializable { <ide> <ide> private static final long serialVersionUID = -4615750558355702881L; <ide> <ide> public final class MessageHeaders implements Map<String, Object>, Serializable { <ide> <ide> private final Map<String, Object> headers; <ide> <add> /** <add> * Constructs a minimal {@link MessageHeaders} with zero headers. <add> */ <add> protected MessageHeaders() { <add> this.headers = new HashMap<String, Object>(); <add> } <ide> <add> /** <add> * Consructs a {@link MessageHeaders} from the headers map; adding (or <add> * overwriting) the {@link #ID} and {@link #TIMESTAMP} headers. <add> * @param headers The map. <add> */ <ide> public MessageHeaders(Map<String, Object> headers) { <ide> this.headers = (headers != null) ? new HashMap<String, Object>(headers) : new HashMap<String, Object>(); <ide> this.headers.put(ID, ((idGenerator != null) ? idGenerator : defaultIdGenerator).generateId()); <ide> this.headers.put(TIMESTAMP, System.currentTimeMillis()); <ide> } <ide> <add> protected Map<String, Object> getRawHeaders() { <add> return this.headers; <add> } <ide> <ide> public UUID getId() { <ide> return this.get(ID, UUID.class); <ide><path>spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> import java.util.Set; <add>import java.util.UUID; <add>import java.util.concurrent.atomic.AtomicLong; <ide> <ide> import org.junit.Test; <ide> <ide> * Test fixture for {@link MessageHeaders}. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Gary Russell <ide> */ <ide> public class MessageHeadersTests { <ide> <ide> public void serializeWithNonSerializableHeader() throws Exception { <ide> assertNull(output.get("address")); <ide> } <ide> <add> @Test <add> public void subclass() { <add> final AtomicLong id = new AtomicLong(); <add> @SuppressWarnings("serial") <add> class MyMH extends MessageHeaders { <add> <add> public MyMH() { <add> this.getRawHeaders().put(ID, new UUID(0, id.incrementAndGet())); <add> } <add> <add> } <add> MessageHeaders headers = new MyMH(); <add> assertEquals("00000000-0000-0000-0000-000000000001", headers.getId().toString()); <add> assertEquals(1, headers.size()); <add> } <ide> <ide> private static Object serializeAndDeserialize(Object object) throws Exception { <ide> ByteArrayOutputStream baos = new ByteArrayOutputStream();
2
Text
Text
add example about branch and a branch model
8e1970ce85a5707186b8a248354f906e5f7febaf
<ide><path>guide/portuguese/git/git-branch/index.md <ide> localeTitle: Filial Git <ide> <ide> A funcionalidade de ramificação do Git permite criar novas ramificações de um projeto para testar ideias, isolar novos recursos ou experimentar sem afetar o projeto principal. <ide> <add>A ramificação no Git é muito útil, pois ajuda na organização do repositório e também facilita o entendimento da estrutura do código. Pode-se, por exemplo, em projetos onde se tenham mais de um desenvolvedor trabalhando no código, adotar regras de ramificações. De forma que a ramificação "master" (que é a padrão, criada automáticamente pelo Git ao se iniciar um repositório), seja sempre a ramificação com código em estado pronto, e a cada correção, atualização, introdução de uma nova funcionalidade no projeto, deve-se primeiro criar uma nova ramificação, identificando-a por exemplo como "correcao-bug" e testar o código até que esteja estável e que tenha resolvido o bug, para então, após testado e comprovado o resultado, dar um merge na ramificação master. <add> <add>Na imagem abaixo, tem-se um exemplo de como é a ramificação no Git, com três ramificações: master, hotfix e iss53. <add> <add>![Exemplo de ramificação no Git](https://git-scm.com/figures/18333fig0313-tn.png "Exemplo de ramificação no Git") <add> <ide> **Índice** <ide> <ide> * [Exibir filiais](#view-branches) <ide> git help branch <ide> * O comando `git checkout` : [fCC Guide](https://guide.freecodecamp.org/git/git-checkout/) <ide> * O comando `git commit` : [fCC Guide](https://guide.freecodecamp.org/git/git-commit/) <ide> * O comando `git stash` : [fCC Guide](https://guide.freecodecamp.org/git/git-stash/) <del>* Documentação do Git: [branch](https://git-scm.com/docs/git-branch) <ide>\ No newline at end of file <add>* Documentação do Git: [branch](https://git-scm.com/docs/git-branch) <add>* Um modelo de ramificação bem-sucedido do Git (post original em inglês): [A successful Git branching model](https://nvie.com/posts/a-successful-git-branching-model/)
1
PHP
PHP
remove unneeded type casting
f664c358b6c6109499c327f776e018d0f0c7953b
<ide><path>src/Utility/Security.php <ide> public static function getSalt(): string <ide> */ <ide> public static function setSalt(string $salt): void <ide> { <del> static::$_salt = (string)$salt; <add> static::$_salt = $salt; <ide> } <ide> }
1
Java
Java
integrate fabric into rn tester
8724a24bf58f63ee240dea9f6795873c0a6ff3bf
<ide><path>RNTester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.java <ide> <ide> package com.facebook.react.uiapp; <ide> <add>import static com.facebook.react.uiapp.RNTesterApplication.IS_FABRIC_ENABLED; <add> <ide> import android.content.res.Configuration; <ide> import android.os.Bundle; <ide> import androidx.annotation.Nullable; <ide> import com.facebook.react.ReactActivity; <ide> import com.facebook.react.ReactActivityDelegate; <ide> import com.facebook.react.ReactInstanceManager; <add>import com.facebook.react.ReactRootView; <ide> <ide> public class RNTesterActivity extends ReactActivity { <ide> public static class RNTesterActivityDelegate extends ReactActivityDelegate { <ide> public RNTesterActivityDelegate(ReactActivity activity, String mainComponentName <ide> this.mActivity = activity; <ide> } <ide> <add> @Override <add> protected ReactRootView createRootView() { <add> ReactRootView reactRootView = new ReactRootView(getContext()); <add> reactRootView.setIsFabric(IS_FABRIC_ENABLED); <add> return reactRootView; <add> } <add> <ide> @Override <ide> protected void onCreate(Bundle savedInstanceState) { <ide> // Get remote param before calling super which uses it <ide><path>RNTester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java <ide> <ide> package com.facebook.react.uiapp; <ide> <add>import static com.facebook.react.uiapp.BuildConfig.FLAVOR; <add> <ide> import android.app.Application; <ide> import android.content.Context; <add>import androidx.annotation.Nullable; <ide> import com.facebook.react.BuildConfig; <ide> import com.facebook.react.ReactApplication; <ide> import com.facebook.react.ReactInstanceManager; <ide> import com.facebook.react.ReactNativeHost; <ide> import com.facebook.react.ReactPackage; <add>import com.facebook.react.bridge.JSIModulePackage; <add>import com.facebook.react.bridge.JSIModuleProvider; <add>import com.facebook.react.bridge.JSIModuleSpec; <add>import com.facebook.react.bridge.JSIModuleType; <add>import com.facebook.react.bridge.JavaScriptContextHolder; <add>import com.facebook.react.bridge.ReactApplicationContext; <add>import com.facebook.react.bridge.UIManager; <add>import com.facebook.react.fabric.ComponentFactory; <add>import com.facebook.react.fabric.CoreComponentsRegistry; <add>import com.facebook.react.fabric.FabricJSIModuleProvider; <add>import com.facebook.react.fabric.ReactNativeConfig; <ide> import com.facebook.react.shell.MainReactPackage; <ide> import com.facebook.react.views.text.ReactFontManager; <ide> import com.facebook.soloader.SoLoader; <ide> import java.lang.reflect.InvocationTargetException; <add>import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.List; <ide> <ide> public class RNTesterApplication extends Application implements ReactApplication { <add> <add> static final boolean IS_FABRIC_ENABLED = FLAVOR.contains("fabric"); <add> <ide> private final ReactNativeHost mReactNativeHost = <ide> new ReactNativeHost(this) { <ide> @Override <ide> public boolean getUseDeveloperSupport() { <ide> public List<ReactPackage> getPackages() { <ide> return Arrays.<ReactPackage>asList(new MainReactPackage()); <ide> } <add> <add> @Nullable <add> @Override <add> protected JSIModulePackage getJSIModulePackage() { <add> if (!IS_FABRIC_ENABLED) { <add> return null; <add> } <add> <add> return new JSIModulePackage() { <add> @Override <add> public List<JSIModuleSpec> getJSIModules( <add> final ReactApplicationContext reactApplicationContext, <add> final JavaScriptContextHolder jsContext) { <add> List<JSIModuleSpec> specs = new ArrayList<>(); <add> specs.add( <add> new JSIModuleSpec() { <add> @Override <add> public JSIModuleType getJSIModuleType() { <add> return JSIModuleType.UIManager; <add> } <add> <add> @Override <add> public JSIModuleProvider<UIManager> getJSIModuleProvider() { <add> ComponentFactory ComponentFactory = new ComponentFactory(); <add> CoreComponentsRegistry.register(ComponentFactory); <add> return new FabricJSIModuleProvider( <add> reactApplicationContext, <add> ComponentFactory, <add> // TODO: T71362667 add ReactNativeConfig's support in RNTester <add> new ReactNativeConfig() { <add> @Override <add> public boolean getBool(String s) { <add> return true; <add> } <add> <add> @Override <add> public int getInt64(String s) { <add> return 0; <add> } <add> <add> @Override <add> public String getString(String s) { <add> return ""; <add> } <add> <add> @Override <add> public double getDouble(String s) { <add> return 0; <add> } <add> }); <add> } <add> }); <add> <add> return specs; <add> } <add> }; <add> } <ide> }; <ide> <ide> @Override
2
Ruby
Ruby
translate ast to a formatter before url generation
e883db02bce5d5f06628dc9eae51c8f526a4df97
<ide><path>actionpack/lib/action_dispatch/journey/route.rb <ide> def format(path_options) <ide> value.to_s == defaults[key].to_s && !required_parts.include?(key) <ide> end <ide> <del> Visitors::Formatter.new(path_options).accept(path.spec) <add> format = Visitors::FormatBuilder.new.accept(path.spec) <add> format.evaluate path_options <ide> end <ide> <ide> def optimized_path <ide><path>actionpack/lib/action_dispatch/journey/visitors.rb <ide> <ide> module ActionDispatch <ide> module Journey # :nodoc: <add> class Format <add> ESCAPE_PATH = ->(value) { Router::Utils.escape_path(value) } <add> ESCAPE_SEGMENT = ->(value) { Router::Utils.escape_segment(value) } <add> <add> class Parameter < Struct.new(:name, :escaper) <add> def escape(value); escaper.call value; end <add> end <add> <add> def self.required_path(symbol) <add> Parameter.new symbol, ESCAPE_PATH <add> end <add> <add> def self.required_segment(symbol) <add> Parameter.new symbol, ESCAPE_SEGMENT <add> end <add> <add> def initialize(parts) <add> @parts = parts <add> @children = [] <add> @parameters = [] <add> <add> parts.each_with_index do |object,i| <add> case object <add> when Journey::Format <add> @children << i <add> when Parameter <add> @parameters << i <add> end <add> end <add> end <add> <add> def evaluate(hash) <add> parts = @parts.dup <add> <add> @parameters.each do |index| <add> param = parts[index] <add> value = hash.fetch(param.name) { return ''.freeze } <add> parts[index] = param.escape value <add> end <add> <add> @children.each { |index| parts[index] = parts[index].evaluate(hash) } <add> <add> parts.join <add> end <add> end <add> <ide> module Visitors # :nodoc: <ide> class Visitor # :nodoc: <ide> DISPATCH_CACHE = {} <ide> def visit_DOT(n); terminal(n); end <ide> end <ide> end <ide> <add> class FormatBuilder < Visitor # :nodoc: <add> def accept(node); Journey::Format.new(super); end <add> def terminal(node); [node.left]; end <add> <add> def binary(node) <add> visit(node.left) + visit(node.right) <add> end <add> <add> def visit_GROUP(n); [Journey::Format.new(unary(n))]; end <add> <add> def visit_STAR(n) <add> [Journey::Format.required_path(n.left.to_sym)] <add> end <add> <add> def visit_SYMBOL(n) <add> symbol = n.to_sym <add> if symbol == :controller <add> [Journey::Format.required_path(symbol)] <add> else <add> [Journey::Format.required_segment(symbol)] <add> end <add> end <add> end <add> <ide> # Loop through the requirements AST <ide> class Each < Visitor # :nodoc: <ide> attr_reader :block
2
Ruby
Ruby
remove full_clone from coretap
b5569ffd331c6ea95f492f0ac7f42a1dbf11ae29
<ide><path>Library/Homebrew/tap.rb <ide> def self.ensure_installed! <ide> end <ide> <ide> # CoreTap never allows shallow clones (on request from GitHub). <del> def install(full_clone: true, quiet: false, clone_target: nil, force_auto_update: nil) <add> def install(quiet: false, clone_target: nil, force_auto_update: nil) <ide> raise "Shallow clones are not supported for homebrew-core!" unless full_clone <ide> <ide> remote = Homebrew::EnvConfig.core_git_remote <ide> if remote != default_remote <ide> $stderr.puts "HOMEBREW_CORE_GIT_REMOTE set: using #{remote} for Homebrew/core Git remote URL." <ide> end <del> super(full_clone: full_clone, quiet: quiet, clone_target: remote, force_auto_update: force_auto_update) <add> super(quiet: quiet, clone_target: remote, force_auto_update: force_auto_update) <ide> end <ide> <ide> # @private
1
Text
Text
update formatting, add image + solution
807244c81a9c7cdad56788008a2a842945b5d441
<ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-199-iterative-circle-packing.english.md <ide> forumTopicId: 301837 <ide> <section id='description'> <ide> Three circles of equal radius are placed inside a larger circle such that each pair of circles is tangent to one another and the inner circles do not overlap. There are four uncovered "gaps" which are to be filled iteratively with more tangent circles. <ide> <del> <add><img class="img-responsive center-block" alt="a diagram of non-overlapping concentric circles" src="https://cdn-media-1.freecodecamp.org/project-euler/199-circles-in-circles.gif" style="background-color: white; padding: 10px;"> <ide> <ide> At each iteration, a maximally sized circle is placed in each gap, which creates more gaps for the next iteration. After 3 iterations (pictured), there are 108 gaps and the fraction of the area which is not covered by circles is 0.06790342, rounded to eight decimal places. <ide> <del> <del>What fraction of the area is not covered by circles after 10 iterations? <add>What fraction of the area is not covered by circles after `n` iterations? <ide> Give your answer rounded to eight decimal places using the format x.xxxxxxxx . <ide> </section> <ide> <ide> Give your answer rounded to eight decimal places using the format x.xxxxxxxx . <ide> <ide> ```yml <ide> tests: <del> - text: <code>euler199()</code> should return 0.00396087. <del> testString: assert.strictEqual(euler199(), 0.00396087); <add> - text: <code>iterativeCirclePacking(10)</code> should return a number. <add> testString: assert(typeof iterativeCirclePacking(10) === 'number'); <add> - text: <code>iterativeCirclePacking(10)</code> should return 0.00396087. <add> testString: assert.strictEqual(iterativeCirclePacking(10), 0.00396087); <add> - text: <code>iterativeCirclePacking(3)</code> should return 0.06790342. <add> testString: assert.strictEqual(iterativeCirclePacking(3), 0.06790342); <ide> <ide> ``` <ide> <ide> tests: <ide> <div id='js-seed'> <ide> <ide> ```js <del>function euler199() { <add>function iterativeCirclePacking(n) { <ide> // Good luck! <ide> return true; <ide> } <ide> <del>euler199(); <add>iterativeCirclePacking(10); <ide> ``` <ide> <ide> </div> <ide> euler199(); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>function iterativeCirclePacking(n) { <add> let k1 = 1; <add> let k0 = k1 * (3 - 2 * Math.sqrt(3)); <add> let a0 = 1 / (k0 * k0); <add> let a1 = 3 / (k1 * k1); <add> a1 += 3 * getArea(k0, k1, k1, n); <add> a1 += getArea(k1, k1, k1, n); <add> let final = ((a0 - a1) / a0).toFixed(8); <add> <add> return parseFloat(final); <add> function getArea(k1, k2, k3, depth) { <add> if (depth == 0) return 0.0; <add> let k4 = k1 + k2 + k3 + 2 * Math.sqrt(k1 * k2 + k2 * k3 + k3 * k1); <add> let a = 1 / (k4 * k4); <add> a += getArea(k1, k2, k4, depth - 1); <add> a += getArea(k2, k3, k4, depth - 1); <add> a += getArea(k3, k1, k4, depth - 1); <add> return a; <add> } <add>} <ide> ``` <ide> <ide> </section>
1
Ruby
Ruby
include lib files for uploader
28449b4129c83279c360bfb12419d31508d9255b
<ide><path>lib/github_uploader.rb <add>require "rest-client" <add>require "github_api" <add># We can stop requiring nokogiri when github_api is updated <add>require "nokogiri" <add> <add>class GithubUploader <add> <add> def initialize(login, username, repo, root=Dir.pwd) <add> @login = login <add> @username = username <add> @repo = repo <add> @root = root <add> @token = check_token <add> end <add> <add> def authorized? <add> !!@token <add> end <add> <add> def token_path <add> File.expand_path(".github-upload-token", @root) <add> end <add> <add> def check_token <add> File.exist?(token_path) ? File.open(token_path, "rb").read : nil <add> end <add> <add> def authorize <add> return if authorized? <add> <add> puts "There is no file named .github-upload-token in this folder. This file holds the OAuth token needed to communicate with GitHub." <add> puts "You will be asked to enter your GitHub password so a new OAuth token will be created." <add> print "GitHub Password: " <add> system "stty -echo" # disable echoing of entered chars so password is not shown on console <add> pw = STDIN.gets.chomp <add> system "stty echo" # enable echoing of entered chars <add> puts "" <add> <add> # check if the user already granted access for Ember.js Uploader by checking the available authorizations <add> response = RestClient.get "https://#{@login}:#{pw}@api.github.com/authorizations" <add> JSON.parse(response.to_str).each do |auth| <add> if auth["note"] == "Ember.js Uploader" <add> # user already granted access, so we reuse the existing token <add> @token = auth["token"] <add> end <add> end <add> <add> ## we need to create a new token <add> unless @token <add> payload = { <add> :scopes => ["public_repo"], <add> :note => "Ember.js Uploader", <add> :note_url => "https://github.com/#{@username}/#{@repo}" <add> } <add> response = RestClient.post "https://#{@login}:#{pw}@api.github.com/authorizations", payload.to_json, :content_type => :json <add> @token = JSON.parse(response.to_str)["token"] <add> end <add> <add> # finally save the token into .github-upload-token <add> File.open(".github-upload-token", 'w') {|f| f.write(@token)} <add> end <add> <add> def upload_file(filename, description, file) <add> return false unless authorized? <add> <add> gh = Github.new :user => @username, :repo => @repo, :oauth_token => @token <add> <add> # remvove previous download with the same name <add> gh.repos.downloads do |download| <add> if filename == download.name <add> gh.repos.delete_download @username, @repo, download.id <add> break <add> end <add> end <add> <add> # step 1 <add> hash = gh.repos.create_download @username, @repo, <add> "name" => filename, <add> "size" => File.size(file), <add> "description" => description, <add> "content_type" => "application/json" <add> <add> # step 2 <add> gh.repos.upload hash, file <add> <add> return true <add> end <add> <add>end
1
Python
Python
add license info to minified build
b632110d2d8ee69194b31ad2022408b1afb44520
<ide><path>utils/build/build.py <ide> def main(argv=None): <ide> # header <ide> <ide> with open(output,'r') as f: text = f.read() <del> with open(output,'w') as f: f.write('// three.js - http://github.com/mrdoob/three.js\n' + text + sourcemapping) <add> with open(output,'w') as f: f.write('// three.js - http://github.com/mrdoob/three.js\n// Released under the MIT license.\n// https://github.com/mrdoob/three.js/blob/master/LICENSE\n' + text + sourcemapping) <ide> <ide> os.close(fd) <ide> os.remove(path)
1
Text
Text
fix node name typo in dependency matcher example
dc816bba9d564ae572af28a17cbf0580ba11db5e
<ide><path>website/docs/usage/rule-based-matching.md <ide> pattern = [ <ide> { <ide> "LEFT_ID": "anchor_founded", <ide> "REL_OP": ">", <del> "RIGHT_ID": "subject", <add> "RIGHT_ID": "founded_subject", <ide> "RIGHT_ATTRS": {"DEP": "nsubj"}, <ide> } <ide> # ... <ide> pattern = [ <ide> { <ide> "LEFT_ID": "anchor_founded", <ide> "REL_OP": ">", <del> "RIGHT_ID": "subject", <add> "RIGHT_ID": "founded_subject", <ide> "RIGHT_ATTRS": {"DEP": "nsubj"}, <ide> }, <ide> {
1
Javascript
Javascript
remove global buildin
3c50dba922843d433102dd7f8d86b78082c3bf07
<ide><path>buildin/global.js <del>var g; <del> <del>// This works in non-strict mode <del>g = (function() { <del> return this; <del>})(); <del> <del>try { <del> // This works if eval is allowed (see CSP) <del> g = g || new Function("return this")(); <del>} catch (e) { <del> // This works if the window reference is available <del> if (typeof window === "object") g = window; <del>} <del> <del>// g can still be undefined, but nothing to do about it... <del>// We return undefined, instead of nothing here, so it's <del>// easier to handle this case. if(!global) { ...} <del> <del>module.exports = g; <ide><path>lib/RuntimeGlobals.js <ide> exports.startup = "__webpack_require__.x"; <ide> */ <ide> exports.interceptModuleExecution = "__webpack_require__.i"; <ide> <add>/** <add> * the global object <add> */ <add>exports.global = "__webpack_require__.g"; <add> <ide> /** <ide> * the filename of the HMR manifest <ide> */ <ide><path>lib/RuntimePlugin.js <ide> const DefinePropertyGetterRuntimeModule = require("./runtime/DefinePropertyGette <ide> const EnsureChunkRuntimeModule = require("./runtime/EnsureChunkRuntimeModule"); <ide> const GetChunkFilenameRuntimeModule = require("./runtime/GetChunkFilenameRuntimeModule"); <ide> const GetMainFilenameRuntimeModule = require("./runtime/GetMainFilenameRuntimeModule"); <add>const GlobalRuntimeModule = require("./runtime/GlobalRuntimeModule"); <ide> const MakeNamespaceObjectRuntimeModule = require("./runtime/MakeNamespaceObjectRuntimeModule"); <ide> const PublicPathRuntimeModule = require("./runtime/PublicPathRuntimeModule"); <ide> <ide> const DEPENDENCIES = { <ide> [RuntimeGlobals.ensureChunk]: [RuntimeGlobals.require], <ide> [RuntimeGlobals.entryModuleId]: [RuntimeGlobals.require], <ide> [RuntimeGlobals.getFullHash]: [RuntimeGlobals.require], <add> [RuntimeGlobals.global]: [RuntimeGlobals.require], <ide> [RuntimeGlobals.makeNamespaceObject]: [RuntimeGlobals.require], <ide> [RuntimeGlobals.moduleCache]: [RuntimeGlobals.require], <ide> [RuntimeGlobals.moduleFactories]: [RuntimeGlobals.require], <ide> class RuntimePlugin { <ide> ); <ide> return true; <ide> }); <add> compilation.hooks.runtimeRequirementInTree <add> .for(RuntimeGlobals.global) <add> .tap("RuntimePlugin", chunk => { <add> compilation.addRuntimeModule(chunk, new GlobalRuntimeModule()); <add> return true; <add> }); <ide> compilation.hooks.runtimeRequirementInTree <ide> .for(RuntimeGlobals.getChunkScriptFilename) <ide> .tap("RuntimePlugin", (chunk, set) => { <ide><path>lib/node/NodeSourcePlugin.js <ide> <ide> "use strict"; <ide> <del>const { getModulePath } = require("../JavascriptParserHelpers"); <del>const ProvidedDependency = require("../dependencies/ProvidedDependency"); <add>const RuntimeGlobals = require("../RuntimeGlobals"); <add>const ConstDependency = require("../dependencies/ConstDependency"); <ide> <ide> /** @typedef {import("../../declarations/WebpackOptions").NodeOptions} NodeOptions */ <ide> /** @typedef {import("../Compiler")} Compiler */ <ide> module.exports = class NodeSourcePlugin { <ide> compiler.hooks.compilation.tap( <ide> "NodeSourcePlugin", <ide> (compilation, { normalModuleFactory }) => { <del> compilation.dependencyFactories.set( <del> ProvidedDependency, <del> normalModuleFactory <del> ); <del> compilation.dependencyTemplates.set( <del> ProvidedDependency, <del> new ProvidedDependency.Template() <del> ); <del> <ide> const handler = (parser, parserOptions) => { <ide> if (parserOptions.node === false) return; <ide> <ide> let localOptions = options; <ide> if (parserOptions.node) { <ide> localOptions = Object.assign({}, localOptions, parserOptions.node); <ide> } <add> <ide> if (localOptions.global) { <ide> parser.hooks.expression <ide> .for("global") <ide> .tap("NodeSourcePlugin", expr => { <del> const dep = new ProvidedDependency( <del> getModulePath( <del> parser.state.module.context, <del> require.resolve("../../buildin/global") <del> ), <del> "global", <del> null, <del> expr.range <add> const dep = new ConstDependency( <add> RuntimeGlobals.global, <add> expr.range, <add> [RuntimeGlobals.global] <ide> ); <ide> dep.loc = expr.loc; <ide> parser.state.module.addDependency(dep); <ide><path>lib/runtime/GlobalRuntimeModule.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add>*/ <add> <add>"use strict"; <add> <add>const RuntimeGlobals = require("../RuntimeGlobals"); <add>const RuntimeModule = require("../RuntimeModule"); <add>const Template = require("../Template"); <add> <add>class GlobalRuntimeModule extends RuntimeModule { <add> constructor() { <add> super("global"); <add> } <add> <add> /** <add> * @returns {string} runtime code <add> */ <add> generate() { <add> return Template.asString([ <add> `${RuntimeGlobals.global} = (function() {`, <add> Template.indent([ <add> // This works in non-strict mode <add> "var g = (function() { return this; })();", <add> "try {", <add> Template.indent( <add> // This works if eval is allowed (see CSP) <add> "g = g || new Function('return this')();" <add> ), <add> "} catch (e) {", <add> Template.indent( <add> // This works if the window reference is available <add> "if (typeof window === 'object') g = window;" <add> ), <add> "}", <add> // g can still be `undefined`, but nothing to do about it... <add> // We return `undefined`, instead of nothing here, so it's <add> // easier to handle this case: <add> // if (!global) { … } <add> "return g;" <add> ]), <add> "})();" <add> ]); <add> } <add>} <add> <add>module.exports = GlobalRuntimeModule;
5
Javascript
Javascript
add default render loading on android webview
a74d05be629c12d91cd6a74a664274b5c60f6cee
<ide><path>Libraries/Components/WebView/WebView.android.js <ide> 'use strict'; <ide> <ide> var EdgeInsetsPropType = require('EdgeInsetsPropType'); <add>var ProgressBarAndroid = require('ProgressBarAndroid'); <ide> var React = require('React'); <ide> var ReactNativeViewAttributes = require('ReactNativeViewAttributes'); <ide> var StyleSheet = require('StyleSheet'); <ide> var WebViewState = keyMirror({ <ide> ERROR: null, <ide> }); <ide> <add>var defaultRenderLoading = () => ( <add> <View style={styles.loadingView}> <add> <ProgressBarAndroid <add> style={styles.loadingProgressBar} <add> styleAttr="Inverse" <add> /> <add> </View> <add>); <add> <ide> /** <ide> * Renders a native WebView. <ide> */ <ide> var WebView = React.createClass({ <ide> var otherView = null; <ide> <ide> if (this.state.viewState === WebViewState.LOADING) { <del> otherView = this.props.renderLoading && this.props.renderLoading(); <add> otherView = (this.props.renderLoading || defaultRenderLoading)(); <ide> } else if (this.state.viewState === WebViewState.ERROR) { <ide> var errorEvent = this.state.lastErrorEvent; <ide> otherView = this.props.renderError && this.props.renderError( <ide> var styles = StyleSheet.create({ <ide> height: 0, <ide> flex: 0, // disable 'flex:1' when hiding a View <ide> }, <add> loadingView: { <add> flex: 1, <add> justifyContent: 'center', <add> alignItems: 'center', <add> }, <add> loadingProgressBar: { <add> height: 20, <add> }, <ide> }); <ide> <ide> module.exports = WebView;
1
Java
Java
fix configuration issues in defaultsockjsservice
9925d8385ff9e80bb3ec3bfbe2d4224538fed6a9
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/WebSocketHttpRequestHandler.java <ide> public void handleRequest(HttpServletRequest request, HttpServletResponse respon <ide> ServerHttpRequest httpRequest = new ServletServerHttpRequest(request); <ide> ServerHttpResponse httpResponse = new ServletServerHttpResponse(response); <ide> <del> try { <del> this.handshakeHandler.doHandshake(httpRequest, httpResponse, this.webSocketHandler); <del> httpResponse.flush(); <del> } <del> catch (IOException ex) { <del> throw ex; <del> } <add> this.handshakeHandler.doHandshake(httpRequest, httpResponse, this.webSocketHandler); <add> httpResponse.flush(); <ide> } <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/DefaultSockJsService.java <ide> import org.springframework.web.socket.sockjs.SockJsService; <ide> import org.springframework.web.socket.sockjs.support.AbstractSockJsService; <ide> import org.springframework.web.socket.sockjs.support.frame.Jackson2SockJsMessageCodec; <add>import org.springframework.web.socket.sockjs.support.frame.JacksonSockJsMessageCodec; <ide> import org.springframework.web.socket.sockjs.support.frame.SockJsMessageCodec; <ide> import org.springframework.web.socket.sockjs.transport.TransportHandler; <ide> import org.springframework.web.socket.sockjs.transport.TransportType; <ide> public class DefaultSockJsService extends AbstractSockJsService { <ide> * application stops. <ide> */ <ide> public DefaultSockJsService(TaskScheduler taskScheduler) { <del> super(taskScheduler); <del> addTransportHandlers(getDefaultTransportHandlers()); <del> initMessageCodec(); <del> } <del> <del> protected void initMessageCodec() { <del> if (jackson2Present) { <del> this.messageCodec = new Jackson2SockJsMessageCodec(); <del> } <del> else if (jacksonPresent) { <del> this.messageCodec = new Jackson2SockJsMessageCodec(); <del> } <add> this(taskScheduler, null); <ide> } <ide> <ide> /** <ide> else if (jacksonPresent) { <ide> * Spring bean to ensure it is initialized at start up and shut down when the <ide> * application stops. <ide> * @param transportHandlers the transport handlers to use (replaces the default ones); <del> * can be {@code null}. <add> * can be {@code null} if you don't want to install the default ones. <ide> * @param transportHandlerOverrides zero or more overrides to the default transport <ide> * handler types. <ide> */ <ide> public DefaultSockJsService(TaskScheduler taskScheduler, Collection<TransportHan <ide> <ide> initMessageCodec(); <ide> <del> if (!CollectionUtils.isEmpty(transportHandlers)) { <add> if (CollectionUtils.isEmpty(transportHandlers)) { <add> addTransportHandlers(getDefaultTransportHandlers()); <add> } <add> else { <ide> addTransportHandlers(transportHandlers); <ide> } <add> <ide> if (!ObjectUtils.isEmpty(transportHandlerOverrides)) { <ide> addTransportHandlers(Arrays.asList(transportHandlerOverrides)); <ide> } <ide> public DefaultSockJsService(TaskScheduler taskScheduler, Collection<TransportHan <ide> } <ide> } <ide> <add> private void initMessageCodec() { <add> if (jackson2Present) { <add> this.messageCodec = new Jackson2SockJsMessageCodec(); <add> } <add> else if (jacksonPresent) { <add> this.messageCodec = new JacksonSockJsMessageCodec(); <add> } <add> } <ide> <ide> protected final Set<TransportHandler> getDefaultTransportHandlers() { <ide> Set<TransportHandler> result = new HashSet<TransportHandler>(); <ide> result.add(new XhrPollingTransportHandler()); <del> result.add(new XhrTransportHandler()); <add> result.add(new XhrReceivingTransportHandler()); <ide> result.add(new JsonpPollingTransportHandler()); <del> result.add(new JsonpTransportHandler()); <add> result.add(new JsonpReceivingTransportHandler()); <ide> result.add(new XhrStreamingTransportHandler()); <ide> result.add(new EventSourceTransportHandler()); <ide> result.add(new HtmlFileTransportHandler()); <add><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/JsonpReceivingTransportHandler.java <del><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/JsonpTransportHandler.java <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <del>public class JsonpTransportHandler extends AbstractHttpReceivingTransportHandler { <add>public class JsonpReceivingTransportHandler extends AbstractHttpReceivingTransportHandler { <ide> <ide> private final FormHttpMessageConverter formConverter = new FormHttpMessageConverter(); <ide> <add><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/XhrReceivingTransportHandler.java <del><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/XhrTransportHandler.java <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <del>public class XhrTransportHandler extends AbstractHttpReceivingTransportHandler { <add>public class XhrReceivingTransportHandler extends AbstractHttpReceivingTransportHandler { <ide> <ide> <ide> @Override <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/transport/handler/DefaultSockJsServiceTests.java <ide> package org.springframework.web.socket.sockjs.transport.handler; <ide> <ide> import java.util.Arrays; <add>import java.util.List; <ide> import java.util.Map; <ide> <ide> import org.junit.Before; <ide> public void defaultTransportHandlers() { <ide> assertNotNull(handlers.get(TransportType.EVENT_SOURCE)); <ide> } <ide> <add> @Test <add> public void defaultTransportHandlersWithOverride() { <add> <add> XhrReceivingTransportHandler xhrHandler = new XhrReceivingTransportHandler(); <add> <add> DefaultSockJsService service = new DefaultSockJsService(mock(TaskScheduler.class), null, xhrHandler); <add> Map<TransportType, TransportHandler> handlers = service.getTransportHandlers(); <add> <add> assertEquals(8, handlers.size()); <add> assertSame(xhrHandler, handlers.get(xhrHandler.getTransportType())); <add> } <add> <add> @Test <add> public void customizedTransportHandlerList() { <add> <add> List<TransportHandler> handlers = Arrays.<TransportHandler>asList( <add> new XhrPollingTransportHandler(), new XhrReceivingTransportHandler()); <add> <add> DefaultSockJsService service = new DefaultSockJsService(mock(TaskScheduler.class), handlers); <add> Map<TransportType, TransportHandler> actualHandlers = service.getTransportHandlers(); <add> <add> assertEquals(handlers.size(), actualHandlers.size()); <add> } <add> <ide> @Test <ide> public void handleTransportRequestXhr() throws Exception { <ide> <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/transport/handler/HttpReceivingTransportHandlerTests.java <ide> <ide> /** <ide> * Test fixture for {@link AbstractHttpReceivingTransportHandler} and sub-classes <del> * {@link XhrTransportHandler} and {@link JsonpTransportHandler}. <add> * {@link XhrReceivingTransportHandler} and {@link JsonpReceivingTransportHandler}. <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <ide> public void setUp() { <ide> @Test <ide> public void readMessagesXhr() throws Exception { <ide> this.servletRequest.setContent("[\"x\"]".getBytes("UTF-8")); <del> handleRequest(new XhrTransportHandler()); <add> handleRequest(new XhrReceivingTransportHandler()); <ide> <ide> assertEquals(204, this.servletResponse.getStatus()); <ide> } <ide> <ide> @Test <ide> public void readMessagesJsonp() throws Exception { <ide> this.servletRequest.setContent("[\"x\"]".getBytes("UTF-8")); <del> handleRequest(new JsonpTransportHandler()); <add> handleRequest(new JsonpReceivingTransportHandler()); <ide> <ide> assertEquals(200, this.servletResponse.getStatus()); <ide> assertEquals("ok", this.servletResponse.getContentAsString()); <ide> public void readMessagesJsonp() throws Exception { <ide> public void readMessagesJsonpFormEncoded() throws Exception { <ide> this.servletRequest.setContent("d=[\"x\"]".getBytes("UTF-8")); <ide> this.servletRequest.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE); <del> handleRequest(new JsonpTransportHandler()); <add> handleRequest(new JsonpReceivingTransportHandler()); <ide> <ide> assertEquals(200, this.servletResponse.getStatus()); <ide> assertEquals("ok", this.servletResponse.getContentAsString()); <ide> public void readMessagesJsonpFormEncoded() throws Exception { <ide> public void readMessagesJsonpFormEncodedWithEncoding() throws Exception { <ide> this.servletRequest.setContent("d=[\"x\"]".getBytes("UTF-8")); <ide> this.servletRequest.setContentType("application/x-www-form-urlencoded;charset=UTF-8"); <del> handleRequest(new JsonpTransportHandler()); <add> handleRequest(new JsonpReceivingTransportHandler()); <ide> <ide> assertEquals(200, this.servletResponse.getStatus()); <ide> assertEquals("ok", this.servletResponse.getContentAsString()); <ide> public void readMessagesBadContent() throws Exception { <ide> @Test(expected=IllegalArgumentException.class) <ide> public void readMessagesNoSession() throws Exception { <ide> WebSocketHandler webSocketHandler = mock(WebSocketHandler.class); <del> new XhrTransportHandler().handleRequest(this.request, this.response, webSocketHandler, null); <add> new XhrReceivingTransportHandler().handleRequest(this.request, this.response, webSocketHandler, null); <ide> } <ide> <ide> @Test <ide> public void delegateMessageException() throws Exception { <ide> doThrow(new Exception()).when(wsHandler).handleMessage(session, new TextMessage("x")); <ide> <ide> try { <del> XhrTransportHandler transportHandler = new XhrTransportHandler(); <add> XhrReceivingTransportHandler transportHandler = new XhrReceivingTransportHandler(); <ide> transportHandler.setSockJsServiceConfiguration(sockJsConfig); <ide> transportHandler.handleRequest(this.request, this.response, wsHandler, session); <ide> fail("Expected exception"); <ide> private void handleRequestAndExpectFailure() throws Exception { <ide> WebSocketHandler wsHandler = mock(WebSocketHandler.class); <ide> AbstractSockJsSession session = new TestHttpSockJsSession("1", new StubSockJsServiceConfig(), wsHandler); <ide> <del> new XhrTransportHandler().handleRequest(this.request, this.response, wsHandler, session); <add> new XhrReceivingTransportHandler().handleRequest(this.request, this.response, wsHandler, session); <ide> <ide> assertEquals(500, this.servletResponse.getStatus()); <ide> verifyNoMoreInteractions(wsHandler);
6
Ruby
Ruby
pass the route name to define_url_helper
212057b912627b9c4056f911a43c83b18ae3ab34
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def length <ide> end <ide> <ide> class UrlHelper # :nodoc: <del> def self.create(route, options, url_strategy) <add> def self.create(route, options, route_name, url_strategy) <ide> if optimize_helper?(route) <del> OptimizedUrlHelper.new(route, options, url_strategy) <add> OptimizedUrlHelper.new(route, options, route_name, url_strategy) <ide> else <del> new route, options, url_strategy <add> new route, options, route_name, url_strategy <ide> end <ide> end <ide> <ide> def self.optimize_helper?(route) <ide> !route.glob? && route.path.requirements.empty? <ide> end <ide> <del> attr_reader :url_strategy <add> attr_reader :url_strategy, :route_name <ide> <ide> class OptimizedUrlHelper < UrlHelper # :nodoc: <ide> attr_reader :arg_size <ide> <del> def initialize(route, options, url_strategy) <add> def initialize(route, options, route_name, url_strategy) <ide> super <ide> @required_parts = @route.required_parts <ide> @arg_size = @required_parts.size <ide> def raise_generation_error(args, missing_keys) <ide> end <ide> end <ide> <del> def initialize(route, options, url_strategy) <add> def initialize(route, options, route_name, url_strategy) <ide> @options = options <ide> @segment_keys = route.segment_keys.uniq <ide> @route = route <ide> @url_strategy = url_strategy <add> @route_name = route_name <ide> end <ide> <ide> def call(t, args, inner_options) <ide> def call(t, args, inner_options) <ide> options, <ide> @segment_keys) <ide> <del> t._routes.url_for(hash, url_strategy) <add> t._routes.url_for(hash, route_name, url_strategy) <ide> end <ide> <ide> def handle_positional_args(controller_options, inner_options, args, result, path_params) <ide> def handle_positional_args(controller_options, inner_options, args, result, path <ide> # <ide> # foo_url(bar, baz, bang, sort_by: 'baz') <ide> # <del> def define_url_helper(route, name, opts, url_strategy) <del> helper = UrlHelper.create(route, opts, url_strategy) <add> def define_url_helper(route, name, opts, route_key, url_strategy) <add> helper = UrlHelper.create(route, opts, route_key, url_strategy) <ide> <ide> @module.remove_possible_method name <ide> @module.module_eval do <ide> def define_url_helper(route, name, opts, url_strategy) <ide> end <ide> <ide> def define_named_route_methods(name, route) <del> define_url_helper route, :"#{name}_path", <del> route.defaults.merge(:use_route => name), PATH <del> <del> define_url_helper route, :"#{name}_url", <del> route.defaults.merge(:use_route => name), FULL <add> define_url_helper route, :"#{name}_path", route.defaults, name, PATH <add> define_url_helper route, :"#{name}_url", route.defaults, name, FULL <ide> end <ide> end <ide> <ide> class Generator #:nodoc: <ide> <ide> attr_reader :options, :recall, :set, :named_route <ide> <del> def initialize(options, recall, set) <del> @named_route = options.delete(:use_route) <add> def initialize(named_route, options, recall, set) <add> @named_route = named_route <ide> @options = options.dup <ide> @recall = recall.dup <ide> @set = set <ide> def extra_keys(options, recall={}) <ide> end <ide> <ide> def generate_extras(options, recall={}) <del> path, params = generate(options, recall) <add> route_key = options.delete :use_route <add> path, params = generate(route_key, options, recall) <ide> return path, params.keys <ide> end <ide> <del> def generate(options, recall = {}) <del> Generator.new(options, recall, self).generate <add> def generate(route_key, options, recall = {}) <add> Generator.new(route_key, options, recall, self).generate <ide> end <add> private :generate <ide> <ide> RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length, <ide> :trailing_slash, :anchor, :params, :only_path, :script_name, <ide> def find_script_name(options) <ide> end <ide> <ide> # The +options+ argument must be a hash whose keys are *symbols*. <del> def url_for(options, url_strategy = UNKNOWN) <add> def url_for(options, route_name = nil, url_strategy = UNKNOWN) <ide> options = default_url_options.merge options <ide> <ide> user = password = nil <ide> def url_for(options, url_strategy = UNKNOWN) <ide> path_options = options.dup <ide> RESERVED_OPTIONS.each { |ro| path_options.delete ro } <ide> <del> path, params = generate(path_options, recall) <add> path, params = generate(route_name, path_options, recall) <ide> <ide> if options.key? :params <ide> params.merge! options[:params] <ide><path>actionpack/lib/action_dispatch/routing/url_for.rb <ide> def url_for(options = nil) <ide> when nil <ide> _routes.url_for(url_options.symbolize_keys) <ide> when Hash <del> _routes.url_for(options.symbolize_keys.reverse_merge!(url_options)) <add> route_name = options.delete :use_route <add> _routes.url_for(options.symbolize_keys.reverse_merge!(url_options), <add> route_name) <ide> when String <ide> options <ide> when Symbol <ide><path>actionpack/test/abstract_unit.rb <ide> def patch(uri_or_host, path = nil) <ide> <ide> module RoutingTestHelpers <ide> def url_for(set, options) <del> set.url_for options.merge(:only_path => true) <add> route_name = options.delete :use_route <add> set.url_for options.merge(:only_path => true), route_name <ide> end <ide> <ide> def make_set(strict = true)
3
Java
Java
update mockmvc default for suffixpattern matching
cc2b980e5c4255d0ddb6fd4900ec740c8acde14d
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilder.java <ide> /* <del> * Copyright 2002-2020 the original author or authors. <add> * Copyright 2002-2021 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public class StandaloneMockMvcBuilder extends AbstractMockMvcBuilder<StandaloneM <ide> @Nullable <ide> private PathPatternParser patternParser; <ide> <del> private boolean useSuffixPatternMatch = true; <add> private boolean useSuffixPatternMatch = false; <ide> <ide> private boolean useTrailingSlashPatternMatch = true; <ide> <ide> public void setPatternParser(PathPatternParser parser) { <ide> /** <ide> * Whether to use suffix pattern match (".*") when matching patterns to <ide> * requests. If enabled a method mapped to "/users" also matches to "/users.*". <del> * <p>The default value is {@code true}. <add> * <p>The default value is {@code false}. <ide> * @deprecated as of 5.2.4. See class-level note in <ide> * {@link RequestMappingHandlerMapping} on the deprecation of path extension <ide> * config options.
1
Text
Text
add note about jbuilder
961779997cb28750d52d6186b41c29c33677ae0f
<ide><path>guides/source/action_view_overview.md <ide> xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do <ide> end <ide> ``` <ide> <add>#### Jbuilder <add><a href="https://github.com/rails/jbuilder">Jbuilder</a> is a gem that's <add>maintained by the Rails team and included in the default Rails Gemfile. <add>It's similar to Builder, but is used to generate JSON, instead of XML. <add> <add>If you don't have it, you can add the following to your Gemfile: <add> <add>```ruby <add>gem 'jbuilder' <add>``` <add> <add>A Jbuilder object named `json` is automatically made available to templates with <add>a `.jbuilder` extension. <add> <add>Here is a basic example: <add> <add>```ruby <add>json.name("Alex") <add>json.email("[email protected]") <add>``` <add> <add>would produce: <add> <add>```json <add>{ <add> "name": "Alex", <add> "email: "[email protected]" <add>} <add>``` <add> <add>See the <a href="https://github.com/rails/jbuilder#jbuilder"> <add>Jbuilder documention</a> for more examples and information. <add> <ide> #### Template Caching <ide> <ide> By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will check the file's modification time and recompile it in development mode.
1
Text
Text
add bert trained from review corpus.
9907dc523ae960a1261b4b522dedc2851447b0a7
<ide><path>model_cards/activebus/BERT-DK_laptop/README.md <add># ReviewBERT <add> <add>BERT (post-)trained from review corpus to understand sentiment, options and various e-commence aspects. <add> <add>`BERT-DK_laptop` is trained from 100MB laptop corpus under `Electronics/Computers & Accessories/Laptops`. <add> <add> <add>## Model Description <add> <add>The original model is from `BERT-base-uncased` trained from Wikipedia+BookCorpus. <add>Models are post-trained from [Amazon Dataset](http://jmcauley.ucsd.edu/data/amazon/) and [Yelp Dataset](https://www.yelp.com/dataset/challenge/). <add> <add>`BERT-DK_laptop` is trained from 100MB laptop corpus under `Electronics/Computers & Accessories/Laptops`. <add> <add>## Instructions <add>Loading the post-trained weights are as simple as, e.g., <add> <add>```python <add>import torch <add>from transformers import AutoModel, AutoTokenizer <add> <add>tokenizer = AutoTokenizer.from_pretrained("activebus/BERT-DK_laptop") <add>model = AutoModel.from_pretrained("activebus/BERT-DK_laptop") <add> <add>``` <add> <add> <add>## Evaluation Results <add> <add>Check our [NAACL paper](https://www.aclweb.org/anthology/N19-1242.pdf) <add> <add> <add>## Citation <add>If you find this work useful, please cite as following. <add>``` <add>@inproceedings{xu_bert2019, <add> title = "BERT Post-Training for Review Reading Comprehension and Aspect-based Sentiment Analysis", <add> author = "Xu, Hu and Liu, Bing and Shu, Lei and Yu, Philip S.", <add> booktitle = "Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics", <add> month = "jun", <add> year = "2019", <add>} <add>``` <ide><path>model_cards/activebus/BERT-DK_rest/README.md <add># ReviewBERT <add> <add>BERT (post-)trained from review corpus to understand sentiment, options and various e-commence aspects. <add> <add>`BERT-DK_rest` is trained from 1G (19 types) restaurants from Yelp. <add> <add>## Model Description <add> <add>The original model is from `BERT-base-uncased` trained from Wikipedia+BookCorpus. <add>Models are post-trained from [Amazon Dataset](http://jmcauley.ucsd.edu/data/amazon/) and [Yelp Dataset](https://www.yelp.com/dataset/challenge/). <add> <add> <add>## Instructions <add>Loading the post-trained weights are as simple as, e.g., <add> <add>```python <add>import torch <add>from transformers import AutoModel, AutoTokenizer <add> <add>tokenizer = AutoTokenizer.from_pretrained("activebus/BERT-DK_rest") <add>model = AutoModel.from_pretrained("activebus/BERT-DK_rest") <add> <add>``` <add> <add> <add>## Evaluation Results <add> <add>Check our [NAACL paper](https://www.aclweb.org/anthology/N19-1242.pdf) <add> <add> <add>## Citation <add>If you find this work useful, please cite as following. <add>``` <add>@inproceedings{xu_bert2019, <add> title = "BERT Post-Training for Review Reading Comprehension and Aspect-based Sentiment Analysis", <add> author = "Xu, Hu and Liu, Bing and Shu, Lei and Yu, Philip S.", <add> booktitle = "Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics", <add> month = "jun", <add> year = "2019", <add>} <add>``` <ide><path>model_cards/activebus/BERT-PT_laptop/README.md <add># ReviewBERT <add> <add>BERT (post-)trained from review corpus to understand sentiment, options and various e-commence aspects. <add> <add>`BERT-DK_laptop` is trained from 100MB laptop corpus under `Electronics/Computers & Accessories/Laptops`. <add>`BERT-PT_*` addtionally uses SQuAD 1.1. <add> <add>## Model Description <add> <add>The original model is from `BERT-base-uncased` trained from Wikipedia+BookCorpus. <add>Models are post-trained from [Amazon Dataset](http://jmcauley.ucsd.edu/data/amazon/) and [Yelp Dataset](https://www.yelp.com/dataset/challenge/). <add> <add> <add>## Instructions <add>Loading the post-trained weights are as simple as, e.g., <add> <add>```python <add>import torch <add>from transformers import AutoModel, AutoTokenizer <add> <add>tokenizer = AutoTokenizer.from_pretrained("activebus/BERT-PT_laptop") <add>model = AutoModel.from_pretrained("activebus/BERT-PT_laptop") <add> <add>``` <add> <add>## Evaluation Results <add> <add>Check our [NAACL paper](https://www.aclweb.org/anthology/N19-1242.pdf) <add> <add> <add>## Citation <add>If you find this work useful, please cite as following. <add>``` <add>@inproceedings{xu_bert2019, <add> title = "BERT Post-Training for Review Reading Comprehension and Aspect-based Sentiment Analysis", <add> author = "Xu, Hu and Liu, Bing and Shu, Lei and Yu, Philip S.", <add> booktitle = "Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics", <add> month = "jun", <add> year = "2019", <add>} <add>``` <ide><path>model_cards/activebus/BERT-PT_rest/README.md <add># ReviewBERT <add> <add>BERT (post-)trained from review corpus to understand sentiment, options and various e-commence aspects. <add> <add>`BERT-DK_rest` is trained from 1G (19 types) restaurants from Yelp. <add>`BERT-PT_*` addtionally uses SQuAD 1.1. <add> <add>## Model Description <add> <add>The original model is from `BERT-base-uncased` trained from Wikipedia+BookCorpus. <add>Models are post-trained from [Amazon Dataset](http://jmcauley.ucsd.edu/data/amazon/) and [Yelp Dataset](https://www.yelp.com/dataset/challenge/). <add> <add> <add>## Instructions <add>Loading the post-trained weights are as simple as, e.g., <add> <add>```python <add>import torch <add>from transformers import AutoModel, AutoTokenizer <add> <add>tokenizer = AutoTokenizer.from_pretrained("activebus/BERT-PT_rest") <add>model = AutoModel.from_pretrained("activebus/BERT-PT_rest") <add> <add>``` <add> <add> <add>## Evaluation Results <add> <add>Check our [NAACL paper](https://www.aclweb.org/anthology/N19-1242.pdf) <add> <add> <add>## Citation <add>If you find this work useful, please cite as following. <add>``` <add>@inproceedings{xu_bert2019, <add> title = "BERT Post-Training for Review Reading Comprehension and Aspect-based Sentiment Analysis", <add> author = "Xu, Hu and Liu, Bing and Shu, Lei and Yu, Philip S.", <add> booktitle = "Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics", <add> month = "jun", <add> year = "2019", <add>} <add>``` <ide><path>model_cards/activebus/BERT-XD_Review/README.md <add># ReviewBERT <add> <add>BERT (post-)trained from review corpus to understand sentiment, options and various e-commence aspects. <add>Please visit https://github.com/howardhsu/BERT-for-RRC-ABSA for details. <add> <add>`BERT-XD_Review` is a cross-domain (beyond just `laptop` and `restaurant`) language model, where each example is from a single product / restaurant with the same rating, post-trained (fine-tuned) on a combination of 5-core Amazon reviews and all Yelp data, expected to be 22 G in total. It is trained for 4 epochs on `bert-base-uncased`. <add>The preprocessing code [here](https://github.com/howardhsu/BERT-for-RRC-ABSA/transformers). <add> <add>## Model Description <add> <add>The original model is from `BERT-base-uncased`. <add>Models are post-trained from [Amazon Dataset](http://jmcauley.ucsd.edu/data/amazon/) and [Yelp Dataset](https://www.yelp.com/dataset/challenge/). <add> <add> <add>## Instructions <add>Loading the post-trained weights are as simple as, e.g., <add> <add>```python <add>import torch <add>from transformers import AutoModel, AutoTokenizer <add> <add>tokenizer = AutoTokenizer.from_pretrained("activebus/BERT-XD_Review") <add>model = AutoModel.from_pretrained("activebus/BERT-XD_Review") <add> <add>``` <add> <add> <add>## Evaluation Results <add> <add>Check our [NAACL paper](https://www.aclweb.org/anthology/N19-1242.pdf) <add>`BERT_Review` is expected to have similar performance on domain-specific tasks (such as aspect extraction) as `BERT-DK`, but much better on general tasks such as aspect sentiment classification (different domains mostly share similar sentiment words). <add> <add> <add>## Citation <add>If you find this work useful, please cite as following. <add>``` <add>@inproceedings{xu_bert2019, <add> title = "BERT Post-Training for Review Reading Comprehension and Aspect-based Sentiment Analysis", <add> author = "Xu, Hu and Liu, Bing and Shu, Lei and Yu, Philip S.", <add> booktitle = "Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics", <add> month = "jun", <add> year = "2019", <add>} <add>``` <ide><path>model_cards/activebus/BERT_Review/README.md <add># ReviewBERT <add> <add>BERT (post-)trained from review corpus to understand sentiment, options and various e-commence aspects. <add> <add>`BERT_Review` is cross-domain (beyond just `laptop` and `restaurant`) language model with one example from randomly mixed domains, post-trained (fine-tuned) on a combination of 5-core Amazon reviews and all Yelp data, expected to be 22 G in total. It is trained for 4 epochs on `bert-base-uncased`. <add>The preprocessing code [here](https://github.com/howardhsu/BERT-for-RRC-ABSA/transformers). <add> <add> <add>## Model Description <add> <add>The original model is from `BERT-base-uncased` trained from Wikipedia+BookCorpus. <add>Models are post-trained from [Amazon Dataset](http://jmcauley.ucsd.edu/data/amazon/) and [Yelp Dataset](https://www.yelp.com/dataset/challenge/). <add> <add> <add>## Instructions <add>Loading the post-trained weights are as simple as, e.g., <add> <add>```python <add>import torch <add>from transformers import AutoModel, AutoTokenizer <add> <add>tokenizer = AutoTokenizer.from_pretrained("activebus/BERT_Review") <add>model = AutoModel.from_pretrained("activebus/BERT_Review") <add> <add>``` <add> <add> <add>## Evaluation Results <add> <add>Check our [NAACL paper](https://www.aclweb.org/anthology/N19-1242.pdf) <add>`BERT_Review` is expected to have similar performance on domain-specific tasks (such as aspect extraction) as `BERT-DK`, but much better on general tasks such as aspect sentiment classification (different domains mostly share similar sentiment words). <add> <add> <add>## Citation <add>If you find this work useful, please cite as following. <add>``` <add>@inproceedings{xu_bert2019, <add> title = "BERT Post-Training for Review Reading Comprehension and Aspect-based Sentiment Analysis", <add> author = "Xu, Hu and Liu, Bing and Shu, Lei and Yu, Philip S.", <add> booktitle = "Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics", <add> month = "jun", <add> year = "2019", <add>} <add>```
6
Ruby
Ruby
fix some bugs
e12c23faa87aa9c6f493dcd4aa47d1124c41a418
<ide><path>Library/Homebrew/formula.rb <ide> def latest_formula <ide> end <ide> <ide> def old_installed_formulae <del> alias_path ? self.class.installed_with_alias_path(alias_path) : [] <add> # If this formula isn't the current target of the alias, <add> # it doesn't make sense to say that other formulae are older versions of it <add> # because we don't know which came first. <add> return [] if alias_path.nil? || installed_alias_target_changed? <add> self.class.installed_with_alias_path(alias_path) - [self] <ide> end <ide> <ide> # @private
1
Java
Java
fix javadoc for cronsequencegenerator
644b0b8bebaff53022bb58c3417980965920d9ef
<ide><path>spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java <ide> * <li>"0 0 * * * *" = the top of every hour of every day.</li> <ide> * <li>"*&#47;10 * * * * *" = every ten seconds.</li> <ide> * <li>"0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.</li> <del> * <li>"0 * 6,19 * * *" = 6:00 AM and 7:00 PM every day.</li> <add> * <li>"0 0 6,19 * * *" = 6:00 AM and 7:00 PM every day.</li> <ide> * <li>"0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.</li> <ide> * <li>"0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays</li> <ide> * <li>"0 0 0 25 12 ?" = every Christmas Day at midnight</li>
1
Javascript
Javascript
update cameraroll examples to use promises
a7e5312aeb9b1e94a61babf76e723da1fd89f5b8
<ide><path>Examples/UIExplorer/CameraRollView.js <ide> var CameraRollView = React.createClass({ <ide> fetchParams.after = this.state.lastCursor; <ide> } <ide> <del> CameraRoll.getPhotos(fetchParams, this._appendAssets, logError); <add> CameraRoll.getPhotos(fetchParams) <add> .then((data) => this._appendAssets(data), (e) => logError(e)); <ide> }, <ide> <ide> /** <ide><path>Examples/UIExplorer/XHRExample.ios.js <ide> class FormUploader extends React.Component { <ide> <ide> _fetchRandomPhoto() { <ide> CameraRoll.getPhotos( <del> {first: PAGE_SIZE}, <add> {first: PAGE_SIZE} <add> ).then( <ide> (data) => { <ide> if (!this._isMounted) { <ide> return;
2
Java
Java
add validation of http method in form tag
59084354e2277c4244e8949128466b33e7c9206d
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java <ide> <ide> import org.springframework.beans.PropertyAccessor; <ide> import org.springframework.core.Conventions; <add>import org.springframework.http.HttpMethod; <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.servlet.support.RequestDataValueProcessor; <ide> protected boolean isMethodBrowserSupported(String method) { <ide> return ("get".equalsIgnoreCase(method) || "post".equalsIgnoreCase(method)); <ide> } <ide> <del> <ide> /** <ide> * Writes the opening part of the block '<code>form</code>' tag and exposes <ide> * the form object name in the {@link javax.servlet.jsp.PageContext}. <ide> protected int writeTagContent(TagWriter tagWriter) throws JspException { <ide> tagWriter.forceBlock(); <ide> <ide> if (!isMethodBrowserSupported(getMethod())) { <add> assertHttpMethod(getMethod()); <ide> String inputName = getMethodParameter(); <ide> String inputType = "hidden"; <ide> tagWriter.startTag(INPUT_TAG); <ide> protected int writeTagContent(TagWriter tagWriter) throws JspException { <ide> return EVAL_BODY_INCLUDE; <ide> } <ide> <add> private void assertHttpMethod(String method) { <add> for (HttpMethod httpMethod : HttpMethod.values()) { <add> if (httpMethod.name().equalsIgnoreCase(method)) { <add> return; <add> } <add> } <add> throw new IllegalArgumentException("Invalid HTTP method: " + method); <add> } <add> <ide> /** <ide> * Autogenerated IDs correspond to the form object name. <ide> */
1
Ruby
Ruby
replace nokogiri with rexml
7835bcd10b5cdb8ba6235bd6827c70c74638867c
<ide><path>Library/Homebrew/unversioned_cask_checker.rb <ide> def guess_cask_version <ide> <ide> distribution_path = extract_dir/"Distribution" <ide> if distribution_path.exist? <del> Homebrew.install_bundler_gems! <del> require "nokogiri" <add> require "rexml/document" <ide> <del> xml = Nokogiri::XML(distribution_path.read) <add> xml = REXML::Document.new(distribution_path.read) <ide> <del> product_version = xml.xpath("//installer-gui-script//product").first&.attr("version") <del> return product_version if product_version <add> product = xml.get_elements("//installer-gui-script//product").first <add> product_version = product["version"] if product <add> return product_version if product_version.present? <ide> end <ide> <ide> opoo "#{pkg_path.basename} contains multiple packages: #{packages}" if packages.count != 1
1
Python
Python
fix runtimeerror message format
d365f5074f44d09dafd1ba68b97ea2cc9e0d63d3
<ide><path>src/transformers/pipelines/__init__.py <ide> def pipeline( <ide> <ide> if task is None and model is None: <ide> raise RuntimeError( <del> "Impossible to instantiate a pipeline without either a task or a model" <del> "being specified." <add> "Impossible to instantiate a pipeline without either a task or a model " <add> "being specified. " <ide> "Please provide a task class or a model" <ide> ) <ide>
1
Python
Python
add solution to problem 74
d8f573c0fbc5363b268accca6d73c85b463da65f
<ide><path>project_euler/problem_074/sol2.py <add>""" <add> Project Euler Problem 074: https://projecteuler.net/problem=74 <add> <add> Starting from any positive integer number <add> it is possible to attain another one summing the factorial of its digits. <add> <add> Repeating this step, we can build chains of numbers. <add> It is not difficult to prove that EVERY starting number <add> will eventually get stuck in a loop. <add> <add> The request is to find how many numbers less than one million <add> produce a chain with exactly 60 non repeating items. <add> <add> Solution approach: <add> This solution simply consists in a loop that generates <add> the chains of non repeating items. <add> The generation of the chain stops before a repeating item <add> or if the size of the chain is greater then the desired one. <add> After generating each chain, the length is checked and the counter increases. <add>""" <add> <add> <add>def factorial(a: int) -> int: <add> """Returns the factorial of the input a <add> >>> factorial(5) <add> 120 <add> <add> >>> factorial(6) <add> 720 <add> <add> >>> factorial(0) <add> 1 <add> """ <add> <add> # The factorial function is not defined for negative numbers <add> if a < 0: <add> raise ValueError("Invalid negative input!", a) <add> <add> # The case of 0! is handled separately <add> if a == 0: <add> return 1 <add> else: <add> # use a temporary support variable to store the computation <add> temporary_computation = 1 <add> <add> while a > 0: <add> temporary_computation *= a <add> a -= 1 <add> <add> return temporary_computation <add> <add> <add>def factorial_sum(a: int) -> int: <add> """Function to perform the sum of the factorial <add> of all the digits in a <add> <add> >>> factorial_sum(69) <add> 363600 <add> """ <add> <add> # Prepare a variable to hold the computation <add> fact_sum = 0 <add> <add> """ Convert a in string to iterate on its digits <add> convert the digit back into an int <add> and add its factorial to fact_sum. <add> """ <add> for i in str(a): <add> fact_sum += factorial(int(i)) <add> <add> return fact_sum <add> <add> <add>def solution(chain_length: int = 60, number_limit: int = 1000000) -> int: <add> """Returns the number of numbers that produce <add> chains with exactly 60 non repeating elements. <add> >>> solution(60,1000000) <add> 402 <add> >>> solution(15,1000000) <add> 17800 <add> """ <add> <add> # the counter for the chains with the exact desired length <add> chain_counter = 0 <add> <add> for i in range(1, number_limit + 1): <add> <add> # The temporary list will contain the elements of the chain <add> chain_list = [i] <add> <add> # The new element of the chain <add> new_chain_element = factorial_sum(chain_list[-1]) <add> <add> """ Stop computing the chain when you find a repeating item <add> or the length it greater then the desired one. <add> """ <add> while not (new_chain_element in chain_list) and ( <add> len(chain_list) <= chain_length <add> ): <add> chain_list += [new_chain_element] <add> <add> new_chain_element = factorial_sum(chain_list[-1]) <add> <add> """ If the while exited because the chain list contains the exact amount of elements <add> increase the counter <add> """ <add> chain_counter += len(chain_list) == chain_length <add> <add> return chain_counter <add> <add> <add>if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod() <add> print(f"{solution()}")
1
Javascript
Javascript
fix regexp in file extension checking
c6bd0e56cbdbc63e8b272239af63a394745c19c4
<ide><path>src/node.js <ide> function findModulePath (id, dirs, callback) { <ide> return; <ide> } <ide> <del> if (/.(js|node)$/.exec(id)) { <add> if (/\.(js|node)$/.exec(id)) { <ide> throw new Error("No longer accepting filename extension in module names"); <ide> } <ide>
1
Javascript
Javascript
add sharewis in showcase
75992e700d8e692dda93885d30638afc36d537df
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> linkAppStore: 'https://itunes.apple.com/us/app/spatula/id1090496189?ls=1&mt=8', <ide> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.usespatula', <ide> author: 'Kushal Dave' <add> }, <add> { <add> name: 'ShareWis', <add> icon: 'https://s3-ap-northeast-1.amazonaws.com/sw-misc/sharewis3_app.png', <add> link: 'https://itunes.apple.com/jp/app/id585517208', <add> author: 'ShareWis Inc.' <ide> } <ide> ]; <ide>
1
Javascript
Javascript
move toastandroid to apis, not components
0ef1bc39255d9ef30360d5cc01d580a225e6befa
<ide><path>Libraries/react-native/react-native-implementation.js <ide> module.exports = { <ide> get TextInput() { <ide> return require('TextInput'); <ide> }, <del> get ToastAndroid() { <del> return require('ToastAndroid'); <del> }, <ide> get ToolbarAndroid() { <ide> return require('ToolbarAndroid'); <ide> }, <ide> module.exports = { <ide> get TimePickerAndroid() { <ide> return require('TimePickerAndroid'); <ide> }, <add> get ToastAndroid() { <add> return require('ToastAndroid'); <add> }, <ide> get TVEventHandler() { <ide> return require('TVEventHandler'); <ide> },
1
Javascript
Javascript
avoid unnecessary concat of a single buffer
8854183fe565fafceb6b30149c1026401b60e4eb
<ide><path>lib/_stream_readable.js <ide> function fromList(n, state) { <ide> // read it all, truncate the array. <ide> if (stringMode) <ide> ret = list.join(''); <add> else if (list.length === 1) <add> ret = list[0]; <ide> else <ide> ret = Buffer.concat(list, length); <ide> list.length = 0;
1
Javascript
Javascript
avoid test timeouts on rpi
e4e5b13efd118346509b75c1f0d6a913981786f0
<ide><path>test/parallel/test-crypto-binary-default.js <ide> assert.throws(function() { <ide> <ide> // Test Diffie-Hellman with two parties sharing a secret, <ide> // using various encodings as we go along <del>var dh1 = crypto.createDiffieHellman(1024); <add>var dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256); <ide> var p1 = dh1.getPrime('buffer'); <ide> var dh2 = crypto.createDiffieHellman(p1, 'base64'); <ide> var key1 = dh1.generateKeys(); <ide><path>test/parallel/test-crypto-dh.js <ide> var crypto = require('crypto'); <ide> <ide> // Test Diffie-Hellman with two parties sharing a secret, <ide> // using various encodings as we go along <del>var dh1 = crypto.createDiffieHellman(1024); <add>var dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256); <ide> var p1 = dh1.getPrime('buffer'); <ide> var dh2 = crypto.createDiffieHellman(p1, 'buffer'); <ide> var key1 = dh1.generateKeys();
2
Javascript
Javascript
add getinfrastructurelogger to multicompiler
def294792902705299faafd43f034912b8a5a609
<ide><path>lib/MultiCompiler.js <ide> module.exports = class MultiCompiler extends Tapable { <ide> } <ide> } <ide> <add> getInfrastructureLogger(name) { <add> return this.compilers[0].getInfrastructureLogger(name); <add> } <add> <ide> validateDependencies(callback) { <ide> const edges = new Set(); <ide> const missing = [];
1
PHP
PHP
remove type hinting in toroute
319de5a80a3bddf64489d2935ddd47e70e0274ce
<ide><path>src/Illuminate/Routing/UrlGenerator.php <ide> public function route($name, $parameters = array(), $absolute = true) <ide> * Get the URL for a given route instance. <ide> * <ide> * @param \Illuminate\Routing\Route $route <del> * @param array $parameters <del> * @param bool $absolute <add> * @param mixed $parameters <add> * @param bool $absolute <ide> * @return string <ide> */ <del> protected function toRoute($route, array $parameters, $absolute) <add> protected function toRoute($route, $parameters, $absolute) <ide> { <ide> $parameters = $this->formatParameters($parameters); <ide>
1
Ruby
Ruby
invert the conditional
5b1ea3ea00579e45ed8b46a23a007c328f766786
<ide><path>activerecord/lib/active_record/schema.rb <ide> def migrations_paths <ide> def define(info, &block) # :nodoc: <ide> instance_eval(&block) <ide> <del> unless info[:version].blank? <add> if info[:version].present? <ide> initialize_schema_migrations_table <ide> connection.assume_migrated_upto_version(info[:version], migrations_paths) <ide> end
1
Java
Java
fix import issue introduced in prior commit
7dff02b2c145a94ff47da3e8931d34d05f05f331
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMapMethodArgumentResolver.java <ide> <ide> package org.springframework.web.servlet.mvc.method.annotation; <ide> <add>import java.util.Collections; <ide> import java.util.LinkedHashMap; <ide> import java.util.Map; <ide> <ide> import org.springframework.web.method.support.ModelAndViewContainer; <ide> import org.springframework.web.servlet.HandlerMapping; <ide> <del>import edu.emory.mathcs.backport.java.util.Collections; <del> <ide> /** <ide> * Resolves {@link Map} method arguments annotated with an @{@link PathVariable} <ide> * where the annotation does not specify a path variable name. The created
1
PHP
PHP
allow explicit model definitions in database rules
57306b716362331b6a95bf05336fcdb52057cca7
<ide><path>src/Illuminate/Validation/Rules/DatabaseRule.php <ide> namespace Illuminate\Validation\Rules; <ide> <ide> use Closure; <add>use Illuminate\Support\Str; <add>use Illuminate\Database\Eloquent\Model; <ide> <ide> trait DatabaseRule <ide> { <ide> trait DatabaseRule <ide> */ <ide> public function __construct($table, $column = 'NULL') <ide> { <del> $this->table = $table; <add> $this->table = $this->resolveTableName($table); <ide> $this->column = $column; <ide> } <ide> <add> /** <add> * Resolves the name of the table from the given string. <add> * <add> * @param string $table <add> * @return string <add> */ <add> public function resolveTableName($table) { <add> if (! Str::contains($table, '\\') || ! class_exists($table)) { <add> return $table; <add> } <add> <add> $model = new $table; <add> <add> if (! $model instanceof Model) { <add> return $table; <add> } <add> <add> return $model->getTable(); <add> } <add> <ide> /** <ide> * Set a "where" constraint on the query. <ide> * <ide><path>tests/Validation/ValidationExistsRuleTest.php <ide> public function testItCorrectlyFormatsAStringVersionOfTheRule() <ide> $rule = new Exists('table', 'column'); <ide> $rule->where('foo', 'bar'); <ide> $this->assertSame('exists:table,column,foo,"bar"', (string) $rule); <add> <add> $rule = new Exists(User::class, 'column'); <add> $rule->where('foo', 'bar'); <add> $this->assertSame('exists:users,column,foo,"bar"', (string) $rule); <add> <add> $rule = new Exists('Illuminate\Tests\Validation\User', 'column'); <add> $rule->where('foo', 'bar'); <add> $this->assertSame('exists:users,column,foo,"bar"', (string) $rule); <add> <add> $rule = new Exists(NoTableNameModel::class, 'column'); <add> $rule->where('foo', 'bar'); <add> $this->assertSame('exists:no_table_name_models,column,foo,"bar"', (string) $rule); <ide> } <ide> <ide> public function testItChoosesValidRecordsUsingWhereInRule() <ide> { <ide> $rule = new Exists('users', 'id'); <ide> $rule->whereIn('type', ['foo', 'bar']); <ide> <del> EloquentTestUser::create(['id' => '1', 'type' => 'foo']); <del> EloquentTestUser::create(['id' => '2', 'type' => 'bar']); <del> EloquentTestUser::create(['id' => '3', 'type' => 'baz']); <del> EloquentTestUser::create(['id' => '4', 'type' => 'other']); <add> User::create(['id' => '1', 'type' => 'foo']); <add> User::create(['id' => '2', 'type' => 'bar']); <add> User::create(['id' => '3', 'type' => 'baz']); <add> User::create(['id' => '4', 'type' => 'other']); <ide> <ide> $trans = $this->getIlluminateArrayTranslator(); <ide> $v = new Validator($trans, [], ['id' => $rule]); <ide> public function testItChoosesValidRecordsUsingWhereNotInRule() <ide> $rule = new Exists('users', 'id'); <ide> $rule->whereNotIn('type', ['foo', 'bar']); <ide> <del> EloquentTestUser::create(['id' => '1', 'type' => 'foo']); <del> EloquentTestUser::create(['id' => '2', 'type' => 'bar']); <del> EloquentTestUser::create(['id' => '3', 'type' => 'baz']); <del> EloquentTestUser::create(['id' => '4', 'type' => 'other']); <add> User::create(['id' => '1', 'type' => 'foo']); <add> User::create(['id' => '2', 'type' => 'bar']); <add> User::create(['id' => '3', 'type' => 'baz']); <add> User::create(['id' => '4', 'type' => 'other']); <ide> <ide> $trans = $this->getIlluminateArrayTranslator(); <ide> $v = new Validator($trans, [], ['id' => $rule]); <ide> public function testItChoosesValidRecordsUsingWhereNotInAndWhereNotInRulesTogeth <ide> $rule = new Exists('users', 'id'); <ide> $rule->whereIn('type', ['foo', 'bar', 'baz'])->whereNotIn('type', ['foo', 'bar']); <ide> <del> EloquentTestUser::create(['id' => '1', 'type' => 'foo']); <del> EloquentTestUser::create(['id' => '2', 'type' => 'bar']); <del> EloquentTestUser::create(['id' => '3', 'type' => 'baz']); <del> EloquentTestUser::create(['id' => '4', 'type' => 'other']); <add> User::create(['id' => '1', 'type' => 'foo']); <add> User::create(['id' => '2', 'type' => 'bar']); <add> User::create(['id' => '3', 'type' => 'baz']); <add> User::create(['id' => '4', 'type' => 'other']); <ide> <ide> $trans = $this->getIlluminateArrayTranslator(); <ide> $v = new Validator($trans, [], ['id' => $rule]); <ide> public function getIlluminateArrayTranslator() <ide> /** <ide> * Eloquent Models. <ide> */ <del>class EloquentTestUser extends Eloquent <add>class User extends Eloquent <ide> { <ide> protected $table = 'users'; <ide> protected $guarded = []; <ide> public $timestamps = false; <ide> } <add> <add>/** <add> * Eloquent Models. <add> */ <add>class NoTableNameModel extends Eloquent <add>{ <add> protected $guarded = []; <add> public $timestamps = false; <add>}
2
Python
Python
move files to core/ and common/
432a448a2a1a49cf3a3ec8bba9f883877a3015f2
<ide><path>official/common/__init__.py <add> <ide><path>official/common/flags.py <add># Lint as: python3 <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""The central place to define flags.""" <add> <add>from absl import flags <add> <add> <add>def define_flags(): <add> """Defines flags.""" <add> flags.DEFINE_string( <add> 'experiment', default=None, help='The experiment type registered.') <add> <add> flags.DEFINE_enum( <add> 'mode', <add> default=None, <add> enum_values=['train', 'eval', 'train_and_eval', <add> 'continuous_eval', 'continuous_train_and_eval'], <add> help='Mode to run: `train`, `eval`, `train_and_eval`, ' <add> '`continuous_eval`, and `continuous_train_and_eval`.') <add> <add> flags.DEFINE_string( <add> 'model_dir', <add> default=None, <add> help='The directory where the model and training/evaluation summaries' <add> 'are stored.') <add> <add> flags.DEFINE_multi_string( <add> 'config_file', <add> default=None, <add> help='YAML/JSON files which specifies overrides. The override order ' <add> 'follows the order of args. Note that each file ' <add> 'can be used as an override template to override the default parameters ' <add> 'specified in Python. If the same parameter is specified in both ' <add> '`--config_file` and `--params_override`, `config_file` will be used ' <add> 'first, followed by params_override.') <add> <add> flags.DEFINE_string( <add> 'params_override', <add> default=None, <add> help='a YAML/JSON string or a YAML file which specifies additional ' <add> 'overrides over the default parameters and those specified in ' <add> '`--config_file`. Note that this is supposed to be used only to override ' <add> 'the model parameters, but not the parameters like TPU specific flags. ' <add> 'One canonical use case of `--config_file` and `--params_override` is ' <add> 'users first define a template config file using `--config_file`, then ' <add> 'use `--params_override` to adjust the minimal set of tuning parameters, ' <add> 'for example setting up different `train_batch_size`. The final override ' <add> 'order of parameters: default_model_params --> params from config_file ' <add> '--> params in params_override. See also the help message of ' <add> '`--config_file`.') <add> <add> flags.DEFINE_multi_string( <add> 'gin_file', default=None, help='List of paths to the config files.') <add> <add> flags.DEFINE_multi_string( <add> 'gin_params', <add> default=None, <add> help='Newline separated list of Gin parameter bindings.') <add> <add> flags.DEFINE_string( <add> 'tpu', default=None, <add> help='The Cloud TPU to use for training. This should be either the name ' <add> 'used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 ' <add> 'url.') <ide><path>official/common/registry_imports.py <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""All necessary imports for registration.""" <add> <add># pylint: disable=unused-import <add>from official.nlp import tasks <add>from official.utils.testing import mock_task <ide><path>official/core/train_lib.py <add># Lint as: python3 <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""TFM common training driver library.""" <add> <add>import os <add>from typing import Any, Mapping <add> <add># Import libraries <add>from absl import logging <add>import orbit <add>import tensorflow as tf <add> <add>from official.common import train_utils <add>from official.core import base_task <add>from official.modeling.hyperparams import config_definitions <add> <add> <add>def run_experiment(distribution_strategy: tf.distribute.Strategy, <add> task: base_task.Task, <add> mode: str, <add> params: config_definitions.ExperimentConfig, <add> model_dir: str, <add> run_post_eval: bool = False, <add> save_summary: bool = True) -> Mapping[str, Any]: <add> """Runs train/eval configured by the experiment params. <add> <add> Args: <add> distribution_strategy: A distribution distribution_strategy. <add> task: A Task instance. <add> mode: A 'str', specifying the mode. Can be 'train', 'eval', 'train_and_eval' <add> or 'continuous_eval'. <add> params: ExperimentConfig instance. <add> model_dir: A 'str', a path to store model checkpoints and summaries. <add> run_post_eval: Whether to run post eval once after training, metrics logs <add> are returned. <add> save_summary: Whether to save train and validation summary. <add> <add> Returns: <add> eval logs: returns eval metrics logs when run_post_eval is set to True, <add> othewise, returns {}. <add> """ <add> <add> with distribution_strategy.scope(): <add> trainer = train_utils.create_trainer( <add> params, <add> task, <add> model_dir, <add> train='train' in mode, <add> evaluate=('eval' in mode) or run_post_eval) <add> <add> if trainer.checkpoint: <add> checkpoint_manager = tf.train.CheckpointManager( <add> trainer.checkpoint, <add> directory=model_dir, <add> max_to_keep=params.trainer.max_to_keep, <add> step_counter=trainer.global_step, <add> checkpoint_interval=params.trainer.checkpoint_interval, <add> init_fn=trainer.initialize) <add> else: <add> checkpoint_manager = None <add> <add> controller = orbit.Controller( <add> distribution_strategy, <add> trainer=trainer if 'train' in mode else None, <add> evaluator=trainer, <add> global_step=trainer.global_step, <add> steps_per_loop=params.trainer.steps_per_loop, <add> checkpoint_manager=checkpoint_manager, <add> summary_dir=os.path.join(model_dir, 'train') if ( <add> save_summary) else None, <add> eval_summary_dir=os.path.join(model_dir, 'validation') if ( <add> save_summary) else None, <add> summary_interval=params.trainer.summary_interval if ( <add> save_summary) else None) <add> <add> logging.info('Starts to execute mode: %s', mode) <add> with distribution_strategy.scope(): <add> if mode == 'train': <add> controller.train(steps=params.trainer.train_steps) <add> elif mode == 'train_and_eval': <add> controller.train_and_evaluate( <add> train_steps=params.trainer.train_steps, <add> eval_steps=params.trainer.validation_steps, <add> eval_interval=params.trainer.validation_interval) <add> elif mode == 'eval': <add> controller.evaluate(steps=params.trainer.validation_steps) <add> elif mode == 'continuous_eval': <add> controller.evaluate_continuously( <add> steps=params.trainer.validation_steps, <add> timeout=params.trainer.continuous_eval_timeout) <add> else: <add> raise NotImplementedError('The mode is not implemented: %s' % mode) <add> <add> if run_post_eval: <add> with distribution_strategy.scope(): <add> return trainer.evaluate( <add> tf.convert_to_tensor(params.trainer.validation_steps)) <add> else: <add> return {} <ide><path>official/core/train_lib_test.py <add># Lint as: python3 <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Tests for train_ctl_lib.""" <add>import json <add>import os <add> <add>from absl import flags <add>from absl.testing import flagsaver <add>from absl.testing import parameterized <add>import tensorflow as tf <add> <add>from tensorflow.python.distribute import combinations <add>from tensorflow.python.distribute import strategy_combinations <add>from official.common import flags as tfm_flags <add># pylint: disable=unused-import <add>from official.common import registry_imports <add># pylint: enable=unused-import <add>from official.core import task_factory <add>from official.core import train_lib <add>from official.core import train_utils <add> <add>FLAGS = flags.FLAGS <add> <add>tfm_flags.define_flags() <add> <add> <add>class TrainTest(tf.test.TestCase, parameterized.TestCase): <add> <add> def setUp(self): <add> super(TrainTest, self).setUp() <add> self._test_config = { <add> 'trainer': { <add> 'checkpoint_interval': 10, <add> 'steps_per_loop': 10, <add> 'summary_interval': 10, <add> 'train_steps': 10, <add> 'validation_steps': 5, <add> 'validation_interval': 10, <add> 'optimizer_config': { <add> 'optimizer': { <add> 'type': 'sgd', <add> }, <add> 'learning_rate': { <add> 'type': 'constant' <add> } <add> } <add> }, <add> } <add> <add> @combinations.generate( <add> combinations.combine( <add> distribution_strategy=[ <add> strategy_combinations.default_strategy, <add> strategy_combinations.tpu_strategy, <add> strategy_combinations.one_device_strategy_gpu, <add> ], <add> mode='eager', <add> flag_mode=['train', 'eval', 'train_and_eval'], <add> run_post_eval=[True, False])) <add> def test_end_to_end(self, distribution_strategy, flag_mode, run_post_eval): <add> model_dir = self.get_temp_dir() <add> flags_dict = dict( <add> experiment='mock', <add> mode=flag_mode, <add> model_dir=model_dir, <add> params_override=json.dumps(self._test_config)) <add> with flagsaver.flagsaver(**flags_dict): <add> params = train_utils.parse_configuration(flags.FLAGS) <add> train_utils.serialize_config(params, model_dir) <add> with distribution_strategy.scope(): <add> task = task_factory.get_task(params.task, logging_dir=model_dir) <add> <add> logs = train_lib.run_experiment( <add> distribution_strategy=distribution_strategy, <add> task=task, <add> mode=flag_mode, <add> params=params, <add> model_dir=model_dir, <add> run_post_eval=run_post_eval) <add> <add> if run_post_eval: <add> self.assertNotEmpty(logs) <add> else: <add> self.assertEmpty(logs) <add> self.assertNotEmpty( <add> tf.io.gfile.glob(os.path.join(model_dir, 'params.yaml'))) <add> if flag_mode != 'eval': <add> self.assertNotEmpty( <add> tf.io.gfile.glob(os.path.join(model_dir, 'checkpoint'))) <add> <add> <add>if __name__ == '__main__': <add> tf.test.main() <ide><path>official/core/train_utils.py <add># Lint as: python3 <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Training utils.""" <add> <add>import json <add>import os <add>import pprint <add> <add>from absl import logging <add>import tensorflow as tf <add> <add>from official.core import base_trainer <add>from official.core import exp_factory <add>from official.modeling import hyperparams <add>from official.modeling.hyperparams import config_definitions <add> <add> <add>def create_trainer(params, task, model_dir, train, evaluate): <add> del model_dir <add> logging.info('Running default trainer.') <add> trainer = base_trainer.Trainer(params, task, train=train, evaluate=evaluate) <add> return trainer <add> <add> <add>def parse_configuration(flags_obj): <add> """Parses ExperimentConfig from flags.""" <add> <add> # 1. Get the default config from the registered experiment. <add> params = exp_factory.get_exp_config(flags_obj.experiment) <add> params.override({ <add> 'runtime': { <add> 'tpu': flags_obj.tpu, <add> } <add> }) <add> <add> # 2. Get the first level of override from `--config_file`. <add> # `--config_file` is typically used as a template that specifies the common <add> # override for a particular experiment. <add> for config_file in flags_obj.config_file or []: <add> params = hyperparams.override_params_dict( <add> params, config_file, is_strict=True) <add> <add> # 3. Get the second level of override from `--params_override`. <add> # `--params_override` is typically used as a further override over the <add> # template. For example, one may define a particular template for training <add> # ResNet50 on ImageNet in a config file and pass it via `--config_file`, <add> # then define different learning rates and pass it via `--params_override`. <add> if flags_obj.params_override: <add> params = hyperparams.override_params_dict( <add> params, flags_obj.params_override, is_strict=True) <add> <add> params.validate() <add> params.lock() <add> <add> pp = pprint.PrettyPrinter() <add> logging.info('Final experiment parameters: %s', pp.pformat(params.as_dict())) <add> <add> return params <add> <add> <add>def serialize_config(params: config_definitions.ExperimentConfig, <add> model_dir: str): <add> """Serializes and saves the experiment config.""" <add> params_save_path = os.path.join(model_dir, 'params.yaml') <add> logging.info('Saving experiment configuration to %s', params_save_path) <add> tf.io.gfile.makedirs(model_dir) <add> hyperparams.save_params_dict_to_yaml(params, params_save_path) <add> <add> <add>def read_global_step_from_checkpoint(ckpt_file_path): <add> """Read global step from checkpoint, or get global step from its filename.""" <add> global_step = tf.Variable(-1, dtype=tf.int64) <add> ckpt = tf.train.Checkpoint(global_step=global_step) <add> try: <add> ckpt.restore(ckpt_file_path).expect_partial() <add> global_step_maybe_restored = global_step.numpy() <add> except tf.errors.InvalidArgumentError: <add> global_step_maybe_restored = -1 <add> <add> if global_step_maybe_restored == -1: <add> raise ValueError('global_step not found in checkpoint {}. ' <add> 'If you want to run finetune eval jobs, you need to ' <add> 'make sure that your pretrain model writes ' <add> 'global_step in its checkpoints.'.format(ckpt_file_path)) <add> global_step_restored = global_step.numpy() <add> logging.info('get global_step %d from checkpoint %s', <add> global_step_restored, ckpt_file_path) <add> return global_step_restored <add> <add> <add>def write_json_summary(log_dir, global_step, eval_metrics): <add> """Dump evaluation metrics to json file.""" <add> serializable_dict = {} <add> for name, value in eval_metrics.items(): <add> if hasattr(value, 'numpy'): <add> serializable_dict[name] = str(value.numpy()) <add> else: <add> serializable_dict[name] = str(value) <add> output_json = os.path.join(log_dir, 'metrics-{}.json'.format(global_step)) <add> logging.info('Evaluation results at pretrain step %d: %s', <add> global_step, serializable_dict) <add> with tf.io.gfile.GFile(output_json, 'w') as writer: <add> writer.write(json.dumps(serializable_dict, indent=4) + '\n') <add> <add> <add>def write_summary(summary_writer, global_step, eval_metrics): <add> """Write evaluation metrics to TF summary.""" <add> numeric_dict = {} <add> for name, value in eval_metrics.items(): <add> if hasattr(value, 'numpy'): <add> numeric_dict[name] = value.numpy().astype(float) <add> else: <add> numeric_dict[name] = value <add> with summary_writer.as_default(): <add> for name, value in numeric_dict.items(): <add> tf.summary.scalar(name, value, step=global_step) <add> summary_writer.flush() <add> <add> <add>def remove_ckpts(model_dir): <add> """Remove model checkpoints, so we can restart.""" <add> ckpts = os.path.join(model_dir, 'ckpt-*') <add> logging.info('removing checkpoint files %s', ckpts) <add> for file_to_remove in tf.io.gfile.glob(ckpts): <add> tf.io.gfile.rmtree(file_to_remove) <add> <add> file_to_remove = os.path.join(model_dir, 'checkpoint') <add> if tf.io.gfile.exists(file_to_remove): <add> tf.io.gfile.remove(file_to_remove)
6
Python
Python
fix issue with rpath in fcompiler/gnu.py
7562de3a37fa39863ae094fd40215e77ca3156b4
<ide><path>numpy/distutils/fcompiler/gnu.py <ide> def get_flags_arch(self): <ide> return [] <ide> <ide> def runtime_library_dir_option(self, dir): <del> return '-Wl,-rpath="%s"' % dir <add> sep = ',' if sys.platform == 'darwin' else '=' <add> return '-Wl,-rpath%s"%s"' % (sep, dir) <add> <ide> <ide> class Gnu95FCompiler(GnuFCompiler): <ide> compiler_type = 'gnu95'
1
PHP
PHP
add methods for sending cookies with test requests
073f9a976e836109c7f2b704d9ac3481f933909a
<ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php <ide> <ide> trait MakesHttpRequests <ide> { <add> /** <add> * Additional cookies for the request. <add> * <add> * @var array <add> */ <add> protected $defaultCookies = []; <add> <ide> /** <ide> * Additional headers for the request. <ide> * <ide> trait MakesHttpRequests <ide> */ <ide> protected $followRedirects = false; <ide> <add> /** <add> * Indicates whether cookies should be encrypted. <add> * <add> * @var bool <add> */ <add> protected $encryptCookies = true; <add> <ide> /** <ide> * Define additional headers to be sent with the request. <ide> * <ide> public function withMiddleware($middleware = null) <ide> return $this; <ide> } <ide> <add> /** <add> * Define additional cookies to be sent with the request. <add> * <add> * @param array $cookies <add> * @return $this <add> */ <add> public function withCookies(array $cookies) <add> { <add> $this->defaultCookies = array_merge($this->defaultCookies, $cookies); <add> <add> return $this; <add> } <add> <add> /** <add> * Add a cookie to be sent with the request. <add> * <add> * @param string $name <add> * @param string $value <add> * @return $this <add> */ <add> public function withCookie(string $name, string $value) <add> { <add> $this->defaultCookies[$name] = $value; <add> <add> return $this; <add> } <add> <ide> /** <ide> * Automatically follow any redirects returned from the response. <ide> * <ide> public function followingRedirects() <ide> return $this; <ide> } <ide> <add> /** <add> * Disable automatic encryption of cookie values. <add> * <add> * @return $this <add> */ <add> public function disableCookieEncryption() <add> { <add> $this->encryptCookies = false; <add> <add> return $this; <add> } <add> <ide> /** <ide> * Set the referer header and previous URL session value in order to simulate a previous request. <ide> * <ide> public function from(string $url) <ide> public function get($uri, array $headers = []) <ide> { <ide> $server = $this->transformHeadersToServerVars($headers); <add> $cookies = $this->prepareCookiesForRequest(); <ide> <del> return $this->call('GET', $uri, [], [], [], $server); <add> return $this->call('GET', $uri, [], $cookies, [], $server); <ide> } <ide> <ide> /** <ide> public function getJson($uri, array $headers = []) <ide> public function post($uri, array $data = [], array $headers = []) <ide> { <ide> $server = $this->transformHeadersToServerVars($headers); <add> $cookies = $this->prepareCookiesForRequest(); <ide> <del> return $this->call('POST', $uri, $data, [], [], $server); <add> return $this->call('POST', $uri, $data, $cookies, [], $server); <ide> } <ide> <ide> /** <ide> public function postJson($uri, array $data = [], array $headers = []) <ide> public function put($uri, array $data = [], array $headers = []) <ide> { <ide> $server = $this->transformHeadersToServerVars($headers); <add> $cookies = $this->prepareCookiesForRequest(); <ide> <del> return $this->call('PUT', $uri, $data, [], [], $server); <add> return $this->call('PUT', $uri, $data, $cookies, [], $server); <ide> } <ide> <ide> /** <ide> public function putJson($uri, array $data = [], array $headers = []) <ide> public function patch($uri, array $data = [], array $headers = []) <ide> { <ide> $server = $this->transformHeadersToServerVars($headers); <add> $cookies = $this->prepareCookiesForRequest(); <ide> <del> return $this->call('PATCH', $uri, $data, [], [], $server); <add> return $this->call('PATCH', $uri, $data, $cookies, [], $server); <ide> } <ide> <ide> /** <ide> public function patchJson($uri, array $data = [], array $headers = []) <ide> public function delete($uri, array $data = [], array $headers = []) <ide> { <ide> $server = $this->transformHeadersToServerVars($headers); <add> $cookies = $this->prepareCookiesForRequest(); <ide> <del> return $this->call('DELETE', $uri, $data, [], [], $server); <add> return $this->call('DELETE', $uri, $data, $cookies, [], $server); <ide> } <ide> <ide> /** <ide> public function deleteJson($uri, array $data = [], array $headers = []) <ide> public function options($uri, array $data = [], array $headers = []) <ide> { <ide> $server = $this->transformHeadersToServerVars($headers); <add> $cookies = $this->prepareCookiesForRequest(); <ide> <del> return $this->call('OPTIONS', $uri, $data, [], [], $server); <add> return $this->call('OPTIONS', $uri, $data, $cookies, [], $server); <ide> } <ide> <ide> /** <ide> protected function extractFilesFromDataArray(&$data) <ide> return $files; <ide> } <ide> <add> /** <add> * If enabled, encrypt cookie values for request. <add> * <add> * @return array <add> */ <add> protected function prepareCookiesForRequest() <add> { <add> if (! $this->encryptCookies) { <add> return $this->defaultCookies; <add> } <add> <add> return collect($this->defaultCookies)->map(function ($value) { <add> return encrypt($value, false); <add> })->all(); <add> } <add> <ide> /** <ide> * Follow a redirect chain until a non-redirect is received. <ide> * <ide><path>tests/Foundation/Testing/Concerns/MakesHttpRequestsTest.php <ide> public function testWithoutAndWithMiddlewareWithParameter() <ide> $this->app->make(MyMiddleware::class)->handle('foo', $next) <ide> ); <ide> } <add> <add> public function testWithCookieSetCookie() <add> { <add> $this->withCookie('foo', 'bar'); <add> <add> $this->assertCount(1, $this->defaultCookies); <add> $this->assertSame('bar', $this->defaultCookies['foo']); <add> } <add> <add> public function testWithCookiesSetsCookiesAndOverwritesPreviousValues() <add> { <add> $this->withCookie('foo', 'bar'); <add> $this->withCookies([ <add> 'foo' => 'baz', <add> 'new-cookie' => 'new-value', <add> ]); <add> <add> $this->assertCount(2, $this->defaultCookies); <add> $this->assertSame('baz', $this->defaultCookies['foo']); <add> $this->assertSame('new-value', $this->defaultCookies['new-cookie']); <add> } <ide> } <ide> <ide> class MyMiddleware
2
Ruby
Ruby
place api_parser code into util module
d4bbffdce85bbe164f540897fd2cb3561966351d
<ide><path>Library/Homebrew/utils/update.rb <ide> require 'json' <ide> <ide> module Utils <del> <add> class ApiParser <add> def call_api(url) <add> puts "- Calling API #{url}" <add> uri = URI(url) <add> response = Net::HTTP.get(uri) <add> <add> puts "- Parsing response" <add> JSON.parse(response) <add> end <add> <add> def query_repology_api(last_package_in_response = '') <add> url = 'https://repology.org/api/v1/projects/' + last_package_in_response + '?inrepo=homebrew&outdated=1' <add> <add> self.call_api(url) <add> end <add> <add> def parse_repology_api() <add> puts "\n-------- Query outdated packages from Repology --------" <add> page_no = 1 <add> puts "\n- Paginating repology api page: #{page_no}" <add> <add> outdated_packages = self.query_repology_api('') <add> last_pacakge_index = outdated_packages.size - 1 <add> response_size = outdated_packages.size <add> <add> while response_size > 1 do <add> page_no += 1 <add> puts "\n- Paginating repology api page: #{page_no}" <add> <add> last_package_in_response = outdated_packages.keys[last_pacakge_index] <add> response = self.query_repology_api("#{last_package_in_response}/") <add> <add> response_size = response.size <add> outdated_packages.merge!(response) <add> last_pacakge_index = outdated_packages.size - 1 <add> end <add> <add> puts "\n- #{outdated_packages.size} outdated pacakges identified by repology" <add> outdated_packages <add> end <add> end <add> <add> def query_homebrew <add> puts "\n-------- Get Homebrew Formulas --------" <add> self.call_api('https://formulae.brew.sh/api/formula.json') <add> end <add> <add> def parse_homebrew_formulas() <add> formulas = self.query_homebrew() <add> parsed_homebrew_formulas = {} <add> <add> formulas.each do |formula| <add> parsed_homebrew_formulas[formula['name']] = { <add> "fullname" => formula["full_name"], <add> "oldname" => formula["oldname"], <add> "version" => formula["versions"]['stable'], <add> "download_url" => formula["urls"]['stable']['url'], <add> } <add> end <add> <add> parsed_homebrew_formulas <add> end <add> <add> def validate_packages(outdated_repology_packages, brew_formulas) <add> puts "\n-------- Verify Outdated Repology packages as Homebrew Formulas --------" <add> packages = {} <add> <add> outdated_repology_packages.each do |package_name, repo_using_package| <add> # Identify homebrew repo <add> repology_homebrew_repo = repo_using_package.select { |repo| repo['repo'] == 'homebrew' }[0] <add> next if repology_homebrew_repo.empty? <add> <add> latest_version = nil <add> <add> # Identify latest version amongst repos <add> repo_using_package.each do |repo| <add> latest_version = repo['version'] if repo['status'] == 'newest' <add> end <add> <add> repology_homebrew_repo['latest_version'] = latest_version if latest_version <add> homebrew_package_details = brew_formulas[repology_homebrew_repo['srcname']] <add> <add> # Format package <add> packages[repology_homebrew_repo['srcname']] = format_package(homebrew_package_details, repology_homebrew_repo) <add> end <add> <add> packages <add> end <add> <add> <add> def format_package(homebrew_details, repology_details) <add> puts "- Formatting package: #{repology_details['srcname']}" <add> <add> homebrew_formula = HomebrewFormula.new <add> new_download_url = homebrew_formula.generate_new_download_url(homebrew_details['download_url'], homebrew_details['version'], repology_details['latest_version']) <add> <add> brew_commands = BrewCommands.new <add> livecheck_response = brew_commands.livecheck_check_formula(repology_details['srcname']) <add> has_open_pr = brew_commands.check_for_open_pr(repology_details['srcname'], new_download_url) <add> <add> formatted_package = { <add> 'fullname'=> homebrew_details['fullname'], <add> 'repology_version' => repology_details['latest_version'], <add> 'homebrew_version' => homebrew_details['version'], <add> 'livecheck_latest_version' => livecheck_response['livecheck_latest_version'], <add> 'current_download_url' => homebrew_details['download_url'], <add> 'latest_download_url' => new_download_url, <add> 'repology_latest_version' => repology_details['latest_version'], <add> 'has_open_pr' => has_open_pr <add> } <add> <add> formatted_package <add> end <add> <add> def display_version_data(outdated_packages) <add> puts "==============Formatted outdated packages============\n" <add> <add> outdated_packages.each do |package_name, package_details| <add> puts "" <add> puts "Package: #{package_name}" <add> puts "Brew current: #{package_details['homebrew_version']}" <add> puts "Repology latest: #{package_details['repology_version']}" <add> puts "Livecheck latest: #{package_details['livecheck_latest_version']}" <add> puts "Has Open PR?: #{package_details['has_open_pr']}" <add> end <add> end <ide> end
1
Javascript
Javascript
add comment, optimize code
4479b6c660d69f9ec72d742df944f41b580b9e39
<ide><path>lib/optimize/SideEffectsFlagPlugin.js <ide> class SideEffectsFlagPlugin { <ide> reexportMaps.set(module, (map = new Map())); <ide> } <ide> for (const [key, ids] of mode.map) { <add> // TODO Support reexporting namespace object <ide> if (ids.length > 0 && !mode.checked.has(key)) { <ide> map.set(key, { <ide> module: moduleGraph.getModule(dep), <ide> class SideEffectsFlagPlugin { <ide> } <ide> <ide> // Update imports along the reexports from sideEffectFree modules <del> for (const pair of reexportMaps) { <del> const module = pair[0]; <del> const map = pair[1]; <add> for (const [module, map] of reexportMaps) { <ide> for (const connection of moduleGraph.getIncomingConnections( <ide> module <ide> )) {
1
PHP
PHP
add once option to css()
758599e6f4d184c1b8024cbb69db200ebb1d0957
<ide><path>lib/Cake/Test/Case/View/Helper/HtmlHelperTest.php <ide> public function testCssLink() { <ide> $this->assertTags($result, $expected); <ide> } <ide> <add>/** <add> * Test css() with once option. <add> * <add> * @return void <add> */ <add> public function testCssLinkOnce() { <add> Configure::write('Asset.filter.css', false); <add> <add> $result = $this->Html->css('screen', array('once' => true)); <add> $expected = array( <add> 'link' => array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'preg:/.*css\/screen\.css/') <add> ); <add> $this->assertTags($result, $expected); <add> <add> $result = $this->Html->css('screen', array('once' => true)); <add> $this->assertEquals('', $result); <add> <add> // Default is once=false <add> $result = $this->Html->css('screen'); <add> $expected = array( <add> 'link' => array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'preg:/.*css\/screen\.css/') <add> ); <add> $this->assertTags($result, $expected); <add> } <add> <ide> /** <ide> * Test css link BC usage <ide> * <ide><path>lib/Cake/View/Helper/HtmlHelper.php <ide> class HtmlHelper extends AppHelper { <ide> protected $_crumbs = array(); <ide> <ide> /** <del> * Names of script files that have been included once <add> * Names of script & css files that have been included once <ide> * <ide> * @var array <ide> */ <del> protected $_includedScripts = array(); <add> protected $_includedAssets = array(); <ide> <ide> /** <ide> * Options for the currently opened script block buffer if any. <ide> public function link($title, $url = null, $options = array(), $confirmMessage = <ide> * <ide> * - `inline` If set to false, the generated tag will be appended to the 'css' block, <ide> * and included in the `$scripts_for_layout` layout variable. Defaults to true. <add> * - `once` Whether or not the css file should be checked for uniqueness. If true css <add> * files will only be included once, use false to allow the same <add> * css to be included more than once per request. <ide> * - `block` Set the name of the block link/style tag will be appended to. <ide> * This overrides the `inline` option. <ide> * - `plugin` False value will prevent parsing path as a plugin <ide> public function css($path, $options = array()) { <ide> unset($rel); <ide> } <ide> <del> $options += array('block' => null, 'inline' => true, 'rel' => 'stylesheet'); <add> $options += array( <add> 'block' => null, <add> 'inline' => true, <add> 'once' => false, <add> 'rel' => 'stylesheet' <add> ); <ide> if (!$options['inline'] && empty($options['block'])) { <ide> $options['block'] = __FUNCTION__; <ide> } <ide> public function css($path, $options = array()) { <ide> return; <ide> } <ide> <add> if ($options['once'] && isset($this->_includedAssets[$path])) { <add> return ''; <add> } <add> unset($options['once']); <add> $this->_includedAssets[$path] = true; <add> <ide> if (strpos($path, '//') !== false) { <ide> $url = $path; <ide> } else { <ide> public function script($url, $options = array()) { <ide> } <ide> return null; <ide> } <del> if ($options['once'] && isset($this->_includedScripts[$url])) { <add> if ($options['once'] && isset($this->_includedAssets[$url])) { <ide> return null; <ide> } <del> $this->_includedScripts[$url] = true; <add> $this->_includedAssets[$url] = true; <ide> <ide> if (strpos($url, '//') === false) { <ide> $url = $this->assetUrl($url, $options + array('pathPrefix' => Configure::read('App.jsBaseUrl'), 'ext' => '.js'));
2
Javascript
Javascript
add example to files.js example index 📝
3c78098a701094fff84fd70aa2f86a883ec17304
<ide><path>examples/files.js <ide> var files = { <ide> "webvr_sculpt", <ide> "webvr_video", <ide> "webvr_vive_paint", <del> "webvr_vive_sculpt" <add> "webvr_vive_sculpt", <add> "webvr_6dof_panorama" <ide> ], <ide> "physics": [ <ide> "webgl_physics_cloth",
1
PHP
PHP
add a `findor` method to eloquent
b062355f05f07f72119d868e065aac0c0c958ffd
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function findOrNew($id, $columns = ['*']) <ide> return $this->newModelInstance(); <ide> } <ide> <add> /** <add> * Find a model by its primary key or call a callback. <add> * <add> * @param mixed $id <add> * @param \Closure|array $columns <add> * @param \Closure|null $callback <add> * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|mixed <add> */ <add> public function findOr($id, $columns = ['*'], Closure $callback = null) <add> { <add> if ($columns instanceof Closure) { <add> $callback = $columns; <add> <add> $columns = ['*']; <add> } <add> <add> if (! is_null($model = $this->find($id, $columns))) { <add> return $model; <add> } <add> <add> return $callback(); <add> } <add> <ide> /** <ide> * Get the first record matching the attributes or instantiate it. <ide> * <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php <ide> public function findOrFail($id, $columns = ['*']) <ide> throw (new ModelNotFoundException)->setModel(get_class($this->related), $id); <ide> } <ide> <add> /** <add> * Find a related model by its primary key or call a callback. <add> * <add> * @param mixed $id <add> * @param \Closure|array $columns <add> * @param \Closure|null $callback <add> * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|mixed <add> */ <add> public function findOr($id, $columns = ['*'], Closure $callback = null) <add> { <add> if ($columns instanceof Closure) { <add> $callback = $columns; <add> <add> $columns = ['*']; <add> } <add> <add> $result = $this->find($id, $columns); <add> <add> $id = $id instanceof Arrayable ? $id->toArray() : $id; <add> <add> if (is_array($id)) { <add> if (count($result) === count(array_unique($id))) { <add> return $result; <add> } <add> } elseif (! is_null($result)) { <add> return $result; <add> } <add> <add> return $callback(); <add> } <add> <ide> /** <ide> * Add a basic where clause to the query, and return the first result. <ide> * <ide><path>src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php <ide> public function findOrFail($id, $columns = ['*']) <ide> throw (new ModelNotFoundException)->setModel(get_class($this->related), $id); <ide> } <ide> <add> /** <add> * Find a related model by its primary key or call a callback. <add> * <add> * @param mixed $id <add> * @param \Closure|array $columns <add> * @param \Closure|null $callback <add> * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|mixed <add> */ <add> public function findOr($id, $columns = ['*'], Closure $callback = null) <add> { <add> if ($columns instanceof Closure) { <add> $callback = $columns; <add> <add> $columns = ['*']; <add> } <add> <add> $result = $this->find($id, $columns); <add> <add> $id = $id instanceof Arrayable ? $id->toArray() : $id; <add> <add> if (is_array($id)) { <add> if (count($result) === count(array_unique($id))) { <add> return $result; <add> } <add> } elseif (! is_null($result)) { <add> return $result; <add> } <add> <add> return $callback(); <add> } <add> <ide> /** <ide> * Get the results of the relationship. <ide> * <ide><path>tests/Database/DatabaseEloquentBuilderTest.php <ide> public function testFindOrFailMethodWithManyUsingCollectionThrowsModelNotFoundEx <ide> $builder->findOrFail(new Collection([1, 2]), ['column']); <ide> } <ide> <add> public function testFindOrMethod() <add> { <add> $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]); <add> $model = $this->getMockModel(); <add> $model->shouldReceive('getKeyType')->andReturn('int'); <add> $builder->setModel($model); <add> $builder->getQuery()->shouldReceive('where')->with('foo_table.foo', '=', 1)->twice(); <add> $builder->getQuery()->shouldReceive('where')->with('foo_table.foo', '=', 2)->once(); <add> $builder->shouldReceive('first')->andReturn($model)->once(); <add> $builder->shouldReceive('first')->with(['column'])->andReturn($model)->once(); <add> $builder->shouldReceive('first')->andReturn(null)->once(); <add> <add> $this->assertSame($model, $builder->findOr(1, fn () => 'callback result')); <add> $this->assertSame($model, $builder->findOr(1, ['column'], fn () => 'callback result')); <add> $this->assertSame('callback result', $builder->findOr(2, fn () => 'callback result')); <add> } <add> <add> public function testFindOrMethodWithMany() <add> { <add> $builder = m::mock(Builder::class.'[get]', [$this->getMockQueryBuilder()]); <add> $model1 = $this->getMockModel(); <add> $model2 = $this->getMockModel(); <add> $builder->setModel($model1); <add> $builder->getQuery()->shouldReceive('whereIn')->with('foo_table.foo', [1, 2])->twice(); <add> $builder->getQuery()->shouldReceive('whereIn')->with('foo_table.foo', [1, 2, 3])->once(); <add> $builder->shouldReceive('get')->andReturn(new Collection([$model1, $model2]))->once(); <add> $builder->shouldReceive('get')->with(['column'])->andReturn(new Collection([$model1, $model2]))->once(); <add> $builder->shouldReceive('get')->andReturn(null)->once(); <add> <add> $result = $builder->findOr([1, 2], fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame($model1, $result[0]); <add> $this->assertSame($model2, $result[1]); <add> <add> $result = $builder->findOr([1, 2], ['column'], fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame($model1, $result[0]); <add> $this->assertSame($model2, $result[1]); <add> <add> $result = $builder->findOr([1, 2, 3], fn () => 'callback result'); <add> $this->assertSame('callback result', $result); <add> } <add> <add> public function testFindOrMethodWithManyUsingCollection() <add> { <add> $builder = m::mock(Builder::class.'[get]', [$this->getMockQueryBuilder()]); <add> $model1 = $this->getMockModel(); <add> $model2 = $this->getMockModel(); <add> $builder->setModel($model1); <add> $builder->getQuery()->shouldReceive('whereIn')->with('foo_table.foo', [1, 2])->twice(); <add> $builder->getQuery()->shouldReceive('whereIn')->with('foo_table.foo', [1, 2, 3])->once(); <add> $builder->shouldReceive('get')->andReturn(new Collection([$model1, $model2]))->once(); <add> $builder->shouldReceive('get')->with(['column'])->andReturn(new Collection([$model1, $model2]))->once(); <add> $builder->shouldReceive('get')->andReturn(null)->once(); <add> <add> $result = $builder->findOr(new Collection([1, 2]), fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame($model1, $result[0]); <add> $this->assertSame($model2, $result[1]); <add> <add> $result = $builder->findOr(new Collection([1, 2]), ['column'], fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame($model1, $result[0]); <add> $this->assertSame($model2, $result[1]); <add> <add> $result = $builder->findOr(new Collection([1, 2, 3]), fn () => 'callback result'); <add> $this->assertSame('callback result', $result); <add> } <add> <ide> public function testFirstOrFailMethodThrowsModelNotFoundException() <ide> { <ide> $this->expectException(ModelNotFoundException::class); <ide><path>tests/Database/DatabaseEloquentHasManyThroughIntegrationTest.php <ide> public function testFindOrFailWithManyUsingCollectionThrowsAnException() <ide> HasManyThroughTestCountry::first()->posts()->findOrFail(new Collection([1, 2])); <ide> } <ide> <add> public function testFindOrMethod() <add> { <add> HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us']) <add> ->users()->create(['id' => 1, 'email' => '[email protected]', 'country_short' => 'us']) <add> ->posts()->create(['id' => 1, 'title' => 'A title', 'body' => 'A body', 'email' => '[email protected]']); <add> <add> $result = HasManyThroughTestCountry::first()->posts()->findOr(1, fn () => 'callback result'); <add> $this->assertInstanceOf(HasManyThroughTestPost::class, $result); <add> $this->assertSame(1, $result->id); <add> $this->assertSame('A title', $result->title); <add> <add> $result = HasManyThroughTestCountry::first()->posts()->findOr(1, ['posts.id'], fn () => 'callback result'); <add> $this->assertInstanceOf(HasManyThroughTestPost::class, $result); <add> $this->assertSame(1, $result->id); <add> $this->assertNull($result->title); <add> <add> $result = HasManyThroughTestCountry::first()->posts()->findOr(2, fn () => 'callback result'); <add> $this->assertSame('callback result', $result); <add> } <add> <add> public function testFindOrMethodWithMany() <add> { <add> HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us']) <add> ->users()->create(['id' => 1, 'email' => '[email protected]', 'country_short' => 'us']) <add> ->posts()->createMany([ <add> ['id' => 1, 'title' => 'A title', 'body' => 'A body', 'email' => '[email protected]'], <add> ['id' => 2, 'title' => 'Another title', 'body' => 'Another body', 'email' => '[email protected]'], <add> ]); <add> <add> $result = HasManyThroughTestCountry::first()->posts()->findOr([1, 2], fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame(1, $result[0]->id); <add> $this->assertSame(2, $result[1]->id); <add> $this->assertSame('A title', $result[0]->title); <add> $this->assertSame('Another title', $result[1]->title); <add> <add> $result = HasManyThroughTestCountry::first()->posts()->findOr([1, 2], ['posts.id'], fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame(1, $result[0]->id); <add> $this->assertSame(2, $result[1]->id); <add> $this->assertNull($result[0]->title); <add> $this->assertNull($result[1]->title); <add> <add> $result = HasManyThroughTestCountry::first()->posts()->findOr([1, 2, 3], fn () => 'callback result'); <add> $this->assertSame('callback result', $result); <add> } <add> <add> public function testFindOrMethodWithManyUsingCollection() <add> { <add> HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us']) <add> ->users()->create(['id' => 1, 'email' => '[email protected]', 'country_short' => 'us']) <add> ->posts()->createMany([ <add> ['id' => 1, 'title' => 'A title', 'body' => 'A body', 'email' => '[email protected]'], <add> ['id' => 2, 'title' => 'Another title', 'body' => 'Another body', 'email' => '[email protected]'], <add> ]); <add> <add> $result = HasManyThroughTestCountry::first()->posts()->findOr(new Collection([1, 2]), fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame(1, $result[0]->id); <add> $this->assertSame(2, $result[1]->id); <add> $this->assertSame('A title', $result[0]->title); <add> $this->assertSame('Another title', $result[1]->title); <add> <add> $result = HasManyThroughTestCountry::first()->posts()->findOr(new Collection([1, 2]), ['posts.id'], fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame(1, $result[0]->id); <add> $this->assertSame(2, $result[1]->id); <add> $this->assertNull($result[0]->title); <add> $this->assertNull($result[1]->title); <add> <add> $result = HasManyThroughTestCountry::first()->posts()->findOr(new Collection([1, 2, 3]), fn () => 'callback result'); <add> $this->assertSame('callback result', $result); <add> } <add> <ide> public function testFirstRetrievesFirstRecord() <ide> { <ide> $this->seedData(); <ide><path>tests/Integration/Database/EloquentBelongsToManyTest.php <ide> public function testFindOrNewMethod() <ide> $this->assertInstanceOf(Tag::class, $post->tags()->findOrNew(666)); <ide> } <ide> <add> public function testFindOrMethod() <add> { <add> $post = Post::create(['title' => Str::random()]); <add> $post->tags()->create(['name' => Str::random()]); <add> <add> $result = $post->tags()->findOr(1, fn () => 'callback result'); <add> $this->assertInstanceOf(Tag::class, $result); <add> $this->assertSame(1, $result->id); <add> $this->assertNotNull($result->name); <add> <add> $result = $post->tags()->findOr(1, ['id'], fn () => 'callback result'); <add> $this->assertInstanceOf(Tag::class, $result); <add> $this->assertSame(1, $result->id); <add> $this->assertNull($result->name); <add> <add> $result = $post->tags()->findOr(2, fn () => 'callback result'); <add> $this->assertSame('callback result', $result); <add> } <add> <add> public function testFindOrMethodWithMany() <add> { <add> $post = Post::create(['title' => Str::random()]); <add> $post->tags()->createMany([ <add> ['name' => Str::random()], <add> ['name' => Str::random()], <add> ]); <add> <add> $result = $post->tags()->findOr([1, 2], fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame(1, $result[0]->id); <add> $this->assertSame(2, $result[1]->id); <add> $this->assertNotNull($result[0]->name); <add> $this->assertNotNull($result[1]->name); <add> <add> $result = $post->tags()->findOr([1, 2], ['id'], fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame(1, $result[0]->id); <add> $this->assertSame(2, $result[1]->id); <add> $this->assertNull($result[0]->name); <add> $this->assertNull($result[1]->name); <add> <add> $result = $post->tags()->findOr([1, 2, 3], fn () => 'callback result'); <add> $this->assertSame('callback result', $result); <add> } <add> <add> public function testFindOrMethodWithManyUsingCollection() <add> { <add> $post = Post::create(['title' => Str::random()]); <add> $post->tags()->createMany([ <add> ['name' => Str::random()], <add> ['name' => Str::random()], <add> ]); <add> <add> $result = $post->tags()->findOr(new Collection([1, 2]), fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame(1, $result[0]->id); <add> $this->assertSame(2, $result[1]->id); <add> $this->assertNotNull($result[0]->name); <add> $this->assertNotNull($result[1]->name); <add> <add> $result = $post->tags()->findOr(new Collection([1, 2]), ['id'], fn () => 'callback result'); <add> $this->assertInstanceOf(Collection::class, $result); <add> $this->assertSame(1, $result[0]->id); <add> $this->assertSame(2, $result[1]->id); <add> $this->assertNull($result[0]->name); <add> $this->assertNull($result[1]->name); <add> <add> $result = $post->tags()->findOr(new Collection([1, 2, 3]), fn () => 'callback result'); <add> $this->assertSame('callback result', $result); <add> } <add> <ide> public function testFirstOrNewMethod() <ide> { <ide> $post = Post::create(['title' => Str::random()]);
6
PHP
PHP
set the app key in the config after updating it
306810528329467771653c81a2f984ae80956290
<ide><path>src/Illuminate/Foundation/Console/KeyGenerateCommand.php <ide> public function fire() <ide> <ide> $this->files->put($path, $contents); <ide> <add> $this->laravel['config']['app.key'] = $key; <add> <ide> $this->info("Application key [$key] set successfully."); <ide> } <ide>
1
Ruby
Ruby
restore consistency with the rest of the doc
43532f6b25758e1299d6fc9404c12b76df8fb3b0
<ide><path>actionpack/lib/action_view/helpers/url_helper.rb <ide> def button_to(name, options = {}, html_options = {}) <ide> # "Go Back" link instead of a link to the comments page, we could do something like this... <ide> # <ide> # <%= <del> # link_to_unless_current("Comment", { :controller => 'comments', :action => 'new'}) do <del> # link_to("Go back", { :controller => 'posts', :action => 'index' }) <add> # link_to_unless_current("Comment", { :controller => "comments", :action => "new" }) do <add> # link_to("Go back", { :controller => "posts", :action => "index" }) <ide> # end <ide> # %> <ide> def link_to_unless_current(name, options = {}, html_options = {}, &block)
1