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 |
|---|---|---|---|---|---|
Javascript | Javascript | add strict equalities in src/core/murmurhash3.js | a154ca2dd343a548a567de4d3f1f609836faf70b | <ide><path>src/core/murmurhash3.js
<ide> var MurmurHash3_64 = (function MurmurHash3_64Closure (seed) {
<ide> update: function MurmurHash3_64_update(input) {
<ide> var useUint32ArrayView = alwaysUseUint32ArrayView;
<ide> var i;
<del> if (typeof input == 'string') {
<add> if (typeof input === 'string') {
<ide> var data = new Uint8Array(input.length * 2);
<ide> var length = 0;
<ide> for (i = 0; i < input.length; i++) { | 1 |
Javascript | Javascript | remove xxx and output debuglog | ad63d350d4a4fe51547bf36a529631a746f3b1f8 | <ide><path>lib/readline.js
<ide> const kHistorySize = 30;
<ide>
<ide> const util = require('util');
<add>const debug = util.debuglog('readline');
<ide> const internalUtil = require('internal/util');
<ide> const inherits = util.inherits;
<ide> const Buffer = require('buffer').Buffer;
<ide> Interface.prototype._tabComplete = function() {
<ide> self.resume();
<ide>
<ide> if (err) {
<del> // XXX Log it somewhere?
<add> debug('tab completion error %j', err);
<ide> return;
<ide> }
<ide> | 1 |
Javascript | Javascript | fix an instance of array#indexof in ie8 | e4a867039190a4b59bee434f8776731ae7dbc484 | <ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> var set = Ember.set, get = Ember.get,
<ide> finishPartial = Mixin.finishPartial,
<ide> reopen = Mixin.prototype.reopen,
<ide> classToString = Mixin.prototype.toString,
<del> MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER;
<add> MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER,
<add> indexOf = Ember.EnumerableUtils.indexOf;
<ide>
<ide> var undefinedDescriptor = {
<ide> configurable: true,
<ide> function makeCtor() {
<ide> Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
<ide> Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('_super') !== -1));
<ide>
<del> if (concatenatedProperties && concatenatedProperties.indexOf(keyName) >= 0) {
<add> if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
<ide> var baseValue = this[keyName];
<ide>
<ide> if (baseValue) { | 1 |
PHP | PHP | add tests for custom integer return values | 5e7433288590abf5cfaad9bdc5a5ae23279facbf | <ide><path>tests/TestCase/Console/ShellDispatcherTest.php
<ide> public function testDispatchShellWithMain()
<ide> $this->assertEquals([], $dispatcher->args);
<ide> }
<ide>
<add> /**
<add> * Verifies correct dispatch of Shell subclasses with integer exit codes.
<add> *
<add> * @return void
<add> */
<add> public function testDispatchShellWithIntegerSuccessCode()
<add> {
<add> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<add> ->setMethods(['findShell'])
<add> ->getMock();
<add> $Shell = $this->getMockBuilder('Cake\Console\Shell')->getMock();
<add>
<add> $Shell->expects($this->once())->method('initialize');
<add> $Shell->expects($this->once())->method('runCommand')
<add> ->with(['initdb'])
<add> ->will($this->returnValue(Shell::CODE_SUCCESS));
<add>
<add> $dispatcher->expects($this->any())
<add> ->method('findShell')
<add> ->with('mock_without_main')
<add> ->will($this->returnValue($Shell));
<add>
<add> $dispatcher->args = ['mock_without_main', 'initdb'];
<add> $result = $dispatcher->dispatch();
<add> $this->assertEquals(Shell::CODE_SUCCESS, $result);
<add> }
<add>
<add> /**
<add> * Verifies correct dispatch of Shell subclasses with custom integer exit codes.
<add> *
<add> * @return void
<add> */
<add> public function testDispatchShellWithCustomIntegerCodes()
<add> {
<add> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<add> ->setMethods(['findShell'])
<add> ->getMock();
<add> $Shell = $this->getMockBuilder('Cake\Console\Shell')->getMock();
<add>
<add> $Shell->expects($this->once())->method('initialize');
<add> $Shell->expects($this->once())->method('runCommand')
<add> ->with(['initdb'])
<add> ->will($this->returnValue(3));
<add>
<add> $dispatcher->expects($this->any())
<add> ->method('findShell')
<add> ->with('mock_without_main')
<add> ->will($this->returnValue($Shell));
<add>
<add> $dispatcher->args = ['mock_without_main', 'initdb'];
<add> $result = $dispatcher->dispatch();
<add> $this->assertEquals(3, $result);
<add> }
<add>
<ide> /**
<ide> * Verify correct dispatch of Shell subclasses without a main method
<ide> * | 1 |
Text | Text | add digital first media to companies using | f025efc26aae32128195ab0aea4b39e3e2ba0d7f | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [Clover Health](https://www.cloverhealth.com) [[@gwax](https://github.com/gwax) & [@vansivallab](https://github.com/vansivallab)]
<ide> 1. Chartboost [[@cgelman](https://github.com/cgelman) & [@dclubb](https://github.com/dclubb)]
<ide> 1. [Cotap](https://github.com/cotap/) [[@maraca](https://github.com/maraca) & [@richardchew](https://github.com/richardchew)]
<add>1. [Digital First Media](https://www.digitalfirstmedia.com/) [[@duffn](https://github.com/duffn)]
<ide> 1. [Easy Taxi](http://www.easytaxi.com/) [[@caique-lima](https://github.com/caique-lima) & [@WesleyBatista](https://github.com/WesleyBatista)]
<ide> 1. [FreshBooks](https://github.com/freshbooks) [[@DinoCow](https://github.com/DinoCow)]
<ide> 1. [Gentner Lab](http://github.com/gentnerlab) [[@neuromusic](https://github.com/neuromusic)] | 1 |
Javascript | Javascript | remove usage of array#fill | 6f62abb58ae46d9c88525635f1790487285666e6 | <ide><path>packages/react-reconciler/src/ReactFiberLane.js
<ide> export function higherLanePriority(
<ide> }
<ide>
<ide> export function createLaneMap<T>(initial: T): LaneMap<T> {
<del> return new Array(TotalLanes).fill(initial);
<add> // Intentionally pushing one by one.
<add> // https://v8.dev/blog/elements-kinds#avoid-creating-holes
<add> const laneMap = [];
<add> for (let i = 0; i < TotalLanes; i++) {
<add> laneMap.push(initial);
<add> }
<add> return laneMap;
<ide> }
<ide>
<ide> export function markRootUpdated( | 1 |
Javascript | Javascript | remove unused inject() calls | 349742b3f0ffb4ff771bcd8a8b0ae2abfe00c1e9 | <ide><path>test/ng/httpSpec.js
<ide> describe('$http', function() {
<ide> describe('the instance', function() {
<ide> var $httpBackend, $http, $rootScope;
<ide>
<del> beforeEach(inject(['$rootScope', function($rs) {
<del> $rootScope = $rs;
<del>
<del> spyOn($rootScope, '$apply').andCallThrough();
<del> }]));
<del>
<del> beforeEach(inject(['$httpBackend', '$http', function($hb, $h) {
<add> beforeEach(inject(['$httpBackend', '$http', '$rootScope', function($hb, $h, $rs) {
<ide> $httpBackend = $hb;
<ide> $http = $h;
<add> $rootScope = $rs;
<add> spyOn($rootScope, '$apply').andCallThrough();
<ide> }]));
<ide>
<del> it('should throw error if the request configuration is not an object', inject(function($httpBackend, $http) {
<add> it('should throw error if the request configuration is not an object', function() {
<ide> expect(function() {
<ide> $http('/url');
<ide> }).toThrowMinErr('$http','badreq', 'Http request configuration must be an object. Received: /url');
<del> }));
<add> });
<ide>
<del> it('should send GET requests if no method specified', inject(function($httpBackend, $http) {
<add> it('should send GET requests if no method specified', function() {
<ide> $httpBackend.expect('GET', '/url').respond('');
<ide> $http({url: '/url'});
<del> }));
<add> });
<ide>
<del> it('should do basic request', inject(function($httpBackend, $http) {
<add> it('should do basic request', function() {
<ide> $httpBackend.expect('GET', '/url').respond('');
<ide> $http({url: '/url', method: 'GET'});
<del> }));
<add> });
<ide>
<ide>
<del> it('should pass data if specified', inject(function($httpBackend, $http) {
<add> it('should pass data if specified', function() {
<ide> $httpBackend.expect('POST', '/url', 'some-data').respond('');
<ide> $http({url: '/url', method: 'POST', data: 'some-data'});
<del> }));
<add> });
<ide>
<ide>
<ide> describe('params', function() {
<del> it('should do basic request with params and encode', inject(function($httpBackend, $http) {
<add> it('should do basic request with params and encode', function() {
<ide> $httpBackend.expect('GET', '/url?a%3D=%3F%26&b=2').respond('');
<ide> $http({url: '/url', params: {'a=':'?&', b:2}, method: 'GET'});
<del> }));
<add> });
<ide>
<ide>
<del> it('should merge params if url contains some already', inject(function($httpBackend, $http) {
<add> it('should merge params if url contains some already', function() {
<ide> $httpBackend.expect('GET', '/url?c=3&a=1&b=2').respond('');
<ide> $http({url: '/url?c=3', params: {a:1, b:2}, method: 'GET'});
<del> }));
<add> });
<ide>
<ide>
<del> it('should jsonify objects in params map', inject(function($httpBackend, $http) {
<add> it('should jsonify objects in params map', function() {
<ide> $httpBackend.expect('GET', '/url?a=1&b=%7B%22c%22:3%7D').respond('');
<ide> $http({url: '/url', params: {a:1, b:{c:3}}, method: 'GET'});
<del> }));
<add> });
<ide>
<ide>
<del> it('should expand arrays in params map', inject(function($httpBackend, $http) {
<add> it('should expand arrays in params map', function() {
<ide> $httpBackend.expect('GET', '/url?a=1&a=2&a=3').respond('');
<ide> $http({url: '/url', params: {a: [1,2,3]}, method: 'GET'});
<del> }));
<add> });
<ide>
<ide>
<ide> it('should not encode @ in url params', function() {
<ide> describe('$http', function() {
<ide> $httpBackend.flush();
<ide> }));
<ide>
<del> it('should send execute result if header value is function', inject(function() {
<add> it('should send execute result if header value is function', function() {
<ide> var headerConfig = {'Accept': function() { return 'Rewritten'; }};
<ide>
<ide> function checkHeaders(headers) {
<ide> describe('$http', function() {
<ide> $http({url: '/url', method: 'DELETE', headers: headerConfig});
<ide>
<ide> $httpBackend.flush();
<del> }));
<add> });
<ide>
<ide> it('should check the cache before checking the XSRF cookie', inject(function($browser, $cacheFactory) {
<ide> var testCache = $cacheFactory('testCache'), | 1 |
PHP | PHP | convert spaces to tabs | 25ad84b1f3a1dc22c91b8060e73127e2d376e6cd | <ide><path>app/config/database.php
<ide> 'password' => '',
<ide> 'charset' => 'utf8',
<ide> 'prefix' => '',
<del> 'schema' => 'public',
<add> 'schema' => 'public',
<ide> ),
<ide>
<ide> 'sqlsrv' => array(
<ide>
<ide> ),
<ide>
<del>);
<ide>\ No newline at end of file
<add>); | 1 |
PHP | PHP | move defaultsettings to behavior | 3663cc9d688714ba643b10cc341860f47d6edc67 | <ide><path>Cake/Model/Behavior/TimestampBehavior.php
<ide> class TimestampBehavior extends Behavior {
<ide> */
<ide> protected $_ts;
<ide>
<del>/**
<del> * Constructor
<del> *
<del> * Merge settings with the default and store in the settings property
<del> *
<del> * @param Table $table The table this behavior is attached to.
<del> * @param array $settings The settings for this behavior.
<del> */
<del> public function __construct(Table $table, array $settings = []) {
<del> $this->_settings = $settings + $this->_defaultSettings;
<del> }
<del>
<ide> /**
<ide> * handleEvent
<ide> *
<ide><path>Cake/ORM/Behavior.php
<ide> class Behavior implements EventListener {
<ide> */
<ide> protected static $_reflectionMethods = [];
<ide>
<add>/**
<add> * Default settings
<add> *
<add> * These are merged with user-provided settings when the behavior is used.
<add> *
<add> * @var array
<add> */
<add> protected $_defaultSettings = [];
<add>
<ide> /**
<ide> * Contains configuration settings.
<ide> *
<ide> class Behavior implements EventListener {
<ide> /**
<ide> * Constructor
<ide> *
<add> * Merge settings with the default and store in the settings property
<add> *
<ide> * Does not retain a reference to the Table object. If you need this
<ide> * you should override the constructor.
<ide> *
<add> *
<ide> * @param Table $table The table this behavior is attached to.
<ide> * @param array $settings The settings for this behavior.
<ide> */
<ide> public function __construct(Table $table, array $settings = []) {
<del> $this->_settings = $settings;
<add> $this->_settings = $settings + $this->_defaultSettings;
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | change var to let/const in internal/querystring.js | c1f0e80989cc653e5177827cf1f40785d32dc204 | <ide><path>lib/internal/querystring.js
<ide> const { ERR_INVALID_URI } = require('internal/errors').codes;
<ide>
<ide> const hexTable = new Array(256);
<del>for (var i = 0; i < 256; ++i)
<add>for (let i = 0; i < 256; ++i)
<ide> hexTable[i] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase();
<ide>
<ide> const isHexTable = [
<ide> function encodeStr(str, noEscapeTable, hexTable) {
<ide> if (len === 0)
<ide> return '';
<ide>
<del> var out = '';
<del> var lastPos = 0;
<add> let out = '';
<add> let lastPos = 0;
<ide>
<del> for (var i = 0; i < len; i++) {
<del> var c = str.charCodeAt(i);
<add> for (let i = 0; i < len; i++) {
<add> let c = str.charCodeAt(i);
<ide>
<ide> // ASCII
<ide> if (c < 0x80) {
<ide> function encodeStr(str, noEscapeTable, hexTable) {
<ide> if (i >= len)
<ide> throw new ERR_INVALID_URI();
<ide>
<del> var c2 = str.charCodeAt(i) & 0x3FF;
<add> const c2 = str.charCodeAt(i) & 0x3FF;
<ide>
<ide> lastPos = i + 1;
<ide> c = 0x10000 + (((c & 0x3FF) << 10) | c2); | 1 |
PHP | PHP | make validatearray parameter optional | ceaf3918c9076b9cee48798da15cc8f38261c2eb | <ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php
<ide> public function validateAlphaNum($attribute, $value)
<ide> * @param array $parameters
<ide> * @return bool
<ide> */
<del> public function validateArray($attribute, $value, $parameters)
<add> public function validateArray($attribute, $value, $parameters = [])
<ide> {
<ide> if (! is_array($value)) {
<ide> return false; | 1 |
Javascript | Javascript | fix links in docs | e21a868524758f1fd53ea4e6f6344910874dc0eb | <ide><path>src/Scope.js
<ide> function errorHandlerFor(element, error) {
<ide> * - Scopes can be attached (bound) to the HTML DOM tree (the view).
<ide> * - A scope {@link angular.scope.$become becomes} `this` for a controller.
<ide> * - A scope's {@link angular.scope.$eval $eval} is used to update its view.
<del> * - Scopes can {@link angular.scope.$watch watch} properties and fire events.
<add> * - Scopes can {@link angular.scope.$watch $watch} properties and fire events.
<ide> *
<ide> * # Basic Operations
<del> * Scopes can be created by calling {@link angular.scope() angular.scope()} or by compiling HTML.
<add> * Scopes can be created by calling {@link angular.scope angular.scope()} or by compiling HTML.
<ide> *
<ide> * {@link angular.widget Widgets} and data bindings register listeners on the current scope to be
<ide> * notified of changes to the scope state. When notified, these listeners push the updated state
<ide> function errorHandlerFor(element, error) {
<ide> * This example demonstrates scope inheritance and property overriding.
<ide> *
<ide> * In this example, the root scope encompasses the whole HTML DOM tree. This scope has `salutation`,
<del> * `name`, and `names` properties. The {@link angular.widget@ng:repeat ng:repeat} creates a child
<add> * `name`, and `names` properties. The {@link angular.widget.@ng:repeat ng:repeat} creates a child
<ide> * scope, one for each element in the names array. The repeater also assigns $index and name into
<ide> * the child scope.
<ide> *
<ide> function createScope(parent, providers, instanceCache) {
<ide> *
<ide> * @description
<ide> * Evaluates the expression in the context of the current scope just like
<del> * {@link angular.scope.$eval()} with expression parameter, but also wraps it in a try/catch
<add> * {@link angular.scope.$eval} with expression parameter, but also wraps it in a try/catch
<ide> * block.
<ide> *
<ide> * If an exception is thrown then `exceptionHandler` is used to handle the exception.
<ide><path>src/service/defer.js
<ide> * @requires $updateView
<ide> *
<ide> * @description
<del> * Delegates to {@link angular.service.$browser.defer $browser.defer}, but wraps the `fn` function
<add> * Delegates to {@link angular.service.$browser $browser.defer}, but wraps the `fn` function
<ide> * into a try/catch block and delegates any exceptions to
<del> * {@link angular.services.$exceptionHandler $exceptionHandler} service.
<add> * {@link angular.service.$exceptionHandler $exceptionHandler} service.
<ide> *
<ide> * In tests you can use `$browser.defer.flush()` to flush the queue of deferred functions.
<ide> *
<ide><path>src/service/updateView.js
<ide> * without angular knowledge and you may need to call '$updateView()' directly.
<ide> *
<ide> * NOTE: if you wish to update the view immediately (without delay), you can do so by calling
<del> * {@link scope.$eval} at any time from your code:
<add> * {@link angular.scope.$eval} at any time from your code:
<ide> * <pre>scope.$root.$eval()</pre>
<ide> *
<ide> * In unit-test mode the update is instantaneous and synchronous to simplify writing tests.
<ide><path>src/widgets.js
<ide> angularWidget("@ng:non-bindable", noop);
<ide> * Every time the current route changes, the included view changes with it according to the
<ide> * configuration of the `$route` service.
<ide> *
<del> * This widget provides functionality similar to {@link angular.service.ng:include ng:include} when
<add> * This widget provides functionality similar to {@link angular.widget.ng:include ng:include} when
<ide> * used like this:
<ide> *
<ide> * <ng:include src="$route.current.template" scope="$route.current.scope"></ng:include> | 4 |
Ruby | Ruby | show either changelog or release noted link | a0e663d833f9a320cd50ab63d6b904b4fdd5f51b | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def update_report
<ide> puts "Updated Homebrew from #{shorten_revision(initial_revision)} to #{shorten_revision(current_revision)}."
<ide> updated = true
<ide>
<del> tag = Utils.safe_popen_read("git", "tag", "--points-at", "HEAD")
<del> new_repository_version = tag.chomp if tag.present?
<add> new_repository_version = Utils.safe_popen_read("git", "tag", "--points-at", "HEAD").chomp.presence
<ide> end
<ide>
<ide> Homebrew.failed = true if ENV["HOMEBREW_UPDATE_FAILED"]
<ide> def update_report
<ide> return if new_repository_version.blank?
<ide>
<ide> ohai "Homebrew was updated to version #{new_repository_version}"
<del> puts <<~EOS
<del> The changelog can be found at:
<del> #{Formatter.url("https://github.com/Homebrew/brew/releases/tag/#{new_repository_version}")}
<del> EOS
<del>
<del> return unless new_repository_version.split(".").last == "0"
<del>
<del> puts <<~EOS
<del> More detailed release notes are available on the Homebrew Blog:
<del> #{Formatter.url("https://brew.sh/blog/")}
<del> EOS
<add> if new_repository_version.split(".").last == "0"
<add> puts <<~EOS
<add> More detailed release notes are available on the Homebrew Blog:
<add> #{Formatter.url("https://brew.sh/blog/")}
<add> EOS
<add> else
<add> puts <<~EOS
<add> The changelog can be found at:
<add> #{Formatter.url("https://github.com/Homebrew/brew/releases/tag/#{new_repository_version}")}
<add> EOS
<add> end
<ide> end
<ide>
<ide> def shorten_revision(revision) | 1 |
Javascript | Javascript | show current line, fix for | 028e652a73319e9c31fd47ef02e10f592b899333 | <ide><path>lib/_debugger.js
<ide> Interface.prototype.list = function(delta) {
<ide> line = lines[i];
<ide> }
<ide>
<del> self.print(leftPad(lineno, breakpoint && '*') + ' ' + line);
<add> var prefixChar = ' ';
<add> if (current) {
<add> prefixChar = '>';
<add> } else if (breakpoint) {
<add> prefixChar = '*';
<add> }
<add>
<add> self.print(leftPad(lineno, prefixChar) + ' ' + line);
<ide> }
<ide> self.resume();
<ide> }); | 1 |
PHP | PHP | remove extra whitespace from | b712fee13730790f266bb46fb06612311c53ed63 | <ide><path>tests/TestCase/Utility/SecurityTest.php
<ide> public function testDecryptInvalidData()
<ide> public function testEngineEquivalence()
<ide> {
<ide> $this->skipIf(!function_exists('mcrypt_encrypt') || version_compare(PHP_VERSION, '7.1', '>='), 'This needs mcrypt extension to be loaded.');
<del>
<add>
<ide> $restore = Security::engine();
<ide> $txt = "Obi-wan you're our only hope";
<ide> $key = 'This is my secret key phrase it is quite long.'; | 1 |
Ruby | Ruby | remove stray checks for rspec in the testing setup | 4954379283099231965fbc3fe00c39e0ef91c4b0 | <ide><path>activesupport/lib/active_support/testing/declarative.rb
<ide> def self.name
<ide> end
<ide> end
<ide>
<del> if defined?(Spec)
<del> class << self
<del> alias_method :test, :it
<del> end
<del> end
<del>
<ide> end
<ide> end
<ide>
<ide><path>activesupport/lib/active_support/testing/setup_and_teardown.rb
<ide> def self.included(base)
<ide>
<ide> if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions
<ide> include ForMiniTest
<del> elsif defined? Spec
<del> include ForRspec
<ide> else
<ide> include ForClassicTestUnit
<ide> end | 2 |
Java | Java | collapse catch blocks in template | a379879adf99800d22da8bc10c3a22f06cb02e20 | <ide><path>template/android/app/src/main/java/com/helloworld/MainApplication.java
<ide> private static void initializeFlipper(
<ide> aClass
<ide> .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
<ide> .invoke(null, context, reactInstanceManager);
<del> } catch (ClassNotFoundException e) {
<del> e.printStackTrace();
<del> } catch (NoSuchMethodException e) {
<del> e.printStackTrace();
<del> } catch (IllegalAccessException e) {
<del> e.printStackTrace();
<del> } catch (InvocationTargetException e) {
<add> } catch (ClassNotFoundException
<add> | InvocationTargetException
<add> | IllegalAccessException
<add> | NoSuchMethodException e) {
<ide> e.printStackTrace();
<ide> }
<ide> } | 1 |
Javascript | Javascript | fix lgtm errors | 68080d3af0bd208273ad8a6d3c75e0097e195c3c | <ide><path>examples/js/loaders/AWDLoader.js
<ide> THREE.AWDLoader = ( function () {
<ide>
<ide> this.id = 0;
<ide> this.data = null;
<add> this.namespace = 0;
<add> this.flags = 0;
<ide>
<ide> }
<ide>
<ide> THREE.AWDLoader = ( function () {
<ide> parseNextBlock: function () {
<ide>
<ide> var assetData,
<del> ns, type, len, block,
<add> block,
<ide> blockId = this.readU32(),
<ide> ns = this.readU8(),
<ide> type = this.readU8(),
<ide> THREE.AWDLoader = ( function () {
<ide> this._blocks[ blockId ] = block = new Block();
<ide> block.data = assetData;
<ide> block.id = blockId;
<add> block.namespace = ns;
<add> block.flags = flags;
<ide>
<ide>
<ide> },
<ide> THREE.AWDLoader = ( function () {
<ide>
<ide> while ( methods_parsed < num_methods ) {
<ide>
<del> var method_type = this.readU16();
<add> // read method_type before
<add> this.readU16();
<ide> this.parseProperties( null );
<ide> this.parseUserAttributes();
<ide>
<ide> THREE.AWDLoader = ( function () {
<ide> var url = this.readUTFBytes( data_len );
<ide> console.log( url );
<ide>
<del> asset = this.loadTexture( url );
<add> asset = this.loadTexture(url);
<add> asset.userData = {};
<add> asset.userData.name = name;
<ide>
<ide> } else {
<ide> // embed texture not supported
<ide> THREE.AWDLoader = ( function () {
<ide> parseSkeleton: function () {
<ide>
<ide> // Array<Bone>
<del> var name = this.readUTF(),
<del> num_joints = this.readU16(),
<add> //
<add> this.readUTF();
<add> var num_joints = this.readU16(),
<ide> skeleton = [],
<ide> joints_parsed = 0;
<ide> | 1 |
Javascript | Javascript | show module name during multidir error | 351fe4b79c50a45a11af2fcd2aa7b6fd3b70058d | <ide><path>src/loader.js
<ide> function setupModuleLoader(window) {
<ide> * @description
<ide> * See {@link auto.$provide#provider $provide.provider()}.
<ide> */
<del> provider: invokeLater('$provide', 'provider'),
<add> provider: invokeLaterAndSetModuleName('$provide', 'provider'),
<ide>
<ide> /**
<ide> * @ngdoc method
<ide> function setupModuleLoader(window) {
<ide> * @description
<ide> * See {@link auto.$provide#factory $provide.factory()}.
<ide> */
<del> factory: invokeLater('$provide', 'factory'),
<add> factory: invokeLaterAndSetModuleName('$provide', 'factory'),
<ide>
<ide> /**
<ide> * @ngdoc method
<ide> function setupModuleLoader(window) {
<ide> * @description
<ide> * See {@link auto.$provide#service $provide.service()}.
<ide> */
<del> service: invokeLater('$provide', 'service'),
<add> service: invokeLaterAndSetModuleName('$provide', 'service'),
<ide>
<ide> /**
<ide> * @ngdoc method
<ide> function setupModuleLoader(window) {
<ide> * @description
<ide> * See {@link auto.$provide#decorator $provide.decorator()}.
<ide> */
<del> decorator: invokeLater('$provide', 'decorator'),
<add> decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
<ide>
<ide> /**
<ide> * @ngdoc method
<ide> function setupModuleLoader(window) {
<ide> * See {@link ng.$animateProvider#register $animateProvider.register()} and
<ide> * {@link ngAnimate ngAnimate module} for more information.
<ide> */
<del> animation: invokeLater('$animateProvider', 'register'),
<add> animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
<ide>
<ide> /**
<ide> * @ngdoc method
<ide> function setupModuleLoader(window) {
<ide> * (`myapp_subsection_filterx`).
<ide> * </div>
<ide> */
<del> filter: invokeLater('$filterProvider', 'register'),
<add> filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
<ide>
<ide> /**
<ide> * @ngdoc method
<ide> function setupModuleLoader(window) {
<ide> * @description
<ide> * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
<ide> */
<del> controller: invokeLater('$controllerProvider', 'register'),
<add> controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
<ide>
<ide> /**
<ide> * @ngdoc method
<ide> function setupModuleLoader(window) {
<ide> * @description
<ide> * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
<ide> */
<del> directive: invokeLater('$compileProvider', 'directive'),
<add> directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
<ide>
<ide> /**
<ide> * @ngdoc method
<ide> function setupModuleLoader(window) {
<ide> return moduleInstance;
<ide> };
<ide> }
<add>
<add> /**
<add> * @param {string} provider
<add> * @param {string} method
<add> * @returns {angular.Module}
<add> */
<add> function invokeLaterAndSetModuleName(provider, method) {
<add> return function(recipeName, factoryFunction) {
<add> if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
<add> invokeQueue.push([provider, method, arguments]);
<add> return moduleInstance;
<add> };
<add> }
<ide> });
<ide> };
<ide> });
<ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> if (isObject(bindings.isolateScope)) {
<ide> directive.$$isolateBindings = bindings.isolateScope;
<ide> }
<add> directive.$$moduleName = directiveFactory.$$moduleName;
<ide> directives.push(directive);
<ide> } catch (e) {
<ide> $exceptionHandler(e);
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> return a.index - b.index;
<ide> }
<ide>
<del>
<ide> function assertNoDuplicate(what, previousDirective, directive, element) {
<add>
<add> function wrapModuleNameIfDefined(moduleName) {
<add> return moduleName ?
<add> (' (module: ' + moduleName + ')') :
<add> '';
<add> }
<add>
<ide> if (previousDirective) {
<del> throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
<del> previousDirective.name, directive.name, what, startingTag(element));
<add> throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
<add> previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
<add> directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
<ide> }
<ide> }
<ide>
<ide><path>test/ng/compileSpec.js
<ide> describe('$compile', function() {
<ide> );
<ide> });
<ide> });
<add>
<add> describe('multidir isolated scope error messages', function() {
<add> angular.module('fakeIsoledScopeModule', [])
<add> .directive('fakeScope', function(log) {
<add> return {
<add> scope: true,
<add> restrict: 'CA',
<add> compile: function() {
<add> return {pre: function(scope, element) {
<add> log(scope.$id);
<add> expect(element.data('$scope')).toBe(scope);
<add> }};
<add> }
<add> };
<add> })
<add> .directive('fakeIScope', function(log) {
<add> return {
<add> scope: {},
<add> restrict: 'CA',
<add> compile: function() {
<add> return function(scope, element) {
<add> iscope = scope;
<add> log(scope.$id);
<add> expect(element.data('$isolateScopeNoTemplate')).toBe(scope);
<add> };
<add> }
<add> };
<add> });
<add>
<add> beforeEach(module('fakeIsoledScopeModule', function() {
<add> directive('anonymModuleScopeDirective', function(log) {
<add> return {
<add> scope: true,
<add> restrict: 'CA',
<add> compile: function() {
<add> return {pre: function(scope, element) {
<add> log(scope.$id);
<add> expect(element.data('$scope')).toBe(scope);
<add> }};
<add> }
<add> };
<add> });
<add> }));
<add>
<add> it('should add module name to multidir isolated scope message if directive defined through module', inject(
<add> function($rootScope, $compile) {
<add> expect(function() {
<add> $compile('<div class="fake-scope; fake-i-scope"></div>');
<add> }).toThrowMinErr('$compile', 'multidir',
<add> 'Multiple directives [fakeIScope (module: fakeIsoledScopeModule), fakeScope (module: fakeIsoledScopeModule)] ' +
<add> 'asking for new/isolated scope on: <div class="fake-scope; fake-i-scope">');
<add> })
<add> );
<add>
<add> it('sholdn\'t add module name to multidir isolated scope message if directive is defined directly with $compileProvider', inject(
<add> function($rootScope, $compile) {
<add> expect(function() {
<add> $compile('<div class="anonym-module-scope-directive; fake-i-scope"></div>');
<add> }).toThrowMinErr('$compile', 'multidir',
<add> 'Multiple directives [anonymModuleScopeDirective, fakeIScope (module: fakeIsoledScopeModule)] ' +
<add> 'asking for new/isolated scope on: <div class="anonym-module-scope-directive; fake-i-scope">');
<add> })
<add> );
<add> });
<ide> });
<ide> });
<ide> }); | 3 |
PHP | PHP | add test for find('list') option as array | 9543b35e21bb5a0ac1af1ca0acc0e3fc3a2bbabd | <ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testFindListSelectedFields()
<ide> $query = $articles->find('list', ['groupField' => 'author_id']);
<ide> $expected = ['id', 'title', 'author_id'];
<ide> $this->assertSame($expected, $query->clause('select'));
<add>
<add> $query = $articles->find('list', ['valueField' => ['author_id', 'title']])
<add> ->order('id');
<add> $expected = ['id', 'author_id', 'title'];
<add> $this->assertSame($expected, $query->clause('select'));
<add>
<add> $expected = [
<add> 1 => '1;First Article',
<add> 2 => '3;Second Article',
<add> 3 => '1;Third Article',
<add> ];
<add> $this->assertSame($expected, $query->toArray());
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | add test for parentviewdidchange event | 854a460682b1c15ba28f7e3e7519952c70249754 | <ide><path>packages/ember-views/tests/views/container_view_test.js
<ide> test("should set the parentView property on views that are added to the child vi
<ide> });
<ide> });
<ide>
<add>test("should trigger parentViewDidChange when parentView is changed", function() {
<add> container = Ember.ContainerView.create();
<add>
<add> var secondContainer = Ember.ContainerView.create();
<add> var parentViewChanged = 0;
<add>
<add> var View = Ember.View.extend({
<add> parentViewDidChange: function() { parentViewChanged++; }
<add> });
<add>
<add> view = View.create();
<add>
<add> container.pushObject(view);
<add> container.removeChild(view);
<add> secondContainer.pushObject(view);
<add>
<add> equal(parentViewChanged, 3);
<add>
<add> Ember.run(function() {
<add> secondContainer.destroy();
<add> });
<add>});
<add>
<ide> test("views that are removed from a ContainerView should have their child views cleared", function() {
<ide> container = Ember.ContainerView.create();
<ide> view = Ember.View.createWithMixins({ | 1 |
Javascript | Javascript | remove unused forceaddtowindow | 96e6403573e1a1cdaeeb9984d3efd7707f39b27c | <ide><path>spec/atom-environment-spec.js
<ide> describe('AtomEnvironment', () => {
<ide>
<ide> it('does not attempt to restore the project state, instead adding the project paths', async () => {
<ide> const pathToOpen = path.join(__dirname, 'fixtures')
<del> await atom.openLocations([{ pathToOpen, exists: true, isDirectory: true, forceAddToWindow: true }])
<add> await atom.openLocations([{ pathToOpen, exists: true, isDirectory: true }])
<ide> expect(atom.attemptRestoreProjectStateForPaths).not.toHaveBeenCalled()
<ide> expect(atom.project.getPaths()).toEqual([__dirname, pathToOpen])
<ide> })
<ide><path>spec/main-process/atom-window.test.js
<ide> describe('AtomWindow', function () {
<ide> pathToOpen: 'file.txt',
<ide> initialLine: 1,
<ide> initialColumn: 2,
<del> mustBeDirectory: false,
<del> forceAddToWindow: false,
<add> isDirectory: false,
<ide> hasWaitSession: false
<ide> },
<ide> {
<ide> pathToOpen: '/directory',
<ide> initialLine: null,
<ide> initialColumn: null,
<del> mustBeDirectory: true,
<del> forceAddToWindow: false,
<add> isDirectory: true,
<ide> hasWaitSession: false
<ide> }
<ide> ]
<ide><path>src/main-process/atom-application.js
<ide> class AtomApplication extends EventEmitter {
<ide>
<ide> const locationsToOpen = await Promise.all(
<ide> pathsToOpen.map(pathToOpen => this.parsePathToOpen(pathToOpen, executedFrom, {
<del> forceAddToWindow: addToLastWindow,
<ide> hasWaitSession: pidToKillWhenClosed != null
<ide> }))
<ide> )
<ide> class AtomApplication extends EventEmitter {
<ide> initialColumn: null,
<ide> exists: true,
<ide> isDirectory: true,
<del> forceAddToWindow: addToLastWindow,
<ide> hasWaitSession: pidToKillWhenClosed != null
<ide> })
<ide> } | 3 |
PHP | PHP | implement remaining basic form interface | f8323cb477454a4ecaaa59b8fc4788630dde0f20 | <ide><path>src/Form/Form.php
<ide> public function errors() {
<ide> }
<ide>
<ide> public function execute($data) {
<add> if (!$this->isValid($data)) {
<add> return false;
<add> }
<add> return $this->_execute($data);
<add> }
<add>
<add> protected function _execute($data) {
<ide> }
<ide>
<ide> }
<ide><path>tests/TestCase/Form/FormTest.php
<ide> public function testIsValid() {
<ide> $this->assertCount(0, $form->errors());
<ide> }
<ide>
<add>/**
<add> * Test the errors methods.
<add> *
<add> * @return void
<add> */
<add> public function testErrors() {
<add> $form = new Form();
<add> $form->validator()
<add> ->add('email', 'format', [
<add> 'message' => 'Must be a valid email',
<add> 'rule' => 'email'
<add> ])
<add> ->add('body', 'length', [
<add> 'message' => 'Must be so long',
<add> 'rule' => ['minLength', 12],
<add> ]);
<add>
<add> $data = [
<add> 'email' => 'rong',
<add> 'body' => 'too short'
<add> ];
<add> $form->isValid($data);
<add> $errors = $form->errors();
<add> $this->assertCount(2, $errors);
<add> $this->assertEquals('Must be a valid email', $errors['email']['format']);
<add> $this->assertEquals('Must be so long', $errors['body']['length']);
<add> }
<add>
<add>/**
<add> * Test _execute is skipped on validation failure.
<add> *
<add> * @return void
<add> */
<ide> public function testExecuteInvalid() {
<add> $form = $this->getMock('Cake\Form\Form', ['_execute']);
<add> $form->validator()
<add> ->add('email', 'format', ['rule' => 'email']);
<add> $data = [
<add> 'email' => 'rong'
<add> ];
<add> $form->expects($this->never())
<add> ->method('_execute');
<add>
<add> $this->assertFalse($form->execute($data));
<ide> }
<ide>
<ide> public function testExecuteValid() {
<add> $form = $this->getMock('Cake\Form\Form', ['_execute']);
<add> $form->validator()
<add> ->add('email', 'format', ['rule' => 'email']);
<add> $data = [
<add> 'email' => 'test@example.com'
<add> ];
<add> $form->expects($this->once())
<add> ->method('_execute')
<add> ->with($data);
<add>
<add> $this->assertNull($form->execute($data));
<ide> }
<ide>
<ide> } | 2 |
Javascript | Javascript | add test for webpack | 77eaad8a171eb4e8511afd2a8f2b932b19c8d701 | <ide><path>test/configCases/async-library/0-create-library/a.js
<add>export const a = await Promise.resolve(42);
<ide><path>test/configCases/async-library/0-create-library/test.config.js
<add>exports.noTests = true;
<ide><path>test/configCases/async-library/0-create-library/webpack.config.js
<add>/** @type {import("../../../../types").Configuration} */
<add>module.exports = {
<add> entry: "./a.js",
<add> output: {
<add> filename: "lib.js",
<add> library: {
<add> type: "module"
<add> }
<add> },
<add> target: "node14",
<add> optimization: {
<add> minimize: true
<add> },
<add> experiments: {
<add> topLevelAwait: true,
<add> outputModule: true
<add> }
<add>};
<ide><path>test/configCases/async-library/1-use-library/index.js
<add>it("should get valid export from library", () => {
<add> return import("library").then(({ a }) => {
<add> expect(a).toBe(42);
<add> });
<add>});
<ide><path>test/configCases/async-library/1-use-library/webpack.config.js
<add>var path = require("path");
<add>
<add>/** @type {function(any, any): import("../../../../types").Configuration} */
<add>module.exports = (env, { testPath }) => ({
<add> target: "node14",
<add> output: {
<add> chunkLoading: "import"
<add> },
<add> resolve: {
<add> alias: {
<add> library: path.resolve(testPath, "../0-create-library/lib.js")
<add> }
<add> },
<add> experiments: {
<add> topLevelAwait: true,
<add> outputModule: true
<add> }
<add>}); | 5 |
Python | Python | add dataflow_default_options to templated_fields | 88402038cac10597a67d3dba6af66eb1bc14377d | <ide><path>airflow/providers/google/cloud/operators/dataflow.py
<ide> class DataflowTemplatedJobStartOperator(BaseOperator):
<ide> "gcp_conn_id",
<ide> "impersonation_chain",
<ide> "environment",
<add> "dataflow_default_options",
<ide> )
<ide> ui_color = "#0273d4"
<ide> operator_extra_links = (DataflowJobLink(),) | 1 |
Java | Java | add tck test for limit() | aff44822dd2d7b74091d2f351b1cb08ff87b30fd | <ide><path>src/test/java/io/reactivex/tck/LimitTckTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.tck;
<add>
<add>import org.reactivestreams.Publisher;
<add>import org.testng.annotations.Test;
<add>
<add>import io.reactivex.Flowable;
<add>
<add>@Test
<add>public class LimitTckTest extends BaseTck<Integer> {
<add>
<add> @Override
<add> public Publisher<Integer> createPublisher(long elements) {
<add> return
<add> Flowable.range(0, (int)elements * 2).limit(elements)
<add> ;
<add> }
<add>} | 1 |
Javascript | Javascript | use consistent indentation for ternaries | 85dacd63f0938cf135d49d393ceb9e85b4b1fac5 | <ide><path>lib/_stream_readable.js
<ide> function fromListPartial(n, list, hasStrings) {
<ide> ret = list.shift();
<ide> } else {
<ide> // result spans more than one buffer
<del> ret = (hasStrings ?
<del> copyFromBufferString(n, list) :
<del> copyFromBuffer(n, list));
<add> ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
<ide> }
<ide> return ret;
<ide> }
<ide><path>lib/cluster.js
<ide>
<ide> 'use strict';
<ide>
<del>module.exports = ('NODE_UNIQUE_ID' in process.env) ?
<del> require('internal/cluster/child') :
<del> require('internal/cluster/master');
<add>const childOrMaster = 'NODE_UNIQUE_ID' in process.env ? 'child' : 'master';
<add>module.exports = require(`internal/cluster/${childOrMaster}`);
<ide><path>lib/fs.js
<ide> function FSWatcher() {
<ide> if (status < 0) {
<ide> self._handle.close();
<ide> const error = !filename ?
<del> errnoException(status, 'Error watching file for changes:') :
<del> errnoException(status,
<del> `Error watching file ${filename} for changes:`);
<add> errnoException(status, 'Error watching file for changes:') :
<add> errnoException(status, `Error watching file ${filename} for changes:`);
<ide> error.filename = filename;
<ide> self.emit('error', error);
<ide> } else {
<ide><path>lib/internal/bootstrap_node.js
<ide> enumerable: true,
<ide> get: function() {
<ide> if (!console) {
<del> console = originalConsole === undefined ?
<del> NativeModule.require('console') :
<del> installInspectorConsole(originalConsole);
<add> console = (originalConsole === undefined) ?
<add> NativeModule.require('console') :
<add> installInspectorConsole(originalConsole);
<ide> }
<ide> return console;
<ide> }
<ide><path>lib/internal/child_process.js
<ide> function _validateStdio(stdio, sync) {
<ide> } else if (getHandleWrapType(stdio) || getHandleWrapType(stdio.handle) ||
<ide> getHandleWrapType(stdio._handle)) {
<ide> var handle = getHandleWrapType(stdio) ?
<del> stdio :
<del> getHandleWrapType(stdio.handle) ? stdio.handle : stdio._handle;
<add> stdio :
<add> getHandleWrapType(stdio.handle) ? stdio.handle : stdio._handle;
<ide>
<ide> acc.push({
<ide> type: 'wrap',
<ide><path>lib/url.js
<ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) {
<ide> this.query = Object.create(null);
<ide> }
<ide>
<del> var firstIdx = (questionIdx !== -1 &&
<del> (hashIdx === -1 || questionIdx < hashIdx) ?
<del> questionIdx :
<del> hashIdx);
<add> const useQuestionIdx =
<add> questionIdx !== -1 && (hashIdx === -1 || questionIdx < hashIdx);
<add> const firstIdx = useQuestionIdx ? questionIdx : hashIdx;
<ide> if (firstIdx === -1) {
<ide> if (rest.length > 0)
<ide> this.pathname = rest;
<ide> Url.prototype.format = function format() {
<ide> if (this.host) {
<ide> host = auth + this.host;
<ide> } else if (this.hostname) {
<del> host = auth + (this.hostname.indexOf(':') === -1 ?
<add> host = auth + (
<add> this.hostname.indexOf(':') === -1 ?
<ide> this.hostname :
<del> '[' + this.hostname + ']');
<add> '[' + this.hostname + ']'
<add> );
<ide> if (this.port) {
<ide> host += ':' + this.port;
<ide> } | 6 |
Text | Text | write readme for dilbert | 93e82ab4240a6f5b13a02303c1af385e24165938 | <ide><path>examples/distillation/README.md
<ide> # DilBERT
<ide>
<del>You'll have the details soon enough!
<ide>\ No newline at end of file
<add>This section contains examples showcasing how to use DilBERT and the original code to train DilBERT.
<add>
<add>## What is DilBERT?
<add>
<add>DilBERT stands for DistiLlation-BERT. DilBERT is a small, fast, cheap and light Transformer model: it has 40% less parameters than `bert-base-uncased`, runs 40% faster while preserving 96% on the language understanding capabilties (as shown on the GLUE benchmark). DilBERT is trained by distillation: a technique to compress a large model called the teacher into a smaller model called the student. By applying this compression technique, we obtain a smaller Transformer model that bears a lot of similarities with the original BERT model, while being lighter, smaller and faster. Thus, DilBERT can be an interesting solution to put large Transformer model into production.
<add>
<add>For more information on DilBERT, we refer to [our blog post](TODO(Link)).
<add>
<add>## How to use DilBERT?
<add>
<add>PyTorch-Transformers includes two pre-trained models:
<add>- `dilbert-base-uncased`: The language model pretrained by distillation under the supervision of `bert-base-uncased`. The model has 6 layers, 768 dimension and 12 heads, totalizing 66M parameters.
<add>- `dilbert-base-uncased-distilled-squad`: The `dilbert-base-uncased` finetune by distillation on SQuAD. It reaches a F1 score of 86.2 on the dev set, while `bert-base-uncased` reaches a 88.5 F1 score.
<add>
<add>Using DilBERT is really similar to using BERT. DilBERT uses the same tokenizer as BERT and more specifically `bert-base-uncased`. You should only use this tookenizer as the only pre-trained weights available for now are supervised by `bert-base-uncased`.
<add>
<add>```python
<add>tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
<add>model = DilBertModel.from_pretrained('dilbert-base-uncased')
<add>
<add>input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0)
<add>outputs = model(input_ids)
<add>last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
<add>```
<add>
<add>## How to train DilBERT?
<add>
<add>In the following, we will explain how you can train your own compressed model.
<add>
<add>### A. Preparing the data
<add>
<add>The weights we release are trained using a concatenation of Toronto Book Corpus and English Wikipedia (same training data as BERT).
<add>
<add>To avoid processing the data several time, we do it once and for all before the training. From now on, will suppose that you have a text file `dump.txt` which contains one sequence per line (a sequence being composed of one of several coherent sentences).
<add>
<add>First, we will binarize the data: we tokenize the data and associate each token to an id.
<add>
<add>```bash
<add>python scripts/binarized_data.py \
<add> --file_path data/dump.txt \
<add> --bert_tokenizer bert-base-uncased \
<add> --dump_file data/binarized_text
<add>```
<add>
<add>In the masked language modeling loss, we follow [XLM](https://github.com/facebookresearch/XLM) and smooth the probability of masking with a factor that put more emphasis on rare words. Thus we count the occurences of each tokens in the data:
<add>
<add>```bash
<add>python scripts/token_counts.py \
<add> --data_file data/binarized_text.bert-base-uncased.pickle \
<add> --token_counts_dump data/token_counts.bert-base-uncased.pickle
<add>```
<add>
<add>### B. Training
<add>
<add>Launching a distillation is really simple once you have setup the data:
<add>
<add>```bash
<add>python train.py \
<add> --dump_path serialization_dir/my_first_training \
<add> --data_file data/binarized_text.bert-base-uncased.pickle \
<add> --token_counts data/token_counts.bert-base-uncased.pickle \
<add> --force # It overwrites the `dump_path` if it already exists.
<add>```
<add>
<add>By default, this will launch a training on a single GPU (even if more are available on the cluster). Other parameters are available in the command line, please refer to `train.py`.
<add>
<add>We also highly encourage using distributed training. Here's an example that launchs a distributed traininng on a single node with 4 GPUs:
<add>```bash
<add>export NODE_RANK=0
<add>export N_NODES=1
<add>
<add>export N_GPU_NODE=4
<add>export WORLD_SIZE=4
<add>export MASTER_PORT=<AN_OPEN_PORT>
<add>export MASTER_ADDR=<I.P.>
<add>
<add>pkill -f 'python -u train.py'
<add>
<add>python -m torch.distributed.launch \
<add> --nproc_per_node=$N_GPU_NODE \
<add> --nnodes=$N_NODES \
<add> --node_rank $NODE_RANK \
<add> --master_addr $MASTER_ADDR \
<add> --master_port $MASTER_PORT \
<add> train.py \
<add> --force \
<add> --n_gpu $WORLD_SIZE \
<add> --data_file data/dump_concat_wiki_toronto_bk.bert-base-uncased.pickle \
<add> --token_counts data/token_counts_concat_wiki_toronto_bk.bert-base-uncased.pickle \
<add> --dump_path serialization_dir/with_transform/last_word
<add>```
<add>
<add>**Tips** Start the distillation from some sort of structure initialization is crucial to reach a good final performance. In our experiments, we use initialization from some of the layers of the teacher itself! Please refer to `scripts/extract_for_distil.py` to create a valid initialization checkpoint and add `from_pretrained_weights` and `from_pretrained_config` when launching your distillation!
<add>
<add>Happy distillation! | 1 |
Python | Python | fix reuters example | eb7cf7376b6c81f5d1792441f772de2771563c61 | <ide><path>examples/reuters_mlp.py
<ide>
<ide> model.fit(X_train, Y_train, nb_epoch=4, batch_size=batch_size, verbose=1, show_accuracy=True, validation_split=0.1)
<ide> score = model.evaluate(X_test, Y_test, batch_size=batch_size, verbose=1, show_accuracy=True)
<del>print('Test score:', score)
<del>
<del>classes = model.predict_classes(X_test, batch_size=batch_size, verbose=0)
<del>acc = np_utils.accuracy(classes, y_test)
<del>print('Test accuracy:', acc)
<add>print('Test score:', score[0])
<add>print('Test accuracy:', score[1]) | 1 |
Python | Python | generalize dense to nd tensors | 18e5b75f67ed640ff207ae52b425e9e3c0c293be | <ide><path>keras/layers/core.py
<ide> def _fix_unknown_dimension(self, input_shape, output_shape):
<ide> '''Find and replace a single missing dimension in an output shape
<ide> given an input shape.
<ide>
<del> A near direct port of the internal Numpy function _fix_unknown_dimension
<del> in numpy/core/src/multiarray/shape.c
<add> A near direct port of the internal Numpy function
<add> _fix_unknown_dimension in numpy/core/src/multiarray/shape.c
<ide>
<ide> # Arguments
<ide> input_shape: shape of array being reshaped
<ide> def _fix_unknown_dimension(self, input_shape, output_shape):
<ide> return tuple(output_shape)
<ide>
<ide> def get_output_shape_for(self, input_shape):
<del> return (input_shape[0],) + self._fix_unknown_dimension(input_shape[1:], self.target_shape)
<add> return (input_shape[0],) + self._fix_unknown_dimension(input_shape[1:],
<add> self.target_shape)
<ide>
<ide> def call(self, x, mask=None):
<ide> # In case the target shape is not fully defined,
<ide> class Flatten(Layer):
<ide>
<ide> ```python
<ide> model = Sequential()
<del> model.add(Convolution2D(64, 3, 3, border_mode='same', input_shape=(3, 32, 32)))
<add> model.add(Convolution2D(64, 3, 3,
<add> border_mode='same',
<add> input_shape=(3, 32, 32)))
<ide> # now: model.output_shape == (None, 64, 32, 32)
<ide>
<ide> model.add(Flatten())
<ide> def antirectifier_output_shape(input_shape):
<ide> shape[-1] *= 2
<ide> return tuple(shape)
<ide>
<del> model.add(Lambda(antirectifier, output_shape=antirectifier_output_shape))
<add> model.add(Lambda(antirectifier,
<add> output_shape=antirectifier_output_shape))
<ide> ```
<ide>
<ide> # Arguments
<ide> def __init__(self, function, output_shape=None, arguments={}, **kwargs):
<ide>
<ide> def get_output_shape_for(self, input_shape):
<ide> if self._output_shape is None:
<del> # if TensorFlow, we can infer the output shape directly:
<add> # With TensorFlow, we can infer the output shape directly:
<ide> if K.backend() == 'tensorflow':
<ide> if isinstance(input_shape, list):
<ide> xs = [K.placeholder(shape=shape) for shape in input_shape]
<ide> def get_output_shape_for(self, input_shape):
<ide> return [K.int_shape(x_elem) for x_elem in x]
<ide> else:
<ide> return K.int_shape(x)
<del> # otherwise, we default to the input shape
<add> # Otherwise, we default to the input shape.
<ide> warnings.warn('`output_shape` argument not specified for layer {} '
<ide> 'and cannot be automatically inferred with the Theano backend. '
<ide> 'Defaulting to output shape `{}` (same as input shape). '
<ide> class Dense(Layer):
<ide> (eg. maxnorm, nonneg), applied to the main weights matrix.
<ide> b_constraint: instance of the [constraints](../constraints.md) module,
<ide> applied to the bias.
<del> bias: whether to include a bias (i.e. make the layer affine rather than linear).
<del> input_dim: dimensionality of the input (integer).
<del> This argument (or alternatively, the keyword argument `input_shape`)
<add> bias: whether to include a bias
<add> (i.e. make the layer affine rather than linear).
<add> input_dim: dimensionality of the input (integer). This argument
<add> (or alternatively, the keyword argument `input_shape`)
<ide> is required when using this layer as the first layer in a model.
<ide>
<ide> # Input shape
<del> 2D tensor with shape: `(nb_samples, input_dim)`.
<add> nD tensor with shape: `(nb_samples, ..., input_dim)`.
<add> The most common situation would be
<add> a 2D input with shape `(nb_samples, input_dim)`.
<ide>
<ide> # Output shape
<del> 2D tensor with shape: `(nb_samples, output_dim)`.
<add> nD tensor with shape: `(nb_samples, ..., output_dim)`.
<add> For instance, for a 2D input with shape `(nb_samples, input_dim)`,
<add> the output would have shape `(nb_samples, output_dim)`.
<ide> '''
<ide> def __init__(self, output_dim, init='glorot_uniform',
<ide> activation=None, weights=None,
<ide> def __init__(self, output_dim, init='glorot_uniform',
<ide>
<ide> self.bias = bias
<ide> self.initial_weights = weights
<del> self.input_spec = [InputSpec(ndim=2)]
<add> self.input_spec = [InputSpec(ndim='2+')]
<ide>
<ide> if self.input_dim:
<ide> kwargs['input_shape'] = (self.input_dim,)
<ide> super(Dense, self).__init__(**kwargs)
<ide>
<ide> def build(self, input_shape):
<del> assert len(input_shape) == 2
<del> input_dim = input_shape[1]
<add> assert len(input_shape) >= 2
<add> input_dim = input_shape[-1]
<add> self.input_dim = input_dim
<ide> self.input_spec = [InputSpec(dtype=K.floatx(),
<del> shape=(None, input_dim))]
<add> ndim='2+')]
<ide>
<ide> self.W = self.add_weight((input_dim, self.output_dim),
<ide> initializer=self.init,
<ide> def call(self, x, mask=None):
<ide> return self.activation(output)
<ide>
<ide> def get_output_shape_for(self, input_shape):
<del> assert input_shape and len(input_shape) == 2
<del> return (input_shape[0], self.output_dim)
<add> assert input_shape and len(input_shape) >= 2
<add> assert input_shape[-1] and input_shape[-1] == self.input_dim
<add> output_shape = list(input_shape)
<add> output_shape[-1] = self.output_dim
<add> return tuple(output_shape)
<ide>
<ide> def get_config(self):
<ide> config = {'output_dim': self.output_dim,
<ide> class MaxoutDense(Layer):
<ide> (eg. maxnorm, nonneg), applied to the main weights matrix.
<ide> b_constraint: instance of the [constraints](../constraints.md) module,
<ide> applied to the bias.
<del> bias: whether to include a bias (i.e. make the layer affine rather than linear).
<del> input_dim: dimensionality of the input (integer).
<del> This argument (or alternatively, the keyword argument `input_shape`)
<add> bias: whether to include a bias
<add> (i.e. make the layer affine rather than linear).
<add> input_dim: dimensionality of the input (integer). This argument
<add> (or alternatively, the keyword argument `input_shape`)
<ide> is required when using this layer as the first layer in a model.
<ide>
<ide> # Input shape
<ide> class MaxoutDense(Layer):
<ide> # References
<ide> - [Maxout Networks](http://arxiv.org/pdf/1302.4389.pdf)
<ide> '''
<del> def __init__(self, output_dim, nb_feature=4,
<del> init='glorot_uniform', weights=None,
<del> W_regularizer=None, b_regularizer=None, activity_regularizer=None,
<del> W_constraint=None, b_constraint=None,
<del> bias=True, input_dim=None, **kwargs):
<add> def __init__(self, output_dim,
<add> nb_feature=4,
<add> init='glorot_uniform',
<add> weights=None,
<add> W_regularizer=None,
<add> b_regularizer=None,
<add> activity_regularizer=None,
<add> W_constraint=None,
<add> b_constraint=None,
<add> bias=True,
<add> input_dim=None,
<add> **kwargs):
<ide> self.output_dim = output_dim
<ide> self.nb_feature = nb_feature
<ide> self.init = initializations.get(init)
<ide> class Highway(Layer):
<ide> (eg. maxnorm, nonneg), applied to the main weights matrix.
<ide> b_constraint: instance of the [constraints](../constraints.md) module,
<ide> applied to the bias.
<del> bias: whether to include a bias (i.e. make the layer affine rather than linear).
<del> input_dim: dimensionality of the input (integer).
<del> This argument (or alternatively, the keyword argument `input_shape`)
<add> bias: whether to include a bias
<add> (i.e. make the layer affine rather than linear).
<add> input_dim: dimensionality of the input (integer). This argument
<add> (or alternatively, the keyword argument `input_shape`)
<ide> is required when using this layer as the first layer in a model.
<ide>
<ide> # Input shape
<ide> class Highway(Layer):
<ide> # References
<ide> - [Highway Networks](http://arxiv.org/pdf/1505.00387v2.pdf)
<ide> '''
<del> def __init__(self, init='glorot_uniform', transform_bias=-2,
<del> activation=None, weights=None,
<del> W_regularizer=None, b_regularizer=None, activity_regularizer=None,
<del> W_constraint=None, b_constraint=None,
<del> bias=True, input_dim=None, **kwargs):
<add> def __init__(self,
<add> init='glorot_uniform',
<add> transform_bias=-2,
<add> activation=None,
<add> weights=None,
<add> W_regularizer=None,
<add> b_regularizer=None,
<add> activity_regularizer=None,
<add> W_constraint=None,
<add> b_constraint=None,
<add> bias=True,
<add> input_dim=None,
<add> **kwargs):
<ide> self.init = initializations.get(init)
<ide> self.transform_bias = transform_bias
<ide> self.activation = activations.get(activation)
<ide> class TimeDistributedDense(Layer):
<ide> (eg. maxnorm, nonneg), applied to the main weights matrix.
<ide> b_constraint: instance of the [constraints](../constraints.md) module,
<ide> applied to the bias.
<del> bias: whether to include a bias (i.e. make the layer affine rather than linear).
<del> input_dim: dimensionality of the input (integer).
<del> This argument (or alternatively, the keyword argument `input_shape`)
<add> bias: whether to include a bias
<add> (i.e. make the layer affine rather than linear).
<add> input_dim: dimensionality of the input (integer). This argument
<add> (or alternatively, the keyword argument `input_shape`)
<ide> is required when using this layer as the first layer in a model.
<ide> input_length: length of inputs sequences
<ide> (integer, or None for variable-length sequences).
<ide> '''
<ide>
<ide> def __init__(self, output_dim,
<del> init='glorot_uniform', activation=None, weights=None,
<del> W_regularizer=None, b_regularizer=None, activity_regularizer=None,
<del> W_constraint=None, b_constraint=None,
<del> bias=True, input_dim=None, input_length=None, **kwargs):
<del> warnings.warn('TimeDistributedDense is deprecated, '
<del> 'please use TimeDistributed(Dense(...)) instead.')
<add> init='glorot_uniform',
<add> activation=None,
<add> weights=None,
<add> W_regularizer=None,
<add> b_regularizer=None,
<add> activity_regularizer=None,
<add> W_constraint=None,
<add> b_constraint=None,
<add> bias=True,
<add> input_dim=None,
<add> input_length=None,
<add> **kwargs):
<add> warnings.warn('`TimeDistributedDense` is deprecated, '
<add> 'And will be removed on May 1st, 2017. '
<add> 'Please use a `Dense` layer instead.')
<ide> self.output_dim = output_dim
<ide> self.init = initializations.get(init)
<ide> self.activation = activations.get(activation)
<ide> def call(self, x, mask=None):
<ide> input_shape = self.input_spec[0].shape
<ide> # x has shape (samples, timesteps, input_dim)
<ide> input_length = input_shape[1]
<del> # Note: input_length should always be provided when using tensorflow backend.
<ide> if not input_length:
<ide> if hasattr(K, 'int_shape'):
<ide> input_length = K.int_shape(x)[1]
<ide><path>tests/keras/layers/test_core.py
<ide> def test_dense():
<ide> kwargs={'output_dim': 3},
<ide> input_shape=(3, 2))
<ide>
<add> layer_test(core.Dense,
<add> kwargs={'output_dim': 3},
<add> input_shape=(3, 4, 2))
<add>
<add> layer_test(core.Dense,
<add> kwargs={'output_dim': 3},
<add> input_shape=(3, 4, 5, 2))
<add>
<ide> layer_test(core.Dense,
<ide> kwargs={'output_dim': 3,
<ide> 'W_regularizer': regularizers.l2(0.01), | 2 |
Javascript | Javascript | fix dock dragging | 2498b991c60472e654909b8b572577832a5f0a15 | <ide><path>src/pane-container.js
<ide> module.exports =
<ide> class PaneContainer {
<ide> constructor (params) {
<ide> let applicationDelegate, deserializerManager, notificationManager;
<del> ({config: this.config, applicationDelegate, notificationManager, deserializerManager, viewRegistry: this.viewRegistry} = params)
<add> ({config: this.config, applicationDelegate, notificationManager, deserializerManager, viewRegistry: this.viewRegistry, location: this.location} = params)
<ide> this.emitter = new Emitter()
<ide> this.subscriptions = new CompositeDisposable()
<ide> this.itemRegistry = new ItemRegistry()
<ide> class PaneContainer {
<ide> this.didActivatePane(this.getRoot())
<ide> }
<ide>
<add> getLocation () { return this.location }
<add>
<ide> getElement () {
<ide> return this.element != null ? this.element : (this.element = new PaneContainerElement().initialize(this, {views: this.viewRegistry}))
<ide> }
<ide><path>src/workspace-center.js
<ide> const PaneContainer = require('./pane-container')
<ide>
<ide> module.exports = class WorkspaceCenter {
<ide> constructor (params) {
<add> params.location = 'center'
<ide> this.paneContainer = new PaneContainer(params)
<ide> this.didActivate = params.didActivate
<ide> this.paneContainer.onDidActivatePane(() => this.didActivate(this)) | 2 |
Javascript | Javascript | add linkedin passport strategy | c95ee75eeebd98f2950cab001920a6254abe601d | <ide><path>config/passport.js
<ide> var FacebookStrategy = require('passport-facebook').Strategy;
<ide> var TwitterStrategy = require('passport-twitter').Strategy;
<ide> var GitHubStrategy = require('passport-github').Strategy;
<ide> var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
<add>var LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;
<ide> var OAuthStrategy = require('passport-oauth').OAuthStrategy; // Tumblr
<ide> var OAuth2Strategy = require('passport-oauth').OAuth2Strategy; // Venmo, Foursquare
<ide> var User = require('../models/User');
<ide> passport.use(new GoogleStrategy(secrets.google, function(req, accessToken, refre
<ide> }
<ide> }));
<ide>
<add>/**
<add> * Sign in with LinkedIn.
<add> */
<add>
<add>passport.use(new LinkedInStrategy(secrets.linkedin, function(req, accessToken, refreshToken, profile, done) {
<add> if (req.user) {
<add> User.findOne({ $or: [
<add> { linkedin: profile.id },
<add> { email: profile._json.emailAddress }
<add> ] }, function(err, existingUser) {
<add> if (existingUser) {
<add> req.flash('errors', { msg: 'There is already a LinkedIn account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
<add> done(err);
<add> } else {
<add> User.findById(req.user.id, function(err, user) {
<add> user.linkedin = profile.id;
<add> user.tokens.push({ kind: 'linkedin', accessToken: accessToken });
<add> user.profile.name = user.profile.name || profile.displayName;
<add> user.profile.location = user.profile.location || profile._json.location.name;
<add> user.profile.picture = user.profile.picture || profile._json.pictureUrl;
<add> user.profile.website = user.profile.website || profile._json.publicProfileUrl;
<add> user.save(function(err) {
<add> req.flash('info', { msg: 'LinkedIn account has been linked.' });
<add> done(err, user);
<add> });
<add> });
<add> }
<add> });
<add> } else {
<add> User.findOne({ linkedin: profile.id }, function(err, existingUser) {
<add> if (existingUser) return done(null, existingUser);
<add> User.findOne({ email: profile._json.emailAddress }, function(err, existingEmailUser) {
<add> if (existingEmailUser) {
<add> req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Google manually from Account Settings.' });
<add> done(err);
<add> } else {
<add> var user = new User();
<add> user.linkedin = profile.id;
<add> user.tokens.push({ kind: 'linkedin', accessToken: accessToken });
<add> user.email = profile._json.emailAddress;
<add> user.profile.name = profile.displayName;
<add> user.profile.location = profile._json.location.name;
<add> user.profile.picture = profile._json.pictureUrl;
<add> user.profile.website = profile._json.publicProfileUrl;
<add> user.save(function(err) {
<add> done(err, user);
<add> });
<add> }
<add> });
<add> });
<add> }
<add>}));
<add>
<ide> /**
<ide> * Tumblr API
<ide> * Uses OAuth 1.0a Strategy. | 1 |
Text | Text | fix repetitive word in the tutorial | a609e4e1ca98228bef7537d7770d7919ac25a047 | <ide><path>docs/tutorial/1-serialization.md
<ide> Quit out of the shell...
<ide>
<ide> In another terminal window, we can test the server.
<ide>
<del>We can test our API using using [curl][curl] or [httpie][httpie]. Httpie is a user friendly http client that's written in Python. Let's install that.
<add>We can test our API using [curl][curl] or [httpie][httpie]. Httpie is a user friendly http client that's written in Python. Let's install that.
<ide>
<ide> You can install httpie using pip:
<ide> | 1 |
Javascript | Javascript | add a helpful warning | c2a83893f5df634c0037b8a194c78734ba21ef5f | <ide><path>packages/ember-runtime/lib/mixins/action_handler.js
<ide> Ember.ActionHandler = Ember.Mixin.create({
<ide> var hashName;
<ide>
<ide> if (!props._actions) {
<add> Ember.assert(this + " 'actions' should not be a function", typeof(props.actions) !== 'function');
<add>
<ide> if (typeOf(props.actions) === 'object') {
<ide> hashName = 'actions';
<ide> } else if (typeOf(props.events) === 'object') {
<ide><path>packages/ember-runtime/tests/mixins/action_handler_test.js
<add>test("passing a function for the actions hash triggers an assertion", function() {
<add> expect(1);
<add>
<add> var controller = Ember.Controller.extend({
<add> actions: function(){}
<add> });
<add>
<add> expectAssertion(function(){
<add> Ember.run(function(){
<add> controller.create();
<add> });
<add> });
<add>}); | 2 |
Python | Python | add flag to enable xprof | 154d3ffa6650a308fc110d993501ae95534e8a6a | <ide><path>official/resnet/keras/keras_common.py
<ide> def define_keras_flags():
<ide> help='The number of steps to run for training. If it is larger than '
<ide> '# batches per epoch, then use # batches per epoch. When this flag is '
<ide> 'set, only one epoch is going to run for training.')
<add> flags.DEFINE_boolean(
<add> name='enable_e2e_xprof', default=False,
<add> help='Save end-to-end profiling data to model dir using Xprof. Profiling '
<add> 'has an overhead on both computation and memory usage, and can generate '
<add> 'gigantic files when profiling a lot of steps.')
<ide>
<ide>
<ide> def get_synth_input_fn(height, width, num_channels, num_classes,
<ide><path>official/resnet/keras/keras_imagenet_main.py
<ide> from absl import flags
<ide> import tensorflow as tf # pylint: disable=g-bad-import-order
<ide>
<add>from tensorflow.python.eager import profiler
<ide> from official.resnet import imagenet_main
<ide> from official.resnet.keras import keras_common
<ide> from official.resnet.keras import resnet_model
<ide> def run(flags_obj):
<ide> callbacks = [time_callback, lr_callback]
<ide> if flags_obj.enable_tensorboard:
<ide> callbacks.append(tensorboard_callback)
<add> if flags_obj.enable_e2e_xprof:
<add> profiler.start()
<ide>
<ide> history = model.fit(train_input_dataset,
<ide> epochs=train_epochs,
<ide> def run(flags_obj):
<ide> validation_freq=flags_obj.epochs_between_evals,
<ide> verbose=2)
<ide>
<add> if flags_obj.enable_e2e_xprof:
<add> results = profiler.stop()
<add> profiler.save(flags_obj.model_dir, results)
<add>
<ide> eval_output = None
<ide> if not flags_obj.skip_eval:
<ide> eval_output = model.evaluate(eval_input_dataset, | 2 |
Javascript | Javascript | address pr feedback | 9bea0556fe15ecc68651e51bad34dd916b20022b | <ide><path>examples/js/controls/OrbitControls.js
<ide> THREE.OrbitControls = function ( object, domElement ) {
<ide> this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 };
<ide>
<ide> // Mouse buttons
<del> this.mouseButtons = { ORBIT: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT };
<add> this.mouseButtons = { LEFT: THREE.MOUSE.LEFT, MIDDLE: THREE.MOUSE.MIDDLE, RIGHT: THREE.MOUSE.RIGHT };
<ide>
<ide> // for reset
<ide> this.target0 = this.target.clone();
<ide> THREE.OrbitControls = function ( object, domElement ) {
<ide> // public methods
<ide> //
<ide>
<del> this.getStateForMouseDown = function ( event ) {
<del>
<del> if ( event.button === scope.mouseButtons.ORBIT && ! event.ctrlKey ) return STATE.ROTATE;
<del>
<del> if ( event.button === scope.mouseButtons.ZOOM ) return STATE.DOLLY;
<del>
<del> if ( event.button === scope.mouseButtons.PAN || ( event.button === scope.mouseButtons.ORBIT && event.ctrlKey ) ) return STATE.PAN;
<del>
<del> return STATE.NONE;
<del>
<del> };
<del>
<ide> this.getPolarAngle = function () {
<ide>
<ide> return spherical.phi;
<ide> THREE.OrbitControls = function ( object, domElement ) {
<ide>
<ide> event.preventDefault();
<ide>
<del> var newState = scope.getStateForMouseDown( event );
<add> switch ( event.button ) {
<ide>
<del> switch ( newState ) {
<add> case scope.mouseButtons.LEFT:
<ide>
<del> case STATE.ROTATE:
<add> if ( event.ctrlKey || event.metaKey ) {
<ide>
<del> if ( scope.enableRotate === false ) return;
<add> if ( scope.enablePan === false ) return;
<add>
<add> handleMouseDownPan( event );
<add>
<add> state = STATE.PAN;
<add>
<add> } else {
<add>
<add> if ( scope.enableRotate === false ) return;
<ide>
<del> handleMouseDownRotate( event );
<add> handleMouseDownRotate( event );
<add>
<add> state = STATE.ROTATE;
<add>
<add> }
<ide>
<ide> break;
<ide>
<del> case STATE.DOLLY:
<add> case scope.mouseButtons.MIDDLE:
<ide>
<ide> if ( scope.enableZoom === false ) return;
<ide>
<ide> handleMouseDownDolly( event );
<ide>
<add> state = STATE.DOLLY;
<add>
<ide> break;
<ide>
<del> case STATE.PAN:
<add> case scope.mouseButtons.RIGHT:
<ide>
<ide> if ( scope.enablePan === false ) return;
<ide>
<ide> handleMouseDownPan( event );
<ide>
<del> break;
<del>
<del> default: // STATE.NONE
<add> state = STATE.PAN;
<ide>
<del> return;
<add> break;
<ide>
<ide> }
<ide>
<del> state = newState;
<add> if ( state !== STATE.NONE ) {
<ide>
<del> document.addEventListener( 'mousemove', onMouseMove, false );
<del> document.addEventListener( 'mouseup', onMouseUp, false );
<add> document.addEventListener( 'mousemove', onMouseMove, false );
<add> document.addEventListener( 'mouseup', onMouseUp, false );
<ide>
<del> scope.dispatchEvent( startEvent );
<add> scope.dispatchEvent( startEvent );
<add>
<add> }
<ide>
<ide> }
<ide> | 1 |
Ruby | Ruby | convert nestedcontainer test to spec | 3db8cdf8613694a26051e0ee291f931a7ca00ae3 | <add><path>Library/Homebrew/cask/spec/cask/artifact/nested_container_spec.rb
<del><path>Library/Homebrew/cask/test/cask/artifact/nested_container_test.rb
<del>require "test_helper"
<add>require "spec_helper"
<ide>
<ide> describe Hbc::Artifact::NestedContainer do
<ide> describe "install" do
<ide> it "extracts the specified paths as containers" do
<ide> cask = Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/nested-app.rb").tap do |c|
<del> TestHelper.install_without_artifacts(c)
<add> InstallHelper.install_without_artifacts(c)
<ide> end
<ide>
<ide> shutup do
<ide> Hbc::Artifact::NestedContainer.new(cask).install_phase
<ide> end
<ide>
<del> cask.staged_path.join("MyNestedApp.app").must_be :directory?
<add> expect(cask.staged_path.join("MyNestedApp.app")).to be_a_directory
<ide> end
<ide> end
<ide> end | 1 |
PHP | PHP | remove @throws docblock tags | 6d06919511fa34ffca24e03cd494db4d63ee2575 | <ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function fromRaw($expression, $bindings = [])
<ide> *
<ide> * @param \Closure|\Illuminate\Database\Query\Builder|string $query
<ide> * @return array
<del> *
<del> * @throws \InvalidArgumentException
<ide> */
<ide> protected function createSub($query)
<ide> {
<ide> public function leftJoinWhere($table, $first, $operator, $second)
<ide> * @param string|null $operator
<ide> * @param string|null $second
<ide> * @return \Illuminate\Database\Query\Builder|static
<del> *
<del> * @throws \InvalidArgumentException
<ide> */
<ide> public function leftJoinSub($query, $as, $first, $operator = null, $second = null)
<ide> {
<ide> public function rightJoinWhere($table, $first, $operator, $second)
<ide> * @param string|null $operator
<ide> * @param string|null $second
<ide> * @return \Illuminate\Database\Query\Builder|static
<del> *
<del> * @throws \InvalidArgumentException
<ide> */
<ide> public function rightJoinSub($query, $as, $first, $operator = null, $second = null)
<ide> {
<ide> public function insertGetId(array $values, $sequence = null)
<ide> * @param array $columns
<ide> * @param \Closure|\Illuminate\Database\Query\Builder|string $query
<ide> * @return int
<del> *
<del> * @throws \InvalidArgumentException
<ide> */
<ide> public function insertUsing(array $columns, $query)
<ide> { | 1 |
Go | Go | fix empty-lines (revive) | 31441778fa52b8fa8828356679328cc1c9f98c68 | <ide><path>api/types/strslice/strslice_test.go
<ide> func TestStrSliceUnmarshalJSON(t *testing.T) {
<ide> "[]": {},
<ide> `["/bin/sh","-c","echo"]`: {"/bin/sh", "-c", "echo"},
<ide> }
<del> for json, expectedParts := range parts {
<add> for input, expected := range parts {
<ide> strs := StrSlice{"default", "values"}
<del> if err := strs.UnmarshalJSON([]byte(json)); err != nil {
<add> if err := strs.UnmarshalJSON([]byte(input)); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> actualParts := []string(strs)
<del> if !reflect.DeepEqual(actualParts, expectedParts) {
<del> t.Fatalf("%#v: expected %v, got %v", json, expectedParts, actualParts)
<add> if !reflect.DeepEqual(actualParts, expected) {
<add> t.Fatalf("%#v: expected %v, got %v", input, expected, actualParts)
<ide> }
<del>
<ide> }
<ide> }
<ide> | 1 |
PHP | PHP | set default to null to make static analyers happy | b1d98ecc37df5670a3f8542372feabecf546dbcb | <ide><path>src/Cache/Engine/MemcachedEngine.php
<ide> class MemcachedEngine extends CacheEngine
<ide> 'host' => null,
<ide> 'username' => null,
<ide> 'password' => null,
<del> 'persistent' => false,
<add> 'persistent' => null,
<ide> 'port' => null,
<ide> 'prefix' => 'cake_',
<ide> 'serialize' => 'php',
<ide> public function init(array $config = []): bool
<ide> }
<ide>
<ide> if ($this->_config['persistent']) {
<del> $this->_Memcached = new Memcached((string)$this->_config['persistent']);
<add> $this->_Memcached = new Memcached($this->_config['persistent']);
<ide> } else {
<ide> $this->_Memcached = new Memcached();
<ide> } | 1 |
Python | Python | fix python for blender 2.58 | 83628d5e151c3424f9dd2268ef910f82dca7fb28 | <ide><path>utils/exporters/blender/2.58/scripts/addons/io_mesh_threejs/__init__.py
<ide>
<ide> import bpy
<ide> from bpy.props import *
<del>from io_utils import ExportHelper, ImportHelper
<add>from bpy_extras.io_utils import ExportHelper, ImportHelper
<ide>
<ide> # ################################################################
<ide> # Custom properties | 1 |
PHP | PHP | add withsession helper | 181810cfdacdc50d47a80eb88ae441b38ae16dc8 | <ide><path>src/Illuminate/Foundation/Testing/ApplicationTrait.php
<ide> protected function withoutEvents()
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Set the session to the given array.
<add> *
<add> * @param array $data
<add> * @return void
<add> */
<add> public function withSession(array $data)
<add> {
<add> $this->session($data);
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Set the session to the given array.
<ide> * | 1 |
Java | Java | add new constructor to jettyclienthttpconnector | 1cfedb20b89310a4b7cc9d0e4e5e24e79d7921f9 | <ide><path>spring-web/src/main/java/org/springframework/http/client/reactive/JettyClientHttpConnector.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 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 JettyClientHttpConnector() {
<ide> * Constructor with an {@link JettyResourceFactory} that will manage shared resources.
<ide> * @param resourceFactory the {@link JettyResourceFactory} to use
<ide> * @param customizer the lambda used to customize the {@link HttpClient}
<add> * @deprecated in favor of {@link JettyClientHttpConnector#JettyClientHttpConnector(HttpClient, JettyResourceFactory)}
<ide> */
<add> @Deprecated
<ide> public JettyClientHttpConnector(
<ide> JettyResourceFactory resourceFactory, @Nullable Consumer<HttpClient> customizer) {
<del>
<del> HttpClient httpClient = new HttpClient();
<del> httpClient.setExecutor(resourceFactory.getExecutor());
<del> httpClient.setByteBufferPool(resourceFactory.getByteBufferPool());
<del> httpClient.setScheduler(resourceFactory.getScheduler());
<add> this(new HttpClient(), resourceFactory);
<ide> if (customizer != null) {
<del> customizer.accept(httpClient);
<add> customizer.accept(this.httpClient);
<ide> }
<del> this.httpClient = httpClient;
<ide> }
<ide>
<ide> /**
<ide> * Constructor with an initialized {@link HttpClient}.
<ide> */
<ide> public JettyClientHttpConnector(HttpClient httpClient) {
<add> this(httpClient, null);
<add> }
<add>
<add> /**
<add> * Constructor with an initialized {@link HttpClient} and configures it
<add> * with the given {@link JettyResourceFactory}.
<add> * @param httpClient the {@link HttpClient} to use
<add> * @param resourceFactory the {@link JettyResourceFactory} to use
<add> */
<add> public JettyClientHttpConnector(HttpClient httpClient,
<add> @Nullable JettyResourceFactory resourceFactory) {
<ide> Assert.notNull(httpClient, "HttpClient is required");
<add> if (resourceFactory != null) {
<add> httpClient.setExecutor(resourceFactory.getExecutor());
<add> httpClient.setByteBufferPool(resourceFactory.getByteBufferPool());
<add> httpClient.setScheduler(resourceFactory.getScheduler());
<add> }
<ide> this.httpClient = httpClient;
<ide> }
<ide> | 1 |
Java | Java | add @donotstrip annotation to getjavamodule | 44678bbf766c2ede54dd8ccd9d4105b72f93f612 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManager.java
<ide> public List<String> getEagerInitModuleNames() {
<ide> return mTurbomoduleManagerDelegate.getEagerInitModuleNames();
<ide> }
<ide>
<add> @DoNotStrip
<ide> @Nullable
<ide> private TurboModule getJavaModule(String name) {
<ide> if (!mTurboModules.containsKey(name)) { | 1 |
Ruby | Ruby | report new_tag even when old_tag blank | a25f827b8fb88a0f61872b95d408f7d58e3fdaf4 | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def output_update_report
<ide>
<ide> Settings.write "latesttag", new_tag if new_tag != old_tag
<ide>
<del> if old_tag.blank? || (new_tag == old_tag)
<add> if new_tag == old_tag
<ide> puts "Updated Homebrew from #{shorten_revision(initial_revision)} to #{shorten_revision(current_revision)}."
<add> elsif old_tag.blank?
<add> ohai "Updated Homebrew from #{shorten_revision(initial_revision)} " \
<add> "to #{new_tag} (#{shorten_revision(current_revision)})."
<ide> else
<ide> ohai "Updated Homebrew from #{old_tag} (#{shorten_revision(initial_revision)}) " \
<ide> "to #{new_tag} (#{shorten_revision(current_revision)})." | 1 |
Javascript | Javascript | add closure externs for angular.$q.promise.finally | a7aa4cc0a97abaa1c4e8796f2b5ed5e216eff0e4 | <ide><path>closure/angular.js
<ide> angular.$q.Promise;
<ide> */
<ide> angular.$q.Promise.then = function(successCallback, opt_errorCallback) {};
<ide>
<del>/**
<del> * @param {?function(?)} callback
<del> * @return {angular.$q.Promise}
<del> */
<del>angular.$q.Promise.finally = function(callback) {};
<del>
<ide> /******************************************************************************
<ide> * $route Service
<ide> *****************************************************************************/ | 1 |
Javascript | Javascript | replace fixturesdir with fixtures module | 8597a18cdbb339abd20a2342d263c8eee3bc51e8 | <ide><path>test/parallel/test-global.js
<ide>
<ide> /* eslint-disable strict */
<ide> const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<ide>
<ide> const assert = require('assert');
<del>const path = require('path');
<ide>
<ide> common.globalCheck = false;
<ide>
<ide> assert.strictEqual(baseBar, // eslint-disable-line no-undef
<ide> 'bar',
<ide> 'global.x -> x in base level not working');
<ide>
<del>const mod = require(path.join(common.fixturesDir, 'global', 'plain'));
<add>const mod = require(fixtures.path('global', 'plain'));
<ide> const fooBar = mod.fooBar;
<ide>
<ide> assert.strictEqual(fooBar.foo, 'foo', 'x -> global.x in sub level not working'); | 1 |
Text | Text | fix formatting of activerecord postgresql guide | 0d34b550a491dab2ab58168c328907accdee6781 | <ide><path>guides/source/active_record_postgresql.md
<ide> Book.where("array_length(ratings, 1) >= 3")
<ide>
<ide> * [type definition](http://www.postgresql.org/docs/current/static/hstore.html)
<ide>
<del>NOTE: you need to enable the `hstore` extension to use hstore.
<add>NOTE: You need to enable the `hstore` extension to use hstore.
<ide>
<ide> ```ruby
<ide> # db/migrate/20131009135255_create_profiles.rb
<ide> article.save!
<ide> ```
<ide>
<ide> To add a new value before/after existing one you should use [ALTER TYPE](http://www.postgresql.org/docs/current/static/sql-altertype.html):
<add>
<ide> ```ruby
<ide> # db/migrate/20150720144913_add_new_state_to_articles.rb
<ide> # NOTE: ALTER TYPE ... ADD VALUE cannot be executed inside of a transaction block so here we are using disable_ddl_transaction!
<ide> def up
<ide> end
<ide> ```
<ide>
<del>NOTE: by now we can't drop ENUM values. You can read why [here](http://www.postgresql.org/message-id/29F36C7C98AB09499B1A209D48EAA615B7653DBC8A@mail2a.alliedtesting.com).
<add>NOTE: ENUM values can't be dropped currently. You can read why [here](http://www.postgresql.org/message-id/29F36C7C98AB09499B1A209D48EAA615B7653DBC8A@mail2a.alliedtesting.com).
<ide>
<ide> Hint: to show all the values of the all enums you have, you should call this query in `bin/rails db` or `psql` console:
<add>
<ide> ```sql
<ide> SELECT n.nspname AS enum_schema,
<ide> t.typname AS enum_name,
<ide> SELECT n.nspname AS enum_schema,
<ide> * [pgcrypto generator function](http://www.postgresql.org/docs/current/static/pgcrypto.html#AEN159361)
<ide> * [uuid-ossp generator functions](http://www.postgresql.org/docs/current/static/uuid-ossp.html)
<ide>
<del>NOTE: you need to enable the `pgcrypto` (only PostgreSQL >= 9.4) or `uuid-ossp`
<add>NOTE: You need to enable the `pgcrypto` (only PostgreSQL >= 9.4) or `uuid-ossp`
<ide> extension to use uuid.
<ide>
<ide> ```ruby
<ide> A point is casted to an array containing `x` and `y` coordinates.
<ide> UUID Primary Keys
<ide> -----------------
<ide>
<del>NOTE: you need to enable the `pgcrypto` (only PostgreSQL >= 9.4) or `uuid-ossp`
<add>NOTE: You need to enable the `pgcrypto` (only PostgreSQL >= 9.4) or `uuid-ossp`
<ide> extension to generate random UUIDs.
<ide>
<ide> ```ruby | 1 |
Python | Python | replace timer by sleep | 5bccb814392d9ecf12b410843b1e7330d0fb72d2 | <ide><path>glances/plugins/glances_docker.py
<ide> def run(self):
<ide> """Function called to grab stats.
<ide> Infinite loop, should be stopped by calling the stop() method"""
<ide>
<del> is_stopped = False
<ide> for i in self._stats_stream:
<ide> self._stats = i
<del> countdown = Timer(self._refresh_time)
<del> while not countdown.finished() and not is_stopped:
<del> is_stopped = self.stopped()
<del> time.sleep(0.1)
<del> if is_stopped:
<add> # countdown = Timer(self._refresh_time)
<add> # while not countdown.finished() and not is_stopped:
<add> # is_stopped = self.stopped()
<add> # time.sleep(0.1)
<add> # if is_stopped:
<add> # break
<add> time.sleep(0.1)
<add> if self.stopped():
<ide> break
<ide>
<ide> @property | 1 |
Ruby | Ruby | replace nokogiri with rexml | 282c71d275a5bc11f4bb1f284f82a83742629d26 | <ide><path>Library/Homebrew/bundle_version.rb
<ide> def self.from_info_plist_content(plist)
<ide>
<ide> sig { params(package_info_path: Pathname).returns(T.nilable(T.attached_class)) }
<ide> def self.from_package_info(package_info_path)
<del> Homebrew.install_bundler_gems!
<del> require "nokogiri"
<add> require "rexml/document"
<ide>
<del> xml = Nokogiri::XML(package_info_path.read)
<add> xml = REXML::Document.new(package_info_path.read)
<ide>
<del> bundle_id = xml.xpath("//pkg-info//bundle-version//bundle").first&.attr("id")
<del> return unless bundle_id
<add> bundle_version_bundle = xml.get_elements("//pkg-info//bundle-version//bundle").first
<add> bundle_id = bundle_version_bundle["id"] if bundle_version_bundle
<add> return if bundle_id.blank?
<ide>
<del> bundle = xml.xpath("//pkg-info//bundle").find { |b| b["id"] == bundle_id }
<add> bundle = xml.get_elements("//pkg-info//bundle").find { |b| b["id"] == bundle_id }
<ide> return unless bundle
<ide>
<ide> short_version = bundle["CFBundleShortVersionString"] | 1 |
PHP | PHP | add failed jobs table | b7d2b48b75afbaa34c82688cb30be2f00a7d8c57 | <ide><path>database/migrations/2019_08_19_175727_create_failed_jobs_table.php
<add><?php
<add>
<add>use Illuminate\Support\Facades\Schema;
<add>use Illuminate\Database\Schema\Blueprint;
<add>use Illuminate\Database\Migrations\Migration;
<add>
<add>class CreateFailedJobsTable extends Migration
<add>{
<add> /**
<add> * Run the migrations.
<add> *
<add> * @return void
<add> */
<add> public function up()
<add> {
<add> Schema::create('failed_jobs', function (Blueprint $table) {
<add> $table->bigIncrements('id');
<add> $table->text('connection');
<add> $table->text('queue');
<add> $table->longText('payload');
<add> $table->longText('exception');
<add> $table->timestamp('failed_at')->useCurrent();
<add> });
<add> }
<add>
<add> /**
<add> * Reverse the migrations.
<add> *
<add> * @return void
<add> */
<add> public function down()
<add> {
<add> Schema::dropIfExists('failed_jobs');
<add> }
<add>} | 1 |
Ruby | Ruby | add start and stop as generic executables | bba2b7616735fe5503923c908cc36c9222b40393 | <ide><path>Library/Homebrew/formula_cellar_checks.rb
<ide> def check_non_executables bin
<ide>
<ide> def check_generic_executables bin
<ide> return unless bin.directory?
<del> generic_names = %w[run service]
<add> generic_names = %w[run service start stop]
<ide> generics = bin.children.select { |g| generic_names.include? g.basename.to_s }
<ide> return if generics.empty?
<ide> | 1 |
Python | Python | remove unused import | 12c45f06a5e0c2303977ce91abc3614b4b00556f | <ide><path>flask/cli.py
<ide> import click
<ide>
<ide> from . import __version__
<del>from ._compat import iteritems, reraise, PY2
<add>from ._compat import iteritems, reraise
<ide> from .globals import current_app
<ide> from .helpers import get_debug_flag
<ide> from ._compat import getargspec | 1 |
Python | Python | add timer to docker thread | ffb26c849e58a893e9e3a2eea364b58ad9a8ea59 | <ide><path>glances/core/glances_logging.py
<ide> },
<ide> 'short': {
<ide> 'format': '%(levelname)s: %(message)s'
<add> },
<add> 'free': {
<add> 'format': '%(message)s'
<ide> }
<ide> },
<ide> 'handlers': {
<ide> 'console': {
<ide> 'level': 'CRITICAL',
<ide> 'class': 'logging.StreamHandler',
<del> 'formatter': 'short'
<add> 'formatter': 'free'
<ide> }
<ide> },
<ide> 'loggers': {
<ide><path>glances/core/glances_stats.py
<ide> def get_plugin(self, plugin_name):
<ide>
<ide> def end(self):
<ide> """End of the Glances stats."""
<del> # Close the export module
<add> # Close export modules
<ide> for e in self._exports:
<ide> self._exports[e].exit()
<add> # Close plugins
<add> for p in self._plugins:
<add> self._plugins[p].exit()
<ide>
<ide>
<ide> class GlancesStatsServer(GlancesStats):
<ide><path>glances/plugins/glances_docker.py
<ide>
<ide> """Docker plugin."""
<ide>
<del>import numbers
<ide> import os
<ide> import re
<add>import threading
<add>import time
<ide>
<ide> # Import Glances libs
<ide> from glances.core.glances_logging import logger
<ide> from glances.core.glances_timer import getTimeSinceLastUpdate
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<add>from glances.core.glances_timer import Timer
<ide>
<ide> # Docker-py library (optional and Linux-only)
<ide> # https://github.com/docker/docker-py
<ide> def __init__(self, args=None):
<ide> # Init the Docker API
<ide> self.docker_client = False
<ide>
<add> # Dict of thread (to grab stats asynchroniously, one thread is created by container)
<add> # key: Container Id
<add> # value: instance of ThreadDockerGrabber
<add> self.thread_list = {}
<add>
<add> def exit(self):
<add> """Overwrite the exit method to close threads"""
<add> logger.debug("Stop the Docker plugin")
<add> for t in self.thread_list.values():
<add> t.stop()
<add>
<ide> def get_key(self):
<ide> """Return the key of the list."""
<ide> return 'name'
<ide> def update(self):
<ide>
<ide> if self.input_method == 'local':
<ide> # Update stats
<add>
<add> # Docker version
<ide> # Exemple: {
<ide> # "KernelVersion": "3.16.4-tinycore64",
<ide> # "Arch": "amd64",
<ide> def update(self):
<ide> self.stats['version'] = self.docker_client.version()
<ide> except Exception as e:
<ide> # Correct issue#649
<del> logger.error("Plugin can not get Docker version ({})".format(e))
<add> logger.error("{} plugin - Can not get Docker version ({})".format(self.plugin_name, e))
<add> return self.stats
<add>
<add> # Container globals information
<ide> # Example: [{u'Status': u'Up 36 seconds',
<ide> # u'Created': 1420378904,
<ide> # u'Image': u'nginx:1',
<ide> def update(self):
<ide> # u'Command': u"nginx -g 'daemon off;'",
<ide> # u'Names': [u'/webstack_nginx_1'],
<ide> # u'Id': u'b0da859e84eb4019cf1d965b15e9323006e510352c402d2f442ea632d61faaa5'}]
<del> self.stats['containers'] = self.docker_client.containers()
<del> # Get stats for all containers
<del> for c in self.stats['containers']:
<del> if not hasattr(self, 'docker_stats'):
<del> # Create a dict with all the containers' stats instance
<del> self.docker_stats = {}
<del>
<del> # TODO: Find a way to correct this
<del> # The following optimization is not compatible with the network stats
<del> # The self.docker_client.stats method should be call every time in order to have network stats refreshed
<del> # Nevertheless, if we call it every time, Glances is slow...
<del> if c['Id'] not in self.docker_stats:
<del> # Create the stats instance for the current container
<del> try:
<del> self.docker_stats[c['Id']] = self.docker_client.stats(c['Id'], decode=True)
<del> logger.debug("Create Docker stats object for container {0}".format(c['Id']))
<del> except Exception as e:
<del> # Correct Issue #602
<del> logger.error("Cannot call Docker stats method {0}".format(e))
<del>
<del> # Get the docker stats
<del> try:
<del> # self.docker_stats[c['Id']] = self.docker_client.stats(c['Id'], decode=True)
<del> all_stats = self.docker_stats[c['Id']].next()
<del> except Exception:
<del> all_stats = {}
<ide>
<del> c['cpu'] = self.get_docker_cpu(c['Id'], all_stats)
<del> c['memory'] = self.get_docker_memory(c['Id'], all_stats)
<del> # c['network'] = self.get_docker_network(c['Id'], all_stats)
<add> # Update current containers list
<add> try:
<add> self.stats['containers'] = self.docker_client.containers()
<add> except Exception as e:
<add> logger.error("{} plugin - Can not get containers list ({})".format(self.plugin_name, e))
<add> return self.stats
<add>
<add> # Start new thread for new container
<add> for container in self.stats['containers']:
<add> if container['Id'] not in self.thread_list:
<add> # Thread did not exist in the internal dict
<add> # Create it and add it to the internal dict
<add> logger.debug("{} plugin - Create thread for container {}".format(self.plugin_name, container['Id'][:12]))
<add> t = ThreadDockerGrabber(self.docker_client, container['Id'], self.args.time)
<add> self.thread_list[container['Id']] = t
<add> t.start()
<add>
<add> # Stop threads for non-existing containers
<add> nonexisting_containers = list(set(self.thread_list.keys()) - set([c['Id'] for c in self.stats['containers']]))
<add> for container_id in nonexisting_containers:
<add> # Stop the thread
<add> logger.debug("{} plugin - Stop thread for old container {}".format(self.plugin_name, container_id[:12]))
<add> self.thread_list[container_id].stop()
<add> # Delete the item from the dict
<add> del(self.thread_list[container_id])
<add>
<add> # Get stats for all containers
<add> for container in self.stats['containers']:
<add> # The key is the container name and not the Id
<add> container['key'] = self.get_key()
<ide>
<ide> # Export name (first name in the list, without the /)
<del> c['name'] = c['Names'][0][1:]
<add> container['name'] = container['Names'][0][1:]
<ide>
<del> # The key is the container name and not the Id
<del> c['key'] = self.get_key()
<add> container['cpu'] = self.get_docker_cpu(container['Id'], self.thread_list[container['Id']].stats)
<add> container['memory'] = self.get_docker_memory(container['Id'], self.thread_list[container['Id']].stats)
<add> container['network'] = self.get_docker_network(container['Id'], self.thread_list[container['Id']].stats)
<ide>
<ide> elif self.input_method == 'snmp':
<ide> # Update stats using SNMP
<ide> def update(self):
<ide>
<ide> return self.stats
<ide>
<del> def get_docker_cpu_old(self, container_id):
<del> """Return the container CPU usage by reading /sys/fs/cgroup/.
<del>
<del> Input: id is the full container id
<del> Output: a dict {'total': 1.49, 'user': 0.65, 'system': 0.84}
<del> """
<del> ret = {}
<del> # Read the stats
<del> try:
<del> with open('/sys/fs/cgroup/cpuacct/docker/' + container_id + '/cpuacct.stat', 'r') as f:
<del> for line in f:
<del> m = re.search(r"(system|user)\s+(\d+)", line)
<del> if m:
<del> ret[m.group(1)] = int(m.group(2))
<del> except IOError as e:
<del> logger.error("Can not grab container CPU stat ({0})".format(e))
<del> return ret
<del> if isinstance(ret["system"], numbers.Number) and isinstance(ret["user"], numbers.Number):
<del> ret["total"] = ret["system"] + ret["user"]
<del> # Return the stats
<del> return ret
<del>
<ide> def get_docker_cpu(self, container_id, all_stats):
<ide> """Return the container CPU usage.
<ide>
<ide> def get_docker_cpu(self, container_id, all_stats):
<ide> cpu_new['nb_core'] = len(all_stats['cpu_stats']['cpu_usage']['percpu_usage'])
<ide> except KeyError as e:
<ide> # all_stats do not have CPU information
<del> logger.debug("Can not grab CPU usage for container {0} ({1}). Trying fallback method.".format(container_id, e))
<del> # Trying fallback to old grab method
<del> ret = self.get_docker_cpu_old(container_id)
<del> # Get the user ticks
<del> ticks = self.get_user_ticks()
<del> for k in ret.keys():
<del> ret[k] = float(ret[k]) / ticks
<add> logger.debug("Can not grab CPU usage for container {0} ({1})".format(container_id, e))
<ide> else:
<ide> # Previous CPU stats stored in the cpu_old variable
<ide> if not hasattr(self, 'cpu_old'):
<ide> def get_docker_cpu(self, container_id, all_stats):
<ide> # Return the stats
<ide> return ret
<ide>
<del> def get_docker_memory_old(self, container_id):
<del> """Return the container MEMORY usage by reading /sys/fs/cgroup/.
<del>
<del> Input: id is the full container id
<del> Output: a dict {'rss': 1015808, 'cache': 356352}
<del> """
<del> ret = {}
<del> # Read the stats
<del> try:
<del> with open('/sys/fs/cgroup/memory/docker/' + container_id + '/memory.stat', 'r') as f:
<del> for line in f:
<del> m = re.search(r"(rss|cache)\s+(\d+)", line)
<del> if m:
<del> ret[m.group(1)] = int(m.group(2))
<del> except IOError as e:
<del> logger.error("Can not grab container MEM stat ({0})".format(e))
<del> return ret
<del> # Return the stats
<del> return ret
<del>
<ide> def get_docker_memory(self, container_id, all_stats):
<ide> """Return the container MEMORY.
<ide>
<ide> def get_docker_memory(self, container_id, all_stats):
<ide> ret['max_usage'] = all_stats['memory_stats']['max_usage']
<ide> except KeyError as e:
<ide> # all_stats do not have MEM information
<del> logger.debug("Can not grab MEM usage for container {0} ({1}). Trying fallback method.".format(container_id, e))
<del> # Trying fallback to old grab method
<del> ret = self.get_docker_memory_old(container_id)
<add> logger.debug("Can not grab MEM usage for container {0} ({1})".format(container_id, e))
<ide> # Return the stats
<ide> return ret
<ide>
<ide> def msg_curse(self, args=None):
<ide> ret.append(self.curse_add_line(msg))
<ide> msg = '{0:>7}'.format('MEM')
<ide> ret.append(self.curse_add_line(msg))
<del> # msg = '{0:>6}'.format('Rx/s')
<del> # ret.append(self.curse_add_line(msg))
<del> # msg = '{0:>6}'.format('Tx/s')
<del> # ret.append(self.curse_add_line(msg))
<add> msg = '{0:>6}'.format('Rx/s')
<add> ret.append(self.curse_add_line(msg))
<add> msg = '{0:>6}'.format('Tx/s')
<add> ret.append(self.curse_add_line(msg))
<ide> msg = ' {0:8}'.format('Command')
<ide> ret.append(self.curse_add_line(msg))
<ide> # Data
<ide> def msg_curse(self, args=None):
<ide> msg = '{0:>7}'.format('?')
<ide> ret.append(self.curse_add_line(msg))
<ide> # NET RX/TX
<del> # for r in ['rx', 'tx']:
<del> # try:
<del> # value = self.auto_unit(int(container['network'][r] // container['network']['time_since_update'] * 8)) + "b"
<del> # msg = '{0:>6}'.format(value)
<del> # except KeyError:
<del> # msg = '{0:>6}'.format('?')
<del> # ret.append(self.curse_add_line(msg))
<add> for r in ['rx', 'tx']:
<add> try:
<add> value = self.auto_unit(int(container['network'][r] // container['network']['time_since_update'] * 8)) + "b"
<add> msg = '{0:>6}'.format(value)
<add> except KeyError:
<add> msg = '{0:>6}'.format('?')
<add> ret.append(self.curse_add_line(msg))
<ide> # Command
<ide> msg = ' {0}'.format(container['Command'])
<ide> ret.append(self.curse_add_line(msg))
<ide> def container_alert(self, status):
<ide> return 'CAREFUL'
<ide> else:
<ide> return 'OK'
<add>
<add>class ThreadDockerGrabber(threading.Thread):
<add> """
<add> Specific thread to grab docker stats.
<add>
<add> stats is a dict
<add> """
<add>
<add> def __init__(self, docker_client, container_id, refresh_time=3):
<add> """Init the class:
<add> docker_client: instance of Docker-py client
<add> container_id: Id of the container"""
<add> logger.debug("docker plugin - Create thread for container {}".format(container_id[:12]))
<add> super(ThreadDockerGrabber, self).__init__()
<add> # Refresh time for sub thread
<add> self._refresh_time = refresh_time
<add> # Event needed to stop properly the thread
<add> self._stop = threading.Event()
<add> # The docker-py return stats as a stream
<add> self._container_id = container_id
<add> self._stats_stream = docker_client.stats(container_id, decode=True)
<add> # The class return the stats as a dict
<add> self._stats = {}
<add>
<add> def run(self):
<add> """Function called to grab stats.
<add> Infinite loop, should be stopped by calling the stop() method"""
<add>
<add> is_stopped = False
<add> for i in self._stats_stream:
<add> self._stats = i
<add> countdown = Timer(self._refresh_time)
<add> while not countdown.finished() and not is_stopped:
<add> is_stopped = self.stopped()
<add> time.sleep(0.1)
<add> if is_stopped:
<add> break
<add>
<add> @property
<add> def stats(self):
<add> return self._stats
<add>
<add> @stats.setter
<add> def stats(self, value):
<add> self._stats = value
<add>
<add> def stop(self, timeout=None):
<add> logger.debug("docker plugin - Close thread for container {}".format(self._container_id[:12]))
<add> self._stop.set()
<add> super(ThreadDockerGrabber, self).join(timeout)
<add>
<add> def stopped(self):
<add> return self._stop.isSet()
<ide><path>glances/plugins/glances_plugin.py
<ide> def __init__(self, args=None, items_history_list=None):
<ide> # Init the views
<ide> self.views = dict()
<ide>
<add> def exit(self):
<add> """Method to be called when Glances exit"""
<add> logger.debug("Stop the {} plugin".format(self.plugin_name))
<add>
<ide> def __repr__(self):
<ide> """Return the raw stats."""
<ide> return self.stats | 4 |
Text | Text | clarify ci requirement in pr template [ci skip] | 2d239ad994ca0d2ee06547590218f6435d68c8d7 | <ide><path>.github/pull_request_template.md
<ide> Before submitting the PR make sure the following are checked:
<ide> * [ ] Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: `[Fix #issue-number]`
<ide> * [ ] Tests are added or updated if you fix a bug or add a feature.
<ide> * [ ] CHANGELOG files are updated for the changed libraries if there is a behavior change or additional feature. Minor bug fixes and documentation changes should not be included.
<del>* [ ] CI is passing.
<del> | 1 |
Javascript | Javascript | apply sideeffect at didmount on the client side | a0aaa933dec41da0cbb5c0f33e3f6e66df629d5d | <ide><path>lib/side-effect.js
<ide> export default function withSideEffect (reduceComponentsToState, handleStateChan
<ide>
<ide> constructor (props) {
<ide> super(props)
<add> if (!SideEffect.canUseDOM) {
<add> mountedInstances.add(this)
<add> emitChange(this)
<add> }
<add> }
<add> componentDidMount () {
<ide> mountedInstances.add(this)
<ide> emitChange(this)
<ide> }
<del>
<ide> componentDidUpdate () {
<ide> emitChange(this)
<ide> }
<ide><path>test/integration/basic/pages/dynamic/head.js
<add>import dynamic from 'next/dynamic'
<add>import Head from 'next/head'
<add>
<add>const Test = dynamic({
<add> loader: async () => {
<add> // component
<add> return () => {
<add> return <div className='dynamic-style'>
<add> <Head>
<add> <style dangerouslySetInnerHTML={{ __html: `
<add> .dynamic-style {
<add> background-color: green;
<add> height: 200px;
<add> }
<add> `}} />
<add> </Head>
<add> test
<add> </div>
<add> }
<add> },
<add> ssr: false
<add>})
<add>
<add>export default Test
<ide><path>test/integration/basic/test/dynamic.js
<ide> export default (context, render) => {
<ide> }
<ide> }
<ide> })
<add>
<add> it('should render the component Head content', async () => {
<add> let browser
<add> try {
<add> browser = await webdriver(context.appPort, '/dynamic/head')
<add> await check(() => browser.elementByCss('body').text(), /test/)
<add> const backgroundColor = await browser.elementByCss('.dynamic-style').getComputedCss('background-color')
<add> const height = await browser.elementByCss('.dynamic-style').getComputedCss('height')
<add> expect(height).toBe('200px')
<add> expect(backgroundColor).toBe('rgba(0, 128, 0, 1)')
<add> } finally {
<add> if (browser) {
<add> browser.close()
<add> }
<add> }
<add> })
<ide> })
<ide> describe('ssr:false option', () => {
<ide> it('Should render loading on the server side', async () => { | 3 |
Javascript | Javascript | apply correct hover styles | fa1b0db453c679320d97513692cf1aac4819da02 | <ide><path>src/core/core.controller.js
<ide> break;
<ide> case 'label':
<ide> for (var i = 0; i < this.lastActive.length; i++) {
<del> this.data.datasets[this.lastActive[0]._datasetIndex].controller.removeHoverStyle(this.lastActive[i], this.lastActive[i]._datasetIndex, this.lastActive[i]._index);
<add> this.data.datasets[this.lastActive[i]._datasetIndex].controller.removeHoverStyle(this.lastActive[i], this.lastActive[i]._datasetIndex, this.lastActive[i]._index);
<ide> }
<ide> break;
<ide> case 'dataset':
<ide> break;
<ide> case 'label':
<ide> for (var i = 0; i < this.active.length; i++) {
<del> this.data.datasets[this.active[0]._datasetIndex].controller.setHoverStyle(this.active[i]);
<add> this.data.datasets[this.active[i]._datasetIndex].controller.setHoverStyle(this.active[i]);
<ide> }
<ide> break;
<ide> case 'dataset': | 1 |
Java | Java | fix chrome debugging | 251a4086a76a62d74a20168955e7540816e906b5 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.java
<ide> public String getWebsocketProxyURL() {
<ide> * @return the host to use when connecting to the bundle server from the host itself.
<ide> */
<ide> private static String getHostForJSProxy() {
<del> return "localhost";
<add> return DEVICE_LOCALHOST;
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | apply fixes from styleci | 5db5288100817b036d315aa3941039280989a5c8 | <ide><path>tests/Foundation/Http/Middleware/TrimStringsTest.php
<ide>
<ide> namespace Illuminate\Tests\Foundation\Http\Middleware;
<ide>
<del>use Illuminate\Foundation\Http\Middleware\TrimStrings;
<ide> use Illuminate\Http\Request;
<ide> use PHPUnit\Framework\TestCase;
<add>use Illuminate\Foundation\Http\Middleware\TrimStrings;
<ide> use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
<ide>
<ide> class TrimStringsTest extends TestCase | 1 |
Javascript | Javascript | add helpful assertion when template is missing | 39875a4869d73ad34c165bbeecce0b4d4d15ab39 | <ide><path>packages/ember-glimmer/lib/renderer.js
<ide> class Renderer {
<ide> };
<ide> let { _env: env } = this;
<ide> let render = () => {
<add> assert(`You cannot render \`${self.value()}\` without a template.`, template);
<add>
<ide> let result = template.asEntryPoint().render(self, env, {
<ide> appendTo: parentElement,
<ide> dynamicScope | 1 |
Python | Python | add center_crop to imagefeatureextractomixin | 090e3e68963e64b1da55a8b704a3f1679f5968a8 | <ide><path>src/transformers/image_utils.py
<ide> def resize(self, image, size, resample=PIL.Image.BILINEAR):
<ide> image = self.to_pil_image(image)
<ide>
<ide> return image.resize(size, resample=resample)
<add>
<add> def center_crop(self, image, size):
<add> """
<add> Crops :obj:`image` to the given size using a center crop. Note that if the image is too small to be cropped to
<add> the size given, it will be padded (so the returned result has the size asked).
<add>
<add> Args:
<add> image (:obj:`PIL.Image.Image` or :obj:`np.ndarray` or :obj:`torch.Tensor`):
<add> The image to resize.
<add> size (:obj:`int` or :obj:`Tuple[int, int]`):
<add> The size to which crop the image.
<add> """
<add> self._ensure_format_supported(image)
<add> if not isinstance(size, tuple):
<add> size = (size, size)
<add>
<add> # PIL Image.size is (width, height) but NumPy array and torch Tensors have (height, width)
<add> image_shape = (image.size[1], image.size[0]) if isinstance(image, PIL.Image.Image) else image.shape[-2:]
<add> top = (image_shape[0] - size[0]) // 2
<add> bottom = top + size[0] # In case size is odd, (image_shape[0] + size[0]) // 2 won't give the proper result.
<add> left = (image_shape[1] - size[1]) // 2
<add> right = left + size[1] # In case size is odd, (image_shape[1] + size[1]) // 2 won't give the proper result.
<add>
<add> # For PIL Images we have a method to crop directly.
<add> if isinstance(image, PIL.Image.Image):
<add> return image.crop((left, top, right, bottom))
<add>
<add> # Check if all the dimensions are inside the image.
<add> if top >= 0 and bottom <= image_shape[0] and left >= 0 and right <= image_shape[1]:
<add> return image[..., top:bottom, left:right]
<add>
<add> # Otherwise, we may need to pad if the image is too small. Oh joy...
<add> new_shape = image.shape[:-2] + (max(size[0], image_shape[0]), max(size[1], image_shape[1]))
<add> if isinstance(image, np.ndarray):
<add> new_image = np.zeros_like(image, shape=new_shape)
<add> elif is_torch_tensor(image):
<add> new_image = image.new_zeros(new_shape)
<add>
<add> top_pad = (new_shape[-2] - image_shape[0]) // 2
<add> bottom_pad = top_pad + image_shape[0]
<add> left_pad = (new_shape[-1] - image_shape[1]) // 2
<add> right_pad = left_pad + image_shape[1]
<add> new_image[..., top_pad:bottom_pad, left_pad:right_pad] = image
<add>
<add> top += top_pad
<add> bottom += top_pad
<add> left += left_pad
<add> right += left_pad
<add>
<add> return new_image[
<add> ..., max(0, top) : min(new_image.shape[-2], bottom), max(0, left) : min(new_image.shape[-1], right)
<add> ]
<ide><path>tests/test_image_utils.py
<ide> def test_normalize_tensor(self):
<ide>
<ide> normalized_tensor = feature_extractor.normalize(tensor, torch.tensor(mean), torch.tensor(std))
<ide> self.assertTrue(torch.equal(normalized_tensor, expected))
<add>
<add> def test_center_crop_image(self):
<add> feature_extractor = ImageFeatureExtractionMixin()
<add> image = get_random_image(16, 32)
<add>
<add> # Test various crop sizes: bigger on all dimensions, on one of the dimensions only and on both dimensions.
<add> crop_sizes = [8, (8, 64), 20, (32, 64)]
<add> for size in crop_sizes:
<add> cropped_image = feature_extractor.center_crop(image, size)
<add> self.assertTrue(isinstance(cropped_image, PIL.Image.Image))
<add>
<add> # PIL Image.size is transposed compared to NumPy or PyTorch (width first instead of height first).
<add> expected_size = (size, size) if isinstance(size, int) else (size[1], size[0])
<add> self.assertEqual(cropped_image.size, expected_size)
<add>
<add> def test_center_crop_array(self):
<add> feature_extractor = ImageFeatureExtractionMixin()
<add> image = get_random_image(16, 32)
<add> array = feature_extractor.to_numpy_array(image)
<add>
<add> # Test various crop sizes: bigger on all dimensions, on one of the dimensions only and on both dimensions.
<add> crop_sizes = [8, (8, 64), 20, (32, 64)]
<add> for size in crop_sizes:
<add> cropped_array = feature_extractor.center_crop(array, size)
<add> self.assertTrue(isinstance(cropped_array, np.ndarray))
<add>
<add> expected_size = (size, size) if isinstance(size, int) else size
<add> self.assertEqual(cropped_array.shape[-2:], expected_size)
<add>
<add> # Check result is consistent with PIL.Image.crop
<add> cropped_image = feature_extractor.center_crop(image, size)
<add> self.assertTrue(np.array_equal(cropped_array, feature_extractor.to_numpy_array(cropped_image)))
<add>
<add> @require_torch
<add> def test_center_crop_tensor(self):
<add> feature_extractor = ImageFeatureExtractionMixin()
<add> image = get_random_image(16, 32)
<add> array = feature_extractor.to_numpy_array(image)
<add> tensor = torch.tensor(array)
<add>
<add> # Test various crop sizes: bigger on all dimensions, on one of the dimensions only and on both dimensions.
<add> crop_sizes = [8, (8, 64), 20, (32, 64)]
<add> for size in crop_sizes:
<add> cropped_tensor = feature_extractor.center_crop(tensor, size)
<add> self.assertTrue(isinstance(cropped_tensor, torch.Tensor))
<add>
<add> expected_size = (size, size) if isinstance(size, int) else size
<add> self.assertEqual(cropped_tensor.shape[-2:], expected_size)
<add>
<add> # Check result is consistent with PIL.Image.crop
<add> cropped_image = feature_extractor.center_crop(image, size)
<add> self.assertTrue(torch.equal(cropped_tensor, torch.tensor(feature_extractor.to_numpy_array(cropped_image)))) | 2 |
PHP | PHP | fix deprecation warnings in client/auth | dbd0c07ec69d29bc7c97bb2acf31fcbb0c48e208 | <ide><path>src/Http/Client/Auth/Digest.php
<ide> protected function _generateHeader(Request $request, $credentials)
<ide> {
<ide> $path = $request->getUri()->getPath();
<ide> $a1 = md5($credentials['username'] . ':' . $credentials['realm'] . ':' . $credentials['password']);
<del> $a2 = md5($request->method() . ':' . $path);
<add> $a2 = md5($request->getMethod() . ':' . $path);
<ide> $nc = null;
<ide>
<ide> if (empty($credentials['qop'])) {
<ide><path>tests/TestCase/Http/Client/Auth/OauthTest.php
<ide> public function testPlainTextSigning()
<ide> */
<ide> public function testBaseStringNormalizeUrl()
<ide> {
<del> $request = new Request();
<del> $request->url('HTTP://exAmple.com:80/parts/foo');
<add> $request = new Request('HTTP://exAmple.com:80/parts/foo');
<ide>
<ide> $auth = new Oauth();
<ide> $creds = [];
<ide> public function testBaseStringNormalizeUrl()
<ide> */
<ide> public function testBaseStringWithQueryString()
<ide> {
<del> $request = new Request();
<del> $request->url('http://example.com/search?q=pogo&cat=2');
<add> $request = new Request('http://example.com/search?q=pogo&cat=2');
<ide>
<ide> $auth = new Oauth();
<ide> $values = [
<ide> public function testBaseStringWithQueryString()
<ide> */
<ide> public function testBaseStringWithPostDataNestedArrays()
<ide> {
<del> $request = new Request();
<del> $request->url('http://example.com/search?q=pogo')
<del> ->method(Request::METHOD_POST)
<del> ->body([
<add> $request = new Request(
<add> 'http://example.com/search?q=pogo',
<add> Request::METHOD_POST,
<add> [],
<add> [
<ide> 'search' => [
<ide> 'filters' => [
<ide> 'field' => 'date',
<ide> 'value' => 'one two'
<ide> ]
<ide> ]
<del> ]);
<add> ]
<add> );
<ide>
<ide> $auth = new Oauth();
<ide> $values = [
<ide> public function testBaseStringWithPostDataNestedArrays()
<ide> */
<ide> public function testBaseStringWithPostData()
<ide> {
<del> $request = new Request();
<del> $request->url('http://example.com/search?q=pogo')
<del> ->method(Request::METHOD_POST)
<del> ->body([
<add> $request = new Request(
<add> 'http://example.com/search?q=pogo',
<add> Request::METHOD_POST,
<add> [],
<add> [
<ide> 'address' => 'post',
<ide> 'zed' => 'last',
<ide> 'tags' => ['oauth', 'cake']
<del> ]);
<add> ]
<add> );
<ide>
<ide> $auth = new Oauth();
<ide> $values = [
<ide> public function testBaseStringWithPostData()
<ide> */
<ide> public function testHmacSigning()
<ide> {
<del> $request = new Request();
<del> $request->url('http://photos.example.net/photos')
<del> ->body([
<del> 'file' => 'vacation.jpg',
<del> 'size' => 'original'
<del> ]);
<add> $request = new Request(
<add> 'http://photos.example.net/photos',
<add> 'GET',
<add> [],
<add> ['file' => 'vacation.jpg', 'size' => 'original']
<add> );
<ide>
<ide> $options = [
<ide> 'consumerKey' => 'dpf43f3p2l4k3l03',
<ide> public function testHmacSigning()
<ide> */
<ide> public function testRsaSigningString()
<ide> {
<del> $request = new Request();
<del> $request->url('http://photos.example.net/photos')
<del> ->body([
<del> 'file' => 'vacaction.jpg',
<del> 'size' => 'original'
<del> ]);
<add> $request = new Request(
<add> 'http://photos.example.net/photos',
<add> 'GET',
<add> [],
<add> ['file' => 'vacaction.jpg', 'size' => 'original']
<add> );
<ide> $privateKey = $this->privateKeyString;
<ide>
<ide> $options = [
<ide> public function testRsaSigningString()
<ide> $auth = new Oauth();
<ide> $request = $auth->authentication($request, $options);
<ide>
<del> $result = $request->header('Authorization');
<add> $result = $request->getHeaderLine('Authorization');
<ide> $expected = 'jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=';
<ide> $this->assertContains(
<ide> 'oauth_signature="' . $expected . '"',
<ide> public function testRsaSigningString()
<ide> */
<ide> public function testRsaSigningFile()
<ide> {
<del> $request = new Request();
<del> $request->url('http://photos.example.net/photos')
<del> ->body([
<del> 'file' => 'vacaction.jpg',
<del> 'size' => 'original'
<del> ]);
<add> $request = new Request(
<add> 'http://photos.example.net/photos',
<add> 'GET',
<add> [],
<add> ['file' => 'vacaction.jpg', 'size' => 'original']
<add> );
<ide> $privateKey = fopen(TEST_APP . DS . 'config' . DS . 'key.pem', 'r');
<ide>
<ide> $options = [
<ide> public function testRsaSigningFile()
<ide> $auth = new Oauth();
<ide> $request = $auth->authentication($request, $options);
<ide>
<del> $result = $request->header('Authorization');
<add> $result = $request->getHeaderLine('Authorization');
<ide> $expected = 'jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=';
<ide> $this->assertContains(
<ide> 'oauth_signature="' . $expected . '"',
<ide> public function testRsaSigningFile()
<ide> */
<ide> public function testRsaSigningWithPassphraseString()
<ide> {
<del> $request = new Request();
<del> $request->url('http://photos.example.net/photos')
<del> ->body([
<del> 'file' => 'vacaction.jpg',
<del> 'size' => 'original'
<del> ]);
<add> $request = new Request(
<add> 'http://photos.example.net/photos',
<add> 'GET',
<add> [],
<add> ['file' => 'vacaction.jpg', 'size' => 'original']
<add> );
<ide> $privateKey = fopen(TEST_APP . DS . 'config' . DS . 'key_with_passphrase.pem', 'r');
<ide> $passphrase = 'fancy-cakephp-passphrase';
<ide>
<ide> public function testRsaSigningWithPassphraseString()
<ide> $auth = new Oauth();
<ide> $request = $auth->authentication($request, $options);
<ide>
<del> $result = $request->header('Authorization');
<add> $result = $request->getHeaderLine('Authorization');
<ide> $expected = 'jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=';
<ide> $this->assertContains(
<ide> 'oauth_signature="' . $expected . '"',
<ide> public function testRsaSigningWithPassphraseString()
<ide> */
<ide> public function testRsaSigningStringWithPassphraseString()
<ide> {
<del> $request = new Request();
<del> $request->url('http://photos.example.net/photos')
<del> ->body([
<del> 'file' => 'vacaction.jpg',
<del> 'size' => 'original'
<del> ]);
<add> $request = new Request(
<add> 'http://photos.example.net/photos',
<add> 'GET',
<add> [],
<add> ['file' => 'vacaction.jpg', 'size' => 'original']
<add> );
<ide> $privateKey = $this->privateKeyStringEnc;
<ide> $passphrase = 'fancy-cakephp-passphrase';
<ide>
<ide> public function testRsaSigningStringWithPassphraseString()
<ide> $auth = new Oauth();
<ide> $request = $auth->authentication($request, $options);
<ide>
<del> $result = $request->header('Authorization');
<add> $result = $request->getHeaderLine('Authorization');
<ide> $expected = 'jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=';
<ide> $this->assertContains(
<ide> 'oauth_signature="' . $expected . '"',
<ide> public function testRsaSigningWithPassphraseFile()
<ide> {
<ide> $this->skipIf(PHP_EOL != "\n", 'Just the line ending "\n" is supported. You can run the test again e.g. on a linux system.');
<ide>
<del> $request = new Request();
<del> $request->url('http://photos.example.net/photos')
<del> ->body([
<del> 'file' => 'vacaction.jpg',
<del> 'size' => 'original'
<del> ]);
<add> $request = new Request(
<add> 'http://photos.example.net/photos',
<add> 'GET',
<add> [],
<add> ['file' => 'vacaction.jpg', 'size' => 'original']
<add> );
<ide> $privateKey = fopen(TEST_APP . DS . 'config' . DS . 'key_with_passphrase.pem', 'r');
<ide> $passphrase = fopen(TEST_APP . DS . 'config' . DS . 'key_passphrase_lf', 'r');
<ide>
<ide> public function testRsaSigningWithPassphraseFile()
<ide> $auth = new Oauth();
<ide> $request = $auth->authentication($request, $options);
<ide>
<del> $result = $request->header('Authorization');
<add> $result = $request->getHeaderLine('Authorization');
<ide> $expected = 'jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=';
<ide> $this->assertContains(
<ide> 'oauth_signature="' . $expected . '"',
<ide> public function testRsaSigningStringWithPassphraseFile()
<ide> {
<ide> $this->skipIf(PHP_EOL != "\n", 'Just the line ending "\n" is supported. You can run the test again e.g. on a linux system.');
<ide>
<del> $request = new Request();
<del> $request->url('http://photos.example.net/photos')
<del> ->body([
<del> 'file' => 'vacaction.jpg',
<del> 'size' => 'original'
<del> ]);
<add> $request = new Request(
<add> 'http://photos.example.net/photos',
<add> 'GET',
<add> [],
<add> ['file' => 'vacaction.jpg', 'size' => 'original']
<add> );
<ide> $privateKey = $this->privateKeyStringEnc;
<ide> $passphrase = fopen(TEST_APP . DS . 'config' . DS . 'key_passphrase_lf', 'r');
<ide>
<ide> public function testRsaSigningStringWithPassphraseFile()
<ide> $auth = new Oauth();
<ide> $request = $auth->authentication($request, $options);
<ide>
<del> $result = $request->header('Authorization');
<add> $result = $request->getHeaderLine('Authorization');
<ide> $expected = 'jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=';
<ide> $this->assertContains(
<ide> 'oauth_signature="' . $expected . '"', | 2 |
Java | Java | fix exception handling result handler resolution | 95abd18fea067b271bf50252b0a741c5850cab93 | <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/DispatcherHandler.java
<ide> private Mono<HandlerResult> invokeHandler(ServerWebExchange exchange, Object han
<ide> private Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
<ide> return getResultHandler(result).handleResult(exchange, result)
<ide> .otherwise(ex -> result.applyExceptionHandler(ex).then(exceptionResult ->
<del> getResultHandler(result).handleResult(exchange, exceptionResult)));
<add> getResultHandler(exceptionResult).handleResult(exchange, exceptionResult)));
<ide> }
<ide>
<ide> private HandlerResultHandler getResultHandler(HandlerResult handlerResult) {
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java
<ide> import org.springframework.context.annotation.ComponentScan;
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.ResponseEntity;
<ide> import org.springframework.web.bind.annotation.ExceptionHandler;
<ide> import org.springframework.web.bind.annotation.GetMapping;
<ide> import org.springframework.web.bind.annotation.RestController;
<ide> protected ApplicationContext initApplicationContext() {
<ide>
<ide> @Test
<ide> public void controllerThrowingException() throws Exception {
<del> String expected = "Recovered from error: Boo";
<add> String expected = "Recovered from error: State";
<ide> assertEquals(expected, performGet("/thrown-exception", new HttpHeaders(), String.class).getBody());
<ide> }
<ide>
<ide> @Test
<ide> public void controllerReturnsMonoError() throws Exception {
<del> String expected = "Recovered from error: Boo";
<add> String expected = "Recovered from error: Argument";
<ide> assertEquals(expected, performGet("/mono-error", new HttpHeaders(), String.class).getBody());
<ide> }
<ide>
<ide> private static class TestController {
<ide>
<ide> @GetMapping("/thrown-exception")
<ide> public Publisher<String> handleAndThrowException() {
<del> throw new IllegalStateException("Boo");
<add> throw new IllegalStateException("State");
<ide> }
<ide>
<ide> @GetMapping("/mono-error")
<ide> public Publisher<String> handleWithError() {
<del> return Mono.error(new IllegalStateException("Boo"));
<add> return Mono.error(new IllegalArgumentException("Argument"));
<ide> }
<ide>
<ide> @ExceptionHandler
<del> public Publisher<String> handleException(IllegalStateException ex) {
<add> public Publisher<String> handleArgumentException(IllegalArgumentException ex) {
<ide> return Mono.just("Recovered from error: " + ex.getMessage());
<ide> }
<ide>
<add> @ExceptionHandler
<add> public ResponseEntity<Publisher<String>> handleStateException(IllegalStateException ex) {
<add> return ResponseEntity.ok(Mono.just("Recovered from error: " + ex.getMessage()));
<add> }
<add>
<ide> }
<ide>
<ide> } | 2 |
Text | Text | update ruby version to 2.3.0p0 | a48f97e0e611496f96882a5383756a11758c7596 | <ide><path>guides/source/getting_started.md
<ide> current version of Ruby installed:
<ide>
<ide> ```bash
<ide> $ ruby -v
<del>ruby 2.2.2p95
<add>ruby 2.3.0p0
<ide> ```
<ide>
<ide> TIP: A number of tools exist to help you quickly install Ruby and Ruby | 1 |
Text | Text | remove reference to annotated todos - fixes #583 | 7ad0873be294d9d365dea74de9d51e91083b9be5 | <ide><path>README.md
<ide> Hopefully you can see how all three of these powerful tools work together: start
<ide>
<ide> For new users, we recommend downloading the [Ember.js Starter Kit](https://github.com/emberjs/starter-kit/downloads), which includes everything you need to get started.
<ide>
<del>We also recommend that you check out the [annotated Todos example](http://annotated-todos.strobeapp.com/), which shows you the best practices for architecting an MVC-based web application. You can also [browse or fork the code on Github](https://github.com/emberjs/todos).
<del>
<ide> # Building Ember.js
<ide>
<ide> NOTE: Due to the rename, these instructions may be in flux | 1 |
Text | Text | improve portuguese translation of compilers guide | d5046d6e82de535c8e8a6fdec52d1ca5f70b7198 | <ide><path>guide/portuguese/computer-science/compilers/index.md
<ide> title: Compilers
<ide> localeTitle: Compiladores
<ide> ---
<add>
<ide> ## Compiladores
<ide>
<ide> ### Programação
<ide>
<del>Na sua essência, um computador barebones (também conhecido como computador de programa armazenado) nada mais é do que uma máquina que sabe ler etapas escritas em um conjunto de instruções fixo e executá-las. O conjunto de instruções que um computador entende é muito específico para ele. Isso também é conhecido como linguagem de máquina ( **opcodes** ). Linguagem de máquina é muitas vezes referida como código binário.
<add>Na sua essência, um computador barebones (também conhecido como computador de programa armazenado) nada mais é do que uma máquina que sabe ler etapas escritas em um conjunto de instruções fixo e executá-las. O conjunto de instruções que um computador entende é muito específico para ele. Isso também é conhecido como linguagem de máquina (**opcodes**). Linguagem de máquina é muitas vezes referida como código binário.
<ide>
<del>Humanos interagem com computadores usando **Programas** . Um programa é simplesmente uma sequência de opcodes fornecidos ao computador juntamente com dados que são necessários para executar os opcodes.
<add>Humanos interagem com computadores usando **Programas**. Um programa é simplesmente uma sequência de opcodes fornecidos ao computador juntamente com dados que são necessários para executar os opcodes.
<ide>
<ide> Por exemplo,
<add>
<ide> ```
<del>ADD 10, 20 // ADD is the Opcode
<del> // and 10, 20 are the two operands(data)
<del> // needed for the ADD instruction to be executed successfully
<add>ADD 10, 20 // ADD é o Opcode (código da operação)
<add> // e 10, 20 são os dois operandos (dados)
<add> // necessários para que a instrução ADD seja executada com sucesso
<ide> ```
<ide>
<del>Os humanos desenvolvem programas para resolver problemas complexos. Observando como os opcodes são simples, se tentarmos desenvolver programas usando apenas opcodes, será muito complicado e difícil de depurar. Para resolver este problema, linguagens de alto nível como C / C ++, Python, Java, Javascript, etc foram desenvolvidas.
<add>Os humanos desenvolvem programas para resolver problemas complexos. Observando como os opcodes são simples, se tentarmos desenvolver programas usando apenas opcodes, será muito complicado e difícil de depurar. Para resolver este problema, linguagens de alto nível como C/C++, Python, Java, Javascript, etc foram desenvolvidas.
<ide>
<ide> Agora, linguagens de alto nível não são adequadas para execução por computadores. Assim, surgiu a necessidade de um tradutor que pudesse digerir os programas de linguagem de alto nível e convertê-los em instruções de linguagem de máquina adequadas para execução por um computador.
<ide>
<del>#### \[HUMANOS\] -> \[Programas de idiomas de alto nível\] -> \[Tradutor\] -> \[Linguagem de máquina\] -> \[Computador\]
<add>#### \[HUMANOS\] -> \[Programas em linguagem de alto nível\] -> \[Tradutor\] -> \[Linguagem de máquina\] -> \[Computador\]
<ide>
<ide> Um **compilador** é um tipo de programa tradutor, que traduz linguagens de alto nível em código binário, que não é nada além de 1s e 0s. Quando você executa seu código-fonte, um compilador traduz todo o código primeiro e depois produz o código binário. Então o computador pega o código binário e o executa.
<ide>
<ide> Se houver erros no seu código-fonte, o compilador detecta e sinaliza-os. Isso i
<ide>
<ide> A maioria dos compiladores divide-se em três estágios principais: Análise, Transformação e Geração de Código
<ide>
<del>1. _A análise_ está tomando código bruto e transformando-o em uma representação mais abstrata do código.
<del>2. _A transformação_ leva essa representação abstrata e manipula para fazer o que o compilador quiser.
<del>3. _Geração de código_ leva a representação transformada do código e transforma-lo em novo código.
<add>1. _Análise (Parsing)_ é tomar código bruto e transformá-lo em uma representação mais abstrata do código.
<add>2. A _Transformação_ pega essa representação abstrata e a manipula para fazer o que o compilador quiser.
<add>3. A _Geração de Código_ pega a representação transformada do código e o transforma em novo código.
<ide>
<ide> #### Análise
<ide>
<del>A análise normalmente é dividida em duas fases: **Análise Lexical** e **Análise Sintática** .
<add>A análise normalmente é dividida em duas fases: **Análise Lexical** e **Análise Sintática**.
<add>
<add>A _Análise Lexical_ pega o código bruto e o separa em coisas chamadas de tokens por uma coisa chamada tokenizer (ou lexer).
<ide>
<del>_A análise lexical_ pega o código bruto e o separa nessas coisas chamadas de tokens por uma coisa chamada tokenizer (ou lexer).
<ide> ```
<del>Tokens are an array of tiny little objects that describe an isolated piece of the syntax.
<del> They could be numbers, labels, punctuation, operators, etc.
<add>Tokens são uma lista de pequenos objetos que descrevem uma peça isolada da sintaxe.
<add>Eles podem ser números, rótulos, pontuação, operadores, etc.
<ide> ```
<ide>
<del>_A análise sintática_ pega os tokens e os reformata em uma representação que descreve cada parte da sintaxe e sua relação com o outro. Isso é conhecido como uma representação intermediária ou Abstract Syntax Tree.
<add>A _Análise Sintática_ pega os tokens e os reformata em uma representação que descreve cada parte da sintaxe e sua relação com as outras. Isso é conhecido como uma representação intermediária ou Árvore de Sintaxe Abstrata.
<add>
<ide> ```
<del>An Abstract Syntax Tree, or AST for short, is a deeply nested object.
<del> It represents code in a way that is both easy to work with and tells us a lot of information.
<add>Uma Árvore de Sintaxe Abstrata (ou *Abstract Syntax Tree*, AST) é um objeto profundamente aninhado.
<add>Ela representa o código de uma maneira que é simples de trabalhar e nos fornece muitas informações.
<ide> ```
<ide>
<ide> #### Transformação
<ide>
<del>O próximo tipo de estágio para um compilador é a transformação. Novamente, isso apenas pega a AST da última etapa e faz alterações nela. Ele pode manipular o AST na mesma língua ou pode traduzi-lo em um idioma totalmente novo.
<add>O próximo tipo de estágio para um compilador é a transformação. Novamente, isso apenas pega a AST da última etapa e faz alterações nela. Ele pode manipular o AST na mesma linguagem ou pode traduzi-lo para uma linguagem totalmente nova.
<ide>
<ide> #### Geração de Código
<ide>
<ide> Todos os compiladores precisam executar estas etapas. A maioria dos compiladores
<ide>
<ide> #### Mais Informações:
<ide>
<del>["A Gentler Introduction to Programming", de Matt Adesanya,](https://medium.freecodecamp.org/a-gentler-introduction-to-programming-707453a79ee8) abrange compiladores versus intérpretes, juntamente com outros conceitos básicos de programação.
<ide>\ No newline at end of file
<add>["A Gentler Introduction to Programming", de Matt Adesanya,](https://medium.freecodecamp.org/a-gentler-introduction-to-programming-707453a79ee8) abrange compiladores versus intérpretes, juntamente com outros conceitos básicos de programação. | 1 |
Python | Python | fix typo in comments | 6b24281229e4ec0754f79735e398730d9d58e8af | <ide><path>src/transformers/modeling_bert.py
<ide> def forward(
<ide> # ourselves in which case we just need to make it broadcastable to all heads.
<ide> extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device)
<ide>
<del> # If a 2D ou 3D attention mask is provided for the cross-attention
<del> # we need to make broadcastabe to [batch_size, num_heads, seq_length, seq_length]
<add> # If a 2D or 3D attention mask is provided for the cross-attention
<add> # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
<ide> if self.config.is_decoder and encoder_hidden_states is not None:
<ide> encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
<ide> encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) | 1 |
Javascript | Javascript | fix undefined curvenode | e0fb997c502adf4d1853d87fdc66ecf5d7e08af4 | <ide><path>examples/js/loaders/FBXLoader.js
<ide>
<ide> }
<ide>
<del> console.log( FBXTree );
<add> // console.log( FBXTree );
<ide>
<ide> var textureLoader = new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ).setCrossOrigin( this.crossOrigin );
<ide>
<ide> var curveNodesMap = parseAnimationCurveNodes( FBXTree );
<ide>
<ide> parseAnimationCurves( FBXTree, connections, curveNodesMap );
<add>
<ide> var layersMap = parseAnimationLayers( FBXTree, connections, curveNodesMap );
<ide> var rawClips = parseAnimStacks( FBXTree, connections, layersMap );
<ide>
<ide>
<ide> curveNodesMap.get( animationCurveID ).curves[ 'z' ] = animationCurve;
<ide>
<del> } else if ( animationCurveRelationship.match( /d|DeformPercent/ ) ) {
<add> } else if ( animationCurveRelationship.match( /d|DeformPercent/ ) && curveNodesMap.has( animationCurveID ) ) {
<ide>
<ide> curveNodesMap.get( animationCurveID ).curves[ 'morph' ] = animationCurve;
<ide> | 1 |
PHP | PHP | adjust coding style | eb9d915f3d3b0e01d784b5f844ceaf0625fa6c47 | <ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function getFresh($columns = array('*'))
<ide> */
<ide> protected function runSelect()
<ide> {
<del> if ($this->useWritePdo) {
<add> if ($this->useWritePdo)
<add> {
<ide> return $this->connection->select($this->toSql(), $this->getBindings(), false);
<ide> }
<ide>
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> protected function getSqlServerBuilder()
<ide> return new Builder(m::mock('Illuminate\Database\ConnectionInterface'), $grammar, $processor);
<ide> }
<ide>
<add>
<ide> protected function getMySqlBuilderWithProcessor()
<ide> {
<ide> $grammar = new Illuminate\Database\Query\Grammars\MySqlGrammar; | 2 |
Javascript | Javascript | remove footer and nav from certs | 293e58cc235db6d313a16e03e18739362f89a250 | <ide><path>client/gatsby-browser.js
<ide> import { Provider } from 'react-redux';
<ide> import { createStore } from './src/redux/createStore';
<ide> import AppMountNotifier from './src/components/AppMountNotifier';
<ide> import GuideNavContextProvider from './src/contexts/GuideNavigationContext';
<del>import DefaultLayout from './src/components/layouts/Default';
<del>import GuideLayout from './src/components/layouts/Guide';
<add>import {
<add> CertificationLayout,
<add> DefaultLayout,
<add> GuideLayout
<add>} from './src/components/layouts';
<ide>
<ide> const store = createStore();
<ide>
<ide> export const wrapPageElement = ({ element, props }) => {
<ide> </DefaultLayout>
<ide> );
<ide> }
<add> if (/^\/certification(\/.*)*/.test(pathname)) {
<add> return <CertificationLayout>{element}</CertificationLayout>;
<add> }
<ide> if (/^\/guide(\/.*)*/.test(pathname)) {
<ide> return (
<ide> <DefaultLayout>
<ide><path>client/gatsby-ssr.js
<ide> import headComponents from './src/head';
<ide> import { createStore } from './src/redux/createStore';
<ide>
<ide> import GuideNavContextProvider from './src/contexts/GuideNavigationContext';
<del>import DefaultLayout from './src/components/layouts/Default';
<del>import GuideLayout from './src/components/layouts/Guide';
<add>import {
<add> CertificationLayout,
<add> DefaultLayout,
<add> GuideLayout
<add>} from './src/components/layouts';
<ide>
<ide> const store = createStore();
<ide>
<ide> export const wrapPageElement = ({ element, props }) => {
<ide> </DefaultLayout>
<ide> );
<ide> }
<add> if (/^\/certification(\/.*)*/.test(pathname)) {
<add> return <CertificationLayout>{element}</CertificationLayout>;
<add> }
<ide> if (/^\/guide(\/.*)*/.test(pathname)) {
<ide> return (
<ide> <DefaultLayout>
<ide><path>client/src/components/layouts/Certification.js
<add>import React, { Fragment } from 'react';
<add>import PropTypes from 'prop-types';
<add>
<add>function CertificationLayout({ children }) {
<add> return <Fragment>{children}</Fragment>;
<add>}
<add>
<add>CertificationLayout.displayName = 'CertificationLayout';
<add>CertificationLayout.propTypes = { children: PropTypes.any };
<add>
<add>export default CertificationLayout;
<ide><path>client/src/components/layouts/index.js
<add>export { default as CertificationLayout } from './Certification';
<add>export { default as DefaultLayout } from './Default';
<add>export { default as GuideLayout } from './Guide';
<add>export { default as LearnLayout } from './Learn'; | 4 |
Python | Python | fix warning for gradient_checkpointing | 83d3dc0f6f8ae03e01aa5acacf88e79b2c1ecd06 | <ide><path>src/transformers/configuration_utils.py
<ide> def __init__(self, **kwargs):
<ide> self.transformers_version = kwargs.pop("transformers_version", None)
<ide>
<ide> # Deal with gradient checkpointing
<del> if kwargs.get("gradient_checkpointing", True):
<add> if kwargs.get("gradient_checkpointing", False):
<ide> warnings.warn(
<ide> "Passing `gradient_checkpointing` to a config initialization is deprecated and will be removed in v5 "
<ide> "Transformers. Using `model.gradient_checkpointing_enable()` instead, or if you are using the " | 1 |
Javascript | Javascript | remove redundant code | e73f4549ecc3978099d8a29c62f8c168887248f2 | <ide><path>src/renderers/webgl/WebGLGeometries.js
<ide> function WebGLGeometries( gl, attributes, info ) {
<ide>
<ide> delete geometries[ geometry.id ];
<ide>
<del> // TODO Remove duplicate code
<del>
<del> var attribute = wireframeAttributes[ geometry.id ];
<del>
<del> if ( attribute ) {
<del>
<del> attributes.remove( attribute );
<del> delete wireframeAttributes[ geometry.id ];
<del>
<del> }
<del>
<ide> attribute = wireframeAttributes[ buffergeometry.id ];
<ide>
<ide> if ( attribute ) { | 1 |
Ruby | Ruby | use correct gemfile in `bin/setup` test | 99620d1534ffb47d1496ccc1efae60a90967671c | <ide><path>railties/test/application/bin_setup_test.rb
<ide> class BinSetupTest < ActiveSupport::TestCase
<ide>
<ide> def setup
<ide> build_app
<add>
<add> create_gemfile
<add> update_boot_file_to_use_bundler
<add> @old_gemfile_env = ENV["BUNDLE_GEMFILE"]
<add> ENV["BUNDLE_GEMFILE"] = app_path + "/Gemfile"
<ide> end
<ide>
<ide> def teardown
<ide> teardown_app
<add>
<add> ENV["BUNDLE_GEMFILE"] = @old_gemfile_env
<ide> end
<ide>
<ide> def test_bin_setup
<ide> def test_bin_setup_output
<ide> OUTPUT
<ide> end
<ide> end
<add>
<add> private
<add> def create_gemfile
<add> app_file("Gemfile", "source 'https://rubygems.org'")
<add> app_file("Gemfile", "gem 'rails', path: '#{RAILS_FRAMEWORK_ROOT}'", "a")
<add> app_file("Gemfile", "gem 'sqlite3'", "a")
<add> end
<add>
<add> def update_boot_file_to_use_bundler
<add> app_file("config/boot.rb", "require 'bundler/setup'")
<add> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | use common.port in simple/test-http-timeout | 586e160a258336663bdf7f063aae9602fe9e1dc9 | <ide><path>test/simple/test-http-timeout.js
<ide> var assert = require('assert');
<ide>
<ide> var http = require('http');
<ide>
<del>var port = 12345;
<add>var port = common.PORT;
<add>
<ide> var server = http.createServer(function(req, res) {
<ide> res.writeHead(200, {'Content-Type': 'text/plain'});
<ide> res.end('OK'); | 1 |
PHP | PHP | add dispatch_sync helper | 97fe4a1a7cb8dd8982a2c8af98154dd030fe6c95 | <ide><path>src/Illuminate/Bus/Dispatcher.php
<ide> public function dispatch($command)
<ide> /**
<ide> * Dispatch a command to its appropriate handler in the current process.
<ide> *
<del> * Queuable jobs will be dispatched to the "sync" queue.
<add> * Queueable jobs will be dispatched to the "sync" queue.
<ide> *
<ide> * @param mixed $command
<ide> * @param mixed $handler
<ide><path>src/Illuminate/Contracts/Bus/Dispatcher.php
<ide> public function dispatch($command);
<ide> /**
<ide> * Dispatch a command to its appropriate handler in the current process.
<ide> *
<del> * Queuable jobs will be dispatched to the "sync" queue.
<add> * Queueable jobs will be dispatched to the "sync" queue.
<ide> *
<ide> * @param mixed $command
<ide> * @param mixed $handler
<ide><path>src/Illuminate/Foundation/Bus/Dispatchable.php
<ide> public static function dispatchUnless($boolean, ...$arguments)
<ide> /**
<ide> * Dispatch a command to its appropriate handler in the current process.
<ide> *
<del> * Queuable jobs will be dispatched to the "sync" queue.
<add> * Queueable jobs will be dispatched to the "sync" queue.
<ide> *
<ide> * @return mixed
<ide> */
<ide><path>src/Illuminate/Foundation/helpers.php
<ide> function dispatch($job)
<ide> }
<ide> }
<ide>
<add>if (! function_exists('dispatch_sync')) {
<add> /**
<add> * Dispatch a command to its appropriate handler in the current process.
<add> *
<add> * Queueable jobs will be dispatched to the "sync" queue.
<add> *
<add> * @param mixed $job
<add> * @param mixed $handler
<add> * @return mixed
<add> */
<add> function dispatch_sync($job, $handler = null)
<add> {
<add> return app(Dispatcher::class)->dispatchSync($job, $handler);
<add> }
<add>}
<add>
<ide> if (! function_exists('dispatch_now')) {
<ide> /**
<ide> * Dispatch a command to its appropriate handler in the current process.
<ide><path>src/Illuminate/Support/Testing/Fakes/BusFake.php
<ide> public function dispatch($command)
<ide> /**
<ide> * Dispatch a command to its appropriate handler in the current process.
<ide> *
<del> * Queuable jobs will be dispatched to the "sync" queue.
<add> * Queueable jobs will be dispatched to the "sync" queue.
<ide> *
<ide> * @param mixed $command
<ide> * @param mixed $handler | 5 |
Mixed | Ruby | make csrf failure logging optional/configurable | 67584c6ae37c88f8abba6f4fbdeedc7c1a6dfa1b | <ide><path>actionpack/CHANGELOG.md
<ide> `default_url_options` methods.
<ide>
<ide> *Tony Wooster*
<add>* Make logging of CSRF failures optional (but on by default) with the
<add> `log_warning_on_csrf_failure` configuration setting in
<add> ActionController::RequestForgeryProtection
<add>
<add> *John Barton*
<ide>
<ide> Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/actionpack/CHANGELOG.md) for previous changes.
<ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb
<ide> module RequestForgeryProtection
<ide> config_accessor :allow_forgery_protection
<ide> self.allow_forgery_protection = true if allow_forgery_protection.nil?
<ide>
<add> # Controls whether a CSRF failure logs a warning. On by default.
<add> config_accessor :log_warning_on_csrf_failure
<add> self.log_warning_on_csrf_failure = true
<add>
<ide> helper_method :form_authenticity_token
<ide> helper_method :protect_against_forgery?
<ide> end
<ide> def verify_authenticity_token
<ide> mark_for_same_origin_verification!
<ide>
<ide> if !verified_request?
<del> logger.warn "Can't verify CSRF token authenticity" if logger
<add> if logger && log_warning_on_csrf_failure
<add> logger.warn "Can't verify CSRF token authenticity"
<add> end
<ide> handle_unverified_request
<ide> end
<ide> end
<ide><path>actionpack/test/controller/request_forgery_protection_test.rb
<ide> def test_should_warn_on_missing_csrf_token
<ide> end
<ide> end
<ide>
<add> def test_should_not_warn_if_csrf_logging_disabled
<add> old_logger = ActionController::Base.logger
<add> logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
<add> ActionController::Base.logger = logger
<add> ActionController::Base.log_warning_on_csrf_failure = false
<add>
<add> begin
<add> assert_blocked { post :index }
<add>
<add> assert_equal 0, logger.logged(:warn).size
<add> ensure
<add> ActionController::Base.logger = old_logger
<add> ActionController::Base.log_warning_on_csrf_failure = true
<add> end
<add> end
<add>
<ide> def test_should_only_allow_same_origin_js_get_with_xhr_header
<ide> assert_cross_origin_blocked { get :same_origin_js }
<ide> assert_cross_origin_blocked { get :same_origin_js, format: 'js' } | 3 |
Javascript | Javascript | add docs for the $location.search setter | baa7af0df099fd4bfabe1e90d275822d2558d69c | <ide><path>src/service/location.js
<ide> LocationUrl.prototype = {
<ide> *
<ide> * Change search part when called with parameter and return `$location`.
<ide> *
<del> * @param {string|object<string,string>=} search New search part - string or hash object
<add> * @param {string|object<string,string>=} search New search params - string or hash object
<add> * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
<add> * single search parameter. If the value is `null`, the parameter will be deleted.
<add> *
<ide> * @return {string}
<ide> */
<ide> search: function(search, paramValue) { | 1 |
Javascript | Javascript | remove work around for babel bug | c3dd592c27ab4769be6b7a1f06d75b81b72296eb | <ide><path>packages/ember-metal/lib/watch_key.js
<ide> if (isEnabled('mandatory-setter')) {
<ide> };
<ide> }
<ide>
<del>// This is super annoying, but required until
<del>// https://github.com/babel/babel/issues/906 is resolved
<del>; // jshint ignore:line
<del>
<ide> export function unwatchKey(obj, keyName, meta) {
<ide> var m = meta || metaFor(obj);
<ide> let count = m.peekWatching(keyName); | 1 |
Go | Go | add netlable. keyvalue() and tomap() | b7c2b8111f1cdc4fbf31c89dde8164871962b7a8 | <ide><path>libnetwork/netlabel/labels.go
<ide> package netlabel
<ide>
<del>import "strings"
<add>import (
<add> "fmt"
<add> "strings"
<add>)
<ide>
<ide> const (
<ide> // Prefix constant marks the reserved label space for libnetwork
<ide> const (
<ide> // MacAddress constant represents Mac Address config of a Container
<ide> MacAddress = Prefix + ".endpoint.macaddress"
<ide>
<del> // ExposedPorts constant represents exposedports of a Container
<add> // ExposedPorts constant represents the container's Exposed Ports
<ide> ExposedPorts = Prefix + ".endpoint.exposedports"
<ide>
<ide> //EnableIPv6 constant represents enabling IPV6 at network level
<ide> func Value(label string) string {
<ide>
<ide> return kv[1]
<ide> }
<add>
<add>// KeyValue decomposes the label in the (key,value) pair
<add>func KeyValue(label string) (string, string, error) {
<add> kv := strings.SplitN(label, "=", 2)
<add> if len(kv) != 2 {
<add> return "", "", fmt.Errorf("invalid label: %s", label)
<add> }
<add> return kv[0], kv[1], nil
<add>}
<add>
<add>// ToMap converts a list of labels in amap of (key,value) pairs
<add>func ToMap(labels []string) map[string]string {
<add> m := make(map[string]string, len(labels))
<add> for _, l := range labels {
<add> if k, v, err := KeyValue(l); err == nil {
<add> m[k] = v
<add> }
<add> }
<add> return m
<add>}
<ide><path>libnetwork/netlabel/labels_test.go
<add>package netlabel
<add>
<add>import (
<add> "testing"
<add>
<add> _ "github.com/docker/libnetwork/testutils"
<add>)
<add>
<add>func TestKeyValue(t *testing.T) {
<add> input := []struct {
<add> label string
<add> key string
<add> value string
<add> good bool
<add> }{
<add> {"name=joe", "name", "joe", true},
<add> {"age=24", "age", "24", true},
<add> {"address:1234 First st.", "", "", false},
<add> {"girlfriend=", "girlfriend", "", true},
<add> {"nickname=o=u=8", "nickname", "o=u=8", true},
<add> {"", "", "", false},
<add> }
<add>
<add> for _, i := range input {
<add> k, v, err := KeyValue(i.label)
<add> if k != i.key || v != i.value || i.good != (err == nil) {
<add> t.Fatalf("unexpected: %s, %s, %v", k, v, err)
<add> }
<add> }
<add>}
<add>
<add>func TestToMap(t *testing.T) {
<add> input := []struct {
<add> label string
<add> key string
<add> value string
<add> good bool
<add> }{
<add> {"name=joe", "name", "joe", true},
<add> {"age=24", "age", "24", true},
<add> {"address:1234 First st.", "", "", false},
<add> {"girlfriend=", "girlfriend", "", true},
<add> {"nickname=o=u=8", "nickname", "o=u=8", true},
<add> {"", "", "", false},
<add> }
<add>
<add> lista := make([]string, len(input))
<add> for ind, i := range input {
<add> lista[ind] = i.label
<add> }
<add>
<add> mappa := ToMap(lista)
<add>
<add> if len(mappa) != len(lista)-2 {
<add> t.Fatalf("Incorrect map length. Expected %d. Got %d", len(lista), len(mappa))
<add> }
<add>
<add> for _, i := range input {
<add> if i.good {
<add> if v, ok := mappa[i.key]; !ok || v != i.value {
<add> t.Fatalf("Cannot find key or value for key: %s", i.key)
<add> }
<add> } else {
<add> if _, ok := mappa[i.key]; ok {
<add> t.Fatalf("Found invalid key in map: %s", i.key)
<add> }
<add> }
<add> }
<add>} | 2 |
PHP | PHP | apply fixes from styleci | 86e9e051e8b6ec8ae72b33535a485938c170b756 | <ide><path>src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php
<ide> public function compileIndex(Blueprint $blueprint, Fluent $command)
<ide> */
<ide> protected function compileKey(Blueprint $blueprint, Fluent $command, $type)
<ide> {
<del> return sprintf("alter table %s add %s %s%s(%s)",
<add> return sprintf('alter table %s add %s %s%s(%s)',
<ide> $this->wrapTable($blueprint),
<ide> $type,
<ide> $this->wrap($command->index), | 1 |
Javascript | Javascript | add cross browser stacktrace (#776) | 8318f5b8dead742dea7b4db1968a1379a5332497 | <ide><path>lib/error-debug.js
<ide> import React from 'react'
<ide> import ansiHTML from 'ansi-html'
<ide> import Head from './head'
<ide>
<del>export default ({ err: { name, message, stack, module } }) => (
<add>export default ({ err, err: { name, message, module } }) => (
<ide> <div style={styles.errorDebug}>
<ide> <Head>
<ide> <meta name='viewport' content='width=device-width, initial-scale=1.0' />
<ide> export default ({ err: { name, message, stack, module } }) => (
<ide> {
<ide> name === 'ModuleBuildError'
<ide> ? <pre style={styles.message} dangerouslySetInnerHTML={{ __html: ansiHTML(encodeHtml(message)) }} />
<del> : <pre style={styles.message}>{stack}</pre>
<add> : <StackTrace error={err} />
<ide> }
<ide> </div>
<ide> )
<ide>
<add>const StackTrace = ({ error: { name, message, stack } }) => (
<add> <div>
<add> <div style={styles.heading}>{name && message && `${name}: ${message}`}</div>
<add> <pre style={styles.message}>
<add> {stack}
<add> </pre>
<add> </div>
<add>)
<add>
<ide> const styles = {
<ide> errorDebug: {
<ide> background: '#a6004c', | 1 |
Ruby | Ruby | require https for download.savannah.gnu.org (#438) | df4982ed0810fac1b58aedeb6653ca908dccbd51 | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_urls
<ide> case p
<ide> when %r{^http://ftp\.gnu\.org/},
<ide> %r{^http://ftpmirror\.gnu\.org/},
<add> %r{^http://download\.savannah\.gnu\.org/},
<add> %r{^http://download-mirror\.savannah\.gnu\.org/},
<ide> %r{^http://[^/]*\.apache\.org/},
<ide> %r{^http://code\.google\.com/},
<ide> %r{^http://fossies\.org/}, | 1 |
Ruby | Ruby | show python caveats if modules installed | 744a8944b0e79a79b0801616d2a6f339be0c8cca | <ide><path>Library/Homebrew/caveats.rb
<ide> def initialize(f)
<ide>
<ide> def caveats
<ide> caveats = []
<del> caveats << f.caveats
<add> caveats << f.caveats if f.caveats.to_s.length > 0
<ide> caveats << f.keg_only_text if f.keg_only? && f.respond_to?(:keg_only_text)
<ide> caveats << bash_completion_caveats
<ide> caveats << zsh_completion_caveats
<ide> caveats << plist_caveats
<add> caveats << python_caveats
<ide> caveats.compact.join("\n")
<ide> end
<ide>
<ide> def zsh_completion_caveats
<ide> end
<ide> end
<ide>
<add> def python_caveats
<add> site_packages = if f.keg_only?
<add> "#{f.opt_prefix}/lib/python2.7/site-packages"
<add> else
<add> "#{HOMEBREW_PREFIX}/lib/python2.7/site-packages"
<add> end
<add> if keg and keg.python_site_packages_installed? \
<add> and !ENV['PYTHONPATH'].to_s.include? site_packages
<add> <<-EOS.undent
<add> Set PYTHONPATH if you want Python to find your site-packages:
<add> export PYTHONPATH=#{site_packages}:$PYTHONPATH
<add> EOS
<add> end
<add> end
<add>
<ide> def plist_caveats
<ide> s = []
<ide> if f.plist or (keg and keg.plist_installed?)
<ide><path>Library/Homebrew/keg.rb
<ide> def plist_installed?
<ide> end
<ide> end
<ide>
<add> def python_site_packages_installed?
<add> (self/'lib/python2.7/site-packages').directory?
<add> end
<add>
<ide> def version
<ide> require 'version'
<ide> Version.new(basename.to_s) | 2 |
Javascript | Javascript | fix spelling error in lib/url.js comment | 46eee3018b560cf5e613de3ee5066a125106d1fd | <ide><path>lib/url.js
<ide> Url.prototype.resolveObject = function(relative) {
<ide> // Put this after the other two cases because it simplifies the booleans
<ide> if (psychotic) {
<ide> result.hostname = result.host = srcPath.shift();
<del> //occationaly the auth can get stuck only in host
<add> //occasionally the auth can get stuck only in host
<ide> //this especially happens in cases like
<ide> //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
<ide> var authInHost = result.host && result.host.indexOf('@') > 0 ?
<ide> Url.prototype.resolveObject = function(relative) {
<ide> if (psychotic) {
<ide> result.hostname = result.host = isAbsolute ? '' :
<ide> srcPath.length ? srcPath.shift() : '';
<del> //occationaly the auth can get stuck only in host
<add> //occasionally the auth can get stuck only in host
<ide> //this especially happens in cases like
<ide> //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
<ide> var authInHost = result.host && result.host.indexOf('@') > 0 ? | 1 |
Ruby | Ruby | remove dead code | 9dda9339ad600e652d80aa41cc9809509454eda7 | <ide><path>Library/Homebrew/formula_support.rb
<ide> def version val=nil
<ide> end
<ide>
<ide> def mirror val
<del> @mirrors ||= []
<ide> @mirrors << val
<ide> end
<ide> end | 1 |
Java | Java | use an import instead of fqcn | 5322fa0fb71a55fdda1bf22396863d329026ce39 | <ide><path>spring-core/src/main/java/org/springframework/util/xml/StaxStreamXMLReader.java
<ide> private void handleComment() throws SAXException {
<ide>
<ide> private void handleDtd() throws SAXException {
<ide> if (getLexicalHandler() != null) {
<del> javax.xml.stream.Location location = this.reader.getLocation();
<add> Location location = this.reader.getLocation();
<ide> getLexicalHandler().startDTD(null, location.getPublicId(), location.getSystemId());
<ide> }
<ide> if (getLexicalHandler() != null) { | 1 |
Java | Java | replace webclient.filter with builder.filter | 4a0597d612d68d6e948c748da8d36621639d1b7f | <ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/DefaultWebTestClient.java
<ide> import org.springframework.web.reactive.function.BodyExtractor;
<ide> import org.springframework.web.reactive.function.BodyInserter;
<ide> import org.springframework.web.reactive.function.client.ClientResponse;
<del>import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
<ide> import org.springframework.web.reactive.function.client.WebClient;
<ide> import org.springframework.web.util.UriBuilder;
<ide>
<del>import static java.nio.charset.StandardCharsets.*;
<del>import static org.springframework.test.util.AssertionErrors.*;
<del>import static org.springframework.web.reactive.function.BodyExtractors.*;
<add>import static java.nio.charset.StandardCharsets.UTF_8;
<add>import static org.springframework.test.util.AssertionErrors.assertEquals;
<add>import static org.springframework.test.util.AssertionErrors.assertTrue;
<add>import static org.springframework.web.reactive.function.BodyExtractors.toFlux;
<add>import static org.springframework.web.reactive.function.BodyExtractors.toMono;
<ide>
<ide> /**
<ide> * Default implementation of {@link WebTestClient}.
<ide> class DefaultWebTestClient implements WebTestClient {
<ide> this.timeout = (timeout != null ? timeout : Duration.ofSeconds(5));
<ide> }
<ide>
<del> private DefaultWebTestClient(DefaultWebTestClient webTestClient, ExchangeFilterFunction filter) {
<del> this.webClient = webTestClient.webClient.filter(filter);
<del> this.wiretapConnector = webTestClient.wiretapConnector;
<del> this.timeout = webTestClient.timeout;
<del> }
<del>
<ide>
<ide> private Duration getTimeout() {
<ide> return this.timeout;
<ide> private <S extends RequestHeadersSpec<?>> UriSpec<S> toUriSpec(
<ide> }
<ide>
<ide>
<del> @Override
<del> public WebTestClient filter(ExchangeFilterFunction filter) {
<del> return new DefaultWebTestClient(this, filter);
<del> }
<del>
<del>
<ide> @SuppressWarnings("unchecked")
<ide> private class DefaultUriSpec<S extends RequestHeadersSpec<?>> implements UriSpec<S> {
<ide>
<ide> public RequestBodySpec header(String headerName, String... headerValues) {
<ide> }
<ide>
<ide> @Override
<del> public RequestBodySpec headers(HttpHeaders headers) {
<del> this.bodySpec.headers(headers);
<add> public RequestBodySpec headers(Consumer<HttpHeaders> headersConsumer) {
<add> this.bodySpec.headers(headersConsumer);
<ide> return this;
<ide> }
<ide>
<ide> public RequestBodySpec cookie(String name, String value) {
<ide> }
<ide>
<ide> @Override
<del> public RequestBodySpec cookies(MultiValueMap<String, String> cookies) {
<del> this.bodySpec.cookies(cookies);
<add> public RequestBodySpec cookies(
<add> Consumer<MultiValueMap<String, String>> cookiesConsumer) {
<add> this.bodySpec.cookies(cookiesConsumer);
<ide> return this;
<ide> }
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/DefaultWebTestClientBuilder.java
<ide> package org.springframework.test.web.reactive.server;
<ide>
<ide> import java.time.Duration;
<add>import java.util.List;
<add>import java.util.function.Consumer;
<ide>
<add>import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.client.reactive.ClientHttpConnector;
<ide> import org.springframework.http.client.reactive.ReactorClientHttpConnector;
<ide> import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.util.MultiValueMap;
<add>import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
<ide> import org.springframework.web.reactive.function.client.ExchangeStrategies;
<ide> import org.springframework.web.reactive.function.client.WebClient;
<ide> import org.springframework.web.util.UriBuilderFactory;
<ide> public WebTestClient.Builder defaultHeader(String headerName, String... headerVa
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public WebTestClient.Builder defaultHeaders(Consumer<HttpHeaders> headersConsumer) {
<add> this.webClientBuilder.defaultHeaders(headersConsumer);
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public WebTestClient.Builder defaultCookie(String cookieName, String... cookieValues) {
<ide> this.webClientBuilder.defaultCookie(cookieName, cookieValues);
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public WebTestClient.Builder defaultCookies(
<add> Consumer<MultiValueMap<String, String>> cookiesConsumer) {
<add> this.webClientBuilder.defaultCookies(cookiesConsumer);
<add> return this;
<add> }
<add>
<add> @Override
<add> public WebTestClient.Builder filter(ExchangeFilterFunction filter) {
<add> this.webClientBuilder.filter(filter);
<add> return this;
<add> }
<add>
<add> @Override
<add> public WebTestClient.Builder filters(Consumer<List<ExchangeFilterFunction>> filtersConsumer) {
<add> this.webClientBuilder.filters(filtersConsumer);
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public WebTestClient.Builder exchangeStrategies(ExchangeStrategies strategies) {
<ide> this.webClientBuilder.exchangeStrategies(strategies);
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/WebTestClient.java
<ide> import org.springframework.web.reactive.config.WebFluxConfigurer;
<ide> import org.springframework.web.reactive.function.BodyInserter;
<ide> import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
<del>import org.springframework.web.reactive.function.client.ExchangeFunction;
<ide> import org.springframework.web.reactive.function.client.ExchangeStrategies;
<ide> import org.springframework.web.reactive.function.client.WebClient;
<ide> import org.springframework.web.reactive.function.server.HandlerStrategies;
<ide> public interface WebTestClient {
<ide> UriSpec<RequestHeadersSpec<?>> options();
<ide>
<ide>
<del> /**
<del> * Filter the client with the given {@code ExchangeFilterFunction}.
<del> * @param filterFunction the filter to apply to this client
<del> * @return the filtered client
<del> * @see ExchangeFilterFunction#apply(ExchangeFunction)
<del> */
<del> WebTestClient filter(ExchangeFilterFunction filterFunction);
<del>
<del>
<ide> // Static, factory methods
<ide>
<ide> /**
<ide> interface Builder {
<ide> */
<ide> Builder defaultHeader(String headerName, String... headerValues);
<ide>
<add> /**
<add> * Manipulate the default headers with the given consumer. The
<add> * headers provided to the consumer are "live", so that the consumer can be used to
<add> * {@linkplain HttpHeaders#set(String, String) overwrite} existing header values,
<add> * {@linkplain HttpHeaders#remove(Object) remove} values, or use any of the other
<add> * {@link HttpHeaders} methods.
<add> * @param headersConsumer a function that consumes the {@code HttpHeaders}
<add> * @return this builder
<add> */
<add> Builder defaultHeaders(Consumer<HttpHeaders> headersConsumer);
<add>
<ide> /**
<ide> * Add the given header to all requests that haven't added it.
<ide> * @param cookieName the cookie name
<ide> * @param cookieValues the cookie values
<ide> */
<ide> Builder defaultCookie(String cookieName, String... cookieValues);
<ide>
<add> /**
<add> * Manipulate the default cookies with the given consumer. The
<add> * map provided to the consumer is "live", so that the consumer can be used to
<add> * {@linkplain MultiValueMap#set(Object, Object) overwrite} existing header values,
<add> * {@linkplain MultiValueMap#remove(Object) remove} values, or use any of the other
<add> * {@link MultiValueMap} methods.
<add> * @param cookiesConsumer a function that consumes the cookies map
<add> * @return this builder
<add> */
<add> Builder defaultCookies(Consumer<MultiValueMap<String, String>> cookiesConsumer);
<add>
<add> /**
<add> * Add the given filter to the filter chain.
<add> * @param filter the filter to be added to the chain
<add> */
<add> Builder filter(ExchangeFilterFunction filter);
<add>
<add> /**
<add> * Manipulate the filters with the given consumer. The
<add> * list provided to the consumer is "live", so that the consumer can be used to remove
<add> * filters, change ordering, etc.
<add> * @param filtersConsumer a function that consumes the filter list
<add> * @return this builder
<add> */
<add> Builder filters(Consumer<List<ExchangeFilterFunction>> filtersConsumer);
<add>
<ide> /**
<ide> * Configure the {@link ExchangeStrategies} to use.
<ide> * <p>By default {@link ExchangeStrategies#withDefaults()} is used.
<ide> interface Builder {
<ide> S cookie(String name, String value);
<ide>
<ide> /**
<del> * Copy the given cookies into the entity's cookies map.
<del> *
<del> * @param cookies the existing cookies to copy from
<del> * @return the same instance
<add> * Manipulate this request's cookies with the given consumer. The
<add> * map provided to the consumer is "live", so that the consumer can be used to
<add> * {@linkplain MultiValueMap#set(Object, Object) overwrite} existing header values,
<add> * {@linkplain MultiValueMap#remove(Object) remove} values, or use any of the other
<add> * {@link MultiValueMap} methods.
<add> * @param cookiesConsumer a function that consumes the cookies map
<add> * @return this builder
<ide> */
<del> S cookies(MultiValueMap<String, String> cookies);
<add> S cookies(Consumer<MultiValueMap<String, String>> cookiesConsumer);
<ide>
<ide> /**
<ide> * Set the value of the {@code If-Modified-Since} header.
<ide> interface Builder {
<ide> S header(String headerName, String... headerValues);
<ide>
<ide> /**
<del> * Copy the given headers into the entity's headers map.
<del> * @param headers the existing headers to copy from
<del> * @return the same instance
<add> * Manipulate the request's headers with the given consumer. The
<add> * headers provided to the consumer are "live", so that the consumer can be used to
<add> * {@linkplain HttpHeaders#set(String, String) overwrite} existing header values,
<add> * {@linkplain HttpHeaders#remove(Object) remove} values, or use any of the other
<add> * {@link HttpHeaders} methods.
<add> * @param headersConsumer a function that consumes the {@code HttpHeaders}
<add> * @return this builder
<ide> */
<del> S headers(HttpHeaders headers);
<add> S headers(Consumer<HttpHeaders> headersConsumer);
<ide>
<ide> /**
<ide> * Perform the exchange without a request body.
<ide><path>spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ExchangeMutatorWebFilterTests.java
<ide> public void globalMutator() throws Exception {
<ide>
<ide> @Test
<ide> public void perRequestMutators() throws Exception {
<del> this.webTestClient
<add>
<add> this.webTestClient = WebTestClient.bindToController(new TestController())
<add> .webFilter(this.exchangeMutator)
<add> .configureClient()
<ide> .filter(this.exchangeMutator.perClient(userIdentity("Giovanni")))
<add> .build();
<add>
<add> this.webTestClient
<ide> .get().uri("/userIdentity")
<ide> .exchange()
<ide> .expectStatus().isOk()
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClient.java
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.function.Consumer;
<ide> import java.util.function.Function;
<ide>
<ide> import org.reactivestreams.Publisher;
<ide> class DefaultWebClient implements WebClient {
<ide>
<ide> private final MultiValueMap<String, String> defaultCookies;
<ide>
<add> private final DefaultWebClientBuilder builder;
<add>
<ide>
<ide> DefaultWebClient(ExchangeFunction exchangeFunction, @Nullable UriBuilderFactory factory,
<del> @Nullable HttpHeaders defaultHeaders, @Nullable MultiValueMap<String, String> defaultCookies) {
<add> @Nullable HttpHeaders defaultHeaders, @Nullable MultiValueMap<String, String> defaultCookies,
<add> DefaultWebClientBuilder builder) {
<ide>
<ide> this.exchangeFunction = exchangeFunction;
<ide> this.uriBuilderFactory = (factory != null ? factory : new DefaultUriBuilderFactory());
<del> this.defaultHeaders = (defaultHeaders != null ?
<del> HttpHeaders.readOnlyHttpHeaders(defaultHeaders) : null);
<del> this.defaultCookies = (defaultCookies != null ?
<del> CollectionUtils.unmodifiableMultiValueMap(defaultCookies) : null);
<add> this.defaultHeaders = defaultHeaders;
<add> this.defaultCookies = defaultCookies;
<add> this.builder = builder;
<ide> }
<ide>
<ide>
<ide> private <S extends RequestHeadersSpec<?>> UriSpec<S> methodInternal(HttpMethod h
<ide> }
<ide>
<ide> @Override
<del> public WebClient filter(ExchangeFilterFunction filterFunction) {
<del> ExchangeFunction filteredExchangeFunction = this.exchangeFunction.filter(filterFunction);
<del> return new DefaultWebClient(filteredExchangeFunction,
<del> this.uriBuilderFactory, this.defaultHeaders, this.defaultCookies);
<add> public Builder mutate() {
<add> return this.builder;
<ide> }
<ide>
<del>
<ide> private class DefaultUriSpec<S extends RequestHeadersSpec<?>> implements UriSpec<S> {
<ide>
<ide> private final HttpMethod httpMethod;
<ide> public DefaultRequestBodySpec header(String headerName, String... headerValues)
<ide> }
<ide>
<ide> @Override
<del> public DefaultRequestBodySpec headers(HttpHeaders headers) {
<del> getHeaders().putAll(headers);
<add> public DefaultRequestBodySpec headers(Consumer<HttpHeaders> headersConsumer) {
<add> Assert.notNull(headersConsumer, "'headersConsumer' must not be null");
<add> headersConsumer.accept(this.headers);
<ide> return this;
<ide> }
<ide>
<ide> public DefaultRequestBodySpec cookie(String name, String value) {
<ide> }
<ide>
<ide> @Override
<del> public DefaultRequestBodySpec cookies(MultiValueMap<String, String> cookies) {
<del> getCookies().putAll(cookies);
<add> public DefaultRequestBodySpec cookies(
<add> Consumer<MultiValueMap<String, String>> cookiesConsumer) {
<add> Assert.notNull(cookiesConsumer, "'cookiesConsumer' must not be null");
<add> cookiesConsumer.accept(this.cookies);
<ide> return this;
<ide> }
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClientBuilder.java
<ide>
<ide> package org.springframework.web.reactive.function.client;
<ide>
<add>import java.util.ArrayList;
<ide> import java.util.Arrays;
<add>import java.util.Collections;
<add>import java.util.LinkedHashMap;
<add>import java.util.List;
<ide> import java.util.Map;
<add>import java.util.function.Consumer;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.client.reactive.ClientHttpConnector;
<ide> import org.springframework.http.client.reactive.ReactorClientHttpConnector;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.util.DefaultUriBuilderFactory;
<ide> class DefaultWebClientBuilder implements WebClient.Builder {
<ide>
<ide> private MultiValueMap<String, String> defaultCookies;
<ide>
<add> private List<ExchangeFilterFunction> filters;
<add>
<ide> private ClientHttpConnector connector;
<ide>
<ide> private ExchangeStrategies exchangeStrategies = ExchangeStrategies.withDefaults();
<ide>
<ide> private ExchangeFunction exchangeFunction;
<ide>
<add> public DefaultWebClientBuilder() {
<add> }
<add>
<add> public DefaultWebClientBuilder(DefaultWebClientBuilder other) {
<add> Assert.notNull(other, "'other' must not be null");
<add>
<add> this.baseUrl = other.baseUrl;
<add> this.defaultUriVariables = (other.defaultUriVariables != null ?
<add> new LinkedHashMap<>(other.defaultUriVariables) : null);
<add> this.uriBuilderFactory = other.uriBuilderFactory;
<add> if (other.defaultHeaders != null) {
<add> this.defaultHeaders = new HttpHeaders();
<add> this.defaultHeaders.putAll(other.defaultHeaders);
<add> }
<add> else {
<add> this.defaultHeaders = null;
<add> }
<add> this.defaultCookies = (other.defaultCookies != null ?
<add> new LinkedMultiValueMap<>(other.defaultCookies) : null);
<add> this.filters = (other.filters != null ? new ArrayList<>(other.filters) : null);
<add> this.connector = other.connector;
<add> this.exchangeStrategies = other.exchangeStrategies;
<add> this.exchangeFunction = other.exchangeFunction;
<add> }
<ide>
<ide> @Override
<ide> public WebClient.Builder baseUrl(String baseUrl) {
<ide> public WebClient.Builder uriBuilderFactory(UriBuilderFactory uriBuilderFactory)
<ide>
<ide> @Override
<ide> public WebClient.Builder defaultHeader(String headerName, String... headerValues) {
<del> if (this.defaultHeaders == null) {
<del> this.defaultHeaders = new HttpHeaders();
<del> }
<add> initHeaders();
<ide> for (String headerValue : headerValues) {
<ide> this.defaultHeaders.add(headerName, headerValue);
<ide> }
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public WebClient.Builder defaultHeaders(Consumer<HttpHeaders> headersConsumer) {
<add> Assert.notNull(headersConsumer, "'headersConsumer' must not be null");
<add> initHeaders();
<add> headersConsumer.accept(this.defaultHeaders);
<add> return this;
<add> }
<add>
<add> private void initHeaders() {
<add> if (this.defaultHeaders == null) {
<add> this.defaultHeaders = new HttpHeaders();
<add> }
<add> }
<add>
<ide> @Override
<ide> public WebClient.Builder defaultCookie(String cookieName, String... cookieValues) {
<add> initCookies();
<add> this.defaultCookies.addAll(cookieName, Arrays.asList(cookieValues));
<add> return this;
<add> }
<add>
<add> @Override
<add> public WebClient.Builder defaultCookies(
<add> Consumer<MultiValueMap<String, String>> cookiesConsumer) {
<add> Assert.notNull(cookiesConsumer, "'cookiesConsumer' must not be null");
<add> initCookies();
<add> cookiesConsumer.accept(this.defaultCookies);
<add> return this;
<add> }
<add>
<add> private void initCookies() {
<ide> if (this.defaultCookies == null) {
<ide> this.defaultCookies = new LinkedMultiValueMap<>(4);
<ide> }
<del> this.defaultCookies.addAll(cookieName, Arrays.asList(cookieValues));
<del> return this;
<ide> }
<ide>
<ide> @Override
<ide> public WebClient.Builder clientConnector(ClientHttpConnector connector) {
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public WebClient.Builder filter(ExchangeFilterFunction filter) {
<add> Assert.notNull(filter, "'filter' must not be null");
<add> initFilters();
<add> this.filters.add(filter);
<add> return this;
<add> }
<add>
<add> @Override
<add> public WebClient.Builder filters(Consumer<List<ExchangeFilterFunction>> filtersConsumer) {
<add> Assert.notNull(filtersConsumer, "'filtersConsumer' must not be null");
<add> initFilters();
<add> filtersConsumer.accept(this.filters);
<add> return this;
<add> }
<add>
<add> private void initFilters() {
<add> if (this.filters == null) {
<add> this.filters = new ArrayList<>();
<add> }
<add> }
<add>
<ide> @Override
<ide> public WebClient.Builder exchangeStrategies(ExchangeStrategies strategies) {
<del> Assert.notNull(strategies, "ExchangeStrategies is required.");
<add> Assert.notNull(strategies, "'strategies' must not be null");
<ide> this.exchangeStrategies = strategies;
<ide> return this;
<ide> }
<ide> public WebClient.Builder exchangeFunction(ExchangeFunction exchangeFunction) {
<ide>
<ide> @Override
<ide> public WebClient build() {
<del> return new DefaultWebClient(initExchangeFunction(), initUriBuilderFactory(),
<del> this.defaultHeaders, this.defaultCookies);
<add> ExchangeFunction exchange = initExchangeFunction();
<add> ExchangeFunction filteredExchange = (this.filters != null ? this.filters.stream()
<add> .reduce(ExchangeFilterFunction::andThen)
<add> .map(filter -> filter.apply(exchange))
<add> .orElse(exchange) : exchange);
<add> return new DefaultWebClient(filteredExchange, initUriBuilderFactory(),
<add> unmodifiableCopy(this.defaultHeaders), unmodifiableCopy(this.defaultCookies),
<add> new DefaultWebClientBuilder(this));
<add> }
<add>
<add> private static @Nullable HttpHeaders unmodifiableCopy(@Nullable HttpHeaders original) {
<add> if (original != null) {
<add> HttpHeaders copy = new HttpHeaders();
<add> copy.putAll(original);
<add> return HttpHeaders.readOnlyHttpHeaders(copy);
<add> } else {
<add> return null;
<add> }
<add> }
<add>
<add> private static @Nullable <K, V> MultiValueMap<K, V> unmodifiableCopy(@Nullable MultiValueMap<K, V> original) {
<add> if (original != null) {
<add> return CollectionUtils.unmodifiableMultiValueMap(new LinkedMultiValueMap<>(original));
<add> }
<add> else {
<add> return null;
<add> }
<add> }
<add>
<add> private static <T> List<T> unmodifiableCopy(List<? extends T> list) {
<add> return Collections.unmodifiableList(new ArrayList<>(list));
<ide> }
<ide>
<ide> private UriBuilderFactory initUriBuilderFactory() {
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/WebClient.java
<ide> import java.time.ZonedDateTime;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.function.Consumer;
<ide> import java.util.function.Function;
<ide>
<ide> import org.reactivestreams.Publisher;
<ide> public interface WebClient {
<ide>
<ide>
<ide> /**
<del> * Filter the client with the given {@code ExchangeFilterFunction}.
<del> * @param filterFunction the filter to apply to this client
<del> * @return the filtered client
<del> * @see ExchangeFilterFunction#apply(ExchangeFunction)
<add> * Return a builder to mutate properties of this web client.
<ide> */
<del> WebClient filter(ExchangeFilterFunction filterFunction);
<add> Builder mutate();
<ide>
<ide>
<ide> // Static, factory methods
<ide> interface Builder {
<ide> Builder uriBuilderFactory(UriBuilderFactory uriBuilderFactory);
<ide>
<ide> /**
<del> * Add the given header to all requests that haven't added it.
<add> * Add the given header to all requests that have not added it.
<ide> * @param headerName the header name
<ide> * @param headerValues the header values
<ide> */
<ide> Builder defaultHeader(String headerName, String... headerValues);
<ide>
<add> /**
<add> * Manipulate the default headers with the given consumer. The
<add> * headers provided to the consumer are "live", so that the consumer can be used to
<add> * {@linkplain HttpHeaders#set(String, String) overwrite} existing header values,
<add> * {@linkplain HttpHeaders#remove(Object) remove} values, or use any of the other
<add> * {@link HttpHeaders} methods.
<add> * @param headersConsumer a function that consumes the {@code HttpHeaders}
<add> * @return this builder
<add> */
<add> Builder defaultHeaders(Consumer<HttpHeaders> headersConsumer);
<add>
<ide> /**
<ide> * Add the given header to all requests that haven't added it.
<ide> * @param cookieName the cookie name
<ide> * @param cookieValues the cookie values
<ide> */
<ide> Builder defaultCookie(String cookieName, String... cookieValues);
<ide>
<add> /**
<add> * Manipulate the default cookies with the given consumer. The
<add> * map provided to the consumer is "live", so that the consumer can be used to
<add> * {@linkplain MultiValueMap#set(Object, Object) overwrite} existing header values,
<add> * {@linkplain MultiValueMap#remove(Object) remove} values, or use any of the other
<add> * {@link MultiValueMap} methods.
<add> * @param cookiesConsumer a function that consumes the cookies map
<add> * @return this builder
<add> */
<add> Builder defaultCookies(Consumer<MultiValueMap<String, String>> cookiesConsumer);
<add>
<ide> /**
<ide> * Configure the {@link ClientHttpConnector} to use.
<ide> * <p>By default an instance of
<ide> interface Builder {
<ide> */
<ide> Builder clientConnector(ClientHttpConnector connector);
<ide>
<add> /**
<add> * Add the given filter to the filter chain.
<add> * @param filter the filter to be added to the chain
<add> */
<add> Builder filter(ExchangeFilterFunction filter);
<add>
<add> /**
<add> * Manipulate the filters with the given consumer. The
<add> * list provided to the consumer is "live", so that the consumer can be used to remove
<add> * filters, change ordering, etc.
<add> * @param filtersConsumer a function that consumes the filter list
<add> * @return this builder
<add> */
<add> Builder filters(Consumer<List<ExchangeFilterFunction>> filtersConsumer);
<add>
<ide> /**
<ide> * Configure the {@link ExchangeStrategies} to use.
<ide> * <p>By default {@link ExchangeStrategies#withDefaults()} is used.
<ide> interface Builder {
<ide> S cookie(String name, String value);
<ide>
<ide> /**
<del> * Copy the given cookies into the entity's cookies map.
<del> * @param cookies the existing cookies to copy from
<add> * Manipulate the request's cookies with the given consumer. The
<add> * map provided to the consumer is "live", so that the consumer can be used to
<add> * {@linkplain MultiValueMap#set(Object, Object) overwrite} existing header values,
<add> * {@linkplain MultiValueMap#remove(Object) remove} values, or use any of the other
<add> * {@link MultiValueMap} methods.
<add> * @param cookiesConsumer a function that consumes the cookies map
<ide> * @return this builder
<ide> */
<del> S cookies(MultiValueMap<String, String> cookies);
<add> S cookies(Consumer<MultiValueMap<String, String>> cookiesConsumer);
<ide>
<ide> /**
<ide> * Set the value of the {@code If-Modified-Since} header.
<ide> interface Builder {
<ide> S header(String headerName, String... headerValues);
<ide>
<ide> /**
<del> * Copy the given headers into the entity's headers map.
<del> * @param headers the existing headers to copy from
<add> * Manipulate the request's headers with the given consumer. The
<add> * headers provided to the consumer are "live", so that the consumer can be used to
<add> * {@linkplain HttpHeaders#set(String, String) overwrite} existing header values,
<add> * {@linkplain HttpHeaders#remove(Object) remove} values, or use any of the other
<add> * {@link HttpHeaders} methods.
<add> * @param headersConsumer a function that consumes the {@code HttpHeaders}
<ide> * @return this builder
<ide> */
<del> S headers(HttpHeaders headers);
<add> S headers(Consumer<HttpHeaders> headersConsumer);
<ide>
<ide> /**
<ide> * Exchange the request for a {@code ClientResponse} with full access
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java
<ide> public void bodyObjectPublisher() throws Exception {
<ide> client.post().uri("http://example.com").syncBody(mono);
<ide> }
<ide>
<add> @Test
<add> public void mutateDoesCopy() throws Exception {
<add>
<add> WebClient.Builder builder = WebClient.builder();
<add> builder.filter((request, next) -> next.exchange(request));
<add> builder.defaultHeader("foo", "bar");
<add> builder.defaultCookie("foo", "bar");
<add> WebClient client1 = builder.build();
<add> builder.filter((request, next) -> next.exchange(request));
<add> builder.defaultHeader("baz", "qux");
<add> builder.defaultCookie("baz", "qux");
<add> WebClient client2 = builder.build();
<add>
<add> client1.mutate().filters(filters -> assertEquals(1, filters.size()));
<add> client1.mutate().defaultHeaders(headers -> assertEquals(1, headers.size()));
<add> client1.mutate().defaultCookies(cookies -> assertEquals(1, cookies.size()));
<add> client2.mutate().filters(filters -> assertEquals(2, filters.size()));
<add> client2.mutate().defaultHeaders(headers -> assertEquals(2, headers.size()));
<add> client2.mutate().defaultCookies(cookies -> assertEquals(2, cookies.size()));
<add> }
<add>
<add>
<ide>
<ide> private WebClient.Builder builder() {
<ide> return WebClient.builder().baseUrl("/base").exchangeFunction(this.exchangeFunction);
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java
<ide> public class WebClientIntegrationTests {
<ide>
<ide> private WebClient webClient;
<ide>
<add> private String baseUrl;
<ide>
<ide> @Before
<ide> public void setup() {
<ide> this.server = new MockWebServer();
<del> String baseUrl = this.server.url("/").toString();
<add> baseUrl = this.server.url("/").toString();
<ide> this.webClient = WebClient.create(baseUrl);
<ide> }
<ide>
<ide> public void retrieveToEntityNotFound() throws Exception {
<ide>
<ide> @Test
<ide> public void filter() throws Exception {
<del> this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain").setBody("Hello Spring!"));
<add> this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain")
<add> .setBody("Hello Spring!"));
<ide>
<del> WebClient filteredClient = this.webClient.filter(
<del> (request, next) -> {
<del> ClientRequest filteredRequest = ClientRequest.from(request).header("foo", "bar").build();
<add> WebClient filteredClient = this.webClient.mutate()
<add> .filter((request, next) -> {
<add> ClientRequest filteredRequest =
<add> ClientRequest.from(request).header("foo", "bar").build();
<ide> return next.exchange(filteredRequest);
<del> });
<add> })
<add> .build();
<ide>
<ide> Mono<String> result = filteredClient.get()
<ide> .uri("/greeting?name=Spring")
<ide> public void errorHandlingFilter() throws Exception {
<ide> }
<ide> );
<ide>
<del> WebClient filteredClient = this.webClient.filter(filter);
<add> WebClient filteredClient = this.webClient.mutate()
<add> .filter(filter)
<add> .build();
<ide>
<ide> // header not present
<ide> this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain").setBody("Hello Spring!"));
<ide> public void errorHandlingFilter() throws Exception {
<ide> Assert.assertEquals(2, server.getRequestCount());
<ide> }
<ide>
<add>
<ide> @SuppressWarnings("serial")
<ide> private static class MyException extends RuntimeException {
<ide> | 9 |
Text | Text | update dataset websites in detection_model_zoo.md | 155c65cb583f39605340ed9aa38a4ad4f414ed8b | <ide><path>research/object_detection/g3doc/detection_model_zoo.md
<ide> # Tensorflow detection model zoo
<ide>
<ide> We provide a collection of detection models pre-trained on the [COCO
<del>dataset](http://mscoco.org), the [Kitti dataset](http://www.cvlibs.net/datasets/kitti/),
<del>the [Open Images dataset](https://github.com/openimages/dataset), the
<add>dataset](http://cocodataset.org/), the [Kitti dataset](http://www.cvlibs.net/datasets/kitti/),
<add>the [Open Images dataset](https://storage.googleapis.com/openimages/web/index.html), the
<ide> [AVA v2.1 dataset](https://research.google.com/ava/) and the
<ide> [iNaturalist Species Detection Dataset](https://github.com/visipedia/inat_comp/blob/master/2017/README.md#bounding-boxes).
<ide> These models can be useful for out-of-the-box inference if you are interested in | 1 |
Mixed | Python | fix two typos | ee017e0dbf2d2401d14657b4271256de5266cc28 | <ide><path>inception/README.md
<ide> We find that the evaluation arrives at roughly 93.4% precision@1 after the model
<ide> has been running for 2000 steps.
<ide>
<ide> ```shell
<del>Succesfully loaded model from /tmp/flowers/model.ckpt-1999 at step=1999.
<add>Successfully loaded model from /tmp/flowers/model.ckpt-1999 at step=1999.
<ide> 2016-03-01 16:52:51.761219: starting evaluation on (validation).
<ide> 2016-03-01 16:53:05.450419: [20 batches out of 20] (36.5 examples/sec; 0.684sec/batch)
<ide> 2016-03-01 16:53:05.450471: precision @ 1 = 0.9340 recall @ 5 = 0.9960 [500 examples]
<ide><path>neural_gpu/wmt_utils.py
<ide> def maybe_download(directory, filename, url):
<ide> print "Downloading %s to %s" % (url, filepath)
<ide> filepath, _ = urllib.request.urlretrieve(url, filepath)
<ide> statinfo = os.stat(filepath)
<del> print "Succesfully downloaded", filename, statinfo.st_size, "bytes"
<add> print "Successfully downloaded", filename, statinfo.st_size, "bytes"
<ide> return filepath
<ide>
<ide> | 2 |
Ruby | Ruby | add caller to request_uri deprecation notice | 52efbdcdefa678ae2ee9530bcfefd0e2529b188f | <ide><path>actionpack/lib/action_dispatch/http/url.rb
<ide> def subdomain(tld_length = 1)
<ide> # Returns the request URI, accounting for server idiosyncrasies.
<ide> # WEBrick includes the full URL. IIS leaves REQUEST_URI blank.
<ide> def request_uri
<del> ActiveSupport::Deprecation.warn "Using #request_uri is deprecated. Use fullpath instead."
<add> ActiveSupport::Deprecation.warn "Using #request_uri is deprecated. Use fullpath instead.", caller
<ide> fullpath
<ide> end
<ide>
<ide><path>railties/lib/rails/rack/logger.rb
<ide> def call(env)
<ide>
<ide> def before_dispatch(env)
<ide> request = ActionDispatch::Request.new(env)
<del> path = request.request_uri.inspect rescue "unknown"
<add> path = request.fullpath.inspect rescue "unknown"
<ide>
<ide> info "\n\nStarted #{request.method.to_s.upcase} #{path} " <<
<ide> "for #{request.remote_ip} at #{Time.now.to_s(:db)}" | 2 |
Python | Python | remove word “shuffled” from comments in examples | 4f2e65c385d60fa87bb143c6c506cbe428895f44 | <ide><path>examples/antirectifier.py
<ide> def call(self, inputs):
<ide> num_classes = 10
<ide> epochs = 40
<ide>
<del># the data, shuffled and split between train and test sets
<add># the data, split between train and test sets
<ide> (x_train, y_train), (x_test, y_test) = mnist.load_data()
<ide>
<ide> x_train = x_train.reshape(60000, 784)
<ide><path>examples/cifar10_cnn.py
<ide> save_dir = os.path.join(os.getcwd(), 'saved_models')
<ide> model_name = 'keras_cifar10_trained_model.h5'
<ide>
<del># The data, shuffled and split between train and test sets:
<add># The data, split between train and test sets:
<ide> (x_train, y_train), (x_test, y_test) = cifar10.load_data()
<ide> print('x_train shape:', x_train.shape)
<ide> print(x_train.shape[0], 'train samples')
<ide><path>examples/cifar10_cnn_tfaugment2d.py
<ide> def augment_2d(inputs, rotation=0, horizontal_flip=False, vertical_flip=False):
<ide> save_dir = '/tmp/saved_models'
<ide> model_name = 'keras_cifar10_trained_model.h5'
<ide>
<del># The data, shuffled and split between train and test sets:
<add># The data, split between train and test sets:
<ide> (x_train, y_train), (x_test, y_test) = cifar10.load_data()
<ide> print('x_train shape:', x_train.shape)
<ide> print(x_train.shape[0], 'train samples')
<ide><path>examples/mnist_cnn.py
<ide> # input image dimensions
<ide> img_rows, img_cols = 28, 28
<ide>
<del># the data, shuffled and split between train and test sets
<add># the data, split between train and test sets
<ide> (x_train, y_train), (x_test, y_test) = mnist.load_data()
<ide>
<ide> if K.image_data_format() == 'channels_first':
<ide><path>examples/mnist_hierarchical_rnn.py
<ide> row_hidden = 128
<ide> col_hidden = 128
<ide>
<del># The data, shuffled and split between train and test sets.
<add># The data, split between train and test sets.
<ide> (x_train, y_train), (x_test, y_test) = mnist.load_data()
<ide>
<ide> # Reshapes data to 4D for Hierarchical RNN.
<ide><path>examples/mnist_irnn.py
<ide> learning_rate = 1e-6
<ide> clip_norm = 1.0
<ide>
<del># the data, shuffled and split between train and test sets
<add># the data, split between train and test sets
<ide> (x_train, y_train), (x_test, y_test) = mnist.load_data()
<ide>
<ide> x_train = x_train.reshape(x_train.shape[0], -1, 1)
<ide><path>examples/mnist_mlp.py
<ide> num_classes = 10
<ide> epochs = 20
<ide>
<del># the data, shuffled and split between train and test sets
<add># the data, split between train and test sets
<ide> (x_train, y_train), (x_test, y_test) = mnist.load_data()
<ide>
<ide> x_train = x_train.reshape(60000, 784)
<ide><path>examples/mnist_siamese.py
<ide> def accuracy(y_true, y_pred):
<ide> return K.mean(K.equal(y_true, K.cast(y_pred < 0.5, y_true.dtype)))
<ide>
<ide>
<del># the data, shuffled and split between train and test sets
<add># the data, split between train and test sets
<ide> (x_train, y_train), (x_test, y_test) = mnist.load_data()
<ide> x_train = x_train.astype('float32')
<ide> x_test = x_test.astype('float32')
<ide><path>examples/mnist_swwae.py
<ide> def getwhere(x):
<ide> # input image dimensions
<ide> img_rows, img_cols = 28, 28
<ide>
<del># the data, shuffled and split between train and test sets
<add># the data, split between train and test sets
<ide> (x_train, _), (x_test, _) = mnist.load_data()
<ide>
<ide> x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
<ide><path>examples/mnist_transfer_cnn.py
<ide> def train_model(model, train, test, num_classes):
<ide> print('Test accuracy:', score[1])
<ide>
<ide>
<del># the data, shuffled and split between train and test sets
<add># the data, split between train and test sets
<ide> (x_train, y_train), (x_test, y_test) = mnist.load_data()
<ide>
<ide> # create two datasets one with digits below 5 and one with 5 and above | 10 |
Javascript | Javascript | add .css(function) incoming value tests | ebaf374f2ac02e224ff0d0775b9709579404dd58 | <ide><path>test/unit/css.js
<ide> test("css(String, Function)", function() {
<ide> jQuery("#cssFunctionTest").remove();
<ide> });
<ide>
<add>test("css(String, Function) with incoming value", function() {
<add> expect(3);
<add>
<add> var sizes = ["10px", "20px", "30px"];
<add>
<add> jQuery("<div id='cssFunctionTest'><div class='cssFunction'></div>" +
<add> "<div class='cssFunction'></div>" +
<add> "<div class='cssFunction'></div></div>")
<add> .appendTo("body");
<add>
<add> var index = 0;
<add>
<add> jQuery("#cssFunctionTest div").css("font-size", function() {
<add> var size = sizes[index];
<add> index++;
<add> return size;
<add> });
<add>
<add> index = 0;
<add>
<add> jQuery("#cssFunctionTest div").css("font-size", function(i, computedSize) {
<add> var expectedSize = sizes[index]
<add> equals( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize );
<add> index++;
<add> return computedSize;
<add> });
<add>
<add> jQuery("#cssFunctionTest").remove();
<add>});
<add>
<ide> test("css(Object) where values are Functions", function() {
<ide> expect(3);
<ide>
<ide> test("css(Object) where values are Functions", function() {
<ide> jQuery("#cssFunctionTest").remove();
<ide> });
<ide>
<add>test("css(Object) where values are Functions with incoming values", function() {
<add> expect(3);
<add>
<add> var sizes = ["10px", "20px", "30px"];
<add>
<add> jQuery("<div id='cssFunctionTest'><div class='cssFunction'></div>" +
<add> "<div class='cssFunction'></div>" +
<add> "<div class='cssFunction'></div></div>")
<add> .appendTo("body");
<add>
<add> var index = 0;
<add>
<add> jQuery("#cssFunctionTest div").css({fontSize: function() {
<add> var size = sizes[index];
<add> index++;
<add> return size;
<add> }});
<add>
<add> index = 0;
<add>
<add> jQuery("#cssFunctionTest div").css({"font-size": function(i, computedSize) {
<add> var expectedSize = sizes[index]
<add> equals( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize );
<add> index++;
<add> return computedSize;
<add> }});
<add>
<add> jQuery("#cssFunctionTest").remove();
<add>});
<add>
<ide> test("jQuery.css(elem, 'height') doesn't clear radio buttons (bug #1095)", function () {
<ide> expect(4);
<ide> | 1 |
Java | Java | remove deprecated uiimplementationprovider | e7d75631959f1ce3f50a44f13056eacaf82378ff | <ide><path>ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java
<ide> import com.facebook.react.modules.deviceinfo.DeviceInfoModule;
<ide> import com.facebook.react.modules.systeminfo.AndroidInfoModule;
<ide> import com.facebook.react.turbomodule.core.interfaces.TurboModule;
<del>import com.facebook.react.uimanager.UIImplementationProvider;
<ide> import com.facebook.react.uimanager.UIManagerModule;
<ide> import com.facebook.react.uimanager.ViewManager;
<ide> import com.facebook.react.uimanager.ViewManagerResolver;
<ide> public class CoreModulesPackage extends TurboReactPackage implements ReactPackag
<ide> public CoreModulesPackage(
<ide> ReactInstanceManager reactInstanceManager,
<ide> DefaultHardwareBackBtnHandler hardwareBackBtnHandler,
<del> @Nullable UIImplementationProvider uiImplementationProvider,
<ide> boolean lazyViewManagersEnabled,
<ide> int minTimeLeftInFrameForNonBatchedOperationMs) {
<ide> mReactInstanceManager = reactInstanceManager;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> import com.facebook.react.turbomodule.core.interfaces.TurboModuleRegistry;
<ide> import com.facebook.react.uimanager.DisplayMetricsHolder;
<ide> import com.facebook.react.uimanager.ReactRoot;
<del>import com.facebook.react.uimanager.UIImplementationProvider;
<ide> import com.facebook.react.uimanager.UIManagerHelper;
<ide> import com.facebook.react.uimanager.ViewManager;
<ide> import com.facebook.react.views.imagehelper.ResourceDrawableIdHelper;
<ide> public static ReactInstanceManagerBuilder builder() {
<ide> boolean requireActivity,
<ide> @Nullable NotThreadSafeBridgeIdleDebugListener bridgeIdleDebugListener,
<ide> LifecycleState initialLifecycleState,
<del> @Nullable UIImplementationProvider mUIImplementationProvider,
<ide> JSExceptionHandler jSExceptionHandler,
<ide> @Nullable RedBoxHandler redBoxHandler,
<ide> boolean lazyViewManagersEnabled,
<ide> public void invokeDefaultOnBackPressed() {
<ide> ReactInstanceManager.this.invokeDefaultOnBackPressed();
<ide> }
<ide> },
<del> mUIImplementationProvider,
<ide> lazyViewManagersEnabled,
<ide> minTimeLeftInFrameForNonBatchedOperationMs));
<ide> if (mUseDeveloperSupport) {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java
<ide> import com.facebook.react.jscexecutor.JSCExecutorFactory;
<ide> import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
<ide> import com.facebook.react.packagerconnection.RequestHandler;
<del>import com.facebook.react.uimanager.UIImplementationProvider;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> public class ReactInstanceManagerBuilder {
<ide> private @Nullable DevSupportManagerFactory mDevSupportManagerFactory;
<ide> private boolean mRequireActivity;
<ide> private @Nullable LifecycleState mInitialLifecycleState;
<del> private @Nullable UIImplementationProvider mUIImplementationProvider;
<ide> private @Nullable JSExceptionHandler mJSExceptionHandler;
<ide> private @Nullable Activity mCurrentActivity;
<ide> private @Nullable DefaultHardwareBackBtnHandler mDefaultHardwareBackBtnHandler;
<ide> public class ReactInstanceManagerBuilder {
<ide>
<ide> /* package protected */ ReactInstanceManagerBuilder() {}
<ide>
<del> /** Sets a provider of {@link UIImplementation}. Uses default provider if null is passed. */
<del> public ReactInstanceManagerBuilder setUIImplementationProvider(
<del> @Nullable UIImplementationProvider uiImplementationProvider) {
<del> mUIImplementationProvider = uiImplementationProvider;
<del> return this;
<del> }
<del>
<ide> public ReactInstanceManagerBuilder setJSIModulesPackage(
<ide> @Nullable JSIModulePackage jsiModulePackage) {
<ide> mJSIModulesPackage = jsiModulePackage;
<ide> public ReactInstanceManager build() {
<ide> mJSMainModulePath != null || mJSBundleAssetUrl != null || mJSBundleLoader != null,
<ide> "Either MainModulePath or JS Bundle File needs to be provided");
<ide>
<del> if (mUIImplementationProvider == null) {
<del> // create default UIImplementationProvider if the provided one is null.
<del> mUIImplementationProvider = new UIImplementationProvider();
<del> }
<del>
<ide> // We use the name of the device and the app for debugging & metrics
<ide> //noinspection ConstantConditions
<ide> String appName = mApplication.getPackageName();
<ide> public ReactInstanceManager build() {
<ide> mRequireActivity,
<ide> mBridgeIdleDebugListener,
<ide> Assertions.assertNotNull(mInitialLifecycleState, "Initial lifecycle state was not set"),
<del> mUIImplementationProvider,
<ide> mJSExceptionHandler,
<ide> mRedBoxHandler,
<ide> mLazyViewManagersEnabled,
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java
<ide> import com.facebook.react.common.SurfaceDelegateFactory;
<ide> import com.facebook.react.devsupport.DevSupportManagerFactory;
<ide> import com.facebook.react.devsupport.interfaces.RedBoxHandler;
<del>import com.facebook.react.uimanager.UIImplementationProvider;
<ide> import java.util.List;
<ide>
<ide> /**
<ide> protected ReactInstanceManager createReactInstanceManager() {
<ide> .setLazyViewManagersEnabled(getLazyViewManagersEnabled())
<ide> .setRedBoxHandler(getRedBoxHandler())
<ide> .setJavaScriptExecutorFactory(getJavaScriptExecutorFactory())
<del> .setUIImplementationProvider(getUIImplementationProvider())
<ide> .setJSIModulesPackage(getJSIModulePackage())
<ide> .setInitialLifecycleState(LifecycleState.BEFORE_CREATE)
<ide> .setReactPackageTurboModuleManagerDelegateBuilder(
<ide> protected final Application getApplication() {
<ide> return mApplication;
<ide> }
<ide>
<del> /**
<del> * Get the {@link UIImplementationProvider} to use. Override this method if you want to use a
<del> * custom UI implementation.
<del> *
<del> * <p>Note: this is very advanced functionality, in 99% of cases you don't need to override this.
<del> */
<del> protected UIImplementationProvider getUIImplementationProvider() {
<del> return new UIImplementationProvider();
<del> }
<del>
<ide> protected @Nullable JSIModulePackage getJSIModulePackage() {
<ide> return null;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java
<ide> import com.facebook.yoga.YogaConstants;
<ide> import com.facebook.yoga.YogaDirection;
<ide> import java.util.Arrays;
<del>import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> /**
<ide> public interface LayoutUpdateListener {
<ide> void onLayoutUpdated(ReactShadowNode root);
<ide> }
<ide>
<del> public UIImplementation(
<del> ReactApplicationContext reactContext,
<del> ViewManagerResolver viewManagerResolver,
<del> EventDispatcher eventDispatcher,
<del> int minTimeLeftInFrameForNonBatchedOperationMs) {
<del> this(
<del> reactContext,
<del> new ViewManagerRegistry(viewManagerResolver),
<del> eventDispatcher,
<del> minTimeLeftInFrameForNonBatchedOperationMs);
<del> }
<del>
<del> public UIImplementation(
<del> ReactApplicationContext reactContext,
<del> List<ViewManager> viewManagers,
<del> EventDispatcher eventDispatcher,
<del> int minTimeLeftInFrameForNonBatchedOperationMs) {
<del> this(
<del> reactContext,
<del> new ViewManagerRegistry(viewManagers),
<del> eventDispatcher,
<del> minTimeLeftInFrameForNonBatchedOperationMs);
<del> }
<del>
<ide> UIImplementation(
<ide> ReactApplicationContext reactContext,
<ide> ViewManagerRegistry viewManagers,
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementationProvider.java
<del>/*
<del> * Copyright (c) Meta Platforms, Inc. and affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>package com.facebook.react.uimanager;
<del>
<del>import com.facebook.react.bridge.ReactApplicationContext;
<del>import com.facebook.react.uimanager.events.EventDispatcher;
<del>import com.facebook.systrace.Systrace;
<del>import java.util.List;
<del>
<del>/** Provides UIImplementation to use in {@link UIManagerModule}. */
<del>@Deprecated
<del>public class UIImplementationProvider {
<del>
<del> public UIImplementation createUIImplementation(
<del> ReactApplicationContext reactContext,
<del> ViewManagerResolver viewManagerResolver,
<del> EventDispatcher eventDispatcher,
<del> int minTimeLeftInFrameForNonBatchedOperationMs) {
<del> Systrace.beginSection(
<del> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementationProvider.createUIImplementation[1]");
<del> try {
<del> return new UIImplementation(
<del> reactContext,
<del> viewManagerResolver,
<del> eventDispatcher,
<del> minTimeLeftInFrameForNonBatchedOperationMs);
<del> } finally {
<del> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<del> }
<del> }
<del>
<del> public UIImplementation createUIImplementation(
<del> ReactApplicationContext reactContext,
<del> List<ViewManager> viewManagerList,
<del> EventDispatcher eventDispatcher,
<del> int minTimeLeftInFrameForNonBatchedOperationMs) {
<del> Systrace.beginSection(
<del> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementationProvider.createUIImplementation[2]");
<del> try {
<del> return new UIImplementation(
<del> reactContext,
<del> viewManagerList,
<del> eventDispatcher,
<del> minTimeLeftInFrameForNonBatchedOperationMs);
<del> } finally {
<del> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<del> }
<del> }
<del>
<del> UIImplementation createUIImplementation(
<del> ReactApplicationContext reactContext,
<del> ViewManagerRegistry viewManagerRegistry,
<del> EventDispatcher eventDispatcher,
<del> int minTimeLeftInFrameForNonBatchedOperationMs) {
<del> Systrace.beginSection(
<del> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementationProvider.createUIImplementation[3]");
<del> try {
<del> return new UIImplementation(
<del> reactContext,
<del> viewManagerRegistry,
<del> eventDispatcher,
<del> minTimeLeftInFrameForNonBatchedOperationMs);
<del> } finally {
<del> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<del> }
<del> }
<del>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java
<ide> public interface CustomEventNamesResolver {
<ide> private int mBatchId = 0;
<ide> private int mNumRootViews = 0;
<ide>
<del> @SuppressWarnings("deprecated")
<ide> public UIManagerModule(
<ide> ReactApplicationContext reactContext,
<ide> ViewManagerResolver viewManagerResolver,
<ide> int minTimeLeftInFrameForNonBatchedOperationMs) {
<del> this(
<del> reactContext,
<del> viewManagerResolver,
<del> new UIImplementationProvider(),
<del> minTimeLeftInFrameForNonBatchedOperationMs);
<del> }
<del>
<del> @SuppressWarnings("deprecated")
<del> public UIManagerModule(
<del> ReactApplicationContext reactContext,
<del> List<ViewManager> viewManagersList,
<del> int minTimeLeftInFrameForNonBatchedOperationMs) {
<del> this(
<del> reactContext,
<del> viewManagersList,
<del> new UIImplementationProvider(),
<del> minTimeLeftInFrameForNonBatchedOperationMs);
<del> }
<del>
<del> @Deprecated
<del> public UIManagerModule(
<del> ReactApplicationContext reactContext,
<del> ViewManagerResolver viewManagerResolver,
<del> UIImplementationProvider uiImplementationProvider,
<del> int minTimeLeftInFrameForNonBatchedOperationMs) {
<ide> super(reactContext);
<ide> DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext);
<ide> mEventDispatcher = new EventDispatcherImpl(reactContext);
<ide> mModuleConstants = createConstants(viewManagerResolver);
<ide> mCustomDirectEvents = UIManagerModuleConstants.getDirectEventTypeConstants();
<ide> mViewManagerRegistry = new ViewManagerRegistry(viewManagerResolver);
<ide> mUIImplementation =
<del> uiImplementationProvider.createUIImplementation(
<add> new UIImplementation(
<ide> reactContext,
<ide> mViewManagerRegistry,
<ide> mEventDispatcher,
<ide> public UIManagerModule(
<ide> reactContext.addLifecycleEventListener(this);
<ide> }
<ide>
<del> @Deprecated
<ide> public UIManagerModule(
<ide> ReactApplicationContext reactContext,
<ide> List<ViewManager> viewManagersList,
<del> UIImplementationProvider uiImplementationProvider,
<ide> int minTimeLeftInFrameForNonBatchedOperationMs) {
<ide> super(reactContext);
<ide> DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext);
<ide> public UIManagerModule(
<ide> mModuleConstants = createConstants(viewManagersList, null, mCustomDirectEvents);
<ide> mViewManagerRegistry = new ViewManagerRegistry(viewManagersList);
<ide> mUIImplementation =
<del> uiImplementationProvider.createUIImplementation(
<add> new UIImplementation(
<ide> reactContext,
<ide> mViewManagerRegistry,
<ide> mEventDispatcher,
<ide> public void runGuarded() {
<ide> }
<ide>
<ide> /** Listener that drops the CSSNode pool on low memory when the app is backgrounded. */
<del> private class MemoryTrimCallback implements ComponentCallbacks2 {
<add> private static class MemoryTrimCallback implements ComponentCallbacks2 {
<ide>
<ide> @Override
<ide> public void onTrimMemory(int level) { | 7 |
Python | Python | add keycertificateconnection class | 0c61644b6a281a342f1055a4cf11470e4a5c75ff | <ide><path>libcloud/common/base.py
<ide> def __init__(self, cert_file, secure=True, host=None, port=None, url=None,
<ide> self.cert_file = cert_file
<ide>
<ide>
<add>class KeyCertificateConnection(CertificateConnection):
<add> """
<add> Base connection class which accepts both ``key_file and cert_file``
<add> argument.
<add> """
<add> key_file=None
<add> def __init__(self, key_file, cert_file, secure=True, host=None, port=None,
<add> url=None, proxy_url=None, timeout=None, backoff=None,
<add> retry_delay=None):
<add> """
<add> Initialize `cert_file`; set `secure` to an ``int`` based on
<add> passed value.
<add> """
<add> super(KeyCertificateConnection, self).__init__(cert_file,
<add> secure=secure,
<add> host=host,
<add> port=port, url=url,
<add> timeout=timeout,
<add> backoff=backoff,
<add> retry_delay=retry_delay,
<add> proxy_url=proxy_url)
<add>
<add> self.key_file = key_file
<add>
<add>
<ide> class ConnectionUserAndKey(ConnectionKey):
<ide> """
<ide> Base connection class which accepts a ``user_id`` and ``key`` argument. | 1 |
PHP | PHP | update some docblocks | 6c150a23209a06329dc82b5e70060170f0874ac0 | <ide><path>src/Illuminate/Cookie/Guard.php
<ide> protected function encrypt(Response $response)
<ide> /**
<ide> * Duplicate a cookie with a new value.
<ide> *
<del> * @param \Symfony\Component\HttpFoundation\Cookie $cookie
<add> * @param \Symfony\Component\HttpFoundation\Cookie $c
<ide> * @param mixed $value
<ide> * @return \Symfony\Component\HttpFoundation\Cookie
<ide> */
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function getObservableEvents()
<ide> /**
<ide> * Set the observable event names.
<ide> *
<add> * @param array $observables
<ide> * @return void
<ide> */
<ide> public function setObservableEvents(array $observables)
<ide> public function getKeyName()
<ide> /**
<ide> * Set the primary key for the model.
<ide> *
<add> * @param string $key
<ide> * @return void
<ide> */
<ide> public function setKeyName($key)
<ide><path>src/Illuminate/Database/Schema/Blueprint.php
<ide> public function binary($column)
<ide> * Add the proper columns for a polymorphic table.
<ide> *
<ide> * @param string $name
<add> * @param string|null $indexName
<ide> * @return void
<ide> */
<ide> public function morphs($name, $indexName = null)
<ide><path>src/Illuminate/Foundation/Console/RoutesCommand.php
<ide> protected function getRoutes()
<ide> /**
<ide> * Get the route information for a given route.
<ide> *
<del> * @param string $name
<ide> * @param \Illuminate\Routing\Route $route
<ide> * @return array
<ide> */
<ide><path>src/Illuminate/Html/FormBuilder.php
<ide> protected function setQuickTextAreaSize($options)
<ide> * Create a number input field.
<ide> *
<ide> * @param string $name
<del> * @param array $options
<add> * @param string|null $value
<add> * @param array $options
<ide> * @return string
<ide> */
<ide> public function number($name, $value = null, $options = array()) | 5 |
Ruby | Ruby | add missing test | 98de70e2e12cff98acbc38727e709ff99db331b6 | <ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb
<ide> def test_polymorphic_with_custom_primary_key
<ide>
<ide> assert_equal toy, sponsor.reload.sponsorable
<ide> end
<add>
<add> test "stale tracking doesn't care about the type" do
<add> apple = Firm.create("name" => "Apple")
<add> citibank = Account.create("credit_limit" => 10)
<add>
<add> citibank.firm_id = apple.id
<add> citibank.firm # load it
<add>
<add> citibank.firm_id = apple.id.to_s
<add>
<add> assert !citibank.association(:firm).stale_target?
<add> end
<ide> end | 1 |
Python | Python | remove unused files | 399e0e859ca7874bd068bc3667e86c8410ca7b53 | <ide><path>doc/source/user/plot_approx.py
<del>from scipy import misc
<del>import matplotlib.pyplot as plt
<del>import numpy as np
<del>from numpy import linalg
<del>
<del>img = misc.face()
<del>img_array = img / 255
<del>img_gray = img_array @ [0.2126, 0.7152, 0.0722]
<del>
<del>U, s, Vt = linalg.svd(img_gray)
<del>
<del>Sigma = np.zeros((768, 1024))
<del>for i in range(768):
<del> Sigma[i, i] = s[i]
<del>
<del>k = 10
<del>
<del>approx = U @ Sigma[:, :k] @ Vt[:k, :]
<del>plt.imshow(approx, cmap="gray")
<ide><path>doc/source/user/plot_face.py
<del>from scipy import misc
<del>import matplotlib.pyplot as plt
<del>
<del>img = misc.face()
<del>plt.imshow(img)
<ide><path>doc/source/user/plot_final.py
<del>from scipy import misc
<del>import matplotlib.pyplot as plt
<del>import numpy as np
<del>from numpy import linalg
<del>
<del>img = misc.face()
<del>img_array = img / 255
<del>img_array_transposed = np.transpose(img_array, (2, 0, 1))
<del>
<del>U, s, Vt = linalg.svd(img_array_transposed)
<del>
<del>Sigma = np.zeros((3, 768, 1024))
<del>for j in range(3):
<del> np.fill_diagonal(Sigma[j, :, :], s[j, :])
<del>
<del>k = 10
<del>
<del>approx_img = U @ Sigma[..., :k] @ Vt[..., :k, :]
<del>plt.imshow(np.transpose(approx_img, (1, 2, 0)))
<ide><path>doc/source/user/plot_gray.py
<del>from scipy import misc
<del>import matplotlib.pyplot as plt
<del>import numpy as np
<del>
<del>img = misc.face()
<del>img_array = img / 255
<del>img_gray = img_array @ [0.2126, 0.7152, 0.0722]
<del>plt.imshow(img_gray, cmap="gray")
<ide><path>doc/source/user/plot_gray_svd.py
<del>from scipy import misc
<del>import matplotlib.pyplot as plt
<del>import numpy as np
<del>from numpy import linalg
<del>
<del>img = misc.face()
<del>img_array = img / 255
<del>img_gray = img_array @ [0.2126, 0.7152, 0.0722]
<del>
<del>U, s, Vt = linalg.svd(img_gray)
<del>
<del>Sigma = np.zeros((768, 1024))
<del>for i in range(768):
<del> Sigma[i, i] = s[i]
<del>
<del>plt.plot(s)
<ide><path>doc/source/user/plot_reconstructed.py
<del>from scipy import misc
<del>import matplotlib.pyplot as plt
<del>import numpy as np
<del>from numpy import linalg
<del>
<del>img = misc.face()
<del>img_array = img / 255
<del>img_array_transposed = np.transpose(img_array, (2, 0, 1))
<del>
<del>U, s, Vt = linalg.svd(img_array_transposed)
<del>
<del>Sigma = np.zeros((3, 768, 1024))
<del>for j in range(3):
<del> np.fill_diagonal(Sigma[j, :, :], s[j, :])
<del>
<del>reconstructed = U @ Sigma @ Vt
<del>plt.imshow(np.transpose(reconstructed, (1, 2, 0))) | 6 |
Text | Text | write a release guide | fbfecd13ce03d0386ea93b73cc645ccc09bbbed3 | <ide><path>scripts/release-manager/Readme.md
<ide>
<ide> This is a tool that is being used to manage React releases.
<ide>
<del>General prereqs:
<del>- A separate clone of React. This clone can be anywhere, so long as it is a separate working copy. Ideally this is where you are most comfortable working on React.
<del>- Your `react` clone should have the latest commits fetched before running commands. You may need to rebase or reset & re-run commands if not.
<add>## Prerequisites
<ide>
<add>You should have an existing clone of the React repo. We will call this a **“working copy”**. Ideally this is where you are most comfortable working on React.
<ide>
<del>## Commands
<add>Your working copy of React **should be up to date**. Check out the `master` branch in it and run `git pull` just to be sure.
<ide>
<del>### `init`
<add>## Cloning the Release Manager
<ide>
<del>Run this first, it will make sure you have a GitHub token generated, letting you use the API.
<add>**If this is your first time using the Release Manager**, you need to set it up.
<add>Skip this section if you’ve done this before.
<ide>
<del>### `docs-prs`
<add>The Release Manager is also located inside the React repository so you need to **clone it to a separate folder**. Call it something other than `react` so that you don’t confuse it with the working copy.
<ide>
<del>Cherry-picks PRs that have the `Documentation: needs merge to stable` label from `master` to the current branch. Then it removes the label from the PRs and pushes the branch to the remote it's tracking (resulting in Travis CI rebuilding the website)
<add>Check it out, install the dependencies, and run the CLI:
<ide>
<del>**Prereqs:**
<del>- Have your `react` clone on the branch from which the production website is generate (currently `15-stable`)
<add> ```
<add> cd ~/projects # or wherever
<add> git clone https://github.com/facebook/react.git react-release-manager
<add> cd react-release-manager/scripts/release-manager
<add> yarn
<add> ./cli.js
<add> ```
<add>
<add> You will see a command-line interface that lets you enter commands.
<add> It will need to learn a few things to work on your machine.
<add> Type `init` and press Enter. It will ask you a few prompts:
<add>
<add> 1. `GitHub token? (needs "repo" privs)`
<add> Follow [these instructions](https://help.github.com/articles/creating-an-access-token-for-command-line-use/) to generate a GitHub token. Make sure to put a checkmark for `repo` privileges. Don’t share it with anyone!
<ide>
<del>### `stable-prs`
<add> 2. `Location of local React checkout?`
<add> Enter the local path to your React working copy. For example, it is `~/projects/react` on my machine.
<add>
<add>Now you should be all set for releasing React on this machine!
<ide>
<del>Cherry-picks PRs that are set to the `15-next` milestone. Handles merge conflicts by pausing & allowing you to switch to your working copy of React to manually merge. A menu allows you to continue from where you left off.
<add>## Before You Do Anything Else
<ide>
<del>**Prereqs:**
<del>- Have your `react` clone on the dev branch (currently `15-dev`)
<add>You should have two separate React checkouts by now:
<ide>
<del>### `version`
<add>* **The Release Manager copy.** The previous section described how to set it up. You will only use this checkout for *running* the Release Manager. Run `git checkout master` and `git pull` to ensure it is up-to-date.
<ide>
<del>Bumps the version in all the places that need it.
<add>* **Your working copy of React.** The Release Manager will operate on it, and you will fix any merge conflicts inside of it. This should be the folder path you specified when you ran `init` in the previous section. Run `git checkout master` and `git pull` to ensure it is up-to-date.
<ide>
<del>### `npm-publish`
<add>Both clones clean and up-to-date?
<add>If you aren’t already running it, run the Release Manager CLI:
<ide>
<del>Publishes all built packages to npm (`next` dist-tag) and then for stable releases, also updates the `latest` dist-tag.
<add>```
<add>cd react-release-manager/scripts/release-manager
<add>./cli.js
<add>```
<ide>
<del>**Prereqs:**
<del>- Have done everything else required for releasing (updating version, etc) and run `grunt build` or `grunt release`.
<add>Keep your working copy and the running Release Manager in separate terminal tabs.
<ide>
<del>### `q`
<add>## Updating the Documentation
<add>
<add>When we merge a pull request to the documentation and it is relevant to the current version, we tag it with a `Documentation: needs merge to stable` label. The Release Manager can cherry-pick those commits so that they appear on the website.
<add>
<add>The documentation is built from the current stable branch. For example, for React 15.x the branch is called `15-stable`. Switch your working copy to it:
<add>
<add>```
<add>cd react
<add>git checkout 15-stable
<add>git pull
<add>```
<add>
<add>Then, in the Release Manager, run the command:
<add>
<add>```
<add>docs-prs
<add>```
<add>
<add>The Release Manager should find the PRs that haven’t been merged yet. Reply with `y` to get them merged and then with `y` to push your changes.
<add>
<add>**Tip:** If you see an error like `The previous cherry-pick is now empty, possibly due to conflict resolution` it might mean that there’s a stray PR with a label that has already been merged to the stable branch. In this case you need to remove the label manually and retry the command.
<add>
<add>## Cutting a Release
<add>
<add>### Verifying Permissions
<add>
<add>In the Release Manager, verify you have npm publish permissions:
<add>
<add>```
<add>npm-check-access
<add>```
<add>
<add>You will need to get all permissions before you can proceed.
<add>
<add>### Cherry Picking PRs
<add>
<add>If the permissions are cool, run:
<add>
<add>```
<add>start-release
<add>```
<add>
<add>**Tip:** if you get an error saying `'upstream' does not appear to be a git repository`, run `git remote add upstream https://github.com/facebook/react.git` in your working copy of React and try again.
<add>
<add>If everything went well, you should see a green `OK!` in the output.
<add>
<add>Create a new milestone in the [GitHub web interface](https://github.com/facebook/react/milestones) for the new release. Name it exactly after the version you intend to cut (e.g. `15.4.1`). Then run:
<add>
<add>```
<add>stable-prs
<add>```
<add>
<add>First, choose the current major “stable” milestone (such as `15-next`). Note that the Release Manager only sees merged PRs that have this milestone.
<add>
<add>**Tip:** our 15.x branch has diverged significantly so we are using `15-hipri` for things we really need to get out, and `15-lopri` for everything else. This is a temporary situation that should get better after Fiber is out.
<add>
<add>Next, choose the milestone you just created. This one should be specific and correspond to the version you intend to publish (such as `15.4.1`). The Release Manager will re-tag all PRs matching the previous “stable” milestone with this specific milestone after cherry-picking them.
<add>
<add>Finally, pick all appropriate labels with a spacebar. For example, a patch release usually contains `exempt` and `patch` PRs, and a minor release contains `minor` PRs in addition to them.
<add>
<add>Now the Release Manager will find all relevant PRs and attempt to cherry-pick them. Before agreeing to this, copy the list of PRs it prints out so that you can look them up later when you write the changelog.
<add>
<add>It is likely that some PRs won’t get merged cleanly. You’ll need to manually resolve the conflicts in the working copy. If the resolutions are not obvious it might be a sign the branches diverged too much which might be bad. (Talk to the team.)
<add>
<add>### Verifying the Changes
<add>
<add>Your working copy should now be in a clean state on a development branch. For example, during 15.x the development branch is `15-dev`.
<add>
<add>Verify it by running:
<add>
<add>```
<add>git status
<add>
<add>>On branch 15-dev
<add>>Your branch is ahead of 'origin/15-dev' by 10 commits.
<add>> (use "git push" to publish your local commits)
<add>>nothing to commit, working directory clean
<add>```
<add>
<add>Next, run `npm test`.
<add>
<add>If there are any issues you might have introduced mistakes resolving conflicts.
<add>You can fix them in a separate commit.
<add>
<add>**Tip:** tests might also be failing if dependency versions are incorrect. You might want to run `yarn` first since sometimes `package.json` on master is different from the stable branches.
<add>
<add>### Push and Choose the Branch
<add>
<add>If you followed the guide correctly (and ran `start-release` in the beginning), you should be on a “stable development” branch such as `15-dev`. Now is a good time to push the development branch:
<add>
<add>```
<add>git push
<add>```
<add>
<add>Then comes the important part.
<add>**If you plan to cut a stable release, switch the branch to the stable branch now.**
<add>
<add>For example, if you plan to cut `15.4.1` (rather than a `15.4.1-0` alpha release), run:
<add>
<add>```
<add>git checkout 15-stable
<add>git merge --no-ff 15-dev
<add>```
<add>
<add>This will merge the commits you cherry-picked into the stable branch.
<add>
<add>However, if you plan to cut an alpha or a beta, you should stay on the “stable development” branch.
<add>
<add>### Update the Shrinkwrap
<add>
<add>Run this so that the build is reproducible:
<add>
<add>```
<add>rm npm-shrinkwrap.json
<add>rm -rf node_modules
<add>npm cache clear
<add>npm i
<add>npm shrinkwrap --dev
<add>```
<add>
<add>Check `git diff`. Do changes look sensible?
<add>
<add>**Tip:** there are buggy npm versions that remove information from shrinkwrap. If you see a lot of `"dev": true` lines removed, you may be on a buggy version. Last time I tried, `npm@3.10.8` worked well.
<add>
<add>Commit your changes:
<add>
<add>```
<add>git commit -am 'Update shrinkwrap'
<add>```
<add>
<add>If you’re feeling extra careful, you can run `npm test` again.
<add>
<add>### Write the Changelog
<add>
<add>**This step is only necessary for a stable release.**
<add>If you’re just cutting an alpha, you should skip it.
<add>
<add>Open `CHANGELOG.md` in the working copy and add release notes in the same format as earlier. It’s usually a good idea to summarize changes in a friendly way instead of using PR titles. While you may skip non-essential changes, it’s still good to give credit to contributors, so maybe group them together. You can verify that you haven’t messed up the markup by previewing them in an online Markdown editor.
<add>
<add>Commit your changes, for example:
<add>
<add>```
<add>git commit -am 'Add <put the version here> changelog'
<add>```
<add>
<add>You will see the commit hash. Copy it in your editor. You will need it later to cherry-pick the changelog update to master.
<add>
<add>### Bump the Version
<add>
<add>In the Release Manager, run:
<add>
<add>```
<add>version
<add>```
<add>
<add>It will ask you about the version you want to ship and it will commit the result with a tag.
<add>
<add>We’re not pushing anything yet, it will just create a local commit.
<add>
<add>### Ensure You Have the Bower Repo
<add>
<add>**This step is only necessary for a stable release.**
<add>If you’re just cutting an alpha, you should skip it.
<add>
<add>There’s another repository you need to clone!
<add>This time, it should be a sibling of your React working copy.
<add>
<add>In the working copy directory, you can run:
<add>
<add>```
<add>git clone https://github.com/reactjs/react-bower.git ../react-bower
<add>```
<add>
<add>### Build It!
<add>
<add>The next step depends on the type of release you want to cut.
<add>
<add>For a **stable** release, run in the working copy:
<add>
<add>```
<add>./node_modules/.bin/grunt release
<add>```
<add>
<add>This will create the build products in the working copy. You won’t see changes in git because the `build` folder is ignored. It will also create a commit and a tag in the `../react-bower` folder. I recommend checking `git log` and running `git show <put last commit hash here>` to verify the changes roughly correspond to what you expect.
<add>
<add>For a **pre-release**, run this instead:
<add>
<add>```
<add>npm run build
<add>```
<add>
<add>### Verify the Build Works
<add>
<add>At the very least, open `fixtures/globals.html` in the browser. You should see a “Hello, World!” fading in, and the console should have no errors.
<add>
<add>If you changed anything related to how packages are created, I recommend following the instructions in `fixtures/README.md` and verifying that each of those manual tests works. You can skip the “build React” step in it but still need to build the fixtures.
<add>
<add>They are manual tests, so the CI wouldn’t have caught errors in them.
<add>
<add>### Update the Docs
<add>
<add>**This step is only necessary for a stable release.**
<add>If you’re just cutting an alpha, you should skip it.
<add>
<add>You will see that `docs/js/react-dom.js` and `docs/js/react.js` have changed. This is because the docs are now using a newer version of React. In addition to those changes, bump the version inside `docs/_config.yml`:
<add>
<add>```diff
<add>- react_version: 15.4.0
<add>+ react_version: <put the new version here>
<add>```
<add>
<add>Now commit the changes:
<add>
<add>```
<add>git commit -am 'Update React version in docs'
<add>```
<add>
<add>### Push the Working Copy
<add>
<add>Now we are ready to push the branch in the working copy:
<add>
<add>```
<add>git push
<add>git push --tags
<add>```
<add>
<add>### Release on Bower
<add>
<add>**This step is only necessary for a stable release.**
<add>If you’re just cutting an alpha, you should skip it.
<add>
<add>Go to the Bower folder from your working copy and push the new commit and tag:
<add>
<add>```
<add>cd ../react-bower
<add>git push
<add>git push --tags
<add>cd ../react
<add>```
<add>
<add>### Release on npm
<add>
<add>In the Release Manager, run:
<add>
<add>```
<add>npm-publish
<add>```
<add>
<add>### Cherry-Pick the Changelog
<add>
<add>**This step is only necessary for a stable release.**
<add>If you’re just cutting an alpha, you should skip it.
<add>
<add>Remember how you saved the hash of the commit changelog a few hours before?
<add>
<add>Now it’s time to switch our working copy to `master` and cherry-pick it:
<add>
<add>```
<add>git checkout master
<add>git pull
<add>git cherry-pick <hash of the changelog commit>
<add>```
<add>
<add>Verify you picked the right commit:
<add>
<add>```
<add>git diff HEAD~
<add>```
<add>
<add>Looks good? Push it.
<add>
<add>```
<add>git push
<add>```
<add>
<add>### Creating a GitHub Release
<add>
<add>**This step is only necessary for a stable release.**
<add>If you’re just cutting an alpha, you should skip it.
<add>
<add>Copy your new release notes from `CHANGELOG.md` and [create a new Release](https://github.com/facebook/react/releases/new) on GitHub. Choose the tag version you just pushed in the dropdown so that it says “Existing tag”. Paste the release notes and push the button.
<add>
<add>### Force-Updating the Website
<add>
<add>**This step is only necessary for a stable release.**
<add>If you’re just cutting an alpha, you should skip it.
<add>
<add>Normally the docs should update themselves after CI runs.
<add>However sometimes our CI might be slow or something might break.
<add>
<add>You can rebuild the docs manually if you want to.
<add>Make sure you have a React copy in a sibling folder called `react-gh-pages`:
<add>
<add>```
<add>git clone https://github.com/facebook/react.git ../react-gh-pages
<add>```
<add>
<add>Then make sure it’s on `gh-pages` branch and that it’s up-to-date:
<add>
<add>```
<add>cd ../react-gh-pages
<add>git checkout gh-pages
<add>git pull
<add>```
<add>
<add>Switch back to the working copy and go to the `docs` folder:
<add>
<add>```
<add>cd ../react/docs
<add>```
<add>
<add>Switch to the stable branch (the one you just spent a lot of time with).
<add>For example:
<add>
<add>```
<add>git checkout 15-stable
<add>```
<add>
<add>Build the docs now:
<add>
<add>```
<add>bundle install # Might need sudo.
<add>bundle exec rake release
<add>```
<add>
<add>If this fails, maybe you’re missing some Ruby dependencies:
<add>
<add>```
<add>gem install bundler
<add>```
<add>
<add>Install them and try again.
<add>
<add>This should not produce any changes in the working copy, but `react-gh-pages` should get some file changes:
<add>
<add>```
<add>cd ../../react-gh-pages
<add>git diff
<add>```
<add>
<add>If they look alright, commit and push them:
<add>
<add>```
<add>git commit -am 'Rebuild the website'
<add>git push
<add>```
<add>
<add>Now open https://facebook.github.io/react/, give it a few minutes, refresh, and behold.
<add>
<add>Don’t forget to switch to `master` for the future development.
<add>
<add>```
<add>git checkout master
<add>```
<add>
<add>### Bonus: Trying It Out
<add>
<add>Run:
<add>
<add>```
<add>npm i -g create-react-app
<add>create-react-app ../my-new-app
<add>cd ../my-new-app
<add>npm start
<add>```
<add>
<add>This should use the latest version of React.
<ide>
<del>A secret alias to `exit` because `q` is faster. | 1 |
Text | Text | add the text "my change" to the article | c7abdcecf9a16b707418e2fda0c5cb2efee03329 | <ide><path>guide/english/game-development/unreal-engine/index.md
<ide> Unreal has gone through 4 major revisions. Although some code is common between
<ide> Released in 2015 and targets PC, PlayStation 4, Xbox One, Mac OS X, iOS, Android, many VR systems, Linux, SteamOS, and HTML5, and the editor can run on Windows, OS X and Linux. Unreal Script has been removed and replaced with dynamically reloaded C++ modules, and a more advanced visual scripting interface called Blueprints. Since the release of version 4.20, Unreal Engine has been taking big steps towards mobile gaming and currently is a great tool for developing high-end titles on Android, iOS platforms.
<ide>
<ide> ### Popular Games made in Unreal
<add>- Ashen
<ide> - Batman Arkham City
<ide> - Mass Effect
<ide> - Bioshock
<add>- BioShock 2
<ide> - Borderlands
<ide> - Gears of War
<ide> - Fortnite
<add>- Spec Ops: The Line
<add>- Disney's Brother Bear
<add>- Clive Barker's Undying
<add>- Deus Ex- Spec Ops: The Line
<add>- Enslaved: Odyssey to the West
<add>- Adventure Pinball: Forgotten Island
<add>
<ide>
<ide> #### More Information:
<ide> | 1 |
Ruby | Ruby | perform both tests within a single line | fe9713bf4ff7366be3a0909864c4aa1836eb9e09 | <ide><path>activesupport/lib/active_support/core_ext/class/subclasses.rb
<ide> class Class
<ide> def descendants
<ide> descendants = []
<ide> ObjectSpace.each_object(singleton_class) do |k|
<del> next if k.singleton_class?
<del> descendants.unshift k unless k == self
<add> descendants.unshift k unless k.singleton_class? || k == self
<ide> end
<ide> descendants
<ide> end | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.