content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
PHP | PHP | remove dead code in orm | 35a7038bd862430fb00c9de73f0342a5d74f119b | <ide><path>src/ORM/EntityValidator.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://cakephp.org CakePHP(tm) Project
<del> * @since 3.0.0
<del> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\ORM;
<del>
<del>use ArrayObject;
<del>use Cake\Datasource\EntityInterface;
<del>use Cake\ORM\Association;
<del>use Cake\ORM\Table;
<del>use Cake\Validation\ValidatableInterface;
<del>
<del>/**
<del> * Contains logic for validating entities and their associations.
<del> *
<del> * This class is generally used by the internals of the ORM. It
<del> * provides methods for traversing a set of entities and their associated
<del> * properties.
<del> */
<del>class EntityValidator
<del>{
<del>
<del> /**
<del> * The table instance this validator is for.
<del> *
<del> * @var \Cake\ORM\Table
<del> */
<del> protected $_table;
<del>
<del> /**
<del> * Constructor.
<del> *
<del> * @param \Cake\ORM\Table $table The table this validator is for
<del> */
<del> public function __construct(Table $table)
<del> {
<del> $this->_table = $table;
<del> }
<del>
<del> /**
<del> * Build the map of property => association names.
<del> *
<del> * @param array $include The array of included associations.
<del> * @return array
<del> */
<del> protected function _buildPropertyMap($include)
<del> {
<del> if (empty($include['associated'])) {
<del> return [];
<del> }
<del>
<del> $map = [];
<del> foreach ($include['associated'] as $key => $options) {
<del> if (is_int($key) && is_scalar($options)) {
<del> $key = $options;
<del> $options = [];
<del> }
<del>
<del> $options += ['validate' => true, 'associated' => []];
<del> $assoc = $this->_table->association($key);
<del> if ($assoc) {
<del> $map[$assoc->property()] = [
<del> 'association' => $assoc,
<del> 'options' => $options
<del> ];
<del> }
<del> }
<del> return $map;
<del> }
<del>
<del> /**
<del> * Validates a single entity by getting the correct validator object from
<del> * the table and traverses associations passed in $options to validate them
<del> * as well.
<del> *
<del> * @param \Cake\Datasource\EntityInterface $entity The entity to be validated
<del> * @param array|\ArrayObject $options options for validation, including an optional key of
<del> * associations to also be validated. This argument should use the same format as the $options
<del> * argument to \Cake\ORM\Table::save().
<del> * @return bool true if all validations passed, false otherwise
<del> */
<del> public function one(EntityInterface $entity, $options = [])
<del> {
<del> $valid = true;
<del> $types = [Association::ONE_TO_ONE, Association::MANY_TO_ONE];
<del> $propertyMap = $this->_buildPropertyMap($options);
<del> $options = new ArrayObject($options);
<del>
<del> foreach ($propertyMap as $key => $assoc) {
<del> $value = $entity->get($key);
<del> $association = $assoc['association'];
<del>
<del> if (!$value) {
<del> continue;
<del> }
<del> $isOne = in_array($association->type(), $types);
<del> if ($isOne && !($value instanceof EntityInterface)) {
<del> $valid = false;
<del> continue;
<del> }
<del>
<del> $validator = new self($association->target());
<del> if ($isOne) {
<del> $valid = $validator->one($value, $assoc['options']) && $valid;
<del> } else {
<del> $valid = $validator->many($value, $assoc['options']) && $valid;
<del> }
<del> }
<del>
<del> if (!isset($options['validate'])) {
<del> $options['validate'] = true;
<del> }
<del>
<del> if (!($entity instanceof ValidatableInterface)) {
<del> return $valid;
<del> }
<del>
<del> return $this->_processValidation($entity, $options) && $valid;
<del> }
<del>
<del> /**
<del> * Validates a list of entities by getting the correct validator for the related
<del> * table and traverses associations passed in $include to validate them as well.
<del> *
<del> * If any of the entities in `$entities` does not implement `Cake\Datasource\EntityInterface`,
<del> * it will be treated as an invalid result.
<del> *
<del> * @param array $entities List of entities to be validated
<del> * @param array|\ArrayObject $options options for validation, including an optional key of
<del> * associations to also be validated. This argument should use the same format as the $options
<del> * argument to \Cake\ORM\Table::save().
<del> * @return bool true if all validations passed, false otherwise
<del> */
<del> public function many(array $entities, $options = [])
<del> {
<del> $valid = true;
<del> foreach ($entities as $entity) {
<del> if (!($entity instanceof EntityInterface)) {
<del> return false;
<del> }
<del> $valid = $this->one($entity, $options) && $valid;
<del> }
<del> return $valid;
<del> }
<del>
<del> /**
<del> * Validates the $entity if the 'validate' key is not set to false in $options
<del> * If not empty it will construct a default validation object or get one with
<del> * the name passed in the key
<del> *
<del> * @param \Cake\ORM\Entity $entity The entity to validate
<del> * @param \ArrayObject $options The option for processing validation
<del> * @return bool true if the entity is valid, false otherwise
<del> */
<del> protected function _processValidation($entity, $options)
<del> {
<del> $type = is_string($options['validate']) ? $options['validate'] : 'default';
<del> $validator = $this->_table->validator($type);
<del> $pass = compact('entity', 'options', 'validator');
<del> $event = $this->_table->dispatchEvent('Model.beforeValidate', $pass);
<del>
<del> if ($event->isStopped()) {
<del> return (bool)$event->result;
<del> }
<del>
<del> if (!count($validator)) {
<del> return true;
<del> }
<del>
<del> $success = !$entity->validate($validator);
<del>
<del> $event = $this->_table->dispatchEvent('Model.afterValidate', $pass);
<del> if ($event->isStopped()) {
<del> $success = (bool)$event->result;
<del> }
<del>
<del> return $success;
<del> }
<del>}
<ide><path>src/ORM/EntityValidatorTrait.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://cakephp.org CakePHP(tm) Project
<del> * @since 3.0.0
<del> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\ORM;
<del>
<del>use Cake\Validation\Validator;
<del>
<del>/**
<del> * Contains a method that can be used to apply a validator to an entity's internal
<del> * properties. This trait can be used to satisfy the Cake\Validation\ValidatableInterface
<del> */
<del>trait EntityValidatorTrait
<del>{
<del>
<del> /**
<del> * Validates the internal properties using a validator object and returns any
<del> * validation errors found.
<del> *
<del> * @param \Cake\Validation\Validator $validator The validator to use when validating the entity.
<del> * @return array
<del> */
<del> public function validate(Validator $validator)
<del> {
<del> $data = $this->_properties;
<del> $new = $this->isNew();
<del> $validator->provider('entity', $this);
<del> $this->errors($validator->errors($data, $new === null ? true : $new));
<del> return $this->_errors;
<del> }
<del>}
<ide><path>tests/TestCase/ORM/EntityTest.php
<ide> use Cake\Validation\Validator;
<ide> use TestApp\Model\Entity\Extending;
<ide> use TestApp\Model\Entity\NonExtending;
<del>use TestApp\Model\Entity\ValidatableEntity;
<ide>
<ide> /**
<ide> * Entity test case.
<ide> public function testToArrayVirtualProperties()
<ide> $this->assertEquals(['name'], $entity->hiddenProperties());
<ide> }
<ide>
<del> /**
<del> * Tests that missing fields will not be passed as null to the validator
<del> *
<del> * @return void
<del> */
<del> public function testValidateMissingFields()
<del> {
<del> $entity = $this->getMockBuilder('TestApp\Model\Entity\ValidatableEntity')
<del> ->setMethods(['getSomething'])
<del> ->disableOriginalConstructor()
<del> ->getMock();
<del> $entity->accessible('*', true);
<del>
<del> $validator = $this->getMock('\Cake\Validation\Validator');
<del> $entity->set('a', 'b');
<del>
<del> $validator->expects($this->once())
<del> ->method('provider')
<del> ->with('entity', $entity);
<del> $validator->expects($this->once())->method('errors')
<del> ->with(['a' => 'b'], true)
<del> ->will($this->returnValue(['a' => ['not valid']]));
<del> $this->assertNotEmpty($entity->validate($validator));
<del> $this->assertEquals(['a' => ['not valid']], $entity->errors());
<del> }
<del>
<del> /**
<del> * Tests validate when the validator returns no errors
<del> *
<del> * @return void
<del> */
<del> public function testValidateSuccess()
<del> {
<del> $validator = $this->getMock('\Cake\Validation\Validator');
<del> $data = [
<del> 'a' => 'b',
<del> 'cool' => false,
<del> 'something' => true
<del> ];
<del> $entity = new ValidatableEntity($data);
<del> $entity->isNew(true);
<del>
<del> $validator->expects($this->once())
<del> ->method('provider')
<del> ->with('entity', $entity);
<del> $validator->expects($this->once())->method('errors')
<del> ->with($data, true)
<del> ->will($this->returnValue([]));
<del> $this->assertEmpty($entity->validate($validator));
<del> $this->assertEquals([], $entity->errors());
<del> }
<del>
<ide> /**
<ide> * Tests the errors method
<ide> *
<ide><path>tests/TestCase/ORM/EntityValidatorTest.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://cakephp.org CakePHP(tm) Project
<del> * @since 3.0.0
<del> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Test\TestCase\ORM;
<del>
<del>use Cake\ORM\Entity;
<del>use Cake\ORM\EntityValidator;
<del>use Cake\ORM\Table;
<del>use Cake\ORM\TableRegistry;
<del>use Cake\TestSuite\TestCase;
<del>
<del>/**
<del> * EntityValidator test
<del> */
<del>class EntityValidatorTest extends TestCase
<del>{
<del>
<del> /**
<del> * setup
<del> *
<del> * @return void
<del> */
<del> public function setUp()
<del> {
<del> parent::setUp();
<del> $articles = TableRegistry::get('Articles');
<del> $users = TableRegistry::get('Users');
<del> $articles->belongsTo('Users');
<del> $articles->hasMany('Comments');
<del>
<del> $comments = TableRegistry::get('Comments');
<del> $comments->belongsTo('Articles');
<del> $comments->belongsTo('Users');
<del>
<del> $this->articles = $articles;
<del> $this->comments = $comments;
<del> $this->users = $users;
<del> }
<del>
<del> /**
<del> * Teardown
<del> *
<del> * @return void
<del> */
<del> public function tearDown()
<del> {
<del> parent::tearDown();
<del> TableRegistry::clear();
<del> unset($this->articles, $this->comments, $this->users);
<del> }
<del>
<del> /**
<del> * Test one() with successful validate
<del> *
<del> * @return void
<del> */
<del> public function testOneSuccess()
<del> {
<del> $entity = $this->getMock('TestApp\Model\Entity\ValidatableEntity', ['validate']);
<del> $validator = $this->getMock('\Cake\Validation\Validator');
<del> $this->articles->validator('default', $validator);
<del> $entityValidator = new EntityValidator($this->articles);
<del>
<del> $validator->expects($this->once())
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del> $entity->expects($this->once())
<del> ->method('validate')
<del> ->with($validator)
<del> ->will($this->returnValue([]));
<del>
<del> $this->assertTrue($entityValidator->one($entity));
<del> }
<del>
<del> /**
<del> * Test one() with failing validate
<del> *
<del> * @return void
<del> */
<del> public function testOneFail()
<del> {
<del> $entity = $this->getMock('TestApp\Model\Entity\ValidatableEntity', ['validate']);
<del> $validator = $this->getMock('\Cake\Validation\Validator');
<del> $this->articles->validator('default', $validator);
<del> $entityValidator = new EntityValidator($this->articles);
<del>
<del> $validator->expects($this->once())
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del> $entity->expects($this->once())
<del> ->method('validate')
<del> ->with($validator)
<del> ->will($this->returnValue(['one' => ['error']]));
<del>
<del> $this->assertFalse($entityValidator->one($entity));
<del> }
<del>
<del> /**
<del> * test one() with association data.
<del> *
<del> * @return void
<del> */
<del> public function testOneAssociationsSuccess()
<del> {
<del> $class = 'TestApp\Model\Entity\ValidatableEntity';
<del> $article = $this->getMock($class, ['validate']);
<del> $comment1 = $this->getMock($class, ['validate']);
<del> $comment2 = $this->getMock($class, ['validate']);
<del> $user = $this->getMock($class, ['validate']);
<del> $article->set('comments', [$comment1, $comment2]);
<del> $article->set('user', $user);
<del>
<del> $validator1 = $this->getMock('\Cake\Validation\Validator');
<del> $validator2 = $this->getMock('\Cake\Validation\Validator');
<del> $validator3 = $this->getMock('\Cake\Validation\Validator');
<del>
<del> $validator1->expects($this->once())
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del> $validator2->expects($this->exactly(2))
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del> $validator3->expects($this->once())
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del>
<del> $this->articles->validator('default', $validator1);
<del> $this->comments->validator('default', $validator2);
<del> $this->users->validator('default', $validator3);
<del>
<del> $entityValidator = new EntityValidator($this->articles);
<del>
<del> $article->expects($this->once())
<del> ->method('validate')
<del> ->with($validator1)
<del> ->will($this->returnValue([]));
<del>
<del> $comment1->expects($this->once())
<del> ->method('validate')
<del> ->with($validator2)
<del> ->will($this->returnValue([]));
<del>
<del> $comment2->expects($this->once())
<del> ->method('validate')
<del> ->with($validator2)
<del> ->will($this->returnValue([]));
<del>
<del> $user->expects($this->once())
<del> ->method('validate')
<del> ->with($validator3)
<del> ->will($this->returnValue([]));
<del>
<del> $options = ['associated' => ['Comments', 'Users']];
<del> $this->assertTrue($entityValidator->one($article, $options));
<del> }
<del>
<del> /**
<del> * test one() with associations that are not entities.
<del> *
<del> * This can happen when request data is not completely marshalled.
<del> * incomplete associations should not cause warnings or fatal errors.
<del> *
<del> * @return void
<del> */
<del> public function testOneAssociationsNoEntities()
<del> {
<del> $class = 'TestApp\Model\Entity\ValidatableEntity';
<del> $article = $this->getMock($class, ['validate']);
<del> $comment1 = ['comment' => 'test'];
<del> $comment2 = ['comment' => 'omg'];
<del> $user = $this->getMock($class, ['validate']);
<del> $article->set('comments', [$comment1, $comment2]);
<del>
<del> $validator1 = $this->getMock('\Cake\Validation\Validator');
<del> $validator2 = $this->getMock('\Cake\Validation\Validator');
<del>
<del> $validator1->expects($this->once())
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del>
<del> // Should not be called as comments are not entities.
<del> $validator2->expects($this->never())
<del> ->method('count');
<del>
<del> $this->articles->validator('default', $validator1);
<del> $this->comments->validator('default', $validator2);
<del>
<del> $entityValidator = new EntityValidator($this->articles);
<del>
<del> $article->expects($this->once())
<del> ->method('validate')
<del> ->with($validator1)
<del> ->will($this->returnValue([]));
<del>
<del> $options = ['associated' => ['Comments']];
<del> $this->assertFalse($entityValidator->one($article, $options));
<del> }
<del>
<del> /**
<del> * test one() with association data and one of them failing validation.
<del> *
<del> * @return void
<del> */
<del> public function testOneAssociationsFail()
<del> {
<del> $class = 'TestApp\Model\Entity\ValidatableEntity';
<del> $article = $this->getMock($class, ['validate']);
<del> $comment1 = $this->getMock($class, ['validate']);
<del> $comment2 = $this->getMock($class, ['validate']);
<del> $user = $this->getMock($class, ['validate']);
<del> $article->set('comments', [$comment1, $comment2]);
<del> $article->set('user', $user);
<del>
<del> $validator1 = $this->getMock('\Cake\Validation\Validator');
<del> $validator2 = $this->getMock('\Cake\Validation\Validator');
<del> $validator3 = $this->getMock('\Cake\Validation\Validator');
<del>
<del> $validator1->expects($this->once())
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del> $validator2->expects($this->exactly(2))
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del> $validator3->expects($this->once())
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del>
<del> $this->articles->validator('default', $validator1);
<del> $this->comments->validator('default', $validator2);
<del> $this->users->validator('default', $validator3);
<del>
<del> $entityValidator = new EntityValidator($this->articles);
<del>
<del> $article->expects($this->once())
<del> ->method('validate')
<del> ->with($validator1)
<del> ->will($this->returnValue([]));
<del>
<del> $comment1->expects($this->once())
<del> ->method('validate')
<del> ->with($validator2)
<del> ->will($this->returnValue([]));
<del>
<del> $comment2->expects($this->once())
<del> ->method('validate')
<del> ->with($validator2)
<del> ->will($this->returnValue(['some' => ['error']]));
<del>
<del> $user->expects($this->once())
<del> ->method('validate')
<del> ->with($validator3)
<del> ->will($this->returnValue([]));
<del>
<del> $options = ['associated' => ['Comments', 'Users']];
<del> $this->assertFalse($entityValidator->one($article, $options));
<del> }
<del>
<del> /**
<del> * Test one() with deeper associations and passing the name for custom
<del> * validators
<del> *
<del> * @return void
<del> */
<del> public function testOneDeepAssociationsAndCustomValidators()
<del> {
<del> $class = 'TestApp\Model\Entity\ValidatableEntity';
<del> $comment = $this->getMock($class, ['validate']);
<del> $article = $this->getMock($class, ['validate']);
<del> $user = $this->getMock($class, ['validate']);
<del>
<del> $comment->set('article', $article);
<del> $article->set('user', $user);
<del>
<del> $validator1 = $this->getMock('\Cake\Validation\Validator');
<del> $validator2 = $this->getMock('\Cake\Validation\Validator');
<del> $validator3 = $this->getMock('\Cake\Validation\Validator');
<del>
<del> $validator1->expects($this->once())
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del> $validator2->expects($this->once())
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del> $validator3->expects($this->once())
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del>
<del> $this->articles->validator('crazy', $validator1);
<del> $this->comments->validator('default', $validator2);
<del> $this->users->validator('funky', $validator3);
<del>
<del> $entityValidator = new EntityValidator($this->comments);
<del> $comment->expects($this->once())
<del> ->method('validate')
<del> ->with($validator2)
<del> ->will($this->returnValue([]));
<del>
<del> $article->expects($this->once())
<del> ->method('validate')
<del> ->with($validator1)
<del> ->will($this->returnValue([]));
<del>
<del> $user->expects($this->once())
<del> ->method('validate')
<del> ->with($validator3)
<del> ->will($this->returnValue([]));
<del>
<del> $this->assertTrue($entityValidator->one($comment, [
<del> 'associated' => [
<del> 'Articles' => [
<del> 'validate' => 'crazy',
<del> 'associated' => ['Users' => ['validate' => 'funky']]
<del> ]
<del> ]
<del> ]));
<del> }
<del>
<del> /**
<del> * Test many() with successful validate
<del> *
<del> * @return void
<del> */
<del> public function testManySuccess()
<del> {
<del> $class = 'TestApp\Model\Entity\ValidatableEntity';
<del> $comment1 = $this->getMock($class, ['validate']);
<del> $comment2 = $this->getMock($class, ['validate']);
<del> $validator = $this->getMock('\Cake\Validation\Validator');
<del> $data = [$comment1, $comment2];
<del> $this->comments->validator('default', $validator);
<del> $entityValidator = new EntityValidator($this->comments);
<del>
<del> $validator->expects($this->exactly(2))
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del> $comment1->expects($this->once())
<del> ->method('validate')
<del> ->with($validator)
<del> ->will($this->returnValue([]));
<del>
<del> $comment2->expects($this->once())
<del> ->method('validate')
<del> ->with($validator)
<del> ->will($this->returnValue([]));
<del>
<del> $this->assertTrue($entityValidator->many($data));
<del> }
<del>
<del> /**
<del> * Test many() with failure
<del> *
<del> * @return void
<del> */
<del> public function testManyFailure()
<del> {
<del> $class = 'TestApp\Model\Entity\ValidatableEntity';
<del> $comment1 = $this->getMock($class, ['validate']);
<del> $comment2 = $this->getMock($class, ['validate']);
<del> $validator = $this->getMock('\Cake\Validation\Validator');
<del> $data = [$comment1, $comment2];
<del> $this->comments->validator('default', $validator);
<del> $entityValidator = new EntityValidator($this->comments);
<del>
<del> $validator->expects($this->exactly(2))
<del> ->method('count')
<del> ->will($this->returnValue(1));
<del>
<del> $comment1->expects($this->once())
<del> ->method('validate')
<del> ->with($validator)
<del> ->will($this->returnValue(['some' => ['error']]));
<del>
<del> $comment2->expects($this->once())
<del> ->method('validate')
<del> ->with($validator)
<del> ->will($this->returnValue([]));
<del>
<del> $this->assertFalse($entityValidator->many($data));
<del> }
<del>}
<ide><path>tests/test_app/TestApp/Model/Entity/ValidatableEntity.php
<del><?php
<del>
<del>namespace TestApp\Model\Entity;
<del>
<del>use Cake\ORM\Entity;
<del>use Cake\ORM\EntityValidatorTrait;
<del>use Cake\Validation\ValidatableInterface;
<del>
<del>/**
<del> * Tests entity class used for asserting correct loading
<del> *
<del> */
<del>class ValidatableEntity extends Entity implements ValidatableInterface
<del>{
<del>
<del> use EntityValidatorTrait;
<del>} | 5 |
Python | Python | remove location from vhdimage type repr | d5b3dd3151c2120c96e9c25b3c5e72c7282be7c3 | <ide><path>libcloud/compute/drivers/azure_arm.py
<ide> def __init__(self, storage_account, blob_container, name, driver):
<ide> super(AzureVhdImage, self).__init__(urn, name, driver)
<ide>
<ide> def __repr__(self):
<del> return (('<AzureVhdImage: id=%s, name=%s, location=%s>')
<del> % (self.id, self.name, self.location))
<add> return (('<AzureVhdImage: id=%s, name=%s>')
<add> % (self.id, self.name))
<ide>
<ide>
<ide> class AzureResourceGroup(object): | 1 |
Python | Python | update example for adding entity type | 683d81bb49096867f5ad8d3dde23217ea54d6790 | <ide><path>examples/training/train_new_entity_type.py
<ide> * Saving and loading models: https://spacy.io/docs/usage/saving-loading
<ide>
<ide> Developed for: spaCy 1.7.6
<del>Last tested for: spaCy 1.7.6
<add>Last updated for: spaCy 2.0.0a13
<ide> """
<ide> from __future__ import unicode_literals, print_function
<ide>
<ide> import random
<ide>
<ide> import spacy
<del>from spacy.gold import GoldParse
<del>from spacy.tagger import Tagger
<add>from spacy.gold import GoldParse, minibatch
<add>from spacy.pipeline import NeuralEntityRecognizer
<add>from spacy.pipeline import TokenVectorEncoder
<ide>
<ide>
<add>def get_gold_parses(tokenizer, train_data):
<add> '''Shuffle and create GoldParse objects'''
<add> random.shuffle(train_data)
<add> for raw_text, entity_offsets in train_data:
<add> doc = tokenizer(raw_text)
<add> gold = GoldParse(doc, entities=entity_offsets)
<add> yield doc, gold
<add>
<add>
<ide> def train_ner(nlp, train_data, output_dir):
<del> # Add new words to vocab
<del> for raw_text, _ in train_data:
<del> doc = nlp.make_doc(raw_text)
<del> for word in doc:
<del> _ = nlp.vocab[word.orth]
<ide> random.seed(0)
<del> # You may need to change the learning rate. It's generally difficult to
<del> # guess what rate you should set, especially when you have limited data.
<del> nlp.entity.model.learn_rate = 0.001
<del> for itn in range(1000):
<del> random.shuffle(train_data)
<del> loss = 0.
<del> for raw_text, entity_offsets in train_data:
<del> gold = GoldParse(doc, entities=entity_offsets)
<del> # By default, the GoldParse class assumes that the entities
<del> # described by offset are complete, and all other words should
<del> # have the tag 'O'. You can tell it to make no assumptions
<del> # about the tag of a word by giving it the tag '-'.
<del> # However, this allows a trivial solution to the current
<del> # learning problem: if words are either 'any tag' or 'ANIMAL',
<del> # the model can learn that all words can be tagged 'ANIMAL'.
<del> #for i in range(len(gold.ner)):
<del> #if not gold.ner[i].endswith('ANIMAL'):
<del> # gold.ner[i] = '-'
<del> doc = nlp.make_doc(raw_text)
<del> nlp.tagger(doc)
<del> # As of 1.9, spaCy's parser now lets you supply a dropout probability
<del> # This might help the model generalize better from only a few
<del> # examples.
<del> loss += nlp.entity.update(doc, gold, drop=0.9)
<del> if loss == 0:
<del> break
<del> # This step averages the model's weights. This may or may not be good for
<del> # your situation --- it's empirical.
<del> nlp.end_training()
<del> if output_dir:
<del> if not output_dir.exists():
<del> output_dir.mkdir()
<del> nlp.save_to_directory(output_dir)
<add> optimizer = nlp.begin_training(lambda: [])
<add> nlp.meta['name'] = 'en_ent_animal'
<add> for itn in range(50):
<add> losses = {}
<add> for batch in minibatch(get_gold_parses(nlp.make_doc, train_data), size=3):
<add> docs, golds = zip(*batch)
<add> nlp.update(docs, golds, losses=losses, sgd=optimizer, update_shared=True,
<add> drop=0.35)
<add> print(losses)
<add> if not output_dir:
<add> return
<add> elif not output_dir.exists():
<add> output_dir.mkdir()
<add> nlp.to_disk(output_dir)
<ide>
<ide>
<ide> def main(model_name, output_directory=None):
<del> print("Loading initial model", model_name)
<del> nlp = spacy.load(model_name)
<add> print("Creating initial model", model_name)
<add> nlp = spacy.blank(model_name)
<ide> if output_directory is not None:
<ide> output_directory = Path(output_directory)
<ide>
<ide> def main(model_name, output_directory=None):
<ide> "Horses are too tall and they pretend to care about your feelings",
<ide> [(0, 6, 'ANIMAL')],
<ide> ),
<add> (
<add> "Do they bite?",
<add> [],
<add> ),
<add>
<ide> (
<ide> "horses are too tall and they pretend to care about your feelings",
<ide> [(0, 6, 'ANIMAL')]
<ide> def main(model_name, output_directory=None):
<ide> )
<ide>
<ide> ]
<del> nlp.entity.add_label('ANIMAL')
<add> nlp.pipeline.append(TokenVectorEncoder(nlp.vocab))
<add> nlp.pipeline.append(NeuralEntityRecognizer(nlp.vocab))
<add> nlp.pipeline[-1].add_label('ANIMAL')
<ide> train_ner(nlp, train_data, output_directory)
<ide>
<ide> # Test that the entity is recognized
<del> doc = nlp('Do you like horses?')
<add> text = 'Do you like horses?'
<ide> print("Ents in 'Do you like horses?':")
<add> doc = nlp(text)
<ide> for ent in doc.ents:
<ide> print(ent.label_, ent.text)
<ide> if output_directory:
<ide> print("Loading from", output_directory)
<del> nlp2 = spacy.load('en', path=output_directory)
<del> nlp2.entity.add_label('ANIMAL')
<add> nlp2 = spacy.load(output_directory)
<ide> doc2 = nlp2('Do you like horses?')
<ide> for ent in doc2.ents:
<ide> print(ent.label_, ent.text) | 1 |
PHP | PHP | fix incorrect formatting in treebehavior | a63dd9ee9d7e58b9df6fe4110120e9f1b40f5275 | <ide><path>lib/Cake/Model/Behavior/TreeBehavior.php
<ide> public function generateTreeList(Model $Model, $conditions = null, $keyPath = nu
<ide> $valuePath = array('%s%s', '{n}.tree_prefix', $valuePath);
<ide>
<ide> } else {
<del> $valuePath[0] = '{' . (count($valuePath) - 1) . '}' . $valuePath[0];
<del> $valuePath[] = '{n}.tree_prefix';
<add> array_unshift($valuePath, '%s' . $valuePath[0], '{n}.tree_prefix');
<ide> }
<ide> $order = $Model->alias . '.' . $left . ' asc';
<ide> $results = $Model->find('all', compact('conditions', 'fields', 'order', 'recursive'));
<ide><path>lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php
<ide> public function testGenerateTreeListWithSelfJoin() {
<ide> $this->assertSame($expected, $result);
<ide> }
<ide>
<add>/**
<add> * Test the formatting options of generateTreeList()
<add> *
<add> * @return void
<add> */
<add> public function testGenerateTreeListFormatting() {
<add> extract($this->settings);
<add> $this->Tree = new $modelClass();
<add> $this->Tree->initialize(2, 2);
<add>
<add> $result = $this->Tree->generateTreeList(
<add> null,
<add> "{n}.$modelClass.id",
<add> array('%s - %s', "{n}.$modelClass.id", "{n}.$modelClass.name")
<add> );
<add> $this->assertEquals('1 - 1. Root', $result[1]);
<add> $this->assertEquals('_2 - 1.1', $result[2]);
<add> $this->assertEquals('__3 - 1.1.1', $result[3]);
<add> }
<add>
<ide> /**
<ide> * testArraySyntax method
<ide> * | 2 |
PHP | PHP | use database manager in db session driver | fe0502ded91ccf41733228dc4c423142fa100aa4 | <ide><path>system/session/db.php
<ide> <?php namespace System\Session;
<ide>
<ide> use System\Config;
<add>use System\DB\Manager;
<ide>
<ide> class DB implements Driver {
<ide>
<ide> public function sweep($expiration)
<ide> */
<ide> private function table()
<ide> {
<del> return \System\DB::table(Config::get('session.table'));
<add> return Manager::connection()->table(Config::get('session.table'));
<ide> }
<ide>
<ide> }
<ide>\ No newline at end of file | 1 |
Javascript | Javascript | fix win32 relative() when "to" is a prefix | b33879d9e287aab0129e8d67ceb4852b9d1be48e | <ide><path>lib/path.js
<ide> const win32 = {
<ide> var i = 0;
<ide> for (; i <= length; ++i) {
<ide> if (i === length) {
<del> if (lastCommonSep > 2 && // ignore separator match following device root
<del> toLen > length &&
<del> to.charCodeAt(i) === 92/*\*/) {
<del> // We get here if `from` is the exact base path for `to`.
<del> // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz'
<del> return toOrig.slice(i + 1);
<add> if (toLen > length) {
<add> if (to.charCodeAt(toStart + i) === 92/*\*/) {
<add> // We get here if `from` is the exact base path for `to`.
<add> // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz'
<add> return toOrig.slice(toStart + i + 1);
<add> } else if (lastCommonSep === 2) {
<add> // We get here if `from` is the device root.
<add> // For example: from='C:\\'; to='C:\\foo'
<add> return toOrig.slice(toStart + i);
<add> }
<add> }
<add> if (fromLen > length) {
<add> if (from.charCodeAt(fromStart + i) === 92/*\*/) {
<add> // We get here if `to` is the exact base path for `from`.
<add> // For example: from='C:\\foo\\bar'; to='C:\\foo'
<add> lastCommonSep = i;
<add> } else if (lastCommonSep === 2) {
<add> // We get here if `to` is the device root.
<add> // For example: from='C:\\foo\\bar'; to='C:\\'
<add> lastCommonSep = 3;
<add> }
<ide> }
<del> lastCommonSep = i;
<ide> break;
<ide> }
<ide> var fromCode = from.charCodeAt(fromStart + i);
<ide><path>test/parallel/test-path.js
<ide> const relativeTests = [
<ide> ['c:/AaAa/bbbb', 'c:/aaaa/bbbb', ''],
<ide> ['c:/aaaaa/', 'c:/aaaa/cccc', '..\\aaaa\\cccc'],
<ide> ['C:\\foo\\bar\\baz\\quux', 'C:\\', '..\\..\\..\\..'],
<del> ['C:\\foo\\test', 'C:\\foo\\test\\bar\\package.json', 'bar\\package.json']
<add> ['C:\\foo\\test', 'C:\\foo\\test\\bar\\package.json', 'bar\\package.json'],
<add> ['C:\\foo\\bar\\baz-quux', 'C:\\foo\\bar\\baz', '..\\baz']
<ide> ]
<ide> ],
<ide> [ path.posix.relative, | 2 |
Python | Python | allow rawqueryset serialization | b689db17b3c1ef5a2bca3a7fa90d3381bd5ba4fe | <ide><path>djangorestframework/serializer.py
<ide> Customizable serialization.
<ide> """
<ide> from django.db import models
<del>from django.db.models.query import QuerySet
<add>from django.db.models.query import QuerySet, RawQuerySet
<ide> from django.utils.encoding import smart_unicode, is_protected_type, smart_str
<ide>
<ide> import inspect
<ide> def serialize(self, obj):
<ide> if isinstance(obj, (dict, models.Model)):
<ide> # Model instances & dictionaries
<ide> return self.serialize_model(obj)
<del> elif isinstance(obj, (tuple, list, set, QuerySet, types.GeneratorType)):
<add> elif isinstance(obj, (tuple, list, set, QuerySet, RawQuerySet, types.GeneratorType)):
<ide> # basic iterables
<ide> return self.serialize_iter(obj)
<ide> elif isinstance(obj, models.Manager): | 1 |
Python | Python | remove defaults to none if optional | 77f4c46b501322e9bffb5416dfbf0397deefd7d8 | <ide><path>examples/research_projects/wav2vec2/run_asr.py
<ide> class Orthography:
<ide> Args:
<ide> do_lower_case (:obj:`bool`, `optional`, defaults to :obj:`False`):
<ide> Whether or not to accept lowercase input and lowercase the output when decoding.
<del> vocab_file (:obj:`str`, `optional`, defaults to :obj:`None`):
<add> vocab_file (:obj:`str`, `optional`):
<ide> File containing the vocabulary.
<ide> word_delimiter_token (:obj:`str`, `optional`, defaults to :obj:`"|"`):
<ide> The token used for delimiting words; it needs to be in the vocabulary.
<ide> translation_table (:obj:`Dict[str, str]`, `optional`, defaults to :obj:`{}`):
<ide> Table to use with `str.translate()` when preprocessing text (e.g., "-" -> " ").
<ide> words_to_remove (:obj:`Set[str]`, `optional`, defaults to :obj:`set()`):
<ide> Words to remove when preprocessing text (e.g., "sil").
<del> untransliterator (:obj:`Callable[[str], str]`, `optional`, defaults to :obj:`None`):
<add> untransliterator (:obj:`Callable[[str], str]`, `optional`):
<ide> Function that untransliterates text back into native writing system.
<ide> """
<ide>
<ide><path>src/transformers/debug_utils.py
<ide> class DebugUnderflowOverflow:
<ide> How many frames back to record
<ide> trace_batch_nums(:obj:`List[int]`, `optional`, defaults to ``[]``):
<ide> Which batch numbers to trace (turns detection off)
<del> abort_after_batch_num (:obj:`int`, `optional`, defaults to :obj:`None`):
<add> abort_after_batch_num (:obj:`int`, `optional`):
<ide> Whether to abort after a certain batch number has finished
<ide>
<ide> """
<ide><path>src/transformers/modeling_tf_utils.py
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
<ide> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
<ide> git-based system for storing models and other artifacts on huggingface.co, so ``revision`` can be any
<ide> identifier allowed by git.
<del> mirror(:obj:`str`, `optional`, defaults to :obj:`None`):
<add> mirror(:obj:`str`, `optional`):
<ide> Mirror source to accelerate downloads in China. If you are from China and have an accessibility
<ide> problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety.
<ide> Please refer to the mirror site for more information.
<ide><path>src/transformers/modeling_utils.py
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P
<ide> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
<ide> git-based system for storing models and other artifacts on huggingface.co, so ``revision`` can be any
<ide> identifier allowed by git.
<del> mirror(:obj:`str`, `optional`, defaults to :obj:`None`):
<add> mirror(:obj:`str`, `optional`):
<ide> Mirror source to accelerate downloads in China. If you are from China and have an accessibility
<ide> problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety.
<ide> Please refer to the mirror site for more information.
<ide><path>src/transformers/models/albert/tokenization_albert_fast.py
<ide> def build_inputs_with_special_tokens(
<ide> Args:
<ide> token_ids_0 (:obj:`List[int]`):
<ide> List of IDs to which the special tokens will be added
<del> token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
<add> token_ids_1 (:obj:`List[int]`, `optional`):
<ide> Optional second list of IDs for sequence pairs.
<ide>
<ide> Returns:
<ide> def create_token_type_ids_from_sequences(
<ide> Args:
<ide> token_ids_0 (:obj:`List[int]`):
<ide> List of ids.
<del> token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
<add> token_ids_1 (:obj:`List[int]`, `optional`):
<ide> Optional second list of IDs for sequence pairs.
<ide>
<ide> Returns:
<ide><path>src/transformers/models/big_bird/tokenization_big_bird_fast.py
<ide> def build_inputs_with_special_tokens(
<ide> Args:
<ide> token_ids_0 (:obj:`List[int]`):
<ide> List of IDs to which the special tokens will be added
<del> token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
<add> token_ids_1 (:obj:`List[int]`, `optional`):
<ide> Optional second list of IDs for sequence pairs.
<ide>
<ide> Returns:
<ide> def get_special_tokens_mask(
<ide> Args:
<ide> token_ids_0 (:obj:`List[int]`):
<ide> List of ids.
<del> token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
<add> token_ids_1 (:obj:`List[int]`, `optional`):
<ide> Optional second list of IDs for sequence pairs.
<ide> already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
<ide> Set to True if the token list is already formatted with special tokens for the model
<ide> def create_token_type_ids_from_sequences(
<ide> Args:
<ide> token_ids_0 (:obj:`List[int]`):
<ide> List of ids.
<del> token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
<add> token_ids_1 (:obj:`List[int]`, `optional`):
<ide> Optional second list of IDs for sequence pairs.
<ide>
<ide> Returns:
<ide><path>src/transformers/models/ibert/quant_modules.py
<ide> class QuantAct(nn.Module):
<ide> Momentum for updating the activation quantization range.
<ide> per_channel (:obj:`bool`, `optional`, defaults to :obj:`False`):
<ide> Whether to or not use channel-wise quantization.
<del> channel_len (:obj:`int`, `optional`, defaults to :obj:`None`):
<add> channel_len (:obj:`int`, `optional`):
<ide> Specify the channel length when set the `per_channel` True.
<ide> quant_mode (:obj:`bool`, `optional`, defaults to :obj:`False`):
<ide> Whether or not the layer is quantized.
<ide> class FixedPointMul(Function):
<ide> Quantization bitwidth.
<ide> z_scaling_factor (:obj:`torch.Tensor`):
<ide> Scaling factor of the output tensor.
<del> identity (:obj:`torch.Tensor`, `optional`, defaults to :obj:`None`):
<add> identity (:obj:`torch.Tensor`, `optional`):
<ide> Identity tensor, if exists.
<del> identity_scaling_factor (:obj:`torch.Tensor`, `optional`, defaults to :obj:`None`):
<add> identity_scaling_factor (:obj:`torch.Tensor`, `optional`):
<ide> Scaling factor of the identity tensor `identity`, if exists.
<ide>
<ide> Returns:
<ide><path>src/transformers/models/mpnet/modeling_mpnet.py
<ide> def forward(self, hidden_states):
<ide> details.
<ide>
<ide> `What are input IDs? <../glossary.html#input-ids>`__
<del> attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
<add> attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide> Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<ide><path>src/transformers/models/mpnet/tokenization_mpnet.py
<ide> def build_inputs_with_special_tokens(
<ide> Args:
<ide> token_ids_0 (:obj:`List[int]`):
<ide> List of IDs to which the special tokens will be added
<del> token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
<add> token_ids_1 (:obj:`List[int]`, `optional`):
<ide> Optional second list of IDs for sequence pairs.
<ide>
<ide> Returns:
<ide><path>src/transformers/models/xlm_prophetnet/tokenization_xlm_prophetnet.py
<ide> def build_inputs_with_special_tokens(
<ide> Args:
<ide> token_ids_0 (:obj:`List[int]`):
<ide> List of IDs to which the special tokens will be added
<del> token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
<add> token_ids_1 (:obj:`List[int]`, `optional`):
<ide> Optional second list of IDs for sequence pairs.
<ide>
<ide> Returns:
<ide><path>src/transformers/pipelines/text2text_generation.py
<ide> def __call__(
<ide> Whether or not to include the decoded texts in the outputs.
<ide> clean_up_tokenization_spaces (:obj:`bool`, `optional`, defaults to :obj:`False`):
<ide> Whether or not to clean up the potential extra spaces in the text output.
<del> src_lang (:obj:`str`, `optional`, defaults to :obj:`None`):
<add> src_lang (:obj:`str`, `optional`):
<ide> The language of the input. Might be required for multilingual models. Will not have any effect for
<ide> single pair translation models
<del> tgt_lang (:obj:`str`, `optional`, defaults to :obj:`None`):
<add> tgt_lang (:obj:`str`, `optional`):
<ide> The language of the desired output. Might be required for multilingual models. Will not have any effect
<ide> for single pair translation models
<ide> generate_kwargs: | 11 |
Javascript | Javascript | add mandatory setter assertion | 1d03e01b8e6dc7458575a31b6721d643ef8482ba | <ide><path>packages/ember-debug/lib/main.js
<ide> if ('undefined' === typeof Ember) {
<ide> }
<ide> }
<ide>
<add>Ember.ENV = 'undefined' === typeof ENV ? {} : ENV;
<add>
<add>if (!('MANDATORY_SETTER' in Ember.ENV)) {
<add> //Ember.ENV.MANDATORY_SETTER = 'defineProperty' in Object;
<add> Ember.ENV.MANDATORY_SETTER = false;
<add>}
<add>
<ide> /**
<ide> Define an assertion that will throw an exception if the condition is not
<ide> met. Ember build tools will remove any calls to Ember.assert() when
<ide><path>packages/ember-metal/lib/accessors.js
<ide> require('ember-metal/utils');
<ide>
<ide> var META_KEY = Ember.META_KEY, get, set;
<ide>
<add>var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER;
<add>
<ide> // ..........................................................
<ide> // GET AND SET
<ide> //
<ide> get = function get(obj, keyName) {
<ide> return obj.unknownProperty(keyName);
<ide> }
<ide>
<add> if (MANDATORY_SETTER && meta && meta.watching[keyName] > 0) { return meta.values[keyName]; }
<ide> return obj[keyName];
<ide> }
<ide> };
<ide> get = function get(obj, keyName) {
<ide> set = function set(obj, keyName, value) {
<ide> Ember.assert("You need to provide an object and key to `set`.", !!obj && keyName !== undefined);
<ide>
<add> if (obj.isDestroyed) return;
<add>
<ide> var meta = obj[META_KEY], desc = meta && meta.descs[keyName];
<ide> if (desc) {
<ide> desc.set(obj, keyName, value);
<ide> set = function set(obj, keyName, value) {
<ide> // `setUnknownProperty` method exists on the object
<ide> if (isUnknown && 'function' === typeof obj.setUnknownProperty) {
<ide> obj.setUnknownProperty(keyName, value);
<del> } else if (meta && meta.watching[keyName]) {
<add> } else if (meta && meta.watching[keyName] > 0) {
<ide> // only trigger a change if the value has changed
<ide> if (value !== obj[keyName]) {
<ide> Ember.propertyWillChange(obj, keyName);
<del> obj[keyName] = value;
<add> if (MANDATORY_SETTER) {
<add> meta.values[keyName] = value;
<add> } else {
<add> obj[keyName] = value;
<add> }
<ide> Ember.propertyDidChange(obj, keyName);
<ide> }
<ide> } else {
<ide><path>packages/ember-metal/lib/computed.js
<ide> ComputedPropertyPrototype.didChange = function(obj, keyName) {
<ide> var meta = metaFor(obj);
<ide> if (keyName in meta.cache) {
<ide> delete meta.cache[keyName];
<del> if (!meta.watching[keyName]) {
<add> if (!(meta.watching[keyName] > 0)) {
<ide> removeDependentKeys(this, obj, keyName, meta);
<ide> }
<ide> }
<ide> ComputedPropertyPrototype.get = function(obj, keyName) {
<ide> cache = meta.cache;
<ide> if (keyName in cache) { return cache[keyName]; }
<ide> ret = cache[keyName] = this.func.call(obj, keyName);
<del> if (!meta.watching[keyName]) {
<add> if (!(meta.watching[keyName] > 0)) {
<ide> addDependentKeys(this, obj, keyName, meta);
<ide> }
<ide> } else {
<ide><path>packages/ember-metal/lib/mixin.js
<ide> var Mixin, REQUIRED, Alias,
<ide> EMPTY_META = {}, // dummy for non-writable meta
<ide> META_SKIP = { __emberproto__: true, __ember_count__: true },
<ide> o_create = Ember.create,
<add> defineProperty = Ember.defineProperty,
<ide> guidFor = Ember.guidFor;
<ide>
<ide> /** @private */
<ide> function finishPartial(obj, m) {
<ide> /** @private */
<ide> function applyMixin(obj, mixins, partial) {
<ide> var descs = {}, values = {}, m = Ember.meta(obj), req = m.required,
<del> key, value, desc,
<del> prevDesc, prevValue, paths, len, idx;
<add> key, value, desc, prevValue, paths, len, idx;
<ide>
<ide> // Go through all mixins and hashes passed in, and:
<ide> //
<ide> function applyMixin(obj, mixins, partial) {
<ide>
<ide> detectBinding(obj, key, value, m);
<ide>
<del> // Ember.defineProperty
<del> prevDesc = m.descs[key];
<del> if (prevDesc && !(key in Object.prototype)) {
<del> prevDesc.teardown(obj, key);
<del> }
<del>
<del> m.descs[key] = desc;
<del> obj[key] = value;
<del>
<del> if (desc) {
<del> desc.setup(obj, key);
<del> }
<del> // Ember.defineProperty
<add> defineProperty(obj, key, desc, value, m);
<ide>
<ide> if ('function' === typeof value) {
<ide> if (paths = value.__ember_observesBefore__) {
<ide> function applyMixin(obj, mixins, partial) {
<ide> req.__ember_count__--;
<ide> req[key] = false;
<ide> }
<del>
<del> if (m.watching[key]) {
<del> Ember.overrideChains(obj, key, m);
<del> }
<ide> }
<ide> }
<ide>
<ide><path>packages/ember-metal/lib/properties.js
<ide> var GUID_KEY = Ember.GUID_KEY,
<ide> o_create = Ember.create,
<ide> objectDefineProperty = Ember.platform.defineProperty;
<ide>
<add>var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER;
<add>
<ide> // ..........................................................
<ide> // DESCRIPTOR
<ide> //
<ide> var Descriptor = Ember.Descriptor = function() {};
<ide> return this.firstName+' '+this.lastName;
<ide> }).property('firstName', 'lastName').cacheable());
<ide> */
<del>Ember.defineProperty = function(obj, keyName, desc, val) {
<del> var meta = metaFor(obj),
<del> descs = meta.descs,
<del> existingDesc = meta.descs[keyName];
<add>Ember.defineProperty = function(obj, keyName, desc, val, meta) {
<add> var descs, existingDesc, watching;
<add>
<add> if (!meta) meta = metaFor(obj);
<add> descs = meta.descs;
<add> existingDesc = meta.descs[keyName];
<add> watching = meta.watching[keyName] > 0;
<ide>
<ide> if (existingDesc instanceof Ember.Descriptor) {
<ide> existingDesc.teardown(obj, keyName);
<ide> }
<ide>
<ide> if (desc instanceof Ember.Descriptor) {
<ide> descs[keyName] = desc;
<del> obj[keyName] = undefined; // make enumerable
<add> if (MANDATORY_SETTER && watching) {
<add> objectDefineProperty(obj, keyName, {
<add> configurable: true,
<add> enumerable: true,
<add> writable: true,
<add> value: undefined // make enumerable
<add> });
<add> } else {
<add> obj[keyName] = undefined; // make enumerable
<add> }
<ide> desc.setup(obj, keyName);
<ide> } else {
<ide> descs[keyName] = undefined; // shadow descriptor in proto
<ide> if (desc == null) {
<del> obj[keyName] = val;
<add> if (MANDATORY_SETTER && watching) {
<add> meta.values[keyName] = val;
<add> } else {
<add> obj[keyName] = val;
<add> }
<ide> } else {
<ide> // compatibility with ES5
<ide> objectDefineProperty(obj, keyName, desc);
<ide> Ember.defineProperty = function(obj, keyName, desc, val) {
<ide>
<ide> // if key is being watched, override chains that
<ide> // were initialized with the prototype
<del> if (meta.watching[keyName]) { Ember.overrideChains(obj, keyName, meta); }
<add> if (watching) { Ember.overrideChains(obj, keyName, meta); }
<ide>
<ide> return this;
<ide> };
<ide><path>packages/ember-metal/lib/utils.js
<ide> var o_defineProperty = Ember.platform.defineProperty,
<ide> numberCache = [],
<ide> stringCache = {};
<ide>
<add>var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER;
<add>
<ide> /**
<ide> @private
<ide> @static
<ide> var EMPTY_META = {
<ide> watching: {}
<ide> };
<ide>
<add>if (MANDATORY_SETTER) { EMPTY_META.values = {}; }
<add>
<ide> Ember.EMPTY_META = EMPTY_META;
<ide>
<ide> if (Object.freeze) Object.freeze(EMPTY_META);
<ide> Ember.meta = function meta(obj, writable) {
<ide> source: obj
<ide> };
<ide>
<add> if (MANDATORY_SETTER) { ret.values = {}; }
<add>
<ide> obj[META_KEY] = ret;
<ide>
<ide> // make sure we don't accidentally try to create constructor like desc
<ide> Ember.meta = function meta(obj, writable) {
<ide> ret.cache = {};
<ide> ret.source = obj;
<ide>
<add> if (MANDATORY_SETTER) { ret.values = o_create(ret.values); }
<add>
<ide> obj[META_KEY] = ret;
<ide> }
<ide> return ret;
<ide><path>packages/ember-metal/lib/watching.js
<ide> var guidFor = Ember.guidFor, // utils.js
<ide> FIRST_KEY = /^([^\.\*]+)/,
<ide> IS_PATH = /[\.\*]/;
<ide>
<add>var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER,
<add>o_defineProperty = Ember.platform.defineProperty;
<add>
<ide> /** @private */
<ide> function firstKey(path) {
<ide> return path.match(FIRST_KEY)[0];
<ide> Ember.watch = function(obj, keyName) {
<ide> if ('function' === typeof obj.willWatchProperty) {
<ide> obj.willWatchProperty(keyName);
<ide> }
<add>
<add> if (MANDATORY_SETTER && keyName in obj) {
<add> m.values[keyName] = obj[keyName];
<add> o_defineProperty(obj, keyName, {
<add> configurable: true,
<add> enumerable: true,
<add> set: function() {
<add> if (this.isDestroyed) {
<add> Ember.assert('You cannot set observed properties on destroyed objects', false);
<add> } else {
<add> Ember.assert('Must use Ember.set() to access this property', false);
<add> }
<add> },
<add> get: function() {
<add> var meta = this[META_KEY];
<add> return meta && meta.values[keyName];
<add> }
<add> });
<add> }
<ide> } else {
<ide> chainsFor(obj).add(keyName);
<ide> }
<ide> Ember.unwatch = function(obj, keyName) {
<ide> if ('function' === typeof obj.didUnwatchProperty) {
<ide> obj.didUnwatchProperty(keyName);
<ide> }
<add>
<add> if (MANDATORY_SETTER && keyName in obj) {
<add> o_defineProperty(obj, keyName, {
<add> configurable: true,
<add> enumerable: true,
<add> writable: true,
<add> value: m.values[keyName]
<add> });
<add> }
<ide> } else {
<ide> chainsFor(obj).remove(keyName);
<ide> } | 7 |
PHP | PHP | add tests for app environment helpers | 9b28de1cd6431b2aa17558755e71b10677da060d | <ide><path>tests/Foundation/FoundationApplicationTest.php
<ide> public function testEnvironment()
<ide> $this->assertFalse($app->environment(['qux', 'bar']));
<ide> }
<ide>
<add> public function testEnvironmentHelpers()
<add> {
<add> $local = new Application;
<add> $local['env'] = 'local';
<add>
<add> $this->assertTrue($local->isLocal());
<add> $this->assertFalse($local->isProduction());
<add> $this->assertFalse($local->runningUnitTests());
<add>
<add> $production = new Application;
<add> $production['env'] = 'production';
<add>
<add> $this->assertTrue($production->isProduction());
<add> $this->assertFalse($production->isLocal());
<add> $this->assertFalse($production->runningUnitTests());
<add>
<add> $testing = new Application;
<add> $testing['env'] = 'testing';
<add>
<add> $this->assertTrue($testing->runningUnitTests());
<add> $this->assertFalse($testing->isLocal());
<add> $this->assertFalse($testing->isProduction());
<add> }
<add>
<ide> public function testMethodAfterLoadingEnvironmentAddsClosure()
<ide> {
<ide> $app = new Application; | 1 |
Javascript | Javascript | add guard around focuswithin responder root events | b6c94d636cb33a265671b864b97870da38d97207 | <ide><path>packages/react-interactions/events/src/dom/Focus.js
<ide> type FocusState = {
<ide> isFocused: boolean,
<ide> isFocusVisible: boolean,
<ide> pointerType: PointerType,
<del> ...
<add> addedRootEvents?: boolean,
<ide> };
<ide>
<ide> type FocusProps = {
<ide> const focusResponderImpl = {
<ide> isFocused: false,
<ide> isFocusVisible: false,
<ide> pointerType: '',
<add> addedRootEvents: false,
<ide> };
<ide> },
<ide> onMount() {
<ide> const focusWithinResponderImpl = {
<ide> onBeforeBlurWithin,
<ide> DiscreteEvent,
<ide> );
<del> context.addRootEventTypes(rootEventTypes);
<add> if (!state.addedRootEvents) {
<add> state.addedRootEvents = true;
<add> context.addRootEventTypes(rootEventTypes);
<add> }
<ide> } else {
<ide> // We want to propagate to next focusWithin responder
<ide> // if this responder doesn't handle beforeblur
<ide> const focusWithinResponderImpl = {
<ide> if (detachedTarget !== null && detachedTarget === event.target) {
<ide> dispatchBlurWithinEvents(context, event, props, state);
<ide> state.detachedTarget = null;
<del> context.removeRootEventTypes(rootEventTypes);
<add> if (state.addedRootEvents) {
<add> state.addedRootEvents = false;
<add> context.removeRootEventTypes(rootEventTypes);
<add> }
<ide> }
<ide> }
<ide> }, | 1 |
Ruby | Ruby | recommend python .pth file instead | d8ef8d4f82417459af359109d33d2d2a4e1cb693 | <ide><path>Library/Homebrew/caveats.rb
<ide> def zsh_completion_caveats
<ide> end
<ide>
<ide> def python_caveats
<add> return unless keg
<add> return unless keg.python_site_packages_installed?
<add> return if Formula["python"].installed?
<ide> site_packages = if f.keg_only?
<ide> "#{f.opt_prefix}/lib/python2.7/site-packages"
<ide> else
<ide> "#{HOMEBREW_PREFIX}/lib/python2.7/site-packages"
<ide> end
<del> if keg and keg.python_site_packages_installed? \
<del> and !ENV['PYTHONPATH'].to_s.include? site_packages
<del> <<-EOS.undent
<del> Set PYTHONPATH if you need Python to find the installed site-packages:
<del> export PYTHONPATH=#{site_packages}:$PYTHONPATH
<del> EOS
<add> dir = "~/Library/Python/2.7/lib/python/site-packages"
<add> dir_path = Pathname.new(dir).expand_path
<add> file = "#{dir}/homebrew.pth"
<add> file_path = Pathname.new(file).expand_path
<add> if !file_path.readable? || !file_path.read.include?(site_packages)
<add> s = "If you need Python to find the installed site-packages:\n"
<add> s += " mkdir -p #{dir}\n" unless dir_path.exist?
<add> s += " echo '#{site_packages}' >> #{file}"
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | increase coverage for lib/events.js | a912b791d4dd10d694c8b278fea9345f377adf58 | <ide><path>test/parallel/test-event-emitter-listeners.js
<ide> require('../common');
<ide> const assert = require('assert');
<ide> const events = require('events');
<add>const util = require('util');
<ide>
<ide> function listener() {}
<ide> function listener2() {}
<add>class TestStream { constructor() { } }
<add>util.inherits(TestStream, events.EventEmitter);
<ide>
<ide> {
<ide> const ee = new events.EventEmitter();
<ide> function listener2() {}
<ide> ee.once('foo', listener2);
<ide> assert.deepStrictEqual(ee.listeners('foo'), [listener, listener2]);
<ide> }
<add>
<add>{
<add> const ee = new events.EventEmitter();
<add> ee._events = undefined;
<add> assert.deepStrictEqual(ee.listeners('foo'), []);
<add>}
<add>
<add>{
<add> const s = new TestStream();
<add> assert.deepStrictEqual(s.listeners('foo'), []);
<add>} | 1 |
Javascript | Javascript | fix a typo in comment | 86727b15f3f1d33a077e4044991264be74497b37 | <ide><path>lib/child_process.js
<ide> exports.exec = function (command /*, options, callback */) {
<ide> };
<ide>
<ide>
<del>// execFile("something.sh", { env: ENV }, funciton() { })
<add>// execFile("something.sh", { env: ENV }, function() { })
<ide>
<ide> exports.execFile = function (file /* args, options, callback */) {
<ide> var options = { encoding: 'utf8' | 1 |
Ruby | Ruby | preserve backtrace from original exception | a9556651022a92ae8134b1efbfa67831d5eb2e5e | <ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> def determine_path
<ide> when "gcc-4.2"
<ide> begin
<ide> apple_gcc42 = Formulary.factory('apple-gcc42')
<del> rescue Exception # in --debug, catch bare exceptions too
<add> rescue FormulaUnavailableError
<ide> end
<ide> paths << apple_gcc42.opt_bin.to_s if apple_gcc42
<ide> when GNU_GCC_REGEXP
<ide><path>Library/Homebrew/formulary.rb
<ide> def get_formula(spec)
<ide> def klass
<ide> begin
<ide> have_klass = Formulary.formula_class_defined? class_name
<del> rescue NameError
<del> raise FormulaUnavailableError.new(name)
<add> rescue NameError => e
<add> raise FormulaUnavailableError, name, e.backtrace
<ide> end
<ide>
<ide> load_file unless have_klass
<ide> def load_file
<ide> # This is a programming error in an existing formula, and should not
<ide> # have a "no such formula" message.
<ide> raise
<del> rescue LoadError, NameError
<del> raise if ARGV.debug? # let's see the REAL error
<del> raise FormulaUnavailableError.new(name)
<add> rescue LoadError, NameError => e
<add> raise FormulaUnavailableError, name, e.backtrace
<ide> end
<ide> end
<ide> end
<ide> def initialize tapped_name
<ide>
<ide> def get_formula(spec)
<ide> super
<del> rescue FormulaUnavailableError
<del> raise TapFormulaUnavailableError.new(tapped_name)
<add> rescue FormulaUnavailableError => e
<add> raise TapFormulaUnavailableError, tapped_name, e.backtrace
<ide> end
<ide> end
<ide> | 2 |
Go | Go | reap failed nodes after 24 hours | e98b152bacafec4676161749785a5a5ff2fd4bc3 | <ide><path>libnetwork/networkdb/cluster.go
<ide> import (
<ide> )
<ide>
<ide> const (
<del> reapInterval = 60 * time.Second
<del> reapPeriod = 5 * time.Second
<del> retryInterval = 1 * time.Second
<add> reapInterval = 60 * time.Second
<add> reapPeriod = 5 * time.Second
<add> retryInterval = 1 * time.Second
<add> nodeReapInterval = 24 * time.Hour
<add> nodeReapPeriod = 2 * time.Hour
<ide> )
<ide>
<ide> type logWriter struct{}
<ide> func (nDB *NetworkDB) clusterInit() error {
<ide> {config.GossipInterval, nDB.gossip},
<ide> {config.PushPullInterval, nDB.bulkSyncTables},
<ide> {retryInterval, nDB.reconnectNode},
<add> {nodeReapPeriod, nDB.reapDeadNode},
<ide> } {
<ide> t := time.NewTicker(trigger.interval)
<ide> go nDB.triggerFunc(trigger.interval, t.C, nDB.stopCh, trigger.fn)
<ide> func (nDB *NetworkDB) triggerFunc(stagger time.Duration, C <-chan time.Time, sto
<ide> }
<ide> }
<ide>
<add>func (nDB *NetworkDB) reapDeadNode() {
<add> nDB.Lock()
<add> defer nDB.Unlock()
<add> for id, n := range nDB.failedNodes {
<add> if n.reapTime > 0 {
<add> n.reapTime -= reapPeriod
<add> continue
<add> }
<add> logrus.Debugf("Removing failed node %v from gossip cluster", n.Name)
<add> delete(nDB.failedNodes, id)
<add> }
<add>}
<add>
<ide> func (nDB *NetworkDB) reconnectNode() {
<ide> nDB.RLock()
<ide> if len(nDB.failedNodes) == 0 {
<ide><path>libnetwork/networkdb/event_delegate.go
<ide> func (e *eventDelegate) NotifyLeave(mn *memberlist.Node) {
<ide> e.nDB.Lock()
<ide> if n, ok := e.nDB.nodes[mn.Name]; ok {
<ide> delete(e.nDB.nodes, mn.Name)
<add>
<add> n.reapTime = reapInterval
<ide> e.nDB.failedNodes[mn.Name] = n
<ide> }
<ide> e.nDB.Unlock()
<ide><path>libnetwork/networkdb/networkdb.go
<ide> type NetworkDB struct {
<ide> type node struct {
<ide> memberlist.Node
<ide> ltime serf.LamportTime
<add> // Number of hours left before the reaper removes the node
<add> reapTime time.Duration
<ide> }
<ide>
<ide> // network describes the node/network attachment. | 3 |
Python | Python | add all xxxpretrainedmodel to the main init | 9eda6b52e20d80cf165224d996babc67f913017e | <ide><path>src/transformers/__init__.py
<ide> "DetrForObjectDetection",
<ide> "DetrForSegmentation",
<ide> "DetrModel",
<add> "DetrPreTrainedModel",
<ide> ]
<ide> )
<ide> else:
<ide> [
<ide> "BertGenerationDecoder",
<ide> "BertGenerationEncoder",
<add> "BertGenerationPreTrainedModel",
<ide> "load_tf_weights_in_bert_generation",
<ide> ]
<ide> )
<ide> "BigBirdPegasusForQuestionAnswering",
<ide> "BigBirdPegasusForSequenceClassification",
<ide> "BigBirdPegasusModel",
<add> "BigBirdPegasusPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.blenderbot"].extend(
<ide> "BlenderbotForCausalLM",
<ide> "BlenderbotForConditionalGeneration",
<ide> "BlenderbotModel",
<add> "BlenderbotPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.blenderbot_small"].extend(
<ide> "BlenderbotSmallForCausalLM",
<ide> "BlenderbotSmallForConditionalGeneration",
<ide> "BlenderbotSmallModel",
<add> "BlenderbotSmallPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.camembert"].extend(
<ide> "FunnelForSequenceClassification",
<ide> "FunnelForTokenClassification",
<ide> "FunnelModel",
<add> "FunnelPreTrainedModel",
<ide> "load_tf_weights_in_funnel",
<ide> ]
<ide> )
<ide> "LayoutLMForSequenceClassification",
<ide> "LayoutLMForTokenClassification",
<ide> "LayoutLMModel",
<add> "LayoutLMPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.led"].extend(
<ide> "LEDForQuestionAnswering",
<ide> "LEDForSequenceClassification",
<ide> "LEDModel",
<add> "LEDPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.longformer"].extend(
<ide> "LongformerForSequenceClassification",
<ide> "LongformerForTokenClassification",
<ide> "LongformerModel",
<add> "LongformerPreTrainedModel",
<ide> "LongformerSelfAttention",
<ide> ]
<ide> )
<ide> "M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST",
<ide> "M2M100ForConditionalGeneration",
<ide> "M2M100Model",
<add> "M2M100PreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.marian"].extend(["MarianForCausalLM", "MarianModel", "MarianMTModel"])
<ide> "MBartForQuestionAnswering",
<ide> "MBartForSequenceClassification",
<ide> "MBartModel",
<add> "MBartPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.megatron_bert"].extend(
<ide> "MegatronBertForSequenceClassification",
<ide> "MegatronBertForTokenClassification",
<ide> "MegatronBertModel",
<add> "MegatronBertPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.mmbt"].extend(["MMBTForClassification", "MMBTModel", "ModalEmbeddings"])
<ide> ]
<ide> )
<ide> _import_structure["models.pegasus"].extend(
<del> ["PegasusForCausalLM", "PegasusForConditionalGeneration", "PegasusModel"]
<add> ["PegasusForCausalLM", "PegasusForConditionalGeneration", "PegasusModel", "PegasusPreTrainedModel"]
<ide> )
<ide> _import_structure["models.prophetnet"].extend(
<ide> [
<ide> "ProphetNetPreTrainedModel",
<ide> ]
<ide> )
<del> _import_structure["models.rag"].extend(["RagModel", "RagSequenceForGeneration", "RagTokenForGeneration"])
<add> _import_structure["models.rag"].extend(
<add> ["RagModel", "RagPreTrainedModel", "RagSequenceForGeneration", "RagTokenForGeneration"]
<add> )
<ide> _import_structure["models.reformer"].extend(
<ide> [
<ide> "REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
<ide> "ReformerLayer",
<ide> "ReformerModel",
<ide> "ReformerModelWithLMHead",
<add> "ReformerPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.retribert"].extend(
<ide> "RobertaForSequenceClassification",
<ide> "RobertaForTokenClassification",
<ide> "RobertaModel",
<add> "RobertaPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.roformer"].extend(
<ide> "SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST",
<ide> "Speech2TextForConditionalGeneration",
<ide> "Speech2TextModel",
<add> "Speech2TextPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.squeezebert"].extend(
<ide> "TapasForQuestionAnswering",
<ide> "TapasForSequenceClassification",
<ide> "TapasModel",
<add> "TapasPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.transfo_xl"].extend(
<ide> "TFBertPreTrainedModel",
<ide> ]
<ide> )
<del> _import_structure["models.blenderbot"].extend(["TFBlenderbotForConditionalGeneration", "TFBlenderbotModel"])
<add> _import_structure["models.blenderbot"].extend(
<add> ["TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel"]
<add> )
<ide> _import_structure["models.blenderbot_small"].extend(
<del> ["TFBlenderbotSmallForConditionalGeneration", "TFBlenderbotSmallModel"]
<add> ["TFBlenderbotSmallForConditionalGeneration", "TFBlenderbotSmallModel", "TFBlenderbotSmallPreTrainedModel"]
<ide> )
<ide> _import_structure["models.camembert"].extend(
<ide> [
<ide> "TFFlaubertForSequenceClassification",
<ide> "TFFlaubertForTokenClassification",
<ide> "TFFlaubertModel",
<add> "TFFlaubertPreTrainedModel",
<ide> "TFFlaubertWithLMHeadModel",
<ide> ]
<ide> )
<ide> "TFFunnelForSequenceClassification",
<ide> "TFFunnelForTokenClassification",
<ide> "TFFunnelModel",
<add> "TFFunnelPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.gpt2"].extend(
<ide> "TFLongformerForSequenceClassification",
<ide> "TFLongformerForTokenClassification",
<ide> "TFLongformerModel",
<add> "TFLongformerPreTrainedModel",
<ide> "TFLongformerSelfAttention",
<ide> ]
<ide> )
<ide> "TFLxmertVisualFeatureEncoder",
<ide> ]
<ide> )
<del> _import_structure["models.marian"].extend(["TFMarianModel", "TFMarianMTModel"])
<del> _import_structure["models.mbart"].extend(["TFMBartForConditionalGeneration", "TFMBartModel"])
<add> _import_structure["models.marian"].extend(["TFMarianModel", "TFMarianMTModel", "TFMarianPreTrainedModel"])
<add> _import_structure["models.mbart"].extend(
<add> ["TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel"]
<add> )
<ide> _import_structure["models.mobilebert"].extend(
<ide> [
<ide> "TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
<ide> "TFOpenAIGPTPreTrainedModel",
<ide> ]
<ide> )
<del> _import_structure["models.pegasus"].extend(["TFPegasusForConditionalGeneration", "TFPegasusModel"])
<add> _import_structure["models.pegasus"].extend(
<add> ["TFPegasusForConditionalGeneration", "TFPegasusModel", "TFPegasusPreTrainedModel"]
<add> )
<ide> _import_structure["models.rag"].extend(
<ide> [
<ide> "TFRagModel",
<add> "TFRagPreTrainedModel",
<ide> "TFRagSequenceForGeneration",
<ide> "TFRagTokenForGeneration",
<ide> ]
<ide> "FlaxBartForQuestionAnswering",
<ide> "FlaxBartForSequenceClassification",
<ide> "FlaxBartModel",
<add> "FlaxBartPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.bert"].extend(
<ide> "FlaxCLIPModel",
<ide> "FlaxCLIPPreTrainedModel",
<ide> "FlaxCLIPTextModel",
<add> "FlaxCLIPTextPreTrainedModel",
<ide> "FlaxCLIPVisionModel",
<add> "FlaxCLIPVisionPreTrainedModel",
<ide> ]
<ide> )
<ide> _import_structure["models.electra"].extend(
<ide> "FlaxElectraPreTrainedModel",
<ide> ]
<ide> )
<del> _import_structure["models.gpt2"].extend(["FlaxGPT2LMHeadModel", "FlaxGPT2Model"])
<add> _import_structure["models.gpt2"].extend(["FlaxGPT2LMHeadModel", "FlaxGPT2Model", "FlaxGPT2PreTrainedModel"])
<ide> _import_structure["models.roberta"].extend(
<ide> [
<ide> "FlaxRobertaForMaskedLM",
<ide> "FlaxRobertaPreTrainedModel",
<ide> ]
<ide> )
<del> _import_structure["models.t5"].extend(["FlaxT5ForConditionalGeneration", "FlaxT5Model"])
<del> _import_structure["models.vit"].extend(["FlaxViTForImageClassification", "FlaxViTModel"])
<add> _import_structure["models.t5"].extend(["FlaxT5ForConditionalGeneration", "FlaxT5Model", "FlaxT5PreTrainedModel"])
<add> _import_structure["models.vit"].extend(["FlaxViTForImageClassification", "FlaxViTModel", "FlaxViTPreTrainedModel"])
<ide> else:
<ide> from .utils import dummy_flax_objects
<ide>
<ide> DetrForObjectDetection,
<ide> DetrForSegmentation,
<ide> DetrModel,
<add> DetrPreTrainedModel,
<ide> )
<ide> else:
<ide> from .utils.dummy_timm_objects import *
<ide> from .models.bert_generation import (
<ide> BertGenerationDecoder,
<ide> BertGenerationEncoder,
<add> BertGenerationPreTrainedModel,
<ide> load_tf_weights_in_bert_generation,
<ide> )
<ide> from .models.big_bird import (
<ide> BigBirdPegasusForQuestionAnswering,
<ide> BigBirdPegasusForSequenceClassification,
<ide> BigBirdPegasusModel,
<add> BigBirdPegasusPreTrainedModel,
<ide> )
<ide> from .models.blenderbot import (
<ide> BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> BlenderbotForCausalLM,
<ide> BlenderbotForConditionalGeneration,
<ide> BlenderbotModel,
<add> BlenderbotPreTrainedModel,
<ide> )
<ide> from .models.blenderbot_small import (
<ide> BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> BlenderbotSmallForCausalLM,
<ide> BlenderbotSmallForConditionalGeneration,
<ide> BlenderbotSmallModel,
<add> BlenderbotSmallPreTrainedModel,
<ide> )
<ide> from .models.camembert import (
<ide> CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> FunnelForSequenceClassification,
<ide> FunnelForTokenClassification,
<ide> FunnelModel,
<add> FunnelPreTrainedModel,
<ide> load_tf_weights_in_funnel,
<ide> )
<ide> from .models.gpt2 import (
<ide> LayoutLMForSequenceClassification,
<ide> LayoutLMForTokenClassification,
<ide> LayoutLMModel,
<add> LayoutLMPreTrainedModel,
<ide> )
<ide> from .models.led import (
<ide> LED_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> LEDForConditionalGeneration,
<ide> LEDForQuestionAnswering,
<ide> LEDForSequenceClassification,
<ide> LEDModel,
<add> LEDPreTrainedModel,
<ide> )
<ide> from .models.longformer import (
<ide> LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> LongformerForSequenceClassification,
<ide> LongformerForTokenClassification,
<ide> LongformerModel,
<add> LongformerPreTrainedModel,
<ide> LongformerSelfAttention,
<ide> )
<ide> from .models.luke import (
<ide> LxmertVisualFeatureEncoder,
<ide> LxmertXLayer,
<ide> )
<del> from .models.m2m_100 import M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, M2M100ForConditionalGeneration, M2M100Model
<add> from .models.m2m_100 import (
<add> M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST,
<add> M2M100ForConditionalGeneration,
<add> M2M100Model,
<add> M2M100PreTrainedModel,
<add> )
<ide> from .models.marian import MarianForCausalLM, MarianModel, MarianMTModel
<ide> from .models.mbart import (
<ide> MBartForCausalLM,
<ide> MBartForConditionalGeneration,
<ide> MBartForQuestionAnswering,
<ide> MBartForSequenceClassification,
<ide> MBartModel,
<add> MBartPreTrainedModel,
<ide> )
<ide> from .models.megatron_bert import (
<ide> MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> MegatronBertForSequenceClassification,
<ide> MegatronBertForTokenClassification,
<ide> MegatronBertModel,
<add> MegatronBertPreTrainedModel,
<ide> )
<ide> from .models.mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings
<ide> from .models.mobilebert import (
<ide> OpenAIGPTPreTrainedModel,
<ide> load_tf_weights_in_openai_gpt,
<ide> )
<del> from .models.pegasus import PegasusForCausalLM, PegasusForConditionalGeneration, PegasusModel
<add> from .models.pegasus import (
<add> PegasusForCausalLM,
<add> PegasusForConditionalGeneration,
<add> PegasusModel,
<add> PegasusPreTrainedModel,
<add> )
<ide> from .models.prophetnet import (
<ide> PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> ProphetNetDecoder,
<ide> ProphetNetModel,
<ide> ProphetNetPreTrainedModel,
<ide> )
<del> from .models.rag import RagModel, RagSequenceForGeneration, RagTokenForGeneration
<add> from .models.rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration
<ide> from .models.reformer import (
<ide> REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> ReformerAttention,
<ide> ReformerLayer,
<ide> ReformerModel,
<ide> ReformerModelWithLMHead,
<add> ReformerPreTrainedModel,
<ide> )
<ide> from .models.retribert import RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RetriBertModel, RetriBertPreTrainedModel
<ide> from .models.roberta import (
<ide> RobertaForSequenceClassification,
<ide> RobertaForTokenClassification,
<ide> RobertaModel,
<add> RobertaPreTrainedModel,
<ide> )
<ide> from .models.roformer import (
<ide> ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> Speech2TextForConditionalGeneration,
<ide> Speech2TextModel,
<add> Speech2TextPreTrainedModel,
<ide> )
<ide> from .models.squeezebert import (
<ide> SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> TapasForQuestionAnswering,
<ide> TapasForSequenceClassification,
<ide> TapasModel,
<add> TapasPreTrainedModel,
<ide> )
<ide> from .models.transfo_xl import (
<ide> TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> TFBertModel,
<ide> TFBertPreTrainedModel,
<ide> )
<del> from .models.blenderbot import TFBlenderbotForConditionalGeneration, TFBlenderbotModel
<del> from .models.blenderbot_small import TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel
<add> from .models.blenderbot import (
<add> TFBlenderbotForConditionalGeneration,
<add> TFBlenderbotModel,
<add> TFBlenderbotPreTrainedModel,
<add> )
<add> from .models.blenderbot_small import (
<add> TFBlenderbotSmallForConditionalGeneration,
<add> TFBlenderbotSmallModel,
<add> TFBlenderbotSmallPreTrainedModel,
<add> )
<ide> from .models.camembert import (
<ide> TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> TFCamembertForMaskedLM,
<ide> TFFlaubertForSequenceClassification,
<ide> TFFlaubertForTokenClassification,
<ide> TFFlaubertModel,
<add> TFFlaubertPreTrainedModel,
<ide> TFFlaubertWithLMHeadModel,
<ide> )
<ide> from .models.funnel import (
<ide> TFFunnelForSequenceClassification,
<ide> TFFunnelForTokenClassification,
<ide> TFFunnelModel,
<add> TFFunnelPreTrainedModel,
<ide> )
<ide> from .models.gpt2 import (
<ide> TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> TFLongformerForSequenceClassification,
<ide> TFLongformerForTokenClassification,
<ide> TFLongformerModel,
<add> TFLongformerPreTrainedModel,
<ide> TFLongformerSelfAttention,
<ide> )
<ide> from .models.lxmert import (
<ide> TFLxmertPreTrainedModel,
<ide> TFLxmertVisualFeatureEncoder,
<ide> )
<del> from .models.marian import TFMarianModel, TFMarianMTModel
<del> from .models.mbart import TFMBartForConditionalGeneration, TFMBartModel
<add> from .models.marian import TFMarianModel, TFMarianMTModel, TFMarianPreTrainedModel
<add> from .models.mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel
<ide> from .models.mobilebert import (
<ide> TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> TFMobileBertForMaskedLM,
<ide> TFOpenAIGPTModel,
<ide> TFOpenAIGPTPreTrainedModel,
<ide> )
<del> from .models.pegasus import TFPegasusForConditionalGeneration, TFPegasusModel
<del> from .models.rag import TFRagModel, TFRagSequenceForGeneration, TFRagTokenForGeneration
<add> from .models.pegasus import TFPegasusForConditionalGeneration, TFPegasusModel, TFPegasusPreTrainedModel
<add> from .models.rag import TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration
<ide> from .models.roberta import (
<ide> TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
<ide> TFRobertaForMaskedLM,
<ide> FlaxBartForQuestionAnswering,
<ide> FlaxBartForSequenceClassification,
<ide> FlaxBartModel,
<add> FlaxBartPreTrainedModel,
<ide> )
<ide> from .models.bert import (
<ide> FlaxBertForMaskedLM,
<ide> FlaxBigBirdModel,
<ide> FlaxBigBirdPreTrainedModel,
<ide> )
<del> from .models.clip import FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPVisionModel
<add> from .models.clip import (
<add> FlaxCLIPModel,
<add> FlaxCLIPPreTrainedModel,
<add> FlaxCLIPTextModel,
<add> FlaxCLIPTextPreTrainedModel,
<add> FlaxCLIPVisionModel,
<add> FlaxCLIPVisionPreTrainedModel,
<add> )
<ide> from .models.electra import (
<ide> FlaxElectraForMaskedLM,
<ide> FlaxElectraForMultipleChoice,
<ide> FlaxElectraModel,
<ide> FlaxElectraPreTrainedModel,
<ide> )
<del> from .models.gpt2 import FlaxGPT2LMHeadModel, FlaxGPT2Model
<add> from .models.gpt2 import FlaxGPT2LMHeadModel, FlaxGPT2Model, FlaxGPT2PreTrainedModel
<ide> from .models.roberta import (
<ide> FlaxRobertaForMaskedLM,
<ide> FlaxRobertaForMultipleChoice,
<ide> FlaxRobertaModel,
<ide> FlaxRobertaPreTrainedModel,
<ide> )
<del> from .models.t5 import FlaxT5ForConditionalGeneration, FlaxT5Model
<del> from .models.vit import FlaxViTForImageClassification, FlaxViTModel
<add> from .models.t5 import FlaxT5ForConditionalGeneration, FlaxT5Model, FlaxT5PreTrainedModel
<add> from .models.vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel
<ide> else:
<ide> # Import the same objects as dummies to get them in the namespace.
<ide> # They will raise an import error if the user tries to instantiate / use them.
<ide><path>src/transformers/models/bart/__init__.py
<ide> "FlaxBartForQuestionAnswering",
<ide> "FlaxBartForSequenceClassification",
<ide> "FlaxBartModel",
<add> "FlaxBartPreTrainedModel",
<ide> ]
<ide>
<ide> if TYPE_CHECKING:
<ide> FlaxBartForQuestionAnswering,
<ide> FlaxBartForSequenceClassification,
<ide> FlaxBartModel,
<add> FlaxBartPreTrainedModel,
<ide> )
<ide>
<ide> else:
<ide><path>src/transformers/models/bert_generation/__init__.py
<ide> _import_structure["modeling_bert_generation"] = [
<ide> "BertGenerationDecoder",
<ide> "BertGenerationEncoder",
<add> "BertGenerationPreTrainedModel",
<ide> "load_tf_weights_in_bert_generation",
<ide> ]
<ide>
<ide> from .modeling_bert_generation import (
<ide> BertGenerationDecoder,
<ide> BertGenerationEncoder,
<add> BertGenerationPreTrainedModel,
<ide> load_tf_weights_in_bert_generation,
<ide> )
<ide>
<ide><path>src/transformers/models/blenderbot/__init__.py
<ide>
<ide>
<ide> if is_tf_available():
<del> _import_structure["modeling_tf_blenderbot"] = ["TFBlenderbotForConditionalGeneration", "TFBlenderbotModel"]
<add> _import_structure["modeling_tf_blenderbot"] = [
<add> "TFBlenderbotForConditionalGeneration",
<add> "TFBlenderbotModel",
<add> "TFBlenderbotPreTrainedModel",
<add> ]
<ide>
<ide>
<ide> if TYPE_CHECKING:
<ide> )
<ide>
<ide> if is_tf_available():
<del> from .modeling_tf_blenderbot import TFBlenderbotForConditionalGeneration, TFBlenderbotModel
<add> from .modeling_tf_blenderbot import (
<add> TFBlenderbotForConditionalGeneration,
<add> TFBlenderbotModel,
<add> TFBlenderbotPreTrainedModel,
<add> )
<ide>
<ide> else:
<ide> import importlib
<ide><path>src/transformers/models/blenderbot_small/__init__.py
<ide> _import_structure["modeling_tf_blenderbot_small"] = [
<ide> "TFBlenderbotSmallForConditionalGeneration",
<ide> "TFBlenderbotSmallModel",
<add> "TFBlenderbotSmallPreTrainedModel",
<ide> ]
<ide>
<ide> if TYPE_CHECKING:
<ide> )
<ide>
<ide> if is_tf_available():
<del> from .modeling_tf_blenderbot_small import TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel
<add> from .modeling_tf_blenderbot_small import (
<add> TFBlenderbotSmallForConditionalGeneration,
<add> TFBlenderbotSmallModel,
<add> TFBlenderbotSmallPreTrainedModel,
<add> )
<ide>
<ide> else:
<ide> import importlib
<ide><path>src/transformers/models/clip/__init__.py
<ide> "FlaxCLIPModel",
<ide> "FlaxCLIPPreTrainedModel",
<ide> "FlaxCLIPTextModel",
<add> "FlaxCLIPTextPreTrainedModel",
<ide> "FlaxCLIPVisionModel",
<add> "FlaxCLIPVisionPreTrainedModel",
<ide> ]
<ide>
<ide>
<ide> )
<ide>
<ide> if is_flax_available():
<del> from .modeling_flax_clip import FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPVisionModel
<add> from .modeling_flax_clip import (
<add> FlaxCLIPModel,
<add> FlaxCLIPPreTrainedModel,
<add> FlaxCLIPTextModel,
<add> FlaxCLIPTextPreTrainedModel,
<add> FlaxCLIPVisionModel,
<add> FlaxCLIPVisionPreTrainedModel,
<add> )
<ide>
<ide>
<ide> else:
<ide><path>src/transformers/models/flaubert/__init__.py
<ide> "TFFlaubertForSequenceClassification",
<ide> "TFFlaubertForTokenClassification",
<ide> "TFFlaubertModel",
<add> "TFFlaubertPreTrainedModel",
<ide> "TFFlaubertWithLMHeadModel",
<ide> ]
<ide>
<ide> TFFlaubertForSequenceClassification,
<ide> TFFlaubertForTokenClassification,
<ide> TFFlaubertModel,
<add> TFFlaubertPreTrainedModel,
<ide> TFFlaubertWithLMHeadModel,
<ide> )
<ide>
<ide><path>src/transformers/models/funnel/__init__.py
<ide> "FunnelForSequenceClassification",
<ide> "FunnelForTokenClassification",
<ide> "FunnelModel",
<add> "FunnelPreTrainedModel",
<ide> "load_tf_weights_in_funnel",
<ide> ]
<ide>
<ide> "TFFunnelForSequenceClassification",
<ide> "TFFunnelForTokenClassification",
<ide> "TFFunnelModel",
<add> "TFFunnelPreTrainedModel",
<ide> ]
<ide>
<ide>
<ide> FunnelForSequenceClassification,
<ide> FunnelForTokenClassification,
<ide> FunnelModel,
<add> FunnelPreTrainedModel,
<ide> load_tf_weights_in_funnel,
<ide> )
<ide>
<ide> TFFunnelForSequenceClassification,
<ide> TFFunnelForTokenClassification,
<ide> TFFunnelModel,
<add> TFFunnelPreTrainedModel,
<ide> )
<ide>
<ide> else:
<ide><path>src/transformers/models/gpt2/__init__.py
<ide> ]
<ide>
<ide> if is_flax_available():
<del> _import_structure["modeling_flax_gpt2"] = ["FlaxGPT2LMHeadModel", "FlaxGPT2Model"]
<add> _import_structure["modeling_flax_gpt2"] = ["FlaxGPT2LMHeadModel", "FlaxGPT2Model", "FlaxGPT2PreTrainedModel"]
<ide>
<ide> if TYPE_CHECKING:
<ide> from .configuration_gpt2 import GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2Config
<ide> )
<ide>
<ide> if is_flax_available():
<del> from .modeling_flax_gpt2 import FlaxGPT2LMHeadModel, FlaxGPT2Model
<add> from .modeling_flax_gpt2 import FlaxGPT2LMHeadModel, FlaxGPT2Model, FlaxGPT2PreTrainedModel
<ide>
<ide> else:
<ide> import importlib
<ide><path>src/transformers/models/layoutlm/__init__.py
<ide> "LayoutLMForSequenceClassification",
<ide> "LayoutLMForTokenClassification",
<ide> "LayoutLMModel",
<add> "LayoutLMPreTrainedModel",
<ide> ]
<ide>
<ide> if is_tf_available():
<ide> LayoutLMForSequenceClassification,
<ide> LayoutLMForTokenClassification,
<ide> LayoutLMModel,
<add> LayoutLMPreTrainedModel,
<ide> )
<ide> if is_tf_available():
<ide> from .modeling_tf_layoutlm import (
<ide><path>src/transformers/models/longformer/__init__.py
<ide> "LongformerForSequenceClassification",
<ide> "LongformerForTokenClassification",
<ide> "LongformerModel",
<add> "LongformerPreTrainedModel",
<ide> "LongformerSelfAttention",
<ide> ]
<ide>
<ide> "TFLongformerForSequenceClassification",
<ide> "TFLongformerForTokenClassification",
<ide> "TFLongformerModel",
<add> "TFLongformerPreTrainedModel",
<ide> "TFLongformerSelfAttention",
<ide> ]
<ide>
<ide> LongformerForSequenceClassification,
<ide> LongformerForTokenClassification,
<ide> LongformerModel,
<add> LongformerPreTrainedModel,
<ide> LongformerSelfAttention,
<ide> )
<ide>
<ide> TFLongformerForSequenceClassification,
<ide> TFLongformerForTokenClassification,
<ide> TFLongformerModel,
<add> TFLongformerPreTrainedModel,
<ide> TFLongformerSelfAttention,
<ide> )
<ide>
<ide><path>src/transformers/models/marian/__init__.py
<ide> ]
<ide>
<ide> if is_tf_available():
<del> _import_structure["modeling_tf_marian"] = ["TFMarianModel", "TFMarianMTModel"]
<add> _import_structure["modeling_tf_marian"] = ["TFMarianModel", "TFMarianMTModel", "TFMarianPreTrainedModel"]
<ide>
<ide>
<ide> if TYPE_CHECKING:
<ide> )
<ide>
<ide> if is_tf_available():
<del> from .modeling_tf_marian import TFMarianModel, TFMarianMTModel
<add> from .modeling_tf_marian import TFMarianModel, TFMarianMTModel, TFMarianPreTrainedModel
<ide>
<ide> else:
<ide> import importlib
<ide><path>src/transformers/models/mbart/__init__.py
<ide> ]
<ide>
<ide> if is_tf_available():
<del> _import_structure["modeling_tf_mbart"] = ["TFMBartForConditionalGeneration", "TFMBartModel"]
<add> _import_structure["modeling_tf_mbart"] = [
<add> "TFMBartForConditionalGeneration",
<add> "TFMBartModel",
<add> "TFMBartPreTrainedModel",
<add> ]
<ide>
<ide>
<ide> if TYPE_CHECKING:
<ide> )
<ide>
<ide> if is_tf_available():
<del> from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel
<add> from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel
<ide>
<ide> else:
<ide> import importlib
<ide><path>src/transformers/models/megatron_bert/__init__.py
<ide> "MegatronBertForSequenceClassification",
<ide> "MegatronBertForTokenClassification",
<ide> "MegatronBertModel",
<add> "MegatronBertPreTrainedModel",
<ide> ]
<ide>
<ide> if TYPE_CHECKING:
<ide> MegatronBertForSequenceClassification,
<ide> MegatronBertForTokenClassification,
<ide> MegatronBertModel,
<add> MegatronBertPreTrainedModel,
<ide> )
<ide>
<ide> else:
<ide><path>src/transformers/models/pegasus/__init__.py
<ide> ]
<ide>
<ide> if is_tf_available():
<del> _import_structure["modeling_tf_pegasus"] = ["TFPegasusForConditionalGeneration", "TFPegasusModel"]
<add> _import_structure["modeling_tf_pegasus"] = [
<add> "TFPegasusForConditionalGeneration",
<add> "TFPegasusModel",
<add> "TFPegasusPreTrainedModel",
<add> ]
<ide>
<ide>
<ide> if TYPE_CHECKING:
<ide> )
<ide>
<ide> if is_tf_available():
<del> from .modeling_tf_pegasus import TFPegasusForConditionalGeneration, TFPegasusModel
<add> from .modeling_tf_pegasus import TFPegasusForConditionalGeneration, TFPegasusModel, TFPegasusPreTrainedModel
<ide>
<ide> else:
<ide> import importlib
<ide><path>src/transformers/models/rag/__init__.py
<ide> }
<ide>
<ide> if is_torch_available():
<del> _import_structure["modeling_rag"] = ["RagModel", "RagSequenceForGeneration", "RagTokenForGeneration"]
<add> _import_structure["modeling_rag"] = [
<add> "RagModel",
<add> "RagPreTrainedModel",
<add> "RagSequenceForGeneration",
<add> "RagTokenForGeneration",
<add> ]
<ide>
<ide> if is_tf_available():
<del> _import_structure["modeling_tf_rag"] = ["TFRagModel", "TFRagSequenceForGeneration", "TFRagTokenForGeneration"]
<add> _import_structure["modeling_tf_rag"] = [
<add> "TFRagModel",
<add> "TFRagPreTrainedModel",
<add> "TFRagSequenceForGeneration",
<add> "TFRagTokenForGeneration",
<add> ]
<ide>
<ide>
<ide> if TYPE_CHECKING:
<ide> from .tokenization_rag import RagTokenizer
<ide>
<ide> if is_torch_available():
<del> from .modeling_rag import RagModel, RagSequenceForGeneration, RagTokenForGeneration
<add> from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration
<ide>
<ide> if is_tf_available():
<del> from .modeling_tf_rag import TFRagModel, TFRagSequenceForGeneration, TFRagTokenForGeneration
<add> from .modeling_tf_rag import (
<add> TFRagModel,
<add> TFRagPreTrainedModel,
<add> TFRagSequenceForGeneration,
<add> TFRagTokenForGeneration,
<add> )
<ide>
<ide> else:
<ide> import importlib
<ide><path>src/transformers/models/reformer/__init__.py
<ide> "ReformerLayer",
<ide> "ReformerModel",
<ide> "ReformerModelWithLMHead",
<add> "ReformerPreTrainedModel",
<ide> ]
<ide>
<ide>
<ide> ReformerLayer,
<ide> ReformerModel,
<ide> ReformerModelWithLMHead,
<add> ReformerPreTrainedModel,
<ide> )
<ide>
<ide> else:
<ide><path>src/transformers/models/roberta/__init__.py
<ide> "RobertaForSequenceClassification",
<ide> "RobertaForTokenClassification",
<ide> "RobertaModel",
<add> "RobertaPreTrainedModel",
<ide> ]
<ide>
<ide> if is_tf_available():
<ide> RobertaForSequenceClassification,
<ide> RobertaForTokenClassification,
<ide> RobertaModel,
<add> RobertaPreTrainedModel,
<ide> )
<ide>
<ide> if is_tf_available():
<ide><path>src/transformers/models/tapas/__init__.py
<ide> "TapasForQuestionAnswering",
<ide> "TapasForSequenceClassification",
<ide> "TapasModel",
<add> "TapasPreTrainedModel",
<ide> ]
<ide>
<ide>
<ide> TapasForQuestionAnswering,
<ide> TapasForSequenceClassification,
<ide> TapasModel,
<add> TapasPreTrainedModel,
<ide> )
<ide>
<ide> else:
<ide><path>src/transformers/models/vit/__init__.py
<ide>
<ide>
<ide> if is_flax_available():
<del> _import_structure["modeling_flax_vit"] = ["FlaxViTForImageClassification", "FlaxViTModel"]
<add> _import_structure["modeling_flax_vit"] = [
<add> "FlaxViTForImageClassification",
<add> "FlaxViTModel",
<add> "FlaxViTPreTrainedModel",
<add> ]
<ide>
<ide> if TYPE_CHECKING:
<ide> from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig
<ide> )
<ide>
<ide> if is_flax_available():
<del> from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel
<add> from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel
<ide>
<ide>
<ide> else:
<ide><path>src/transformers/utils/dummy_flax_objects.py
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["flax"])
<ide>
<ide>
<add>class FlaxBartPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["flax"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["flax"])
<add>
<add>
<ide> class FlaxBertForMaskedLM:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["flax"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["flax"])
<ide>
<ide>
<add>class FlaxCLIPTextPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["flax"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["flax"])
<add>
<add>
<ide> class FlaxCLIPVisionModel:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["flax"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["flax"])
<ide>
<ide>
<add>class FlaxCLIPVisionPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["flax"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["flax"])
<add>
<add>
<ide> class FlaxElectraForMaskedLM:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["flax"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["flax"])
<ide>
<ide>
<add>class FlaxGPT2PreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["flax"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["flax"])
<add>
<add>
<ide> class FlaxRobertaForMaskedLM:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["flax"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["flax"])
<ide>
<ide>
<add>class FlaxT5PreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["flax"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["flax"])
<add>
<add>
<ide> class FlaxViTForImageClassification:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["flax"])
<ide> def __init__(self, *args, **kwargs):
<ide> @classmethod
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["flax"])
<add>
<add>
<add>class FlaxViTPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["flax"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["flax"])
<ide><path>src/transformers/utils/dummy_pt_objects.py
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["torch"])
<ide>
<ide>
<add>class BertGenerationPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> def load_tf_weights_in_bert_generation(*args, **kwargs):
<ide> requires_backends(load_tf_weights_in_bert_generation, ["torch"])
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class BigBirdPegasusPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class BlenderbotPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class BlenderbotSmallPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class FunnelPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> def load_tf_weights_in_funnel(*args, **kwargs):
<ide> requires_backends(load_tf_weights_in_funnel, ["torch"])
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class LayoutLMPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> LED_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class LEDPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class LongformerPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> class LongformerSelfAttention:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["torch"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class M2M100PreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> class MarianForCausalLM:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["torch"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class MBartPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class MegatronBertPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> class MMBTForClassification:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["torch"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class PegasusPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class RagPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> class RagSequenceForGeneration:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["torch"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class ReformerPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class RobertaPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class Speech2TextPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["torch"])
<ide>
<ide>
<add>class TapasPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["torch"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["torch"])
<add>
<add>
<ide> TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide><path>src/transformers/utils/dummy_tf_objects.py
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["tf"])
<ide>
<ide>
<add>class TFBlenderbotPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["tf"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["tf"])
<add>
<add>
<ide> class TFBlenderbotSmallForConditionalGeneration:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["tf"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["tf"])
<ide>
<ide>
<add>class TFBlenderbotSmallPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["tf"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["tf"])
<add>
<add>
<ide> TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["tf"])
<ide>
<ide>
<add>class TFFlaubertPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["tf"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["tf"])
<add>
<add>
<ide> class TFFlaubertWithLMHeadModel:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["tf"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["tf"])
<ide>
<ide>
<add>class TFFunnelPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["tf"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["tf"])
<add>
<add>
<ide> TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["tf"])
<ide>
<ide>
<add>class TFLongformerPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["tf"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["tf"])
<add>
<add>
<ide> class TFLongformerSelfAttention:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["tf"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["tf"])
<ide>
<ide>
<add>class TFMarianPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["tf"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["tf"])
<add>
<add>
<ide> class TFMBartForConditionalGeneration:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["tf"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["tf"])
<ide>
<ide>
<add>class TFMBartPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["tf"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["tf"])
<add>
<add>
<ide> TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST = None
<ide>
<ide>
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["tf"])
<ide>
<ide>
<add>class TFPegasusPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["tf"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["tf"])
<add>
<add>
<ide> class TFRagModel:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["tf"])
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["tf"])
<ide>
<ide>
<add>class TFRagPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["tf"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["tf"])
<add>
<add>
<ide> class TFRagSequenceForGeneration:
<ide> def __init__(self, *args, **kwargs):
<ide> requires_backends(self, ["tf"])
<ide><path>src/transformers/utils/dummy_timm_and_vision_objects.py
<ide> def __init__(self, *args, **kwargs):
<ide> @classmethod
<ide> def from_pretrained(cls, *args, **kwargs):
<ide> requires_backends(cls, ["timm", "vision"])
<add>
<add>
<add>class DetrPreTrainedModel:
<add> def __init__(self, *args, **kwargs):
<add> requires_backends(self, ["timm", "vision"])
<add>
<add> @classmethod
<add> def from_pretrained(cls, *args, **kwargs):
<add> requires_backends(cls, ["timm", "vision"])
<ide><path>templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/to_replace_{{cookiecutter.lowercase_modelname}}.py
<ide> "{{cookiecutter.camelcase_modelname}}ForQuestionAnswering",
<ide> "{{cookiecutter.camelcase_modelname}}ForSequenceClassification",
<ide> "{{cookiecutter.camelcase_modelname}}Model",
<add> "{{cookiecutter.camelcase_modelname}}PreTrainedModel",
<ide> ]
<ide> )
<ide> {% endif -%}
<ide> {{cookiecutter.camelcase_modelname}}ForQuestionAnswering,
<ide> {{cookiecutter.camelcase_modelname}}ForSequenceClassification,
<ide> {{cookiecutter.camelcase_modelname}}Model,
<add> {{cookiecutter.camelcase_modelname}}PreTrainedModel,
<ide> )
<ide> {% endif -%}
<ide> # End.
<ide><path>utils/check_repo.py
<ide> PATH_TO_TESTS = "tests"
<ide> PATH_TO_DOC = "docs/source"
<ide>
<add># Update this list with models that are supposed to be private.
<add>PRIVATE_MODELS = [
<add> "DPRSpanPredictor",
<add> "T5Stack",
<add> "TFDPRSpanPredictor",
<add>]
<add>
<ide> # Update this list for models that are not tested with a comment explaining the reason it should not be.
<ide> # Being in this list is an exception and should **not** be the rule.
<del>IGNORE_NON_TESTED = [
<add>IGNORE_NON_TESTED = PRIVATE_MODELS.copy() + [
<ide> # models to ignore for not tested
<ide> "BigBirdPegasusEncoder", # Building part of bigger (tested) model.
<ide> "BigBirdPegasusDecoder", # Building part of bigger (tested) model.
<ide> "PegasusEncoder", # Building part of bigger (tested) model.
<ide> "PegasusDecoderWrapper", # Building part of bigger (tested) model.
<ide> "DPREncoder", # Building part of bigger (tested) model.
<del> "DPRSpanPredictor", # Building part of bigger (tested) model.
<ide> "ProphetNetDecoderWrapper", # Building part of bigger (tested) model.
<ide> "ReformerForMaskedLM", # Needs to be setup as decoder.
<del> "T5Stack", # Building part of bigger (tested) model.
<ide> "TFDPREncoder", # Building part of bigger (tested) model.
<del> "TFDPRSpanPredictor", # Building part of bigger (tested) model.
<ide> "TFElectraMainLayer", # Building part of bigger (tested) model (should it be a TFPreTrainedModel ?)
<ide> "TFRobertaForMultipleChoice", # TODO: fix
<ide> "SeparableConv1D", # Building part of bigger (tested) model.
<ide>
<ide> # Update this list for models that are not in any of the auto MODEL_XXX_MAPPING. Being in this list is an exception and
<ide> # should **not** be the rule.
<del>IGNORE_NON_AUTO_CONFIGURED = [
<add>IGNORE_NON_AUTO_CONFIGURED = PRIVATE_MODELS.copy() + [
<ide> # models to ignore for model xxx mapping
<ide> "CLIPTextModel",
<ide> "CLIPVisionModel",
<ide> "FlaxCLIPTextModel",
<ide> "FlaxCLIPVisionModel",
<ide> "DetrForSegmentation",
<ide> "DPRReader",
<del> "DPRSpanPredictor",
<ide> "FlaubertForQuestionAnswering",
<ide> "GPT2DoubleHeadsModel",
<ide> "LukeForEntityClassification",
<ide> "RagModel",
<ide> "RagSequenceForGeneration",
<ide> "RagTokenForGeneration",
<del> "T5Stack",
<ide> "TFDPRReader",
<del> "TFDPRSpanPredictor",
<ide> "TFGPT2DoubleHeadsModel",
<ide> "TFOpenAIGPTDoubleHeadsModel",
<ide> "TFRagModel",
<ide> def get_model_modules():
<ide> return modules
<ide>
<ide>
<del>def get_models(module):
<add>def get_models(module, include_pretrained=False):
<ide> """Get the objects in module that are models."""
<ide> models = []
<ide> model_classes = (transformers.PreTrainedModel, transformers.TFPreTrainedModel, transformers.FlaxPreTrainedModel)
<ide> for attr_name in dir(module):
<del> if "Pretrained" in attr_name or "PreTrained" in attr_name:
<add> if not include_pretrained and ("Pretrained" in attr_name or "PreTrained" in attr_name):
<ide> continue
<ide> attr = getattr(module, attr_name)
<ide> if isinstance(attr, type) and issubclass(attr, model_classes) and attr.__module__ == module.__name__:
<ide> models.append((attr_name, attr))
<ide> return models
<ide>
<ide>
<add>def is_a_private_model(model):
<add> """Returns True if the model should not be in the main init."""
<add> if model in PRIVATE_MODELS:
<add> return True
<add>
<add> # Wrapper, Encoder and Decoder are all privates
<add> if model.endswith("Wrapper"):
<add> return True
<add> if model.endswith("Encoder"):
<add> return True
<add> if model.endswith("Decoder"):
<add> return True
<add> return False
<add>
<add>
<add>def check_models_are_in_init():
<add> """Checks all models defined in the library are in the main init."""
<add> models_not_in_init = []
<add> dir_transformers = dir(transformers)
<add> for module in get_model_modules():
<add> models_not_in_init += [
<add> model[0] for model in get_models(module, include_pretrained=True) if model[0] not in dir_transformers
<add> ]
<add>
<add> # Remove private models
<add> models_not_in_init = [model for model in models_not_in_init if not is_a_private_model(model)]
<add> if len(models_not_in_init) > 0:
<add> raise Exception(f"The following models should be in the main init: {','.join(models_not_in_init)}.")
<add>
<add>
<ide> # If some test_modeling files should be ignored when checking models are all tested, they should be added in the
<ide> # nested list _ignore_files of this function.
<ide> def get_model_test_files():
<ide> def find_tested_models(test_file):
<ide>
<ide> def check_models_are_tested(module, test_file):
<ide> """Check models defined in module are tested in test_file."""
<add> # XxxPreTrainedModel are not tested
<ide> defined_models = get_models(module)
<ide> tested_models = find_tested_models(test_file)
<ide> if tested_models is None:
<ide> def check_all_objects_are_documented():
<ide>
<ide> def check_repo_quality():
<ide> """Check all models are properly tested and documented."""
<add> print("Checking all models are public.")
<add> check_models_are_in_init()
<ide> print("Checking all models are properly tested.")
<ide> check_all_decorator_order()
<ide> check_all_models_are_tested() | 26 |
PHP | PHP | remove useless imports | e05deec2d36aa980880e1c7d893ee9e41c038388 | <ide><path>src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php
<ide> use Illuminate\Foundation\Composer;
<ide> use Illuminate\Filesystem\Filesystem;
<ide> use Illuminate\Console\GeneratorCommand;
<del>use Symfony\Component\Console\Input\InputArgument;
<ide>
<ide> class SeederMakeCommand extends GeneratorCommand {
<ide>
<ide><path>src/Illuminate/Foundation/Bus/DispatchesCommands.php
<ide> <?php namespace Illuminate\Foundation\Bus;
<ide>
<del>use ArrayAccess;
<del>
<ide> /**
<ide> * @deprecated since version 5.1. Use the DispatchesJobs trait directly.
<ide> */ | 2 |
Go | Go | fix issue with autoremove | e7269b98416e8228930dde9461bfcad38eeb2c56 | <ide><path>commands.go
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> // Detached mode
<ide> <-wait
<ide> } else {
<del> status, err := getExitCode(cli, runResult.ID)
<add> running, status, err := getExitCode(cli, runResult.ID)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> if autoRemove {
<del> if _, _, err = cli.call("DELETE", "/containers/"+runResult.ID, nil); err != nil {
<add> if running {
<add> return fmt.Errorf("Impossible to auto-remove a detached container")
<add> }
<add> // Wait for the process to
<add> if _, _, err := cli.call("POST", "/containers/"+runResult.ID+"/wait", nil); err != nil {
<add> return err
<add> }
<add> if _, _, err := cli.call("DELETE", "/containers/"+runResult.ID, nil); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func waitForExit(cli *DockerCli, containerId string) (int, error) {
<ide> return out.StatusCode, nil
<ide> }
<ide>
<del>func getExitCode(cli *DockerCli, containerId string) (int, error) {
<add>// getExitCode perform an inspect on the container. It returns
<add>// the running state and the exit code.
<add>func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
<ide> body, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil)
<ide> if err != nil {
<ide> // If we can't connect, then the daemon probably died.
<ide> if err != ErrConnectionRefused {
<del> return -1, err
<add> return false, -1, err
<ide> }
<del> return -1, nil
<add> return false, -1, nil
<ide> }
<ide> c := &Container{}
<ide> if err := json.Unmarshal(body, c); err != nil {
<del> return -1, err
<add> return false, -1, err
<ide> }
<del> return c.State.ExitCode, nil
<add> return c.State.Running, c.State.ExitCode, nil
<ide> }
<ide>
<ide> func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli { | 1 |
Ruby | Ruby | remove invalid magic comment [ci skip] | e6a0c34be443212dd374f9ad5e0dbd01b838cc64 | <ide><path>actionpack/lib/action_dispatch/http/mime_type.rb
<ide> # frozen_string_literal: true
<ide>
<del># -*- frozen-string-literal: true -*-
<del>
<ide> require "singleton"
<ide> require "active_support/core_ext/string/starts_ends_with"
<ide> | 1 |
PHP | PHP | morphinstanceto() | 2f4135d8db5ded851d1f4f611124c53b768a3c08 | <ide><path>src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php
<ide> protected function morphEagerTo($name, $type, $id)
<ide> protected function morphInstanceTo($target, $name, $type, $id)
<ide> {
<ide> $instance = $this->newRelatedInstance(
<del> Model::getActualClassNameForMorph($target)
<add> static::getActualClassNameForMorph($target)
<ide> );
<ide>
<ide> return new MorphTo( | 1 |
Ruby | Ruby | modify to_hash output | 9a2f84d4a553b79e5f08e7c440a3d2108033a946 | <ide><path>Library/Homebrew/formula.rb
<ide> def to_hash
<ide> "aliases" => aliases.sort,
<ide> "versioned_formulae" => versioned_formulae.map(&:name),
<ide> "desc" => desc,
<del> "license" => license.class == String ? [license] : license,
<add> "license" => license,
<ide> "homepage" => homepage,
<ide> "versions" => {
<ide> "stable" => stable&.version&.to_s, | 1 |
Text | Text | fix translation errors | 52808516853b4bee805cd9ef29ac0de35774e0c9 | <ide><path>curriculum/challenges/russian/01-responsive-web-design/applied-visual-design/adjust-the-hover-state-of-an-anchor-tag.russian.md
<ide> id: 587d781d367417b2b2512ac8
<ide> title: Adjust the Hover State of an Anchor Tag
<ide> challengeType: 0
<ide> videoUrl: ''
<del>localeTitle: Отрегулируйте состояние наведения якорной метки
<add>localeTitle: Отрегулируйте состояние ссылок при наведении курсора
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id="description"> Эта проблема будет касаться использования псевдоклассов. Псевдокласс - это ключевое слово, которое можно добавить в селектор, чтобы выбрать конкретное состояние элемента. Например, стиль тега привязки может быть изменен для его состояния зависания с помощью селектора псевдо-класса <code>:hover</code> . Вот CSS, чтобы изменить <code>color</code> привязанного тега на красный во время наведения на него: <blockquote> a: hover { <br> красный цвет; <br> } </blockquote></section>
<ide>
<add>
<ide> ## Instructions
<ide> <section id="instructions"> Редактор кода имеет правило CSS в стиле все <code>a</code> теги черный. Добавьте правила, так чтобы когда пользователь наводит на <code>a</code> тег, то <code>color</code> становился синим. </section>
<ide> | 1 |
Java | Java | use the configured charset for part headers | 75117f42b827397890060d2297b79bbc1b0c528c | <ide><path>spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java
<ide> import java.nio.charset.StandardCharsets;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<add>import java.util.HashMap;
<ide> import java.util.Iterator;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> public void addPartConverter(HttpMessageConverter<?> partConverter) {
<ide> /**
<ide> * Set the default character set to use for reading and writing form data when
<ide> * the request or response Content-Type header does not explicitly specify it.
<del> * <p>By default this is set to "UTF-8". As of 4.3, it will also be used as
<del> * the default charset for the conversion of text bodies in a multipart request.
<del> * In contrast to this, {@link #setMultipartCharset} only affects the encoding of
<del> * <i>file names</i> in a multipart request according to the encoded-word syntax.
<add> *
<add> * <p>As of 4.3, this is also used as the default charset for the conversion
<add> * of text bodies in a multipart request.
<add> *
<add> * <p>As of 5.0 this is also used for part headers including
<add> * "Content-Disposition" (and its filename parameter) unless (the mutually
<add> * exclusive) {@link #setMultipartCharset} is also set, in which case part
<add> * headers are encoded as ASCII and <i>filename</i> is encoded with the
<add> * "encoded-word" syntax from RFC 2047.
<add> *
<add> * <p>By default this is set to "UTF-8".
<ide> */
<ide> public void setCharset(Charset charset) {
<ide> if (charset != this.charset) {
<ide> private void applyDefaultCharset() {
<ide>
<ide> /**
<ide> * Set the character set to use when writing multipart data to encode file
<del> * names. Encoding is based on the encoded-word syntax defined in RFC 2047
<add> * names. Encoding is based on the "encoded-word" syntax defined in RFC 2047
<ide> * and relies on {@code MimeUtility} from "javax.mail".
<del> * <p>If not set file names will be encoded as US-ASCII.
<add> *
<add> * <p>As of 5.0 by default part headers, including Content-Disposition (and
<add> * its filename parameter) will be encoded based on the setting of
<add> * {@link #setCharset(Charset)} or {@code UTF-8} by default.
<add> *
<ide> * @since 4.1.1
<ide> * @see <a href="http://en.wikipedia.org/wiki/MIME#Encoded-Word">Encoded-Word</a>
<ide> */
<ide> public void writeTo(OutputStream outputStream) throws IOException {
<ide>
<ide> private void writeMultipart(final MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage) throws IOException {
<ide> final byte[] boundary = generateMultipartBoundary();
<del> Map<String, String> parameters = Collections.singletonMap("boundary", new String(boundary, "US-ASCII"));
<add> Map<String, String> parameters = new HashMap<>(2);
<add> parameters.put("boundary", new String(boundary, "US-ASCII"));
<add> if (!isFilenameCharsetSet()) {
<add> parameters.put("charset", this.charset.name());
<add> }
<ide>
<ide> MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters);
<ide> HttpHeaders headers = outputMessage.getHeaders();
<ide> public void writeTo(OutputStream outputStream) throws IOException {
<ide> }
<ide> }
<ide>
<add> /**
<add> * When {@link #setMultipartCharset(Charset)} is configured (i.e. RFC 2047,
<add> * "encoded-word" syntax) we need to use ASCII for part headers or otherwise
<add> * we encode directly using the configured {@link #setCharset(Charset)}.
<add> */
<add> private boolean isFilenameCharsetSet() {
<add> return this.multipartCharset != null;
<add> }
<add>
<ide> private void writeParts(OutputStream os, MultiValueMap<String, Object> parts, byte[] boundary) throws IOException {
<ide> for (Map.Entry<String, List<Object>> entry : parts.entrySet()) {
<ide> String name = entry.getKey();
<ide> private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) t
<ide> MediaType partContentType = partHeaders.getContentType();
<ide> for (HttpMessageConverter<?> messageConverter : this.partConverters) {
<ide> if (messageConverter.canWrite(partType, partContentType)) {
<del> HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os);
<add> Charset charset = isFilenameCharsetSet() ? StandardCharsets.US_ASCII : this.charset;
<add> HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os, charset);
<ide> multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
<ide> if (!partHeaders.isEmpty()) {
<ide> multipartMessage.getHeaders().putAll(partHeaders);
<ide> private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) t
<ide> "found for request type [" + partType.getName() + "]");
<ide> }
<ide>
<del>
<ide> /**
<ide> * Generate a multipart boundary.
<ide> * <p>This implementation delegates to
<ide> private static class MultipartHttpOutputMessage implements HttpOutputMessage {
<ide>
<ide> private final OutputStream outputStream;
<ide>
<add> private final Charset charset;
<add>
<ide> private final HttpHeaders headers = new HttpHeaders();
<ide>
<ide> private boolean headersWritten = false;
<ide>
<del> public MultipartHttpOutputMessage(OutputStream outputStream) {
<add> public MultipartHttpOutputMessage(OutputStream outputStream, Charset charset) {
<ide> this.outputStream = outputStream;
<add> this.charset = charset;
<ide> }
<ide>
<ide> @Override
<ide> public OutputStream getBody() throws IOException {
<ide> private void writeHeaders() throws IOException {
<ide> if (!this.headersWritten) {
<ide> for (Map.Entry<String, List<String>> entry : this.headers.entrySet()) {
<del> byte[] headerName = getAsciiBytes(entry.getKey());
<add> byte[] headerName = getBytes(entry.getKey());
<ide> for (String headerValueString : entry.getValue()) {
<del> byte[] headerValue = getAsciiBytes(headerValueString);
<add> byte[] headerValue = getBytes(headerValueString);
<ide> this.outputStream.write(headerName);
<ide> this.outputStream.write(':');
<ide> this.outputStream.write(' ');
<ide> private void writeHeaders() throws IOException {
<ide> }
<ide> }
<ide>
<del> private byte[] getAsciiBytes(String name) {
<del> return name.getBytes(StandardCharsets.US_ASCII);
<add> private byte[] getBytes(String name) {
<add> return name.getBytes(this.charset);
<ide> }
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide>
<del>import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.CoreMatchers.allOf;
<ide> import static org.hamcrest.CoreMatchers.endsWith;
<ide> import static org.hamcrest.CoreMatchers.startsWith;
<del>import static org.junit.Assert.*;
<del>import static org.mockito.BDDMockito.*;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertNotNull;
<add>import static org.junit.Assert.assertNull;
<add>import static org.junit.Assert.assertThat;
<add>import static org.junit.Assert.assertTrue;
<add>import static org.mockito.BDDMockito.never;
<add>import static org.mockito.BDDMockito.verify;
<ide>
<ide> /**
<ide> * @author Arjen Poutsma
<ide> public String getFilename() {
<ide> parts.add("xml", entity);
<ide>
<ide> MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
<del> this.converter.setMultipartCharset(StandardCharsets.UTF_8);
<ide> this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);
<ide>
<ide> final MediaType contentType = outputMessage.getHeaders().getContentType(); | 2 |
Javascript | Javascript | remove reference to flushnext | 04492ef2279e2be18162bef89b0a75992a400cae | <ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.$TimeoutDecorator = function($delegate, $browser) {
<ide> $browser.defer.flush(delay);
<ide> };
<ide>
<del> /**
<del> * @ngdoc method
<del> * @name ngMock.$timeout#flushNext
<del> * @methodOf ngMock.$timeout
<del> * @description
<del> *
<del> * Flushes the next timeout in the queue and compares it to the provided delay
<del> *
<del> * @param {number=} expectedDelay the delay value that will be asserted against the delay of the
<del> * next timeout function
<del> */
<del> $delegate.flushNext = function(expectedDelay) {
<del> $browser.defer.flushNext(expectedDelay);
<del> };
<del>
<ide> /**
<ide> * @ngdoc method
<ide> * @name ngMock.$timeout#verifyNoPendingTasks
<ide> angular.mock.clearDataCache = function() {
<ide> }
<ide> }
<ide> };
<del>})(window);
<ide>\ No newline at end of file
<add>})(window); | 1 |
Text | Text | fix broken links | c272d567eb73723c9d213d782454e5669a330c30 | <ide><path>docs/portuguese/how-to-catch-outgoing-emails-locally.md
<ide> Alguns do fluxos de email, como atualizar o email de um usuário, necessita de u
<ide>
<ide> Como instalar e rodar MailHog depende do seu sistema operacional:
<ide>
<del>- [Instalando MailHog no macOS](#installing-mailhog-on-macos)
<del>- [Instalando MailHog no Windows](#installing-mailhog-on-windows)
<del>- [Instalando MailHog no Linux](#installing-mailhog-on-linux)
<add>- [Instalando MailHog no macOS](#instalando-mailhog-no-macos)
<add>- [Instalando MailHog no Windows](#instalando-mailhog-no-windows)
<add>- [Instalando MailHog no Linux](#instalando-mailhog-no-linux)
<ide>
<ide> ### Instalando MailHog no macOS
<ide>
<ide> brew services start mailhog
<ide>
<ide> Este comando vai iniciar o serviço mailhog em background.
<ide>
<del>A seguir, você pode pular para [usando MailHog](#using-mailhog).
<add>A seguir, você pode pular para [usando MailHog](#usando-o-mailhog).
<ide>
<ide> ### Instalando MailHog no Windows
<ide>
<ide> Quando o download finalizar, clique no arquivo. Você provavelmente vai receber
<ide>
<ide> Para fechar o MailHog basta fechar o prompt de comando. Para rodar de novo é só clicar no mesmo arquivo executável baixado anteriormente. Não precisa fazer o download novamente.
<ide>
<del>A seguir, você pode pular para [usando MailHog](#using-mailhog).
<add>A seguir, você pode pular para [usando MailHog](#usando-o-mailhog).
<ide>
<ide> ### Instalando MailHog no Linux
<ide>
<ide> sudo cp /home/$(whoami)/go/bin/MailHog /usr/local/bin/mailhog
<ide> mailhog
<ide> ```
<ide>
<del>A seguir, você pode pular para [usando MailHog](#using-mailhog).
<add>A seguir, você pode pular para [usando MailHog](#usando-o-mailhog).
<ide>
<ide> ## Usando o MailHog
<ide>
<ide> Uma vez que você instalou o MailHog e iniciou o serviço, você precisa abrir seu inbox MailHog no browser. Abra uma nova aba ou janela e entre em [http://localhost:8025](http://localhost:8025).
<ide> Você deve ver agora algo semelhante com a tela abaixo:
<ide>
<del>
<add>
<ide>
<ide> Quando sua instalação do freeCodeCamp enviar um email você irá ver ele aparecer aqui. Como mostra abaixo:
<ide>
<del>
<add>
<ide>
<ide> Abra o email e você deve ver duas abas onde pode ver o conteúdo - texto simples e o fonte. Assegure que você está na aba de texto simples.
<ide>
<del>
<add>
<ide>
<ide> Qualquer link no email deve ser clicável.
<ide>
<ide> ## Links úteis
<ide>
<del>- Para qualquer dúvidas ou questões relacionadas ao MailHog ou instruções ou configurações customizadas, verifique o repositório do [MailHog](https://github.com/mailhog/MailHog).
<ide>\ No newline at end of file
<add>- Para qualquer dúvidas ou questões relacionadas ao MailHog ou instruções ou configurações customizadas, verifique o repositório do [MailHog](https://github.com/mailhog/MailHog). | 1 |
Go | Go | fix building client on openbsd | 925bc27b8108a154161b578e176d2b7d79e8002c | <ide><path>pkg/parsers/kernel/kernel_unix.go
<del>// +build linux freebsd solaris
<add>// +build linux freebsd solaris openbsd
<ide>
<ide> // Package kernel provides helper function to get, parse and compare kernel
<ide> // versions for different platforms.
<ide><path>pkg/system/stat_openbsd.go
<ide> func fromStatT(s *syscall.Stat_t) (*StatT, error) {
<ide> rdev: uint64(s.Rdev),
<ide> mtim: s.Mtim}, nil
<ide> }
<add>
<add>// Stat takes a path to a file and returns
<add>// a system.Stat_t type pertaining to that file.
<add>//
<add>// Throws an error if the file does not exist
<add>func Stat(path string) (*StatT, error) {
<add> s := &syscall.Stat_t{}
<add> if err := syscall.Stat(path, s); err != nil {
<add> return nil, err
<add> }
<add> return fromStatT(s)
<add>} | 2 |
Javascript | Javascript | change onrefresh flow typing | 884c86ae02b0be7ea1e4b258dab39f4c5aee0b9d | <ide><path>Libraries/Components/RefreshControl/RefreshControl.js
<ide> export type RefreshControlProps = $ReadOnly<{|
<ide> /**
<ide> * Called when the view starts refreshing.
<ide> */
<del> onRefresh?: ?() => void,
<add> onRefresh?: ?() => void | Promise<void>,
<ide>
<ide> /**
<ide> * Whether the view should be indicating an active refresh. | 1 |
Javascript | Javascript | support callbacks in newresource | 76ba745cc26769fcd47496e7ef023b460f7ad380 | <ide><path>lib/ContextReplacementPlugin.js
<ide> var path = require("path");
<ide>
<ide> function ContextReplacementPlugin(resourceRegExp, newContentResource, newContentRecursive, newContentRegExp) {
<ide> this.resourceRegExp = resourceRegExp;
<del> if(typeof newContentResource !== "string") {
<del> newContentRegExp = newContentRecursive;
<del> newContentRecursive = newContentResource;
<del> newContentResource = undefined;
<add> if(typeof newContentResource === "function") {
<add> this.newContentCallback = newContentResource;
<add> } else {
<add> if(typeof newContentResource !== "string") {
<add> newContentRegExp = newContentRecursive;
<add> newContentRecursive = newContentResource;
<add> newContentResource = undefined;
<add> }
<add> if(typeof newContentRecursive !== "boolean") {
<add> newContentRegExp = newContentRecursive;
<add> newContentRecursive = undefined;
<add> }
<add> this.newContentResource = newContentResource;
<add> this.newContentRecursive = newContentRecursive;
<add> this.newContentRegExp = newContentRegExp;
<ide> }
<del> if(typeof newContentRecursive !== "boolean") {
<del> newContentRegExp = newContentRecursive;
<del> newContentRecursive = undefined;
<del> }
<del> this.newContentResource = newContentResource;
<del> this.newContentRecursive = newContentRecursive;
<del> this.newContentRegExp = newContentRegExp;
<ide> }
<ide> module.exports = ContextReplacementPlugin;
<ide> ContextReplacementPlugin.prototype.apply = function(compiler) {
<ide> var resourceRegExp = this.resourceRegExp;
<add> var newContentCallback = this.newContentCallback;
<ide> var newContentResource = this.newContentResource;
<ide> var newContentRecursive = this.newContentRecursive;
<ide> var newContentRegExp = this.newContentRegExp;
<ide> compiler.plugin("context-module-factory", function(cmf) {
<ide> cmf.plugin("before-resolve", function(result, callback) {
<ide> if(!result) return callback();
<ide> if(resourceRegExp.test(result.request)) {
<del> if(typeof newContentResource !== "undefined")
<del> result.request = newContentResource;
<del> if(typeof newContentRecursive !== "undefined")
<del> result.recursive = newContentRecursive;
<del> if(typeof newContentRegExp !== "undefined")
<del> result.regExp = newContentRegExp;
<add> if(typeof newContentCallback === "function") {
<add> newContentCallback(result);
<add> } else {
<add> if(typeof newContentResource !== "undefined")
<add> result.request = newContentResource;
<add> if(typeof newContentRecursive !== "undefined")
<add> result.recursive = newContentRecursive;
<add> if(typeof newContentRegExp !== "undefined")
<add> result.regExp = newContentRegExp;
<add> }
<ide> }
<ide> return callback(null, result);
<ide> });
<ide> cmf.plugin("after-resolve", function(result, callback) {
<ide> if(!result) return callback();
<ide> if(resourceRegExp.test(result.resource)) {
<del> if(typeof newContentResource !== "undefined")
<del> result.resource = path.resolve(result.resource, newContentResource);
<del> if(typeof newContentRecursive !== "undefined")
<del> result.recursive = newContentRecursive;
<del> if(typeof newContentRegExp !== "undefined")
<del> result.regExp = newContentRegExp;
<add> if(typeof newContentCallback === "function") {
<add> var origResource = result.resource;
<add> newContentCallback(result);
<add> if (result.resource !== origResource) {
<add> result.resource = path.resolve(origResource, result.resource);
<add> }
<add> } else {
<add> if(typeof newContentResource !== "undefined")
<add> result.resource = path.resolve(result.resource, newContentResource);
<add> if(typeof newContentRecursive !== "undefined")
<add> result.recursive = newContentRecursive;
<add> if(typeof newContentRegExp !== "undefined")
<add> result.regExp = newContentRegExp;
<add> }
<ide> }
<ide> return callback(null, result);
<ide> });
<ide> });
<del>};
<ide>\ No newline at end of file
<add>}; | 1 |
Javascript | Javascript | fix the failing specs | ba1b47f85b771f8221db58a46b58429375b0ee6e | <ide><path>docs/spec/ngdocSpec.js
<ide> describe('ngdoc', function() {
<ide> var d1 = new Doc('@name a.b.c').parse();
<ide> var d2 = new Doc('@name a.b.ng-c').parse();
<ide> var d3 = new Doc('@name some text: more text').parse();
<del> expect(ngdoc.metadata([d1])[0].shortName).toEqual('c');
<del> expect(ngdoc.metadata([d2])[0].shortName).toEqual('ng-c');
<add> expect(ngdoc.metadata([d1])[0].shortName).toEqual('a.b.c');
<add> expect(ngdoc.metadata([d2])[0].shortName).toEqual('a.b.ng-c');
<ide> expect(ngdoc.metadata([d3])[0].shortName).toEqual('more text');
<ide> });
<ide>
<ide><path>docs/spec/sourceLinkSpec.js
<ide> describe('Docs Links', function() {
<ide> });
<ide>
<ide> it('should have an "view source" button', function() {
<del> spyOn(gruntUtil, 'getVersion').andReturn({cdn: '1.2.299'});
<add> spyOn(gruntUtil, 'getVersion').andReturn({full: '1.2.299'});
<ide>
<ide> expect(doc.html()).
<ide> toContain('<a href="http://github.com/angular/angular.js/tree/v1.2.299/test.js#L42" class="view-source btn btn-action"><i class="icon-zoom-in"> </i> View source</a>'); | 2 |
Javascript | Javascript | use accessors to transfer the poster attribute | 6f5e49fc1603b1793ca73a60468fad57f840849a | <ide><path>test/unit/mediafaker.js
<ide> vjs.MediaFaker.prototype.createEl = function(){
<ide> var el = goog.base(this, 'createEl', 'div', {
<ide> className: 'vjs-tech'
<ide> });
<del> if (this.player_.poster_) {
<add> if (this.player().poster()) {
<ide> // transfer the poster image to mimic HTML
<del> el.poster = this.player_.poster_;
<add> el.poster = this.player().poster();
<ide> }
<ide>
<ide> vjs.insertFirst(el, this.player_.el()); | 1 |
Go | Go | add `len()` to image store for info endpoint | f6a7763b6f3256bed9a7352021745189d0ca8dc9 | <ide><path>daemon/images/service.go
<ide> type ImageService struct {
<ide> // CountImages returns the number of images stored by ImageService
<ide> // called from info.go
<ide> func (i *ImageService) CountImages() int {
<del> return len(i.imageStore.Map())
<add> return i.imageStore.Len()
<ide> }
<ide>
<ide> // Children returns the children image.IDs for a parent image.
<ide><path>image/store.go
<ide> type Store interface {
<ide> Children(id ID) []ID
<ide> Map() map[ID]*Image
<ide> Heads() map[ID]*Image
<add> Len() int
<ide> }
<ide>
<ide> // LayerGetReleaser is a minimal interface for getting and releasing images.
<ide> func (is *store) imagesMap(all bool) map[ID]*Image {
<ide> }
<ide> return images
<ide> }
<add>
<add>func (is *store) Len() int {
<add> is.RLock()
<add> defer is.RUnlock()
<add> return len(is.images)
<add>} | 2 |
Javascript | Javascript | remove `getall` from `evaluatorpreprocessor_read` | 93ea866f0141dbad92edc7be0555b1510582ee2b | <ide><path>src/core/evaluator.js
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> // but doing so is meaningless without knowing the semantics.
<ide> continue;
<ide> default:
<del> // Note: Let's hope that the ignored operator does not have any
<del> // non-serializable arguments, otherwise postMessage will throw
<add> // Note: Ignore the operator if it has `Dict` arguments, since
<add> // those are non-serializable, otherwise postMessage will throw
<ide> // "An object could not be cloned.".
<add> if (args !== null) {
<add> for (i = 0, ii = args.length; i < ii; i++) {
<add> if (args[i] instanceof Dict) {
<add> break;
<add> }
<add> }
<add> if (i < ii) {
<add> warn('getOperatorList - ignoring operator: ' + fn);
<add> continue;
<add> }
<add> }
<ide> }
<ide> operatorList.addOp(fn, args);
<ide> }
<ide> var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
<ide> if (!args) {
<ide> args = [];
<ide> }
<del> args.push((obj instanceof Dict ? obj.getAll() : obj));
<add> args.push(obj);
<ide> assert(args.length <= 33, 'Too many arguments');
<ide> }
<ide> } | 1 |
Text | Text | fix a version number | 513f7b1bff6b79382b679b728c1435b91631aa7e | <ide><path>docs/templates/applications.md
<ide> Weights are downloaded automatically when instantiating a model. They are stored
<ide> All of these architectures are compatible with all the backends (TensorFlow, Theano, and CNTK), and upon instantiation the models will be built according to the image data format set in your Keras configuration file at `~/.keras/keras.json`. For instance, if you have set `image_data_format=channels_last`, then any model loaded from this repository will get built according to the TensorFlow data format convention, "Height-Width-Depth".
<ide>
<ide> Note that:
<del>- For `Keras < 2.1.7`, The Xception model is only available for TensorFlow, due to its reliance on `SeparableConvolution` layers.
<add>- For `Keras < 2.2.0`, The Xception model is only available for TensorFlow, due to its reliance on `SeparableConvolution` layers.
<ide> - For `Keras < 2.1.5`, The MobileNet model is only available for TensorFlow, due to its reliance on `DepthwiseConvolution` layers.
<ide>
<ide> ----- | 1 |
Java | Java | expose awaitterminationmillis presion | 0a974511bd4826136f0a6e8be3d326587314a229 | <ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public abstract class ExecutorConfigurationSupport extends CustomizableThreadFac
<ide>
<ide> private boolean waitForTasksToCompleteOnShutdown = false;
<ide>
<del> private int awaitTerminationSeconds = 0;
<add> private long awaitTerminationMillis = 0;
<ide>
<ide> @Nullable
<ide> private String beanName;
<ide> public void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnS
<ide> * @see java.util.concurrent.ExecutorService#awaitTermination
<ide> */
<ide> public void setAwaitTerminationSeconds(int awaitTerminationSeconds) {
<del> this.awaitTerminationSeconds = awaitTerminationSeconds;
<add> this.awaitTerminationMillis = awaitTerminationSeconds * 1000;
<ide> }
<ide>
<add> /**
<add> * Variant of {@link #setAwaitTerminationSeconds} with millisecond precision.
<add> * @since 5.2.4
<add> * @see java.util.concurrent.ExecutorService#shutdown()
<add> * @see java.util.concurrent.ExecutorService#awaitTermination
<add> */
<add> public void setAwaitTerminationMillis(long awaitTerminationMillis) {
<add> this.awaitTerminationMillis = awaitTerminationMillis;
<add> }
<add>
<add>
<ide> @Override
<ide> public void setBeanName(String name) {
<ide> this.beanName = name;
<ide> protected void cancelRemainingTask(Runnable task) {
<ide> * {@link #setAwaitTerminationSeconds "awaitTerminationSeconds"} property.
<ide> */
<ide> private void awaitTerminationIfNecessary(ExecutorService executor) {
<del> if (this.awaitTerminationSeconds > 0) {
<add> if (this.awaitTerminationMillis > 0) {
<ide> try {
<del> if (!executor.awaitTermination(this.awaitTerminationSeconds, TimeUnit.SECONDS)) {
<add> if (!executor.awaitTermination(this.awaitTerminationMillis, TimeUnit.MILLISECONDS)) {
<ide> if (logger.isWarnEnabled()) {
<ide> logger.warn("Timed out while waiting for executor" +
<ide> (this.beanName != null ? " '" + this.beanName + "'" : "") + " to terminate"); | 1 |
Javascript | Javascript | fix roughnessmipmapper | d80a715d0114903be289cd22312c2bcc287e5202 | <ide><path>examples/jsm/utils/RoughnessMipmapper.js
<ide> class RoughnessMipmapper {
<ide>
<ide> _renderer.copyFramebufferToTexture( position, material.roughnessMap, mip );
<ide>
<add> _mipmapMaterial.uniforms.roughnessMap.value = material.roughnessMap;
<add>
<ide> }
<ide>
<del> if ( roughnessMap !== material.roughnessMap ) roughnessMap.dispose();
<add> roughnessMap.dispose();
<ide>
<ide> _renderer.setRenderTarget( oldTarget );
<ide>
<ide><path>src/renderers/WebGLRenderer.js
<ide> function WebGLRenderer( parameters = {} ) {
<ide> const width = Math.floor( texture.image.width * levelScale );
<ide> const height = Math.floor( texture.image.height * levelScale );
<ide>
<del> let glFormat = utils.convert( texture.format );
<del>
<del> if ( capabilities.isWebGL2 ) {
<del>
<del> // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
<del> // Not needed in Chrome 93+
<del>
<del> if ( glFormat === _gl.RGB ) glFormat = _gl.RGB8;
<del> if ( glFormat === _gl.RGBA ) glFormat = _gl.RGBA8;
<del>
<del> }
<del>
<ide> textures.setTexture2D( texture, 0 );
<ide>
<del> _gl.copyTexImage2D( _gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0 );
<add> _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
<ide>
<ide> state.unbindTexture();
<ide>
<ide><path>src/renderers/webgl/WebGLTextures.js
<ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils,
<ide>
<ide> function getMipLevels( texture, image, supportsMips ) {
<ide>
<del> if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true ) {
<del>
<del> // generated mipmaps via gl.generateMipmap()
<add> if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
<ide>
<ide> return Math.log2( Math.max( image.width, image.height ) ) + 1;
<ide>
<ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils,
<ide>
<ide> } else if ( texture.isFramebufferTexture ) {
<ide>
<del> // texture data extracted from framebuffers require mutuable textures defined via gl.copyTexImage2D()
<add> if ( useTexStorage && allocateMemory ) {
<add>
<add> state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
<add>
<add> } else {
<add>
<add> state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
<add>
<add> }
<ide>
<ide> } else {
<ide> | 3 |
Javascript | Javascript | use memoizedstate in componentdidupdate | fae3e5308bca79da4f7acc2d06b8adc3fbb1ea27 | <ide><path>src/renderers/shared/fiber/ReactFiber.js
<ide> exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi
<ide> alt.pendingWorkPriority = priorityLevel;
<ide>
<ide> alt.memoizedProps = fiber.memoizedProps;
<add> alt.memoizedState = fiber.memoizedState;
<ide> alt.output = fiber.output;
<ide>
<ide> return alt;
<ide><path>src/renderers/shared/fiber/ReactFiberCommitWork.js
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> } else {
<ide> if (typeof instance.componentDidUpdate === 'function') {
<ide> const prevProps = current.memoizedProps;
<del> // TODO: This is the new state. We don't currently have the previous
<del> // state anymore.
<del> const prevState = instance.state || null;
<add> const prevState = current.memoizedState;
<ide> instance.componentDidUpdate(prevProps, prevState);
<ide> }
<ide> } | 2 |
Javascript | Javascript | remove picker from textlegend example | 70727a5d44958c8d35783466a4cda0665d8ee9af | <ide><path>packages/rn-tester/js/components/TextLegend.js
<ide> * @flow
<ide> */
<ide>
<del>const React = require('react');
<add>import * as React from 'react';
<add>import {Text, View, StyleSheet} from 'react-native';
<add>import RNTOption from './RNTOption';
<ide>
<del>const {Text, View} = require('react-native');
<del>import {Picker} from 'react-native';
<add>const PANGRAMS = {
<add> arabic:
<add> 'صِف خَلقَ خَودِ كَمِثلِ الشَمسِ إِذ بَزَغَت — يَحظى الضَجيعُ بِها نَجلاءَ مِعطارِ',
<add> chinese: 'Innovation in China 中国智造,慧及全球 0123456789',
<add> english: 'The quick brown fox jumps over the lazy dog.',
<add> emoji: '🙏🏾🚗💩😍🤯👩🏽🔧🇨🇦💯',
<add> german: 'Falsches Üben von Xylophonmusik quält jeden größeren Zwerg',
<add> greek: 'Ταχίστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός',
<add> hebrew: 'דג סקרן שט בים מאוכזב ולפתע מצא חברה',
<add> hindi:
<add> 'ऋषियों को सताने वाले दुष्ट राक्षसों के राजा रावण का सर्वनाश करने वाले विष्णुवतार भगवान श्रीराम, अयोध्या के महाराज दशरथ के बड़े सपुत्र थे।',
<add> igbo:
<add> 'Nne, nna, wepụ he’l’ụjọ dum n’ime ọzụzụ ụmụ, vufesi obi nye Chukwu, ṅụrịanụ, gbakọọnụ kpaa, kwee ya ka o guzoshie ike; ọ ghaghị ito, nwapụta ezi agwa',
<add> irish: 'D’fhuascail Íosa Úrmhac na hÓighe Beannaithe pór Éava agus Ádhaimh',
<add> japanese:
<add> '色は匂へど 散りぬるを 我が世誰ぞ 常ならむ 有為の奥山 今日越えて 浅き夢見じ 酔ひもせず',
<add> korean: '키스의 고유조건은 입술끼리 만나야 하고 특별한 기술은 필요치 않다',
<add> norwegian:
<add> 'Vår sære Zulu fra badeøya spilte jo whist og quickstep i min taxi.',
<add> polish: 'Jeżu klątw, spłódź Finom część gry hańb!',
<add> romanian: 'Muzicologă în bej vând whisky și tequila, preț fix.',
<add> russian: 'Эх, чужак, общий съём цен шляп (юфть) – вдрызг!',
<add> swedish: 'Yxskaftbud, ge vår WC-zonmö IQ-hjälp.',
<add> thai:
<add> 'เป็นมนุษย์สุดประเสริฐเลิศคุณค่า กว่าบรรดาฝูงสัตว์เดรัจฉาน จงฝ่าฟันพัฒนาวิชาการ อย่าล้างผลาญฤๅเข่นฆ่าบีฑาใคร ไม่ถือโทษโกรธแช่งซัดฮึดฮัดด่า หัดอภัยเหมือนกีฬาอัชฌาสัย ปฏิบัติประพฤติกฎกำหนดใจ พูดจาให้จ๊ะๆ จ๋าๆ น่าฟังเอยฯ',
<add>};
<ide>
<del>class TextLegend extends React.Component<*, *> {
<del> state: {|
<del> alignment: $TEMPORARY$string<'left'>,
<del> fontSize: number,
<del> language: $TEMPORARY$string<'english'>,
<del> textMetrics: Array<any>,
<del> |} = {
<del> textMetrics: [],
<del> language: 'english',
<del> alignment: 'left',
<del> fontSize: 50,
<del> };
<del>
<del> render(): React.Node {
<del> const PANGRAMS = {
<del> arabic:
<del> 'صِف خَلقَ خَودِ كَمِثلِ الشَمسِ إِذ بَزَغَت — يَحظى الضَجيعُ بِها نَجلاءَ مِعطارِ',
<del> chinese: 'Innovation in China 中国智造,慧及全球 0123456789',
<del> english: 'The quick brown fox jumps over the lazy dog.',
<del> emoji: '🙏🏾🚗💩😍🤯👩🏽🔧🇨🇦💯',
<del> german: 'Falsches Üben von Xylophonmusik quält jeden größeren Zwerg',
<del> greek: 'Ταχίστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός',
<del> hebrew: 'דג סקרן שט בים מאוכזב ולפתע מצא חברה',
<del> hindi:
<del> 'ऋषियों को सताने वाले दुष्ट राक्षसों के राजा रावण का सर्वनाश करने वाले विष्णुवतार भगवान श्रीराम, अयोध्या के महाराज दशरथ के बड़े सपुत्र थे।',
<del> igbo:
<del> 'Nne, nna, wepụ he’l’ụjọ dum n’ime ọzụzụ ụmụ, vufesi obi nye Chukwu, ṅụrịanụ, gbakọọnụ kpaa, kwee ya ka o guzoshie ike; ọ ghaghị ito, nwapụta ezi agwa',
<del> irish:
<del> 'D’fhuascail Íosa Úrmhac na hÓighe Beannaithe pór Éava agus Ádhaimh',
<del> japanese:
<del> '色は匂へど 散りぬるを 我が世誰ぞ 常ならむ 有為の奥山 今日越えて 浅き夢見じ 酔ひもせず',
<del> korean:
<del> '키스의 고유조건은 입술끼리 만나야 하고 특별한 기술은 필요치 않다',
<del> norwegian:
<del> 'Vår sære Zulu fra badeøya spilte jo whist og quickstep i min taxi.',
<del> polish: 'Jeżu klątw, spłódź Finom część gry hańb!',
<del> romanian: 'Muzicologă în bej vând whisky și tequila, preț fix.',
<del> russian: 'Эх, чужак, общий съём цен шляп (юфть) – вдрызг!',
<del> swedish: 'Yxskaftbud, ge vår WC-zonmö IQ-hjälp.',
<del> thai:
<del> 'เป็นมนุษย์สุดประเสริฐเลิศคุณค่า กว่าบรรดาฝูงสัตว์เดรัจฉาน จงฝ่าฟันพัฒนาวิชาการ อย่าล้างผลาญฤๅเข่นฆ่าบีฑาใคร ไม่ถือโทษโกรธแช่งซัดฮึดฮัดด่า หัดอภัยเหมือนกีฬาอัชฌาสัย ปฏิบัติประพฤติกฎกำหนดใจ พูดจาให้จ๊ะๆ จ๋าๆ น่าฟังเอยฯ',
<del> };
<del> return (
<del> <View>
<del> <Text
<del> onPress={() =>
<del> this.setState(prevState => ({fontSize: prevState.fontSize + 3}))
<del> }>
<del> Increase size
<del> </Text>
<del> <Text
<del> onPress={() =>
<del> this.setState(prevState => ({fontSize: prevState.fontSize - 3}))
<del> }>
<del> Decrease size
<del> </Text>
<del> <Picker
<del> selectedValue={this.state.language}
<del> onValueChange={itemValue => this.setState({language: itemValue})}>
<del> {Object.keys(PANGRAMS).map(x => (
<del> <Picker.Item
<del> label={x[0].toUpperCase() + x.substring(1)}
<del> key={x}
<del> value={x}
<add>export default function TextLegend(): React.Node {
<add> const [language, setLanguage] = React.useState('english');
<add> const [alignment, setAlignment] = React.useState('left');
<add> const [textMetrics, setTextMetrics] = React.useState([]);
<add> const [fontSize, setFontSize] = React.useState(50);
<add> return (
<add> <View>
<add> <Text onPress={() => setFontSize(fontSize + 3)}>Increase size</Text>
<add> <Text onPress={() => setFontSize(fontSize - 3)}>Decrease size</Text>
<add> <View style={styles.block}>
<add> <Text style={styles.title}>Language</Text>
<add> <View style={styles.row}>
<add> {Object.keys(PANGRAMS).map(lang => (
<add> <RNTOption
<add> label={lang[0].toUpperCase() + lang.substring(1)}
<add> key={lang}
<add> onPress={() => setLanguage(lang)}
<add> selected={lang === language}
<add> style={styles.option}
<ide> />
<ide> ))}
<del> </Picker>
<del> <View>
<del> {this.state.textMetrics.map(
<del> ({
<del> x,
<del> y,
<del> width,
<del> height,
<del> capHeight,
<del> ascender,
<del> descender,
<del> xHeight,
<del> }) => {
<del> return [
<del> <View
<del> key="baseline view"
<del> style={{
<del> top: y + ascender,
<del> height: 1,
<del> left: 0,
<del> right: 0,
<del> position: 'absolute',
<del> backgroundColor: 'red',
<del> }}
<del> />,
<del> <Text
<del> key="baseline text"
<del> style={{
<del> top: y + ascender,
<del> right: 0,
<del> position: 'absolute',
<del> color: 'red',
<del> }}>
<del> Baseline
<del> </Text>,
<del> <View
<del> key="capheight view"
<del> style={{
<del> top: y + ascender - capHeight,
<del> height: 1,
<del> left: 0,
<del> right: 0,
<del> position: 'absolute',
<del> backgroundColor: 'green',
<del> }}
<del> />,
<del> <Text
<del> key="capheight text"
<del> style={{
<del> top: y + ascender - capHeight,
<del> right: 0,
<del> position: 'absolute',
<del> color: 'green',
<del> }}>
<del> Capheight
<del> </Text>,
<del> <View
<del> key="xheight view"
<del> style={{
<del> top: y + ascender - xHeight,
<del> height: 1,
<del> left: 0,
<del> right: 0,
<del> position: 'absolute',
<del> backgroundColor: 'blue',
<del> }}
<del> />,
<del> <Text
<del> key="xheight text"
<del> style={{
<del> top: y + ascender - xHeight,
<del> right: 0,
<del> position: 'absolute',
<del> color: 'blue',
<del> }}>
<del> X-height
<del> </Text>,
<del> <View
<del> key="descender view"
<del> style={{
<del> top: y + ascender + descender,
<del> height: 1,
<del> left: 0,
<del> right: 0,
<del> position: 'absolute',
<del> backgroundColor: 'orange',
<del> }}
<del> />,
<del> <Text
<del> key="descender text"
<del> style={{
<del> top: y + ascender + descender,
<del> right: 0,
<del> position: 'absolute',
<del> color: 'orange',
<del> }}>
<del> Descender
<del> </Text>,
<del> <View
<del> key="end of text view"
<del> style={{
<del> top: y,
<del> height: height,
<del> width: 1,
<del> left: x + width,
<del> position: 'absolute',
<del> backgroundColor: 'brown',
<del> }}
<del> />,
<del> <Text
<del> key="end of text text"
<del> style={{
<del> top: y,
<del> left: x + width + 5,
<del> position: 'absolute',
<del> color: 'brown',
<del> }}>
<del> End of text
<del> </Text>,
<del> <View
<del> key="start of text view"
<del> style={{
<del> top: y,
<del> height: height,
<del> width: 1,
<del> left: x,
<del> position: 'absolute',
<del> backgroundColor: 'brown',
<del> }}
<del> />,
<del> <Text
<del> key="start of text text"
<del> style={{
<del> top: y,
<del> left: x + 5,
<del> position: 'absolute',
<del> color: 'brown',
<del> }}>
<del> Start of text
<del> </Text>,
<del> ];
<del> },
<del> )}
<del> <Text
<del> onTextLayout={event => {
<del> this.setState({textMetrics: event.nativeEvent.lines});
<del> }}
<del> style={{
<del> fontSize: this.state.fontSize,
<del> textAlign: this.state.alignment,
<del> }}>
<del> {PANGRAMS[this.state.language]}
<del> </Text>
<ide> </View>
<del> <Picker
<del> selectedValue={this.state.alignment}
<del> onValueChange={itemValue => this.setState({alignment: itemValue})}>
<del> <Picker.Item label="Left align" value="left" />
<del> <Picker.Item label="Center align" value="center" />
<del> <Picker.Item label="Right align" value="right" />
<del> </Picker>
<ide> </View>
<del> );
<del> }
<add> <View>
<add> {textMetrics.map(
<add> ({x, y, width, height, capHeight, ascender, descender, xHeight}) => {
<add> return [
<add> <View
<add> key="baseline view"
<add> style={{
<add> top: y + ascender,
<add> height: 1,
<add> left: 0,
<add> right: 0,
<add> position: 'absolute',
<add> backgroundColor: 'red',
<add> }}
<add> />,
<add> <Text
<add> key="baseline text"
<add> style={{
<add> top: y + ascender,
<add> right: 0,
<add> position: 'absolute',
<add> color: 'red',
<add> }}>
<add> Baseline
<add> </Text>,
<add> <View
<add> key="capheight view"
<add> style={{
<add> top: y + ascender - capHeight,
<add> height: 1,
<add> left: 0,
<add> right: 0,
<add> position: 'absolute',
<add> backgroundColor: 'green',
<add> }}
<add> />,
<add> <Text
<add> key="capheight text"
<add> style={{
<add> top: y + ascender - capHeight,
<add> right: 0,
<add> position: 'absolute',
<add> color: 'green',
<add> }}>
<add> Capheight
<add> </Text>,
<add> <View
<add> key="xheight view"
<add> style={{
<add> top: y + ascender - xHeight,
<add> height: 1,
<add> left: 0,
<add> right: 0,
<add> position: 'absolute',
<add> backgroundColor: 'blue',
<add> }}
<add> />,
<add> <Text
<add> key="xheight text"
<add> style={{
<add> top: y + ascender - xHeight,
<add> right: 0,
<add> position: 'absolute',
<add> color: 'blue',
<add> }}>
<add> X-height
<add> </Text>,
<add> <View
<add> key="descender view"
<add> style={{
<add> top: y + ascender + descender,
<add> height: 1,
<add> left: 0,
<add> right: 0,
<add> position: 'absolute',
<add> backgroundColor: 'orange',
<add> }}
<add> />,
<add> <Text
<add> key="descender text"
<add> style={{
<add> top: y + ascender + descender,
<add> right: 0,
<add> position: 'absolute',
<add> color: 'orange',
<add> }}>
<add> Descender
<add> </Text>,
<add> <View
<add> key="end of text view"
<add> style={{
<add> top: y,
<add> height: height,
<add> width: 1,
<add> left: x + width,
<add> position: 'absolute',
<add> backgroundColor: 'brown',
<add> }}
<add> />,
<add> <Text
<add> key="end of text text"
<add> style={{
<add> top: y,
<add> left: x + width + 5,
<add> position: 'absolute',
<add> color: 'brown',
<add> }}>
<add> End of text
<add> </Text>,
<add> <View
<add> key="start of text view"
<add> style={{
<add> top: y,
<add> height: height,
<add> width: 1,
<add> left: x,
<add> position: 'absolute',
<add> backgroundColor: 'brown',
<add> }}
<add> />,
<add> <Text
<add> key="start of text text"
<add> style={{
<add> top: y,
<add> left: x + 5,
<add> position: 'absolute',
<add> color: 'brown',
<add> }}>
<add> Start of text
<add> </Text>,
<add> ];
<add> },
<add> )}
<add> <Text
<add> onTextLayout={event => {
<add> setTextMetrics(event.nativeEvent.lines);
<add> }}
<add> style={{
<add> fontSize: fontSize,
<add> textAlign: alignment,
<add> }}>
<add> {PANGRAMS[language]}
<add> </Text>
<add> </View>
<add> <View style={styles.row}>
<add> <Text>Alignment:</Text>
<add> <RNTOption
<add> label="Left Align"
<add> key="left_align"
<add> onPress={() => setAlignment('left')}
<add> selected={alignment === 'left'}
<add> style={styles.option}
<add> />
<add> <RNTOption
<add> label="Center Align"
<add> key="center_align"
<add> onPress={() => setAlignment('center')}
<add> selected={alignment === 'center'}
<add> style={styles.option}
<add> />
<add> <RNTOption
<add> label="Right Align"
<add> key="right_align"
<add> onPress={() => setAlignment('right')}
<add> selected={alignment === 'right'}
<add> style={styles.option}
<add> />
<add> </View>
<add> </View>
<add> );
<ide> }
<del>module.exports = TextLegend;
<add>
<add>const styles = StyleSheet.create({
<add> row: {
<add> flexDirection: 'row',
<add> flexWrap: 'wrap',
<add> margin: 6,
<add> alignItems: 'center',
<add> },
<add> title: {
<add> fontWeight: 'bold',
<add> },
<add> block: {
<add> borderColor: 'rgba(0,0,0, 0.1)',
<add> borderBottomWidth: 1,
<add> padding: 6,
<add> },
<add> option: {
<add> margin: 4,
<add> },
<add>});
<ide><path>packages/rn-tester/js/examples/Text/TextExample.android.js
<ide> const RNTesterBlock = require('../../components/RNTesterBlock');
<ide> const RNTesterPage = require('../../components/RNTesterPage');
<ide> const React = require('react');
<ide> const TextInlineView = require('../../components/TextInlineView');
<del>const TextLegend = require('../../components/TextLegend');
<add>import TextLegend from '../../components/TextLegend';
<ide>
<ide> const {LayoutAnimation, StyleSheet, Text, View} = require('react-native');
<ide>
<ide><path>packages/rn-tester/js/examples/Text/TextExample.ios.js
<ide> const React = require('react');
<ide> const TextAncestor = require('react-native/Libraries/Text/TextAncestor');
<ide> const TextInlineView = require('../../components/TextInlineView');
<del>const TextLegend = require('../../components/TextLegend');
<add>import TextLegend from '../../components/TextLegend';
<ide>
<ide> const {
<ide> Button, | 3 |
Go | Go | check the exit codes | ac36c986e008e8e4e4f56fe510ba7ab0dab0c778 | <ide><path>container_test.go
<ide> func TestUser(t *testing.T) {
<ide> }
<ide> defer docker.Destroy(container)
<ide> output, err = container.Output()
<del> if err != nil {
<add> if err != nil || container.State.ExitCode != 0 {
<ide> t.Fatal(err)
<ide> }
<ide> if !strings.Contains(string(output), "uid=0(root) gid=0(root)") {
<ide> func TestUser(t *testing.T) {
<ide> User: "0",
<ide> },
<ide> )
<del> if err != nil {
<add> if err != nil || container.State.ExitCode != 0 {
<ide> t.Fatal(err)
<ide> }
<ide> defer docker.Destroy(container)
<ide> output, err = container.Output()
<del> if err != nil {
<add> if err != nil || container.State.ExitCode != 0 {
<ide> t.Fatal(err)
<ide> }
<ide> if !strings.Contains(string(output), "uid=0(root) gid=0(root)") {
<ide> func TestUser(t *testing.T) {
<ide> }
<ide> defer docker.Destroy(container)
<ide> output, err = container.Output()
<del> if err != nil {
<add> if err != nil || container.State.ExitCode != 0 {
<ide> t.Fatal(err)
<ide> }
<ide> if !strings.Contains(string(output), "uid=1(daemon) gid=1(daemon)") {
<ide> func TestUser(t *testing.T) {
<ide> }
<ide> defer docker.Destroy(container)
<ide> output, err = container.Output()
<del> if err != nil {
<add> if err != nil || container.State.ExitCode != 0 {
<ide> t.Fatal(err)
<ide> }
<ide> if !strings.Contains(string(output), "uid=1(daemon) gid=1(daemon)") { | 1 |
Ruby | Ruby | prevent lockfile modification during installation | 5e31f41a52808fa09d6afecc4f6b92cf77980690 | <ide><path>Library/Homebrew/utils/gems.rb
<ide> def install_bundler_gems!(only_warn_on_failure: false, setup_path: true, groups:
<ide> old_gem_home = ENV.fetch("GEM_HOME", nil)
<ide> old_bundle_gemfile = ENV.fetch("BUNDLE_GEMFILE", nil)
<ide> old_bundle_with = ENV.fetch("BUNDLE_WITH", nil)
<add> old_bundle_frozen = ENV.fetch("BUNDLE_FROZEN", nil)
<ide>
<ide> install_bundler!
<ide>
<ide> def install_bundler_gems!(only_warn_on_failure: false, setup_path: true, groups:
<ide>
<ide> ENV["BUNDLE_GEMFILE"] = File.join(ENV.fetch("HOMEBREW_LIBRARY"), "Homebrew", "Gemfile")
<ide> ENV["BUNDLE_WITH"] = groups.join(" ")
<add> ENV["BUNDLE_FROZEN"] = "true"
<ide>
<ide> if @bundle_installed_groups != groups
<ide> bundle = File.join(find_in_path("bundle"), "bundle")
<ide> def install_bundler_gems!(only_warn_on_failure: false, setup_path: true, groups:
<ide> ENV["GEM_HOME"] = old_gem_home
<ide> ENV["BUNDLE_GEMFILE"] = old_bundle_gemfile
<ide> ENV["BUNDLE_WITH"] = old_bundle_with
<add> ENV["BUNDLE_FROZEN"] = old_bundle_frozen
<ide> end
<ide> end
<ide> end | 1 |
Ruby | Ruby | exclude zsh completions from unbrewed | 8e42077a8eeb827c3ffcdf08195239c8f82cb588 | <ide><path>Library/Homebrew/cmd/list.rb
<ide> def list
<ide> share/info/dir
<ide> share/man/man1/brew.1
<ide> share/man/whatis
<add> share/zsh/site-functions/_brew
<ide> ]
<ide>
<ide> def list_unbrewed | 1 |
Ruby | Ruby | use the accessors to update the test double | 372945299dc52b04338ad58ac666f105e2f463f2 | <ide><path>Library/Homebrew/test/test_compiler_selector.rb
<ide> def test_mixed_failures_4
<ide> end
<ide>
<ide> def test_older_clang_precedence
<del> @versions = CompilerVersions.new(:clang_build_version => 211)
<add> @versions.clang_build_version = 211
<ide> @f << :gcc << { :gcc => "4.8" }
<ide> assert_equal :llvm, actual_cc
<ide> end
<ide> def test_llvm_precedence
<ide> end
<ide>
<ide> def test_missing_gcc
<del> @versions = CompilerVersions.new(:gcc_build_version => nil)
<add> @versions.gcc_build_version = nil
<ide> @f << :clang << :llvm << { :gcc => "4.8" }
<ide> assert_raises(CompilerSelectionError) { actual_cc }
<ide> end
<ide>
<ide> def test_missing_llvm_and_gcc
<del> @versions = CompilerVersions.new(
<del> :gcc_build_version => nil,
<del> :llvm_build_version => nil
<del> )
<add> @versions.gcc_build_version = @versions.llvm_build_version = nil
<ide> @f << :clang << { :gcc => "4.8" }
<ide> assert_raises(CompilerSelectionError) { actual_cc }
<ide> end | 1 |
Javascript | Javascript | remove unused ecdhpeerkey | c88096507422978ccc4718fe7fa82e0b5608da1d | <ide><path>test/parallel/test-webcrypto-wrap-unwrap.js
<ide> async function testWrap(wrappingKey, unwrappingKey, key, wrap, format) {
<ide> assert.deepStrictEqual(exported, exportedAgain);
<ide> }
<ide>
<del>async function testWrapping(name, keys, ecdhPeerKey) {
<add>async function testWrapping(name, keys) {
<ide> const variations = [];
<ide>
<ide> const {
<ide> async function testWrapping(name, keys, ecdhPeerKey) {
<ide> (async function() {
<ide> await generateWrappingKeys();
<ide> const keys = await generateKeysToWrap();
<del> const ecdhPeerKey = await subtle.generateKey({
<del> name: 'ECDH',
<del> namedCurve: 'P-384'
<del> }, true, ['deriveBits']);
<ide> const variations = [];
<ide> Object.keys(kWrappingData).forEach((name) => {
<del> return testWrapping(name, keys, ecdhPeerKey);
<add> return testWrapping(name, keys);
<ide> });
<ide> await Promise.all(variations);
<ide> })().then(common.mustCall()); | 1 |
Python | Python | use spacy hash_string function instead of md5 | f4748834d973a525024cac18fb58fe9934957170 | <ide><path>spacy/pattern/parser.py
<ide> # coding: utf-8
<ide>
<ide> from spacy.compat import intern, queue
<add>from spacy.strings import hash_string
<ide> from operator import itemgetter
<ide> import re
<del>from hashlib import md5
<ide> import json
<ide>
<ide> from .pattern import DependencyPattern
<ide> def __new__(cls, lineno, type, value):
<ide> return tuple.__new__(cls, (lineno, intern(str(type)), value))
<ide>
<ide> def hash(self):
<del> string = str(self.value)
<del> return md5(string.encode('utf-8')).hexdigest()
<add> string = self.value
<add> return hash_string(string)
<ide>
<ide> def __repr__(self):
<ide> return 'Token(%r, %r, %r)' % ( | 1 |
Go | Go | add getter function for default address pools | 814f6c1f4b06a71e529421f426450ffa993fc0b4 | <ide><path>libnetwork/ipam/allocator.go
<ide> func NewAllocator(lcDs, glDs datastore.DataStore) (*Allocator, error) {
<ide> a := &Allocator{}
<ide>
<ide> // Load predefined subnet pools
<add>
<ide> a.predefined = map[string][]*net.IPNet{
<del> localAddressSpace: ipamutils.PredefinedLocalScopeDefaultNetworks,
<del> globalAddressSpace: ipamutils.PredefinedGlobalScopeDefaultNetworks,
<add> localAddressSpace: ipamutils.GetLocalScopeDefaultNetworks(),
<add> globalAddressSpace: ipamutils.GetGlobalScopeDefaultNetworks(),
<ide> }
<ide>
<ide> // Initialize asIndices map
<ide><path>libnetwork/ipamutils/utils.go
<ide> func configDefaultNetworks(defaultAddressPool []*NetworkToSplit, result *[]*net.
<ide> return nil
<ide> }
<ide>
<add>// GetGlobalScopeDefaultNetworks returns PredefinedGlobalScopeDefaultNetworks
<add>func GetGlobalScopeDefaultNetworks() []*net.IPNet {
<add> mutex.Lock()
<add> defer mutex.Unlock()
<add> return PredefinedGlobalScopeDefaultNetworks
<add>}
<add>
<add>// GetLocalScopeDefaultNetworks returns PredefinedLocalScopeDefaultNetworks
<add>func GetLocalScopeDefaultNetworks() []*net.IPNet {
<add> mutex.Lock()
<add> defer mutex.Unlock()
<add> return PredefinedLocalScopeDefaultNetworks
<add>}
<add>
<ide> // ConfigGlobalScopeDefaultNetworks configures global default pool.
<ide> // Ideally this will be called from SwarmKit as part of swarm init
<ide> func ConfigGlobalScopeDefaultNetworks(defaultAddressPool []*NetworkToSplit) error { | 2 |
Ruby | Ruby | fix another handful of warnings | aa58a404eda3eb4ef1e0f09df8509fba3da5c851 | <ide><path>Library/Homebrew/cmd/bottle.rb
<ide> def keg_contains string, keg
<ide> def bottle_formula f
<ide> unless f.installed?
<ide> return ofail "Formula not installed: #{f.name}"
<del> return
<ide> end
<ide>
<ide> unless built_as_bottle? f
<ide><path>Library/Homebrew/cmd/edit.rb
<ide> def edit
<ide> raise FormulaUnavailableError, path.basename('.rb').to_s unless path.file?
<ide> end
<ide> end
<del> exec_editor *paths
<add> exec_editor(*paths)
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/cmd/home.rb
<ide> def home
<ide> if ARGV.named.empty?
<ide> exec_browser HOMEBREW_WWW
<ide> else
<del> exec_browser *ARGV.formulae.map{ |f| f.homepage }
<add> exec_browser(*ARGV.formulae.map(&:homepage))
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cmd/link.rb
<ide> def self.puts str
<ide> end
<ide> end
<ide>
<del> puts_capture.instance_eval &block
<add> puts_capture.instance_eval(&block)
<ide>
<ide> ensure
<ide> puts unless $did_puts
<ide><path>Library/Homebrew/cmd/uninstall.rb
<ide> def uninstall
<ide> keg.unlink
<ide> keg.uninstall
<ide> rm_opt_link keg.fname
<del> unpin keg.fname
<add> rm_pin keg.fname
<ide> end
<ide> end
<ide> else
<ide> def rm_opt_link name
<ide> optlink.unlink if optlink.symlink?
<ide> end
<ide>
<del> def unpin name
<add> def rm_pin name
<ide> Formula.factory(name).unpin rescue nil
<ide> end
<ide> end
<ide><path>Library/Homebrew/superenv.rb
<ide> def make_jobs
<ide> # This should be a safe hack to prevent that exception cropping up.
<ide> # Main consqeuence of this is that ENV['CFLAGS'] is never nil even when it
<ide> # is which can break if checks, but we don't do such a check in our code.
<add> alias_method :"old_[]", :[]
<ide> def [] key
<ide> if has_key? key
<ide> fetch(key) | 6 |
Python | Python | add a comment to avoid accidental removal | 0c284e39681ed4b47970196e8dc774e0aae94983 | <ide><path>runtests.py
<ide> def main(argv):
<ide> "version; remove -g flag ***")
<ide>
<ide> if not args.no_build:
<add> # we need the noarch path in case the package is pure python.
<ide> site_dir, site_dir_noarch = build_project(args)
<ide> sys.path.insert(0, site_dir)
<ide> sys.path.insert(0, site_dir_noarch) | 1 |
PHP | PHP | remove additional references to containable | ebc3cb716dd7cd1c18db9adc13f229051b93183e | <ide><path>Cake/Model/Model.php
<ide> class Model extends Object implements EventListener {
<ide> */
<ide> public $__backOriginalAssociation = array();
<ide>
<del>/**
<del> * Back containable association
<del> *
<del> * @var array
<del> */
<del> public $__backContainableAssociation = array();
<del>
<ide> // @codingStandardsIgnoreEnd
<ide>
<ide> /**
<ide><path>Cake/Test/TestCase/Console/Command/Task/TestTaskTest.php
<ide> public function testGetRealClassname() {
<ide> $result = $this->Task->getRealClassname('Helper', 'FormHelper');
<ide> $this->assertEquals('App\View\Helper\FormHelper', $result);
<ide>
<del> $result = $this->Task->getRealClassname('Behavior', 'Containable');
<del> $this->assertEquals('App\Model\Behavior\ContainableBehavior', $result);
<del>
<del> $result = $this->Task->getRealClassname('Behavior', 'ContainableBehavior');
<del> $this->assertEquals('App\Model\Behavior\ContainableBehavior', $result);
<add> $result = $this->Task->getRealClassname('Behavior', 'Tree');
<add> $this->assertEquals('App\Model\Behavior\TreeBehavior', $result);
<ide>
<ide> $result = $this->Task->getRealClassname('Component', 'Auth');
<ide> $this->assertEquals('App\Controller\Component\AuthComponent', $result);
<ide> public static function caseFileNameProvider() {
<ide> array('Model', 'Post', 'TestCase/Model/PostTest.php'),
<ide> array('Helper', 'Form', 'TestCase/View/Helper/FormHelperTest.php'),
<ide> array('Controller', 'Posts', 'TestCase/Controller/PostsControllerTest.php'),
<del> array('Behavior', 'Containable', 'TestCase/Model/Behavior/ContainableBehaviorTest.php'),
<add> array('Behavior', 'Tree', 'TestCase/Model/Behavior/TreeBehaviorTest.php'),
<ide> array('Component', 'Auth', 'TestCase/Controller/Component/AuthComponentTest.php'),
<ide> array('model', 'Post', 'TestCase/Model/PostTest.php'),
<ide> array('helper', 'Form', 'TestCase/View/Helper/FormHelperTest.php'),
<ide> array('controller', 'Posts', 'TestCase/Controller/PostsControllerTest.php'),
<del> array('behavior', 'Containable', 'TestCase/Model/Behavior/ContainableBehaviorTest.php'),
<add> array('behavior', 'Tree', 'TestCase/Model/Behavior/TreeBehaviorTest.php'),
<ide> array('component', 'Auth', 'TestCase/Controller/Component/AuthComponentTest.php'),
<ide> );
<ide> }
<ide><path>Cake/Test/TestCase/Model/ModelIntegrationTest.php
<ide> public function testConstruct() {
<ide> $this->loadFixtures('Post');
<ide>
<ide> $TestModel = ClassRegistry::init('MergeVarPluginPost');
<del> $this->assertEquals(array('Containable' => null, 'Tree' => null), $TestModel->actsAs);
<del> $this->assertTrue(isset($TestModel->Behaviors->Containable));
<add> $this->assertEquals(array('Tree' => null), $TestModel->actsAs);
<ide> $this->assertTrue(isset($TestModel->Behaviors->Tree));
<del>
<del> $TestModel = ClassRegistry::init('MergeVarPluginComment');
<del> $expected = array('Containable' => array('some_settings'));
<del> $this->assertEquals($expected, $TestModel->actsAs);
<del> $this->assertTrue(isset($TestModel->Behaviors->Containable));
<ide> }
<ide>
<ide> /**
<ide><path>Cake/Test/TestCase/Model/ModelValidationTest.php
<ide> public function testGetMethodsRefresh() {
<ide> $expected = array_map('strtolower', get_class_methods('Article'));
<ide> $this->assertEquals($expected, array_keys($result));
<ide>
<del> $TestModel->Behaviors->load('Containable');
<add> $TestModel->Behaviors->load('Tree');
<ide> $newList = array(
<del> 'contain',
<del> 'resetbindings',
<del> 'containments',
<del> 'fielddependencies',
<del> 'containmentsmap'
<add> 'childcount',
<add> 'children',
<add> 'generatetreelist',
<add> 'getparentnode',
<add> 'getpath',
<add> 'movedown',
<add> 'moveup',
<add> 'recover',
<add> 'reorder',
<add> 'removefromtree',
<add> 'verify',
<ide> );
<ide> $this->assertEquals(array_merge($expected, $newList), array_keys($Validator->getMethods()));
<ide>
<del> $TestModel->Behaviors->unload('Containable');
<add> $TestModel->Behaviors->unload('Tree');
<ide> $this->assertEquals($expected, array_keys($Validator->getMethods()));
<ide> }
<ide>
<ide><path>Cake/Test/TestCase/Model/models.php
<ide> class User extends CakeTestModel {
<ide> public $validate = array('user' => 'notEmpty', 'password' => 'notEmpty');
<ide>
<ide> /**
<del> * beforeFind() callback used to run ContainableBehaviorTest::testLazyLoad()
<add> * beforeFind() callback
<ide> *
<ide> * @return boolean
<ide> * @throws \Exception
<ide> public function afterFind($results, $primary = false) {
<ide> */
<ide> class MergeVarPluginAppModel extends Model {
<ide>
<del>/**
<del> * actsAs parameter
<del> *
<del> * @var array
<del> */
<del> public $actsAs = array(
<del> 'Containable'
<del> );
<ide> }
<ide>
<ide> /**
<ide> class MergeVarPluginPost extends MergeVarPluginAppModel {
<ide> */
<ide> class MergeVarPluginComment extends MergeVarPluginAppModel {
<ide>
<del>/**
<del> * actsAs parameter
<del> *
<del> * @var array
<del> */
<del> public $actsAs = array(
<del> 'Containable' => array('some_settings')
<del> );
<del>
<ide> /**
<ide> * useTable parameter
<ide> * | 5 |
Ruby | Ruby | prefer string interpolation over direct mutation | 7c936996a40291b71bdeeee7a3de1aa32bc4a4d8 | <ide><path>actionpack/lib/action_dispatch/http/response.rb
<ide> def parsed_content_type_header
<ide> end
<ide>
<ide> def set_content_type(content_type, charset)
<del> type = +(content_type || "")
<del> type << "; charset=#{charset.to_s.downcase}" if charset
<add> type = content_type || ""
<add> type = "#{type}; charset=#{charset.to_s.downcase}" if charset
<ide> set_header CONTENT_TYPE, type
<ide> end
<ide> | 1 |
Go | Go | skip privileged tests when non-root | 6349b32e1b3e8d5e219452c0662909e5e7fb222d | <ide><path>daemon/oci_linux_test.go
<ide> import (
<ide> "github.com/docker/libnetwork"
<ide> "gotest.tools/v3/assert"
<ide> is "gotest.tools/v3/assert/cmp"
<add> "gotest.tools/v3/skip"
<ide> )
<ide>
<ide> func setupFakeDaemon(t *testing.T, c *container.Container) *Daemon {
<ide> func cleanupFakeContainer(c *container.Container) {
<ide> // in "Duplicate mount point" error from the engine.
<ide> // https://github.com/moby/moby/issues/35455
<ide> func TestTmpfsDevShmNoDupMount(t *testing.T) {
<add> skip.If(t, os.Getuid() != 0, "skipping test that requires root")
<ide> c := &container.Container{
<ide> ShmPath: "foobar", // non-empty, for c.IpcMounts() to work
<ide> HostConfig: &containertypes.HostConfig{
<ide> func TestTmpfsDevShmNoDupMount(t *testing.T) {
<ide> // the resulting /dev/shm mount is NOT made read-only.
<ide> // https://github.com/moby/moby/issues/36503
<ide> func TestIpcPrivateVsReadonly(t *testing.T) {
<add> skip.If(t, os.Getuid() != 0, "skipping test that requires root")
<ide> c := &container.Container{
<ide> HostConfig: &containertypes.HostConfig{
<ide> IpcMode: containertypes.IpcMode("private"),
<ide> func TestIpcPrivateVsReadonly(t *testing.T) {
<ide> // TestSysctlOverride ensures that any implicit sysctls (such as
<ide> // Config.Domainname) are overridden by an explicit sysctl in the HostConfig.
<ide> func TestSysctlOverride(t *testing.T) {
<add> skip.If(t, os.Getuid() != 0, "skipping test that requires root")
<ide> c := &container.Container{
<ide> Config: &containertypes.Config{
<ide> Hostname: "foobar",
<ide> func TestSysctlOverride(t *testing.T) {
<ide> // TestSysctlOverrideHost ensures that any implicit network sysctls are not set
<ide> // with host networking
<ide> func TestSysctlOverrideHost(t *testing.T) {
<add> skip.If(t, os.Getuid() != 0, "skipping test that requires root")
<ide> c := &container.Container{
<ide> Config: &containertypes.Config{},
<ide> HostConfig: &containertypes.HostConfig{ | 1 |
Java | Java | add more systraces | 857be044ccf3085eb9c9e1561f51132882dbfd9c | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> import java.util.List;
<ide>
<ide> import android.app.Activity;
<del>import android.app.Application;
<ide> import android.content.Context;
<ide> import android.content.Intent;
<ide> import android.net.Uri;
<del>import android.os.Bundle;
<ide> import android.os.Process;
<ide> import android.view.View;
<ide>
<ide> import com.facebook.react.bridge.ReactContext;
<ide> import com.facebook.react.bridge.ReactMarker;
<ide> import com.facebook.react.bridge.ReactMarkerConstants;
<del>import com.facebook.react.bridge.WritableMap;
<del>import com.facebook.react.bridge.WritableNativeMap;
<ide> import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec;
<ide> import com.facebook.react.common.LifecycleState;
<ide> import com.facebook.react.common.ReactConstants;
<ide> import com.facebook.react.common.annotations.VisibleForTesting;
<del>import com.facebook.react.cxxbridge.Arguments;
<ide> import com.facebook.react.cxxbridge.CatalystInstanceImpl;
<ide> import com.facebook.react.cxxbridge.JSBundleLoader;
<ide> import com.facebook.react.cxxbridge.JSCJavaScriptExecutor;
<ide> private void attachMeasuredRootViewToInstance(
<ide> }
<ide>
<ide> UIManagerModule uiManagerModule = catalystInstance.getNativeModule(UIManagerModule.class);
<del> int rootTag = uiManagerModule.addMeasuredRootView(rootView);
<add> final int rootTag = uiManagerModule.addMeasuredRootView(rootView);
<ide> rootView.setRootViewTag(rootTag);
<ide> rootView.runApplication();
<add> Systrace.beginAsyncSection(
<add> TRACE_TAG_REACT_JAVA_BRIDGE,
<add> "pre_rootView.onAttachedToReactInstance",
<add> rootTag);
<ide> UiThreadUtil.runOnUiThread(new Runnable() {
<ide> @Override
<ide> public void run() {
<add> Systrace.endAsyncSection(
<add> TRACE_TAG_REACT_JAVA_BRIDGE,
<add> "pre_rootView.onAttachedToReactInstance",
<add> rootTag);
<ide> rootView.onAttachedToReactInstance();
<ide> }
<ide> });
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java
<ide> import com.facebook.react.uimanager.SizeMonitoringFrameLayout;
<ide> import com.facebook.react.uimanager.UIManagerModule;
<ide> import com.facebook.react.uimanager.events.EventDispatcher;
<add>import com.facebook.systrace.Systrace;
<add>
<add>import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE;
<ide>
<ide> /**
<ide> * Default root view for catalyst apps. Provides the ability to listen for size changes so that a UI
<ide> public void setAppProperties(@Nullable Bundle appProperties) {
<ide> * same rootTag, which will re-render the application from the root.
<ide> */
<ide> /* package */ void runApplication() {
<del> if (mReactInstanceManager == null || !mIsAttachedToInstance) {
<del> return;
<del> }
<add> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.runApplication");
<add> try {
<add> if (mReactInstanceManager == null || !mIsAttachedToInstance) {
<add> return;
<add> }
<ide>
<del> ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
<del> if (reactContext == null) {
<del> return;
<del> }
<add> ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
<add> if (reactContext == null) {
<add> return;
<add> }
<ide>
<del> CatalystInstance catalystInstance = reactContext.getCatalystInstance();
<add> CatalystInstance catalystInstance = reactContext.getCatalystInstance();
<ide>
<del> WritableNativeMap appParams = new WritableNativeMap();
<del> appParams.putDouble("rootTag", getRootViewTag());
<del> @Nullable Bundle appProperties = getAppProperties();
<del> if (appProperties != null) {
<del> appParams.putMap("initialProps", Arguments.fromBundle(appProperties));
<del> }
<add> WritableNativeMap appParams = new WritableNativeMap();
<add> appParams.putDouble("rootTag", getRootViewTag());
<add> @Nullable Bundle appProperties = getAppProperties();
<add> if (appProperties != null) {
<add> appParams.putMap("initialProps", Arguments.fromBundle(appProperties));
<add> }
<ide>
<del> String jsAppModuleName = getJSModuleName();
<del> catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams);
<add> String jsAppModuleName = getJSModuleName();
<add> catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams);
<add> } finally {
<add> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java
<ide> public Map<String,Double> getPerformanceCounters() {
<ide> * NB: this method is horribly not-thread-safe.
<ide> */
<ide> public int addMeasuredRootView(final SizeMonitoringFrameLayout rootView) {
<add> Systrace.beginSection(
<add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE,
<add> "UIManagerModule.addMeasuredRootView");
<ide> final int tag = mNextRootViewTag;
<ide> mNextRootViewTag += ROOT_VIEW_TAG_INCREMENT;
<ide>
<ide> public void runGuarded() {
<ide> }
<ide> });
<ide>
<add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<ide> return tag;
<ide> }
<ide> | 3 |
Javascript | Javascript | fix missing return statement in copy functions | 451d16f6787156568b5df26365425f71ab9fdb09 | <ide><path>examples/jsm/nodes/accessors/CameraNode.js
<ide> CameraNode.prototype.copy = function ( source ) {
<ide>
<ide> }
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> CameraNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/accessors/ColorsNode.js
<ide> ColorsNode.prototype.copy = function ( source ) {
<ide>
<ide> this.index = source.index;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> ColorsNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/accessors/LightNode.js
<ide> LightNode.prototype.copy = function ( source ) {
<ide>
<ide> this.scope = source.scope;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> LightNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/accessors/NormalNode.js
<ide> NormalNode.prototype.copy = function ( source ) {
<ide>
<ide> this.scope = source.scope;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> NormalNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/accessors/PositionNode.js
<ide> PositionNode.prototype.copy = function ( source ) {
<ide>
<ide> this.scope = source.scope;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> PositionNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/accessors/ResolutionNode.js
<ide> ResolutionNode.prototype.copy = function ( source ) {
<ide>
<ide> this.renderer = source.renderer;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> ResolutionNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/accessors/ScreenUVNode.js
<ide> ScreenUVNode.prototype.copy = function ( source ) {
<ide>
<ide> this.resolution = source.resolution;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> ScreenUVNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/accessors/UVNode.js
<ide> UVNode.prototype.copy = function ( source ) {
<ide>
<ide> this.index = source.index;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> UVNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/bsdfs/BlinnExponentToRoughnessNode.js
<ide> BlinnExponentToRoughnessNode.prototype.copy = function ( source ) {
<ide>
<ide> this.blinnExponent = source.blinnExponent;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> BlinnExponentToRoughnessNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/bsdfs/RoughnessToBlinnExponentNode.js
<ide> RoughnessToBlinnExponentNode.prototype.copy = function ( source ) {
<ide>
<ide> this.texture = source.texture;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> RoughnessToBlinnExponentNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/core/AttributeNode.js
<ide> AttributeNode.prototype.copy = function ( source ) {
<ide>
<ide> this.type = source.type;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> AttributeNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/core/ConstNode.js
<ide> ConstNode.prototype.copy = function ( source ) {
<ide>
<ide> this.parse( source.src, source.useDefine );
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> ConstNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/core/FunctionCallNode.js
<ide> FunctionCallNode.prototype.copy = function ( source ) {
<ide>
<ide> this.value = source.value;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> FunctionCallNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/core/FunctionNode.js
<ide> FunctionNode.prototype.copy = function ( source ) {
<ide>
<ide> if ( source.type !== undefined ) this.type = source.type;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> FunctionNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/core/InputNode.js
<ide> InputNode.prototype.copy = function ( source ) {
<ide>
<ide> if ( source.readonly !== undefined ) this.readonly = source.readonly;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> InputNode.prototype.createJSONNode = function ( meta ) {
<ide><path>examples/jsm/nodes/core/Node.js
<ide> Node.prototype = {
<ide>
<ide> if ( source.userData !== undefined ) this.userData = JSON.parse( JSON.stringify( source.userData ) );
<ide>
<add> return this;
<add>
<ide> },
<ide>
<ide> createJSONNode: function ( meta ) {
<ide><path>examples/jsm/nodes/core/VarNode.js
<ide> VarNode.prototype.copy = function ( source ) {
<ide> this.type = source.type;
<ide> this.value = source.value;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> VarNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/effects/BlurNode.js
<ide> BlurNode.prototype.copy = function ( source ) {
<ide> this.blurX = source.blurX;
<ide> this.blurY = source.blurY;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> BlurNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/effects/ColorAdjustmentNode.js
<ide> ColorAdjustmentNode.prototype.copy = function ( source ) {
<ide> this.adjustment = source.adjustment;
<ide> this.method = source.method;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> ColorAdjustmentNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/effects/LuminanceNode.js
<ide> LuminanceNode.prototype.copy = function ( source ) {
<ide>
<ide> this.rgb = source.rgb;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> LuminanceNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/BoolNode.js
<ide> BoolNode.prototype.copy = function ( source ) {
<ide>
<ide> this.value = source.value;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> BoolNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/ColorNode.js
<ide> ColorNode.prototype.copy = function ( source ) {
<ide>
<ide> this.value.copy( source );
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> ColorNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/CubeTextureNode.js
<ide> CubeTextureNode.prototype.copy = function ( source ) {
<ide>
<ide> if ( source.bias ) this.bias = source.bias;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> CubeTextureNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/FloatNode.js
<ide> FloatNode.prototype.copy = function ( source ) {
<ide>
<ide> this.value = source.value;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> FloatNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/IntNode.js
<ide> IntNode.prototype.copy = function ( source ) {
<ide>
<ide> this.value = source.value;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> IntNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/Matrix3Node.js
<ide> Matrix3Node.prototype.copy = function ( source ) {
<ide>
<ide> this.value.fromArray( source.elements );
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> Matrix3Node.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/Matrix4Node.js
<ide> Matrix4Node.prototype.copy = function ( source ) {
<ide>
<ide> this.scope.value.fromArray( source.elements );
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> Matrix4Node.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/RTTNode.js
<ide> RTTNode.prototype.copy = function ( source ) {
<ide>
<ide> this.saveTo = source.saveTo;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> RTTNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/ReflectorNode.js
<ide> ReflectorNode.prototype.copy = function ( source ) {
<ide>
<ide> this.scope.mirror = source.mirror;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> ReflectorNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/TextureNode.js
<ide> TextureNode.prototype.copy = function ( source ) {
<ide> if ( source.bias ) this.bias = source.bias;
<ide> if ( source.project !== undefined ) this.project = source.project;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> TextureNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/Vector2Node.js
<ide> Vector2Node.prototype.copy = function ( source ) {
<ide>
<ide> this.value.copy( source );
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> Vector2Node.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/Vector3Node.js
<ide> Vector3Node.prototype.copy = function ( source ) {
<ide>
<ide> this.value.copy( source );
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> Vector3Node.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/inputs/Vector4Node.js
<ide> Vector4Node.prototype.copy = function ( source ) {
<ide>
<ide> this.value.copy( source );
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> Vector4Node.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/materials/NodeMaterial.js
<ide> NodeMaterial.prototype.copy = function ( source ) {
<ide>
<ide> }
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> NodeMaterial.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/materials/nodes/PhongNode.js
<ide> PhongNode.prototype.copy = function ( source ) {
<ide> if ( source.environment ) this.environment = source.environment;
<ide> if ( source.environmentAlpha ) this.environmentAlpha = source.environmentAlpha;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> PhongNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/materials/nodes/RawNode.js
<ide> RawNode.prototype.copy = function ( source ) {
<ide>
<ide> this.value = source.value;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> RawNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/materials/nodes/SpriteNode.js
<ide> SpriteNode.prototype.copy = function ( source ) {
<ide>
<ide> if ( source.alpha ) this.alpha = source.alpha;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> SpriteNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/materials/nodes/StandardNode.js
<ide> StandardNode.prototype.copy = function ( source ) {
<ide>
<ide> if ( source.environment ) this.environment = source.environment;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> StandardNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/math/CondNode.js
<ide> CondNode.prototype.copy = function ( source ) {
<ide> this.ifNode = source.ifNode;
<ide> this.elseNode = source.elseNode;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> CondNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/math/MathNode.js
<ide> MathNode.prototype.copy = function ( source ) {
<ide> this.c = source.c;
<ide> this.method = source.method;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> MathNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/math/OperatorNode.js
<ide> OperatorNode.prototype.copy = function ( source ) {
<ide> this.b = source.b;
<ide> this.op = source.op;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> OperatorNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/misc/BumpMapNode.js
<ide> BumpMapNode.prototype.copy = function ( source ) {
<ide> this.value = source.value;
<ide> this.scale = source.scale;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> BumpMapNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/misc/NormalMapNode.js
<ide> NormalMapNode.prototype.copy = function ( source ) {
<ide> this.value = source.value;
<ide> this.scale = source.scale;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> NormalMapNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/postprocessing/NodePass.js
<ide> NodePass.prototype.copy = function ( source ) {
<ide>
<ide> this.input = source.input;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> NodePass.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/postprocessing/NodePostProcessing.js
<ide> NodePostProcessing.prototype = {
<ide>
<ide> this.output = source.output;
<ide>
<add> return this;
<add>
<ide> },
<ide>
<ide> toJSON: function ( meta ) {
<ide><path>examples/jsm/nodes/procedural/CheckerNode.js
<ide> CheckerNode.prototype.copy = function ( source ) {
<ide>
<ide> this.uv = source.uv;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> CheckerNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/procedural/NoiseNode.js
<ide> NoiseNode.prototype.copy = function ( source ) {
<ide>
<ide> this.uv = source.uv;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> NoiseNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/utils/BypassNode.js
<ide> BypassNode.prototype.copy = function ( source ) {
<ide> this.code = source.code;
<ide> this.value = source.value;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> BypassNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/utils/ColorSpaceNode.js
<ide> ColorSpaceNode.prototype.copy = function ( source ) {
<ide> this.input = source.input;
<ide> this.method = source.method;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> ColorSpaceNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/utils/JoinNode.js
<ide> JoinNode.prototype.copy = function ( source ) {
<ide>
<ide> }
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> JoinNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/utils/SwitchNode.js
<ide> SwitchNode.prototype.copy = function ( source ) {
<ide> this.node = source.node;
<ide> this.components = source.components;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> SwitchNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/utils/TimerNode.js
<ide> TimerNode.prototype.copy = function ( source ) {
<ide>
<ide> this.timeScale = source.timeScale;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> TimerNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/utils/UVTransformNode.js
<ide> UVTransformNode.prototype.copy = function ( source ) {
<ide> this.uv = source.uv;
<ide> this.position = source.position;
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> UVTransformNode.prototype.toJSON = function ( meta ) {
<ide><path>examples/jsm/nodes/utils/VelocityNode.js
<ide> VelocityNode.prototype.copy = function ( source ) {
<ide>
<ide> this.setParams( source.params );
<ide>
<add> return this;
<add>
<ide> };
<ide>
<ide> VelocityNode.prototype.toJSON = function ( meta ) { | 54 |
Text | Text | update preview mode docs with note on local dev | 213db224f36f43aec18a5b67ee502851c4386315 | <ide><path>docs/advanced-features/preview-mode.md
<ide> export default function myApiRoute(req, res) {
<ide> Both the bypass cookie value and the private key for encrypting the `previewData` change when `next build` is completed.
<ide> This ensures that the bypass cookie can’t be guessed.
<ide>
<add>> **Note:** To test Preview Mode locally over HTTP your browser will need to allow third-party cookies and local storage access.
<add>
<ide> ## Learn more
<ide>
<ide> The following pages might also be useful. | 1 |
Javascript | Javascript | skip undefined attribute in head | c480c37c8e23d95fb976012e879376bb3a8bb275 | <ide><path>packages/next/client/head-manager.js
<ide> function reactElementToDOM({ type, props }) {
<ide> if (!props.hasOwnProperty(p)) continue
<ide> if (p === 'children' || p === 'dangerouslySetInnerHTML') continue
<ide>
<add> // we don't render undefined props to the DOM
<add> if (props[p] === undefined) continue
<add>
<ide> const attr = DOMAttributeNames[p] || p.toLowerCase()
<ide> el.setAttribute(attr, props[p])
<ide> }
<ide><path>test/integration/client-navigation/pages/head.js
<ide> export default () => (
<ide>
<ide> <meta content="my meta" />
<ide>
<add> {/* this will not render the content prop */}
<add> <meta name="empty-content" content={undefined} />
<add>
<ide> {/* allow duplicates for specific tags */}
<ide> <meta property="article:tag" content="tag1" key="tag1key" />
<ide> <meta property="article:tag" content="tag2" key="tag2key" />
<ide><path>test/integration/client-navigation/test/index.test.js
<ide> describe('Client Navigation', () => {
<ide> await browser.close()
<ide> })
<ide>
<add> it('should handle undefined prop in head client-side', async () => {
<add> const browser = await webdriver(context.appPort, '/head')
<add> const value = await browser.eval(
<add> `document.querySelector('meta[name="empty-content"]').hasAttribute('content')`
<add> )
<add>
<add> expect(value).toBe(false)
<add> })
<add>
<ide> renderingSuite(
<ide> (p, q) => renderViaHTTP(context.appPort, p, q),
<ide> (p, q) => fetchViaHTTP(context.appPort, p, q)
<ide><path>test/integration/client-navigation/test/rendering.js
<ide> export default function(render, fetch) {
<ide> expect(html.includes('My component!')).toBeTruthy()
<ide> })
<ide>
<add> it('should handle undefined prop in head server-side', async () => {
<add> const html = await render('/head')
<add> const $ = cheerio.load(html)
<add> const value = 'content' in $('meta[name="empty-content"]').attr()
<add>
<add> expect(value).toBe(false)
<add> })
<add>
<ide> test('renders with fragment syntax', async () => {
<ide> const html = await render('/fragment-syntax')
<ide> expect(html.includes('My component!')).toBeTruthy() | 4 |
Javascript | Javascript | define properties on prototype | 7ce5a310612bfcfc153836e718fe3c6309369fb4 | <ide><path>lib/events.js
<ide> function EventEmitter() {
<ide> }
<ide> exports.EventEmitter = EventEmitter;
<ide>
<add>EventEmitter.prototype.domain = undefined;
<add>EventEmitter.prototype._events = undefined;
<add>EventEmitter.prototype._maxListeners = undefined;
<ide>
<ide> // By default EventEmitters will print a warning if more than 10 listeners are
<ide> // added to it. This is a useful default which helps finding memory leaks. | 1 |
Text | Text | harmonize intro with website | 70ab25a5dbc8f54dbe15e9375687b4669ed919df | <ide><path>README.md
<ide> Docker: the Linux container engine
<ide> ==================================
<ide>
<del>Docker is an open-source engine which automates the deployment of
<del>applications as highly portable, self-sufficient containers.
<add>Docker is an open source project to pack, ship and run any application
<add>as a lightweight container
<ide>
<ide> Docker containers are both *hardware-agnostic* and
<ide> *platform-agnostic*. This means that they can run anywhere, from your | 1 |
PHP | PHP | fix typo in method name | 41fbdc4c76d35bda5cace03407abe79117579100 | <ide><path>src/Database/Type.php
<ide> public function newId() {
<ide> * @param mixed $value The value to convert.
<ide> * @return mixed Converted value.
<ide> */
<del> public function marshall($value) {
<add> public function marshal($value) {
<ide> return $value;
<ide> }
<ide>
<ide><path>src/Database/Type/DateTimeType.php
<ide> public function toPHP($value, Driver $driver) {
<ide> * @param mixed $value Request data
<ide> * @return \DateTime
<ide> */
<del> public function marshall($value) {
<add> public function marshal($value) {
<ide> try {
<ide> if ($value === '' || $value === null || $value === false || $value === true) {
<ide> return $value;
<ide><path>src/Database/Type/DateType.php
<ide> public function toPHP($value, Driver $driver) {
<ide> * @param mixed $value Request data
<ide> * @return \DateTime
<ide> */
<del> public function marshall($value) {
<add> public function marshal($value) {
<ide> try {
<ide> if ($value === '' || $value === null || $value === false || $value === true) {
<ide> return $value;
<ide><path>src/ORM/Marshaller.php
<ide> public function one(array $data, $include = []) {
<ide> $value = $this->_marshalAssociation($assoc, $value, $nested);
<ide> } elseif ($columnType) {
<ide> $converter = Type::build($columnType);
<del> $value = $converter->marshall($value);
<add> $value = $converter->marshal($value);
<ide> }
<ide> $properties[$key] = $value;
<ide> }
<ide><path>tests/TestCase/Database/Type/DateTimeTypeTest.php
<ide> public function testToDatabase() {
<ide> }
<ide>
<ide> /**
<del> * Data provider for marshall()
<add> * Data provider for marshal()
<ide> *
<ide> * @return array
<ide> */
<del> public function marshallProvider() {
<add> public function marshalProvider() {
<ide> return [
<ide> // invalid types.
<ide> [null, null],
<ide> public function marshallProvider() {
<ide> /**
<ide> * test marshalling data.
<ide> *
<del> * @dataProvider marshallProvider
<add> * @dataProvider marshalProvider
<ide> * @return void
<ide> */
<del> public function testMarshall($value, $expected) {
<del> $result = $this->type->marshall($value);
<add> public function testMarshal($value, $expected) {
<add> $result = $this->type->marshal($value);
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Type/DateTypeTest.php
<ide> public function testToDatabase() {
<ide> }
<ide>
<ide> /**
<del> * Data provider for marshall()
<add> * Data provider for marshal()
<ide> *
<ide> * @return array
<ide> */
<del> public function marshallProvider() {
<add> public function marshalProvider() {
<ide> $date = new \DateTime('@1392387900');
<ide> $date->setTime(0, 0, 0);
<ide>
<ide> public function marshallProvider() {
<ide> }
<ide>
<ide> /**
<del> * test marshalling data.
<add> * test marshaling data.
<ide> *
<del> * @dataProvider marshallProvider
<add> * @dataProvider marshalProvider
<ide> * @return void
<ide> */
<del> public function testMarshall($value, $expected) {
<del> $result = $this->type->marshall($value);
<add> public function testMarshal($value, $expected) {
<add> $result = $this->type->marshal($value);
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> | 6 |
Python | Python | get buildbot running | 3687528ba7080be47a40b89a6b8924e952cb07c8 | <ide><path>build.py
<ide> def x(cmd):
<ide> x('pip install -r requirements.txt')
<ide>
<ide> if install_mode == 'pip':
<add> for filename in os.listdir('dist'):
<add> os.unlink(os.path.join('dist', filename))
<ide> x('python setup.py sdist')
<del> dists = os.listdir('dist')
<del> assert len(dists) == 1
<del> x('pip install dist/%s' % dists[0])
<add> filenames = os.listdir('dist')
<add> assert len(filenames) == 1
<add> x('pip install dist/%s' % filenames[0])
<ide>
<ide> elif install_mode == 'setup-install':
<ide> x('python setup.py install') | 1 |
Javascript | Javascript | add missing chunk groups to hotupdatechunks | fac6c5241f760d10a6efc9d3096aecf2bbd0d441 | <ide><path>lib/HotModuleReplacementPlugin.js
<ide> class HotModuleReplacementPlugin {
<ide> ChunkGraph.setChunkGraphForChunk(hotUpdateChunk, chunkGraph);
<ide> hotUpdateChunk.id = chunkId;
<ide> hotUpdateChunk.runtime = newRuntime;
<add> if (currentChunk) {
<add> for (const group of currentChunk.groupsIterable)
<add> hotUpdateChunk.addGroup(group);
<add> }
<ide> chunkGraph.attachModules(hotUpdateChunk, newModules || []);
<ide> chunkGraph.attachRuntimeModules(
<ide> hotUpdateChunk, | 1 |
Python | Python | add support for elision in french | 902f136f18a807a0b84f7832df868856a20c3d76 | <ide><path>spacy/fr/__init__.py
<ide> from ..attrs import LANG
<ide>
<ide> from .language_data import *
<add>from .punctuation import TOKENIZER_INFIXES
<ide>
<ide>
<ide> class French(Language):
<ide> class Defaults(Language.Defaults):
<ide>
<ide> tokenizer_exceptions = TOKENIZER_EXCEPTIONS
<ide> stop_words = STOP_WORDS
<add> infixes = tuple(TOKENIZER_INFIXES)
<ide><path>spacy/fr/punctuation.py
<add># encoding: utf8
<add>
<add>from __future__ import unicode_literals
<add>
<add>from ..language_data.punctuation import ALPHA, TOKENIZER_INFIXES
<add>
<add>
<add>_ELISION = " ' ’ "
<add>ELISION = _ELISION.strip().replace(' ', '').replace('\n', '')
<add>
<add>TOKENIZER_INFIXES += [
<add> r'(?<=[{a}][{el}])(?=[{a}])'.format(a=ALPHA, el=ELISION),
<add>]
<add>
<add>
<add>__all__ = ["TOKENIZER_SUFFIXES", "TOKENIZER_INFIXES"] | 2 |
Text | Text | remove stability highlight for stable functions | 4a218fd96fbd1dfd7158881798508a1259925d9d | <ide><path>doc/api/n-api.md
<ide> This is an opaque pointer that is used to represent a JavaScript value.
<ide>
<ide> ### napi_threadsafe_function
<ide>
<del>> Stability: 2 - Stable
<del>
<ide> This is an opaque pointer that represents a JavaScript function which can be
<ide> called asynchronously from multiple threads via
<ide> `napi_call_threadsafe_function()`.
<ide>
<ide> ### napi_threadsafe_function_release_mode
<ide>
<del>> Stability: 2 - Stable
<del>
<ide> A value to be given to `napi_release_threadsafe_function()` to indicate whether
<ide> the thread-safe function is to be closed immediately (`napi_tsfn_abort`) or
<ide> merely released (`napi_tsfn_release`) and thus available for subsequent use via
<ide> typedef enum {
<ide>
<ide> ### napi_threadsafe_function_call_mode
<ide>
<del>> Stability: 2 - Stable
<del>
<ide> A value to be given to `napi_call_threadsafe_function()` to indicate whether
<ide> the call should block whenever the queue associated with the thread-safe
<ide> function is full.
<ide> typedef void (*napi_async_complete_callback)(napi_env env,
<ide>
<ide> #### napi_threadsafe_function_call_js
<ide>
<del>> Stability: 2 - Stable
<del>
<ide> Function pointer used with asynchronous thread-safe function calls. The callback
<ide> will be called on the main thread. Its purpose is to use a data item arriving
<ide> via the queue from one of the secondary threads to construct the parameters
<ide> prevent the event loop from exiting. The APIs `napi_ref_threadsafe_function` and
<ide>
<ide> ### napi_create_threadsafe_function
<ide>
<del>> Stability: 2 - Stable
<del>
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> napiVersion: 4
<ide> parameters and with `undefined` as its `this` value.
<ide>
<ide> ### napi_get_threadsafe_function_context
<ide>
<del>> Stability: 2 - Stable
<del>
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> napiVersion: 4
<ide> This API may be called from any thread which makes use of `func`.
<ide>
<ide> ### napi_call_threadsafe_function
<ide>
<del>> Stability: 2 - Stable
<del>
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> napiVersion: 4
<ide> This API may be called from any thread which makes use of `func`.
<ide>
<ide> ### napi_acquire_threadsafe_function
<ide>
<del>> Stability: 2 - Stable
<del>
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> napiVersion: 4
<ide> This API may be called from any thread which will start making use of `func`.
<ide>
<ide> ### napi_release_threadsafe_function
<ide>
<del>> Stability: 2 - Stable
<del>
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> napiVersion: 4
<ide> This API may be called from any thread which will stop making use of `func`.
<ide>
<ide> ### napi_ref_threadsafe_function
<ide>
<del>> Stability: 2 - Stable
<del>
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> napiVersion: 4
<ide> This API may only be called from the main thread.
<ide>
<ide> ### napi_unref_threadsafe_function
<ide>
<del>> Stability: 2 - Stable
<del>
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> napiVersion: 4 | 1 |
Python | Python | fix non-executed sql | f0e09e27f6461cf65cbaa68c097e8368e0f14ec0 | <ide><path>django/db/backends/schema.py
<ide> def create_field(self, model, field, keep_default=False):
<ide> "column": self.quote_name(field.column),
<ide> }
<ide> }
<add> self.execute(sql)
<ide> # Add any FK constraints later
<ide> if field.rel and self.connection.features.supports_foreign_keys:
<ide> to_table = field.rel.to._meta.db_table | 1 |
Javascript | Javascript | increase test coverage of readline-interface | f2b9d5e41e8868365753ba4a8aad959dcab0efd1 | <ide><path>test/parallel/test-readline-interface.js
<ide> function isWarned(emitter) {
<ide> }));
<ide> }
<ide>
<add> // constructor throws if historySize is not a positive number
<add> {
<add> const fi = new FakeInput();
<add> assert.throws(function() {
<add> readline.createInterface({
<add> input: fi, historySize: 'not a number'
<add> });
<add> }, common.expectsError({
<add> type: RangeError,
<add> code: 'ERR_INVALID_OPT_VALUE'
<add> }));
<add>
<add> assert.throws(function() {
<add> readline.createInterface({
<add> input: fi, historySize: -1
<add> });
<add> }, common.expectsError({
<add> type: RangeError,
<add> code: 'ERR_INVALID_OPT_VALUE'
<add> }));
<add>
<add> assert.throws(function() {
<add> readline.createInterface({
<add> input: fi, historySize: NaN
<add> });
<add> }, common.expectsError({
<add> type: RangeError,
<add> code: 'ERR_INVALID_OPT_VALUE'
<add> }));
<add> }
<add>
<ide> // duplicate lines are removed from history when
<ide> // `options.removeHistoryDuplicates` is `true`
<ide> {
<ide> function isWarned(emitter) {
<ide> assert.notStrictEqual(rli.line, expectedLines[--callCount]);
<ide> assert.strictEqual(rli.line, expectedLines[--callCount]);
<ide> assert.strictEqual(callCount, 0);
<add> fi.emit('keypress', '.', { name: 'down' }); // 'baz'
<add> assert.strictEqual(rli.line, 'baz');
<add> fi.emit('keypress', '.', { name: 'n', ctrl: true }); // 'bar'
<add> assert.strictEqual(rli.line, 'bar');
<add> fi.emit('keypress', '.', { name: 'down' }); // 'bat'
<add> assert.strictEqual(rli.line, 'bat');
<add> fi.emit('keypress', '.', { name: 'down' }); // ''
<add> assert.strictEqual(rli.line, '');
<ide> rli.close();
<ide> }
<ide>
<ide> function isWarned(emitter) {
<ide> rli.close();
<ide> }
<ide>
<add> // calling the question callback
<add> {
<add> let called = false;
<add> const fi = new FakeInput();
<add> const rli = new readline.Interface(
<add> { input: fi, output: fi, terminal: terminal }
<add> );
<add> rli.question('foo?', function(answer) {
<add> called = true;
<add> assert.strictEqual(answer, 'bar');
<add> });
<add> rli.write('bar\n');
<add> assert.ok(called);
<add> rli.close();
<add> }
<add>
<ide> if (terminal) {
<add> // history is bound
<add> {
<add> const fi = new FakeInput();
<add> const rli = new readline.Interface(
<add> { input: fi, output: fi, terminal, historySize: 2 }
<add> );
<add> const lines = ['line 1', 'line 2', 'line 3'];
<add> fi.emit('data', lines.join('\n') + '\n');
<add> assert.strictEqual(rli.history.length, 2);
<add> assert.strictEqual(rli.history[0], 'line 3');
<add> assert.strictEqual(rli.history[1], 'line 2');
<add> }
<ide> // question
<ide> {
<ide> const fi = new FakeInput();
<ide> function isWarned(emitter) {
<ide> rli.close();
<ide> });
<ide> }
<add>
<add> // multi-line cursor position
<add> {
<add> const fi = new FakeInput();
<add> const rli = new readline.Interface({
<add> input: fi,
<add> output: fi,
<add> prompt: '',
<add> terminal: terminal
<add> });
<add> fi.columns = 10;
<add> fi.emit('data', 'multi-line text');
<add> const cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 1);
<add> assert.strictEqual(cursorPos.cols, 5);
<add> }
<ide> }
<ide>
<ide> // isFullWidthCodePoint() should return false for non-numeric values | 1 |
Python | Python | fix syntax error for dimensiondatastatus object | 4d21a8d219dfeaefd12efcf28d17114423f1b1dd | <ide><path>libcloud/common/dimensiondata.py
<ide> def __repr__(self):
<ide> return (('<DimensionDataStatus: action=%s, request_time=%s, '
<ide> 'user_name=%s, number_of_steps=%s, update_time=%s, '
<ide> 'step_name=%s, step_number=%s, '
<del> 'step_percent_complete=%s, failure_reason=%s')
<add> 'step_percent_complete=%s, failure_reason=%s>')
<ide> % (self.action, self.request_time, self.user_name,
<ide> self.number_of_steps, self.update_time, self.step_name,
<ide> self.step_number, self.step_percent_complete, | 1 |
Ruby | Ruby | remove unused conditions for 1.9 | b74f5b73989edaca124b4b6f8594e63bda6344c9 | <ide><path>actionpack/test/controller/test_test.rb
<ide> def test_should_detect_if_cookie_is_deleted
<ide>
<ide> FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
<ide>
<del> if RUBY_VERSION < '1.9'
<del> READ_BINARY = 'rb'
<del> READ_PLAIN = 'r'
<del> else
<del> READ_BINARY = 'rb:binary'
<del> READ_PLAIN = 'r:binary'
<del> end
<add> READ_BINARY = 'rb:binary'
<add> READ_PLAIN = 'r:binary'
<ide>
<ide> def test_test_uploaded_file
<ide> filename = 'mona_lisa.jpg'
<ide><path>actionpack/test/template/capture_helper_test.rb
<ide> def test_with_output_buffer_restores_the_output_buffer
<ide> assert buffer.equal?(@av.output_buffer)
<ide> end
<ide>
<del> unless RUBY_VERSION < '1.9'
<del> def test_with_output_buffer_sets_proper_encoding
<del> @av.output_buffer = ActionView::OutputBuffer.new
<add> def test_with_output_buffer_sets_proper_encoding
<add> @av.output_buffer = ActionView::OutputBuffer.new
<ide>
<del> # Ensure we set the output buffer to an encoding different than the default one.
<del> alt_encoding = alt_encoding(@av.output_buffer)
<del> @av.output_buffer.force_encoding(alt_encoding)
<add> # Ensure we set the output buffer to an encoding different than the default one.
<add> alt_encoding = alt_encoding(@av.output_buffer)
<add> @av.output_buffer.force_encoding(alt_encoding)
<ide>
<del> @av.with_output_buffer do
<del> assert_equal alt_encoding, @av.output_buffer.encoding
<del> end
<add> @av.with_output_buffer do
<add> assert_equal alt_encoding, @av.output_buffer.encoding
<ide> end
<ide> end
<ide>
<ide> def test_flush_output_buffer_concats_output_buffer_to_response
<ide> assert_equal '', view.output_buffer
<ide> end
<ide>
<del> unless RUBY_VERSION < '1.9'
<del> def test_flush_output_buffer_preserves_the_encoding_of_the_output_buffer
<del> view = view_with_controller
<del> alt_encoding = alt_encoding(view.output_buffer)
<del> view.output_buffer.force_encoding(alt_encoding)
<del> flush_output_buffer
<del> assert_equal alt_encoding, view.output_buffer.encoding
<del> end
<add> def test_flush_output_buffer_preserves_the_encoding_of_the_output_buffer
<add> view = view_with_controller
<add> alt_encoding = alt_encoding(view.output_buffer)
<add> view.output_buffer.force_encoding(alt_encoding)
<add> flush_output_buffer
<add> assert_equal alt_encoding, view.output_buffer.encoding
<ide> end
<ide>
<ide> def alt_encoding(output_buffer)
<ide><path>actionpack/test/template/text_helper_test.rb
<ide> def test_truncate_with_options_hash
<ide> assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 15, :separator => ' ')
<ide> end
<ide>
<del> if RUBY_VERSION < '1.9.0'
<del> def test_truncate_multibyte
<del> with_kcode 'none' do
<del> assert_equal "\354\225\210\353\205\225\355...", truncate("\354\225\210\353\205\225\355\225\230\354\204\270\354\232\224", :length => 10)
<del> end
<del> with_kcode 'u' do
<del> assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...",
<del> truncate("\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244", :length => 10)
<del> end
<del> end
<del> else
<del> def test_truncate_multibyte
<del> # .mb_chars always returns a UTF-8 String.
<del> # assert_equal "\354\225\210\353\205\225\355...",
<del> # truncate("\354\225\210\353\205\225\355\225\230\354\204\270\354\232\224", :length => 10)
<del>
<del> assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding('UTF-8'),
<del> truncate("\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding('UTF-8'), :length => 10)
<del> end
<add> def test_truncate_multibyte
<add> # .mb_chars always returns a UTF-8 String.
<add> # assert_equal "\354\225\210\353\205\225\355...",
<add> # truncate("\354\225\210\353\205\225\355\225\230\354\204\270\354\232\224", :length => 10)
<add>
<add> assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding('UTF-8'),
<add> truncate("\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding('UTF-8'), :length => 10)
<ide> end
<ide>
<ide> def test_highlight_should_be_html_safe
<ide> def test_excerpt_with_options_hash
<ide> )
<ide> end
<ide>
<del> if RUBY_VERSION < '1.9'
<del> def test_excerpt_with_utf8
<del> with_kcode('u') do
<del> assert_equal("...\357\254\203ciency could not be...", excerpt("That's why e\357\254\203ciency could not be helped", 'could', 8))
<del> end
<del> with_kcode('none') do
<del> assert_equal("...\203ciency could not be...", excerpt("That's why e\357\254\203ciency could not be helped", 'could', 8))
<del> end
<del> end
<del> else
<del> def test_excerpt_with_utf8
<del> assert_equal("...\357\254\203ciency could not be...".force_encoding('UTF-8'), excerpt("That's why e\357\254\203ciency could not be helped".force_encoding('UTF-8'), 'could', 8))
<del> # .mb_chars always returns UTF-8, even in 1.9. This is not great, but it's how it works. Let's work this out.
<del> # assert_equal("...\203ciency could not be...", excerpt("That's why e\357\254\203ciency could not be helped".force_encoding("BINARY"), 'could', 8))
<del> end
<add> def test_excerpt_with_utf8
<add> assert_equal("...\357\254\203ciency could not be...".force_encoding('UTF-8'), excerpt("That's why e\357\254\203ciency could not be helped".force_encoding('UTF-8'), 'could', 8))
<add> # .mb_chars always returns UTF-8, even in 1.9. This is not great, but it's how it works. Let's work this out.
<add> # assert_equal("...\203ciency could not be...", excerpt("That's why e\357\254\203ciency could not be helped".force_encoding("BINARY"), 'could', 8))
<ide> end
<ide>
<ide> def test_word_wrap | 3 |
Ruby | Ruby | add test for brew commands --quiet | 193b5aa07ac9e278dfe123d03566c14572321deb | <ide><path>Library/Homebrew/test/cmd/commands_spec.rb
<ide> it "prints a list of all available commands" do
<ide> expect { brew "commands" }
<ide> .to output(/Built-in commands/).to_stdout
<add> .and not_to_output.to_stderr
<add> .and be_a_success
<add>
<add> expect { brew "commands", "--quiet" }
<add> .to output.to_stdout
<add> .and not_to_output.to_stderr
<ide> .and be_a_success
<ide> end
<ide> end | 1 |
Javascript | Javascript | move guards from auto binding to event dispatch | 16cc45156f65ff7fdda57383759121f59f585e41 | <ide><path>src/isomorphic/classic/class/ReactClass.js
<ide>
<ide> var ReactComponent = require('ReactComponent');
<ide> var ReactElement = require('ReactElement');
<del>var ReactErrorUtils = require('ReactErrorUtils');
<ide> var ReactPropTypeLocations = require('ReactPropTypeLocations');
<ide> var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
<ide> var ReactNoopUpdateQueue = require('ReactNoopUpdateQueue');
<ide> function bindAutoBindMethods(component) {
<ide> var method = component.__reactAutoBindMap[autoBindKey];
<ide> component[autoBindKey] = bindAutoBindMethod(
<ide> component,
<del> ReactErrorUtils.guard(
<del> method,
<del> component.constructor.displayName + '.' + autoBindKey
<del> )
<add> method
<ide> );
<ide> }
<ide> }
<ide><path>src/renderers/dom/client/__tests__/ReactBrowserEventEmitter-test.js
<ide> describe('ReactBrowserEventEmitter', function() {
<ide> expect(idCallOrder[2]).toBe(getID(GRANDPARENT));
<ide> });
<ide>
<add> it('should continue bubbling if an error is thrown', function() {
<add> ReactBrowserEventEmitter.putListener(
<add> getID(CHILD),
<add> ON_CLICK_KEY,
<add> recordID.bind(null, getID(CHILD))
<add> );
<add> ReactBrowserEventEmitter.putListener(
<add> getID(PARENT),
<add> ON_CLICK_KEY,
<add> function() {
<add> recordID(getID(PARENT));
<add> throw new Error('Handler interrupted');
<add> }
<add> );
<add> ReactBrowserEventEmitter.putListener(
<add> getID(GRANDPARENT),
<add> ON_CLICK_KEY,
<add> recordID.bind(null, getID(GRANDPARENT))
<add> );
<add> expect(function() {
<add> ReactTestUtils.Simulate.click(CHILD);
<add> }).toThrow();
<add> expect(idCallOrder.length).toBe(3);
<add> expect(idCallOrder[0]).toBe(getID(CHILD));
<add> expect(idCallOrder[1]).toBe(getID(PARENT));
<add> expect(idCallOrder[2]).toBe(getID(GRANDPARENT));
<add> });
<add>
<ide> it('should set currentTarget', function() {
<ide> ReactBrowserEventEmitter.putListener(
<ide> getID(CHILD),
<ide><path>src/renderers/shared/event/EventPluginHub.js
<ide>
<ide> var EventPluginRegistry = require('EventPluginRegistry');
<ide> var EventPluginUtils = require('EventPluginUtils');
<add>var ReactErrorUtils = require('ReactErrorUtils');
<ide>
<ide> var accumulateInto = require('accumulateInto');
<ide> var forEachAccumulated = require('forEachAccumulated');
<ide> var EventPluginHub = {
<ide> 'processEventQueue(): Additional events were enqueued while processing ' +
<ide> 'an event queue. Support for this has not yet been implemented.'
<ide> );
<add> // This would be a good time to rethrow if any of the event handlers threw.
<add> ReactErrorUtils.rethrowCaughtError();
<ide> },
<ide>
<ide> /**
<ide><path>src/renderers/shared/event/EventPluginUtils.js
<ide> 'use strict';
<ide>
<ide> var EventConstants = require('EventConstants');
<add>var ReactErrorUtils = require('ReactErrorUtils');
<ide>
<ide> var invariant = require('invariant');
<ide> var warning = require('warning');
<ide> function forEachEventDispatch(event, cb) {
<ide> */
<ide> function executeDispatch(event, listener, domID) {
<ide> event.currentTarget = injection.Mount.getNode(domID);
<del> var returnValue = listener(event, domID);
<add> var type = event.type || 'unknown-event';
<add> var returnValue =
<add> ReactErrorUtils.invokeGuardedCallback(type, listener, event, domID);
<ide> event.currentTarget = null;
<ide> return returnValue;
<ide> }
<ide><path>src/renderers/shared/reconciler/__tests__/ReactCompositeComponentError-test.js
<del>/**
<del> * Copyright 2013-2015, Facebook, Inc.
<del> * All rights reserved.
<del> *
<del> * This source code is licensed under the BSD-style license found in the
<del> * LICENSE file in the root directory of this source tree. An additional grant
<del> * of patent rights can be found in the PATENTS file in the same directory.
<del> *
<del> * @emails react-core
<del> */
<del>
<del>'use strict';
<del>
<del>var React = require('React');
<del>var ReactErrorUtils = require('ReactErrorUtils');
<del>
<del>describe('ReactCompositeComponent-error', function() {
<del>
<del> it('should be passed the component and method name', function() {
<del> spyOn(ReactErrorUtils, 'guard').andCallThrough();
<del> var Component = React.createClass({
<del> someHandler: function() {},
<del> render: function() {
<del> return <div />;
<del> },
<del> });
<del>
<del> void new Component();
<del>
<del> expect(ReactErrorUtils.guard.mostRecentCall.args[1])
<del> .toEqual('Component.someHandler');
<del> });
<del>
<del>});
<ide><path>src/shared/utils/ReactErrorUtils.js
<ide>
<ide> 'use strict';
<ide>
<add>var caughtError = null;
<add>
<ide> var ReactErrorUtils = {
<ide> /**
<del> * Creates a guarded version of a function. This is supposed to make debugging
<del> * of event handlers easier. To aid debugging with the browser's debugger,
<del> * this currently simply returns the original function.
<add> * Call a function while guarding against errors that happens within it.
<ide> *
<del> * @param {function} func Function to be executed
<del> * @param {string} name The name of the guard
<del> * @return {function}
<add> * @param name (?String) name of the guard to use for logging or debugging
<add> * @param func (Function) function to invoke
<add> * @param a (*) a First argument
<add> * @param b (*) b Second argument
<add> */
<add> invokeGuardedCallback: function(name, func, a, b) {
<add> try {
<add> return func(a, b);
<add> } catch(x) {
<add> if (caughtError === null) {
<add> caughtError = x;
<add> }
<add> return undefined;
<add> }
<add> },
<add>
<add> /**
<add> * During execution of guarded functions we will capture the first error which
<add> * we will rethrow to be handled by the top level error handler.
<ide> */
<del> guard: function(func, name) {
<del> return func;
<add> rethrowCaughtError: function() {
<add> if (caughtError) {
<add> var error = caughtError;
<add> caughtError = null;
<add> throw error;
<add> }
<ide> },
<ide> };
<ide>
<add>if (__DEV__) {
<add> /**
<add> * To help development we can get better devtools integration by simulating a
<add> * real browser event.
<add> */
<add> if (typeof window !== 'undefined' &&
<add> typeof window.dispatchEvent === 'function' &&
<add> typeof Event === 'function') {
<add> var fakeNode = document.createElement('react');
<add> ReactErrorUtils.invokeGuardedCallback = function(name, func, a, b) {
<add> var boundFunc = func.bind(null, a, b);
<add> fakeNode.addEventListener(name, boundFunc, false);
<add> fakeNode.dispatchEvent(new Event(name));
<add> fakeNode.removeEventListener(name, boundFunc, false);
<add> };
<add> }
<add>}
<add>
<ide> module.exports = ReactErrorUtils; | 6 |
Javascript | Javascript | fix broken code block and make the example nicer | 1fd2e176ae1e6d66aaf67fda730f942ddde6c18b | <ide><path>Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.android.js
<ide> var DRAWER_STATES = [
<ide> * ```
<ide> * render: function() {
<ide> * var navigationView = (
<del> * <Text style={{margin: 10, fontSize: 15, textAlign: 'left'}}>I'm in the Drawer!</Text>
<add> * <View style={{flex: 1, backgroundColor: '#fff'}}>
<add> * <Text style={{margin: 10, fontSize: 15, textAlign: 'left'}}>I'm in the Drawer!</Text>
<add> * </View>
<ide> * );
<ide> * return (
<ide> * <DrawerLayoutAndroid
<ide> * drawerWidth={300}
<ide> * drawerPosition={DrawerLayoutAndroid.positions.Left}
<ide> * renderNavigationView={() => navigationView}>
<del> * <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text>
<del> * <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>World!</Text>
<add> * <View style={{flex: 1, alignItems: 'center'}}>
<add> * <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text>
<add> * <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>World!</Text>
<add> * </View>
<ide> * </DrawerLayoutAndroid>
<ide> * );
<ide> * }, | 1 |
Javascript | Javascript | add fallback for `${modulename}/index` | 80270f186a7863ea3c946ee2d14ca6118dd7e3a8 | <ide><path>packages/ember-metal/lib/index.js
<ide> Ember.onerror = null;
<ide> // do this for side-effects of updating Ember.assert, warn, etc when
<ide> // ember-debug is present
<ide> // This needs to be called before any deprecateFunc
<del>if (Ember.__loader.registry['ember-debug']) {
<add>if (Ember.__loader.registry['ember-debug/index']) {
<ide> requireModule('ember-debug');
<ide> } else {
<ide> Ember.Debug = { };
<ide><path>packages/ember/lib/index.js
<ide> import 'ember-routing-views';
<ide> import Ember from 'ember-metal/core';
<ide> import { runLoadHooks } from 'ember-runtime/system/lazy_load';
<ide>
<del>if (Ember.__loader.registry['ember-template-compiler']) {
<add>if (Ember.__loader.registry['ember-template-compiler/index']) {
<ide> requireModule('ember-template-compiler');
<ide> }
<ide>
<ide> // do this to ensure that Ember.Test is defined properly on the global
<ide> // if it is present.
<del>if (Ember.__loader.registry['ember-testing']) {
<add>if (Ember.__loader.registry['ember-testing/index']) {
<ide> requireModule('ember-testing');
<ide> }
<ide>
<ide><path>packages/loader/lib/index.js
<ide> var mainContext = this;
<ide> }
<ide> }
<ide>
<del> function internalRequire(name, referrerName) {
<add> function internalRequire(_name, referrerName) {
<add> var name = _name;
<add> var mod = registry[name];
<add>
<add> if (!mod) {
<add> name = name + '/index';
<add> mod = registry[name];
<add> }
<add>
<ide> var exports = seen[name];
<ide>
<ide> if (exports !== undefined) {
<ide> var mainContext = this;
<ide>
<ide> exports = seen[name] = {};
<ide>
<del> if (!registry[name]) {
<del> missingModule(name, referrerName);
<add> if (!mod) {
<add> missingModule(_name, referrerName);
<ide> }
<ide>
<del> var mod = registry[name];
<ide> var deps = mod.deps;
<ide> var callback = mod.callback;
<ide> var length = deps.length; | 3 |
Java | Java | add fabric logs to textlayoutmanager | 6f8fc40195952d371d964b487409c177d25b5813 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.java
<ide> import android.util.LayoutDirection;
<ide> import android.util.LruCache;
<ide> import androidx.annotation.Nullable;
<add>import com.facebook.common.logging.FLog;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.uimanager.PixelUtil;
<ide> /** Class responsible of creating {@link Spanned} object for the JS representation of Text */
<ide> public class TextLayoutManager {
<ide>
<add> // TODO T67606397: Refactor configuration of fabric logs
<add> private static final boolean ENABLE_MEASURE_LOGGING = false;
<add>
<add> private static final String TAG = "TextLayoutManager";
<add>
<ide> // It's important to pass the ANTI_ALIAS_FLAG flag to the constructor rather than setting it
<ide> // later by calling setFlags. This is because the latter approach triggers a bug on Android 4.4.2.
<ide> // The bug is that unicode emoticons aren't measured properly which causes text to be clipped.
<ide> public static long measureText(
<ide> }
<ide> }
<ide>
<del> return YogaMeasureOutput.make(
<del> PixelUtil.toSPFromPixel(calculatedWidth), PixelUtil.toSPFromPixel(calculatedHeight));
<add> float widthInSP = PixelUtil.toSPFromPixel(calculatedWidth);
<add> float heightInSP = PixelUtil.toSPFromPixel(calculatedHeight);
<add>
<add> if (ENABLE_MEASURE_LOGGING) {
<add> FLog.e(
<add> TAG,
<add> "TextMeasure call ('"
<add> + text
<add> + "'): w: "
<add> + calculatedWidth
<add> + " px - h: "
<add> + calculatedHeight
<add> + " px - w : "
<add> + widthInSP
<add> + " sp - h: "
<add> + heightInSP
<add> + " sp");
<add> }
<add>
<add> return YogaMeasureOutput.make(widthInSP, heightInSP);
<ide> }
<ide>
<ide> // TODO T31905686: This class should be private | 1 |
Python | Python | add caveat for acks_on_failure_or_timeout | 7d69b746f23303edac3557941ef1d6440427abdc | <ide><path>celery/app/task.py
<ide> class Task(object):
<ide> #: When enabled messages for this task will be acknowledged even if it
<ide> #: fails or times out.
<ide> #:
<add> #: Configuring this setting only applies to tasks that are
<add> #: acknowledged **after** they have been executed.
<add> #:
<ide> #: The application default can be overridden with the
<ide> #: :setting:`task_acks_on_failure_or_timeout` setting.
<ide> acks_on_failure_or_timeout = True | 1 |
PHP | PHP | improve parameter description wording | 6e9c082831b0dc450a23c31c8a526e17800db00e | <ide><path>src/TestSuite/IntegrationTestTrait.php
<ide> public function assertCookieEncrypted($expected, $name, $encrypt = 'aes', $key =
<ide> /**
<ide> * Asserts that a file with the given name was sent in the response
<ide> *
<del> * @param string $expected The file name that should be sent in the response
<add> * @param string $expected The absolute file path that should be sent in the response.
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */ | 1 |
Java | Java | fix javadoc typos | f585eb0b79429d4e2f15031ff237d16f01572b4d | <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java
<ide> public ParseState() {
<ide> }
<ide>
<ide> /**
<del> * Create a new {@code ParseState} whose {@link LinkedList} is a {@link Object#clone clone}
<add> * Create a new {@code ParseState} whose {@link LinkedList} is an {@link Object#clone clone}
<ide> * of that of the passed in {@code ParseState}.
<ide> */
<ide> @SuppressWarnings("unchecked")
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/parsing/ReaderContext.java
<ide> public void warning(String message, @Nullable Object source, @Nullable ParseStat
<ide> // Explicit parse events
<ide>
<ide> /**
<del> * Fire an defaults-registered event.
<add> * Fire a defaults-registered event.
<ide> */
<ide> public void fireDefaultsRegistered(DefaultsDefinition defaultsDefinition) {
<ide> this.eventListener.defaultsRegistered(defaultsDefinition);
<ide> }
<ide>
<ide> /**
<del> * Fire an component-registered event.
<add> * Fire a component-registered event.
<ide> */
<ide> public void fireComponentRegistered(ComponentDefinition componentDefinition) {
<ide> this.eventListener.componentRegistered(componentDefinition); | 2 |
Text | Text | fix typo in next/amp docs | 099471eaec8e86d49d6fa11b3d19defa819b1ed8 | <ide><path>docs/api-reference/next/amp.md
<ide> export const config = { amp: true }
<ide> The `amp` config accepts the following values:
<ide>
<ide> - `true` - The page will be AMP-only
<del>- `'hybrid'` - The page will two versions, one with AMP and another one with HTML
<add>- `'hybrid'` - The page will have two versions, one with AMP and another one with HTML
<ide>
<ide> To learn more about the `amp` config, read the sections below.
<ide> | 1 |
Javascript | Javascript | remove the "tagged" telemetry-reporting | c70ceecff40275439516a89f54d69f24db8538f3 | <ide><path>web/app.js
<ide> const PDFViewerApplication = {
<ide> _saveInProgress: false,
<ide> _docStats: null,
<ide> _wheelUnusedTicks: 0,
<del> _idleCallbacks: new Set(),
<ide> _PDFBug: null,
<ide> _hasAnnotationEditors: false,
<ide> _title: document.title,
<ide> const PDFViewerApplication = {
<ide> secondaryToolbar.viewBookmarkButton.hidden = true;
<ide> },
<ide>
<del> /**
<del> * @private
<del> */
<del> _cancelIdleCallbacks() {
<del> if (!this._idleCallbacks.size) {
<del> return;
<del> }
<del> for (const callback of this._idleCallbacks) {
<del> window.cancelIdleCallback(callback);
<del> }
<del> this._idleCallbacks.clear();
<del> },
<del>
<ide> /**
<ide> * Closes opened PDF document.
<ide> * @returns {Promise} - Returns the promise, which is resolved when all
<ide> const PDFViewerApplication = {
<ide> this._docStats = null;
<ide> this._hasAnnotationEditors = false;
<ide>
<del> this._cancelIdleCallbacks();
<ide> promises.push(this.pdfScriptingManager.destroyPromise);
<ide>
<ide> this.setTitle();
<ide> const PDFViewerApplication = {
<ide> }
<ide> this.pdfLayerViewer.render({ optionalContentConfig, pdfDocument });
<ide> });
<del> if (
<del> (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) ||
<del> "requestIdleCallback" in window
<del> ) {
<del> const callback = window.requestIdleCallback(
<del> () => {
<del> this._collectTelemetry(pdfDocument);
<del> this._idleCallbacks.delete(callback);
<del> },
<del> { timeout: 1000 }
<del> );
<del> this._idleCallbacks.add(callback);
<del> }
<ide> });
<ide>
<ide> this._initializePageLabels(pdfDocument);
<ide> const PDFViewerApplication = {
<ide> };
<ide> },
<ide>
<del> /**
<del> * A place to fetch data for telemetry after one page is rendered and the
<del> * viewer is idle.
<del> * @private
<del> */
<del> async _collectTelemetry(pdfDocument) {
<del> const markInfo = await this.pdfDocument.getMarkInfo();
<del> if (pdfDocument !== this.pdfDocument) {
<del> return; // Document was closed while waiting for mark info.
<del> }
<del> const tagged = markInfo?.Marked || false;
<del> this.externalServices.reportTelemetry({
<del> type: "tagged",
<del> tagged,
<del> });
<del> },
<del>
<ide> /**
<ide> * @private
<ide> */ | 1 |
Javascript | Javascript | explore potential test for ef94657438 | c163564a9e97820d82b66a4934fbb52999a9ecd0 | <ide><path>spec/tree-sitter-language-mode-spec.js
<ide> describe('TreeSitterLanguageMode', () => {
<ide> ])
<ide> })
<ide>
<add> it('handles injections that contain comments', async () => {
<add> const ejsGrammar = new TreeSitterGrammar(
<add> atom.grammars,
<add> ejsGrammarPath,
<add> {
<add> id: 'ejs',
<add> parser: 'tree-sitter-embedded-template',
<add> scopes: {
<add> '"<%"': 'directive',
<add> '"%>"': 'directive'
<add> },
<add> injectionPoints: [
<add> {
<add> type: 'template',
<add> language (node) { return 'javascript' },
<add> content (node) { return node.descendantsOfType('code') },
<add> newlinesBetween: true
<add> },
<add> {
<add> type: 'template',
<add> language (node) { return 'html' },
<add> content (node) { return node.descendantsOfType('content') }
<add> }
<add> ]
<add> }
<add> )
<add>
<add> atom.grammars.addGrammar(jsGrammar)
<add> atom.grammars.addGrammar(htmlGrammar)
<add>
<add> buffer.setText('<% // js comment%>\n<% b() %>')
<add> const languageMode = new TreeSitterLanguageMode({
<add> buffer,
<add> grammar: ejsGrammar,
<add> grammars: atom.grammars
<add> })
<add> buffer.setLanguageMode(languageMode)
<add>
<add> expectTokensToEqual(editor, [
<add> [
<add> { text: '<%', scopes: ['directive'] },
<add> { text: ' ', scopes: [] },
<add> { text: '// js comment ', scopes: ['comment'] },
<add> { text: '%>', scopes: ['directive'] }
<add> ],
<add> [
<add> { text: '<%', scopes: ['directive'] },
<add> { text: ' ', scopes: [] },
<add> { text: 'b', scopes: ['function'] },
<add> { text: '() ', scopes: [] },
<add> { text: '%>', scopes: ['directive'] }
<add> ]
<add> ])
<add> })
<add>
<ide> it('notifies onDidTokenize listeners the first time all syntax highlighting is done', async () => {
<ide> const promise = new Promise(resolve => {
<ide> editor.onDidTokenize(event => { | 1 |
Go | Go | normalize comment formatting | b7f931e170d523f84b2d0f97e808ec63656edcb7 | <ide><path>registry/registry_mock_test.go
<ide> func requiresAuth(w http.ResponseWriter, r *http.Request) bool {
<ide> value := fmt.Sprintf("FAKE-SESSION-%d", time.Now().UnixNano())
<ide> cookie := &http.Cookie{Name: "session", Value: value, MaxAge: 3600}
<ide> http.SetCookie(w, cookie)
<del> //FIXME(sam): this should be sent only on Index routes
<add> // FIXME(sam): this should be sent only on Index routes
<ide> value = fmt.Sprintf("FAKE-TOKEN-%d", time.Now().UnixNano())
<ide> w.Header().Add("X-Docker-Token", value)
<ide> } | 1 |
Python | Python | fix loading of english in span test | 25163821065de4b936cdc8af4d776f862c0cab51 | <ide><path>spacy/tests/spans/test_span.py
<ide> def test_root(doc):
<ide> assert np.root.head.orth_ == 'is'
<ide>
<ide>
<del>def test_root2():
<add>def test_root2(EN):
<ide> text = 'through North and South Carolina'
<del> EN = English(parser=False)
<ide> doc = EN(text)
<ide> heads = np.asarray([[0, 3, -1, -2, -4]], dtype='int32')
<ide> doc.from_array([HEAD], heads.T) | 1 |
Python | Python | stop timer in test | 0a84a664c0d2d30972ee0f9a07c9bf5736eceb34 | <ide><path>celery/tests/worker/test_worker.py
<ide> def test_receive_message_eta(self):
<ide> eta=(datetime.now() + timedelta(days=1)).isoformat(),
<ide> )
<ide>
<del> l.blueprint.start(l)
<del> p = l.app.conf.BROKER_CONNECTION_RETRY
<del> l.app.conf.BROKER_CONNECTION_RETRY = False
<del> l.blueprint.start(l)
<del> l.app.conf.BROKER_CONNECTION_RETRY = p
<del> l.blueprint.restart(l)
<del> l.event_dispatcher = Mock()
<del> callback = self._get_on_message(l)
<del> callback(m.decode(), m)
<del> l.timer.stop()
<add> try:
<add> l.blueprint.start(l)
<add> p = l.app.conf.BROKER_CONNECTION_RETRY
<add> l.app.conf.BROKER_CONNECTION_RETRY = False
<add> l.blueprint.start(l)
<add> l.app.conf.BROKER_CONNECTION_RETRY = p
<add> l.blueprint.restart(l)
<add> l.event_dispatcher = Mock()
<add> callback = self._get_on_message(l)
<add> callback(m.decode(), m)
<add> finally:
<add> l.timer.stop()
<add> l.timer.join()
<add>
<ide> in_hold = l.timer.queue[0]
<ide> self.assertEqual(len(in_hold), 3)
<ide> eta, priority, entry = in_hold | 1 |
Text | Text | fix broken readme link | 25de2e814ecda011d4d99386f6c95be0efb3cdf1 | <ide><path>readme.md
<ide> Next.js bundles [styled-jsx](https://github.com/zeit/styled-jsx) supporting scop
<ide>
<ide> We track V8. Since V8 has wide support for ES6 and `async` and `await`, we transpile those. Since V8 doesn’t support class decorators, we don’t transpile those.
<ide>
<del>See [this](https://github.com/zeit/next.js/blob/master/server/build/webpack.js#L79) and [this](https://github.com/zeit/next.js/issues/26)
<add>See the documentation about [customizing the babel config](#customizing-babel-config) and [next/preset](./build/babel/preset.js) for more information.
<ide>
<ide> </details>
<ide> | 1 |
Javascript | Javascript | add missing license header | c04081bc562047f796a72ad372791b411b971985 | <ide><path>src/utils/onlyChild.js
<ide> /**
<add> * Copyright 2013 Facebook, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> *
<ide> * @providesModule onlyChild
<ide> */
<ide> "use strict"; | 1 |
PHP | PHP | add test for redis increment/decrement setting ttl | 9b891c88f92397aa2db7d34062d2713e9ebfd30b | <ide><path>src/Cache/Engine/RedisEngine.php
<ide> public function read($key)
<ide> }
<ide>
<ide> /**
<del> * Increments the value of an integer cached key
<add> * Increments the value of an integer cached key & update the expiry time
<ide> *
<ide> * @param string $key Identifier for the data
<ide> * @param int $offset How much to increment
<ide> public function increment($key, $offset = 1)
<ide> $key = $this->_key($key);
<ide>
<ide> $value = (int)$this->_Redis->incrBy($key, $offset);
<del>
<ide> $this->_Redis->setTimeout($key, $duration);
<ide>
<ide> return $value;
<ide> }
<ide>
<ide> /**
<del> * Decrements the value of an integer cached key
<add> * Decrements the value of an integer cached key & update the expiry time
<ide> *
<ide> * @param string $key Identifier for the data
<ide> * @param int $offset How much to subtract
<ide> public function decrement($key, $offset = 1)
<ide> $key = $this->_key($key);
<ide>
<ide> $value = (int)$this->_Redis->decrBy($key, $offset);
<del>
<ide> $this->_Redis->setTimeout($key, $duration);
<ide>
<ide> return $value;
<ide><path>tests/TestCase/Cache/Engine/RedisEngineTest.php
<ide> <?php
<ide> /**
<del> * RedisEngineTest file
<del> *
<del> * CakePHP(tm) Tests <https://book.cakephp.org/view/1196/Testing>
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> *
<ide> * Licensed under The MIT License
<ide> public function testIncrement()
<ide> $this->assertEquals(3, $result);
<ide> }
<ide>
<add> /**
<add> * Test that increment and decrement set ttls.
<add> *
<add> * @return void
<add> */
<add> public function testIncrementDecrementExpiring()
<add> {
<add> $this->_configCache(['duration' => 1]);
<add> Cache::delete('test_increment', 'redis');
<add> Cache::delete('test_decrement', 'redis');
<add>
<add> $this->assertSame(1, Cache::increment('test_increment', 1, 'redis'));
<add> $this->assertSame(-1, Cache::decrement('test_decrement', 1, 'redis'));
<add>
<add> sleep(1);
<add>
<add> $this->assertFalse(Cache::read('test_increment', 'redis'));
<add> $this->assertFalse(Cache::read('test_decrement', 'redis'));
<add> }
<add>
<ide> /**
<ide> * test clearing redis.
<ide> * | 2 |
Text | Text | fix some typos in documentation | b352c8a24cde5af5f99c758e5024e6288ac064b3 | <ide><path>docs/api-guide/metadata.md
<ide> The following third party packages provide additional metadata implementations.
<ide> [drf-schema-adapter][drf-schema-adapter] is a set of tools that makes it easier to provide schema information to frontend frameworks and libraries. It provides a metadata mixin as well as 2 metadata classes and several adapters suitable to generate [json-schema][json-schema] as well as schema information readable by various libraries.
<ide>
<ide> You can also write your own adapter to work with your specific frontend.
<del>If you whish to do so, it also provides an exporter that can export those schema information to json files.
<add>If you wish to do so, it also provides an exporter that can export those schema information to json files.
<ide>
<ide> [cite]: http://tools.ietf.org/html/rfc7231#section-4.3.7
<ide> [no-options]: https://www.mnot.net/blog/2012/10/29/NO_OPTIONS
<ide><path>docs/api-guide/permissions.md
<ide> The [REST Condition][rest-condition] package is another extension for building c
<ide>
<ide> ## DRY Rest Permissions
<ide>
<del>The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrive per user.
<add>The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrieve per user.
<ide>
<ide> ## Django Rest Framework Roles
<ide>
<ide><path>docs/api-guide/settings.md
<ide> Default:
<ide> If set, this maps the `'pk'` identifier in the URL conf onto the actual field
<ide> name when generating a schema path parameter. Typically this will be `'id'`.
<ide> This gives a more suitable representation as "primary key" is an implementation
<del>detail, wheras "identifier" is a more general concept.
<add>detail, whereas "identifier" is a more general concept.
<ide>
<ide> Default: `True`
<ide>
<ide><path>docs/topics/3.1-announcement.md
<ide> For more information, see the documentation on [customizing field mappings][cust
<ide>
<ide> We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to `pip install` the new packages, and change any import paths.
<ide>
<del>We're making this change in order to help distribute the maintainance workload, and keep better focus of the core essentials of the framework.
<add>We're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework.
<ide>
<ide> The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained [Django OAuth toolkit](https://github.com/evonove/django-oauth-toolkit) has now been promoted as our recommended option for integrating OAuth support.
<ide>
<ide><path>docs/topics/3.4-announcement.md
<ide> Name | Support | PyPI pa
<ide> ---------------------------------|-------------------------------------|--------------------------------
<ide> [Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`.
<ide> [Swagger / OpenAPI][swagger] | Schema generation & client support. | The `openapi-codec` package.
<del>[JSON Hyper-Schema][hyperschema] | Currrently client support only. | The `hyperschema-codec` package.
<add>[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
<ide> [API Blueprint][api-blueprint] | Not yet available. | Not yet available.
<ide>
<ide> ---
<ide><path>docs/topics/api-clients.md
<ide> credentials, headers and bookmarks:
<ide>
<ide> # Python client library
<ide>
<del>The `coreapi` Python package allows you to programatically interact with any
<add>The `coreapi` Python package allows you to programmatically interact with any
<ide> API that exposes a supported schema format.
<ide>
<ide> ## Getting started
<ide><path>docs/topics/kickstarter-announcement.md
<ide> Our gold sponsors include companies large and small. Many thanks for their signi
<ide>
<ide> ### Silver sponsors
<ide>
<del>The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank you to individuals who have choosen to privately support the project at this level.
<add>The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank you to individuals who have chosen to privately support the project at this level.
<ide>
<ide> <ul class="sponsor silver">
<ide> <li><a href="http://www.imtapps.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-imt_computer_services.png);">IMT Computer Services</a></li>
<ide><path>docs/topics/release-notes.md
<ide> You can determine your currently installed version using `pip freeze`:
<ide> * Fixed use of deprecated Query.aggregates. ([#4003][gh4003])
<ide> * Fix blank lines around docstrings. ([#4002][gh4002])
<ide> * Fixed admin pagination when limit is 0. ([#3990][gh3990])
<del>* OrderingFilter adjustements. ([#3983][gh3983])
<add>* OrderingFilter adjustments. ([#3983][gh3983])
<ide> * Non-required serializer related fields. ([#3976][gh3976])
<ide> * Using safer calling way of "@api_view" in tutorial. ([#3971][gh3971])
<ide> * ListSerializer doesn't handle unique_together constraints. ([#3970][gh3970]) | 8 |
PHP | PHP | move file validation into the constructor | cec6e7cd64588cb4701dd9897c81b517f0e5e6d3 | <ide><path>src/TestSuite/Schema/SchemaGenerator.php
<ide> public function __construct(string $file, string $connection)
<ide> {
<ide> $this->file = $file;
<ide> $this->connection = $connection;
<add>
<add> if (!file_exists($this->file)) {
<add> throw new RuntimeException("Cannot load `{$this->file}`");
<add> }
<ide> }
<ide>
<ide> /**
<ide> public function __construct(string $file, string $connection)
<ide> */
<ide> public function reload(?array $tables = null): void
<ide> {
<del> if (!file_exists($this->file)) {
<del> throw new RuntimeException("Cannot load `{$this->file}`");
<del> }
<del>
<ide> $cleaner = new SchemaCleaner();
<ide> $cleaner->dropTables($this->connection, $tables);
<ide> | 1 |
Java | Java | use jackson sequencewriter for streaming | 54669c51c927cda27a80fb4a3e56a3207942bb66 | <ide><path>spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Encoder.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.http.codec.json;
<ide>
<ide> import java.io.IOException;
<del>import java.io.OutputStream;
<ide> import java.lang.annotation.Annotation;
<ide> import java.nio.charset.Charset;
<ide> import java.util.ArrayList;
<ide> import com.fasterxml.jackson.core.JsonEncoding;
<ide> import com.fasterxml.jackson.core.JsonGenerator;
<ide> import com.fasterxml.jackson.core.JsonProcessingException;
<add>import com.fasterxml.jackson.core.util.ByteArrayBuilder;
<ide> import com.fasterxml.jackson.databind.JavaType;
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide> import com.fasterxml.jackson.databind.ObjectWriter;
<add>import com.fasterxml.jackson.databind.SequenceWriter;
<ide> import com.fasterxml.jackson.databind.exc.InvalidDefinitionException;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import org.springframework.core.codec.Hints;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<del>import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.core.log.LogFormatUtils;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.codec.HttpMessageEncoder;
<ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe
<ide> Assert.notNull(bufferFactory, "'bufferFactory' must not be null");
<ide> Assert.notNull(elementType, "'elementType' must not be null");
<ide>
<del> JsonEncoding encoding = getJsonEncoding(mimeType);
<del>
<ide> if (inputStream instanceof Mono) {
<del> return Mono.from(inputStream).map(value ->
<del> encodeValue(value, bufferFactory, elementType, mimeType, hints, encoding)).flux();
<add> return Mono.from(inputStream)
<add> .map(value -> encodeValue(value, bufferFactory, elementType, mimeType, hints))
<add> .flux();
<ide> }
<ide> else {
<del> return this.streamingMediaTypes.stream()
<del> .filter(mediaType -> mediaType.isCompatibleWith(mimeType))
<del> .findFirst()
<del> .map(mediaType -> {
<del> byte[] separator = STREAM_SEPARATORS.getOrDefault(mediaType, NEWLINE_SEPARATOR);
<del> return Flux.from(inputStream).map(value -> {
<del> DataBuffer buffer = encodeValue(
<del> value, bufferFactory, elementType, mimeType, hints, encoding);
<del> if (separator != null) {
<del> buffer.write(separator);
<del> }
<del> return buffer;
<del> });
<del> })
<del> .orElseGet(() -> {
<del> ResolvableType listType = ResolvableType.forClassWithGenerics(List.class, elementType);
<del> return Flux.from(inputStream).collectList().map(list ->
<del> encodeValue(list, bufferFactory, listType, mimeType, hints, encoding)).flux();
<del> });
<add> byte[] separator = streamSeparator(mimeType);
<add> if (separator != null) { // streaming
<add> try {
<add> ObjectWriter writer = createObjectWriter(elementType, mimeType, hints);
<add> ByteArrayBuilder byteBuilder = new ByteArrayBuilder(writer.getFactory()._getBufferRecycler());
<add> JsonEncoding encoding = getJsonEncoding(mimeType);
<add> JsonGenerator generator = getObjectMapper().getFactory().createGenerator(byteBuilder, encoding);
<add> SequenceWriter sequenceWriter = writer.writeValues(generator);
<add>
<add> return Flux.from(inputStream)
<add> .map(value -> encodeStreamingValue(value, bufferFactory, hints, sequenceWriter, byteBuilder,
<add> separator));
<add> }
<add> catch (IOException ex) {
<add> return Flux.error(ex);
<add> }
<add> }
<add> else { // non-streaming
<add> ResolvableType listType = ResolvableType.forClassWithGenerics(List.class, elementType);
<add> return Flux.from(inputStream)
<add> .collectList()
<add> .map(list -> encodeValue(list, bufferFactory, listType, mimeType, hints))
<add> .flux();
<add> }
<add>
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory,
<ide> ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<del> return encodeValue(value, bufferFactory, valueType, mimeType, hints, getJsonEncoding(mimeType));
<del> }
<add> ObjectWriter writer = createObjectWriter(valueType, mimeType, hints);
<add> ByteArrayBuilder byteBuilder = new ByteArrayBuilder(writer.getFactory()._getBufferRecycler());
<add> JsonEncoding encoding = getJsonEncoding(mimeType);
<ide>
<del> private DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory, ResolvableType valueType,
<del> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints, JsonEncoding encoding) {
<add> logValue(hints, value);
<ide>
<del> if (!Hints.isLoggingSuppressed(hints)) {
<del> LogFormatUtils.traceDebug(logger, traceOn -> {
<del> String formatted = LogFormatUtils.formatValue(value, !traceOn);
<del> return Hints.getLogPrefix(hints) + "Encoding [" + formatted + "]";
<del> });
<add> try {
<add> JsonGenerator generator = getObjectMapper().getFactory().createGenerator(byteBuilder, encoding);
<add> writer.writeValue(generator, value);
<add> generator.flush();
<add> }
<add> catch (InvalidDefinitionException ex) {
<add> throw new CodecException("Type definition error: " + ex.getType(), ex);
<add> }
<add> catch (JsonProcessingException ex) {
<add> throw new EncodingException("JSON encoding error: " + ex.getOriginalMessage(), ex);
<add> }
<add> catch (IOException ex) {
<add> throw new IllegalStateException("Unexpected I/O error while writing to byte array builder",
<add> ex);
<ide> }
<ide>
<del> JavaType javaType = getJavaType(valueType.getType(), null);
<del> Class<?> jsonView = (hints != null ? (Class<?>) hints.get(Jackson2CodecSupport.JSON_VIEW_HINT) : null);
<del> ObjectWriter writer = (jsonView != null ?
<del> getObjectMapper().writerWithView(jsonView) : getObjectMapper().writer());
<add> byte[] bytes = byteBuilder.toByteArray();
<add> DataBuffer buffer = bufferFactory.allocateBuffer(bytes.length);
<add> buffer.write(bytes);
<ide>
<del> if (javaType.isContainerType()) {
<del> writer = writer.forType(javaType);
<del> }
<add> return buffer;
<add> }
<ide>
<del> writer = customizeWriter(writer, mimeType, valueType, hints);
<add> private DataBuffer encodeStreamingValue(Object value, DataBufferFactory bufferFactory, @Nullable Map<String, Object> hints,
<add> SequenceWriter sequenceWriter, ByteArrayBuilder byteArrayBuilder, byte[] separator) {
<ide>
<del> DataBuffer buffer = bufferFactory.allocateBuffer();
<del> boolean release = true;
<del> OutputStream outputStream = buffer.asOutputStream();
<add> logValue(hints, value);
<ide>
<ide> try {
<del> JsonGenerator generator = getObjectMapper().getFactory().createGenerator(outputStream, encoding);
<del> writer.writeValue(generator, value);
<del> generator.flush();
<del> release = false;
<add> sequenceWriter.write(value);
<add> sequenceWriter.flush();
<ide> }
<ide> catch (InvalidDefinitionException ex) {
<ide> throw new CodecException("Type definition error: " + ex.getType(), ex);
<ide> private DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory, Re
<ide> throw new EncodingException("JSON encoding error: " + ex.getOriginalMessage(), ex);
<ide> }
<ide> catch (IOException ex) {
<del> throw new IllegalStateException("Unexpected I/O error while writing to data buffer",
<add> throw new IllegalStateException("Unexpected I/O error while writing to byte array builder",
<ide> ex);
<ide> }
<del> finally {
<del> if (release) {
<del> DataBufferUtils.release(buffer);
<del> }
<add>
<add> byte[] bytes = byteArrayBuilder.toByteArray();
<add> byteArrayBuilder.reset();
<add>
<add> int offset;
<add> int length;
<add> if (bytes.length > 0 && bytes[0] == ' ') {
<add> // SequenceWriter writes an unnecessary space in between values
<add> offset = 1;
<add> length = bytes.length - 1;
<add> }
<add> else {
<add> offset = 0;
<add> length = bytes.length;
<ide> }
<add> DataBuffer buffer = bufferFactory.allocateBuffer(length + separator.length);
<add> buffer.write(bytes, offset, length);
<add> buffer.write(separator);
<ide>
<ide> return buffer;
<ide> }
<ide>
<add> private void logValue(@Nullable Map<String, Object> hints, Object value) {
<add> if (!Hints.isLoggingSuppressed(hints)) {
<add> LogFormatUtils.traceDebug(logger, traceOn -> {
<add> String formatted = LogFormatUtils.formatValue(value, !traceOn);
<add> return Hints.getLogPrefix(hints) + "Encoding [" + formatted + "]";
<add> });
<add> }
<add> }
<add>
<add> private ObjectWriter createObjectWriter(ResolvableType valueType, @Nullable MimeType mimeType,
<add> @Nullable Map<String, Object> hints) {
<add> JavaType javaType = getJavaType(valueType.getType(), null);
<add> Class<?> jsonView = (hints != null ? (Class<?>) hints.get(Jackson2CodecSupport.JSON_VIEW_HINT) : null);
<add> ObjectWriter writer = (jsonView != null ?
<add> getObjectMapper().writerWithView(jsonView) : getObjectMapper().writer());
<add>
<add> if (javaType.isContainerType()) {
<add> writer = writer.forType(javaType);
<add> }
<add>
<add> return customizeWriter(writer, mimeType, valueType, hints);
<add> }
<add>
<ide> protected ObjectWriter customizeWriter(ObjectWriter writer, @Nullable MimeType mimeType,
<ide> ResolvableType elementType, @Nullable Map<String, Object> hints) {
<ide>
<ide> return writer;
<ide> }
<ide>
<add> @Nullable
<add> private byte[] streamSeparator(@Nullable MimeType mimeType) {
<add> for (MediaType streamingMediaType : this.streamingMediaTypes) {
<add> if (streamingMediaType.isCompatibleWith(mimeType)) {
<add> return STREAM_SEPARATORS.getOrDefault(streamingMediaType, NEWLINE_SEPARATOR);
<add> }
<add> }
<add> return null;
<add> }
<add>
<ide> /**
<ide> * Determine the JSON encoding to use for the given mime type.
<ide> * @param mimeType the mime type as requested by the caller
<ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2SmileEncoderTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.io.UncheckedIOException;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<del>import java.util.function.Consumer;
<ide>
<add>import com.fasterxml.jackson.databind.MappingIterator;
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide> import org.junit.jupiter.api.Test;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<add>import reactor.test.StepVerifier;
<ide>
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.core.testfixture.codec.AbstractEncoderTests;
<del>import org.springframework.core.testfixture.io.buffer.DataBufferTestUtils;
<ide> import org.springframework.http.codec.ServerSentEvent;
<ide> import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
<ide> import org.springframework.util.MimeType;
<ide> public Jackson2SmileEncoderTests() {
<ide>
<ide> }
<ide>
<del> public Consumer<DataBuffer> pojoConsumer(Pojo expected) {
<del> return dataBuffer -> {
<del> try {
<del> Pojo actual = this.mapper.reader().forType(Pojo.class)
<del> .readValue(DataBufferTestUtils.dumpBytes(dataBuffer));
<del> assertThat(actual).isEqualTo(expected);
<del> release(dataBuffer);
<del> }
<del> catch (IOException ex) {
<del> throw new UncheckedIOException(ex);
<del> }
<del> };
<del> }
<del>
<del>
<ide> @Override
<ide> @Test
<ide> public void canEncode() {
<ide> public void encode() {
<ide> Flux<Pojo> input = Flux.fromIterable(list);
<ide>
<ide> testEncode(input, Pojo.class, step -> step
<del> .consumeNextWith(expect(list, List.class)));
<add> .consumeNextWith(dataBuffer -> {
<add> try {
<add> Object actual = this.mapper.reader().forType(List.class)
<add> .readValue(dataBuffer.asInputStream());
<add> assertThat(actual).isEqualTo(list);
<add> }
<add> catch (IOException e) {
<add> throw new UncheckedIOException(e);
<add> }
<add> finally {
<add> release(dataBuffer);
<add> }
<add> }));
<ide> }
<ide>
<ide> @Test
<ide> public void encodeAsStream() throws Exception {
<ide> Flux<Pojo> input = Flux.just(pojo1, pojo2, pojo3);
<ide> ResolvableType type = ResolvableType.forClass(Pojo.class);
<ide>
<del> testEncodeAll(input, type, step -> step
<del> .consumeNextWith(expect(pojo1, Pojo.class))
<del> .consumeNextWith(expect(pojo2, Pojo.class))
<del> .consumeNextWith(expect(pojo3, Pojo.class))
<del> .verifyComplete(),
<del> STREAM_SMILE_MIME_TYPE, null);
<add> Flux<DataBuffer> result = this.encoder
<add> .encode(input, bufferFactory, type, STREAM_SMILE_MIME_TYPE, null);
<add>
<add> Mono<MappingIterator<Pojo>> joined = DataBufferUtils.join(result)
<add> .map(buffer -> {
<add> try {
<add> return this.mapper.reader().forType(Pojo.class).readValues(buffer.asInputStream(true));
<add> }
<add> catch (IOException ex) {
<add> throw new UncheckedIOException(ex);
<add> }
<add> });
<add>
<add> StepVerifier.create(joined)
<add> .assertNext(iter -> assertThat(iter).toIterable().contains(pojo1, pojo2, pojo3))
<add> .verifyComplete();
<ide> }
<ide>
<del>
<del> private <T> Consumer<DataBuffer> expect(T expected, Class<T> expectedType) {
<del> return dataBuffer -> {
<del> try {
<del> Object actual = this.mapper.reader().forType(expectedType)
<del> .readValue(dataBuffer.asInputStream());
<del> assertThat(actual).isEqualTo(expected);
<del> }
<del> catch (IOException e) {
<del> throw new UncheckedIOException(e);
<del> }
<del> finally {
<del> release(dataBuffer);
<del> }
<del> };
<del>
<del> }
<del>
<del>
<del>
<ide> } | 2 |
Text | Text | add my focus | 5c891eab3d23fc442a318ad7d185ec8e2f4c5283 | <ide><path>docs/focus/2018-03-05.md
<ide> - Begin "Remember me" within the credential dialog [#1327](https://github.com/atom/github/pull/1327)
<ide> - Teletype
<ide> - Tree-sitter
<add> - Shifted focus to address some open-source contributions to parsers:
<add> - Wrote documentation about how to create parsers: http://tree-sitter.github.io/tree-sitter
<add> - Fixed issues with the Bash parser
<add> - Fixed a bug found during constant fuzzing by the security team: https://github.com/tree-sitter/tree-sitter/issues/133
<ide> - Xray
<ide> - Reactor Duty
<ide>
<ide> - Kick-start our GPG pinentry handling (@smashwilson) [#846](https://github.com/atom/github/pull/846)
<ide> - Teletype
<ide> - Tree-sitter
<add> - Carrying over goals from previous weeks:
<add> - Optimize syntax tree updates in the presence of syntax errors. This will improve performance across the board but also make Tree-sitter usable in edge cases where the wrong language is being used to parse a document.
<add> - Start work on allowing parsing to take place on a background thread
<ide> - Xray
<ide> - Reactor Duty | 1 |
Javascript | Javascript | remove unused parameters | 6c382dea6bb88330cb2a66a097a49401da85f878 | <ide><path>test/addons-napi/test_async/test.js
<ide> const testException = 'test_async_cb_exception';
<ide> // Exception thrown from async completion callback.
<ide> // (Tested in a spawned process because the exception is fatal.)
<ide> if (process.argv[2] === 'child') {
<del> test_async.Test(1, common.mustCall(function(err, val) {
<add> test_async.Test(1, common.mustCall(function() {
<ide> throw new Error(testException);
<ide> }));
<ide> return;
<ide><path>test/addons-napi/test_typedarray/test.js
<ide> const arrayTypes = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array,
<ide> Uint16Array, Int32Array, Uint32Array, Float32Array,
<ide> Float64Array ];
<ide>
<del>arrayTypes.forEach((currentType, key) => {
<add>arrayTypes.forEach((currentType) => {
<ide> const template = Reflect.construct(currentType, buffer);
<ide> const theArray = test_typedarray.CreateTypedArray(template, buffer);
<ide>
<ide><path>test/addons/repl-domain-abort/test.js
<ide> const lines = [
<ide> const dInput = new stream.Readable();
<ide> const dOutput = new stream.Writable();
<ide>
<del>dInput._read = function _read(size) {
<add>dInput._read = function _read() {
<ide> while (lines.length > 0 && this.push(lines.shift()));
<ide> if (lines.length === 0)
<ide> this.push(null); | 3 |
Text | Text | fix an erratum; s/two/three/ | 8c93958fcb1b1fc838c76b08cc4dde4ce37691bb | <ide><path>docs/userguide/networking/dockernetworks.md
<ide> Once you have several machines provisioned, you can use Docker Swarm to quickly
<ide> form them into a swarm which includes a discovery service as well.
<ide>
<ide> To create an overlay network, you configure options on the `daemon` on each
<del>Docker Engine for use with `overlay` network. There are two options to set:
<add>Docker Engine for use with `overlay` network. There are three options to set:
<ide>
<ide> <table>
<ide> <thead> | 1 |
Python | Python | fix typo in gen-postmortem-metadata.py | e46c3f743dc78ef0a614289a874e1c60c7e96490 | <ide><path>tools/gen-postmortem-metadata.py
<ide> #
<ide> # gen-postmortem-metadata.py output_file.cc
<ide> #
<del># Creates debugging symbols to help naviage Node's internals using post-mortem
<add># Creates debugging symbols to help navigate Node's internals using post-mortem
<ide> # debugging tools.
<ide> #
<ide> | 1 |
PHP | PHP | apply fixes from styleci | cdb14c79e9035acfc925a1c9794aa577cb7ef452 | <ide><path>src/Illuminate/Notifications/AnonymousNotifiable.php
<ide> public function with($attributes)
<ide> $this->attributes = array_merge($this->attributes, $attributes);
<ide>
<ide> return $this;
<del> }
<add> }
<ide>
<ide> /**
<ide> * Send the given notification. | 1 |
PHP | PHP | send eloquent collection for proper serializationg | 1c78e00ef3815e7b0bf710037b52faefb464e97d | <ide><path>src/Illuminate/Notifications/ChannelManager.php
<ide> protected function queueNotification($notifiables, $notification)
<ide> foreach ($notifiables as $notifiable) {
<ide> foreach ($notification->via($notifiable) as $channel) {
<ide> $bus->dispatch(
<del> (new SendQueuedNotifications([$notifiable], $notification, [$channel]))
<add> (new SendQueuedNotifications($this->formatNotifiables($notifiable), $notification, [$channel]))
<ide> ->onConnection($notification->connection)
<ide> ->onQueue($notification->queue)
<ide> ->delay($notification->delay) | 1 |
Ruby | Ruby | remove useless metaprogramming | 86dd717c203f6056b4fa367080c989c3411b7300 | <ide><path>lib/arel/algebra/predicates.rb
<ide> def not
<ide> end
<ide>
<ide> class Polyadic < Predicate
<del> attributes :predicates
<add> attr_reader :predicates
<ide>
<ide> def initialize(*predicates)
<ide> @predicates = predicates | 1 |
Text | Text | move tests to /learn | 49f2055b98c34cbd95de42f603a06ed3d16efe47 | <ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/issue-tracker.md
<ide> When you are done, make sure a working demo of your project is hosted somewhere
<ide> ## Instructions
<ide> <section id='instructions'>
<ide>
<del>- Complete the neccessary routes in `/routes/api.js`
<add>- Complete the necessary routes in `/routes/api.js`
<ide> - Create all of the functional tests in `tests/2_functional-tests.js`
<ide> - Copy the `sample.env` file to `.env` and set the variables appropriately
<ide> - To run the tests uncomment `NODE_ENV=test` in your `.env` file
<ide> - To run the tests in the console, use the command `npm run test`. To open the Repl.it console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell"
<ide>
<add>Write the following tests in `tests/2_functional-tests.js`:
<add>
<add>- Create an issue with every field: POST request to `/api/issues/{project}`
<add>- Create an issue with only required fields: POST request to `/api/issues/{project}`
<add>- Create an issue with missing required fields: POST request to `/api/issues/{project}`
<add>- View issues on a project: GET request to `/api/issues/{project}`
<add>- View issues on a project with one filter: GET request to `/api/issues/{project}`
<add>- View issues on a project with multiple filters: GET request to `/api/issues/{project}`
<add>- Update one field on an issue: PUT request to `/api/issues/{project}`
<add>- Update multiple fields on an issue: PUT request to `/api/issues/{project}`
<add>- Update an issue with missing `_id`: PUT request to `/api/issues/{project}`
<add>- Update an issue with no fields to update: PUT request to `/api/issues/{project}`
<add>- Update an issue with an invalid `_id`: PUT request to `/api/issues/{project}`
<add>- Delete an issue: DELETE request to `/api/issues/{project}`
<add>- Delete an issue with an invalid `_id`: DELETE request to `/api/issues/{project}`
<add>- Delete an issue with missing `_id`: DELETE request to `/api/issues/{project}`
<add>
<ide> </section>
<ide>
<ide> ## Tests | 1 |
Javascript | Javascript | save connection url as class variable | 8facc865ab2ec032da34f6f755ee8870ee4741aa | <ide><path>Libraries/WebSocket/WebSocket.js
<ide> class WebSocket extends (EventTarget(...WEBSOCKET_EVENTS): any) {
<ide> options: ?{headers?: {origin?: string, ...}, ...},
<ide> ) {
<ide> super();
<add> this.url = url;
<ide> if (typeof protocols === 'string') {
<ide> protocols = [protocols];
<ide> } | 1 |
Java | Java | add support for x-forwarded-for and forwarded for | 883ad098f927760e6bd52af531d0938e0c6ab5dc | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultServerHttpRequestBuilder.java
<ide> class DefaultServerHttpRequestBuilder implements ServerHttpRequest.Builder {
<ide> @Nullable
<ide> private SslInfo sslInfo;
<ide>
<add> @Nullable
<add> private InetSocketAddress remoteAddress;
<add>
<ide> private Flux<DataBuffer> body;
<ide>
<ide> private final ServerHttpRequest originalRequest;
<ide> public DefaultServerHttpRequestBuilder(ServerHttpRequest original) {
<ide> this.uri = original.getURI();
<ide> this.headers = HttpHeaders.writableHttpHeaders(original.getHeaders());
<ide> this.httpMethodValue = original.getMethodValue();
<add> this.remoteAddress = original.getRemoteAddress();
<ide> this.body = original.getBody();
<ide> this.originalRequest = original;
<ide> }
<ide> public ServerHttpRequest.Builder sslInfo(SslInfo sslInfo) {
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public ServerHttpRequest.Builder remoteAddress(InetSocketAddress remoteAddress) {
<add> this.remoteAddress = remoteAddress;
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public ServerHttpRequest build() {
<ide> return new MutatedServerHttpRequest(getUriToUse(), this.contextPath,
<del> this.httpMethodValue, this.sslInfo, this.body, this.originalRequest);
<add> this.httpMethodValue, this.sslInfo, this.remoteAddress, this.body, this.originalRequest);
<ide> }
<ide>
<ide> private URI getUriToUse() {
<ide> private static class MutatedServerHttpRequest extends AbstractServerHttpRequest
<ide> @Nullable
<ide> private final SslInfo sslInfo;
<ide>
<add> @Nullable
<add> private InetSocketAddress remoteAddress;
<add>
<ide> private final Flux<DataBuffer> body;
<ide>
<ide> private final ServerHttpRequest originalRequest;
<ide>
<ide>
<ide> public MutatedServerHttpRequest(URI uri, @Nullable String contextPath,
<del> String methodValue, @Nullable SslInfo sslInfo,
<add> String methodValue, @Nullable SslInfo sslInfo, @Nullable InetSocketAddress remoteAddress,
<ide> Flux<DataBuffer> body, ServerHttpRequest originalRequest) {
<ide>
<ide> super(uri, contextPath, originalRequest.getHeaders());
<ide> this.methodValue = methodValue;
<del> this.sslInfo = sslInfo != null ? sslInfo : originalRequest.getSslInfo();
<add> this.remoteAddress = (remoteAddress != null ? remoteAddress : originalRequest.getRemoteAddress());
<add> this.sslInfo = (sslInfo != null ? sslInfo : originalRequest.getSslInfo());
<ide> this.body = body;
<ide> this.originalRequest = originalRequest;
<ide> }
<ide> public InetSocketAddress getLocalAddress() {
<ide> @Override
<ide> @Nullable
<ide> public InetSocketAddress getRemoteAddress() {
<del> return this.originalRequest.getRemoteAddress();
<add> return this.remoteAddress;
<ide> }
<ide>
<ide> @Override
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServerHttpRequest.java
<ide> interface Builder {
<ide> */
<ide> Builder sslInfo(SslInfo sslInfo);
<ide>
<add> /**
<add> * Set the address of the remote client.
<add> * @since 5.3
<add> */
<add> Builder remoteAddress(InetSocketAddress remoteAddress);
<add>
<ide> /**
<ide> * Build a {@link ServerHttpRequest} decorator with the mutated properties.
<ide> */
<ide><path>spring-web/src/main/java/org/springframework/web/filter/ForwardedHeaderFilter.java
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide> import java.util.function.Supplier;
<add>import java.util.regex.Pattern;
<ide>
<ide> import javax.servlet.FilterChain;
<ide> import javax.servlet.ServletException;
<ide> import javax.servlet.http.HttpServletResponse;
<ide> import javax.servlet.http.HttpServletResponseWrapper;
<ide>
<add>import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpRequest;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.server.ServletServerHttpRequest;
<ide> public class ForwardedHeaderFilter extends OncePerRequestFilter {
<ide>
<ide> private static final Set<String> FORWARDED_HEADER_NAMES =
<del> Collections.newSetFromMap(new LinkedCaseInsensitiveMap<>(6, Locale.ENGLISH));
<add> Collections.newSetFromMap(new LinkedCaseInsensitiveMap<>(10, Locale.ENGLISH));
<ide>
<ide> static {
<ide> FORWARDED_HEADER_NAMES.add("Forwarded");
<ide> public class ForwardedHeaderFilter extends OncePerRequestFilter {
<ide> FORWARDED_HEADER_NAMES.add("X-Forwarded-Proto");
<ide> FORWARDED_HEADER_NAMES.add("X-Forwarded-Prefix");
<ide> FORWARDED_HEADER_NAMES.add("X-Forwarded-Ssl");
<add> FORWARDED_HEADER_NAMES.add("X-Forwarded-For");
<ide> }
<ide>
<ide>
<ide> public Enumeration<String> getHeaderNames() {
<ide> */
<ide> private static class ForwardedHeaderExtractingRequest extends ForwardedHeaderRemovingRequest {
<ide>
<add> private static final String X_FORWARDED_FOR_HEADER = "X-Forwarded-For";
<add> private static final String FORWARDED_HEADER = "Forwarded";
<add> private static final Pattern FORWARDED_FOR_PATTERN = Pattern.compile("(?i:^[^,]*for=.+)");
<add>
<ide> @Nullable
<ide> private final String scheme;
<ide>
<ide> private static class ForwardedHeaderExtractingRequest extends ForwardedHeaderRem
<ide>
<ide> private final int port;
<ide>
<add> @Nullable
<add> private final String remoteHost;
<add>
<add> @Nullable
<add> private final String remoteAddr;
<add>
<add> private final int remotePort;
<add>
<ide> private final ForwardedPrefixExtractor forwardedPrefixExtractor;
<ide>
<ide>
<ide> private static class ForwardedHeaderExtractingRequest extends ForwardedHeaderRem
<ide> this.host = uriComponents.getHost();
<ide> this.port = (port == -1 ? (this.secure ? 443 : 80) : port);
<ide>
<add> HttpHeaders headers = httpRequest.getHeaders();
<add> boolean hasForwardedFor = StringUtils.hasText(headers.getFirst(X_FORWARDED_FOR_HEADER)) ||
<add> (StringUtils.hasText(headers.getFirst(FORWARDED_HEADER)) &&
<add> FORWARDED_FOR_PATTERN.matcher(headers.getFirst(FORWARDED_HEADER)).matches());
<add> if (hasForwardedFor) {
<add> UriComponents remoteUriComponents = UriComponentsBuilder.newInstance()
<add> .host(request.getRemoteHost())
<add> .port(request.getRemotePort())
<add> .adaptFromForwardedForHeader(headers)
<add> .build();
<add> this.remoteHost = remoteUriComponents.getHost();
<add> this.remoteAddr = this.remoteHost;
<add> this.remotePort = remoteUriComponents.getPort();
<add> } else {
<add> this.remoteHost = request.getRemoteHost();
<add> this.remoteAddr = request.getRemoteAddr();
<add> this.remotePort = request.getRemotePort();
<add> }
<add>
<ide> String baseUrl = this.scheme + "://" + this.host + (port == -1 ? "" : ":" + port);
<ide> Supplier<HttpServletRequest> delegateRequest = () -> (HttpServletRequest) getRequest();
<ide> this.forwardedPrefixExtractor = new ForwardedPrefixExtractor(delegateRequest, pathHelper, baseUrl);
<ide> public String getRequestURI() {
<ide> public StringBuffer getRequestURL() {
<ide> return this.forwardedPrefixExtractor.getRequestUrl();
<ide> }
<add>
<add> @Override
<add> @Nullable
<add> public String getRemoteHost() {
<add> return this.remoteHost;
<add> }
<add>
<add> @Override
<add> @Nullable
<add> public String getRemoteAddr() {
<add> return this.remoteAddr;
<add> }
<add>
<add> @Override
<add> public int getRemotePort() {
<add> return remotePort;
<add> }
<ide> }
<ide>
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/server/adapter/ForwardedHeaderTransformer.java
<ide>
<ide> package org.springframework.web.server.adapter;
<ide>
<add>import java.net.InetSocketAddress;
<ide> import java.net.URI;
<ide> import java.util.Collections;
<ide> import java.util.Locale;
<ide> import java.util.Set;
<ide> import java.util.function.Function;
<add>import java.util.regex.Pattern;
<ide>
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.LinkedCaseInsensitiveMap;
<ide> import org.springframework.util.StringUtils;
<add>import org.springframework.web.util.UriComponents;
<ide> import org.springframework.web.util.UriComponentsBuilder;
<ide>
<ide> /**
<ide> */
<ide> public class ForwardedHeaderTransformer implements Function<ServerHttpRequest, ServerHttpRequest> {
<ide>
<add> private static final String X_FORWARDED_FOR_HEADER = "X-Forwarded-For";
<add> private static final String FORWARDED_HEADER = "Forwarded";
<add> private static final Pattern FORWARDED_FOR_PATTERN = Pattern.compile("(?i:^[^,]*for=.+)");
<ide> static final Set<String> FORWARDED_HEADER_NAMES =
<del> Collections.newSetFromMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH));
<add> Collections.newSetFromMap(new LinkedCaseInsensitiveMap<>(10, Locale.ENGLISH));
<ide>
<ide> static {
<ide> FORWARDED_HEADER_NAMES.add("Forwarded");
<ide> public class ForwardedHeaderTransformer implements Function<ServerHttpRequest, S
<ide> FORWARDED_HEADER_NAMES.add("X-Forwarded-Proto");
<ide> FORWARDED_HEADER_NAMES.add("X-Forwarded-Prefix");
<ide> FORWARDED_HEADER_NAMES.add("X-Forwarded-Ssl");
<add> FORWARDED_HEADER_NAMES.add("X-Forwarded-For");
<ide> }
<ide>
<ide>
<ide> public ServerHttpRequest apply(ServerHttpRequest request) {
<ide> builder.path(prefix + uri.getRawPath());
<ide> builder.contextPath(prefix);
<ide> }
<add> InetSocketAddress remoteAddress = request.getRemoteAddress();
<add> HttpHeaders headers = request.getHeaders();
<add> boolean hasForwardedFor = StringUtils.hasText(headers.getFirst(X_FORWARDED_FOR_HEADER)) ||
<add> (StringUtils.hasText(headers.getFirst(FORWARDED_HEADER)) &&
<add> FORWARDED_FOR_PATTERN.matcher(headers.getFirst(FORWARDED_HEADER)).matches());
<add> if (hasForwardedFor) {
<add> String originalRemoteHost = ((remoteAddress != null) ? remoteAddress.getHostName() : null);
<add> int originalRemotePort = ((remoteAddress != null) ? remoteAddress.getPort() : -1);
<add> UriComponents remoteUriComponents = UriComponentsBuilder.newInstance()
<add> .host(originalRemoteHost)
<add> .port(originalRemotePort)
<add> .adaptFromForwardedForHeader(headers)
<add> .build();
<add> String remoteHost = remoteUriComponents.getHost();
<add> int remotePort = (remoteUriComponents.getPort() != -1 ? remoteUriComponents.getPort() : 0);
<add> if (remoteHost != null) {
<add> builder.remoteAddress(InetSocketAddress.createUnresolved(remoteHost, remotePort));
<add> }
<add> } else {
<add> builder.remoteAddress(remoteAddress);
<add> }
<ide> }
<ide> removeForwardedHeaders(builder);
<ide> request = builder.build();
<ide><path>spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java
<ide> public class UriComponentsBuilder implements UriBuilder, Cloneable {
<ide> "^" + HTTP_PATTERN + "(//(" + USERINFO_PATTERN + "@)?" + HOST_PATTERN + "(:" + PORT_PATTERN + ")?" + ")?" +
<ide> PATH_PATTERN + "(\\?" + LAST_PATTERN + ")?");
<ide>
<del> private static final Pattern FORWARDED_HOST_PATTERN = Pattern.compile("host=\"?([^;,\"]+)\"?");
<add> private static final Pattern FORWARDED_HOST_PATTERN = Pattern.compile("(?i:host)=\"?([^;,\"]+)\"?");
<ide>
<del> private static final Pattern FORWARDED_PROTO_PATTERN = Pattern.compile("proto=\"?([^;,\"]+)\"?");
<add> private static final Pattern FORWARDED_PROTO_PATTERN = Pattern.compile("(?i:proto)=\"?([^;,\"]+)\"?");
<add>
<add> private static final Pattern FORWARDED_FOR_PATTERN = Pattern.compile("(?i:for)=\"?([^;,\"]+)\"?");
<add>
<add> private static final String FORWARDED_FOR_NUMERIC_PORT_PATTERN = "^(\\d{1,5})$";
<ide>
<ide> private static final Object[] EMPTY_VALUES = new Object[0];
<ide>
<ide> public UriComponentsBuilder uriVariables(Map<String, Object> uriVariables) {
<ide> return this;
<ide> }
<ide>
<add> /**
<add> * Adapt this builders's host+port from the "for" parameter of the "Forwarded"
<add> * header or from "X-Forwarded-For" if "Forwarded" is not found. If neither
<add> * "Forwarded" nor "X-Forwarded-For" is found no changes are made to the
<add> * builder.
<add> * @param headers the HTTP headers to consider
<add> * @return this UriComponentsBuilder
<add> */
<add> public UriComponentsBuilder adaptFromForwardedForHeader(HttpHeaders headers) {
<add> String forwardedHeader = headers.getFirst("Forwarded");
<add> if (StringUtils.hasText(forwardedHeader)) {
<add> String forwardedToUse = StringUtils.tokenizeToStringArray(forwardedHeader, ",")[0];
<add> Matcher matcher = FORWARDED_FOR_PATTERN.matcher(forwardedToUse);
<add> if (matcher.find()) {
<add> adaptForwardedForHost(matcher.group(1).trim());
<add> }
<add> }
<add> else {
<add> String forHeader = headers.getFirst("X-Forwarded-For");
<add> if (StringUtils.hasText(forHeader)) {
<add> String forwardedForToUse = StringUtils.tokenizeToStringArray(forHeader, ",")[0];
<add> host(forwardedForToUse);
<add> }
<add> }
<add> return this;
<add> }
<add>
<ide> /**
<ide> * Adapt this builder's scheme+host+port from the given headers, specifically
<ide> * "Forwarded" (<a href="https://tools.ietf.org/html/rfc7239">RFC 7239</a>,
<ide> private void adaptForwardedHost(String hostToUse) {
<ide> }
<ide> }
<ide>
<add> private void adaptForwardedForHost(String hostToUse) {
<add> String hostName = hostToUse;
<add> int portSeparatorIdx = hostToUse.lastIndexOf(':');
<add> if (portSeparatorIdx > hostToUse.lastIndexOf(']')) {
<add> String hostPort = hostToUse.substring(portSeparatorIdx + 1);
<add> // check if port is not obfuscated
<add> if (hostPort.matches(FORWARDED_FOR_NUMERIC_PORT_PATTERN)) {
<add> port(Integer.parseInt(hostPort));
<add> }
<add> hostName = hostToUse.substring(0, portSeparatorIdx);
<add> }
<add> if (hostName.matches(HOST_IPV6_PATTERN)) {
<add> host(hostName.substring(hostName.indexOf('[') + 1, hostName.indexOf(']')));
<add> } else {
<add> host(hostName);
<add> }
<add> }
<add>
<ide> private void resetHierarchicalComponents() {
<ide> this.userInfo = null;
<ide> this.host = null;
<ide><path>spring-web/src/test/java/org/springframework/web/filter/ForwardedHeaderFilterTests.java
<ide> public class ForwardedHeaderFilterTests {
<ide> private static final String X_FORWARDED_PREFIX = "x-forwarded-prefix";
<ide>
<ide> private static final String X_FORWARDED_SSL = "x-forwarded-ssl";
<add> private static final String X_FORWARDED_FOR = "x-forwarded-for";
<add> private static final String FORWARDED = "forwarded";
<ide>
<ide>
<ide> private final ForwardedHeaderFilter filter = new ForwardedHeaderFilter();
<ide> public void setup() throws Exception {
<ide> this.filterChain = new MockFilterChain(new HttpServlet() {});
<ide> }
<ide>
<add> @Test
<add> public void forwardedForEmpty() throws Exception {
<add> this.request.addHeader(X_FORWARDED_FOR, "");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(MockHttpServletRequest.DEFAULT_REMOTE_ADDR);
<add> assertThat(actual.getRemoteHost()).isEqualTo(MockHttpServletRequest.DEFAULT_REMOTE_HOST);
<add> assertThat(actual.getRemotePort()).isEqualTo(MockHttpServletRequest.DEFAULT_SERVER_PORT);
<add> }
<add>
<add> @Test
<add> public void forwardedForSingleIdentifier() throws Exception {
<add> this.request.addHeader(X_FORWARDED_FOR, "203.0.113.195");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("203.0.113.195");
<add> assertThat(actual.getRemotePort()).isEqualTo(MockHttpServletRequest.DEFAULT_SERVER_PORT);
<add> }
<add>
<add> @Test
<add> public void forwardedForMultipleIdentifiers() throws Exception {
<add> this.request.addHeader(X_FORWARDED_FOR, "203.0.113.195, 70.41.3.18, 150.172.238.178");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("203.0.113.195");
<add> assertThat(actual.getRemotePort()).isEqualTo(MockHttpServletRequest.DEFAULT_SERVER_PORT);
<add> }
<add>
<add> @Test
<add> public void standardizedForwardedForIpV4Identifier() throws Exception {
<add> this.request.addHeader(FORWARDED, "for=203.0.113.195");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("203.0.113.195");
<add> assertThat(actual.getRemotePort()).isEqualTo(MockHttpServletRequest.DEFAULT_SERVER_PORT);
<add> }
<add>
<add> @Test
<add> public void standardizedForwardedForIpV6Identifier() throws Exception {
<add> this.request.addHeader(FORWARDED, "for=\"[2001:db8:cafe::17]\"");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("2001:db8:cafe::17");
<add> assertThat(actual.getRemotePort()).isEqualTo(MockHttpServletRequest.DEFAULT_SERVER_PORT);
<add> }
<add>
<add> @Test
<add> public void standardizedForwardedForUnknownIdentifier() throws Exception {
<add> this.request.addHeader(FORWARDED, "for=unknown");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("unknown");
<add> assertThat(actual.getRemotePort()).isEqualTo(MockHttpServletRequest.DEFAULT_SERVER_PORT);
<add> }
<add>
<add> @Test
<add> public void standardizedForwardedForObfuscatedIdentifier() throws Exception {
<add> this.request.addHeader(FORWARDED, "for=_abc-12_d.e");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("_abc-12_d.e");
<add> assertThat(actual.getRemotePort()).isEqualTo(MockHttpServletRequest.DEFAULT_SERVER_PORT);
<add> }
<add>
<add> @Test
<add> public void standardizedForwardedForIpV4IdentifierWithPort() throws Exception {
<add> this.request.addHeader(FORWARDED, "for=\"203.0.113.195:47011\"");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("203.0.113.195");
<add> assertThat(actual.getRemotePort()).isEqualTo(47011);
<add> }
<add>
<add> @Test
<add> public void standardizedForwardedForIpV6IdentifierWithPort() throws Exception {
<add> this.request.addHeader(FORWARDED, "For=\"[2001:db8:cafe::17]:47011\"");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("2001:db8:cafe::17");
<add> assertThat(actual.getRemotePort()).isEqualTo(47011);
<add> }
<add>
<add> @Test
<add> public void standardizedForwardedForUnknownIdentifierWithPort() throws Exception {
<add> this.request.addHeader(FORWARDED, "for=\"unknown:47011\"");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("unknown");
<add> assertThat(actual.getRemotePort()).isEqualTo(47011);
<add> }
<add>
<add> @Test
<add> public void standardizedForwardedForObfuscatedIdentifierWithPort() throws Exception {
<add> this.request.addHeader(FORWARDED, "for=\"_abc-12_d.e:47011\"");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("_abc-12_d.e");
<add> assertThat(actual.getRemotePort()).isEqualTo(47011);
<add> }
<add>
<add> @Test
<add> public void standardizedForwardedForMultipleIdentifiers() throws Exception {
<add> this.request.addHeader(FORWARDED, "for=203.0.113.195;proto=http, for=\"[2001:db8:cafe::17]\", for=unknown");
<add> HttpServletRequest actual = filterAndGetWrappedRequest();
<add>
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("203.0.113.195");
<add> assertThat(actual.getRemotePort()).isEqualTo(MockHttpServletRequest.DEFAULT_SERVER_PORT);
<add> }
<ide>
<ide> @Test
<ide> public void contextPathEmpty() throws Exception {
<ide> public String getHeader(String header) {
<ide>
<ide> @Test
<ide> public void shouldFilter() {
<del> testShouldFilter("Forwarded");
<add> testShouldFilter(FORWARDED);
<ide> testShouldFilter(X_FORWARDED_HOST);
<ide> testShouldFilter(X_FORWARDED_PORT);
<ide> testShouldFilter(X_FORWARDED_PROTO);
<ide> testShouldFilter(X_FORWARDED_SSL);
<add> testShouldFilter(X_FORWARDED_FOR);
<ide> }
<ide>
<ide> private void testShouldFilter(String headerName) {
<ide> public void forwardedRequest() throws Exception {
<ide> this.request.addHeader(X_FORWARDED_HOST, "84.198.58.199");
<ide> this.request.addHeader(X_FORWARDED_PORT, "443");
<ide> this.request.addHeader("foo", "bar");
<add> this.request.addHeader(X_FORWARDED_FOR, "203.0.113.195");
<ide>
<ide> this.filter.doFilter(this.request, new MockHttpServletResponse(), this.filterChain);
<ide> HttpServletRequest actual = (HttpServletRequest) this.filterChain.getRequest();
<ide> public void forwardedRequest() throws Exception {
<ide> assertThat(actual.getServerName()).isEqualTo("84.198.58.199");
<ide> assertThat(actual.getServerPort()).isEqualTo(443);
<ide> assertThat(actual.isSecure()).isTrue();
<add> assertThat(actual.getRemoteAddr()).isEqualTo(actual.getRemoteHost()).isEqualTo("203.0.113.195");
<ide>
<ide> assertThat(actual.getHeader(X_FORWARDED_PROTO)).isNull();
<ide> assertThat(actual.getHeader(X_FORWARDED_HOST)).isNull();
<ide> assertThat(actual.getHeader(X_FORWARDED_PORT)).isNull();
<add> assertThat(actual.getHeader(X_FORWARDED_FOR)).isNull();
<ide> assertThat(actual.getHeader("foo")).isEqualTo("bar");
<ide> }
<ide>
<ide> public void forwardedRequestInRemoveOnlyMode() throws Exception {
<ide> this.request.addHeader(X_FORWARDED_PORT, "443");
<ide> this.request.addHeader(X_FORWARDED_SSL, "on");
<ide> this.request.addHeader("foo", "bar");
<add> this.request.addHeader(X_FORWARDED_FOR, "203.0.113.195");
<ide>
<ide> this.filter.setRemoveOnly(true);
<ide> this.filter.doFilter(this.request, new MockHttpServletResponse(), this.filterChain);
<ide> public void forwardedRequestInRemoveOnlyMode() throws Exception {
<ide> assertThat(actual.getServerName()).isEqualTo("localhost");
<ide> assertThat(actual.getServerPort()).isEqualTo(80);
<ide> assertThat(actual.isSecure()).isFalse();
<add> assertThat(actual.getRemoteAddr()).isEqualTo(MockHttpServletRequest.DEFAULT_REMOTE_ADDR);
<add> assertThat(actual.getRemoteHost()).isEqualTo(MockHttpServletRequest.DEFAULT_REMOTE_HOST);
<ide>
<ide> assertThat(actual.getHeader(X_FORWARDED_PROTO)).isNull();
<ide> assertThat(actual.getHeader(X_FORWARDED_HOST)).isNull();
<ide> assertThat(actual.getHeader(X_FORWARDED_PORT)).isNull();
<ide> assertThat(actual.getHeader(X_FORWARDED_SSL)).isNull();
<add> assertThat(actual.getHeader(X_FORWARDED_FOR)).isNull();
<ide> assertThat(actual.getHeader("foo")).isEqualTo("bar");
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/web/server/adapter/ForwardedHeaderTransformerTests.java
<ide>
<ide> package org.springframework.web.server.adapter;
<ide>
<add>import java.net.InetSocketAddress;
<ide> import java.net.URI;
<add>import java.net.URISyntaxException;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> public class ForwardedHeaderTransformerTests {
<ide>
<ide> private static final String BASE_URL = "https://example.com/path";
<ide>
<del>
<ide> private final ForwardedHeaderTransformer requestMutator = new ForwardedHeaderTransformer();
<ide>
<del>
<ide> @Test
<ide> void removeOnly() {
<ide> this.requestMutator.setRemoveOnly(true);
<ide> void removeOnly() {
<ide> headers.add("X-Forwarded-Proto", "http");
<ide> headers.add("X-Forwarded-Prefix", "prefix");
<ide> headers.add("X-Forwarded-Ssl", "on");
<add> headers.add("X-Forwarded-For", "203.0.113.195");
<ide> ServerHttpRequest request = this.requestMutator.apply(getRequest(headers));
<ide>
<ide> assertForwardedHeadersRemoved(request);
<ide> void shouldConcatenatePrefixesWithTrailingSlashes() throws Exception {
<ide> assertForwardedHeadersRemoved(request);
<ide> }
<ide>
<add> @Test
<add> public void noForwardedFor() throws URISyntaxException {
<add> HttpHeaders headers = new HttpHeaders();
<add> headers.add("Forwarded", "host=84.198.58.199;proto=https");
<add>
<add> InetSocketAddress remoteAddress = new InetSocketAddress("example.client", 47011);
<add>
<add> ServerHttpRequest request = MockServerHttpRequest
<add> .method(HttpMethod.GET, new URI("https://example.com/a%20b?q=a%2Bb"))
<add> .remoteAddress(remoteAddress)
<add> .headers(headers)
<add> .build();
<add>
<add> request = this.requestMutator.apply(request);
<add> assertThat(request.getRemoteAddress()).isEqualTo(remoteAddress);
<add> }
<add>
<add> @Test
<add> public void forwardedFor() throws URISyntaxException {
<add> HttpHeaders headers = new HttpHeaders();
<add> headers.add("Forwarded", "for=\"203.0.113.195:4711\";host=84.198.58.199;proto=https");
<add>
<add> InetSocketAddress remoteAddress = new InetSocketAddress("example.client", 47011);
<add>
<add> ServerHttpRequest request = MockServerHttpRequest
<add> .method(HttpMethod.GET, new URI("https://example.com/a%20b?q=a%2Bb"))
<add> .remoteAddress(remoteAddress)
<add> .headers(headers)
<add> .build();
<add>
<add> request = this.requestMutator.apply(request);
<add> assertThat(request.getRemoteAddress().getHostName()).isEqualTo("203.0.113.195");
<add> assertThat(request.getRemoteAddress().getPort()).isEqualTo(4711);
<add> }
<add>
<add> @Test
<add> public void xForwardedFor() throws URISyntaxException {
<add> HttpHeaders headers = new HttpHeaders();
<add> headers.add("x-forwarded-for", "203.0.113.195, 70.41.3.18, 150.172.238.178");
<add>
<add> ServerHttpRequest request = MockServerHttpRequest
<add> .method(HttpMethod.GET, new URI("https://example.com/a%20b?q=a%2Bb"))
<add> .headers(headers)
<add> .build();
<add>
<add> request = this.requestMutator.apply(request);
<add> assertThat(request.getRemoteAddress().getHostName()).isEqualTo("203.0.113.195");
<add> }
<add>
<ide>
<ide> private MockServerHttpRequest getRequest(HttpHeaders headers) {
<ide> return MockServerHttpRequest.get(BASE_URL).headers(headers).build(); | 7 |
Python | Python | fix metadata in training | acba2e1051a0734d7d6ae2cc11211096039446bd | <ide><path>spacy/cli/train.py
<ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=10, n_sents=0,
<ide>
<ide> lang_class = util.get_lang_class(lang)
<ide> nlp = lang_class()
<add> meta['pipeline'] = pipeline
<add> nlp.meta.update(meta)
<ide> if vectors:
<ide> util.load_model(vectors, vocab=nlp.vocab)
<ide> for name in pipeline: | 1 |
PHP | PHP | apply fixes from styleci | b0dfbdf78ac7178c13384e91e650697e0d6f3397 | <ide><path>src/Illuminate/Foundation/Http/Kernel.php
<ide> use Illuminate\Routing\Router;
<ide> use Illuminate\Support\Facades\Facade;
<ide> use InvalidArgumentException;
<del>use Symfony\Component\Debug\Exception\FatalThrowableError;
<ide> use Throwable;
<ide>
<ide> class Kernel implements KernelContract | 1 |
Python | Python | fix e712 flake8 warning (x1) | 357db7098c4431a7b28526b8de74c0fa08af0a9b | <ide><path>examples/run_multiple_choice.py
<ide> def load_and_cache_examples(args, task, tokenizer, evaluate=False, test=False):
<ide> cached_mode = "test"
<ide> else:
<ide> cached_mode = "train"
<del> assert (evaluate == True and test == True) == False
<add> assert not (evaluate and test)
<ide> cached_features_file = os.path.join(
<ide> args.data_dir,
<ide> "cached_{}_{}_{}_{}".format( | 1 |
Ruby | Ruby | use delegation for mach-o methods | a8c4136e9edb02e6b637b53357af7a921538c149 | <ide><path>Library/Homebrew/os/mac/mach.rb
<ide> require "os/mac/architecture_list"
<ide>
<ide> module MachOShim
<add> extend Forwardable
<add>
<add> delegate [:dylib_id, :rpaths, :delete_rpath] => :macho
<add>
<ide> # @private
<ide> def macho
<ide> @macho ||= begin
<ide> def dynamically_linked_libraries(except: :none)
<ide> lcs.map(&:name).map(&:to_s).uniq
<ide> end
<ide>
<del> def dylib_id
<del> macho.dylib_id
<del> end
<del>
<del> def rpaths
<del> macho.rpaths
<del> end
<del>
<del> def delete_rpath(rpath)
<del> macho.delete_rpath(rpath)
<del> end
<del>
<ide> def archs
<ide> mach_data.map { |m| m.fetch :arch }.extend(ArchitectureListExtension)
<ide> end | 1 |
Text | Text | add note about beforefiles continuing | 6e99f7af39d5a31bab8c227e945bd3e765b3d3fe | <ide><path>docs/api-reference/next.config.js/rewrites.md
<ide> module.exports = {
<ide> }
<ide> ```
<ide>
<add>Note: rewrites in `beforeFiles` do not check the filesystem/dynamic routes immediately after matching a source, they continue until all `beforeFiles` have been checked.
<add>
<ide> ## Rewrite parameters
<ide>
<ide> When using parameters in a rewrite the parameters will be passed in the query by default when none of the parameters are used in the `destination`. | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.