content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
PHP | PHP | fix multiple methods on routes command | 114d33dd940ccea8cbacbc400409a9b9b5bef131 | <ide><path>src/Illuminate/Foundation/Console/RoutesCommand.php
<ide> protected function getRoutes()
<ide> */
<ide> protected function getRouteInformation(Route $route)
<ide> {
<del> $uri = head($route->methods()).' '.$route->uri();
<add> $uri = implode('|', $route->methods()).' '.$route->uri();
<ide>
<ide> return $this->filterRoute(array(
<ide> 'host' => $route->domain(), | 1 |
Go | Go | add godoc comment about client tls verification | 4e2c0f385c3032b0b15105c81b18e3981e6e40ad | <ide><path>api/client/lib/client.go
<ide> type Client struct {
<ide> // Use DOCKER_HOST to set the url to the docker server.
<ide> // Use DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest.
<ide> // Use DOCKER_CERT_PATH to load the tls certificates from.
<add>// Use DOCKER_TLS_VERIFY to enable or disable TLS verification, off by default.
<ide> func NewEnvClient() (*Client, error) {
<ide> var transport *http.Transport
<ide> if dockerCertPath := os.Getenv("DOCKER_CERT_PATH"); dockerCertPath != "" { | 1 |
Ruby | Ruby | fix tests with ruby 3 | a09b04e63720022c5de12b200ea2ce975b3f88f9 | <ide><path>actionpack/test/dispatch/request_id_test.rb
<ide>
<ide> class RequestIdTest < ActiveSupport::TestCase
<ide> test "passing on the request id from the outside" do
<del> assert_equal "external-uu-rid", stub_request("HTTP_X_REQUEST_ID" => "external-uu-rid").request_id
<add> assert_equal "external-uu-rid", stub_request({ "HTTP_X_REQUEST_ID" => "external-uu-rid" }).request_id
<ide> end
<ide>
<ide> test "passing on the request id via a configured header" do
<ide> assert_equal "external-uu-rid", stub_request({ "HTTP_TRACER_ID" => "external-uu-rid" }, header: "Tracer-Id").request_id
<ide> end
<ide>
<ide> test "ensure that only alphanumeric uurids are accepted" do
<del> assert_equal "X-Hacked-HeaderStuff", stub_request("HTTP_X_REQUEST_ID" => "; X-Hacked-Header: Stuff").request_id
<add> assert_equal "X-Hacked-HeaderStuff", stub_request({ "HTTP_X_REQUEST_ID" => "; X-Hacked-Header: Stuff" }).request_id
<ide> end
<ide>
<ide> test "accept Apache mod_unique_id format" do
<ide> mod_unique_id = "abcxyz@ABCXYZ-0123456789"
<del> assert_equal mod_unique_id, stub_request("HTTP_X_REQUEST_ID" => mod_unique_id).request_id
<add> assert_equal mod_unique_id, stub_request({ "HTTP_X_REQUEST_ID" => mod_unique_id }).request_id
<ide> end
<ide>
<ide> test "ensure that 255 char limit on the request id is being enforced" do
<del> assert_equal "X" * 255, stub_request("HTTP_X_REQUEST_ID" => "X" * 500).request_id
<add> assert_equal "X" * 255, stub_request({ "HTTP_X_REQUEST_ID" => "X" * 500 }).request_id
<ide> end
<ide>
<ide> test "generating a request id when none is supplied" do
<ide> assert_match(/\w+-\w+-\w+-\w+-\w+/, stub_request.request_id)
<ide> end
<ide>
<ide> test "uuid alias" do
<del> assert_equal "external-uu-rid", stub_request("HTTP_X_REQUEST_ID" => "external-uu-rid").uuid
<add> assert_equal "external-uu-rid", stub_request({ "HTTP_X_REQUEST_ID" => "external-uu-rid" }).uuid
<ide> end
<ide>
<ide> private | 1 |
Mixed | Ruby | allow list explicit list of allowed properties | 795b1c654a908dee6ecf64b9bf49f2320a734506 | <ide><path>activerecord/lib/active_record/encryption/encryptable_record.rb
<ide> def build_previous_types(previous_config_list, type)
<ide> previous_config_list = [previous_config_list] unless previous_config_list.is_a?(Array)
<ide> previous_config_list.collect do |previous_config|
<ide> key_provider = build_key_provider(**previous_config.slice(:key_provider, :key, :deterministic))
<del> context_properties = previous_config.without(:key_provider, :downcase, :ignore_case, :deterministic, :subtype)
<add> context_properties = previous_config.slice(*ActiveRecord::Encryption::Context::PROPERTIES.without(:key_provider))
<ide> ActiveRecord::Encryption::EncryptedAttributeType.new \
<ide> key_provider: key_provider, downcase: previous_config[:downcase] || previous_config[:ignore_case],
<ide> deterministic: previous_config[:deterministic], subtype: type, **context_properties
<ide><path>guides/source/active_record_encryption.md
<ide> After reading this guide, you will know:
<ide>
<ide> --------------------------------------------------------------------------------
<ide>
<del>Active Record supports application-level encryption. To use by declaring which attributes should be encrypted and seamlessly encrypting and decrypting them when necessary. The encryption layer is placed between the database and the application. The application will access unencrypted data, but the database will store it encrypted.
<add>Active Record supports application-level encryption. It works by declaring which attributes should be encrypted and seamlessly encrypting and decrypting them when necessary. The encryption layer is placed between the database and the application. The application will access unencrypted data, but the database will store it encrypted.
<ide>
<ide> ## Basic usage
<ide>
<ide> To ease migrations of unencrypted data, the library includes the option `config.
<ide> * Trying to read encrypted attributes that are not encrypted will work without raising any error
<ide> * Queries with deterministically-encrypted attributes will include the "clear text" version of them to support finding both encrypted and unencrypted content.
<ide>
<del>**This option is meant to be used in transition periods** while clear data and encrypted data need to coexist. Their value is `false` by default, which is the recommended goal for any application: errors will be raised when working with unencrypted data.
<add>**This option is meant to be used in transition periods** while clear data and encrypted data need to coexist. Its value is `false` by default, which is the recommended goal for any application: errors will be raised when working with unencrypted data.
<ide>
<ide> ### Ignoring case
<ide>
<ide> You can use the `:downcase` when declaring the encrypted attribute. This will d
<ide>
<ide> ```ruby
<ide> class Person
<del> encrypts :email_address, deterministic: true, downcase: true
<add> encrypts :email_address, deterministic: true, downcase: true
<ide> end
<ide> ```
<ide>
<ide> When using `:downcase` the original case is lost. There might be cases where you need to preserve the original case when reading the value, but you need to ignore the case when querying. For those cases you can use the option `:ignore_case`, which requires you to add a new column named `original_<column_name>` to store the content with the case unchanged:
<ide>
<ide> ```ruby
<ide> class Label
<del>encrypts :name, deterministic: true, ignore_case: true # the content with the original case will be stored in the column `original_name`
<add> encrypts :name, deterministic: true, ignore_case: true # the content with the original case will be stored in the column `original_name`
<ide> end
<ide> ```
<ide>
<ide> You can configure a key provider on a per-class basis with the `:key_provider` o
<ide>
<ide> ```ruby
<ide> class Article < ApplicationRecord
<del>encrypts :summary, key_provider: ArticleKeyProvider.new
<add> encrypts :summary, key_provider: ArticleKeyProvider.new
<ide> end
<ide> ```
<ide>
<ide> The key will be used internally to derive the key used to encrypt and decrypt th
<ide>
<ide> ```yml
<ide> active_record_encryption:
<del> master_key:
<del> - bc17e7b413fd4720716a7633027f8cc4 # Active, encrypts new content
<del> - a1cc4d7b9f420e40a337b9e68c5ecec6 # Previous keys can still decrypt existing content
<del> key_derivation_salt: a3226b97b3b2f8372d1fc6d497a0c0d3
<add> master_key:
<add> - bc17e7b413fd4720716a7633027f8cc4 # Active, encrypts new content
<add> - a1cc4d7b9f420e40a337b9e68c5ecec6 # Previous keys can still decrypt existing content
<add> key_derivation_salt: a3226b97b3b2f8372d1fc6d497a0c0d3
<ide> ```
<ide>
<ide> This enabled workflows where you keep a short list of keys, by adding new keys, re-encrypting content and deleting old keys.
<ide> This works consistently across the built-in key providers. Also, when using a de
<ide> ```yaml
<ide> active_record_encryption:
<ide> deterministic_key:
<del> - dd9e4ffef6eced8317667d70df7c75eb # Active, encrypts new content
<del> - 6940371df37f040e0e8a12948bb31cda # Previous keys can still decrypt existing content
<add> - dd9e4ffef6eced8317667d70df7c75eb # Active, encrypts new content
<add> - 6940371df37f040e0e8a12948bb31cda # Previous keys can still decrypt existing content
<ide> ```
<ide>
<ide> NOTE: Active Record Encryption doesn't provide automatic management of key rotation processes yet. All the pieces are there, but this hasn't been implemented yet. | 2 |
Text | Text | fix typo in readme.md | 21e258d7328e56fd451e6ed0324cff094ec70798 | <ide><path>daemon/graphdriver/devmapper/README.md
<ide> stored in the `$graph/devicemapper/json` file (encoded as Json).
<ide>
<ide> In order to support multiple devicemapper graphs on a system the thin
<ide> pool will be named something like: `docker-0:33-19478248-pool`, where
<del>the `0:30` part is the minor/major device nr and `19478248` is the
<add>the `0:33` part is the minor/major device nr and `19478248` is the
<ide> inode number of the $graph directory.
<ide>
<ide> On the thin pool docker automatically creates a base thin device, | 1 |
PHP | PHP | prependkeyswith helper | ffa6cca4285f87cf19b6dbc9986fb73fca04abd6 | <ide><path>src/Illuminate/Collections/Arr.php
<ide> public static function keyBy($array, $keyBy)
<ide> return Collection::make($array)->keyBy($keyBy)->all();
<ide> }
<ide>
<add> /**
<add> * Prepend the key names of an associative array.
<add> *
<add> * @param array $array
<add> * @param string $prependWith
<add> * @return array
<add> */
<add> public static function prependKeysWith($array, $prependWith)
<add> {
<add> return Collection::make($array)->mapWithKeys(function ($item, $key) use ($prependWith) {
<add> return [$prependWith.$key => $item];
<add> })->all();
<add> }
<add>
<ide> /**
<ide> * Get a subset of the items from the given array.
<ide> *
<ide><path>tests/Support/SupportArrTest.php
<ide> public function testKeyBy()
<ide> '498' => ['id' => '498', 'data' => 'hgi'],
<ide> ], Arr::keyBy($array, 'id'));
<ide> }
<add>
<add> public function testPrependKeysWith()
<add> {
<add> $array = [
<add> 'id' => '123',
<add> 'data' => '456',
<add> 'list' => [1, 2, 3],
<add> 'meta' => [
<add> 'key' => 1,
<add> ],
<add> ];
<add>
<add> $this->assertEquals([
<add> 'test.id' => '123',
<add> 'test.data' => '456',
<add> 'test.list' => [1, 2, 3],
<add> 'test.meta' => [
<add> 'key' => 1,
<add> ],
<add> ], Arr::prependKeysWith($array, 'test.'));
<add> }
<ide> } | 2 |
Javascript | Javascript | fix hot test cases for async-node | 2b964c62d1290b5c5cc90bb1385c98e1d6e7eaa3 | <ide><path>test/hotCases/conditional-runtime/accept-conditional/index.js
<ide> it("should create a conditional import when accepted", done => {
<ide> if (Math.random() < 0) new Worker(new URL("worker.js", import.meta.url));
<ide> import("./module")
<del> .then(module => module.test(done))
<add> .then(module =>
<add> module.test(callback => {
<add> NEXT(require("../../update")(done, undefined, callback));
<add> }, done)
<add> )
<ide> .catch(done);
<ide> });
<ide><path>test/hotCases/conditional-runtime/accept-conditional/module.js
<ide> import { f } from "./shared";
<ide>
<del>export function test(done) {
<add>export function test(next, done) {
<ide> expect(f()).toBe(42);
<del> NEXT(
<del> require("../../update")(done, undefined, () => {
<del> expect(f()).toBe(43);
<del> done();
<del> })
<del> );
<add> next(() => {
<add> expect(f()).toBe(43);
<add> done();
<add> });
<ide> } | 2 |
PHP | PHP | add extra test for overriding relationship | fbd80a587323fabab67adffea8e6851065a3a7d7 | <ide><path>tests/Integration/Database/EloquentRelationshipsTest.php
<ide>
<ide> namespace Illuminate\Tests\Integration\Database\EloquentRelationshipsTest;
<ide>
<add>use Illuminate\Database\Eloquent\Relations\HasOneThrough;
<ide> use Orchestra\Testbench\TestCase;
<ide> use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Database\Eloquent\Builder;
<ide> public function standard_relationships()
<ide> $this->assertInstanceOf(MorphMany::class, $post->likes());
<ide> $this->assertInstanceOf(BelongsToMany::class, $post->viewers());
<ide> $this->assertInstanceOf(HasManyThrough::class, $post->lovers());
<add> $this->assertInstanceOf(HasOneThrough::class, $post->contract());
<ide> $this->assertInstanceOf(MorphToMany::class, $post->tags());
<ide> $this->assertInstanceOf(MorphTo::class, $post->postable());
<ide> }
<ide> public function overridden_relationships()
<ide> $this->assertInstanceOf(CustomMorphMany::class, $post->likes());
<ide> $this->assertInstanceOf(CustomBelongsToMany::class, $post->viewers());
<ide> $this->assertInstanceOf(CustomHasManyThrough::class, $post->lovers());
<add> $this->assertInstanceOf(CustomHasOneThrough::class, $post->contract());
<ide> $this->assertInstanceOf(CustomMorphToMany::class, $post->tags());
<ide> $this->assertInstanceOf(CustomMorphTo::class, $post->postable());
<ide> }
<ide> public function lovers()
<ide> return $this->hasManyThrough(FakeRelationship::class, FakeRelationship::class);
<ide> }
<ide>
<add> public function contract()
<add> {
<add> return $this->hasOneThrough(FakeRelationship::class, FakeRelationship::class);
<add> }
<add>
<ide> public function tags()
<ide> {
<ide> return $this->morphToMany(FakeRelationship::class, 'taggable');
<ide> protected function newHasManyThrough(Builder $query, Model $farParent, Model $th
<ide> return new CustomHasManyThrough($query, $farParent, $throughParent, $firstKey, $secondKey, $localKey, $secondLocalKey);
<ide> }
<ide>
<add> protected function newHasOneThrough(Builder $query, Model $farParent, Model $throughParent, $firstKey,
<add> $secondKey, $localKey, $secondLocalKey
<add> ) {
<add> return new CustomHasOneThrough($query, $farParent, $throughParent, $firstKey, $secondKey, $localKey, $secondLocalKey);
<add> }
<add>
<ide> protected function newMorphToMany(Builder $query, Model $parent, $name, $table, $foreignPivotKey,
<ide> $relatedPivotKey, $parentKey, $relatedKey, $relationName = null, $inverse = false)
<ide> {
<ide> class CustomHasManyThrough extends HasManyThrough
<ide> {
<ide> }
<ide>
<add>class CustomHasOneThrough extends HasOneThrough
<add>{
<add>}
<add>
<ide> class CustomMorphToMany extends MorphToMany
<ide> {
<ide> } | 1 |
PHP | PHP | check type of token as well | ba0cf2a1c9280e99d39aad5d4d686d554941eea1 | <ide><path>app/filters.php
<ide>
<ide> Route::filter('csrf', function()
<ide> {
<del> if (Session::token() != Input::get('_token'))
<add> if (Session::token() !== Input::get('_token'))
<ide> {
<ide> throw new Illuminate\Session\TokenMismatchException;
<ide> } | 1 |
Python | Python | move matrix tests in lib to matrixlib | 1394d0a723832d22ca749e402975786c7707fe02 | <ide><path>numpy/lib/polynomial.py
<ide> def poly(seq_of_zeros):
<ide> >>> np.poly(P)
<ide> array([ 1. , 0. , 0.16666667])
<ide>
<del> Or a square matrix object:
<del>
<del> >>> np.poly(np.matrix(P))
<del> array([ 1. , 0. , 0.16666667])
<del>
<ide> Note how in all cases the leading coefficient is always 1.
<ide>
<ide> """
<ide><path>numpy/lib/scimath.py
<ide> def arctanh(x):
<ide> --------
<ide> >>> np.set_printoptions(precision=4)
<ide>
<del> >>> np.emath.arctanh(np.matrix(np.eye(2)))
<add> >>> np.emath.arctanh(np.eye(2))
<ide> array([[ Inf, 0.],
<ide> [ 0., Inf]])
<ide> >>> np.emath.arctanh([1j])
<ide><path>numpy/lib/tests/test_arraysetops.py
<ide> def test_ediff1d(self):
<ide> assert_array_equal([1,7,8], ediff1d(two_elem, to_end=[7,8]))
<ide> assert_array_equal([7,1], ediff1d(two_elem, to_begin=7))
<ide> assert_array_equal([5,6,1], ediff1d(two_elem, to_begin=[5,6]))
<del> assert(isinstance(ediff1d(np.matrix(1)), np.matrix))
<del> assert(isinstance(ediff1d(np.matrix(1), to_begin=1), np.matrix))
<ide>
<ide> def test_isin(self):
<ide> # the tests for in1d cover most of isin's behavior
<ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_basic(self):
<ide> assert_almost_equal(y5.mean(0), average(y5, 0))
<ide> assert_almost_equal(y5.mean(1), average(y5, 1))
<ide>
<del> y6 = np.matrix(rand(5, 5))
<del> assert_array_equal(y6.mean(0), average(y6, 0))
<del>
<ide> def test_weights(self):
<ide> y = np.arange(10)
<ide> w = np.arange(10)
<ide> class subclass(np.ndarray):
<ide> assert_equal(type(np.average(a)), subclass)
<ide> assert_equal(type(np.average(a, weights=w)), subclass)
<ide>
<del> # also test matrices
<del> a = np.matrix([[1,2],[3,4]])
<del> w = np.matrix([[1,2],[3,4]])
<del>
<del> r = np.average(a, axis=0, weights=w)
<del> assert_equal(type(r), np.matrix)
<del> assert_equal(r, [[2.5, 10.0/3]])
<del>
<ide> def test_upcasting(self):
<ide> types = [('i4', 'i4', 'f8'), ('i4', 'f4', 'f8'), ('f4', 'i4', 'f8'),
<ide> ('f4', 'f4', 'f4'), ('f4', 'f8', 'f8')]
<ide> def test_masked(self):
<ide> xm = np.ma.array(x, mask=mask)
<ide> assert_almost_equal(trapz(y, xm), r)
<ide>
<del> def test_matrix(self):
<del> # Test to make sure matrices give the same answer as ndarrays
<del> x = np.linspace(0, 5)
<del> y = x * x
<del> r = trapz(y, x)
<del> mx = np.matrix(x)
<del> my = np.matrix(y)
<del> mr = trapz(my, mx)
<del> assert_almost_equal(mr, r)
<del>
<ide>
<ide> class TestSinc(object):
<ide>
<ide><path>numpy/lib/tests/test_index_tricks.py
<ide> def test_2d(self):
<ide> assert_array_equal(d[:5, :], b)
<ide> assert_array_equal(d[5:, :], c)
<ide>
<del> def test_matrix(self):
<del> a = [1, 2]
<del> b = [3, 4]
<del>
<del> ab_r = np.r_['r', a, b]
<del> ab_c = np.r_['c', a, b]
<del>
<del> assert_equal(type(ab_r), np.matrix)
<del> assert_equal(type(ab_c), np.matrix)
<del>
<del> assert_equal(np.array(ab_r), [[1,2,3,4]])
<del> assert_equal(np.array(ab_c), [[1],[2],[3],[4]])
<del>
<del> assert_raises(ValueError, lambda: np.r_['rc', a, b])
<del>
<del> def test_matrix_scalar(self):
<del> r = np.r_['r', [1, 2], 3]
<del> assert_equal(type(r), np.matrix)
<del> assert_equal(np.array(r), [[1,2,3]])
<del>
<del> def test_matrix_builder(self):
<del> a = np.array([1])
<del> b = np.array([2])
<del> c = np.array([3])
<del> d = np.array([4])
<del> actual = np.r_['a, b; c, d']
<del> expected = np.bmat([[a, b], [c, d]])
<del>
<del> assert_equal(actual, expected)
<del> assert_equal(type(actual), type(expected))
<del>
<ide> def test_0d(self):
<ide> assert_equal(r_[0, np.array(1), 2], [0, 1, 2])
<ide> assert_equal(r_[[0, 1, 2], np.array(3)], [0, 1, 2, 3])
<ide><path>numpy/lib/tests/test_nanfunctions.py
<ide> def test_scalar(self):
<ide> for f in self.nanfuncs:
<ide> assert_(f(0.) == 0.)
<ide>
<del> def test_matrices(self):
<add> def test_subclass(self):
<add> class MyNDArray(np.ndarray):
<add> pass
<add>
<ide> # Check that it works and that type and
<ide> # shape are preserved
<del> mat = np.matrix(np.eye(3))
<add> mine = np.eye(3).view(MyNDArray)
<ide> for f in self.nanfuncs:
<del> res = f(mat, axis=0)
<del> assert_(isinstance(res, np.matrix))
<del> assert_(res.shape == (1, 3))
<del> res = f(mat, axis=1)
<del> assert_(isinstance(res, np.matrix))
<del> assert_(res.shape == (3, 1))
<del> res = f(mat)
<del> assert_(np.isscalar(res))
<add> res = f(mine, axis=0)
<add> assert_(isinstance(res, MyNDArray))
<add> assert_(res.shape == (3,))
<add> res = f(mine, axis=1)
<add> assert_(isinstance(res, MyNDArray))
<add> assert_(res.shape == (3,))
<add> res = f(mine)
<add> assert_(res.shape == ())
<add>
<ide> # check that rows of nan are dealt with for subclasses (#4628)
<del> mat[1] = np.nan
<add> mine[1] = np.nan
<ide> for f in self.nanfuncs:
<ide> with warnings.catch_warnings(record=True) as w:
<ide> warnings.simplefilter('always')
<del> res = f(mat, axis=0)
<del> assert_(isinstance(res, np.matrix))
<add> res = f(mine, axis=0)
<add> assert_(isinstance(res, MyNDArray))
<ide> assert_(not np.any(np.isnan(res)))
<ide> assert_(len(w) == 0)
<ide>
<ide> with warnings.catch_warnings(record=True) as w:
<ide> warnings.simplefilter('always')
<del> res = f(mat, axis=1)
<del> assert_(isinstance(res, np.matrix))
<del> assert_(np.isnan(res[1, 0]) and not np.isnan(res[0, 0])
<del> and not np.isnan(res[2, 0]))
<add> res = f(mine, axis=1)
<add> assert_(isinstance(res, MyNDArray))
<add> assert_(np.isnan(res[1]) and not np.isnan(res[0])
<add> and not np.isnan(res[2]))
<ide> assert_(len(w) == 1, 'no warning raised')
<ide> assert_(issubclass(w[0].category, RuntimeWarning))
<ide>
<ide> with warnings.catch_warnings(record=True) as w:
<ide> warnings.simplefilter('always')
<del> res = f(mat)
<del> assert_(np.isscalar(res))
<add> res = f(mine)
<add> assert_(res.shape == ())
<ide> assert_(res != np.nan)
<ide> assert_(len(w) == 0)
<ide>
<ide> def test_scalar(self):
<ide> for f in self.nanfuncs:
<ide> assert_(f(0.) == 0.)
<ide>
<del> def test_matrices(self):
<add> def test_subclass(self):
<add> class MyNDArray(np.ndarray):
<add> pass
<add>
<ide> # Check that it works and that type and
<ide> # shape are preserved
<del> mat = np.matrix(np.eye(3))
<add> mine = np.eye(3).view(MyNDArray)
<ide> for f in self.nanfuncs:
<del> res = f(mat, axis=0)
<del> assert_(isinstance(res, np.matrix))
<del> assert_(res.shape == (1, 3))
<del> res = f(mat, axis=1)
<del> assert_(isinstance(res, np.matrix))
<del> assert_(res.shape == (3, 1))
<del> res = f(mat)
<del> assert_(np.isscalar(res))
<add> res = f(mine, axis=0)
<add> assert_(isinstance(res, MyNDArray))
<add> assert_(res.shape == (3,))
<add> res = f(mine, axis=1)
<add> assert_(isinstance(res, MyNDArray))
<add> assert_(res.shape == (3,))
<add> res = f(mine)
<add> assert_(res.shape == ())
<ide>
<ide>
<ide> class TestNanFunctions_IntTypes(object):
<ide> def test_scalar(self):
<ide> for f in self.nanfuncs:
<ide> assert_(f(0.) == 0.)
<ide>
<del> def test_matrices(self):
<add> def test_subclass(self):
<add> class MyNDArray(np.ndarray):
<add> pass
<add>
<ide> # Check that it works and that type and
<ide> # shape are preserved
<del> mat = np.matrix(np.eye(3))
<add> array = np.eye(3)
<add> mine = array.view(MyNDArray)
<ide> for f in self.nanfuncs:
<del> res = f(mat, axis=0)
<del> assert_(isinstance(res, np.matrix))
<del> assert_(res.shape == (1, 3))
<del> res = f(mat, axis=1)
<del> assert_(isinstance(res, np.matrix))
<del> assert_(res.shape == (3, 1))
<del> res = f(mat)
<del> assert_(np.isscalar(res))
<add> expected_shape = f(array, axis=0).shape
<add> res = f(mine, axis=0)
<add> assert_(isinstance(res, MyNDArray))
<add> assert_(res.shape == expected_shape)
<add> expected_shape = f(array, axis=1).shape
<add> res = f(mine, axis=1)
<add> assert_(isinstance(res, MyNDArray))
<add> assert_(res.shape == expected_shape)
<add> expected_shape = f(array).shape
<add> res = f(mine)
<add> assert_(isinstance(res, MyNDArray))
<add> assert_(res.shape == expected_shape)
<ide>
<ide>
<ide> class TestNanFunctions_SumProd(SharedNanFunctionsTestsMixin):
<ide> def test_keepdims(self):
<ide> res = f(d, axis=axis)
<ide> assert_equal(res.shape, (3, 5, 7, 11))
<ide>
<del> def test_matrices(self):
<del> # Check that it works and that type and
<del> # shape are preserved
<del> mat = np.matrix(np.eye(3))
<del> for f in self.nanfuncs:
<del> for axis in np.arange(2):
<del> res = f(mat, axis=axis)
<del> assert_(isinstance(res, np.matrix))
<del> assert_(res.shape == (3, 3))
<del> res = f(mat)
<del> assert_(res.shape == (1, 3*3))
<del>
<ide> def test_result_values(self):
<ide> for axis in (-2, -1, 0, 1, None):
<ide> tgt = np.cumprod(_ndat_ones, axis=axis)
<ide><path>numpy/lib/tests/test_shape_base.py
<ide> def test_3d(self):
<ide> [[27, 30, 33], [36, 39, 42], [45, 48, 51]])
<ide>
<ide> def test_preserve_subclass(self):
<del> # this test is particularly malicious because matrix
<del> # refuses to become 1d
<ide> def double(row):
<ide> return row * 2
<del> m = np.matrix([[0, 1], [2, 3]])
<del> expected = np.matrix([[0, 2], [4, 6]])
<add>
<add> class MyNDArray(np.ndarray):
<add> pass
<add>
<add> m = np.array([[0, 1], [2, 3]]).view(MyNDArray)
<add> expected = np.array([[0, 2], [4, 6]]).view(MyNDArray)
<ide>
<ide> result = apply_along_axis(double, 0, m)
<del> assert_(isinstance(result, np.matrix))
<add> assert_(isinstance(result, MyNDArray))
<ide> assert_array_equal(result, expected)
<ide>
<ide> result = apply_along_axis(double, 1, m)
<del> assert_(isinstance(result, np.matrix))
<add> assert_(isinstance(result, MyNDArray))
<ide> assert_array_equal(result, expected)
<ide>
<ide> def test_subclass(self):
<ide> def test_basic(self):
<ide>
<ide> class TestKron(object):
<ide> def test_return_type(self):
<del> a = np.ones([2, 2])
<del> m = np.asmatrix(a)
<del> assert_equal(type(kron(a, a)), np.ndarray)
<del> assert_equal(type(kron(m, m)), np.matrix)
<del> assert_equal(type(kron(a, m)), np.matrix)
<del> assert_equal(type(kron(m, a)), np.matrix)
<del>
<ide> class myarray(np.ndarray):
<ide> __array_priority__ = 0.0
<ide>
<add> a = np.ones([2, 2])
<ide> ma = myarray(a.shape, a.dtype, a.data)
<ide> assert_equal(type(kron(a, a)), np.ndarray)
<ide> assert_equal(type(kron(ma, ma)), myarray)
<ide><path>numpy/matrixlib/tests/test_interaction.py
<ide> """
<ide> from __future__ import division, absolute_import, print_function
<ide>
<add>import warnings
<add>
<ide> import numpy as np
<ide> from numpy.testing import (assert_, assert_equal, assert_raises,
<del> assert_raises_regex)
<add> assert_raises_regex, assert_array_equal,
<add> assert_almost_equal)
<ide>
<ide>
<ide> def test_fancy_indexing():
<ide> def test_polynomial_mapdomain():
<ide> dom1 = [0, 4]
<ide> dom2 = [1, 3]
<ide> x = np.matrix([dom1, dom1])
<del> res = np.polynomial.mapdomain(x, dom1, dom2)
<add> res = np.polynomial.polyutils.mapdomain(x, dom1, dom2)
<ide> assert_(isinstance(res, np.matrix))
<ide>
<ide>
<ide> def test_inner_scalar_and_matrix():
<ide> assert_equal(np.inner(sca, arr), desired)
<ide>
<ide>
<del>def test_inner_scalar_and_matrix_of_objects(self):
<add>def test_inner_scalar_and_matrix_of_objects():
<ide> # Ticket #4482
<ide> # 2018-04-29: moved here from core.tests.test_multiarray
<ide> arr = np.matrix([1, 2], dtype=object)
<ide> def test_object_scalar_multiply():
<ide> desired = np.matrix([[3, 6]], dtype=object)
<ide> assert_equal(np.multiply(arr, 3), desired)
<ide> assert_equal(np.multiply(3, arr), desired)
<add>
<add>
<add>def test_nanfunctions_matrices():
<add> # Check that it works and that type and
<add> # shape are preserved
<add> # 2018-04-29: moved here from core.tests.test_nanfunctions
<add> mat = np.matrix(np.eye(3))
<add> for f in [np.nanmin, np.nanmax]:
<add> res = f(mat, axis=0)
<add> assert_(isinstance(res, np.matrix))
<add> assert_(res.shape == (1, 3))
<add> res = f(mat, axis=1)
<add> assert_(isinstance(res, np.matrix))
<add> assert_(res.shape == (3, 1))
<add> res = f(mat)
<add> assert_(np.isscalar(res))
<add> # check that rows of nan are dealt with for subclasses (#4628)
<add> mat[1] = np.nan
<add> for f in [np.nanmin, np.nanmax]:
<add> with warnings.catch_warnings(record=True) as w:
<add> warnings.simplefilter('always')
<add> res = f(mat, axis=0)
<add> assert_(isinstance(res, np.matrix))
<add> assert_(not np.any(np.isnan(res)))
<add> assert_(len(w) == 0)
<add>
<add> with warnings.catch_warnings(record=True) as w:
<add> warnings.simplefilter('always')
<add> res = f(mat, axis=1)
<add> assert_(isinstance(res, np.matrix))
<add> assert_(np.isnan(res[1, 0]) and not np.isnan(res[0, 0])
<add> and not np.isnan(res[2, 0]))
<add> assert_(len(w) == 1, 'no warning raised')
<add> assert_(issubclass(w[0].category, RuntimeWarning))
<add>
<add> with warnings.catch_warnings(record=True) as w:
<add> warnings.simplefilter('always')
<add> res = f(mat)
<add> assert_(np.isscalar(res))
<add> assert_(res != np.nan)
<add> assert_(len(w) == 0)
<add>
<add>
<add>def test_nanfunctions_matrices_general():
<add> # Check that it works and that type and
<add> # shape are preserved
<add> # 2018-04-29: moved here from core.tests.test_nanfunctions
<add> mat = np.matrix(np.eye(3))
<add> for f in (np.nanargmin, np.nanargmax, np.nansum, np.nanprod,
<add> np.nanmean, np.nanvar, np.nanstd):
<add> res = f(mat, axis=0)
<add> assert_(isinstance(res, np.matrix))
<add> assert_(res.shape == (1, 3))
<add> res = f(mat, axis=1)
<add> assert_(isinstance(res, np.matrix))
<add> assert_(res.shape == (3, 1))
<add> res = f(mat)
<add> assert_(np.isscalar(res))
<add>
<add> for f in np.nancumsum, np.nancumprod:
<add> res = f(mat, axis=0)
<add> assert_(isinstance(res, np.matrix))
<add> assert_(res.shape == (3, 3))
<add> res = f(mat, axis=1)
<add> assert_(isinstance(res, np.matrix))
<add> assert_(res.shape == (3, 3))
<add> res = f(mat)
<add> assert_(isinstance(res, np.matrix))
<add> assert_(res.shape == (1, 3*3))
<add>
<add>
<add>def test_average_matrix():
<add> # 2018-04-29: moved here from core.tests.test_function_base.
<add> y = np.matrix(np.random.rand(5, 5))
<add> assert_array_equal(y.mean(0), np.average(y, 0))
<add>
<add> a = np.matrix([[1, 2], [3, 4]])
<add> w = np.matrix([[1, 2], [3, 4]])
<add>
<add> r = np.average(a, axis=0, weights=w)
<add> assert_equal(type(r), np.matrix)
<add> assert_equal(r, [[2.5, 10.0/3]])
<add>
<add>
<add>def test_trapz_matrix():
<add> # Test to make sure matrices give the same answer as ndarrays
<add> # 2018-04-29: moved here from core.tests.test_function_base.
<add> x = np.linspace(0, 5)
<add> y = x * x
<add> r = np.trapz(y, x)
<add> mx = np.matrix(x)
<add> my = np.matrix(y)
<add> mr = np.trapz(my, mx)
<add> assert_almost_equal(mr, r)
<add>
<add>
<add>def test_ediff1d_matrix():
<add> # 2018-04-29: moved here from core.tests.test_arraysetops.
<add> assert(isinstance(np.ediff1d(np.matrix(1)), np.matrix))
<add> assert(isinstance(np.ediff1d(np.matrix(1), to_begin=1), np.matrix))
<add>
<add>
<add>def test_apply_along_axis_matrix():
<add> # this test is particularly malicious because matrix
<add> # refuses to become 1d
<add> # 2018-04-29: moved here from core.tests.test_shape_base.
<add> def double(row):
<add> return row * 2
<add>
<add> m = np.matrix([[0, 1], [2, 3]])
<add> expected = np.matrix([[0, 2], [4, 6]])
<add>
<add> result = np.apply_along_axis(double, 0, m)
<add> assert_(isinstance(result, np.matrix))
<add> assert_array_equal(result, expected)
<add>
<add> result = np.apply_along_axis(double, 1, m)
<add> assert_(isinstance(result, np.matrix))
<add> assert_array_equal(result, expected)
<add>
<add>
<add>def test_kron_matrix():
<add> # 2018-04-29: moved here from core.tests.test_shape_base.
<add> a = np.ones([2, 2])
<add> m = np.asmatrix(a)
<add> assert_equal(type(np.kron(a, a)), np.ndarray)
<add> assert_equal(type(np.kron(m, m)), np.matrix)
<add> assert_equal(type(np.kron(a, m)), np.matrix)
<add> assert_equal(type(np.kron(m, a)), np.matrix)
<add>
<add>
<add>class TestConcatenatorMatrix(object):
<add> # 2018-04-29: moved here from core.tests.test_index_tricks.
<add> def test_matrix(self):
<add> a = [1, 2]
<add> b = [3, 4]
<add>
<add> ab_r = np.r_['r', a, b]
<add> ab_c = np.r_['c', a, b]
<add>
<add> assert_equal(type(ab_r), np.matrix)
<add> assert_equal(type(ab_c), np.matrix)
<add>
<add> assert_equal(np.array(ab_r), [[1, 2, 3, 4]])
<add> assert_equal(np.array(ab_c), [[1], [2], [3], [4]])
<add>
<add> assert_raises(ValueError, lambda: np.r_['rc', a, b])
<add>
<add> def test_matrix_scalar(self):
<add> r = np.r_['r', [1, 2], 3]
<add> assert_equal(type(r), np.matrix)
<add> assert_equal(np.array(r), [[1, 2, 3]])
<add>
<add> def test_matrix_builder(self):
<add> a = np.array([1])
<add> b = np.array([2])
<add> c = np.array([3])
<add> d = np.array([4])
<add> actual = np.r_['a, b; c, d']
<add> expected = np.bmat([[a, b], [c, d]])
<add>
<add> assert_equal(actual, expected)
<add> assert_equal(type(actual), type(expected)) | 8 |
PHP | PHP | shorten a few lines | ac6aec3e5e78fd99ac992991e9e924da72a977bc | <ide><path>src/Illuminate/Mail/Mailer.php
<ide> public function queue($view, array $data, $callback, $queue = null)
<ide> {
<ide> $callback = $this->buildQueueCallable($callback);
<ide>
<del> return $this->queue->push('mailer@handleQueuedMessage', compact('view', 'data', 'callback'), $queue);
<add> return $this->queue->push(
<add> 'mailer@handleQueuedMessage', compact('view', 'data', 'callback'), $queue
<add> );
<ide> }
<ide>
<ide> /**
<ide> public function later($delay, $view, array $data, $callback, $queue = null)
<ide> {
<ide> $callback = $this->buildQueueCallable($callback);
<ide>
<del> return $this->queue->later($delay, 'mailer@handleQueuedMessage', compact('view', 'data', 'callback'), $queue);
<add> return $this->queue->later(
<add> $delay, 'mailer@handleQueuedMessage',
<add> compact('view', 'data', 'callback'), $queue
<add> );
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | use average bias while grouping arrays | b97b003c352cf9da5885ac0a5516fee0a767f134 | <ide><path>lib/internal/util/inspect.js
<ide> function groupArrayElements(ctx, output, value) {
<ide> (totalLength / actualMax > 5 || maxLength <= 6)) {
<ide>
<ide> const approxCharHeights = 2.5;
<del> const biasedMax = Math.max(actualMax - 4, 1);
<add> const averageBias = Math.sqrt(actualMax - totalLength / output.length);
<add> const biasedMax = Math.max(actualMax - 3 - averageBias, 1);
<ide> // Dynamically check how many columns seem possible.
<ide> const columns = Math.min(
<ide> // Ideally a square should be drawn. We expect a character to be about 2.5
<ide><path>test/parallel/test-util-inspect.js
<ide> assert.strictEqual(
<ide>
<ide> expected = [
<ide> '[',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<add> ' 1, 1, 1, 1,',
<add> ' 1, 1, 1, 1,',
<add> ' 1, 1, 1, 1,',
<add> ' 1, 1, 1, 1,',
<add> ' 1, 1, 1, 1,',
<add> ' 1, 1, 1, 1,',
<ide> ' 1, 1, 123456789',
<ide> ']'
<ide> ].join('\n'); | 2 |
Ruby | Ruby | permit license groups | f1e06b865a0eabaf938a2f1026853642db253e5d | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_formula_name
<ide> openssl@1.1
<ide> ].freeze
<ide>
<add> PERMITTED_LICENSE_MISMATCHES = {
<add> "AGPL-3.0" => ["AGPL-3.0-only", "AGPL-3.0-or-later"],
<add> "GPL-2.0" => ["GPL-2.0-only", "GPL-2.0-or-later"],
<add> "GPL-3.0" => ["GPL-3.0-only", "GPL-3.0-or-later"],
<add> "LGPL-2.1" => ["LGPL-2.1-only", "LGPL-2.1-or-later"],
<add> "LGPL-3.0" => ["LGPL-3.0-only", "LGPL-3.0-or-later"],
<add> }.freeze
<add>
<ide> def audit_license
<ide> if formula.license.present?
<ide> non_standard_licenses = formula.license.map do |license|
<ide> def audit_license
<ide>
<ide> github_license = GitHub.get_repo_license(user, repo)
<ide> return if github_license && (formula.license + ["NOASSERTION"]).include?(github_license)
<add> return if PERMITTED_LICENSE_MISMATCHES[github_license]&.any? { |license| formula.license.include? license }
<ide>
<del> problem "License mismatch - GitHub license is: #{Array(github_license)}, "\
<del> "but Formulae license states: #{formula.license}."
<add> problem "Formula license #{formula.license} does not match GitHub license #{Array(github_license)}."
<ide>
<del> elsif @new_formula
<del> problem "No license specified for package."
<add> elsif @new_formula && @core_tap
<add> problem "Formulae in homebrew/core must specify a license."
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb
<ide> class Foo < Formula
<ide> end
<ide>
<ide> it "detects no license info" do
<del> fa = formula_auditor "foo", <<~RUBY, spdx_data: spdx_data, new_formula: true
<add> fa = formula_auditor "foo", <<~RUBY, spdx_data: spdx_data, new_formula: true, core_tap: true
<ide> class Foo < Formula
<ide> url "https://brew.sh/foo-1.0.tgz"
<ide> end
<ide> RUBY
<ide>
<ide> fa.audit_license
<del> expect(fa.problems.first).to match "No license specified for package."
<add> expect(fa.problems.first).to match "Formulae in homebrew/core must specify a license."
<ide> end
<ide>
<ide> it "detects if license is not a standard spdx-id" do
<ide> class Cask < Formula
<ide> expect(fa.problems).to be_empty
<ide> end
<ide>
<add> it "checks online and verifies that a standard license id is in the same exempted license group"\
<add> "as what is indicated on its Github repo" do
<add> fa = formula_auditor "cask", <<~RUBY, spdx_data: spdx_data, online: true, new_formula: true
<add> class Cask < Formula
<add> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz"
<add> head "https://github.com/cask/cask.git"
<add> license "GPL-3.0-or-later"
<add> end
<add> RUBY
<add>
<add> fa.audit_license
<add> expect(fa.problems).to be_empty
<add> end
<add>
<add> it "checks online and verifies that a standard license array is in the same exempted license group"\
<add> "as what is indicated on its Github repo" do
<add> fa = formula_auditor "cask", <<~RUBY, spdx_data: spdx_data, online: true, new_formula: true
<add> class Cask < Formula
<add> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz"
<add> head "https://github.com/cask/cask.git"
<add> license ["GPL-3.0-or-later", "MIT"]
<add> end
<add> RUBY
<add>
<add> fa.audit_license
<add> expect(fa.problems).to be_empty
<add> end
<add>
<ide> it "checks online and detects that a formula-specified license is not "\
<ide> "the same as what is indicated on its Github repository" do
<ide> fa = formula_auditor "cask", <<~RUBY, online: true, spdx_data: spdx_data, core_tap: true, new_formula: true
<ide> class Cask < Formula
<ide> RUBY
<ide>
<ide> fa.audit_license
<del> expect(fa.problems.first).to match "License mismatch - GitHub license is: [\"GPL-3.0\"], "\
<del> "but Formulae license states: #{Array(standard_mismatch_spdx_id)}."
<add> expect(fa.problems.first).to match "Formula license #{Array(standard_mismatch_spdx_id)} "\
<add> "does not match GitHub license [\"GPL-3.0\"]."
<ide> end
<ide>
<ide> it "checks online and detects that an array of license does not contain "\
<ide> class Cask < Formula
<ide> RUBY
<ide>
<ide> fa.audit_license
<del> expect(fa.problems.first).to match "License mismatch - GitHub license is: [\"GPL-3.0\"], "\
<del> "but Formulae license states: #{Array(license_array_mismatch)}."
<add> expect(fa.problems.first).to match "Formula license #{license_array_mismatch} "\
<add> "does not match GitHub license [\"GPL-3.0\"]."
<ide> end
<ide>
<ide> it "checks online and verifies that an array of license contains "\ | 2 |
Ruby | Ruby | support schemas in postgresql `enum_types` | 3ac1d8fe272c8983ba5faf6775fc5112fb86729b | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def enum_types
<ide> SELECT
<ide> type.typname AS name,
<ide> type.OID AS oid,
<add> n.nspname AS schema,
<ide> string_agg(enum.enumlabel, ',' ORDER BY enum.enumsortorder) AS value
<ide> FROM pg_enum AS enum
<del> JOIN pg_type AS type
<del> ON (type.oid = enum.enumtypid)
<del> GROUP BY type.OID, type.typname;
<add> JOIN pg_type AS type ON (type.oid = enum.enumtypid)
<add> JOIN pg_namespace n ON type.typnamespace = n.oid
<add> GROUP BY type.OID, n.nspname, type.typname;
<ide> SQL
<ide>
<ide> exec_query(query, "SCHEMA", allow_retry: true, uses_transaction: false).cast_values.each_with_object({}) do |row, memo|
<del> memo[row.first] = row.last
<add> name, schema = row[0], row[2]
<add> schema = nil if schema == current_schema
<add> full_name = [schema, name].compact.join(".")
<add> memo[full_name] = row.last
<ide> end.to_a
<ide> end
<ide>
<ide><path>activerecord/test/cases/adapters/postgresql/enum_test.rb
<ide> def test_assigning_enum_to_nil
<ide> def test_schema_dump
<ide> @connection.add_column "postgresql_enums", "good_mood", :mood, default: "happy", null: false
<ide>
<del> output = dump_table_schema("postgresql_enums")
<add> output = dump_all_table_schema
<ide>
<ide> assert output.include?("# Note that some types may not work with other database engines. Be careful if changing database."), output
<ide>
<ide> def test_works_with_activerecord_enum
<ide> end
<ide>
<ide> def test_enum_type_scoped_to_schemas
<del> old_search_path = @connection.schema_search_path
<del> @connection.create_schema("test_schema")
<del> @connection.schema_search_path = "test_schema"
<del> @connection.schema_cache.clear!
<del> @connection.create_enum("mood_in_other_schema", ["sad", "ok", "happy"])
<add> with_test_schema("test_schema") do
<add> @connection.create_enum("mood_in_other_schema", ["sad", "ok", "happy"])
<ide>
<del> assert_nothing_raised do
<del> @connection.create_table("postgresql_enums_in_other_schema") do |t|
<del> t.column :current_mood, :mood_in_other_schema, default: "happy", null: false
<add> assert_nothing_raised do
<add> @connection.create_table("postgresql_enums_in_other_schema") do |t|
<add> t.column :current_mood, :mood_in_other_schema, default: "happy", null: false
<add> end
<ide> end
<del> end
<ide>
<del> assert_nothing_raised do
<del> @connection.drop_table("postgresql_enums_in_other_schema")
<del> @connection.drop_enum("mood_in_other_schema")
<add> assert @connection.table_exists?("postgresql_enums_in_other_schema")
<ide> end
<del> ensure
<del> @connection.drop_schema("test_schema")
<del> @connection.schema_search_path = old_search_path
<del> @connection.schema_cache.clear!
<ide> end
<ide>
<ide> def test_enum_type_explicit_schema
<ide> def test_enum_type_explicit_schema
<ide> ensure
<ide> @connection.drop_schema("test_schema", if_exists: true)
<ide> end
<add>
<add> def test_schema_dump_scoped_to_schemas
<add> with_test_schema("test_schema") do
<add> @connection.create_enum("mood_in_test_schema", ["sad", "ok", "happy"])
<add> @connection.create_table("postgresql_enums_in_test_schema") do |t|
<add> t.column :current_mood, :mood_in_test_schema
<add> end
<add>
<add> output = dump_all_table_schema
<add>
<add> assert output.include?('create_enum "public.mood", ["sad", "ok", "happy"]'), output
<add> assert output.include?('create_enum "mood_in_test_schema", ["sad", "ok", "happy"]'), output
<add> assert output.include?('t.enum "current_mood", enum_type: "mood_in_test_schema"'), output
<add> end
<add> end
<add>
<add> def test_schema_load_scoped_to_schemas
<add> silence_stream($stdout) do
<add> with_test_schema("test_schema", drop: false) do
<add> ActiveRecord::Schema.define do
<add> create_enum "mood_in_test_schema", ["sad", "ok", "happy"]
<add> create_enum "public.mood", ["sad", "ok", "happy"]
<add>
<add> create_table "postgresql_enums_in_test_schema", force: :cascade do |t|
<add> t.enum "current_mood", enum_type: "mood_in_test_schema"
<add> end
<add> end
<add>
<add> assert @connection.column_exists?(:postgresql_enums_in_test_schema, :current_mood, sql_type: "mood_in_test_schema")
<add> end
<add>
<add> # This is outside `with_test_schema`, so we need to explicitly specify which schema we query
<add> assert @connection.column_exists?("test_schema.postgresql_enums_in_test_schema", :current_mood, sql_type: "test_schema.mood_in_test_schema")
<add> end
<add> ensure
<add> @connection.drop_schema("test_schema")
<add> end
<add>
<add> private
<add> def with_test_schema(name, drop: true)
<add> old_search_path = @connection.schema_search_path
<add> @connection.create_schema(name)
<add> @connection.schema_search_path = name
<add> yield
<add> ensure
<add> @connection.drop_schema(name) if drop
<add> @connection.schema_search_path = old_search_path
<add> @connection.schema_cache.clear!
<add> end
<ide> end
<ide><path>activerecord/test/cases/schema_dumper_test.rb
<ide> class SchemaDumperTest < ActiveRecord::TestCase
<ide> end
<ide>
<ide> def standard_dump
<del> @@standard_dump ||= perform_schema_dump
<del> end
<del>
<del> def perform_schema_dump
<del> dump_all_table_schema []
<add> @@standard_dump ||= dump_all_table_schema
<ide> end
<ide>
<ide> def test_dump_schema_information_with_empty_versions
<ide> def test_schema_dump_includes_extensions
<ide> connection = ActiveRecord::Base.connection
<ide>
<ide> connection.stub(:extensions, ["hstore"]) do
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert_match "# These are extensions that must be enabled", output
<ide> assert_match %r{enable_extension "hstore"}, output
<ide> end
<ide>
<ide> connection.stub(:extensions, []) do
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert_no_match "# These are extensions that must be enabled", output
<ide> assert_no_match %r{enable_extension}, output
<ide> end
<ide> def test_schema_dump_includes_extensions_in_alphabetic_order
<ide> connection = ActiveRecord::Base.connection
<ide>
<ide> connection.stub(:extensions, ["hstore", "uuid-ossp", "xml2"]) do
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> enabled_extensions = output.scan(%r{enable_extension "(.+)"}).flatten
<ide> assert_equal ["hstore", "uuid-ossp", "xml2"], enabled_extensions
<ide> end
<ide>
<ide> connection.stub(:extensions, ["uuid-ossp", "xml2", "hstore"]) do
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> enabled_extensions = output.scan(%r{enable_extension "(.+)"}).flatten
<ide> assert_equal ["hstore", "uuid-ossp", "xml2"], enabled_extensions
<ide> end
<ide> def test_do_not_dump_foreign_keys_when_bypassed_by_config
<ide> }
<ide> )
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert_no_match(/^\s+add_foreign_key "fk_test_has_fk"[^\n]+\n\s+add_foreign_key "lessons_students"/, output)
<ide> ensure
<ide> ActiveRecord::Base.establish_connection(:arunit)
<ide> def test_schema_dump_with_table_name_prefix_and_suffix
<ide> migration = CreateDogMigration.new
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert_no_match %r{create_table "foo_.+_bar"}, output
<ide> assert_no_match %r{add_index "foo_.+_bar"}, output
<ide> assert_no_match %r{create_table "schema_migrations"}, output
<ide> def test_schema_dump_with_table_name_prefix_and_suffix_regexp_escape
<ide> migration = CreateDogMigration.new
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert_no_match %r{create_table "foo\$.+\$bar"}, output
<ide> assert_no_match %r{add_index "foo\$.+\$bar"}, output
<ide> assert_no_match %r{create_table "schema_migrations"}, output
<ide> def down
<ide> end
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert output.include?('t.datetime "this_should_remain_datetime"')
<ide> assert output.include?('t.datetime "this_is_an_alias_of_datetime"')
<ide> assert output.include?('t.datetime "without_time_zone"')
<ide> def down
<ide> end
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert output.include?('t.datetime "this_should_remain_datetime"')
<ide> assert output.include?('t.datetime "this_is_an_alias_of_datetime"')
<ide> assert output.include?('t.timestamp "without_time_zone"')
<ide> def down
<ide> end
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert output.include?('t.datetime "this_should_remain_datetime"')
<ide> assert output.include?('t.datetime "this_is_an_alias_of_datetime"')
<ide> assert output.include?('t.datetime "this_is_also_an_alias_of_datetime"')
<ide> def down
<ide> end
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> # Normally we'd write `t.datetime` here. But because you've changed the `datetime_type`
<ide> # to something else, `t.datetime` now means `:timestamptz`. To ensure that old columns
<ide> # are still created as a `:timestamp` we need to change what is written to the schema dump.
<ide> def down
<ide> end
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert output.include?('t.datetime "default_format"')
<ide> assert output.include?('t.datetime "without_time_zone"')
<ide> assert output.include?('t.timestamptz "with_time_zone"')
<ide>
<ide> datetime_type_was = ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.datetime_type
<ide> ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.datetime_type = :timestamptz
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert output.include?('t.timestamp "default_format"')
<ide> assert output.include?('t.timestamp "without_time_zone"')
<ide> assert output.include?('t.datetime "with_time_zone"')
<ide> def down
<ide> end
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert output.include?('t.datetime "default_format"')
<ide> assert output.include?('t.datetime "without_time_zone"')
<ide> assert output.include?('t.datetime "also_without_time_zone"')
<ide> def down
<ide> end
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert output.include?('t.datetime "default_format"')
<ide> assert output.include?('t.datetime "without_time_zone"')
<ide> assert output.include?('t.datetime "also_without_time_zone"')
<ide> def down
<ide> end
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> assert output.include?('t.datetime "default_format"')
<ide> assert output.include?('t.datetime "without_time_zone"')
<ide> assert output.include?('t.datetime "also_without_time_zone"')
<ide> def down
<ide> end
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> # Normally we'd write `t.datetime` here. But because you've changed the `datetime_type`
<ide> # to something else, `t.datetime` now means `:timestamptz`. To ensure that old columns
<ide> # are still created as a `:timestamp` we need to change what is written to the schema dump.
<ide> def down
<ide> end
<ide> migration.migrate(:up)
<ide>
<del> output = perform_schema_dump
<add> output = dump_all_table_schema
<ide> # Normally we'd write `t.datetime` here. But because you've changed the `datetime_type`
<ide> # to something else, `t.datetime` now means `:timestamptz`. To ensure that old columns
<ide> # are still created as a `:timestamp` we need to change what is written to the schema dump.
<ide><path>activerecord/test/support/schema_dumping_helper.rb
<ide> def dump_table_schema(table, connection = ActiveRecord::Base.connection)
<ide> ActiveRecord::SchemaDumper.ignore_tables = old_ignore_tables
<ide> end
<ide>
<del> def dump_all_table_schema(ignore_tables)
<add> def dump_all_table_schema(ignore_tables = [])
<ide> old_ignore_tables, ActiveRecord::SchemaDumper.ignore_tables = ActiveRecord::SchemaDumper.ignore_tables, ignore_tables
<ide> stream = StringIO.new
<ide> ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream) | 4 |
Text | Text | add basic documentation for whatwg url api | 4757ddcce10af04e87fe5bbb470880c266e0baba | <ide><path>doc/api/url.md
<ide> properties of URL objects:
<ide> For example, the ASCII space character (`' '`) is encoded as `%20`. The ASCII
<ide> forward slash (`/`) character is encoded as `%3C`.
<ide>
<add>## The WHATWG URL API
<add>
<add>> Stability: 1 - Experimental
<add>
<add>The `url` module provides an *experimental* implementation of the
<add>[WHATWG URL Standard][] as an alternative to the existing `url.parse()` API.
<add>
<add>```js
<add>const URL = require('url').URL;
<add>const myURL = new URL('https://example.org/foo');
<add>
<add>console.log(myURL.href); // https://example.org/foo
<add>console.log(myURL.protocol); // https:
<add>console.log(myURL.hostname); // example.org
<add>console.log(myURL.pathname); // /foo
<add>```
<add>
<add>*Note*: Using the `delete` keyword (e.g. `delete myURL.protocol`,
<add>`delete myURL.pathname`, etc) has no effect but will still return `true`.
<add>
<add>### Class: URL
<add>#### Constructor: new URL(input[, base])
<add>
<add>* `input` {String} The input URL to parse
<add>* `base` {String | URL} The base URL to resolve against if the `input` is not
<add> absolute.
<add>
<add>Creates a new `URL` object by parsing the `input` relative to the `base`. If
<add>`base` is passed as a string, it will be parsed equivalent to `new URL(base)`.
<add>
<add>```js
<add>const myURL = new URL('/foo', 'https://example.org/');
<add> // https://example.org/foo
<add>```
<add>
<add>A `TypeError` will be thrown if the `input` or `base` are not valid URLs. Note
<add>that an effort will be made to coerce the given values into strings. For
<add>instance:
<add>
<add>```js
<add>const myURL = new URL({toString: () => 'https://example.org/'});
<add> // https://example.org/
<add>```
<add>
<add>Unicode characters appearing within the hostname of `input` will be
<add>automatically converted to ASCII using the [Punycode][] algorithm.
<add>
<add>```js
<add>const myURL = new URL('https://你好你好');
<add> // https://xn--6qqa088eba
<add>```
<add>
<add>Additional [examples of parsed URLs][] may be found in the WHATWG URL Standard.
<add>
<add>#### url.hash
<add>
<add>Gets and sets the fragment portion of the URL.
<add>
<add>```js
<add>const myURL = new URL('https://example.org/foo#bar');
<add>console.log(myURL.hash);
<add> // Prints #bar
<add>
<add>myURL.hash = 'baz';
<add>console.log(myURL.href);
<add> // Prints https://example.org/foo#baz
<add>```
<add>
<add>Invalid URL characters included in the value assigned to the `hash` property
<add>are [percent-encoded](#whatwg-percent-encoding). Note that the selection of
<add>which characters to percent-encode may vary somewhat from what the
<add>[`url.parse()`][] and [`url.format()`][] methods would produce.
<add>
<add>#### url.host
<add>
<add>Gets and sets the host portion of the URL.
<add>
<add>```js
<add>const myURL = new URL('https://example.org:81/foo');
<add>console.log(myURL.host);
<add> // Prints example.org:81
<add>
<add>myURL.host = 'example.com:82';
<add>console.log(myURL.href);
<add> // Prints https://example.com:82/foo
<add>```
<add>
<add>Invalid host values assigned to the `host` property are ignored.
<add>
<add>#### url.hostname
<add>
<add>Gets and sets the hostname portion of the URL. The key difference between
<add>`url.host` and `url.hostname` is that `url.hostname` does *not* include the
<add>port.
<add>
<add>```js
<add>const myURL = new URL('https://example.org:81/foo');
<add>console.log(myURL.hostname);
<add> // Prints example.org
<add>
<add>myURL.hostname = 'example.com:82';
<add>console.log(myURL.href);
<add> // Prints https://example.com:81/foo
<add>```
<add>
<add>Invalid hostname values assigned to the `hostname` property are ignored.
<add>
<add>#### url.href
<add>
<add>Gets and sets the serialized URL.
<add>
<add>```js
<add>const myURL = new URL('https://example.org/foo');
<add>console.log(myURL.href);
<add> // Prints https://example.org/foo
<add>
<add>myURL.href = 'https://example.com/bar'
<add> // Prints https://example.com/bar
<add>```
<add>
<add>Setting the value of the `href` property to a new value is equivalent to
<add>creating a new `URL` object using `new URL(value)`. Each of the `URL` object's
<add>properties will be modified.
<add>
<add>If the value assigned to the `href` property is not a valid URL, a `TypeError`
<add>will be thrown.
<add>
<add>#### url.origin
<add>
<add>Gets the read-only serialization of the URL's origin. Unicode characters that
<add>may be contained within the hostname will be encoded as-is without [Punycode][]
<add>encoding.
<add>
<add>```js
<add>const myURL = new URL('https://example.org/foo/bar?baz');
<add>console.log(myURL.origin);
<add> // Prints https://example.org
<add>```
<add>
<add>```js
<add>const idnURL = new URL('https://你好你好');
<add>console.log(idnURL.origin);
<add> // Prints https://你好你好
<add>
<add>console.log(idnURL.hostname);
<add> // Prints xn--6qqa088eba
<add>```
<add>
<add>#### url.password
<add>
<add>Gets and sets the password portion of the URL.
<add>
<add>```js
<add>const myURL = new URL('https://abc:xyz@example.com');
<add>console.log(myURL.password);
<add> // Prints xyz
<add>
<add>myURL.password = '123';
<add>console.log(myURL.href);
<add> // Prints https://abc:123@example.com
<add>```
<add>
<add>Invalid URL characters included in the value assigned to the `password` property
<add>are [percent-encoded](#whatwg-percent-encoding). Note that the selection of
<add>which characters to percent-encode may vary somewhat from what the
<add>[`url.parse()`][] and [`url.format()`][] methods would produce.
<add>
<add>#### url.pathname
<add>
<add>Gets and sets the path portion of the URL.
<add>
<add>```js
<add>const myURL = new URL('https://example.org/abc/xyz?123');
<add>console.log(myURL.pathname);
<add> // Prints /abc/xyz
<add>
<add>myURL.pathname = '/abcdef';
<add>console.log(myURL.href);
<add> // Prints https://example.org/abcdef?123
<add>```
<add>
<add>Invalid URL characters included in the value assigned to the `pathname`
<add>property are [percent-encoded](#whatwg-percent-encoding). Note that the
<add>selection of which characters to percent-encode may vary somewhat from what the
<add>[`url.parse()`][] and [`url.format()`][] methods would produce.
<add>
<add>#### url.port
<add>
<add>Gets and sets the port portion of the URL. When getting the port, the value
<add>is returned as a String.
<add>
<add>```js
<add>const myURL = new URL('https://example.org:8888');
<add>console.log(myURL.port);
<add> // Prints 8888
<add>
<add>myURL.port = 1234;
<add>console.log(myURL.href);
<add> // Prints https://example.org:1234
<add>```
<add>
<add>The port value may be set as either a number or as a String containing a number
<add>in the range `0` to `65535` (inclusive). Setting the value to the default port
<add>of the `URL` objects given `protocol` will result in the `port` value becoming
<add>the empty string (`''`).
<add>
<add>Invalid URL port values assigned to the `port` property are ignored.
<add>
<add>#### url.protocol
<add>
<add>Gets and sets the protocol portion of the URL.
<add>
<add>```js
<add>const myURL = new URL('https://example.org');
<add>console.log(myURL.protocol);
<add> // Prints http:
<add>
<add>myURL.protocol = 'ftp';
<add>console.log(myURL.href);
<add> // Prints ftp://example.org
<add>```
<add>
<add>Invalid URL protocol values assigned to the `protocol` property are ignored.
<add>
<add>#### url.search
<add>
<add>Gets and sets the serialized query portion of the URL.
<add>
<add>```js
<add>const myURL = new URL('https://example.org/abc?123');
<add>console.log(myURL.search);
<add> // Prints ?123
<add>
<add>myURL.search = 'abc=xyz';
<add>console.log(myURL.href);
<add> // Prints https://example.org/abc?abc=xyz
<add>```
<add>
<add>Any invalid URL characters appearing in the value assigned the `search`
<add>property will be [percent-encoded](#whatwg-percent-encoding). Note that the
<add>selection of which characters to percent-encode may vary somewhat from what the
<add>[`url.parse()`][] and [`url.format()`][] methods would produce.
<add>
<add>#### url.searchParams
<add>
<add>Gets a [`URLSearchParams`](#url_class_urlsearchparams) object representing the
<add>query parameters of the URL.
<add>
<add>#### url.username
<add>
<add>Gets and sets the username portion of the URL.
<add>
<add>```js
<add>const myURL = new URL('https://abc:xyz@example.com');
<add>console.log(myURL.username);
<add> // Prints abc
<add>
<add>myURL.username = '123';
<add>console.log(myURL.href);
<add> // Prints https://123:xyz@example.com
<add>```
<add>
<add>Any invalid URL characters appearing in the value assigned the `username`
<add>property will be [percent-encoded](#whatwg-percent-encoding). Note that the
<add>selection of which characters to percent-encode may vary somewhat from what the
<add>[`url.parse()`][] and [`url.format()`][] methods would produce.
<add>
<add>#### url.toString()
<add>
<add>The `toString()` method on the `URL` object returns the serialized URL. The
<add>value returned is equivalent to that of `url.href`.
<add>
<add>### Class: URLSearchParams
<add>
<add>The `URLSearchParams` object provides read and write access to the query of a
<add>`URL`.
<add>
<add>```js
<add>const URL = require('url').URL;
<add>const myURL = new URL('https://example.org/?abc=123');
<add>console.log(myURL.searchParams.get('abc'));
<add> // Prints 123
<add>
<add>myURL.searchParams.append('abc', 'xyz');
<add>console.log(myURL.href);
<add> // Prints https://example.org/?abc=123&abc=xyz
<add>
<add>myURL.searchParams.delete('abc');
<add>myURL.searchParams.set('a', 'b');
<add>console.log(myURL.href);
<add> // Prints https://example.org/?a=b
<add>```
<add>
<add>#### Constructor: new URLSearchParams([init])
<add>
<add>* `init` {String} The URL query
<add>
<add>#### urlSearchParams.append(name, value)
<add>
<add>* `name` {String}
<add>* `value` {String}
<add>
<add>Append a new name-value pair to the query string.
<add>
<add>#### urlSearchParams.delete(name)
<add>
<add>* `name` {String}
<add>
<add>Remove all name-value pairs whose name is `name`.
<add>
<add>#### urlSearchParams.entries()
<add>
<add>* Returns: {Iterator}
<add>
<add>Returns an ES6 Iterator over each of the name-value pairs in the query.
<add>Each item of the iterator is a JavaScript Array. The first item of the Array
<add>is the `name`, the second item of the Array is the `value`.
<add>
<add>Alias for `urlSearchParams\[\@\@iterator\]()`.
<add>
<add>#### urlSearchParams.forEach(fn)
<add>
<add>* `fn` {Function} Function invoked for each name-value pair in the query.
<add>
<add>Iterates over each name-value pair in the query and invokes the given function.
<add>
<add>```js
<add>const URL = require('url').URL;
<add>const myURL = new URL('https://example.org/?a=b&c=d');
<add>myURL.searchParams.forEach((value, name) => {
<add> console.log(name, value);
<add>});
<add>```
<add>
<add>#### urlSearchParams.get(name)
<add>
<add>* `name` {String}
<add>* Returns: {String} or `null` if there is no name-value pair with the given
<add> `name`.
<add>
<add>Returns the value of the first name-value pair whose name is `name`.
<add>
<add>#### urlSearchParams.getAll(name)
<add>
<add>* `name` {String}
<add>* Returns: {Array}
<add>
<add>Returns the values of all name-value pairs whose name is `name`.
<add>
<add>#### urlSearchParams.has(name)
<add>
<add>* `name` {String}
<add>* Returns: {Boolean}
<add>
<add>Returns `true` if there is at least one name-value pair whose name is `name`.
<add>
<add>#### urlSearchParams.keys()
<add>
<add>* Returns: {Iterator}
<add>
<add>Returns an ES6 Iterator over the names of each name-value pair.
<add>
<add>#### urlSearchParams.set(name, value)
<add>
<add>* `name` {String}
<add>* `value` {String}
<add>
<add>Remove any existing name-value pairs whose name is `name` and append a new
<add>name-value pair.
<add>
<add>#### urlSearchParams.toString()
<add>
<add>* Returns: {String}
<add>
<add>Returns the search parameters serialized as a URL-encoded string.
<add>
<add>#### urlSearchParams.values()
<add>
<add>* Returns: {Iterator}
<add>
<add>Returns an ES6 Iterator over the values of each name-value pair.
<add>
<add>#### urlSearchParams\[\@\@iterator\]()
<add>
<add>* Returns: {Iterator}
<add>
<add>Returns an ES6 Iterator over each of the name-value pairs in the query string.
<add>Each item of the iterator is a JavaScript Array. The first item of the Array
<add>is the `name`, the second item of the Array is the `value`.
<add>
<add>Alias for `urlSearchParams.entries()`.
<add>
<add>### require('url').domainToAscii(domain)
<add>
<add>* `domain` {String}
<add>* Returns: {String}
<add>
<add>Returns the [Punycode][] ASCII serialization of the `domain`.
<add>
<add>*Note*: The `require('url').domainToAscii()` method is introduced as part of
<add>the new `URL` implementation but is not part of the WHATWG URL standard.
<add>
<add>### require('url').domainToUnicode(domain)
<add>
<add>* `domain` {String}
<add>* Returns: {String}
<add>
<add>Returns the Unicode serialization of the `domain`.
<add>
<add>*Note*: The `require('url').domainToUnicode()` API is introduced as part of the
<add>the new `URL` implementation but is not part of the WHATWG URL standard.
<add>
<add><a id="whatwg-percent-encoding"></a>
<add>### Percent-Encoding in the WHATWG URL Standard
<add>
<add>URLs are permitted to only contain a certain range of characters. Any character
<add>falling outside of that range must be encoded. How such characters are encoded,
<add>and which characters to encode depends entirely on where the character is
<add>located within the structure of the URL. The WHATWG URL Standard uses a more
<add>selective and fine grained approach to selecting encoded characters than that
<add>used by the older [`url.parse()`][] and [`url.format()`][] methods.
<add>
<add>The WHATWG algorithm defines three "encoding sets" that describe ranges of
<add>characters that must be percent-encoded:
<add>
<add>* The *simple encode set* includes code points in range U+0000 to U+001F
<add> (inclusive) and all code points greater than U+007E.
<add>
<add>* The *default encode set* includes the *simple encode set* and code points
<add> U+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060, U+007B, and U+007D.
<add>
<add>* The *userinfo encode set* includes the *default encode set* and code points
<add> U+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D, U+005E, and
<add> U+007C.
<add>
<add>The *simple encode set* is used primary for URL fragments and certain specific
<add>conditions for the path. The *userinfo encode set* is used specifically for
<add>username and passwords encoded within the URL. The *default encode set* is used
<add>for all other cases.
<add>
<add>When non-ASCII characters appear within a hostname, the hostname is encoded
<add>using the [Punycode][] algorithm. Note, however, that a hostname *may* contain
<add>*both* Punycode encoded and percent-encoded characters. For example:
<add>
<add>```js
<add>const URL = require('url').URL;
<add>const myURL = new URL('https://%CF%80.com/foo');
<add>console.log(myURL.href);
<add> // Prints https://xn--1xa.com/foo
<add>console.log(myURL.origin);
<add> // Prints https://π.com
<add>```
<add>
<ide>
<ide> [`Error`]: errors.html#errors_class_error
<ide> [`querystring`]: querystring.html
<ide> [`TypeError`]: errors.html#errors_class_typeerror
<add>[WHATWG URL Standard]: https://url.spec.whatwg.org/
<add>[examples of parsed URLs]: https://url.spec.whatwg.org/#example-url-parsing
<add>[`url.parse()`]: #url_url_parse_urlstring_parsequerystring_slashesdenotehost
<add>[`url.format()`]: #url_url_format_urlobject
<add>[Punycode]: https://tools.ietf.org/html/rfc5891#section-4.4 | 1 |
PHP | PHP | update docblock for h() | 27537e55c32503957e67d0f5098ec8e44823a645 | <ide><path>src/Core/functions.php
<ide> /**
<ide> * Convenience method for htmlspecialchars.
<ide> *
<del> * @param string|array|object $text Text to wrap through htmlspecialchars. Also works with arrays, and objects.
<add> * @param mixed $text Text to wrap through htmlspecialchars. Also works with arrays, and objects.
<ide> * Arrays will be mapped and have all their elements escaped. Objects will be string cast if they
<ide> * implement a `__toString` method. Otherwise the class name will be used.
<add> * Other scalar types will be returned unchanged.
<ide> * @param bool|string $double Encode existing html entities. If string it will be used as character set.
<ide> * @param string|null $charset Character set to use when escaping. Defaults to config value in `mb_internal_encoding()`
<ide> * or 'UTF-8'.
<del> * @return string|array Wrapped text.
<add> * @return mixed Wrapped text.
<ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#h
<ide> */
<ide> function h($text, $double = true, $charset = null)
<ide><path>src/View/Helper/NumberHelper.php
<ide> public function format($number, array $options = [])
<ide> $formatted = $this->_engine->format($number, $options);
<ide> $options += ['escape' => true];
<ide>
<del> return $options['escape'] ? (string)h($formatted) : $formatted;
<add> return $options['escape'] ? h($formatted) : $formatted;
<ide> }
<ide>
<ide> /**
<ide> public function currency($number, $currency = null, array $options = [])
<ide> $formatted = $this->_engine->currency($number, $currency, $options);
<ide> $options += ['escape' => true];
<ide>
<del> return $options['escape'] ? (string)h($formatted) : $formatted;
<add> return $options['escape'] ? h($formatted) : $formatted;
<ide> }
<ide>
<ide> /**
<ide> public function formatDelta($value, array $options = [])
<ide> $formatted = $this->_engine->formatDelta($value, $options);
<ide> $options += ['escape' => true];
<ide>
<del> return $options['escape'] ? (string)h($formatted) : $formatted;
<add> return $options['escape'] ? h($formatted) : $formatted;
<ide> }
<ide>
<ide> /** | 2 |
Ruby | Ruby | assert the return value in the test | 8a0086609915bc666d08ff416717950da1b6b8da | <ide><path>activerecord/test/cases/associations/has_many_through_associations_test.rb
<ide> def test_has_many_through_obeys_order_on_through_association
<ide> end
<ide>
<ide> def test_has_many_through_with_includes_in_through_association_scope
<del> posts(:welcome).author_address_extra_with_address.to_a
<add> assert_not_empty posts(:welcome).author_address_extra_with_address
<ide> end
<ide> end | 1 |
Text | Text | add v4.4.0 to changelog | d723329ee9ee2dc278ead43f2302ef01b0aa8e9e | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>## v3.28.9 (April 19, 2022)
<del>
<del>- [#20028](https://github.com/emberjs/ember.js/pull/20028) Fix a memory leak in the Router Service class
<del>
<del>### v4.4.0-beta.1 (March 24, 2022)
<add>### v4.4.0 (May 2, 2022)
<ide>
<ide> - [#19882](https://github.com/emberjs/ember.js/pull/19882) / [#20005](https://github.com/emberjs/ember.js/pull/20005) [FEATURE] Implement the `unique-id` helper per [RFC #0659](https://github.com/emberjs/rfcs/blob/master/text/0659-unique-id-helper.md).
<ide> - [#19981](https://github.com/emberjs/ember.js/pull/19981) [FEATURE] Facilitate custom test setups per [RFC #0637](https://github.com/emberjs/rfcs/blob/master/text/0637-customizable-test-setups.md).
<ide> - [#16879](https://github.com/emberjs/ember.js/pull/16879) [BUGFIX] isEmpty on nested objects
<ide> - [#17978](https://github.com/emberjs/ember.js/pull/17978) Make hasListeners public
<ide> - [#20014](https://github.com/emberjs/ember.js/pull/20014) Log `until` for deprecations
<ide>
<add>### v3.28.9 (April 19, 2022)
<add>
<add>- [#20028](https://github.com/emberjs/ember.js/pull/20028) Fix a memory leak in the Router Service class
<add>
<ide> ### v4.3.0 (March 21, 2022)
<ide>
<ide> - [#20025](https://github.com/emberjs/ember.js/pull/20025) [BUGFIX] Fix a memory leak in the Router Service class | 1 |
Python | Python | map textfield max_length to charfield | a1dad503cfe637e9575168f74782eca654dbb041 | <ide><path>rest_framework/utils/field_mapping.py
<ide> def get_field_kwargs(field_name, model_field):
<ide> # Ensure that max_length is passed explicitly as a keyword arg,
<ide> # rather than as a validator.
<ide> max_length = getattr(model_field, 'max_length', None)
<del> if max_length is not None and isinstance(model_field, models.CharField):
<add> if max_length is not None and (isinstance(model_field, models.CharField) or
<add> isinstance(model_field, models.TextField)):
<ide> kwargs['max_length'] = max_length
<ide> validator_kwarg = [
<ide> validator for validator in validator_kwarg
<ide><path>tests/test_model_serializer.py
<ide> class RegularFieldsModel(models.Model):
<ide> positive_small_integer_field = models.PositiveSmallIntegerField()
<ide> slug_field = models.SlugField(max_length=100)
<ide> small_integer_field = models.SmallIntegerField()
<del> text_field = models.TextField()
<add> text_field = models.TextField(max_length=100)
<ide> time_field = models.TimeField()
<ide> url_field = models.URLField(max_length=100)
<ide> custom_field = CustomField()
<ide> class Meta:
<ide> positive_small_integer_field = IntegerField()
<ide> slug_field = SlugField(max_length=100)
<ide> small_integer_field = IntegerField()
<del> text_field = CharField(style={'base_template': 'textarea.html'})
<add> text_field = CharField(max_length=100, style={'base_template': 'textarea.html'})
<ide> time_field = TimeField()
<ide> url_field = URLField(max_length=100)
<ide> custom_field = ModelField(model_field=<tests.test_model_serializer.CustomField: custom_field>)
<ide> """)
<add>
<ide> self.assertEqual(unicode_repr(TestSerializer()), expected)
<ide>
<ide> def test_field_options(self): | 2 |
Javascript | Javascript | move component invocation test into ember-htmlbars | 0ee52696fce0407bd73d34dd51e5813c1b0085f5 | <add><path>packages/ember-htmlbars/tests/integration/component_invocation_test.js
<del><path>packages/ember-handlebars/tests/views/component_test.js
<ide> import Container from 'container/container';
<ide> import run from "ember-metal/run_loop";
<ide> import jQuery from "ember-views/system/jquery";
<ide> import EmberHandlebars from 'ember-handlebars-compiler';
<add>import htmlbarsCompile from "ember-htmlbars/system/compile";
<ide> import ComponentLookup from 'ember-views/component_lookup';
<ide>
<del>var compile = EmberHandlebars.compile;
<add>var compile;
<add>if (Ember.FEATURES.isEnabled('ember-htmlbars')) {
<add> compile = htmlbarsCompile;
<add>} else {
<add> compile = EmberHandlebars.compile;
<add>}
<add>
<ide> var container, view;
<ide>
<ide> QUnit.module('component - invocation', { | 1 |
Ruby | Ruby | extract heartbeat class to perform periodical ping | 786bbbb0ee1de0f2c8c9be517b8d5c93f95421d4 | <ide><path>lib/action_cable/connection.rb
<ide> module ActionCable
<ide> module Connection
<ide> autoload :Base, 'action_cable/connection/base'
<add> autoload :Heartbeat, 'action_cable/connection/heartbeat'
<ide> autoload :Identification, 'action_cable/connection/identification'
<ide> autoload :InternalChannel, 'action_cable/connection/internal_channel'
<ide> autoload :Subscriptions, 'action_cable/connection/subscriptions'
<ide><path>lib/action_cable/connection/base.rb
<ide> class Base
<ide> include Identification
<ide> include InternalChannel
<ide>
<del> PING_INTERVAL = 3
<del>
<ide> attr_reader :server, :env
<ide> delegate :worker_pool, :pubsub, to: :server
<ide>
<del> attr_reader :subscriptions
<del>
<ide> attr_reader :logger
<ide>
<ide> def initialize(server, env)
<ide> def initialize(server, env)
<ide>
<ide> @logger = TaggedLoggerProxy.new(server.logger, tags: log_tags)
<ide>
<add> @heartbeat = ActionCable::Connection::Heartbeat.new(self)
<ide> @subscriptions = ActionCable::Connection::Subscriptions.new(self)
<ide> end
<ide>
<ide> def process
<ide> @websocket = Faye::WebSocket.new(@env)
<ide>
<ide> @websocket.on(:open) do |event|
<del> transmit_ping_timestamp
<del> @ping_timer = EventMachine.add_periodic_timer(PING_INTERVAL) { transmit_ping_timestamp }
<add> heartbeat.start
<ide> worker_pool.async.invoke(self, :on_open)
<ide> end
<ide>
<ide> def process
<ide> @websocket.on(:close) do |event|
<ide> logger.info finished_request_message
<ide>
<add> heartbeat.stop
<ide> worker_pool.async.invoke(self, :on_close)
<del> EventMachine.cancel_timer(@ping_timer) if @ping_timer
<ide> end
<ide>
<ide> @websocket.rack_response
<ide> def cookies
<ide>
<ide>
<ide> private
<add> attr_reader :heartbeat, :subscriptions
<add>
<ide> def on_open
<ide> server.add_connection(self)
<ide>
<ide> def on_close
<ide> end
<ide>
<ide>
<del> def transmit_ping_timestamp
<del> transmit({ identifier: '_ping', message: Time.now.to_i }.to_json)
<del> end
<del>
<del>
<ide> def process_message(message)
<ide> subscriptions.find(message['identifier']).perform_action(ActiveSupport::JSON.decode(message['data']))
<ide> rescue Exception => e
<ide><path>lib/action_cable/connection/heartbeat.rb
<add>module ActionCable
<add> module Connection
<add> class Heartbeat
<add> BEAT_INTERVAL = 3
<add>
<add> def initialize(connection)
<add> @connection = connection
<add> end
<add>
<add> def start
<add> beat
<add> @timer = EventMachine.add_periodic_timer(BEAT_INTERVAL) { beat }
<add> end
<add>
<add> def stop
<add> EventMachine.cancel_timer(@timer) if @timer
<add> end
<add>
<add> private
<add> attr_reader :connection
<add>
<add> def beat
<add> connection.transmit({ identifier: '_ping', message: Time.now.to_i }.to_json)
<add> end
<add> end
<add> end
<add>end
<ide>\ No newline at end of file | 3 |
Go | Go | remove the options of cmdattach | 9442d6b349295818d9a0ddecc10ca19019ead935 | <ide><path>commands.go
<ide> func (srv *Server) CmdLogs(stdin io.ReadCloser, stdout io.Writer, args ...string
<ide> }
<ide>
<ide> func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
<del> cmd := rcli.Subcmd(stdout, "attach", "[OPTIONS]", "Attach to a running container")
<del> flStdin := cmd.Bool("i", false, "Attach to stdin")
<del> flStdout := cmd.Bool("o", true, "Attach to stdout")
<del> flStderr := cmd.Bool("e", true, "Attach to stderr")
<add> cmd := rcli.Subcmd(stdout, "attach", "CONTAINER", "Attach to a running container")
<ide> if err := cmd.Parse(args); err != nil {
<ide> return nil
<ide> }
<ide> func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout io.Writer, args ...stri
<ide> return errors.New("No such container: " + name)
<ide> }
<ide> var wg sync.WaitGroup
<del> if *flStdin {
<add> if container.Config.OpenStdin {
<ide> cStdin, err := container.StdinPipe()
<ide> if err != nil {
<ide> return err
<ide> }
<ide> wg.Add(1)
<ide> go func() { io.Copy(cStdin, stdin); wg.Add(-1) }()
<ide> }
<del> if *flStdout {
<del> cStdout, err := container.StdoutPipe()
<del> if err != nil {
<del> return err
<del> }
<del> wg.Add(1)
<del> go func() { io.Copy(stdout, cStdout); wg.Add(-1) }()
<add> cStdout, err := container.StdoutPipe()
<add> if err != nil {
<add> return err
<ide> }
<del> if *flStderr {
<del> cStderr, err := container.StderrPipe()
<del> if err != nil {
<del> return err
<del> }
<del> wg.Add(1)
<del> go func() { io.Copy(stdout, cStderr); wg.Add(-1) }()
<add> wg.Add(1)
<add> go func() { io.Copy(stdout, cStdout); wg.Add(-1) }()
<add> cStderr, err := container.StderrPipe()
<add> if err != nil {
<add> return err
<ide> }
<add> wg.Add(1)
<add> go func() { io.Copy(stdout, cStderr); wg.Add(-1) }()
<ide> wg.Wait()
<ide> return nil
<ide> } | 1 |
Python | Python | bugfix iscoroutinefunction with python3.7 | 6d5ccdefe29292974d0bb8e1d80dcd1a06f28368 | <ide><path>src/flask/app.py
<add>import functools
<add>import inspect
<ide> import os
<ide> import sys
<ide> import weakref
<ide> from datetime import timedelta
<del>from inspect import iscoroutinefunction
<ide> from itertools import chain
<ide> from threading import Lock
<ide>
<ide> from .wrappers import Response
<ide>
<ide>
<add>if sys.version_info >= (3, 8):
<add> iscoroutinefunction = inspect.iscoroutinefunction
<add>else:
<add>
<add> def iscoroutinefunction(func):
<add> while inspect.ismethod(func):
<add> func = func.__func__
<add>
<add> while isinstance(func, functools.partial):
<add> func = func.func
<add>
<add> return inspect.iscoroutinefunction(func)
<add>
<add>
<ide> def _make_timedelta(value):
<ide> if value is None or isinstance(value, timedelta):
<ide> return value | 1 |
Ruby | Ruby | use odie instead of bare exception | d8c2e311ab03eb43dee91240aaea9eb09faa3b14 | <ide><path>Library/Homebrew/extend/os/linux/parser.rb
<ide> def validate_options
<ide> return unless @args.respond_to?(:cask?)
<ide> return unless @args.cask?
<ide>
<del> # NOTE: We don't raise a UsageError here because
<del> # we don't want to print the help page.
<del> raise "Invalid usage: Casks are not supported on Linux"
<add> # NOTE: We don't raise an error here because we don't want
<add> # to print the help page or a stack trace.
<add> odie "Invalid `--cask` usage: Casks do not work on Linux"
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/cli/parser_spec.rb
<ide>
<ide> it "throws an error when defined" do
<ide> expect { parser.parse(["--cask"]) }
<del> .to raise_error RuntimeError, "Invalid usage: Casks are not supported on Linux"
<add> .to output("Error: Invalid `--cask` usage: Casks do not work on Linux\n").to_stderr
<add> .and not_to_output.to_stdout
<add> .and raise_exception SystemExit
<ide> end
<ide> end
<ide>
<ide>
<ide> it "throws an error when --cask defined" do
<ide> expect { parser.parse(["--cask"]) }
<del> .to raise_error RuntimeError, "Invalid usage: Casks are not supported on Linux"
<add> .to output("Error: Invalid `--cask` usage: Casks do not work on Linux\n").to_stderr
<add> .and not_to_output.to_stdout
<add> .and raise_exception SystemExit
<ide> end
<ide>
<ide> it "throws an error when both defined" do
<ide> expect { parser.parse(["--cask", "--formula"]) }
<del> .to raise_error RuntimeError, "Invalid usage: Casks are not supported on Linux"
<add> .to output("Error: Invalid `--cask` usage: Casks do not work on Linux\n").to_stderr
<add> .and not_to_output.to_stdout
<add> .and raise_exception SystemExit
<ide> end
<ide> end
<ide> end | 2 |
PHP | PHP | adjust test since we do not spam our users anymore | c500f07b26be17c849f3c59a333dc60b72045fc6 | <ide><path>tests/TestCase/Console/CommandRunnerTest.php
<ide> public function testRunValidCommand()
<ide>
<ide> $contents = implode("\n", $output->messages());
<ide> $this->assertContains('URI template', $contents);
<del> $this->assertContains('Welcome to CakePHP', $contents);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Console/ShellTest.php
<ide> public function testRunCommandInvokeTask()
<ide> $task->expects($this->never())
<ide> ->method('_welcome');
<ide>
<del> // One welcome message output.
<del> $io->expects($this->at(2))
<del> ->method('out')
<del> ->with($this->stringContains('Welcome to CakePHP'));
<del>
<ide> $shell->Slice = $task;
<ide> $shell->runCommand(['slice', 'one']);
<ide> $this->assertTrue($task->params['requested'], 'Task is requested, no welcome.');
<ide><path>tests/TestCase/TestSuite/ConsoleIntegrationTestCaseTest.php
<ide> public function testExecWithCommandRunner()
<ide>
<ide> $this->exec('routes');
<ide>
<del> $this->assertOutputContains('Welcome to CakePHP');
<ide> $this->assertExitCode(Shell::CODE_SUCCESS);
<ide> }
<ide>
<ide> public function testExecCoreCommand()
<ide> {
<ide> $this->exec('routes');
<ide>
<del> $this->assertOutputContains('Welcome to CakePHP');
<ide> $this->assertExitCode(Shell::CODE_SUCCESS);
<ide> }
<ide> | 3 |
Javascript | Javascript | update preview on keystroke | 159b2029400dfdb25ac9f8a2e5c838d3e736d155 | <ide><path>client/commonFramework/end.js
<ide> $(document).ready(function() {
<ide> init($);
<ide> });
<ide>
<del> common.editorKeyUp$
<add> const code$ = common.editorKeyUp$
<ide> .debounce(750)
<ide> .map(() => common.editor.getValue())
<ide> .distinctUntilChanged()
<ide> .doOnNext(() => console.log('updating value'))
<del> .subscribe(
<add> .shareReplay();
<add>
<add> // update storage
<add> code$.subscribe(
<ide> code => {
<ide> common.codeStorage.updateStorage(common.challengeName, code);
<ide> common.codeUri.querify(code);
<ide> },
<ide> err => console.error(err)
<ide> );
<ide>
<add> code$
<add> .flatMap(code => {
<add> if (common.hasJs(code)) {
<add> return common.detectLoops$(code)
<add> .flatMap(
<add> ({ err }) => err ? Observable.throw(err) : Observable.just(code)
<add> );
<add> }
<add> return Observable.just(code);
<add> })
<add> .flatMap(code => common.updatePreview$(code))
<add> .catch(err => Observable.just({ err }))
<add> .subscribe(
<add> ({ err }) => {
<add> if (err) {
<add> return console.error(err);
<add> }
<add> console.log('updating preview');
<add> },
<add> err => console.error(err)
<add> );
<add>
<ide> common.resetBtn$
<ide> .doOnNext(() => {
<ide> common.editor.setValue(common.replaceSafeTags(common.seed));
<ide><path>client/commonFramework/execute-challenge-stream.js
<ide> window.common = (function(global) {
<ide> });
<ide> }
<ide>
<del> if (common.challengeType === '0') {
<del> let openingComments = code.match(/\<\!\-\-/gi);
<del> let closingComments = code.match(/\-\-\>/gi) || [];
<del> if (
<del> openingComments &&
<del> openingComments.length > closingComments.length
<del> ) {
<del> return Observable.throw({
<del> err: 'SyntaxError: Unfinished HTML comment',
<del> code
<del> });
<del> }
<del> }
<del>
<ide> if (code.match(detectUnsafeConsoleCall)) {
<ide> return Observable.throw({
<ide> err: 'Invalid if (null) console.log(1); detected',
<ide><path>client/commonFramework/update-preview.js
<ide> window.common = (function(global) {
<ide> .map(script => `<script>${script}</script>`)
<ide> .flatMap(script => {
<ide> preview.open();
<del> preview.write(libraryIncludes + code + script);
<add> preview.write(libraryIncludes + code + '<!-- -->' + script);
<ide> preview.close();
<ide> return Observable.fromCallback($(preview).ready, $(preview))()
<ide> .first() | 3 |
Ruby | Ruby | add more tap regexes | 202c6ef8262ca95bc5362bb431377c14847a3679 | <ide><path>Library/Homebrew/cmd/info.rb
<ide> def github_fork
<ide> def github_info f
<ide> path = f.path.realpath
<ide>
<del> if path.to_s =~ %r{#{HOMEBREW_REPOSITORY}/Library/Taps/(\w+)-(\w+)/(.*)}
<add> if path.to_s =~ HOMEBREW_TAP_PATH_REGEX
<ide> user = $1
<ide> repo = "homebrew-#$2"
<ide> path = $3
<ide><path>Library/Homebrew/cmd/versions.rb
<ide> def pretty_relative_path
<ide> private
<ide> def repository
<ide> @repository ||= begin
<del> if path.realpath.to_s =~ %r{#{HOMEBREW_REPOSITORY}/Library/Taps/(\w+)-(\w+)}
<add> if path.realpath.to_s =~ HOMEBREW_TAP_DIR_REGEX
<ide> HOMEBREW_REPOSITORY/"Library/Taps/#$1-#$2"
<ide> else
<ide> HOMEBREW_REPOSITORY
<ide><path>Library/Homebrew/formula.rb
<ide> def self.factory name
<ide> end
<ide>
<ide> def tap
<del> if path.realpath.to_s =~ %r{#{HOMEBREW_REPOSITORY}/Library/Taps/(\w+)-(\w+)}
<add> if path.realpath.to_s =~ HOMEBREW_TAP_DIR_REGEX
<ide> "#$1/#$2"
<ide> elsif core_formula?
<ide> "mxcl/master"
<ide><path>Library/Homebrew/global.rb
<ide> def mkpath
<ide> HOMEBREW_CURL_ARGS = '-f#LA'
<ide>
<ide> HOMEBREW_TAP_FORMULA_REGEX = %r{^(\w+)/(\w+)/([^/]+)$}
<add>HOMEBREW_TAP_DIR_REGEX = %r{#{HOMEBREW_REPOSITORY}/Library/Taps/(\w+)-(\w+)}
<add>HOMEBREW_TAP_PATH_REGEX = Regexp.new(HOMEBREW_TAP_DIR_REGEX.source \
<add> + %r{/(.*)}.source)
<ide>
<ide> module Homebrew extend self
<ide> include FileUtils | 4 |
Javascript | Javascript | unify promise switch statements | fa77f52e74d816f3d7ad0e71850932508c1b353e | <ide><path>packages/react-reconciler/src/ReactFiberHooks.new.js
<ide> import {now} from './Scheduler';
<ide> import {
<ide> prepareThenableState,
<ide> trackUsedThenable,
<del> getPreviouslyUsedThenableAtIndex,
<ide> } from './ReactFiberThenable.new';
<ide>
<ide> const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals;
<ide> if (enableUseMemoCacheHook) {
<ide> };
<ide> }
<ide>
<del>function noop(): void {}
<del>
<ide> function use<T>(usable: Usable<T>): T {
<ide> if (usable !== null && typeof usable === 'object') {
<ide> // $FlowFixMe[method-unbinding]
<ide> function use<T>(usable: Usable<T>): T {
<ide> // Track the position of the thenable within this fiber.
<ide> const index = thenableIndexCounter;
<ide> thenableIndexCounter += 1;
<del>
<del> // TODO: Unify this switch statement with the one in trackUsedThenable.
<del> switch (thenable.status) {
<del> case 'fulfilled': {
<del> const fulfilledValue: T = thenable.value;
<del> return fulfilledValue;
<del> }
<del> case 'rejected': {
<del> const rejectedError = thenable.reason;
<del> throw rejectedError;
<del> }
<del> default: {
<del> const prevThenableAtIndex: Thenable<T> | null = getPreviouslyUsedThenableAtIndex(
<del> index,
<del> );
<del> if (prevThenableAtIndex !== null) {
<del> if (thenable !== prevThenableAtIndex) {
<del> // Avoid an unhandled rejection errors for the Promises that we'll
<del> // intentionally ignore.
<del> thenable.then(noop, noop);
<del> }
<del> switch (prevThenableAtIndex.status) {
<del> case 'fulfilled': {
<del> const fulfilledValue: T = prevThenableAtIndex.value;
<del> return fulfilledValue;
<del> }
<del> case 'rejected': {
<del> const rejectedError: mixed = prevThenableAtIndex.reason;
<del> throw rejectedError;
<del> }
<del> default: {
<del> // The thenable still hasn't resolved. Suspend with the same
<del> // thenable as last time to avoid redundant listeners.
<del> throw prevThenableAtIndex;
<del> }
<del> }
<del> } else {
<del> // This is the first time something has been used at this index.
<del> // Stash the thenable at the current index so we can reuse it during
<del> // the next attempt.
<del> trackUsedThenable(thenable, index);
<del>
<del> // Suspend.
<del> // TODO: Throwing here is an implementation detail that allows us to
<del> // unwind the call stack. But we shouldn't allow it to leak into
<del> // userspace. Throw an opaque placeholder value instead of the
<del> // actual thenable. If it doesn't get captured by the work loop, log
<del> // a warning, because that means something in userspace must have
<del> // caught it.
<del> throw thenable;
<del> }
<del> }
<del> }
<add> return trackUsedThenable(thenable, index);
<ide> } else if (
<ide> usable.$$typeof === REACT_CONTEXT_TYPE ||
<ide> usable.$$typeof === REACT_SERVER_CONTEXT_TYPE
<ide><path>packages/react-reconciler/src/ReactFiberHooks.old.js
<ide> import {now} from './Scheduler';
<ide> import {
<ide> prepareThenableState,
<ide> trackUsedThenable,
<del> getPreviouslyUsedThenableAtIndex,
<ide> } from './ReactFiberThenable.old';
<ide>
<ide> const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals;
<ide> if (enableUseMemoCacheHook) {
<ide> };
<ide> }
<ide>
<del>function noop(): void {}
<del>
<ide> function use<T>(usable: Usable<T>): T {
<ide> if (usable !== null && typeof usable === 'object') {
<ide> // $FlowFixMe[method-unbinding]
<ide> function use<T>(usable: Usable<T>): T {
<ide> // Track the position of the thenable within this fiber.
<ide> const index = thenableIndexCounter;
<ide> thenableIndexCounter += 1;
<del>
<del> // TODO: Unify this switch statement with the one in trackUsedThenable.
<del> switch (thenable.status) {
<del> case 'fulfilled': {
<del> const fulfilledValue: T = thenable.value;
<del> return fulfilledValue;
<del> }
<del> case 'rejected': {
<del> const rejectedError = thenable.reason;
<del> throw rejectedError;
<del> }
<del> default: {
<del> const prevThenableAtIndex: Thenable<T> | null = getPreviouslyUsedThenableAtIndex(
<del> index,
<del> );
<del> if (prevThenableAtIndex !== null) {
<del> if (thenable !== prevThenableAtIndex) {
<del> // Avoid an unhandled rejection errors for the Promises that we'll
<del> // intentionally ignore.
<del> thenable.then(noop, noop);
<del> }
<del> switch (prevThenableAtIndex.status) {
<del> case 'fulfilled': {
<del> const fulfilledValue: T = prevThenableAtIndex.value;
<del> return fulfilledValue;
<del> }
<del> case 'rejected': {
<del> const rejectedError: mixed = prevThenableAtIndex.reason;
<del> throw rejectedError;
<del> }
<del> default: {
<del> // The thenable still hasn't resolved. Suspend with the same
<del> // thenable as last time to avoid redundant listeners.
<del> throw prevThenableAtIndex;
<del> }
<del> }
<del> } else {
<del> // This is the first time something has been used at this index.
<del> // Stash the thenable at the current index so we can reuse it during
<del> // the next attempt.
<del> trackUsedThenable(thenable, index);
<del>
<del> // Suspend.
<del> // TODO: Throwing here is an implementation detail that allows us to
<del> // unwind the call stack. But we shouldn't allow it to leak into
<del> // userspace. Throw an opaque placeholder value instead of the
<del> // actual thenable. If it doesn't get captured by the work loop, log
<del> // a warning, because that means something in userspace must have
<del> // caught it.
<del> throw thenable;
<del> }
<del> }
<del> }
<add> return trackUsedThenable(thenable, index);
<ide> } else if (
<ide> usable.$$typeof === REACT_CONTEXT_TYPE ||
<ide> usable.$$typeof === REACT_SERVER_CONTEXT_TYPE
<ide><path>packages/react-reconciler/src/ReactFiberThenable.new.js
<ide> import type {
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> const {ReactCurrentActQueue} = ReactSharedInternals;
<ide>
<del>// TODO: Sparse arrays are bad for performance.
<del>export opaque type ThenableState = Array<Thenable<any> | void>;
<add>export opaque type ThenableState = Array<Thenable<any>>;
<ide>
<ide> let thenableState: ThenableState | null = null;
<ide>
<ide> export function isThenableStateResolved(thenables: ThenableState): boolean {
<ide> return true;
<ide> }
<ide>
<del>export function trackUsedThenable<T>(thenable: Thenable<T>, index: number) {
<add>function noop(): void {}
<add>
<add>export function trackUsedThenable<T>(thenable: Thenable<T>, index: number): T {
<ide> if (__DEV__ && ReactCurrentActQueue.current !== null) {
<ide> ReactCurrentActQueue.didUsePromise = true;
<ide> }
<ide>
<ide> if (thenableState === null) {
<ide> thenableState = [thenable];
<ide> } else {
<del> thenableState[index] = thenable;
<add> const previous = thenableState[index];
<add> if (previous === undefined) {
<add> thenableState.push(thenable);
<add> } else {
<add> if (previous !== thenable) {
<add> // Reuse the previous thenable, and drop the new one. We can assume
<add> // they represent the same value, because components are idempotent.
<add>
<add> // Avoid an unhandled rejection errors for the Promises that we'll
<add> // intentionally ignore.
<add> thenable.then(noop, noop);
<add> thenable = previous;
<add> }
<add> }
<ide> }
<ide>
<ide> // We use an expando to track the status and result of a thenable so that we
<ide> export function trackUsedThenable<T>(thenable: Thenable<T>, index: number) {
<ide> // If the thenable doesn't have a status, set it to "pending" and attach
<ide> // a listener that will update its status and result when it resolves.
<ide> switch (thenable.status) {
<del> case 'fulfilled':
<del> case 'rejected':
<del> // A thenable that already resolved shouldn't have been thrown, so this is
<del> // unexpected. Suggests a mistake in a userspace data library. Don't track
<del> // this thenable, because if we keep trying it will likely infinite loop
<del> // without ever resolving.
<del> // TODO: Log a warning?
<del> break;
<add> case 'fulfilled': {
<add> const fulfilledValue: T = thenable.value;
<add> return fulfilledValue;
<add> }
<add> case 'rejected': {
<add> const rejectedError = thenable.reason;
<add> throw rejectedError;
<add> }
<ide> default: {
<ide> if (typeof thenable.status === 'string') {
<ide> // Only instrument the thenable if the status if not defined. If
<ide> // it's defined, but an unknown value, assume it's been instrumented by
<ide> // some custom userspace implementation. We treat it as "pending".
<del> break;
<add> } else {
<add> const pendingThenable: PendingThenable<mixed> = (thenable: any);
<add> pendingThenable.status = 'pending';
<add> pendingThenable.then(
<add> fulfilledValue => {
<add> if (thenable.status === 'pending') {
<add> const fulfilledThenable: FulfilledThenable<mixed> = (thenable: any);
<add> fulfilledThenable.status = 'fulfilled';
<add> fulfilledThenable.value = fulfilledValue;
<add> }
<add> },
<add> (error: mixed) => {
<add> if (thenable.status === 'pending') {
<add> const rejectedThenable: RejectedThenable<mixed> = (thenable: any);
<add> rejectedThenable.status = 'rejected';
<add> rejectedThenable.reason = error;
<add> }
<add> },
<add> );
<ide> }
<del> const pendingThenable: PendingThenable<mixed> = (thenable: any);
<del> pendingThenable.status = 'pending';
<del> pendingThenable.then(
<del> fulfilledValue => {
<del> if (thenable.status === 'pending') {
<del> const fulfilledThenable: FulfilledThenable<mixed> = (thenable: any);
<del> fulfilledThenable.status = 'fulfilled';
<del> fulfilledThenable.value = fulfilledValue;
<del> }
<del> },
<del> (error: mixed) => {
<del> if (thenable.status === 'pending') {
<del> const rejectedThenable: RejectedThenable<mixed> = (thenable: any);
<del> rejectedThenable.status = 'rejected';
<del> rejectedThenable.reason = error;
<del> }
<del> },
<del> );
<del> break;
<del> }
<del> }
<del>}
<ide>
<del>export function getPreviouslyUsedThenableAtIndex<T>(
<del> index: number,
<del>): Thenable<T> | null {
<del> if (thenableState !== null) {
<del> const thenable = thenableState[index];
<del> if (thenable !== undefined) {
<del> return thenable;
<add> // Suspend.
<add> // TODO: Throwing here is an implementation detail that allows us to
<add> // unwind the call stack. But we shouldn't allow it to leak into
<add> // userspace. Throw an opaque placeholder value instead of the
<add> // actual thenable. If it doesn't get captured by the work loop, log
<add> // a warning, because that means something in userspace must have
<add> // caught it.
<add> throw thenable;
<ide> }
<ide> }
<del> return null;
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberThenable.old.js
<ide> import type {
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> const {ReactCurrentActQueue} = ReactSharedInternals;
<ide>
<del>// TODO: Sparse arrays are bad for performance.
<del>export opaque type ThenableState = Array<Thenable<any> | void>;
<add>export opaque type ThenableState = Array<Thenable<any>>;
<ide>
<ide> let thenableState: ThenableState | null = null;
<ide>
<ide> export function isThenableStateResolved(thenables: ThenableState): boolean {
<ide> return true;
<ide> }
<ide>
<del>export function trackUsedThenable<T>(thenable: Thenable<T>, index: number) {
<add>function noop(): void {}
<add>
<add>export function trackUsedThenable<T>(thenable: Thenable<T>, index: number): T {
<ide> if (__DEV__ && ReactCurrentActQueue.current !== null) {
<ide> ReactCurrentActQueue.didUsePromise = true;
<ide> }
<ide>
<ide> if (thenableState === null) {
<ide> thenableState = [thenable];
<ide> } else {
<del> thenableState[index] = thenable;
<add> const previous = thenableState[index];
<add> if (previous === undefined) {
<add> thenableState.push(thenable);
<add> } else {
<add> if (previous !== thenable) {
<add> // Reuse the previous thenable, and drop the new one. We can assume
<add> // they represent the same value, because components are idempotent.
<add>
<add> // Avoid an unhandled rejection errors for the Promises that we'll
<add> // intentionally ignore.
<add> thenable.then(noop, noop);
<add> thenable = previous;
<add> }
<add> }
<ide> }
<ide>
<ide> // We use an expando to track the status and result of a thenable so that we
<ide> export function trackUsedThenable<T>(thenable: Thenable<T>, index: number) {
<ide> // If the thenable doesn't have a status, set it to "pending" and attach
<ide> // a listener that will update its status and result when it resolves.
<ide> switch (thenable.status) {
<del> case 'fulfilled':
<del> case 'rejected':
<del> // A thenable that already resolved shouldn't have been thrown, so this is
<del> // unexpected. Suggests a mistake in a userspace data library. Don't track
<del> // this thenable, because if we keep trying it will likely infinite loop
<del> // without ever resolving.
<del> // TODO: Log a warning?
<del> break;
<add> case 'fulfilled': {
<add> const fulfilledValue: T = thenable.value;
<add> return fulfilledValue;
<add> }
<add> case 'rejected': {
<add> const rejectedError = thenable.reason;
<add> throw rejectedError;
<add> }
<ide> default: {
<ide> if (typeof thenable.status === 'string') {
<ide> // Only instrument the thenable if the status if not defined. If
<ide> // it's defined, but an unknown value, assume it's been instrumented by
<ide> // some custom userspace implementation. We treat it as "pending".
<del> break;
<add> } else {
<add> const pendingThenable: PendingThenable<mixed> = (thenable: any);
<add> pendingThenable.status = 'pending';
<add> pendingThenable.then(
<add> fulfilledValue => {
<add> if (thenable.status === 'pending') {
<add> const fulfilledThenable: FulfilledThenable<mixed> = (thenable: any);
<add> fulfilledThenable.status = 'fulfilled';
<add> fulfilledThenable.value = fulfilledValue;
<add> }
<add> },
<add> (error: mixed) => {
<add> if (thenable.status === 'pending') {
<add> const rejectedThenable: RejectedThenable<mixed> = (thenable: any);
<add> rejectedThenable.status = 'rejected';
<add> rejectedThenable.reason = error;
<add> }
<add> },
<add> );
<ide> }
<del> const pendingThenable: PendingThenable<mixed> = (thenable: any);
<del> pendingThenable.status = 'pending';
<del> pendingThenable.then(
<del> fulfilledValue => {
<del> if (thenable.status === 'pending') {
<del> const fulfilledThenable: FulfilledThenable<mixed> = (thenable: any);
<del> fulfilledThenable.status = 'fulfilled';
<del> fulfilledThenable.value = fulfilledValue;
<del> }
<del> },
<del> (error: mixed) => {
<del> if (thenable.status === 'pending') {
<del> const rejectedThenable: RejectedThenable<mixed> = (thenable: any);
<del> rejectedThenable.status = 'rejected';
<del> rejectedThenable.reason = error;
<del> }
<del> },
<del> );
<del> break;
<del> }
<del> }
<del>}
<ide>
<del>export function getPreviouslyUsedThenableAtIndex<T>(
<del> index: number,
<del>): Thenable<T> | null {
<del> if (thenableState !== null) {
<del> const thenable = thenableState[index];
<del> if (thenable !== undefined) {
<del> return thenable;
<add> // Suspend.
<add> // TODO: Throwing here is an implementation detail that allows us to
<add> // unwind the call stack. But we shouldn't allow it to leak into
<add> // userspace. Throw an opaque placeholder value instead of the
<add> // actual thenable. If it doesn't get captured by the work loop, log
<add> // a warning, because that means something in userspace must have
<add> // caught it.
<add> throw thenable;
<ide> }
<ide> }
<del> return null;
<ide> }
<ide><path>packages/react-server/src/ReactFizzHooks.js
<ide> import type {ThenableState} from './ReactFizzThenable';
<ide>
<ide> import {readContext as readContextImpl} from './ReactFizzNewContext';
<ide> import {getTreeId} from './ReactFizzTreeContext';
<del>import {
<del> getPreviouslyUsedThenableAtIndex,
<del> createThenableState,
<del> trackUsedThenable,
<del>} from './ReactFizzThenable';
<add>import {createThenableState, trackUsedThenable} from './ReactFizzThenable';
<ide>
<ide> import {makeId} from './ReactServerFormatConfig';
<ide>
<ide> function use<T>(usable: Usable<T>): T {
<ide> const index = thenableIndexCounter;
<ide> thenableIndexCounter += 1;
<ide>
<del> // TODO: Unify this switch statement with the one in trackUsedThenable.
<del> switch (thenable.status) {
<del> case 'fulfilled': {
<del> const fulfilledValue: T = thenable.value;
<del> return fulfilledValue;
<del> }
<del> case 'rejected': {
<del> const rejectedError = thenable.reason;
<del> throw rejectedError;
<del> }
<del> default: {
<del> const prevThenableAtIndex: Thenable<T> | null = getPreviouslyUsedThenableAtIndex(
<del> thenableState,
<del> index,
<del> );
<del> if (prevThenableAtIndex !== null) {
<del> if (thenable !== prevThenableAtIndex) {
<del> // Avoid an unhandled rejection errors for the Promises that we'll
<del> // intentionally ignore.
<del> thenable.then(noop, noop);
<del> }
<del> switch (prevThenableAtIndex.status) {
<del> case 'fulfilled': {
<del> const fulfilledValue: T = prevThenableAtIndex.value;
<del> return fulfilledValue;
<del> }
<del> case 'rejected': {
<del> const rejectedError: mixed = prevThenableAtIndex.reason;
<del> throw rejectedError;
<del> }
<del> default: {
<del> // The thenable still hasn't resolved. Suspend with the same
<del> // thenable as last time to avoid redundant listeners.
<del> throw prevThenableAtIndex;
<del> }
<del> }
<del> } else {
<del> // This is the first time something has been used at this index.
<del> // Stash the thenable at the current index so we can reuse it during
<del> // the next attempt.
<del> if (thenableState === null) {
<del> thenableState = createThenableState();
<del> }
<del> trackUsedThenable(thenableState, thenable, index);
<del>
<del> // Suspend.
<del> // TODO: Throwing here is an implementation detail that allows us to
<del> // unwind the call stack. But we shouldn't allow it to leak into
<del> // userspace. Throw an opaque placeholder value instead of the
<del> // actual thenable. If it doesn't get captured by the work loop, log
<del> // a warning, because that means something in userspace must have
<del> // caught it.
<del> throw thenable;
<del> }
<del> }
<add> if (thenableState === null) {
<add> thenableState = createThenableState();
<ide> }
<add> return trackUsedThenable(thenableState, thenable, index);
<ide> } else if (
<ide> usable.$$typeof === REACT_CONTEXT_TYPE ||
<ide> usable.$$typeof === REACT_SERVER_CONTEXT_TYPE
<ide><path>packages/react-server/src/ReactFizzThenable.js
<ide> import type {
<ide> RejectedThenable,
<ide> } from 'shared/ReactTypes';
<ide>
<del>// TODO: Sparse arrays are bad for performance.
<del>export opaque type ThenableState = Array<Thenable<any> | void>;
<add>export opaque type ThenableState = Array<Thenable<any>>;
<ide>
<ide> export function createThenableState(): ThenableState {
<ide> // The ThenableState is created the first time a component suspends. If it
<ide> // suspends again, we'll reuse the same state.
<ide> return [];
<ide> }
<ide>
<add>function noop(): void {}
<add>
<ide> export function trackUsedThenable<T>(
<ide> thenableState: ThenableState,
<ide> thenable: Thenable<T>,
<ide> index: number,
<del>) {
<del> thenableState[index] = thenable;
<add>): T {
<add> const previous = thenableState[index];
<add> if (previous === undefined) {
<add> thenableState.push(thenable);
<add> } else {
<add> if (previous !== thenable) {
<add> // Reuse the previous thenable, and drop the new one. We can assume
<add> // they represent the same value, because components are idempotent.
<add>
<add> // Avoid an unhandled rejection errors for the Promises that we'll
<add> // intentionally ignore.
<add> thenable.then(noop, noop);
<add> thenable = previous;
<add> }
<add> }
<ide>
<ide> // We use an expando to track the status and result of a thenable so that we
<ide> // can synchronously unwrap the value. Think of this as an extension of the
<ide> export function trackUsedThenable<T>(
<ide> // If the thenable doesn't have a status, set it to "pending" and attach
<ide> // a listener that will update its status and result when it resolves.
<ide> switch (thenable.status) {
<del> case 'fulfilled':
<del> case 'rejected':
<del> // A thenable that already resolved shouldn't have been thrown, so this is
<del> // unexpected. Suggests a mistake in a userspace data library. Don't track
<del> // this thenable, because if we keep trying it will likely infinite loop
<del> // without ever resolving.
<del> // TODO: Log a warning?
<del> break;
<add> case 'fulfilled': {
<add> const fulfilledValue: T = thenable.value;
<add> return fulfilledValue;
<add> }
<add> case 'rejected': {
<add> const rejectedError = thenable.reason;
<add> throw rejectedError;
<add> }
<ide> default: {
<ide> if (typeof thenable.status === 'string') {
<ide> // Only instrument the thenable if the status if not defined. If
<ide> // it's defined, but an unknown value, assume it's been instrumented by
<ide> // some custom userspace implementation. We treat it as "pending".
<del> break;
<add> } else {
<add> const pendingThenable: PendingThenable<mixed> = (thenable: any);
<add> pendingThenable.status = 'pending';
<add> pendingThenable.then(
<add> fulfilledValue => {
<add> if (thenable.status === 'pending') {
<add> const fulfilledThenable: FulfilledThenable<mixed> = (thenable: any);
<add> fulfilledThenable.status = 'fulfilled';
<add> fulfilledThenable.value = fulfilledValue;
<add> }
<add> },
<add> (error: mixed) => {
<add> if (thenable.status === 'pending') {
<add> const rejectedThenable: RejectedThenable<mixed> = (thenable: any);
<add> rejectedThenable.status = 'rejected';
<add> rejectedThenable.reason = error;
<add> }
<add> },
<add> );
<ide> }
<del> const pendingThenable: PendingThenable<mixed> = (thenable: any);
<del> pendingThenable.status = 'pending';
<del> pendingThenable.then(
<del> fulfilledValue => {
<del> if (thenable.status === 'pending') {
<del> const fulfilledThenable: FulfilledThenable<mixed> = (thenable: any);
<del> fulfilledThenable.status = 'fulfilled';
<del> fulfilledThenable.value = fulfilledValue;
<del> }
<del> },
<del> (error: mixed) => {
<del> if (thenable.status === 'pending') {
<del> const rejectedThenable: RejectedThenable<mixed> = (thenable: any);
<del> rejectedThenable.status = 'rejected';
<del> rejectedThenable.reason = error;
<del> }
<del> },
<del> );
<del> break;
<del> }
<del> }
<del>}
<ide>
<del>export function getPreviouslyUsedThenableAtIndex<T>(
<del> thenableState: ThenableState | null,
<del> index: number,
<del>): Thenable<T> | null {
<del> if (thenableState !== null) {
<del> const thenable = thenableState[index];
<del> if (thenable !== undefined) {
<del> return thenable;
<add> // Suspend.
<add> // TODO: Throwing here is an implementation detail that allows us to
<add> // unwind the call stack. But we shouldn't allow it to leak into
<add> // userspace. Throw an opaque placeholder value instead of the
<add> // actual thenable. If it doesn't get captured by the work loop, log
<add> // a warning, because that means something in userspace must have
<add> // caught it.
<add> throw thenable;
<ide> }
<ide> }
<del> return null;
<ide> }
<ide><path>packages/react-server/src/ReactFlightHooks.js
<ide> import {
<ide> } from 'shared/ReactSymbols';
<ide> import {readContext as readContextImpl} from './ReactFlightNewContext';
<ide> import {enableUseHook} from 'shared/ReactFeatureFlags';
<del>import {
<del> getPreviouslyUsedThenableAtIndex,
<del> createThenableState,
<del> trackUsedThenable,
<del>} from './ReactFlightThenable';
<add>import {createThenableState, trackUsedThenable} from './ReactFlightThenable';
<ide>
<ide> let currentRequest = null;
<ide> let thenableIndexCounter = 0;
<ide> function useId(): string {
<ide> return ':' + currentRequest.identifierPrefix + 'S' + id.toString(32) + ':';
<ide> }
<ide>
<del>function noop(): void {}
<del>
<ide> function use<T>(usable: Usable<T>): T {
<ide> if (usable !== null && typeof usable === 'object') {
<ide> // $FlowFixMe[method-unbinding]
<ide> function use<T>(usable: Usable<T>): T {
<ide> const index = thenableIndexCounter;
<ide> thenableIndexCounter += 1;
<ide>
<del> switch (thenable.status) {
<del> case 'fulfilled': {
<del> const fulfilledValue: T = thenable.value;
<del> return fulfilledValue;
<del> }
<del> case 'rejected': {
<del> const rejectedError = thenable.reason;
<del> throw rejectedError;
<del> }
<del> default: {
<del> const prevThenableAtIndex: Thenable<T> | null = getPreviouslyUsedThenableAtIndex(
<del> thenableState,
<del> index,
<del> );
<del> if (prevThenableAtIndex !== null) {
<del> if (thenable !== prevThenableAtIndex) {
<del> // Avoid an unhandled rejection errors for the Promises that we'll
<del> // intentionally ignore.
<del> thenable.then(noop, noop);
<del> }
<del> switch (prevThenableAtIndex.status) {
<del> case 'fulfilled': {
<del> const fulfilledValue: T = prevThenableAtIndex.value;
<del> return fulfilledValue;
<del> }
<del> case 'rejected': {
<del> const rejectedError: mixed = prevThenableAtIndex.reason;
<del> throw rejectedError;
<del> }
<del> default: {
<del> // The thenable still hasn't resolved. Suspend with the same
<del> // thenable as last time to avoid redundant listeners.
<del> throw prevThenableAtIndex;
<del> }
<del> }
<del> } else {
<del> // This is the first time something has been used at this index.
<del> // Stash the thenable at the current index so we can reuse it during
<del> // the next attempt.
<del> if (thenableState === null) {
<del> thenableState = createThenableState();
<del> }
<del> trackUsedThenable(thenableState, thenable, index);
<del>
<del> // Suspend.
<del> // TODO: Throwing here is an implementation detail that allows us to
<del> // unwind the call stack. But we shouldn't allow it to leak into
<del> // userspace. Throw an opaque placeholder value instead of the
<del> // actual thenable. If it doesn't get captured by the work loop, log
<del> // a warning, because that means something in userspace must have
<del> // caught it.
<del> throw thenable;
<del> }
<del> }
<add> if (thenableState === null) {
<add> thenableState = createThenableState();
<ide> }
<add> return trackUsedThenable(thenableState, thenable, index);
<ide> } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) {
<ide> const context: ReactServerContext<T> = (usable: any);
<ide> return readContext(context);
<ide><path>packages/react-server/src/ReactFlightThenable.js
<ide> import type {
<ide> RejectedThenable,
<ide> } from 'shared/ReactTypes';
<ide>
<del>// TODO: Sparse arrays are bad for performance.
<del>export opaque type ThenableState = Array<Thenable<any> | void>;
<add>export opaque type ThenableState = Array<Thenable<any>>;
<ide>
<ide> export function createThenableState(): ThenableState {
<ide> // The ThenableState is created the first time a component suspends. If it
<ide> // suspends again, we'll reuse the same state.
<ide> return [];
<ide> }
<ide>
<add>function noop(): void {}
<add>
<ide> export function trackUsedThenable<T>(
<ide> thenableState: ThenableState,
<ide> thenable: Thenable<T>,
<ide> index: number,
<del>) {
<del> thenableState[index] = thenable;
<add>): T {
<add> const previous = thenableState[index];
<add> if (previous === undefined) {
<add> thenableState.push(thenable);
<add> } else {
<add> if (previous !== thenable) {
<add> // Reuse the previous thenable, and drop the new one. We can assume
<add> // they represent the same value, because components are idempotent.
<add>
<add> // Avoid an unhandled rejection errors for the Promises that we'll
<add> // intentionally ignore.
<add> thenable.then(noop, noop);
<add> thenable = previous;
<add> }
<add> }
<ide>
<ide> // We use an expando to track the status and result of a thenable so that we
<ide> // can synchronously unwrap the value. Think of this as an extension of the
<ide> export function trackUsedThenable<T>(
<ide> // If the thenable doesn't have a status, set it to "pending" and attach
<ide> // a listener that will update its status and result when it resolves.
<ide> switch (thenable.status) {
<del> case 'fulfilled':
<del> case 'rejected':
<del> // A thenable that already resolved shouldn't have been thrown, so this is
<del> // unexpected. Suggests a mistake in a userspace data library. Don't track
<del> // this thenable, because if we keep trying it will likely infinite loop
<del> // without ever resolving.
<del> // TODO: Log a warning?
<del> break;
<add> case 'fulfilled': {
<add> const fulfilledValue: T = thenable.value;
<add> return fulfilledValue;
<add> }
<add> case 'rejected': {
<add> const rejectedError = thenable.reason;
<add> throw rejectedError;
<add> }
<ide> default: {
<ide> if (typeof thenable.status === 'string') {
<ide> // Only instrument the thenable if the status if not defined. If
<ide> // it's defined, but an unknown value, assume it's been instrumented by
<ide> // some custom userspace implementation. We treat it as "pending".
<del> break;
<add> } else {
<add> const pendingThenable: PendingThenable<mixed> = (thenable: any);
<add> pendingThenable.status = 'pending';
<add> pendingThenable.then(
<add> fulfilledValue => {
<add> if (thenable.status === 'pending') {
<add> const fulfilledThenable: FulfilledThenable<mixed> = (thenable: any);
<add> fulfilledThenable.status = 'fulfilled';
<add> fulfilledThenable.value = fulfilledValue;
<add> }
<add> },
<add> (error: mixed) => {
<add> if (thenable.status === 'pending') {
<add> const rejectedThenable: RejectedThenable<mixed> = (thenable: any);
<add> rejectedThenable.status = 'rejected';
<add> rejectedThenable.reason = error;
<add> }
<add> },
<add> );
<ide> }
<del> const pendingThenable: PendingThenable<mixed> = (thenable: any);
<del> pendingThenable.status = 'pending';
<del> pendingThenable.then(
<del> fulfilledValue => {
<del> if (thenable.status === 'pending') {
<del> const fulfilledThenable: FulfilledThenable<mixed> = (thenable: any);
<del> fulfilledThenable.status = 'fulfilled';
<del> fulfilledThenable.value = fulfilledValue;
<del> }
<del> },
<del> (error: mixed) => {
<del> if (thenable.status === 'pending') {
<del> const rejectedThenable: RejectedThenable<mixed> = (thenable: any);
<del> rejectedThenable.status = 'rejected';
<del> rejectedThenable.reason = error;
<del> }
<del> },
<del> );
<del> break;
<del> }
<del> }
<del>}
<ide>
<del>export function getPreviouslyUsedThenableAtIndex<T>(
<del> thenableState: ThenableState | null,
<del> index: number,
<del>): Thenable<T> | null {
<del> if (thenableState !== null) {
<del> const thenable = thenableState[index];
<del> if (thenable !== undefined) {
<del> return thenable;
<add> // Suspend.
<add> // TODO: Throwing here is an implementation detail that allows us to
<add> // unwind the call stack. But we shouldn't allow it to leak into
<add> // userspace. Throw an opaque placeholder value instead of the
<add> // actual thenable. If it doesn't get captured by the work loop, log
<add> // a warning, because that means something in userspace must have
<add> // caught it.
<add> throw thenable;
<ide> }
<ide> }
<del> return null;
<ide> } | 8 |
Python | Python | fix typo in taskgroup docstrings | 891fb2d9f42e180abd12a11db5a52fe4a334ab29 | <ide><path>airflow/utils/task_group.py
<ide> class TaskGroup(TaskMixin):
<ide> :param prefix_group_id: If set to True, child task_id and group_id will be prefixed with
<ide> this TaskGroup's group_id. If set to False, child task_id and group_id are not prefixed.
<ide> Default is True.
<del> :type prerfix_group_id: bool
<add> :type prefix_group_id: bool
<ide> :param parent_group: The parent TaskGroup of this TaskGroup. parent_group is set to None
<ide> for the root TaskGroup.
<ide> :type parent_group: TaskGroup | 1 |
Text | Text | add blog post | 6e3b69f055920f3e8fd8ec5a4812a6a6e46b31f2 | <ide><path>docs/_posts/2016-07-22-create-apps-with-no-configuration.md
<add>---
<add>title: "Create Apps with No Configuration"
<add>author: gaearon
<add>---
<add>
<add>**[Create React App](https://github.com/facebookincubator/create-react-app)** is a new officially supported way to create single-page React applications. It offers a modern build setup with no configuration.
<add>
<add>## Getting Started
<add>
<add>### Installation
<add>
<add>First, install the global package:
<add>
<add>```sh
<add>npm install -g create-react-app
<add>```
<add>
<add>Node.js 4.x or higher is required.
<add>
<add>### Creating an App
<add>
<add>Now you can use it to create a new app:
<add>
<add>```sh
<add>create-react-app hello-world
<add>```
<add>
<add>This will take a while as npm installs the transient dependencies, but once it’s done, you will see the list the commands you can run in the created folder:
<add>
<add>
<add>
<add>### Starting the Server
<add>
<add>Run `npm start` to launch the development server. The browser will open automatically with the created app’s URL.
<add>
<add>
<add>
<add>Create React App uses both Webpack and Babel under the hood.
<add>The console output is tuned to be minimal to help you focus on the problems:
<add>
<add>
<add>
<add>ESLint is also integrated so lint warnings are displayed right in the console:
<add>
<add>
<add>
<add>We only picked a small subset of lint rules that often lead to bugs.
<add>
<add>### Building for Production
<add>
<add>To build an optimized bundle, run `npm run build`:
<add>
<add>
<add>
<add>It is minified, correctly envified, and the assets include content hashes for caching.
<add>
<add>### One Dependency
<add>
<add>Your `package.json` contains only a single build dependency and a few scripts:
<add>
<add>```js
<add>{
<add> "name": "hello-world",
<add> "dependencies": {
<add> "react": "^15.2.1",
<add> "react-dom": "^15.2.1"
<add> },
<add> "devDependencies": {
<add> "react-scripts": "0.1.0"
<add> },
<add> "scripts": {
<add> "start": "react-scripts start",
<add> "build": "react-scripts build",
<add> "eject": "react-scripts eject"
<add> }
<add>}
<add>```
<add>
<add>We take care of updating Babel, ESLint, and Webpack to stable compatible versions so you can update a single dependency to get them all.
<add>
<add>### Zero Configuration
<add>
<add>It is worth repeating: there is no configuration files or complicated folder structures. The tool only generates the files you need to build your app.
<add>
<add>```
<add>hello-world/
<add> README.md
<add> index.html
<add> favicon.ico
<add> node_modules/
<add> package.json
<add> src/
<add> App.css
<add> App.js
<add> index.css
<add> index.js
<add> logo.svg
<add>```
<add>
<add>All the build settings are preconfigured and can’t be changed. Some features, such as testing, are currently missing. This is an intentional limitation, and we recognize it might not work for everybody. And this brings us to the last point.
<add>
<add>### No Lock-In
<add>
<add>We first saw this feature in [Enclave](https://github.com/eanplatter/enclave), and we loved it. We talked to [Ean](https://twitter.com/EanPlatter), and he was excited to collaborate with us. He already sent a few pull requests!
<add>
<add>“Ejecting” lets you leave the comfort of Create React App setup at any time. You run a single command, and all the build dependencies, configs, and scripts are moved right into your project. At this point you can customize everything you want, but effectively you are forking our configuration and going your own way. If you’re experienced with build tooling and prefer to fine-tune everything to your taste, this lets you use Create React App as a boilerplate generator.
<add>
<add>We expect that at early stages, many people will “eject” for one reason or another, but as we learn from them, we will make the default setup more and more compelling while still providing no configuration.
<add>
<add>## Try It Out!
<add>
<add>You can find [**Create React App**](http://github.com/facebookincubator/create-react-app) with additional instructions on GitHub.
<add>
<add>This is an experiment, and only time will tell if it becomes a popular way of creating and building React apps, or fades into obscurity.
<add>
<add>We welcome you to participate in this experiment. Help us build the React tooling that more people can use. We are always [open to feedback](https://github.com/facebookincubator/create-react-app/issues/11).
<add>
<add>## The Backstory
<add>
<add>React was one of the first libraries to embrace transpiling JavaScript. As a result, even though you can [learn React without any tooling](https://github.com/facebook/react/blob/3fd582643ef3d222a00a0c756292c15b88f9f83c/examples/basic-jsx/index.html), the React ecosystem has commonly become associated with an overwhelming explosion of tools.
<add>
<add>Eric Clemmons called this phenomenon the “[JavaScript Fatigue](https://medium.com/@ericclemmons/javascript-fatigue-48d4011b6fc4)”:
<add>
<add>>Ultimately, the problem is that by choosing React (and inherently JSX), you’ve unwittingly opted into a confusing nest of build tools, boilerplate, linters, & time-sinks to deal with before you ever get to create anything.
<add>
<add>It is tempting to write code in ES2015 and JSX. It is sensible to use a bundler to keep the codebase modular, and a linter to catch the common mistakes. It is nice to have a development server with fast rebuilds, and a command to produce optimized bundles for production.
<add>
<add>Combining these tools requires some experience with each of them. Even so, it is far too easy to get dragged into fighting small incompatibilities, unsatisfied peerDependencies, and illegible configuration files.
<add>
<add>Many of those tools are plugin platforms and don’t directly acknowledge each other’s existence. They leave it up to the users to wire them together. The tools mature and change independently, and tutorials quickly get out of date.
<add>
<add><blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">Marc was almost ready to implement his "hello world" React app <a href="https://t.co/ptdg4yteF1">pic.twitter.com/ptdg4yteF1</a></p>— Thomas Fuchs (@thomasfuchs) <a href="https://twitter.com/thomasfuchs/status/708675139253174273">March 12, 2016</a></blockquote>
<add><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
<add>
<add>This doesn’t mean those tools aren’t great. To many of us, they have become indispensable, and we very much appreciate the effort of their maintainers. They already have too much on their plates to worry about the state of the React ecosystem.
<add>
<add>Still, we knew it was frustrating to spend days setting up a project when all you wanted was to learn React. We wanted to fix this.
<add>
<add>## Could We Fix This?
<add>
<add>We found ourselves in an unusual dilemma.
<add>
<add>So far, [our strategy](/react/contributing/design-principles.html#dogfooding) has been to only release the code that we are using at Facebook. This helped us ensure that every project is battle-tested and has clearly defined scope and priorities.
<add>
<add>However, tooling at Facebook is different than at many smaller companies. Linting, transpilation, and packaging are all handled by powerful remote development servers, and product engineers don’t need to configure them. While we wish we could give a dedicated server to every user of React, even Facebook cannot scale that well!
<add>
<add>The React community is very important to us. We knew that we couldn’t fix the problem within the limits of our open source philosophy. This is why we decided to make an exception, and to ship something that we didn’t use ourselves, but that we thought would be useful to the community.
<add>
<add>## The Quest for a React <abbr title="Command Line Interface">CLI</abbr>
<add>
<add>Having just attended [EmberCamp](http://embercamp.com/) a week ago, I was excited about [Ember CLI](https://ember-cli.com/). Ember users have a great “getting started” experience thanks to a curated set of tools united under a single command-line interface. I have heard similar feedback about [Elm Reactor](https://github.com/elm-lang/elm-reactor).
<add>
<add>Providing a cohesive curated experience is valuable by itself, even if the user could in theory assemble those parts themselves. Kathy Sierra [explains it best](http://seriouspony.com/blog/2013/7/24/your-app-makes-me-fat):
<add>
<add>>If your UX asks the user to make *choices*, for example, even if those choices are both clear and useful, the act of *deciding* is a cognitive drain. And not just *while* they’re deciding... even *after* we choose, an unconscious cognitive background thread is slowly consuming/leaking resources, “Was *that* the right choice?”
<add>
<add>I never tried to write a command-line tool for React apps, and neither has [Christopher](http://twitter.com/vjeux). We were chatting on Messenger about this idea, and we decided to work together on it for a week as a hackathon project.
<add>
<add>We knew that such projects traditionally haven’t been very successful in the React ecosystem. Christopher told me that multiple “React CLI” projects have started and failed at Facebook. The community tools with similar goals also exist, but so far they have not yet gained enough traction.
<add>
<add>Still, we decided it was worth another shot. Christopher and I created a very rough proof of concept on the weekend, and [Kevin](https://twitter.com/lacker) soon joined us.
<add>
<add>We invited some of the community members to collaborate with us, and we have spent this week working on this tool. We hope that you’ll enjoy using it! [Let us know what you think.](https://github.com/facebookincubator/create-react-app/issues/11)
<add>
<add>We would like to express our gratitude to [Max Stoiber](https://twitter.com/mxstbr), [Jonny Buchanan](https://twitter.com/jbscript), [Ean Platter](https://twitter.com/eanplatter), [Tyler McGinnis](https://github.com/tylermcginnis), [Kent C. Dodds](https://github.com/kentcdodds), and [Eric Clemmons](https://twitter.com/ericclemmons) for their early feedback, ideas, and contributions. | 1 |
Java | Java | use random id for websocket sessions | 3302798e2ff515205183f9a26a2aca8d92cc5352 | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/AbstractWebSocketSession.java
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.util.AlternativeJdkIdGenerator;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.IdGenerator;
<ide> import org.springframework.web.socket.BinaryMessage;
<ide> import org.springframework.web.socket.CloseStatus;
<ide> import org.springframework.web.socket.PingMessage;
<ide> */
<ide> public abstract class AbstractWebSocketSession<T> implements NativeWebSocketSession {
<ide>
<add> protected static final IdGenerator idGenerator = new AlternativeJdkIdGenerator();
<add>
<ide> protected static final Log logger = LogFactory.getLog(NativeWebSocketSession.class);
<ide>
<add>
<ide> private final Map<String, Object> attributes = new ConcurrentHashMap<>();
<ide>
<ide> @Nullable
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/jetty/JettyWebSocketSession.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.CollectionUtils;
<del>import org.springframework.util.ObjectUtils;
<ide> import org.springframework.web.socket.BinaryMessage;
<ide> import org.springframework.web.socket.CloseStatus;
<ide> import org.springframework.web.socket.PingMessage;
<ide> */
<ide> public class JettyWebSocketSession extends AbstractWebSocketSession<Session> {
<ide>
<del> @Nullable
<del> private String id;
<add> private final String id;
<ide>
<ide> @Nullable
<ide> private URI uri;
<ide> public JettyWebSocketSession(Map<String, Object> attributes) {
<ide> */
<ide> public JettyWebSocketSession(Map<String, Object> attributes, @Nullable Principal user) {
<ide> super(attributes);
<add> this.id = idGenerator.generateId().toString();
<ide> this.user = user;
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public String getId() {
<del> Assert.state(this.id != null, "WebSocket session is not yet initialized");
<ide> return this.id;
<ide> }
<ide>
<ide> public boolean isOpen() {
<ide> public void initializeNativeSession(Session session) {
<ide> super.initializeNativeSession(session);
<ide>
<del> this.id = ObjectUtils.getIdentityHexString(getNativeSession());
<ide> this.uri = session.getUpgradeRequest().getRequestURI();
<ide>
<ide> HttpHeaders headers = new HttpHeaders();
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/standard/StandardWebSocketSession.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> public class StandardWebSocketSession extends AbstractWebSocketSession<Session> {
<ide>
<del> @Nullable
<del> private String id;
<add> private final String id;
<ide>
<ide> @Nullable
<ide> private URI uri;
<ide> public StandardWebSocketSession(@Nullable HttpHeaders headers, @Nullable Map<Str
<ide> @Nullable Principal user) {
<ide>
<ide> super(attributes);
<add> this.id = idGenerator.generateId().toString();
<ide> headers = (headers != null ? headers : new HttpHeaders());
<ide> this.handshakeHeaders = HttpHeaders.readOnlyHttpHeaders(headers);
<ide> this.user = user;
<ide> public StandardWebSocketSession(@Nullable HttpHeaders headers, @Nullable Map<Str
<ide>
<ide> @Override
<ide> public String getId() {
<del> Assert.state(this.id != null, "WebSocket session is not yet initialized");
<ide> return this.id;
<ide> }
<ide>
<ide> public boolean isOpen() {
<ide> public void initializeNativeSession(Session session) {
<ide> super.initializeNativeSession(session);
<ide>
<del> this.id = session.getId();
<ide> this.uri = session.getRequestURI();
<del>
<ide> this.acceptedProtocol = session.getNegotiatedSubprotocol();
<ide>
<ide> List<Extension> standardExtensions = getNativeSession().getNegotiatedExtensions();
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/StandardWebSocketHandlerAdapterTests.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.web.socket.adapter.standard;
<ide>
<add>import java.net.URI;
<ide> import javax.websocket.CloseReason;
<ide> import javax.websocket.CloseReason.CloseCodes;
<ide> import javax.websocket.MessageHandler;
<ide> public void setup() {
<ide>
<ide> @Test
<ide> public void onOpen() throws Throwable {
<del> given(this.session.getId()).willReturn("123");
<add> URI uri = URI.create("http://example.org");
<add> given(this.session.getRequestURI()).willReturn(uri);
<ide> this.adapter.onOpen(this.session, null);
<ide>
<ide> verify(this.webSocketHandler).afterConnectionEstablished(this.webSocketSession);
<ide> verify(this.session, atLeast(2)).addMessageHandler(any(MessageHandler.Whole.class));
<ide>
<del> given(this.session.getId()).willReturn("123");
<del> assertEquals("123", this.webSocketSession.getId());
<add> given(this.session.getRequestURI()).willReturn(uri);
<add> assertEquals(uri, this.webSocketSession.getUri());
<ide> }
<ide>
<ide> @Test | 4 |
Javascript | Javascript | clarify corner cases | ce351e69b15c3f55287a976e027e0e75b94aa89f | <ide><path>src/Angular.js
<ide> function isLeafNode (node) {
<ide> * * If no destination is supplied, a copy of the object or array is created.
<ide> * * If a destination is provided, all of its elements (for array) or properties (for objects)
<ide> * are deleted and then all elements/properties from the source are copied to it.
<del> * * If `source` is not an object or array, `source` is returned.
<add> * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
<add> * * If `source` is identical to 'destination' an exception will be thrown.
<ide> *
<ide> * Note: this function is used to augment the Object type in Angular expressions. See
<ide> * {@link ng.$filter} for more information about Angular arrays. | 1 |
PHP | PHP | enhance handle docblocks | 227f982f11c8485ce7dda6e75bcb91eea7b9a23d | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> class Handler implements ExceptionHandlerContract
<ide> /**
<ide> * A list of the exception types that are not reported.
<ide> *
<del> * @var array
<add> * @var string[]
<ide> */
<ide> protected $dontReport = [];
<ide>
<ide> /**
<ide> * The callbacks that should be used during reporting.
<ide> *
<del> * @var array
<add> * @var \Illuminate\Foundation\Exceptions\ReportableHandler[]
<ide> */
<ide> protected $reportCallbacks = [];
<ide>
<ide> /**
<ide> * The callbacks that should be used during rendering.
<ide> *
<del> * @var array
<add> * @var \Closure[]
<ide> */
<ide> protected $renderCallbacks = [];
<ide>
<ide> /**
<ide> * The registered exception mappings.
<ide> *
<del> * @var array
<add> * @var array<string, \Closure>
<ide> */
<ide> protected $exceptionMap = [];
<ide> | 1 |
Text | Text | add kiwi.com as a user to readme | 16740dd1dadf53aa0444394cfce302c78b968de4 | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> * [Hootsuite](https://github.com/hootsuite)
<ide> * [ING](http://www.ing.com/)
<ide> * [Jampp](https://github.com/jampp)
<add>* [Kiwi.com](https://kiwi.com/) [[@underyx](https://github.com/underyx)]
<ide> * [Kogan.com](https://github.com/kogan) [[@geeknam](https://github.com/geeknam)]
<ide> * [LendUp](https://www.lendup.com/) [[@lendup](https://github.com/lendup)]
<ide> * [LingoChamp](http://www.liulishuo.com/) [[@haitaoyao](https://github.com/haitaoyao)] | 1 |
Python | Python | add punctuations for bengali | d91be7aed409302f9514ea17397e6fff5ac3a118 | <ide><path>spacy/bn/__init__.py
<ide> class Defaults(Language.Defaults):
<ide>
<ide> tokenizer_exceptions = TOKENIZER_EXCEPTIONS
<ide> stop_words = STOP_WORDS
<add>
<add> prefixes = tuple(TOKENIZER_PREFIXES)
<add> suffixes = tuple(TOKENIZER_SUFFIXES)
<add> infixes = tuple(TOKENIZER_INFIXES)
<ide><path>spacy/bn/language_data.py
<ide> # encoding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from .. import language_data as base
<del>from ..language_data import update_exc, strings_to_exc
<del>
<add>from spacy.language_data import strings_to_exc, update_exc
<add>from .punctuation import *
<ide> from .stop_words import STOP_WORDS
<del>
<add>from .. import language_data as base
<ide>
<ide> STOP_WORDS = set(STOP_WORDS)
<ide>
<del>
<ide> TOKENIZER_EXCEPTIONS = strings_to_exc(base.EMOTICONS)
<ide> update_exc(TOKENIZER_EXCEPTIONS, strings_to_exc(base.ABBREVIATIONS))
<ide>
<add>TOKENIZER_PREFIXES = TOKENIZER_PREFIXES
<add>TOKENIZER_SUFFIXES = TOKENIZER_SUFFIXES
<add>TOKENIZER_INFIXES = TOKENIZER_INFIXES
<ide>
<del>__all__ = ["TOKENIZER_EXCEPTIONS", "STOP_WORDS"]
<add>__all__ = ["TOKENIZER_EXCEPTIONS", "STOP_WORDS", "TOKENIZER_PREFIXES", "TOKENIZER_SUFFIXES", "TOKENIZER_INFIXES"]
<ide><path>spacy/bn/punctuation.py
<add># encoding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from ..language_data.punctuation import ALPHA_LOWER, LIST_ELLIPSES, QUOTES, ALPHA_UPPER, LIST_QUOTES, UNITS, \
<add> CURRENCY, LIST_PUNCT, ALPHA, _QUOTES
<add>
<add>CURRENCY_SYMBOLS = r"\$ ¢ £ € ¥ ฿ ৳"
<add>
<add>_PUNCT = '। ॥'
<add>
<add>LIST_PUNCT.extend(_PUNCT.strip().split())
<add>
<add>TOKENIZER_PREFIXES = (
<add> [r'\+'] +
<add> LIST_PUNCT +
<add> LIST_ELLIPSES +
<add> LIST_QUOTES
<add>)
<add>
<add>TOKENIZER_SUFFIXES = (
<add> LIST_PUNCT +
<add> LIST_ELLIPSES +
<add> LIST_QUOTES +
<add> [
<add> r'(?<=[0-9])\+',
<add> r'(?<=°[FfCcKk])\.',
<add> r'(?<=[0-9])(?:{c})'.format(c=CURRENCY),
<add> r'(?<=[0-9])(?:{u})'.format(u=UNITS),
<add> r'(?<=[{al}{p}{c}(?:{q})])\.'.format(al=ALPHA_LOWER, p=r'%²\-\)\]\+', q=QUOTES, c=CURRENCY_SYMBOLS),
<add> r'(?<=[{al})])-e'.format(al=ALPHA_LOWER)
<add> ]
<add>)
<add>
<add>TOKENIZER_INFIXES = (
<add> LIST_ELLIPSES +
<add> [
<add> r'(?<=[{al}])\.(?=[{au}])'.format(al=ALPHA_LOWER, au=ALPHA_UPPER),
<add> r'(?<=[{a}]),(?=[{a}])'.format(a=ALPHA),
<add> r'(?<=[{a}"])[:<>=](?=[{a}])'.format(a=ALPHA),
<add> r'(?<=[{a}])--(?=[{a}])'.format(a=ALPHA),
<add> r'(?<=[{a}]),(?=[{a}])'.format(a=ALPHA),
<add> r'(?<=[{a}])([{q}\)\]\(\[])(?=[\-{a}])'.format(a=ALPHA, q=_QUOTES.replace("'", "").strip().replace(" ", "")),
<add> ]
<add>)
<add>__all__ = ["TOKENIZER_PREFIXES", "TOKENIZER_SUFFIXES", "TOKENIZER_INFIXES"] | 3 |
Javascript | Javascript | remove forced optimization from util | ca86aa5323a36895a3aed917fc9a4a3509d3df9b | <ide><path>benchmark/util/format.js
<ide>
<ide> const util = require('util');
<ide> const common = require('../common');
<del>const v8 = require('v8');
<ide> const types = [
<ide> 'string',
<ide> 'number',
<ide> function main(conf) {
<ide>
<ide> const input = inputs[type];
<ide>
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del>
<del> util.format(input[0], input[1]);
<del> eval('%OptimizeFunctionOnNextCall(util.format)');
<del> util.format(input[0], input[1]);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> util.format(input[0], input[1]); | 1 |
Go | Go | deprecate some consts and move them to pkg/idtools | 46c591b045a77b7f0f96f96a51d8304264685929 | <ide><path>builder/dockerfile/copy_windows.go
<ide> func fixPermissionsReexec() {
<ide> }
<ide>
<ide> func fixPermissionsWindows(source, destination, SID string) error {
<del>
<del> privileges := []string{winio.SeRestorePrivilege, system.SeTakeOwnershipPrivilege}
<add> privileges := []string{winio.SeRestorePrivilege, idtools.SeTakeOwnershipPrivilege}
<ide>
<ide> err := winio.EnableProcessPrivileges(privileges)
<ide> if err != nil {
<ide><path>builder/dockerfile/internals_windows.go
<ide> import (
<ide> "github.com/docker/docker/api/types/mount"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/jsonmessage"
<del> "github.com/docker/docker/pkg/system"
<ide> "golang.org/x/sys/windows"
<ide> )
<ide>
<ide> func getAccountIdentity(builder *Builder, accountName string, ctrRootPath string
<ide>
<ide> // Check if the account name is one unique to containers.
<ide> if strings.EqualFold(accountName, "ContainerAdministrator") {
<del> return idtools.Identity{SID: system.ContainerAdministratorSidString}, nil
<add> return idtools.Identity{SID: idtools.ContainerAdministratorSidString}, nil
<ide>
<ide> } else if strings.EqualFold(accountName, "ContainerUser") {
<del> return idtools.Identity{SID: system.ContainerUserSidString}, nil
<add> return idtools.Identity{SID: idtools.ContainerUserSidString}, nil
<ide> }
<ide>
<ide> // All other lookups failed, so therefore determine if the account in
<ide><path>pkg/idtools/idtools_windows.go
<ide> import (
<ide> "github.com/docker/docker/pkg/system"
<ide> )
<ide>
<add>const (
<add> SeTakeOwnershipPrivilege = "SeTakeOwnershipPrivilege"
<add>)
<add>
<add>const (
<add> ContainerAdministratorSidString = "S-1-5-93-2-1"
<add> ContainerUserSidString = "S-1-5-93-2-2"
<add>)
<add>
<ide> // This is currently a wrapper around MkdirAll, however, since currently
<ide> // permissions aren't set through this path, the identity isn't utilized.
<ide> // Ownership is handled elsewhere, but in the future could be support here
<ide><path>pkg/system/syscall_windows.go
<ide> import (
<ide> )
<ide>
<ide> const (
<add> // Deprecated: use github.com/docker/pkg/idtools.SeTakeOwnershipPrivilege
<ide> SeTakeOwnershipPrivilege = "SeTakeOwnershipPrivilege"
<ide> )
<ide>
<ide> const (
<add> // Deprecated: use github.com/docker/pkg/idtools.ContainerAdministratorSidString
<ide> ContainerAdministratorSidString = "S-1-5-93-2-1"
<del> ContainerUserSidString = "S-1-5-93-2-2"
<add> // Deprecated: use github.com/docker/pkg/idtools.ContainerUserSidString
<add> ContainerUserSidString = "S-1-5-93-2-2"
<ide> )
<ide>
<ide> var ( | 4 |
Ruby | Ruby | add order to bindparams in the tosql collector | 590c784a30b13153667f8db7915998d7731e24e5 | <ide><path>lib/arel/collectors/sql_string.rb
<ide> module Arel
<ide> module Collectors
<ide> class SQLString < PlainString
<add> def initialize(*)
<add> super
<add> @bind_index = 1
<add> end
<add>
<ide> def add_bind bind
<del> self << bind.to_s
<add> self << yield(@bind_index)
<add> @bind_index += 1
<ide> self
<ide> end
<ide>
<ide><path>lib/arel/nodes.rb
<ide> require 'arel/nodes/select_core'
<ide> require 'arel/nodes/insert_statement'
<ide> require 'arel/nodes/update_statement'
<add>require 'arel/nodes/bind_param'
<ide>
<ide> # terminal
<ide>
<ide><path>lib/arel/nodes/bind_param.rb
<add>module Arel
<add> module Nodes
<add> class BindParam < Node
<add> end
<add> end
<add>end
<ide><path>lib/arel/nodes/sql_literal.rb
<ide> def encode_with(coder)
<ide> coder.scalar = self.to_s
<ide> end
<ide> end
<del>
<del> class BindParam < SqlLiteral
<del> end
<ide> end
<ide> end
<ide><path>lib/arel/visitors/postgresql.rb
<ide> def visit_Arel_Nodes_DistinctOn o, collector
<ide> collector << "DISTINCT ON ( "
<ide> visit(o.expr, collector) << " )"
<ide> end
<add>
<add> def visit_Arel_Nodes_BindParam o, collector
<add> collector.add_bind(o) { |i| "$#{i}" }
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/visitors/to_sql.rb
<ide> def visit_Arel_Nodes_Values o, collector
<ide>
<ide> len = o.expressions.length - 1
<ide> o.expressions.zip(o.columns).each_with_index { |(value, attr), i|
<del> if Nodes::SqlLiteral === value
<add> case value
<add> when Nodes::SqlLiteral, Nodes::BindParam
<ide> collector = visit value, collector
<ide> else
<ide> collector << quote(value, attr && column_for(attr)).to_s
<ide> def visit_Arel_Attributes_Attribute o, collector
<ide> def literal o, collector; collector << o.to_s; end
<ide>
<ide> def visit_Arel_Nodes_BindParam o, collector
<del> collector.add_bind o
<add> collector.add_bind(o) { "?" }
<ide> end
<ide>
<ide> alias :visit_Arel_Nodes_SqlLiteral :literal
<ide><path>test/collectors/test_bind_collector.rb
<ide> def ast_with_binds bv
<ide> end
<ide>
<ide> def test_leaves_binds
<del> node = Nodes::BindParam.new 'omg'
<add> node = Nodes::BindParam.new
<ide> list = compile node
<ide> assert_equal node, list.first
<ide> assert_equal node.class, list.first.class
<ide> end
<ide>
<ide> def test_adds_strings
<del> bv = Nodes::BindParam.new('?')
<add> bv = Nodes::BindParam.new
<ide> list = compile ast_with_binds bv
<ide> assert_operator list.length, :>, 0
<ide> assert_equal bv, list.grep(Nodes::BindParam).first
<ide> assert_equal bv.class, list.grep(Nodes::BindParam).first.class
<ide> end
<ide>
<ide> def test_substitute_binds
<del> bv = Nodes::BindParam.new('?')
<add> bv = Nodes::BindParam.new
<ide> collector = collect ast_with_binds bv
<ide>
<ide> values = collector.value
<ide> def test_substitute_binds
<ide> end
<ide>
<ide> def test_compile
<del> bv = Nodes::BindParam.new('?')
<add> bv = Nodes::BindParam.new
<ide> collector = collect ast_with_binds bv
<ide>
<ide> sql = collector.compile ["hello", "world"]
<ide><path>test/collectors/test_sql_string.rb
<ide> def ast_with_binds bv
<ide> end
<ide>
<ide> def test_compile
<del> bv = Nodes::BindParam.new('?')
<add> bv = Nodes::BindParam.new
<ide> collector = collect ast_with_binds bv
<ide>
<ide> sql = collector.compile ["hello", "world"]
<ide><path>test/test_update_manager.rb
<ide> module Arel
<ide> table = Table.new(:users)
<ide> um = Arel::UpdateManager.new Table.engine
<ide> um.table table
<del> um.set [[table[:name], (Arel::Nodes::BindParam.new '?')]]
<add> um.set [[table[:name], Arel::Nodes::BindParam.new]]
<ide> um.to_sql.must_be_like %{ UPDATE "users" SET "name" = ? }
<ide> end
<ide>
<ide><path>test/visitors/test_bind_visitor.rb
<ide> def setup
<ide> def test_assignment_binds_are_substituted
<ide> table = Table.new(:users)
<ide> um = Arel::UpdateManager.new Table.engine
<del> bp = Nodes::BindParam.new '?'
<add> bp = Nodes::BindParam.new
<ide> um.set [[table[:name], bp]]
<ide> visitor = Class.new(Arel::Visitors::ToSql) {
<ide> include Arel::Visitors::BindVisitor
<ide> def test_visitor_yields_on_binds
<ide> include Arel::Visitors::BindVisitor
<ide> }.new nil
<ide>
<del> bp = Nodes::BindParam.new 'omg'
<add> bp = Nodes::BindParam.new
<ide> called = false
<ide> visitor.accept(bp, collector) { called = true }
<ide> assert called
<ide><path>test/visitors/test_postgres.rb
<ide> def compile node
<ide> }
<ide> end
<ide> end
<add>
<add> describe "Nodes::BindParam" do
<add> it "increments each bind param" do
<add> query = @table[:name].eq(Arel::Nodes::BindParam.new)
<add> .and(@table[:id].eq(Arel::Nodes::BindParam.new))
<add> compile(query).must_be_like %{
<add> "users"."name" = $1 AND "users"."id" = $2
<add> }
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/visitors/test_to_sql.rb
<ide> def compile node
<ide> end
<ide>
<ide> it 'works with BindParams' do
<del> node = Nodes::BindParam.new 'omg'
<add> node = Nodes::BindParam.new
<ide> sql = compile node
<del> sql.must_be_like 'omg'
<add> sql.must_be_like '?'
<add> end
<add>
<add> it 'does not quote BindParams used as part of a Values' do
<add> bp = Nodes::BindParam.new
<add> values = Nodes::Values.new([bp])
<add> sql = compile values
<add> sql.must_be_like 'VALUES (?)'
<ide> end
<ide>
<ide> it 'can define a dispatch method' do | 12 |
Java | Java | add systrace sections to uiimplementationprovider | c609952ddbebecba1aca62da1fb3fd143f5d11d1 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementationProvider.java
<ide>
<ide> import com.facebook.react.bridge.ReactApplicationContext;
<ide> import com.facebook.react.uimanager.events.EventDispatcher;
<add>import com.facebook.systrace.Systrace;
<ide> import java.util.List;
<ide>
<ide> /** Provides UIImplementation to use in {@link UIManagerModule}. */
<ide> public UIImplementation createUIImplementation(
<ide> UIManagerModule.ViewManagerResolver viewManagerResolver,
<ide> EventDispatcher eventDispatcher,
<ide> int minTimeLeftInFrameForNonBatchedOperationMs) {
<del> return new UIImplementation(
<del> reactContext,
<del> viewManagerResolver,
<del> eventDispatcher,
<del> minTimeLeftInFrameForNonBatchedOperationMs);
<add> Systrace.beginSection(
<add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementationProvider.createUIImplementation[1]");
<add> try {
<add> return new UIImplementation(
<add> reactContext,
<add> viewManagerResolver,
<add> eventDispatcher,
<add> minTimeLeftInFrameForNonBatchedOperationMs);
<add> } finally {
<add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<add> }
<ide> }
<ide>
<ide> public UIImplementation createUIImplementation(
<ide> ReactApplicationContext reactContext,
<ide> List<ViewManager> viewManagerList,
<ide> EventDispatcher eventDispatcher,
<ide> int minTimeLeftInFrameForNonBatchedOperationMs) {
<del> return new UIImplementation(
<del> reactContext, viewManagerList, eventDispatcher, minTimeLeftInFrameForNonBatchedOperationMs);
<add> Systrace.beginSection(
<add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementationProvider.createUIImplementation[2]");
<add> try {
<add> return new UIImplementation(
<add> reactContext,
<add> viewManagerList,
<add> eventDispatcher,
<add> minTimeLeftInFrameForNonBatchedOperationMs);
<add> } finally {
<add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<add> }
<ide> }
<ide>
<ide> UIImplementation createUIImplementation(
<ide> ReactApplicationContext reactContext,
<ide> ViewManagerRegistry viewManagerRegistry,
<ide> EventDispatcher eventDispatcher,
<ide> int minTimeLeftInFrameForNonBatchedOperationMs) {
<del> return new UIImplementation(
<del> reactContext,
<del> viewManagerRegistry,
<del> eventDispatcher,
<del> minTimeLeftInFrameForNonBatchedOperationMs);
<add> Systrace.beginSection(
<add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementationProvider.createUIImplementation[3]");
<add> try {
<add> return new UIImplementation(
<add> reactContext,
<add> viewManagerRegistry,
<add> eventDispatcher,
<add> minTimeLeftInFrameForNonBatchedOperationMs);
<add> } finally {
<add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<add> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | streamline arrow fn and refine regex | ca3d131bd42afa0c68be6aeb27623d53eae547a1 | <ide><path>test/parallel/test-console.js
<ide> assert.doesNotThrow(function() {
<ide> });
<ide>
<ide> // an Object with a custom .inspect() function
<del>const custom_inspect = { foo: 'bar', inspect: () => { return 'inspect'; } };
<add>const custom_inspect = { foo: 'bar', inspect: () => 'inspect' };
<ide>
<ide> const stdout_write = global.process.stdout.write;
<ide> const stderr_write = global.process.stderr.write;
<ide> assert.strictEqual(errStrings.length, 0);
<ide>
<ide> assert.throws(() => {
<ide> console.assert(false, 'should throw');
<del>}, /should throw/);
<add>}, /^AssertionError: should throw$/);
<ide>
<ide> assert.doesNotThrow(() => {
<ide> console.assert(true, 'this should not throw'); | 1 |
Javascript | Javascript | add eslint docs urls | 2b7c910e8ab709d3ddef369ea3abb36e36f121a6 | <ide><path>packages/eslint-plugin-next/lib/rules/google-font-display.js
<ide> module.exports = {
<ide> description:
<ide> 'Ensure correct font-display property is assigned for Google Fonts',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/google-font-display',
<ide> },
<ide> },
<ide> create: function (context) {
<ide><path>packages/eslint-plugin-next/lib/rules/google-font-preconnect.js
<ide> module.exports = {
<ide> docs: {
<ide> description: 'Ensure preconnect is used with Google Fonts',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/google-font-preconnect',
<ide> },
<ide> },
<ide> create: function (context) {
<ide><path>packages/eslint-plugin-next/lib/rules/inline-script-id.js
<ide> module.exports = {
<ide> description:
<ide> 'next/script components with inline content must specify an `id` attribute.',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/inline-script-id',
<ide> },
<ide> },
<ide> create: function (context) {
<ide><path>packages/eslint-plugin-next/lib/rules/link-passhref.js
<ide> module.exports = {
<ide> 'Ensure passHref is assigned if child of Link component is a custom component',
<ide> category: 'HTML',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/link-passhref',
<ide> },
<ide> fixable: null,
<ide> },
<ide><path>packages/eslint-plugin-next/lib/rules/next-script-for-ga.js
<ide> module.exports = {
<ide> description:
<ide> 'Prefer next script component when using the inline script for Google Analytics',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/next-script-for-ga',
<ide> },
<ide> },
<ide> create: function (context) {
<ide><path>packages/eslint-plugin-next/lib/rules/no-document-import-in-page.js
<ide> module.exports = {
<ide> description:
<ide> 'Disallow importing next/document outside of pages/document.js',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/no-document-import-in-page',
<ide> },
<ide> },
<ide> create: function (context) {
<ide><path>packages/eslint-plugin-next/lib/rules/no-duplicate-head.js
<ide> module.exports = {
<ide> docs: {
<ide> description: 'Enforce no duplicate usage of <Head> in pages/document.js',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/no-duplicate-head',
<ide> },
<ide> },
<ide> create: function (context) {
<ide><path>packages/eslint-plugin-next/lib/rules/no-head-import-in-document.js
<ide> module.exports = {
<ide> docs: {
<ide> description: 'Disallow importing next/head in pages/document.js',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/no-head-import-in-document',
<ide> },
<ide> },
<ide> create: function (context) {
<ide><path>packages/eslint-plugin-next/lib/rules/no-html-link-for-pages.js
<ide> module.exports = {
<ide> description: 'Prohibit full page refresh for Next.js pages',
<ide> category: 'HTML',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/no-html-link-for-pages',
<ide> },
<ide> fixable: null, // or "code" or "whitespace"
<ide> schema: [
<ide><path>packages/eslint-plugin-next/lib/rules/no-img-element.js
<ide> module.exports = {
<ide> description: 'Prohibit usage of HTML <img> element',
<ide> category: 'HTML',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/no-img-element',
<ide> },
<ide> fixable: 'code',
<ide> },
<ide><path>packages/eslint-plugin-next/lib/rules/no-page-custom-font.js
<ide> module.exports = {
<ide> description:
<ide> 'Recommend adding custom font in a custom document and not in a specific page',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/no-page-custom-font',
<ide> },
<ide> },
<ide> create: function (context) {
<ide><path>packages/eslint-plugin-next/lib/rules/no-script-in-document.js
<ide> module.exports = {
<ide> docs: {
<ide> description: 'Disallow importing next/script inside pages/_document.js',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/no-script-in-document-page',
<ide> },
<ide> },
<ide> create: function (context) {
<ide><path>packages/eslint-plugin-next/lib/rules/no-script-in-head.js
<ide> module.exports = {
<ide> docs: {
<ide> description: 'Disallow using next/script inside the next/head component',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/no-script-in-head-component',
<ide> },
<ide> },
<ide> create: function (context) {
<ide><path>packages/eslint-plugin-next/lib/rules/no-title-in-document-head.js
<ide> module.exports = {
<ide> meta: {
<ide> docs: {
<ide> description: 'Disallow using <title> with Head from next/document',
<add> url: 'https://nextjs.org/docs/messages/no-title-in-document-head',
<ide> },
<ide> },
<ide> create: function (context) {
<ide><path>packages/eslint-plugin-next/lib/rules/no-unwanted-polyfillio.js
<ide> module.exports = {
<ide> 'Prohibit unwanted features to be listed in Polyfill.io tag.',
<ide> category: 'HTML',
<ide> recommended: true,
<add> url: 'https://nextjs.org/docs/messages/no-unwanted-polyfillio',
<ide> },
<ide> fixable: null, // or "code" or "whitespace"
<ide> }, | 15 |
Javascript | Javascript | remove duplicated function names | 47912f49b410334e547f710ff473ac36682a2c76 | <ide><path>src/controllers/controller.bar.js
<ide> module.exports = function(Chart) {
<ide> },
<ide>
<ide> // Get the number of datasets that display bars. We use this to correctly calculate the bar width
<del> getBarCount: function getBarCount() {
<add> getBarCount: function() {
<ide> var me = this;
<ide> var barCount = 0;
<ide> helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) {
<ide> module.exports = function(Chart) {
<ide> return barCount;
<ide> },
<ide>
<del> update: function update(reset) {
<add> update: function(reset) {
<ide> var me = this;
<ide> helpers.each(me.getMeta().data, function(rectangle, index) {
<ide> me.updateElement(rectangle, index, reset);
<ide> }, me);
<ide> },
<ide>
<del> updateElement: function updateElement(rectangle, index, reset) {
<add> updateElement: function(rectangle, index, reset) {
<ide> var me = this;
<ide> var meta = me.getMeta();
<ide> var xScale = me.getScaleForId(meta.xAxisID);
<ide> module.exports = function(Chart) {
<ide> };
<ide>
<ide> Chart.controllers.horizontalBar = Chart.controllers.bar.extend({
<del> updateElement: function updateElement(rectangle, index, reset) {
<add> updateElement: function(rectangle, index, reset) {
<ide> var me = this;
<ide> var meta = me.getMeta();
<ide> var xScale = me.getScaleForId(meta.xAxisID);
<ide><path>src/controllers/controller.bubble.js
<ide> module.exports = function(Chart) {
<ide>
<ide> dataElementType: Chart.elements.Point,
<ide>
<del> update: function update(reset) {
<add> update: function(reset) {
<ide> var me = this;
<ide> var meta = me.getMeta();
<ide> var points = meta.data;
<ide><path>src/controllers/controller.doughnut.js
<ide> module.exports = function(Chart) {
<ide> linkScales: helpers.noop,
<ide>
<ide> // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
<del> getRingIndex: function getRingIndex(datasetIndex) {
<add> getRingIndex: function(datasetIndex) {
<ide> var ringIndex = 0;
<ide>
<ide> for (var j = 0; j < datasetIndex; ++j) {
<ide> module.exports = function(Chart) {
<ide> return ringIndex;
<ide> },
<ide>
<del> update: function update(reset) {
<add> update: function(reset) {
<ide> var me = this;
<ide> var chart = me.chart,
<ide> chartArea = chart.chartArea,
<ide><path>src/controllers/controller.line.js
<ide> module.exports = function(Chart) {
<ide> }
<ide> },
<ide>
<del> update: function update(reset) {
<add> update: function(reset) {
<ide> var me = this;
<ide> var meta = me.getMeta();
<ide> var line = meta.dataset;
<ide><path>src/controllers/controller.polarArea.js
<ide> module.exports = function(Chart) {
<ide>
<ide> linkScales: helpers.noop,
<ide>
<del> update: function update(reset) {
<add> update: function(reset) {
<ide> var me = this;
<ide> var chart = me.chart;
<ide> var chartArea = chart.chartArea;
<ide><path>src/controllers/controller.radar.js
<ide> module.exports = function(Chart) {
<ide> this.updateBezierControlPoints();
<ide> },
<ide>
<del> update: function update(reset) {
<add> update: function(reset) {
<ide> var me = this;
<ide> var meta = me.getMeta();
<ide> var line = meta.dataset;
<ide><path>src/core/core.controller.js
<ide> module.exports = function(Chart) {
<ide>
<ide> helpers.extend(Chart.Controller.prototype, /** @lends Chart.Controller */ {
<ide>
<del> initialize: function initialize() {
<add> initialize: function() {
<ide> var me = this;
<ide> // Before init plugin notification
<ide> Chart.plugins.notify('beforeInit', [me]);
<ide> module.exports = function(Chart) {
<ide> return me;
<ide> },
<ide>
<del> clear: function clear() {
<add> clear: function() {
<ide> helpers.clear(this.chart);
<ide> return this;
<ide> },
<ide>
<del> stop: function stop() {
<add> stop: function() {
<ide> // Stops any current animation loop occuring
<ide> Chart.animationService.cancelAnimation(this);
<ide> return this;
<ide> module.exports = function(Chart) {
<ide> return me;
<ide> },
<ide>
<del> ensureScalesHaveIDs: function ensureScalesHaveIDs() {
<add> ensureScalesHaveIDs: function() {
<ide> var options = this.options;
<ide> var scalesOptions = options.scales || {};
<ide> var scaleOptions = options.scale;
<ide> module.exports = function(Chart) {
<ide> /**
<ide> * Builds a map of scale ID to scale object for future lookup.
<ide> */
<del> buildScales: function buildScales() {
<add> buildScales: function() {
<ide> var me = this;
<ide> var options = me.options;
<ide> var scales = me.scales = {};
<ide> module.exports = function(Chart) {
<ide> Chart.layoutService.update(this, this.chart.width, this.chart.height);
<ide> },
<ide>
<del> buildOrUpdateControllers: function buildOrUpdateControllers() {
<add> buildOrUpdateControllers: function() {
<ide> var me = this;
<ide> var types = [];
<ide> var newControllers = [];
<ide> module.exports = function(Chart) {
<ide> return newControllers;
<ide> },
<ide>
<del> resetElements: function resetElements() {
<add> resetElements: function() {
<ide> var me = this;
<ide> helpers.each(me.data.datasets, function(dataset, datasetIndex) {
<ide> me.getDatasetMeta(datasetIndex).controller.reset();
<ide> module.exports = function(Chart) {
<ide> return typeof meta.hidden === 'boolean'? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
<ide> },
<ide>
<del> generateLegend: function generateLegend() {
<add> generateLegend: function() {
<ide> return this.options.legendCallback(this);
<ide> },
<ide>
<del> destroy: function destroy() {
<add> destroy: function() {
<ide> var me = this;
<ide> me.stop();
<ide> me.clear();
<ide> module.exports = function(Chart) {
<ide> delete Chart.instances[me.id];
<ide> },
<ide>
<del> toBase64Image: function toBase64Image() {
<add> toBase64Image: function() {
<ide> return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
<ide> },
<ide>
<del> initToolTip: function initToolTip() {
<add> initToolTip: function() {
<ide> var me = this;
<ide> me.tooltip = new Chart.Tooltip({
<ide> _chart: me.chart,
<ide> module.exports = function(Chart) {
<ide> }, me);
<ide> },
<ide>
<del> bindEvents: function bindEvents() {
<add> bindEvents: function() {
<ide> var me = this;
<ide> helpers.bindEvents(me, me.options.events, function(evt) {
<ide> me.eventHandler(evt);
<ide><path>src/core/core.datasetController.js
<ide> module.exports = function(Chart) {
<ide> me.updateElement(element, index, true);
<ide> },
<ide>
<del> buildOrUpdateElements: function buildOrUpdateElements() {
<add> buildOrUpdateElements: function() {
<ide> // Handle the number of data points changing
<ide> var meta = this.getMeta(),
<ide> md = meta.data,
<ide><path>src/core/core.scale.js
<ide> module.exports = function(Chart) {
<ide> },
<ide>
<ide> // Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not
<del> getRightValue: function getRightValue(rawValue) {
<add> getRightValue: function(rawValue) {
<ide> // Null and undefined values first
<ide> if (rawValue === null || typeof(rawValue) === 'undefined') {
<ide> return NaN;
<ide> module.exports = function(Chart) {
<ide> if ((rawValue instanceof Date) || (rawValue.isValid)) {
<ide> return rawValue;
<ide> } else {
<del> return getRightValue(this.isHorizontal() ? rawValue.x : rawValue.y);
<add> return this.getRightValue(this.isHorizontal() ? rawValue.x : rawValue.y);
<ide> }
<ide> }
<ide>
<ide><path>src/core/core.tooltip.js
<ide> module.exports = function(Chart) {
<ide>
<ide> return me;
<ide> },
<del> getTooltipSize: function getTooltipSize(vm) {
<add> getTooltipSize: function(vm) {
<ide> var ctx = this._chart.ctx;
<ide>
<ide> var size = {
<ide> module.exports = function(Chart) {
<ide>
<ide> return size;
<ide> },
<del> determineAlignment: function determineAlignment(size) {
<add> determineAlignment: function(size) {
<ide> var me = this;
<ide> var model = me._model;
<ide> var chart = me._chart;
<ide> module.exports = function(Chart) {
<ide> }
<ide> }
<ide> },
<del> getBackgroundPoint: function getBackgroundPoint(vm, size) {
<add> getBackgroundPoint: function(vm, size) {
<ide> // Background Position
<ide> var pt = {
<ide> x: vm.x,
<ide> module.exports = function(Chart) {
<ide>
<ide> return pt;
<ide> },
<del> drawCaret: function drawCaret(tooltipPoint, size, opacity) {
<add> drawCaret: function(tooltipPoint, size, opacity) {
<ide> var vm = this._view;
<ide> var ctx = this._chart.ctx;
<ide> var x1, x2, x3;
<ide> module.exports = function(Chart) {
<ide> ctx.closePath();
<ide> ctx.fill();
<ide> },
<del> drawTitle: function drawTitle(pt, vm, ctx, opacity) {
<add> drawTitle: function(pt, vm, ctx, opacity) {
<ide> var title = vm.title;
<ide>
<ide> if (title.length) {
<ide> module.exports = function(Chart) {
<ide> }
<ide> }
<ide> },
<del> drawBody: function drawBody(pt, vm, ctx, opacity) {
<add> drawBody: function(pt, vm, ctx, opacity) {
<ide> var bodyFontSize = vm.bodyFontSize;
<ide> var bodySpacing = vm.bodySpacing;
<ide> var body = vm.body;
<ide> module.exports = function(Chart) {
<ide> helpers.each(vm.afterBody, fillLineOfText);
<ide> pt.y -= bodySpacing; // Remove last body spacing
<ide> },
<del> drawFooter: function drawFooter(pt, vm, ctx, opacity) {
<add> drawFooter: function(pt, vm, ctx, opacity) {
<ide> var footer = vm.footer;
<ide>
<ide> if (footer.length) {
<ide> module.exports = function(Chart) {
<ide> });
<ide> }
<ide> },
<del> draw: function draw() {
<add> draw: function() {
<ide> var ctx = this._chart.ctx;
<ide> var vm = this._view;
<ide>
<ide><path>src/scales/scale.time.js
<ide> module.exports = function(Chart) {
<ide> return label;
<ide> },
<ide> // Function to format an individual tick mark
<del> tickFormatFunction: function tickFormatFunction(tick, index, ticks) {
<add> tickFormatFunction: function(tick, index, ticks) {
<ide> var formattedTick = tick.format(this.displayFormat);
<ide> var tickOpts = this.options.ticks;
<ide> var callback = helpers.getValueOrDefault(tickOpts.callback, tickOpts.userCallback); | 11 |
Ruby | Ruby | handle requests for multiple formulae | dc1bbe7f81a453079d397c387cc55a53ee22eb13 | <ide><path>Library/Homebrew/dev-cmd/bump.rb
<ide> def bump_args
<ide> def bump
<ide> args = bump_args.parse
<ide>
<del> requested_formula = args.formulae.first.to_s if args.formulae.first
<add> requested_formulae = !args.formulae.empty? ? args.formulae.map(&:name) : nil
<add>
<ide> requested_limit = args.limit.to_i if args.limit.present?
<ide>
<del> raise FormulaUnavailableError, requested_formula if requested_formula && !validate_formula(requested_formula)
<add> repology_data = if requested_formulae
<add> response = {}
<add> requested_formulae.each do |formula|
<add> raise FormulaUnavailableError, formula unless validate_formula(formula)
<add>
<add> package_data = Repology.single_package_query(formula)
<add> response[package_data.keys.first] = package_data.values.first if package_data
<add> end
<ide>
<del> repology_data = if requested_formula
<del> Repology.single_package_query(requested_formula)
<add> response
<ide> else
<ide> Repology.parse_api_response
<ide> end
<ide>
<del> validated_formulae = if repology_data.blank?
<del> { requested_formula.to_s => Repology.format_package(requested_formula, nil) }
<del> else
<del> Repology.validate_and_format_packages(repology_data, requested_limit)
<add> validated_formulae = {}
<add>
<add> validated_formulae = Repology.validate_and_format_packages(repology_data, requested_limit) if repology_data
<add>
<add> if requested_formulae
<add> repology_excluded_formulae = requested_formulae.reject do |formula|
<add> repology_data[formula]
<add> end
<add>
<add> formulae = {}
<add> repology_excluded_formulae.each do |formula|
<add> formulae[formula] = Repology.format_package(formula, nil)
<add> end
<add>
<add> formulae.each { |formula, data| validated_formulae[formula] = data }
<ide> end
<ide>
<ide> display(validated_formulae)
<ide><path>Library/Homebrew/utils/repology.rb
<ide> def validate_and_format_packages(outdated_repology_packages, limit)
<ide> packages = {}
<ide>
<ide> outdated_repology_packages.each do |_name, repositories|
<del> # identify homebrew repo
<ide> repology_homebrew_repo = repositories.find do |repo|
<ide> repo["repo"] == "homebrew"
<ide> end | 2 |
Ruby | Ruby | add inspect to requirement subclass | cf3ee4546f782a0bbe082e97c9746c5ad9b04841 | <ide><path>Library/Homebrew/requirements.rb
<ide> def message
<ide> EOS
<ide> end
<ide> end
<add>
<add> def inspect
<add> "#<#{self.class.name}: #{name.inspect} #{tags.inspect} version=#{@version.inspect}>"
<add> end
<ide> end
<ide>
<ide> class MysqlDependency < Requirement
<ide><path>Library/Homebrew/requirements/mpi_dependency.rb
<ide> def mpi_wrapper_works? compiler
<ide> quiet_system compiler, '--version'
<ide> end
<ide>
<add> def inspect
<add> "#<#{self.class.name}: #{name.inspect} #{tags.inspect} lang_list=#{@lang_list.inspect}>"
<add> end
<add>
<ide> satisfy do
<ide> @lang_list.each do |lang|
<ide> case lang | 2 |
Python | Python | add initial benchmarks for __array_function__ | 415f327069d26b7ff6159ef1ebacd1fdeaaac6a5 | <ide><path>benchmarks/benchmarks/bench_overrides.py
<add>from __future__ import absolute_import, division, print_function
<add>
<add>from .common import Benchmark
<add>
<add>from numpy.core.overrides import array_function_dispatch
<add>import numpy as np
<add>
<add>
<add>def _broadcast_to_dispatcher(array, shape, subok=None):
<add> return (array,)
<add>
<add>
<add>@array_function_dispatch(_broadcast_to_dispatcher)
<add>def mock_broadcast_to(array, shape, subok=False):
<add> pass
<add>
<add>
<add>def _concatenate_dispatcher(arrays, axis=None, out=None):
<add> for array in arrays:
<add> yield array
<add> if out is not None:
<add> yield out
<add>
<add>
<add>@array_function_dispatch(_concatenate_dispatcher)
<add>def mock_concatenate(arrays, axis=0, out=None):
<add> pass
<add>
<add>
<add>class DuckArray(object):
<add> def __array_function__(self, func, types, args, kwargs):
<add> pass
<add>
<add>
<add>class ArrayFunction(Benchmark):
<add>
<add> def setup(self):
<add> self.numpy_array = np.array(1)
<add> self.numpy_arrays = [np.array(1), np.array(2)]
<add> self.many_arrays = 500 * self.numpy_arrays
<add> self.duck_array = DuckArray()
<add> self.duck_arrays = [DuckArray(), DuckArray()]
<add> self.mixed_arrays = [np.array(1), DuckArray()]
<add>
<add> def time_mock_broadcast_to_numpy(self):
<add> mock_broadcast_to(self.numpy_array, ())
<add>
<add> def time_mock_broadcast_to_duck(self):
<add> mock_broadcast_to(self.duck_array, ())
<add>
<add> def time_mock_concatenate_numpy(self):
<add> mock_concatenate(self.numpy_arrays, axis=0)
<add>
<add> def time_mock_concatenate_many(self):
<add> mock_concatenate(self.many_arrays, axis=0)
<add>
<add> def time_mock_concatenate_duck(self):
<add> mock_concatenate(self.duck_arrays, axis=0)
<add>
<add> def time_mock_concatenate_mixed(self):
<add> mock_concatenate(self.mixed_arrays, axis=0)
<ide><path>benchmarks/benchmarks/common.py
<ide> def get_indexes_rand_():
<ide>
<ide>
<ide> class Benchmark(object):
<del> goal_time = 0.25
<add> sample_time = 0.25 | 2 |
Javascript | Javascript | raise sleep times in child process tests | bb4dff783ddb3b20c67041f7ccef796c335c2407 | <ide><path>test/parallel/test-child-process-spawnsync-timeout.js
<ide> const { debuglog, getSystemErrorName } = require('util');
<ide> const debug = debuglog('test');
<ide>
<ide> const TIMER = 200;
<del>const SLEEP = common.platformTimeout(5000);
<add>let SLEEP = common.platformTimeout(5000);
<add>
<add>if (common.isWindows) {
<add> // Some of the windows machines in the CI need more time to launch
<add> // and receive output from child processes.
<add> // https://github.com/nodejs/build/issues/3014
<add> SLEEP = common.platformTimeout(15000);
<add>}
<ide>
<ide> switch (process.argv[2]) {
<ide> case 'child':
<ide><path>test/sequential/test-child-process-execsync.js
<ide> const { execFileSync, execSync, spawnSync } = require('child_process');
<ide> const { getSystemErrorName } = require('util');
<ide>
<ide> const TIMER = 200;
<del>const SLEEP = 2000;
<add>let SLEEP = 2000;
<add>if (common.isWindows) {
<add> // Some of the windows machines in the CI need more time to launch
<add> // and receive output from child processes.
<add> // https://github.com/nodejs/build/issues/3014
<add> SLEEP = 10000;
<add>}
<ide>
<ide> const execOpts = { encoding: 'utf8', shell: true };
<ide> | 2 |
Java | Java | add pathsegmentcontainer subpath extracting method | 97917aa57d898e3e085beb0d17d26728813bb10c | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultPathSegmentContainer.java
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<add>import java.util.stream.Collectors;
<ide>
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.CollectionUtils;
<ide> class DefaultPathSegmentContainer implements PathSegmentContainer {
<ide> private final boolean trailingSlash;
<ide>
<ide>
<del> DefaultPathSegmentContainer(String path, List<PathSegment> segments) {
<add> private DefaultPathSegmentContainer(String path, List<PathSegment> segments) {
<ide> this.path = path;
<ide> this.absolute = path.startsWith("/");
<ide> this.pathSegments = Collections.unmodifiableList(segments);
<ide> private static void parseParamValues(String input, Charset charset, MultiValueMa
<ide> }
<ide> }
<ide>
<add> static PathSegmentContainer subPath(PathSegmentContainer container, int fromIndex, int toIndex) {
<add> List<PathSegment> segments = container.pathSegments();
<add> if (fromIndex == 0 && toIndex == segments.size()) {
<add> return container;
<add> }
<add> Assert.isTrue(fromIndex < toIndex, "fromIndex: " + fromIndex + " should be < toIndex " + toIndex);
<add> Assert.isTrue(fromIndex >= 0 && fromIndex < segments.size(), "Invalid fromIndex: " + fromIndex);
<add> Assert.isTrue(toIndex >= 0 && toIndex <= segments.size(), "Invalid toIndex: " + toIndex);
<add>
<add> List<PathSegment> subList = segments.subList(fromIndex, toIndex);
<add> String prefix = fromIndex > 0 || container.isAbsolute() ? "/" : "";
<add> String suffix = toIndex == segments.size() && container.hasTrailingSlash() ? "/" : "";
<add> String path = subList.stream().map(PathSegment::value).collect(Collectors.joining(prefix, "/", suffix));
<add> return new DefaultPathSegmentContainer(path, subList);
<add> }
<ide>
<ide>
<ide> private static class DefaultPathSegment implements PathSegment {
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultRequestPath.java
<ide>
<ide> import java.net.URI;
<ide> import java.nio.charset.Charset;
<del>import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<ide> import org.springframework.util.Assert;
<ide> class DefaultRequestPath implements RequestPath {
<ide> DefaultRequestPath(URI uri, String contextPath, Charset charset) {
<ide> this.fullPath = PathSegmentContainer.parse(uri.getRawPath(), charset);
<ide> this.contextPath = initContextPath(this.fullPath, contextPath);
<del> this.pathWithinApplication = initPathWithinApplication(this.fullPath, this.contextPath);
<add> this.pathWithinApplication = extractPathWithinApplication(this.fullPath, this.contextPath);
<ide> }
<ide>
<ide> DefaultRequestPath(RequestPath requestPath, String contextPath) {
<ide> this.fullPath = requestPath;
<ide> this.contextPath = initContextPath(this.fullPath, contextPath);
<del> this.pathWithinApplication = initPathWithinApplication(this.fullPath, this.contextPath);
<add> this.pathWithinApplication = extractPathWithinApplication(this.fullPath, this.contextPath);
<ide> }
<ide>
<del>
<ide> private static PathSegmentContainer initContextPath(PathSegmentContainer path, String contextPath) {
<ide> if (!StringUtils.hasText(contextPath) || "/".equals(contextPath)) {
<ide> return DefaultPathSegmentContainer.EMPTY_PATH;
<ide> private static PathSegmentContainer initContextPath(PathSegmentContainer path, S
<ide> int length = contextPath.length();
<ide> int counter = 0;
<ide>
<del> List<PathSegment> result = new ArrayList<>();
<del> for (PathSegment pathSegment : path.pathSegments()) {
<del> result.add(pathSegment);
<del> counter += 1; // for '/' separators
<add> for (int i=0; i < path.pathSegments().size(); i++) {
<add> PathSegment pathSegment = path.pathSegments().get(i);
<add> counter += 1; // for slash separators
<ide> counter += pathSegment.value().length();
<ide> counter += pathSegment.semicolonContent().length();
<ide> if (length == counter) {
<del> return new DefaultPathSegmentContainer(contextPath, result);
<add> return DefaultPathSegmentContainer.subPath(path, 0, i + 1);
<ide> }
<ide> }
<ide>
<ide> private static PathSegmentContainer initContextPath(PathSegmentContainer path, S
<ide> " given path='" + path.value() + "'");
<ide> }
<ide>
<del> private static PathSegmentContainer initPathWithinApplication(PathSegmentContainer path,
<add> private static PathSegmentContainer extractPathWithinApplication(PathSegmentContainer fullPath,
<ide> PathSegmentContainer contextPath) {
<ide>
<del> String value = path.value().substring(contextPath.value().length());
<del> List<PathSegment> pathSegments = new ArrayList<>(path.pathSegments());
<del> pathSegments.removeAll(contextPath.pathSegments());
<del> return new DefaultPathSegmentContainer(value, pathSegments);
<add> return PathSegmentContainer.subPath(fullPath, contextPath.pathSegments().size());
<ide> }
<ide>
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/PathSegmentContainer.java
<ide> static PathSegmentContainer parse(String path, Charset encoding) {
<ide> return DefaultPathSegmentContainer.parsePath(path, encoding);
<ide> }
<ide>
<add> /**
<add> * Extract a sub-path starting at the given offset into the path segment list.
<add> * @param path the path to extract from
<add> * @param pathSegmentIndex the start index (inclusive)
<add> * @return the sub-path
<add> */
<add> static PathSegmentContainer subPath(PathSegmentContainer path, int pathSegmentIndex) {
<add> return DefaultPathSegmentContainer.subPath(path, pathSegmentIndex, path.pathSegments().size());
<add> }
<add>
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/DefaultPathSegmentContainerTests.java
<ide>
<ide> import static java.nio.charset.StandardCharsets.UTF_8;
<ide> import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertSame;
<ide>
<ide> /**
<ide> * Unit tests for {@link DefaultPathSegmentContainer}.
<ide> private void testPath(String input, String value, boolean empty, boolean absolut
<ide> assertEquals("hasTrailingSlash: '" + input + "'", trailingSlash, path.hasTrailingSlash());
<ide> }
<ide>
<add> @Test
<add> public void subPath() throws Exception {
<add> // basic
<add> PathSegmentContainer path = PathSegmentContainer.parse("/a/b/c", UTF_8);
<add> assertSame(path, PathSegmentContainer.subPath(path, 0));
<add> assertEquals("/b/c", PathSegmentContainer.subPath(path, 1).value());
<add> assertEquals("/c", PathSegmentContainer.subPath(path, 2).value());
<add>
<add> // trailing slash
<add> path = PathSegmentContainer.parse("/a/b/", UTF_8);
<add> assertEquals("/b/", PathSegmentContainer.subPath(path, 1).value());
<add> }
<add>
<ide> } | 4 |
Python | Python | set version to v2.2.0.dev1 | af7fad2c6d75ea3ce755058c1acaee3a827d77d2 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy"
<del>__version__ = "2.2.0.dev0"
<add>__version__ = "2.2.0.dev1"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI" | 1 |
Javascript | Javascript | remove s_client from test-tls-ci-reneg-attack | c4216194be1b6856b9d02999ea0adc25cc036804 | <ide><path>test/pummel/test-tls-ci-reneg-attack.js
<ide> if (!common.opensslCli)
<ide> common.skip('node compiled without OpenSSL CLI.');
<ide>
<ide> const assert = require('assert');
<del>const spawn = require('child_process').spawn;
<ide> const tls = require('tls');
<ide> const fixtures = require('../common/fixtures');
<ide>
<ide> function test(next) {
<ide> key: fixtures.readSync('test_key.pem')
<ide> };
<ide>
<del> let seenError = false;
<del>
<ide> const server = tls.createServer(options, function(conn) {
<ide> conn.on('error', function(err) {
<ide> console.error(`Caught exception: ${err}`);
<ide> assert(/TLS session renegotiation attack/.test(err));
<ide> conn.destroy();
<del> seenError = true;
<ide> });
<ide> conn.pipe(conn);
<ide> });
<ide>
<del> server.listen(common.PORT, function() {
<del> const args = (`s_client -connect 127.0.0.1:${common.PORT}`).split(' ');
<del> const child = spawn(common.opensslCli, args);
<del>
<del> child.stdout.resume();
<del> child.stderr.resume();
<add> server.listen(0, function() {
<add> const options = {
<add> host: server.address().host,
<add> port: server.address().port,
<add> rejectUnauthorized: false
<add> };
<add> const client = tls.connect(options, spam);
<ide>
<del> // Count handshakes, start the attack after the initial handshake is done
<del> let handshakes = 0;
<ide> let renegs = 0;
<ide>
<del> child.stderr.on('data', function(data) {
<del> if (seenError) return;
<del> handshakes += ((String(data)).match(/verify return:1/g) || []).length;
<del> if (handshakes === 2) spam();
<del> renegs += ((String(data)).match(/RENEGOTIATING/g) || []).length;
<del> });
<del>
<del> child.on('exit', function() {
<add> client.on('close', function() {
<ide> assert.strictEqual(renegs, tls.CLIENT_RENEG_LIMIT + 1);
<ide> server.close();
<ide> process.nextTick(next);
<ide> });
<ide>
<del> let closed = false;
<del> child.stdin.on('error', function(err) {
<del> switch (err.code) {
<del> case 'ECONNRESET':
<del> case 'EPIPE':
<del> break;
<del> default:
<del> assert.strictEqual(err.code, 'ECONNRESET');
<del> break;
<del> }
<del> closed = true;
<add> client.on('error', function(err) {
<add> console.log('CLIENT ERR', err);
<add> throw err;
<ide> });
<del> child.stdin.on('close', function() {
<del> closed = true;
<add>
<add> client.on('close', function(hadErr) {
<add> assert.strictEqual(hadErr, false);
<ide> });
<ide>
<ide> // simulate renegotiation attack
<ide> function spam() {
<del> if (closed) return;
<del> child.stdin.write('R\n');
<del> setTimeout(spam, 50);
<add> client.write('');
<add> client.renegotiate({}, (err) => {
<add> assert.ifError(err);
<add> assert.ok(renegs <= tls.CLIENT_RENEG_LIMIT);
<add> spam();
<add> });
<add> renegs++;
<ide> }
<ide> });
<ide> } | 1 |
Javascript | Javascript | get next func index | 396ecae06c65588c1c3af821c6d5c40fa4398552 | <ide><path>lib/WebAssemblyGenerator.js
<ide> function compose(...fns) {
<ide>
<ide> // Utility functions
<ide> const isGlobalImport = moduleImport => moduleImport.descr.type === "GlobalType";
<add>const isFuncImport = moduleImport =>
<add> moduleImport.descr.type === "FuncImportDescr";
<ide> const initFuncId = t.identifier("__init__");
<ide>
<ide> /**
<ide> const removeStartFunc = state => bin => {
<ide> });
<ide> };
<ide>
<add>/**
<add> * Retrieve the start function
<add> *
<add> * @param {Object} ast - Module's AST
<add> * @returns {t.Identifier | undefined} - node if any
<add> */
<ide> function getStartFuncIndex(ast) {
<ide> let startAtFuncIndex;
<ide>
<ide> function getStartFuncIndex(ast) {
<ide> return startAtFuncIndex;
<ide> }
<ide>
<add>/**
<add> * Get imported globals
<add> *
<add> * @param {Object} ast - Module's AST
<add> * @returns {Array<t.ModuleImport>} - nodes
<add> */
<ide> function getImportedGlobals(ast) {
<ide> const importedGlobals = [];
<ide>
<ide> function getImportedGlobals(ast) {
<ide> return importedGlobals;
<ide> }
<ide>
<add>/**
<add> * Get next func index
<add> *
<add> * We need to respect the instantation order, first count the number of imported
<add> * func and func declared in the module.
<add> *
<add> * @param {Object} ast - Module's AST
<add> * @returns {t.indexLiteral} - index
<add> */
<add>function getNextFuncIndex(ast) {
<add> let count = 0;
<add>
<add> t.traverse(ast, {
<add> ModuleImport({ node }) {
<add> if (isFuncImport(node) === true) {
<add> count++;
<add> }
<add> },
<add>
<add> Func({ node }) {
<add> count++;
<add> }
<add> });
<add>
<add> return t.indexLiteral(count);
<add>}
<add>
<ide> /**
<ide> * Rewrite the import globals:
<ide> * - removes the ModuleImport instruction
<ide> const rewriteImportedGlobals = state => bin => {
<ide> const addInitFunction = ({
<ide> startAtFuncIndex,
<ide> importedGlobals,
<del> funcSectionMetadata
<add> funcSectionMetadata,
<add> nextFuncIndex
<ide> }) => bin => {
<ide> debug("addInitFunction");
<ide>
<del> const nextTypeIndex = funcSectionMetadata.vectorOfSize;
<del>
<ide> const funcParams = importedGlobals.map(importedGlobal => {
<ide> // used for debugging
<ide> const id = t.identifier(`${importedGlobal.module}.${importedGlobal.name}`);
<ide> const addInitFunction = ({
<ide> const func = t.func(initFuncId, funcParams, funcResults, funcBody);
<ide>
<ide> const functype = t.typeInstructionFunc(func.params, func.result);
<del> const funcindex = t.indexInFuncSection(t.indexLiteral(nextTypeIndex));
<add> const funcindex = t.indexInFuncSection(nextFuncIndex);
<ide>
<del> const moduleExport = t.moduleExport(
<del> initFuncId.value,
<del> "Func",
<del> t.indexLiteral(nextTypeIndex)
<del> );
<add> const moduleExport = t.moduleExport(initFuncId.value, "Func", nextFuncIndex);
<ide>
<ide> return add(bin, [func, moduleExport, funcindex, functype]);
<ide> };
<ide> class WebAssemblyGenerator {
<ide> const importedGlobals = getImportedGlobals(ast);
<ide> const funcSectionMetadata = t.getSectionMetadata(ast, "func");
<ide> const startAtFuncIndex = getStartFuncIndex(ast);
<add> const nextFuncIndex = getNextFuncIndex(ast);
<ide>
<ide> const transform = compose(
<ide> removeStartFunc(),
<ide> class WebAssemblyGenerator {
<ide> addInitFunction({
<ide> importedGlobals,
<ide> funcSectionMetadata,
<del> startAtFuncIndex
<add> startAtFuncIndex,
<add> nextFuncIndex
<ide> })
<ide> );
<ide> | 1 |
PHP | PHP | improve readability | 0574295121ae6c86266cb2e7d398bc7722904236 | <ide><path>src/Illuminate/Database/Connection.php
<ide> public function select($query, $bindings = [], $useReadPdo = true)
<ide> // For select statements, we'll simply execute the query and return an array
<ide> // of the database result set. Each element in the array will be a single
<ide> // row from the database table, and will either be an array or objects.
<del> $statement = $this->prepared($this->getPdoForSelect($useReadPdo)
<del> ->prepare($query));
<add> $statement = $this->prepared(
<add> $this->getPdoForSelect($useReadPdo)->prepare($query)
<add> );
<ide>
<ide> $this->bindValues($statement, $this->prepareBindings($bindings));
<ide> | 1 |
Python | Python | fix formatting of complex coefficients in poly1d | 0d5e8c8e97e3075b1ccb2c257c998b63fad80903 | <ide><path>numpy/lib/polynomial.py
<ide> from numpy.lib.twodim_base import diag, vander
<ide> from numpy.lib.shape_base import hstack, atleast_1d
<ide> from numpy.lib.function_base import trim_zeros, sort_complex
<add>from numpy.lib.type_check import iscomplex, real, imag
<ide> from numpy.linalg import eigvals, lstsq
<ide>
<ide> class RankWarning(UserWarning):
<ide> def __str__(self):
<ide> coeffs = self.coeffs[NX.logical_or.accumulate(self.coeffs != 0)]
<ide> N = len(coeffs)-1
<ide>
<add> def fmt_float(q):
<add> s = '%.4g' % q
<add> if s.endswith('.0000'):
<add> s = s[:-5]
<add> return s
<add>
<ide> for k in range(len(coeffs)):
<del> coefstr ='%.4g' % abs(coeffs[k])
<del> if coefstr[-4:] == '0000':
<del> coefstr = coefstr[:-5]
<add> if not iscomplex(coeffs[k]):
<add> coefstr = fmt_float(real(coeffs[k]))
<add> elif real(coeffs[k]) == 0:
<add> coefstr = '%sj' % fmt_float(imag(coeffs[k]))
<add> else:
<add> coefstr = '(%s + %sj)' % (fmt_float(real(coeffs[k])),
<add> fmt_float(imag(coeffs[k])))
<add>
<ide> power = (N-k)
<ide> if power == 0:
<ide> if coefstr != '0':
<ide> def __str__(self):
<ide>
<ide> if k > 0:
<ide> if newstr != '':
<del> if coeffs[k] < 0:
<del> thestr = "%s - %s" % (thestr, newstr)
<add> if newstr.startswith('-'):
<add> thestr = "%s - %s" % (thestr, newstr[1:])
<ide> else:
<ide> thestr = "%s + %s" % (thestr, newstr)
<del> elif (k == 0) and (newstr != '') and (coeffs[k] < 0):
<del> thestr = "-%s" % (newstr,)
<ide> else:
<ide> thestr = newstr
<ide> return _raise_power(thestr)
<ide><path>numpy/lib/tests/test_polynomial.py
<ide> >>> print q
<ide> 2
<ide> 3 x + 2 x + 1
<add>>>> print poly1d([1.89999+2j, -3j, -5.12345678, 2+1j])
<add> 3 2
<add>(1.9 + 2j) x - 3j x - 5.123 x + (2 + 1j)
<add>>>> print poly1d([100e-90, 1.234567e-9j+3, -1234.999e8])
<add> 2
<add>1e-88 x + (3 + 1.235e-09j) x - 1.235e+11
<add>>>> print poly1d([-3, -2, -1])
<add> 2
<add>-3 x - 2 x - 1
<ide>
<ide> >>> p(0)
<ide> 3.0 | 2 |
Python | Python | add degree symbol in hddtemp | bbf4cffa8639568fb97789c956d2d0cc8fc8d480 | <ide><path>glances/plugins/glances_hddtemp.py
<ide> def __update__(self):
<ide> device = fields[offset + 1].decode('utf-8')
<ide> device = os.path.basename(device)
<ide> temperature = float(fields[offset + 3].decode('utf-8'))
<add> unit = fields[offset + 4].decode('utf-8')
<ide> hddtemp_current['label'] = device
<ide> hddtemp_current['value'] = temperature
<add> hddtemp_current['unit'] = unit
<ide> self.hddtemp_list.append(hddtemp_current)
<ide>
<ide> def fetch(self): | 1 |
Python | Python | fix language detection | 798040bc1d7073b44c349a4120bdf99a2a7dea99 | <ide><path>spacy/language.py
<ide> def from_config(
<ide> ).merge(config)
<ide> if "nlp" not in config:
<ide> raise ValueError(Errors.E985.format(config=config))
<del> config_lang = config["nlp"]["lang"]
<add> config_lang = config["nlp"].get("lang")
<ide> if config_lang is not None and config_lang != cls.lang:
<ide> raise ValueError(
<ide> Errors.E958.format( | 1 |
Java | Java | add delayerror to maybe.delay | bb3260ec3729d9d9c0934a958f3added8ca65408 | <ide><path>src/main/java/io/reactivex/rxjava3/core/Maybe.java
<ide> public final Single<T> defaultIfEmpty(@NonNull T defaultItem) {
<ide> /**
<ide> * Returns a {@code Maybe} that signals the events emitted by the current {@code Maybe} shifted forward in time by a
<ide> * specified delay.
<add> * An error signal will not be delayed.
<ide> * <p>
<ide> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.png" alt="">
<ide> * <dl>
<ide> public final Single<T> defaultIfEmpty(@NonNull T defaultItem) {
<ide> * @param time
<ide> * the delay to shift the source by
<ide> * @param unit
<del> * the {@link TimeUnit} in which {@code period} is defined
<add> * the {@link TimeUnit} in which {@code time} is defined
<ide> * @return the new {@code Maybe} instance
<ide> * @throws NullPointerException if {@code unit} is {@code null}
<ide> * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
<del> * @see #delay(long, TimeUnit, Scheduler)
<add> * @see #delay(long, TimeUnit, Scheduler, boolean)
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.COMPUTATION)
<ide> @NonNull
<ide> public final Maybe<T> delay(long time, @NonNull TimeUnit unit) {
<del> return delay(time, unit, Schedulers.computation());
<add> return delay(time, unit, Schedulers.computation(), false);
<add> }
<add>
<add> /**
<add> * Returns a {@code Maybe} that signals the events emitted by the current {@code Maybe} shifted forward in time by a
<add> * specified delay.
<add> * <p>
<add> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>This version of {@code delay} operates by default on the {@code computation} {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param time the delay to shift the source by
<add> * @param unit the {@link TimeUnit} in which {@code time} is defined
<add> * @param delayError if {@code true}, both success and error signals are delayed. if {@code false}, only success signals are delayed.
<add> * @return the new {@code Maybe} instance
<add> * @throws NullPointerException if {@code unit} is {@code null}
<add> * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
<add> * @see #delay(long, TimeUnit, Scheduler, boolean)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.COMPUTATION)
<add> @NonNull
<add> public final Maybe<T> delay(long time, @NonNull TimeUnit unit, boolean delayError) {
<add> return delay(time, unit, Schedulers.computation(), delayError);
<add> }
<add>
<add> /**
<add> * Returns a {@code Maybe} that signals the events emitted by the current {@code Maybe} shifted forward in time by a
<add> * specified delay.
<add> * An error signal will not be delayed.
<add> * <p>
<add> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>you specify the {@link Scheduler} where the non-blocking wait and emission happens</dd>
<add> * </dl>
<add> *
<add> * @param time the delay to shift the source by
<add> * @param unit the {@link TimeUnit} in which {@code time} is defined
<add> * @param scheduler the {@code Scheduler} to use for delaying
<add> * @return the new {@code Maybe} instance
<add> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null}
<add> * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
<add> * @see #delay(long, TimeUnit, Scheduler, boolean)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.CUSTOM)
<add> @NonNull
<add> public final Maybe<T> delay(long time, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) {
<add> return delay(time, unit, scheduler, false);
<ide> }
<ide>
<ide> /**
<ide> public final Maybe<T> delay(long time, @NonNull TimeUnit unit) {
<ide> * @param time
<ide> * the delay to shift the source by
<ide> * @param unit
<del> * the time unit of {@code delay}
<add> * the {@link TimeUnit} in which {@code time} is defined
<ide> * @param scheduler
<ide> * the {@code Scheduler} to use for delaying
<add> * @param delayError if {@code true}, both success and error signals are delayed. if {@code false}, only success signals are delayed.
<ide> * @return the new {@code Maybe} instance
<ide> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null}
<ide> * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
<ide> */
<ide> @CheckReturnValue
<ide> @NonNull
<ide> @SchedulerSupport(SchedulerSupport.CUSTOM)
<del> public final Maybe<T> delay(long time, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) {
<add> public final Maybe<T> delay(long time, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, boolean delayError) {
<ide> Objects.requireNonNull(unit, "unit is null");
<ide> Objects.requireNonNull(scheduler, "scheduler is null");
<del> return RxJavaPlugins.onAssembly(new MaybeDelay<>(this, Math.max(0L, time), unit, scheduler));
<add> return RxJavaPlugins.onAssembly(new MaybeDelay<>(this, Math.max(0L, time), unit, scheduler, delayError));
<ide> }
<ide>
<ide> /**
<ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeDelay.java
<ide>
<ide> final Scheduler scheduler;
<ide>
<del> public MaybeDelay(MaybeSource<T> source, long delay, TimeUnit unit, Scheduler scheduler) {
<add> final boolean delayError;
<add>
<add> public MaybeDelay(MaybeSource<T> source, long delay, TimeUnit unit, Scheduler scheduler, boolean delayError) {
<ide> super(source);
<ide> this.delay = delay;
<ide> this.unit = unit;
<ide> this.scheduler = scheduler;
<add> this.delayError = delayError;
<ide> }
<ide>
<ide> @Override
<ide> protected void subscribeActual(MaybeObserver<? super T> observer) {
<del> source.subscribe(new DelayMaybeObserver<>(observer, delay, unit, scheduler));
<add> source.subscribe(new DelayMaybeObserver<>(observer, delay, unit, scheduler, delayError));
<ide> }
<ide>
<ide> static final class DelayMaybeObserver<T>
<ide> protected void subscribeActual(MaybeObserver<? super T> observer) {
<ide>
<ide> final Scheduler scheduler;
<ide>
<add> final boolean delayError;
<add>
<ide> T value;
<ide>
<ide> Throwable error;
<ide>
<del> DelayMaybeObserver(MaybeObserver<? super T> actual, long delay, TimeUnit unit, Scheduler scheduler) {
<add> DelayMaybeObserver(MaybeObserver<? super T> actual, long delay, TimeUnit unit, Scheduler scheduler, boolean delayError) {
<ide> this.downstream = actual;
<ide> this.delay = delay;
<ide> this.unit = unit;
<ide> this.scheduler = scheduler;
<add> this.delayError = delayError;
<ide> }
<ide>
<ide> @Override
<ide> public void onSubscribe(Disposable d) {
<ide> @Override
<ide> public void onSuccess(T value) {
<ide> this.value = value;
<del> schedule();
<add> schedule(delay);
<ide> }
<ide>
<ide> @Override
<ide> public void onError(Throwable e) {
<ide> this.error = e;
<del> schedule();
<add> schedule(delayError ? delay : 0);
<ide> }
<ide>
<ide> @Override
<ide> public void onComplete() {
<del> schedule();
<add> schedule(delay);
<ide> }
<ide>
<del> void schedule() {
<add> void schedule(long delay) {
<ide> DisposableHelper.replace(this, scheduler.scheduleDirect(this, delay, unit));
<ide> }
<ide> }
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeDelayTest.java
<ide> public Maybe<Object> apply(Maybe<Object> f) throws Exception {
<ide> }
<ide> });
<ide> }
<add>
<add> @Test
<add> public void delayedErrorOnSuccess() {
<add> final TestScheduler scheduler = new TestScheduler();
<add> final TestObserver<Integer> observer = Maybe.just(1)
<add> .delay(5, TimeUnit.SECONDS, scheduler, true)
<add> .test();
<add>
<add> scheduler.advanceTimeTo(2, TimeUnit.SECONDS);
<add> observer.assertNoValues();
<add>
<add> scheduler.advanceTimeTo(5, TimeUnit.SECONDS);
<add> observer.assertValue(1);
<add> }
<add>
<add> @Test
<add> public void delayedErrorOnError() {
<add> final TestScheduler scheduler = new TestScheduler();
<add> final TestObserver<?> observer = Maybe.error(new TestException())
<add> .delay(5, TimeUnit.SECONDS, scheduler, true)
<add> .test();
<add>
<add> scheduler.advanceTimeTo(2, TimeUnit.SECONDS);
<add> observer.assertNoErrors();
<add>
<add> scheduler.advanceTimeTo(5, TimeUnit.SECONDS);
<add> observer.assertError(TestException.class);
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/rxjava3/validators/ParamValidationCheckerTest.java
<ide> public void checkParallelFlowable() {
<ide> // negative time is considered as zero time
<ide> addOverride(new ParamOverride(Maybe.class, 0, ParamMode.ANY, "delay", Long.TYPE, TimeUnit.class));
<ide> addOverride(new ParamOverride(Maybe.class, 0, ParamMode.ANY, "delay", Long.TYPE, TimeUnit.class, Scheduler.class));
<add> addOverride(new ParamOverride(Maybe.class, 0, ParamMode.ANY, "delay", Long.TYPE, TimeUnit.class, Boolean.TYPE));
<add> addOverride(new ParamOverride(Maybe.class, 0, ParamMode.ANY, "delay", Long.TYPE, TimeUnit.class, Scheduler.class, Boolean.TYPE));
<ide>
<ide> // zero repeat is allowed
<ide> addOverride(new ParamOverride(Maybe.class, 0, ParamMode.NON_NEGATIVE, "repeat", Long.TYPE)); | 4 |
Ruby | Ruby | fix trivial typo | 2f9c84a604b3288504196e23c95348221a298b35 | <ide><path>actionpack/test/dispatch/system_testing/screenshot_helper_test.rb
<ide> def setup
<ide> assert_match %r|\[Screenshot HTML\].+?tmp/screenshots/1_x\.html|, display_image_actual
<ide> end
<ide>
<del> test "take_screenshot allows changing screeenshot display format via RAILS_SYSTEM_TESTING_SCREENSHOT env" do
<add> test "take_screenshot allows changing screenshot display format via RAILS_SYSTEM_TESTING_SCREENSHOT env" do
<ide> original_output_type = ENV["RAILS_SYSTEM_TESTING_SCREENSHOT"]
<ide> ENV["RAILS_SYSTEM_TESTING_SCREENSHOT"] = "artifact"
<ide>
<ide> def setup
<ide> ENV["RAILS_SYSTEM_TESTING_SCREENSHOT"] = original_output_type
<ide> end
<ide>
<del> test "take_screenshot allows changing screeenshot display format via screenshot: kwarg" do
<add> test "take_screenshot allows changing screenshot display format via screenshot: kwarg" do
<ide> display_image_actual = nil
<ide>
<ide> Rails.stub :root, Pathname.getwd do | 1 |
PHP | PHP | fix long line | 0836e3284269c8dc7e313cfd5be849c147f7f5a3 | <ide><path>src/Http/Middleware/CsrfProtectionMiddleware.php
<ide> protected function _createToken(): string
<ide> * @param \Psr\Http\Message\ResponseInterface $response The response.
<ide> * @return \Psr\Http\Message\ResponseInterface $response Modified response.
<ide> */
<del> protected function _addTokenCookie(string $token, ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
<del> {
<add> protected function _addTokenCookie(
<add> string $token,
<add> ServerRequestInterface $request,
<add> ResponseInterface $response
<add> ): ResponseInterface {
<ide> $cookie = Cookie::create(
<ide> $this->_config['cookieName'],
<ide> $token, | 1 |
Ruby | Ruby | show upgrade command on formula parameters | 4aacf5400e08860ebd6e579c38a08f02d386a65d | <ide><path>Library/Homebrew/cmd/update.rb
<ide> module Homebrew extend self
<ide> DEPRECATED_TAPS = ['adamv-alt']
<ide>
<ide> def update
<del> abort "This command updates brew itself, and does not take formula names." unless ARGV.named.empty?
<add> unless ARGV.named.empty?
<add> abort <<-EOS.undent
<add> This command updates brew itself, and does not take formula names.
<add> Use `brew upgrade <formula>`.
<add> EOS
<add> end
<ide> abort "Please `brew install git' first." unless which "git"
<ide>
<ide> # ensure GIT_CONFIG is unset as we need to operate on .git/config | 1 |
Text | Text | add contents table to contributing.md | 639ec8314e7de10fabe0f0eade2b4b63bdce9329 | <ide><path>CONTRIBUTING.md
<ide> small and all contributions are valued.
<ide> This guide explains the process for contributing to the Node.js project's core
<ide> `nodejs/node` GitHub Repository and describes what to expect at each step.
<ide>
<add>## Contents
<add>
<add>* [Code of Conduct](#code-of-conduct)
<add>* [Issues](#issues)
<add>* [Pull Requests](#pull-requests)
<add>* [Developer's Certificate of Origin 1.1](#developers-certificate-of-origin-11)
<add>
<ide> ## [Code of Conduct](./doc/guides/contributing/coc.md)
<ide>
<ide> The Node.js project has a | 1 |
Go | Go | allow readby and tracedby | b36455258f323448c0cf00d39bccfd14584ed500 | <ide><path>profiles/apparmor/template.go
<ide> profile {{.Name}} flags=(attach_disconnected,mediate_deleted) {
<ide>
<ide> {{if ge .Version 208095}}
<ide> # suppress ptrace denials when using 'docker ps' or using 'ps' inside a container
<del> ptrace (trace,read) peer={{.Name}},
<add> ptrace (trace,read,tracedby,readby) peer={{.Name}},
<ide> {{end}}
<ide> }
<ide> ` | 1 |
Python | Python | fix pieces argument to precomputedmaxout | b27c5878005fddb749bf36eabfb4497135b91bdf | <ide><path>spacy/_ml.py
<ide> def backward(dY_ids, sgd=None):
<ide> d_b=Gradient("b")
<ide> )
<ide> class PrecomputableMaxouts(Model):
<del> def __init__(self, nO=None, nI=None, nF=None, pieces=3, **kwargs):
<add> def __init__(self, nO=None, nI=None, nF=None, nP=3, **kwargs):
<ide> Model.__init__(self, **kwargs)
<ide> self.nO = nO
<del> self.nP = pieces
<add> self.nP = nP
<ide> self.nI = nI
<ide> self.nF = nF
<ide> | 1 |
Ruby | Ruby | fix indentation mismatches | dc07c0e02b16031e5ff7cf650f0894654d525a03 | <ide><path>activeresource/test/base_test.rb
<ide> def test_create
<ide> end
<ide>
<ide> def test_clone
<del> matz = Person.find(1)
<del> matz_c = matz.clone
<del> assert matz_c.new?
<del> matz.attributes.each do |k, v|
<del> assert_equal v, matz_c.send(k) if k != Person.primary_key
<del> end
<del> end
<del>
<del> def test_nested_clone
<del> addy = StreetAddress.find(1, :params => {:person_id => 1})
<del> addy_c = addy.clone
<del> assert addy_c.new?
<del> addy.attributes.each do |k, v|
<del> assert_equal v, addy_c.send(k) if k != StreetAddress.primary_key
<del> end
<del> assert_equal addy.prefix_options, addy_c.prefix_options
<del> end
<del>
<del> def test_complex_clone
<del> matz = Person.find(1)
<del> matz.address = StreetAddress.find(1, :params => {:person_id => matz.id})
<del> matz.non_ar_hash = {:not => "an ARes instance"}
<del> matz.non_ar_arr = ["not", "ARes"]
<del> matz_c = matz.clone
<del> assert matz_c.new?
<del> assert_raises(NoMethodError) {matz_c.address}
<del> assert_equal matz.non_ar_hash, matz_c.non_ar_hash
<del> assert_equal matz.non_ar_arr, matz_c.non_ar_arr
<del>
<del> # Test that actual copy, not just reference copy
<del> matz.non_ar_hash[:not] = "changed"
<del> assert_not_equal matz.non_ar_hash, matz_c.non_ar_hash
<del> end
<add> matz = Person.find(1)
<add> matz_c = matz.clone
<add> assert matz_c.new?
<add> matz.attributes.each do |k, v|
<add> assert_equal v, matz_c.send(k) if k != Person.primary_key
<add> end
<add> end
<add>
<add> def test_nested_clone
<add> addy = StreetAddress.find(1, :params => {:person_id => 1})
<add> addy_c = addy.clone
<add> assert addy_c.new?
<add> addy.attributes.each do |k, v|
<add> assert_equal v, addy_c.send(k) if k != StreetAddress.primary_key
<add> end
<add> assert_equal addy.prefix_options, addy_c.prefix_options
<add> end
<add>
<add> def test_complex_clone
<add> matz = Person.find(1)
<add> matz.address = StreetAddress.find(1, :params => {:person_id => matz.id})
<add> matz.non_ar_hash = {:not => "an ARes instance"}
<add> matz.non_ar_arr = ["not", "ARes"]
<add> matz_c = matz.clone
<add> assert matz_c.new?
<add> assert_raises(NoMethodError) {matz_c.address}
<add> assert_equal matz.non_ar_hash, matz_c.non_ar_hash
<add> assert_equal matz.non_ar_arr, matz_c.non_ar_arr
<add>
<add> # Test that actual copy, not just reference copy
<add> matz.non_ar_hash[:not] = "changed"
<add> assert_not_equal matz.non_ar_hash, matz_c.non_ar_hash
<add> end
<ide>
<ide> def test_update
<ide> matz = Person.find(:first)
<ide> def test_exists
<ide> def test_exists_with_redefined_to_param
<ide> Person.module_eval do
<ide> alias_method :original_to_param_exists, :to_param
<del> def to_param
<del> name
<del> end
<add> def to_param
<add> name
<add> end
<ide> end
<ide>
<ide> # Class method.
<ide> def to_param
<ide> # Nested instance method.
<ide> assert StreetAddress.find(1, :params => { :person_id => Person.find('Greg').to_param }).exists?
<ide>
<del> ensure
<del> # revert back to original
<del> Person.module_eval do
<del> # save the 'new' to_param so we don't get a warning about discarding the method
<del> alias_method :exists_to_param, :to_param
<del> alias_method :to_param, :original_to_param_exists
<del> end
<add> ensure
<add> # revert back to original
<add> Person.module_eval do
<add> # save the 'new' to_param so we don't get a warning about discarding the method
<add> alias_method :exists_to_param, :to_param
<add> alias_method :to_param, :original_to_param_exists
<add> end
<ide> end
<ide>
<ide> def test_to_xml
<ide><path>activeresource/test/format_test.rb
<ide> def test_setting_format_before_site
<ide> end
<ide>
<ide> def test_serialization_of_nested_resource
<del> address = { :street => '12345 Street' }
<del> person = { :name=> 'Rus', :address => address}
<add> address = { :street => '12345 Street' }
<add> person = { :name=> 'Rus', :address => address}
<ide>
<del> [:json, :xml].each do |format|
<del> encoded_person = ActiveResource::Formats[format].encode(person)
<del> assert_match(/12345 Street/, encoded_person)
<del> remote_person = Person.new(person.update({:address => StreetAddress.new(address)}))
<del> assert_kind_of StreetAddress, remote_person.address
<del> using_format(Person, format) do
<del> ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, encoded_person, 201, {'Location' => "/people/5.#{format}"}
<del> remote_person.save
<del> end
<del> end
<del> end
<add> [:json, :xml].each do |format|
<add> encoded_person = ActiveResource::Formats[format].encode(person)
<add> assert_match(/12345 Street/, encoded_person)
<add> remote_person = Person.new(person.update({:address => StreetAddress.new(address)}))
<add> assert_kind_of StreetAddress, remote_person.address
<add> using_format(Person, format) do
<add> ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, encoded_person, 201, {'Location' => "/people/5.#{format}"}
<add> remote_person.save
<add> end
<add> end
<add> end
<ide>
<ide> private
<ide> def using_format(klass, mime_type_reference) | 2 |
Javascript | Javascript | remove the `webkiturl` polyfill | 8266cc18e7076f961c2c66e592c992705b2a9b6b | <ide><path>src/shared/compatibility.js
<ide> if (typeof PDFJS === 'undefined') {
<ide>
<ide> PDFJS.compatibilityChecked = true;
<ide>
<del>// URL = URL || webkitURL
<del>// Support: Safari<7, Android 4.2+
<del>(function normalizeURLObject() {
<del> if (!globalScope.URL) {
<del> globalScope.URL = globalScope.webkitURL;
<del> }
<del>})();
<del>
<ide> // No XMLHttpRequest#response?
<ide> // Support: IE<11, Android <4.0
<ide> (function checkXMLHttpRequestResponseCompatibility() { | 1 |
Ruby | Ruby | fix error when using older/no clang | 3717815adec94d952115cb8461c544170458fec0 | <ide><path>Library/Homebrew/extend/ENV/std.rb
<ide> def determine_cxx
<ide> def clang
<ide> super
<ide> replace_in_cflags(/-Xarch_#{Hardware::CPU.arch_32_bit} (-march=\S*)/, '\1')
<del> map = Hardware::CPU.optimization_flags
<add> map = Hardware::CPU.optimization_flags.dup
<ide> if DevelopmentTools.clang_build_version < 700
<ide> # Clang mistakenly enables AES-NI on plain Nehalem
<ide> map[:nehalem] = "-march=nehalem -Xclang -target-feature -Xclang -aes" | 1 |
PHP | PHP | fix failing test | c1d7da92a92f7f297c98bfa9b86a1cc3b37209f8 | <ide><path>tests/Database/DatabaseConnectionTest.php
<ide> public function testTransactionRetriesOnSerializationFailure()
<ide>
<ide> $pdo = $this->getMockBuilder(DatabaseConnectionTestMockPDO::class)->setMethods(['beginTransaction', 'commit', 'rollBack'])->getMock();
<ide> $mock = $this->getMockConnection([], $pdo);
<del> $pdo->method('commit')->will($this->throwException(new DatabaseConnectionTestMockPDOException('Serialization failure', '40001')));
<add> $pdo->expects($this->exactly(3))->method('commit')->will($this->throwException(new DatabaseConnectionTestMockPDOException('Serialization failure', '40001')));
<ide> $pdo->expects($this->exactly(3))->method('beginTransaction');
<del> $pdo->expects($this->never())->method('rollBack');
<del> $pdo->expects($this->exactly(3))->method('commit');
<ide> $mock->transaction(function () {
<ide> }, 3);
<ide> } | 1 |
PHP | PHP | fix expiration on cookie sessions | 453f504c449af9aa77b8b5a13fb065a7d7f06952 | <ide><path>src/Illuminate/Session/CookieSessionHandler.php
<ide>
<ide> namespace Illuminate\Session;
<ide>
<add>use Carbon\Carbon;
<ide> use SessionHandlerInterface;
<ide> use Symfony\Component\HttpFoundation\Request;
<ide> use Illuminate\Contracts\Cookie\QueueingFactory as CookieJar;
<ide> public function close()
<ide> */
<ide> public function read($sessionId)
<ide> {
<del> return $this->request->cookies->get($sessionId) ?: '';
<add> $value = $this->request->cookies->get($sessionId) ?: '';
<add>
<add> if (! is_null($decoded = json_decode($value, true)) && is_array($decoded)) {
<add> if (isset($decoded['expires']) && time() <= $decoded['expires']) {
<add> return $decoded['data'];
<add> }
<add> }
<add>
<add> return $value;
<ide> }
<ide>
<ide> /**
<ide> * {@inheritdoc}
<ide> */
<ide> public function write($sessionId, $data)
<ide> {
<del> $this->cookie->queue($sessionId, $data, $this->minutes);
<add> $this->cookie->queue($sessionId, json_encode([
<add> 'data' => $data,
<add> 'expires' => Carbon::now()->addMinutes($this->minutes)->getTimestamp()
<add> ]), $this->minutes);
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | set version to v2.1.5 | 3bc4d618f920998e76cc5302a1ce79d285cdc5c3 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy"
<del>__version__ = "2.1.5.dev0"
<add>__version__ = "2.1.5"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI"
<ide> __email__ = "contact@explosion.ai"
<ide> __license__ = "MIT"
<del>__release__ = False
<add>__release__ = True
<ide>
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Ruby | Ruby | add back user and repo method | 842c0227bc7f69211a1feaa6f34c8a85c925c139 | <ide><path>Library/Homebrew/exceptions.rb
<ide> def to_s
<ide> end
<ide>
<ide> class TapFormulaUnavailableError < FormulaUnavailableError
<del> attr_reader :tap
<add> attr_reader :tap, :user, :repo
<ide>
<ide> def initialize tap, name
<ide> @tap = tap
<add> @user = tap.user
<add> @repo = tap.repo
<ide> super "#{tap}/#{name}"
<ide> end
<ide> | 1 |
Mixed | Text | replace 'rake' with 'rails_command' | 1a5941e3cfb67056a9468d590f8ae03485f75ccc | <ide><path>guides/source/rails_application_templates.md
<ide> $ rails new blog -m ~/template.rb
<ide> $ rails new blog -m http://example.com/template.rb
<ide> ```
<ide>
<del>You can use the rake task `rails:template` to apply templates to an existing Rails application. The location of the template needs to be passed in to an environment variable named LOCATION. Again, this can either be path to a file or a URL.
<add>You can use the task `rails:template` to apply templates to an existing Rails application. The location of the template needs to be passed in to an environment variable named LOCATION. Again, this can either be path to a file or a URL.
<ide>
<ide> ```bash
<ide> $ bin/rails rails:template LOCATION=~/template.rb
<ide> The Rails templates API is easy to understand. Here's an example of a typical Ra
<ide> # template.rb
<ide> generate(:scaffold, "person name:string")
<ide> route "root to: 'people#index'"
<del>rake("db:migrate")
<add>rails_command("db:migrate")
<ide>
<ide> after_bundle do
<ide> git :init
<ide> Executes an arbitrary command. Just like the backticks. Let's say you want to re
<ide> run "rm README.rdoc"
<ide> ```
<ide>
<del>### rake(command, options = {})
<add>### rails_command(command, options = {})
<ide>
<del>Runs the supplied rake tasks in the Rails application. Let's say you want to migrate the database:
<add>Runs the supplied task in the Rails application. Let's say you want to migrate the database:
<ide>
<ide> ```ruby
<del>rake "db:migrate"
<add>rails_command "db:migrate"
<ide> ```
<ide>
<del>You can also run rake tasks with a different Rails environment:
<add>You can also run tasks with a different Rails environment:
<ide>
<ide> ```ruby
<del>rake "db:migrate", env: 'production'
<add>rails_command "db:migrate", env: 'production'
<add>```
<add>
<add>You can also run tasks as a super-user:
<add>
<add>```ruby
<add>rails_command "log:clear", sudo: true
<ide> ```
<ide>
<ide> ### route(routing_code)
<ide> CODE
<ide> These methods let you ask questions from templates and decide the flow based on the user's answer. Let's say you want to Freeze Rails only if the user wants to:
<ide>
<ide> ```ruby
<del>rake("rails:freeze:gems") if yes?("Freeze rails gems?")
<add>rails_command("rails:freeze:gems") if yes?("Freeze rails gems?")
<ide> # no?(question) acts just the opposite.
<ide> ```
<ide>
<ide><path>railties/CHANGELOG.md
<add>* Alias `rake` with `rails_command` in the Rails Application Templates API
<add> following Rails 5 convention of preferring "rails" to "rake" to run tasks.
<add>
<add> *claudiob*
<add>
<ide> * Change fail fast of `bin/rails test` interrupts run on error.
<ide>
<ide> *Yuji Yaginuma*
<ide><path>railties/lib/rails/generators/actions.rb
<ide> def rake(command, options={})
<ide> sudo = options[:sudo] && RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ ? 'sudo ' : ''
<ide> in_root { run("#{sudo}#{extify(:rake)} #{command} RAILS_ENV=#{env}", verbose: false) }
<ide> end
<add> alias :rails_command :rake
<ide>
<ide> # Just run the capify command in root
<ide> #
<ide><path>railties/test/generators/actions_test.rb
<ide> def test_rake_with_sudo_option_should_run_rake_command_with_sudo
<ide> end
<ide> end
<ide>
<add> def test_rails_command_should_run_rails_command_with_default_env
<add> assert_called_with(generator, :run, ["rake log:clear RAILS_ENV=development", verbose: false]) do
<add> with_rails_env nil do
<add> action :rails_command, 'log:clear'
<add> end
<add> end
<add> end
<add>
<add> def test_rails_command_with_env_option_should_run_rails_command_in_env
<add> assert_called_with(generator, :run, ['rake log:clear RAILS_ENV=production', verbose: false]) do
<add> action :rails_command, 'log:clear', env: 'production'
<add> end
<add> end
<add>
<add> def test_rails_command_with_rails_env_variable_should_run_rails_command_in_env
<add> assert_called_with(generator, :run, ['rake log:clear RAILS_ENV=production', verbose: false]) do
<add> with_rails_env "production" do
<add> action :rails_command, 'log:clear'
<add> end
<add> end
<add> end
<add>
<add> def test_env_option_should_win_over_rails_env_variable_when_running_rails
<add> assert_called_with(generator, :run, ['rake log:clear RAILS_ENV=production', verbose: false]) do
<add> with_rails_env "staging" do
<add> action :rails_command, 'log:clear', env: 'production'
<add> end
<add> end
<add> end
<add>
<add> def test_rails_command_with_sudo_option_should_run_rails_command_with_sudo
<add> assert_called_with(generator, :run, ["sudo rake log:clear RAILS_ENV=development", verbose: false]) do
<add> with_rails_env nil do
<add> action :rails_command, 'log:clear', sudo: true
<add> end
<add> end
<add> end
<add>
<ide> def test_capify_should_run_the_capify_command
<ide> assert_called_with(generator, :run, ['capify .', verbose: false]) do
<ide> action :capify! | 4 |
PHP | PHP | fix sqs queue for 7.2 | c55de5e654d136bc24ca126aca4f5daf87491faa | <ide><path>src/Illuminate/Queue/SqsQueue.php
<ide> public function pop($queue = null)
<ide> 'AttributeNames' => ['ApproximateReceiveCount'],
<ide> ]);
<ide>
<del> if (count($response['Messages']) > 0) {
<add> if (! is_null($response['Messages']) && count($response['Messages']) > 0) {
<ide> return new SqsJob(
<ide> $this->container, $this->sqs, $response['Messages'][0],
<ide> $this->connectionName, $queue
<ide><path>tests/Queue/QueueSqsQueueTest.php
<ide> public function setUp()
<ide> ],
<ide> ]);
<ide>
<add> $this->mockedReceiveEmptyMessageResponseModel = new Result([
<add> 'Messages' => null,
<add> ]);
<add>
<ide> $this->mockedQueueAttributesResponseModel = new Result([
<ide> 'Attributes' => [
<ide> 'ApproximateNumberOfMessages' => 1,
<ide> public function testPopProperlyPopsJobOffOfSqs()
<ide> $this->assertInstanceOf('Illuminate\Queue\Jobs\SqsJob', $result);
<ide> }
<ide>
<add> public function testPopProperlyHandlesEmptyMessage()
<add> {
<add> $queue = $this->getMockBuilder('Illuminate\Queue\SqsQueue')->setMethods(['getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock();
<add> $queue->setContainer(m::mock('Illuminate\Container\Container'));
<add> $queue->expects($this->once())->method('getQueue')->with($this->queueName)->will($this->returnValue($this->queueUrl));
<add> $this->sqs->shouldReceive('receiveMessage')->once()->with(['QueueUrl' => $this->queueUrl, 'AttributeNames' => ['ApproximateReceiveCount']])->andReturn($this->mockedReceiveEmptyMessageResponseModel);
<add> $result = $queue->pop($this->queueName);
<add> $this->assertNull($result);
<add> }
<add>
<ide> public function testDelayedPushWithDateTimeProperlyPushesJobOntoSqs()
<ide> {
<ide> $now = \Illuminate\Support\Carbon::now(); | 2 |
Ruby | Ruby | remove unnecessary use of instance_eval | ef0920e01d171497a45226bd8ab83b17c3151376 | <ide><path>Library/Homebrew/formula.rb
<ide> def std_cmake_args
<ide>
<ide> def python(options={:allowed_major_versions => [2, 3]}, &block)
<ide> require 'python_helper'
<del> self.instance_eval{ python_helper(options, &block) }
<add> python_helper(options, &block)
<ide> end
<ide>
<ide> # Explicitly only execute the block for 2.x (if a python 2.x is available) | 1 |
Text | Text | add missing word in stream.md | 3622a97715858dc7e6aead57b605189c9cad0337 | <ide><path>doc/api/stream.md
<ide> that the stream will *remain* paused once those destinations drain and ask for
<ide> more data.
<ide>
<ide> *Note*: If a [Readable][] is switched into flowing mode and there are no
<del>consumers available handle the data, that data will be lost. This can occur,
<add>consumers available to handle the data, that data will be lost. This can occur,
<ide> for instance, when the `readable.resume()` method is called without a listener
<ide> attached to the `'data'` event, or when a `'data'` event handler is removed
<ide> from the stream. | 1 |
Javascript | Javascript | fix issue with parametername | f017384f1d7541cfebd270c3a9ae05560ee589e9 | <ide><path>src/renderers/webgl/WebGLProgramCache.js
<ide> THREE.WebGLProgramCache = function ( renderer1, gl, extensions ) {
<ide> PointCloudMaterial: 'particle_basic'
<ide> };
<ide>
<del> var parameterNames = [ " precision", "supportsVertexTextures", "map", "envMap", "envMapMode", "lightMap", "aoMap", "emissiveMap", "bumpMap", "normalMap", "specularMap", "alphaMap", "combine",
<add> var parameterNames = [ "precision", "supportsVertexTextures", "map", "envMap", "envMapMode", "lightMap", "aoMap", "emissiveMap", "bumpMap", "normalMap", "specularMap", "alphaMap", "combine",
<ide> "vertexColors", "fog", "useFog", "fogExp", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
<ide> "maxMorphTargets", "maxMorphNormals", "maxDirLights", "maxPointLights", "maxSpotLights", "maxHemiLights", "maxShadows", "shadowMapEnabled", "shadowMapType", "shadowMapDebug",
<ide> "alphaTest", "metal", "doubleSided", "flipSided" ]; | 1 |
Javascript | Javascript | add is_valid tests | 8c30898671b0dd1a5fa6e4b77b4a9f4ef81c8ea6 | <ide><path>test/moment/is_valid.js
<ide> exports.isValid = {
<ide> test.done();
<ide> },
<ide>
<add> '24:00:00.000 is valid' : function (test) {
<add> test.equal(moment('2014-01-01 24', 'YYYY-MM-DD HH').isValid(), true, '24 is valid');
<add> test.equal(moment('2014-01-01 24:00', 'YYYY-MM-DD HH:mm').isValid(), true, '24:00 is valid');
<add> test.equal(moment('2014-01-01 24:01', 'YYYY-MM-DD HH:mm').isValid(), false, '24:01 is not valid');
<add> test.done();
<add> },
<add>
<ide> 'oddball permissiveness' : function (test) {
<ide> //https://github.com/moment/moment/issues/1128
<ide> test.ok(moment('2010-10-3199', ['MM/DD/YYYY', 'MM-DD-YYYY', 'YYYY-MM-DD']).isValid()); | 1 |
PHP | PHP | add stderr example | 66f5757d58cb3f6d1152ec2d5f12e247eb2242e2 | <ide><path>config/logging.php
<ide> <?php
<ide>
<add>use Monolog\Handler\StreamHandler;
<add>
<ide> return [
<ide>
<ide> /*
<ide> 'level' => 'critical',
<ide> ],
<ide>
<add> 'stderr' => [
<add> 'driver' => 'monolog',
<add> 'handler' => StreamHandler::class,
<add> 'with' => [
<add> 'stream' => 'php://stderr',
<add> ],
<add> ],
<add>
<ide> 'syslog' => [
<ide> 'driver' => 'syslog',
<ide> 'level' => 'debug', | 1 |
PHP | PHP | replace parse_url() with a regex | 519b0ce66f3c43206ed9b8e026a928ef2339d3ff | <ide><path>src/Core/StaticConfigTrait.php
<ide> public static function parseDsn($dsn)
<ide> throw new InvalidArgumentException('Only strings can be passed to parseDsn');
<ide> }
<ide>
<del> $scheme = '';
<del> if (preg_match("/^([\w\\\]+)/", $dsn, $matches)) {
<del> $scheme = $matches[1];
<del> $dsn = preg_replace("/^([\w\\\]+)/", 'file', $dsn);
<del> }
<add> $pattern = '/^(?P<scheme>[\w\\\\]+):\/\/((?P<user>.*?)(:(?P<password>.*?))?@)?' .
<add> '((?P<host>[.\w\\\\]+)(:(?P<port>\d+))?)?' .
<add> '(?P<path>\/[^?]*)?(\?(?P<query>.*))?$/';
<add> preg_match($pattern, $dsn, $parsed);
<ide>
<del> $parsed = parse_url($dsn);
<del> if ($parsed === false) {
<del> return $dsn;
<add> if (empty($parsed)) {
<add> return false;
<add> }
<add> foreach ($parsed as $k => $v) {
<add> if (is_int($k)) {
<add> unset($parsed[$k]);
<add> }
<add> if ($v === '') {
<add> unset($parsed[$k]);
<add> }
<ide> }
<ide>
<del> $parsed['scheme'] = $scheme;
<ide> $query = '';
<ide>
<ide> if (isset($parsed['query'])) {
<ide><path>tests/TestCase/Datasource/ConnectionManagerTest.php
<ide> public function testParseDsnClassnameDriver()
<ide> $this->assertEquals($expected, ConnectionManager::parseDsn($dsn));
<ide> }
<ide>
<add> /**
<add> * Test parseDsn with special characters in the password.
<add> *
<add> * @return void
<add> */
<add> public function testParseDsnSpecialPassword()
<add> {
<add> $dsn = 'mysql://user:pas#][{}$%20@!@localhost:3306/database?log=1"eIdentifiers=1';
<add> $expected = [
<add> 'className' => 'Cake\Database\Connection',
<add> 'database' => 'database',
<add> 'driver' => 'Cake\Database\Driver\Mysql',
<add> 'host' => 'localhost',
<add> 'password' => 'pas#][{}$%20@!',
<add> 'port' => 3306,
<add> 'scheme' => 'mysql',
<add> 'username' => 'user',
<add> 'log' => 1,
<add> 'quoteIdentifiers' => 1
<add> ];
<add> $this->assertEquals($expected, ConnectionManager::parseDsn($dsn));
<add> }
<add>
<ide> /**
<ide> * Tests that directly setting an instance in a config, will not return a different
<ide> * instance later on | 2 |
Javascript | Javascript | update components for webpack | b7c2db0e852bef302a14806dcc693cfd73b72e77 | <ide><path>glances/outputs/static/js/components/glances/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glances', {
<add>import GlancesController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glances', {
<ide> controller: GlancesController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/glances/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/glances/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesController($scope, GlancesStats, hotkeys, ARGUMENTS) {
<add>export default function GlancesController($scope, GlancesStats, hotkeys, ARGUMENTS) {
<ide> var vm = this;
<ide> vm.dataLoaded = false;
<ide> vm.arguments = ARGUMENTS;
<ide><path>glances/outputs/static/js/components/help/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesHelp', {
<add>import GlancesHelpController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesHelp', {
<ide> controller: GlancesHelpController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/help/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/help/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesHelpController($http) {
<add>export default function GlancesHelpController($http) {
<ide> var vm = this;
<ide>
<ide> $http.get('api/2/help').then(function (response) {
<ide><path>glances/outputs/static/js/components/index.js
<add>
<add>// import all components
<add>
<add>import './glances/component';
<add>import './help/component';
<add>import './plugin-alert/component';
<add>import './plugin-amps/component';
<add>import './plugin-cloud/component';
<add>import './plugin-cpu/component';
<add>import './plugin-diskio/component';
<add>import './plugin-docker/component';
<add>import './plugin-folders/component';
<add>import './plugin-fs/component';
<add>import './plugin-gpu/component';
<add>import './plugin-ip/component';
<add>import './plugin-irq/component';
<add>import './plugin-load/component';
<add>import './plugin-mem/component';
<add>import './plugin-mem-more/component';
<add>import './plugin-memswap/component';
<add>import './plugin-network/component';
<add>import './plugin-percpu/component';
<add>import './plugin-ports/component';
<add>import './plugin-process/component';
<add>import './plugin-processcount/component';
<add>import './plugin-processlist/component';
<add>import './plugin-quicklook/component';
<add>import './plugin-raid/component';
<add>import './plugin-sensors/component';
<add>import './plugin-system/component';
<add>import './plugin-uptime/component';
<add>import './plugin-wifi/component';
<ide><path>glances/outputs/static/js/components/plugin-alert/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginAlert', {
<add>import GlancesPluginAlertController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginAlert', {
<ide> controller: GlancesPluginAlertController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-alert/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-alert/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginAlertController($scope, favicoService) {
<add>export default function GlancesPluginAlertController($scope, favicoService) {
<ide> var vm = this;
<ide> var _alerts = [];
<ide>
<ide><path>glances/outputs/static/js/components/plugin-amps/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginAmps', {
<add>import GlancesPluginAmpsController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginAmps', {
<ide> controller: GlancesPluginAmpsController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-amps/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-amps/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginAmpsController($scope, GlancesStats, favicoService) {
<add>export default function GlancesPluginAmpsController($scope, GlancesStats, favicoService) {
<ide> var vm = this;
<ide> vm.processes = [];
<ide>
<ide><path>glances/outputs/static/js/components/plugin-cloud/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginCloud', {
<add>import GlancesPluginCloudController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginCloud', {
<ide> controller: GlancesPluginCloudController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-cloud/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-cloud/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginCloudController($scope, GlancesStats) {
<add>export default function GlancesPluginCloudController($scope, GlancesStats) {
<ide> var vm = this;
<ide>
<ide> vm.provider = null;
<ide><path>glances/outputs/static/js/components/plugin-cpu/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginCpu', {
<add>import GlancesPluginCpuController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginCpu', {
<ide> controller: GlancesPluginCpuController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-cpu/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-cpu/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginCpuController($scope, GlancesStats) {
<add>export default function GlancesPluginCpuController($scope, GlancesStats) {
<ide> var vm = this;
<ide> var _view = {};
<ide>
<ide><path>glances/outputs/static/js/components/plugin-diskio/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginDiskio', {
<add>import GlancesPluginDiskioController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginDiskio', {
<ide> controller: GlancesPluginDiskioController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-diskio/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-diskio/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginDiskioController($scope, $filter, GlancesStats, ARGUMENTS) {
<add>export default function GlancesPluginDiskioController($scope, $filter, GlancesStats, ARGUMENTS) {
<ide> var vm = this;
<ide> vm.arguments = ARGUMENTS;
<ide> vm.disks = [];
<ide><path>glances/outputs/static/js/components/plugin-docker/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginDocker', {
<add>import GlancesPluginDockerController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginDocker', {
<ide> controller: GlancesPluginDockerController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-docker/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-docker/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginDockerController($scope, GlancesStats) {
<add>export default function GlancesPluginDockerController($scope, GlancesStats) {
<ide> var vm = this;
<ide> vm.containers = [];
<ide> vm.version = null;
<ide><path>glances/outputs/static/js/components/plugin-folders/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginFolders', {
<add>import GlancesPluginFsController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginFolders', {
<ide> controller: GlancesPluginFsController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-folders/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-folders/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginFoldersController($scope, GlancesStats) {
<add>export default function GlancesPluginFoldersController($scope, GlancesStats) {
<ide> var vm = this;
<ide> vm.folders = [];
<ide>
<ide><path>glances/outputs/static/js/components/plugin-fs/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginFs', {
<add>import GlancesPluginFsController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginFs', {
<ide> controller: GlancesPluginFsController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-fs/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-fs/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginFsController($scope, $filter, GlancesStats, ARGUMENTS) {
<add>export default function GlancesPluginFsController($scope, $filter, GlancesStats, ARGUMENTS) {
<ide> var vm = this;
<ide> var _view = {};
<ide> vm.arguments = ARGUMENTS;
<ide> function GlancesPluginFsController($scope, $filter, GlancesStats, ARGUMENTS) {
<ide> shortMountPoint = '_' + fsData['mnt_point'].slice(-8);
<ide> }
<ide>
<del> vm.fileSystems.push(fs = {
<add> vm.fileSystems.push({
<ide> 'name': fsData['device_name'],
<ide> 'mountPoint': fsData['mnt_point'],
<ide> 'shortMountPoint': shortMountPoint,
<ide><path>glances/outputs/static/js/components/plugin-gpu/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginGpu', {
<add>import GlancesPluginGpuController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginGpu', {
<ide> controller: GlancesPluginGpuController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-gpu/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-gpu/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginGpuController($scope, GlancesStats, ARGUMENTS) {
<add>export default function GlancesPluginGpuController($scope, GlancesStats, ARGUMENTS) {
<ide> var vm = this;
<ide> vm.arguments = ARGUMENTS;
<ide> var _view = {};
<ide><path>glances/outputs/static/js/components/plugin-ip/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginIp', {
<add>import GlancesPluginIpController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginIp', {
<ide> controller: GlancesPluginIpController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-ip/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-ip/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginIpController($scope, GlancesStats, ARGUMENTS) {
<add>export default function GlancesPluginIpController($scope, GlancesStats, ARGUMENTS) {
<ide> var vm = this;
<ide> vm.arguments = ARGUMENTS;
<ide>
<ide><path>glances/outputs/static/js/components/plugin-irq/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginIrq', {
<add>import GlancesPluginIrqController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginIrq', {
<ide> controller: GlancesPluginIrqController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-irq/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-irq/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginIrqController($scope, GlancesStats) {
<add>export default function GlancesPluginIrqController($scope, GlancesStats) {
<ide> var vm = this;
<ide> vm.irqs = [];
<ide>
<ide><path>glances/outputs/static/js/components/plugin-load/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginLoad', {
<add>import GlancesPluginLoadController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginLoad', {
<ide> controller: GlancesPluginLoadController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-load/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-load/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginLoadController($scope, GlancesStats) {
<add>export default function GlancesPluginLoadController($scope, GlancesStats) {
<ide> var vm = this;
<ide> var _view = {};
<ide>
<ide><path>glances/outputs/static/js/components/plugin-mem-more/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginMemMore', {
<add>import GlancesPluginMemMoreController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginMemMore', {
<ide> controller: GlancesPluginMemMoreController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-mem-more/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-mem-more/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginMemMoreController($scope, GlancesStats) {
<add>export default function GlancesPluginMemMoreController($scope, GlancesStats) {
<ide> var vm = this;
<ide>
<ide> vm.active = null;
<ide><path>glances/outputs/static/js/components/plugin-mem/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginMem', {
<add>import GlancesPluginMemController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginMem', {
<ide> controller: GlancesPluginMemController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-mem/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-mem/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginMemController($scope, GlancesStats) {
<add>export default function GlancesPluginMemController($scope, GlancesStats) {
<ide> var vm = this;
<ide> var _view = {};
<ide>
<ide><path>glances/outputs/static/js/components/plugin-memswap/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginMemswap', {
<add>import GlancesPluginMemswapController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginMemswap', {
<ide> controller: GlancesPluginMemswapController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-memswap/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-memswap/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginMemswapController($scope, GlancesStats) {
<add>export default function GlancesPluginMemswapController($scope, GlancesStats) {
<ide> var vm = this;
<ide> var _view = {};
<ide>
<ide><path>glances/outputs/static/js/components/plugin-network/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginNetwork', {
<add>import GlancesPluginNetworkController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginNetwork', {
<ide> controller: GlancesPluginNetworkController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-network/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-network/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginNetworkController($scope, $filter, GlancesStats, ARGUMENTS) {
<add>export default function GlancesPluginNetworkController($scope, $filter, GlancesStats, ARGUMENTS) {
<ide> var vm = this;
<ide> vm.arguments = ARGUMENTS;
<ide> vm.networks = [];
<ide><path>glances/outputs/static/js/components/plugin-percpu/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginPercpu', {
<add>import GlancesPluginPercpuController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginPercpu', {
<ide> controller: GlancesPluginPercpuController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-percpu/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-percpu/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginPercpuController($scope, GlancesStats, GlancesPluginHelper) {
<add>export default function GlancesPluginPercpuController($scope, GlancesStats, GlancesPluginHelper) {
<ide> var vm = this;
<ide> vm.cpus = [];
<ide>
<ide><path>glances/outputs/static/js/components/plugin-ports/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginPorts', {
<add>import GlancesPluginPortsController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginPorts', {
<ide> controller: GlancesPluginPortsController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-ports/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-ports/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginPortsController($scope, GlancesStats) {
<add>export default function GlancesPluginPortsController($scope, GlancesStats) {
<ide> var vm = this;
<ide> vm.ports = [];
<ide>
<ide><path>glances/outputs/static/js/components/plugin-process/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginProcess', {
<add>import GlancesPluginProcessController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginProcess', {
<ide> controller: GlancesPluginProcessController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-process/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-process/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginProcessController(ARGUMENTS, hotkeys) {
<add>export default function GlancesPluginProcessController(ARGUMENTS, hotkeys) {
<ide> var vm = this;
<ide> vm.arguments = ARGUMENTS;
<ide>
<ide><path>glances/outputs/static/js/components/plugin-processcount/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginProcesscount', {
<add>import GlancesPluginProcesscountController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginProcesscount', {
<ide> controller: GlancesPluginProcesscountController,
<ide> controllerAs: 'vm',
<ide> bindings: {
<ide> sorter: '<'
<ide> },
<del> templateUrl: 'components/plugin-processcount/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-processcount/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginProcesscountController($scope, GlancesStats) {
<add>export default function GlancesPluginProcesscountController($scope, GlancesStats) {
<ide> var vm = this;
<ide>
<ide> vm.total = null;
<ide><path>glances/outputs/static/js/components/plugin-processlist/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginProcesslist', {
<add>import GlancesPluginProcesslistController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginProcesslist', {
<ide> controller: GlancesPluginProcesslistController,
<ide> controllerAs: 'vm',
<ide> bindings: {
<ide> sorter: '<'
<ide> },
<del> templateUrl: 'components/plugin-processlist/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-processlist/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginProcesslistController($scope, GlancesStats, GlancesPluginHelper, $filter, CONFIG, ARGUMENTS) {
<add>export default function GlancesPluginProcesslistController($scope, GlancesStats, GlancesPluginHelper, $filter, CONFIG, ARGUMENTS) {
<ide> var vm = this;
<ide> vm.arguments = ARGUMENTS;
<ide> vm.processes = [];
<ide><path>glances/outputs/static/js/components/plugin-quicklook/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginQuicklook', {
<add>import GlancesPluginQuicklookController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginQuicklook', {
<ide> controller: GlancesPluginQuicklookController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-quicklook/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-quicklook/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginQuicklookController($scope, GlancesStats, ARGUMENTS) {
<add>export default function GlancesPluginQuicklookController($scope, GlancesStats, ARGUMENTS) {
<ide> var vm = this;
<ide> vm.arguments = ARGUMENTS;
<ide> var _view = {};
<ide><path>glances/outputs/static/js/components/plugin-raid/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginRaid', {
<add>import GlancesPluginRaidController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginRaid', {
<ide> controller: GlancesPluginRaidController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-raid/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-raid/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginRaidController($scope, GlancesStats) {
<add>export default function GlancesPluginRaidController($scope, GlancesStats) {
<ide> var vm = this;
<ide> vm.disks = [];
<ide>
<ide><path>glances/outputs/static/js/components/plugin-sensors/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginSensors', {
<add>import GlancesPluginSensorsController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginSensors', {
<ide> controller: GlancesPluginSensorsController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-sensors/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-sensors/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginSensorsController($scope, GlancesStats, GlancesPluginHelper, ARGUMENTS) {
<add>export default function GlancesPluginSensorsController($scope, GlancesStats, GlancesPluginHelper, ARGUMENTS) {
<ide> var vm = this;
<ide> vm.sensors = [];
<ide> var convertToFahrenheit = ARGUMENTS.fahrenheit;
<ide><path>glances/outputs/static/js/components/plugin-system/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginSystem', {
<add>import GlancesPluginSystemController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginSystem', {
<ide> controller: GlancesPluginSystemController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-system/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-system/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginSystemController($scope, GlancesStats) {
<add>export default function GlancesPluginSystemController($scope, GlancesStats) {
<ide> var vm = this;
<ide>
<ide> vm.hostname = null;
<ide><path>glances/outputs/static/js/components/plugin-uptime/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginUptime', {
<add>import GlancesPluginUptimeController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginUptime', {
<ide> controller: GlancesPluginUptimeController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-uptime/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-uptime/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginUptimeController($scope, GlancesStats) {
<add>export default function GlancesPluginUptimeController($scope, GlancesStats) {
<ide> var vm = this;
<ide> vm.value = null;
<ide>
<ide><path>glances/outputs/static/js/components/plugin-wifi/component.js
<ide> 'use strict';
<ide>
<del>glancesApp.component('glancesPluginWifi', {
<add>import GlancesPluginWifiController from './controller';
<add>import template from './view.html';
<add>
<add>export default angular.module('glancesApp').component('glancesPluginWifi', {
<ide> controller: GlancesPluginWifiController,
<ide> controllerAs: 'vm',
<del> templateUrl: 'components/plugin-wifi/view.html'
<add> templateUrl: template,
<ide> });
<ide><path>glances/outputs/static/js/components/plugin-wifi/controller.js
<ide> 'use strict';
<ide>
<del>function GlancesPluginWifiController($scope, $filter, GlancesStats) {
<add>export default function GlancesPluginWifiController($scope, $filter, GlancesStats) {
<ide> var vm = this;
<ide> var _view = {};
<ide> | 59 |
Python | Python | grab the stats, but not display it in the ui.. | b61f70ae99c00db6a05cd5fc9ef1dc02b9483683 | <ide><path>glances/plugins/glances_network.py
<ide> def update(self):
<ide> except UnicodeDecodeError:
<ide> return self.stats
<ide>
<del> # New in PsUtil 3.0: optionaly import the interface's status (issue #765)
<add> # New in PsUtil 3.0
<add> # - import the interface's status (issue #765)
<add> # - import the interface's speed (issue #718)
<ide> netstatus = {}
<ide> try:
<ide> netstatus = psutil.net_if_stats()
<ide> def update(self):
<ide> continue
<ide> else:
<ide> # Optional stats (only compliant with PsUtil 3.0+)
<add> # Interface status
<ide> try:
<ide> netstat['is_up'] = netstatus[net].isup
<ide> except (KeyError, AttributeError):
<ide> pass
<del> # Set the key
<add> # Interface speed in Mbps, convert it to bps
<add> # Can be always 0 on some OS
<add> try:
<add> netstat['speed'] = netstatus[net].speed * 1048576
<add> except (KeyError, AttributeError):
<add> pass
<add>
<add> # Finaly, set the key
<ide> netstat['key'] = self.get_key()
<ide> self.stats.append(netstat)
<ide> | 1 |
Ruby | Ruby | remove redundant conditional | 1678a4a65d9a592c137f49e4bd558dfacc67c46d | <ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade
<ide> outdated -= pinned
<ide> end
<ide>
<del> if outdated.length > 0
<del> oh1 "Upgrading #{outdated.length} outdated package#{outdated.length.plural_s}, with result:"
<del> puts outdated.map{ |f| "#{f.name} #{f.version}" } * ", "
<del> end
<add> oh1 "Upgrading #{outdated.length} outdated package#{outdated.length.plural_s}, with result:"
<add> puts outdated.map{ |f| "#{f.name} #{f.version}" } * ", "
<ide>
<ide> if not upgrade_pinned? and pinned.length > 0
<ide> oh1 "Not upgrading #{pinned.length} pinned package#{pinned.length.plural_s}:" | 1 |
Javascript | Javascript | port attrs and classes via bind-attr to attrnode | a87de7ac38a48b3da362fcf5b2dd64daf2a3c8aa | <ide><path>packages/ember-htmlbars/lib/attr_nodes/legacy_bind.js
<add>/**
<add>@module ember
<add>@submodule ember-htmlbars
<add>*/
<add>
<add>import { fmt } from "ember-runtime/system/string";
<add>import { typeOf } from "ember-metal/utils";
<add>import isNone from 'ember-metal/is_none';
<add>import SimpleAttrNode from "./simple";
<add>import { create as o_create } from "ember-metal/platform";
<add>
<add>function LegacyBindAttrNode(element, attrName, attrValue, dom) {
<add> this.init(element, attrName, attrValue, dom);
<add>}
<add>
<add>LegacyBindAttrNode.prototype = o_create(SimpleAttrNode.prototype);
<add>
<add>LegacyBindAttrNode.prototype.super$init = SimpleAttrNode.prototype.init;
<add>
<add>LegacyBindAttrNode.prototype.render = function init() {
<add> var name = this.attrName;
<add> var value = this.currentValue;
<add> var type = typeOf(value);
<add>
<add> Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [value]),
<add> value === null || value === undefined || type === 'number' || type === 'string' || type === 'boolean');
<add>
<add> // if this changes, also change the logic in ember-handlebars/lib/helpers/binding.js
<add> if (name !== 'value' && (type === 'string' || (type === 'number' && !isNaN(value)))) {
<add> this.dom.setAttribute(this.element, name, value);
<add> } else if (name === 'value' || type === 'boolean') {
<add> if (isNone(value) || value === false) {
<add> // `null`, `undefined` or `false` should remove attribute
<add> this.dom.removeAttribute(this.element, name);
<add> // In IE8 `prop` couldn't remove attribute when name is `required`.
<add> if (name === 'required') {
<add> this.dom.setProperty(this.element, name, null);
<add> } else {
<add> this.dom.setProperty(this.element, name, '');
<add> }
<add> } else {
<add> // value should always be properties
<add> this.dom.setProperty(this.element, name, value);
<add> }
<add> } else if (!value) {
<add> if (this.lastValue !== null) {
<add> this.dom.removeAttribute(this.element, name);
<add> }
<add> }
<add>};
<add>
<add>export default LegacyBindAttrNode;
<add>
<ide><path>packages/ember-htmlbars/lib/helpers/bind-attr.js
<ide> import Ember from "ember-metal/core"; // Ember.assert
<ide>
<ide> import { fmt } from "ember-runtime/system/string";
<del>import { typeOf } from "ember-metal/utils";
<del>import { forEach } from "ember-metal/array";
<add>import QuotedClassAttrNode from "ember-htmlbars/attr_nodes/quoted_class";
<add>import LegacyBindAttrNode from "ember-htmlbars/attr_nodes/legacy_bind";
<ide> import View from "ember-views/views/view";
<add>import Stream from "ember-metal/streams/stream";
<ide> import keys from "ember-metal/keys";
<ide> import helpers from "ember-htmlbars/helpers";
<del>import jQuery from "ember-views/system/jquery";
<ide>
<ide> /**
<ide> `bind-attr` allows you to create a binding between DOM element attributes and
<ide> import jQuery from "ember-views/system/jquery";
<ide> @return {String} HTML string
<ide> */
<ide> function bindAttrHelper(params, hash, options, env) {
<del> var element = jQuery(options.element);
<add> var element = options.element;
<ide>
<ide> Ember.assert("You must specify at least one hash argument to bind-attr", !!keys(hash).length);
<ide>
<ide> function bindAttrHelper(params, hash, options, env) {
<ide> // Handle classes differently, as we can bind multiple classes
<ide> var classBindings = hash['class'];
<ide> if (classBindings != null) {
<del>
<del> var classResults = bindClasses(element, classBindings, view, options);
<del>
<del> View.applyAttributeBindings(element, 'class', classResults.join(' '));
<del>
<add> var attrValue = streamifyClassBindings(view, classBindings);
<add> new QuotedClassAttrNode(element, 'class', attrValue, env.dom);
<ide> delete hash['class'];
<ide> }
<ide>
<ide> var attrKeys = keys(hash);
<ide>
<del> // For each attribute passed, create an observer and emit the
<del> // current value of the property as an attribute.
<del> forEach.call(attrKeys, function(attr) {
<del> var path = hash[attr];
<del>
<del> var lazyValue;
<del>
<add> var attr, path, lazyValue;
<add> for (var i=0, l=attrKeys.length;i<l;i++) {
<add> attr = attrKeys[i];
<add> path = hash[attr];
<ide> if (path.isStream) {
<ide> lazyValue = path;
<ide> } else {
<del> Ember.assert(fmt("You must provide an expression as the value of bound attribute." +
<del> " You specified: %@=%@", [attr, path]), typeof path === 'string' || path.isStream);
<del>
<add> Ember.assert(
<add> fmt("You must provide an expression as the value of bound attribute." +
<add> " You specified: %@=%@", [attr, path]),
<add> typeof path === 'string'
<add> );
<ide> lazyValue = view.getStream(path);
<ide> }
<del>
<del> var value = lazyValue.value();
<del> var type = typeOf(value);
<del>
<del> Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [value]),
<del> value === null || value === undefined || type === 'number' || type === 'string' || type === 'boolean');
<del>
<del>
<del> lazyValue.subscribe(view._wrapAsScheduled(function applyAttributeBindings() {
<del> var result = lazyValue.value();
<del>
<del> Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [result]),
<del> result === null || result === undefined || typeof result === 'number' ||
<del> typeof result === 'string' || typeof result === 'boolean');
<del>
<del> View.applyAttributeBindings(element, attr, result);
<del> }));
<del>
<del> if (value && type === 'boolean') {
<del> value = attr;
<del> }
<del>
<del> View.applyAttributeBindings(element, attr, value);
<del> }, this);
<add> new LegacyBindAttrNode(element, attr, lazyValue, env.dom);
<add> }
<ide> }
<ide>
<ide> /**
<ide> function bindAttrHelperDeprecated() {
<ide> element to update
<ide> @return {Array} An array of class names to add
<ide> */
<del>function bindClasses(element, classBindings, view, options) {
<del> var ret = [];
<del> var newClass, value;
<del>
<del> // For each property passed, loop through and setup
<del> // an observer.
<del> forEach.call(classBindings.split(' '), function(binding) {
<del>
<del> // Variable in which the old class value is saved. The observer function
<del> // closes over this variable, so it knows which string to remove when
<del> // the property changes.
<del> var oldClass;
<del> var parsedPath = View._parsePropertyPath(binding);
<del> var path = parsedPath.path;
<del> var initialValue;
<del>
<del> if (path === '') {
<del> initialValue = true;
<del> } else {
<del> var lazyValue = view.getStream(path);
<del> initialValue = lazyValue.value();
<del>
<del> // Set up an observer on the context. If the property changes, toggle the
<del> // class name.
<del> lazyValue.subscribe(view._wrapAsScheduled(function applyClassNameBindings() {
<del> // Get the current value of the property
<del> var value = lazyValue.value();
<del> newClass = classStringForParsedPath(parsedPath, value);
<del>
<del> // If we had previously added a class to the element, remove it.
<del> if (oldClass) {
<del> element.removeClass(oldClass);
<del> }
<del>
<del> // If necessary, add a new class. Make sure we keep track of it so
<del> // it can be removed in the future.
<del> if (newClass) {
<del> element.addClass(newClass);
<del> oldClass = newClass;
<del> } else {
<del> oldClass = null;
<del> }
<del> }));
<del> }
<del>
<del> // We've already setup the observer; now we just need to figure out the
<del> // correct behavior right now on the first pass through.
<del> value = classStringForParsedPath(parsedPath, initialValue);
<add>function streamifyClassBindings(view, classBindingsString) {
<add> var classBindings = classBindingsString.split(' ');
<add> var streamified = [];
<ide>
<del> if (value) {
<del> ret.push(value);
<add> var parsedPath;
<add> for (var i=0, l=classBindings.length;i<l;i++) {
<add> parsedPath = View._parsePropertyPath(classBindings[i]);
<ide>
<del> // Make sure we save the current value so that it can be removed if the
<del> // observer fires.
<del> oldClass = value;
<add> if (parsedPath.path === '') {
<add> streamified.push(classStringForParsedPath(parsedPath, true));
<add> } else {
<add> (function(){
<add> var lazyValue = view.getStream(parsedPath.path);
<add> var _parsedPath = parsedPath;
<add> var classNameBound = new Stream(function(){
<add> var value = lazyValue.value();
<add> return classStringForParsedPath(_parsedPath, value);
<add> });
<add> lazyValue.subscribe(function(){
<add> classNameBound.notify();
<add> });
<add> streamified.push(classNameBound);
<add> })(); // jshint ignore:line
<ide> }
<del> });
<del>
<del> return ret;
<add> }
<add>
<add> return streamified;
<ide> }
<ide>
<ide> function classStringForParsedPath(parsedPath, value) {
<ide> export default bindAttrHelper;
<ide>
<ide> export {
<ide> bindAttrHelper,
<del> bindAttrHelperDeprecated,
<del> bindClasses
<add> bindAttrHelperDeprecated
<ide> };
<ide><path>packages/ember-htmlbars/tests/helpers/bind_attr_test.js
<ide> test("should not allow XSS injection via {{bind-attr}} with class", function() {
<ide> foo: '" onmouseover="alert(\'I am in your classes hacking your app\');'
<ide> });
<ide>
<del> appendView(view);
<add> try {
<add> appendView(view);
<add> } catch (e) {
<add> }
<ide>
<ide> equal(view.$('img').attr('onmouseover'), undefined);
<del> // If the whole string is here, then it means we got properly escaped
<del> equal(view.$('img').attr('class'), '" onmouseover="alert(\'I am in your classes hacking your app\');');
<ide> });
<ide>
<ide> test("should be able to bind class attribute using ternary operator in {{bind-attr}}", function() {
<ide><path>packages/ember-views/lib/views/view.js
<ide> View.views = {};
<ide> // method.
<ide> View.childViewsProperty = childViewsProperty;
<ide>
<add>// Used by Handlebars helpers, view element attributes
<ide> View.applyAttributeBindings = function(elem, name, value) {
<ide> var type = typeOf(value);
<ide> | 4 |
Python | Python | skip broken test | 9740a03f61eee729fc153fd3ec43bf3e631270d1 | <ide><path>tests/pipelines/test_pipelines_image_segmentation.py
<ide> def test_small_model_pt_no_panoptic(self):
<ide> )
<ide>
<ide> @require_torch
<add> @unittest.skip("This test is broken for now")
<ide> def test_small_model_pt(self):
<ide> model_id = "hf-internal-testing/tiny-detr-mobilenetsv3-panoptic"
<ide> | 1 |
Javascript | Javascript | fix warning extraction script | 8121212f0db77a263a778a658c59ed7ba1f71d2d | <ide><path>scripts/print-warnings/print-warnings.js
<ide> function transform(file, enc, cb) {
<ide> const callee = astPath.get('callee');
<ide> if (
<ide> callee.isIdentifier({name: 'warning'}) ||
<add> callee.isIdentifier({name: 'warningWithoutStack'}) ||
<ide> callee.isIdentifier({name: 'lowPriorityWarning'})
<ide> ) {
<ide> const node = astPath.node;
<ide> function transform(file, enc, cb) {
<ide> });
<ide> }
<ide>
<del>gs(['packages/**/*.js', '!**/__tests__/**/*.js', '!**/__mocks__/**/*.js']).pipe(
<add>gs([
<add> 'packages/**/*.js',
<add> '!packages/shared/warning.js',
<add> '!**/__tests__/**/*.js',
<add> '!**/__mocks__/**/*.js',
<add>]).pipe(
<ide> through.obj(transform, cb => {
<ide> process.stdout.write(
<ide> Array.from(warnings) | 1 |
Ruby | Ruby | fix another ordering failure | 842d55cb16eac7e48660ecd4df5ec1daf946f4d1 | <ide><path>activerecord/test/cases/base_test.rb
<ide> def test_decrement_counter
<ide> end
<ide>
<ide> def test_update_counter
<del> category = Category.first
<add> category = categories(:general)
<ide> assert_nil category.categorizations_count
<ide> assert_equal 2, category.categorizations.count
<ide> | 1 |
PHP | PHP | add sql cast function cakephp | 6b27418ffec75ddde448bfbd3fa1e10f7e44d958 | <ide><path>src/Database/FunctionsBuilder.php
<ide> public function coalesce(array $args, array $types = []): FunctionExpression
<ide> return new FunctionExpression('COALESCE', $args, $types, current($types) ?: 'string');
<ide> }
<ide>
<add> /**
<add> * Returns a FunctionExpression representing a call to SQL CAST function.
<add> *
<add> * @param string|\Cake\Database\ExpressionInterface $field Field or expression to cast.
<add> * @param string $type The target data type
<add> * @return \Cake\Database\Expression\FunctionExpression
<add> */
<add> public function cast($field, string $type): FunctionExpression
<add> {
<add> $expression = new FunctionExpression('CAST', $this->toLiteralParam($field));
<add> $expression->setConjunction(' AS')->add([$type => 'literal']);
<add>
<add> return $expression;
<add> }
<add>
<ide> /**
<ide> * Returns a FunctionExpression representing the difference in days between
<ide> * two dates.
<ide><path>tests/TestCase/Database/FunctionsBuilderTest.php
<ide> public function testCoalesce()
<ide> $this->assertSame('date', $function->getReturnType());
<ide> }
<ide>
<add> /**
<add> * Tests generating a CAST() function
<add> *
<add> * @return void
<add> */
<add> public function testCast()
<add> {
<add> $function = $this->functions->cast('field', 'varchar');
<add> $this->assertInstanceOf(FunctionExpression::class, $function);
<add> $this->assertSame('CAST(field AS varchar)', $function->sql(new ValueBinder()));
<add> $this->assertSame('string', $function->getReturnType());
<add>
<add> $function = $this->functions->cast($this->functions->now(), 'varchar');
<add> $this->assertInstanceOf(FunctionExpression::class, $function);
<add> $this->assertSame('CAST(NOW() AS varchar)', $function->sql(new ValueBinder()));
<add> $this->assertSame('string', $function->getReturnType());
<add> }
<add>
<ide> /**
<ide> * Tests generating a NOW(), CURRENT_TIME() and CURRENT_DATE() function
<ide> * | 2 |
PHP | PHP | simplify behaviors init | 8a257cf748f3fbfecc4b43f1062ff6c57bbbd59c | <ide><path>src/ORM/Table.php
<ide> public function __construct(array $config = [])
<ide> }
<ide> }
<ide> $this->_eventManager = $eventManager ?: new EventManager();
<del> if ($behaviors) {
<del> $behaviors->setTable($this);
<del> } else {
<del> $behaviors = new BehaviorRegistry($this);
<del> }
<del> $this->_behaviors = $behaviors;
<add> $this->_behaviors = $behaviors ?: new BehaviorRegistry();
<add> $this->_behaviors->setTable($this);
<ide> $this->_associations = $associations ?: new AssociationCollection();
<ide>
<ide> $this->initialize($config); | 1 |
PHP | PHP | add multipolygonz type for postgresql | 2bd0ef74d6962daea31045cb6f15aecb1fe2d19e | <ide><path>src/Illuminate/Database/Schema/Blueprint.php
<ide> public function multiPolygon($column)
<ide> return $this->addColumn('multipolygon', $column);
<ide> }
<ide>
<add> /**
<add> * Create a new multipolygon column on the table.
<add> *
<add> * @param string $column
<add> * @return \Illuminate\Database\Schema\ColumnDefinition
<add> */
<add> public function multiPolygonZ($column)
<add> {
<add> return $this->addColumn('multipolygonz', $column);
<add> }
<add>
<ide> /**
<ide> * Create a new generated, computed column on the table.
<ide> *
<ide><path>src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php
<ide> protected function typeMultiPolygon(Fluent $column)
<ide> return $this->formatPostGisType('multipolygon');
<ide> }
<ide>
<add> /**
<add> * Create the column definition for a spatial MultiPolygonZ type.
<add> *
<add> * @param \Illuminate\Support\Fluent $column
<add> * @return string
<add> */
<add> protected function typeMultiPolygonZ(Fluent $column)
<add> {
<add> return $this->formatPostGisType('multipolygonz');
<add> }
<add>
<ide> /**
<ide> * Format the column definition for a PostGIS spatial type.
<ide> * | 2 |
Ruby | Ruby | fix failing test from [7619bcf2] | b04bce28ff475a93311304069085b0b99d1dbac4 | <ide><path>railties/lib/rails/generators/generated_attribute.rb
<ide> def parse_type_and_options(type)
<ide> when /(string|text|binary|integer)\{(\d+)\}/
<ide> return $1, :limit => $2.to_i
<ide> when /decimal\{(\d+)[,.-](\d+)\}/
<del> return :decimal, :precision => $1.to_i, :scale => $3.to_i
<add> return :decimal, :precision => $1.to_i, :scale => $2.to_i
<ide> else
<ide> return type, {}
<ide> end | 1 |
Ruby | Ruby | fix `effective_arch` on linux | 23340403c15c4ff814eb7a66d77a71bb57a35d09 | <ide><path>Library/Homebrew/extend/os/linux/extend/ENV/shared.rb
<ide> module SharedEnvExtension
<ide> # @private
<ide> def effective_arch
<del> if @args&.build_bottle? && @args&.bottle_arch
<del> @args.bottle_arch.to_sym
<del> elsif @args&.build_bottle?
<add> if @build_bottle && @bottle_arch
<add> @bottle_arch.to_sym
<add> elsif @build_bottle
<ide> Hardware.oldest_cpu
<ide> else
<ide> :native | 1 |
Javascript | Javascript | restrict translation to audited certs | b197f73881f0882ed067b3e1cdbc846e28d92479 | <ide><path>curriculum/getChallenges.js
<ide> const {
<ide> const { COMMENT_TRANSLATIONS } = require('./comment-dictionary');
<ide>
<ide> const { dasherize } = require('../utils/slugs');
<add>const { isAuditedCert } = require('../utils/is-audited');
<ide>
<ide> const challengesDir = path.resolve(__dirname, './challenges');
<ide> const metaDir = path.resolve(challengesDir, '_meta');
<ide> async function createChallenge(fullPath, maybeMeta) {
<ide> meta = require(metaPath);
<ide> }
<ide> const { name: superBlock } = superBlockInfoFromFullPath(fullPath);
<del> if (!isAcceptedLanguage(getChallengeLang(fullPath)))
<del> throw Error(`${getChallengeLang(fullPath)} is not a accepted language.
<add> const lang = getChallengeLang(fullPath);
<add> if (!isAcceptedLanguage(lang))
<add> throw Error(`${lang} is not a accepted language.
<ide> Trying to parse ${fullPath}`);
<del> const challenge = await (isEnglishChallenge(fullPath)
<add> // assumes superblock names are unique
<add> // while the auditing is ongoing, we default to English for un-audited certs
<add> // once that's complete, we can revert to using isEnglishChallenge(fullPath)
<add> const isEnglish =
<add> isEnglishChallenge(fullPath) || !isAuditedCert(lang, superBlock);
<add> if (isEnglish) fullPath = getEnglishPath(fullPath);
<add> const challenge = await (isEnglish
<ide> ? parseMarkdown(fullPath)
<ide> : parseTranslation(
<ide> getEnglishPath(fullPath),
<ide><path>utils/is-audited.js
<add>// this can go once all certs have been audited.
<add>function isAuditedCert(lang, cert) {
<add> if (!lang || !cert)
<add> throw Error('Both arguments must be provided for auditing');
<add> // in order to see the challenges in the client, add the certification that
<add> // contains those challenges to this array:
<add> const auditedCerts = [
<add> 'responsive-web-design',
<add> 'javascript-algorithms-and-data-structures',
<add> 'certificates'
<add> ];
<add> return lang === 'english' || auditedCerts.includes(cert);
<add>}
<add>
<add>exports.isAuditedCert = isAuditedCert; | 2 |
Javascript | Javascript | allow sharing options between multiple inputs | 9c9c6b3fe4edfe78ae275c413ee3eefb81f1ebf6 | <ide><path>src/ng/directive/ngModel.js
<ide> var ngModelOptionsDirective = function() {
<ide> restrict: 'A',
<ide> controller: ['$scope', '$attrs', function($scope, $attrs) {
<ide> var that = this;
<del> this.$options = $scope.$eval($attrs.ngModelOptions);
<add> this.$options = angular.copy($scope.$eval($attrs.ngModelOptions));
<ide> // Allow adding/overriding bound events
<ide> if (this.$options.updateOn !== undefined) {
<ide> this.$options.updateOnDefault = false;
<ide><path>test/ng/directive/ngModelSpec.js
<ide> describe('ngModelOptions attributes', function() {
<ide> });
<ide>
<ide>
<add> it('should allow sharing options between multiple inputs', function() {
<add> $rootScope.options = {updateOn: 'default'};
<add> var inputElm = helper.compileInput(
<add> '<input type="text" ng-model="name1" name="alias1" ' +
<add> 'ng-model-options="options"' +
<add> '/>' +
<add> '<input type="text" ng-model="name2" name="alias2" ' +
<add> 'ng-model-options="options"' +
<add> '/>');
<add>
<add> helper.changeGivenInputTo(inputElm.eq(0), 'a');
<add> helper.changeGivenInputTo(inputElm.eq(1), 'b');
<add> expect($rootScope.name1).toEqual('a');
<add> expect($rootScope.name2).toEqual('b');
<add> });
<add>
<add>
<add> it('should hold a copy of the options object', function() {
<add> $rootScope.options = {updateOn: 'default'};
<add> var inputElm = helper.compileInput(
<add> '<input type="text" ng-model="name" name="alias" ' +
<add> 'ng-model-options="options"' +
<add> '/>');
<add> expect($rootScope.options).toEqual({updateOn: 'default'});
<add> expect($rootScope.form.alias.$options).not.toBe($rootScope.options);
<add> });
<add>
<add>
<ide> it('should allow overriding the model update trigger event on checkboxes', function() {
<ide> var inputElm = helper.compileInput(
<ide> '<input type="checkbox" ng-model="checkbox" ' + | 2 |
Go | Go | fix error-checking when looking at empty log | 2a0291489247b79058f0f94a2af7c5b3f89b78af | <ide><path>integration-cli/docker_cli_logs_test.go
<ide> func (s *DockerSuite) TestLogsSinceFutureFollow(c *check.C) {
<ide>
<ide> since := t.Unix() + 2
<ide> out, _ = dockerCmd(c, "logs", "-t", "-f", fmt.Sprintf("--since=%v", since), name)
<add> c.Assert(out, checker.Not(checker.HasLen), 0, check.Commentf("cannot read from empty log"))
<ide> lines := strings.Split(strings.TrimSpace(out), "\n")
<del> c.Assert(lines, checker.Not(checker.HasLen), 0)
<ide> for _, v := range lines {
<ide> ts, err := time.Parse(time.RFC3339Nano, strings.Split(v, " ")[0])
<ide> c.Assert(err, checker.IsNil, check.Commentf("cannot parse timestamp output from log: '%v'", v)) | 1 |
Text | Text | add directories for other languages | 293ca82c6d4285dfd4b2302df1a08844afa5bd9f | <ide><path>docs/arabic/CONTRIBUTING.md
<add><table>
<add> <tr>
<add> <td> Read these guidelines in </td>
<add> <td><a href="/CONTRIBUTING.md"> English </a></td>
<add> <td><a href="/docs/chinese/CONTRIBUTING.md"> 中文 </a></td>
<add> <td><a href="/docs/russian/CONTRIBUTING.md"> русский </a></td>
<add> <td><a href="/docs/arabic/CONTRIBUTING.md"> عربى </a></td>
<add> <td><a href="/docs/spanish/CONTRIBUTING.md"> Español </a></td>
<add> <td><a href="/docs/portuguese/CONTRIBUTING.md"> Português </a></td>
<add> </tr>
<add></table>
<add>
<add># Contribution Guidelines
<add>
<add>Hello 👋 !
<add>
<add>These instructions have not been translated yet.
<ide>\ No newline at end of file
<ide><path>docs/arabic/README.md
<add><table>
<add> <tr>
<add> <td> Read these guidelines in </td>
<add> <td><a href="/CONTRIBUTING.md"> English </a></td>
<add> <td><a href="/docs/chinese/README.md"> 中文 </a></td>
<add> <td><a href="/docs/russian/README.md"> русский </a></td>
<add> <td><a href="/docs/arabic/README.md"> عربى </a></td>
<add> <td><a href="/docs/spanish/README.md"> Español </a></td>
<add> <td><a href="/docs/portuguese/README.md"> Português </a></td>
<add> </tr>
<add></table>
<add>
<add># Documentation
<add>
<add>Hello 👋 !
<add>
<add>These instructions have not been translated yet.
<ide>\ No newline at end of file
<ide><path>docs/chinese/CONTRIBUTING.md
<add><table>
<add> <tr>
<add> <td> Read these guidelines in </td>
<add> <td><a href="/CONTRIBUTING.md"> English </a></td>
<add> <td><a href="/docs/chinese/CONTRIBUTING.md"> 中文 </a></td>
<add> <td><a href="/docs/russian/CONTRIBUTING.md"> русский </a></td>
<add> <td><a href="/docs/arabic/CONTRIBUTING.md"> عربى </a></td>
<add> <td><a href="/docs/spanish/CONTRIBUTING.md"> Español </a></td>
<add> <td><a href="/docs/portuguese/CONTRIBUTING.md"> Português </a></td>
<add> </tr>
<add></table>
<add>
<add># Contribution Guidelines
<add>
<add>Hello 👋 !
<add>
<add>These instructions have not been translated yet.
<ide>\ No newline at end of file
<ide><path>docs/chinese/README.md
<add><table>
<add> <tr>
<add> <td> Read these guidelines in </td>
<add> <td><a href="/CONTRIBUTING.md"> English </a></td>
<add> <td><a href="/docs/chinese/README.md"> 中文 </a></td>
<add> <td><a href="/docs/russian/README.md"> русский </a></td>
<add> <td><a href="/docs/arabic/README.md"> عربى </a></td>
<add> <td><a href="/docs/spanish/README.md"> Español </a></td>
<add> <td><a href="/docs/portuguese/README.md"> Português </a></td>
<add> </tr>
<add></table>
<add>
<add># Documentation
<add>
<add>Hello 👋 !
<add>
<add>These instructions have not been translated yet.
<ide>\ No newline at end of file
<ide><path>docs/portuguese/CONTRIBUTING.md
<add><table>
<add> <tr>
<add> <td> Read these guidelines in </td>
<add> <td><a href="/CONTRIBUTING.md"> English </a></td>
<add> <td><a href="/docs/chinese/CONTRIBUTING.md"> 中文 </a></td>
<add> <td><a href="/docs/russian/CONTRIBUTING.md"> русский </a></td>
<add> <td><a href="/docs/arabic/CONTRIBUTING.md"> عربى </a></td>
<add> <td><a href="/docs/spanish/CONTRIBUTING.md"> Español </a></td>
<add> <td><a href="/docs/portuguese/CONTRIBUTING.md"> Português </a></td>
<add> </tr>
<add></table>
<add>
<add># Contribution Guidelines
<add>
<add>Hello 👋 !
<add>
<add>These instructions have not been translated yet.
<ide>\ No newline at end of file
<ide><path>docs/portuguese/README.md
<add><table>
<add> <tr>
<add> <td> Read these guidelines in </td>
<add> <td><a href="/CONTRIBUTING.md"> English </a></td>
<add> <td><a href="/docs/chinese/README.md"> 中文 </a></td>
<add> <td><a href="/docs/russian/README.md"> русский </a></td>
<add> <td><a href="/docs/arabic/README.md"> عربى </a></td>
<add> <td><a href="/docs/spanish/README.md"> Español </a></td>
<add> <td><a href="/docs/portuguese/README.md"> Português </a></td>
<add> </tr>
<add></table>
<add>
<add># Documentation
<add>
<add>Hello 👋 !
<add>
<add>These instructions have not been translated yet.
<ide>\ No newline at end of file
<ide><path>docs/russian/CONTRIBUTING.md
<add><table>
<add> <tr>
<add> <td> Read these guidelines in </td>
<add> <td><a href="/CONTRIBUTING.md"> English </a></td>
<add> <td><a href="/docs/chinese/CONTRIBUTING.md"> 中文 </a></td>
<add> <td><a href="/docs/russian/CONTRIBUTING.md"> русский </a></td>
<add> <td><a href="/docs/arabic/CONTRIBUTING.md"> عربى </a></td>
<add> <td><a href="/docs/spanish/CONTRIBUTING.md"> Español </a></td>
<add> <td><a href="/docs/portuguese/CONTRIBUTING.md"> Português </a></td>
<add> </tr>
<add></table>
<add>
<add># Contribution Guidelines
<add>
<add>Hello 👋 !
<add>
<add>These instructions have not been translated yet.
<ide>\ No newline at end of file
<ide><path>docs/russian/README.md
<add><table>
<add> <tr>
<add> <td> Read these guidelines in </td>
<add> <td><a href="/CONTRIBUTING.md"> English </a></td>
<add> <td><a href="/docs/chinese/README.md"> 中文 </a></td>
<add> <td><a href="/docs/russian/README.md"> русский </a></td>
<add> <td><a href="/docs/arabic/README.md"> عربى </a></td>
<add> <td><a href="/docs/spanish/README.md"> Español </a></td>
<add> <td><a href="/docs/portuguese/README.md"> Português </a></td>
<add> </tr>
<add></table>
<add>
<add># Documentation
<add>
<add>Hello 👋 !
<add>
<add>These instructions have not been translated yet.
<ide>\ No newline at end of file
<ide><path>docs/spanish/CONTRIBUTING.md
<add><table>
<add> <tr>
<add> <td> Read these guidelines in </td>
<add> <td><a href="/CONTRIBUTING.md"> English </a></td>
<add> <td><a href="/docs/chinese/CONTRIBUTING.md"> 中文 </a></td>
<add> <td><a href="/docs/russian/CONTRIBUTING.md"> русский </a></td>
<add> <td><a href="/docs/arabic/CONTRIBUTING.md"> عربى </a></td>
<add> <td><a href="/docs/spanish/CONTRIBUTING.md"> Español </a></td>
<add> <td><a href="/docs/portuguese/CONTRIBUTING.md"> Português </a></td>
<add> </tr>
<add></table>
<add>
<add># Contribution Guidelines
<add>
<add>Hello 👋 !
<add>
<add>These instructions have not been translated yet.
<ide>\ No newline at end of file
<ide><path>docs/spanish/README.md
<add><table>
<add> <tr>
<add> <td> Read these guidelines in </td>
<add> <td><a href="/CONTRIBUTING.md"> English </a></td>
<add> <td><a href="/docs/chinese/README.md"> 中文 </a></td>
<add> <td><a href="/docs/russian/README.md"> русский </a></td>
<add> <td><a href="/docs/arabic/README.md"> عربى </a></td>
<add> <td><a href="/docs/spanish/README.md"> Español </a></td>
<add> <td><a href="/docs/portuguese/README.md"> Português </a></td>
<add> </tr>
<add></table>
<add>
<add># Documentation
<add>
<add>Hello 👋 !
<add>
<add>These instructions have not been translated yet.
<ide>\ No newline at end of file | 10 |
Go | Go | reduce permissions changes scope after add/copy | f3cedce3608afe7bd570666a7fc878ab85c7bc03 | <ide><path>builder/internals.go
<ide> func (b *Builder) addContext(container *daemon.Container, orig, dest string, dec
<ide> }
<ide>
<ide> if fi.IsDir() {
<del> return copyAsDirectory(origPath, destPath, destExists)
<add> return copyAsDirectory(origPath, destPath)
<ide> }
<ide>
<ide> // If we are adding a remote file (or we've been told not to decompress), do not try to untar it
<ide> func (b *Builder) addContext(container *daemon.Container, orig, dest string, dec
<ide> resPath = path.Join(destPath, path.Base(origPath))
<ide> }
<ide>
<del> return fixPermissions(resPath, 0, 0)
<add> return fixPermissions(origPath, resPath, 0, 0)
<ide> }
<ide>
<del>func copyAsDirectory(source, destination string, destinationExists bool) error {
<add>func copyAsDirectory(source, destination string) error {
<ide> if err := chrootarchive.CopyWithTar(source, destination); err != nil {
<ide> return err
<ide> }
<del>
<del> if destinationExists {
<del> files, err := ioutil.ReadDir(source)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> for _, file := range files {
<del> if err := fixPermissions(filepath.Join(destination, file.Name()), 0, 0); err != nil {
<del> return err
<del> }
<del> }
<del> return nil
<del> }
<del>
<del> return fixPermissions(destination, 0, 0)
<add> return fixPermissions(source, destination, 0, 0)
<ide> }
<ide>
<del>func fixPermissions(destination string, uid, gid int) error {
<del> return filepath.Walk(destination, func(path string, info os.FileInfo, err error) error {
<del> if err := os.Lchown(path, uid, gid); err != nil && !os.IsNotExist(err) {
<add>func fixPermissions(source, destination string, uid, gid int) error {
<add> // We Walk on the source rather than on the destination because we don't
<add> // want to change permissions on things we haven't created or modified.
<add> return filepath.Walk(source, func(fullpath string, info os.FileInfo, err error) error {
<add> // Do not alter the walk root itself as it potentially existed before.
<add> if source == fullpath {
<add> return nil
<add> }
<add> // Path is prefixed by source: substitute with destination instead.
<add> cleaned, err := filepath.Rel(source, fullpath)
<add> if err != nil {
<ide> return err
<ide> }
<del> return nil
<add> fullpath = path.Join(destination, cleaned)
<add> return os.Lchown(fullpath, uid, gid)
<ide> })
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_build_test.go
<ide> ADD . /`,
<ide> logDone("build - add etc directory to root")
<ide> }
<ide>
<add>// Testing #9401
<add>func TestBuildAddPreservesFilesSpecialBits(t *testing.T) {
<add> name := "testaddpreservesfilesspecialbits"
<add> defer deleteImages(name)
<add> ctx, err := fakeContext(`FROM busybox
<add>ADD suidbin /usr/bin/suidbin
<add>RUN chmod 4755 /usr/bin/suidbin
<add>RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]
<add>ADD ./data/ /
<add>RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]`,
<add> map[string]string{
<add> "suidbin": "suidbin",
<add> "/data/usr/test_file": "test1",
<add> })
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer ctx.Close()
<add>
<add> if _, err := buildImageFromContext(name, ctx, true); err != nil {
<add> t.Fatal(err)
<add> }
<add> logDone("build - add preserves files special bits")
<add>}
<add>
<ide> func TestBuildCopySingleFileToRoot(t *testing.T) {
<ide> name := "testcopysinglefiletoroot"
<ide> defer deleteImages(name) | 2 |
PHP | PHP | add tests for datetimetype | 9c4a527045f161affaca907fb91292da31a37315 | <ide><path>lib/Cake/Model/Datasource/Database/Type/DateTimeType.php
<ide> use Cake\Model\Datasource\Database\Driver;
<ide> use \DateTime;
<ide>
<add>/**
<add> * Datetime type converter.
<add> *
<add> * Use to convert datetime instances to strings & back.
<add> */
<ide> class DateTimeType extends \Cake\Model\Datasource\Database\Type {
<ide>
<add>/**
<add> * Convert DateTime instance into strings.
<add> *
<add> * @param string|Datetime $value The value to convert.
<add> * @param Driver $driver The driver instance to convert with.
<add> * @return string
<add> */
<ide> public function toDatabase($value, Driver $driver) {
<ide> if (is_string($value)) {
<ide> return $value;
<ide> }
<ide> return $value->format('Y-m-d H:i:s');
<ide> }
<ide>
<add>/**
<add> * Convert strings into DateTime instances.
<add> *
<add> * @param string $value The value to convert.
<add> * @param Driver $driver The driver instance to convert with.
<add> * @return Datetime
<add> */
<ide> public function toPHP($value, Driver $driver) {
<ide> if ($value === null) {
<ide> return null;
<ide><path>lib/Cake/Test/TestCase/Model/Datasource/Database/Type/DateTimeTypeTest.php
<add><?php
<add>/**
<add> * PHP Version 5.4
<add> *
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since CakePHP(tm) v 3.0.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<add>namespace Cake\Test\TestCase\Model\Datasource\Database\Type;
<add>
<add>use Cake\Model\Datasource\Database\Type;
<add>use Cake\Model\Datasource\Database\Type\DateTimeType;
<add>use Cake\TestSuite\TestCase;
<add>
<add>/**
<add> * Test for the DateTime type.
<add> */
<add>class DateTimeTypeTest extends TestCase {
<add>
<add>/**
<add> * Setup
<add> *
<add> * @return void
<add> */
<add> public function setUp() {
<add> parent::setUp();
<add> $this->type = Type::build('datetime');
<add> $this->driver = $this->getMock('Cake\Model\Datasource\Database\Driver');
<add> }
<add>
<add>/**
<add> * Test toPHP
<add> *
<add> * @return void
<add> */
<add> public function testToPHP() {
<add> $this->assertNull($this->type->toPHP(null, $this->driver));
<add>
<add> $result = $this->type->toPHP('2001-01-04 12:13:14', $this->driver);
<add> $this->assertInstanceOf('DateTime', $result);
<add> $this->assertEqual('2001', $result->format('Y'));
<add> $this->assertEqual('01', $result->format('m'));
<add> $this->assertEqual('04', $result->format('d'));
<add> $this->assertEqual('12', $result->format('H'));
<add> $this->assertEqual('13', $result->format('i'));
<add> $this->assertEqual('14', $result->format('s'));
<add> }
<add>
<add>/**
<add> * Test converting to database format
<add> *
<add> * @return void
<add> */
<add> public function testToDatabase() {
<add> $value = '2001-01-04 12:13:14';
<add> $result = $this->type->toDatabase($value, $this->driver);
<add> $this->assertEquals($value, $result);
<add>
<add> $date = new \DateTime('2013-08-12 15:16:17');
<add> $result = $this->type->toDatabase($date, $this->driver);
<add> $this->assertEquals('2013-08-12 15:16:17', $result);
<add> }
<add>
<add>} | 2 |
PHP | PHP | add empty line before return | 8fa4e52662a53f46114f9a8a417116469b44870b | <ide><path>src/TestSuite/TestCase.php
<ide> public function getFixtures()
<ide> 'Setting fixtures as string is deprecated and will be removed in 4.0.' .
<ide> ' Set TestCase::$fixtures as array instead.'
<ide> );
<add>
<ide> return array_map('trim', explode(',', $this->fixtures));
<ide> }
<ide> | 1 |
Javascript | Javascript | use sendevent to fire willinsert/didinsertelement | ddda9e99d61d0960fcd1a6285f795625ac42cabe | <ide><path>packages/ember-metal-views/lib/main.js
<ide> import { set } from "ember-metal/property_set";
<ide> import { lookupView, setupView, teardownView, setupEventDispatcher, reset, events } from "ember-metal-views/events";
<ide> import { setupClassNames, setupClassNameBindings, setupAttributeBindings } from "ember-metal-views/attributes";
<ide> import { Placeholder } from "placeholder";
<add>import { sendEvent } from "ember-metal/events";
<ide>
<ide> // FIXME: don't have a hard dependency on the ember run loop
<ide> // FIXME: avoid render/afterRender getting defined twice
<ide> function childViewsPlaceholder(parentView) {
<ide> function _render(_view) {
<ide> var views = [_view],
<ide> idx = 0,
<del> view, ret, tagName, el;
<add> view, parentView, ret, tagName, el, i, l;
<ide>
<ide> while (idx < views.length) {
<ide> view = views[idx];
<ide> function _render(_view) {
<ide> childView;
<ide>
<ide> if (childViews) {
<del> for (var i = 0, l = childViews.length; i < l; i++) {
<add> for (i = 0, l = childViews.length; i < l; i++) {
<ide> childView = childViews[i];
<ide> childView._parentView = view;
<ide> views.push(childView);
<ide> function _render(_view) {
<ide> if (_view._placeholder) {
<ide> setupEventDispatcher();
<ide>
<del> for (var i = 0, l = views.length; i<l; i++) {
<del> var view = views[i];
<add> for (i = 0, l = views.length; i<l; i++) {
<add> view = views[i];
<ide> if (view.willInsertElement) {
<ide> view.willInsertElement(view.element);
<ide> }
<add> sendEvent(view, 'willInsertElement', view.element);
<ide> }
<ide>
<ide> _view._placeholder.update(ret);
<ide>
<del> for (var i = 0, l = views.length; i<l; i++) {
<del> var view = views[i];
<add> for (i = 0, l = views.length; i<l; i++) {
<add> view = views[i];
<ide> if (view.transitionTo) {
<ide> view.transitionTo('inDOM');
<ide> }
<ide> if (view.didInsertElement) {
<ide> view.didInsertElement(view.element);
<ide> }
<add> sendEvent(view, 'didInsertElement', view.element);
<ide> }
<ide> }
<ide>
<ide> function _findTemplate(view) {
<ide>
<ide> function _renderContents(view, el) {
<ide> var template = _findTemplate(view),
<del> templateOptions = {}, // TODO
<add> templateOptions = view.templateOptions || (view._parentView && view._parentView.templateOptions) || view.constructor.templateOptions || {data: {keywords: {controller: view.controller}}},
<ide> i, l;
<ide>
<ide> if (template) {
<del> if (!view.templateOptions) {
<del> console.log('templateOptions not specified on ', view);
<del> view.templateOptions = {data: {keywords: {controller: view.controller}}};
<del> }
<del> view.templateOptions.data.view = view;
<add> // if (!templateOptions) {
<add> // console.log('templateOptions not specified on ', view);
<add> // view.templateOptions = {data: {keywords: {controller: view.controller}}};
<add> // }
<add> templateOptions.data.view = view;
<ide> if (view.beforeTemplate) { view.beforeTemplate(); }
<del> var templateFragment = template(view, view.templateOptions);
<add> var templateFragment = template(view, templateOptions);
<ide> if (view.isVirtual) {
<ide> el = templateFragment;
<ide> } else {
<ide> function _renderContents(view, el) {
<ide> el.appendChild(templateFragment);
<ide> }
<ide> }
<del> view.templateOptions.data.view = null;
<add> templateOptions.data.view = null;
<ide> } else if (view.textContent) { // TODO: bind?
<ide> el.textContent = view.textContent;
<ide> } else if (view.innerHTML) { // TODO: bind?
<ide> function fakeBufferFor(el) {
<ide> push: function(str) {
<ide> el.innerHTML += str;
<ide> }
<del> }
<add> };
<ide> }
<ide>
<ide> function _triggerRecursively(view, functionOrEventName, skipParent) {
<ide> function contextDidChange(view) {
<ide> var destroy = remove;
<ide> var createElementForView = _createElementForView;
<ide>
<del>export { reset, events, appendTo, render, createChildView, appendChild, remove, destroy, createElementForView }
<add>export { reset, events, appendTo, render, createChildView, appendChild, remove, destroy, createElementForView }; | 1 |
Ruby | Ruby | remove problematic test | 86cc780ea252881cdda4541c3c251af7995224b0 | <ide><path>Library/Homebrew/test/test_tap.rb
<ide> def test_remote
<ide> assert_equal "https://github.com/Homebrew/homebrew-foo", @tap.remote
<ide> assert_raises(TapUnavailableError) { Tap.new("Homebrew", "bar").remote }
<ide> refute_predicate @tap, :custom_remote?
<del> assert_predicate @tap, :private?
<ide>
<ide> version_tap = Tap.new("Homebrew", "versions")
<ide> version_tap.path.mkpath | 1 |
Ruby | Ruby | inline install_bottle? logic into the installer | 7b6fa8b7bb6538650c6915ec19b17c243ea36229 | <ide><path>Library/Homebrew/bottles.rb
<ide> def bottle_filename options={}
<ide> "#{options[:name]}-#{options[:version]}#{bottle_native_suffix(options)}"
<ide> end
<ide>
<del>def install_bottle? f, options={:warn=>false}
<del> return true if f.local_bottle_path
<del> return true if ARGV.force_bottle?
<del> return false unless f.pour_bottle?
<del> return false unless f.bottle
<del>
<del> unless f.bottle.compatible_cellar?
<del> if options[:warn]
<del> opoo "Building source; cellar of #{f}'s bottle is #{f.bottle.cellar}"
<del> end
<del> return false
<del> end
<del>
<del> true
<del>end
<del>
<ide> def built_as_bottle? f
<ide> return false unless f.installed?
<ide> tab = Tab.for_keg(f.installed_prefix)
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def initialize ff
<ide> def pour_bottle? install_bottle_options={:warn=>false}
<ide> return false if @pour_failed
<ide> return false if build_from_source || build_bottle
<del> options.empty? && install_bottle?(f, install_bottle_options)
<add> return false unless options.empty?
<add>
<add> return true if f.local_bottle_path
<add> return true if ARGV.force_bottle?
<add> return false unless f.bottle && f.pour_bottle?
<add>
<add> unless f.bottle.compatible_cellar?
<add> if install_bottle_options[:warn]
<add> opoo "Building source; cellar of #{f}'s bottle is #{f.bottle.cellar}"
<add> end
<add> return false
<add> end
<add>
<add> true
<add> end
<add>
<add> def install_bottle_for_dep?(dep, build)
<add> return false if build_from_source
<add> return false unless dep.bottle && dep.pour_bottle?
<add> return false unless build.used_options.empty?
<add> return false unless dep.bottle.compatible_cellar?
<add> return true
<ide> end
<ide>
<ide> def prelude
<ide> def expand_requirements
<ide>
<ide> if (req.optional? || req.recommended?) && build.without?(req)
<ide> Requirement.prune
<del> elsif req.build? && install_bottle?(dependent)
<add> elsif req.build? && dependent == f && pour_bottle?
<add> Requirement.prune
<add> elsif req.build? && dependent != f && install_bottle_for_dep?(dependent, build)
<ide> Requirement.prune
<ide> elsif req.satisfied?
<ide> Requirement.prune
<ide> def expand_dependencies(deps)
<ide> Dependency.prune
<ide> elsif dep.build? && dependent == f && pour_bottle?
<ide> Dependency.prune
<del> elsif dep.build? && dependent != f && install_bottle?(dependent)
<add> elsif dep.build? && dependent != f && install_bottle_for_dep?(dependent, build)
<ide> Dependency.prune
<ide> elsif dep.satisfied?(options)
<ide> Dependency.skip | 2 |
PHP | PHP | add resources method to router | 3264ebd87c64353bcaaf01e3cd2be2a91271df59 | <ide><path>src/Illuminate/Routing/Router.php
<ide> protected function addFallthroughRoute($controller, $uri)
<ide> $missing->where('_missing', '(.*)');
<ide> }
<ide>
<add> /**
<add> * Register an array of resource controllers.
<add> *
<add> * @param array $resources
<add> * @return void
<add> */
<add> public function resources(array $resources)
<add> {
<add> foreach ($resources as $name => $controller)
<add> {
<add> $this->resource($name, $controller);
<add> }
<add> }
<add>
<ide> /**
<ide> * Route a resource to a controller.
<ide> * | 1 |
Text | Text | fix trivial formatting | 5aaf98d44f00106a7a991cc01e58157078134290 | <ide><path>CHANGELOG.md
<ide> app. This is no longer possible within a single module.
<ide>
<ide>
<ide> - **ngModelOptions:** due to [adfc322b](https://github.com/angular/angular.js/commit/adfc322b04a58158fb9697e5b99aab9ca63c80bb),
<del>
<add>
<ide>
<ide> This commit changes the API on `NgModelController`, both semantically and
<ide> in terms of adding and renaming methods.
<ide> The animation mock module has been renamed from `mock.animate` to `ngAnimateMock
<ide> ## Breaking Changes
<ide>
<ide> - **$http:** due to [e1cfb195](https://github.com/angular/angular.js/commit/e1cfb1957feaf89408bccf48fae6f529e57a82fe),
<del> it is now necessary to separately specify default HTTP headers for PUT, POST and PATCH requests, as these no longer share a single object.
<add> it is now necessary to seperately specify default HTTP headers for PUT, POST and PATCH requests, as these no longer share a single object.
<ide>
<del> To migrate your code, follow the example below:
<add> To migrate your code, follow the example below:
<ide>
<del> Before:
<add> Before:
<ide>
<del> // Will apply to POST, PUT and PATCH methods
<del> $httpProvider.defaults.headers.post = {
<del> "X-MY-CSRF-HEADER": "..."
<del> };
<add> ```
<add> // Will apply to POST, PUT and PATCH methods
<add> $httpProvider.defaults.headers.post = {
<add> "X-MY-CSRF-HEADER": "..."
<add> };
<add> ```
<ide>
<del> After:
<add> After:
<ide>
<del> // POST, PUT and PATCH default headers must be specified separately,
<del> // as they do not share data.
<del> $httpProvider.defaults.headers.post =
<del> $httpProvider.defaults.headers.put =
<del> $httpProviders.defaults.headers.patch = {
<del> "X-MY-CSRF-HEADER": "..."
<del> };
<add> ```
<add> // POST, PUT and PATCH default headers must be specified seperately,
<add> // as they do not share data.
<add> $httpProvider.defaults.headers.post =
<add> $httpProvider.defaults.headers.put =
<add> $httpProviders.defaults.headers.patch = {
<add> "X-MY-CSRF-HEADER": "..."
<add> };
<add> ```
<ide>
<ide> <a name="1.2.8"></a>
<ide> # 1.2.8 interdimensional-cartography (2014-01-10)
<ide><path>CONTRIBUTING.md
<ide> project.
<ide>
<ide>
<ide> ## <a name="docs"></a> Want a Doc Fix?
<del>If you want to help improve the docs, it's a good idea to let others know what you're working on to
<del>minimize duplication of effort. Before starting, check out the issue queue for [Milestone:Docs Only](https://github.com/angular/angular.js/issues?milestone=24&state=open).
<add>If you want to help improve the docs, it's a good idea to let others know what you're working on to
<add>minimize duplication of effort. Before starting, check out the issue queue for
<add>[Milestone:Docs Only](https://github.com/angular/angular.js/issues?milestone=24&state=open).
<ide> Comment on an issue to let others know what you're working on, or create a new issue if your work
<ide> doesn't fit within the scope of any of the existing doc fix projects.
<ide> | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.