content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Text | Text | add link to doc with social processes | 9bc00fd66c56a427bb3ccff541dc0bcd670d93aa | <ide><path>doc/contributing/suggesting-social-media-posts.md
<add># Suggesting Social Media Posts
<add>
<add>Node.js social media is managed by OpenJS Foundation staff. The processes are
<add>documented in
<add>[Node.js Social Amplification Request Guidelines](https://docs.google.com/document/d/1yrYZJ2twrbpUuScbo3rmN_v-Jfv6d2tO74nCT6PcpxI). | 1 |
Java | Java | copy cookies to serverresponse builders | 4ca27db0ccc35b31ac7a9fdfd66a9a6fd91d13ca | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilder.java
<ide> public EntityResponse.Builder<T> header(String headerName, String... headerValue
<ide> }
<ide>
<ide> @Override
<del> public EntityResponse.Builder<T> headers(HttpHeaders headers) {
<del> this.headers.putAll(headers);
<add> public EntityResponse.Builder<T> headers(Consumer<HttpHeaders> headersConsumer) {
<add> headersConsumer.accept(this.headers);
<ide> return this;
<ide> }
<ide>
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultRenderingResponseBuilder.java
<ide> public RenderingResponse.Builder header(String headerName, String... headerValue
<ide> }
<ide>
<ide> @Override
<del> public RenderingResponse.Builder headers(HttpHeaders headers) {
<del> this.headers.putAll(headers);
<add> public RenderingResponse.Builder headers(Consumer<HttpHeaders> headersConsumer) {
<add> headersConsumer.accept(this.headers);
<ide> return this;
<ide> }
<ide>
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerResponseBuilder.java
<ide> public ServerResponse build(
<ide> @Override
<ide> public ServerResponse body(Object body) {
<ide> return DefaultEntityResponseBuilder.fromObject(body)
<del> .headers(this.headers)
<ide> .status(this.statusCode)
<add> .headers(headers -> headers.putAll(this.headers))
<add> .cookies(cookies -> cookies.addAll(this.cookies))
<ide> .build();
<ide> }
<ide>
<ide> @Override
<ide> public <T> ServerResponse body(T body, ParameterizedTypeReference<T> bodyType) {
<ide> return DefaultEntityResponseBuilder.fromObject(body, bodyType)
<del> .headers(this.headers)
<ide> .status(this.statusCode)
<add> .headers(headers -> headers.putAll(this.headers))
<add> .cookies(cookies -> cookies.addAll(this.cookies))
<ide> .build();
<ide> }
<ide>
<ide> @Override
<ide> public ServerResponse render(String name, Object... modelAttributes) {
<ide> return new DefaultRenderingResponseBuilder(name)
<del> .headers(this.headers)
<ide> .status(this.statusCode)
<add> .headers(headers -> headers.putAll(this.headers))
<add> .cookies(cookies -> cookies.addAll(this.cookies))
<ide> .modelAttributes(modelAttributes)
<ide> .build();
<ide> }
<ide>
<ide> @Override
<ide> public ServerResponse render(String name, Map<String, ?> model) {
<ide> return new DefaultRenderingResponseBuilder(name)
<del> .headers(this.headers)
<ide> .status(this.statusCode)
<add> .headers(headers -> headers.putAll(this.headers))
<add> .cookies(cookies -> cookies.addAll(this.cookies))
<ide> .modelAttributes(model)
<ide> .build();
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/EntityResponse.java
<ide> static <T> Builder<T> fromObject(T t, ParameterizedTypeReference<T> entityType)
<ide> Builder<T> header(String headerName, String... headerValues);
<ide>
<ide> /**
<del> * Copy the given headers into the entity's headers map.
<del> * @param headers the existing HttpHeaders to copy from
<add> * Manipulate this response's headers with the given consumer. The
<add> * headers provided to the consumer are "live", so that the consumer can be used to
<add> * {@linkplain HttpHeaders#set(String, String) overwrite} existing header values,
<add> * {@linkplain HttpHeaders#remove(Object) remove} values, or use any of the other
<add> * {@link HttpHeaders} methods.
<add> * @param headersConsumer a function that consumes the {@code HttpHeaders}
<ide> * @return this builder
<del> * @see HttpHeaders#add(String, String)
<ide> */
<del> Builder<T> headers(HttpHeaders headers);
<add> Builder<T> headers(Consumer<HttpHeaders> headersConsumer);
<ide>
<ide> /**
<ide> * Set the HTTP status.
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/RenderingResponse.java
<ide> interface Builder {
<ide> Builder header(String headerName, String... headerValues);
<ide>
<ide> /**
<del> * Copy the given headers into the entity's headers map.
<del> * @param headers the existing HttpHeaders to copy from
<add> * Manipulate this response's headers with the given consumer. The
<add> * headers provided to the consumer are "live", so that the consumer can be used to
<add> * {@linkplain HttpHeaders#set(String, String) overwrite} existing header values,
<add> * {@linkplain HttpHeaders#remove(Object) remove} values, or use any of the other
<add> * {@link HttpHeaders} methods.
<add> * @param headersConsumer a function that consumes the {@code HttpHeaders}
<ide> * @return this builder
<del> * @see HttpHeaders#add(String, String)
<ide> */
<del> Builder headers(HttpHeaders headers);
<add> Builder headers(Consumer<HttpHeaders> headersConsumer);
<ide>
<ide> /**
<ide> * Set the HTTP status.
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilderTests.java
<ide> public void headers() {
<ide> String body = "foo";
<ide> HttpHeaders headers = new HttpHeaders();
<ide> headers.set("foo", "bar");
<del> EntityResponse<String> result = EntityResponse.fromObject(body).headers(headers).build();
<add> EntityResponse<String> result = EntityResponse.fromObject(body)
<add> .headers(h -> h.addAll(headers))
<add> .build();
<ide> assertEquals(headers, result.headers());
<ide> }
<ide>
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultRenderingResponseTests.java
<ide> public void status() throws Exception {
<ide> public void headers() throws Exception {
<ide> HttpHeaders headers = new HttpHeaders();
<ide> headers.set("foo", "bar");
<del> RenderingResponse result = RenderingResponse.create("foo").headers(headers).build();
<add> RenderingResponse result = RenderingResponse.create("foo")
<add> .headers(h -> h.addAll(headers))
<add> .build();
<ide>
<ide> MockHttpServletRequest request = new MockHttpServletRequest();
<ide> MockHttpServletResponse response = new MockHttpServletResponse(); | 7 |
Python | Python | fix typo and grammar errors | 527ce2981bc4efe7b5d6ad273880d93f4a26d7fb | <ide><path>official/core/base_task.py
<ide> def logging_dir(self) -> str:
<ide> def initialize(self, model: tf.keras.Model):
<ide> """A callback function used as CheckpointManager's init_fn.
<ide>
<del> This function will be called when no checkpoint found for the model.
<add> This function will be called when no checkpoint is found for the model.
<ide> If there is a checkpoint, the checkpoint will be loaded and this function
<ide> will not be called. You can use this callback function to load a pretrained
<ide> checkpoint, saved under a directory other than the model_dir.
<ide> def initialize(self, model: tf.keras.Model):
<ide>
<ide> @abc.abstractmethod
<ide> def build_model(self) -> tf.keras.Model:
<del> """Creates the model architecture.
<add> """Creates model architecture.
<ide>
<ide> Returns:
<ide> A model instance.
<ide> def build_losses(self, labels, model_outputs, aux_losses=None) -> tf.Tensor:
<ide> Args:
<ide> labels: optional label tensors.
<ide> model_outputs: a nested structure of output tensors.
<del> aux_losses: auxiliarly loss tensors, i.e. `losses` in keras.Model.
<add> aux_losses: auxiliary loss tensors, i.e. `losses` in keras.Model.
<ide>
<ide> Returns:
<ide> The total loss tensor.
<ide> def train_step(self,
<ide> return logs
<ide>
<ide> def validation_step(self, inputs, model: tf.keras.Model, metrics=None):
<del> """Validatation step.
<add> """Validation step.
<ide>
<ide> With distribution strategies, this method runs on devices.
<ide> | 1 |
Ruby | Ruby | add gtk-mac-integration 2.1.3 | 40c3184f82d15e0a1cfb9d40c084ad9f50ab09b5 | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_specs
<ide> gnome_devel_whitelist = %w[
<ide> libart 2.3.21
<ide> pygtkglext 1.1.0
<add> gtk-mac-integration 2.1.3
<ide> ].each_slice(2).to_a.map do |formula, version|
<ide> [formula, version.split(".")[0..1].join(".")]
<ide> end | 1 |
Javascript | Javascript | check writereport when error with one line stack | 1c989c9f546cc811ebbd1e930a9a57caf4fc80e0 | <ide><path>test/report/test-report-writereport.js
<ide> function validate() {
<ide> validate();
<ide> }
<ide>
<add>{
<add> // Test with an error with one line stack
<add> const error = new Error();
<add> error.stack = 'only one line';
<add> process.report.writeReport(error);
<add> validate();
<add>}
<add>
<ide> {
<ide> // Test with a file argument.
<ide> const file = process.report.writeReport('custom-name-1.json'); | 1 |
Python | Python | add classes for exceptions | b2c0c1df52e7dc083b9e52633ce2afccc9e86f0d | <ide><path>libcloud/dns/types.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide>
<add>from libcloud.common.types import LibcloudError
<add>
<ide> __all__ = [
<del> 'RecordType'
<add> 'RecordType',
<add> 'ZoneError',
<add> 'ZoneDoesNotExistError',
<add> 'ZoneAlreadyExistsError',
<add> 'RecordError',
<add> 'RecordDoesNotExistError',
<add> 'RecordAlreadyExistsError'
<ide> ]
<ide>
<ide>
<ide> class RecordType(object):
<ide> SOA = 8
<ide> SPF = 9
<ide> SRV = 10
<add>
<add>
<add>class ZoneError(LibcloudError):
<add> error_type = 'ZoneError'
<add>
<add> def __init__(self, value, driver, zone_id):
<add> self.zone_id = zone_id
<add> super(ZoneError, self).__init__(value=value, driver=driver)
<add>
<add> def __str__(self):
<add> return ('<%s in %s, zone_id=%s, value=%s>' %
<add> (self.error_type, repr(self.driver),
<add> self.zone_id, self.value))
<add>
<add>
<add>class ZoneDoesNotExistError(ZoneError):
<add> error_type = 'ZoneDoesNotExistError'
<add>
<add>
<add>class ZoneAlreadyExistsError(ZoneError):
<add> error_type = 'ZoneAlreadyExistsError'
<add>
<add>
<add>class RecordError(LibcloudError):
<add> error_type = 'RecordError'
<add>
<add> def __init__(self, value, driver, record_id):
<add> self.record_id = record_id
<add> super(RecordError, self).__init__(value=value, driver=driver)
<add>
<add> def __str__(self):
<add> return ('<%s in %s, record_id=%s, value=%s>' %
<add> (self.error_type, repr(self.driver),
<add> self.record_id, self.value))
<add>
<add>
<add>class RecordDoesNotExistError(RecordError):
<add> error_type = 'RecordDoesNotExistError'
<add>
<add>
<add>class RecordAlreadyExistsError(RecordError):
<add> error_type = 'RecordAlreadyExistsError' | 1 |
PHP | PHP | fix broken primary key check for sqliteschema | e6deb49ea968695c31765c5da1cdb8fded2787b5 | <ide><path>src/Database/Schema/SqliteSchema.php
<ide> public function convertColumnDescription(Table $table, $row) {
<ide> 'null' => !$row['notnull'],
<ide> 'default' => $row['dflt_value'] === null ? null : trim($row['dflt_value'], "'"),
<ide> ];
<del> if ($row['pk'] === true) {
<add> if ($row['pk']) {
<ide> $field['null'] = false;
<ide> $field['autoIncrement'] = true;
<ide> }
<ide> $table->addColumn($row['name'], $field);
<del> if ($row['pk'] === true) {
<add> if ($row['pk']) {
<ide> $constraint = (array)$table->constraint('primary') + [
<ide> 'type' => Table::CONSTRAINT_PRIMARY,
<ide> 'columns' => [] | 1 |
PHP | PHP | add test for dynamic relations of models | 7e05da7dcd7bbceb3f36a047e091b02d630f5cfb | <ide><path>tests/Database/DatabaseEloquentDynamicRelationsTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Database;
<add>
<add>use Illuminate\Database\Eloquent\Builder;
<add>use Illuminate\Database\Eloquent\Model;
<add>use Illuminate\Database\Eloquent\Relations\HasMany;
<add>use Illuminate\Database\Eloquent\Relations\HasOne;
<add>use Illuminate\Database\Query\Builder as Query;
<add>use Illuminate\Tests\Database\DynamicRelationModel2 as Related;
<add>use PHPUnit\Framework\TestCase;
<add>
<add>class DatabaseEloquentDynamicRelationsTest extends TestCase
<add>{
<add> public function testBasicDynamicRelations()
<add> {
<add> DynamicRelationModel::resolveRelationUsing('dynamicRel_2', fn () => new FakeHasManyRel);
<add> $model = new DynamicRelationModel;
<add> $this->assertEquals(['many' => 'related'], $model->dynamicRel_2);
<add> $this->assertEquals(['many' => 'related'], $model->getRelationValue('dynamicRel_2'));
<add> }
<add>
<add> public function testDynamicRelationsOverride()
<add> {
<add> // Dynamic Relations can override each other.
<add> DynamicRelationModel::resolveRelationUsing('dynamicRelConflict', fn ($m) => $m->hasOne(Related::class));
<add> DynamicRelationModel::resolveRelationUsing('dynamicRelConflict', fn (DynamicRelationModel $m) => new FakeHasManyRel);
<add>
<add> $model = new DynamicRelationModel;
<add> $this->assertInstanceOf(HasMany::class, $model->dynamicRelConflict());
<add> $this->assertEquals(['many' => 'related'], $model->dynamicRelConflict);
<add> $this->assertEquals(['many' => 'related'], $model->getRelationValue('dynamicRelConflict'));
<add> $this->assertTrue($model->isRelation('dynamicRelConflict'));
<add> }
<add>
<add> public function testDynamicRelationsCanNotHaveTheSameNameAsNormalRelations()
<add> {
<add> $model = new DynamicRelationModel;
<add>
<add> // Dynamic relations can not override hard-coded methods.
<add> DynamicRelationModel::resolveRelationUsing('hardCodedRelation', fn ($m) => $m->hasOne(Related::class));
<add> $this->assertInstanceOf(HasMany::class, $model->hardCodedRelation());
<add> $this->assertEquals(['many' => 'related'], $model->hardCodedRelation);
<add> $this->assertEquals(['many' => 'related'], $model->getRelationValue('hardCodedRelation'));
<add> $this->assertTrue($model->isRelation('hardCodedRelation'));
<add> }
<add>
<add> public function testRelationResolvers()
<add> {
<add> $model1 = new DynamicRelationModel;
<add> $model3 = new DynamicRelationModel3;
<add>
<add> // Same dynamic methods with the same name on two models do not conflict or override.
<add> DynamicRelationModel::resolveRelationUsing('dynamicRel', fn ($m) => $m->hasOne(Related::class));
<add> DynamicRelationModel3::resolveRelationUsing('dynamicRel', fn (DynamicRelationModel3 $m) => $m->hasMany(Related::class));
<add> $this->assertInstanceOf(HasOne::class, $model1->dynamicRel());
<add> $this->assertInstanceOf(HasMany::class, $model3->dynamicRel());
<add> $this->assertTrue($model1->isRelation('dynamicRel'));
<add> $this->assertTrue($model3->isRelation('dynamicRel'));
<add> }
<add>}
<add>
<add>class DynamicRelationModel extends Model
<add>{
<add> public function hardCodedRelation()
<add> {
<add> return new FakeHasManyRel();
<add> }
<add>}
<add>
<add>class DynamicRelationModel2 extends Model
<add>{
<add> public function getResults()
<add> {
<add> //
<add> }
<add>
<add> public function newQuery()
<add> {
<add> $query = new class extends Query
<add> {
<add> public function __construct()
<add> {
<add> //
<add> }
<add> };
<add>
<add> return new Builder($query);
<add> }
<add>}
<add>
<add>class DynamicRelationModel3 extends Model
<add>{
<add> //
<add>}
<add>
<add>class FakeHasManyRel extends HasMany
<add>{
<add> public function __construct()
<add> {
<add> //
<add> }
<add>
<add> public function getResults()
<add> {
<add> return ['many' => 'related'];
<add> }
<add>}
<ide><path>tests/Database/DatabaseEloquentRelationTest.php
<ide> public function testMacroable()
<ide> $this->assertSame('foo', $result);
<ide> }
<ide>
<del> public function testRelationResolvers()
<del> {
<del> $model = new EloquentRelationResetModelStub;
<del> $builder = m::mock(Builder::class);
<del> $builder->shouldReceive('getModel')->andReturn($model);
<del>
<del> EloquentRelationResetModelStub::resolveRelationUsing('customer', function ($model) use ($builder) {
<del> return new EloquentResolverRelationStub($builder, $model);
<del> });
<del>
<del> $this->assertInstanceOf(EloquentResolverRelationStub::class, $model->customer());
<del> $this->assertSame(['key' => 'value'], $model->customer);
<del> }
<del>
<ide> public function testIsRelationIgnoresAttribute()
<ide> {
<ide> $model = new EloquentRelationAndAtrributeModelStub;
<ide> class EloquentNoTouchingAnotherModelStub extends Model
<ide> ];
<ide> }
<ide>
<del>class EloquentResolverRelationStub extends EloquentRelationStub
<del>{
<del> public function getResults()
<del> {
<del> return ['key' => 'value'];
<del> }
<del>}
<del>
<ide> class EloquentRelationAndAtrributeModelStub extends Model
<ide> {
<ide> protected $table = 'one_more_table'; | 2 |
PHP | PHP | fix tests for mysql driver | f128a349523577a8d193caa614864113c791dcc4 | <ide><path>src/Database/Driver/Mysql.php
<ide> public function connect()
<ide> $this->_connect($dsn, $config);
<ide>
<ide> if (!empty($config['init'])) {
<add> $connection = $this->connection();
<ide> foreach ((array)$config['init'] as $command) {
<del> $this->connection()->exec($command);
<add> $connection->exec($command);
<ide> }
<ide> }
<ide> return true;
<ide><path>tests/TestCase/Database/Driver/MysqlTest.php
<ide> class MysqlTest extends TestCase
<ide> public function setup()
<ide> {
<ide> parent::setUp();
<del> $config = Configure::read('Datasource.test');
<del> $this->skipIf(strpos($config['datasource'], 'Mysql') === false, 'Not using Mysql for test config');
<add> $config = ConnectionManager::config('test');
<add> $this->skipIf(strpos($config['driver'], 'Mysql') === false, 'Not using Mysql for test config');
<ide> }
<ide>
<ide> /**
<ide> public function setup()
<ide> */
<ide> public function testConnectionConfigDefault()
<ide> {
<del> $driver = $this->getMock('Cake\Database\Driver\Mysql', ['_connect']);
<add> $driver = $this->getMock('Cake\Database\Driver\Mysql', ['_connect', 'connection']);
<ide> $dsn = 'mysql:host=localhost;port=3306;dbname=cake;charset=utf8';
<ide> $expected = [
<ide> 'persistent' => true,
<ide> public function testConnectionConfigDefault()
<ide> 'flags' => [],
<ide> 'encoding' => 'utf8',
<ide> 'timezone' => null,
<del> 'init' => [],
<add> 'init' => ['SET NAMES utf8'],
<ide> ];
<ide>
<ide> $expected['flags'] += [
<ide> PDO::ATTR_PERSISTENT => true,
<ide> PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
<ide> PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
<ide> ];
<add> $connection = $this->getMock('StdClass', ['exec']);
<add>
<ide> $driver->expects($this->once())->method('_connect')
<ide> ->with($dsn, $expected);
<add>
<add> $driver->expects($this->any())
<add> ->method('connection')
<add> ->will($this->returnValue($connection));
<ide> $driver->connect([]);
<ide> }
<ide>
<ide> public function testConnectionConfigCustom()
<ide> 'flags' => [1 => true, 2 => false],
<ide> 'encoding' => 'a-language',
<ide> 'timezone' => 'Antartica',
<del> 'init' => ['Execute this', 'this too']
<add> 'init' => [
<add> 'Execute this',
<add> 'this too',
<add> ]
<ide> ];
<ide> $driver = $this->getMock(
<ide> 'Cake\Database\Driver\Mysql',
<ide> public function testConnectionConfigCustom()
<ide> $dsn = 'mysql:host=foo;port=3440;dbname=bar;charset=a-language';
<ide> $expected = $config;
<ide> $expected['init'][] = "SET time_zone = 'Antartica'";
<add> $expected['init'][] = "SET NAMES a-language";
<ide> $expected['flags'] += [
<ide> PDO::ATTR_PERSISTENT => false,
<ide> PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
<ide> public function testConnectionConfigCustom()
<ide> $connection->expects($this->at(0))->method('exec')->with('Execute this');
<ide> $connection->expects($this->at(1))->method('exec')->with('this too');
<ide> $connection->expects($this->at(2))->method('exec')->with("SET time_zone = 'Antartica'");
<del> $connection->expects($this->exactly(3))->method('exec');
<add> $connection->expects($this->at(3))->method('exec')->with("SET NAMES a-language");
<add> $connection->expects($this->exactly(4))->method('exec');
<ide>
<ide> $driver->expects($this->once())->method('_connect')
<ide> ->with($dsn, $expected); | 2 |
Ruby | Ruby | reset time.zone to avoid leaking into other tests | 65d7aa5811075cccf1f0b7504372cad2ed3f8e7f | <ide><path>activejob/test/cases/timezones_test.rb
<ide> class TimezonesTest < ActiveSupport::TestCase
<ide> end
<ide>
<ide> assert_equal "Happy New Year!", JobBuffer.last_value
<add> ensure
<add> Time.zone = nil
<ide> end
<ide> end | 1 |
Javascript | Javascript | remove flare bundles from build | 2512c309e34f0207d29c19392d144edab719f347 | <ide><path>scripts/rollup/bundles.js
<ide> const bundles = [
<ide> externals: ['react'],
<ide> },
<ide>
<del> {
<del> bundleTypes: [
<del> UMD_DEV,
<del> UMD_PROD,
<del> NODE_DEV,
<del> NODE_PROD,
<del> FB_WWW_DEV,
<del> FB_WWW_PROD,
<del> ],
<del> moduleType: NON_FIBER_RENDERER,
<del> entry: 'react-interactions/events/input',
<del> global: 'ReactEventsInput',
<del> externals: ['react'],
<del> },
<del>
<ide> {
<ide> bundleTypes: [
<ide> UMD_DEV,
<ide> const bundles = [
<ide> externals: ['react'],
<ide> },
<ide>
<del> {
<del> bundleTypes: [
<del> UMD_DEV,
<del> UMD_PROD,
<del> NODE_DEV,
<del> NODE_PROD,
<del> FB_WWW_DEV,
<del> FB_WWW_PROD,
<del> ],
<del> moduleType: NON_FIBER_RENDERER,
<del> entry: 'react-interactions/events/press',
<del> global: 'ReactEventsPress',
<del> externals: [
<del> 'react',
<del> 'react-interactions/events/tap',
<del> 'react-interactions/events/keyboard',
<del> ],
<del> },
<del>
<ide> {
<ide> bundleTypes: [
<ide> UMD_DEV,
<ide> const bundles = [
<ide> global: 'ReactEventsPressLegacy',
<ide> externals: ['react'],
<ide> },
<del>
<del> {
<del> bundleTypes: [
<del> UMD_DEV,
<del> UMD_PROD,
<del> NODE_DEV,
<del> NODE_PROD,
<del> FB_WWW_DEV,
<del> FB_WWW_PROD,
<del> ],
<del> moduleType: NON_FIBER_RENDERER,
<del> entry: 'react-interactions/events/tap',
<del> global: 'ReactEventsTap',
<del> externals: ['react'],
<del> },
<ide> ];
<ide>
<ide> const fbBundleExternalsMap = { | 1 |
Mixed | Ruby | add implicit to path conversion to uploaded file | 20543c049625784a91944efdebc1d0c397406f21 | <ide><path>actionpack/CHANGELOG.md
<add>* `ActionDispatch::Http::UploadedFile` now delegates `to_path` to its tempfile.
<add>
<add> This allows uploaded file objects to be passed directly to `File.read`
<add> without raising a `TypeError`:
<add>
<add> uploaded_file = ActionDispatch::Http::UploadedFile.new(tempfile: tmp_file)
<add> File.read(uploaded_file)
<add>
<add> *Aaron Kromer*
<add>
<ide> * Pass along arguments to underlying `get` method in `follow_redirect!`
<ide>
<ide> Now all arguments passed to `follow_redirect!` are passed to the underlying
<ide><path>actionpack/lib/action_dispatch/http/upload.rb
<ide> def path
<ide> @tempfile.path
<ide> end
<ide>
<add> # Shortcut for +tempfile.to_path+.
<add> def to_path
<add> @tempfile.to_path
<add> end
<add>
<ide> # Shortcut for +tempfile.rewind+.
<ide> def rewind
<ide> @tempfile.rewind
<ide><path>actionpack/test/dispatch/uploaded_file_test.rb
<ide> def test_delegate_eof_to_tempfile
<ide> assert_predicate uf, :eof?
<ide> end
<ide>
<add> def test_delegate_to_path_to_tempfile
<add> tf = Class.new { def to_path; "/any/file/path" end; }
<add> uf = Http::UploadedFile.new(tempfile: tf.new)
<add> assert_equal "/any/file/path", uf.to_path
<add> end
<add>
<ide> def test_respond_to?
<ide> tf = Class.new { def read; yield end }
<ide> uf = Http::UploadedFile.new(tempfile: tf.new) | 3 |
Javascript | Javascript | remove a broken jqlite cache clearing | feee36c8c9e17d47e044c085012128108ce36b76 | <ide><path>test/ngMock/angular-mocksSpec.js
<ide> describe('sharedInjector', function() {
<ide> define();
<ide> sdescribe.root.run();
<ide> } finally {
<del> // avoid failing testability for the additional
<del> // injectors etc created
<del> angular.element.cache = {};
<del>
<ide> // clear up
<ide> module.$$beforeAllHook = null;
<ide> module.$$afterAllHook = null; | 1 |
Python | Python | remove name keyword argument to register | a31e8ce4c91f5d9ff41863456836f53082e54199 | <ide><path>celery/registry.py
<ide> def autodiscover(self):
<ide> """Autodiscovers tasks using :func:`celery.discovery.autodiscover`."""
<ide> discovery.autodiscover()
<ide>
<del> def register(self, task, name=None):
<add> def register(self, task):
<ide> """Register a task in the task registry.
<ide>
<ide> Task can either be a regular function, or a class inheriting
<ide> def register(self, task, name=None):
<ide> """
<ide>
<ide> task = task() if inspect.isclass(task) else task
<del>
<del> if not name:
<del> name = getattr(task, "name")
<add> name = task.name
<ide>
<ide> if name in self.data:
<ide> raise self.AlreadyRegistered( | 1 |
Text | Text | add blurb about angularjs to readme.md | a8b04004e3200b988543b0f2842d9071988d10c9 | <ide><path>README.md
<ide> AngularJS
<ide> =========
<ide>
<add>AngularJS lets you write client-side web applications as if you had a smarter browser. It lets use
<add>good old HTML (or HAML, Jade and friends!) as your template language and lets you extend HTML’s
<add>syntax to express your application’s components clearly and succinctly. It automatically
<add>synchronizes data from your UI (view) with your JavaScript objects (model) through 2-way data
<add>binding. To help you structure your application better and make it easy to test AngularJS teaches
<add>the browser how to do dependency injection and inversion of control. Oh yeah and it also helps with
<add>server-side communication, taming async callbacks with promises and deferreds; and make client-side
<add>navigation and deeplinking with hashbang urls or HTML5 pushState a piece of cake. The most important
<add>of all: it makes development fun!
<add>
<ide> * Web site: http://angularjs.org
<del>* Tutorial: http://docs.angularjs.org/#!/tutorial
<add>* Tutorial: http://docs.angularjs.org/tutorial
<ide> * API Docs: http://docs.angularjs.org
<del>* Developer Guide: http://docs.angularjs.org/#!/guide
<add>* Developer Guide: http://docs.angularjs.org/guide
<ide>
<ide> Compiling
<ide> --------- | 1 |
Text | Text | add section on mixins | 9f1fc32cf45be8c4436f1e97656a681f963a08d7 | <ide><path>guide/english/css/css-preprocessors/index.md
<ide> Yet another feature which CSS lacks are If/Else statements. These will run a set
<ide> ```
<ide> Here, the background color will change color depending on the width of the page's body.
<ide>
<add>### Mixins
<add>There are probably portions of your styling you would like to reuse. Mixins allow you to group any number of properties under one common name. You declare mixin with the @mixin <name> and use it with the @include <name>.
<ide>
<ide> These are but a few of the major functions of CSS Preprocessors. As you can see, CSS Preprocessors are incredibly useful and versatile tools. Many web developers use them, and it is highly recommended to learn at least one of them.
<ide> #### More Information: | 1 |
PHP | PHP | convert arrayable attributes to array | 29560b5e3c8a115e358df1ffef40baf3de019c90 | <ide><path>src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
<ide> public function attributesToArray()
<ide> foreach ($this->getArrayableAppends() as $key) {
<ide> $attributes[$key] = $this->mutateAttributeForArray($key, null);
<ide> }
<add>
<add> foreach ($attributes as $key => $value) {
<add> if ($value instanceof Arrayable) {
<add> $attributes[$key] = $value->toArray();
<add> }
<add> }
<ide>
<ide> return $attributes;
<ide> } | 1 |
Javascript | Javascript | add highlights class for package compatibility | 207cd310549b26eddcea46b48017f8f4e38a495c | <ide><path>src/text-editor-component.js
<ide> class LinesTileComponent {
<ide>
<ide> return $.div(
<ide> {
<add> className: 'highlights',
<ide> style: {
<ide> position: 'absolute',
<ide> contain: 'strict', | 1 |
Text | Text | update time to first byte (ttfb) link | a0275f27508d5d726d8afb9ef472068b66f3484c | <ide><path>docs/basic-features/data-fetching/get-server-side-props.md
<ide> The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/get-s
<ide>
<ide> ## When should I use getServerSideProps
<ide>
<del>You should use `getServerSideProps` only if you need to pre-render a page whose data must be fetched at request time. [Time to First Byte (TTFB)](/learn/seo/web-performance) will be higher than [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) because the server must compute the result on every request, and the result can only be cached by a CDN using `cache-control` headers (which could require extra configuration).
<add>You should use `getServerSideProps` only if you need to pre-render a page whose data must be fetched at request time. [Time to First Byte (TTFB)](https://web.dev/ttfb/) will be higher than [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) because the server must compute the result on every request, and the result can only be cached by a CDN using `cache-control` headers (which could require extra configuration).
<ide>
<ide> If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side).
<ide> | 1 |
Go | Go | check nil terminal to avoid panic | 7f0d304f3767d4f33d23480a3ca2f54bb72938b7 | <ide><path>container/container.go
<ide> func (container *Container) ExitOnNext() {
<ide> // Resize changes the TTY of the process running inside the container
<ide> // to the given height and width. The container must be running.
<ide> func (container *Container) Resize(h, w int) error {
<add> if container.Command.ProcessConfig.Terminal == nil {
<add> return fmt.Errorf("Container %s does not have a terminal ready", container.ID)
<add> }
<ide> if err := container.Command.ProcessConfig.Terminal.Resize(h, w); err != nil {
<ide> return err
<ide> } | 1 |
Javascript | Javascript | use countdown timer | 7d2b08a3b55ef46719436a1445e207e34d6a355d | <ide><path>test/parallel/test-http-response-status-message.js
<ide> require('../common');
<ide> const assert = require('assert');
<ide> const http = require('http');
<ide> const net = require('net');
<del>
<del>let testsComplete = 0;
<add>const Countdown = require('../common/countdown');
<ide>
<ide> const testCases = [
<ide> { path: '/200', statusMessage: 'OK',
<ide> const server = net.createServer(function(connection) {
<ide> });
<ide> });
<ide>
<add>const countdown = new Countdown(testCases.length, () => server.close());
<add>
<ide> function runTest(testCaseIndex) {
<ide> const testCase = testCases[testCaseIndex];
<ide>
<ide> function runTest(testCaseIndex) {
<ide> assert.strictEqual(testCase.statusMessage, response.statusMessage);
<ide>
<ide> response.on('end', function() {
<del> testsComplete++;
<del>
<add> countdown.dec();
<ide> if (testCaseIndex + 1 < testCases.length) {
<ide> runTest(testCaseIndex + 1);
<del> } else {
<del> server.close();
<ide> }
<ide> });
<ide>
<ide> function runTest(testCaseIndex) {
<ide> }
<ide>
<ide> server.listen(0, function() { runTest(0); });
<del>
<del>process.on('exit', function() {
<del> assert.strictEqual(testCases.length, testsComplete);
<del>}); | 1 |
PHP | PHP | add reference to model in massassignmentexception | d84a0e2334d0732f560b34b7cb5307a4ea4389c2 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function fill(array $attributes)
<ide> if ($this->isFillable($key)) {
<ide> $this->setAttribute($key, $value);
<ide> } elseif ($totallyGuarded) {
<add> $model = get_class($this);
<ide> throw new MassAssignmentException(
<del> "Add [{$key}] to fillable property to allow mass assignment."
<add> "Add [{$key}] to fillable property to allow mass assignment on {$model}."
<ide> );
<ide> }
<ide> } | 1 |
Java | Java | implement review feedback | 9e79b344ca02c7dd04d59f5c7567e29947b79c22 | <ide><path>spring-web-reactive/src/main/java/org/springframework/core/codec/support/StringDecoder.java
<ide> public class StringDecoder extends AbstractDecoder<String> {
<ide>
<ide> public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
<del> public static final String EMPTY = "";
<ide>
<ide> private final boolean reduceToSingleBuffer;
<ide>
<ide> public Flux<String> decode(Publisher<DataBuffer> inputStream, ResolvableType typ
<ide> }
<ide> Charset charset = getCharset(mimeType);
<ide> return inputFlux.map(content -> {
<del> // fast-path exit.
<del> if(content.readableByteCount() == 0) {
<del> return EMPTY;
<del> }
<del>
<ide> CharBuffer charBuffer = charset.decode(content.asByteBuffer());
<ide> return charBuffer.toString();
<ide> });
<ide><path>spring-web-reactive/src/test/java/org/springframework/core/codec/support/StringDecoderTests.java
<ide> public void decodeSingle() throws InterruptedException {
<ide>
<ide> @Test
<ide> public void decodeEmpty() throws InterruptedException {
<del> Flux<DataBuffer> source = Flux.just(stringBuffer(""));
<del> Single<String> single = RxJava1SingleConverter.from(this.decoder.decode(source,
<del> ResolvableType.forClassWithGenerics(Single.class, String.class),
<del> MediaType.TEXT_PLAIN));
<del> String result = single.toBlocking().value();
<del> assertEquals("", result);
<add> Mono<DataBuffer> source = Mono.just(stringBuffer(""));
<add> Flux<String> output =
<add> this.decoder.decode(source, ResolvableType.forClass(String.class), null);
<add> TestSubscriber<String> testSubscriber = new TestSubscriber<>();
<add> testSubscriber.bindTo(output).assertValues("");
<ide> }
<ide>
<ide> } | 2 |
Javascript | Javascript | expose `getviewbounds` on `viewutils` | dfbb59fa85cce50cba299b5fdbb85b89a28e07fa | <ide><path>packages/ember-views/lib/index.js
<ide> import Ember from 'ember-runtime';
<ide> import jQuery from 'ember-views/system/jquery';
<ide> import {
<ide> isSimpleClick,
<add> getViewBounds,
<ide> getViewClientRects,
<ide> getViewBoundingClientRect,
<ide> getRootViews,
<ide> Ember.ViewTargetActionSupport = ViewTargetActionSupport;
<ide>
<ide> const ViewUtils = Ember.ViewUtils = {};
<ide> ViewUtils.isSimpleClick = isSimpleClick;
<add>ViewUtils.getViewBounds = getViewBounds;
<ide> ViewUtils.getViewClientRects = getViewClientRects;
<ide> ViewUtils.getViewBoundingClientRect = getViewBoundingClientRect;
<ide> ViewUtils.getRootViews = getRootViews; | 1 |
Python | Python | add tests for local storage lock context manager | b0921294333a8c44da5c575b825a308f0fd724a6 | <ide><path>libcloud/storage/drivers/local.py
<ide> class LockLocalStorage(object):
<ide> A class to help in locking a local path before being updated
<ide> """
<ide>
<del> def __init__(self, path):
<add> def __init__(self, path, timeout=5):
<ide> self.path = path
<add> self.lock_acquire_timeout = timeout
<ide>
<ide> self.ipc_lock_path = os.path.join(tempfile.gettempdir(), "%s.lock" % (
<ide> sha256(path.encode("utf-8")).hexdigest()))
<ide> def __init__(self, path):
<ide> self.ipc_lock = fasteners.InterProcessLock(self.ipc_lock_path)
<ide>
<ide> def __enter__(self):
<del> lock_acquire_timeout = 5
<add> lock_acquire_timeout = self.lock_acquire_timeout
<ide> start_time = int(time.time())
<ide> end_time = start_time + lock_acquire_timeout
<ide>
<ide> def __enter__(self):
<ide>
<ide> if not success:
<ide> raise LibcloudError("Failed to acquire thread lock for path %s "
<del> "in 5 seconds" % (self.path))
<add> "in %s seconds" % (self.path,
<add> lock_acquire_timeout))
<ide>
<del> success = self.ipc_lock.acquire(blocking=True, timeout=5)
<add> success = self.ipc_lock.acquire(blocking=True,
<add> timeout=lock_acquire_timeout)
<ide>
<ide> if not success:
<ide> raise LibcloudError("Failed to acquire IPC lock (%s) for path %s "
<del> "in 5 seconds" %
<del> (self.ipc_lock_path, self.path))
<add> "in %s seconds" %
<add> (self.ipc_lock_path, self.path,
<add> lock_acquire_timeout))
<ide>
<ide> def __exit__(self, type, value, traceback):
<ide> if self.thread_lock.locked():
<ide><path>libcloud/test/storage/test_local.py
<ide> import platform
<ide> import shutil
<ide> import unittest
<add>import time
<ide> import tempfile
<del>
<del>import mock
<add>import multiprocessing
<ide>
<ide> from libcloud.common.types import LibcloudError
<ide> from libcloud.storage.base import Container
<ide> def remove_tmp_file(self, tmppath):
<ide> return
<ide> raise e
<ide>
<add> def test_lock_local_storage(self):
<add> # 1. Acquire succeeds
<add> lock = LockLocalStorage("/tmp/a")
<add> with lock:
<add> self.assertTrue(True)
<add>
<add> # 2. Acquire fails because lock is already acquired
<add> lock = LockLocalStorage("/tmp/b", timeout=0.5)
<add> with lock:
<add> expected_msg = "Failed to acquire thread lock"
<add> self.assertRaisesRegex(LibcloudError, expected_msg, lock.__enter__)
<add>
<add> # 3. Multiprocessing scenario where IPC lock is involved
<add> def acquire_lock_in_subprocess(pid, success):
<add> # For first process acquire should succeed and for the second it should fail
<add>
<add> lock = LockLocalStorage("/tmp/c", timeout=0.5)
<add>
<add> if pid == 1:
<add> with lock:
<add> time.sleep(1)
<add>
<add> success.value = 1
<add> elif pid == 2:
<add> expected_msg = "Failed to acquire IPC lock"
<add> self.assertRaisesRegex(LibcloudError, expected_msg, lock.__enter__)
<add> success.value = 1
<add> else:
<add> raise ValueError("Invalid pid")
<add>
<add> success_1 = multiprocessing.Value('i', 0)
<add> success_2 = multiprocessing.Value('i', 0)
<add>
<add> p1 = multiprocessing.Process(target=acquire_lock_in_subprocess, args=(1, success_1,))
<add> p1.start()
<add>
<add> p2 = multiprocessing.Process(target=acquire_lock_in_subprocess, args=(2, success_2,))
<add> p2.start()
<add>
<add> p1.join()
<add> p2.join()
<add>
<add> self.assertEqual(bool(success_1.value), True, "Check didn't pass")
<add> self.assertEqual(bool(success_2.value), True, "Second check didn't pass")
<add>
<ide> def test_list_containers_empty(self):
<ide> containers = self.driver.list_containers()
<ide> self.assertEqual(len(containers), 0) | 2 |
Javascript | Javascript | simplify nextmissingchunk(), getendchunk() | e5477c3156a1b5dcb8f7ba3763c5d327d11cc573 | <ide><path>src/core/chunked_stream.js
<ide> var ChunkedStream = (function ChunkedStreamClosure() {
<ide> },
<ide>
<ide> nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) {
<del> var chunk, n;
<del> for (chunk = beginChunk, n = this.numChunks; chunk < n; ++chunk) {
<del> if (!this.loadedChunks[chunk]) {
<del> return chunk;
<del> }
<del> }
<del> // Wrap around to beginning
<del> for (chunk = 0; chunk < beginChunk; ++chunk) {
<add> var chunk, numChunks = this.numChunks;
<add> for (var i = 0; i < numChunks; ++i) {
<add> chunk = (beginChunk + i) % numChunks; // Wrap around to beginning
<ide> if (!this.loadedChunks[chunk]) {
<ide> return chunk;
<ide> }
<ide> var ChunkedStreamManager = (function ChunkedStreamManagerClosure() {
<ide> this.requestChunks(chunksToRequest, callback);
<ide> },
<ide>
<del> // Groups a sorted array of chunks into as few continguous larger
<add> // Groups a sorted array of chunks into as few contiguous larger
<ide> // chunks as possible
<ide> groupChunks: function ChunkedStreamManager_groupChunks(chunks) {
<ide> var groupedChunks = [];
<ide> var ChunkedStreamManager = (function ChunkedStreamManagerClosure() {
<ide> },
<ide>
<ide> getEndChunk: function ChunkedStreamManager_getEndChunk(end) {
<del> if (end % this.chunkSize === 0) {
<del> return end / this.chunkSize;
<del> }
<del>
<del> // 0 -> 0
<del> // 1 -> 1
<del> // 99 -> 1
<del> // 100 -> 1
<del> // 101 -> 2
<ide> var chunk = Math.floor((end - 1) / this.chunkSize) + 1;
<ide> return chunk;
<ide> } | 1 |
Ruby | Ruby | remove all references to slave in the codebase | 3e81490717a314437f9123d86fa3e9dc55558e95 | <ide><path>railties/test/application/console_test.rb
<ide> class Post < ActiveRecord::Base
<ide> CODE
<ide> system "#{app_path}/bin/rails runner 'Post.connection.create_table :posts'"
<ide>
<del> @master, @slave = PTY.open
<add> @primary, @replica = PTY.open
<ide> end
<ide>
<ide> def teardown
<ide> teardown_app
<ide> end
<ide>
<ide> def write_prompt(command, expected_output = nil)
<del> @master.puts command
<del> assert_output command, @master
<del> assert_output expected_output, @master if expected_output
<del> assert_output "> ", @master
<add> @primary.puts command
<add> assert_output command, @primary
<add> assert_output expected_output, @primary if expected_output
<add> assert_output "> ", @primary
<ide> end
<ide>
<ide> def spawn_console(options)
<ide> Process.spawn(
<ide> "#{app_path}/bin/rails console #{options}",
<del> in: @slave, out: @slave, err: @slave
<add> in: @replica, out: @replica, err: @replica
<ide> )
<ide>
<del> assert_output "> ", @master, 30
<add> assert_output "> ", @primary, 30
<ide> end
<ide>
<ide> def test_sandbox
<ide> def test_sandbox
<ide> write_prompt "Post.count", "=> 0"
<ide> write_prompt "Post.create"
<ide> write_prompt "Post.count", "=> 1"
<del> @master.puts "quit"
<add> @primary.puts "quit"
<ide>
<ide> spawn_console("--sandbox")
<ide>
<ide> write_prompt "Post.count", "=> 0"
<ide> write_prompt "Post.transaction { Post.create; raise }"
<ide> write_prompt "Post.count", "=> 0"
<del> @master.puts "quit"
<add> @primary.puts "quit"
<ide> end
<ide>
<ide> def test_environment_option_and_irb_option
<ide> spawn_console("test -- --verbose")
<ide>
<ide> write_prompt "a = 1", "a = 1"
<ide> write_prompt "puts Rails.env", "puts Rails.env\r\ntest"
<del> @master.puts "quit"
<add> @primary.puts "quit"
<ide> end
<ide> end
<ide><path>railties/test/application/dbconsole_test.rb
<ide> def test_use_value_defined_in_environment_file_in_database_yml
<ide> end
<ide> RUBY
<ide>
<del> master, slave = PTY.open
<del> spawn_dbconsole(slave)
<del> assert_output("sqlite>", master)
<add> primary, replica = PTY.open
<add> spawn_dbconsole(replica)
<add> assert_output("sqlite>", primary)
<ide> ensure
<ide> master.puts ".exit"
<ide> end
<ide> def test_respect_environment_option
<ide> database: db/production.sqlite3
<ide> YAML
<ide>
<del> master, slave = PTY.open
<del> spawn_dbconsole(slave, "-e production")
<del> assert_output("sqlite>", master)
<add> primary, replica = PTY.open
<add> spawn_dbconsole(replica, "-e production")
<add> assert_output("sqlite>", primary)
<ide>
<ide> master.puts "pragma database_list;"
<ide> assert_output("production.sqlite3", master)
<ide><path>railties/test/application/server_test.rb
<ide> def teardown
<ide> f.puts "require 'bundler/setup'"
<ide> end
<ide>
<del> master, slave = PTY.open
<add> primary, replica = PTY.open
<ide> pid = nil
<ide>
<ide> begin
<del> pid = Process.spawn("#{app_path}/bin/rails server -P tmp/dummy.pid", in: slave, out: slave, err: slave)
<del> assert_output("Listening", master)
<add> pid = Process.spawn("#{app_path}/bin/rails server -P tmp/dummy.pid", in: replica, out: replica, err: replica)
<add> assert_output("Listening", primary)
<ide>
<ide> rails("restart")
<ide>
<del> assert_output("Restarting", master)
<del> assert_output("Inherited", master)
<add> assert_output("Restarting", primary)
<add> assert_output("Inherited", primary)
<ide> ensure
<ide> kill(pid) if pid
<ide> end
<ide><path>railties/test/engine/commands_test.rb
<ide> def test_runner_command_work_inside_engine
<ide> def test_console_command_work_inside_engine
<ide> skip "PTY unavailable" unless available_pty?
<ide>
<del> master, slave = PTY.open
<del> spawn_command("console", slave)
<del> assert_output(">", master)
<add> primary, replica = PTY.open
<add> spawn_command("console", replica)
<add> assert_output(">", primary)
<ide> ensure
<ide> master.puts "quit"
<ide> end
<ide>
<ide> def test_dbconsole_command_work_inside_engine
<ide> skip "PTY unavailable" unless available_pty?
<ide>
<del> master, slave = PTY.open
<del> spawn_command("dbconsole", slave)
<del> assert_output("sqlite>", master)
<add> primary, replica = PTY.open
<add> spawn_command("dbconsole", replica)
<add> assert_output("sqlite>", primary)
<ide> ensure
<ide> master.puts ".exit"
<ide> end
<ide>
<ide> def test_server_command_work_inside_engine
<ide> skip "PTY unavailable" unless available_pty?
<ide>
<del> master, slave = PTY.open
<del> pid = spawn_command("server", slave)
<del> assert_output("Listening on", master)
<add> primary, replica = PTY.open
<add> pid = spawn_command("server", replica)
<add> assert_output("Listening on", primary)
<ide> ensure
<ide> kill(pid)
<ide> end | 4 |
Javascript | Javascript | remove unused function | 590bc734bb33163e794b4d18cae173b2fa0828de | <ide><path>lib/internal/repl.js
<ide> module.exports.createInternalRepl = createRepl;
<ide> // The debounce is to guard against code pasted into the REPL.
<ide> const kDebounceHistoryMS = 15;
<ide>
<del>// XXX(chrisdickinson): hack to make sure that the internal debugger
<del>// uses the original repl.
<del>function replStart() {
<del> return REPL.start.apply(REPL, arguments);
<del>}
<del>
<ide> function createRepl(env, opts, cb) {
<ide> if (typeof opts === 'function') {
<ide> cb = opts; | 1 |
PHP | PHP | update typhints for command/ | 82797c1c874efcc4cebe99318527eeec060ec082 | <ide><path>src/Command/HelpCommand.php
<ide> */
<ide> namespace Cake\Command;
<ide>
<add>use ArrayIterator;
<ide> use Cake\Console\Arguments;
<ide> use Cake\Console\Command;
<ide> use Cake\Console\CommandCollection;
<ide> public function execute(Arguments $args, ConsoleIo $io): int
<ide> * @param \ArrayIterator $commands The command collection to output.
<ide> * @return void
<ide> */
<del> protected function asText($io, $commands): void
<add> protected function asText(ConsoleIo $io, ArrayIterator $commands): void
<ide> {
<ide> $invert = [];
<ide> foreach ($commands as $name => $class) {
<ide> protected function asText($io, $commands): void
<ide> * @param string[] $names Names
<ide> * @return string
<ide> */
<del> protected function getShortestName(array $names)
<add> protected function getShortestName(array $names): string
<ide> {
<ide> if (count($names) <= 1) {
<ide> return array_shift($names);
<ide> protected function getShortestName(array $names)
<ide> * @param \ArrayIterator $commands The command collection to output
<ide> * @return void
<ide> */
<del> protected function asXml($io, $commands): void
<add> protected function asXml(ConsoleIo $io, ArrayIterator $commands): void
<ide> {
<ide> $shells = new SimpleXMLElement('<shells></shells>');
<ide> foreach ($commands as $name => $class) {
<ide><path>src/Command/UpgradeCommand.php
<ide> public function execute(Arguments $args, ConsoleIo $io)
<ide> *
<ide> * @return void
<ide> */
<del> protected function processTemplates()
<add> protected function processTemplates(): void
<ide> {
<ide> if (is_dir($this->path . 'src/Template')) {
<ide> $this->rename(
<ide> protected function processTemplates()
<ide> *
<ide> * @return void
<ide> */
<del> protected function processLocales()
<add> protected function processLocales(): void
<ide> {
<ide> if (is_dir($this->path . 'src/Locale')) {
<ide> $this->rename(
<ide> protected function processLocales()
<ide> * @param string $type Type
<ide> * @return void
<ide> */
<del> protected function moveDir($path, $type)
<add> protected function moveDir(string $path, string $type): void
<ide> {
<ide> $info = $this->types[$type];
<ide>
<ide> protected function moveDir($path, $type)
<ide> * @param string $path Path.
<ide> * @return void
<ide> */
<del> protected function renameSubFolders($path)
<add> protected function renameSubFolders(string $path): void
<ide> {
<ide> $dirIter = new RecursiveDirectoryIterator(
<ide> $path,
<ide> protected function renameSubFolders($path)
<ide> * @param string $path Path
<ide> * @return void
<ide> */
<del> protected function changeExt($path)
<add> protected function changeExt(string $path): void
<ide> {
<ide> $dirIter = new RecursiveDirectoryIterator(
<ide> $path,
<ide> protected function changeExt($path)
<ide> * @param string $dest Destination path.
<ide> * @return void
<ide> */
<del> protected function rename($source, $dest)
<add> protected function rename(string $source, string $dest): void
<ide> {
<ide> $this->io->out("Move $source to $dest");
<ide> | 2 |
Javascript | Javascript | fix helper blueprint for module unification | fbce6687d9db75f1b3445853097fe8e8a46755bf | <ide><path>blueprints/helper/index.js
<ide> const path = require('path');
<ide> module.exports = {
<ide> description: 'Generates a helper function.',
<ide>
<add> filesPath() {
<add> let rootPath = isModuleUnificationProject(this.project) ? 'mu-files' : 'files';
<add> return path.join(this.path, rootPath);
<add> },
<add>
<ide> fileMapTokens() {
<ide> if (isModuleUnificationProject(this.project)) {
<ide> return {
<ide><path>blueprints/helper/mu-files/__root__/__collection__/__name__.js
<add>import { helper as buildHelper } from '@ember/component/helper';
<add>
<add>export function <%= camelizedModuleName %>(params/*, hash*/) {
<add> return params;
<add>}
<add>
<add>export const helper = buildHelper(<%= camelizedModuleName %>);
<ide><path>node-tests/blueprints/helper-test.js
<ide> describe('Blueprint: helper', function() {
<ide>
<ide> it('helper foo/bar-baz', function() {
<ide> return emberGenerateDestroy(['helper', 'foo/bar-baz'], _file => {
<del> expect(_file('src/ui/components/foo/bar-baz.js')).to.equal(fixture('helper/helper.js'));
<add> expect(_file('src/ui/components/foo/bar-baz.js')).to.equal(fixture('helper/mu-helper.js'));
<ide> expect(_file('src/ui/components/foo/bar-baz-test.js')).to.equal(
<ide> fixture('helper-test/integration.js')
<ide> );
<ide> describe('Blueprint: helper', function() {
<ide>
<ide> it('helper foo/bar-baz unit', function() {
<ide> return emberGenerateDestroy(['helper', '--test-type=unit', 'foo/bar-baz'], _file => {
<del> expect(_file('src/ui/components/foo/bar-baz.js')).to.equal(fixture('helper/helper.js'));
<add> expect(_file('src/ui/components/foo/bar-baz.js')).to.equal(fixture('helper/mu-helper.js'));
<ide> expect(_file('src/ui/components/foo/bar-baz-test.js')).to.equal(
<ide> fixture('helper-test/unit.js')
<ide> );
<ide> describe('Blueprint: helper', function() {
<ide>
<ide> it('helper foo/bar-baz', function() {
<ide> return emberGenerateDestroy(['helper', 'foo/bar-baz'], _file => {
<del> expect(_file('src/ui/components/foo/bar-baz.js')).to.equal(fixture('helper/helper.js'));
<add> expect(_file('src/ui/components/foo/bar-baz.js')).to.equal(fixture('helper/mu-helper.js'));
<ide> expect(_file('src/ui/components/foo/bar-baz-test.js')).to.equal(
<ide> fixture('helper-test/integration.js')
<ide> );
<ide> describe('Blueprint: helper', function() {
<ide>
<ide> it('helper foo/bar-baz unit', function() {
<ide> return emberGenerateDestroy(['helper', '--test-type=unit', 'foo/bar-baz'], _file => {
<del> expect(_file('src/ui/components/foo/bar-baz.js')).to.equal(fixture('helper/helper.js'));
<add> expect(_file('src/ui/components/foo/bar-baz.js')).to.equal(fixture('helper/mu-helper.js'));
<ide> expect(_file('src/ui/components/foo/bar-baz-test.js')).to.equal(
<ide> fixture('helper-test/module-unification/addon-unit.js')
<ide> );
<ide> describe('Blueprint: helper', function() {
<ide> it('helper foo/bar-baz --in-repo-addon=my-addon', function() {
<ide> return emberGenerateDestroy(['helper', 'foo/bar-baz', '--in-repo-addon=my-addon'], _file => {
<ide> expect(_file('packages/my-addon/src/ui/components/foo/bar-baz.js')).to.equal(
<del> fixture('helper/helper.js')
<add> fixture('helper/mu-helper.js')
<ide> );
<ide> expect(_file('packages/my-addon/src/ui/components/foo/bar-baz-test.js')).to.equal(
<ide> fixture('helper-test/integration.js')
<ide> describe('Blueprint: helper', function() {
<ide> ['helper', '--test-type=unit', 'foo/bar-baz', '--in-repo-addon=my-addon'],
<ide> _file => {
<ide> expect(_file('packages/my-addon/src/ui/components/foo/bar-baz.js')).to.equal(
<del> fixture('helper/helper.js')
<add> fixture('helper/mu-helper.js')
<ide> );
<ide> expect(_file('packages/my-addon/src/ui/components/foo/bar-baz-test.js')).to.equal(
<ide> fixture('helper-test/module-unification/addon-unit.js')
<ide><path>node-tests/fixtures/helper/mu-helper.js
<add>import { helper as buildHelper } from '@ember/component/helper';
<add>
<add>export function fooBarBaz(params/*, hash*/) {
<add> return params;
<add>}
<add>
<add>export const helper = buildHelper(fooBarBaz); | 4 |
Javascript | Javascript | add support for templates fetched from npm | 17c175a149bc410a9b167b31f13474d8c6e9832c | <ide><path>local-cli/generator/copyProjectTemplateAndReplace.js
<ide> const walk = require('../util/walk');
<ide> * @param srcPath e.g. '/Users/martin/AwesomeApp/node_modules/react-native/local-cli/templates/HelloWorld'
<ide> * @param destPath e.g. '/Users/martin/AwesomeApp'
<ide> * @param newProjectName e.g. 'AwesomeApp'
<add> * @param options e.g. {
<add> * upgrade: true,
<add> * force: false,
<add> * displayName: 'Hello World',
<add> * ignorePaths: ['template/file/to/ignore.md'],
<add> * }
<ide> */
<ide> function copyProjectTemplateAndReplace(srcPath, destPath, newProjectName, options) {
<ide> if (!srcPath) { throw new Error('Need a path to copy from'); }
<ide> function copyProjectTemplateAndReplace(srcPath, destPath, newProjectName, option
<ide> .replace(/HelloWorld/g, newProjectName)
<ide> .replace(/helloworld/g, newProjectName.toLowerCase());
<ide>
<add> // Templates may contain files that we don't want to copy.
<add> // Examples:
<add> // - Dummy package.json file included in the template only for publishing to npm
<add> // - Docs specific to the template (.md files)
<add> if (options.ignorePaths) {
<add> if (!Array.isArray(options.ignorePaths)) {
<add> throw new Error('options.ignorePaths must be an array');
<add> }
<add> if (options.ignorePaths.some(ignorePath => ignorePath === relativeFilePath)) {
<add> // Skip copying this file
<add> return;
<add> }
<add> }
<add>
<ide> let contentChangedCallback = null;
<ide> if (options.upgrade && (!options.force)) {
<ide> contentChangedCallback = (_, contentChanged) => {
<ide><path>local-cli/generator/templates.js
<ide> const execSync = require('child_process').execSync;
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<del>const availableTemplates = {
<add>/**
<add> * Templates released as part of react-native in local-cli/templates.
<add> */
<add>const builtInTemplates = {
<ide> navigation: 'HelloNavigation',
<ide> };
<ide>
<ide> function listTemplatesAndExit(newProjectName, options) {
<ide> // Just listing templates using 'react-native init --template'.
<ide> // Not creating a new app.
<ide> // Print available templates and exit.
<del> const templateKeys = Object.keys(availableTemplates);
<add> const templateKeys = Object.keys(builtInTemplates);
<ide> if (templateKeys.length === 0) {
<del> // Just a guard, should never happen as long availableTemplates
<add> // Just a guard, should never happen as long builtInTemplates
<ide> // above is defined correctly :)
<ide> console.log(
<ide> 'There are no templates available besides ' +
<ide> function listTemplatesAndExit(newProjectName, options) {
<ide> }
<ide>
<ide> /**
<add> * @param destPath Create the new project at this path.
<ide> * @param newProjectName For example 'AwesomeApp'.
<del> * @param templateKey Template to use, for example 'navigation'.
<add> * @param template Template to use, for example 'navigation'.
<ide> * @param yarnVersion Version of yarn available on the system, or null if
<ide> * yarn is not available. For example '0.18.1'.
<ide> */
<del>function createProjectFromTemplate(destPath, newProjectName, templateKey, yarnVersion) {
<add>function createProjectFromTemplate(destPath, newProjectName, template, yarnVersion) {
<ide> // Expand the basic 'HelloWorld' template
<ide> copyProjectTemplateAndReplace(
<ide> path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld'),
<ide> destPath,
<ide> newProjectName
<ide> );
<ide>
<del> if (templateKey !== undefined) {
<del> // Keep the files from the 'HelloWorld' template, and overwrite some of them
<del> // with the specified project template.
<del> // The 'HelloWorld' template contains the native files (these are used by
<del> // all templates) and every other template only contains additional JS code.
<del> // Reason:
<del> // This way we don't have to duplicate the native files in every template.
<del> // If we duplicated them we'd make RN larger and risk that people would
<del> // forget to maintain all the copies so they would go out of sync.
<del> const templateName = availableTemplates[templateKey];
<del> if (templateName) {
<del> copyProjectTemplateAndReplace(
<del> path.resolve(
<del> 'node_modules', 'react-native', 'local-cli', 'templates', templateName
<del> ),
<del> destPath,
<del> newProjectName
<del> );
<add> if (template === undefined) {
<add> // No specific template, use just the HelloWorld template above
<add> return;
<add> }
<add>
<add> // Keep the files from the 'HelloWorld' template, and overwrite some of them
<add> // with the specified project template.
<add> // The 'HelloWorld' template contains the native files (these are used by
<add> // all templates) and every other template only contains additional JS code.
<add> // Reason:
<add> // This way we don't have to duplicate the native files in every template.
<add> // If we duplicated them we'd make RN larger and risk that people would
<add> // forget to maintain all the copies so they would go out of sync.
<add> const builtInTemplateName = builtInTemplates[template];
<add> if (builtInTemplateName) {
<add> // template is e.g. 'navigation',
<add> // use the built-in local-cli/templates/HelloNavigation folder
<add> createFromBuiltInTemplate(builtInTemplateName, destPath, newProjectName, yarnVersion);
<add> } else {
<add> // template is e.g. 'ignite',
<add> // use the template react-native-template-ignite from npm
<add> createFromRemoteTemplate(template, destPath, newProjectName, yarnVersion);
<add> }
<add>}
<add>
<add>// (We might want to get rid of built-in templates in the future -
<add>// publish them to npm and install from there.)
<add>function createFromBuiltInTemplate(templateName, destPath, newProjectName, yarnVersion) {
<add> const templatePath = path.resolve(
<add> 'node_modules', 'react-native', 'local-cli', 'templates', templateName
<add> );
<add> copyProjectTemplateAndReplace(
<add> templatePath,
<add> destPath,
<add> newProjectName,
<add> );
<add> installTemplateDependencies(templatePath, yarnVersion);
<add>}
<add>
<add>/**
<add> * The following formats are supported for the template:
<add> * - 'demo' -> Fetch the package react-native-template-demo from npm
<add> * - git://..., http://..., file://... or any other URL supported by npm
<add> */
<add>function createFromRemoteTemplate(template, destPath, newProjectName, yarnVersion) {
<add> let installPackage;
<add> let templateName;
<add> if (template.includes('://')) {
<add> // URL, e.g. git://, file://
<add> installPackage = template;
<add> templateName = template.substr(template.lastIndexOf('/') + 1);
<add> } else {
<add> // e.g 'demo'
<add> installPackage = 'react-native-template-' + template;
<add> templateName = installPackage;
<add> }
<add>
<add> // Check if the template exists
<add> console.log(`Fetching template ${installPackage}...`);
<add> try {
<add> if (yarnVersion) {
<add> execSync(`yarn add ${installPackage} --ignore-scripts`, {stdio: 'inherit'});
<ide> } else {
<del> throw new Error('Uknown template: ' + templateKey);
<add> execSync(`npm install ${installPackage} --save --save-exact --ignore-scripts`, {stdio: 'inherit'});
<add> }
<add> const templatePath = path.resolve(
<add> 'node_modules', templateName
<add> );
<add> copyProjectTemplateAndReplace(
<add> templatePath,
<add> destPath,
<add> newProjectName,
<add> {
<add> // Every template contains a dummy package.json file included
<add> // only for publishing the template to npm.
<add> // We want to ignore this dummy file, otherwise it would overwrite
<add> // our project's package.json file.
<add> ignorePaths: ['package.json', 'dependencies.json'],
<add> }
<add> );
<add> installTemplateDependencies(templatePath, yarnVersion);
<add> } finally {
<add> // Clean up the temp files
<add> try {
<add> if (yarnVersion) {
<add> execSync(`yarn remove ${templateName} --ignore-scripts`);
<add> } else {
<add> execSync(`npm uninstall ${templateName} --ignore-scripts`);
<add> }
<add> } catch (err) {
<add> // Not critical but we still want people to know and report
<add> // if this the clean up fails.
<add> console.warn(
<add> `Failed to clean up template temp files in node_modules/${templateName}. ` +
<add> 'This is not a critical error, you can work on your app.'
<add> );
<ide> }
<add> }
<add>}
<ide>
<del> // Add dependencies:
<add>function installTemplateDependencies(templatePath, yarnVersion) {
<add> // dependencies.json is a special file that lists additional dependencies
<add> // that are required by this template
<add> const dependenciesJsonPath = path.resolve(
<add> templatePath, 'dependencies.json'
<add> );
<add> console.log('Adding dependencies for the project...');
<add> if (!fs.existsSync(dependenciesJsonPath)) {
<add> console.log('No additional dependencies.');
<add> return;
<add> }
<ide>
<del> // dependencies.json is a special file that lists additional dependencies
<del> // that are required by this template
<del> const dependenciesJsonPath = path.resolve(
<del> 'node_modules', 'react-native', 'local-cli', 'templates', templateName, 'dependencies.json'
<add> let dependencies;
<add> try {
<add> dependencies = JSON.parse(fs.readFileSync(dependenciesJsonPath));
<add> } catch (err) {
<add> throw new Error(
<add> 'Could not parse the template\'s dependencies.json: ' + err.message
<ide> );
<del> if (fs.existsSync(dependenciesJsonPath)) {
<del> console.log('Adding dependencies for the project...');
<del> const dependencies = JSON.parse(fs.readFileSync(dependenciesJsonPath));
<del> for (let depName in dependencies) {
<del> const depVersion = dependencies[depName];
<del> const depToInstall = depName + '@' + depVersion;
<del> console.log('Adding ' + depToInstall + '...');
<del> if (yarnVersion) {
<del> execSync(`yarn add ${depToInstall}`, {stdio: 'inherit'});
<del> } else {
<del> execSync(`npm install ${depToInstall} --save --save-exact`, {stdio: 'inherit'});
<del> }
<del> }
<add> }
<add> for (let depName in dependencies) {
<add> const depVersion = dependencies[depName];
<add> const depToInstall = depName + '@' + depVersion;
<add> console.log('Adding ' + depToInstall + '...');
<add> if (yarnVersion) {
<add> execSync(`yarn add ${depToInstall}`, {stdio: 'inherit'});
<add> } else {
<add> execSync(`npm install ${depToInstall} --save --save-exact`, {stdio: 'inherit'});
<ide> }
<ide> }
<add> console.log('Linking native dependencies into the project\'s build files...');
<add> execSync('react-native link', {stdio: 'inherit'});
<ide> }
<ide>
<ide> module.exports = {
<ide><path>local-cli/link/link.js
<ide> * This source code is licensed under the BSD-style license found in the
<ide> * LICENSE file in the root directory of this source tree. An additional grant
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @flow
<ide> */
<ide>
<ide> const log = require('npmlog');
<ide> const pollParams = require('./pollParams');
<ide> const commandStub = require('./commandStub');
<ide> const promisify = require('./promisify');
<ide>
<add>import type {ConfigT} from '../core';
<add>
<ide> log.heading = 'rnpm-link';
<ide>
<ide> const dedupeAssets = (assets) => uniq(assets, asset => path.basename(asset));
<ide> const linkAssets = (project, assets) => {
<ide> };
<ide>
<ide> /**
<del> * Updates project and links all dependencies to it
<add> * Updates project and links all dependencies to it.
<ide> *
<del> * If optional argument [packageName] is provided, it's the only one that's checked
<add> * @param args If optional argument [packageName] is provided,
<add> * only that package is processed.
<add> * @param config CLI config, see local-cli/core/index.js
<ide> */
<del>function link(args, config) {
<add>function link(args: Array<string>, config: ConfigT) {
<ide> var project;
<ide> try {
<ide> project = config.getProjectConfig();
<ide> } catch (err) {
<ide> log.error(
<ide> 'ERRPACKAGEJSON',
<del> 'No package found. Are you sure it\'s a React Native project?'
<add> 'No package found. Are you sure this is a React Native project?'
<ide> );
<ide> return Promise.reject(err);
<ide> }
<ide> function link(args, config) {
<ide>
<ide> return promiseWaterfall(tasks).catch(err => {
<ide> log.error(
<del> `It seems something went wrong while linking. Error: ${err.message} \n`
<del> + 'Please file an issue here: https://github.com/facebook/react-native/issues'
<add> `Something went wrong while linking. Error: ${err.message} \n` +
<add> 'Please file an issue here: https://github.com/facebook/react-native/issues'
<ide> );
<ide> throw err;
<ide> });
<ide> }
<ide>
<ide> module.exports = {
<ide> func: link,
<del> description: 'links all native dependencies',
<add> description: 'links all native dependencies (updates native build files)',
<ide> name: 'link [packageName]',
<ide> }; | 3 |
Python | Python | fix line length | ad942e22121a0cdae253f16de713bef97cacccc6 | <ide><path>research/object_detection/exporter_lib_tf2_test.py
<ide> def test_export_saved_model_and_run_inference_with_side_inputs(
<ide> side_input_2 = np.ones((2, 2), dtype=np.uint8)
<ide> if (use_default_serving):
<ide> detections = detect_fn_sig(input_tensor=image,
<del> side_inp_1=tf.constant(side_input_1),
<del> side_inp_2=tf.constant(side_input_2))
<add> side_inp_1=tf.constant(side_input_1),
<add> side_inp_2=tf.constant(side_input_2))
<ide> else:
<del> detections = detect_fn(image, tf.constant(side_input_1), tf.constant(side_input_2))
<add> detections = detect_fn(image,
<add> tf.constant(side_input_1),
<add> tf.constant(side_input_2))
<ide>
<ide> detection_fields = fields.DetectionResultFields
<ide> self.assertAllClose(detections[detection_fields.detection_boxes], | 1 |
PHP | PHP | add tests for deprecated methods | 92837bd8f2d639c6d81b32dc72f19b5b4600fba0 | <ide><path>tests/TestCase/Mailer/EmailTest.php
<ide> public function assertLineLengths($message)
<ide> );
<ide> }
<ide> }
<add>
<add> /**
<add> * Test deprecated methods
<add> *
<add> * @return void
<add> */
<add> public function testDeprecatedMethods()
<add> {
<add> $this->deprecated(function () {
<add> $this->Email
<add> ->setTemplate('foo')
<add> ->setLayout('bar')
<add> ->setTheme('baz')
<add> ->setHelpers(['A', 'B']);
<add>
<add> $this->assertSame('foo', $this->Email->getTemplate());
<add> $this->assertSame('bar', $this->Email->getLayout());
<add> $this->assertSame('baz', $this->Email->getTheme());
<add> $this->assertSame(['A', 'B'], $this->Email->getHelpers());
<add>
<add> $this->Email->setLayout('');
<add> $this->assertFalse($this->Email->getLayout());
<add> });
<add> }
<ide> } | 1 |
Java | Java | add @ignored test case to reproduce spr-10243 | 19eecb151b8a0e2b2dad1aa4baf4c552587342fb | <ide><path>spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java
<ide> import javax.validation.constraints.NotNull;
<ide>
<ide> import org.hibernate.validator.HibernateValidator;
<add>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide>
<ide> import org.springframework.validation.BeanPropertyBindingResult;
<ide> import org.springframework.validation.Errors;
<ide> import org.springframework.validation.FieldError;
<ide> import org.springframework.validation.ObjectError;
<ide>
<add>import static org.hamcrest.Matchers.instanceOf;
<ide> import static org.junit.Assert.*;
<ide>
<ide> /**
<ide> public void testSimpleValidationWithClassLevel() throws Exception {
<ide> assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NameAddressValid);
<ide> }
<ide>
<add> @Test
<add> @Ignore
<add> public void testSpringValidationFieldType() throws Exception {
<add> LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
<add> validator.afterPropertiesSet();
<add> ValidPerson person = new ValidPerson();
<add> person.setName("Phil");
<add> person.getAddress().setStreet("Phil's Street");
<add> BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person");
<add> validator.validate(person, errors);
<add> assertEquals(1, errors.getErrorCount());
<add> assertThat("Field/Value type missmatch",
<add> errors.getFieldError("address").getRejectedValue(),
<add> instanceOf(ValidAddress.class));
<add> }
<add>
<ide> @Test
<ide> public void testSpringValidation() throws Exception {
<ide> LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
<ide> public void initialize(NameAddressValid constraintAnnotation) {
<ide> }
<ide>
<ide> @Override
<del> public boolean isValid(ValidPerson value, ConstraintValidatorContext constraintValidatorContext) {
<del> return (value.name == null || !value.address.street.contains(value.name));
<add> public boolean isValid(ValidPerson value, ConstraintValidatorContext context) {
<add> boolean valid = (value.name == null || !value.address.street.contains(value.name));
<add> if (!valid && "Phil".equals(value.name)) {
<add> context.buildConstraintViolationWithTemplate(
<add> context.getDefaultConstraintMessageTemplate()).addNode("address").addConstraintViolation().disableDefaultConstraintViolation();
<add> }
<add> return valid;
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | add support for stemhw/stemvw/stemsnaph/stemsnapv | 63e4f0293f6a0f39b8bb65ba3d0f60c87a973123 | <ide><path>fonts.js
<ide> var Type1Parser = function() {
<ide> * Returns an object containing a Subrs array and a CharStrings array
<ide> * extracted from and eexec encrypted block of data
<ide> */
<add> function readNumberArray(str, index) {
<add> var start = ++index;
<add> var count = 0;
<add> while (str[index++] != "]")
<add> count++;
<add>
<add> var array = str.substr(start, count).split(" ");
<add> for (var i = 0; i < array.length; i++)
<add> array[i] = parseFloat(array[i] || 0);
<add> return array;
<add> };
<add>
<ide> this.extractFontProgram = function t1_extractFontProgram(stream) {
<ide> var eexec = decrypt(stream, kEexecEncryptionKey, 4);
<ide> var eexecString = "";
<ide> var Type1Parser = function() {
<ide> var glyphsSection = false, subrsSection = false;
<ide> var extracted = {
<ide> subrs: [],
<del> charstrings: []
<add> charstrings: [],
<add> properties: {
<add> stemSnapH: [0, 0],
<add> stemSnapV: [0, 0]
<add> }
<ide> };
<ide>
<ide> var glyph = "";
<ide> var Type1Parser = function() {
<ide> extracted.subrs.push(str.charstring);
<ide> }
<ide> i += length + 3;
<del> } else if (c == " ") {
<add> } else if (c == " " || c == "\n") {
<ide> length = parseInt(token);
<ide> token = "";
<ide> } else {
<ide> token += c;
<ide> if (!glyphsSection) {
<del> glyphsSection = token.indexOf("/CharString") != -1;
<del> subrsSection = subrsSection || token.indexOf("Subrs") != -1;
<add> switch (token) {
<add> case "/CharString":
<add> glyphsSection = true;
<add> break;
<add> case "/Subrs":
<add> subrsSection = true;
<add> break;
<add> case "/StdHW":
<add> extracted.properties.stdHW = readNumberArray(eexecString, i + 2)[0];
<add> break;
<add> case "/StdVW":
<add> extracted.properties.stdVW = readNumberArray(eexecString, i + 2)[0];
<add> break;
<add> case "/StemSnapH":
<add> extracted.properties.stemSnapH = readNumberArray(eexecString, i + 2);
<add> break;
<add> case "/StemSnapV":
<add> extracted.properties.stemSnapV = readNumberArray(eexecString, i + 2);
<add> break;
<add> }
<ide> } else if (c == "/") {
<ide> token = glyph = "";
<ide> while ((c = eexecString[++i]) != " ")
<ide> var Type1Parser = function() {
<ide> textMatrix: null
<ide> };
<ide>
<del> function readNumberArray(str, index) {
<del> var start = ++index;
<del> var count = 0;
<del> while ((c = str[index++]) != "]")
<del> count++;
<del>
<del> var array = str.substr(start, count).split(" ");
<del> for (var i = 0; i < array.length; i++)
<del> array[i] = parseFloat(array[i]);
<del> return array;
<del> };
<del>
<ide> var token = "";
<ide> var count = headerString.length;
<ide> for (var i = 0; i < count; i++) {
<ide> var Type1Parser = function() {
<ide>
<ide> return info;
<ide> };
<del>
<ide> };
<ide>
<ide> /**
<ide> var CFF = function(name, file, properties) {
<ide>
<ide> var headerBlock = file.getBytes(length1);
<ide> var header = type1Parser.extractFontHeader(headerBlock);
<del> for (var info in header) {
<add> for (var info in header)
<ide> properties[info] = header[info];
<del> }
<ide>
<ide> // Decrypt the data blocks and retrieve it's content
<ide> var eexecBlock = file.getBytes(length2);
<ide> var data = type1Parser.extractFontProgram(eexecBlock);
<add> for (var info in data.properties)
<add> properties[info] = data.properties[info];
<ide>
<ide> var charstrings = this.getOrderedCharStrings(data.charstrings);
<ide> var type2Charstrings = this.getType2Charstrings(charstrings);
<ide> CFF.prototype = {
<ide> "charstrings": this.createCFFIndexHeader([[0x8B, 0x0E]].concat(glyphs), true),
<ide>
<ide> "private": (function(self) {
<del> log(properties.stemSnapH);
<ide> var data =
<ide> "\x8b\x14" + // defaultWidth
<ide> "\x8b\x15" + // nominalWidth
<del> "\x8b\x0a" + // StdHW
<del> "\x8b\x0a" + // StdVW
<del> "\x8b\x8b\x0c\x0c" + // StemSnapH
<del> "\x8b\x8b\x0c\x0d"; // StemSnapV
<add> self.encodeNumber(properties.stdHW) + "\x0a" + // StdHW
<add> self.encodeNumber(properties.stdVW) + "\x0b"; // StdVW
<add>
<add> var stemH = properties.stemSnapH;
<add> for (var i = 0; i < stemH.length; i++)
<add> data += self.encodeNumber(stemH[i]);
<add> data += "\x0c\x0c"; // StemSnapH
<add>
<add> var stemV = properties.stemSnapV;
<add> for (var i = 0; i < stemV.length; i++)
<add> data += self.encodeNumber(stemV[i]);
<add> data += "\x0c\x0d"; // StemSnapV
<add>
<ide> data += self.encodeNumber(data.length + 4) + "\x13"; // Subrs offset
<ide>
<ide> return data; | 1 |
PHP | PHP | fix trailing space | fe728d73be76efe0bf1d36d9741de2d7a2922c04 | <ide><path>src/Routing/Router.php
<ide> class Router
<ide>
<ide> /**
<ide> * The route collection routes would be added to.
<del> *
<add> *
<ide> * @var \Cake\Routing\RouteCollection
<ide> */
<ide> protected static $_collection; | 1 |
Python | Python | update model to use past | 3edfa1d6aaf30247c413fa15f04758b96d04762c | <ide><path>transformers/modeling_ctrl.py
<ide> def positional_encoding(position, d_model_size, dtype):
<ide> sines = torch.sin(angle_rads[:, 0::2])
<ide> cosines = torch.cos(angle_rads[:, 1::2])
<ide>
<del> pos_encoding = torch.cat([sines, cosines], dim=-1).unsqueeze(0)
<add> pos_encoding = torch.cat([sines, cosines], dim=-1)
<ide> return pos_encoding
<ide>
<ide> def scaled_dot_product_attention(q, k, v, mask, attention_mask=None, head_mask=None):
<ide> def forward(self, v, k, q, mask, layer_past=None, attention_mask=None, head_mask
<ide> k = self.split_into_heads(k, batch_size)
<ide> v = self.split_into_heads(v, batch_size)
<ide> if layer_past is not None:
<del> past_key, past_value = layer_past[0].transpose(-2, -1), layer_past[1] # transpose back cf below
<add> past_key, past_value = layer_past[0], layer_past[1]
<ide> k = torch.cat((past_key, k), dim=-1)
<ide> v = torch.cat((past_value, v), dim=-2)
<del> present = torch.stack((k.transpose(-2, -1), v)) # transpose to have same shapes for stacking
<add> present = torch.stack((k, v))
<ide>
<del> output = scaled_dot_product_attention(q, k, v, mask, attention_mask, head_mask, output_attentions)
<add> output = scaled_dot_product_attention(q, k, v, mask, attention_mask, head_mask)
<ide> scaled_attention = output[0].permute([0, 2, 1, 3])
<ide> attn = output[1]
<ide> original_size_attention = scaled_attention.reshape(batch_size, -1, self.d_model_size)
<ide> output = self.dense(original_size_attention)
<ide>
<del> return output, attn
<add> outputs = (output, present)
<add> if self.output_attentions:
<add> outputs = outputs + (attn,)
<add> return outputs
<ide>
<ide>
<ide>
<ide> def __init__(self, d_model_size, num_heads, dff, rate=0.1, output_attentions=Fal
<ide>
<ide> def forward(self, x, mask, layer_past=None, attention_mask=None, head_mask=None):
<ide> normed = self.layernorm1(x)
<del> attn_output, attn = self.multi_head_attention(normed, normed, normed, mask,
<add> attn_outputs = self.multi_head_attention(normed, normed, normed, mask,
<ide> layer_past=layer_past,
<ide> attention_mask=attention_mask,
<ide> head_mask=head_mask)
<add> attn_output = attn_outputs[0]
<ide> attn_output = self.dropout1(attn_output)
<ide> out1 = x + attn_output
<ide>
<ide> def forward(self, x, mask, layer_past=None, attention_mask=None, head_mask=None)
<ide> ffn_output = self.dropout2(ffn_output)
<ide> out2 = out1 + ffn_output
<ide>
<del> return out2, attn
<add> outputs = (out2,) + attn_outputs[1:]
<add> return outputs
<ide>
<ide>
<ide> class CTRLPreTrainedModel(PreTrainedModel):
<ide> def forward(self, input_ids, past=None, attention_mask=None, token_type_ids=None
<ide> else:
<ide> head_mask = [None] * self.config.n_layer
<ide>
<del> embedded = self.w(input_ids)
<del> x = embedded.unsqueeze(0) if len(input_ids.shape)<2 else embedded
<add> x = self.w(input_ids)
<add> # x = embedded.unsqueeze(0) if len(input_ids.shape)<2 else embedded
<ide> seq_len = input_ids.shape[1]
<ide> mask = torch.triu(torch.ones(seq_len, seq_len), 1).to(x.device)
<ide>
<ide> x *= np.sqrt(self.d_model_size)
<ide>
<del> x += self.pos_encoding[:, position_ids, :].to(x.device)
<add> pos_x = self.pos_encoding[position_ids, :].to(x.device)
<add> x += pos_x
<ide>
<ide> x = self.dropout(x)
<ide>
<ide><path>transformers/tests/modeling_ctrl_test.py
<ide> def create_and_check_ctrl_model(self, config, input_ids, input_mask, head_mask,
<ide>
<ide> model(input_ids, token_type_ids=token_type_ids, head_mask=head_mask)
<ide> model(input_ids, token_type_ids=token_type_ids)
<del> sequence_output, _ = model(input_ids)
<add> sequence_output, presents = model(input_ids)
<ide>
<ide> result = {
<ide> "sequence_output": sequence_output,
<add> "presents": presents,
<ide> }
<ide> self.parent.assertListEqual(
<ide> list(result["sequence_output"].size()),
<ide> [self.batch_size, self.seq_length, self.hidden_size])
<add> self.parent.assertEqual(len(result["presents"]), config.n_layer)
<ide>
<ide> def create_and_check_lm_head_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
<ide> model = CTRLLMHeadModel(config) | 2 |
Javascript | Javascript | move transform options into own property | 8533c0d8162c635db46db51cb08b116545b02708 | <ide><path>packager/src/Bundler/index.js
<ide> export type BundlingOptions = {|
<ide> +transformer: JSTransformerOptions,
<ide> |};
<ide>
<del>export type ExtraTransformOptions = {|
<del> +inlineRequires?: {+blacklist: {[string]: true}} | boolean,
<add>export type ExtraTransformOptions = {
<ide> +preloadedModules?: {[path: string]: true} | false,
<ide> +ramGroups?: Array<string>,
<del>|};
<add> +transform?: {+inlineRequires?: {+blacklist: {[string]: true}} | boolean},
<add>};
<ide>
<ide> export type GetTransformOptionsOpts = {|
<ide> dev: boolean,
<ide> class Bundler {
<ide> .then(r => r.dependencies.map(d => d.path));
<ide>
<ide> const {dev, hot, platform} = options;
<del> const extraOptions = this._getTransformOptions
<add> const extraOptions: ExtraTransformOptions = this._getTransformOptions
<ide> ? await this._getTransformOptions(mainModuleName, {dev, hot, platform}, getDependencies)
<ide> : {};
<add>
<add> const {transform = {}} = extraOptions;
<add>
<ide> return {
<ide> transformer: {
<ide> dev,
<ide> class Bundler {
<ide> dev,
<ide> generateSourceMaps: options.generateSourceMaps,
<ide> hot,
<del> inlineRequires: extraOptions.inlineRequires || false,
<add> inlineRequires: transform.inlineRequires || false,
<ide> platform,
<ide> projectRoot: options.projectRoots[0],
<ide> } | 1 |
Text | Text | fix example of relative workdir | 5514afcd88d40a7a9321a966292e9f724eeafc36 | <ide><path>docs/sources/reference/builder.md
<ide> It can be used multiple times in the one `Dockerfile`. If a relative path
<ide> is provided, it will be relative to the path of the previous `WORKDIR`
<ide> instruction. For example:
<ide>
<del> WORKDIR /a WORKDIR b WORKDIR c RUN pwd
<add> WORKDIR /a
<add> WORKDIR b
<add> WORKDIR c
<add> RUN pwd
<ide>
<ide> The output of the final `pwd` command in this Dockerfile would be
<ide> `/a/b/c`. | 1 |
Text | Text | add the text in definition of array. | db6756aaa226a67e2a6868cb85b4a1823bb1db5f | <ide><path>guide/english/cplusplus/arrays/index.md
<ide> For example, an array containing 5 integer values called numbers is declared lik
<ide> int numbers [5];
<ide> ```
<ide>
<del>Initializiation:
<add>Initialization with values:
<ide> ```cpp
<del>//Initialization with values:
<ide> int numbers [5] = {1, 2, 3, 4, 5};
<ide> //When initializing an array with values, the first value will be stored as the first element, the second value will be stored as the second element, ect... so the first element in this array is the value 1, and the third element is the value 3.
<ide> | 1 |
Ruby | Ruby | count assertions instead of tests in report | 734f98178261e2ba42df3ff6c39c8950e9eb01ed | <ide><path>ci/qunit-selenium-runner.rb
<ide> result = QUnit::Selenium::TestRunner.new(driver).open(ARGV[0], timeout: 60)
<ide> driver.quit
<ide>
<del>puts "Time: #{result.duration} seconds, Total: #{result.tests[:total]}, Passed: #{result.tests[:passed]}, Failed: #{result.tests[:failed]}"
<add>puts "Time: #{result.duration} seconds, Total: #{result.assertions[:total]}, Passed: #{result.assertions[:passed]}, Failed: #{result.assertions[:failed]}"
<ide> exit(result.tests[:failed] > 0 ? 1 : 0) | 1 |
PHP | PHP | fix method order | 4e5a70019d22e7415d512c3ef5df2f29bd587419 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function random($amount = 1)
<ide>
<ide> return is_array($keys) ? array_intersect_key($this->items, array_flip($keys)) : $this->items[$keys];
<ide> }
<del>
<del> /**
<del> * Shuffle the items in the collection.
<del> *
<del> * @return \Illuminate\Support\Collection
<del> */
<del> public function shuffle()
<del> {
<del> shuffle($this->items);
<del>
<del> return $this;
<del> }
<ide>
<ide> /**
<ide> * Reduce the collection to a single value.
<ide> public function shift()
<ide> return array_shift($this->items);
<ide> }
<ide>
<add> /**
<add> * Shuffle the items in the collection.
<add> *
<add> * @return \Illuminate\Support\Collection
<add> */
<add> public function shuffle()
<add> {
<add> shuffle($this->items);
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Slice the underlying collection array.
<ide> * | 1 |
Python | Python | add flag to push tf weights directly into main | c3c62b5d2c777ce50039323412599ff5f570ce3c | <ide><path>src/transformers/commands/pt_to_tf.py
<ide> def convert_command_factory(args: Namespace):
<ide>
<ide> Returns: ServeCommand
<ide> """
<del> return PTtoTFCommand(args.model_name, args.local_dir, args.no_pr, args.new_weights)
<add> return PTtoTFCommand(args.model_name, args.local_dir, args.new_weights, args.no_pr, args.push)
<ide>
<ide>
<ide> class PTtoTFCommand(BaseTransformersCLICommand):
<ide> def register_subcommand(parser: ArgumentParser):
<ide> default="",
<ide> help="Optional local directory of the model repository. Defaults to /tmp/{model_name}",
<ide> )
<add> train_parser.add_argument(
<add> "--new-weights",
<add> action="store_true",
<add> help="Optional flag to create new TensorFlow weights, even if they already exist.",
<add> )
<ide> train_parser.add_argument(
<ide> "--no-pr", action="store_true", help="Optional flag to NOT open a PR with converted weights."
<ide> )
<ide> train_parser.add_argument(
<del> "--new-weights",
<add> "--push",
<ide> action="store_true",
<del> help="Optional flag to create new TensorFlow weights, even if they already exist.",
<add> help="Optional flag to push the weights directly to `main` (requires permissions)",
<ide> )
<ide> train_parser.set_defaults(func=convert_command_factory)
<ide>
<ide> def _find_pt_tf_differences(pt_out, tf_out, differences, attr_name=""):
<ide>
<ide> return _find_pt_tf_differences(pt_outputs, tf_outputs, {})
<ide>
<del> def __init__(self, model_name: str, local_dir: str, no_pr: bool, new_weights: bool, *args):
<add> def __init__(self, model_name: str, local_dir: str, new_weights: bool, no_pr: bool, push: bool, *args):
<ide> self._logger = logging.get_logger("transformers-cli/pt_to_tf")
<ide> self._model_name = model_name
<ide> self._local_dir = local_dir if local_dir else os.path.join("/tmp", model_name)
<del> self._no_pr = no_pr
<ide> self._new_weights = new_weights
<add> self._no_pr = no_pr
<add> self._push = push
<ide>
<ide> def get_text_inputs(self):
<ide> tokenizer = AutoTokenizer.from_pretrained(self._local_dir)
<ide> def run(self):
<ide> )
<ide> )
<ide>
<del> if not self._no_pr:
<add> if self._push:
<add> repo.git_add(auto_lfs_track=True)
<add> repo.git_commit("Add TF weights")
<add> repo.git_push(blocking=True) # this prints a progress bar with the upload
<add> self._logger.warn(f"TF weights pushed into {self._model_name}")
<add> elif not self._no_pr:
<ide> # TODO: remove try/except when the upload to PR feature is released
<ide> # (https://github.com/huggingface/huggingface_hub/pull/884)
<ide> try: | 1 |
Ruby | Ruby | remove unnecessary string interpolation | 8c488de3f654af452d1cdfe5be26aca87b29af3c | <ide><path>Library/Homebrew/cask/lib/hbc/cli/info.rb
<ide> def self.name_info(cask)
<ide> def self.repo_info(cask)
<ide> user, repo, token = QualifiedToken.parse(Hbc.all_tokens.detect { |t| t.split("/").last == cask.token })
<ide> remote_tap = Tap.fetch(user, repo)
<del> return "#{remote_tap.remote}" if remote_tap.custom_remote?
<add> return remote_tap.remote.to_s if remote_tap.custom_remote?
<ide> "#{remote_tap.default_remote}/blob/master/Casks/#{token}.rb"
<ide> end
<ide> | 1 |
Ruby | Ruby | use x_tag instead of x_repository_version | ae2196fa57498ba0edad7f43fe0d3d9fa8993468 | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def output_update_report
<ide> install_core_tap_if_necessary
<ide>
<ide> updated = false
<del> new_repository_version = nil
<add> new_tag = nil
<ide>
<ide> initial_revision = ENV["HOMEBREW_UPDATE_BEFORE"].to_s
<ide> current_revision = ENV["HOMEBREW_UPDATE_AFTER"].to_s
<ide> def output_update_report
<ide> if old_tag.blank? || (new_tag == old_tag)
<ide> puts "Updated Homebrew from #{shorten_revision(initial_revision)} to #{shorten_revision(current_revision)}."
<ide> else
<del> new_repository_version = new_tag
<ide> puts "Updated Homebrew from #{old_tag} (#{shorten_revision(initial_revision)}) " \
<ide> "to #{new_tag} (#{shorten_revision(current_revision)})."
<ide> end
<ide> def output_update_report
<ide> EOS
<ide> end
<ide>
<del> return if new_repository_version.blank?
<add> return if new_tag.blank? || new_tag == old_tag
<ide>
<ide> puts
<del> ohai "Homebrew was updated to version #{new_repository_version}"
<del> Settings.write "latesttag", new_repository_version
<del> if new_repository_version.split(".").last == "0"
<add> ohai "Homebrew was updated to version #{new_tag}"
<add> Settings.write "latesttag", new_tag if new_tag != old_tag
<add> if new_tag.split(".").last == "0"
<ide> puts <<~EOS
<ide> More detailed release notes are available on the Homebrew Blog:
<del> #{Formatter.url("https://brew.sh/blog/#{new_repository_version}")}
<add> #{Formatter.url("https://brew.sh/blog/#{new_tag}")}
<ide> EOS
<ide> elsif !args.quiet?
<ide> puts <<~EOS
<ide> The changelog can be found at:
<del> #{Formatter.url("https://github.com/Homebrew/brew/releases/tag/#{new_repository_version}")}
<add> #{Formatter.url("https://github.com/Homebrew/brew/releases/tag/#{new_tag}")}
<ide> EOS
<ide> end
<ide> end | 1 |
Javascript | Javascript | improve randomuuid performance | 5694f7f0bffbad1dfb7cdbad077144444ff46977 | <ide><path>lib/internal/crypto/random.js
<ide> 'use strict';
<ide>
<ide> const {
<add> Array,
<ide> BigInt,
<ide> FunctionPrototypeBind,
<ide> FunctionPrototypeCall,
<ide> MathMin,
<ide> NumberIsNaN,
<ide> NumberIsSafeInteger,
<add> NumberPrototypeToString,
<add> StringPrototypePadStart,
<ide> } = primordials;
<ide>
<ide> const {
<ide> function getRandomValues(data) {
<ide> // Implements an RFC 4122 version 4 random UUID.
<ide> // To improve performance, random data is generated in batches
<ide> // large enough to cover kBatchSize UUID's at a time. The uuidData
<del>// and uuid buffers are reused. Each call to randomUUID() consumes
<del>// 16 bytes from the buffer.
<del>
<del>const kHexDigits = [
<del> 48, 49, 50, 51, 52, 53, 54, 55,
<del> 56, 57, 97, 98, 99, 100, 101, 102,
<del>];
<add>// buffer is reused. Each call to randomUUID() consumes 16 bytes
<add>// from the buffer.
<ide>
<ide> const kBatchSize = 128;
<ide> let uuidData;
<ide> let uuidNotBuffered;
<del>let uuid;
<ide> let uuidBatch = 0;
<ide>
<del>function getBufferedUUID() {
<del> if (uuidData === undefined) {
<del> uuidData = secureBuffer(16 * kBatchSize);
<del> if (uuidData === undefined)
<del> throw new ERR_OPERATION_FAILED('Out of memory');
<add>let hexBytesCache;
<add>function getHexBytes() {
<add> if (hexBytesCache === undefined) {
<add> hexBytesCache = new Array(256);
<add> for (let i = 0; i < hexBytesCache.length; i++) {
<add> const hex = NumberPrototypeToString(i, 16);
<add> hexBytesCache[i] = StringPrototypePadStart(hex, 2, '0');
<add> }
<ide> }
<add> return hexBytesCache;
<add>}
<add>
<add>function serializeUUID(buf, offset = 0) {
<add> const kHexBytes = getHexBytes();
<add> // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
<add> return kHexBytes[buf[offset]] +
<add> kHexBytes[buf[offset + 1]] +
<add> kHexBytes[buf[offset + 2]] +
<add> kHexBytes[buf[offset + 3]] +
<add> '-' +
<add> kHexBytes[buf[offset + 4]] +
<add> kHexBytes[buf[offset + 5]] +
<add> '-' +
<add> kHexBytes[(buf[offset + 6] & 0x0f) | 0x40] +
<add> kHexBytes[buf[offset + 7]] +
<add> '-' +
<add> kHexBytes[(buf[offset + 8] & 0x3f) | 0x80] +
<add> kHexBytes[buf[offset + 9]] +
<add> '-' +
<add> kHexBytes[buf[offset + 10]] +
<add> kHexBytes[buf[offset + 11]] +
<add> kHexBytes[buf[offset + 12]] +
<add> kHexBytes[buf[offset + 13]] +
<add> kHexBytes[buf[offset + 14]] +
<add> kHexBytes[buf[offset + 15]];
<add>}
<add>
<add>function getBufferedUUID() {
<add> uuidData ??= secureBuffer(16 * kBatchSize);
<add> if (uuidData === undefined)
<add> throw new ERR_OPERATION_FAILED('Out of memory');
<ide>
<ide> if (uuidBatch === 0) randomFillSync(uuidData);
<ide> uuidBatch = (uuidBatch + 1) % kBatchSize;
<del> return uuidData.slice(uuidBatch * 16, (uuidBatch * 16) + 16);
<add> return serializeUUID(uuidData, uuidBatch * 16);
<add>}
<add>
<add>function getUnbufferedUUID() {
<add> uuidNotBuffered ??= secureBuffer(16);
<add> if (uuidNotBuffered === undefined)
<add> throw new ERR_OPERATION_FAILED('Out of memory');
<add> randomFillSync(uuidNotBuffered);
<add> return serializeUUID(uuidNotBuffered);
<ide> }
<ide>
<ide> function randomUUID(options) {
<ide> if (options !== undefined)
<ide> validateObject(options, 'options');
<ide> const {
<ide> disableEntropyCache = false,
<del> } = { ...options };
<add> } = options || {};
<ide>
<ide> validateBoolean(disableEntropyCache, 'options.disableEntropyCache');
<ide>
<del> if (uuid === undefined) {
<del> uuid = Buffer.alloc(36, '-');
<del> uuid[14] = 52; // '4', identifies the UUID version
<del> }
<del>
<del> let uuidBuf;
<del> if (!disableEntropyCache) {
<del> uuidBuf = getBufferedUUID();
<del> } else {
<del> uuidBuf = uuidNotBuffered;
<del> if (uuidBuf === undefined)
<del> uuidBuf = uuidNotBuffered = secureBuffer(16);
<del> if (uuidBuf === undefined)
<del> throw new ERR_OPERATION_FAILED('Out of memory');
<del> randomFillSync(uuidBuf);
<del> }
<del>
<del> // Variant byte: 10xxxxxx (variant 1)
<del> uuidBuf[8] = (uuidBuf[8] & 0x3f) | 0x80;
<del>
<del> // This function is structured the way it is for performance.
<del> // The uuid buffer stores the serialization of the random
<del> // bytes from uuidData.
<del> // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
<del> let n = 0;
<del> uuid[0] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[1] = kHexDigits[uuidBuf[n++] & 0xf];
<del> uuid[2] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[3] = kHexDigits[uuidBuf[n++] & 0xf];
<del> uuid[4] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[5] = kHexDigits[uuidBuf[n++] & 0xf];
<del> uuid[6] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[7] = kHexDigits[uuidBuf[n++] & 0xf];
<del> // -
<del> uuid[9] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[10] = kHexDigits[uuidBuf[n++] & 0xf];
<del> uuid[11] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[12] = kHexDigits[uuidBuf[n++] & 0xf];
<del> // -
<del> // 4, uuid[14] is set already...
<del> uuid[15] = kHexDigits[uuidBuf[n++] & 0xf];
<del> uuid[16] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[17] = kHexDigits[uuidBuf[n++] & 0xf];
<del> // -
<del> uuid[19] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[20] = kHexDigits[uuidBuf[n++] & 0xf];
<del> uuid[21] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[22] = kHexDigits[uuidBuf[n++] & 0xf];
<del> // -
<del> uuid[24] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[25] = kHexDigits[uuidBuf[n++] & 0xf];
<del> uuid[26] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[27] = kHexDigits[uuidBuf[n++] & 0xf];
<del> uuid[28] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[29] = kHexDigits[uuidBuf[n++] & 0xf];
<del> uuid[30] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[31] = kHexDigits[uuidBuf[n++] & 0xf];
<del> uuid[32] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[33] = kHexDigits[uuidBuf[n++] & 0xf];
<del> uuid[34] = kHexDigits[uuidBuf[n] >> 4];
<del> uuid[35] = kHexDigits[uuidBuf[n] & 0xf];
<del>
<del> return uuid.latin1Slice(0, 36);
<add> return disableEntropyCache ? getUnbufferedUUID() : getBufferedUUID();
<ide> }
<ide>
<ide> function createRandomPrimeJob(type, size, options) { | 1 |
Ruby | Ruby | simplify values_list with more composition | ded9a154241989cc65f4f38d7c9643f2cdf01a65 | <ide><path>activerecord/lib/active_record/insert_all.rb
<ide> def update_duplicates?
<ide> on_duplicate == :update
<ide> end
<ide>
<add> def map_key_with_value
<add> inserts.map do |attributes|
<add> attributes = attributes.stringify_keys
<add> verify_attributes(attributes)
<add>
<add> keys.map do |key|
<add> yield key, attributes[key]
<add> end
<add> end
<add> end
<add>
<ide> private
<ide> def ensure_valid_options_for_connection!
<ide> if returning && !connection.supports_insert_returning?
<ide> def primary_keys
<ide> Array.wrap(model.primary_key)
<ide> end
<ide>
<add> def verify_attributes(attributes)
<add> if keys != attributes.keys.to_set
<add> raise ArgumentError, "All objects being inserted must have the same keys"
<add> end
<add> end
<add>
<ide>
<ide> class Builder
<ide> attr_reader :model
<ide> def into
<ide> end
<ide>
<ide> def values_list
<del> columns = connection.schema_cache.columns_hash(model.table_name)
<del> keys = insert_all.keys
<del> verify_columns_exist_for(keys, columns)
<del>
<del> types = keys.map { |key| [ key, connection.lookup_cast_type_from_column(columns[key]) ] }.to_h
<add> types = extract_types_from_columns_on(model.table_name, keys: insert_all.keys)
<ide>
<del> values_list = insert_all.inserts.map do |attributes|
<del> attributes = attributes.stringify_keys
<del>
<del> unless attributes.keys.to_set == keys
<del> raise ArgumentError, "All objects being inserted must have the same keys"
<del> end
<del>
<del> keys.map do |key|
<del> bind = Relation::QueryAttribute.new(key, attributes[key], types[key])
<del> connection.with_yaml_fallback(bind.value_for_database)
<del> end
<add> values_list = insert_all.map_key_with_value do |key, value|
<add> bind = Relation::QueryAttribute.new(key, value, types[key])
<add> connection.with_yaml_fallback(bind.value_for_database)
<ide> end
<ide>
<ide> Arel::InsertManager.new.create_values_list(values_list).to_sql
<ide> def columns_list
<ide> quote_columns(insert_all.keys).join(",")
<ide> end
<ide>
<del> def quote_columns(columns)
<del> columns.map(&connection.method(:quote_column_name))
<del> end
<add> def extract_types_from_columns_on(table_name, keys:)
<add> columns = connection.schema_cache.columns_hash(table_name)
<ide>
<del> def verify_columns_exist_for(keys, columns)
<del> unknown_columns = keys - columns.keys
<add> unknown_column = (keys - columns.keys).first
<add> raise UnknownAttributeError.new(model.new, unknown_column) if unknown_column
<ide>
<del> if unknown_columns.any?
<del> raise UnknownAttributeError.new(model.new, unknown_columns.first)
<del> end
<add> keys.map { |key| [ key, connection.lookup_cast_type_from_column(columns[key]) ] }.to_h
<add> end
<add>
<add> def quote_columns(columns)
<add> columns.map(&connection.method(:quote_column_name))
<ide> end
<ide>
<ide> def conflict_columns | 1 |
PHP | PHP | fix php cs | 85a96a40833289b6419661b3df46466304f4436e | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> namespace Illuminate\Database\Eloquent;
<ide>
<ide> use Closure;
<del>use InvalidArgumentException;
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<add>use InvalidArgumentException;
<ide> use Illuminate\Pagination\Paginator;
<ide> use Illuminate\Database\Query\Expression;
<ide> use Illuminate\Pagination\LengthAwarePaginator;
<ide> public function lists($column, $key = null)
<ide> * @param int|null $page
<ide> * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
<ide> *
<del> * @throws InvalidArgumentException
<add> * @throws \InvalidArgumentException
<ide> */
<ide> public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
<ide> { | 1 |
Python | Python | fix complex casting test on py3.4 | a411e89f5188f0f9756ecee25d47a2b758841ce2 | <ide><path>celery/tests/utils/test_local.py
<ide> def test_complex_cast(self):
<ide> class O(object):
<ide>
<ide> def __complex__(self):
<del> return 10.333
<add> return complex(10.333)
<ide>
<ide> o = Proxy(O)
<del> self.assertEqual(o.__complex__(), 10.333)
<add> self.assertEqual(o.__complex__(), complex(10.333))
<ide>
<ide> def test_index(self):
<ide> | 1 |
Javascript | Javascript | update pane specs for async confirm | 4fdee7bb8f658923cefe0f04379a05a194fb1c51 | <ide><path>spec/pane-spec.js
<ide> describe('Pane', () => {
<ide> describe('when the item has a uri', () => {
<ide> it('saves the item before destroying it', async () => {
<ide> itemURI = 'test'
<del> confirm.andReturn(0)
<add> confirm.andCallFake((options, callback) => callback(0))
<ide>
<ide> const success = await pane.destroyItem(item1)
<ide> expect(item1.save).toHaveBeenCalled()
<ide> describe('Pane', () => {
<ide> itemURI = null
<ide>
<ide> showSaveDialog.andReturn('/selected/path')
<del> confirm.andReturn(0)
<add> confirm.andCallFake((options, callback) => callback(0))
<ide>
<ide> const success = await pane.destroyItem(item1)
<ide> expect(showSaveDialog).toHaveBeenCalledWith({})
<ide> describe('Pane', () => {
<ide>
<ide> describe("if the [Don't Save] option is selected", () => {
<ide> it('removes and destroys the item without saving it', async () => {
<del> confirm.andReturn(2)
<add> confirm.andCallFake((options, callback) => callback(2))
<ide>
<ide> const success = await pane.destroyItem(item1)
<ide> expect(item1.save).not.toHaveBeenCalled()
<ide> describe('Pane', () => {
<ide>
<ide> describe('if the [Cancel] option is selected', () => {
<ide> it('does not save, remove, or destroy the item', async () => {
<del> confirm.andReturn(1)
<add> confirm.andCallFake((options, callback) => callback(1))
<ide>
<ide> const success = await pane.destroyItem(item1)
<ide> expect(item1.save).not.toHaveBeenCalled()
<ide> describe('Pane', () => {
<ide> item1.getURI = () => '/test/path'
<ide> item1.save = jasmine.createSpy('save')
<ide>
<del> confirm.andReturn(0)
<add> confirm.andCallFake((options, callback) => callback(0))
<ide> await pane.close()
<ide> expect(confirm).toHaveBeenCalled()
<ide> expect(item1.save).toHaveBeenCalled()
<ide> describe('Pane', () => {
<ide> item1.getURI = () => '/test/path'
<ide> item1.save = jasmine.createSpy('save')
<ide>
<del> confirm.andReturn(1)
<add> confirm.andCallFake((options, callback) => callback(1))
<ide>
<ide> await pane.close()
<ide> expect(confirm).toHaveBeenCalled()
<ide> describe('Pane', () => {
<ide> item1.shouldPromptToSave = () => true
<ide> item1.saveAs = jasmine.createSpy('saveAs')
<ide>
<del> confirm.andReturn(0)
<add> confirm.andCallFake((options, callback) => callback(0))
<ide> showSaveDialog.andReturn(undefined)
<ide>
<ide> await pane.close()
<ide> describe('Pane', () => {
<ide>
<ide> it('does not destroy the pane if save fails and user clicks cancel', async () => {
<ide> let confirmations = 0
<del> confirm.andCallFake(() => {
<add> confirm.andCallFake((options, callback) => {
<ide> confirmations++
<ide> if (confirmations === 1) {
<del> return 0 // click save
<add> callback(0) // click save
<ide> } else {
<del> return 1
<add> callback(1)
<ide> }
<ide> }) // click cancel
<ide>
<ide> describe('Pane', () => {
<ide> item1.saveAs = jasmine.createSpy('saveAs').andReturn(true)
<ide>
<ide> let confirmations = 0
<del> confirm.andCallFake(() => {
<add> confirm.andCallFake((options, callback) => {
<ide> confirmations++
<del> return 0
<add> callback(0)
<ide> }) // save and then save as
<ide>
<ide> showSaveDialog.andReturn('new/path')
<ide> describe('Pane', () => {
<ide> })
<ide>
<ide> let confirmations = 0
<del> confirm.andCallFake(() => {
<add> confirm.andCallFake((options, callback) => {
<ide> confirmations++
<ide> if (confirmations < 3) {
<del> return 0 // save, save as, save as
<add> callback(0) // save, save as, save as
<add> } else {
<add> callback(2) // don't save
<ide> }
<del> return 2
<del> }) // don't save
<add> })
<ide>
<ide> showSaveDialog.andReturn('new/path')
<ide> | 1 |
Mixed | Javascript | sanitize env variables | abd8cdfc4e7d0d7f563a9b0f91523fe8395d5e25 | <ide><path>doc/api/child_process.md
<ide> the first one case-insensitively matching `PATH` to perform command lookup.
<ide> This may lead to issues on Windows when passing objects to `env` option that
<ide> have multiple variants of `PATH` variable.
<ide>
<add>On Windows Node.js will sanitize the `env` by removing case-insensitive
<add>duplicates. Only first (in lexicographic order) entry will be passed to the
<add>child process.
<add>
<ide> The [`child_process.spawn()`][] method spawns the child process asynchronously,
<ide> without blocking the Node.js event loop. The [`child_process.spawnSync()`][]
<ide> function provides equivalent functionality in a synchronous manner that blocks
<ide><path>lib/child_process.js
<ide> const {
<ide> ObjectDefineProperty,
<ide> ObjectPrototypeHasOwnProperty,
<ide> Promise,
<add> Set,
<ide> } = primordials;
<ide>
<ide> const {
<ide> function normalizeSpawnArguments(file, args, options) {
<ide> env.NODE_V8_COVERAGE = process.env.NODE_V8_COVERAGE;
<ide> }
<ide>
<add> let envKeys = [];
<ide> // Prototype values are intentionally included.
<ide> for (const key in env) {
<add> envKeys.push(key);
<add> }
<add>
<add> if (process.platform === 'win32') {
<add> // On Windows env keys are case insensitive. Filter out duplicates,
<add> // keeping only the first one (in lexicographic order)
<add> const sawKey = new Set();
<add> envKeys = envKeys.sort().filter((key) => {
<add> const uppercaseKey = key.toUpperCase();
<add> if (sawKey.has(uppercaseKey)) {
<add> return false;
<add> }
<add> sawKey.add(uppercaseKey);
<add> return true;
<add> });
<add> }
<add>
<add> for (const key of envKeys) {
<ide> const value = env[key];
<ide> if (value !== undefined) {
<ide> envPairs.push(`${key}=${value}`);
<ide><path>test/parallel/test-child-process-env.js
<ide> const env = {
<ide> 'HELLO': 'WORLD',
<ide> 'UNDEFINED': undefined,
<ide> 'NULL': null,
<del> 'EMPTY': ''
<add> 'EMPTY': '',
<add> 'duplicate': 'lowercase',
<add> 'DUPLICATE': 'uppercase',
<ide> };
<ide> Object.setPrototypeOf(env, {
<ide> 'FOO': 'BAR'
<ide> child.stdout.on('end', mustCall(() => {
<ide> assert.ok(!response.includes('UNDEFINED=undefined'));
<ide> assert.ok(response.includes('NULL=null'));
<ide> assert.ok(response.includes(`EMPTY=${os.EOL}`));
<add> if (isWindows) {
<add> assert.ok(response.includes('DUPLICATE=uppercase'));
<add> assert.ok(!response.includes('duplicate=lowercase'));
<add> } else {
<add> assert.ok(response.includes('DUPLICATE=uppercase'));
<add> assert.ok(response.includes('duplicate=lowercase'));
<add> }
<ide> })); | 3 |
Go | Go | remove unused variable | 08c6575cafd549a9d6688fab218377d73889ba72 | <ide><path>distribution/registry_unit_test.go
<ide> func testTokenPassThru(t *testing.T, ts *httptest.Server) {
<ide> Official: false,
<ide> TrimHostname: false,
<ide> TLSConfig: nil,
<del> //VersionHeader: "verheader",
<ide> }
<ide> n, _ := reference.ParseNamed("testremotename")
<ide> repoInfo := ®istry.RepositoryInfo{
<ide> func TestTokenPassThruDifferentHost(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>// TestDirectory creates a new temporary directory and returns its path.
<add>// testDirectory creates a new temporary directory and returns its path.
<ide> // The contents of directory at path `templateDir` is copied into the
<ide> // new directory.
<ide> func testDirectory(templateDir string) (dir string, err error) { | 1 |
Ruby | Ruby | add check for /library python | 95d7776a905bb89d2bf98407dfab9d12f906d88b | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_for_enthought_python
<ide> end
<ide> end
<ide>
<add>def check_for_library_python
<add> if File.exist?("/Library/Frameworks/Python.framework") then <<-EOS.undent
<add> A Python is installed in /Library/Frameworks
<add>
<add> Homebrew only supports building against the System-provided Python or a
<add> brewed Python. In particular, Pythons installed to /Library can interfere
<add> with other software installs.
<add> EOS
<add> end
<add>end
<add>
<ide> def check_for_old_homebrew_share_python_in_path
<ide> s = ''
<ide> ['', '3'].map do |suffix| | 1 |
Ruby | Ruby | do cache clearing in single location | 22795d7e306704527137d3c1920bae358b00ab03 | <ide><path>Library/Homebrew/test/dependency_collector_spec.rb
<ide> def find_requirement(klass)
<ide> subject.requirements.find { |req| req.is_a? klass }
<ide> end
<ide>
<del> after do
<del> described_class.clear_cache
<del> end
<del>
<ide> describe "#add" do
<ide> specify "dependency creation" do
<ide> subject.add "foo" => :build
<ide><path>Library/Homebrew/test/missing_formula_spec.rb
<ide> subject { described_class.tap_migration_reason(formula) }
<ide>
<ide> before do
<del> Tap.clear_cache
<ide> tap_path = Tap::TAP_DIRECTORY/"homebrew/homebrew-foo"
<ide> tap_path.mkpath
<ide> (tap_path/"tap_migrations.json").write <<~JSON
<ide> subject { described_class.deleted_reason(formula, silent: true) }
<ide>
<ide> before do
<del> Tap.clear_cache
<ide> tap_path = Tap::TAP_DIRECTORY/"homebrew/homebrew-foo"
<ide> tap_path.mkpath
<ide> (tap_path/"deleted-formula.rb").write "placeholder"
<ide><path>Library/Homebrew/test/os/linux/dependency_collector_spec.rb
<ide> describe DependencyCollector do
<ide> alias_matcher :be_a_build_requirement, :be_build
<ide>
<del> after do
<del> described_class.clear_cache
<del> end
<del>
<ide> describe "#add" do
<ide> resource = Resource.new
<ide>
<ide><path>Library/Homebrew/test/os/mac/dependency_collector_spec.rb
<ide> describe DependencyCollector do
<ide> alias_matcher :need_tar_xz_dependency, :be_tar_needs_xz_dependency
<ide>
<del> after do
<del> described_class.clear_cache
<del> end
<del>
<ide> specify "Resource dependency from a '.xz' URL" do
<ide> resource = Resource.new
<ide> resource.url("https://brew.sh/foo.tar.xz")
<ide><path>Library/Homebrew/test/spec_helper.rb
<ide> def find_files
<ide>
<ide> begin
<ide> Homebrew.raise_deprecation_exceptions = true
<add>
<add> Formulary.clear_cache
<add> Tap.clear_cache
<add> DependencyCollector.clear_cache
<ide> Formula.clear_cache
<ide> Keg.clear_cache
<del> Tap.clear_cache
<add> Tab.clear_cache
<ide> FormulaInstaller.clear_attempted
<ide>
<ide> TEST_DIRECTORIES.each(&:mkpath)
<ide> def find_files
<ide> @__stderr.close
<ide> end
<ide>
<del> Tab.clear_cache
<add> Formulary.clear_cache
<add> Tap.clear_cache
<add> DependencyCollector.clear_cache
<ide> Formula.clear_cache
<ide> Keg.clear_cache
<add> Tab.clear_cache
<ide>
<ide> FileUtils.rm_rf [
<ide> TEST_DIRECTORIES.map(&:children),
<ide><path>Library/Homebrew/test/tap_spec.rb
<ide> def setup_git_repo
<ide> expect {
<ide> described_class.fetch("homebrew", "homebrew/baz")
<ide> }.to raise_error(/Invalid tap name/)
<del> ensure
<del> described_class.clear_cache
<ide> end
<ide>
<ide> describe "::from_path" do | 6 |
Python | Python | add tests for roll function | 5bc0a84022c2c65addf306f50eef6f37244ae595 | <ide><path>numpy/core/tests/test_numeric.py
<ide> def test_set_string_function(self):
<ide> np.set_string_function(None, repr=False)
<ide> assert_equal(str(a), "[1]")
<ide>
<add>class TestRoll(TestCase):
<add> def test_roll1d(self):
<add> x = np.arange(10)
<add> xr = np.roll(x, 2)
<add> assert_equal(xr, np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]))
<add>
<add> def test_roll2d(self):
<add> x2 = np.reshape(np.arange(10), (2,5))
<add> x2r = np.roll(x2, 1)
<add> assert_equal(x2r, np.array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]]))
<add>
<add> x2r = np.roll(x2, 1, axis=0)
<add> assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))
<add>
<add> x2r = np.roll(x2, 1, axis=1)
<add> assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
<add>
<add> def test_roll_empty(self):
<add> x = np.array([])
<add> assert_equal(np.roll(x, 1), np.array([]))
<add>
<add>
<ide> if __name__ == "__main__":
<ide> run_module_suite() | 1 |
PHP | PHP | remove exceptions no longer used | 6bcf9873f0a7a17fab10f115c857e7e3734f0b5b | <ide><path>src/Error/MissingConnectionException.php
<del><?php
<del>/**
<del> * MissingConnectionException class
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<del> * @since 3.0.0
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>namespace Cake\Error;
<del>
<del>/**
<del> * Used when no connections can be found.
<del> *
<del> */
<del>class MissingConnectionException extends Exception {
<del>
<del> protected $_messageTemplate = 'Database connection "%s" is missing, or could not be created.';
<del>
<del> public function __construct($message, $code = 500) {
<del> if (is_array($message)) {
<del> $message += array('enabled' => true);
<del> }
<del> parent::__construct($message, $code);
<del> }
<del>
<del>}
<ide><path>src/Error/MissingDatabaseException.php
<del><?php
<del>/**
<del> * MissingDatabaseException class
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<del> * @since 3.0.0
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>namespace Cake\Error;
<del>
<del>/**
<del> * Runtime Exceptions for ConnectionManager
<del> *
<del> */
<del>class MissingDatabaseException extends Exception {
<del>
<del> protected $_messageTemplate = 'Database connection "%s" could not be found.';
<del>
<del>}
<ide><path>src/Error/MissingTableException.php
<del><?php
<del>/**
<del> * MissingTableException class
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<del> * @since 3.0.0
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>namespace Cake\Error;
<del>
<del>/**
<del> * Exception class to be thrown when a database table is not found in the datasource
<del> *
<del> */
<del>class MissingTableException extends Exception {
<del>
<del> protected $_messageTemplate = 'Table %s for model %s was not found in datasource %s.';
<del>
<del>}
<ide><path>src/Error/MissingTestLoaderException.php
<del><?php
<del>/**
<del> * MissingTestLoaderException class
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<del> * @since 3.0.0
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>namespace Cake\Error;
<del>
<del>/**
<del> * Exception raised when a test loader could not be found
<del> *
<del> */
<del>class MissingTestLoaderException extends Exception {
<del>
<del> protected $_messageTemplate = 'Test loader %s could not be found.';
<del>
<del>}
<ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> public static function testProvider() {
<ide> ),
<ide> 404
<ide> ),
<del> array(
<del> new Error\MissingTableException(array('table' => 'articles', 'class' => 'Article', 'ds' => 'test')),
<del> array(
<del> '/<h2>Missing Database Table<\/h2>/',
<del> '/Table <em>articles<\/em> for model <em>Article<\/em> was not found in datasource <em>test<\/em>/'
<del> ),
<del> 500
<del> ),
<del> array(
<del> new Error\MissingDatabaseException(array('connection' => 'default')),
<del> array(
<del> '/<h2>Missing Database Connection<\/h2>/',
<del> '/Confirm you have created the file/'
<del> ),
<del> 500
<del> ),
<ide> array(
<ide> new Error\MissingViewException(array('file' => '/posts/about.ctp')),
<ide> array(
<ide> public static function testProvider() {
<ide> ),
<ide> 500
<ide> ),
<del> array(
<del> new Error\MissingConnectionException(array('class' => 'Mysql')),
<del> array(
<del> '/<h2>Missing Database Connection<\/h2>/',
<del> '/A Database connection using "Mysql" was missing or unable to connect./',
<del> ),
<del> 500
<del> ),
<del> array(
<del> new Error\MissingConnectionException(array('class' => 'Mysql', 'enabled' => false)),
<del> array(
<del> '/<h2>Missing Database Connection<\/h2>/',
<del> '/A Database connection using "Mysql" was missing or unable to connect./',
<del> '/Mysql driver is NOT enabled/'
<del> ),
<del> 500
<del> ),
<ide> array(
<ide> new Error\MissingHelperException(array('class' => 'MyCustomHelper')),
<ide> array( | 5 |
Python | Python | fix clone action in kvm | 032a7dc3e2517cdb85a9150763751f03e22c983a | <ide><path>libcloud/compute/drivers/libvirt_driver.py
<ide> import atexit
<ide> import logging
<ide> import netaddr
<add>import random
<ide>
<ide> from tempfile import NamedTemporaryFile
<ide> from os.path import join as pjoin
<ide> def create_node(self, name, disk_size=4, ram=512,
<ide>
<ide> return True
<ide>
<del> def ex_clone_vm(self, node, new_name=None, resume_node=False):
<add> def ex_clone_node(self, node, new_name=None, resume_node=False):
<ide> """Clone a domain
<ide>
<ide> The only required parameters are the `node` to clone and a `new_name`,
<ide> def ex_clone_vm(self, node, new_name=None, resume_node=False):
<ide> Finally, the original guest VM may be optionally resumed.
<ide>
<ide> """
<add>
<ide> # Generate unique clone name, if not provided.
<del> new_name = new_name or '%s-clone-%s' % (node.name,
<del> os.urandom(4).encode('hex'))
<add> new_name = new_name or '%s-clone-%s' % (node.name, random.randint(1,100))
<ide>
<ide> # Get the current domain.
<ide> domain = self._get_domain_for_node(node)
<ide> def ex_clone_vm(self, node, new_name=None, resume_node=False):
<ide> "%s to %s" % (old_disk_path, new_disk_path))
<ide>
<ide> # Define the new domain via the modified XML.
<del> self.connection.defineXML(ET.tostring(et))
<add> self.connection.defineXML(ET.tostring(et).decode())
<ide>
<ide> # Start the new domain.
<ide> new_domain = self.connection.lookupByName(new_name) | 1 |
Ruby | Ruby | remove unconditional cask/formula uninstall | 915eed4c6427271c5b4c01fa36239361c3680c40 | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def migrate_tap_migration
<ide> new_tap = Tap.fetch(new_tap_name)
<ide> # For formulae migrated to cask: Auto-install cask or provide install instructions.
<ide> if new_tap_name == "caskroom/cask"
<del> system HOMEBREW_BREW_FILE, "uninstall", name
<ide> if new_tap.installed? && (HOMEBREW_REPOSITORY/"Caskroom").directory?
<ide> ohai "#{name} has been moved to Homebrew Cask. Installing #{name}..."
<ide> system HOMEBREW_BREW_FILE, "uninstall", "--force", name
<ide> def migrate_tap_migration
<ide> ohai "#{name} has been moved to Homebrew Cask.", <<-EOS.undent
<ide> To uninstall the formula and install the cask run:
<ide> brew uninstall --force #{name}
<del> brew cask install #{name}
<add> brew cask install #{name}
<ide> EOS
<ide> end
<ide> else | 1 |
Javascript | Javascript | fix the parameter order of before/afterevent | c749fbdf5f8ec08df0261fd8600684ce000a9cf0 | <ide><path>src/core/core.plugins.js
<ide> function createDescriptors(plugins, options) {
<ide> * the event will be discarded.
<ide> * @param {Chart} chart - The chart instance.
<ide> * @param {IEvent} event - The event object.
<del> * @param {object} options - The plugin options.
<ide> * @param {boolean} replay - True if this event is replayed from `Chart.update`
<add> * @param {object} options - The plugin options.
<ide> */
<ide> /**
<ide> * @method IPlugin#afterEvent
<ide> * @desc Called after the `event` has been consumed. Note that this hook
<ide> * will not be called if the `event` has been previously discarded.
<ide> * @param {Chart} chart - The chart instance.
<ide> * @param {IEvent} event - The event object.
<del> * @param {object} options - The plugin options.
<ide> * @param {boolean} replay - True if this event is replayed from `Chart.update`
<add> * @param {object} options - The plugin options.
<ide> */
<ide> /**
<ide> * @method IPlugin#resize | 1 |
PHP | PHP | pass the path to the filter event | 633c2bde836f5a0b3898e85a28683ada645b6522 | <ide><path>laravel/view.php
<ide> public function get()
<ide> // us do something like run the contents through Jade, etc.
<ide> if (Event::listeners('view.filter'))
<ide> {
<del> return Event::first('view.filter', $content);
<add> return Event::first('view.filter', array($content, $this->path));
<ide> }
<ide>
<ide> return $content; | 1 |
Javascript | Javascript | handle possible side effect | cb05e419bc9b68b45022096b82255585e8f3c4af | <ide><path>lib/dependencies/HarmonyImportDependencyParserPlugin.js
<ide> module.exports = class HarmonyImportDependencyParserPlugin {
<ide> expression => {
<ide> if (expression.operator !== "in") return;
<ide>
<del> const leftPart = parser.evaluateExpression(expression.left).asString();
<add> const leftPartEvaluated = parser.evaluateExpression(expression.left);
<add> if (leftPartEvaluated.couldHaveSideEffects()) return;
<add> const leftPart = leftPartEvaluated.asString();
<ide> if (!leftPart) return;
<ide>
<ide> const rightPart = parser.evaluateExpression(expression.right); | 1 |
Javascript | Javascript | remove unused argument in test | 1f40774763a83c1ab66d111a3b5a6b4870dd577d | <ide><path>packages/ember-glimmer/tests/integration/components/local-lookup-test.js
<ide> moduleFor('Components test: local lookup', class extends RenderingTest {
<ide> this.assertText('Nested template says: Hi!', 'Re-render works');
<ide> }
<ide>
<del> ['@test tagless blockless component can lookup local template'](assert) {
<add> ['@test tagless blockless component can lookup local template']() {
<ide> this.registerComponent('x-outer/x-inner', { template: 'Nested template says: {{yield}}' });
<ide> this.registerTemplate('components/x-outer', '{{#x-inner}}Hi!{{/x-inner}}');
<ide> this.registerComponent('x-outer', { | 1 |
Mixed | Ruby | remove -j (--javascript) option from `rails new` | 42198064c35ff3b701496309f90df2abc229efbe | <ide><path>railties/CHANGELOG.md
<add>* Remove -j (--javascript) option from `rails new` command
<add>
<add> *claudiob*
<add>
<add>
<ide> Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/railties/CHANGELOG.md) for previous changes.
<ide><path>railties/lib/rails/generators/app_base.rb
<ide> def self.add_shared_options_for(name)
<ide> class_option :database, type: :string, aliases: "-d", default: "sqlite3",
<ide> desc: "Preconfigure for selected database (options: #{DATABASES.join('/')})"
<ide>
<del> class_option :javascript, type: :string, aliases: "-j",
<del> desc: "Preconfigure for selected JavaScript library"
<del>
<ide> class_option :webpack, type: :string, default: nil,
<ide> desc: "Preconfigure for app-like JavaScript with Webpack (options: #{WEBPACKS.join('/')})"
<ide>
<ide> def javascript_gemfile_entry
<ide> gems = [javascript_runtime_gemfile_entry]
<ide> gems << coffee_gemfile_entry unless options[:skip_coffee]
<ide>
<del> if options[:javascript]
<del> gems << GemfileEntry.version("#{options[:javascript]}-rails", nil,
<del> "Use #{options[:javascript]} as the JavaScript library")
<del> end
<del>
<ide> unless options[:skip_turbolinks]
<ide> gems << GemfileEntry.version("turbolinks", "~> 5",
<ide> "Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks")
<ide><path>railties/test/generators/app_generator_test.rb
<ide> def test_rails_ujs_is_the_default_ujs_library
<ide> end
<ide> end
<ide>
<del> def test_inclusion_of_javascript_libraries_if_required
<del> run_generator [destination_root, "-j", "jquery"]
<del> assert_file "app/assets/javascripts/application.js" do |contents|
<del> assert_match %r{^//= require jquery}, contents
<del> end
<del> assert_gem "jquery-rails"
<del> end
<del>
<ide> def test_javascript_is_skipped_if_required
<ide> run_generator [destination_root, "--skip-javascript"]
<ide> | 3 |
Ruby | Ruby | fix access to relocated method | 37b817ed394986808d2fdb595c272ede7a67f20d | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def run
<ide>
<ide>
<ide> unless output.empty?
<del> @output = fix_encoding!(output)
<add> @output = Homebrew.fix_encoding!(output)
<ide> puts @output if (failed? || @puts_output_on_success) && !verbose
<ide> File.write(log_file_path, @output) if ARGV.include? "--keep-logs"
<ide> end | 1 |
Ruby | Ruby | add missing require | 17fb1b6dd87b531d26b8bfe606cce55a5106ab2c | <ide><path>Library/Homebrew/cmd/deps.rb
<ide> require "ostruct"
<ide> require "cli/parser"
<ide> require "cask/caskroom"
<add>require "cask_dependent"
<ide>
<ide> module Homebrew
<ide> extend DependenciesHelpers | 1 |
Javascript | Javascript | fix action tests for ie | 664c34812b4f31b84dc67e186741b60813f6926e | <ide><path>packages/ember-application/tests/system/action_url_test.js
<ide> test("it does not generate the URL when href property is not specified", functio
<ide> ok(!view.$().html().match(/href=['"]\/foo\/bar['"]/), "The html (" + view.$().html() + ") has the href /foo/bar in it");
<ide> });
<ide>
<del>test("it sets a URL with a context", function() {
<add>test("it sets an URL with a context", function() {
<ide> var router = Ember.Router.create({
<ide> location: {
<ide> formatURL: function(url) {
<ide> test("it sets a URL with a context", function() {
<ide> equal(router.getPath('currentState.path'), "root.index", "precond - the current stat is root.index");
<ide>
<ide> var view = Ember.View.create({
<del> template: compile('<a {{action showDashboard context="controller.component" href=true}}>')
<add> template: compile('<a {{action showDashboard context="controller.component" href=true}}>test</a>')
<ide> });
<ide>
<ide> var controller = { | 1 |
Ruby | Ruby | remove unnecessary /scripts; feedback fixes | 98f0d63c9510e930af255ef5e3abb0e7cf53e05f | <ide><path>Library/Homebrew/utils/livecheck.rb
<ide>
<ide> module Livecheck
<ide> def livecheck_formula_response(formula_name)
<del> ohai "- livecheck formula : #{formula_name}"
<del> command_args = [
<del> "brew",
<del> "livecheck",
<del> formula_name,
<del> "--quiet",
<del> ]
<add> ohai "Checking livecheck formula : #{formula_name}"
<add> command_args = ["brew", "livecheck", formula_name, "--quiet"]
<ide>
<ide> response = Open3.capture2e(*command_args)
<ide> parse_livecheck_response(response)
<ide> def parse_livecheck_response(response)
<ide> # eg: ["burp", "2.2.18", "2.2.18"]
<ide> package_name, brew_version, latest_version = output
<ide>
<del> { "name" => package_name, "current_brew_version" => brew_version,
<del> "livecheck_latest_version" => latest_version }
<add> {
<add> name: package_name,
<add> formula_version: brew_version,
<add> livecheck_version: latest_version,
<add> }
<ide> end
<ide> end
<ide><path>Library/Homebrew/utils/repology.rb
<ide> module RepologyParser
<ide> module_function
<ide>
<add> MAX_PAGE_LIMIT = 15
<add>
<ide> def query_api(last_package_in_response = "")
<del> url = "https://repology.org/api/v1/projects/#{last_package_in_response}?inrepo=homebrew&outdated=1"
<add> url = "https://repology.org/api/v1/projects/#{last_package_in_response}/?inrepo=homebrew&outdated=1"
<ide> ohai "Calling API #{url}" if Homebrew.args.verbose?
<ide>
<del> output, errors, status = curl_output(url.to_s)
<del> output = JSON.parse(output)
<add> output, _errors, _status = curl_output(url.to_s)
<add> JSON.parse(output)
<ide> end
<ide>
<del> def parse_api_response()
<add> def parse_api_response
<ide> ohai "Querying outdated packages from Repology"
<ide> page_no = 1
<del> ohai "Paginating repology api page: #{page_no}" if Homebrew.args.verbose?
<add> ohai "Paginating Repology api page: #{page_no}" if Homebrew.args.verbose?
<ide>
<del> outdated_packages = query_api()
<del> last_pacakge_index = outdated_packages.size - 1
<add> outdated_packages = query_api
<add> last_package_index = outdated_packages.size - 1
<ide> response_size = outdated_packages.size
<del> page_limit = 15
<ide>
<del> while response_size > 1 && page_no <= page_limit
<add> while response_size > 1 && page_no <= MAX_PAGE_LIMIT
<ide> page_no += 1
<del> ohai "Paginating repology api page: #{page_no}" if Homebrew.args.verbose?
<add> ohai "Paginating Repology api page: #{page_no}" if Homebrew.args.verbose?
<ide>
<del> last_package_in_response = outdated_packages.keys[last_pacakge_index]
<del> response = query_api("#{last_package_in_response}/")
<add> last_package_in_response = outdated_packages.keys[last_package_index]
<add> response = query_api(last_package_in_response)
<ide>
<ide> response_size = response.size
<ide> outdated_packages.merge!(response)
<del> last_pacakge_index = outdated_packages.size - 1
<add> last_package_index = outdated_packages.size - 1
<ide> end
<ide>
<ide> ohai "#{outdated_packages.size} outdated packages identified"
<ide> def parse_api_response()
<ide> end
<ide>
<ide> def validate__packages(outdated_repology_packages)
<del> ohai "Verifying outdated repology packages as Homebrew Formulae"
<add> ohai "Verifying outdated Repology packages as Homebrew Formulae"
<ide>
<ide> packages = {}
<ide> outdated_repology_packages.each do |_name, repositories|
<ide> def validate__packages(outdated_repology_packages)
<ide> end
<ide>
<ide> next if repology_homebrew_repo.empty?
<add>
<ide> latest_version = nil
<ide>
<ide> # identify latest version amongst repology repos
<ide> def validate__packages(outdated_repology_packages)
<ide>
<ide> info = FormulaInfo.lookup(repology_homebrew_repo["srcname"])
<ide> next unless info
<add>
<ide> current_version = info.pkg_version
<del>
<add>
<ide> packages[repology_homebrew_repo["srcname"]] = {
<ide> "repology_latest_version" => latest_version,
<del> "current_formula_version" => current_version.to_s
<add> "current_formula_version" => current_version.to_s,
<ide> }
<del> puts packages
<add> puts packages
<ide> end
<ide> # hash of hashes {"aacgain"=>{"repology_latest_version"=>"1.9", "current_formula_version"=>"1.8"}, ...}
<ide> packages
<ide><path>Library/Homebrew/utils/versions.rb
<ide> def current_formula_version(formula_name)
<ide> end
<ide>
<ide> def bump_formula_pr(formula_name, url)
<del> command_args = [
<del> "brew",
<del> "bump-formula-pr",
<del> "--no-browse",
<del> "--dry-run",
<del> formula_name,
<del> "--url=#{url}",
<del> ]
<add> command_args = ["brew", "bump-formula-pr", "--no-browse",
<add> "--dry-run", formula_name, "--url=#{url}"]
<ide>
<ide> response = Open3.capture2e(*command_args)
<ide> parse_formula_bump_response(response) | 3 |
Python | Python | change github url to website | 6afba8c6ba9a2d746825a690470fd531606fc2f1 | <ide><path>setup.py
<ide> def run_setup(exts):
<ide> author='Matthew Honnibal',
<ide> author_email='honnibal@gmail.com',
<ide> version=VERSION,
<del> url="http://honnibal.github.io/spaCy/",
<add> url="https://spacy.io",
<ide> package_data=PACKAGE_DATA,
<ide> ext_modules=exts,
<ide> license="MIT", | 1 |
Python | Python | fix loss loss logging for multi-gpu compatibility | 4faeb38b51055d329f4cc5839cd1fefbe27f9d8f | <ide><path>run_classifier_pytorch.py
<ide> def main():
<ide> label_ids = label_ids.to(device)
<ide>
<ide> loss, _ = model(input_ids, segment_ids, input_mask, label_ids)
<del> total_tr_loss += loss.item()
<add> total_tr_loss += loss.sum().item() # sum() is to account for multi-gpu support.
<ide> nb_tr_examples += input_ids.size(0)
<ide> model.zero_grad()
<del> loss.backward()
<add> loss.sum().backward() # sum() is to account for multi-gpu support.
<ide> optimizer.step()
<ide> global_step += 1
<ide>
<ide> def main():
<ide> label_ids = label_ids.to('cpu').numpy()
<ide> tmp_eval_accuracy = accuracy(logits, label_ids)
<ide>
<del> eval_loss += tmp_eval_loss.item()
<add> eval_loss += tmp_eval_loss.sum().item()
<ide> eval_accuracy += tmp_eval_accuracy
<ide>
<ide> nb_eval_examples += input_ids.size(0) | 1 |
Python | Python | update platforms.py "superuser privileges" check | 8a4056087aeac6a5be79a2db4d6f06975f754609 | <ide><path>celery/bin/worker.py
<ide> from celery.bin.base import (COMMA_SEPARATED_LIST, LOG_LEVEL,
<ide> CeleryDaemonCommand, CeleryOption,
<ide> handle_preload_options)
<add>from celery.exceptions import SecurityError
<ide> from celery.platforms import (EX_FAILURE, EX_OK, detached,
<ide> maybe_drop_privileges)
<ide> from celery.utils.log import get_logger
<ide> def worker(ctx, hostname=None, pool_cls=None, app=None, uid=None, gid=None,
<ide> $ celery worker --autoscale=10,0
<ide>
<ide> """
<del> app = ctx.obj.app
<del> if ctx.args:
<del> try:
<del> app.config_from_cmdline(ctx.args, namespace='worker')
<del> except (KeyError, ValueError) as e:
<del> # TODO: Improve the error messages
<del> raise click.UsageError(
<del> "Unable to parse extra configuration from command line.\n"
<del> f"Reason: {e}", ctx=ctx)
<del> if kwargs.get('detach', False):
<del> argv = ['-m', 'celery'] + sys.argv[1:]
<del> if '--detach' in argv:
<del> argv.remove('--detach')
<del> if '-D' in argv:
<del> argv.remove('-D')
<del>
<del> return detach(sys.executable,
<del> argv,
<del> logfile=logfile,
<del> pidfile=pidfile,
<del> uid=uid, gid=gid,
<del> umask=kwargs.get('umask', None),
<del> workdir=kwargs.get('workdir', None),
<del> app=app,
<del> executable=kwargs.get('executable', None),
<del> hostname=hostname)
<del>
<del> maybe_drop_privileges(uid=uid, gid=gid)
<del> worker = app.Worker(
<del> hostname=hostname, pool_cls=pool_cls, loglevel=loglevel,
<del> logfile=logfile, # node format handled by celery.app.log.setup
<del> pidfile=node_format(pidfile, hostname),
<del> statedb=node_format(statedb, hostname),
<del> no_color=ctx.obj.no_color,
<del> **kwargs)
<del> worker.start()
<del> return worker.exitcode
<add> try:
<add> app = ctx.obj.app
<add> if ctx.args:
<add> try:
<add> app.config_from_cmdline(ctx.args, namespace='worker')
<add> except (KeyError, ValueError) as e:
<add> # TODO: Improve the error messages
<add> raise click.UsageError(
<add> "Unable to parse extra configuration from command line.\n"
<add> f"Reason: {e}", ctx=ctx)
<add> if kwargs.get('detach', False):
<add> argv = ['-m', 'celery'] + sys.argv[1:]
<add> if '--detach' in argv:
<add> argv.remove('--detach')
<add> if '-D' in argv:
<add> argv.remove('-D')
<add>
<add> return detach(sys.executable,
<add> argv,
<add> logfile=logfile,
<add> pidfile=pidfile,
<add> uid=uid, gid=gid,
<add> umask=kwargs.get('umask', None),
<add> workdir=kwargs.get('workdir', None),
<add> app=app,
<add> executable=kwargs.get('executable', None),
<add> hostname=hostname)
<add>
<add> maybe_drop_privileges(uid=uid, gid=gid)
<add> worker = app.Worker(
<add> hostname=hostname, pool_cls=pool_cls, loglevel=loglevel,
<add> logfile=logfile, # node format handled by celery.app.log.setup
<add> pidfile=node_format(pidfile, hostname),
<add> statedb=node_format(statedb, hostname),
<add> no_color=ctx.obj.no_color,
<add> **kwargs)
<add> worker.start()
<add> return worker.exitcode
<add> except SecurityError as e:
<add> ctx.obj.error(e.args[0])
<add> ctx.exit(1)
<ide><path>celery/exceptions.py
<ide> - :class:`~celery.exceptions.DuplicateNodenameWarning`
<ide> - :class:`~celery.exceptions.FixupWarning`
<ide> - :class:`~celery.exceptions.NotConfigured`
<add> - :class:`~celery.exceptions.SecurityWarning`
<ide> - :exc:`BaseException`
<ide> - :exc:`SystemExit`
<ide> - :exc:`~celery.exceptions.WorkerTerminate`
<ide> # Warnings
<ide> 'CeleryWarning',
<ide> 'AlwaysEagerIgnored', 'DuplicateNodenameWarning',
<del> 'FixupWarning', 'NotConfigured',
<add> 'FixupWarning', 'NotConfigured', 'SecurityWarning',
<ide>
<ide> # Core errors
<ide> 'CeleryError',
<ide> class NotConfigured(CeleryWarning):
<ide> """Celery hasn't been configured, as no config module has been found."""
<ide>
<ide>
<add>class SecurityWarning(CeleryWarning):
<add> """Potential security issue found."""
<add> pass
<add>
<add>
<ide> class CeleryError(Exception):
<ide> """Base class for all Celery errors."""
<ide>
<ide><path>celery/platforms.py
<ide>
<ide> import atexit
<ide> import errno
<add>import grp
<ide> import math
<ide> import numbers
<ide> import os
<ide> from kombu.utils.compat import maybe_fileno
<ide> from kombu.utils.encoding import safe_str
<ide>
<del>from .exceptions import SecurityError, reraise
<add>from .exceptions import SecurityError, SecurityWarning, reraise
<ide> from .local import try_import
<ide>
<ide> try:
<ide>
<ide> _range = namedtuple('_range', ('start', 'stop'))
<ide>
<del>C_FORCE_ROOT = os.environ.get('C_FORCE_ROOT', False)
<del>
<ide> ROOT_DISALLOWED = """\
<ide> Running a worker with superuser privileges when the
<ide> worker accepts messages serialized with pickle is a very bad idea!
<ide> User information: uid={uid} euid={euid} gid={gid} egid={egid}
<ide> """
<ide>
<add>ASSUMING_ROOT = """\
<add>An entry for the specified gid or egid was not found.
<add>We're assuming this is a potential security issue.
<add>"""
<add>
<ide> SIGNAMES = {
<ide> sig for sig in dir(_signal)
<ide> if sig.startswith('SIG') and '_' not in sig
<ide> def acquire(self):
<ide> except OSError as exc:
<ide> reraise(LockFailed, LockFailed(str(exc)), sys.exc_info()[2])
<ide> return self
<add>
<ide> __enter__ = acquire
<ide>
<ide> def is_locked(self):
<ide> def is_locked(self):
<ide> def release(self, *args):
<ide> """Release lock."""
<ide> self.remove()
<add>
<ide> __exit__ = release
<ide>
<ide> def read_pid(self):
<ide> def open(self):
<ide> mputil._run_after_forkers()
<ide>
<ide> self._is_open = True
<add>
<ide> __enter__ = open
<ide>
<ide> def close(self, *args):
<ide> if self._is_open:
<ide> self._is_open = False
<add>
<ide> __exit__ = close
<ide>
<ide> def _detach(self):
<del> if os.fork() == 0: # first child
<del> os.setsid() # create new session
<del> if os.fork() > 0: # pragma: no cover
<add> if os.fork() == 0: # first child
<add> os.setsid() # create new session
<add> if os.fork() > 0: # pragma: no cover
<ide> # second child
<ide> os._exit(0)
<ide> else:
<ide> def _setgroups_hack(groups):
<ide> while 1:
<ide> try:
<ide> return os.setgroups(groups)
<del> except ValueError: # error from Python's check.
<add> except ValueError: # error from Python's check.
<ide> if len(groups) <= 1:
<ide> raise
<ide> groups[:] = groups[:-1]
<ide> def arm_alarm(self, seconds): # noqa
<ide> _signal.alarm(math.ceil(seconds))
<ide> else: # pragma: no cover
<ide>
<del> def arm_alarm(self, seconds): # noqa
<add> def arm_alarm(self, seconds): # noqa
<ide> return _itimer_alarm(seconds) # noqa
<ide>
<ide> def reset_alarm(self):
<ide> def update(self, _d_=None, **sigmap):
<ide>
<ide>
<ide> signals = Signals()
<del>get_signal = signals.signum # compat
<add>get_signal = signals.signum # compat
<ide> install_signal_handler = signals.__setitem__ # compat
<del>reset_signal = signals.reset # compat
<del>ignore_signal = signals.ignore # compat
<add>reset_signal = signals.reset # compat
<add>ignore_signal = signals.ignore # compat
<ide>
<ide>
<ide> def signal_name(signum):
<ide> def ignore_errno(*errnos, **kwargs):
<ide>
<ide>
<ide> def check_privileges(accept_content):
<add> pickle_or_serialize = ('pickle' in accept_content
<add> or 'application/group-python-serialize' in accept_content)
<add>
<ide> uid = os.getuid() if hasattr(os, 'getuid') else 65535
<ide> gid = os.getgid() if hasattr(os, 'getgid') else 65535
<ide> euid = os.geteuid() if hasattr(os, 'geteuid') else 65535
<ide> egid = os.getegid() if hasattr(os, 'getegid') else 65535
<ide>
<ide> if hasattr(os, 'fchown'):
<ide> if not all(hasattr(os, attr)
<del> for attr in ['getuid', 'getgid', 'geteuid', 'getegid']):
<add> for attr in ('getuid', 'getgid', 'geteuid', 'getegid')):
<ide> raise SecurityError('suspicious platform, contact support')
<ide>
<del> if not uid or not gid or not euid or not egid:
<del> if ('pickle' in accept_content or
<del> 'application/x-python-serialize' in accept_content):
<del> if not C_FORCE_ROOT:
<del> try:
<del> print(ROOT_DISALLOWED.format(
<del> uid=uid, euid=euid, gid=gid, egid=egid,
<del> ), file=sys.stderr)
<del> finally:
<del> sys.stderr.flush()
<del> os._exit(1)
<del> warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format(
<add> # Get the group database entry for the current user's group and effective
<add> # group id using grp.getgrgid() method
<add> # We must handle the case where either the gid or the egid are not found.
<add> try:
<add> gid_entry = grp.getgrgid(gid)
<add> egid_entry = grp.getgrgid(egid)
<add> except KeyError:
<add> warnings.warn(SecurityWarning(ASSUMING_ROOT))
<add> _warn_or_raise_security_error(egid, euid, gid, uid,
<add> pickle_or_serialize)
<add> return
<add>
<add> # Get the group and effective group name based on gid
<add> gid_grp_name = gid_entry[0]
<add> egid_grp_name = egid_entry[0]
<add>
<add> # Create lists to use in validation step later.
<add> gids_in_use = (gid_grp_name, egid_grp_name)
<add> groups_with_security_risk = ('sudo', 'wheel')
<add>
<add> is_root = uid == 0 or euid == 0
<add> # Confirm that the gid and egid are not one that
<add> # can be used to escalate privileges.
<add> if is_root or any(group in gids_in_use
<add> for group in groups_with_security_risk):
<add> _warn_or_raise_security_error(egid, euid, gid, uid,
<add> pickle_or_serialize)
<add>
<add>
<add>def _warn_or_raise_security_error(egid, euid, gid, uid, pickle_or_serialize):
<add> c_force_root = os.environ.get('C_FORCE_ROOT', False)
<add>
<add> if pickle_or_serialize and not c_force_root:
<add> raise SecurityError(ROOT_DISALLOWED.format(
<ide> uid=uid, euid=euid, gid=gid, egid=egid,
<del> )))
<add> ))
<add>
<add> warnings.warn(SecurityWarning(ROOT_DISCOURAGED.format(
<add> uid=uid, euid=euid, gid=gid, egid=egid,
<add> )))
<ide><path>t/unit/utils/test_platforms.py
<ide> import errno
<ide> import os
<add>import re
<ide> import signal
<ide> import sys
<ide> import tempfile
<ide>
<ide> import t.skip
<ide> from celery import _find_option_with_arg, platforms
<del>from celery.exceptions import SecurityError
<del>from celery.platforms import (DaemonContext, LockFailed, Pidfile,
<del> _setgroups_hack, check_privileges,
<add>from celery.exceptions import SecurityError, SecurityWarning
<add>from celery.platforms import (ASSUMING_ROOT, ROOT_DISALLOWED,
<add> ROOT_DISCOURAGED, DaemonContext, LockFailed,
<add> Pidfile, _setgroups_hack, check_privileges,
<ide> close_open_fds, create_pidlock, detached,
<ide> fd_by_path, get_fdmax, ignore_errno, initgroups,
<ide> isatty, maybe_drop_privileges, parse_gid,
<ide> def test_reset(self, set):
<ide> def test_setitem(self, set):
<ide> def handle(*args):
<ide> return args
<add>
<ide> signals['INT'] = handle
<ide> set.assert_called_with(signal.SIGINT, handle)
<ide>
<ide> class pw_struct:
<ide> def raise_on_second_call(*args, **kwargs):
<ide> setuid.side_effect = OSError()
<ide> setuid.side_effect.errno = errno.EPERM
<add>
<ide> setuid.side_effect = raise_on_second_call
<ide> getpwuid.return_value = pw_struct()
<ide> parse_uid.return_value = 5001
<ide> def to_root_on_second_call(mock, first):
<ide> def on_first_call(*args, **kwargs):
<ide> ret, return_value[0] = return_value[0], 0
<ide> return ret
<add>
<ide> mock.side_effect = on_first_call
<add>
<ide> to_root_on_second_call(geteuid, 10)
<ide> to_root_on_second_call(getuid, 10)
<ide> with pytest.raises(SecurityError):
<ide> def on_first_call(*args, **kwargs):
<ide> def raise_on_second_call(*args, **kwargs):
<ide> setuid.side_effect = OSError()
<ide> setuid.side_effect.errno = errno.ENOENT
<add>
<ide> setuid.side_effect = raise_on_second_call
<ide> with pytest.raises(OSError):
<ide> maybe_drop_privileges(uid='user')
<ide> def test_with_guid(self, initgroups, setuid, setgid,
<ide> def raise_on_second_call(*args, **kwargs):
<ide> setuid.side_effect = OSError()
<ide> setuid.side_effect.errno = errno.EPERM
<add>
<ide> setuid.side_effect = raise_on_second_call
<ide> parse_uid.return_value = 5001
<ide> parse_gid.return_value = 50001
<ide> def test_parse_uid_when_int(self):
<ide>
<ide> @patch('pwd.getpwnam')
<ide> def test_parse_uid_when_existing_name(self, getpwnam):
<del>
<ide> class pwent:
<ide> pw_uid = 5001
<ide>
<ide> def test_parse_gid_when_int(self):
<ide>
<ide> @patch('grp.getgrnam')
<ide> def test_parse_gid_when_existing_name(self, getgrnam):
<del>
<ide> class grent:
<ide> gr_gid = 50001
<ide>
<ide> def on_setgroups(groups):
<ide> setgroups.return_value = True
<ide> return
<ide> raise ValueError()
<add>
<ide> setgroups.side_effect = on_setgroups
<ide> _setgroups_hack(list(range(400)))
<ide>
<ide> def on_setgroups(groups):
<ide> setgroups.return_value = True
<ide> return
<ide> raise exc
<add>
<ide> setgroups.side_effect = on_setgroups
<ide>
<ide> _setgroups_hack(list(range(400)))
<ide> def test_setgroups_raises_EPERM(self, hack, getgroups):
<ide> getgroups.assert_called_with()
<ide>
<ide>
<del>def test_check_privileges():
<del> class Obj:
<del> fchown = 13
<del> prev, platforms.os = platforms.os, Obj()
<del> try:
<del> with pytest.raises(SecurityError):
<del> check_privileges({'pickle'})
<del> finally:
<del> platforms.os = prev
<del> prev, platforms.os = platforms.os, object()
<del> try:
<del> check_privileges({'pickle'})
<del> finally:
<del> platforms.os = prev
<add>@pytest.mark.parametrize('accept_content', [
<add> {'pickle'},
<add> {'application/group-python-serialize'},
<add> {'pickle', 'application/group-python-serialize'}
<add>])
<add>def test_check_privileges_suspicious_platform(accept_content):
<add> with patch('celery.platforms.os') as os_module:
<add> del os_module.getuid
<add> del os_module.getgid
<add> del os_module.geteuid
<add> del os_module.getegid
<add>
<add> with pytest.raises(SecurityError,
<add> match=r'suspicious platform, contact support'):
<add> check_privileges(accept_content)
<add>
<add>
<add>@pytest.mark.parametrize('accept_content', [
<add> {'pickle'},
<add> {'application/group-python-serialize'},
<add> {'pickle', 'application/group-python-serialize'}
<add>])
<add>def test_check_privileges(accept_content, recwarn):
<add> check_privileges(accept_content)
<add>
<add> assert len(recwarn) == 0
<add>
<add>
<add>@pytest.mark.parametrize('accept_content', [
<add> {'pickle'},
<add> {'application/group-python-serialize'},
<add> {'pickle', 'application/group-python-serialize'}
<add>])
<add>def test_check_privileges_no_fchown(accept_content, recwarn):
<add> with patch('celery.platforms.os') as os_module:
<add> del os_module.fchown
<add> check_privileges(accept_content)
<add>
<add> assert len(recwarn) == 0
<add>
<add>
<add>@pytest.mark.parametrize('accept_content', [
<add> {'pickle'},
<add> {'application/group-python-serialize'},
<add> {'pickle', 'application/group-python-serialize'}
<add>])
<add>def test_check_privileges_without_c_force_root(accept_content):
<add> with patch('celery.platforms.os') as os_module:
<add> os_module.environ = {}
<add> os_module.getuid.return_value = 0
<add> os_module.getgid.return_value = 0
<add> os_module.geteuid.return_value = 0
<add> os_module.getegid.return_value = 0
<add>
<add> expected_message = re.escape(ROOT_DISALLOWED.format(uid=0, euid=0,
<add> gid=0, egid=0))
<add> with pytest.raises(SecurityError,
<add> match=expected_message):
<add> check_privileges(accept_content)
<add>
<add>
<add>@pytest.mark.parametrize('accept_content', [
<add> {'pickle'},
<add> {'application/group-python-serialize'},
<add> {'pickle', 'application/group-python-serialize'}
<add>])
<add>def test_check_privileges_with_c_force_root(accept_content):
<add> with patch('celery.platforms.os') as os_module:
<add> os_module.environ = {'C_FORCE_ROOT': 'true'}
<add> os_module.getuid.return_value = 0
<add> os_module.getgid.return_value = 0
<add> os_module.geteuid.return_value = 0
<add> os_module.getegid.return_value = 0
<add>
<add> with pytest.warns(SecurityWarning):
<add> check_privileges(accept_content)
<add>
<add>
<add>@pytest.mark.parametrize(('accept_content', 'group_name'), [
<add> ({'pickle'}, 'sudo'),
<add> ({'application/group-python-serialize'}, 'sudo'),
<add> ({'pickle', 'application/group-python-serialize'}, 'sudo'),
<add> ({'pickle'}, 'wheel'),
<add> ({'application/group-python-serialize'}, 'wheel'),
<add> ({'pickle', 'application/group-python-serialize'}, 'wheel'),
<add>])
<add>def test_check_privileges_with_c_force_root_and_with_suspicious_group(accept_content, group_name):
<add> with patch('celery.platforms.os') as os_module, patch('celery.platforms.grp') as grp_module:
<add> os_module.environ = {'C_FORCE_ROOT': 'true'}
<add> os_module.getuid.return_value = 60
<add> os_module.getgid.return_value = 60
<add> os_module.geteuid.return_value = 60
<add> os_module.getegid.return_value = 60
<add>
<add> grp_module.getgrgid.return_value = [group_name]
<add> grp_module.getgrgid.return_value = [group_name]
<add>
<add> expected_message = re.escape(ROOT_DISCOURAGED.format(uid=60, euid=60,
<add> gid=60, egid=60))
<add> with pytest.warns(SecurityWarning, match=expected_message):
<add> check_privileges(accept_content)
<add>
<add>
<add>@pytest.mark.parametrize(('accept_content', 'group_name'), [
<add> ({'pickle'}, 'sudo'),
<add> ({'application/group-python-serialize'}, 'sudo'),
<add> ({'pickle', 'application/group-python-serialize'}, 'sudo'),
<add> ({'pickle'}, 'wheel'),
<add> ({'application/group-python-serialize'}, 'wheel'),
<add> ({'pickle', 'application/group-python-serialize'}, 'wheel'),
<add>])
<add>def test_check_privileges_without_c_force_root_and_with_suspicious_group(accept_content, group_name):
<add> with patch('celery.platforms.os') as os_module, patch('celery.platforms.grp') as grp_module:
<add> os_module.environ = {}
<add> os_module.getuid.return_value = 60
<add> os_module.getgid.return_value = 60
<add> os_module.geteuid.return_value = 60
<add> os_module.getegid.return_value = 60
<add>
<add> grp_module.getgrgid.return_value = [group_name]
<add> grp_module.getgrgid.return_value = [group_name]
<add>
<add> expected_message = re.escape(ROOT_DISALLOWED.format(uid=60, euid=60,
<add> gid=60, egid=60))
<add> with pytest.raises(SecurityError,
<add> match=expected_message):
<add> check_privileges(accept_content)
<add>
<add>
<add>@pytest.mark.parametrize('accept_content', [
<add> {'pickle'},
<add> {'application/group-python-serialize'},
<add> {'pickle', 'application/group-python-serialize'}
<add>])
<add>def test_check_privileges_with_c_force_root_and_no_group_entry(accept_content, recwarn):
<add> with patch('celery.platforms.os') as os_module, patch('celery.platforms.grp') as grp_module:
<add> os_module.environ = {'C_FORCE_ROOT': 'true'}
<add> os_module.getuid.return_value = 60
<add> os_module.getgid.return_value = 60
<add> os_module.geteuid.return_value = 60
<add> os_module.getegid.return_value = 60
<add>
<add> grp_module.getgrgid.side_effect = KeyError
<add>
<add> expected_message = ROOT_DISCOURAGED.format(uid=60, euid=60,
<add> gid=60, egid=60)
<add>
<add> check_privileges(accept_content)
<add> assert len(recwarn) == 2
<add>
<add> assert recwarn[0].message.args[0] == ASSUMING_ROOT
<add> assert recwarn[1].message.args[0] == expected_message
<add>
<add>
<add>@pytest.mark.parametrize('accept_content', [
<add> {'pickle'},
<add> {'application/group-python-serialize'},
<add> {'pickle', 'application/group-python-serialize'}
<add>])
<add>def test_check_privileges_with_c_force_root_and_no_group_entry(accept_content, recwarn):
<add> with patch('celery.platforms.os') as os_module, patch('celery.platforms.grp') as grp_module:
<add> os_module.environ = {}
<add> os_module.getuid.return_value = 60
<add> os_module.getgid.return_value = 60
<add> os_module.geteuid.return_value = 60
<add> os_module.getegid.return_value = 60
<add>
<add> grp_module.getgrgid.side_effect = KeyError
<add>
<add> expected_message = re.escape(ROOT_DISALLOWED.format(uid=60, euid=60,
<add> gid=60, egid=60))
<add> with pytest.raises(SecurityError,
<add> match=expected_message):
<add> check_privileges(accept_content)
<add>
<add> assert recwarn[0].message.args[0] == ASSUMING_ROOT | 4 |
Javascript | Javascript | use strict mode and fix violators | 92fa629d107cf4de1cb486366d783e890e153306 | <ide><path>fonts.js
<ide> /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
<ide> /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
<ide>
<add>"use strict";
<add>
<ide> /**
<ide> * Maximum file size of the font.
<ide> */
<ide> var Type1Parser = function() {
<ide> this.extractFontProgram = function t1_extractFontProgram(aStream) {
<ide> var eexecString = decrypt(aStream, kEexecEncryptionKey, 4);
<ide> var subrs = [], glyphs = [];
<del> var inSubrs = inGlyphs = false;
<add> var inGlyphs = false;
<add> var inSubrs = false;
<ide> var glyph = "";
<ide>
<ide> var token = "";
<ide><path>glyphlist.js
<add>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
<add>/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
<add>
<add>"use strict";
<add>
<ide> var GlyphsUnicode = {
<ide> A: 0x0041,
<ide> AE: 0x00C6,
<ide><path>multi-page-viewer.js
<ide> /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- /
<ide> /* vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */
<ide>
<add>"use strict";
<add>
<ide> var PDFViewer = {
<ide> queryParams: {},
<ide>
<ide><path>pdf.js
<ide> /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- /
<ide> /* vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */
<ide>
<add>"use strict";
<add>
<ide> var ERRORS = 0, WARNINGS = 1, TODOS = 5;
<ide> var verbosity = WARNINGS;
<ide>
<ide> var FlateStream = (function() {
<ide> return [codes, maxLen];
<ide> },
<ide> readBlock: function() {
<add> function repeat(stream, array, len, offset, what) {
<add> var repeat = stream.getBits(len) + offset;
<add> while (repeat-- > 0)
<add> array[i++] = what;
<add> }
<add>
<ide> var stream = this.stream;
<ide>
<ide> // read block header
<ide> var FlateStream = (function() {
<ide> var codes = numLitCodes + numDistCodes;
<ide> var codeLengths = new Array(codes);
<ide> while (i < codes) {
<del> function repeat(stream, array, len, offset, what) {
<del> var repeat = stream.getBits(len) + offset;
<del> while (repeat-- > 0)
<del> array[i++] = what;
<del> }
<ide> var code = this.getCode(codeLenCodeTab);
<ide> if (code == 16) {
<ide> repeat(this, codeLengths, 2, 3, len);
<ide> var Lexer = (function() {
<ide> var done = false;
<ide> var str = "";
<ide> var stream = this.stream;
<add> var ch;
<ide> do {
<ide> switch (ch = stream.getChar()) {
<ide> case undefined:
<ide> var Catalog = (function() {
<ide> return shadow(this, "toplevelPagesDict", obj);
<ide> },
<ide> get numPages() {
<del> obj = this.toplevelPagesDict.get("Count");
<add> var obj = this.toplevelPagesDict.get("Count");
<ide> assertWellFormed(IsInt(obj),
<ide> "page count in top level pages object is not an integer");
<ide> // shadow the prototype getter
<ide> var CanvasGraphics = (function() {
<ide> error("No support for array of functions");
<ide> else if (!IsPDFFunction(fnObj))
<ide> error("Invalid function");
<del> fn = new PDFFunction(this.xref, fnObj);
<add> var fn = new PDFFunction(this.xref, fnObj);
<ide>
<ide> var gradient = this.ctx.createLinearGradient(x0, y0, x1, y1);
<ide> var step = (t1 - t0) / 10;
<ide><path>viewer.js
<ide> /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- /
<ide> /* vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */
<ide>
<del>var pdfDocument, canvas, pageDisplay, pageNum, pageInterval;
<add>"use strict";
<add>
<add>var pdfDocument, canvas, numPages, pageDisplay, pageNum, pageInterval;
<ide> function load(userInput) {
<ide> canvas = document.getElementById("canvas");
<ide> canvas.mozOpaque = true;
<ide> pageNum = parseInt(queryParams().page) || 1;
<del> fileName = userInput;
<add> var fileName = userInput;
<ide> if (!userInput) {
<ide> fileName = queryParams().file || "compressed.tracemonkey-pldi-09.pdf";
<ide> }
<ide> function queryParams() {
<ide>
<ide> function open(url) {
<ide> document.title = url;
<del> req = new XMLHttpRequest();
<add> var req = new XMLHttpRequest();
<ide> req.open("GET", url);
<ide> req.mozResponseType = req.responseType = "arraybuffer";
<ide> req.expected = (document.URL.indexOf("file:") == 0) ? 0 : 200; | 5 |
Go | Go | define pushresult in api types | 13222160e84a01db2174c0dbf3000761a756fd72 | <ide><path>api/types/types.go
<ide> type SecretCreateResponse struct {
<ide> type SecretListOptions struct {
<ide> Filters filters.Args
<ide> }
<add>
<add>// PushResult contains the tag, manifest digest, and manifest size from the
<add>// push. It's used to signal this information to the trust code in the client
<add>// so it can sign the manifest if necessary.
<add>type PushResult struct {
<add> Tag string
<add> Digest string
<add> Size int
<add>}
<ide><path>cli/command/image/trust.go
<ide> import (
<ide> "path"
<ide> "sort"
<ide>
<del> "golang.org/x/net/context"
<del>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/digest"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/cli/command"
<ide> "github.com/docker/docker/cli/trust"
<del> "github.com/docker/docker/distribution"
<ide> "github.com/docker/docker/pkg/jsonmessage"
<ide> "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/notary/client"
<ide> "github.com/docker/notary/tuf/data"
<add> "golang.org/x/net/context"
<ide> )
<ide>
<ide> type target struct {
<ide> func trustedPush(ctx context.Context, cli *command.DockerCli, repoInfo *registry
<ide> return
<ide> }
<ide>
<del> var pushResult distribution.PushResult
<add> var pushResult types.PushResult
<ide> err := json.Unmarshal(*aux, &pushResult)
<del> if err == nil && pushResult.Tag != "" && pushResult.Digest.Validate() == nil {
<del> h, err := hex.DecodeString(pushResult.Digest.Hex())
<del> if err != nil {
<del> target = nil
<del> return
<add> if err == nil && pushResult.Tag != "" {
<add> if dgst, err := digest.ParseDigest(pushResult.Digest); err == nil {
<add> h, err := hex.DecodeString(dgst.Hex())
<add> if err != nil {
<add> target = nil
<add> return
<add> }
<add> target.Name = pushResult.Tag
<add> target.Hashes = data.Hashes{string(dgst.Algorithm()): h}
<add> target.Length = int64(pushResult.Size)
<ide> }
<del> target.Name = pushResult.Tag
<del> target.Hashes = data.Hashes{string(pushResult.Digest.Algorithm()): h}
<del> target.Length = int64(pushResult.Size)
<ide> }
<ide> }
<ide>
<ide><path>distribution/push_v2.go
<ide> import (
<ide> "github.com/docker/distribution/manifest/schema2"
<ide> distreference "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/client"
<add> apitypes "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/distribution/xfer"
<ide> "github.com/docker/docker/layer"
<ide> const (
<ide> middleLayerMaximumSize = 10 * (1 << 20) // 10MB
<ide> )
<ide>
<del>// PushResult contains the tag, manifest digest, and manifest size from the
<del>// push. It's used to signal this information to the trust code in the client
<del>// so it can sign the manifest if necessary.
<del>type PushResult struct {
<del> Tag string
<del> Digest digest.Digest
<del> Size int
<del>}
<del>
<ide> type v2Pusher struct {
<ide> v2MetadataService metadata.V2MetadataService
<ide> ref reference.Named
<ide> func (p *v2Pusher) pushV2Tag(ctx context.Context, ref reference.NamedTagged, id
<ide>
<ide> // Signal digest to the trust client so it can sign the
<ide> // push, if appropriate.
<del> progress.Aux(p.config.ProgressOutput, PushResult{Tag: ref.Tag(), Digest: manifestDigest, Size: len(canonicalManifest)})
<add> progress.Aux(p.config.ProgressOutput, apitypes.PushResult{Tag: ref.Tag(), Digest: manifestDigest.String(), Size: len(canonicalManifest)})
<ide>
<ide> return nil
<ide> } | 3 |
Text | Text | replace process.stdout.fd with 1 | 91d1b60d36b2aa07c996c2418938a29115b99d92 | <ide><path>doc/api/async_hooks.md
<ide> created, while `triggerAsyncId` shows *why* a resource was created.
<ide> The following is a simple demonstration of `triggerAsyncId`:
<ide>
<ide> ```js
<add>const { fd } = process.stdout;
<add>
<ide> async_hooks.createHook({
<ide> init(asyncId, type, triggerAsyncId) {
<ide> const eid = async_hooks.executionAsyncId();
<ide> fs.writeSync(
<del> process.stdout.fd,
<add> fd,
<ide> `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
<ide> }
<ide> }).enable();
<ide>
<del>require('net').createServer((conn) => {}).listen(8080);
<add>net.createServer((conn) => {}).listen(8080);
<ide> ```
<ide>
<ide> Output when hitting the server with `nc localhost 8080`:
<ide> callback to `listen()` will look like. The output formatting is slightly more
<ide> elaborate to make calling context easier to see.
<ide>
<ide> ```js
<add>const { fd } = process.stdout;
<add>
<ide> let indent = 0;
<ide> async_hooks.createHook({
<ide> init(asyncId, type, triggerAsyncId) {
<ide> const eid = async_hooks.executionAsyncId();
<ide> const indentStr = ' '.repeat(indent);
<ide> fs.writeSync(
<del> process.stdout.fd,
<add> fd,
<ide> `${indentStr}${type}(${asyncId}):` +
<ide> ` trigger: ${triggerAsyncId} execution: ${eid}\n`);
<ide> },
<ide> before(asyncId) {
<ide> const indentStr = ' '.repeat(indent);
<del> fs.writeSync(process.stdout.fd, `${indentStr}before: ${asyncId}\n`);
<add> fs.writeSync(fd, `${indentStr}before: ${asyncId}\n`);
<ide> indent += 2;
<ide> },
<ide> after(asyncId) {
<ide> indent -= 2;
<ide> const indentStr = ' '.repeat(indent);
<del> fs.writeSync(process.stdout.fd, `${indentStr}after: ${asyncId}\n`);
<add> fs.writeSync(fd, `${indentStr}after: ${asyncId}\n`);
<ide> },
<ide> destroy(asyncId) {
<ide> const indentStr = ' '.repeat(indent);
<del> fs.writeSync(process.stdout.fd, `${indentStr}destroy: ${asyncId}\n`);
<add> fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\n`);
<ide> },
<ide> }).enable();
<ide>
<del>require('net').createServer(() => {}).listen(8080, () => {
<add>net.createServer(() => {}).listen(8080, () => {
<ide> // Let's wait 10ms before logging the server started.
<ide> setTimeout(() => {
<ide> console.log('>>>', async_hooks.executionAsyncId()); | 1 |
Ruby | Ruby | handle range with excluded end | 8a32d3796778fc1f151a2259fa3b32b9d3c8d56b | <ide><path>activerecord/lib/active_record/relation/predicate_builder.rb
<ide> def build_from_hash(attributes, default_table)
<ide> attribute = arel_table[column] || Arel::Attribute.new(arel_table, column.to_sym)
<ide>
<ide> case value
<del> when Array, Range, ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope
<add> when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope
<ide> attribute.in(value)
<add> when Range
<add> # TODO : Arel should handle ranges with excluded end.
<add> if value.exclude_end?
<add> [attribute.gteq(value.begin), attribute.lt(value.end)]
<add> else
<add> attribute.in(value)
<add> end
<ide> else
<ide> attribute.eq(value)
<ide> end | 1 |
Python | Python | fix type annotations for stack.py | c0ed031b3fcf47736f98dfd89e2588dbffceadde | <ide><path>data_structures/stacks/balanced_parentheses.py
<ide> def balanced_parentheses(parentheses: str) -> bool:
<ide> >>> balanced_parentheses("")
<ide> True
<ide> """
<del> stack = Stack()
<add> stack: Stack[str] = Stack()
<ide> bracket_pairs = {"(": ")", "[": "]", "{": "}"}
<ide> for bracket in parentheses:
<ide> if bracket in bracket_pairs:
<ide><path>data_structures/stacks/dijkstras_two_stack_algorithm.py
<ide> def dijkstras_two_stack_algorithm(equation: str) -> int:
<ide> """
<ide> operators = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub}
<ide>
<del> operand_stack = Stack()
<del> operator_stack = Stack()
<add> operand_stack: Stack[int] = Stack()
<add> operator_stack: Stack[str] = Stack()
<ide>
<ide> for i in equation:
<ide> if i.isdigit():
<ide><path>data_structures/stacks/infix_to_postfix_conversion.py
<ide> def infix_to_postfix(expression_str: str) -> str:
<ide> """
<ide> if not balanced_parentheses(expression_str):
<ide> raise ValueError("Mismatched parentheses")
<del> stack = Stack()
<add> stack: Stack[str] = Stack()
<ide> postfix = []
<ide> for char in expression_str:
<ide> if char.isalpha() or char.isdigit():
<ide><path>data_structures/stacks/stack.py
<ide> from __future__ import annotations
<ide>
<add>from typing import Generic, TypeVar
<add>
<add>T = TypeVar("T")
<add>
<ide>
<ide> class StackOverflowError(BaseException):
<ide> pass
<ide> class StackUnderflowError(BaseException):
<ide> pass
<ide>
<ide>
<del>class Stack:
<add>class Stack(Generic[T]):
<ide> """A stack is an abstract data type that serves as a collection of
<ide> elements with two principal operations: push() and pop(). push() adds an
<ide> element to the top of the stack, and pop() removes an element from the top
<ide> class Stack:
<ide> """
<ide>
<ide> def __init__(self, limit: int = 10):
<del> self.stack: list[int] = []
<add> self.stack: list[T] = []
<ide> self.limit = limit
<ide>
<ide> def __bool__(self) -> bool:
<ide> def __bool__(self) -> bool:
<ide> def __str__(self) -> str:
<ide> return str(self.stack)
<ide>
<del> def push(self, data):
<add> def push(self, data: T) -> None:
<ide> """Push an element to the top of the stack."""
<ide> if len(self.stack) >= self.limit:
<ide> raise StackOverflowError
<ide> self.stack.append(data)
<ide>
<del> def pop(self):
<add> def pop(self) -> T:
<ide> """
<ide> Pop an element off of the top of the stack.
<ide>
<ide> def pop(self):
<ide> raise StackUnderflowError
<ide> return self.stack.pop()
<ide>
<del> def peek(self):
<add> def peek(self) -> T:
<ide> """
<ide> Peek at the top-most element of the stack.
<ide>
<ide> def size(self) -> int:
<ide> """Return the size of the stack."""
<ide> return len(self.stack)
<ide>
<del> def __contains__(self, item) -> bool:
<add> def __contains__(self, item: T) -> bool:
<ide> """Check if item is in stack"""
<ide> return item in self.stack
<ide>
<ide> def test_stack() -> None:
<ide> """
<ide> >>> test_stack()
<ide> """
<del> stack = Stack(10)
<add> stack: Stack[int] = Stack(10)
<ide> assert bool(stack) is False
<ide> assert stack.is_empty() is True
<ide> assert stack.is_full() is False | 4 |
Text | Text | add gitter badge | 687a07ed57e1c59d7c3c1f7805fe8e0045030bdf | <ide><path>README.md
<ide> Immutable collections for JavaScript
<ide> ====================================
<ide>
<del>[](https://travis-ci.org/facebook/immutable-js)
<add>[](https://travis-ci.org/facebook/immutable-js) [](https://gitter.im/immutable-js/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<ide>
<ide> [Immutable][] data cannot be changed once created, leading to much simpler
<ide> application development, no defensive copying, and enabling advanced memoization | 1 |
Javascript | Javascript | remove the `xmlhttprequest.response` polyfill | 4880200cd40e4194bcff8d47864fefcf6e62256b | <ide><path>src/shared/compatibility.js
<ide> if (typeof PDFJS === 'undefined') {
<ide>
<ide> PDFJS.compatibilityChecked = true;
<ide>
<del>// No XMLHttpRequest#response?
<del>// Support: IE<11, Android <4.0
<del>(function checkXMLHttpRequestResponseCompatibility() {
<del> if (typeof XMLHttpRequest === 'undefined') {
<del> return;
<del> }
<del> var xhrPrototype = XMLHttpRequest.prototype;
<del> var xhr = new XMLHttpRequest();
<del> if (!('overrideMimeType' in xhr)) {
<del> // IE10 might have response, but not overrideMimeType
<del> // Support: IE10
<del> Object.defineProperty(xhrPrototype, 'overrideMimeType', {
<del> value: function xmlHttpRequestOverrideMimeType(mimeType) {},
<del> });
<del> }
<del> if ('responseType' in xhr) {
<del> return;
<del> }
<del>
<del> Object.defineProperty(xhrPrototype, 'responseType', {
<del> get: function xmlHttpRequestGetResponseType() {
<del> return this._responseType || 'text';
<del> },
<del> set: function xmlHttpRequestSetResponseType(value) {
<del> if (value === 'text' || value === 'arraybuffer') {
<del> this._responseType = value;
<del> if (value === 'arraybuffer' &&
<del> typeof this.overrideMimeType === 'function') {
<del> this.overrideMimeType('text/plain; charset=x-user-defined');
<del> }
<del> }
<del> },
<del> });
<del>
<del> Object.defineProperty(xhrPrototype, 'response', {
<del> get: function xmlHttpRequestResponseGet() {
<del> if (this.responseType !== 'arraybuffer') {
<del> return this.responseText;
<del> }
<del> var text = this.responseText;
<del> var i, n = text.length;
<del> var result = new Uint8Array(n);
<del> for (i = 0; i < n; ++i) {
<del> result[i] = text.charCodeAt(i) & 0xFF;
<del> }
<del> return result.buffer;
<del> },
<del> });
<del>})();
<del>
<ide> // HTMLElement dataset property
<ide> // Support: IE<11, Safari<5.1, Android<4.0
<ide> (function checkDatasetProperty() { | 1 |
Ruby | Ruby | simplify unbrewed file whitelists | 892d7dc130a6cf88600b71a388f32b9f27874e5c | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def __check_stray_files(dir, pattern, white_list, message)
<ide> Dir[pattern].select { |f| File.file?(f) && !File.symlink?(f) }
<ide> }
<ide>
<del> keys = white_list.keys
<ide> bad = files.reject { |file|
<del> keys.any? { |pat| File.fnmatch?(pat, file) }
<add> white_list.any? { |pat| File.fnmatch?(pat, file) }
<ide> }
<ide>
<ide> bad.map! { |file| File.join(dir, file) }
<ide> def __check_stray_files(dir, pattern, white_list, message)
<ide> def check_for_stray_dylibs
<ide> # Dylibs which are generally OK should be added to this list,
<ide> # with a short description of the software they come with.
<del> white_list = {
<del> "libfuse.2.dylib" => "MacFuse",
<del> "libfuse_ino64.2.dylib" => "MacFuse",
<del> "libosxfuse_i32.2.dylib" => "OSXFuse",
<del> "libosxfuse_i64.2.dylib" => "OSXFuse",
<del> }
<add> white_list = [
<add> "libfuse.2.dylib", # MacFuse
<add> "libfuse_ino64.2.dylib", # MacFuse
<add> "libosxfuse_i32.2.dylib", # OSXFuse
<add> "libosxfuse_i64.2.dylib", # OSXFuse
<add> ]
<ide>
<ide> __check_stray_files "/usr/local/lib", "*.dylib", white_list, <<-EOS.undent
<ide> Unbrewed dylibs were found in /usr/local/lib.
<ide> def check_for_stray_dylibs
<ide> def check_for_stray_static_libs
<ide> # Static libs which are generally OK should be added to this list,
<ide> # with a short description of the software they come with.
<del> white_list = {
<del> "libsecurity_agent_client.a" => "OS X 10.8.2 Supplemental Update",
<del> "libsecurity_agent_server.a" => "OS X 10.8.2 Supplemental Update"
<del> }
<add> white_list = [
<add> "libsecurity_agent_client.a", # OS X 10.8.2 Supplemental Update
<add> "libsecurity_agent_server.a", # OS X 10.8.2 Supplemental Update
<add> ]
<ide>
<ide> __check_stray_files "/usr/local/lib", "*.a", white_list, <<-EOS.undent
<ide> Unbrewed static libraries were found in /usr/local/lib.
<ide> def check_for_stray_static_libs
<ide> def check_for_stray_pcs
<ide> # Package-config files which are generally OK should be added to this list,
<ide> # with a short description of the software they come with.
<del> white_list = {
<del> "osxfuse.pc" => "OSXFuse",
<del> }
<add> white_list = [
<add> "osxfuse.pc", # OSXFuse
<add> ]
<ide>
<ide> __check_stray_files "/usr/local/lib/pkgconfig", "*.pc", white_list, <<-EOS.undent
<ide> Unbrewed .pc files were found in /usr/local/lib/pkgconfig.
<ide> def check_for_stray_pcs
<ide> end
<ide>
<ide> def check_for_stray_las
<del> white_list = {
<del> "libfuse.la" => "MacFuse",
<del> "libfuse_ino64.la" => "MacFuse",
<del> "libosxfuse_i32.la" => "OSXFuse",
<del> "libosxfuse_i64.la" => "OSXFuse",
<del> }
<add> white_list = [
<add> "libfuse.la", # MacFuse
<add> "libfuse_ino64.la", # MacFuse
<add> "libosxfuse_i32.la", # OSXFuse
<add> "libosxfuse_i64.la", # OSXFuse
<add> ]
<ide>
<ide> __check_stray_files "/usr/local/lib", "*.la", white_list, <<-EOS.undent
<ide> Unbrewed .la files were found in /usr/local/lib.
<ide> def check_for_stray_las
<ide> end
<ide>
<ide> def check_for_stray_headers
<del> white_list = {
<del> "osxfuse/*" => "OSXFuse",
<del> }
<add> white_list = [
<add> "osxfuse/*", # OSXFuse
<add> ]
<ide>
<ide> __check_stray_files "/usr/local/include", "**/*.h", white_list, <<-EOS.undent
<ide> Unbrewed header files were found in /usr/local/include. | 1 |
Javascript | Javascript | remove bone.skin assignment | 5cb64c0324cf67c5dff50aca13c7e6a5f50e9d78 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> if ( jointNode ) {
<ide>
<del> jointNode.skin = child;
<ide> bones.push( jointNode );
<ide>
<ide> var m = skinEntry.inverseBindMatrices.array; | 1 |
Go | Go | remove obsolete workaround | 9200fdd197f7c80c495597104928596516b36f41 | <ide><path>daemon/create.go
<ide> func (daemon *Daemon) ContainerCreate(job *engine.Job) engine.Status {
<ide> job.Errorf("IPv4 forwarding is disabled.\n")
<ide> }
<ide> container.LogEvent("create")
<del> // FIXME: this is necessary because daemon.Create might return a nil container
<del> // with a non-nil error. This should not happen! Once it's fixed we
<del> // can remove this workaround.
<del> if container != nil {
<del> job.Printf("%s\n", container.ID)
<del> }
<add>
<add> job.Printf("%s\n", container.ID)
<add>
<ide> for _, warning := range buildWarnings {
<ide> job.Errorf("%s\n", warning)
<ide> }
<ide> func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.Hos
<ide> }
<ide> return container, warnings, nil
<ide> }
<add>
<ide> func (daemon *Daemon) GenerateSecurityOpt(ipcMode runconfig.IpcMode) ([]string, error) {
<ide> if ipcMode.IsHost() {
<ide> return label.DisableSecOpt(), nil | 1 |
Javascript | Javascript | fix memory leak in scrollviewstickyheader | 3a0927ce4336a1fb8ab7daf10e3048216fb34ce3 | <ide><path>Libraries/Components/ScrollView/ScrollViewStickyHeader.js
<ide> class ScrollViewStickyHeader extends React.Component<Props, State> {
<ide> this.setState({nextHeaderLayoutY: y});
<ide> }
<ide>
<add> componentWillUnmount() {
<add> if (this._translateY != null && this._animatedValueListenerId != null) {
<add> this._translateY.removeListener(this._animatedValueListenerId);
<add> }
<add> if (this._timer) {
<add> clearTimeout(this._timer);
<add> }
<add> }
<add>
<ide> UNSAFE_componentWillReceiveProps(nextProps: Props) {
<ide> if (
<ide> nextProps.scrollViewHeight !== this.props.scrollViewHeight || | 1 |
Text | Text | add teletype focus for the coming week | 48602627b6626f9f4c08888ab945ca202b9ae671 | <ide><path>docs/focus/2018-04-16.md
<ide> - GitHub Package
<ide> - Update React to 16.3 (@smashwilson)
<ide> - Get [atom/squeegpg](https://github.com/atom/squeegpg) to the point where we can use it to sign a commit from atom/github (without needing to override the pinentry yet). (@smashwilson)
<add>- Teletype
<add> - Publish RFC for more quickly collaborating with coworkers and friends ([atom/teletype#344](https://github.com/atom/teletype/pull/344))
<add> - Improve ability to tell which cursor belongs to which collaborator ([atom/teletype#338](https://github.com/atom/teletype/issues/338))
<ide> - Tree-sitter
<ide> - Xray | 1 |
Ruby | Ruby | update permissions policy list | 13b0c6330abc2dc63925e778d5ed8d28ff016899 | <ide><path>actionpack/lib/action_dispatch/http/permissions_policy.rb
<ide> def permissions_policy=(policy)
<ide> fullscreen: "fullscreen",
<ide> geolocation: "geolocation",
<ide> gyroscope: "gyroscope",
<add> hid: "hid",
<add> idle_detection: "idle_detection",
<ide> magnetometer: "magnetometer",
<ide> microphone: "microphone",
<ide> midi: "midi",
<ide> payment: "payment",
<ide> picture_in_picture: "picture-in-picture",
<add> screen_wake_lock: "screen-wake-lock",
<add> serial: "serial",
<ide> speaker: "speaker",
<add> sync_xhr: "sync-xhr",
<ide> usb: "usb",
<ide> vibrate: "vibrate",
<ide> vr: "vr",
<add> web_share: "web-share",
<ide> }.freeze
<ide>
<ide> private_constant :MAPPINGS, :DIRECTIVES | 1 |
Javascript | Javascript | fix typo in $browser mock | d6db4b174940782867d1cf42e1e0152046fe05c1 | <ide><path>src/angular-mocks.js
<ide> function MockBrowser() {
<ide> function() {
<ide> if (self.lastUrl != self.url) {
<ide> listener();
<del> self.lastUrl == self.url
<add> self.lastUrl = self.url;
<ide> }
<ide> }
<ide> ); | 1 |
Text | Text | add documentation for formula renames | 4b31fcd07296bbe33bc309f147a4e27bd39c7af8 | <ide><path>share/doc/homebrew/Rename-A-Formula.md
<add># Renaming a Formula
<add>
<add>Sometimes software and formulae need to be renamed. To rename core formula
<add>you need:
<add>
<add>1. Rename formula file and its class to new formula. New name must meet all the rules of naming. Fix any test failures that may occur due to the stricter requirements for new formula than existing formula (e.g. brew audit --strict must pass for that formula).
<add>
<add>2. Create a pull request to the main repository deleting the formula file, adding new formula file and also add it to `Library/Homebrew/formula_renames.rb` with a commit message like `rename: ack -> newack`
<add>
<add>To rename tap formula you need to follow the same steps, but add formula to `formula_renames.json` in the root of your tap. You don't need to change `Library/Homebrew/formula_renames.rb`, because that file is for core formulae only. Use canonical name (e.g. `ack` instead of `user/repo/ack`).
<add>
<add>`Library/Homebrew/formula_renames.rb` example for core formula renames:
<add>
<add>```ruby
<add>FORMULA_RENAMES = {
<add> "ack" => "newack"
<add>}
<add>```
<add>
<add>`formula_renames.json` example for tap:
<add>
<add>```json
<add>{
<add> "ack": "newack"
<add>}
<add>``` | 1 |
Javascript | Javascript | optimize ray.applymatrix4 performance | 8743685a9556f13dbfdb7028f885ab844ce3b891 | <ide><path>src/math/Ray.js
<ide> Object.assign( Ray.prototype, {
<ide>
<ide> applyMatrix4: function ( matrix4 ) {
<ide>
<del> this.direction.add( this.origin ).applyMatrix4( matrix4 );
<ide> this.origin.applyMatrix4( matrix4 );
<del> this.direction.sub( this.origin );
<del> this.direction.normalize();
<add> this.direction.transformDirection( matrix4 );
<ide>
<ide> return this;
<ide> | 1 |
Text | Text | add a checklist item for `brew man` | 34ea8cbc9d0e45b8c30dc05792a3f3ddd82cef9e | <ide><path>.github/PULL_REQUEST_TEMPLATE.md
<ide> - [ ] Have you written new tests for your changes? [Here's an example](https://github.com/Homebrew/brew/blob/HEAD/Library/Homebrew/test/PATH_spec.rb).
<ide> - [ ] Have you successfully run `brew style` with your changes locally?
<ide> - [ ] Have you successfully run `brew tests` with your changes locally?
<add>- [ ] Have you successfully run `brew man` locally and committed any changes?
<ide>
<ide> ----- | 1 |
Ruby | Ruby | handle attempts to load invalid casks | ea9977f3c3ee45925debd032fdd373440a2c92d1 | <ide><path>Library/Homebrew/formula_installer.rb
<ide> def link(keg)
<ide>
<ide> cask_installed_with_formula_name = begin
<ide> Cask::CaskLoader.load(formula.name).installed?
<del> rescue Cask::CaskUnavailableError
<add> rescue Cask::CaskUnavailableError, Cask::CaskInvalidError
<ide> false
<ide> end
<ide> | 1 |
PHP | PHP | change the default namespace for new commands | cc387a9e5068cb7350b1161a0b38bacedbb88544 | <ide><path>src/Illuminate/Foundation/Console/ConsoleMakeCommand.php
<ide> protected function getStub()
<ide> */
<ide> protected function getDefaultNamespace($rootNamespace)
<ide> {
<del> return $rootNamespace.'\Console';
<add> return $rootNamespace.'\Console\Commands';
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | remove overwritten methods on repository interface | 51c6bb8e6430dcf5479565a02ceca52884393daf | <ide><path>src/Illuminate/Contracts/Cache/Repository.php
<ide>
<ide> interface Repository extends CacheInterface
<ide> {
<del> /**
<del> * Determine if an item exists in the cache.
<del> *
<del> * @param string $key
<del> * @return bool
<del> */
<del> public function has($key);
<del>
<del> /**
<del> * Retrieve an item from the cache by key.
<del> *
<del> * @param string $key
<del> * @param mixed $default
<del> * @return mixed
<del> */
<del> public function get($key, $default = null);
<del>
<ide> /**
<ide> * Retrieve an item from the cache and delete it.
<ide> * | 1 |
Python | Python | use a raw string for the fromstring docstring | 92271ec06b7abc5b6c3daf2e94563c575983d436 | <ide><path>numpy/core/records.py
<ide> def fromrecords(recList, dtype=None, shape=None, formats=None, names=None,
<ide>
<ide> def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None,
<ide> names=None, titles=None, aligned=False, byteorder=None):
<del> """Create a record array from binary data
<add> r"""Create a record array from binary data
<ide>
<ide> Note that despite the name of this function it does not accept `str`
<ide> instances. | 1 |
PHP | PHP | fix casing issue on hascolumn | ee25cd0f7ec18be23e902531b984ef5278b4aff5 | <ide><path>src/Illuminate/Database/Schema/Builder.php
<ide> public function hasColumn($table, $column)
<ide> {
<ide> $schema = $this->connection->getDoctrineSchemaManager();
<ide>
<del> return in_array($column, array_keys($schema->listTableColumns($table)));
<add> $columns = array_keys(array_change_key_case($schema->listTableColumns($table)));
<add>
<add> return in_array(strtolower($column), $columns);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | use arrow functions to simplify code | fc37d69a9a0e1c89fe0065e6d7d61e17ae68cd86 | <ide><path>bin/run-tests.js
<ide> function generateTestsFor(packageName) {
<ide> return;
<ide> }
<ide>
<del> testFunctions.push(function() {
<del> return run('package=' + packageName);
<del> });
<del> testFunctions.push(function() {
<del> return run('package=' + packageName + '&dist=es');
<del> });
<del> testFunctions.push(function() {
<del> return run('package=' + packageName + '&enableoptionalfeatures=true');
<del> });
<add> testFunctions.push(() => run('package=' + packageName));
<add> testFunctions.push(() => run('package=' + packageName + '&dist=es'));
<add> testFunctions.push(() => run('package=' + packageName + '&enableoptionalfeatures=true'));
<ide>
<ide> // TODO: this should ultimately be deleted (when all packages can run with and
<ide> // without jQuery)
<ide> if (packageName !== 'ember') {
<del> testFunctions.push(function() {
<del> return run('package=' + packageName + '&jquery=none');
<del> });
<add> testFunctions.push(() => run('package=' + packageName + '&jquery=none'));
<ide> }
<ide> }
<ide>
<ide> function generateBuiltTests() {
<ide> // ember-testing and @ember/debug are stripped from prod/min.
<ide> var common = 'skipPackage=container,ember-testing,@ember/debug';
<ide>
<del> testFunctions.push(function() {
<del> return run(common);
<del> });
<del> testFunctions.push(function() {
<del> return run(common + '&dist=min&prod=true');
<del> });
<del> testFunctions.push(function() {
<del> return run(common + '&dist=prod&prod=true');
<del> });
<del> testFunctions.push(function() {
<del> return run(common + '&enableoptionalfeatures=true&dist=prod&prod=true');
<del> });
<del> testFunctions.push(function() {
<del> return run(common + '&legacy=true');
<del> });
<del> testFunctions.push(function() {
<del> return run(common + '&legacy=true&dist=min&prod=true');
<del> });
<del> testFunctions.push(function() {
<del> return run(common + '&legacy=true&dist=prod&prod=true');
<del> });
<del> testFunctions.push(function() {
<del> return run(common + '&legacy=true&enableoptionalfeatures=true&dist=prod&prod=true');
<del> });
<add> testFunctions.push(() => run(common));
<add> testFunctions.push(() => run(common + '&dist=min&prod=true'));
<add> testFunctions.push(() => run(common + '&dist=prod&prod=true'));
<add> testFunctions.push(() => run(common + '&enableoptionalfeatures=true&dist=prod&prod=true'));
<add> testFunctions.push(() => run(common + '&legacy=true'));
<add> testFunctions.push(() => run(common + '&legacy=true&dist=min&prod=true'));
<add> testFunctions.push(() => run(common + '&legacy=true&dist=prod&prod=true'));
<add> testFunctions.push(() =>
<add> run(common + '&legacy=true&enableoptionalfeatures=true&dist=prod&prod=true')
<add> );
<ide> }
<ide>
<ide> function generateOldJQueryTests() {
<del> testFunctions.push(function() {
<del> return run('jquery=1.10.2');
<del> });
<del> testFunctions.push(function() {
<del> return run('jquery=1.12.4');
<del> });
<del> testFunctions.push(function() {
<del> return run('jquery=2.2.4');
<del> });
<add> testFunctions.push(() => run('jquery=1.10.2'));
<add> testFunctions.push(() => run('jquery=1.12.4'));
<add> testFunctions.push(() => run('jquery=2.2.4'));
<ide> }
<ide>
<ide> function generateExtendPrototypeTests() {
<del> testFunctions.push(function() {
<del> return run('extendprototypes=true');
<del> });
<del> testFunctions.push(function() {
<del> return run('extendprototypes=true&enableoptionalfeatures=true');
<del> });
<add> testFunctions.push(() => run('extendprototypes=true'));
<add> testFunctions.push(() => run('extendprototypes=true&enableoptionalfeatures=true'));
<ide> }
<ide>
<ide> function runAndExit() { | 1 |
PHP | PHP | fix failing tests | a73d5598d64f893dacaa3a6b2d56a76c93b55a63 | <ide><path>lib/Cake/Error/ExceptionRenderer.php
<ide> protected function _getController($exception) {
<ide> $response->header($exception->responseHeader());
<ide> }
<ide>
<del> if (class_exists('AppController')) {
<del> try {
<del> $controller = new ErrorController($request, $response);
<del> $controller->startupProcess();
<del> } catch (\Exception $e) {
<del> if (!empty($controller) && $controller->Components->enabled('RequestHandler')) {
<del> $controller->RequestHandler->startup($controller);
<del> }
<add> try {
<add> $controller = new ErrorController($request, $response);
<add> $controller->startupProcess();
<add> } catch (\Exception $e) {
<add> if (!empty($controller) && $controller->Components->enabled('RequestHandler')) {
<add> $controller->RequestHandler->startup($controller);
<ide> }
<ide> }
<ide> if (empty($controller)) {
<ide><path>lib/Cake/Test/TestCase/Configure/PhpReaderTest.php
<ide> public function testDump() {
<ide> $expected = <<<PHP
<ide> <?php
<ide> \$config = array (
<del> 'One' =>
<add> 'One' =>
<ide> array (
<ide> 'two' => 'value',
<del> 'three' =>
<add> 'three' =>
<ide> array (
<ide> 'four' => 'value four',
<ide> ),
<ide> 'is_null' => NULL,
<ide> 'bool_false' => false,
<ide> 'bool_true' => true,
<ide> ),
<del> 'Asset' =>
<add> 'Asset' =>
<ide> array (
<ide> 'timestamp' => 'force',
<ide> ),
<ide><path>lib/Cake/Test/TestCase/Utility/XmlTest.php
<ide> public function testBuildInvalidData($value) {
<ide> /**
<ide> * Test that building SimpleXmlElement with invalid XML causes the right exception.
<ide> *
<del> * @expectedException XmlException
<add> * @expectedException Cake\Error\XmlException
<ide> * @return void
<ide> */
<ide> public function testBuildInvalidDataSimpleXml() { | 3 |
Ruby | Ruby | change inititial partial request to head request | aa989bd55a2013c9858e19455c700b707d65021e | <ide><path>Library/Homebrew/utils/curl.rb
<ide> def curl(*args, print_stdout: true, **options)
<ide> result
<ide> end
<ide>
<del> def curl_download(*args, to: nil, partial: true, **options)
<add> def curl_download(*args, to: nil, try_partial: true, **options)
<ide> destination = Pathname(to)
<ide> destination.dirname.mkpath
<ide>
<del> if partial
<add> if try_partial
<ide> range_stdout = curl_output("--location", "--range", "0-1",
<ide> "--dump-header", "-",
<ide> "--write-out", "%\{http_code}",
<del> "--output", "/dev/null", *args, **options).stdout
<add> "--head", *args, **options).stdout
<ide> headers, _, http_status = range_stdout.partition("\r\n\r\n")
<ide>
<ide> supports_partial_download = http_status.to_i == 206 # Partial Content | 1 |
Ruby | Ruby | add test for `systemcommand` with `sigint` handler | 2dd40720f075bf93551a27fe0be64c96312632fd | <ide><path>Library/Homebrew/test/spec_helper.rb
<ide>
<ide> config.around do |example|
<ide> def find_files
<add> return [] unless File.exist?(TEST_TMPDIR)
<add>
<ide> Find.find(TEST_TMPDIR)
<ide> .reject { |f| File.basename(f) == ".DS_Store" }
<add> .reject { |f| TEST_DIRECTORIES.include?(Pathname(f)) }
<ide> .map { |f| f.sub(TEST_TMPDIR, "") }
<ide> end
<ide>
<del> begin
<del> Homebrew.raise_deprecation_exceptions = true
<add> Homebrew.raise_deprecation_exceptions = true
<ide>
<del> Formulary.clear_cache
<del> Tap.clear_cache
<del> DependencyCollector.clear_cache
<del> Formula.clear_cache
<del> Keg.clear_cache
<del> Tab.clear_cache
<del> FormulaInstaller.clear_attempted
<del> FormulaInstaller.clear_installed
<add> Formulary.clear_cache
<add> Tap.clear_cache
<add> DependencyCollector.clear_cache
<add> Formula.clear_cache
<add> Keg.clear_cache
<add> Tab.clear_cache
<add> FormulaInstaller.clear_attempted
<add> FormulaInstaller.clear_installed
<ide>
<del> TEST_DIRECTORIES.each(&:mkpath)
<add> TEST_DIRECTORIES.each(&:mkpath)
<ide>
<del> @__homebrew_failed = Homebrew.failed?
<add> @__homebrew_failed = Homebrew.failed?
<ide>
<del> @__files_before_test = find_files
<add> @__files_before_test = find_files
<ide>
<del> @__env = ENV.to_hash # dup doesn't work on ENV
<add> @__env = ENV.to_hash # dup doesn't work on ENV
<ide>
<del> @__stdout = $stdout.clone
<del> @__stderr = $stderr.clone
<add> @__stdout = $stdout.clone
<add> @__stderr = $stderr.clone
<ide>
<add> begin
<ide> if (example.metadata.keys & [:focus, :byebug]).empty? && !ENV.key?("VERBOSE_TESTS")
<ide> $stdout.reopen(File::NULL)
<ide> $stderr.reopen(File::NULL)
<ide> def find_files
<ide> Tab.clear_cache
<ide>
<ide> FileUtils.rm_rf [
<del> TEST_DIRECTORIES.map(&:children),
<add> *TEST_DIRECTORIES,
<ide> *Keg::MUST_EXIST_SUBDIRECTORIES,
<ide> HOMEBREW_LINKED_KEGS,
<ide> HOMEBREW_PINNED_KEGS,
<ide><path>Library/Homebrew/test/system_command_spec.rb
<ide> }.to raise_error.with_message(redacted_msg).and output(redacted_msg).to_stderr
<ide> end
<ide> end
<add>
<add> context "when a `SIGINT` handler is set in the parent process" do
<add> it "is not interrupted" do
<add> start_time = Time.now
<add>
<add> pid = fork do
<add> trap("INT") do
<add> # Ignore SIGINT.
<add> end
<add>
<add> described_class.run! "sleep", args: [5]
<add>
<add> exit!
<add> end
<add>
<add> sleep 1
<add> Process.kill("INT", pid)
<add>
<add> Process.waitpid(pid)
<add>
<add> expect(Time.now - start_time).to be >= 5
<add> end
<add> end
<ide> end
<ide> end | 2 |
Javascript | Javascript | add test for notcacheable in cacheplugin | 46432c4009292bfc2f1e883625a290cd5392084b | <ide><path>test/watchCases/cache/warning-on-not-cacheable/0/index.js
<add>it("should emit a warning", function() {
<add> // nothing
<add>});
<ide><path>test/watchCases/cache/warning-on-not-cacheable/0/warnings.js
<add>module.exports = [
<add> [/CachePlugin - Cache cannot be used because of: for testing/]
<add>];
<ide><path>test/watchCases/cache/warning-on-not-cacheable/webpack.config.js
<add>module.exports = {
<add> plugins: [
<add> function() {
<add> this.plugin("this-compilation", c => {
<add> c.notCacheable = "for testing";
<add> });
<add> }
<add> ]
<add>}; | 3 |
Go | Go | update loaddriver to use pluginv2 | 3504ed88d939b9ec9cf20156dadaef190b599dca | <ide><path>libnetwork/controller.go
<ide> func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
<ide> }
<ide>
<ide> func (c *controller) loadDriver(networkType string) error {
<del> // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
<del> // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
<del> _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
<add> var err error
<add>
<add> if pg := c.GetPluginGetter(); pg != nil {
<add> _, err = pg.Get(networkType, driverapi.NetworkPluginEndpointType, plugingetter.LOOKUP)
<add> } else {
<add> _, err = plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
<add> }
<add>
<ide> if err != nil {
<ide> if err == plugins.ErrNotFound {
<ide> return types.NotFoundErrorf(err.Error())
<ide> func (c *controller) loadDriver(networkType string) error {
<ide> }
<ide>
<ide> func (c *controller) loadIPAMDriver(name string) error {
<del> if _, err := c.GetPluginGetter().Get(name, ipamapi.PluginEndpointType, plugingetter.LOOKUP); err != nil {
<add> var err error
<add>
<add> if pg := c.GetPluginGetter(); pg != nil {
<add> _, err = pg.Get(name, ipamapi.PluginEndpointType, plugingetter.LOOKUP)
<add> } else {
<add> _, err = plugins.Get(name, ipamapi.PluginEndpointType)
<add> }
<add>
<add> if err != nil {
<ide> if err == plugins.ErrNotFound {
<ide> return types.NotFoundErrorf(err.Error())
<ide> } | 1 |
Text | Text | fix typo in error/middleware-upgrade-guide.md | 885defd442fe2b5c5e75c4bf7e0c63cd1e1dfce5 | <ide><path>errors/middleware-upgrade-guide.md
<ide> Prior to Next.js `v12.2`, Middleware was not executed for `_next` requests.
<ide>
<ide> For cases where Middleware is used for authorization, you should migrate to use `rewrite`/`redirect` to Pages that show an authorization error, login forms, or to an API Route.
<ide>
<del>See [No Reponse Body](#no-response-body) for an example of how to migrate to use `rewrite`/`redirect`.
<add>See [No Response Body](#no-response-body) for an example of how to migrate to use `rewrite`/`redirect`. | 1 |
Text | Text | fix wrong date and known issue in changelog.md | 3268383c2b0c28ac6ef1ab336c271f58750eaced | <ide><path>CHANGELOG.md
<ide> # Node.js ChangeLog
<ide>
<del>## 2015-10-29, Version 4.2.2 'Argon' (LTS), @jasnell
<add>## 2015-11-03, Version 4.2.2 'Argon' (LTS), @jasnell
<ide>
<ide> ### Notable changes
<ide>
<ide> This is an LTS maintenance release that addresses a number of issues:
<ide>
<ide> ### Known issues
<ide>
<del>* Some problems with unreferenced timers running during `beforeExit` are still to be resolved. See [#1264](https://github.com/nodejs/node/issues/1264).
<ide> * Surrogate pair in REPL can freeze terminal. [#690](https://github.com/nodejs/node/issues/690)
<ide> * Calling `dns.setServers()` while a DNS query is in progress can cause the process to crash on a failed assertion. [#894](https://github.com/nodejs/node/issues/894)
<ide> * `url.resolve` may transfer the auth portion of the url when resolving between two full hosts, see [#1435](https://github.com/nodejs/node/issues/1435). | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.