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
Java
Java
fix possible npe in statusbarmodule
0f3be77b7d4177c8f94d775bf8ef2a2b68f1e828
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/statusbar/StatusBarModule.java <ide> public void run() { <ide> } <ide> <ide> @ReactMethod <del> public void setStyle(final String style) { <add> public void setStyle(@Nullable final String style) { <ide> final Activity activity = getCurrentActivity(); <ide> if (activity == null) { <ide> FLog.w(ReactConstants.TAG, "StatusBarModule: Ignored status bar change, current activity is null."); <ide> public void setStyle(final String style) { <ide> public void run() { <ide> View decorView = activity.getWindow().getDecorView(); <ide> decorView.setSystemUiVisibility( <del> style.equals("dark-content") ? View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR : 0); <add> "dark-content".equals(style) ? View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR : 0); <ide> } <ide> } <ide> );
1
PHP
PHP
add a setup method in broadcastertest
fa9359c8fed0211ddff970ee99a61e75bcd4fca8
<ide><path>tests/Broadcasting/BroadcasterTest.php <ide> <ide> class BroadcasterTest extends TestCase <ide> { <add> /** <add> * @var \Illuminate\Tests\Broadcasting\FakeBroadcaster <add> */ <add> public $broadcaster; <add> <add> public function setUp() <add> { <add> parent::setUp(); <add> <add> $this->broadcaster = new FakeBroadcaster; <add> } <add> <ide> public function tearDown() <ide> { <ide> m::close(); <ide> } <ide> <ide> public function testExtractingParametersWhileCheckingForUserAccess() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <ide> $callback = function ($user, BroadcasterTestEloquentModelStub $model, $nonModel) { <ide> }; <del> $parameters = $broadcaster->extractAuthParameters('asd.{model}.{nonModel}', 'asd.1.something', $callback); <add> $parameters = $this->broadcaster->extractAuthParameters('asd.{model}.{nonModel}', 'asd.1.something', $callback); <ide> $this->assertEquals(['model.1.instance', 'something'], $parameters); <ide> <ide> $callback = function ($user, BroadcasterTestEloquentModelStub $model, BroadcasterTestEloquentModelStub $model2, $something) { <ide> }; <del> $parameters = $broadcaster->extractAuthParameters('asd.{model}.{model2}.{nonModel}', 'asd.1.uid.something', $callback); <add> $parameters = $this->broadcaster->extractAuthParameters('asd.{model}.{model2}.{nonModel}', 'asd.1.uid.something', $callback); <ide> $this->assertEquals(['model.1.instance', 'model.uid.instance', 'something'], $parameters); <ide> <ide> $callback = function ($user) { <ide> }; <del> $parameters = $broadcaster->extractAuthParameters('asd', 'asd', $callback); <add> $parameters = $this->broadcaster->extractAuthParameters('asd', 'asd', $callback); <ide> $this->assertEquals([], $parameters); <ide> <ide> $callback = function ($user, $something) { <ide> }; <del> $parameters = $broadcaster->extractAuthParameters('asd', 'asd', $callback); <add> $parameters = $this->broadcaster->extractAuthParameters('asd', 'asd', $callback); <ide> $this->assertEquals([], $parameters); <ide> <ide> /* <ide> public function testExtractingParametersWhileCheckingForUserAccess() <ide> $container->instance(BindingRegistrar::class, $binder); <ide> $callback = function ($user, $model) { <ide> }; <del> $parameters = $broadcaster->extractAuthParameters('something.{model}', 'something.1', $callback); <add> $parameters = $this->broadcaster->extractAuthParameters('something.{model}', 'something.1', $callback); <ide> $this->assertEquals(['bound'], $parameters); <ide> Container::setInstance(new Container); <ide> } <ide> <ide> public function testCanUseChannelClasses() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <del> $parameters = $broadcaster->extractAuthParameters('asd.{model}.{nonModel}', 'asd.1.something', DummyBroadcastingChannel::class); <add> $parameters = $this->broadcaster->extractAuthParameters('asd.{model}.{nonModel}', 'asd.1.something', DummyBroadcastingChannel::class); <ide> $this->assertEquals(['model.1.instance', 'something'], $parameters); <ide> } <ide> <ide> public function testCanUseChannelClasses() <ide> */ <ide> public function testUnknownChannelAuthHandlerTypeThrowsException() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <del> $broadcaster->extractAuthParameters('asd.{model}.{nonModel}', 'asd.1.something', 123); <add> $this->broadcaster->extractAuthParameters('asd.{model}.{nonModel}', 'asd.1.something', 123); <ide> } <ide> <ide> public function testCanRegisterChannelsAsClasses() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <del> $broadcaster->channel('something', function () { <add> $this->broadcaster->channel('something', function () { <ide> }); <del> $broadcaster->channel('somethingelse', DummyBroadcastingChannel::class); <add> $this->broadcaster->channel('somethingelse', DummyBroadcastingChannel::class); <ide> } <ide> <ide> /** <ide> * @expectedException \Symfony\Component\HttpKernel\Exception\HttpException <ide> */ <ide> public function testNotFoundThrowsHttpException() <ide> { <del> $broadcaster = new FakeBroadcaster; <ide> $callback = function ($user, BroadcasterTestEloquentModelNotFoundStub $model) { <ide> }; <del> $broadcaster->extractAuthParameters('asd.{model}', 'asd.1', $callback); <add> $this->broadcaster->extractAuthParameters('asd.{model}', 'asd.1', $callback); <ide> } <ide> <ide> public function testCanRegisterChannelsWithoutOptions() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <del> $broadcaster->channel('somechannel', function () {}); <add> $this->broadcaster->channel('somechannel', function () {}); <ide> } <ide> <ide> public function testCanRegisterChannelsWithOptions() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <ide> $options = [ 'a' => [ 'b', 'c' ] ]; <del> $broadcaster->channel('somechannel', function () {}, $options); <add> $this->broadcaster->channel('somechannel', function () {}, $options); <ide> } <ide> <ide> public function testCanRetrieveChannelsOptions() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <ide> $options = [ 'a' => [ 'b', 'c' ] ]; <del> $broadcaster->channel('somechannel', function () {}, $options); <add> $this->broadcaster->channel('somechannel', function () {}, $options); <ide> <ide> $this->assertEquals( <ide> $options, <del> $broadcaster->retrieveChannelOptions('somechannel') <add> $this->broadcaster->retrieveChannelOptions('somechannel') <ide> ); <ide> } <ide> <ide> public function testCanRetrieveChannelsOptionsUsingAChannelNameContainingArgs() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <ide> $options = [ 'a' => [ 'b', 'c' ] ]; <del> $broadcaster->channel('somechannel.{id}.test.{text}', function () {}, $options); <add> $this->broadcaster->channel('somechannel.{id}.test.{text}', function () {}, $options); <ide> <ide> $this->assertEquals( <ide> $options, <del> $broadcaster->retrieveChannelOptions('somechannel.23.test.mytext') <add> $this->broadcaster->retrieveChannelOptions('somechannel.23.test.mytext') <ide> ); <ide> } <ide> <ide> public function testCanRetrieveChannelsOptionsWhenMultipleChannelsAreRegistered() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <ide> $options = [ 'a' => [ 'b', 'c' ] ]; <del> $broadcaster->channel('somechannel', function () {}); <del> $broadcaster->channel('someotherchannel', function () {}, $options); <add> $this->broadcaster->channel('somechannel', function () {}); <add> $this->broadcaster->channel('someotherchannel', function () {}, $options); <ide> <ide> $this->assertEquals( <ide> $options, <del> $broadcaster->retrieveChannelOptions('someotherchannel') <add> $this->broadcaster->retrieveChannelOptions('someotherchannel') <ide> ); <ide> } <ide> <ide> public function testDontRetrieveChannelsOptionsWhenChannelDoesntExists() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <ide> $options = [ 'a' => [ 'b', 'c' ] ]; <del> $broadcaster->channel('somechannel', function () {}, $options); <add> $this->broadcaster->channel('somechannel', function () {}, $options); <ide> <ide> $this->assertEquals( <ide> [], <del> $broadcaster->retrieveChannelOptions('someotherchannel') <add> $this->broadcaster->retrieveChannelOptions('someotherchannel') <ide> ); <ide> } <ide> <ide> public function testRetrieveUserWithoutGuard() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <del> $broadcaster->channel('somechannel', function () {}); <add> $this->broadcaster->channel('somechannel', function () {}); <ide> <ide> $request = m::mock(\Illuminate\Http\Request::class); <ide> $request->shouldReceive('user') <ide> public function testRetrieveUserWithoutGuard() <ide> <ide> $this->assertInstanceOf( <ide> DummyUser::class, <del> $broadcaster->retrieveUser($request, 'somechannel') <add> $this->broadcaster->retrieveUser($request, 'somechannel') <ide> ); <ide> } <ide> <ide> public function testRetrieveUserWithOneGuardUsingAStringForSpecifyingGuard() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <del> $broadcaster->channel('somechannel', function () {}, ['guards' => 'myguard']); <add> $this->broadcaster->channel('somechannel', function () {}, ['guards' => 'myguard']); <ide> <ide> $request = m::mock(\Illuminate\Http\Request::class); <ide> $request->shouldReceive('user') <ide> public function testRetrieveUserWithOneGuardUsingAStringForSpecifyingGuard() <ide> <ide> $this->assertInstanceOf( <ide> DummyUser::class, <del> $broadcaster->retrieveUser($request, 'somechannel') <add> $this->broadcaster->retrieveUser($request, 'somechannel') <ide> ); <ide> } <ide> <ide> public function testRetrieveUserWithMultipleGuardsAndRespectGuardsOrder() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <del> $broadcaster->channel('somechannel', function () {}, ['guards' => ['myguard1', 'myguard2']]); <del> $broadcaster->channel('someotherchannel', function () {}, ['guards' => ['myguard2', 'myguard1']]); <add> $this->broadcaster->channel('somechannel', function () {}, ['guards' => ['myguard1', 'myguard2']]); <add> $this->broadcaster->channel('someotherchannel', function () {}, ['guards' => ['myguard2', 'myguard1']]); <ide> <ide> <ide> $request = m::mock(\Illuminate\Http\Request::class); <ide> public function testRetrieveUserWithMultipleGuardsAndRespectGuardsOrder() <ide> <ide> $this->assertInstanceOf( <ide> DummyUser::class, <del> $broadcaster->retrieveUser($request, 'somechannel') <add> $this->broadcaster->retrieveUser($request, 'somechannel') <ide> ); <ide> <ide> $this->assertInstanceOf( <ide> DummyUser::class, <del> $broadcaster->retrieveUser($request, 'someotherchannel') <add> $this->broadcaster->retrieveUser($request, 'someotherchannel') <ide> ); <ide> } <ide> <ide> public function testRetrieveUserDontUseDefaultGuardWhenOneGuardSpecified() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <del> $broadcaster->channel('somechannel', function () {}, ['guards' => 'myguard']); <add> $this->broadcaster->channel('somechannel', function () {}, ['guards' => 'myguard']); <ide> <ide> $request = m::mock(\Illuminate\Http\Request::class); <ide> $request->shouldReceive('user') <ide> public function testRetrieveUserDontUseDefaultGuardWhenOneGuardSpecified() <ide> $request->shouldNotReceive('user') <ide> ->withNoArgs(); <ide> <del> $broadcaster->retrieveUser($request, 'somechannel'); <add> $this->broadcaster->retrieveUser($request, 'somechannel'); <ide> } <ide> <ide> public function testRetrieveUserDontUseDefaultGuardWhenMultipleGuardsSpecified() <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <del> $broadcaster->channel('somechannel', function () {}, ['guards' => ['myguard1', 'myguard2']]); <del> <add> $this->broadcaster->channel('somechannel', function () {}, ['guards' => ['myguard1', 'myguard2']]); <ide> <ide> $request = m::mock(\Illuminate\Http\Request::class); <ide> $request->shouldReceive('user') <ide> public function testRetrieveUserDontUseDefaultGuardWhenMultipleGuardsSpecified() <ide> $request->shouldNotReceive('user') <ide> ->withNoArgs(); <ide> <del> $broadcaster->retrieveUser($request, 'somechannel'); <add> $this->broadcaster->retrieveUser($request, 'somechannel'); <ide> } <ide> <ide> /** <ide> * @dataProvider channelNameMatchPatternProvider <ide> */ <ide> public function testChannelNameMatchPattern($channel, $pattern, $shouldMatch) <ide> { <del> $broadcaster = new FakeBroadcaster; <del> <del> $this->assertEquals($shouldMatch, $broadcaster->channelNameMatchPattern($channel, $pattern)); <add> $this->assertEquals($shouldMatch, $this->broadcaster->channelNameMatchPattern($channel, $pattern)); <ide> } <ide> <ide> public function channelNameMatchPatternProvider() {
1
Python
Python
improve the computation of polynomials from roots
ef767a54fae8977cb15d7e0849a8cb626c4b0f2c
<ide><path>numpy/polynomial/chebyshev.py <ide> def chebfromroots(roots) : <ide> return np.ones(1) <ide> else : <ide> [roots] = pu.as_series([roots], trim=False) <del> prd = np.array([1], dtype=roots.dtype) <del> for r in roots: <del> prd = chebsub(chebmulx(prd), r*prd) <del> return prd <add> roots.sort() <add> n = len(roots) <add> p = [chebline(-r, 1) for r in roots] <add> while n > 1: <add> m = n//2 <add> tmp = [chebmul(p[i], p[i+m]) for i in range(m)] <add> if n%2: <add> tmp[0] = chebmul(tmp[0], p[-1]) <add> p = tmp <add> n = m <add> return p[0] <ide> <ide> <ide> def chebadd(c1, c2): <ide><path>numpy/polynomial/hermite.py <ide> def hermfromroots(roots) : <ide> return np.ones(1) <ide> else : <ide> [roots] = pu.as_series([roots], trim=False) <del> prd = np.array([1], dtype=roots.dtype) <del> for r in roots: <del> prd = hermsub(hermmulx(prd), r*prd) <del> return prd <add> roots.sort() <add> n = len(roots) <add> p = [hermline(-r, 1) for r in roots] <add> while n > 1: <add> m = n//2 <add> tmp = [hermmul(p[i], p[i+m]) for i in range(m)] <add> if n%2: <add> tmp[0] = hermmul(tmp[0], p[-1]) <add> p = tmp <add> n = m <add> return p[0] <ide> <ide> <ide> def hermadd(c1, c2): <ide><path>numpy/polynomial/hermite_e.py <ide> def hermefromroots(roots) : <ide> return np.ones(1) <ide> else : <ide> [roots] = pu.as_series([roots], trim=False) <del> prd = np.array([1], dtype=roots.dtype) <del> for r in roots: <del> prd = hermesub(hermemulx(prd), r*prd) <del> return prd <add> roots.sort() <add> n = len(roots) <add> p = [hermeline(-r, 1) for r in roots] <add> while n > 1: <add> m = n//2 <add> tmp = [hermemul(p[i], p[i+m]) for i in range(m)] <add> if n%2: <add> tmp[0] = hermemul(tmp[0], p[-1]) <add> p = tmp <add> n = m <add> return p[0] <ide> <ide> <ide> def hermeadd(c1, c2): <ide><path>numpy/polynomial/laguerre.py <ide> def lagfromroots(roots) : <ide> return np.ones(1) <ide> else : <ide> [roots] = pu.as_series([roots], trim=False) <del> prd = np.array([1], dtype=roots.dtype) <del> for r in roots: <del> prd = lagsub(lagmulx(prd), r*prd) <del> return prd <add> roots.sort() <add> n = len(roots) <add> p = [lagline(-r, 1) for r in roots] <add> while n > 1: <add> m = n//2 <add> tmp = [lagmul(p[i], p[i+m]) for i in range(m)] <add> if n%2: <add> tmp[0] = lagmul(tmp[0], p[-1]) <add> p = tmp <add> n = m <add> return p[0] <ide> <ide> <ide> def lagadd(c1, c2): <ide><path>numpy/polynomial/legendre.py <ide> def legfromroots(roots) : <ide> return np.ones(1) <ide> else : <ide> [roots] = pu.as_series([roots], trim=False) <del> prd = np.array([1], dtype=roots.dtype) <del> for r in roots: <del> prd = legsub(legmulx(prd), r*prd) <del> return prd <add> roots.sort() <add> n = len(roots) <add> p = [legline(-r, 1) for r in roots] <add> while n > 1: <add> m = n//2 <add> tmp = [legmul(p[i], p[i+m]) for i in range(m)] <add> if n%2: <add> tmp[0] = legmul(tmp[0], p[-1]) <add> p = tmp <add> n = m <add> return p[0] <ide> <ide> <ide> def legadd(c1, c2): <ide><path>numpy/polynomial/polynomial.py <ide> def polyfromroots(roots) : <ide> return np.ones(1) <ide> else : <ide> [roots] = pu.as_series([roots], trim=False) <del> prd = np.array([1], dtype=roots.dtype) <del> for r in roots: <del> prd = polysub(polymulx(prd), r*prd) <del> return prd <add> roots.sort() <add> n = len(roots) <add> p = [polyline(-r, 1) for r in roots] <add> while n > 1: <add> m = n//2 <add> tmp = [polymul(p[i], p[i+m]) for i in range(m)] <add> if n%2: <add> tmp[0] = polymul(tmp[0], p[-1]) <add> p = tmp <add> n = m <add> return p[0] <ide> <ide> <ide> def polyadd(c1, c2):
6
Javascript
Javascript
add missing @returns to extend()
59eb50204a046599e02a7af0bc31d83a95b81f15
<ide><path>src/Angular.js <ide> function setHashKey(obj, h) { <ide> * <ide> * @param {Object} dst Destination object. <ide> * @param {...Object} src Source object(s). <add> * @returns {Object} Reference to `dst`. <ide> */ <ide> function extend(dst) { <ide> var h = dst.$$hashKey;
1
Javascript
Javascript
rerun $digest from root, rather then per scope
1c9fc1e1dec67c8c05f02da1e0853439238c4d8e
<ide><path>src/Scope.js <ide> Scope.prototype = { <ide> watch, value, last, <ide> watchers = this.$$watchers, <ide> length, count = 0, <del> iterationCount, ttl = 100; <add> dirtyCount, ttl = 100, <add> recheck = !this.$parent || !this.$parent.$$phase; <ide> <ide> if (this.$$phase) { <ide> throw Error(this.$$phase + ' already in progress'); <ide> } <ide> this.$$phase = '$digest'; <ide> do { <del> iterationCount = 0; <add> dirtyCount = 0; <ide> if (watchers) { <ide> // process our watches <ide> length = watchers.length; <ide> Scope.prototype = { <ide> // Most common watches are on primitives, in which case we can short <ide> // circuit it with === operator, only when === fails do we use .equals <ide> if ((value = watch.get(this)) !== (last = watch.last) && !equals(value, last)) { <del> iterationCount++; <add> dirtyCount++; <ide> watch.fn(this, watch.last = copy(value), last); <ide> } <ide> } catch (e) { <ide> Scope.prototype = { <ide> } <ide> child = this.$$childHead; <ide> while(child) { <del> iterationCount += child.$digest(); <add> dirtyCount += child.$digest(); <ide> child = child.$$nextSibling; <ide> } <del> count += iterationCount; <add> count += dirtyCount; <ide> if(!(ttl--)) { <ide> throw Error('100 $digest() iterations reached. Aborting!'); <ide> } <del> } while (iterationCount); <add> } while (recheck && dirtyCount); <ide> this.$$phase = null; <ide> return count; <ide> }, <ide><path>test/ScopeSpec.js <ide> describe('Scope', function(){ <ide> expect(log).toEqual('abc'); <ide> }); <ide> <add> it('should repeat watch cycle from the root elemnt', function(){ <add> var log = ''; <add> var child = root.$new(); <add> root.$watch(function(){ log += 'a'; }); <add> child.$watch(function(){ log += 'b'; }); <add> root.$digest(); <add> expect(log).toEqual('abab'); <add> }); <add> <ide> <ide> it('should prevent infinite recursion', function(){ <ide> root.$watch('a', function(self, v){self.b++;});
2
Python
Python
fix model init from jsonl
59d655e8d04814896ce173a35e0c1788563d5f15
<ide><path>spacy/cli/init_model.py <ide> def init_model(lang, output_dir, freqs_loc=None, clusters_loc=None, jsonl_loc=No <ide> if vectors_loc and vectors_loc.parts[-1].endswith('.npz'): <ide> vectors_data = numpy.load(vectors_loc.open('rb')) <ide> vector_keys = [lex['orth'] for lex in lex_attrs <del> if 'rank' in lex and lex['rank'] < vectors_data.shape[0]] <add> if 'id' in lex and lex['id'] < vectors_data.shape[0]] <ide> else: <ide> vectors_data, vector_keys = read_vectors(vectors_loc) if vectors_loc else (None, None) <ide> nlp = create_model(lang, lex_attrs, vectors_data, vector_keys, prune_vectors) <ide> def read_attrs_from_deprecated(freqs_loc, clusters_loc): <ide> lex_attrs = {} <ide> sorted_probs = sorted(probs.items(), key=lambda item: item[1], reverse=True) <ide> for i, (word, prob) in tqdm(enumerate(sorted_probs)): <del> attrs = {'orth': word, 'rank': i, 'prob': prob} <add> attrs = {'orth': word, 'id': i, 'prob': prob} <ide> # Decode as a little-endian string, so that we can do & 15 to get <ide> # the first 4 bits. See _parse_features.pyx <ide> if word in clusters:
1
Javascript
Javascript
provide better error message for unhandled error
8b9a1537ad5c34c92215660291e962558b6bc8d3
<ide><path>lib/events.js <ide> EventEmitter.prototype.emit = function emit(type) { <ide> } else if (er instanceof Error) { <ide> throw er; // Unhandled 'error' event <ide> } else { <del> throw new Error('Uncaught, unspecified "error" event.'); <add> // At least give some kind of context to the user <add> var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); <add> err.context = er; <add> throw err; <ide> } <ide> return false; <ide> } <ide><path>test/parallel/test-event-emitter-errors.js <add>var EventEmitter = require('events'); <add>var assert = require('assert'); <add> <add>var EE = new EventEmitter(); <add> <add>assert.throws(function() { <add> EE.emit('error', 'Accepts a string'); <add>}, /Accepts a string/);
2
Javascript
Javascript
update path calculation
b1b949d35ee995ee75c6968715a7f8c8ea601157
<ide><path>test/jquery.js <ide> ( function() { <ide> /* global loadTests: false */ <ide> <del> var path = window.location.pathname.split( "test" )[ 0 ], <add> var pathname = window.location.pathname, <add> path = pathname.slice( 0, pathname.lastIndexOf( "test" ) ), <ide> QUnit = window.QUnit || parent.QUnit, <ide> require = window.require || parent.require, <ide>
1
Java
Java
improve exception message
7f4bf41c2320aa8e552ca3c6d568cfa65adc7f65
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/MockRestServiceServer.java <ide> private RequestMatcherClientHttpRequest createRequestInternal(URI uri, HttpMetho <ide> this.requestIterator = MockRestServiceServer.this.expectedRequests.iterator(); <ide> } <ide> if (!this.requestIterator.hasNext()) { <del> throw new AssertionError("No further requests expected"); <add> throw new AssertionError("No further requests expected: HTTP " + httpMethod + " " + uri); <ide> } <ide> <ide> RequestMatcherClientHttpRequest request = this.requestIterator.next();
1
Javascript
Javascript
handle empty username
138115f2a8752e6d7198fefce9e563d994e7b1e2
<ide><path>src/main-process/atom-application.js <ide> class AtomApplication extends EventEmitter { <ide> // Public: The entry point into the Atom application. <ide> static open (options) { <ide> if (!options.socketPath) { <del> const username = process.platform === 'win32' ? process.env.USERNAME : process.env.USER <add> const {username} = os.userInfo() <ide> <ide> // Lowercasing the ATOM_HOME to make sure that we don't get multiple sockets <ide> // on case-insensitive filesystems due to arbitrary case differences in paths. <ide> class AtomApplication extends EventEmitter { <ide> .update('|') <ide> .update(process.arch) <ide> .update('|') <del> .update(username) <add> .update(username || '') <ide> .update('|') <ide> .update(atomHomeUnique) <ide>
1
Python
Python
fix a typo
72a51ef373ec41e99f719e2c41f32606279ddbc4
<ide><path>libcloud/storage/drivers/local.py <ide> 'using pip: pip install lockfile') <ide> <ide> from libcloud.utils.files import read_in_chunks <del>from libcloud.utils.py import relpath <add>from libcloud.utils.py3 import relpath <ide> from libcloud.common.base import Connection <ide> from libcloud.storage.base import Object, Container, StorageDriver <ide> from libcloud.common.types import LibcloudError
1
Ruby
Ruby
extract methods out of the cache update method
9798a11c2bc9cef5d66efe5006b607c9d858da76
<ide><path>activerecord/lib/active_record/associations/belongs_to_association.rb <ide> def update_counters(record) <ide> <ide> return unless counter_cache_name && owner.persisted? <ide> <del> diff_target = if record <del> different_target?(record) <del> else <del> owner[reflection.foreign_key] <del> end <del> <del> if diff_target <del> if record <del> record.class.increment_counter(counter_cache_name, record.id) <del> end <del> <del> if foreign_key_present? <del> klass.decrement_counter(counter_cache_name, target_id) <del> end <add> if record <add> update_with_record record, counter_cache_name <add> else <add> update_without_record counter_cache_name <add> end <add> end <add> <add> def update_with_record record, counter_cache_name <add> return unless different_target? record <add> <add> record.class.increment_counter(counter_cache_name, record.id) <add> <add> decrement_counter counter_cache_name <add> end <add> <add> def update_without_record counter_cache_name <add> decrement_counter counter_cache_name <add> end <add> <add> def decrement_counter counter_cache_name <add> if foreign_key_present? <add> klass.decrement_counter(counter_cache_name, target_id) <ide> end <ide> end <ide>
1
Python
Python
add new reshape option
84d06a530ebbe59679acdc03b3b13460037582e9
<ide><path>keras/engine/topology.py <ide> def save_weights(self, filepath, overwrite=True): <ide> f.flush() <ide> f.close() <ide> <del> def load_weights(self, filepath, by_name=False, skip_mismatch=False): <add> def load_weights(self, filepath, by_name=False, <add> skip_mismatch=False, reshape=False): <ide> """Loads all layer weights from a HDF5 save file. <ide> <ide> If `by_name` is False (default) weights are loaded <ide> def load_weights(self, filepath, by_name=False, skip_mismatch=False): <ide> where there is a mismatch in the number of weights, <ide> or a mismatch in the shape of the weight <ide> (only valid when `by_name`=True). <add> reshape: Reshape weights to fit the layer when the correct number <add> of values are present but the shape does not match. <ide> <ide> <ide> # Raises <ide> def load_weights(self, filepath, by_name=False, skip_mismatch=False): <ide> f = f['model_weights'] <ide> if by_name: <ide> load_weights_from_hdf5_group_by_name( <del> f, self.layers, skip_mismatch=skip_mismatch) <add> f, self.layers, skip_mismatch=skip_mismatch, <add> reshape=reshape) <ide> else: <del> load_weights_from_hdf5_group(f, self.layers) <add> load_weights_from_hdf5_group( <add> f, self.layers, reshape=reshape) <ide> <ide> if hasattr(f, 'close'): <ide> f.close() <ide> def save_weights_to_hdf5_group(f, layers): <ide> <ide> def preprocess_weights_for_loading(layer, weights, <ide> original_keras_version=None, <del> original_backend=None): <add> original_backend=None, <add> reshape=False): <ide> """Converts layers weights from Keras 1 format to Keras 2. <ide> <ide> # Arguments <ide> def preprocess_weights_for_loading(layer, weights, <ide> original_keras_version: Keras version for the weights, as a string. <ide> original_backend: Keras backend the weights were trained with, <ide> as a string. <add> reshape: Reshape weights to fit the layer when the correct number <add> of values are present but the shape does not match. <ide> <ide> # Returns <ide> A list of weights values (Numpy arrays). <ide> def preprocess_weights_for_loading(layer, weights, <ide> 'Conv2DTranspose', <ide> 'ConvLSTM2D'] <ide> if layer.__class__.__name__ in conv_layers: <add> layer_weights_shape = K.int_shape(layer.weights[0]) <ide> if _need_convert_kernel(original_backend): <ide> weights[0] = conv_utils.convert_kernel(weights[0]) <ide> if layer.__class__.__name__ == 'ConvLSTM2D': <ide> weights[1] = conv_utils.convert_kernel(weights[1]) <del> if K.int_shape(layer.weights[0]) != weights[0].shape: <add> if reshape and layer_weights_shape != weights[0].shape: <add> if weights[0].size != np.prod(layer_weights_shape): <add> raise ValueError('Weights must be of equal size to ' + <add> 'apply a reshape operation. ' + <add> 'Layer ' + layer.name + <add> '\'s weights have shape ' + <add> str(layer_weights_shape) + ' and size ' + <add> str(np.prod(layer_weights_shape)) + '. ' + <add> 'The weights for loading have shape ' + <add> str(weights[0].shape) + ' and size ' + <add> str(weights[0].size) + '. ') <add> weights[0] = np.reshape(weights[0], layer_weights_shape) <add> elif layer_weights_shape != weights[0].shape: <ide> weights[0] = np.transpose(weights[0], (3, 2, 0, 1)) <ide> if layer.__class__.__name__ == 'ConvLSTM2D': <ide> weights[1] = np.transpose(weights[1], (3, 2, 0, 1)) <ide> def _need_convert_kernel(original_backend): <ide> return uses_correlation[original_backend] != uses_correlation[K.backend()] <ide> <ide> <del>def load_weights_from_hdf5_group(f, layers): <add>def load_weights_from_hdf5_group(f, layers, reshape=False): <ide> """Implements topological (order-based) weight loading. <ide> <ide> # Arguments <ide> f: A pointer to a HDF5 group. <ide> layers: a list of target layers. <add> reshape: Reshape weights to fit the layer when the correct number <add> of values are present but the shape does not match. <ide> <ide> # Raises <ide> ValueError: in case of mismatch between provided layers <ide> def load_weights_from_hdf5_group(f, layers): <ide> weight_values = preprocess_weights_for_loading(layer, <ide> weight_values, <ide> original_keras_version, <del> original_backend) <add> original_backend, <add> reshape=reshape) <ide> if len(weight_values) != len(symbolic_weights): <ide> raise ValueError('Layer #' + str(k) + <ide> ' (named "' + layer.name + <ide> def load_weights_from_hdf5_group(f, layers): <ide> K.batch_set_value(weight_value_tuples) <ide> <ide> <del>def load_weights_from_hdf5_group_by_name(f, layers, skip_mismatch=False): <add>def load_weights_from_hdf5_group_by_name(f, layers, skip_mismatch=False, <add> reshape=False): <ide> """Implements name-based weight loading. <ide> <ide> (instead of topological weight loading). <ide> def load_weights_from_hdf5_group_by_name(f, layers, skip_mismatch=False): <ide> skip_mismatch: Boolean, whether to skip loading of layers <ide> where there is a mismatch in the number of weights, <ide> or a mismatch in the shape of the weights. <add> reshape: Reshape weights to fit the layer when the correct number <add> of values are present but the shape does not match. <ide> <ide> # Raises <ide> ValueError: in case of mismatch between provided layers <ide> def load_weights_from_hdf5_group_by_name(f, layers, skip_mismatch=False): <ide> layer, <ide> weight_values, <ide> original_keras_version, <del> original_backend) <add> original_backend, <add> reshape=reshape) <ide> if len(weight_values) != len(symbolic_weights): <ide> if skip_mismatch: <ide> warnings.warn('Skipping loading of weights for layer {}'.format(layer.name) + <ide><path>keras/models.py <ide> def set_weights(self, weights): <ide> self.build() <ide> self.model.set_weights(weights) <ide> <del> def load_weights(self, filepath, by_name=False, skip_mismatch=False): <add> def load_weights(self, filepath, by_name=False, skip_mismatch=False, reshape=False): <ide> if h5py is None: <ide> raise ImportError('`load_weights` requires h5py.') <ide> f = h5py.File(filepath, mode='r') <ide> def load_weights(self, filepath, by_name=False, skip_mismatch=False): <ide> layers = self.layers <ide> if by_name: <ide> topology.load_weights_from_hdf5_group_by_name(f, layers, <del> skip_mismatch=skip_mismatch) <add> skip_mismatch=skip_mismatch, <add> reshape=reshape) <ide> else: <del> topology.load_weights_from_hdf5_group(f, layers) <add> topology.load_weights_from_hdf5_group(f, layers, reshape=reshape) <ide> if hasattr(f, 'close'): <ide> f.close() <ide> <ide><path>tests/test_model_saving.py <ide> from keras import backend as K <ide> from keras.models import Model, Sequential <ide> from keras.layers import Dense, Lambda, RepeatVector, TimeDistributed, LSTM <add>from keras.layers import Conv2D, Flatten <ide> from keras.layers import Input <ide> from keras import optimizers <ide> from keras import losses <ide> def test_saving_unused_layers_is_ok(): <ide> <ide> <ide> @keras_test <del>def test_loading_weights_by_name(): <add>def test_loading_weights_by_name_and_reshape(): <ide> """ <ide> test loading model weights by name on: <ide> - sequential model <ide> def test_loading_weights_by_name(): <ide> <ide> # sequential model <ide> model = Sequential() <del> model.add(Dense(2, input_shape=(3,), name='rick')) <add> model.add(Conv2D(2, (1, 1), input_shape=(1, 1, 1), name='rick')) <add> model.add(Flatten()) <ide> model.add(Dense(3, name='morty')) <ide> model.compile(loss=custom_loss, optimizer=custom_opt(), metrics=['acc']) <ide> <del> x = np.random.random((1, 3)) <add> x = np.random.random((1, 1, 1, 1)) <ide> y = np.random.random((1, 3)) <ide> model.train_on_batch(x, y) <ide> <ide> def test_loading_weights_by_name(): <ide> # delete and recreate model <ide> del(model) <ide> model = Sequential() <del> model.add(Dense(2, input_shape=(3,), name='rick')) <del> model.add(Dense(3, name='morty')) <add> model.add(Conv2D(2, (1, 1), input_shape=(1, 1, 1), name='rick')) <add> model.add(Conv2D(3, (1, 1), name='morty')) <ide> model.compile(loss=custom_loss, optimizer=custom_opt(), metrics=['acc']) <ide> <ide> # load weights from first model <del> model.load_weights(fname, by_name=True) <add> with pytest.raises(ValueError): <add> model.load_weights(fname, by_name=True, reshape=False) <add> with pytest.raises(ValueError): <add> model.load_weights(fname, by_name=False, reshape=False) <add> model.load_weights(fname, by_name=False, reshape=True) <add> model.load_weights(fname, by_name=True, reshape=True) <ide> os.remove(fname) <ide> <ide> out2 = model.predict(x) <del> assert_allclose(out, out2, atol=1e-05) <add> assert_allclose(np.squeeze(out), np.squeeze(out2), atol=1e-05) <ide> for i in range(len(model.layers)): <ide> new_weights = model.layers[i].get_weights() <ide> for j in range(len(new_weights)): <del> assert_allclose(old_weights[i][j], new_weights[j], atol=1e-05) <add> # only compare layers that have weights, skipping Flatten() <add> if old_weights[i]: <add> assert_allclose(old_weights[i][j], new_weights[j], atol=1e-05) <ide> <ide> <ide> @keras_test
3
Text
Text
add some (very) late links
346ad93f901b50f200c5f869cf77fa727abe0d23
<ide><path>SUPPORTERS.md <ide> These brilliant people supported our Kickstarter by giving us £15 or more: <ide> * [Nick Jones](mailto:nick@dischord.org) <ide> * [Esmé Cowles](https://github.com/escowles) <ide> * [Garrett L. Ward](http://glward.net) <del>* Carl Laird <add>* [Carl Laird](http://allthingsoptimal.com) <ide> * [Mx A. Matienzo](http://matienzo.org/) <ide> * [Sean Dunn](http://www.dunns.me) <ide> * [Kara Van Malssen](http://avpreserve.com) <ide> These wonderful people supported our Kickstarter by giving us £10 or more: <ide> * [Derek Croft](http://www.kiindly.com) <ide> * [Doc Ritezel](http://ritezel.com) <ide> * [Christoph Heer](http://christophheer.me) <del>* Jakub Suder <add>* [Kuba Suder](http://mackuba.eu) <ide> * [Jason Garber](http://sixtwothree.org) <ide> * [Alejandro Caceres](http://punkspider.hyperiongray.com) <ide> * [Slobodan Miskovic](https://miskovic.ca)
1
Python
Python
update output shape in docstrings
88c26e2fbb92a93d884f405ebbec7eb1ad3daf50
<ide><path>keras/backend.py <ide> def rnn(step_function, <ide> - If `return_all_outputs=True`: a tensor with shape <ide> `(samples, time, ...)` where each entry `outputs[s, t]` is the <ide> output of the step function at time `t` for sample `s` <del> - Else, a tensor equal to `last_output` <add> - Else, a tensor equal to `last_output` with shape <add> `(samples, 1, ...)` <ide> new_states: list of tensors, latest states returned by <ide> the step function, of shape `(samples, ...)`. <ide> <ide><path>keras/layers/rnn/gru.py <ide> def standard_gru(inputs, init_h, kernel, recurrent_kernel, bias, mask, <ide> outputs: <ide> - If `return_sequences=True`: output tensor for all timesteps, <ide> which has shape [batch, time, units]. <del> - Else, a tensor equal to `last_output` <add> - Else, a tensor equal to `last_output` with shape [batch, 1, units] <ide> state_0: the cell output, which has same shape as init_h. <ide> runtime: constant string tensor which indicate real runtime hardware. This <ide> value is for testing purpose and should be used by user. <ide><path>keras/layers/rnn/lstm.py <ide> def standard_lstm(inputs, init_h, init_c, kernel, recurrent_kernel, bias, <ide> outputs: <ide> - If `return_sequences=True`: output tensor for all timesteps, <ide> which has shape [batch, time, units]. <del> - Else, a tensor equal to `last_output` <add> - Else, a tensor equal to `last_output` with shape [batch, 1, units] <ide> state_0: the cell output, which has same shape as init_h. <ide> state_1: the cell hidden state, which has same shape as init_c. <ide> runtime: constant string tensor which indicate real runtime hardware. This <ide> def gpu_lstm(inputs, init_h, init_c, kernel, recurrent_kernel, bias, mask, <ide> outputs: <ide> - If `return_sequences=True`: output tensor for all timesteps, <ide> which has shape [batch, time, units]. <del> - Else, a tensor equal to `last_output` <add> - Else, a tensor equal to `last_output` with shape [batch, 1, units] <ide> state_0: The cell output, which has same shape as init_h. <ide> state_1: The cell hidden state, which has same shape as init_c. <ide> runtime: Constant string tensor which indicate real runtime hardware. This
3
Text
Text
add link to `net.server` in tls.md
1d21c05a677d433c606031623d37cd9e0c194547
<ide><path>doc/api/tls.md <ide> connections on the specified `port` and `hostname`. <ide> This function operates asynchronously. If the `callback` is given, it will be <ide> called when the server has started listening. <ide> <del>See `net.Server` for more information. <add>See [`net.Server`][] for more information. <ide> <ide> ### server.setTicketKeys(keys) <ide> <!-- YAML
1
Mixed
Javascript
move dep0006 to end of life
d4934ae6f2745f8fab1a83821f50290c9688c326
<ide><path>doc/api/deprecations.md <ide> outside `node_modules` in order to better target developers, rather than users. <ide> ### DEP0006: child\_process options.customFds <ide> <!-- YAML <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/25279 <add> description: End-of-Life. <ide> - version: <ide> - v4.8.6 <ide> - v6.12.0 <ide> changes: <ide> description: Documentation-only deprecation. <ide> --> <ide> <del>Type: Runtime <add>Type: End-of-Life <ide> <ide> Within the [`child_process`][] module's `spawn()`, `fork()`, and `exec()` <ide> methods, the `options.customFds` option is deprecated. The `options.stdio` <ide><path>lib/child_process.js <ide> 'use strict'; <ide> <ide> const util = require('util'); <del>const { <del> deprecate, convertToValidSignal, getSystemErrorName <del>} = require('internal/util'); <add>const { convertToValidSignal, getSystemErrorName } = require('internal/util'); <ide> const { isArrayBufferView } = require('internal/util/types'); <ide> const debug = util.debuglog('child_process'); <ide> const { Buffer } = require('buffer'); <ide> Object.defineProperty(exports.execFile, util.promisify.custom, { <ide> value: customPromiseExecFunction(exports.execFile) <ide> }); <ide> <del>const _deprecatedCustomFds = deprecate( <del> function deprecateCustomFds(options) { <del> options.stdio = options.customFds.map(function mapCustomFds(fd) { <del> return fd === -1 ? 'pipe' : fd; <del> }); <del> }, 'child_process: options.customFds option is deprecated. ' + <del> 'Use options.stdio instead.', 'DEP0006'); <del> <del>function _convertCustomFds(options) { <del> if (options.customFds && !options.stdio) { <del> _deprecatedCustomFds(options); <del> } <del>} <del> <ide> function normalizeSpawnArguments(file, args, options) { <ide> validateString(file, 'file'); <ide> <ide> function normalizeSpawnArguments(file, args, options) { <ide> } <ide> } <ide> <del> _convertCustomFds(options); <del> <ide> return { <ide> file: file, <ide> args: args, <ide><path>test/parallel/test-child-process-custom-fds.js <del>// Flags: --expose_internals <del>'use strict'; <del>const common = require('../common'); <del>const assert = require('assert'); <del>const { spawnSync } = require('child_process'); <del>const internalCp = require('internal/child_process'); <del> <del>if (!common.isMainThread) <del> common.skip('stdio is not associated with file descriptors in Workers'); <del> <del>// This test uses the deprecated `customFds` option. We expect a deprecation <del>// warning, but only once (per node process). <del>const msg = 'child_process: options.customFds option is deprecated. ' + <del> 'Use options.stdio instead.'; <del>common.expectWarning('DeprecationWarning', msg, 'DEP0006'); <del> <del>// Verify that customFds is used if stdio is not provided. <del>{ <del> const customFds = [-1, process.stdout.fd, process.stderr.fd]; <del> const oldSpawnSync = internalCp.spawnSync; <del> internalCp.spawnSync = common.mustCall(function(opts) { <del> assert.deepStrictEqual(opts.options.customFds, customFds); <del> assert.deepStrictEqual(opts.options.stdio, [ <del> { type: 'pipe', readable: true, writable: false }, <del> { type: 'fd', fd: process.stdout.fd }, <del> { type: 'fd', fd: process.stderr.fd } <del> ]); <del> }); <del> spawnSync(...common.pwdCommand, { customFds }); <del> internalCp.spawnSync = oldSpawnSync; <del>} <del> <del>// Verify that customFds is ignored when stdio is present. <del>{ <del> const customFds = [0, 1, 2]; <del> const oldSpawnSync = internalCp.spawnSync; <del> internalCp.spawnSync = common.mustCall(function(opts) { <del> assert.deepStrictEqual(opts.options.customFds, customFds); <del> assert.deepStrictEqual(opts.options.stdio, [ <del> { type: 'pipe', readable: true, writable: false }, <del> { type: 'pipe', readable: false, writable: true }, <del> { type: 'pipe', readable: false, writable: true } <del> ]); <del> }); <del> spawnSync(...common.pwdCommand, { customFds, stdio: 'pipe' }); <del> internalCp.spawnSync = oldSpawnSync; <del>}
3
PHP
PHP
fix other failing test by 1 second difference
3b8990ffca90fd79b4cb51ca2676424d6f55a655
<ide><path>lib/Cake/Test/Case/Utility/FileTest.php <ide> public function testLastAccess() { <ide> * @return void <ide> */ <ide> public function testLastChange() { <add> $ts = time(); <ide> $someFile = new File(TMP . 'some_file.txt', false); <ide> $this->assertFalse($someFile->lastChange()); <ide> $this->assertTrue($someFile->open('r+')); <del> $this->assertEquals($someFile->lastChange(), time()); <add> $this->assertTrue($someFile->lastChange() >= $ts); <ide> $someFile->write('something'); <del> $this->assertEquals($someFile->lastChange(), time()); <add> $this->assertTrue($someFile->lastChange() >= $ts); <ide> $someFile->close(); <ide> $someFile->delete(); <ide> }
1
Python
Python
fix mlib.ini generation
35114ae7c33384b0acf7903469426a6955b23b7a
<ide><path>numpy/core/setup.py <ide> def visibility_define(config): <ide> return '' <ide> <ide> def mlib_pkg_content(mathlibs): <del> posix_mlib = ' -l'.join(mathlibs) <del> msvc_mlib = ' '.join(['%s.lib' for l in mathlibs]) <add> posix_mlib = ' '.join(['-l%s' % l for l in mathlibs]) <add> msvc_mlib = ' '.join(['%s.lib' % l for l in mathlibs]) <ide> ret = """ <ide> [meta] <ide> Name = mlib
1
Javascript
Javascript
remove space from generated unit-tests
30172c7bc91ae86cb61d79dbcd2328abca09570d
<ide><path>blueprints/component-test/qunit-files/tests/__testType__/__path__/__test__.js <ide> moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', <ide> }); <ide> <ide> test('it renders', function(assert) { <del> <% if (testType === 'integration' ) { %>// Set any properties with this.set('myProperty', 'value'); <add><% if (testType === 'integration' ) { %> <add> // Set any properties with this.set('myProperty', 'value'); <ide> // Handle any actions with this.on('myAction', function(val) { ... }); <ide> <ide> this.render(hbs`{{<%= componentPathName %>}}`);
1
Ruby
Ruby
pass explicit sort to handle apfs
e308df25a9af0e84172448f03a91892a98c92b8a
<ide><path>Library/Homebrew/cmd/commands.rb <ide> def commands <ide> else <ide> # Find commands in Homebrew/cmd <ide> puts "Built-in commands" <del> puts Formatter.columns(internal_commands) <add> puts Formatter.columns(internal_commands.sort) <ide> <ide> # Find commands in Homebrew/dev-cmd <ide> puts <ide> puts "Built-in developer commands" <del> puts Formatter.columns(internal_developer_commands) <add> puts Formatter.columns(internal_developer_commands.sort) <ide> <ide> # Find commands in the path <ide> unless (exts = external_commands).empty?
1
Javascript
Javascript
remove race condition in http flood test
cee14f52a3bdbd870429de49d8075c24798916c3
<ide><path>test/parallel/test-http-pipeline-flood.js <ide> const assert = require('assert'); <ide> // Normally when the writable stream emits a 'drain' event, the server then <ide> // uncorks the readable stream, although we arent testing that part here. <ide> <add>// The issue being tested exists in Node.js 0.10.20 and is resolved in 0.10.21 <add>// and newer. <add> <ide> switch (process.argv[2]) { <ide> case undefined: <ide> return parent(); <ide> switch (process.argv[2]) { <ide> function parent() { <ide> const http = require('http'); <ide> const bigResponse = new Buffer(10240).fill('x'); <del> var gotTimeout = false; <del> var childClosed = false; <ide> var requests = 0; <ide> var connections = 0; <ide> var backloggedReqs = 0; <ide> function parent() { <ide> const spawn = require('child_process').spawn; <ide> const args = [__filename, 'child']; <ide> const child = spawn(process.execPath, args, { stdio: 'inherit' }); <del> child.on('close', function() { <del> childClosed = true; <add> child.on('close', common.mustCall(function() { <ide> server.close(); <del> }); <add> })); <ide> <del> server.setTimeout(common.platformTimeout(200), function(conn) { <del> gotTimeout = true; <add> server.setTimeout(200, common.mustCall(function() { <ide> child.kill(); <del> }); <add> })); <ide> }); <ide> <ide> process.on('exit', function() { <del> assert(gotTimeout); <del> assert(childClosed); <ide> assert.equal(connections, 1); <ide> }); <ide> } <ide> function child() { <ide> <ide> req = new Array(10241).join(req); <ide> <del> conn.on('connect', function() { <del> // Terminate child after flooding. <del> setTimeout(function() { conn.destroy(); }, common.platformTimeout(1000)); <del> write(); <del> }); <add> conn.on('connect', write); <ide> <del> conn.on('drain', write); <add> // `drain` should fire once and only once <add> conn.on('drain', common.mustCall(write)); <ide> <ide> function write() { <ide> while (false !== conn.write(req, 'ascii'));
1
Javascript
Javascript
remove some leftovers from the previous patch
88512fbdd9fda60993ad718b97a407e81f5f33c1
<ide><path>PDFFont.js <ide> var FontsUtils = { <ide> }; <ide> <ide> <del>/** Implementation dirty logic starts here */ <del> <ide> /** <ide> * The TrueType class verify that the ttf embedded inside the PDF is correct in <ide> * the point of view of the OTS sanitizer and rewrite it on the fly otherwise. <ide> TrueType.prototype = { <ide> /** <ide> * This dictionary holds decoded fonts data. <ide> */ <del>var PSFonts = new Dict(); <del> <del>var Stack = function(aStackSize) { <del> var innerStack = new Array(aStackSize || 0); <del> <del> this.push = function(aOperand) { <del> innerStack.push(aOperand); <del> }; <del> <del> this.pop = function() { <del> if (!this.count()) <del> throw new Error("stackunderflow"); <del> return innerStack.pop(); <del> }; <del> <del> this.peek = function() { <del> if (!this.count()) <del> return null; <del> return innerStack[innerStack.length - 1]; <del> }; <del> <del> this.get = function(aIndex) { <del> return innerStack[aIndex]; <del> }; <del> <del> this.clear = function() { <del> innerStack = []; <del> }; <del> <del> this.count = function() { <del> return innerStack.length; <del> }; <del> <del> this.dump = function() { <del> for (var i = 0; i < this.length; i++) <del> log(innerStack[i]); <del> }; <del> <del> this.clone = function() { <del> return innerStack.slice(); <del> }; <del>}; <del> <ide> var Type1Parser = function() { <ide> // Turn on this flag for additional debugging logs <ide> var debug = false;
1
Mixed
Java
move default spacing out of csslayout
fd34c6d56757618364d2cb9c5fbe3ee10915620a
<ide><path>Examples/UIExplorer/js/TextInputExample.android.js <ide> class BlurOnSubmitExample extends React.Component { <ide> } <ide> } <ide> <add>class ToggleDefaultPaddingExample extends React.Component { <add> constructor(props) { <add> super(props); <add> this.state = {hasPadding: false}; <add> } <add> render() { <add> return ( <add> <View> <add> <TextInput style={this.state.hasPadding ? { padding: 0 } : null}/> <add> <Text onPress={() => this.setState({hasPadding: !this.state.hasPadding})}> <add> Toggle padding <add> </Text> <add> </View> <add> ); <add> } <add>} <add> <ide> var styles = StyleSheet.create({ <ide> multiline: { <ide> height: 60, <ide> exports.examples = [ <ide> ); <ide> } <ide> }, <add> { <add> title: 'Toggle Default Padding', <add> render: function(): ReactElement { return <ToggleDefaultPaddingExample />; }, <add> }, <ide> ]; <ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/CSSNode.java <ide> public CSSDirection getLayoutDirection() { <ide> return layout.direction; <ide> } <ide> <del> /** <del> * Set a default padding (left/top/right/bottom) for this node. <del> */ <del> @Override <del> public void setDefaultPadding(int spacingType, float padding) { <del> if (style.padding.setDefault(spacingType, padding)) { <del> dirty(); <del> } <del> } <del> <ide> /** <ide> * Get this node's overflow property, as defined in the style <ide> */ <ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/CSSNodeAPI.java <ide> void measure( <ide> float getLayoutWidth(); <ide> float getLayoutHeight(); <ide> CSSDirection getLayoutDirection(); <del> void setDefaultPadding(int spacingType, float padding); <ide> CSSOverflow getOverflow(); <ide> void setOverflow(CSSOverflow overflow); <ide> void setData(Object data); <ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/CSSNodeJNI.java <ide> public void setPadding(int spacingType, float padding) { <ide> jni_CSSNodeStyleSetPadding(mNativePointer, spacingType, padding); <ide> } <ide> <del> @Override <del> public void setDefaultPadding(int spacingType, float padding) { <del> // TODO <del> } <del> <ide> private native float jni_CSSNodeStyleGetBorder(long nativePointer, int edge); <ide> @Override <ide> public Spacing getBorder() { <ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/CSSStyle.java <ide> public class CSSStyle { <ide> public Spacing margin = new Spacing(); <ide> public Spacing padding = new Spacing(); <ide> public Spacing border = new Spacing(); <del> public Spacing position = new Spacing(); <add> public Spacing position = new Spacing(CSSConstants.UNDEFINED); <ide> <ide> public float[] dimensions = new float[2]; <ide> <ide> void reset() { <ide> border.reset(); <ide> position.reset(); <ide> <del> position.setDefault(Spacing.LEFT, CSSConstants.UNDEFINED); <del> position.setDefault(Spacing.RIGHT, CSSConstants.UNDEFINED); <del> position.setDefault(Spacing.TOP, CSSConstants.UNDEFINED); <del> position.setDefault(Spacing.BOTTOM, CSSConstants.UNDEFINED); <del> position.setDefault(Spacing.START, CSSConstants.UNDEFINED); <del> position.setDefault(Spacing.END, CSSConstants.UNDEFINED); <del> <ide> Arrays.fill(dimensions, CSSConstants.UNDEFINED); <ide> <ide> minWidth = CSSConstants.UNDEFINED; <ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/Spacing.java <ide> <ide> package com.facebook.csslayout; <ide> <del>import javax.annotation.Nullable; <del> <ide> import java.util.Arrays; <ide> <ide> /** <ide> public class Spacing { <ide> }; <ide> <ide> private final float[] mSpacing = newFullSpacingArray(); <del> @Nullable private float[] mDefaultSpacing = null; <ide> private int mValueFlags = 0; <add> private float mDefaultValue; <ide> private boolean mHasAliasesSet; <ide> <add> public Spacing() { <add> this(0); <add> } <add> <add> public Spacing(float defaultValue) { <add> mDefaultValue = defaultValue; <add> } <add> <ide> /** <ide> * Set a spacing value. <ide> * <ide> public boolean set(int spacingType, float value) { <ide> <ide> return true; <ide> } <del> return false; <del> } <ide> <del> /** <del> * Set a default spacing value. This is used as a fallback when no spacing has been set for a <del> * particular direction. <del> * <del> * @param spacingType one of {@link #LEFT}, {@link #TOP}, {@link #RIGHT}, {@link #BOTTOM} <del> * @param value the default value for this direction <del> * @return <del> */ <del> public boolean setDefault(int spacingType, float value) { <del> if (mDefaultSpacing == null) { <del> mDefaultSpacing = newSpacingResultArray(); <del> } <del> if (!FloatUtil.floatsEqual(mDefaultSpacing[spacingType], value)) { <del> mDefaultSpacing[spacingType] = value; <del> return true; <del> } <ide> return false; <ide> } <ide> <ide> public boolean setDefault(int spacingType, float value) { <ide> * @param spacingType one of {@link #LEFT}, {@link #TOP}, {@link #RIGHT}, {@link #BOTTOM} <ide> */ <ide> public float get(int spacingType) { <del> float defaultValue = (mDefaultSpacing != null) <del> ? mDefaultSpacing[spacingType] <del> : (spacingType == START || spacingType == END ? CSSConstants.UNDEFINED : 0); <add> float defaultValue = (spacingType == START || spacingType == END <add> ? CSSConstants.UNDEFINED <add> : mDefaultValue); <ide> <ide> if (mValueFlags == 0) { <ide> return defaultValue; <ide> public float getRaw(int spacingType) { <ide> */ <ide> void reset() { <ide> Arrays.fill(mSpacing, CSSConstants.UNDEFINED); <del> mDefaultSpacing = null; <ide> mHasAliasesSet = false; <ide> mValueFlags = 0; <ide> } <ide> private static float[] newFullSpacingArray() { <ide> CSSConstants.UNDEFINED, <ide> }; <ide> } <del> <del> private static float[] newSpacingResultArray() { <del> return newSpacingResultArray(0); <del> } <del> <del> private static float[] newSpacingResultArray(float defaultValue) { <del> return new float[] { <del> defaultValue, <del> defaultValue, <del> defaultValue, <del> defaultValue, <del> CSSConstants.UNDEFINED, <del> CSSConstants.UNDEFINED, <del> defaultValue, <del> defaultValue, <del> defaultValue, <del> }; <del> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNode.java <ide> <ide> import java.util.ArrayList; <ide> <add>import com.facebook.csslayout.CSSConstants; <ide> import com.facebook.csslayout.CSSNode; <add>import com.facebook.csslayout.Spacing; <ide> import com.facebook.infer.annotation.Assertions; <ide> import com.facebook.react.uimanager.annotations.ReactPropertyHolder; <ide> <ide> public class ReactShadowNode extends CSSNode { <ide> private float mAbsoluteTop; <ide> private float mAbsoluteRight; <ide> private float mAbsoluteBottom; <add> private final Spacing mDefaultPadding = new Spacing(0); <add> private final Spacing mPadding = new Spacing(CSSConstants.UNDEFINED); <ide> <ide> /** <ide> * Nodes that return {@code true} will be treated as "virtual" nodes. That is, nodes that are not <ide> public void dirty() { <ide> } <ide> } <ide> <add> public void setDefaultPadding(int spacingType, float padding) { <add> mDefaultPadding.set(spacingType, padding); <add> updatePadding(); <add> } <add> <add> @Override <add> public void setPadding(int spacingType, float padding) { <add> mPadding.set(spacingType, padding); <add> updatePadding(); <add> } <add> <add> private void updatePadding() { <add> for (int spacingType = Spacing.LEFT; spacingType <= Spacing.ALL; spacingType++) { <add> if (spacingType == Spacing.LEFT || <add> spacingType == Spacing.RIGHT || <add> spacingType == Spacing.START || <add> spacingType == Spacing.END) { <add> if (CSSConstants.isUndefined(mPadding.getRaw(spacingType)) && <add> CSSConstants.isUndefined(mPadding.getRaw(Spacing.HORIZONTAL)) && <add> CSSConstants.isUndefined(mPadding.getRaw(Spacing.ALL))) { <add> super.setPadding(spacingType, mDefaultPadding.getRaw(spacingType)); <add> } else { <add> super.setPadding(spacingType, mPadding.getRaw(spacingType)); <add> } <add> } else if (spacingType == Spacing.TOP || spacingType == Spacing.BOTTOM) { <add> if (CSSConstants.isUndefined(mPadding.getRaw(spacingType)) && <add> CSSConstants.isUndefined(mPadding.getRaw(Spacing.VERTICAL)) && <add> CSSConstants.isUndefined(mPadding.getRaw(Spacing.ALL))) { <add> super.setPadding(spacingType, mDefaultPadding.getRaw(spacingType)); <add> } else { <add> super.setPadding(spacingType, mPadding.getRaw(spacingType)); <add> } <add> } else { <add> if (CSSConstants.isUndefined(mPadding.getRaw(spacingType))) { <add> super.setPadding(spacingType, mDefaultPadding.getRaw(spacingType)); <add> } else { <add> super.setPadding(spacingType, mPadding.getRaw(spacingType)); <add> } <add> } <add> } <add> } <add> <ide> @Override <ide> public void addChildAt(CSSNode child, int i) { <ide> super.addChildAt(child, i); <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundDrawable.java <ide> public void getOutline(Outline outline) { <ide> super.getOutline(outline); <ide> return; <ide> } <del> if((!CSSConstants.isUndefined(mBorderRadius) && mBorderRadius > 0) || mBorderCornerRadii != null) { <add> if ((!CSSConstants.isUndefined(mBorderRadius) && mBorderRadius > 0) || mBorderCornerRadii != null) { <ide> updatePath(); <ide> <ide> outline.setConvexPath(mPathForBorderRadiusOutline); <ide> private void setBorderRGB(int position, float rgb) { <ide> // set RGB component <ide> if (mBorderRGB == null) { <ide> mBorderRGB = new Spacing(); <del> mBorderRGB.setDefault(Spacing.LEFT, DEFAULT_BORDER_RGB); <del> mBorderRGB.setDefault(Spacing.TOP, DEFAULT_BORDER_RGB); <del> mBorderRGB.setDefault(Spacing.RIGHT, DEFAULT_BORDER_RGB); <del> mBorderRGB.setDefault(Spacing.BOTTOM, DEFAULT_BORDER_RGB); <add> mBorderRGB.set(Spacing.LEFT, DEFAULT_BORDER_RGB); <add> mBorderRGB.set(Spacing.TOP, DEFAULT_BORDER_RGB); <add> mBorderRGB.set(Spacing.RIGHT, DEFAULT_BORDER_RGB); <add> mBorderRGB.set(Spacing.BOTTOM, DEFAULT_BORDER_RGB); <ide> } <ide> if (!FloatUtil.floatsEqual(mBorderRGB.getRaw(position), rgb)) { <ide> mBorderRGB.set(position, rgb); <ide> private void setBorderAlpha(int position, float alpha) { <ide> // set Alpha component <ide> if (mBorderAlpha == null) { <ide> mBorderAlpha = new Spacing(); <del> mBorderAlpha.setDefault(Spacing.LEFT, DEFAULT_BORDER_ALPHA); <del> mBorderAlpha.setDefault(Spacing.TOP, DEFAULT_BORDER_ALPHA); <del> mBorderAlpha.setDefault(Spacing.RIGHT, DEFAULT_BORDER_ALPHA); <del> mBorderAlpha.setDefault(Spacing.BOTTOM, DEFAULT_BORDER_ALPHA); <add> mBorderAlpha.set(Spacing.LEFT, DEFAULT_BORDER_ALPHA); <add> mBorderAlpha.set(Spacing.TOP, DEFAULT_BORDER_ALPHA); <add> mBorderAlpha.set(Spacing.RIGHT, DEFAULT_BORDER_ALPHA); <add> mBorderAlpha.set(Spacing.BOTTOM, DEFAULT_BORDER_ALPHA); <ide> } <ide> if (!FloatUtil.floatsEqual(mBorderAlpha.getRaw(position), alpha)) { <ide> mBorderAlpha.set(position, alpha); <ide> private void updatePath() { <ide> float bottomRightRadius = mBorderCornerRadii != null && !CSSConstants.isUndefined(mBorderCornerRadii[2]) ? mBorderCornerRadii[2] : defaultBorderRadius; <ide> float bottomLeftRadius = mBorderCornerRadii != null && !CSSConstants.isUndefined(mBorderCornerRadii[3]) ? mBorderCornerRadii[3] : defaultBorderRadius; <ide> <del> <ide> mPathForBorderRadius.addRoundRect( <ide> mTempRectForBorderRadius, <ide> new float[] {
8
Javascript
Javascript
replace string concatenation with template
0e003a3508af944587e7e1a7d36a2ce3519c3dbf
<ide><path>test/fixtures/guess-hash-seed.js <ide> const slow_str_gen = (function*() { <ide> let strgen_i = 0; <ide> outer: <ide> while (1) { <del> const str = '#' + (strgen_i++); <add> const str = `#${strgen_i++}`; <ide> for (let i = 0; i < 1000; i++) { <ide> if (time_set_lookup(tester_set, str) < tester_set_treshold) <ide> continue outer;
1
Text
Text
add list of deprecated methods
bbf839d1a8461ecc5ff78765d2a17abd042d39a7
<ide><path>activemodel/CHANGELOG.md <ide> `errors.messages` and `errors.details` hashes directly. Moving forward, <ide> please convert those direct manipulations to use provided API methods instead. <ide> <add> The list of deprecated methods and their planned future behavioral changes at the next major release are: <add> <add> * `errors#slice!` will be removed. <add> * `errors#first` will return Error object instead. <add> * `errors#last` will return Error object instead. <add> * `errors#each` with the `key, value` two-arguments block will stop working, while the `error` single-argument block would return `Error` object. <add> * `errors#values` will be removed. <add> * `errors#keys` will be removed. <add> * `errors#to_xml` will be removed. <add> * `errors#to_h` will be removed, and can be replaced with `errors#to_hash`. <add> * Manipulating `errors` itself as a hash will have no effect (e.g. `errors[:foo] = 'bar'`). <add> * Manipulating the hash returned by `errors#messages` (e.g. `errors.messages[:foo] = 'bar'`) will have no effect. <add> * Manipulating the hash returned by `errors#details` (e.g. `errors.details[:foo].clear`) will have no effect. <add> <ide> *lulalala* <ide> <ide> Please check [6-0-stable](https://github.com/rails/rails/blob/6-0-stable/activemodel/CHANGELOG.md) for previous changes.
1
Javascript
Javascript
add svg polygon
5661d5168e7a521c8abd73eeda61956cab5c091b
<ide><path>src/core/ReactDOM.js <ide> var ReactDOM = objMapKeyVal({ <ide> g: false, <ide> line: false, <ide> path: false, <add> polygon: false, <ide> polyline: false, <ide> rect: false, <ide> svg: false,
1
Ruby
Ruby
pass strings to demodulize method
c20fe91b0562987f5d9e57caee0bdbb6c9ef3220
<ide><path>activemodel/lib/active_model/conversion.rb <ide> module ClassMethods #:nodoc: <ide> # internal method and should not be accessed directly. <ide> def _to_partial_path #:nodoc: <ide> @_to_partial_path ||= begin <del> element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self)) <add> element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(name)) <ide> collection = ActiveSupport::Inflector.tableize(name) <ide> "#{collection}/#{element}".freeze <ide> end
1
PHP
PHP
register swiftmailer before mailer
1178f619426b2ac689f3d8163db36d3c841fe163
<ide><path>src/Illuminate/Mail/MailServiceProvider.php <ide> class MailServiceProvider extends ServiceProvider <ide> */ <ide> public function register() <ide> { <del> $this->app->singleton('mailer', function ($app) { <del> $this->registerSwiftMailer(); <add> $this->registerSwiftMailer(); <ide> <add> $this->app->singleton('mailer', function ($app) { <ide> // Once we have create the mailer instance, we will set a container instance <ide> // on the mailer. This allows us to resolve mailer classes via containers <ide> // for maximum testability on said classes instead of passing Closures.
1
Javascript
Javascript
fix error in flow types
0c5b3901781f145d77dc627fddb54bc88fd8afab
<ide><path>Libraries/Share/Share.js <ide> const { <ide> } = require('NativeModules'); <ide> <ide> type Content = { title?: string, message: string } | { title?: string, url: string }; <del>type Options = { dialogTitle?: string, excludeActivityTypes?: Array<string>, tintColor?: string }; <add>type Options = { dialogTitle?: string, excludedActivityTypes?: Array<string>, tintColor?: string }; <ide> <ide> class Share { <ide>
1
Go
Go
pass message to aux callback
f784907eae4f2e8bd4d9dea3d45c790c92689f3d
<ide><path>pkg/jsonmessage/jsonmessage.go <ide> func (jm *JSONMessage) Display(out io.Writer, termInfo termInfo) error { <ide> // DisplayJSONMessagesStream displays a json message stream from `in` to `out`, `isTerminal` <ide> // describes if `out` is a terminal. If this is the case, it will print `\n` at the end of <ide> // each line and move the cursor while displaying. <del>func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(*json.RawMessage)) error { <add>func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(JSONMessage)) error { <ide> var ( <ide> dec = json.NewDecoder(in) <ide> ids = make(map[string]int) <ide> func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, <ide> <ide> if jm.Aux != nil { <ide> if auxCallback != nil { <del> auxCallback(jm.Aux) <add> auxCallback(jm) <ide> } <ide> continue <ide> } <ide> type stream interface { <ide> } <ide> <ide> // DisplayJSONMessagesToStream prints json messages to the output stream <del>func DisplayJSONMessagesToStream(in io.Reader, stream stream, auxCallback func(*json.RawMessage)) error { <add>func DisplayJSONMessagesToStream(in io.Reader, stream stream, auxCallback func(JSONMessage)) error { <ide> return DisplayJSONMessagesStream(in, stream, stream.FD(), stream.IsTerminal(), auxCallback) <ide> }
1
Javascript
Javascript
fix default $http cache name
c0f0d136f0675ef699d6d6d183f11a3829bcfcb3
<ide><path>src/ng/http.js <ide> function $HttpProvider() { <ide> * * cache a specific response - set config.cache value to TRUE or to a cache object <ide> * <ide> * If caching is enabled, but neither the default cache nor config.cache are set to a cache object, <del> * then the default `$cacheFactory($http)` object is used. <add> * then the default `$cacheFactory("$http")` object is used. <ide> * <ide> * The default cache value can be set by updating the <ide> * {@link ng.$http#defaults `$http.defaults.cache`} property or the
1
Javascript
Javascript
add v8 benchmark test
cac4e6dd27d51072732724f79aff1ff05c1aae4e
<ide><path>test/parallel/test-benchmark-v8.js <add>'use strict'; <add> <add>require('../common'); <add> <add>const runBenchmark = require('../common/benchmark'); <add> <add>runBenchmark('v8', <add> [ <add> 'method=getHeapStatistics', <add> 'n=1' <add> ], <add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });
1
Javascript
Javascript
remove obsolete route
b39b44ac23ce1b8d87d776b7c42fde44079a194d
<ide><path>server/index.js <ide> export default class Server { <ide> // (but it should support as many as params, seperated by '/') <ide> // Othewise this will lead to a pretty simple DOS attack. <ide> // See more: https://github.com/zeit/next.js/issues/2617 <del> routes['/_next/:path*'] = async (req, res, params) => { <del> const p = join(__dirname, '..', 'client', ...(params.path || [])) <del> await this.serveStatic(req, res, p) <del> } <del> <ide> routes['/:path*'] = async (req, res, params, parsedUrl) => { <ide> const { pathname, query } = parsedUrl <ide> await this.render(req, res, pathname, query, parsedUrl)
1
Javascript
Javascript
add draw calls to non-indexed buffers
c2d8c3d5b7400bf5582bff77266321d1e652d236
<ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> if ( extension === null ) { <ide> <del> THREE.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); <add> THREE.error( 'THREE.WebGLRenderer.renderMesh: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); <ide> return; <ide> <ide> } <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> if ( extension === null ) { <ide> <del> THREE.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); <add> THREE.error( 'THREE.WebGLRenderer.renderMesh: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); <ide> return; <ide> <ide> } <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> } else { <ide> <ide> // non-indexed triangles <add> <add> var offsets = geometry.offsets; <ide> <del> if ( updateBuffers ) { <add> if ( offsets.length === 0 ) { <ide> <del> setupVertexAttributes( material, program, geometry, 0 ); <add> if ( updateBuffers ) { <ide> <del> } <add> setupVertexAttributes( material, program, geometry, 0 ); <ide> <del> var position = geometry.attributes[ 'position' ]; <add> } <ide> <del> // render non-indexed triangles <add> var position = geometry.attributes['position']; <ide> <del> if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) { <add> // render non-indexed triangles <ide> <del> var extension = extensions.get( 'ANGLE_instanced_arrays' ); <add> if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) { <ide> <del> if ( extension === null ) { <add> var extension = extensions.get( 'ANGLE_instanced_arrays' ); <ide> <del> THREE.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); <del> return; <add> if ( extension === null ) { <ide> <del> } <add> THREE.error( 'THREE.WebGLRenderer.renderMesh: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); <add> return; <ide> <del> if ( position instanceof THREE.InterleavedBufferAttribute ) { <add> } <add> <add> if ( position instanceof THREE.InterleavedBufferAttribute ) { <add> <add> extension.drawArraysInstancedANGLE( mode, 0, position.data.array.length / position.data.stride, geometry.maxInstancedCount ); // Draw the instanced meshes <add> <add> } else { <add> <add> extension.drawArraysInstancedANGLE( mode, 0, position.array.length / position.itemSize, geometry.maxInstancedCount ); // Draw the instanced meshes <ide> <del> extension.drawArraysInstancedANGLE( mode, 0, position.data.array.length / position.data.stride, geometry.maxInstancedCount ); // Draw the instanced meshes <add> } <ide> <ide> } else { <ide> <del> extension.drawArraysInstancedANGLE( mode, 0, position.array.length / position.itemSize, geometry.maxInstancedCount ); // Draw the instanced meshes <add> if ( position instanceof THREE.InterleavedBufferAttribute ) { <add> <add> _gl.drawArrays( mode, 0, position.data.array.length / position.data.stride ); <add> <add> } else { <add> <add> _gl.drawArrays( mode, 0, position.array.length / position.itemSize ); <add> <add> } <ide> <ide> } <ide> <add> _this.info.render.calls++; <add> _this.info.render.vertices += position.array.length / position.itemSize; <add> _this.info.render.faces += position.array.length / ( 3 * position.itemSize ); <add> <ide> } else { <ide> <del> if ( position instanceof THREE.InterleavedBufferAttribute ) { <add> // if there is more than 1 chunk <add> // must set attribute pointers to use new offsets for each chunk <add> // even if geometry and materials didn't change <ide> <del> _gl.drawArrays( mode, 0, position.data.array.length / position.data.stride ); <add> updateBuffers = true; <ide> <del> } else { <add> for ( var i = 0, il = offsets.length; i < il; i++ ) { <ide> <del> _gl.drawArrays( mode, 0, position.array.length / position.itemSize ); <add> var startIndex = offsets[i].index; <ide> <del> } <add> if ( updateBuffers ) { <ide> <del> } <add> setupVertexAttributes( material, program, geometry, startIndex ); <add> <add> } <ide> <del> _this.info.render.calls ++; <del> _this.info.render.vertices += position.array.length / position.itemSize; <del> _this.info.render.faces += position.array.length / ( 3 * position.itemSize ); <add> var position = geometry.attributes['position']; <ide> <add> // render non-indexed triangles <add> <add> if ( geometry instanceof THREE.InstancedBufferGeometry ) { <add> <add> THREE.error( 'THREE.WebGLRenderer.renderMesh: cannot use drawCalls with THREE.InstancedBufferGeometry.' ); <add> return; <add> <add> } else { <add> <add> _gl.drawArrays( mode, offsets[i].index, offsets[i].count ); <add> <add> } <add> <add> _this.info.render.calls++; <add> _this.info.render.vertices += offsets[i].count - offsets[i].index; <add> _this.info.render.faces += ( offsets[i].count - offsets[i].index ) / 3; <add> <add> } <add> } <ide> } <ide> <ide> }
1
Go
Go
improve deprecation message
f0eb227548427f6fc829f2b270ad83d22bd90c69
<ide><path>pkg/mflag/example/example.go <ide> var ( <ide> <ide> func init() { <ide> flag.Bool([]string{"#hp", "#-halp"}, false, "display the halp") <del> flag.BoolVar(&b, []string{"b"}, false, "a simple bool") <add> flag.BoolVar(&b, []string{"b", "#bal", "#bol", "-bal"}, false, "a simple bool") <add> flag.BoolVar(&b, []string{"g", "#gil"}, false, "a simple bool") <ide> flag.BoolVar(&b2, []string{"#-bool"}, false, "a simple bool") <ide> flag.IntVar(&i, []string{"-integer", "-number"}, -1, "a simple integer") <ide> flag.StringVar(&str, []string{"s", "#hidden", "-string"}, "", "a simple string") //-s -hidden and --string will work, but -hidden won't be in the usage <ide><path>pkg/mflag/flag.go <ide> func (f *FlagSet) parseOne() (bool, string, error) { <ide> f.actual = make(map[string]*Flag) <ide> } <ide> f.actual[name] = flag <del> for _, n := range flag.Names { <add> for i, n := range flag.Names { <ide> if n == fmt.Sprintf("#%s", name) { <del> fmt.Fprintf(f.out(), "Warning: '-%s' is deprecated, it will be removed soon. See usage.\n", name) <add> replacement := "" <add> for j := i; j < len(flag.Names); j++ { <add> if flag.Names[j][0] != '#' { <add> replacement = flag.Names[j] <add> break <add> } <add> } <add> if replacement != "" { <add> fmt.Fprintf(f.out(), "Warning: '-%s' is deprecated, it will be replaced by '-%s' soon. See usage.\n", name, replacement) <add> } else { <add> fmt.Fprintf(f.out(), "Warning: '-%s' is deprecated, it will be removed soon. See usage.\n", name) <add> } <ide> } <ide> } <ide> return true, "", nil
2
Ruby
Ruby
convert javarequirement test to spec
f7151e589fec5cd8caef00798c02e0c54eff5419
<ide><path>Library/Homebrew/test/java_requirement_spec.rb <add>require "requirements/java_requirement" <add> <add>describe JavaRequirement do <add> subject { described_class.new([]) } <add> <add> before(:each) do <add> ENV["JAVA_HOME"] = nil <add> end <add> <add> describe "#message" do <add> its(:message) { is_expected.to match(/Java is required to install this formula./) } <add> end <add> <add> describe "#inspect" do <add> subject { described_class.new(%w[1.7+]) } <add> its(:inspect) { is_expected.to eq('#<JavaRequirement: "java" [] version="1.7+">') } <add> end <add> <add> describe "#display_s" do <add> context "without specific version" do <add> its(:display_s) { is_expected.to eq("java") } <add> end <add> <add> context "with version 1.8" do <add> subject { described_class.new(%w[1.8]) } <add> its(:display_s) { is_expected.to eq("java = 1.8") } <add> end <add> <add> context "with version 1.8+" do <add> subject { described_class.new(%w[1.8+]) } <add> its(:display_s) { is_expected.to eq("java >= 1.8") } <add> end <add> end <add> <add> describe "#satisfied?" do <add> subject { described_class.new(%w[1.8]) } <add> <add> it "returns false if no `java` executable can be found" do <add> allow(File).to receive(:executable?).and_return(false) <add> expect(subject).not_to be_satisfied <add> end <add> <add> it "returns true if #preferred_java returns a path" do <add> allow(subject).to receive(:preferred_java).and_return(Pathname.new("/usr/bin/java")) <add> expect(subject).to be_satisfied <add> end <add> <add> context "when #possible_javas contains paths" do <add> let(:path) { Pathname.new(Dir.mktmpdir) } <add> let(:java) { path/"java" } <add> <add> def setup_java_with_version(version) <add> IO.write java, <<-EOS.undent <add> #!/bin/sh <add> echo 'java version "#{version}"' <add> EOS <add> FileUtils.chmod "+x", java <add> end <add> <add> before(:each) do <add> allow(subject).to receive(:possible_javas).and_return([java]) <add> end <add> <add> after(:each) do <add> path.rmtree <add> end <add> <add> context "and 1.7 is required" do <add> subject { described_class.new(%w[1.7]) } <add> <add> it "returns false if all are lower" do <add> setup_java_with_version "1.6.0_5" <add> expect(subject).not_to be_satisfied <add> end <add> <add> it "returns true if one is equal" do <add> setup_java_with_version "1.7.0_5" <add> expect(subject).to be_satisfied <add> end <add> <add> it "returns false if all are higher" do <add> setup_java_with_version "1.8.0_5" <add> expect(subject).not_to be_satisfied <add> end <add> end <add> <add> context "and 1.7+ is required" do <add> subject { described_class.new(%w[1.7+]) } <add> <add> it "returns false if all are lower" do <add> setup_java_with_version "1.6.0_5" <add> expect(subject).not_to be_satisfied <add> end <add> <add> it "returns true if one is equal" do <add> setup_java_with_version "1.7.0_5" <add> expect(subject).to be_satisfied <add> end <add> <add> it "returns true if one is higher" do <add> setup_java_with_version "1.8.0_5" <add> expect(subject).to be_satisfied <add> end <add> end <add> end <add> end <add>end <ide><path>Library/Homebrew/test/java_requirement_test.rb <del>require "testing_env" <del>require "requirements/java_requirement" <del> <del>class JavaRequirementTests < Homebrew::TestCase <del> def setup <del> super <del> ENV["JAVA_HOME"] = nil <del> end <del> <del> def test_message <del> a = JavaRequirement.new([]) <del> assert_match(/Java is required to install this formula./, a.message) <del> end <del> <del> def test_inspect <del> a = JavaRequirement.new(%w[1.7+]) <del> assert_equal a.inspect, '#<JavaRequirement: "java" [] version="1.7+">' <del> end <del> <del> def test_display_s <del> x = JavaRequirement.new([]) <del> assert_equal x.display_s, "java" <del> y = JavaRequirement.new(%w[1.8]) <del> assert_equal y.display_s, "java = 1.8" <del> z = JavaRequirement.new(%w[1.8+]) <del> assert_equal z.display_s, "java >= 1.8" <del> end <del> <del> def test_satisfied? <del> a = JavaRequirement.new(%w[1.8]) <del> File.stubs(:executable?).returns(false) <del> refute_predicate a, :satisfied? <del> <del> b = JavaRequirement.new([]) <del> b.stubs(:preferred_java).returns(Pathname.new("/usr/bin/java")) <del> assert_predicate b, :satisfied? <del> <del> c = JavaRequirement.new(%w[1.7+]) <del> c.stubs(:possible_javas).returns([Pathname.new("/usr/bin/java")]) <del> Utils.stubs(:popen_read).returns('java version "1.6.0_5"') <del> refute_predicate c, :satisfied? <del> Utils.stubs(:popen_read).returns('java version "1.8.0_5"') <del> assert_predicate c, :satisfied? <del> <del> d = JavaRequirement.new(%w[1.7]) <del> d.stubs(:possible_javas).returns([Pathname.new("/usr/bin/java")]) <del> Utils.stubs(:popen_read).returns('java version "1.8.0_5"') <del> refute_predicate d, :satisfied? <del> end <del>end
2
Text
Text
describe the changes in transactional tests
deba47799ff905f778e0c98a015789a1327d5087
<ide><path>guides/source/5_1_release_notes.md <ide> can generate form tags based on URLs, scopes or models. <ide> </form> <ide> ``` <ide> <add>Incompatibilities <add>----------------- <add> <add>The following changes may require immediate action upon upgrade. <add> <add>### Transactional tests with multiple connections <add> <add>Transactional tests now wrap all Active Record connections in database <add>transactions. <add> <add>When a test spawns additional threads, and those threads obtain database <add>connections, those connections are now handled specially: <add> <add>The threads will share a single connection, which is inside the managed <add>transaction. This ensures all threads see the database in the same <add>state, ignoring the outermost transaction. Previously, such additional <add>connections were unable to see the fixture rows, for example. <add> <add>When a thread enters a nested transaction, it will temporarily obtain <add>exclusive use of the connection, to maintain isolation. <add> <add>If your tests currently rely on obtaining a separate, <add>outside-of-transaction, connection in a spawned thread, you'll need to <add>switch to more explicit connection management. <add> <add>If your tests spawn threads and those threads interact while also using <add>explicit database transactions, this change may introduce a deadlock. <add> <add>The easy way to opt out of this new behavior is to disable transactional <add>tests on any test cases it affects. <add> <ide> Railties <ide> -------- <ide>
1
Ruby
Ruby
use binary io throughout, not utf-8
92a4f5b3f42c92ec272eb28adebea83faa012afb
<ide><path>lib/active_storage/service/disk_service.rb <ide> require "fileutils" <ide> require "pathname" <add>require "digest/md5" <ide> require "active_support/core_ext/numeric/bytes" <ide> <ide> class ActiveStorage::Service::DiskService < ActiveStorage::Service <ide> def initialize(root:) <ide> end <ide> <ide> def upload(key, io, checksum: nil) <del> File.open(make_path_for(key), "wb") do |file| <del> while chunk = io.read(64.kilobytes) <del> file.write(chunk) <del> end <del> end <del> <add> IO.copy_stream(io, make_path_for(key)) <ide> ensure_integrity_of(key, checksum) if checksum <ide> end <ide> <ide> def download(key) <ide> if block_given? <ide> File.open(path_for(key)) do |file| <del> while data = file.read(64.kilobytes) <add> while data = file.binread(64.kilobytes) <ide> yield data <ide> end <ide> end <ide> else <del> File.open path_for(key), &:read <add> File.binread path_for(key) <ide> end <ide> end <ide> <ide><path>test/service/shared_service_tests.rb <ide> module ActiveStorage::Service::SharedServiceTests <ide> extend ActiveSupport::Concern <ide> <ide> FIXTURE_KEY = SecureRandom.base58(24) <del> FIXTURE_FILE = StringIO.new("Hello world!") <add> FIXTURE_DATA = "\211PNG\r\n\032\n\000\000\000\rIHDR\000\000\000\020\000\000\000\020\001\003\000\000\000%=m\"\000\000\000\006PLTE\000\000\000\377\377\377\245\331\237\335\000\000\0003IDATx\234c\370\377\237\341\377_\206\377\237\031\016\2603\334?\314p\1772\303\315\315\f7\215\031\356\024\203\320\275\317\f\367\201R\314\f\017\300\350\377\177\000Q\206\027(\316]\233P\000\000\000\000IEND\256B`\202".force_encoding(Encoding::BINARY) <ide> <ide> included do <ide> setup do <ide> @service = self.class.const_get(:SERVICE) <del> @service.upload FIXTURE_KEY, FIXTURE_FILE <del> FIXTURE_FILE.rewind <add> @service.upload FIXTURE_KEY, StringIO.new(FIXTURE_DATA) <ide> end <ide> <ide> teardown do <ide> @service.delete FIXTURE_KEY <del> FIXTURE_FILE.rewind <ide> end <ide> <ide> test "uploading with integrity" do <ide> module ActiveStorage::Service::SharedServiceTests <ide> end <ide> <ide> test "downloading" do <del> assert_equal FIXTURE_FILE.read, @service.download(FIXTURE_KEY) <add> assert_equal FIXTURE_DATA, @service.download(FIXTURE_KEY) <ide> end <ide> <ide> test "existing" do <ide> module ActiveStorage::Service::SharedServiceTests <ide> @service.delete FIXTURE_KEY <ide> assert_not @service.exist?(FIXTURE_KEY) <ide> end <del> <add> <ide> test "deleting nonexistent key" do <ide> assert_nothing_raised do <ide> @service.delete SecureRandom.base58(24)
2
Python
Python
use promise from amqp.utils
3539b96dab51216a74841ba2820e228a0ba8bff9
<ide><path>celery/concurrency/processes.py <ide> from time import sleep, time <ide> from weakref import ref <ide> <add>from amqp.utils import promise <ide> from billiard import forking_enable <ide> from billiard import pool as _pool <ide> from billiard.exceptions import WorkerLostError <ide> def _select(readers=None, writers=None, err=None, timeout=0): <ide> raise <ide> <ide> <del>class promise(object): <del> <del> def __init__(self, fun, *partial_args, **partial_kwargs): <del> self.fun = fun <del> self.args = partial_args <del> self.kwargs = partial_kwargs <del> self.ready = False <del> <del> def __call__(self, *args, **kwargs): <del> try: <del> return self.fun(*tuple(self.args) + tuple(args), <del> **dict(self.kwargs, **kwargs)) <del> finally: <del> self.ready = True <del> <del> <ide> class Worker(_pool.Worker): <ide> <ide> def on_loop_start(self, pid):
1
Text
Text
update javascript guide for turbolinks 5
2f792616ab01754f432d8642de12faee6aff3535
<ide><path>guides/source/working_with_javascript_in_rails.md <ide> $("<%= escape_javascript(render @user) %>").appendTo("#users"); <ide> Turbolinks <ide> ---------- <ide> <del>Rails 4 ships with the [Turbolinks gem](https://github.com/turbolinks/turbolinks). <del>This gem uses Ajax to speed up page rendering in most applications. <add>Rails ships with the [Turbolinks library](https://github.com/turbolinks/turbolinks), <add>which uses Ajax to speed up page rendering in most applications. <ide> <ide> ### How Turbolinks Works <ide> <ide> will then use PushState to change the URL to the correct one, preserving <ide> refresh semantics and giving you pretty URLs. <ide> <ide> The only thing you have to do to enable Turbolinks is have it in your Gemfile, <del>and put `//= require turbolinks` in your CoffeeScript manifest, which is usually <add>and put `//= require turbolinks` in your JavaScript manifest, which is usually <ide> `app/assets/javascripts/application.js`. <ide> <del>If you want to disable Turbolinks for certain links, add a `data-no-turbolink` <add>If you want to disable Turbolinks for certain links, add a `data-turbolinks="false"` <ide> attribute to the tag: <ide> <ide> ```html <del><a href="..." data-no-turbolink>No turbolinks here</a>. <add><a href="..." data-turbolinks="false">No turbolinks here</a>. <ide> ``` <ide> <ide> ### Page Change Events <ide> event that this relies on will not be fired. If you have code that looks like <ide> this, you must change your code to do this instead: <ide> <ide> ```coffeescript <del>$(document).on "page:change", -> <add>$(document).on "turbolinks:load", -> <ide> alert "page has loaded!" <ide> ``` <ide>
1
Javascript
Javascript
add loop protection on keyup update
096fba0de7d1052a7f33e57fde7c8de1f0053029
<ide><path>client/commonFramework/end.js <ide> $(document).ready(function() { <ide> const common = window.common; <ide> const { Observable } = window.Rx; <del> const { challengeName, challengeType, challengeTypes } = common; <add> const { <add> addLoopProtect, <add> challengeName, <add> challengeType, <add> challengeTypes <add> } = common; <ide> <ide> common.init.forEach(function(init) { <ide> init($); <ide> $(document).ready(function() { <ide> .filter(() => common.challengeType === challengeTypes.HTML) <ide> .flatMap(code => { <ide> return common.detectUnsafeCode$(code) <add> .map(() => { <add> const combinedCode = common.head + code + common.tail; <add> <add> return addLoopProtect(combinedCode); <add> }) <ide> .flatMap(code => common.updatePreview$(code)) <add> .flatMap(() => common.checkPreview$({ code })) <ide> .catch(err => Observable.just({ err })); <ide> }) <ide> .subscribe( <ide><path>client/commonFramework/update-preview.js <ide> window.common = (function(global) { <ide> window.$ = parent.$.proxy(parent.$.fn.find, parent.$(document)); <ide> window.loopProtect = parent.loopProtect; <ide> window.__err = null; <add> window.loopProtect.hit = function(line) { <add> window.__err = new Error( <add> 'Potential infinite loop at line ' + line <add> ); <add> }; <ide> </script> <ide> <link <ide> rel='stylesheet' <ide> window.common = (function(global) { <ide> // and prime it with false <ide> common.previewReady$ = new BehaviorSubject(false); <ide> <del> // runPreviewTests$ should be set up in the preview window <add> // These should be set up in the preview window <add> // if this error is seen it is because the function tried to run <add> // before the iframe has completely loaded <ide> common.runPreviewTests$ = <del> () => Observable.throw(new Error('run preview not enabled')); <add> common.checkPreview$ = <add> () => Observable.throw(new Error('Preview not fully loaded')); <add> <ide> <ide> common.updatePreview$ = function updatePreview$(code = '') { <ide> const preview = common.getIframe('preview'); <ide><path>client/iFrameScripts.js <ide> window.$(document).ready(function() { <ide> var tests = parent.tests; <ide> var common = parent.common; <ide> <del> window.loopProtect.hit = function(line) { <del> window.__err = new Error( <del> 'Potential infinite loop at line ' + line <del> ); <del> }; <del> <ide> common.getJsOutput = function evalJs(code = '') { <ide> let output; <ide> try { <ide> window.$(document).ready(function() { <ide> return Rx.Observable.throw(window.__err); <ide> } <ide> <add> // Iterate throught the test one at a time <add> // on new stacks <ide> return Rx.Observable.from(tests, null, null, Rx.Scheduler.default) <add> // add delay here for firefox to catch up <ide> .delay(100) <ide> .map(test => { <ide> const userTest = {}; <del> common.appendToOutputDisplay(''); <ide> try { <ide> /* eslint-disable no-eval */ <ide> eval(test); <ide> window.$(document).ready(function() { <ide> } <ide> return userTest; <ide> }) <add> // gather tests back into an array <ide> .toArray() <ide> .map(tests => ({ ...rest, tests, originalCode })); <ide> }; <ide> <add> // used when updating preview without running tests <add> common.checkPreview$ = function checkPreview$(args) { <add> if (window.__err) { <add> return Rx.Observable.throw(window.__err); <add> } <add> return Rx.Observable.just(args); <add> }; <add> <ide> // now that the runPreviewTest$ is defined <ide> // we set the subject to true <ide> // this will let the updatePreview
3
Javascript
Javascript
add unit tests for requestshortener
4f3c662f82d12b934e71a90c7ce351166b488338
<ide><path>lib/RequestShortener.js <ide> class RequestShortener { <ide> result = result.replace(this.currentDirectoryRegExp, "!."); <ide> } <ide> if (this.parentDirectoryRegExp) { <del> result = result.replace(this.parentDirectoryRegExp, `!../`); <add> result = result.replace(this.parentDirectoryRegExp, "!../"); <ide> } <ide> if (!this.buildinsAsModule && this.buildinsRegExp) { <ide> result = result.replace(this.buildinsRegExp, "!(webpack)"); <ide><path>test/RequestShortener.unittest.js <add>"use strict"; <add> <add>const RequestShortener = require("../lib/RequestShortener"); <add> <add>describe("RequestShortener", () => { <add> it("should create RequestShortener and shorten with ./ file in directory", () => { <add> const shortener = new RequestShortener("/foo/bar"); <add> expect(shortener.shorten("/foo/bar/some.js")).toEqual("./some.js"); <add> }); <add> <add> it("should create RequestShortener and shorten with ../ file in parent directory", () => { <add> const shortener = new RequestShortener("/foo/bar"); <add> expect(shortener.shorten("/foo/baz/some.js")).toEqual("../baz/some.js"); <add> }); <add> <add> it("should create RequestShortener and not shorten parent directory neighbor", () => { <add> const shortener = new RequestShortener("/foo/bar"); <add> expect(shortener.shorten("/foo_baz/bar/some.js")).toEqual( <add> "/foo_baz/bar/some.js" <add> ); <add> }); <add>});
2
Java
Java
reduce an empty observable
f1a21147939eb2173c64c5e488c3ce784816dd61
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> public Observable<T> onErrorReturn(Func1<Throwable, ? extends T> resumeFunction) <ide> * Observable, whose result will be used in the next accumulator call <ide> * @return an Observable that emits a single item that is the result of accumulating the <ide> * output from the source Observable <add> * @throws IllegalArgumentException <add> * if Observable sequence is empty. <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229154(v%3Dvs.103).aspx">MSDN: Observable.Aggregate</a> <ide> * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> <ide> */ <ide> public Observable<T> reduce(Func2<T, T, T> accumulator) { <del> return create(OperationScan.scan(this, accumulator)).takeLast(1); <add> /* <add> * Discussion and confirmation of implementation at https://github.com/Netflix/RxJava/issues/423#issuecomment-27642532 <add> * <add> * It should use last() not takeLast(1) since it needs to emit an error if the sequence is empty. <add> */ <add> return create(OperationScan.scan(this, accumulator)).last(); <ide> } <ide> <ide> /** <ide><path>rxjava-core/src/test/java/rx/ObservableTests.java <ide> import rx.observables.ConnectableObservable; <ide> import rx.subscriptions.BooleanSubscription; <ide> import rx.subscriptions.Subscriptions; <add>import rx.util.functions.Action0; <ide> import rx.util.functions.Action1; <ide> import rx.util.functions.Func1; <ide> import rx.util.functions.Func2; <ide> public Integer call(Integer t1, Integer t2) { <ide> verify(w).onNext(10); <ide> } <ide> <add> <add> /** <add> * A reduce should fail with an IllegalArgumentException if done on an empty Observable. <add> */ <add> @Test(expected = IllegalArgumentException.class) <add> public void testReduceWithEmptyObservable() { <add> Observable<Integer> observable = Observable.range(1, 0); <add> observable.reduce(new Func2<Integer, Integer, Integer>() { <add> <add> @Override <add> public Integer call(Integer t1, Integer t2) { <add> return t1 + t2; <add> } <add> <add> }).toBlockingObservable().forEach(new Action1<Integer>() { <add> <add> @Override <add> public void call(Integer t1) { <add> // do nothing ... we expect an exception instead <add> } <add> }); <add> <add> fail("Expected an exception to be thrown"); <add> } <add> <ide> @Test <ide> public void testReduceWithInitialValue() { <ide> Observable<Integer> observable = Observable.from(1, 2, 3, 4);
2
Python
Python
add atrousconv2d layer for dilated convolution
b3a26a5b3048c6fc0911e219b6fa61b5ae2b86f5
<ide><path>keras/backend/tensorflow_backend.py <ide> def batch_set_value(tuples): <ide> ops = [tf.assign(x, np.asarray(value)) for x, value in tuples] <ide> get_session().run(ops) <ide> <add> <ide> # GRAPH MANIPULATION <ide> <ide> class Function(object): <ide> def _postprocess_conv3d_output(x, dim_ordering): <ide> <ide> def conv2d(x, kernel, strides=(1, 1), border_mode='valid', <ide> dim_ordering=_IMAGE_DIM_ORDERING, <del> image_shape=None, filter_shape=None): <add> image_shape=None, filter_shape=None, filter_dilation=(1, 1)): <ide> '''2D convolution. <ide> <ide> # Arguments <ide> def conv2d(x, kernel, strides=(1, 1), border_mode='valid', <ide> x = _preprocess_conv2d_input(x, dim_ordering) <ide> kernel = _preprocess_conv2d_kernel(kernel, dim_ordering) <ide> padding = _preprocess_border_mode(border_mode) <del> strides = (1,) + strides + (1,) <del> <del> x = tf.nn.conv2d(x, kernel, strides, padding=padding) <add> if filter_dilation == (1, 1): <add> strides = (1,) + strides + (1,) <add> x = tf.nn.conv2d(x, kernel, strides, padding=padding) <add> else: <add> assert filter_dilation[0] == filter_dilation[1] <add> assert strides == (1, 1), 'Invalid strides for dilated convolution' <add> x = tf.nn.atrous_conv2d(x, kernel, filter_dilation[0], padding=padding) <ide> return _postprocess_conv2d_output(x, dim_ordering) <ide> <ide> <ide><path>keras/backend/theano_backend.py <ide> def l2_normalize(x, axis): <ide> # CONVOLUTIONS <ide> <ide> def conv2d(x, kernel, strides=(1, 1), border_mode='valid', <del> dim_ordering=_IMAGE_DIM_ORDERING, <del> image_shape=None, filter_shape=None): <add> dim_ordering=_IMAGE_DIM_ORDERING, image_shape=None, <add> filter_shape=None, filter_dilation=(1, 1)): <ide> '''2D convolution. <ide> <ide> # Arguments <ide> def int_or_none(value): <ide> if filter_shape is not None: <ide> filter_shape = tuple(int_or_none(v) for v in filter_shape) <ide> <del> conv_out = T.nnet.conv2d(x, kernel, <del> border_mode=th_border_mode, <del> subsample=strides, <del> input_shape=image_shape, <del> filter_shape=filter_shape) <add> # TODO: remove the if statement when theano with no filter dilation is deprecated. <add> if filter_dilation == (1, 1): <add> conv_out = T.nnet.conv2d(x, kernel, <add> border_mode=th_border_mode, <add> subsample=strides, <add> input_shape=image_shape, <add> filter_shape=filter_shape) <add> else: <add> conv_out = T.nnet.conv2d(x, kernel, <add> border_mode=th_border_mode, <add> subsample=strides, <add> input_shape=image_shape, <add> filter_shape=filter_shape, <add> filter_dilation=filter_dilation) <ide> <ide> if border_mode == 'same': <ide> if np_kernel.shape[2] % 2 == 0: <ide><path>keras/layers/convolutional.py <ide> def get_config(self): <ide> return dict(list(base_config.items()) + list(config.items())) <ide> <ide> <add>class AtrousConv2D(Convolution2D): <add> '''Atrous Convolution operator for filtering windows of two-dimensional inputs. <add> A.k.a dilated convolution or convolution with holes. <add> When using this layer as the first layer in a model, <add> provide the keyword argument `input_shape` <add> (tuple of integers, does not include the sample axis), <add> e.g. `input_shape=(3, 128, 128)` for 128x128 RGB pictures. <add> <add> # Examples <add> <add> ```python <add> # apply a 3x3 convolution with atrous rate 2x2 and 64 output filters on a 256x256 image: <add> model = Sequential() <add> model.add(AtrousConv2D(64, 3, 3, atrous_rate=(2,2), border_mode='valid', input_shape=(3, 256, 256))) <add> # now the actual kernel size is dilated from 3x3 to 5x5 (3+(3-1)*(2-1)=5) <add> # thus model.output_shape == (None, 64, 252, 252) <add> ``` <add> <add> # Arguments <add> nb_filter: Number of convolution filters to use. <add> nb_row: Number of rows in the convolution kernel. <add> nb_col: Number of columns in the convolution kernel. <add> init: name of initialization function for the weights of the layer <add> (see [initializations](../initializations.md)), or alternatively, <add> Theano function to use for weights initialization. <add> This parameter is only relevant if you don't pass <add> a `weights` argument. <add> activation: name of activation function to use <add> (see [activations](../activations.md)), <add> or alternatively, elementwise Theano function. <add> If you don't specify anything, no activation is applied <add> (ie. "linear" activation: a(x) = x). <add> weights: list of numpy arrays to set as initial weights. <add> border_mode: 'valid' or 'same'. <add> subsample: tuple of length 2. Factor by which to subsample output. <add> Also called strides elsewhere. <add> atrous_rate: tuple of length 2. Factor for kernel dilation. <add> Also called filter_dilation elsewhere. <add> W_regularizer: instance of [WeightRegularizer](../regularizers.md) <add> (eg. L1 or L2 regularization), applied to the main weights matrix. <add> b_regularizer: instance of [WeightRegularizer](../regularizers.md), <add> applied to the bias. <add> activity_regularizer: instance of [ActivityRegularizer](../regularizers.md), <add> applied to the network output. <add> W_constraint: instance of the [constraints](../constraints.md) module <add> (eg. maxnorm, nonneg), applied to the main weights matrix. <add> b_constraint: instance of the [constraints](../constraints.md) module, <add> applied to the bias. <add> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension <add> (the depth) is at index 1, in 'tf' mode is it at index 3. <add> It defaults to the `image_dim_ordering` value found in your <add> Keras config file at `~/.keras/keras.json`. <add> If you never set it, then it will be "th". <add> bias: whether to include a bias (i.e. make the layer affine rather than linear). <add> <add> # Input shape <add> 4D tensor with shape: <add> `(samples, channels, rows, cols)` if dim_ordering='th' <add> or 4D tensor with shape: <add> `(samples, rows, cols, channels)` if dim_ordering='tf'. <add> <add> # Output shape <add> 4D tensor with shape: <add> `(samples, nb_filter, new_rows, new_cols)` if dim_ordering='th' <add> or 4D tensor with shape: <add> `(samples, new_rows, new_cols, nb_filter)` if dim_ordering='tf'. <add> `rows` and `cols` values might have changed due to padding. <add> <add> # References <add> - [Multi-Scale Context Aggregation by Dilated Convolutions](https://arxiv.org/abs/1511.07122) <add> ''' <add> def __init__(self, nb_filter, nb_row, nb_col, <add> init='glorot_uniform', activation='linear', weights=None, <add> border_mode='valid', subsample=(1, 1), atrous_rate=(1, 1), dim_ordering=K.image_dim_ordering(), <add> W_regularizer=None, b_regularizer=None, activity_regularizer=None, <add> W_constraint=None, b_constraint=None, <add> bias=True, **kwargs): <add> <add> if border_mode not in {'valid', 'same'}: <add> raise Exception('Invalid border mode for AtrousConv2D:', border_mode) <add> <add> self.atrous_rate = tuple(atrous_rate) <add> <add> super(AtrousConv2D, self).__init__(nb_filter, nb_row, nb_col, <add> init=init, activation=activation, <add> weights=weights, border_mode=border_mode, <add> subsample=subsample, dim_ordering=dim_ordering, <add> W_regularizer=W_regularizer, b_regularizer=b_regularizer, <add> activity_regularizer=activity_regularizer, <add> W_constraint=W_constraint, b_constraint=b_constraint, <add> bias=bias, **kwargs) <add> <add> def get_output_shape_for(self, input_shape): <add> if self.dim_ordering == 'th': <add> rows = input_shape[2] <add> cols = input_shape[3] <add> elif self.dim_ordering == 'tf': <add> rows = input_shape[1] <add> cols = input_shape[2] <add> else: <add> raise Exception('Invalid dim_ordering: ' + self.dim_ordering) <add> <add> rows = conv_output_length(rows, self.nb_row, self.border_mode, <add> self.subsample[0], dilation=self.atrous_rate[0]) <add> cols = conv_output_length(cols, self.nb_col, self.border_mode, <add> self.subsample[1], dilation=self.atrous_rate[1]) <add> <add> if self.dim_ordering == 'th': <add> return (input_shape[0], self.nb_filter, rows, cols) <add> elif self.dim_ordering == 'tf': <add> return (input_shape[0], rows, cols, self.nb_filter) <add> else: <add> raise Exception('Invalid dim_ordering: ' + self.dim_ordering) <add> <add> def call(self, x, mask=None): <add> output = K.conv2d(x, self.W, strides=self.subsample, <add> border_mode=self.border_mode, <add> dim_ordering=self.dim_ordering, <add> filter_shape=self.W_shape, <add> filter_dilation=self.atrous_rate) <add> if self.bias: <add> if self.dim_ordering == 'th': <add> output += K.reshape(self.b, (1, self.nb_filter, 1, 1)) <add> elif self.dim_ordering == 'tf': <add> output += K.reshape(self.b, (1, 1, 1, self.nb_filter)) <add> else: <add> raise Exception('Invalid dim_ordering: ' + self.dim_ordering) <add> output = self.activation(output) <add> return output <add> <add> def get_config(self): <add> config = {'atrous_rate': self.atrous_rate} <add> base_config = super(AtrousConv2D, self).get_config() <add> return dict(list(base_config.items()) + list(config.items())) <add> <add> <ide> class Convolution3D(Layer): <ide> '''Convolution operator for filtering windows of three-dimensional inputs. <ide> When using this layer as the first layer in a model, <ide><path>keras/utils/np_utils.py <ide> def convert_kernel(kernel, dim_ordering='th'): <ide> return new_kernel <ide> <ide> <del>def conv_output_length(input_length, filter_size, border_mode, stride): <add>def conv_output_length(input_length, filter_size, border_mode, stride, dilation=1): <ide> if input_length is None: <ide> return None <ide> assert border_mode in {'same', 'valid'} <add> dilated_filter_size = filter_size + (filter_size -1) * (dilation - 1) <ide> if border_mode == 'same': <ide> output_length = input_length <ide> elif border_mode == 'valid': <del> output_length = input_length - filter_size + 1 <add> output_length = input_length - dilated_filter_size + 1 <ide> return (output_length + stride - 1) // stride <ide><path>tests/keras/layers/test_convolutional.py <ide> def test_convolution_2d(): <ide> input_shape=(nb_samples, stack_size, nb_row, nb_col)) <ide> <ide> <add>def test_atrous_conv_2d(): <add> nb_samples = 8 <add> nb_filter = 3 <add> stack_size = 4 <add> nb_row = 10 <add> nb_col = 6 <add> <add> for border_mode in ['valid', 'same']: <add> for subsample in [(1, 1), (2, 2)]: <add> for atrous_rate in [(1, 1), (2, 2)]: <add> if border_mode == 'same' and subsample != (1, 1): <add> continue <add> if subsample != (1, 1) and atrous_rate != (1, 1): <add> continue <add> <add> layer_test(convolutional.AtrousConv2D, <add> kwargs={'nb_filter': nb_filter, <add> 'nb_row': 3, <add> 'nb_col': 3, <add> 'border_mode': border_mode, <add> 'subsample': subsample, <add> 'atrous_rate': atrous_rate}, <add> input_shape=(nb_samples, stack_size, nb_row, nb_col)) <add> <add> layer_test(convolutional.AtrousConv2D, <add> kwargs={'nb_filter': nb_filter, <add> 'nb_row': 3, <add> 'nb_col': 3, <add> 'border_mode': border_mode, <add> 'W_regularizer': 'l2', <add> 'b_regularizer': 'l2', <add> 'activity_regularizer': 'activity_l2', <add> 'subsample': subsample, <add> 'atrous_rate': atrous_rate}, <add> input_shape=(nb_samples, stack_size, nb_row, nb_col)) <add> <add> <ide> def test_maxpooling_2d(): <ide> pool_size = (3, 3) <ide> <ide> def test_upsampling_3d(): <ide> <ide> <ide> if __name__ == '__main__': <del> # pytest.main([__file__]) <del> test_convolution_3d() <add> pytest.main([__file__])
5
Python
Python
move json tests to separate file
a0e2aca770c756d9f7de53339e2cf9067a52df11
<ide><path>tests/test_helpers.py <ide> import io <ide> import os <ide> import sys <del>import uuid <ide> <ide> import pytest <ide> from werkzeug.datastructures import Range <ide> from flask.helpers import get_env <ide> <ide> <del>def has_encoding(name): <del> try: <del> import codecs <del> <del> codecs.lookup(name) <del> return True <del> except LookupError: <del> return False <del> <del> <ide> class FakePath: <ide> """Fake object to represent a ``PathLike object``. <ide> <ide> def __fspath__(self): <ide> return self.path <ide> <ide> <del>class FixedOffset(datetime.tzinfo): <del> """Fixed offset in hours east from UTC. <del> <del> This is a slight adaptation of the ``FixedOffset`` example found in <del> https://docs.python.org/2.7/library/datetime.html. <del> """ <del> <del> def __init__(self, hours, name): <del> self.__offset = datetime.timedelta(hours=hours) <del> self.__name = name <del> <del> def utcoffset(self, dt): <del> return self.__offset <del> <del> def tzname(self, dt): <del> return self.__name <del> <del> def dst(self, dt): <del> return datetime.timedelta() <del> <del> <del>class TestJSON: <del> @pytest.mark.parametrize("debug", (True, False)) <del> def test_bad_request_debug_message(self, app, client, debug): <del> app.config["DEBUG"] = debug <del> app.config["TRAP_BAD_REQUEST_ERRORS"] = False <del> <del> @app.route("/json", methods=["POST"]) <del> def post_json(): <del> flask.request.get_json() <del> return None <del> <del> rv = client.post("/json", data=None, content_type="application/json") <del> assert rv.status_code == 400 <del> contains = b"Failed to decode JSON object" in rv.data <del> assert contains == debug <del> <del> def test_json_bad_requests(self, app, client): <del> @app.route("/json", methods=["POST"]) <del> def return_json(): <del> return flask.jsonify(foo=str(flask.request.get_json())) <del> <del> rv = client.post("/json", data="malformed", content_type="application/json") <del> assert rv.status_code == 400 <del> <del> def test_json_custom_mimetypes(self, app, client): <del> @app.route("/json", methods=["POST"]) <del> def return_json(): <del> return flask.request.get_json() <del> <del> rv = client.post("/json", data='"foo"', content_type="application/x+json") <del> assert rv.data == b"foo" <del> <del> @pytest.mark.parametrize( <del> "test_value,expected", [(True, '"\\u2603"'), (False, '"\u2603"')] <del> ) <del> def test_json_as_unicode(self, test_value, expected, app, app_ctx): <del> <del> app.config["JSON_AS_ASCII"] = test_value <del> rv = flask.json.dumps("\N{SNOWMAN}") <del> assert rv == expected <del> <del> def test_json_dump_to_file(self, app, app_ctx): <del> test_data = {"name": "Flask"} <del> out = io.StringIO() <del> <del> flask.json.dump(test_data, out) <del> out.seek(0) <del> rv = flask.json.load(out) <del> assert rv == test_data <del> <del> @pytest.mark.parametrize( <del> "test_value", [0, -1, 1, 23, 3.14, "s", "longer string", True, False, None] <del> ) <del> def test_jsonify_basic_types(self, test_value, app, client): <del> url = "/jsonify_basic_types" <del> app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x)) <del> rv = client.get(url) <del> assert rv.mimetype == "application/json" <del> assert flask.json.loads(rv.data) == test_value <del> <del> def test_jsonify_dicts(self, app, client): <del> d = { <del> "a": 0, <del> "b": 23, <del> "c": 3.14, <del> "d": "t", <del> "e": "Hi", <del> "f": True, <del> "g": False, <del> "h": ["test list", 10, False], <del> "i": {"test": "dict"}, <del> } <del> <del> @app.route("/kw") <del> def return_kwargs(): <del> return flask.jsonify(**d) <del> <del> @app.route("/dict") <del> def return_dict(): <del> return flask.jsonify(d) <del> <del> for url in "/kw", "/dict": <del> rv = client.get(url) <del> assert rv.mimetype == "application/json" <del> assert flask.json.loads(rv.data) == d <del> <del> def test_jsonify_arrays(self, app, client): <del> """Test jsonify of lists and args unpacking.""" <del> a_list = [ <del> 0, <del> 42, <del> 3.14, <del> "t", <del> "hello", <del> True, <del> False, <del> ["test list", 2, False], <del> {"test": "dict"}, <del> ] <del> <del> @app.route("/args_unpack") <del> def return_args_unpack(): <del> return flask.jsonify(*a_list) <del> <del> @app.route("/array") <del> def return_array(): <del> return flask.jsonify(a_list) <del> <del> for url in "/args_unpack", "/array": <del> rv = client.get(url) <del> assert rv.mimetype == "application/json" <del> assert flask.json.loads(rv.data) == a_list <del> <del> def test_jsonify_date_types(self, app, client): <del> """Test jsonify with datetime.date and datetime.datetime types.""" <del> test_dates = ( <del> datetime.datetime(1973, 3, 11, 6, 30, 45), <del> datetime.date(1975, 1, 5), <del> ) <del> <del> for i, d in enumerate(test_dates): <del> url = f"/datetest{i}" <del> app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val)) <del> rv = client.get(url) <del> assert rv.mimetype == "application/json" <del> assert flask.json.loads(rv.data)["x"] == http_date(d.timetuple()) <del> <del> @pytest.mark.parametrize("tz", (("UTC", 0), ("PST", -8), ("KST", 9))) <del> def test_jsonify_aware_datetimes(self, tz): <del> """Test if aware datetime.datetime objects are converted into GMT.""" <del> tzinfo = FixedOffset(hours=tz[1], name=tz[0]) <del> dt = datetime.datetime(2017, 1, 1, 12, 34, 56, tzinfo=tzinfo) <del> gmt = FixedOffset(hours=0, name="GMT") <del> expected = dt.astimezone(gmt).strftime('"%a, %d %b %Y %H:%M:%S %Z"') <del> assert flask.json.JSONEncoder().encode(dt) == expected <del> <del> def test_jsonify_uuid_types(self, app, client): <del> """Test jsonify with uuid.UUID types""" <del> <del> test_uuid = uuid.UUID(bytes=b"\xDE\xAD\xBE\xEF" * 4) <del> url = "/uuid_test" <del> app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid)) <del> <del> rv = client.get(url) <del> <del> rv_x = flask.json.loads(rv.data)["x"] <del> assert rv_x == str(test_uuid) <del> rv_uuid = uuid.UUID(rv_x) <del> assert rv_uuid == test_uuid <del> <del> def test_json_attr(self, app, client): <del> @app.route("/add", methods=["POST"]) <del> def add(): <del> json = flask.request.get_json() <del> return str(json["a"] + json["b"]) <del> <del> rv = client.post( <del> "/add", <del> data=flask.json.dumps({"a": 1, "b": 2}), <del> content_type="application/json", <del> ) <del> assert rv.data == b"3" <del> <del> def test_template_escaping(self, app, req_ctx): <del> render = flask.render_template_string <del> rv = flask.json.htmlsafe_dumps("</script>") <del> assert rv == '"\\u003c/script\\u003e"' <del> rv = render('{{ "</script>"|tojson }}') <del> assert rv == '"\\u003c/script\\u003e"' <del> rv = render('{{ "<\0/script>"|tojson }}') <del> assert rv == '"\\u003c\\u0000/script\\u003e"' <del> rv = render('{{ "<!--<script>"|tojson }}') <del> assert rv == '"\\u003c!--\\u003cscript\\u003e"' <del> rv = render('{{ "&"|tojson }}') <del> assert rv == '"\\u0026"' <del> rv = render('{{ "\'"|tojson }}') <del> assert rv == '"\\u0027"' <del> rv = render( <del> "<a ng-data='{{ data|tojson }}'></a>", data={"x": ["foo", "bar", "baz'"]} <del> ) <del> assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>' <del> <del> def test_json_customization(self, app, client): <del> class X: # noqa: B903, for Python2 compatibility <del> def __init__(self, val): <del> self.val = val <del> <del> class MyEncoder(flask.json.JSONEncoder): <del> def default(self, o): <del> if isinstance(o, X): <del> return f"<{o.val}>" <del> return flask.json.JSONEncoder.default(self, o) <del> <del> class MyDecoder(flask.json.JSONDecoder): <del> def __init__(self, *args, **kwargs): <del> kwargs.setdefault("object_hook", self.object_hook) <del> flask.json.JSONDecoder.__init__(self, *args, **kwargs) <del> <del> def object_hook(self, obj): <del> if len(obj) == 1 and "_foo" in obj: <del> return X(obj["_foo"]) <del> return obj <del> <del> app.json_encoder = MyEncoder <del> app.json_decoder = MyDecoder <del> <del> @app.route("/", methods=["POST"]) <del> def index(): <del> return flask.json.dumps(flask.request.get_json()["x"]) <del> <del> rv = client.post( <del> "/", <del> data=flask.json.dumps({"x": {"_foo": 42}}), <del> content_type="application/json", <del> ) <del> assert rv.data == b'"<42>"' <del> <del> def test_blueprint_json_customization(self, app, client): <del> class X: <del> __slots__ = ("val",) <del> <del> def __init__(self, val): <del> self.val = val <del> <del> class MyEncoder(flask.json.JSONEncoder): <del> def default(self, o): <del> if isinstance(o, X): <del> return f"<{o.val}>" <del> <del> return flask.json.JSONEncoder.default(self, o) <del> <del> class MyDecoder(flask.json.JSONDecoder): <del> def __init__(self, *args, **kwargs): <del> kwargs.setdefault("object_hook", self.object_hook) <del> flask.json.JSONDecoder.__init__(self, *args, **kwargs) <del> <del> def object_hook(self, obj): <del> if len(obj) == 1 and "_foo" in obj: <del> return X(obj["_foo"]) <del> <del> return obj <del> <del> bp = flask.Blueprint("bp", __name__) <del> bp.json_encoder = MyEncoder <del> bp.json_decoder = MyDecoder <del> <del> @bp.route("/bp", methods=["POST"]) <del> def index(): <del> return flask.json.dumps(flask.request.get_json()["x"]) <del> <del> app.register_blueprint(bp) <del> <del> rv = client.post( <del> "/bp", <del> data=flask.json.dumps({"x": {"_foo": 42}}), <del> content_type="application/json", <del> ) <del> assert rv.data == b'"<42>"' <del> <del> @pytest.mark.skipif( <del> not has_encoding("euc-kr"), reason="The euc-kr encoding is required." <del> ) <del> def test_modified_url_encoding(self, app, client): <del> class ModifiedRequest(flask.Request): <del> url_charset = "euc-kr" <del> <del> app.request_class = ModifiedRequest <del> app.url_map.charset = "euc-kr" <del> <del> @app.route("/") <del> def index(): <del> return flask.request.args["foo"] <del> <del> rv = client.get("/?foo=정상처리".encode("euc-kr")) <del> assert rv.status_code == 200 <del> assert rv.data == "정상처리".encode() <del> <del> def test_json_key_sorting(self, app, client): <del> app.debug = True <del> <del> assert app.config["JSON_SORT_KEYS"] <del> d = dict.fromkeys(range(20), "foo") <del> <del> @app.route("/") <del> def index(): <del> return flask.jsonify(values=d) <del> <del> rv = client.get("/") <del> lines = [x.strip() for x in rv.data.strip().decode("utf-8").splitlines()] <del> sorted_by_str = [ <del> "{", <del> '"values": {', <del> '"0": "foo",', <del> '"1": "foo",', <del> '"10": "foo",', <del> '"11": "foo",', <del> '"12": "foo",', <del> '"13": "foo",', <del> '"14": "foo",', <del> '"15": "foo",', <del> '"16": "foo",', <del> '"17": "foo",', <del> '"18": "foo",', <del> '"19": "foo",', <del> '"2": "foo",', <del> '"3": "foo",', <del> '"4": "foo",', <del> '"5": "foo",', <del> '"6": "foo",', <del> '"7": "foo",', <del> '"8": "foo",', <del> '"9": "foo"', <del> "}", <del> "}", <del> ] <del> sorted_by_int = [ <del> "{", <del> '"values": {', <del> '"0": "foo",', <del> '"1": "foo",', <del> '"2": "foo",', <del> '"3": "foo",', <del> '"4": "foo",', <del> '"5": "foo",', <del> '"6": "foo",', <del> '"7": "foo",', <del> '"8": "foo",', <del> '"9": "foo",', <del> '"10": "foo",', <del> '"11": "foo",', <del> '"12": "foo",', <del> '"13": "foo",', <del> '"14": "foo",', <del> '"15": "foo",', <del> '"16": "foo",', <del> '"17": "foo",', <del> '"18": "foo",', <del> '"19": "foo"', <del> "}", <del> "}", <del> ] <del> <del> try: <del> assert lines == sorted_by_int <del> except AssertionError: <del> assert lines == sorted_by_str <del> <del> <ide> class PyBytesIO: <ide> def __init__(self, *args, **kwargs): <ide> self._io = io.BytesIO(*args, **kwargs) <ide><path>tests/test_json.py <add>import datetime <add>import io <add>import uuid <add> <add>import pytest <add>from werkzeug.http import http_date <add> <add>import flask <add> <add> <add>@pytest.mark.parametrize("debug", (True, False)) <add>def test_bad_request_debug_message(app, client, debug): <add> app.config["DEBUG"] = debug <add> app.config["TRAP_BAD_REQUEST_ERRORS"] = False <add> <add> @app.route("/json", methods=["POST"]) <add> def post_json(): <add> flask.request.get_json() <add> return None <add> <add> rv = client.post("/json", data=None, content_type="application/json") <add> assert rv.status_code == 400 <add> contains = b"Failed to decode JSON object" in rv.data <add> assert contains == debug <add> <add> <add>def test_json_bad_requests(app, client): <add> @app.route("/json", methods=["POST"]) <add> def return_json(): <add> return flask.jsonify(foo=str(flask.request.get_json())) <add> <add> rv = client.post("/json", data="malformed", content_type="application/json") <add> assert rv.status_code == 400 <add> <add> <add>def test_json_custom_mimetypes(app, client): <add> @app.route("/json", methods=["POST"]) <add> def return_json(): <add> return flask.request.get_json() <add> <add> rv = client.post("/json", data='"foo"', content_type="application/x+json") <add> assert rv.data == b"foo" <add> <add> <add>@pytest.mark.parametrize( <add> "test_value,expected", [(True, '"\\u2603"'), (False, '"\u2603"')] <add>) <add>def test_json_as_unicode(test_value, expected, app, app_ctx): <add> <add> app.config["JSON_AS_ASCII"] = test_value <add> rv = flask.json.dumps("\N{SNOWMAN}") <add> assert rv == expected <add> <add> <add>def test_json_dump_to_file(app, app_ctx): <add> test_data = {"name": "Flask"} <add> out = io.StringIO() <add> <add> flask.json.dump(test_data, out) <add> out.seek(0) <add> rv = flask.json.load(out) <add> assert rv == test_data <add> <add> <add>@pytest.mark.parametrize( <add> "test_value", [0, -1, 1, 23, 3.14, "s", "longer string", True, False, None] <add>) <add>def test_jsonify_basic_types(test_value, app, client): <add> url = "/jsonify_basic_types" <add> app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x)) <add> rv = client.get(url) <add> assert rv.mimetype == "application/json" <add> assert flask.json.loads(rv.data) == test_value <add> <add> <add>def test_jsonify_dicts(app, client): <add> d = { <add> "a": 0, <add> "b": 23, <add> "c": 3.14, <add> "d": "t", <add> "e": "Hi", <add> "f": True, <add> "g": False, <add> "h": ["test list", 10, False], <add> "i": {"test": "dict"}, <add> } <add> <add> @app.route("/kw") <add> def return_kwargs(): <add> return flask.jsonify(**d) <add> <add> @app.route("/dict") <add> def return_dict(): <add> return flask.jsonify(d) <add> <add> for url in "/kw", "/dict": <add> rv = client.get(url) <add> assert rv.mimetype == "application/json" <add> assert flask.json.loads(rv.data) == d <add> <add> <add>def test_jsonify_arrays(app, client): <add> """Test jsonify of lists and args unpacking.""" <add> a_list = [ <add> 0, <add> 42, <add> 3.14, <add> "t", <add> "hello", <add> True, <add> False, <add> ["test list", 2, False], <add> {"test": "dict"}, <add> ] <add> <add> @app.route("/args_unpack") <add> def return_args_unpack(): <add> return flask.jsonify(*a_list) <add> <add> @app.route("/array") <add> def return_array(): <add> return flask.jsonify(a_list) <add> <add> for url in "/args_unpack", "/array": <add> rv = client.get(url) <add> assert rv.mimetype == "application/json" <add> assert flask.json.loads(rv.data) == a_list <add> <add> <add>def test_jsonifytypes(app, client): <add> """Test jsonify with datetime.date and datetime.datetime types.""" <add> test_dates = ( <add> datetime.datetime(1973, 3, 11, 6, 30, 45), <add> datetime.date(1975, 1, 5), <add> ) <add> <add> for i, d in enumerate(test_dates): <add> url = f"/datetest{i}" <add> app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val)) <add> rv = client.get(url) <add> assert rv.mimetype == "application/json" <add> assert flask.json.loads(rv.data)["x"] == http_date(d.timetuple()) <add> <add> <add>class FixedOffset(datetime.tzinfo): <add> """Fixed offset in hours east from UTC. <add> <add> This is a slight adaptation of the ``FixedOffset`` example found in <add> https://docs.python.org/2.7/library/datetime.html. <add> """ <add> <add> def __init__(self, hours, name): <add> self.__offset = datetime.timedelta(hours=hours) <add> self.__name = name <add> <add> def utcoffset(self, dt): <add> return self.__offset <add> <add> def tzname(self, dt): <add> return self.__name <add> <add> def dst(self, dt): <add> return datetime.timedelta() <add> <add> <add>@pytest.mark.parametrize("tz", (("UTC", 0), ("PST", -8), ("KST", 9))) <add>def test_jsonify_aware_datetimes(tz): <add> """Test if aware datetime.datetime objects are converted into GMT.""" <add> tzinfo = FixedOffset(hours=tz[1], name=tz[0]) <add> dt = datetime.datetime(2017, 1, 1, 12, 34, 56, tzinfo=tzinfo) <add> gmt = FixedOffset(hours=0, name="GMT") <add> expected = dt.astimezone(gmt).strftime('"%a, %d %b %Y %H:%M:%S %Z"') <add> assert flask.json.JSONEncoder().encode(dt) == expected <add> <add> <add>def test_jsonify_uuid_types(app, client): <add> """Test jsonify with uuid.UUID types""" <add> <add> test_uuid = uuid.UUID(bytes=b"\xDE\xAD\xBE\xEF" * 4) <add> url = "/uuid_test" <add> app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid)) <add> <add> rv = client.get(url) <add> <add> rv_x = flask.json.loads(rv.data)["x"] <add> assert rv_x == str(test_uuid) <add> rv_uuid = uuid.UUID(rv_x) <add> assert rv_uuid == test_uuid <add> <add> <add>def test_json_attr(app, client): <add> @app.route("/add", methods=["POST"]) <add> def add(): <add> json = flask.request.get_json() <add> return str(json["a"] + json["b"]) <add> <add> rv = client.post( <add> "/add", <add> data=flask.json.dumps({"a": 1, "b": 2}), <add> content_type="application/json", <add> ) <add> assert rv.data == b"3" <add> <add> <add>def test_template_escaping(app, req_ctx): <add> render = flask.render_template_string <add> rv = flask.json.htmlsafe_dumps("</script>") <add> assert rv == '"\\u003c/script\\u003e"' <add> rv = render('{{ "</script>"|tojson }}') <add> assert rv == '"\\u003c/script\\u003e"' <add> rv = render('{{ "<\0/script>"|tojson }}') <add> assert rv == '"\\u003c\\u0000/script\\u003e"' <add> rv = render('{{ "<!--<script>"|tojson }}') <add> assert rv == '"\\u003c!--\\u003cscript\\u003e"' <add> rv = render('{{ "&"|tojson }}') <add> assert rv == '"\\u0026"' <add> rv = render('{{ "\'"|tojson }}') <add> assert rv == '"\\u0027"' <add> rv = render( <add> "<a ng-data='{{ data|tojson }}'></a>", data={"x": ["foo", "bar", "baz'"]} <add> ) <add> assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>' <add> <add> <add>def test_json_customization(app, client): <add> class X: # noqa: B903, for Python2 compatibility <add> def __init__(self, val): <add> self.val = val <add> <add> class MyEncoder(flask.json.JSONEncoder): <add> def default(self, o): <add> if isinstance(o, X): <add> return f"<{o.val}>" <add> return flask.json.JSONEncoder.default(self, o) <add> <add> class MyDecoder(flask.json.JSONDecoder): <add> def __init__(self, *args, **kwargs): <add> kwargs.setdefault("object_hook", self.object_hook) <add> flask.json.JSONDecoder.__init__(self, *args, **kwargs) <add> <add> def object_hook(self, obj): <add> if len(obj) == 1 and "_foo" in obj: <add> return X(obj["_foo"]) <add> return obj <add> <add> app.json_encoder = MyEncoder <add> app.json_decoder = MyDecoder <add> <add> @app.route("/", methods=["POST"]) <add> def index(): <add> return flask.json.dumps(flask.request.get_json()["x"]) <add> <add> rv = client.post( <add> "/", <add> data=flask.json.dumps({"x": {"_foo": 42}}), <add> content_type="application/json", <add> ) <add> assert rv.data == b'"<42>"' <add> <add> <add>def test_blueprint_json_customization(app, client): <add> class X: <add> __slots__ = ("val",) <add> <add> def __init__(self, val): <add> self.val = val <add> <add> class MyEncoder(flask.json.JSONEncoder): <add> def default(self, o): <add> if isinstance(o, X): <add> return f"<{o.val}>" <add> <add> return flask.json.JSONEncoder.default(self, o) <add> <add> class MyDecoder(flask.json.JSONDecoder): <add> def __init__(self, *args, **kwargs): <add> kwargs.setdefault("object_hook", self.object_hook) <add> flask.json.JSONDecoder.__init__(self, *args, **kwargs) <add> <add> def object_hook(self, obj): <add> if len(obj) == 1 and "_foo" in obj: <add> return X(obj["_foo"]) <add> <add> return obj <add> <add> bp = flask.Blueprint("bp", __name__) <add> bp.json_encoder = MyEncoder <add> bp.json_decoder = MyDecoder <add> <add> @bp.route("/bp", methods=["POST"]) <add> def index(): <add> return flask.json.dumps(flask.request.get_json()["x"]) <add> <add> app.register_blueprint(bp) <add> <add> rv = client.post( <add> "/bp", <add> data=flask.json.dumps({"x": {"_foo": 42}}), <add> content_type="application/json", <add> ) <add> assert rv.data == b'"<42>"' <add> <add> <add>def _has_encoding(name): <add> try: <add> import codecs <add> <add> codecs.lookup(name) <add> return True <add> except LookupError: <add> return False <add> <add> <add>@pytest.mark.skipif( <add> not _has_encoding("euc-kr"), reason="The euc-kr encoding is required." <add>) <add>def test_modified_url_encoding(app, client): <add> class ModifiedRequest(flask.Request): <add> url_charset = "euc-kr" <add> <add> app.request_class = ModifiedRequest <add> app.url_map.charset = "euc-kr" <add> <add> @app.route("/") <add> def index(): <add> return flask.request.args["foo"] <add> <add> rv = client.get("/?foo=정상처리".encode("euc-kr")) <add> assert rv.status_code == 200 <add> assert rv.data == "정상처리".encode() <add> <add> <add>def test_json_key_sorting(app, client): <add> app.debug = True <add> <add> assert app.config["JSON_SORT_KEYS"] <add> d = dict.fromkeys(range(20), "foo") <add> <add> @app.route("/") <add> def index(): <add> return flask.jsonify(values=d) <add> <add> rv = client.get("/") <add> lines = [x.strip() for x in rv.data.strip().decode("utf-8").splitlines()] <add> sorted_by_str = [ <add> "{", <add> '"values": {', <add> '"0": "foo",', <add> '"1": "foo",', <add> '"10": "foo",', <add> '"11": "foo",', <add> '"12": "foo",', <add> '"13": "foo",', <add> '"14": "foo",', <add> '"15": "foo",', <add> '"16": "foo",', <add> '"17": "foo",', <add> '"18": "foo",', <add> '"19": "foo",', <add> '"2": "foo",', <add> '"3": "foo",', <add> '"4": "foo",', <add> '"5": "foo",', <add> '"6": "foo",', <add> '"7": "foo",', <add> '"8": "foo",', <add> '"9": "foo"', <add> "}", <add> "}", <add> ] <add> sorted_by_int = [ <add> "{", <add> '"values": {', <add> '"0": "foo",', <add> '"1": "foo",', <add> '"2": "foo",', <add> '"3": "foo",', <add> '"4": "foo",', <add> '"5": "foo",', <add> '"6": "foo",', <add> '"7": "foo",', <add> '"8": "foo",', <add> '"9": "foo",', <add> '"10": "foo",', <add> '"11": "foo",', <add> '"12": "foo",', <add> '"13": "foo",', <add> '"14": "foo",', <add> '"15": "foo",', <add> '"16": "foo",', <add> '"17": "foo",', <add> '"18": "foo",', <add> '"19": "foo"', <add> "}", <add> "}", <add> ] <add> <add> try: <add> assert lines == sorted_by_int <add> except AssertionError: <add> assert lines == sorted_by_str
2
Text
Text
fix credential typo in guide
575a2c6ce03e283b75b0043727a77c29f85f9a66
<ide><path>guides/source/active_record_encryption.md <ide> First, you need to add some keys to your [rails credentials](/security.html#cust <ide> $ bin/rails db:encryption:init <ide> Add this entry to the credentials of the target environment: <ide> <del>active_record.encryption: <add>active_record_encryption: <ide> primary_key: EGY8WhulUOXixybod7ZWwMIL68R9o5kC <ide> deterministic_key: aPA5XyALhf75NNnMzaspW7akTfZp0lPY <ide> key_derivation_salt: xEY0dt6TZcAMg52K7O84wYzkjvbA62Hz <ide> The key will be used internally to derive the key used to encrypt and decrypt th <ide> - All the keys will be tried when decrypting content, until one works. <ide> <ide> ```yml <del>active_record.encryption: <add>active_record <add> encryption: <ide> master_key: <ide> - bc17e7b413fd4720716a7633027f8cc4 # Active, encrypts new content <ide> - a1cc4d7b9f420e40a337b9e68c5ecec6 # Previous keys can still decrypt existing content
1
Javascript
Javascript
fix typeerror in syntheticevent
cf3ff07f92736476d15d1ed7f5fc04274d2a8b77
<ide><path>src/event/synthetic/SyntheticEvent.js <ide> function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent) { <ide> <ide> var Interface = this.constructor.Interface; <ide> for (var propName in Interface) { <add> if (!Interface.hasOwnProperty(propName)) { <add> continue; <add> } <ide> var normalize = Interface[propName]; <ide> if (normalize) { <ide> this[propName] = normalize(nativeEvent);
1
Javascript
Javascript
add tests for stats true
e374ab15827ae7a914c6387feff0f8d4a8a998b9
<ide><path>test/Defaults.unittest.js <ide> describe("Defaults", () => { <ide> + "uniqueName": "@@@Hello World!", <ide> `) <ide> ); <add> test("stats true", { stats: true }, e => <add> e.toMatchInlineSnapshot(` <add> - Expected <add> + Received <add> <add> <add> - "stats": Object {}, <add> + "stats": Object { <add> + "preset": "normal", <add> + }, <add> `) <add> ); <ide> });
1
Python
Python
fix azure blobs and skip failed backblaze test
80d7cb0d4302b2b628953b6b1a7b1da89ae01897
<ide><path>libcloud/http.py <ide> def request(self, method, url, body=None, headers=None, raw=False, <ide> stream=False): <ide> url = urlparse.urljoin(self.host, url) <ide> # all headers should be strings <del> if 'Content-Length' in headers and isinstance(headers['Content-Length'], int): <del> headers['Content-Length'] = str(headers['Content-Length']) <add> for header, value in headers.items(): <add> if isinstance(headers[header], int): <add> headers[header] = str(value) <ide> self.response = self.session.request( <ide> method=method.lower(), <ide> url=url, <ide> def request(self, method, url, body=None, headers=None, raw=False, <ide> def prepared_request(self, method, url, body=None, <ide> headers=None, raw=False, stream=False): <ide> # all headers should be strings <del> if 'Content-Length' in headers and isinstance(headers['Content-Length'], int): <del> headers['Content-Length'] = str(headers['Content-Length']) <add> for header, value in headers.items(): <add> if isinstance(headers[header], int): <add> headers[header] = str(value) <ide> req = requests.Request(method, ''.join([self.host, url]), <ide> data=body, headers=headers) <ide> <ide><path>libcloud/test/storage/test_azure_blobs.py <ide> def _test_container200_test(self, method, url, body, headers): <ide> <ide> headers['etag'] = '0x8CFB877BB56A6FB' <ide> headers['last-modified'] = 'Fri, 04 Jan 2013 09:48:06 GMT' <del> headers['content-length'] = 12345 <add> headers['content-length'] = '12345' <ide> headers['content-type'] = 'application/zip' <ide> headers['x-ms-blob-type'] = 'Block' <ide> headers['x-ms-lease-status'] = 'unlocked' <ide> def _foo_bar_container_foo_bar_object_NOT_FOUND(self, method, url, body, <ide> headers, <ide> httplib.responses[httplib.NOT_FOUND]) <ide> <del> def _foo_bar_container_foo_bar_object(self, method, url, body, headers): <add> def _foo_bar_container_foo_bar_object_DELETE(self, method, url, body, headers): <ide> # test_delete_object <ide> return (httplib.ACCEPTED, <ide> body, <ide> def test_delete_object_not_found(self): <ide> self.fail('Exception was not thrown') <ide> <ide> def test_delete_object_success(self): <add> self.mock_response_klass.type = 'DELETE' <ide> container = Container(name='foo_bar_container', extra={}, <ide> driver=self.driver) <ide> obj = Object(name='foo_bar_object', size=1234, hash=None, extra=None, <ide><path>libcloud/test/storage/test_backblaze_b2.py <ide> def test_download_object_as_stream(self): <ide> container = self.driver.list_containers()[0] <ide> obj = self.driver.list_container_objects(container=container)[0] <ide> result = self.driver.download_object_as_stream(obj=obj) <del> result = result.body <ide> self.assertEqual(result, 'ab') <ide> <ide> def test_upload_object(self):
3
Ruby
Ruby
relax assertions in connection config tests
c03c519db0f5bcbb9f1151db5774921ea9bd3a22
<ide><path>activerecord/test/cases/connection_adapters/connection_handler_test.rb <ide> def test_establish_connection_using_3_level_config_defaults_to_default_env_prima <ide> <ide> ActiveRecord::Base.establish_connection <ide> <del> assert_equal "db/primary.sqlite3", ActiveRecord::Base.connection.pool.spec.config[:database] <add> assert_match "db/primary.sqlite3", ActiveRecord::Base.connection.pool.spec.config[:database] <ide> ensure <ide> ActiveRecord::Base.configurations = @prev_configs <ide> ENV["RAILS_ENV"] = previous_env <ide> def test_establish_connection_using_2_level_config_defaults_to_default_env_prima <ide> <ide> ActiveRecord::Base.establish_connection <ide> <del> assert_equal "db/primary.sqlite3", ActiveRecord::Base.connection.pool.spec.config[:database] <add> assert_match "db/primary.sqlite3", ActiveRecord::Base.connection.pool.spec.config[:database] <ide> ensure <ide> ActiveRecord::Base.configurations = @prev_configs <ide> ENV["RAILS_ENV"] = previous_env
1
Go
Go
remove icmp dependency from test, use nslookup
004ac85aa25f08e350465140ee7404ad31602d75
<ide><path>integration-cli/docker_cli_run_test.go <ide> func TestRunLeakyFileDescriptors(t *testing.T) { <ide> logDone("run - check file descriptor leakage") <ide> } <ide> <del>// it should be possible to ping Google DNS resolver <add>// it should be possible to lookup Google DNS <ide> // this will fail when Internet access is unavailable <del>func TestRunPingGoogle(t *testing.T) { <add>func TestRunLookupGoogleDns(t *testing.T) { <ide> defer deleteAllContainers() <ide> <del> runCmd := exec.Command(dockerBinary, "run", "busybox", "ping", "-c", "1", "8.8.8.8") <del> out, _, _, err := runCommandWithStdoutStderr(runCmd) <add> out, _, _, err := runCommandWithStdoutStderr(exec.Command(dockerBinary, "run", "busybox", "nslookup", "google.com")) <ide> if err != nil { <ide> t.Fatalf("failed to run container: %v, output: %q", err, out) <ide> } <ide> <del> logDone("run - ping 8.8.8.8") <add> logDone("run - nslookup google.com") <ide> } <ide> <ide> // the exit code should be 0
1
Text
Text
add descriptions of state properties
800caac2362e602d80b5c61fe1cb288bbcdb316a
<ide><path>doc/api/http2.md <ide> All other interactions will be routed directly to the socket. <ide> added: v8.4.0 <ide> --> <ide> <add>Provides miscellaneous information about the current state of the <add>`Http2Session`. <add> <ide> * Value: {Object} <del> * `effectiveLocalWindowSize` {number} <del> * `effectiveRecvDataLength` {number} <del> * `nextStreamID` {number} <del> * `localWindowSize` {number} <del> * `lastProcStreamID` {number} <del> * `remoteWindowSize` {number} <del> * `outboundQueueSize` {number} <del> * `deflateDynamicTableSize` {number} <del> * `inflateDynamicTableSize` {number} <add> * `effectiveLocalWindowSize` {number} The current local (receive) <add> flow control window size for the `Http2Session`. <add> * `effectiveRecvDataLength` {number} The current number of bytes <add> that have been received since the last flow control `WINDOW_UPDATE`. <add> * `nextStreamID` {number} The numeric identifier to be used the <add> next time a new `Http2Stream` is created by this `Http2Session`. <add> * `localWindowSize` {number} The number of bytes that the remote peer can <add> send without receiving a `WINDOW_UPDATE`. <add> * `lastProcStreamID` {number} The numeric id of the `Http2Stream` <add> for which a `HEADERS` or `DATA` frame was most recently received. <add> * `remoteWindowSize` {number} The number of bytes that this `Http2Session` <add> may send without receiving a `WINDOW_UPDATE`. <add> * `outboundQueueSize` {number} The number of frames currently within the <add> outbound queue for this `Http2Session`. <add> * `deflateDynamicTableSize` {number} The current size in bytes of the <add> outbound header compression state table. <add> * `inflateDynamicTableSize` {number} The current size in bytes of the <add> inbound header compression state table. <ide> <ide> An object describing the current status of this `Http2Session`. <ide> <ide> req.setTimeout(5000, () => req.rstStream(NGHTTP2_CANCEL)); <ide> <!-- YAML <ide> added: v8.4.0 <ide> --> <add>Provides miscellaneous information about the current state of the <add>`Http2Stream`. <ide> <ide> * Value: {Object} <del> * `localWindowSize` {number} <del> * `state` {number} <del> * `localClose` {number} <del> * `remoteClose` {number} <del> * `sumDependencyWeight` {number} <del> * `weight` {number} <add> * `localWindowSize` {number} The number of bytes the connected peer may send <add> for this `Http2Stream` without receiving a `WINDOW_UPDATE`. <add> * `state` {number} A flag indicating the low-level current state of the <add> `Http2Stream` as determined by nghttp2. <add> * `localClose` {number} `true` if this `Http2Stream` has been closed locally. <add> * `remoteClose` {number} `true` if this `Http2Stream` has been closed <add> remotely. <add> * `sumDependencyWeight` {number} The sum weight of all `Http2Stream` <add> instances that depend on this `Http2Stream` as specified using <add> `PRIORITY` frames. <add> * `weight` {number} The priority weight of this `Http2Stream`. <ide> <ide> A current state of this `Http2Stream`. <ide>
1
Javascript
Javascript
add defaults and message to pm2start.js
edd4037a0bd74c5e18e7a41e14e446898a8dfdca
<ide><path>pm2Start.js <add>require('dotenv').load(); <ide> var pm2 = require('pm2'); <add>var instances = process.env.INSTANCES || 1; <add>var serverName = process.env.SERVER_NAME || 'server'; <add>var maxMemory = process.env.MAX_MEMORY || '390M'; <add> <ide> pm2.connect(function() { <ide> pm2.start({ <del> name: process.env.SERVER_NAME || 'server', <add> name: serverName, <ide> script: 'server/production-start.js', <ide> 'exec_mode': 'cluster', <del> instances: process.env.INSTANCES || 1, <del> 'max_memory_restart': process.env.MAX_MEMORY || '300M', <add> instances: instances, <add> 'max_memory_restart': maxMemory, <ide> 'NODE_ENV': 'production' <ide> }, function() { <add> console.log( <add> 'pm2 started %s with %s instances at %s max memory', <add> serverName, <add> instances, <add> maxMemory <add> ); <ide> pm2.disconnect(); <ide> }); <ide> });
1
Text
Text
correct typo on the word "realizing"
527569b95b73d18afb6069091038e8e15caafc5e
<ide><path>guide/english/working-in-tech/unconscious-bias/index.md <ide> Bias is a prejudice in favor of or against one thing, person, or group compared <ide> <ide> <p>Unconscious bias, otherwise known as "implicit bias", occurs when people favour others who look like them and/or share their values. For example a person may be drawn to someone with a similar educational background, from the same area, who shares a similar sexual orientation, or who is the same colour or ethnicity as them.</p> <ide> <del>Implicit or unconscious bias happens by our brains making incredibly quick judgments and assessments of people and situations without us realising. Our biases are influenced by our background, cultural environment and personal experiences. We may not even be aware of these views and opinions, or be aware of their full impact and implications.<sup>3</sup> <add>Implicit or unconscious bias happens by our brains making incredibly quick judgments and assessments of people and situations without us realizing. Our biases are influenced by our background, cultural environment and personal experiences. We may not even be aware of these views and opinions, or be aware of their full impact and implications.<sup>3</sup> <ide> <ide> Unconscious bias is far more prevalent than conscious prejudice and often incompatible with one’s conscious values. Certain scenarios can activate unconscious attitudes and beliefs. For example, biases may be more prevalent when multi-tasking or working under time pressure.<sup>4</sup> <ide> <ide> Unconscious bias can influence decisions in recruitment, promotion and performan <ide> 3. ["Unconscious Bias." *Equality Challenge Unit.* Accessed: October 20, 2017](https://www.ecu.ac.uk/guidance-resources/employment-and-careers/staff-recruitment/unconscious-bias/) <ide> 4. ["What is Unconscious Bias" University of California, San Francisco <ide> Office of Diversity and Outreach. Accessed: October 15, 2017.](https://diversity.ucsf.edu/resources/unconscious-bias) <del>5. ["Unconscious Bias" acas.org.uk Accessed: October 15, 2017.](http://www.acas.org.uk/index.aspx?articleid=5433) <ide>\ No newline at end of file <add>5. ["Unconscious Bias" acas.org.uk Accessed: October 15, 2017.](http://www.acas.org.uk/index.aspx?articleid=5433)
1
Text
Text
add usage of port mapping for boot2docker
9dc2d0b8a35724946139f954f9575411b31695ea
<ide><path>docs/sources/examples/nodejs_web_app.md <ide> Now you can call your app using `curl` (install if needed via: <ide> <ide> Hello world <ide> <add>If you use Boot2docker on OS X, the port is actually mapped to the Docker host VM, <add>and you should use the following command: <add> <add> $ curl $(boot2docker ip):49160 <add> <ide> We hope this tutorial helped you get up and running with Node.js and <ide> CentOS on Docker. You can get the full source code at <ide> [https://github.com/enokd/docker-node-hello/](https://github.com/enokd/docker-node-hello/).
1
Text
Text
add clearer setup description
3f263403e53af403196207e60841f3012e41b2af
<ide><path>BUILDING.md <ide> To run the tests: <ide> $ make test <ide> ``` <ide> <add>At this point you are ready to make code changes and re-run the tests! <add>Optionally, continue below. <add> <ide> To run the tests and generate code coverage reports: <ide> <ide> ```console <ide> and overwrites the `lib/` directory. To clean up after generating the coverage <ide> reports: <ide> <ide> ```console <del>make coverage-clean <add>$ make coverage-clean <ide> ``` <ide> <ide> To build the documentation:
1
Ruby
Ruby
duplicate active record objects on inverse_of
6f6c441662e73084087da3f564e71f0a174c3ee4
<ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> def replace_on_target(record, skip_callbacks, replace:, inversing: false) <ide> <ide> yield(record) if block_given? <ide> <add> if !index && @replaced_or_added_targets.include?(record) <add> index = @target.index(record) <add> end <add> <ide> @replaced_or_added_targets << record if inversing || index || record.new_record? <ide> <ide> if index <ide><path>activerecord/test/cases/associations/inverse_associations_test.rb <ide> def test_with_has_many_inversing_does_not_trigger_association_callbacks_on_set_w <ide> end <ide> end <ide> <add> def test_with_hash_many_inversing_does_not_add_duplicate_associated_objects <add> with_has_many_inversing(Interest) do <add> human = Human.new <add> interest = Interest.new(human: human) <add> human.interests << interest <add> assert_equal 1, human.interests.size <add> end <add> end <add> <ide> def test_unscope_does_not_set_inverse_when_incorrect <ide> interest = interests(:trainspotting) <ide> human = interest.human
2
Python
Python
replace getters/setters with properties - round 4
abec1a72de592e6bac601b480e0c0b8d3aea6636
<ide><path>glances/core/glances_stats.py <ide> def getAllAsDict(self): <ide> <ide> def getAllLimits(self): <ide> """Return the plugins limits list.""" <del> return [self._plugins[p].get_limits() for p in self._plugins] <add> return [self._plugins[p].limits for p in self._plugins] <ide> <ide> def getAllLimitsAsDict(self): <ide> """Return all the stats limits (dict)""" <ide> ret = {} <ide> for p in self._plugins: <del> ret[p] = self._plugins[p].get_limits() <add> ret[p] = self._plugins[p].limits <ide> return ret <ide> <ide> def getAllViews(self): <ide> def update(self): <ide> # For each plugins, call the update method <ide> for p in self._plugins: <ide> # Set the input method to SNMP <del> self._plugins[p].set_input('snmp', self.system_name) <add> self._plugins[p].input_method = 'snmp' <add> self._plugins[p].short_system_name = self.system_name <ide> try: <ide> self._plugins[p].update() <ide> except Exception as e: <ide><path>glances/outputs/glances_bottle.py <ide> def _api_limits(self, plugin): <ide> <ide> try: <ide> # Get the JSON value of the stat limits <del> ret = self.stats.get_plugin(plugin).get_limits() <add> ret = self.stats.get_plugin(plugin).limits <ide> except Exception as e: <ide> abort(404, "Cannot get limits for plugin %s (%s)" % (plugin, str(e))) <ide> return ret <ide><path>glances/plugins/glances_alert.py <ide> def __init__(self, args=None): <ide> self.display_curse = True <ide> <ide> # Set the message position <del> self.set_align('bottom') <add> self.align = 'bottom' <ide> <ide> # Init the stats <ide> self.reset() <ide><path>glances/plugins/glances_batpercent.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats <ide> self.glancesgrabbat.update() <ide> self.stats = self.glancesgrabbat.get() <ide> <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> # Not avalaible <ide> pass <ide><path>glances/plugins/glances_core.py <ide> def update(self): <ide> # Reset the stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> <ide> # The PSUtil 2.0 include psutil.cpu_count() and psutil.cpu_count(logical=False) <ide> def update(self): <ide> except NameError: <ide> self.reset() <ide> <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> # http://stackoverflow.com/questions/5662467/how-to-find-out-the-number-of-cpus-using-snmp <ide> pass <ide><path>glances/plugins/glances_cpu.py <ide> def update(self): <ide> <ide> # Grab CPU stats using psutil's cpu_percent and cpu_times_percent <ide> # methods <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Get all possible values for CPU stats: user, system, idle, <ide> # nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+) <ide> # The following stats are returned by the API but not displayed in the UI: <ide> def update(self): <ide> 'irq', 'softirq', 'steal', 'guest', 'guest_nice']: <ide> if hasattr(cpu_times_percent, stat): <ide> self.stats[stat] = getattr(cpu_times_percent, stat) <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <del> if self.get_short_system_name() in ('windows', 'esxi'): <add> if self.short_system_name in ('windows', 'esxi'): <ide> # Windows or VMWare ESXi <ide> # You can find the CPU utilization of windows system by querying the oid <ide> # Give also the number of core (number of element in the table) <ide> try: <del> cpu_stats = self.get_stats_snmp(snmp_oid=snmp_oid[self.get_short_system_name()], <add> cpu_stats = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name], <ide> bulk=True) <ide> except KeyError: <ide> self.reset() <ide> def update(self): <ide> # Default behavor <ide> try: <ide> self.stats = self.get_stats_snmp( <del> snmp_oid=snmp_oid[self.get_short_system_name()]) <add> snmp_oid=snmp_oid[self.short_system_name]) <ide> except KeyError: <ide> self.stats = self.get_stats_snmp( <ide> snmp_oid=snmp_oid['default']) <ide><path>glances/plugins/glances_diskio.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> # Grab the stat using the PsUtil disk_io_counters method <ide> # read_count: number of reads <ide> def update(self): <ide> <ide> # Save stats to compute next bitrate <ide> self.diskio_old = diskio_new <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> # No standard way for the moment... <ide> pass <ide><path>glances/plugins/glances_docker.py <ide> def update(self): <ide> if not docker_tag or (self.args is not None and self.args.disable_docker): <ide> return self.stats <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats <ide> # Exemple: { <ide> # "KernelVersion": "3.16.4-tinycore64", <ide> def update(self): <ide> # !!! Refresh problem <ide> # c['network'] = self.get_docker_network(c['Id']) <ide> <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> # Not available <ide> pass <ide><path>glances/plugins/glances_fs.py <ide> def update(self): <ide> # Reset the list <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> <ide> # Grab the stats using the PsUtil disk_partitions <ide> def update(self): <ide> fs_current['key'] = self.get_key() <ide> self.stats.append(fs_current) <ide> <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> <ide> # SNMP bulk command to get all file system in one shot <ide> try: <del> fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.get_short_system_name()], <add> fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name], <ide> bulk=True) <ide> except KeyError: <ide> fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid['default'], <ide> bulk=True) <ide> <ide> # Loop over fs <del> if self.get_short_system_name() in ('windows', 'esxi'): <add> if self.short_system_name in ('windows', 'esxi'): <ide> # Windows or ESXi tips <ide> for fs in fs_stat: <ide> # Memory stats are grabed in the same OID table (ignore it) <ide><path>glances/plugins/glances_hddtemp.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> self.stats = self.glancesgrabhddtemp.get() <ide> <ide><path>glances/plugins/glances_ip.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local' and netifaces_tag: <add> if self.input_method == 'local' and netifaces_tag: <ide> # Update stats using the netifaces lib <ide> try: <ide> default_gw = netifaces.gateways()['default'][netifaces.AF_INET] <ide> def update(self): <ide> except KeyError as e: <ide> logger.debug("Can not grab IP information (%s)".format(e)) <ide> <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Not implemented yet <ide> pass <ide> <ide><path>glances/plugins/glances_load.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> <ide> # Get the load using the os standard lib <ide> def update(self): <ide> 'min5': load[1], <ide> 'min15': load[2], <ide> 'cpucore': self.nb_log_core} <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> self.stats = self.get_stats_snmp(snmp_oid=snmp_oid) <ide> <ide><path>glances/plugins/glances_mem.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> # Grab MEM using the PSUtil virtual_memory method <ide> vm_stats = psutil.virtual_memory() <ide> def update(self): <ide> self.stats['free'] += self.stats['cached'] <ide> # used=total-free <ide> self.stats['used'] = self.stats['total'] - self.stats['free'] <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <del> if self.get_short_system_name() in ('windows', 'esxi'): <add> if self.short_system_name in ('windows', 'esxi'): <ide> # Mem stats for Windows|Vmware Esxi are stored in the FS table <ide> try: <del> fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.get_short_system_name()], <add> fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name], <ide> bulk=True) <ide> except KeyError: <ide> self.reset() <ide><path>glances/plugins/glances_memswap.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> # Grab SWAP using the PSUtil swap_memory method <ide> sm_stats = psutil.swap_memory() <ide> def update(self): <ide> 'sin', 'sout']: <ide> if hasattr(sm_stats, swap): <ide> self.stats[swap] = getattr(sm_stats, swap) <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <del> if self.get_short_system_name() == 'windows': <add> if self.short_system_name == 'windows': <ide> # Mem stats for Windows OS are stored in the FS table <ide> try: <del> fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.get_short_system_name()], <add> fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name], <ide> bulk=True) <ide> except KeyError: <ide> self.reset() <ide><path>glances/plugins/glances_monitor.py <ide> def load_limits(self, config): <ide> <ide> def update(self): <ide> """Update the monitored list.""" <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Monitor list only available in a full Glances environment <ide> # Check if the glances_monitor instance is init <ide> if self.glances_monitors is None: <ide><path>glances/plugins/glances_network.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> <ide> # Grab network interface stat using the PsUtil net_io_counter method <ide> def update(self): <ide> # Save stats to compute next bitrate <ide> self.network_old = network_new <ide> <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> <ide> # SNMP bulk command to get all network interface in one shot <ide> try: <del> netiocounters = self.get_stats_snmp(snmp_oid=snmp_oid[self.get_short_system_name()], <add> netiocounters = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name], <ide> bulk=True) <ide> except KeyError: <ide> netiocounters = self.get_stats_snmp(snmp_oid=snmp_oid['default'], <ide> def update(self): <ide> netstat = {} <ide> # Windows: a tips is needed to convert HEX to TXT <ide> # http://blogs.technet.com/b/networking/archive/2009/12/18/how-to-query-the-list-of-network-interfaces-using-snmp-via-the-ifdescr-counter.aspx <del> if self.get_short_system_name() == 'windows': <add> if self.short_system_name == 'windows': <ide> try: <ide> netstat['interface_name'] = str(base64.b16decode(net[2:-2].upper())) <ide> except TypeError: <ide><path>glances/plugins/glances_now.py <ide> def __init__(self, args=None): <ide> self.display_curse = True <ide> <ide> # Set the message position <del> self.set_align('bottom') <add> self.align = 'bottom' <ide> <ide> def update(self): <ide> """Update current date/time.""" <ide><path>glances/plugins/glances_percpu.py <ide> def update(self): <ide> <ide> # Grab per-CPU stats using psutil's cpu_percent(percpu=True) and <ide> # cpu_times_percent(percpu=True) methods <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> percpu_percent = psutil.cpu_percent(interval=0.0, percpu=True) <ide> percpu_times_percent = psutil.cpu_times_percent(interval=0.0, percpu=True) <ide> for cputimes in percpu_times_percent: <ide><path>glances/plugins/glances_plugin.py <ide> def __init__(self, args=None, items_history_list=None): <ide> self.args = args <ide> <ide> # Init the default alignement (for curses) <del> self.set_align('left') <add> self._align = 'left' <ide> <ide> # Init the input method <del> self.input_method = 'local' <del> self.short_system_name = None <add> self._input_method = 'local' <add> self._short_system_name = None <ide> <ide> # Init the stats list <ide> self.stats = None <ide> def __init__(self, args=None, items_history_list=None): <ide> self.stats_history = self.init_stats_history() <ide> <ide> # Init the limits dictionnary <del> self.limits = dict() <add> self._limits = dict() <ide> <ide> # Init the actions <ide> self.actions = GlancesActions() <ide> def get_items_history_list(self): <ide> """Return the items history list""" <ide> return self.items_history_list <ide> <del> def set_input(self, input_method, short_system_name=None): <add> @property <add> def input_method(self): <add> """Get the input method.""" <add> return self._input_method <add> <add> @input_method.setter <add> def input_method(self, input_method): <ide> """Set the input method. <ide> <ide> * local: system local grab (psutil or direct access) <ide> * snmp: Client server mode via SNMP <ide> * glances: Client server mode via Glances API <del> <del> For SNMP, short_system_name is detected short OS name <ide> """ <del> self.input_method = input_method <del> self.short_system_name = short_system_name <add> self._input_method = input_method <ide> <del> def get_input(self): <del> """Get the input method.""" <del> return self.input_method <add> @property <add> def short_system_name(self): <add> """Get the short detected OS name (SNMP).""" <add> return self._short_system_name <ide> <del> def get_short_system_name(self): <del> """Get the short detected OS name""" <del> return self.short_system_name <add> @short_system_name.setter <add> def short_system_name(self, short_name): <add> """Set the short detected OS name (SNMP).""" <add> self._short_system_name = short_name <ide> <ide> def set_stats(self, input_stats): <ide> """Set the stats to input_stats.""" <ide> def load_limits(self, config): <ide> """Load the limits from the configuration file.""" <ide> if (hasattr(config, 'has_section') and <ide> config.has_section(self.plugin_name)): <del> for s, v in config.items(self.plugin_name): <add> for level, v in config.items(self.plugin_name): <ide> # Read limits <add> limit = '_'.join([self.plugin_name, level]) <ide> try: <del> self.limits[ <del> self.plugin_name + '_' + s] = config.get_option(self.plugin_name, s) <add> self._limits[limit] = config.get_option(self.plugin_name, level) <ide> except ValueError: <del> self.limits[ <del> self.plugin_name + '_' + s] = config.get_raw_option(self.plugin_name, s).split(",") <del> logger.debug("Load limit: {0} = {1}".format(self.plugin_name + '_' + s, <del> self.limits[self.plugin_name + '_' + s])) <del> <del> def set_limits(self, input_limits): <del> """Set the limits to input_limits.""" <del> self.limits = input_limits <add> self._limits[limit] = config.get_raw_option(self.plugin_name, level).split(",") <add> logger.debug("Load limit: {0} = {1}".format(limit, self._limits[limit])) <ide> <del> def get_limits(self): <add> @property <add> def limits(self): <ide> """Return the limits object.""" <del> return self.limits <add> return self._limits <add> <add> @limits.setter <add> def limits(self, input_limits): <add> """Set the limits to input_limits.""" <add> self._limits = input_limits <ide> <ide> def get_alert(self, current=0, minimum=0, maximum=100, header="", log=False): <ide> """Return the alert status relative to a current value. <ide> def __get_limit(self, criticity, stat_name=""): <ide> # Get the limit for stat + header <ide> # Exemple: network_wlan0_rx_careful <ide> try: <del> limit = self.limits[stat_name + '_' + criticity] <add> limit = self._limits[stat_name + '_' + criticity] <ide> except KeyError: <ide> # Try fallback to plugin default limit <ide> # Exemple: network_careful <del> limit = self.limits[self.plugin_name + '_' + criticity] <add> limit = self._limits[self.plugin_name + '_' + criticity] <ide> <ide> # Return the limit <ide> return limit <ide> def __get_limit_action(self, criticity, stat_name=""): <ide> # Get the action for stat + header <ide> # Exemple: network_wlan0_rx_careful_action <ide> try: <del> ret = self.limits[stat_name + '_' + criticity + '_action'] <add> ret = self._limits[stat_name + '_' + criticity + '_action'] <ide> except KeyError: <ide> # Try fallback to plugin default limit <ide> # Exemple: network_careful_action <del> ret = self.limits[self.plugin_name + '_' + criticity + '_action'] <add> ret = self._limits[self.plugin_name + '_' + criticity + '_action'] <ide> <ide> # Return the action list <ide> return ret <ide> def __get_limit_log(self, stat_name, default_action=False): <ide> # Get the log tag for stat + header <ide> # Exemple: network_wlan0_rx_log <ide> try: <del> log_tag = self.limits[stat_name + '_log'] <add> log_tag = self._limits[stat_name + '_log'] <ide> except KeyError: <ide> # Try fallback to plugin default log <ide> # Exemple: network_log <ide> try: <del> log_tag = self.limits[self.plugin_name + '_log'] <add> log_tag = self._limits[self.plugin_name + '_log'] <ide> except KeyError: <ide> # By defaukt, log are disabled <ide> return default_action <ide> def get_conf_value(self, value, header="", plugin_name=None): <ide> plugin_name = self.plugin_name <ide> if header == "": <ide> try: <del> return self.limits[plugin_name + '_' + value] <add> return self._limits[plugin_name + '_' + value] <ide> except KeyError: <ide> return [] <ide> else: <ide> try: <del> return self.limits[plugin_name + '_' + header + '_' + value] <add> return self._limits[plugin_name + '_' + header + '_' + value] <ide> except KeyError: <ide> return [] <ide> <ide> def is_hide(self, value, header=""): <ide> def has_alias(self, header): <ide> """Return the alias name for the relative header or None if nonexist""" <ide> try: <del> return self.limits[self.plugin_name + '_' + header + '_' + 'alias'][0] <add> return self._limits[self.plugin_name + '_' + header + '_' + 'alias'][0] <ide> except (KeyError, IndexError): <ide> return None <ide> <ide> def get_stats_display(self, args=None, max_width=None): <ide> if hasattr(self, 'display_curse'): <ide> display_curse = self.display_curse <ide> if hasattr(self, 'align'): <del> align_curse = self.align <add> align_curse = self._align <ide> <ide> if max_width is not None: <ide> ret = {'display': display_curse, <ide> def curse_new_line(self): <ide> """Go to a new line.""" <ide> return self.curse_add_line('\n') <ide> <del> def set_align(self, align='left'): <del> """Set the Curse align""" <del> if align in ('left', 'right', 'bottom'): <del> self.align = align <del> else: <del> self.align = 'left' <add> @property <add> def align(self): <add> """Get the curse align.""" <add> return self._align <ide> <del> def get_align(self): <del> """Get the Curse align""" <del> return self.align <add> @align.setter <add> def align(self, value): <add> """Set the curse align. <add> <add> value: left, right, bottom. <add> """ <add> self._align = value <ide> <ide> def auto_unit(self, number, low_precision=False): <ide> """Make a nice human-readable string out of number. <ide><path>glances/plugins/glances_processcount.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> # Here, update is call for processcount AND processlist <ide> glances_processes.update() <ide> <ide> # Return the processes count <ide> self.stats = glances_processes.getcount() <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> # !!! TODO <ide> pass <ide><path>glances/plugins/glances_processlist.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> # Note: Update is done in the processcount plugin <ide> # Just return the processes list <ide> if glances_processes.is_tree_enabled(): <ide> self.stats = glances_processes.gettree() <ide> else: <ide> self.stats = glances_processes.getlist() <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # No SNMP grab for processes <ide> pass <ide> <ide><path>glances/plugins/glances_psutilversion.py <ide> def update(self): <ide> self.reset() <ide> <ide> # Return PsUtil version as a tuple <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # PsUtil version only available in local <ide> try: <ide> self.stats = tuple([int(num) for num in __psutil_version.split('.')]) <ide><path>glances/plugins/glances_quicklook.py <ide> def update(self): <ide> self.reset() <ide> <ide> # Grab quicklook stats: CPU, MEM and SWAP <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Get the latest CPU percent value <ide> self.stats['cpu'] = cpu_percent.get() <ide> # Use the PsUtil lib for the memory (virtual and swap) <ide> self.stats['mem'] = psutil.virtual_memory().percent <ide> self.stats['swap'] = psutil.swap_memory().percent <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Not available <ide> pass <ide> <ide><path>glances/plugins/glances_raid.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the PyMDstat lib (https://github.com/nicolargo/pymdstat) <ide> try: <ide> mds = MdStat() <ide> def update(self): <ide> logger.debug("Can not grab RAID stats (%s)" % e) <ide> return self.stats <ide> <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> # No standard way for the moment... <ide> pass <ide><path>glances/plugins/glances_sensors.py <ide> def update(self): <ide> # Reset the stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the dedicated lib <ide> self.stats = [] <ide> # Get the temperature <ide> def update(self): <ide> # Append Batteries % <ide> self.stats.extend(batpercent) <ide> <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> # No standard: <ide> # http://www.net-snmp.org/wiki/index.php/Net-SNMP_and_lm-sensors_on_Ubuntu_10.04 <ide><path>glances/plugins/glances_system.py <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> self.stats['os_name'] = platform.system() <ide> self.stats['hostname'] = platform.node() <ide> def update(self): <ide> self.stats['os_name'], self.stats['os_version']) <ide> self.stats['hr_name'] += ' ({0})'.format(self.stats['platform']) <ide> <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> try: <ide> self.stats = self.get_stats_snmp( <del> snmp_oid=snmp_oid[self.get_short_system_name()]) <add> snmp_oid=snmp_oid[self.short_system_name]) <ide> except KeyError: <ide> self.stats = self.get_stats_snmp(snmp_oid=snmp_oid['default']) <ide> # Default behavor: display all the information <ide> self.stats['os_name'] = self.stats['system_name'] <ide> # Windows OS tips <del> if self.get_short_system_name() == 'windows': <add> if self.short_system_name == 'windows': <ide> try: <ide> iteritems = snmp_to_human['windows'].iteritems() <ide> except AttributeError: <ide><path>glances/plugins/glances_uptime.py <ide> def __init__(self, args=None): <ide> self.display_curse = True <ide> <ide> # Set the message position <del> self.set_align('right') <add> self.align = 'right' <ide> <ide> # Init the stats <ide> self.reset() <ide> def update(self): <ide> # Reset stats <ide> self.reset() <ide> <del> if self.get_input() == 'local': <add> if self.input_method == 'local': <ide> # Update stats using the standard system lib <ide> uptime = datetime.now() - \ <ide> datetime.fromtimestamp(psutil.boot_time()) <ide> <ide> # Convert uptime to string (because datetime is not JSONifi) <ide> self.stats = str(uptime).split('.')[0] <del> elif self.get_input() == 'snmp': <add> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> uptime = self.get_stats_snmp(snmp_oid=snmp_oid)['_uptime'] <ide> try:
27
PHP
PHP
add lots of tests for routecollection
d25b456d2767bc73f1c6c571daff28d2f50f3f30
<ide><path>tests/Routing/RouteCollectionTest.php <add><?php <add> <add>use Illuminate\Routing\Route; <add>use Illuminate\Routing\RouteCollection; <add> <add>class RouteCollectionTest extends PHPUnit_Framework_TestCase <add>{ <add> /** <add> * @var \Illuminate\Routing\RouteCollection <add> */ <add> protected $routeCollection; <add> <add> public function setUp() <add> { <add> parent::setUp(); <add> <add> $this->routeCollection = new RouteCollection(); <add> } <add> <add> public function testRouteCollectionCanBeConstructed() <add> { <add> $this->assertInstanceOf(RouteCollection::class, $this->routeCollection); <add> } <add> <add> public function testRouteCollectionCanAddRoute() <add> { <add> $this->routeCollection->add(new Route('GET', 'foo', [ <add> 'uses' => 'FooController@index', <add> 'as' => 'foo_index', <add> ])); <add> $this->assertCount(1, $this->routeCollection); <add> } <add> <add> public function testRouteCollectionAddReturnsTheRoute() <add> { <add> $outputRoute = $this->routeCollection->add($inputRoute = new Route('GET', 'foo', [ <add> 'uses' => 'FooController@index', <add> 'as' => 'foo_index', <add> ])); <add> $this->assertInstanceOf(Route::class, $outputRoute); <add> $this->assertEquals($inputRoute, $outputRoute); <add> } <add> <add> public function testRouteCollectionAddRouteChangesCount() <add> { <add> $this->routeCollection->add(new Route('GET', 'foo', [ <add> 'uses' => 'FooController@index', <add> 'as' => 'foo_index', <add> ])); <add> $this->assertSame(1, $this->routeCollection->count()); <add> } <add> <add> public function testRouteCollectionIsCountable() <add> { <add> $this->routeCollection->add(new Route('GET', 'foo', [ <add> 'uses' => 'FooController@index', <add> 'as' => 'foo_index', <add> ])); <add> $this->assertCount(1, $this->routeCollection); <add> } <add> <add> public function testRouteCollectionCanRetrieveByName() <add> { <add> $this->routeCollection->add($routeIndex = new Route('GET', 'foo/index', [ <add> 'uses' => 'FooController@index', <add> 'as' => 'route_name', <add> ])); <add> <add> $this->assertSame('route_name', $routeIndex->getName()); <add> $this->assertSame('route_name', $this->routeCollection->getByName('route_name')->getName()); <add> $this->assertEquals($routeIndex, $this->routeCollection->getByName('route_name')); <add> } <add> <add> public function testRouteCollectionCanRetrieveByAction() <add> { <add> $this->routeCollection->add($routeIndex = new Route('GET', 'foo/index', $action = [ <add> 'uses' => 'FooController@index', <add> 'as' => 'route_name', <add> ])); <add> <add> $this->assertSame($action, $routeIndex->getAction()); <add> } <add> <add> public function testRouteCollectionCanGetIterator() <add> { <add> $this->routeCollection->add($routeIndex = new Route('GET', 'foo/index', [ <add> 'uses' => 'FooController@index', <add> 'as' => 'foo_index', <add> ])); <add> $this->assertEquals([$routeIndex], $this->routeCollection->getRoutes()); <add> } <add> <add> public function testRouteCollectionCanGetIteratorWhenEMpty() <add> { <add> $this->assertCount(0, $this->routeCollection); <add> $this->assertInstanceOf(ArrayIterator::class, $this->routeCollection->getIterator()); <add> } <add> <add> public function testRouteCollectionCanGetIteratorWhenRouteAreAdded() <add> { <add> $this->routeCollection->add($routeIndex = new Route('GET', 'foo/index', [ <add> 'uses' => 'FooController@index', <add> 'as' => 'foo_index', <add> ])); <add> $this->assertCount(1, $this->routeCollection); <add> <add> $this->routeCollection->add($routeShow = new Route('GET', 'bar/show', [ <add> 'uses' => 'BarController@show', <add> 'as' => 'bar_show', <add> ])); <add> $this->assertCount(2, $this->routeCollection); <add> <add> $this->assertInstanceOf(ArrayIterator::class, $this->routeCollection->getIterator()); <add> } <add> <add> public function testRouteCollectionCanHandleSameRoute() <add> { <add> $routeIndex = new Route('GET', 'foo/index', [ <add> 'uses' => 'FooController@index', <add> 'as' => 'foo_index', <add> ]); <add> <add> $this->routeCollection->add($routeIndex); <add> $this->assertCount(1, $this->routeCollection); <add> <add> // Add exactly the same route <add> $this->routeCollection->add($routeIndex); <add> $this->assertCount(1, $this->routeCollection); <add> <add> // Add a non-existing route <add> $this->routeCollection->add(new Route('GET', 'bar/show', [ <add> 'uses' => 'BarController@show', <add> 'as' => 'bar_show', <add> ])); <add> $this->assertCount(2, $this->routeCollection); <add> } <add> <add> public function testRouteCollectionCanRefreshNameLookups() <add> { <add> $routeIndex = new Route('GET', 'foo/index', [ <add> 'uses' => 'FooController@index', <add> ]); <add> <add> // The name of the route is not yet set. It will be while adding if to the RouteCollection. <add> $this->assertNull($routeIndex->getName()); <add> <add> // The route name is set by calling \Illuminate\Routing\Route::name() <add> $this->routeCollection->add($routeIndex)->name('route_name'); <add> <add> // No route is found. This is normal, as no refresh as been done. <add> $this->assertNull($this->routeCollection->getByName('route_name')); <add> <add> // After the refresh, the name will be properly set to the route. <add> $this->routeCollection->refreshNameLookups(); <add> $this->assertEquals($routeIndex, $this->routeCollection->getByName('route_name')); <add> } <add> <add> public function testRouteCollectionCanGetAllRoutes() <add> { <add> $this->routeCollection->add($routeIndex = new Route('GET', 'foo/index', [ <add> 'uses' => 'FooController@index', <add> 'as' => 'foo_index', <add> ])); <add> <add> $this->routeCollection->add($routeShow = new Route('GET', 'foo/show', [ <add> 'uses' => 'FooController@show', <add> 'as' => 'foo_show', <add> ])); <add> <add> $this->routeCollection->add($routeNew = new Route('POST', 'bar', [ <add> 'uses' => 'BarController@create', <add> 'as' => 'bar_create', <add> ])); <add> <add> $allRoutes = [ <add> $routeIndex, <add> $routeShow, <add> $routeNew, <add> ]; <add> $this->assertEquals($allRoutes, $this->routeCollection->getRoutes()); <add> } <add>}
1
PHP
PHP
replace deprecated class
f54b58433d42a30754719895b653116d20c800f2
<ide><path>src/Illuminate/Redis/Connections/PhpRedisConnection.php <ide> namespace Illuminate\Redis\Connections; <ide> <ide> use Closure; <add>use Illuminate\Collections\Arr; <ide> use Illuminate\Contracts\Redis\Connection as ConnectionContract; <del>use Illuminate\Support\Arr; <ide> use Illuminate\Support\Str; <ide> use Redis; <ide> use RedisCluster;
1
Python
Python
add size_type in definition for volume creation
e438a8f3d957cb7e37e68927d228e83190f6d2b4
<ide><path>libcloud/container/drivers/lxd.py <ide> class LXDContainerDriver(ContainerDriver): <ide> default_profiles = 'default' <ide> <ide> # An ephemeral container means that it <del> # will be restroyed once it is stopped <add> # will be destroyed once it is stopped <ide> default_ephemeral = False <ide> <ide> def __init__(self, key='', secret='', secure=False, <ide> def ex_create_storage_pool(self, definition): <ide> } <ide> <ide> Note that **all** fields in the `definition` parameter are strings. <del> Note that size has to be at least 64M in order to create the pool <add> Note that size has to be at least 64MB in order to create the pool <ide> <ide> For further details on the storage pool types see: <ide> https://lxd.readthedocs.io/en/latest/storage/ <ide> def ex_create_storage_pool_volume(self, pool_id, definition): <ide> raise LXDAPIException("Cannot create a storage volume " <ide> "without a definition") <ide> <add> #import pdb <add> #pdb.set_trace() <add> <add> if definition['config']['size_type'] == 'GB': <add> definition['config'].pop('size_type') <add> definition['config']['size'] = str(LXDContainerDriver._to_bytes(definition['config']['size'])) <add> elif definition['config']['size_type'] == 'MB': <add> definition['config'].pop('size_type') <add> definition['config']['size'] = LXDContainerDriver._to_bytes(definition['config']['size']) <add> else: <add> raise LXDAPIException(message="Definition does not contain size units") <add> <ide> data = json.dumps(definition) <add> #data['config']['size'] = str(data['config']['size']) <ide> <ide> # Return: standard return value or standard error <ide> req = "/%s/storage-pools/%s/volumes" % (self.version, pool_id) <ide> def _to_gb(size): <ide> size = int(size) <ide> return size // 10**9 <ide> <add> @staticmethod <add> def _to_bytes(size): <add> """ <add> convert the given size in GB to bytes <add> :param size: in GBs <add> :return: int representing bytes <add> """ <add> size = int(size) <add> return size*10**9 <add>
1
Python
Python
add reverse_code optional argument to runpython
6d3faba2d28f07f8cd7cf7aa91a6f8a555021d4f
<ide><path>django/db/migrations/operations/special.py <ide> class RunPython(Operation): <ide> reduces_to_sql = False <ide> reversible = False <ide> <del> def __init__(self, code): <add> def __init__(self, code, reverse_code=None): <add> # Forwards code <ide> if isinstance(code, six.string_types): <ide> # Trim any leading whitespace that is at the start of all code lines <ide> # so users can nicely indent code in migration files <ide> code = textwrap.dedent(code) <ide> # Run the code through a parser first to make sure it's at least <ide> # syntactically correct <ide> self.code = compile(code, "<string>", "exec") <del> self.is_callable = False <ide> else: <ide> self.code = code <del> self.is_callable = True <add> # Reverse code <add> if reverse_code is None: <add> self.reverse_code = None <add> elif isinstance(reverse_code, six.string_types): <add> reverse_code = textwrap.dedent(reverse_code) <add> self.reverse_code = compile(reverse_code, "<string>", "exec") <add> else: <add> self.reverse_code = reverse_code <ide> <ide> def state_forwards(self, app_label, state): <ide> # RunPython objects have no state effect. To add some, combine this <ide> def database_forwards(self, app_label, schema_editor, from_state, to_state): <ide> # object, representing the versioned models as an AppCache. <ide> # We could try to override the global cache, but then people will still <ide> # use direct imports, so we go with a documentation approach instead. <del> if self.is_callable: <add> if six.callable(self.code): <ide> self.code(models=from_state.render(), schema_editor=schema_editor) <ide> else: <ide> context = { <ide> def database_forwards(self, app_label, schema_editor, from_state, to_state): <ide> eval(self.code, context) <ide> <ide> def database_backwards(self, app_label, schema_editor, from_state, to_state): <del> raise NotImplementedError("You cannot reverse this operation") <add> if self.reverse_code is None: <add> raise NotImplementedError("You cannot reverse this operation") <add> elif six.callable(self.reverse_code): <add> self.reverse_code(models=from_state.render(), schema_editor=schema_editor) <add> else: <add> context = { <add> "models": from_state.render(), <add> "schema_editor": schema_editor, <add> } <add> eval(self.reverse_code, context) <ide> <ide> def describe(self): <ide> return "Raw Python operation"
1
PHP
PHP
fix double printing of models in consoleshell
5bd45ec65dac99fb8868e7b7b347984b1579f650
<ide><path>lib/Cake/Console/Command/ConsoleShell.php <ide> public function startup() { <ide> <ide> foreach ($this->models as $model) { <ide> $class = $model; <del> $this->models[$model] = $class; <ide> App::uses($class, 'Model'); <ide> $this->{$class} = new $class(); <ide> }
1
Ruby
Ruby
use different test formula
49d2d7b94d85dd150956ea14d66a34870d2f70fd
<ide><path>Library/Homebrew/test/cmd/home_spec.rb <ide> end <ide> <ide> it "opens the homepage for a given Formula" do <del> setup_test_formula "testball" <add> setup_test_formula "testballhome" <ide> <del> expect { brew "home", "testball", "HOMEBREW_BROWSER" => "echo" } <del> .to output("#{Formula["testball"].homepage}\n").to_stdout <add> expect { brew "home", "testballhome", "HOMEBREW_BROWSER" => "echo" } <add> .to output("#{Formula["testballhome"].homepage}\n").to_stdout <ide> .and not_to_output.to_stderr <ide> .and be_a_success <ide> end
1
Ruby
Ruby
combine #should_copy? and #include?
fef866aae4f13d2789d156de33fce1ab1e99db5f
<ide><path>Library/Homebrew/metafiles.rb <ide> class Metafiles <ide> news notes notice readme todo <ide> ] <ide> <del> def should_copy? file <del> include? file <del> end <del> <ide> def should_list? file <ide> return false if %w[.DS_Store INSTALL_RECEIPT.json].include? file <del> not include? file <add> !copy?(file) <ide> end <ide> <del> private <del> <del> def include?(path) <add> def should_copy?(path) <ide> path = path.to_s.downcase <ide> ext = File.extname(path) <ide>
1
Javascript
Javascript
remove unnecessary 'use strict' in the source
45c1ff348e1c7d03567f5bba6cb32cffa9222972
<ide><path>packages/events/EventPluginHub.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import ReactErrorUtils from 'shared/ReactErrorUtils'; <ide> import invariant from 'fbjs/lib/invariant'; <ide> <ide><path>packages/events/EventPluginRegistry.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {DispatchConfig} from './ReactSyntheticEventType'; <ide> import type { <ide> AnyNativeEvent, <ide><path>packages/events/EventPluginUtils.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import ReactErrorUtils from 'shared/ReactErrorUtils'; <ide> import invariant from 'fbjs/lib/invariant'; <ide> import warning from 'fbjs/lib/warning'; <ide><path>packages/events/EventPropagators.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import { <ide> getParentInstance, <ide> traverseTwoPhase, <ide><path>packages/events/PluginModuleType.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide> import type { <ide> DispatchConfig, <ide><path>packages/events/ReactControlledComponent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import invariant from 'fbjs/lib/invariant'; <ide> <ide> import EventPluginUtils from './EventPluginUtils'; <ide><path>packages/events/ReactEventEmitterMixin.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import EventPluginHub from './EventPluginHub'; <ide> <ide> function runEventQueueInBatch(events) { <ide><path>packages/events/ReactGenericBatching.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import ReactControlledComponent from './ReactControlledComponent'; <ide> <ide> // Used as a way to call batchedUpdates when we don't have a reference to <ide><path>packages/events/ReactSyntheticEventType.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide> <ide> export type DispatchConfig = { <ide><path>packages/events/ResponderEventPlugin.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import {getLowestCommonAncestor, isAncestor} from 'shared/ReactTreeTraversal'; <ide> <ide> import EventPluginUtils from './EventPluginUtils'; <ide><path>packages/events/ResponderSyntheticEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticEvent from './SyntheticEvent'; <ide> <ide> /** <ide><path>packages/events/ResponderTouchHistoryStore.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import invariant from 'fbjs/lib/invariant'; <ide> import warning from 'fbjs/lib/warning'; <ide> <ide><path>packages/events/SyntheticEvent.js <ide> <ide> /* eslint valid-typeof: 0 */ <ide> <del>'use strict'; <del> <ide> import emptyFunction from 'fbjs/lib/emptyFunction'; <ide> import invariant from 'fbjs/lib/invariant'; <ide> import warning from 'fbjs/lib/warning'; <ide><path>packages/events/TouchHistoryMath.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> var TouchHistoryMath = { <ide> /** <ide> * This code is optimized and not intended to look beautiful. This allows <ide><path>packages/events/accumulate.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import invariant from 'fbjs/lib/invariant'; <ide> <ide> /** <ide><path>packages/events/accumulateInto.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import invariant from 'fbjs/lib/invariant'; <ide> <ide> /** <ide><path>packages/events/forEachAccumulated.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> /** <ide> * @param {array} arr an "accumulation" of items which is either an Array or <ide> * a single item. Useful when paired with the `accumulate` module. This is a <ide><path>packages/react-art/src/ReactART.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import React from 'react'; <ide> import ReactFiberReconciler from 'react-reconciler'; <ide> import * as ReactDOMFrameScheduling from 'shared/ReactDOMFrameScheduling'; <ide><path>packages/react-call-return/src/ReactCallReturn.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {ReactCall, ReactNodeList, ReactReturn} from 'shared/ReactTypes'; <ide> <ide> // The Symbol used to tag the special React types. If there is no native Symbol <ide><path>packages/react-cs-renderer/src/ReactNativeCS.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <ide> import type {ReactNativeCSType} from './ReactNativeCSTypes'; <ide> <ide><path>packages/react-cs-renderer/src/ReactNativeCSFeatureFlags.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {FeatureFlags} from 'shared/ReactFeatureFlags'; <ide> <ide> var ReactNativeCSFeatureFlags: FeatureFlags = { <ide><path>packages/react-cs-renderer/src/ReactNativeCSTypes.js <ide> * @flow <ide> * @providesModule ReactNativeCSTypes <ide> */ <del>'use strict'; <ide> <ide> /** <ide> * Flat CS renderer bundles are too big for Flow to parse efficiently. <ide><path>packages/react-dom/src/client/DOMPropertyOperations.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import DOMProperty from '../shared/DOMProperty'; <ide> import warning from 'fbjs/lib/warning'; <ide> <ide><path>packages/react-dom/src/client/ReactDOM.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <ide> <ide> import '../shared/checkReact'; <ide><path>packages/react-dom/src/client/ReactDOMClientInjection.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import EventPluginHub from 'events/EventPluginHub'; <ide> import EventPluginUtils from 'events/EventPluginUtils'; <ide> <ide><path>packages/react-dom/src/client/ReactDOMComponentTree.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import {HostComponent, HostText} from 'shared/ReactTypeOfWork'; <ide> import invariant from 'fbjs/lib/invariant'; <ide> <ide><path>packages/react-dom/src/client/ReactDOMFB.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import * as ReactFiberTreeReflection from 'shared/ReactFiberTreeReflection'; <ide> import * as ReactInstanceMap from 'shared/ReactInstanceMap'; <ide> // TODO: direct imports like some-package/src/* are bad. Fix me. <ide><path>packages/react-dom/src/client/ReactDOMFiberComponent.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> // TODO: direct imports like some-package/src/* are bad. Fix me. <ide> import ReactDebugCurrentFiber <ide> from 'react-reconciler/src/ReactDebugCurrentFiber'; <ide><path>packages/react-dom/src/client/ReactDOMFiberInput.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> // TODO: direct imports like some-package/src/* are bad. Fix me. <ide> import ReactDebugCurrentFiber <ide> from 'react-reconciler/src/ReactDebugCurrentFiber'; <ide><path>packages/react-dom/src/client/ReactDOMFiberOption.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import React from 'react'; <ide> import warning from 'fbjs/lib/warning'; <ide> <ide><path>packages/react-dom/src/client/ReactDOMFiberSelect.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> // TODO: direct imports like some-package/src/* are bad. Fix me. <ide> import ReactDebugCurrentFiber <ide> from 'react-reconciler/src/ReactDebugCurrentFiber'; <ide><path>packages/react-dom/src/client/ReactDOMFiberTextarea.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import invariant from 'fbjs/lib/invariant'; <ide> import warning from 'fbjs/lib/warning'; <ide> // TODO: direct imports like some-package/src/* are bad. Fix me. <ide><path>packages/react-dom/src/client/ReactDOMSelection.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import getNodeForCharacterOffset from './getNodeForCharacterOffset'; <ide> import getTextContentAccessor from './getTextContentAccessor'; <ide> import {TEXT_NODE} from '../shared/HTMLNodeType'; <ide><path>packages/react-dom/src/client/ReactInputSelection.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import containsNode from 'fbjs/lib/containsNode'; <ide> import focusNode from 'fbjs/lib/focusNode'; <ide> import getActiveElement from 'fbjs/lib/getActiveElement'; <ide><path>packages/react-dom/src/client/getNodeForCharacterOffset.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import {TEXT_NODE} from '../shared/HTMLNodeType'; <ide> <ide> /** <ide><path>packages/react-dom/src/client/getTextContentAccessor.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'; <ide> <ide> var contentKey = null; <ide><path>packages/react-dom/src/client/inputValueTracking.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> type ValueTracker = { <ide> getValue(): string, <ide> setValue(value: string): void, <ide><path>packages/react-dom/src/client/setInnerHTML.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import {Namespaces} from '../shared/DOMNamespaces'; <ide> import createMicrosoftUnsafeLocalFunction <ide> from '../shared/createMicrosoftUnsafeLocalFunction'; <ide><path>packages/react-dom/src/client/setTextContent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'; <ide> <ide> import setInnerHTML from './setInnerHTML'; <ide><path>packages/react-dom/src/client/validateDOMNesting.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import emptyFunction from 'fbjs/lib/emptyFunction'; <ide> import warning from 'fbjs/lib/warning'; <ide> // TODO: direct imports like some-package/src/* are bad. Fix me. <ide><path>packages/react-dom/src/events/BeforeInputEventPlugin.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import type {TopLevelTypes} from './BrowserEventConstants'; <ide> <ide> import EventPropagators from 'events/EventPropagators'; <ide><path>packages/react-dom/src/events/BrowserEventConstants.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import getVendorPrefixedEventName from './getVendorPrefixedEventName'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/ChangeEventPlugin.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import EventPluginHub from 'events/EventPluginHub'; <ide> import EventPropagators from 'events/EventPropagators'; <ide> import ReactControlledComponent from 'events/ReactControlledComponent'; <ide><path>packages/react-dom/src/events/DOMEventPluginOrder.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> /** <ide> * Module that is injectable into `EventPluginHub`, that specifies a <ide> * deterministic ordering of `EventPlugin`s. A convenient way to reason about <ide><path>packages/react-dom/src/events/EnterLeaveEventPlugin.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import EventPropagators from 'events/EventPropagators'; <ide> <ide> import SyntheticMouseEvent from './SyntheticMouseEvent'; <ide><path>packages/react-dom/src/events/FallbackCompositionState.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import getTextContentAccessor from '../client/getTextContentAccessor'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/ReactBrowserEventEmitter.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import EventPluginRegistry from 'events/EventPluginRegistry'; <ide> import ReactEventEmitterMixin from 'events/ReactEventEmitterMixin'; <ide> <ide><path>packages/react-dom/src/events/ReactDOMEventListener.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import ReactGenericBatching from 'events/ReactGenericBatching'; <ide> import {isFiberMounted} from 'shared/ReactFiberTreeReflection'; <ide> import {HostRoot} from 'shared/ReactTypeOfWork'; <ide><path>packages/react-dom/src/events/SelectEventPlugin.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import EventPropagators from 'events/EventPropagators'; <ide> import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'; <ide> import SyntheticEvent from 'events/SyntheticEvent'; <ide><path>packages/react-dom/src/events/SimpleEventPlugin.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {TopLevelTypes} from './BrowserEventConstants'; <ide> import type { <ide> DispatchConfig, <ide><path>packages/react-dom/src/events/SyntheticAnimationEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticEvent from 'events/SyntheticEvent'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/SyntheticClipboardEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticEvent from 'events/SyntheticEvent'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/SyntheticCompositionEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticEvent from 'events/SyntheticEvent'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/SyntheticDragEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticMouseEvent from './SyntheticMouseEvent'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/SyntheticFocusEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticUIEvent from './SyntheticUIEvent'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/SyntheticInputEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticEvent from 'events/SyntheticEvent'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/SyntheticKeyboardEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticUIEvent from './SyntheticUIEvent'; <ide> import getEventCharCode from './getEventCharCode'; <ide> import getEventKey from './getEventKey'; <ide><path>packages/react-dom/src/events/SyntheticMouseEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticUIEvent from './SyntheticUIEvent'; <ide> import getEventModifierState from './getEventModifierState'; <ide> <ide><path>packages/react-dom/src/events/SyntheticTouchEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticUIEvent from './SyntheticUIEvent'; <ide> import getEventModifierState from './getEventModifierState'; <ide> <ide><path>packages/react-dom/src/events/SyntheticTransitionEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticEvent from 'events/SyntheticEvent'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/SyntheticUIEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticEvent from 'events/SyntheticEvent'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/SyntheticWheelEvent.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import SyntheticMouseEvent from './SyntheticMouseEvent'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/TapEventPlugin.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import EventPluginUtils from 'events/EventPluginUtils'; <ide> import EventPropagators from 'events/EventPropagators'; <ide> import TouchEventUtils from 'fbjs/lib/TouchEventUtils'; <ide><path>packages/react-dom/src/events/getEventCharCode.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> /** <ide> * `charCode` represents the actual "character code" and is safe to use with <ide> * `String.fromCharCode`. As such, only keys that correspond to printable <ide><path>packages/react-dom/src/events/getEventKey.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import getEventCharCode from './getEventCharCode'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/getEventModifierState.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> /** <ide> * Translation from modifier key to the associated property in the event. <ide> * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers <ide><path>packages/react-dom/src/events/getEventTarget.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import {TEXT_NODE} from '../shared/HTMLNodeType'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/getVendorPrefixedEventName.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'; <ide> <ide> /** <ide><path>packages/react-dom/src/events/isEventSupported.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'; <ide> <ide> var useHasFeature; <ide><path>packages/react-dom/src/server/DOMMarkupOperations.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import DOMProperty from '../shared/DOMProperty'; <ide> import quoteAttributeValueForBrowser <ide> from '../shared/quoteAttributeValueForBrowser'; <ide><path>packages/react-dom/src/server/ReactDOMNodeStreamRenderer.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import {Readable} from 'stream'; <ide> <ide> import ReactPartialRenderer from './ReactPartialRenderer'; <ide><path>packages/react-dom/src/server/ReactDOMServerBrowser.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import '../shared/ReactDOMInjection'; <ide> import ReactVersion from 'shared/ReactVersion'; <ide> import invariant from 'fbjs/lib/invariant'; <ide><path>packages/react-dom/src/server/ReactDOMServerNode.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import '../shared/ReactDOMInjection'; <ide> import ReactVersion from 'shared/ReactVersion'; <ide> <ide><path>packages/react-dom/src/server/ReactDOMStringRenderer.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import ReactPartialRenderer from './ReactPartialRenderer'; <ide> <ide> /** <ide><path>packages/react-dom/src/server/ReactPartialRenderer.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {ReactElement} from 'shared/ReactElementType'; <ide> <ide> import React from 'react'; <ide><path>packages/react-dom/src/shared/CSSProperty.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> /** <ide> * CSS properties which accept numbers but are not in units of "px". <ide> */ <ide><path>packages/react-dom/src/shared/CSSPropertyOperations.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import dangerousStyleValue from './dangerousStyleValue'; <ide> import hyphenateStyleName from 'fbjs/lib/hyphenateStyleName'; <ide> import warnValidStyle from './warnValidStyle'; <ide><path>packages/react-dom/src/shared/DOMNamespaces.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; <ide> const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; <ide> const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; <ide><path>packages/react-dom/src/shared/DOMProperty.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import invariant from 'fbjs/lib/invariant'; <ide> <ide> // These attributes should be all lowercase to allow for <ide><path>packages/react-dom/src/shared/HTMLDOMPropertyConfig.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import DOMProperty from './DOMProperty'; <ide> <ide> var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; <ide><path>packages/react-dom/src/shared/HTMLNodeType.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> /** <ide> * HTML nodeType values that represent the type of the node <ide> */ <ide><path>packages/react-dom/src/shared/ReactControlledValuePropTypes.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import checkPropTypes from 'prop-types/checkPropTypes'; <ide> <ide> var ReactControlledValuePropTypes = { <ide><path>packages/react-dom/src/shared/ReactDOMInjection.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import DOMProperty from './DOMProperty'; <ide> import HTMLDOMPropertyConfig from './HTMLDOMPropertyConfig'; <ide> import SVGDOMPropertyConfig from './SVGDOMPropertyConfig'; <ide><path>packages/react-dom/src/shared/ReactDOMInvalidARIAHook.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import warning from 'fbjs/lib/warning'; <ide> import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState'; <ide> <ide><path>packages/react-dom/src/shared/ReactDOMNullInputValuePropHook.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState'; <ide> import warning from 'fbjs/lib/warning'; <ide> <ide><path>packages/react-dom/src/shared/ReactDOMUnknownPropertyHook.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import EventPluginRegistry from 'events/EventPluginRegistry'; <ide> import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState'; <ide> import warning from 'fbjs/lib/warning'; <ide><path>packages/react-dom/src/shared/SVGDOMPropertyConfig.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import DOMProperty from './DOMProperty'; <ide> <ide> var {HAS_STRING_BOOLEAN_VALUE} = DOMProperty.injection; <ide><path>packages/react-dom/src/shared/assertValidProps.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import invariant from 'fbjs/lib/invariant'; <ide> import warning from 'fbjs/lib/warning'; <ide> <ide><path>packages/react-dom/src/shared/createMicrosoftUnsafeLocalFunction.js <ide> <ide> /* globals MSApp */ <ide> <del>'use strict'; <del> <ide> /** <ide> * Create a function which has 'unsafe' privileges (required by windows8 apps) <ide> */ <ide><path>packages/react-dom/src/shared/dangerousStyleValue.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import {isUnitlessNumber} from './CSSProperty'; <ide> <ide> /** <ide><path>packages/react-dom/src/shared/escapeTextContentForBrowser.js <ide> * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> */ <ide> <del>'use strict'; <del> <ide> // code copied and modified from escape-html <ide> /** <ide> * Module variables. <ide><path>packages/react-dom/src/shared/isCustomComponent.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> function isCustomComponent(tagName: string, props: Object) { <ide> if (tagName.indexOf('-') === -1) { <ide> return typeof props.is === 'string'; <ide><path>packages/react-dom/src/shared/omittedCloseTags.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> // For HTML, certain tags should omit their close tag. We keep a whitelist for <ide> // those special-case tags. <ide> <ide><path>packages/react-dom/src/shared/quoteAttributeValueForBrowser.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import escapeTextContentForBrowser from './escapeTextContentForBrowser'; <ide> <ide> /** <ide><path>packages/react-dom/src/shared/validAriaProperties.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> var ariaProperties = { <ide> 'aria-current': 0, // state <ide> 'aria-details': 0, <ide><path>packages/react-dom/src/shared/voidElementTags.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import omittedCloseTags from './omittedCloseTags'; <ide> <ide> // For HTML, certain tags cannot have children. This has the same purpose as <ide><path>packages/react-dom/src/shared/warnValidStyle.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import emptyFunction from 'fbjs/lib/emptyFunction'; <ide> import camelizeStyleName from 'fbjs/lib/camelizeStyleName'; <ide> import warning from 'fbjs/lib/warning'; <ide><path>packages/react-dom/src/test-utils/ReactTestUtils.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import React from 'react'; <ide> import ReactDOM from 'react-dom'; <ide> import {findCurrentFiberUsingSlowPath} from 'shared/ReactFiberTreeReflection'; <ide><path>packages/react-native-renderer/src/NativeMethodsMixin.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> import type { <ide> MeasureInWindowOnSuccessCallback, <ide><path>packages/react-native-renderer/src/NativeMethodsMixinUtils.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> /** <ide> * In the future, we should cleanup callbacks by cancelling them instead of <ide><path>packages/react-native-renderer/src/ReactNativeAttributePayload.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> // Modules provided by RN: <ide> import deepDiffer from 'deepDiffer'; <ide><path>packages/react-native-renderer/src/ReactNativeBridgeEventPlugin.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> import type {ReactNativeBaseComponentViewConfig} from './ReactNativeTypes'; <ide> <ide><path>packages/react-native-renderer/src/ReactNativeComponent.js <ide> * @format <ide> */ <ide> <del>'use strict'; <del> <ide> import type { <ide> MeasureInWindowOnSuccessCallback, <ide> MeasureLayoutOnSuccessCallback, <ide><path>packages/react-native-renderer/src/ReactNativeComponentTree.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import invariant from 'fbjs/lib/invariant'; <ide> <ide> var instanceCache = {}; <ide><path>packages/react-native-renderer/src/ReactNativeEventEmitter.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> import EventPluginHub from 'events/EventPluginHub'; <ide> import EventPluginRegistry from 'events/EventPluginRegistry'; <ide><path>packages/react-native-renderer/src/ReactNativeEventPluginOrder.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> var ReactNativeEventPluginOrder = [ <ide> 'ResponderEventPlugin', <ide><path>packages/react-native-renderer/src/ReactNativeFiberErrorDialog.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {CapturedError} from 'react-reconciler/src/ReactFiberScheduler'; <ide> <ide> // Module provided by RN: <ide><path>packages/react-native-renderer/src/ReactNativeFiberHostComponent.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type { <ide> MeasureInWindowOnSuccessCallback, <ide> MeasureLayoutOnSuccessCallback, <ide><path>packages/react-native-renderer/src/ReactNativeFiberInspector.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide> <ide><path>packages/react-native-renderer/src/ReactNativeFiberRenderer.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {ReactNativeBaseComponentViewConfig} from './ReactNativeTypes'; <ide> <ide> import ReactFiberReconciler from 'react-reconciler'; <ide><path>packages/react-native-renderer/src/ReactNativeFrameScheduling.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Deadline} from 'react-reconciler'; <ide> <ide> const hasNativePerformanceNow = <ide><path>packages/react-native-renderer/src/ReactNativeGlobalResponderHandler.js <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <ide> */ <del>'use strict'; <ide> <ide> // Module provided by RN: <ide> import UIManager from 'UIManager'; <ide><path>packages/react-native-renderer/src/ReactNativeInjection.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> /** <ide> * Make sure essential globals are available and are patched correctly. Please don't remove this <ide><path>packages/react-native-renderer/src/ReactNativePropRegistry.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> var objects = {}; <ide> var uniqueID = 1; <ide><path>packages/react-native-renderer/src/ReactNativeRenderer.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {ReactNativeType} from './ReactNativeTypes'; <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <ide> <ide><path>packages/react-native-renderer/src/ReactNativeTagHandles.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> import invariant from 'fbjs/lib/invariant'; <ide> <ide><path>packages/react-native-renderer/src/ReactNativeTypes.js <ide> * @flow <ide> * @providesModule ReactNativeTypes <ide> */ <del>'use strict'; <ide> <ide> export type MeasureOnSuccessCallback = ( <ide> x: number, <ide><path>packages/react-native-renderer/src/ReactNativeViewConfigRegistry.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type { <ide> ReactNativeBaseComponentViewConfig, <ide> ViewConfigGetter, <ide><path>packages/react-native-renderer/src/createReactNativeComponentClass.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {ViewConfigGetter} from './ReactNativeTypes'; <ide> <ide> import {register} from './ReactNativeViewConfigRegistry'; <ide><path>packages/react-native-renderer/src/findNodeHandle.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide> <ide> import * as ReactInstanceMap from 'shared/ReactInstanceMap'; <ide><path>packages/react-native-renderer/src/findNumericNodeHandle.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> import findNodeHandle from './findNodeHandle'; <ide> <ide><path>packages/react-native-renderer/src/takeSnapshot.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> // Module provided by RN: <ide> import UIManager from 'UIManager'; <ide><path>packages/react-noop-renderer/src/ReactNoop.js <ide> * environment. <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide> import type {UpdateQueue} from 'react-reconciler/src/ReactFiberUpdateQueue'; <ide> <ide><path>packages/react-reconciler/src/ReactChildFiber.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {ReactElement} from 'shared/ReactElementType'; <ide> import type {ReactCall, ReactPortal, ReactReturn} from 'shared/ReactTypes'; <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide><path>packages/react-reconciler/src/ReactDebugCurrentFiber.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState'; <ide> import { <ide> getStackAddendumByWorkInProgressFiber, <ide><path>packages/react-reconciler/src/ReactFiber.js <ide> * <ide> */ <ide> <del>'use strict'; <del> <ide> import type {ReactElement, Source} from 'shared/ReactElementType'; <ide> import type { <ide> ReactCall, <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {HostConfig} from 'react-reconciler'; <ide> import type {ReactCall} from 'shared/ReactTypes'; <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide><path>packages/react-reconciler/src/ReactFiberClassComponent.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from './ReactFiber'; <ide> import type {ExpirationTime} from './ReactFiberExpirationTime'; <ide> <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {HostConfig} from 'react-reconciler'; <ide> import type {Fiber} from './ReactFiber'; <ide> <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {HostConfig} from 'react-reconciler'; <ide> import type {ReactCall} from 'shared/ReactTypes'; <ide> import type {Fiber} from './ReactFiber'; <ide><path>packages/react-reconciler/src/ReactFiberContext.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from './ReactFiber'; <ide> import type {StackCursor} from './ReactFiberStack'; <ide> <ide><path>packages/react-reconciler/src/ReactFiberDevToolsHook.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from './ReactFiber'; <ide> import type {FiberRoot} from './ReactFiberRoot'; <ide> <ide><path>packages/react-reconciler/src/ReactFiberErrorLogger.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {CapturedError} from './ReactFiberScheduler'; <ide> <ide> import invariant from 'fbjs/lib/invariant'; <ide><path>packages/react-reconciler/src/ReactFiberExpirationTime.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> // TODO: Use an opaque type once ESLint et al support the syntax <ide> export type ExpirationTime = number; <ide> <ide><path>packages/react-reconciler/src/ReactFiberHostContext.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {HostConfig} from 'react-reconciler'; <ide> import type {Fiber} from './ReactFiber'; <ide> import type {StackCursor} from './ReactFiberStack'; <ide><path>packages/react-reconciler/src/ReactFiberHydrationContext.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {HostConfig} from 'react-reconciler'; <ide> import type {Fiber} from './ReactFiber'; <ide> <ide><path>packages/react-reconciler/src/ReactFiberInstrumentation.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> // This lets us hook into Fiber to debug what it's doing. <ide> // See https://github.com/facebook/react/pull/8033. <ide> // This is not part of the public API, not even for React DevTools. <ide><path>packages/react-reconciler/src/ReactFiberReconciler.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from './ReactFiber'; <ide> import type {FiberRoot} from './ReactFiberRoot'; <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <ide><path>packages/react-reconciler/src/ReactFiberRoot.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from './ReactFiber'; <ide> import type {ExpirationTime} from './ReactFiberExpirationTime'; <ide> <ide><path>packages/react-reconciler/src/ReactFiberScheduler.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {HostConfig, Deadline} from 'react-reconciler'; <ide> import type {Fiber} from './ReactFiber'; <ide> import type {FiberRoot} from './ReactFiberRoot'; <ide><path>packages/react-reconciler/src/ReactFiberStack.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from './ReactFiber'; <ide> <ide> import warning from 'fbjs/lib/warning'; <ide><path>packages/react-reconciler/src/ReactFiberUpdateQueue.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from './ReactFiber'; <ide> import type {ExpirationTime} from './ReactFiberExpirationTime'; <ide> <ide><path>packages/react-reconciler/src/ReactPortal.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {ReactNodeList, ReactPortal} from 'shared/ReactTypes'; <ide> <ide> // The Symbol used to tag the special React types. If there is no native Symbol <ide><path>packages/react-reconciler/src/ReactTypeOfInternalContext.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> export type TypeOfInternalContext = number; <ide> <ide> export const NoContext = 0; <ide><path>packages/react-rt-renderer/index.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> var ReactNativeRT = require('./src/ReactNativeRT'); <ide> <ide> // TODO: decide on the top-level export form. <ide><path>packages/react-rt-renderer/src/ReactNativeRT.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {ReactNativeRTType} from './ReactNativeRTTypes'; <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <ide> <ide><path>packages/react-rt-renderer/src/ReactNativeRTComponentTree.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide> <ide> var instanceCache: {[key: number]: Fiber} = {}; <ide><path>packages/react-rt-renderer/src/ReactNativeRTEventEmitter.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> import ReactGenericBatching from 'events/ReactGenericBatching'; <ide> // Module provided by RN: <ide><path>packages/react-rt-renderer/src/ReactNativeRTFiberInspector.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> import { <ide> findCurrentFiberUsingSlowPath, <ide><path>packages/react-rt-renderer/src/ReactNativeRTFiberRenderer.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import ReactFiberReconciler from 'react-reconciler'; <ide> import emptyObject from 'fbjs/lib/emptyObject'; <ide> import invariant from 'fbjs/lib/invariant'; <ide><path>packages/react-rt-renderer/src/ReactNativeRTTagHandles.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> import invariant from 'fbjs/lib/invariant'; <ide> <ide><path>packages/react-rt-renderer/src/ReactNativeRTTypes.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> /** <ide> * Flat RT renderer bundles are too big for Flow to parse efficiently. <ide><path>packages/react-test-renderer/src/ReactShallowRenderer.js <ide> * <ide> */ <ide> <del>'use strict'; <del> <ide> import React from 'react'; <ide> import describeComponentFrame from 'shared/describeComponentFrame'; <ide> import getComponentName from 'shared/getComponentName'; <ide><path>packages/react-test-renderer/src/ReactTestRenderer.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide> import type {FiberRoot} from 'react-reconciler/src/ReactFiberRoot'; <ide> <ide><path>packages/react/src/React.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import assign from 'object-assign'; <ide> import ReactVersion from 'shared/ReactVersion'; <ide> import ReactFeatureFlags from 'shared/ReactFeatureFlags'; <ide><path>packages/react/src/ReactBaseClasses.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import emptyObject from 'fbjs/lib/emptyObject'; <ide> import invariant from 'fbjs/lib/invariant'; <ide> import lowPriorityWarning from 'shared/lowPriorityWarning'; <ide><path>packages/react/src/ReactChildren.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import emptyFunction from 'fbjs/lib/emptyFunction'; <ide> import invariant from 'fbjs/lib/invariant'; <ide> import warning from 'fbjs/lib/warning'; <ide><path>packages/react/src/ReactDebugCurrentFrame.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> const ReactDebugCurrentFrame = {}; <ide> <ide> if (__DEV__) { <ide><path>packages/react/src/ReactElement.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import warning from 'fbjs/lib/warning'; <ide> <ide> import ReactCurrentOwner from './ReactCurrentOwner'; <ide><path>packages/react/src/ReactElementValidator.js <ide> * that support it. <ide> */ <ide> <del>'use strict'; <del> <ide> import lowPriorityWarning from 'shared/lowPriorityWarning'; <ide> import describeComponentFrame from 'shared/describeComponentFrame'; <ide> import getComponentName from 'shared/getComponentName'; <ide><path>packages/react/src/ReactNoopUpdateQueue.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import warning from 'fbjs/lib/warning'; <ide> <ide> var didWarnStateUpdateForUnmountedComponent = {}; <ide><path>packages/shared/ReactDOMFrameScheduling.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> // This is a built-in polyfill for requestIdleCallback. It works by scheduling <ide> // a requestAnimationFrame, storing the time for the start of the frame, then <ide> // scheduling a postMessage which gets scheduled after paint. Within the <ide><path>packages/shared/ReactElementType.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> export type Source = { <ide> fileName: string, <ide> lineNumber: number, <ide><path>packages/shared/ReactErrorUtils.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import invariant from 'fbjs/lib/invariant'; <ide> <ide> const ReactErrorUtils = { <ide><path>packages/shared/ReactFeatureFlags.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> export type FeatureFlags = {| <ide> enableAsyncSubtreeAPI: boolean, <ide> enableAsyncSchedulingByDefaultInReactDOM: boolean, <ide><path>packages/shared/ReactFiberComponentTreeHook.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide> <ide> import { <ide><path>packages/shared/ReactFiberTreeReflection.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide> <ide> import invariant from 'fbjs/lib/invariant'; <ide><path>packages/shared/ReactGlobalSharedState.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import React from 'react'; <ide> <ide> var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; <ide><path>packages/shared/ReactInstanceMap.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> /** <ide> * `ReactInstanceMap` maintains a mapping from a public facing stateful <ide> * instance (key) and the internal representation (value). This allows public <ide><path>packages/shared/ReactTreeTraversal.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> import {HostComponent} from './ReactTypeOfWork'; <ide> <ide> function getParent(inst) { <ide><path>packages/shared/ReactTypeOfSideEffect.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> export type TypeOfSideEffect = number; <ide> <ide> // Don't change these two values: <ide><path>packages/shared/ReactTypeOfWork.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> export type TypeOfWork = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10; <ide> <ide> export const IndeterminateComponent = 0; // Before we know whether it is functional or class <ide><path>packages/shared/ReactTypes.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> export type ReactNode = <ide> | React$Element<any> <ide> | ReactCall <ide><path>packages/shared/describeComponentFrame.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> export default function( <ide> name: null | string, <ide> source: any, <ide><path>packages/shared/getComponentName.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> import type {Fiber} from 'react-reconciler/src/ReactFiber'; <ide> <ide> function getComponentName(fiber: Fiber): string | null { <ide><path>packages/shared/isTextInputElement.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <ide> /** <ide> * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary <ide> */ <ide><path>packages/shared/lowPriorityWarning.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <ide> /** <ide> * Forked from fbjs/warning: <ide> * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js <ide><path>packages/shared/reactProdInvariant.js <ide> * <ide> * @flow <ide> */ <del>'use strict'; <ide> <ide> /** <ide> * WARNING: DO NOT manually require this module. <ide><path>packages/shared/validateCallback.js <del>/** <del> * Copyright (c) 2013-present, Facebook, Inc. <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> * @flow <del> */ <del> <del>'use strict'; <del> <del>const invariant = require('fbjs/lib/invariant'); <del> <del>function validateCallback(callback: ?Function) { <del> invariant( <del> !callback || typeof callback === 'function', <del> 'Invalid argument passed as callback. Expected a function. Instead ' + <del> 'received: %s', <del> callback, <del> ); <del>} <del> <del>export default validateCallback;
179
Ruby
Ruby
tell user to `brew update' if no .git
c28943de7b99b2298d60b0cbbbc0d5fa72a9777d
<ide><path>Library/Homebrew/cmd/versions.rb <ide> <ide> module Homebrew extend self <ide> def versions <del> raise "Please `brew install git` first" unless system "/usr/bin/which -s git" <add> raise "Please `brew install git' first" unless system "/usr/bin/which -s git" <add> raise "Please `brew update' first" unless (HOMEBREW_REPOSITORY/".git").directory? <ide> <ide> raise FormulaUnspecifiedError if ARGV.named.empty? <ide>
1
Python
Python
remove unused imports
cd466a9a05388434f4a45e04a7a03ba0c3fb70ce
<ide><path>libcloud/container/drivers/kubernetes.py <ide> <ide> from libcloud.compute.types import NodeState <ide> from libcloud.compute.base import Node <del>from libcloud.compute.base import NodeDriver <ide> from libcloud.compute.base import NodeSize <ide> from libcloud.compute.base import NodeImage <del>from libcloud.compute.base import NodeLocation <ide> <ide> from libcloud.utils.misc import to_n_cpus_from_cpu_str <ide> from libcloud.utils.misc import to_memory_str_from_n_bytes
1
Ruby
Ruby
implement exec_query on mysql2 adapter
269cd1b3c55c6ceb69c167ad97c357b56f49cb4b
<ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb <ide> def configure_connection <ide> <ide> # Returns an array of record hashes with the column names as keys and <ide> # column values as values. <del> def select(sql, name = nil) <del> execute(sql, name).each(:as => :hash) <add> def select(sql, name = nil, binds = []) <add> exec_query(sql, name, binds).to_a <add> end <add> <add> def exec_query(sql, name = 'SQL', binds = []) <add> @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone <add> <add> log(sql, name, binds) do <add> begin <add> result = @connection.query(sql) <add> rescue ActiveRecord::StatementInvalid => exception <add> if exception.message.split(":").first =~ /Packets out of order/ <add> raise ActiveRecord::StatementInvalid, "'Packets out of order' error was received from the database. Please update your mysql bindings (gem install mysql) and read http://dev.mysql.com/doc/mysql/en/password-hashing.html for more information. If you're on Windows, use the Instant Rails installer to get the updated mysql bindings." <add> else <add> raise <add> end <add> end <add> <add> ActiveRecord::Result.new(result.fields, result.to_a) <add> end <ide> end <ide> <ide> def supports_views?
1
Python
Python
fix queue import
ae50fa99b0852668c1deabc94876835747e06017
<ide><path>textsum/batch_reader.py <ide> import time <ide> <ide> import numpy as np <del>from six.moves.queue import Queue <add>from six.moves import queue as Queue <ide> from six.moves import xrange <ide> import tensorflow as tf <ide>
1
Text
Text
add a numfocus badge to readme.md
27b960eaac6681893fbcf4220ce348f8a056223a
<ide><path>README.md <ide> <img src="http://www.numpy.org/_static/numpy_logo.png"><br> <ide> </div> <ide> <add>[![Powered by NumFOCUS](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](http://numfocus.org) <add> <ide> ----------------- <ide> | **`Travis CI Status`** | <ide> |-------------------|
1
Python
Python
fix typo in docscrape_sphinx.py import
211154eb336f5314b33e2486fa79953c90be8a11
<ide><path>doc/sphinxext/numpydoc/docscrape_sphinx.py <ide> from __future__ import division, absolute_import, print_function <ide> <del>import re, inspect, textwrap, pydoc, aya <add>import re, inspect, textwrap, pydoc <ide> import sphinx <ide> import collections <ide> from .docscrape import NumpyDocString, FunctionDoc, ClassDoc
1
Javascript
Javascript
add support for buffergeometry
02888c4051d3f2b42c3e3e8334f406064777bf3d
<ide><path>examples/js/exporters/OBJExporter.js <ide> THREE.OBJExporter.prototype = { <ide> var nbNormals = 0; <ide> <ide> var geometry = mesh.geometry; <del> <add> if ( geometry instanceof THREE.BufferGeometry ) { <add> geometry = new THREE.Geometry().fromBufferGeometry(geometry); <add> } <ide> if ( geometry instanceof THREE.Geometry ) { <ide> <ide> output += 'o ' + mesh.name + '\n';
1
Javascript
Javascript
serialize complete texture info (numeric)
612aa17d75ab4a11f8ea0fe130983edfa4e191f3
<ide><path>src/textures/Texture.js <ide> THREE.Texture.prototype = { <ide> type: 'Texture', <ide> generator: 'Texture.toJSON' <ide> }, <add> <ide> uuid: this.uuid, <del> mapping: this.mapping <add> name: this.name, <add> <add> mapping: this.mapping, <add> <add> repeat: [ this.repeat.x, this.repeat.y ], <add> offset: [ this.offset.x, this.offset.y ], <add> wrap: [ this.wrapS, this.wrapT ], <add> <add> minFilter: this.minFilter, <add> magFilter: this.magFilter, <add> anisotropy: this.anisotropy <ide> }; <ide> <ide> if ( this.image !== undefined ) {
1
Go
Go
remove json alteration
e09383bccfcefa3699aa959dedbd8364d505bf9c
<ide><path>registry.go <ide> func NewImgJson(src []byte) (*Image, error) { <ide> func NewMultipleImgJson(src []byte) ([]*Image, error) { <ide> ret := []*Image{} <ide> <del> dec := json.NewDecoder(strings.NewReader(strings.Replace(string(src), "null", "\"\"", -1))) <add> dec := json.NewDecoder(strings.NewReader(string(src))) <ide> for { <ide> m := &Image{} <ide> if err := dec.Decode(m); err == io.EOF {
1
Text
Text
fix word 'sintaxe' to 'syntax' in readme.md
88dbb82d77155d3a8af37b35ef3add6b5fa34855
<ide><path>README.md <ide> These are the available config options for making requests. Only the `url` is re <ide> firstName: 'Fred' <ide> }, <ide> <del> // sintaxe alternative to send data into the body <add> // syntax alternative to send data into the body <ide> // method post <ide> // only the value is sent, not the key <ide> data: 'Country=Brasil&City=Belo Horizonte',
1
Text
Text
expand use of ctc issue tracker
b899140291f6bd6aabc04cb8e1b114b8ee85a5fe
<ide><path>GOVERNANCE.md <ide> The [nodejs/node](https://github.com/nodejs/node) GitHub repository is <ide> maintained by the CTC and additional Collaborators who are added by the <ide> CTC on an ongoing basis. <ide> <del>Individuals making significant and valuable contributions are made <del>Collaborators and given commit-access to the project. These <del>individuals are identified by the CTC and their addition as <del>Collaborators is discussed during the weekly CTC meeting. <add>Individuals identified by the CTC as making significant and valuable <add>contributions are made Collaborators and given commit access to the project. <ide> <ide> _Note:_ If you make a significant contribution and are not considered <del>for commit-access, log an issue or contact a CTC member directly and it <del>will be brought up in the next CTC meeting. <add>for commit access, log an issue or contact a CTC member directly. <ide> <ide> Modifications of the contents of the nodejs/node repository are made on <ide> a collaborative basis. Anybody with a GitHub account may propose a <ide> participate and there is disagreement around a particular <ide> modification. See [Consensus Seeking Process](#consensus-seeking-process) below <ide> for further detail on the consensus model used for governance. <ide> <del>Collaborators may opt to elevate significant or controversial <del>modifications, or modifications that have not found consensus to the <del>CTC for discussion by assigning the ***ctc-agenda*** tag to a pull <del>request or issue. The CTC should serve as the final arbiter where <del>required. <add>Collaborators may opt to elevate significant or controversial modifications to <add>the CTC by assigning the ***ctc-agenda*** tag to a pull request or issue. The <add>CTC should serve as the final arbiter where required. <ide> <ide> For the current list of Collaborators, see the project <ide> [README.md](./README.md#current-project-team-members). <ide> group of Collaborators. <ide> <ide> Any community member or contributor can ask that something be added to <ide> the next meeting's agenda by logging a GitHub issue. Any Collaborator, <del>CTC member or the moderator can add the item to the agenda by adding <add>CTC member, or the moderator can add the item to the agenda by adding <ide> the ***ctc-agenda*** tag to the issue. <ide> <ide> Prior to each CTC meeting, the moderator will share the agenda with <ide> participate in a non-voting capacity. <ide> The moderator is responsible for summarizing the discussion of each agenda item <ide> and sending it as a pull request after the meeting. <ide> <add>Due to the challenges of scheduling a global meeting with participants in <add>several timezones, the CTC will seek to resolve as many agenda items as possible <add>outside of meetings using <add>[the CTC issue tracker](https://github.com/nodejs/CTC/issues). The process in <add>the issue tracker is: <add> <add>* A CTC member opens an issue explaining the proposal/issue and @-mentions <add> @nodejs/ctc. <add>* After 72 hours, if there are two or more `LGTM`s from other CTC members and no <add> explicit opposition from other CTC members, then the proposal is approved. <add>* If there are any CTC members objecting, then a conversation ensues until <add> either the proposal is dropped or the objecting members are persuaded. If <add> there is an extended impasse, a motion for a vote may be made. <add> <ide> ## Consensus Seeking Process <ide> <ide> The CTC follows a
1
Javascript
Javascript
improve array path matching in history
60fc36a96910a1735ebd7abbd8b4ceb6c0feba09
<ide><path>spec/history-manager-spec.js <ide> describe("HistoryManager", () => { <ide> }) <ide> <ide> it("returns null when it can't find the project", () => { <add> debugger <ide> const project = historyManager.getProject(['/1']) <ide> expect(project).toBeNull() <ide> }) <ide><path>src/history-manager.js <ide> export class HistoryManager { <ide> } <ide> <ide> getProject (paths) { <del> const pathsString = paths.toString() <ide> for (var i = 0; i < this.projects.length; i++) { <del> if (this.projects[i].paths.toString() === pathsString) { <add> if (arrayEquivalent(paths, this.projects[i].paths)) { <ide> return this.projects[i] <ide> } <ide> } <ide> export class HistoryManager { <ide> } <ide> } <ide> <add>function arrayEquivalent(a, b) { <add> if (a.length != b.length) return false <add> for (var i=0; i < a.length; i++) { <add> if (a[i] !== b[i]) return false <add> } <add> return true <add>} <add> <ide> export class HistoryProject { <ide> constructor (paths, lastOpened) { <ide> this.paths = paths
2
Ruby
Ruby
convert values to strings in cc setters
7e079fc37db703da48efff9e6d2f3ab3f1178f0c
<ide><path>Library/Homebrew/extend/ENV/shared.rb <ide> def remove keys, value <ide> end <ide> <ide> def cc= val <del> self['CC'] = self['OBJC'] = val <add> self['CC'] = self['OBJC'] = val.to_s <ide> end <ide> <ide> def cxx= val <del> self['CXX'] = self['OBJCXX'] = val <add> self['CXX'] = self['OBJCXX'] = val.to_s <ide> end <ide> <ide> def cc; self['CC']; end
1
Python
Python
remove 415 immediateresponse
3928802178c8361d6d24364a5d0b866d6907c084
<ide><path>djangorestframework/exceptions.py <ide> def __init__(self, detail=None): <ide> <ide> class PermissionDenied(Exception): <ide> status_code = status.HTTP_403_FORBIDDEN <del> default_detail = 'You do not have permission to access this resource.' <add> default_detail = 'You do not have permission to access this resource' <ide> <ide> def __init__(self, detail=None): <ide> self.detail = detail or self.default_detail <ide> <ide> <add>class UnsupportedMediaType(Exception): <add> status_code = 415 <add> default_detail = 'Unsupported media type in request' <add> <add> def __init__(self, detail=None): <add> self.detail = detail or self.default_detail <add> <ide> # class Throttled(Exception): <ide> # def __init__(self, detail): <ide> # self.detail = detail <ide><path>djangorestframework/request.py <ide> <ide> from django.contrib.auth.models import AnonymousUser <ide> <del>from djangorestframework import status <add>from djangorestframework.exceptions import UnsupportedMediaType <ide> from djangorestframework.utils.mediatypes import is_form_media_type <ide> <ide> <ide> __all__ = ('Request',) <ide> <ide> <del>class Empty: <add>class Empty(object): <add> """ <add> Placeholder for unset attributes. <add> Cannot use `None`, as that may be a valid value. <add> """ <ide> pass <ide> <ide> <ide> class Request(object): <ide> <ide> Kwargs: <ide> - request(HttpRequest). The original request instance. <del> - parsers(list/tuple). The parsers to use for parsing the request content. <del> - authentications(list/tuple). The authentications used to try authenticating the request's user. <add> - parsers(list/tuple). The parsers to use for parsing the <add> request content. <add> - authentications(list/tuple). The authentications used to try <add> authenticating the request's user. <ide> """ <ide> <ide> _USE_FORM_OVERLOADING = True <ide> _METHOD_PARAM = '_method' <ide> _CONTENTTYPE_PARAM = '_content_type' <ide> _CONTENT_PARAM = '_content' <ide> <del> def __init__(self, request=None, parsers=None, authentication=None): <add> def __init__(self, request, parsers=None, authentication=None): <ide> self._request = request <ide> self.parsers = parsers or () <ide> self.authentication = authentication or () <ide> def _load_data_and_files(self): <ide> <ide> def _load_method_and_content_type(self): <ide> """ <del> Sets the method and content_type, and then check if they've been overridden. <add> Sets the method and content_type, and then check if they've <add> been overridden. <ide> """ <del> self._content_type = self.META.get('HTTP_CONTENT_TYPE', self.META.get('CONTENT_TYPE', '')) <add> self._content_type = self.META.get('HTTP_CONTENT_TYPE', <add> self.META.get('CONTENT_TYPE', '')) <ide> self._perform_form_overloading() <ide> # if the HTTP method was not overloaded, we take the raw HTTP method <ide> if not _hasattr(self, '_method'): <ide> def _parse(self): <ide> if parser.can_handle_request(self.content_type): <ide> return parser.parse(self.stream, self.META, self.upload_handlers) <ide> <del> self._raise_415_response(self._content_type) <del> <del> def _raise_415_response(self, content_type): <del> """ <del> Raise a 415 response if we cannot parse the given content type. <del> """ <del> from djangorestframework.response import ImmediateResponse <del> <del> raise ImmediateResponse( <del> { <del> 'error': 'Unsupported media type in request \'%s\'.' <del> % content_type <del> }, <del> status=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE) <add> raise UnsupportedMediaType("Unsupported media type in request '%s'" % <add> self._content_type) <ide> <ide> def _authenticate(self): <ide> """
2
Javascript
Javascript
fix lint error
79c66a2f13b39f5663fe0ff4d523a4dc89fa3c5e
<ide><path>src/core/BufferGeometry.js <ide> BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy <ide> <ide> addAttribute: function ( name, attribute ) { <ide> <del> if ( ! (attribute && (attribute.isBufferAttribute || attribute.isInterleavedBufferAttribute || attribute.isGLBufferAttribute) ) ) { <add> if ( ! ( attribute && ( attribute.isBufferAttribute || attribute.isInterleavedBufferAttribute || attribute.isGLBufferAttribute ) ) ) { <ide> <ide> console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); <ide>
1
Go
Go
add more names
ed55a2db06c7343f00a71844b166da1bbfbb812d
<ide><path>pkg/namesgenerator/names-generator.go <ide> import ( <ide> ) <ide> <ide> var ( <del> left = [...]string{"happy", "jolly", "dreamy", "sad", "angry", "pensive", "focused", "sleepy", "grave", "distracted", "determined", "stoic", "stupefied", "sharp", "agitated", "cocky", "tender", "goofy", "furious", "desperate", "hopeful", "compassionate", "silly", "lonely", "condescending", "naughty", "kickass", "drunk", "boring", "nostalgic", "ecstatic", "insane", "cranky", "mad", "jovial", "sick", "hungry", "thirsty", "elegant", "backstabbing", "clever", "trusting", "loving", "suspicious", "berserk", "high", "romantic", "prickly", "evil"} <add> left = [...]string{"happy", "jolly", "dreamy", "sad", "angry", "pensive", "focused", "sleepy", "grave", "distracted", "determined", "stoic", "stupefied", "sharp", "agitated", "cocky", "tender", "goofy", "furious", "desperate", "hopeful", "compassionate", "silly", "lonely", "condescending", "naughty", "kickass", "drunk", "boring", "nostalgic", "ecstatic", "insane", "cranky", "mad", "jovial", "sick", "hungry", "thirsty", "elegant", "backstabbing", "clever", "trusting", "loving", "suspicious", "berserk", "high", "romantic", "prickly", "evil", "admiring", "adoring", "reverent", "serene", "fervent", "modest", "gloomy", "elated"} <ide> // Docker 0.7.x generates names from notable scientists and hackers. <ide> // <ide> // Ada Lovelace invented the first algorithm. http://en.wikipedia.org/wiki/Ada_Lovelace (thanks James Turnbull) <ide> var ( <ide> // Charles Babbage invented the concept of a programmable computer. http://en.wikipedia.org/wiki/Charles_Babbage. <ide> // Charles Darwin established the principles of natural evolution. http://en.wikipedia.org/wiki/Charles_Darwin. <ide> // Dennis Ritchie and Ken Thompson created UNIX and the C programming language. http://en.wikipedia.org/wiki/Dennis_Ritchie http://en.wikipedia.org/wiki/Ken_Thompson <add> // Dorothy Hodgkin was a British biochemist, credited with the development of protein crystallography. She was awarded the Nobel Prize in Chemistry in 1964. http://en.wikipedia.org/wiki/Dorothy_Hodgkin <ide> // Douglas Engelbart gave the mother of all demos: http://en.wikipedia.org/wiki/Douglas_Engelbart <ide> // Elizabeth Blackwell - American doctor and first American woman to receive a medical degree - http://en.wikipedia.org/wiki/Elizabeth_Blackwell <ide> // Emmett Brown invented time travel. http://en.wikipedia.org/wiki/Emmett_Brown (thanks Brian Goff) <ide> var ( <ide> // Françoise Barré-Sinoussi - French virologist and Nobel Prize Laureate in Physiology or Medicine; her work was fundamental in identifying HIV as the cause of AIDS. http://en.wikipedia.org/wiki/Fran%C3%A7oise_Barr%C3%A9-Sinoussi <ide> // Galileo was a founding father of modern astronomy, and faced politics and obscurantism to establish scientific truth. http://en.wikipedia.org/wiki/Galileo_Galilei <ide> // Gertrude Elion - American biochemist, pharmacologist and the 1988 recipient of the Nobel Prize in Medicine - http://en.wikipedia.org/wiki/Gertrude_Elion <add> // Gerty Theresa Cori - American biochemist who became the third woman—and first American woman—to win a Nobel Prize in science, and the first woman to be awarded the Nobel Prize in Physiology or Medicine. Cori was born in Prague. http://en.wikipedia.org/wiki/Gerty_Cori <ide> // Grace Hopper developed the first compiler for a computer programming language and is credited with popularizing the term "debugging" for fixing computer glitches. http://en.wikipedia.org/wiki/Grace_Hopper <ide> // Henry Poincare made fundamental contributions in several fields of mathematics. http://en.wikipedia.org/wiki/Henri_Poincar%C3%A9 <ide> // Hypatia - Greek Alexandrine Neoplatonist philosopher in Egypt who was one of the earliest mothers of mathematics - http://en.wikipedia.org/wiki/Hypatia <ide> var ( <ide> // Richard Matthew Stallman - the founder of the Free Software movement, the GNU project, the Free Software Foundation, and the League for Programming Freedom. He also invented the concept of copyleft to protect the ideals of this movement, and enshrined this concept in the widely-used GPL (General Public License) for software. http://en.wikiquote.org/wiki/Richard_Stallman <ide> // Rob Pike was a key contributor to Unix, Plan 9, the X graphic system, utf-8, and the Go programming language. http://en.wikipedia.org/wiki/Rob_Pike <ide> // Rosalind Franklin - British biophysicist and X-ray crystallographer whose research was critical to the understanding of DNA - http://en.wikipedia.org/wiki/Rosalind_Franklin <add> // Rosalyn Sussman Yalow - Rosalyn Sussman Yalow was an American medical physicist, and a co-winner of the 1977 Nobel Prize in Physiology or Medicine for development of the radioimmunoassay technique. http://en.wikipedia.org/wiki/Rosalyn_Sussman_Yalow <ide> // Sophie Kowalevski - Russian mathematician responsible for important original contributions to analysis, differential equations and mechanics - http://en.wikipedia.org/wiki/Sofia_Kovalevskaya <ide> // Sophie Wilson designed the first Acorn Micro-Computer and the instruction set for ARM processors. http://en.wikipedia.org/wiki/Sophie_Wilson <ide> // Stephen Hawking pioneered the field of cosmology by combining general relativity and quantum mechanics. http://en.wikipedia.org/wiki/Stephen_Hawking <ide> var ( <ide> // http://en.wikipedia.org/wiki/John_Bardeen <ide> // http://en.wikipedia.org/wiki/Walter_Houser_Brattain <ide> // http://en.wikipedia.org/wiki/William_Shockley <del> right = [...]string{"albattani", "almeida", "archimedes", "ardinghelli", "babbage", "bardeen", "bartik", "bell", "blackwell", "bohr", "brattain", "brown", "carson", "colden", "curie", "darwin", "davinci", "einstein", "elion", "engelbart", "euclid", "fermat", "fermi", "feynman", "franklin", "galileo", "goldstine", "goodall", "hawking", "heisenberg", "hoover", "hopper", "hypatia", "jones", "kirch", "kowalevski", "lalande", "leakey", "lovelace", "lumiere", "mayer", "mccarthy", "mcclintock", "mclean", "meitner", "mestorf", "morse", "newton", "nobel", "pare", "pasteur", "perlman", "pike", "poincare", "ptolemy", "ritchie", "rosalind", "sammet", "shockley", "sinoussi", "stallman", "tesla", "thompson", "torvalds", "turing", "wilson", "wozniak", "wright", "yonath"} <add> right = [...]string{"albattani", "almeida", "archimedes", "ardinghelli", "babbage", "bardeen", "bartik", "bell", "blackwell", "bohr", "brattain", "brown", "carson", "colden", "cori", "curie", "darwin", "davinci", "einstein", "elion", "engelbart", "euclid", "fermat", "fermi", "feynman", "franklin", "galileo", "goldstine", "goodall", "hawking", "heisenberg", "hodgkin", "hoover", "hopper", "hypatia", "jones", "kirch", "kowalevski", "lalande", "leakey", "lovelace", "lumiere", "mayer", "mccarthy", "mcclintock", "mclean", "meitner", "mestorf", "morse", "newton", "nobel", "pare", "pasteur", "perlman", "pike", "poincare", "ptolemy", "ritchie", "rosalind", "sammet", "shockley", "sinoussi", "stallman", "tesla", "thompson", "torvalds", "turing", "wilson", "wozniak", "wright", "yalow", "yonath"} <ide> ) <ide> <ide> func GetRandomName(retry int) string {
1
Ruby
Ruby
add tests around opt links
c0baad7e68940c9783dcfe04b87918ef4029e24b
<ide><path>Library/Homebrew/test/test_keg.rb <ide> def test_unlink_ignores_DS_Store_when_pruning_empty_dirs <ide> refute_predicate HOMEBREW_PREFIX/"lib/foo", :directory? <ide> refute_predicate HOMEBREW_PREFIX/"lib/foo/.DS_Store", :exist? <ide> end <add> <add> def test_existing_opt_link <add> @keg.opt_record.make_relative_symlink Pathname.new(@keg) <add> @keg.optlink <add> assert_predicate @keg.opt_record, :symlink? <add> end <add> <add> def test_existing_opt_link_directory <add> @keg.opt_record.mkpath <add> @keg.optlink <add> assert_predicate @keg.opt_record, :symlink? <add> end <add> <add> def test_existing_opt_link_file <add> @keg.opt_record.parent.mkpath <add> @keg.opt_record.write("foo") <add> @keg.optlink <add> assert_predicate @keg.opt_record, :symlink? <add> end <ide> end
1
Ruby
Ruby
fix whitespace errors
d0d4ef6e8be08ab4f6a7faa2b3a5ef8423a99350
<ide><path>activerecord/lib/active_record/transactions.rb <ide> def with_transaction_returning_status <ide> begin <ide> status = yield <ide> rescue ActiveRecord::Rollback <del> if defined?(@_start_transaction_state) <add> if defined?(@_start_transaction_state) <ide> @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1 <ide> end <ide> status = nil <ide> end <del> <add> <ide> raise ActiveRecord::Rollback unless status <ide> end <ide> status
1
Ruby
Ruby
use new selectmanager#projections= method
cc206a3507699e2c94b2d62ec5226fd20d5d98b3
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> def sanitize_limit(limit) <ide> # on mysql (even when aliasing the tables), but mysql allows using JOIN directly in <ide> # an UPDATE statement, so in the mysql adapters we redefine this to do that. <ide> def join_to_update(update, select) #:nodoc: <del> subselect = select.ast.clone <del> subselect.cores.last.projections = [update.key] <add> subselect = select.clone <add> subselect.projections = [update.key] <ide> <ide> update.where update.key.in(subselect) <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb <ide> def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key) <ide> def join_to_update(update, select) #:nodoc: <ide> if select.limit || select.offset || select.orders.any? <ide> subsubselect = select.clone <del> subsubselect.ast.cores.last.projections = [update.key] <add> subsubselect.projections = [update.key] <ide> <ide> subselect = Arel::SelectManager.new(select.engine) <ide> subselect.project Arel.sql(update.key.name) <ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb <ide> def release_savepoint <ide> def join_to_update(update, select) #:nodoc: <ide> if select.limit || select.offset || select.orders.any? <ide> subsubselect = select.clone <del> subsubselect.ast.cores.last.projections = [update.key] <add> subsubselect.projections = [update.key] <ide> <ide> subselect = Arel::SelectManager.new(select.engine) <ide> subselect.project Arel.sql(update.key.name)
3
Python
Python
fix marian slow test
8af1970e45dc86688b70e1f3fa76d6cc5eca94e9
<ide><path>tests/test_modeling_marian.py <ide> convert_hf_name_to_opus_name, <ide> convert_opus_name_to_hf_name, <ide> ) <add> from transformers.modeling_bart import shift_tokens_right <ide> from transformers.pipelines import TranslationPipeline <ide> <ide> <ide> def test_forward(self): <ide> expected_ids = [38, 121, 14, 697, 38848, 0] <ide> <ide> model_inputs: dict = self.tokenizer.prepare_seq2seq_batch(src, tgt_texts=tgt).to(torch_device) <add> <ide> self.assertListEqual(expected_ids, model_inputs.input_ids[0].tolist()) <ide> <ide> desired_keys = { <ide> "input_ids", <ide> "attention_mask", <del> "decoder_input_ids", <del> "decoder_attention_mask", <add> "labels", <ide> } <ide> self.assertSetEqual(desired_keys, set(model_inputs.keys())) <add> model_inputs["decoder_input_ids"] = shift_tokens_right(model_inputs.labels, self.tokenizer.pad_token_id) <add> model_inputs["return_dict"] = True <add> model_inputs["use_cache"] = False <ide> with torch.no_grad(): <del> logits, *enc_features = self.model(**model_inputs) <del> max_indices = logits.argmax(-1) <add> outputs = self.model(**model_inputs) <add> max_indices = outputs.logits.argmax(-1) <ide> self.tokenizer.batch_decode(max_indices) <ide> <ide> def test_unk_support(self):
1
Javascript
Javascript
remove implicit setting of dns hints
b85a50b6da5bbd7e9c8902a13dfbe1a142fd786a
<ide><path>lib/net.js <ide> function lookupAndConnect(self, options) { <ide> hints: options.hints || 0 <ide> }; <ide> <del> if (dnsopts.family !== 4 && dnsopts.family !== 6 && dnsopts.hints === 0) { <del> dnsopts.hints = dns.ADDRCONFIG; <del> // The AI_V4MAPPED hint is not supported on FreeBSD or Android, <del> // and getaddrinfo returns EAI_BADFLAGS. However, it seems to be <del> // supported on most other systems. See <del> // http://lists.freebsd.org/pipermail/freebsd-bugs/2008-February/028260.html <del> // for more information on the lack of support for FreeBSD. <del> if (process.platform !== 'freebsd' && process.platform !== 'android') <del> dnsopts.hints |= dns.V4MAPPED; <del> } <del> <ide> debug('connect: find host ' + host); <ide> debug('connect: dns options', dnsopts); <ide> self._host = host;
1
PHP
PHP
fix misleading docblocks
fefb64ec0de7bf49fb416ac4b022cc7ff901fdd9
<ide><path>src/Illuminate/Collections/EnumeratesValues.php <ide> public function where($key, $operator = null, $value = null) <ide> } <ide> <ide> /** <del> * Filter items where the given key is not null. <add> * Filter items where the value for the given key is null. <ide> * <ide> * @param string|null $key <ide> * @return static <ide> public function whereNull($key = null) <ide> } <ide> <ide> /** <del> * Filter items where the given key is null. <add> * Filter items where the value for the given key is not null. <ide> * <ide> * @param string|null $key <ide> * @return static
1
Text
Text
add translation kr/threejs-shadertoy.md
93c3d48e2587eca9a3987a334c65719808a05daf
<ide><path>threejs/lessons/kr/threejs-shadertoy.md <add>Title: 쉐이더토이(Shadertoy) 활용하기 <add>Description: Three.js에서 쉐이더토이의 쉐이더를 사용하는 법을 알아봅니다 <add>TOC: 쉐이더토이 쉐이더 활용하기 <add> <add>[쉐이더토이(Shadertoy)](https://shadertoy.com)는 다양한 쉐이더를 제공하는 유명한 사이트입니다. 시리즈를 진행하다보니 쉐이더토이에서 받은 쉐이더를 Three.js에 적용하는 법을 물어보시는 분들이 꽤 있더군요. <add> <add>하지만 쉐이더**토이**라고 불리는 데는 이유가 있습니다. 쉐이더토이에 올라온 쉐이더는 정석대로 만들어진 쉐이더가 아닙니다. [드위터(dwitter)](https://dwitter.net)(140자 내로 코드를 작성하는 사이트)나 [js13kGames](https://js13kgames.com)(13kb 이하의 게임을 만드는 사이트)처럼 여러 사람이 쉐이더-챌린지를 진행하는 곳이죠. <add> <add>쉐이더토이의 미션은 *주어진 픽셀 위치값으로 무언가 재밌는 것을 렌더링하는 함수를 만드는 것*입니다. 재밌는 미션이고 많은 결과물을 보면 대단하다는 소리가 절로 나옵니다. 하지만 초보자가 보고 배우기에 좋은 예제들은 아니죠. <add> <add>아래의 [쉐이더로 도시 전체를 렌더링한 쉐이더토이 예제](https://www.shadertoy.com/view/XtsSWs)를 한 번 봅시다. <add> <add><div class="threejs_center"><img src="resources/images/shadertoy-skyline.png"></div> <add> <add>제 컴퓨터에서 FHD 해상도를 기준으로 약 5 프레임 내외가 나옵니다. 이를 [시티즈: 스카이라인(Cities: Skylines)](https://store.steampowered.com/app/255710/Cities_Skylines/) 같은 게임과 비교해보면 <add> <add><div class="threejs_center"><img src="resources/images/cities-skylines.jpg" style="width: 600px;"></div> <add> <add>같은 컴퓨터에서 30-60 프레임이 나옵니다. 이 게임이 텍스처를 입힌 삼각형을 렌더링하는 등 좀 더 일반적인 기법을 사용했기 때문이죠. <add> <add>뭐 그렇다고 해도 쉐이더토이의 쉐이더를 Three.js에 한 번 불러와보는 건 나쁘지 않을 겁니다. <add> <add>아래는 쉐이더토이에서 ["New"를 클릭했을 때](https://www.shadertoy.com/new) 나오는 기본 쉐이더입니다(2019년 1월 기준). <add> <add>```glsl <add>// By iq: https://www.shadertoy.com/user/iq <add>// license: Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. <add>void mainImage( out vec4 fragColor, in vec2 fragCoord ) <add>{ <add> // Normalized pixel coordinates (from 0 to 1) <add> vec2 uv = fragCoord/iResolution.xy; <add> <add> // Time varying pixel color <add> vec3 col = 0.5 + 0.5*cos(iTime+uv.xyx+vec3(0,2,4)); <add> <add> // Output to screen <add> fragColor = vec4(col,1.0); <add>} <add>``` <add> <add>여기서 중요한 건 쉐이더는 GLSL(Graphic Library Shading Language)로 작성한다는 겁니다. GLSL은 3D 수학을 위해 C 언어 기반으로 고안된 상위 언어로, GLSL만의 고유한 타입이 있습니다. 위 코드의 `vec4`, `vec2`, `vec3`이 그런 고유 타입들이죠. `vec2`는 값이 2개, `vec3`는 3개, `vec4`는 4개인데, 이들은 각각 다양한 값으로 사용되지만 `x`, `y`, `z` 그리고 `w`로 사용하는 게 보통입니다. <add> <add>```glsl <add>vec4 v1 = vec4(1.0, 2.0, 3.0, 4.0); <add>float v2 = v1.x + v1.y; // adds 1.0 + 2.0 <add>``` <add> <add>GLSL은 자바스크립트와 달리 C나 C++처럼 변수를 선언할 때 해당 타입을 사용해야 합니다. 예를 들어 실수(float)를 변수에 담을 때 자바스크립트는 `var v = 1.2;`와 같이 쓰지만, GLSL에서는 `float v = 1.2;`와 같이 씁니다. <add> <add>이 글에서 GLSL을 자세히 설명하는 건 주제에 벗어나니 [이 글](https://webglfundamentals.org/webgl/lessons/ko/webgl-shaders-and-glsl.html)을 읽어보거나 [이 시리즈](https://thebookofshaders.com/?lan=kr)를 정주행해보기 바랍니다. <add> <add>또한 2019년 1월 기준으로 [쉐이더토이](https://shadertoy.com)는 *fragment shaders*만 지원합니다. fragment shader는 아까 말한 미션처럼 픽셀의 좌표를 받아 해당 픽셀에 특정 색을 지정하는 역할을 하죠. <add> <add>위 코드를 보면 `mainImage` 함수에 `fragColor`라는 이름의 `out` 매개변수가 보일 겁니다. `out`은 `output`의 줄임말로, 바로 이 매개변수가 색상값을 지정할 변수 합니다. <add> <add>`fragCoord`, `in`(`input`의 줄임말) 매개변수는 `out`의 색상값을 사용할 픽셀의 좌표입니다. 이 픽셀 좌표로 새로운 색상값을 만들 수 있죠. 만약 400x300짜리 캔버스에 이 쉐이더를 적용한다면 이 함수는 400x300번, 그러니까 총 120,000번 호출되는 셈입니다. <add> <add>코드에 선언부가 없긴 하지만 사용할 수 있는 변수가 2개 더 있습니다. 하나는 캔버스의 해상도를 설정하는 `iResolution`으로, 캔버스를 400x300으로 만들려면 `iResolution`을 `400, 300`으로 설정해야 합니다. 그리고 `iResolution`에 의해 픽셀 좌표가 바뀌면 `uv` 변수는 텍스처 크기의 0.0에서 1.0만큼 위, 옆으로 갑니다. 이렇듯 어떤 값을 *정규화(normalize)*하는 것이 작업을 간단히 하는 데 도움이 되기에 쉐이더토이의 주 함수는 대개 저런 식으로 시작합니다. <add> <add>다른 하나는 `iTime`으로, 이는 페이지가 로드된 이후의 초 단위 시간값입니다. <add> <add>쉐이더의 세계에서 이 전역 변수들은 *균등(uniform)* 변수라고 불립니다. *균등*이라고 불리는 이유는 쉐이더 한 루프 안에서는 전혀 변하지 않는 변수이기 때문이죠. 다만 위에서 언급한 변수들은 GLSL의 *표준* 변수가 아니라 쉐이더토이에서 자체적으로 제공하는 변수입니다. <add> <add>[쉐이더토이 공식 문서에는 몇 가지 변수를 더 언급](https://www.shadertoy.com/howto)해 놓았지만, 일단은 위 두 변수를 활용해 예제를 하나 만들어보겠습니다. <add> <add>먼저 캔버스 전체를 채울 평면을 하나 만듭니다. [배경과 하늘상자 추가하기](threejs-backgrounds.html)에서 정육면체를 뺀 예제를 가져오겠습니다. 코드가 길지 않으니 아래에 전부 적도록 하죠. <add> <add>```js <add>function main() { <add> const canvas = document.querySelector('#c'); <add> const renderer = new THREE.WebGLRenderer({ canvas }); <add> renderer.autoClearColor = false; <add> <add> const camera = new THREE.OrthographicCamera( <add> -1, // left <add> 1, // right <add> 1, // top <add> -1, // bottom <add> -1, // near, <add> 1, // far <add> ); <add> const scene = new THREE.Scene(); <add> const plane = new THREE.PlaneBufferGeometry(2, 2); <add> const material = new THREE.MeshBasicMaterial({ <add> color: 'red', <add> }); <add> scene.add(new THREE.Mesh(plane, material)); <add> <add> function resizeRendererToDisplaySize(renderer) { <add> const canvas = renderer.domElement; <add> const width = canvas.clientWidth; <add> const height = canvas.clientHeight; <add> const needResize = canvas.width !== width || canvas.height !== height; <add> if (needResize) { <add> renderer.setSize(width, height, false); <add> } <add> return needResize; <add> } <add> <add> function render() { <add> resizeRendererToDisplaySize(renderer); <add> <add> renderer.render(scene, camera); <add> <add> requestAnimationFrame(render); <add> } <add> <add> requestAnimationFrame(render); <add>} <add> <add>main(); <add>``` <add> <add>[배경과 하늘상자 추가하기](threejs-backgrounds.html)에서도 설명했지만 위와 같이 `OrthographicCamera`를 설정하면 2칸짜리 평면이 캔버스 전체를 채우게 됩니다. 당장은 평면이 빨간 `MeshBasicMaterial`을 사용했기에 캔버스 전체가 빨갛게 보입니다. <add> <add>{{{example url="../threejs-shadertoy-prep.html" }}} <add> <add>이제 쉐이더토이에서 쉐이더를 가져와 적용해봅시다. <add> <add>```js <add>const fragmentShader = ` <add>#include <common> <add> <add>uniform vec3 iResolution; <add>uniform float iTime; <add> <add>// By iq: https://www.shadertoy.com/user/iq <add>// license: Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. <add>void mainImage( out vec4 fragColor, in vec2 fragCoord ) <add>{ <add> // Normalized pixel coordinates (from 0 to 1) <add> vec2 uv = fragCoord/iResolution.xy; <add> <add> // Time varying pixel color <add> vec3 col = 0.5 + 0.5*cos(iTime+uv.xyx+vec3(0,2,4)); <add> <add> // Output to screen <add> fragColor = vec4(col,1.0); <add>} <add> <add>void main() { <add> mainImage(gl_FragColor, gl_FragCoord.xy); <add>} <add>`; <add>``` <add> <add>위 코드에서는 아까 설명했던 균등 변수 2개를 선언했습니다. 그런 다음 쉐이더토이에서 만든 GLSL 코드를 복사해 넣었죠. 그리고 하단에서 `mainImage`에 `gl_FragColor`와 `gl_FragCoord.xy`를 넘겨 호출했습니다. 여기서 사용한 `gl_FragColor`는 WebGL의 공식 전역 변수로, 쉐이더는 여기에 해당 픽셀의 색상값을 지정해야 합니다. `gl_FragCoord` 또한 WebGL 공식 전역 변수로, 현재 색상을 적용해야 하는 픽셀의 좌표값을 나타내죠. <add> <add>다음으로 쉐이더에 데이터를 전달할 전달해야 하니 Three.js 균등 변수를 생성합니다. <add> <add>```js <add>const uniforms = { <add> iTime: { value: 0 }, <add> iResolution: { value: new THREE.Vector3() }, <add>}; <add>``` <add> <add>Three.js의 균등 변수에는 `value` 속성을 넣어야 합니다. 물론 값으로 들어가는 데이터도 균등 변수의 타입과 맞아야 하죠. <add> <add>fragment 쉐이더와 균등 변수를 `ShaderMaterial`에 넘겨줍니다. <add> <add>```js <add>-const material = new THREE.MeshBasicMaterial({ <add>- color: 'red', <add>-}); <add>+const material = new THREE.ShaderMaterial({ <add>+ fragmentShader, <add>+ uniforms, <add>+}); <add>``` <add> <add>또한 매 프레임마다 균등 변수의 값을 변경하도록 합니다. <add> <add>```js <add>-function render() { <add>+function render(time) { <add>+ time *= 0.001; // 초 단위로 변환 <add> <add> resizeRendererToDisplaySize(renderer); <add> <add>+ const canvas = renderer.domElement; <add>+ uniforms.iResolution.value.set(canvas.width, canvas.height, 1); <add>+ uniforms.iTime.value = time; <add> <add> renderer.render(scene, camera); <add> <add> requestAnimationFrame(render); <add>} <add>``` <add> <add>> 참고: [쉐이더토이 공식 문서](https://www.shadertoy.com/howto)를 뒤져봤지만 `iResolution`가 왜 `vec3`여야 하는지, 3번째 값은 어디에 쓰이는 건지 알아내지 못했습니다. 일단 예제에서는 쓰지 않는 값이니 1로 설정하고 넘어가야겠네요. ¯\\_(ツ)\_/¯ <add> <add>{{{example url="../threejs-shadertoy-basic.html" }}} <add> <add>[쉐이더토이에서 "New"를 클릭했을 때 나왔던 결과](https://www.shadertoy.com/new)와 똑같네요. 물론 2019년 1월 기준으로 말이죠😉. 이 쉐이더는 어떻게 이런 결과를 만들어낸 걸까요? <add> <add>* `uv`가 시간에 따라 서서히 0에서 1로 바뀝니다. <add>* `cos(uv.xyx)`는 입력한 값에 코사인 함수를 적용해 `vec3` 형식으로 반환합니다. 하나는 `uv.x`에, 다른 하나는 `uv.y`에, 마지막은 다시 `uv.x`에 코사인 함수를 실행한 결과값이죠. <add>* 이전에 `cos(iTime+uv.xyx)` 이렇게 시간값을 더해 애니메이션을 구현합니다. <add>* 이전에 `vec3(0,2,4)`를 더해 `cos(iTime+uv.xyx+vec3(0,2,4))`와 같이 하면 코사인 파도가 생깁니다. <add>* `cos`의 결과값은 -1부터 1까지이므로, `0.5 * 0.5 + cos(...)`을 적용하면 -1 <-> 1, 0.0 <-> 1.0 이런 식으로 바뀝니다. <add>* 이 결과값을 현재 픽셀에 대한 RGB 값으로 씁니다. <add> <add>코드를 조금 수정하면 코사인 파도가 더 잘 보일 겁니다. 지금은 `uv`의 값이 0부터 1까지죠. 코사인의 주기는 2π이니 `uv`에 40.0을 곱해 `uv`값이 0부터 40까지 되도록 해보겠습니다. 이러면 화면에 파도가 약 6.3번 반복될 거예요. <add> <add>```glsl <add>-vec3 col = 0.5 + 0.5 * cos(iTime + uv.xyx + vec3(0,2,4)); <add>+vec3 col = 0.5 + 0.5 * cos(iTime + uv.xyx * 40.0 + vec3(0,2,4)); <add>``` <add> <add>아래 예제를 보니 파도가 약 6개 하고 1/3 정도 보입니다. 파란선 사이에 빨간선이 보이는 건 파란색의 위치를 `+ vec3(0,2,4)`로 4만큼 옮겼기 때문이죠. 이렇게 하지 않았다면 빨강과 파랑이 완전히 겹쳐 자주색으로 보였을 겁니다. <add> <add>{{{example url="../threejs-shadertoy-basic-x40.html" }}} <add> <add>주어지는 값이 이렇게 단순한데 이걸로 [도심 운하](https://www.shadertoy.com/view/MdXGW2), [숲](https://www.shadertoy.com/view/4ttSWf), [달팽이](https://www.shadertoy.com/view/ld3Gz2), [버섯](https://www.shadertoy.com/view/4tBXR1) 등을 구현하다니 정말 놀랍네요. 다만 삼각형으로 장면을 구성하는 일반적인 방법에 비해 왜 이 방법이 안 좋은지 분명히 하지 않은 게 아쉽습니다. 한 픽셀 한 픽셀 정성들여 픽셀의 색상을 연산하니 그만큼 한 프레임을 만드는 데 시간이 많이 걸릴 수밖에 없죠. <add> <add>쉐이더토이 쉐이더 중에는 [텍스처를 받아서 사용하는 경우](https://www.shadertoy.com/view/MsXSzM)도 있습니다. <add> <add>```glsl <add>// By Daedelus: https://www.shadertoy.com/user/Daedelus <add>// license: Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. <add>#define TIMESCALE 0.25 <add>#define TILES 8 <add>#define COLOR 0.7, 1.6, 2.8 <add> <add>void mainImage( out vec4 fragColor, in vec2 fragCoord ) <add>{ <add> vec2 uv = fragCoord.xy / iResolution.xy; <add> uv.x *= iResolution.x / iResolution.y; <add> <add> vec4 noise = texture2D(iChannel0, floor(uv * float(TILES)) / float(TILES)); <add> float p = 1.0 - mod(noise.r + noise.g + noise.b + iTime * float(TIMESCALE), 1.0); <add> p = min(max(p * 3.0 - 1.8, 0.1), 2.0); <add> <add> vec2 r = mod(uv * float(TILES), 1.0); <add> r = vec2(pow(r.x - 0.5, 2.0), pow(r.y - 0.5, 2.0)); <add> p *= 1.0 - pow(min(1.0, 12.0 * dot(r, r)), 2.0); <add> <add> fragColor = vec4(COLOR, 1.0) * p; <add>} <add>``` <add> <add>쉐이더에 텍스처를 넘겨주는 건 [재질(material)에 텍스처를 넘겨주는 것](threejs-textures.html)과 비슷하나, 대신 텍스처를 균등 변수에 지정해야 합니다. <add> <add>먼저 쉐이더에 균등 변수를 추가합니다. 텍스처는 GLSL에서 `sampler2D`라고 불립니다. <add> <add>```js <add>const fragmentShader = ` <add>#include <common> <add> <add>uniform vec3 iResolution; <add>uniform float iTime; <add>+uniform sampler2D iChannel0; <add> <add>... <add>``` <add> <add>다음으로 [이 글](threejs-textures.html)에서 했던 것처럼 텍스처를 불러와 균등 변수에 지정합니다. <add> <add>```js <add>+const loader = new THREE.TextureLoader(); <add>+const texture = loader.load('resources/images/bayer.png'); <add>+texture.minFilter = THREE.NearestFilter; <add>+texture.magFilter = THREE.NearestFilter; <add>+texture.wrapS = THREE.RepeatWrapping; <add>+texture.wrapT = THREE.RepeatWrapping; <add>const uniforms = { <add> iTime: { value: 0 }, <add> iResolution: { value: new THREE.Vector3() }, <add>+ iChannel0: { value: texture }, <add>}; <add>``` <add> <add>{{{example url="../threejs-shadertoy-bleepy-blocks.html" }}} <add> <add>여태까지는 [쉐이더토이 사이트](https://shadertoy.com)에 나와있는 대로 캔버스 전체에 쉐이더를 구현했습니다. 하지만 쉐이더를 사용할 때 꼭 예제 형식에 얽매일 필요는 없겠죠. 쉐이더토이의 작가들은 대부분 `fragCoord`와 `iResolution`을 사용한다는 것만 기억하면 됩니다. `fragCoord`가 꼭 픽셀의 좌표여야할 이유는 없다는 말입니다. 이를 텍스처 좌표로 바꿔 쉐이더를 텍스처처럼 사용할 수도 있죠. 이렇게 쉐이더 함수로 텍스처를 만드는 기법을 [*절차적 텍스처(procedural texture)*](https://www.google.com/search?q=procedural+texture)라고 합니다. <add> <add>예제에 이 기법을 적용해봅시다. Three.js에서 텍스처 좌표를 받아 여기에 `iResolution`을 곱해 `fragCoord`에 넘기는 게 제일 간단할 듯하네요. <add> <add>먼저 fragment 쉐이더에서 쓸 *varying*을 추가합니다. varying은 vertex(정점) 쉐이더에서 fragment 쉐이더에 넘겨주는 값으로, 각 정점 사이를 보간한(점진적으로 채운(varied)) 값입니다. Three.js가 텍스처 좌표를 `uv` 앞에 *varying*을 이니셜인 `v`를 붙여 표시하니 그 이름을 그대로 사용하겠습니다. <add> <add>```glsl <add>... <add> <add>+varying vec2 vUv; <add> <add>void main() { <add>- mainImage(gl_FragColor, gl_FragCoord.xy); <add>+ mainImage(gl_FragColor, vUv * iResolution.xy); <add>} <add>``` <add> <add>추가로 vertex 쉐이더를 만들어야 합니다. 아래는 가장 간단한 형태의 Three.js vertex 쉐이더로, `uv`, `projectionMatrix`, `modelViewMatrix`, `position` 등의 변수는 Three.js가 선언해줄 겁니다. <add> <add>```js <add>const vertexShader = ` <add> varying vec2 vUv; <add> void main() { <add> vUv = uv; <add> gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); <add> } <add>`; <add>``` <add> <add>vertex 쉐이더도 같이 `ShaderMaterial`에 넘겨줍니다. <add> <add>```js <add>const material = new THREE.ShaderMaterial({ <add> vertexShader, <add> fragmentShader, <add> uniforms, <add>}); <add>``` <add> <add>텍스처의 크기는 바뀔 일이 없으니 `iResolution` 균등 변수의 초기값을 미리 설정합니다. <add> <add>```js <add>const uniforms = { <add> iTime: { value: 0 }, <add>- iResolution: { value: new THREE.Vector3() }, <add>+ iResolution: { value: new THREE.Vector3(1, 1, 1) }, <add> iChannel0: { value: texture }, <add>}; <add>``` <add> <add>`render` 함수 안에 있던 코드도 삭제합니다. <add> <add>```js <add>-const canvas = renderer.domElement; <add>-uniforms.iResolution.value.set(canvas.width, canvas.height, 1); <add>uniforms.iTime.value = time; <add>``` <add> <add>여기에 [반응형 디자인에 관한 글](threejs-responsive.html)에서 카메라와 회전하는 정육면체 3개를 가져왔습니다. 이제 한 번 실행해보죠. <add> <add>{{{example url="../threejs-shadertoy-as-texture.html" }}} <add> <add>이 글이 Three.js에서 쉐이더토이의 쉐이더를 활용하는 데 도움이 되었으면 합니다. 누차 말하지만 쉐이더토이의 쉐이더는 실제 사용하기 위해 제작되었다기보다-함수 하나로 모든 요소를 만드는-연습용 챌린지에 가깝습니다. 하지만 그래도 쉐이더토이에 올라온 쉐이더들은 여전히 인상 깊고, 놀랍습니다. 배울 점도 굉장히 많죠.
1
PHP
PHP
remove redundant code
f09d7adab905e74858cd53b0f87e4590919a5c0e
<ide><path>src/Utility/Security.php <ide> public static function decrypt(string $cipher, string $key, ?string $hmacSalt = <ide> * @param mixed $original The original value. <ide> * @param mixed $compare The comparison value. <ide> * @return bool <del> * @see https://github.com/resonantcore/php-future/ <ide> * @since 3.6.2 <ide> */ <ide> public static function constantEquals($original, $compare) <ide> { <ide> if (!is_string($original) || !is_string($compare)) { <ide> return false; <ide> } <del> if (function_exists('hash_equals')) { <del> return hash_equals($original, $compare); <del> } <del> $originalLength = mb_strlen($original, '8bit'); <del> $compareLength = mb_strlen($compare, '8bit'); <del> if ($originalLength !== $compareLength) { <del> return false; <del> } <del> $result = 0; <del> for ($i = 0; $i < $originalLength; $i++) { <del> $result |= (ord($original[$i]) ^ ord($compare[$i])); <del> } <ide> <del> return $result === 0; <add> return hash_equals($original, $compare); <ide> } <ide> <ide> /**
1
Mixed
Python
add logger debug for project push and pull
0485cdefcc0d6f2fd81ac2191e36543a2a6d54f1
<ide><path>.github/contributors/nsorros.md <add># spaCy contributor agreement <add> <add>This spaCy Contributor Agreement (**"SCA"**) is based on the <add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf). <add>The SCA applies to any contribution that you make to any product or project <add>managed by us (the **"project"**), and sets out the intellectual property rights <add>you grant to us in the contributed materials. The term **"us"** shall mean <add>[ExplosionAI GmbH](https://explosion.ai/legal). The term <add>**"you"** shall mean the person or entity identified below. <add> <add>If you agree to be bound by these terms, fill in the information requested <add>below and include the filled-in version with your first pull request, under the <add>folder [`.github/contributors/`](/.github/contributors/). The name of the file <add>should be your GitHub username, with the extension `.md`. For example, the user <add>example_user would create the file `.github/contributors/example_user.md`. <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>## Contributor Agreement <add> <add>1. The term "contribution" or "contributed materials" means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, <add>documentation, or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and <add>registrations, in your contribution: <add> <add> * you hereby assign to us joint ownership, and to the extent that such <add> assignment is or becomes invalid, ineffective or unenforceable, you hereby <add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, <add> royalty-free, unrestricted license to exercise all rights under those <add> copyrights. This includes, at our option, the right to sublicense these same <add> rights to third parties through multiple levels of sublicensees or other <add> licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your <add> contribution as if each of us were the sole owners, and if one of us makes <add> a derivative work of your contribution, the one who makes the derivative <add> work (or has it made will be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution <add> against us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and <add> exercise all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the <add> consent of, pay or render an accounting to the other for any use or <add> distribution of your contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, <add>non-exclusive, worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer <add> your contribution in whole or in part, alone or in combination with or <add> included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through <add> multiple levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective <add>on the date you first submitted a contribution to us, even if your submission <add>took place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of <add> authorship and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any <add> third party's copyrights, trademarks, patents, or other intellectual <add> property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and <add> other applicable export and import laws. You agree to notify us if you <add> become aware of any circumstance which would make any of the foregoing <add> representations inaccurate in any respect. We may publicly disclose your <add> participation in the project, including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable <add>U.S. Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add> * [x] I am signing on behalf of myself as an individual and no other person <add> or entity, including my employer, has or will have rights with respect to my <add> contributions. <add> <add> * [ ] I am signing on behalf of my employer or a legal entity and I have the <add> actual authority to contractually bind that entity. <add> <add>## Contributor Details <add> <add>| Field | Entry | <add>|------------------------------- | -------------------- | <add>| Name | Nick Sorros | <add>| Company name (if applicable) | | <add>| Title or role (if applicable) | | <add>| Date | 2/8/2021 | <add>| GitHub username | nsorros | <add>| Website (optional) | | <ide><path>spacy/cli/project/pull.py <ide> from wasabi import msg <ide> from .remote_storage import RemoteStorage <ide> from .remote_storage import get_command_hash <del>from .._util import project_cli, Arg <add>from .._util import project_cli, Arg, logger <ide> from .._util import load_project_config <ide> from .run import update_lockfile <ide> <ide> def project_pull(project_dir: Path, remote: str, *, verbose: bool = False): <ide> # in the list. <ide> while commands: <ide> for i, cmd in enumerate(list(commands)): <add> logger.debug(f"CMD: {cmd['name']}.") <ide> deps = [project_dir / dep for dep in cmd.get("deps", [])] <ide> if all(dep.exists() for dep in deps): <ide> cmd_hash = get_command_hash("", "", deps, cmd["script"]) <ide> for output_path in cmd.get("outputs", []): <ide> url = storage.pull(output_path, command_hash=cmd_hash) <add> logger.debug(f"URL: {url} for {output_path} with command hash {cmd_hash}") <ide> yield url, output_path <ide> <ide> out_locs = [project_dir / out for out in cmd.get("outputs", [])] <ide> def project_pull(project_dir: Path, remote: str, *, verbose: bool = False): <ide> # we iterate over the loop again. <ide> commands.pop(i) <ide> break <add> else: <add> logger.debug(f"Dependency missing. Skipping {cmd['name']} outputs.") <ide> else: <ide> # If we didn't break the for loop, break the while loop. <ide> break <ide><path>spacy/cli/project/push.py <ide> from .remote_storage import RemoteStorage <ide> from .remote_storage import get_content_hash, get_command_hash <ide> from .._util import load_project_config <del>from .._util import project_cli, Arg <add>from .._util import project_cli, Arg, logger <ide> <ide> <ide> @project_cli.command("push") <ide> def project_push(project_dir: Path, remote: str): <ide> remote = config["remotes"][remote] <ide> storage = RemoteStorage(project_dir, remote) <ide> for cmd in config.get("commands", []): <add> logger.debug(f"CMD: cmd['name']") <ide> deps = [project_dir / dep for dep in cmd.get("deps", [])] <ide> if any(not dep.exists() for dep in deps): <add> logger.debug(f"Dependency missing. Skipping {cmd['name']} outputs") <ide> continue <ide> cmd_hash = get_command_hash( <ide> "", "", [project_dir / dep for dep in cmd.get("deps", [])], cmd["script"] <ide> ) <add> logger.debug(f"CMD_HASH: {cmd_hash}") <ide> for output_path in cmd.get("outputs", []): <ide> output_loc = project_dir / output_path <ide> if output_loc.exists() and _is_not_empty_dir(output_loc): <ide> def project_push(project_dir: Path, remote: str): <ide> command_hash=cmd_hash, <ide> content_hash=get_content_hash(output_loc), <ide> ) <add> logger.debug(f"URL: {url} for output {output_path} with cmd_hash {cmd_hash}") <ide> yield output_path, url <ide> <ide>
3
PHP
PHP
return bulider instance on setbindings
be734eca9ba8ec7142c06d2662356e69c12f5257
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function getBindings() <ide> * Set the bindings on the query builder. <ide> * <ide> * @param array $bindings <del> * @return void <add> * @return \Illuminate\Database\Query\Builder <ide> */ <ide> public function setBindings(array $bindings) <ide> { <ide> $this->bindings = $bindings; <add> <add> return $this; <ide> } <ide> <ide> /**
1
Text
Text
update styles for listview in tutorial
bc0ecaddc99378625624164cd624f57366b8ffd6
<ide><path>docs/Tutorial.md <ide> var AwesomeProject = React.createClass({ <ide> <ListView <ide> dataSource={this.state.dataSource} <ide> renderRow={this.renderMovie} <add> style={styles.listView} <ide> /> <ide> ); <ide> },
1
Javascript
Javascript
fix ambiguity in eof handling
31196eaa936e38a1a2bc189f4fcd5f633d814c13
<ide><path>lib/net.js <ide> function onread(nread, buffer) { <ide> <ide> debug('EOF'); <ide> <add> // push a null to signal the end of data. <add> // Do it before `maybeDestroy` for correct order of events: <add> // `end` -> `close` <add> self.push(null); <add> <ide> if (self._readableState.length === 0) { <ide> self.readable = false; <ide> maybeDestroy(self); <ide> } <ide> <del> // push a null to signal the end of data. <del> self.push(null); <del> <ide> // internal end event so that we know that the actual socket <ide> // is no longer readable, and we can start the shutdown <ide> // procedure. No need to wait for all the data to be consumed. <ide><path>test/parallel/test-net-end-close.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add>const net = require('net'); <add> <add>const uv = process.binding('uv'); <add> <add>const s = new net.Socket({ <add> handle: { <add> readStart: function() { <add> process.nextTick(() => this.onread(uv.UV_EOF, null)); <add> }, <add> close: (cb) => process.nextTick(cb) <add> }, <add> writable: false <add>}); <add>s.resume(); <add> <add>const events = []; <add> <add>s.on('end', () => events.push('end')); <add>s.on('close', () => events.push('close')); <add> <add>process.on('exit', () => { <add> assert.deepStrictEqual(events, [ 'end', 'close' ]); <add>});
2
Javascript
Javascript
add simple example of inlined template
b37e8a2b141761d3211b52b8b6802c49c92d44f8
<ide><path>src/widgets.js <ide> var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp <ide> }]; <ide> <ide> <add>/** <add> * @ngdoc widget <add> * @name angular.module.ng.$compileProvider.directive.script <add> * <add> * @description <add> * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the <add> * template can be used by `ng:include` or `ng:view`. <add> * <add> * @example <add> <doc:example> <add> <doc:source> <add> <script type="text/ng-template" id="/tpl.html"> <add> Content of the template. <add> </script> <add> <add> <a ng:click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> <add> <div id="tpl-content" ng-include src="currentTpl"></div> <add> </doc:source> <add> <doc:scenario> <add> it('should load template defined inside script tag', function() { <add> element('#tpl-link').click(); <add> expect(element('#tpl-content').text()).toMatch(/Content of the template/); <add> }); <add> </doc:scenario> <add> </doc:example> <add> */ <ide> var scriptTemplateLoader = ['$templateCache', function($templateCache) { <ide> return { <ide> terminal: true,
1
Javascript
Javascript
use tabs instead of spaces
2dd2e4886b394a85b86da9fbd433706a8af9b7cd
<ide><path>test/unit/manipulation.js <ide> test( "insertAfter, insertBefore, etc do not work when destination is original e <ide> test( "Index for function argument should be received (#13094)", 2, function() { <ide> var i = 0; <ide> <del> jQuery("<div/><div/>").before(function( index ) { <del> equal( index, i++, "Index should be correct" ); <del> }); <add> jQuery("<div/><div/>").before(function( index ) { <add> equal( index, i++, "Index should be correct" ); <add> }); <ide> <ide> }); <ide> <ide> test( "Make sure jQuery.fn.remove can work on elements in documentFragment", 1, function() { <ide> var fragment = document.createDocumentFragment(), <ide> div = fragment.appendChild( document.createElement("div") ); <ide> <del> $( div ).remove(); <add> jQuery( div ).remove(); <ide> <ide> equal( fragment.childNodes.length, 0, "div element was removed from documentFragment" ); <ide> });
1
Python
Python
update error message
0881455a5d9d71a0c2810f6aa05416220d60337d
<ide><path>spacy/errors.py <ide> class Errors: <ide> # TODO: fix numbering after merging develop into master <ide> E941 = ("Can't find model '{name}'. It looks like you're trying to load a " <ide> "model from a shortcut, which is deprecated as of spaCy v3.0. To " <del> "load the model, use its full name instead. For example:\n\n" <add> "load the model, use its full name instead:\n\n" <ide> "nlp = spacy.load(\"{full}\")\n\nFor more details on the available " <del> "models, see the models directory: https://spacy.io/models") <add> "models, see the models directory: https://spacy.io/models. If you " <add> "want to create a blank model, use spacy.blank: " <add> "nlp = spacy.blank(\"{name}\")") <ide> E942 = ("Executing after_{name} callback failed. Expected the function to " <ide> "return an initialized nlp object but got: {value}. Maybe " <ide> "you forgot to return the modified object in your function?")
1
Javascript
Javascript
replace fixturesdir with fixtures
3a265556ece7c23e2d9afdfe492bff2812e43bfb
<ide><path>test/parallel/test-stdin-from-file.js <ide> 'use strict'; <ide> const common = require('../common'); <add>const fixtures = require('../common/fixtures'); <ide> const assert = require('assert'); <del>const join = require('path').join; <add>const { join } = require('path'); <ide> const childProcess = require('child_process'); <ide> const fs = require('fs'); <ide> <del>const stdoutScript = join(common.fixturesDir, 'echo-close-check.js'); <add>const stdoutScript = fixtures.path('echo-close-check.js'); <ide> const tmpFile = join(common.tmpDir, 'stdin.txt'); <ide> <ide> const cmd = `"${process.argv[0]}" "${stdoutScript}" < "${tmpFile}"`;
1
Python
Python
use list to be safe
8c9b5bbf9a5603a4f33b1196e42ea1cc3ab9344e
<ide><path>airflow/utils.py <ide> def import_module_attrs(parent_module_globals, module_attrs_dict): <ide> brings functional operators to those namespaces. <ide> ''' <ide> imported_attrs = [] <del> for mod, attrs in module_attrs_dict.items(): <add> for mod, attrs in list(module_attrs_dict.items()): <ide> try: <ide> folder = os.path.dirname(parent_module_globals['__file__']) <ide> f, filename, description = imp.find_module(mod, [folder])
1