content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
use .code for error in setgid
e57bf473517f12eb169e960aa80ffd5dcd5994d5
<ide><path>test/parallel/test-process-uid-gid.js <ide> const oldgid = process.getgid(); <ide> try { <ide> process.setgid('nobody'); <ide> } catch (err) { <del> if (err.message !== 'setgid group id does not exist') { <add> if (err.code !== 'ERR_UNKNOWN_CREDENTIAL') { <ide> throw err; <ide> } <ide> process.setgid('nogroup');
1
Javascript
Javascript
remove futile optimization
2dd0c2f8feb8eef45e0b077ffa9a648d0c1229c6
<ide><path>src/controllers/controller.bubble.js <ide> module.exports = DatasetController.extend({ <ide> const firstOpts = me._resolveDataElementOptions(start, mode); <ide> const sharedOptions = me._getSharedOptions(mode, points[start], firstOpts); <ide> const includeOptions = me._includeOptions(mode, sharedOptions); <del> let i; <ide> <del> for (i = 0; i < points.length; i++) { <add> for (let i = 0; i < points.length; i++) { <ide> const point = points[i]; <ide> const index = start + i; <ide> const parsed = !reset && me._getParsed(index); <ide> module.exports = DatasetController.extend({ <ide> }; <ide> <ide> if (includeOptions) { <del> properties.options = i === 0 ? firstOpts <del> : me._resolveDataElementOptions(i, mode); <add> properties.options = me._resolveDataElementOptions(i, mode); <ide> <ide> if (reset) { <ide> properties.options.radius = 0; <ide><path>src/controllers/controller.line.js <ide> module.exports = DatasetController.extend({ <ide> const firstOpts = me._resolveDataElementOptions(start, mode); <ide> const sharedOptions = me._getSharedOptions(mode, points[start], firstOpts); <ide> const includeOptions = me._includeOptions(mode, sharedOptions); <del> let i; <ide> <del> for (i = 0; i < points.length; ++i) { <add> for (let i = 0; i < points.length; ++i) { <ide> const index = start + i; <ide> const point = points[i]; <ide> const parsed = me._getParsed(index); <ide> module.exports = DatasetController.extend({ <ide> }; <ide> <ide> if (includeOptions) { <del> properties.options = i === 0 ? firstOpts <del> : me._resolveDataElementOptions(index, mode); <add> properties.options = me._resolveDataElementOptions(index, mode); <ide> } <ide> <ide> me._updateElement(point, index, properties, mode);
2
Ruby
Ruby
remove unnecessary require
f88f699a7b3180e52c2961b9b642f340b2bdae84
<ide><path>activesupport/lib/active_support/core_ext/string/access.rb <del>require 'active_support/multibyte' <del> <ide> class String <ide> # If you pass a single Fixnum, returns a substring of one character at that <ide> # position. The first character of the string is at position 0, the next at <ide><path>activesupport/lib/active_support/core_ext/string/filters.rb <del>require 'active_support/core_ext/string/multibyte' <del> <ide> class String <ide> # Returns the string, first removing all whitespace on both ends of <ide> # the string, and then changing remaining consecutive whitespace <ide><path>activesupport/lib/active_support/inflector/transliterate.rb <ide> # encoding: utf-8 <del>require 'active_support/core_ext/string/multibyte' <add>require 'active_support/multibyte' <ide> require 'active_support/i18n' <ide> <ide> module ActiveSupport
3
PHP
PHP
return null on failure
afe41ade2a30a570f86c81819e3e68fd203f8d47
<ide><path>src/Routing/Middleware/AssetMiddleware.php <ide> protected function isNotModified($request, $file) <ide> * Builds asset file path based off url <ide> * <ide> * @param string $url Asset URL <del> * @return string Absolute path for asset file <add> * @return string|null Absolute path for asset file, null on failure <ide> */ <ide> protected function _getAssetFile($url) <ide> { <ide> protected function _getAssetFile($url) <ide> } <ide> } <ide> <del> return ''; <add> return null; <ide> } <ide> <ide> /**
1
PHP
PHP
fix docs and add missing test coverage
7cb51d7d777ef072bbb953c6e205e9d4cf62e9b6
<ide><path>src/Routing/RouteCollection.php <ide> class RouteCollection { <ide> /** <ide> * Add a route to the collection. <ide> * <add> * @param \Cake\Routing\Route\Route $route The route object to add. <add> * @param array $options Addtional options for the route. Primarily for the <add> * `_name` option, which enables named routes. <ide> */ <del> public function add(Route $route, $options) { <add> public function add(Route $route, $options = []) { <ide> $this->_routes[] = $route; <ide> <ide> // Explicit names <ide><path>tests/TestCase/Routing/RouteCollectionTest.php <ide> public function testNamed() { <ide> } <ide> <ide> /** <del> * Test adding with an error <del> */ <del> public function testAdd() { <del> } <del> <del>/** <del> * Test the routes() method. <add> * Test the add() and routes() method. <ide> * <ide> * @return void <ide> */ <del> public function testRoutes() { <add> public function testAddingRoutes() { <add> $one = new Route('/pages/*', ['controller' => 'Pages', 'action' => 'display']); <add> $two = new Route('/', ['controller' => 'Dashboards', 'action' => 'display']); <add> $this->collection->add($one); <add> $this->collection->add($two); <add> <add> $routes = $this->collection->routes(); <add> $this->assertCount(2, $routes); <add> $this->assertSame($one, $routes[0]); <add> $this->assertSame($two, $routes[1]); <ide> } <ide> <ide> }
2
Text
Text
fix typo in docs
7d085d5b1c7a8efc017e1fc41735b222e776cf13
<ide><path>website/docs/usage/processing-pipelines.md <ide> loss is calculated and to add evaluation scores to the training output. <ide> | [`update`](/api/pipe#update) | Learn from a batch of [`Example`](/api/example) objects containing the predictions and gold-standard annotations, and update the component's model. | <ide> | [`initialize`](/api/pipe#initialize) | Initialize the model. Typically calls into [`Model.initialize`](https://thinc.ai/docs/api-model#initialize) and can be passed custom arguments via the [`[initialize]`](/api/data-formats#config-initialize) config block that are only loaded during training or when you call [`nlp.initialize`](/api/language#initialize), not at runtime. | <ide> | [`get_loss`](/api/pipe#get_loss) | Return a tuple of the loss and the gradient for a batch of [`Example`](/api/example) objects. | <del>| [`score`](/api/pipe#score) | Score a batch of [`Example`](/api/example) objects and return a dictionary of scores. The [`@Language.factory`](/api/language#factory) decorator can define the `default_socre_weights` of the component to decide which keys of the scores to display during training and how they count towards the final score. | <add>| [`score`](/api/pipe#score) | Score a batch of [`Example`](/api/example) objects and return a dictionary of scores. The [`@Language.factory`](/api/language#factory) decorator can define the `default_score_weights` of the component to decide which keys of the scores to display during training and how they count towards the final score. | <ide> <ide> <Infobox title="Custom trainable components and models" emoji="πŸ“–"> <ide>
1
Go
Go
add test coverage to pkg/signal
4b0df45c1a261354f10abb151b9acfa6b61f517d
<ide><path>pkg/signal/signal_linux_test.go <add>// +build darwin linux solaris <add> <add>package signal <add> <add>import ( <add> "os" <add> "syscall" <add> "testing" <add> "time" <add> <add> "github.com/stretchr/testify/assert" <add>) <add> <add>func TestCatchAll(t *testing.T) { <add> sigs := make(chan os.Signal, 1) <add> CatchAll(sigs) <add> defer StopCatch(sigs) <add> <add> listOfSignals := map[string]string{ <add> "CONT": syscall.SIGCONT.String(), <add> "HUP": syscall.SIGHUP.String(), <add> "CHLD": syscall.SIGCHLD.String(), <add> "ILL": syscall.SIGILL.String(), <add> "FPE": syscall.SIGFPE.String(), <add> "CLD": syscall.SIGCLD.String(), <add> } <add> <add> for sigStr := range listOfSignals { <add> signal, ok := SignalMap[sigStr] <add> if ok { <add> go func() { <add> time.Sleep(1 * time.Millisecond) <add> syscall.Kill(syscall.Getpid(), signal) <add> }() <add> <add> s := <-sigs <add> assert.EqualValues(t, s.String(), signal.String()) <add> } <add> <add> } <add>} <add> <add>func TestStopCatch(t *testing.T) { <add> signal, _ := SignalMap["HUP"] <add> channel := make(chan os.Signal, 1) <add> CatchAll(channel) <add> go func() { <add> <add> time.Sleep(1 * time.Millisecond) <add> syscall.Kill(syscall.Getpid(), signal) <add> }() <add> signalString := <-channel <add> assert.EqualValues(t, signalString.String(), signal.String()) <add> <add> StopCatch(channel) <add> _, ok := <-channel <add> assert.EqualValues(t, ok, false) <add>} <ide><path>pkg/signal/signal_test.go <add>package signal <add> <add>import ( <add> "syscall" <add> "testing" <add> <add> "github.com/stretchr/testify/assert" <add>) <add> <add>func TestParseSignal(t *testing.T) { <add> _, checkAtoiError := ParseSignal("0") <add> assert.EqualError(t, checkAtoiError, "Invalid signal: 0") <add> <add> _, error := ParseSignal("SIG") <add> assert.EqualError(t, error, "Invalid signal: SIG") <add> <add> for sigStr := range SignalMap { <add> responseSignal, error := ParseSignal(sigStr) <add> assert.NoError(t, error) <add> signal := SignalMap[sigStr] <add> assert.EqualValues(t, signal, responseSignal) <add> } <add>} <add> <add>func TestValidSignalForPlatform(t *testing.T) { <add> isValidSignal := ValidSignalForPlatform(syscall.Signal(0)) <add> assert.EqualValues(t, false, isValidSignal) <add> <add> for _, sigN := range SignalMap { <add> isValidSignal = ValidSignalForPlatform(syscall.Signal(sigN)) <add> assert.EqualValues(t, true, isValidSignal) <add> } <add>}
2
Javascript
Javascript
modify options to default parameter
9b1d7b5037b788e7e966bbd3dc0f64ac344d184b
<ide><path>lib/Chunk.js <ide> class Chunk { <ide> * @param {Object} options the size display options <ide> * @returns {number} the chunk size <ide> */ <del> size(options) { <add> size(options = {}) { <ide> return this.addMultiplierAndOverhead(this.modulesSize(), options); <ide> } <ide>
1
Javascript
Javascript
fix a typo in server/boot/challenge.js
b575dd112273eddbab530ed08b30ce412b2922e8
<ide><path>server/boot/challenge.js <ide> export default function(app) { <ide> if (!dashedName || !block) { <ide> // this should normally not be hit if database is properly seeded <ide> throw new Error(dedent` <del> Attemped to find '${dashedName}' <add> Attempted to find '${dashedName}' <ide> from '${ challengeId || 'no challenge id found'}' <ide> but came up empty. <ide> db may not be properly seeded.
1
Text
Text
remove obsolete crna information
2b54d70006f385f1d266824cdc4bbce649257634
<ide><path>guide/english/react-native/index.md <ide> It follows the same pattern as React, where the views (what you see on the scree <ide> <ide> There are three quick easy ways to get started with React Native. Depending on your situation, one can be a better option for you. <ide> <del>1. [Expo](https://expo.io) - Best for prototyping apps or useful if an app is in an earlier stage. Using Expo you can even create an quick app using drag and drop features from snack.expo.io in the browser. <del>1. [Ignite CLI](https://github.com/infinitered/ignite) - Empowers developers to easily create a new React Native app with plug ins. Ignite CLI also enables developers to easily setup best practices. <add>1. [Expo](https://expo.io) - Similar to Create React App to get up and running an app using the terminal. Using Expo you do need XCode or Android Studio to build a React Native application. <add>2. [Ignite CLI](https://github.com/infinitered/ignite) - Empowers developers to easily create a new React Native app with plug ins. Ignite CLI also enables developers to easily setup best practices.
1
Javascript
Javascript
use stricter `from()` input validation
75eaf25e78fcb21b338855404b2a6082a4414911
<ide><path>lib/buffer.js <ide> Buffer.from = function from(value, encodingOrOffset, length) { <ide> if (typeof value === 'string') <ide> return fromString(value, encodingOrOffset); <ide> <del> if (isAnyArrayBuffer(value)) <del> return fromArrayBuffer(value, encodingOrOffset, length); <add> if (typeof value === 'object' && value !== null) { <add> if (isAnyArrayBuffer(value)) <add> return fromArrayBuffer(value, encodingOrOffset, length); <ide> <del> if (value === null || value === undefined) { <del> throw new ERR_INVALID_ARG_TYPE( <del> 'first argument', <del> ['string', 'Buffer', 'ArrayBuffer', 'Array', 'Array-like Object'], <del> value <del> ); <del> } <del> <del> if (typeof value === 'number') { <del> throw new ERR_INVALID_ARG_TYPE('value', 'not number', value); <del> } <add> const valueOf = value.valueOf && value.valueOf(); <add> if (valueOf !== null && valueOf !== undefined && valueOf !== value) <add> return Buffer.from(valueOf, encodingOrOffset, length); <ide> <del> const valueOf = value.valueOf && value.valueOf(); <del> if (valueOf !== null && valueOf !== undefined && valueOf !== value) <del> return Buffer.from(valueOf, encodingOrOffset, length); <del> <del> const b = fromObject(value); <del> if (b) <del> return b; <add> const b = fromObject(value); <add> if (b) <add> return b; <ide> <del> if (typeof value[Symbol.toPrimitive] === 'function') { <del> return Buffer.from(value[Symbol.toPrimitive]('string'), <del> encodingOrOffset, <del> length); <add> if (typeof value[Symbol.toPrimitive] === 'function') { <add> return Buffer.from(value[Symbol.toPrimitive]('string'), <add> encodingOrOffset, <add> length); <add> } <ide> } <ide> <ide> throw new ERR_INVALID_ARG_TYPE( <ide><path>test/parallel/test-buffer-bad-overload.js <del>'use strict'; <del>const common = require('../common'); <del>const assert = require('assert'); <del> <del>Buffer.allocUnsafe(10); // Should not throw. <del> <del>const err = common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "value" argument must not be of type number. ' + <del> 'Received type number' <del>}); <del>assert.throws(function() { <del> Buffer.from(10, 'hex'); <del>}, err); <del> <del>Buffer.from('deadbeaf', 'hex'); // Should not throw. <ide><path>test/parallel/test-buffer-from.js <ide> 'use strict'; <ide> <del>const common = require('../common'); <add>require('../common'); <ide> const { deepStrictEqual, throws } = require('assert'); <ide> const { runInNewContext } = require('vm'); <ide> <ide> deepStrictEqual( <ide> [{ valueOf() { return null; } }, 'object'], <ide> [{ valueOf() { return undefined; } }, 'object'], <ide> [{ valueOf: null }, 'object'], <del> [Object.create(null), 'object'] <add> [Object.create(null), 'object'], <add> [new Number(true), 'number'], <add> [new MyBadPrimitive(), 'number'], <add> [Symbol(), 'symbol'], <add> [5n, 'bigint'], <add> [(one, two, three) => {}, 'function'], <add> [undefined, 'undefined'], <add> [null, 'object'] <ide> ].forEach(([input, actualType]) => { <del> const err = common.expectsError({ <add> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <add> name: 'TypeError', <ide> message: 'The first argument must be one of type string, Buffer, ' + <ide> 'ArrayBuffer, Array, or Array-like Object. Received ' + <ide> `type ${actualType}` <del> }); <del> throws(() => Buffer.from(input), err); <add> }; <add> throws(() => Buffer.from(input), errObj); <add> throws(() => Buffer.from(input, 'hex'), errObj); <ide> }); <ide> <del>[ <del> new Number(true), <del> new MyBadPrimitive() <del>].forEach((input) => { <del> const errMsg = common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "value" argument must not be of type number. ' + <del> 'Received type number' <del> }); <del> throws(() => Buffer.from(input), errMsg); <del>}); <add>Buffer.allocUnsafe(10); // Should not throw. <add>Buffer.from('deadbeaf', 'hex'); // Should not throw.
3
PHP
PHP
add support for custom console error handling
34e1afd8efa3a02ba637ef53a952a0fc1b56f60c
<ide><path>lib/Cake/Console/ShellDispatcher.php <ide> protected function _bootstrap() { <ide> include_once CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Console' . DS . 'Templates' . DS . 'skel' . DS . 'Config' . DS . 'core.php'; <ide> App::build(); <ide> } <del> require_once CAKE . 'Console' . DS . 'ConsoleErrorHandler.php'; <del> $ErrorHandler = new ConsoleErrorHandler(); <del> set_exception_handler(array($ErrorHandler, 'handleException')); <del> set_error_handler(array($ErrorHandler, 'handleError'), Configure::read('Error.level')); <add> <add> $this->setErrorHandlers(); <ide> <ide> if (!defined('FULL_BASE_URL')) { <ide> define('FULL_BASE_URL', 'http://localhost'); <ide> protected function _bootstrap() { <ide> return true; <ide> } <ide> <add>/** <add> * Set the error/exception handlers for the console <add> * based on the `Error.consoleHandler`, and `Exception.consoleHandler` values <add> * if they are set. If they are not set, the default ConsoleErrorHandler will be <add> * used. <add> * <add> * @return void <add> */ <add> public function setErrorHandlers() { <add> App::uses('ConsoleErrorHandler', 'Console'); <add> $error = Configure::read('Error'); <add> $exception = Configure::read('Exception'); <add> <add> $errorHandler = new ConsoleErrorHandler(); <add> if (empty($error['consoleHandler'])) { <add> $error['consoleHandler'] = array($errorHandler, 'handleError'); <add> } <add> if (empty($exception['consoleHandler'])) { <add> $exception['consoleHandler'] = array($errorHandler, 'handleException'); <add> } <add> set_exception_handler($exception['consoleHandler']); <add> set_error_handler($error['consoleHandler'], Configure::read('Error.level')); <add> } <add> <ide> /** <ide> * Dispatches a CLI request <ide> *
1
Mixed
Javascript
add abortsignal support to finished
7837d3fde90552e00f6c29641dab81fd450b23b1
<ide><path>doc/api/stream.md <ide> further errors except from `_destroy()` may be emitted as `'error'`. <ide> <!-- YAML <ide> added: v10.0.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/37354 <add> description: The `signal` option was added. <ide> - version: v14.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/32158 <ide> description: The `finished(stream, cb)` will wait for the `'close'` event <ide> changes: <ide> * `writable` {boolean} When set to `false`, the callback will be called when <ide> the stream ends even though the stream might still be writable. <ide> **Default:** `true`. <add> * `signal` {AbortSignal} allows aborting the wait for the stream finish. The <add> underlying stream will *not* be aborted if the signal is aborted. The <add> callback will get called with an `AbortError`. All registered <add> listeners added by this function will also be removed. <ide> * `callback` {Function} A callback function that takes an optional error <ide> argument. <ide> * Returns: {Function} A cleanup function which removes all registered <ide><path>lib/internal/streams/end-of-stream.js <ide> const { <ide> FunctionPrototype, <ide> FunctionPrototypeCall, <add> ReflectApply, <ide> } = primordials; <add>const { <add> AbortError, <add> codes, <add>} = require('internal/errors'); <ide> const { <ide> ERR_STREAM_PREMATURE_CLOSE <del>} = require('internal/errors').codes; <add>} = codes; <ide> const { once } = require('internal/util'); <ide> const { <add> validateAbortSignal, <ide> validateFunction, <ide> validateObject, <ide> } = require('internal/validators'); <ide> function eos(stream, options, callback) { <ide> validateObject(options, 'options'); <ide> } <ide> validateFunction(callback, 'callback'); <add> validateAbortSignal(options.signal, 'options.signal'); <ide> <ide> callback = once(callback); <ide> <ide> function eos(stream, options, callback) { <ide> }); <ide> } <ide> <del> return function() { <add> const cleanup = () => { <ide> callback = nop; <ide> stream.removeListener('aborted', onclose); <ide> stream.removeListener('complete', onfinish); <ide> function eos(stream, options, callback) { <ide> stream.removeListener('error', onerror); <ide> stream.removeListener('close', onclose); <ide> }; <add> <add> if (options.signal && !closed) { <add> const abort = () => { <add> // Keep it because cleanup removes it. <add> const endCallback = callback; <add> cleanup(); <add> FunctionPrototypeCall(endCallback, stream, new AbortError()); <add> }; <add> if (options.signal.aborted) { <add> process.nextTick(abort); <add> } else { <add> const originalCallback = callback; <add> callback = once((...args) => { <add> options.signal.removeEventListener('abort', abort); <add> ReflectApply(originalCallback, stream, args); <add> }); <add> options.signal.addEventListener('abort', abort); <add> } <add> } <add> <add> return cleanup; <ide> } <ide> <ide> module.exports = eos; <ide><path>test/parallel/test-stream-finished.js <ide> const http = require('http'); <ide> run(); <ide> } <ide> <add>{ <add> // Check pre-cancelled <add> const signal = new EventTarget(); <add> signal.aborted = true; <add> <add> const rs = Readable.from((function* () {})()); <add> finished(rs, { signal }, common.mustCall((err) => { <add> assert.strictEqual(err.name, 'AbortError'); <add> })); <add>} <add> <add>{ <add> // Check cancelled before the stream ends sync. <add> const ac = new AbortController(); <add> const { signal } = ac; <add> <add> const rs = Readable.from((function* () {})()); <add> finished(rs, { signal }, common.mustCall((err) => { <add> assert.strictEqual(err.name, 'AbortError'); <add> })); <add> <add> ac.abort(); <add>} <add> <add>{ <add> // Check cancelled before the stream ends async. <add> const ac = new AbortController(); <add> const { signal } = ac; <add> <add> const rs = Readable.from((function* () {})()); <add> setTimeout(() => ac.abort(), 1); <add> finished(rs, { signal }, common.mustCall((err) => { <add> assert.strictEqual(err.name, 'AbortError'); <add> })); <add>} <add> <add>{ <add> // Check cancelled after doesn't throw. <add> const ac = new AbortController(); <add> const { signal } = ac; <add> <add> const rs = Readable.from((function* () { <add> yield 5; <add> setImmediate(() => ac.abort()); <add> })()); <add> rs.resume(); <add> finished(rs, { signal }, common.mustSucceed()); <add>} <add> <add>{ <add> // Promisified abort works <add> const finishedPromise = promisify(finished); <add> async function run() { <add> const ac = new AbortController(); <add> const { signal } = ac; <add> const rs = Readable.from((function* () {})()); <add> setImmediate(() => ac.abort()); <add> await finishedPromise(rs, { signal }); <add> } <add> <add> assert.rejects(run, { name: 'AbortError' }).then(common.mustCall()); <add>} <add> <add>{ <add> // Promisified pre-aborted works <add> const finishedPromise = promisify(finished); <add> async function run() { <add> const signal = new EventTarget(); <add> signal.aborted = true; <add> const rs = Readable.from((function* () {})()); <add> await finishedPromise(rs, { signal }); <add> } <add> <add> assert.rejects(run, { name: 'AbortError' }).then(common.mustCall()); <add>} <add> <add> <ide> { <ide> const rs = fs.createReadStream('file-does-not-exist'); <ide>
3
Python
Python
fix py3 compatibility
9d120bf9e02520e91cb7a3cc7453f27d9c404412
<ide><path>keras/layers/normalization.py <ide> def get_output(self, train): <ide> X = self.get_input(train) <ide> if self.mode == 0: <ide> input_shape = self.input_shape <del> reduction_axes = range(len(input_shape)) <add> reduction_axes = list(range(len(input_shape))) <ide> broadcast_shape = [1] * len(input_shape) <ide> broadcast_shape[self.axis] = input_shape[self.axis] <ide> del reduction_axes[self.axis]
1
Ruby
Ruby
fix typo in test name and documentation
4237d74213f01a882a1122dd0d3f53d80561ca5f
<ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb <ide> def test_valid_column <ide> assert @conn.valid_type?(column.type) <ide> end <ide> <del> # sqlite databses should be able to support any type and not <add> # sqlite databases should be able to support any type and not <ide> # just the ones mentioned in the native_database_types. <ide> # Therefore test_invalid column should always return true <ide> # even if the type is not valid. <ide><path>activerecord/test/cases/associations_test.rb <ide> def test_create_with_bang_via_association_with_block <ide> assert_equal post.body, "More cool stuff!" <ide> end <ide> <del> def test_reload_returns_assocition <add> def test_reload_returns_association <ide> david = developers(:david) <ide> assert_nothing_raised do <ide> assert_equal david.projects, david.projects.reload.reload
2
Javascript
Javascript
remove unnecessary string literals
a64b2f2b94c018dcfaf2ddb9adffd6dea5082919
<ide><path>test/parallel/test-vm-function-declaration.js <ide> code += '(function(){return this})().b;\n'; <ide> <ide> const res = vm.runInContext(code, o, 'test'); <ide> <del>assert.strictEqual(typeof res, 'function', 'result should be function'); <del>assert.strictEqual(res.name, 'b', 'res should be named b'); <del>assert.strictEqual(typeof o.a, 'function', 'a should be function'); <del>assert.strictEqual(typeof o.b, 'function', 'b should be function'); <del>assert.strictEqual(res, o.b, 'result should be global b function'); <add>assert.strictEqual(typeof res, 'function'); <add>assert.strictEqual(res.name, 'b'); <add>assert.strictEqual(typeof o.a, 'function'); <add>assert.strictEqual(typeof o.b, 'function'); <add>assert.strictEqual(res, o.b);
1
PHP
PHP
add missing connection parameters
35b50b1883b8b0771eeb3edc8a11735440a66d5a
<ide><path>Cake/ORM/TableRegistry.php <ide> public static function get($alias, $options = []) { <ide> $class = Inflector::classify($alias); <ide> $className = App::classname($class, 'Model\Repository', 'Table'); <ide> $options['className'] = $className ?: 'Cake\ORM\Table'; <del> $options['className'] = $className; <ide> } <ide> <ide> if (isset(static::$_config[$alias])) { <ide><path>Cake/Test/TestCase/ORM/ResultSetTest.php <ide> class ResultSetTest extends TestCase { <ide> public function setUp() { <ide> parent::setUp(); <ide> $this->connection = ConnectionManager::get('test'); <del> $this->table = new Table(['table' => 'articles']); <add> $this->table = new Table([ <add> 'table' => 'articles', <add> 'connection' => $this->connection, <add> ]); <ide> <ide> $this->fixtureData = [ <ide> ['id' => 1, 'author_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y'], <ide><path>Cake/Test/TestCase/ORM/TableTest.php <ide> public function testAliasMethod() { <ide> * @return void <ide> */ <ide> public function testConnection() { <del> Table::clearRegistry(); <ide> $table = new Table(['table' => 'users']); <ide> $this->assertNull($table->connection()); <ide> $table->connection($this->connection); <ide> public function testDisplaySet() { <ide> */ <ide> public function testSchema() { <ide> $schema = $this->connection->schemaCollection()->describe('users'); <del> $table = new Table(['table' => 'users']); <add> $table = new Table([ <add> 'table' => 'users', <add> 'connection' => $this->connection, <add> ]); <ide> $this->assertEquals($schema, $table->schema()); <ide> <ide> $table = new Table(['table' => 'stuff']); <ide> public function testSchema() { <ide> * @return void <ide> */ <ide> public function testFindAllNoFieldsAndNoHydration() { <del> $table = new Table(['table' => 'users']); <add> $table = new Table([ <add> 'table' => 'users', <add> 'connection' => $this->connection, <add> ]); <ide> $results = $table <ide> ->find('all') <ide> ->where(['id IN' => [1, 2]]) <ide> public function testFindAllNoFieldsAndNoHydration() { <ide> * @return void <ide> */ <ide> public function testFindAllSomeFieldsNoHydration() { <del> $table = new Table(['table' => 'users']); <add> $table = new Table([ <add> 'table' => 'users', <add> 'connection' => $this->connection, <add> ]); <ide> $results = $table->find('all') <ide> ->select(['username', 'password']) <ide> ->hydrate(false) <ide> public function testFindAllSomeFieldsNoHydration() { <ide> * @return void <ide> */ <ide> public function testFindAllConditionAutoTypes() { <del> $table = new Table(['table' => 'users']); <add> $table = new Table([ <add> 'table' => 'users', <add> 'connection' => $this->connection, <add> ]); <ide> $query = $table->find('all') <ide> ->select(['id', 'username']) <ide> ->where(['created >=' => new \DateTime('2010-01-22 00:00')]) <ide> public function testFindAllConditionAutoTypes() { <ide> * @return void <ide> */ <ide> public function testFindBeforeFindEventMutateQuery() { <del> $table = new Table(['table' => 'users']); <add> $table = new Table([ <add> 'table' => 'users', <add> 'connection' => $this->connection, <add> ]); <ide> $table->getEventManager()->attach(function ($event, $query, $options) { <ide> $query->limit(1); <ide> }, 'Model.beforeFind'); <ide> public function testFindBeforeFindEventMutateQuery() { <ide> * @return void <ide> */ <ide> public function testFindBeforeFindEventOverrideReturn() { <del> $table = new Table(['table' => 'users']); <add> $table = new Table([ <add> 'table' => 'users', <add> 'connection' => $this->connection, <add> ]); <ide> $expected = ['One', 'Two', 'Three']; <ide> $table->getEventManager()->attach(function ($event, $query, $options) use ($expected) { <ide> $query->setResult($expected); <ide> public function testBelongsToMany() { <ide> * @return void <ide> */ <ide> public function testUpdateAll() { <del> $table = new Table(['table' => 'users']); <add> $table = new Table([ <add> 'table' => 'users', <add> 'connection' => $this->connection, <add> ]); <ide> $fields = ['username' => 'mark']; <ide> $result = $table->updateAll($fields, ['id <' => 4]); <ide> $this->assertTrue($result); <ide> public function testUpdateAllFailure() { <ide> * @return void <ide> */ <ide> public function testDeleteAll() { <del> $table = new Table(['table' => 'users']); <add> $table = new Table([ <add> 'table' => 'users', <add> 'connection' => $this->connection, <add> ]); <ide> $result = $table->deleteAll(['id <' => 4]); <ide> $this->assertTrue($result); <ide> <ide> public function testFindApplyOptions() { <ide> * @return void <ide> */ <ide> public function testFindListNoHydration() { <del> $table = new Table(['table' => 'users']); <add> $table = new Table([ <add> 'table' => 'users', <add> 'connection' => $this->connection, <add> ]); <ide> $table->displayField('username'); <ide> $query = $table->find('list', ['fields' => ['id', 'username']]) <ide> ->hydrate(false) <ide> public function testFindListNoHydration() { <ide> * @return void <ide> */ <ide> public function testFindThreadedNoHydration() { <del> $table = new Table(['table' => 'categories']); <add> $table = new Table([ <add> 'table' => 'categories', <add> 'connection' => $this->connection, <add> ]); <ide> $expected = [ <ide> [ <ide> 'id' => 1, <ide> public function testStackingFinders() { <ide> * @return void <ide> */ <ide> public function testFindThreadedHydrated() { <del> $table = new Table(['table' => 'categories']); <add> $table = new Table([ <add> 'table' => 'categories', <add> 'connection' => $this->connection, <add> ]); <ide> $results = $table->find('all') <ide> ->threaded() <ide> ->select(['id', 'parent_id', 'name']) <ide> public function testFindThreadedHydrated() { <ide> * @return void <ide> */ <ide> public function testFindListHydrated() { <del> $table = new Table(['table' => 'users']); <add> $table = new Table([ <add> 'table' => 'users', <add> 'connection' => $this->connection, <add> ]); <ide> $table->displayField('username'); <ide> $query = $table <ide> ->find('list', ['fields' => ['id', 'username']]) <ide> public function testSetEntityClass() { <ide> * @return void <ide> */ <ide> public function testReciprocalBelongsToLoading() { <del> $table = new \TestApp\Model\Repository\ArticleTable; <add> $table = new \TestApp\Model\Repository\ArticleTable([ <add> 'connection' => $this->connection, <add> ]); <ide> $result = $table->find('all')->contain(['author'])->first(); <ide> $this->assertInstanceOf('TestApp\Model\Entity\Author', $result->author); <ide> } <ide> public function testReciprocalBelongsToLoading() { <ide> * @return void <ide> */ <ide> public function testReciprocalHasManyLoading() { <del> $table = new \TestApp\Model\Repository\ArticleTable; <add> $table = new \TestApp\Model\Repository\ArticleTable([ <add> 'connection' => $this->connection, <add> ]); <ide> $result = $table->find('all')->contain(['author' => ['article']])->first(); <ide> $this->assertCount(2, $result->author->article); <ide> foreach ($result->author->article as $article) {
3
Python
Python
fix mypy issues in `example_twitter_dag`
041babb0608a102fd9d83e77b7fab5d9831ec2b4
<ide><path>airflow/providers/apache/hive/example_dags/example_twitter_dag.py <ide> def transfer_to_db(): <ide> tags=['example'], <ide> catchup=False, <ide> ) as dag: <del> fetch_tweets = fetch_tweets() <del> clean_tweets = clean_tweets() <del> analyze_tweets = analyze_tweets() <add> fetch = fetch_tweets() <add> clean = clean_tweets() <add> analyze = analyze_tweets() <ide> hive_to_mysql = transfer_to_db() <ide> <del> fetch_tweets >> clean_tweets >> analyze_tweets <add> fetch >> clean >> analyze <ide> <ide> # -------------------------------------------------------------------------------- <ide> # The following tasks are generated using for loop. The first task puts the eight <ide> def transfer_to_db(): <ide> ), <ide> ) <ide> <del> analyze_tweets >> load_to_hdfs >> load_to_hive >> hive_to_mysql <add> analyze >> load_to_hdfs >> load_to_hive >> hive_to_mysql <ide> <ide> for channel in from_channels: <ide> file_name = f"from_{channel}_{dt}.csv" <ide> def transfer_to_db(): <ide> ), <ide> ) <ide> <del> analyze_tweets >> load_to_hdfs >> load_to_hive >> hive_to_mysql <add> analyze >> load_to_hdfs >> load_to_hive >> hive_to_mysql
1
Java
Java
fix checkstyle violation
74e9825a654b9699ccea7b481629a8c297f6ef73
<ide><path>spring-tx/src/main/java/org/springframework/transaction/package-info.java <ide> /** <ide> * Spring's core transaction management APIs (independent of any specific transaction <del> * management system); an exception hierarchy for Spring's transaction infrastructure; <add> * management system); an exception hierarchy for Spring's transaction infrastructure; <ide> * and transaction manager, definition, and status interfaces. <ide> */ <ide> @NonNullApi
1
PHP
PHP
fix failing tests
30663f23b38b03e49c52eb63b8d6913d4b7e325e
<ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testUpdateProcess() <ide> $events->shouldReceive('fire')->once()->with('eloquent.updated: '.get_class($model), $model)->andReturn(true); <ide> $events->shouldReceive('fire')->once()->with('eloquent.saved: '.get_class($model), $model)->andReturn(true); <ide> <add> $model->id = 1; <ide> $model->foo = 'bar'; <ide> // make sure foo isn't synced so we can test that dirty attributes only are updated <ide> $model->syncOriginal(); <del> $model->id = 1; <ide> $model->name = 'taylor'; <ide> $model->exists = true; <ide> $this->assertTrue($model->save()); <ide> public function testUpdateProcessDoesntOverrideTimestamps() <ide> $events->shouldReceive('until'); <ide> $events->shouldReceive('fire'); <ide> <del> $model->syncOriginal(); <ide> $model->id = 1; <add> $model->syncOriginal(); <ide> $model->created_at = 'foo'; <ide> $model->updated_at = 'bar'; <ide> $model->exists = true; <ide> public function testUpdateProcessWithoutTimestamps() <ide> $model->expects($this->any())->method('fireModelEvent')->will($this->returnValue(true)); <ide> <ide> $model->id = 1; <add> $model->syncOriginal(); <ide> $model->name = 'taylor'; <ide> $model->exists = true; <ide> $this->assertTrue($model->save());
1
Javascript
Javascript
add friendly error message on auth create attemp
7b8dc2e77eacd49bbd46d2714fd4d792c4f87b3e
<ide><path>common/models/User-Identity.js <ide> const debug = debugFactory('fcc:models:userIdent'); <ide> export default function(UserIdent) { <ide> // original source <ide> // github.com/strongloop/loopback-component-passport <add> const createAccountMessage = <add> 'Accounts can only be created using GitHub or though email'; <ide> UserIdent.login = function( <ide> provider, <ide> authScheme, <ide> export default function(UserIdent) { <ide> <ide> const userObj = options.profileToUser(provider, profile, options); <ide> if (getSocialProvider(provider) !== 'github') { <del> return process.nextTick(() => cb( <del> new Error( <del> 'accounts can only be created using Github or though email' <del> ) <del> )); <add> const err = new Error(createAccountMessage); <add> err.userMessage = createAccountMessage; <add> err.messageType = 'info'; <add> err.redirectTo = '/signin'; <add> return process.nextTick(() => cb(err)); <ide> } <ide> <ide> let query; <ide><path>server/middlewares/error-handlers.js <ide> export default function prodErrorHandler() { <ide> var message = 'Oops! Something went wrong. Please try again later'; <ide> if (type === 'html') { <ide> if (typeof req.flash === 'function') { <del> req.flash('errors', { <del> msg: message <add> req.flash(err.messageType || 'errors', { <add> msg: err.userMessage || message <ide> }); <ide> } <del> return res.redirect('/map'); <add> return res.redirect(err.redirectTo || '/map'); <ide> // json <ide> } else if (type === 'json') { <ide> res.setHeader('Content-Type', 'application/json');
2
Javascript
Javascript
apply suggestions from code review
7e22ae3ced97db1b37596d40ca25f2f26fd61042
<ide><path>packages/@ember/-internals/runtime/lib/mixins/array.js <ide> const ArrayMixin = Mixin.create(Enumerable, { <ide> let foods = [ <ide> { name: 'apple', eaten: false }, <ide> { name: 'banana', eaten: false }, <del> { name: carrot': eaten: false } <add> { name: 'carrot', eaten: false } <ide> ]; <ide> <ide> foods.forEach((food) => food.eaten = true); <ide> <ide> let output = ''; <ide> foods.forEach((item, index, array) => <del> output += `${index + 1}/${array.length}) ${item}\n` <add> output += `${index + 1}/${array.length} ${item.name}\n`; <ide> ); <add> console.log(output); <add> // 1/3 apple <add> // 2/3 banana <add> // 3/3 carrot <ide> ``` <ide> <ide> @method forEach
1
Java
Java
scheduler correctness improvements
8fa3a37420c3bcca5ed8355a09cd67b75ae6665e
<ide><path>rxjava-core/src/main/java/rx/schedulers/EventLoopsScheduler.java <ide> import rx.Scheduler; <ide> import rx.Subscription; <ide> import rx.functions.Action0; <del>import rx.schedulers.NewThreadScheduler.OnActionComplete; <add>import rx.schedulers.NewThreadScheduler.NewThreadWorker.Remover; <add>import rx.schedulers.NewThreadScheduler.NewThreadWorker.ScheduledAction; <ide> import rx.subscriptions.CompositeSubscription; <ide> import rx.subscriptions.Subscriptions; <ide> <ide> /* package */class EventLoopsScheduler extends Scheduler { <del> <del> private static class ComputationSchedulerPool { <del> final int cores = Runtime.getRuntime().availableProcessors(); <add> /** Manages a fixed number of workers. */ <add> static final class FixedSchedulerPool { <add> final int cores; <ide> final ThreadFactory factory = new ThreadFactory() { <ide> final AtomicInteger counter = new AtomicInteger(); <ide> <ide> public Thread newThread(Runnable r) { <ide> } <ide> }; <ide> <del> final EventLoopScheduler[] eventLoops; <add> final PoolWorker[] eventLoops; <add> long n; <ide> <del> ComputationSchedulerPool() { <add> FixedSchedulerPool() { <ide> // initialize event loops <del> eventLoops = new EventLoopScheduler[cores]; <add> this.cores = Runtime.getRuntime().availableProcessors(); <add> this.eventLoops = new PoolWorker[cores]; <ide> for (int i = 0; i < cores; i++) { <del> eventLoops[i] = new EventLoopScheduler(factory); <add> this.eventLoops[i] = new PoolWorker(factory); <ide> } <ide> } <ide> <del> private static ComputationSchedulerPool INSTANCE = new ComputationSchedulerPool(); <del> <del> long n = 0; <del> <del> public EventLoopScheduler getEventLoop() { <del> // round-robin selection (improvements to come) <del> return eventLoops[(int) (n++ % cores)]; <add> public PoolWorker getEventLoop() { <add> // simple round robin, improvements to come <add> return eventLoops[(int)(n++ % cores)]; <ide> } <del> <ide> } <ide> <add> final FixedSchedulerPool pool; <add> <add> /** <add> * Create a scheduler with pool size equal to the available processor <add> * count and using least-recent worker selection policy. <add> */ <add> EventLoopsScheduler() { <add> pool = new FixedSchedulerPool(); <add> } <add> <ide> @Override <ide> public Worker createWorker() { <del> return new EventLoop(); <add> return new EventLoopWorker(pool.getEventLoop()); <ide> } <ide> <del> private static class EventLoop extends Scheduler.Worker { <add> private static class EventLoopWorker extends Scheduler.Worker { <ide> private final CompositeSubscription innerSubscription = new CompositeSubscription(); <del> private final EventLoopScheduler pooledEventLoop; <del> private final OnActionComplete onComplete; <del> <del> EventLoop() { <del> pooledEventLoop = ComputationSchedulerPool.INSTANCE.getEventLoop(); <del> onComplete = new OnActionComplete() { <add> private final PoolWorker poolWorker; <ide> <del> @Override <del> public void complete(Subscription s) { <del> innerSubscription.remove(s); <del> } <del> <del> }; <add> EventLoopWorker(PoolWorker poolWorker) { <add> this.poolWorker = poolWorker; <add> <ide> } <ide> <ide> @Override <ide> public boolean isUnsubscribed() { <ide> <ide> @Override <ide> public Subscription schedule(Action0 action) { <del> if (innerSubscription.isUnsubscribed()) { <del> // don't schedule, we are unsubscribed <del> return Subscriptions.empty(); <del> } <del> return pooledEventLoop.schedule(action, onComplete); <add> return schedule(action, 0, null); <ide> } <del> <ide> @Override <ide> public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) { <ide> if (innerSubscription.isUnsubscribed()) { <ide> // don't schedule, we are unsubscribed <ide> return Subscriptions.empty(); <ide> } <ide> <del> return pooledEventLoop.schedule(action, delayTime, unit, onComplete); <add> ScheduledAction s = poolWorker.scheduleActual(action, delayTime, unit); <add> innerSubscription.add(s); <add> s.addParent(innerSubscription); <add> return s; <ide> } <del> <ide> } <del> <del> private static class EventLoopScheduler extends NewThreadScheduler.EventLoopScheduler { <del> EventLoopScheduler(ThreadFactory threadFactory) { <add> <add> private static final class PoolWorker extends NewThreadScheduler.NewThreadWorker { <add> PoolWorker(ThreadFactory threadFactory) { <ide> super(threadFactory); <ide> } <ide> } <del> <del>} <add>} <ide>\ No newline at end of file <ide><path>rxjava-core/src/main/java/rx/schedulers/NewThreadScheduler.java <ide> */ <ide> package rx.schedulers; <ide> <del>import java.util.concurrent.ExecutorService; <ide> import java.util.concurrent.Executors; <del>import java.util.concurrent.ScheduledFuture; <add>import java.util.concurrent.Future; <add>import java.util.concurrent.ScheduledExecutorService; <ide> import java.util.concurrent.ThreadFactory; <ide> import java.util.concurrent.TimeUnit; <add>import java.util.concurrent.atomic.AtomicBoolean; <ide> import java.util.concurrent.atomic.AtomicLong; <del>import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import rx.Scheduler; <ide> import rx.Subscription; <ide> private NewThreadScheduler() { <ide> <ide> @Override <ide> public Worker createWorker() { <del> return new EventLoopScheduler(THREAD_FACTORY); <add> return new NewThreadWorker(THREAD_FACTORY); <ide> } <ide> <del> /* package */static class EventLoopScheduler extends Scheduler.Worker implements Subscription { <add> /* package */static class NewThreadWorker extends Scheduler.Worker implements Subscription { <ide> private final CompositeSubscription innerSubscription = new CompositeSubscription(); <del> private final ExecutorService executor; <add> private final ScheduledExecutorService executor; <ide> <del> /* package */EventLoopScheduler(ThreadFactory threadFactory) { <del> executor = Executors.newSingleThreadExecutor(threadFactory); <add> /* package */NewThreadWorker(ThreadFactory threadFactory) { <add> executor = Executors.newScheduledThreadPool(1, threadFactory); <ide> } <ide> <ide> @Override <ide> public Subscription schedule(final Action0 action) { <ide> } <ide> <ide> /* package */Subscription schedule(final Action0 action, final OnActionComplete onComplete) { <add> return scheduleActual(action, 0, null); <add> } <add> <add> @Override <add> public Subscription schedule(final Action0 action, long delayTime, TimeUnit unit) { <ide> if (innerSubscription.isUnsubscribed()) { <del> // don't schedule, we are unsubscribed <ide> return Subscriptions.empty(); <ide> } <del> <del> final AtomicReference<Subscription> sf = new AtomicReference<Subscription>(); <del> Subscription s = Subscriptions.from(executor.submit(new Runnable() { <del> <del> @Override <del> public void run() { <del> try { <del> if (innerSubscription.isUnsubscribed()) { <del> return; <del> } <del> action.call(); <del> } finally { <del> // remove the subscription now that we're completed <del> Subscription s = sf.get(); <del> if (s != null) { <del> innerSubscription.remove(s); <del> } <del> if (onComplete != null) { <del> onComplete.complete(s); <del> } <del> } <del> } <del> })); <del> <del> sf.set(s); <del> innerSubscription.add(s); <del> return s; <add> return scheduleActual(action, delayTime, unit); <ide> } <ide> <del> @Override <del> public Subscription schedule(final Action0 action, long delayTime, TimeUnit unit) { <del> return schedule(action, delayTime, unit, null); <add> /* package */ScheduledAction scheduleActual(final Action0 action, long delayTime, TimeUnit unit) { <add> ScheduledAction run = new ScheduledAction(action, innerSubscription); <add> Future<?> f; <add> if (delayTime <= 0) { <add> f = executor.submit(run); <add> } else { <add> f = executor.schedule(run, delayTime, unit); <add> } <add> run.add(Subscriptions.from(f)); <add> <add> return run; <ide> } <add> <add> /** Remove a child subscription from a composite when unsubscribing. */ <add> public static final class Remover implements Subscription { <add> final Subscription s; <add> final CompositeSubscription parent; <add> final AtomicBoolean once; <add> <add> public Remover(Subscription s, CompositeSubscription parent) { <add> this.s = s; <add> this.parent = parent; <add> this.once = new AtomicBoolean(); <add> } <add> <add> @Override <add> public boolean isUnsubscribed() { <add> return s.isUnsubscribed(); <add> } <add> <add> @Override <add> public void unsubscribe() { <add> if (once.compareAndSet(false, true)) { <add> parent.remove(s); <add> } <add> } <add> <add> } <add> /** <add> * A runnable that executes an Action0 and can be cancelled <add> * The analogue is the Subscriber in respect of an Observer. <add> */ <add> public static final class ScheduledAction implements Runnable, Subscription { <add> final CompositeSubscription cancel; <add> final Action0 action; <add> final CompositeSubscription parent; <add> final AtomicBoolean once; <add> <add> public ScheduledAction(Action0 action, CompositeSubscription parent) { <add> this.action = action; <add> this.parent = parent; <add> this.cancel = new CompositeSubscription(); <add> this.once = new AtomicBoolean(); <add> } <ide> <del> /* package */Subscription schedule(final Action0 action, long delayTime, TimeUnit unit, final OnActionComplete onComplete) { <del> final AtomicReference<Subscription> sf = new AtomicReference<Subscription>(); <del> // we will use the system scheduler since it doesn't make sense to launch a new Thread and then sleep <del> // we will instead schedule the event then launch the thread after the delay has passed <del> ScheduledFuture<?> f = GenericScheduledExecutorService.getInstance().schedule(new Runnable() { <del> <del> @Override <del> public void run() { <del> try { <del> if (innerSubscription.isUnsubscribed()) { <del> return; <del> } <del> // now that the delay is past schedule the work to be done for real on the UI thread <del> schedule(action); <del> } finally { <del> // remove the subscription now that we're completed <del> Subscription s = sf.get(); <del> if (s != null) { <del> innerSubscription.remove(s); <del> } <del> if (onComplete != null) { <del> onComplete.complete(s); <del> } <del> } <add> @Override <add> public void run() { <add> try { <add> action.call(); <add> } finally { <add> unsubscribe(); <ide> } <del> }, delayTime, unit); <add> } <ide> <del> // add the ScheduledFuture as a subscription so we can cancel the scheduled action if an unsubscribe happens <del> Subscription s = Subscriptions.from(f); <del> sf.set(s); <del> innerSubscription.add(s); <del> return s; <add> @Override <add> public boolean isUnsubscribed() { <add> return cancel.isUnsubscribed(); <add> } <add> <add> @Override <add> public void unsubscribe() { <add> if (once.compareAndSet(false, true)) { <add> cancel.unsubscribe(); <add> parent.remove(this); <add> } <add> } <add> public void add(Subscription s) { <add> cancel.add(s); <add> } <add> /** <add> * Adds a parent to this ScheduledAction so when it is <add> * cancelled or terminates, it can remove itself from this parent. <add> * @param parent <add> */ <add> public void addParent(CompositeSubscription parent) { <add> cancel.add(new Remover(this, parent)); <add> } <ide> } <ide> <ide> @Override <ide> public void unsubscribe() { <add> executor.shutdown(); <ide> innerSubscription.unsubscribe(); <ide> } <ide> <ide> public boolean isUnsubscribed() { <ide> <ide> } <ide> <del>} <add>} <ide>\ No newline at end of file
2
Python
Python
replace non-empty sets with set literals
56d72e3ff8798a2662847355d1b73b2c1f57b31f
<ide><path>airflow/models/dag.py <ide> def get_paused_dag_ids(dag_ids: List[str], session: Session = None) -> Set[str]: <ide> .all() <ide> ) <ide> <del> paused_dag_ids = set(paused_dag_id for paused_dag_id, in paused_dag_ids) <add> paused_dag_ids = {paused_dag_id for paused_dag_id, in paused_dag_ids} <ide> return paused_dag_ids <ide> <ide> def get_default_view(self) -> str: <ide><path>airflow/providers/plexus/operators/job.py <ide> def __init__(self, job_params: Dict, **kwargs) -> None: <ide> super().__init__(**kwargs) <ide> <ide> self.job_params = job_params <del> self.required_params = set(["name", "app", "queue", "num_cores", "num_nodes"]) <add> self.required_params = {"name", "app", "queue", "num_cores", "num_nodes"} <ide> self.lookups = { <ide> "app": ("apps/", "id", "name"), <ide> "billing_account_id": ("users/{}/billingaccounts/", "id", None), <ide><path>airflow/www/security.py <ide> def get_editable_dags(self, user): <ide> <ide> def get_readable_dag_ids(self, user) -> Set[str]: <ide> """Gets the DAG IDs readable by authenticated user.""" <del> return set(dag.dag_id for dag in self.get_readable_dags(user)) <add> return {dag.dag_id for dag in self.get_readable_dags(user)} <ide> <ide> def get_editable_dag_ids(self, user) -> Set[str]: <ide> """Gets the DAG IDs editable by authenticated user.""" <del> return set(dag.dag_id for dag in self.get_editable_dags(user)) <add> return {dag.dag_id for dag in self.get_editable_dags(user)} <ide> <ide> def get_accessible_dag_ids(self, user) -> Set[str]: <ide> """Gets the DAG IDs editable or readable by authenticated user.""" <ide> accessible_dags = self.get_accessible_dags( <ide> [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ], user <ide> ) <del> return set(dag.dag_id for dag in accessible_dags) <add> return {dag.dag_id for dag in accessible_dags} <ide> <ide> @provide_session <ide> def get_accessible_dags(self, user_actions, user, session=None): <ide><path>airflow/www/utils.py <ide> def get_sensitive_variables_fields(): <ide> sensitive_fields = set(DEFAULT_SENSITIVE_VARIABLE_FIELDS) <ide> sensitive_variable_fields = conf.get('admin', 'sensitive_variable_fields') <ide> if sensitive_variable_fields: <del> sensitive_fields.update(set(field.strip() for field in sensitive_variable_fields.split(','))) <add> sensitive_fields.update({field.strip() for field in sensitive_variable_fields.split(',')}) <ide> return sensitive_fields <ide> <ide> <ide><path>tests/core/test_project_structure.py <ide> def test_providers_modules_should_have_tests(self): <ide> missing_tests_files = expected_test_files - expected_test_files.intersection(current_test_files) <ide> <ide> with self.subTest("Detect missing tests in providers module"): <del> expected_missing_test_modules = set(pair[1] for pair in expected_missing_providers_modules) <add> expected_missing_test_modules = {pair[1] for pair in expected_missing_providers_modules} <ide> missing_tests_files = missing_tests_files - set(expected_missing_test_modules) <ide> self.assertEqual(set(), missing_tests_files) <ide> <ide> with self.subTest("Verify removed deprecated module also removed from deprecated list"): <del> expected_missing_modules = set(pair[0] for pair in expected_missing_providers_modules) <add> expected_missing_modules = {pair[0] for pair in expected_missing_providers_modules} <ide> removed_deprecated_module = expected_missing_modules - modules_files <ide> if removed_deprecated_module: <ide> self.fail( <ide> def has_example_dag(operator_set): <ide> return False <ide> <ide> with self.subTest("Detect missing example dags"): <del> missing_example = set(s for s in operator_sets if not has_example_dag(s)) <add> missing_example = {s for s in operator_sets if not has_example_dag(s)} <ide> missing_example -= self.MISSING_EXAMPLE_DAGS <ide> self.assertEqual(set(), missing_example) <ide> <ide><path>tests/utils/test_dag_processing.py <ide> def fake_processor_factory(*args, **kwargs): <ide> assert fake_processors[-1]._file_path == test_dag_path <ide> callback_requests = fake_processors[-1]._callback_requests <ide> assert ( <del> set(zombie.simple_task_instance.key for zombie in expected_failure_callback_requests) == <del> set(result.simple_task_instance.key for result in callback_requests) <add> {zombie.simple_task_instance.key for zombie in expected_failure_callback_requests} == <add> {result.simple_task_instance.key for result in callback_requests} <ide> ) <ide> <ide> child_pipe.close()
6
Text
Text
add spectrum badge
fd7cb2a804a1ddcf208ed8adad57d2a3d5d1d14b
<ide><path>readme.md <ide> [![Build status](https://ci.appveyor.com/api/projects/status/gqp5hs71l3ebtx1r/branch/master?svg=true)](https://ci.appveyor.com/project/arunoda/next-js/branch/master) <ide> [![Coverage Status](https://coveralls.io/repos/zeit/next.js/badge.svg?branch=master)](https://coveralls.io/r/zeit/next.js?branch=master) <ide> [![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat) <add>[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/next-js) <ide> <ide> Next.js is a minimalistic framework for server-rendered React applications. <ide>
1
Javascript
Javascript
fix halffloattype bug in webglutils
51dad3fe3899b3d463b3d6f765a4412833c618f3
<ide><path>src/renderers/webgl/WebGLUtils.js <ide> function WebGLUtils( gl, extensions ) { <ide> <ide> if ( p === HalfFloatType ) { <ide> <add> if ( isWebGL2 ) return gl.HALF_FLOAT; <add> <ide> extension = extensions.get( 'OES_texture_half_float' ); <ide> <del> return isWebGL2 ? gl.HALF_FLOAT : extension.HALF_FLOAT_OES; <add> if ( extension !== null ) return extension.HALF_FLOAT_OES; <ide> <ide> } <ide>
1
Python
Python
add option to omit extra lexeme tables in cli
daaa7bf45111cd7d033868f875442b494a9dfead
<ide><path>spacy/cli/init_model.py <ide> from ..vectors import Vectors <ide> from ..errors import Errors, Warnings <ide> from ..util import ensure_path, get_lang_class, OOV_RANK <add>from ..lookups import Lookups <ide> <ide> try: <ide> import ftfy <ide> str, <ide> ), <ide> model_name=("Optional name for the model meta", "option", "mn", str), <add> omit_extra_lookups=("Don't include extra lookups in model", "flag", "OEL", bool), <ide> ) <ide> def init_model( <ide> lang, <ide> def init_model( <ide> prune_vectors=-1, <ide> vectors_name=None, <ide> model_name=None, <add> omit_extra_lookups=False, <ide> ): <ide> """ <ide> Create a new model from raw data, like word frequencies, Brown clusters <ide> def init_model( <ide> <ide> with msg.loading("Creating model..."): <ide> nlp = create_model(lang, lex_attrs, name=model_name) <add> <add> # Create empty extra lexeme tables so the data from spacy-lookups-data <add> # isn't loaded if these features are accessed <add> if omit_extra_lookups: <add> nlp.vocab.lookups_extra = Lookups() <add> nlp.vocab.lookups_extra.add_table("lexeme_cluster") <add> nlp.vocab.lookups_extra.add_table("lexeme_prob") <add> nlp.vocab.lookups_extra.add_table("lexeme_settings") <add> <ide> msg.good("Successfully created model") <ide> if vectors_loc is not None: <ide> add_vectors(nlp, vectors_loc, truncate_vectors, prune_vectors, vectors_name) <ide><path>spacy/cli/train.py <ide> from ..util import use_gpu as set_gpu <ide> from ..gold import GoldCorpus <ide> from ..compat import path2str <add>from ..lookups import Lookups <ide> from .. import util <ide> from .. import about <ide> <ide> textcat_arch=("Textcat model architecture", "option", "ta", str), <ide> textcat_positive_label=("Textcat positive label for binary classes with two labels", "option", "tpl", str), <ide> tag_map_path=("Location of JSON-formatted tag map", "option", "tm", Path), <add> omit_extra_lookups=("Don't include extra lookups in model", "flag", "OEL", bool), <ide> verbose=("Display more information for debug", "flag", "VV", bool), <ide> debug=("Run data diagnostics before training", "flag", "D", bool), <ide> # fmt: on <ide> def train( <ide> textcat_arch="bow", <ide> textcat_positive_label=None, <ide> tag_map_path=None, <add> omit_extra_lookups=False, <ide> verbose=False, <ide> debug=False, <ide> ): <ide> def train( <ide> # Update tag map with provided mapping <ide> nlp.vocab.morphology.tag_map.update(tag_map) <ide> <add> # Create empty extra lexeme tables so the data from spacy-lookups-data <add> # isn't loaded if these features are accessed <add> if omit_extra_lookups: <add> nlp.vocab.lookups_extra = Lookups() <add> nlp.vocab.lookups_extra.add_table("lexeme_cluster") <add> nlp.vocab.lookups_extra.add_table("lexeme_prob") <add> nlp.vocab.lookups_extra.add_table("lexeme_settings") <add> <ide> if vectors: <ide> msg.text("Loading vector from model '{}'".format(vectors)) <ide> _load_vectors(nlp, vectors)
2
Javascript
Javascript
reduce size, simplify setdocument
29a9544a4fb743491a42f827a6cf8627b7b99e0f
<ide><path>src/selector.js <ide> define( [ <ide> "./core", <ide> "./var/document", <add> "./var/documentElement", <ide> "./var/indexOf", <ide> "./var/pop", <ide> "./var/push", <add> "./selector/rbuggyQSA", <ide> "./selector/support", <ide> <ide> // The following utils are attached directly to the jQuery object. <ide> "./selector/contains", <ide> "./selector/escapeSelector", <ide> "./selector/uniqueSort" <del>], function( jQuery, document, indexOf, pop, push, support ) { <add>], function( jQuery, document, documentElement, indexOf, pop, push, rbuggyQSA, support ) { <ide> <ide> "use strict"; <ide> <del>var preferredDoc = document; <add>var preferredDoc = document, <add> matches = documentElement.matches || documentElement.msMatchesSelector; <ide> <ide> ( function() { <ide> <ide> var i, <ide> <ide> // Local document vars <ide> document, <del> docElem, <add> documentElement, <ide> documentIsHTML, <del> rbuggyQSA, <del> matches, <ide> <ide> // Instance-specific data <ide> expando = jQuery.expando, <ide> var i, <ide> ridentifier = new RegExp( "^" + identifier + "$" ), <ide> <ide> matchExpr = { <del> "ID": new RegExp( "^#(" + identifier + ")" ), <del> "CLASS": new RegExp( "^\\.(" + identifier + ")" ), <del> "TAG": new RegExp( "^(" + identifier + "|[*])" ), <del> "ATTR": new RegExp( "^" + attributes ), <del> "PSEUDO": new RegExp( "^" + pseudos ), <del> "CHILD": new RegExp( <add> ID: new RegExp( "^#(" + identifier + ")" ), <add> CLASS: new RegExp( "^\\.(" + identifier + ")" ), <add> TAG: new RegExp( "^(" + identifier + "|[*])" ), <add> ATTR: new RegExp( "^" + attributes ), <add> PSEUDO: new RegExp( "^" + pseudos ), <add> CHILD: new RegExp( <ide> "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + <ide> whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + <ide> whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), <del> "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), <add> bool: new RegExp( "^(?:" + booleans + ")$", "i" ), <ide> <ide> // For use in libraries implementing .is() <ide> // We use this for POS matching in `select` <del> "needsContext": new RegExp( "^" + whitespace + <add> needsContext: new RegExp( "^" + whitespace + <ide> "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + <ide> "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) <ide> }, <ide> function find( selector, context, results, seed ) { <ide> if ( nodeType === 9 ) { <ide> if ( ( elem = context.getElementById( m ) ) ) { <ide> results.push( elem ); <del> return results; <del> } else { <del> return results; <ide> } <add> return results; <ide> <ide> // Element context <ide> } else { <ide> function testContext( context ) { <ide> /** <ide> * Sets document-related variables once based on the current document <ide> * @param {Element|Object} [node] An element or document object to use to set the document <del> * @returns {Object} Returns the current document <ide> */ <ide> function setDocument( node ) { <ide> var subWindow, <ide> doc = node ? node.ownerDocument || node : preferredDoc; <ide> <ide> // Return early if doc is invalid or already selected <del> if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { <del> return document; <add> if ( doc === document || doc.nodeType !== 9 ) { <add> return; <ide> } <ide> <ide> // Update global variables <ide> document = doc; <del> docElem = document.documentElement; <add> documentElement = document.documentElement; <ide> documentIsHTML = !jQuery.isXMLDoc( document ); <ide> <ide> // Support: IE 9 - 11+, Edge 12 - 18+ <ide> function setDocument( node ) { <ide> // Support: IE 9 - 11+, Edge 12 - 18+ <ide> subWindow.addEventListener( "unload", unloadHandler ); <ide> } <del> <del> // ID filter and find <del> Expr.filter.ID = function( id ) { <del> var attrId = id.replace( runescape, funescape ); <del> return function( elem ) { <del> return elem.getAttribute( "id" ) === attrId; <del> }; <del> }; <del> Expr.find.ID = function( id, context ) { <del> if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { <del> var elem = context.getElementById( id ); <del> return elem ? [ elem ] : []; <del> } <del> }; <del> <del> // Tag <del> Expr.find.TAG = function( tag, context ) { <del> if ( typeof context.getElementsByTagName !== "undefined" ) { <del> return context.getElementsByTagName( tag ); <del> <del> // DocumentFragment nodes don't have gEBTN <del> } else { <del> return context.querySelectorAll( tag ); <del> } <del> }; <del> <del> // Class <del> Expr.find.CLASS = function( className, context ) { <del> if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { <del> return context.getElementsByClassName( className ); <del> } <del> }; <del> <del> /* QSA/matchesSelector <del> ---------------------------------------------------------------------- */ <del> <del> // QSA and matchesSelector support <del> <del> rbuggyQSA = []; <del> <del> var testEl = document.createElement( "fieldset" ); <del> <del> testEl.innerHTML = "<a href='' disabled='disabled'></a>" + <del> "<select disabled='disabled'><option/></select>"; <del> <del> // Support: Windows 8 Native Apps <del> // The type and name attributes are restricted during .innerHTML assignment <del> var input = document.createElement( "input" ); <del> input.setAttribute( "type", "hidden" ); <del> testEl.appendChild( input ).setAttribute( "name", "D" ); <del> <del> // Support: Chrome 74+ <del> // :enabled/:disabled and hidden elements (hidden elements are still enabled) <del> if ( testEl.querySelectorAll( ":enabled" ).length !== 2 ) { <del> rbuggyQSA.push( ":enabled", ":disabled" ); <del> } <del> <del> // Support: IE 9 - 11+ <del> // IE's :disabled selector does not pick up the children of disabled fieldsets <del> docElem.appendChild( testEl ).disabled = true; <del> if ( testEl.querySelectorAll( ":disabled" ).length !== 2 ) { <del> rbuggyQSA.push( ":enabled", ":disabled" ); <del> } <del> <del> docElem.removeChild( testEl ); <del> <del> matches = docElem.matches || docElem.msMatchesSelector; <del> <del> rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); <del> <del> return document; <ide> } <ide> <ide> find.matches = function( expr, elements ) { <ide> Expr = jQuery.expr = { <ide> <ide> match: matchExpr, <ide> <del> find: {}, <add> find: { <add> ID: function( id, context ) { <add> if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { <add> var elem = context.getElementById( id ); <add> return elem ? [ elem ] : []; <add> } <add> }, <add> <add> TAG: function( tag, context ) { <add> if ( typeof context.getElementsByTagName !== "undefined" ) { <add> return context.getElementsByTagName( tag ); <add> <add> // DocumentFragment nodes don't have gEBTN <add> } else { <add> return context.querySelectorAll( tag ); <add> } <add> }, <add> <add> CLASS: function( className, context ) { <add> if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { <add> return context.getElementsByClassName( className ); <add> } <add> } <add> }, <ide> <ide> relative: { <ide> ">": { dir: "parentNode", first: true }, <ide> Expr = jQuery.expr = { <ide> }, <ide> <ide> preFilter: { <del> "ATTR": function( match ) { <add> ATTR: function( match ) { <ide> match[ 1 ] = match[ 1 ].replace( runescape, funescape ); <ide> <ide> // Move the given value to match[3] whether quoted or unquoted <ide> Expr = jQuery.expr = { <ide> return match.slice( 0, 4 ); <ide> }, <ide> <del> "CHILD": function( match ) { <add> CHILD: function( match ) { <ide> <ide> /* matches from matchExpr["CHILD"] <ide> 1 type (only|nth|...) <ide> Expr = jQuery.expr = { <ide> return match; <ide> }, <ide> <del> "PSEUDO": function( match ) { <add> PSEUDO: function( match ) { <ide> var excess, <ide> unquoted = !match[ 6 ] && match[ 2 ]; <ide> <ide> Expr = jQuery.expr = { <ide> }, <ide> <ide> filter: { <add> ID: function( id ) { <add> var attrId = id.replace( runescape, funescape ); <add> return function( elem ) { <add> return elem.getAttribute( "id" ) === attrId; <add> }; <add> }, <ide> <del> "TAG": function( nodeNameSelector ) { <add> TAG: function( nodeNameSelector ) { <ide> var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); <ide> return nodeNameSelector === "*" ? <ide> function() { <ide> Expr = jQuery.expr = { <ide> }; <ide> }, <ide> <del> "CLASS": function( className ) { <add> CLASS: function( className ) { <ide> var pattern = classCache[ className + " " ]; <ide> <ide> return pattern || <ide> Expr = jQuery.expr = { <ide> } ); <ide> }, <ide> <del> "ATTR": function( name, operator, check ) { <add> ATTR: function( name, operator, check ) { <ide> return function( elem ) { <ide> var result = jQuery.attr( elem, name ); <ide> <ide> Expr = jQuery.expr = { <ide> }; <ide> }, <ide> <del> "CHILD": function( type, what, _argument, first, last ) { <add> CHILD: function( type, what, _argument, first, last ) { <ide> var simple = type.slice( 0, 3 ) !== "nth", <ide> forward = type.slice( -4 ) !== "last", <ide> ofType = what === "of-type"; <ide> Expr = jQuery.expr = { <ide> }; <ide> }, <ide> <del> "PSEUDO": function( pseudo, argument ) { <add> PSEUDO: function( pseudo, argument ) { <ide> <ide> // pseudo-class names are case-insensitive <ide> // http://www.w3.org/TR/selectors/#pseudo-classes <ide> Expr = jQuery.expr = { <ide> pseudos: { <ide> <ide> // Potentially complex pseudos <del> "not": markFunction( function( selector ) { <add> not: markFunction( function( selector ) { <ide> <ide> // Trim the selector passed to compile <ide> // to avoid treating leading and trailing <ide> Expr = jQuery.expr = { <ide> }; <ide> } ), <ide> <del> "has": markFunction( function( selector ) { <add> has: markFunction( function( selector ) { <ide> return function( elem ) { <ide> return find( selector, elem ).length > 0; <ide> }; <ide> } ), <ide> <del> "contains": markFunction( function( text ) { <add> contains: markFunction( function( text ) { <ide> text = text.replace( runescape, funescape ); <ide> return function( elem ) { <ide> return ( elem.textContent || jQuery.text( elem ) ).indexOf( text ) > -1; <ide> Expr = jQuery.expr = { <ide> // The matching of C against the element's language value is performed case-insensitively. <ide> // The identifier C does not have to be a valid language name." <ide> // http://www.w3.org/TR/selectors/#lang-pseudo <del> "lang": markFunction( function( lang ) { <add> lang: markFunction( function( lang ) { <ide> <ide> // lang value must be a valid identifier <ide> if ( !ridentifier.test( lang || "" ) ) { <ide> Expr = jQuery.expr = { <ide> } ), <ide> <ide> // Miscellaneous <del> "target": function( elem ) { <add> target: function( elem ) { <ide> var hash = window.location && window.location.hash; <ide> return hash && hash.slice( 1 ) === elem.id; <ide> }, <ide> <del> "root": function( elem ) { <del> return elem === docElem; <add> root: function( elem ) { <add> return elem === documentElement; <ide> }, <ide> <del> "focus": function( elem ) { <add> focus: function( elem ) { <ide> return elem === document.activeElement && <del> ( !document.hasFocus || document.hasFocus() ) && <add> document.hasFocus() && <ide> !!( elem.type || elem.href || ~elem.tabIndex ); <ide> }, <ide> <ide> // Boolean properties <del> "enabled": createDisabledPseudo( false ), <del> "disabled": createDisabledPseudo( true ), <add> enabled: createDisabledPseudo( false ), <add> disabled: createDisabledPseudo( true ), <ide> <del> "checked": function( elem ) { <add> checked: function( elem ) { <ide> <ide> // In CSS3, :checked should return both checked and selected elements <ide> // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked <ide> Expr = jQuery.expr = { <ide> ( nodeName === "option" && !!elem.selected ); <ide> }, <ide> <del> "selected": function( elem ) { <add> selected: function( elem ) { <ide> <ide> // Support: IE <=11+ <ide> // Accessing the selectedIndex property <ide> Expr = jQuery.expr = { <ide> }, <ide> <ide> // Contents <del> "empty": function( elem ) { <add> empty: function( elem ) { <ide> <ide> // http://www.w3.org/TR/selectors/#empty-pseudo <ide> // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), <ide> Expr = jQuery.expr = { <ide> return true; <ide> }, <ide> <del> "parent": function( elem ) { <add> parent: function( elem ) { <ide> return !Expr.pseudos.empty( elem ); <ide> }, <ide> <ide> // Element/input types <del> "header": function( elem ) { <add> header: function( elem ) { <ide> return rheader.test( elem.nodeName ); <ide> }, <ide> <del> "input": function( elem ) { <add> input: function( elem ) { <ide> return rinputs.test( elem.nodeName ); <ide> }, <ide> <del> "button": function( elem ) { <add> button: function( elem ) { <ide> var name = elem.nodeName.toLowerCase(); <ide> return name === "input" && elem.type === "button" || name === "button"; <ide> }, <ide> <del> "text": function( elem ) { <add> text: function( elem ) { <ide> return elem.nodeName.toLowerCase() === "input" && <ide> elem.type === "text"; <ide> }, <ide> <ide> // Position-in-collection <del> "first": createPositionalPseudo( function() { <add> first: createPositionalPseudo( function() { <ide> return [ 0 ]; <ide> } ), <ide> <del> "last": createPositionalPseudo( function( _matchIndexes, length ) { <add> last: createPositionalPseudo( function( _matchIndexes, length ) { <ide> return [ length - 1 ]; <ide> } ), <ide> <del> "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { <add> eq: createPositionalPseudo( function( _matchIndexes, length, argument ) { <ide> return [ argument < 0 ? argument + length : argument ]; <ide> } ), <ide> <del> "even": createPositionalPseudo( function( matchIndexes, length ) { <add> even: createPositionalPseudo( function( matchIndexes, length ) { <ide> var i = 0; <ide> for ( ; i < length; i += 2 ) { <ide> matchIndexes.push( i ); <ide> } <ide> return matchIndexes; <ide> } ), <ide> <del> "odd": createPositionalPseudo( function( matchIndexes, length ) { <add> odd: createPositionalPseudo( function( matchIndexes, length ) { <ide> var i = 1; <ide> for ( ; i < length; i += 2 ) { <ide> matchIndexes.push( i ); <ide> } <ide> return matchIndexes; <ide> } ), <ide> <del> "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { <add> lt: createPositionalPseudo( function( matchIndexes, length, argument ) { <ide> var i; <ide> <ide> if ( argument < 0 ) { <ide> Expr = jQuery.expr = { <ide> return matchIndexes; <ide> } ), <ide> <del> "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { <add> gt: createPositionalPseudo( function( matchIndexes, length, argument ) { <ide> var i = argument < 0 ? argument + length : argument; <ide> for ( ; ++i < length; ) { <ide> matchIndexes.push( i ); <ide> setDocument(); <ide> <ide> jQuery.find = find; <ide> <del>/* eslint-enable */ <del> <ide> } )(); <ide> <ide> } ); <ide><path>src/selector/rbuggyQSA.js <add>define( [ <add> "../var/document", <add> "../var/isIE" <add>], function( document, isIE ) { <add> <add>"use strict"; <add> <add>var rbuggyQSA = [], <add> testEl = document.createElement( "div" ); <add> <add>testEl.innerHTML = "<a href=''></a>"; <add> <add>// Support: Chrome 38 - 77 only <add>// Chrome considers anchor elements with href to match ":enabled" <add>// See https://bugs.chromium.org/p/chromium/issues/detail?id=993387 <add>if ( testEl.querySelectorAll( ":enabled" ).length ) { <add> rbuggyQSA.push( ":enabled" ); <add>} <add> <add>// Support: IE 9 - 11+ <add>// IE's :disabled selector does not pick up the children of disabled fieldsets <add>if ( isIE ) { <add> rbuggyQSA.push( ":enabled", ":disabled" ); <add>} <add> <add>rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); <add> <add>return rbuggyQSA; <add> <add>} ); <ide><path>test/unit/selector.js <ide> QUnit.test( "pseudo - fieldset:(dis|en)abled", function( assert ) { <ide> QUnit.test( "pseudo - :disabled by ancestry", function( assert ) { <ide> assert.expect( 1 ); <ide> <del> // Don't test for presence of select <del> // IE6 doesn't visibly or functionally disable them when the fieldset is disabled <ide> assert.t( <ide> "Inputs inherit disabled from fieldset", <ide> "#disabled-fieldset :disabled", <ide> QUnit.test( "pseudo - :disabled by ancestry", function( assert ) { <ide> ); <ide> } ); <ide> <add>QUnit.test( "pseudo - a:(dis|en)abled", function( assert ) { <add> assert.expect( 2 ); <add> <add> var enabled, disabled, <add> container = jQuery( "<div/>" ), <add> anchor = jQuery( "<a href='#'>Link</a>" ); <add> <add> container.appendTo( "#qunit-fixture" ); <add> <add> enabled = container.find( "a:enabled" ); <add> disabled = container.find( "a:disabled" ); <add> <add> assert.strictEqual( enabled.length, 0, ":enabled doesn't match anchor elements" ); <add> assert.strictEqual( disabled.length, 0, ":disabled doesn't match anchor elements" ); <add>} ); <add> <ide> QUnit.test( "pseudo - :target and :root", function( assert ) { <ide> assert.expect( 2 ); <ide>
3
Text
Text
update changelog with vulnerability credits
72fbd48f2a805e789fc574176e7a9a87979418d7
<ide><path>CHANGELOG.md <ide> <a name="1.8.0"></a> <ide> # 1.8.0 nested-vaccination (2020-06-01) <ide> <add>_This release contains a breaking change to resolve a security issue which was discovered by <add>Krzysztof Kotowicz(@koto); and independently by Esben Sparre Andreasen (@esbena) while <add>performing a Variant Analysis of [CVE-2020-11022](https://github.com/advisories/GHSA-gxr4-xjj5-5px2) <add>which itself was found and reported by Masato Kinugawa (@masatokinugawa)._ <add> <ide> ## Bug Fixes <ide> - **jqLite:** <ide> - prevent possible XSS due to regex-based HTML replacement
1
Ruby
Ruby
reuse view_context_class when possible
94643fde8f5f2a47faede2c1bdd1b4b786e2685f
<ide><path>actionview/lib/action_view/rendering.rb <ide> def _routes <ide> def _helpers <ide> end <ide> <add> def inherit_view_context_class? <add> superclass.respond_to?(:view_context_class) && <add> supports_path? == superclass.supports_path? && <add> _routes.equal?(superclass._routes) && <add> _helpers.equal?(superclass._helpers) <add> end <add> <ide> def build_view_context_class(klass, supports_path, routes, helpers) <add> if inherit_view_context_class? <add> return superclass.view_context_class <add> end <add> <ide> Class.new(klass) do <ide> if routes <ide> include routes.url_helpers(supports_path)
1
Python
Python
add missing tests for bool scalar conversion
db0041d3a8db8594ddbeed654103a036f5aaa35c
<ide><path>numpy/core/tests/test_multiarray.py <ide> def test_array_scalar_relational_operation(self): <ide> assert_(np.array(-1, dtype=dt1) == np.array(-1, dtype=dt2), <ide> "type %s and %s failed" % (dt1, dt2)) <ide> <add> def test_to_bool_scalar(self): <add> assert_equal(bool(np.array([False])), False) <add> assert_equal(bool(np.array([True])), True) <add> assert_equal(bool(np.array([[42]])), True) <add> assert_raises(ValueError, bool, np.array([1, 2])) <add> <add> class NotConvertible(object): <add> def __bool__(self): <add> raise NotImplementedError <add> __nonzero__ = __bool__ # python 2 <add> <add> assert_raises(NotImplementedError, bool, np.array(NotConvertible())) <add> assert_raises(NotImplementedError, bool, np.array([NotConvertible()])) <add> <add> self_containing = np.array([None]) <add> self_containing[0] = self_containing <add> try: <add> Error = RecursionError <add> except NameError: <add> Error = RuntimeError # python < 3.5 <add> assert_raises(Error, bool, self_containing) # previously stack overflow <add> <ide> <ide> class TestWhere(TestCase): <ide> def test_basic(self):
1
Text
Text
use normal email format
25e4fe185407bf0ed490b08ec5698295583786df
<ide><path>CONTRIBUTING.md <ide> Feel free to ask us questions on the related issue threads, and we will be glad <ide> | Ahmad Abdolsaheb | [`@ahmadabdolsaheb`](https://github.com/ahmadabdolsaheb) | [`@Abdolsaheb`](https://twitter.com/Abdolsaheb) | <ide> | Kristofer Koishigawa | [`@scissorsneedfoodtoo`](https://github.com/scissorsneedfoodtoo) | [`@kriskoishigawa`](https://twitter.com/kriskoishigawa) | <ide> <del>> **Email: `dev at freecodecamp dot org`** <add>> **Email: `dev@freecodecamp.org`** <ide> <ide> ## Frequently Asked Questions <ide>
1
Python
Python
fix typo in docstrings
cd82fc3adab4d88de805a90bb20ec6207a28b310
<ide><path>airflow/api_connexion/schemas/task_instance_schema.py <ide> def get_attribute(self, obj, attr, default): <ide> <ide> <ide> class TaskInstanceReferenceCollection(NamedTuple): <del> """List of objects with meatadata about taskinstance and dag_run_id""" <add> """List of objects with metadata about taskinstance and dag_run_id""" <ide> <ide> task_instances: List[Tuple[TaskInstance, str]] <ide>
1
Python
Python
add tests for default email backend
b14da32464cd0f8feec4a328d8793fcad1fdb05d
<ide><path>tests/core.py <ide> import re <ide> import unittest <ide> import mock <add>import tempfile <ide> from datetime import datetime, time, timedelta <add>from email.mime.multipart import MIMEMultipart <add>from email.mime.application import MIMEApplication <add>import errno <ide> from time import sleep <ide> <ide> from dateutil.relativedelta import relativedelta <ide> def test_custom_backend(self, mock_send_email): <ide> assert not mock_send_email.called <ide> <ide> <add>class EmailSmtpTest(unittest.TestCase): <add> <add> def setUp(self): <add> configuration.set('smtp', 'SMTP_SSL', 'False') <add> <add> @mock.patch('airflow.utils.send_MIME_email') <add> def test_send_smtp(self, mock_send_mime): <add> attachment = tempfile.NamedTemporaryFile() <add> attachment.write(b'attachment') <add> attachment.seek(0) <add> utils.send_email_smtp('to', 'subject', 'content', files=[attachment.name]) <add> assert mock_send_mime.called <add> call_args = mock_send_mime.call_args[0] <add> assert call_args[0] == configuration.get('smtp', 'SMTP_MAIL_FROM') <add> assert call_args[1] == ['to'] <add> msg = call_args[2] <add> assert msg['Subject'] == 'subject' <add> assert msg['From'] == configuration.get('smtp', 'SMTP_MAIL_FROM') <add> assert len(msg.get_payload()) == 2 <add> mimeapp = MIMEApplication('attachment') <add> assert msg.get_payload()[-1].get_payload() == mimeapp.get_payload() <add> <add> @mock.patch('smtplib.SMTP_SSL') <add> @mock.patch('smtplib.SMTP') <add> def test_send_mime(self, mock_smtp, mock_smtp_ssl): <add> mock_smtp.return_value = mock.Mock() <add> mock_smtp_ssl.return_value = mock.Mock() <add> msg = MIMEMultipart() <add> utils.send_MIME_email('from', 'to', msg, dryrun=False) <add> mock_smtp.assert_called_with( <add> configuration.get('smtp', 'SMTP_HOST'), <add> configuration.getint('smtp', 'SMTP_PORT'), <add> ) <add> assert mock_smtp.return_value.starttls.called <add> mock_smtp.return_value.login.assert_called_with( <add> configuration.get('smtp', 'SMTP_USER'), <add> configuration.get('smtp', 'SMTP_PASSWORD'), <add> ) <add> mock_smtp.return_value.sendmail.assert_called_with('from', 'to', msg.as_string()) <add> assert mock_smtp.return_value.quit.called <add> <add> @mock.patch('smtplib.SMTP_SSL') <add> @mock.patch('smtplib.SMTP') <add> def test_send_mime_ssl(self, mock_smtp, mock_smtp_ssl): <add> configuration.set('smtp', 'SMTP_SSL', 'True') <add> mock_smtp.return_value = mock.Mock() <add> mock_smtp_ssl.return_value = mock.Mock() <add> utils.send_MIME_email('from', 'to', MIMEMultipart(), dryrun=False) <add> assert not mock_smtp.called <add> mock_smtp_ssl.assert_called_with( <add> configuration.get('smtp', 'SMTP_HOST'), <add> configuration.getint('smtp', 'SMTP_PORT'), <add> ) <add> <add> @mock.patch('smtplib.SMTP_SSL') <add> @mock.patch('smtplib.SMTP') <add> def test_send_mime_dryrun(self, mock_smtp, mock_smtp_ssl): <add> utils.send_MIME_email('from', 'to', MIMEMultipart(), dryrun=True) <add> assert not mock_smtp.called <add> assert not mock_smtp_ssl.called <add> <add> <ide> if 'AIRFLOW_RUNALL_TESTS' in os.environ: <ide> <ide>
1
Javascript
Javascript
stabilize hmr tests on ci
bc845f2206a6cb5c12838f89656fd649272c92b0
<ide><path>packages/next/client/dev/error-overlay/hot-dev-client.js <ide> function handleErrors(errors) { <ide> <ide> // Do not attempt to reload now. <ide> // We will reload on next success instead. <add> if (process.env.__NEXT_TEST_MODE) { <add> if (self.__NEXT_HMR_CB) { <add> self.__NEXT_HMR_CB(formatted.errors[0]) <add> self.__NEXT_HMR_CB = null <add> } <add> } <ide> } <ide> <ide> function tryDismissErrorOverlay() { <ide><path>test/acceptance/helpers.js <ide> export async function sandbox(id = nanoid()) { <ide> <ide> console.log('Application re-loaded.') <ide> // Slow down tests a bit: <del> await new Promise(resolve => setTimeout(resolve, 250)) <add> await new Promise(resolve => setTimeout(resolve, 750)) <ide> return false <ide> } <ide> if (status === 'success') { <ide> export async function sandbox(id = nanoid()) { <ide> await new Promise(resolve => setTimeout(resolve, 30)) <ide> } <ide> <del> // Slow down tests a bit: <del> await new Promise(resolve => setTimeout(resolve, 250)) <add> // Slow down tests a bit (we don't know how long re-rendering takes): <add> await new Promise(resolve => setTimeout(resolve, 750)) <ide> return true <ide> }, <ide> async remove(fileName) { <ide> export async function sandbox(id = nanoid()) { <ide> ) <ide> } <ide> }, <add> async getOverlayContent() { <add> await browser.waitForElementByCss('iframe', 10000) <add> const hasIframe = await browser.hasElementByCssSelector('iframe') <add> if (!hasIframe) { <add> throw new Error('Unable to find overlay') <add> } <add> return browser.eval( <add> `document.querySelector('iframe').contentWindow.document.body.innerHTML` <add> ) <add> }, <ide> }, <ide> function cleanup() { <ide> async function _cleanup() {
2
Javascript
Javascript
add test with dynamic indexed access to imports
1237fdedbd0aba40893622347a440a37015610c4
<ide><path>test/cases/parsing/issue-3116/file2.js <add>export default "default"; <add>export var abc = "abc"; <ide><path>test/cases/parsing/issue-3116/index.js <ide> import * as file from "./file"; <add>import * as file2 from "./file2"; <ide> <ide> it("should translate indexed access to harmony import correctly", function() { <ide> file["default"].should.be.eql("default"); <ide> file["abc"].should.be.eql("abc"); <ide> }); <add> <add>it("should translate dynamic indexed access to harmony import correctly", function() { <add> var fault = "fault"; <add> file2["de" + fault].should.be.eql("default"); <add> file2["abc"].should.be.eql("abc"); <add>});
2
Ruby
Ruby
add releasenotes module
e1f73e407ad5e5ac4dcb602625d930235ed49a53
<ide><path>Library/Homebrew/dev-cmd/release-notes.rb <ide> # frozen_string_literal: true <ide> <ide> require "cli/parser" <add>require "release_notes" <ide> <ide> module Homebrew <ide> extend T::Sig <ide> def release_notes <ide> odie "Ref #{ref} does not exist!" <ide> end <ide> <del> output = Utils.popen_read( <del> "git", "-C", HOMEBREW_REPOSITORY, "log", "--pretty=format:'%s >> - %b%n'", "#{previous_tag}..#{end_ref}" <del> ).lines.grep(/Merge pull request/) <del> <del> output.map! do |s| <del> s.gsub(%r{.*Merge pull request #(\d+) from ([^/]+)/[^>]*(>>)*}, <del> "https://github.com/Homebrew/brew/pull/\\1 (@\\2)") <del> end <del> if args.markdown? <del> output.map! do |s| <del> /(.*\d)+ \(@(.+)\) - (.*)/ =~ s <del> "- [#{Regexp.last_match(3)}](#{Regexp.last_match(1)}) (@#{Regexp.last_match(2)})" <del> end <del> end <add> release_notes = ReleaseNotes.generate_release_notes previous_tag, end_ref, markdown: T.must(args.markdown?) <ide> <ide> $stderr.puts "Release notes between #{previous_tag} and #{end_ref}:" <del> if args.markdown? && args.named.first <del> puts "Release notes for major and minor releases can be found in the [Homebrew blog](https://brew.sh/blog/)." <del> end <del> puts output <add> puts release_notes <ide> end <ide> end <ide><path>Library/Homebrew/dev-cmd/release.rb <ide> # frozen_string_literal: true <ide> <ide> require "cli/parser" <add>require "release_notes" <ide> <ide> module Homebrew <ide> extend T::Sig <ide> def release <ide> end <ide> <ide> new_version = if args.major? <del> Version.new [latest_version.major.to_i + 1, 0, 0].join(".") <add> Version.new "#{latest_version.major.to_i + 1}.0.0" <ide> elsif args.minor? <del> Version.new [latest_version.major, latest_version.minor.to_i + 1, 0].join(".") <add> Version.new "#{latest_version.major}.#{latest_version.minor.to_i + 1}.0" <ide> else <del> Version.new [latest_version.major, latest_version.minor, latest_version.patch.to_i + 1].join(".") <add> Version.new "#{latest_version.major}.#{latest_version.minor}.#{latest_version.patch.to_i + 1}" <ide> end.to_s <ide> <ide> ohai "Creating draft release for version #{new_version}" <add> <ide> release_notes = if args.major? || args.minor? <del> ["Release notes for this release can be found on the [Homebrew blog](https://brew.sh/blog/#{new_version})."] <add> "Release notes for this release can be found on the [Homebrew blog](https://brew.sh/blog/#{new_version}).\n" <ide> else <del> [] <del> end <del> release_notes += Utils.popen_read( <del> "git", "-C", HOMEBREW_REPOSITORY, "log", "--pretty=format:'%s >> - %b%n'", "#{latest_version}..origin/HEAD" <del> ).lines.grep(/Merge pull request/).map! do |s| <del> pr = s.gsub(%r{.*Merge pull request #(\d+) from ([^/]+)/[^>]*(>>)*}, <del> "https://github.com/Homebrew/brew/pull/\\1 (@\\2)") <del> /(.*\d)+ \(@(.+)\) - (.*)/ =~ pr <del> "- [#{Regexp.last_match(3)}](#{Regexp.last_match(1)}) (@#{Regexp.last_match(2)})" <add> "" <ide> end <add> release_notes += ReleaseNotes.generate_release_notes latest_version, "origin/HEAD", markdown: true <ide> <ide> begin <del> release = GitHub.create_or_update_release "Homebrew", "brew", new_version, <del> body: release_notes.join("\n"), draft: true <add> release = GitHub.create_or_update_release "Homebrew", "brew", new_version, body: release_notes, draft: true <ide> rescue *GitHub::API_ERRORS => e <ide> odie "Unable to create release: #{e.message}!" <ide> end <ide><path>Library/Homebrew/release_notes.rb <add># typed: true <add># frozen_string_literal: true <add> <add># Helper functions for generating release notes. <add># <add># @api private <add>module ReleaseNotes <add> extend T::Sig <add> <add> module_function <add> <add> sig { <add> params(start_ref: T.any(String, Version), end_ref: T.any(String, Version), markdown: T::Boolean) <add> .returns(String) <add> } <add> def generate_release_notes(start_ref, end_ref, markdown: false) <add> log_output = Utils.popen_read( <add> "git", "-C", HOMEBREW_REPOSITORY, "log", "--pretty=format:'%s >> - %b%n'", "#{start_ref}..#{end_ref}" <add> ).lines.grep(/Merge pull request/) <add> <add> log_output.map! do |s| <add> s.gsub(%r{.*Merge pull request #(\d+) from ([^/]+)/[^>]*(>>)*}, <add> "https://github.com/Homebrew/brew/pull/\\1 (@\\2)") <add> end <add> <add> if markdown <add> log_output.map! do |s| <add> /(.*\d)+ \(@(.+)\) - (.*)/ =~ s <add> "- [#{Regexp.last_match(3)}](#{Regexp.last_match(1)}) (@#{Regexp.last_match(2)})\n" <add> end <add> end <add> <add> log_output.join <add> end <add>end
3
Python
Python
use typeerror instead of attributeerror
850e2ab573d7fac171a364d68371dc57b92112fc
<ide><path>numpy/core/tests/test_dtype.py <add>import sys <ide> import numpy as np <ide> from numpy.testing import * <ide> <ide> def test_dtype_non_writable_attributes_deletion(self): <ide> attr = ["subdtype", "descr", "str", "name", "base", "shape", <ide> "isbuiltin", "isnative", "isalignedstruct", "fields", <ide> "metadata", "hasobject"] <add> <add> if sys.version[:3] == '2.4': <add> error = TypeError <add> else: <add> error = AttributeError <add> <ide> for s in attr: <del> assert_raises(AttributeError, delattr, dt, s) <add> assert_raises(error, delattr, dt, s) <ide> <ide> <ide> def test_dtype_writable_attributes_deletion(self): <ide><path>numpy/core/tests/test_nditer.py <ide> def test_iter_maskna_default_use_maskna(): <ide> assert_array_equal(it.operands[2], a+b+1) <ide> <ide> <del>def test_iter_writable_attribute_deletion(): <add>def test_iter_non_writable_attribute_deletion(): <ide> it = np.nditer(np.ones(2)) <ide> attr = ["value", "shape", "operands", "itviews", "has_delayed_bufalloc", <ide> "iterationneedsapi", "has_multi_index", "has_index", "dtypes", <ide> "ndim", "nop", "itersize", "finished"] <add> <add> if sys.version[:3] == '2.4': <add> error = TypeError <add> else: <add> error = AttributeError <add> <ide> for s in attr: <del> assert_raises(AttributeError, delattr, it, s) <add> assert_raises(error, delattr, it, s) <ide> <ide> <del>def test_iter_non_writable_attribute_deletion(): <add>def test_iter_writable_attribute_deletion(): <ide> it = np.nditer(np.ones(2)) <ide> attr = [ "multi_index", "index", "iterrange", "iterindex"] <ide> for s in attr:
2
Text
Text
fix root example
98ad3aba7a45797ea0cb9faeca54604a39af5b99
<ide><path>README.md <ide> export default class Counter { <ide> ```js <ide> import React from 'react'; <ide> import { root } from 'redux'; <del>import * from './stores/index'; <add>import * as stores from './stores/index'; <ide> <ide> // Let it know about all the stores <ide> @root(stores)
1
Ruby
Ruby
remove dead code, and the tests for it
b9a9b91a3e3b892ab72ff5c618181747d6b4be04
<ide><path>actionpack/lib/action_view/compiled_templates.rb <del>module ActionView <del> <del> # CompiledTemplates modules hold methods that have been compiled. <del> # Templates are compiled into these methods so that they do not need to be <del> # read and parsed for each request. <del> # <del> # Each template may be compiled into one or more methods. Each method accepts a given <del> # set of parameters which is used to implement local assigns passing. <del> # <del> # To use a compiled template module, create a new instance and include it into the class <del> # in which you want the template to be rendered. <del> class CompiledTemplates < Module <del> attr_reader :method_names <del> <del> def initialize <del> @method_names = Hash.new do |hash, key| <del> hash[key] = "__compiled_method_#{(hash.length + 1)}" <del> end <del> @mtimes = {} <del> end <del> <del> # Return the full key for the given identifier and argument names <del> def full_key(identifier, arg_names) <del> [identifier, arg_names] <del> end <del> <del> # Return the selector for this method or nil if it has not been compiled <del> def selector(identifier, arg_names) <del> key = full_key(identifier, arg_names) <del> method_names.key?(key) ? method_names[key] : nil <del> end <del> alias :compiled? :selector <del> <del> # Return the time at which the method for the given identifier and argument names was compiled. <del> def mtime(identifier, arg_names) <del> @mtimes[full_key(identifier, arg_names)] <del> end <del> <del> # Compile the provided source code for the given argument names and with the given initial line number. <del> # The identifier should be unique to this source. <del> # <del> # The file_name, if provided will appear in backtraces. If not provided, the file_name defaults <del> # to the identifier. <del> # <del> # This method will return the selector for the compiled version of this method. <del> def compile_source(identifier, arg_names, source, initial_line_number = 0, file_name = nil) <del> file_name ||= identifier <del> name = method_names[full_key(identifier, arg_names)] <del> arg_desc = arg_names.empty? ? '' : "(#{arg_names * ', '})" <del> fake_file_name = "#{file_name}#{arg_desc}" # Include the arguments for this version (for now) <del> <del> method_def = wrap_source(name, arg_names, source) <del> <del> begin <del> module_eval(method_def, fake_file_name, initial_line_number) <del> @mtimes[full_key(identifier, arg_names)] = Time.now <del> rescue Exception => e # errors from compiled source <del> e.blame_file! identifier <del> raise <del> end <del> name <del> end <del> <del> # Wrap the provided source in a def ... end block. <del> def wrap_source(name, arg_names, source) <del> "def #{name}(#{arg_names * ', '})\n#{source}\nend" <del> end <del> end <del>end <ide><path>actionpack/test/template/compiled_templates_test.rb <del>require 'abstract_unit' <del>require 'action_view/helpers/date_helper' <del>require 'action_view/compiled_templates' <del> <del>class CompiledTemplateTests < Test::Unit::TestCase <del> def setup <del> @ct = ActionView::CompiledTemplates.new <del> @v = Class.new <del> @v.send :include, @ct <del> @a = './test_compile_template_a.rhtml' <del> @b = './test_compile_template_b.rhtml' <del> @s = './test_compile_template_link.rhtml' <del> end <del> def teardown <del> [@a, @b, @s].each do |f| <del> FileUtils.rm(f) if File.exist?(f) || File.symlink?(f) <del> end <del> end <del> attr_reader :ct, :v <del> <del> def test_name_allocation <del> hi_world = ct.method_names['hi world'] <del> hi_sexy = ct.method_names['hi sexy'] <del> wish_upon_a_star = ct.method_names['I love seeing decent error messages'] <del> <del> assert_equal hi_world, ct.method_names['hi world'] <del> assert_equal hi_sexy, ct.method_names['hi sexy'] <del> assert_equal wish_upon_a_star, ct.method_names['I love seeing decent error messages'] <del> assert_equal 3, [hi_world, hi_sexy, wish_upon_a_star].uniq.length <del> end <del> <del> def test_wrap_source <del> assert_equal( <del> "def aliased_assignment(value)\nself.value = value\nend", <del> @ct.wrap_source(:aliased_assignment, [:value], 'self.value = value') <del> ) <del> <del> assert_equal( <del> "def simple()\nnil\nend", <del> @ct.wrap_source(:simple, [], 'nil') <del> ) <del> end <del> <del> def test_compile_source_single_method <del> selector = ct.compile_source('doubling method', [:a], 'a + a') <del> assert_equal 2, @v.new.send(selector, 1) <del> assert_equal 4, @v.new.send(selector, 2) <del> assert_equal -4, @v.new.send(selector, -2) <del> assert_equal 0, @v.new.send(selector, 0) <del> selector <del> end <del> <del> def test_compile_source_two_method <del> sel1 = test_compile_source_single_method # compile the method in the other test <del> sel2 = ct.compile_source('doubling method', [:a, :b], 'a + b + a + b') <del> assert_not_equal sel1, sel2 <del> <del> assert_equal 2, @v.new.send(sel1, 1) <del> assert_equal 4, @v.new.send(sel1, 2) <del> <del> assert_equal 6, @v.new.send(sel2, 1, 2) <del> assert_equal 32, @v.new.send(sel2, 15, 1) <del> end <del> <del> def test_mtime <del> t1 = Time.now <del> <del> test_compile_source_single_method <del> mtime = ct.mtime('doubling method', [:a]) <del> <del> assert mtime < Time.now <del> assert mtime > t1 <del> end <del> <del> uses_mocha 'test_compile_time' do <del> <del> def test_compile_time <del> t = Time.now <del> <del> File.open(@a, "w"){|f| f.puts @a} <del> File.open(@b, "w"){|f| f.puts @b} <del> # windows doesn't support symlinks (even under cygwin) <del> windows = (RUBY_PLATFORM =~ /win32/) <del> `ln -s #{@a} #{@s}` unless windows <del> <del> v = ActionView::Base.new <del> v.base_path = '.' <del> v.cache_template_loading = false <del> <del> ta = ActionView::Template.new(v, @a, false, {}) <del> tb = ActionView::Template.new(v, @b, false, {}) <del> ts = ActionView::Template.new(v, @s, false, {}) <del> <del> @handler_class = ActionView::Template.handler_class_for_extension(:rhtml) <del> @handler = @handler_class.new(v) <del> <del> # All templates were created at t+1 <del> File::Stat.any_instance.expects(:mtime).times(windows ? 2 : 3).returns(t + 1.second) <del> <del> # private methods template_changed_since? and compile_template? <del> # should report true for all since they have not been compiled <del> assert @handler.send(:template_changed_since?, @a, t) <del> assert @handler.send(:template_changed_since?, @b, t) <del> assert @handler.send(:template_changed_since?, @s, t) unless windows <del> <del> assert @handler.send(:compile_template?, ta) <del> assert @handler.send(:compile_template?, tb) <del> assert @handler.send(:compile_template?, ts) unless windows <del> <del> # All templates are rendered at t+2 <del> Time.expects(:now).times(windows ? 2 : 3).returns(t + 2.seconds) <del> v.send(:render_template, ta) <del> v.send(:render_template, tb) <del> v.send(:render_template, ts) unless windows <del> a_n = v.method_names[@a] <del> b_n = v.method_names[@b] <del> s_n = v.method_names[@s] unless windows <del> # all of the files have changed since last compile <del> assert @handler.compile_time[a_n] > t <del> assert @handler.compile_time[b_n] > t <del> assert @handler.compile_time[s_n] > t unless windows <del> <del> # private methods template_changed_since? and compile_template? <del> # should report false for all since none have changed since compile <del> File::Stat.any_instance.expects(:mtime).times(windows ? 6 : 12).returns(t + 1.second) <del> assert !@handler.send(:template_changed_since?, @a, @handler.compile_time[a_n]) <del> assert !@handler.send(:template_changed_since?, @b, @handler.compile_time[b_n]) <del> assert !@handler.send(:template_changed_since?, @s, @handler.compile_time[s_n]) unless windows <del> assert !@handler.send(:compile_template?, ta) <del> assert !@handler.send(:compile_template?, tb) <del> assert !@handler.send(:compile_template?, ts) unless windows <del> v.send(:render_template, ta) <del> v.send(:render_template, tb) <del> v.send(:render_template, ts) unless windows <del> # none of the files have changed since last compile <del> assert @handler.compile_time[a_n] < t + 3.seconds <del> assert @handler.compile_time[b_n] < t + 3.seconds <del> assert @handler.compile_time[s_n] < t + 3.seconds unless windows <del> <del> `rm #{@s}; ln -s #{@b} #{@s}` unless windows <del> # private methods template_changed_since? and compile_template? <del> # should report true for symlink since it has changed since compile <del> <del> # t + 3.seconds is for the symlink <del> File::Stat.any_instance.expects(:mtime).times(windows ? 6 : 9).returns( <del> *(windows ? [ t + 1.second, t + 1.second ] : <del> [ t + 1.second, t + 1.second, t + 3.second ]) * 3) <del> assert !@handler.send(:template_changed_since?, @a, @handler.compile_time[a_n]) <del> assert !@handler.send(:template_changed_since?, @b, @handler.compile_time[b_n]) <del> assert @handler.send(:template_changed_since?, @s, @handler.compile_time[s_n]) unless windows <del> assert !@handler.send(:compile_template?, ta) <del> assert !@handler.send(:compile_template?, tb) <del> assert @handler.send(:compile_template?, ts) unless windows <del> <del> # Only the symlink template gets rendered at t+3 <del> Time.stubs(:now).returns(t + 3.seconds) unless windows <del> v.send(:render_template, ta) <del> v.send(:render_template, tb) <del> v.send(:render_template, ts) unless windows <del> # the symlink has changed since last compile <del> assert @handler.compile_time[a_n] < t + 3.seconds <del> assert @handler.compile_time[b_n] < t + 3.seconds <del> assert_equal @handler.compile_time[s_n], t + 3.seconds unless windows <del> <del> FileUtils.touch @b <del> # private methods template_changed_since? and compile_template? <del> # should report true for symlink and file at end of symlink <del> # since it has changed since last compile <del> # <del> # t+4 is for @b and also for the file that @s points to, which is @b <del> File::Stat.any_instance.expects(:mtime).times(windows ? 6 : 12).returns( <del> *(windows ? [ t + 1.second, t + 4.seconds ] : <del> [ t + 1.second, t + 4.seconds, t + 3.second, t + 4.seconds ]) * 3) <del> assert !@handler.send(:template_changed_since?, @a, @handler.compile_time[a_n]) <del> assert @handler.send(:template_changed_since?, @b, @handler.compile_time[b_n]) <del> assert @handler.send(:template_changed_since?, @s, @handler.compile_time[s_n]) unless windows <del> assert !@handler.send(:compile_template?, ta) <del> assert @handler.send(:compile_template?, tb) <del> assert @handler.send(:compile_template?, ts) unless windows <del> <del> Time.expects(:now).times(windows ? 1 : 2).returns(t + 5.seconds) <del> v.send(:render_template, ta) <del> v.send(:render_template, tb) <del> v.send(:render_template, ts) unless windows <del> # the file at the end of the symlink has changed since last compile <del> # both the symlink and the file at the end of it should be recompiled <del> assert @handler.compile_time[a_n] < t + 5.seconds <del> assert_equal @handler.compile_time[b_n], t + 5.seconds <del> assert_equal @handler.compile_time[s_n], t + 5.seconds unless windows <del> end <del> end <del>end
2
Ruby
Ruby
add check for stray .pc files
f4cd85aa49160d2223d40de12fb0cf719fed1108
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_for_stray_static_libs <ide> puts <ide> end <ide> <add>def check_for_stray_pcs <add> unbrewed_pcs = Dir['/usr/local/lib/pkgconfig/*.pc'].select { |f| File.file? f and not File.symlink? f } <add> <add> # Package-config files which are generally OK should be added to this list, <add> # with a short description of the software they come with. <add> white_list = { <add> "fuse.pc" => "MacFuse", <add> } <add> <add> bad_pcs = unbrewed_pcs.reject {|d| white_list.key? File.basename(d) } <add> return if bad_pcs.empty? <add> <add> puts <<-EOS.undent <add> Unbrewed .pc files were found in /usr/local/lib/pkgconfig. <add> <add> If you didn't put them there on purpose they could cause problems when <add> building Homebrew formulae, and may need to be deleted. <add> <add> Unexpected .pc files: <add> EOS <add> puts *bad_pcs.collect { |f| " #{f}" } <add> puts <add>end <add> <ide> def check_for_x11 <ide> unless x11_installed? <ide> puts <<-EOS.undent <ide> def doctor <ide> check_for_macgpg2 <ide> check_for_stray_dylibs <ide> check_for_stray_static_libs <add> check_for_stray_pcs <ide> check_gcc_versions <ide> check_for_other_package_managers <ide> check_for_x11
1
Python
Python
fix minor typo in configuration.py
2b10680a2f5188400459089713876c1ce49f1caf
<ide><path>airflow/configuration.py <ide> def getimport(self, section, key, **kwargs): <ide> """ <ide> Reads options, imports the full qualified name, and returns the object. <ide> <del> In case of failure, it throws an exception a clear message with the key aad the section names <add> In case of failure, it throws an exception with the key and section names <ide> <ide> :return: The object or None, if the option is empty <ide> """
1
Go
Go
use gotest.tools compare and assert.check
38b0c47f37fec8fbf104ae90b48d8b5b263f8e28
<ide><path>integration-cli/docker_cli_links_test.go <ide> import ( <ide> <ide> "github.com/docker/docker/runconfig" <ide> "gotest.tools/v3/assert" <del> "gotest.tools/v3/assert/cmp" <add> is "gotest.tools/v3/assert/cmp" <ide> ) <ide> <ide> type DockerCLILinksSuite struct { <ide> func (s *DockerCLILinksSuite) TestLinksInvalidContainerTarget(c *testing.T) { <ide> out, _, err := dockerCmdWithError("run", "--link", "bogus:alias", "busybox", "true") <ide> <ide> // an invalid container target should produce an error <del> assert.Assert(c, err != nil, "out: %s", out) <del> // an invalid container target should produce an error <del> // note: convert the output to lowercase first as the error string <del> // capitalization was changed after API version 1.32 <del> assert.Assert(c, strings.Contains(strings.ToLower(out), "could not get container")) <add> assert.Check(c, is.ErrorContains(err, "could not get container for bogus")) <add> assert.Check(c, is.Contains(out, "could not get container")) <ide> } <ide> <ide> func (s *DockerCLILinksSuite) TestLinksPingLinkedContainers(c *testing.T) { <ide> func (s *DockerCLILinksSuite) TestLinksHostsFilesInject(c *testing.T) { <ide> readContainerFileWithExec(c, idOne, "/etc/hosts") <ide> contentTwo := readContainerFileWithExec(c, idTwo, "/etc/hosts") <ide> // Host is not present in updated hosts file <del> assert.Assert(c, strings.Contains(string(contentTwo), "onetwo")) <add> assert.Assert(c, is.Contains(string(contentTwo), "onetwo")) <ide> } <ide> <ide> func (s *DockerCLILinksSuite) TestLinksUpdateOnRestart(c *testing.T) { <ide> func (s *DockerCLILinksSuite) TestLinksUpdateOnRestart(c *testing.T) { <ide> return string(matches[1]) <ide> } <ide> ip := getIP(content, "one") <del> assert.Equal(c, ip, realIP) <add> assert.Check(c, is.Equal(ip, realIP)) <ide> <ide> ip = getIP(content, "onetwo") <del> assert.Equal(c, ip, realIP) <add> assert.Check(c, is.Equal(ip, realIP)) <ide> <ide> dockerCmd(c, "restart", "one") <ide> realIP = inspectField(c, "one", "NetworkSettings.Networks.bridge.IPAddress") <ide> <ide> content = readContainerFileWithExec(c, id, "/etc/hosts") <ide> ip = getIP(content, "one") <del> assert.Equal(c, ip, realIP) <add> assert.Check(c, is.Equal(ip, realIP)) <ide> <ide> ip = getIP(content, "onetwo") <del> assert.Equal(c, ip, realIP) <add> assert.Check(c, is.Equal(ip, realIP)) <ide> } <ide> <ide> func (s *DockerCLILinksSuite) TestLinksEnvs(c *testing.T) { <ide> testRequires(c, DaemonIsLinux) <ide> dockerCmd(c, "run", "-d", "-e", "e1=", "-e", "e2=v2", "-e", "e3=v3=v3", "--name=first", "busybox", "top") <ide> out, _ := dockerCmd(c, "run", "--name=second", "--link=first:first", "busybox", "env") <del> assert.Assert(c, strings.Contains(out, "FIRST_ENV_e1=\n")) <del> assert.Assert(c, strings.Contains(out, "FIRST_ENV_e2=v2")) <del> assert.Assert(c, strings.Contains(out, "FIRST_ENV_e3=v3=v3")) <add> assert.Assert(c, is.Contains(out, "FIRST_ENV_e1=\n")) <add> assert.Assert(c, is.Contains(out, "FIRST_ENV_e2=v2")) <add> assert.Assert(c, is.Contains(out, "FIRST_ENV_e3=v3=v3")) <ide> } <ide> <ide> func (s *DockerCLILinksSuite) TestLinkShortDefinition(c *testing.T) { <ide> func (s *DockerCLILinksSuite) TestLinksNetworkHostContainer(c *testing.T) { <ide> out, _, err := dockerCmdWithError("run", "--name", "should_fail", "--link", "host_container:tester", "busybox", "true") <ide> <ide> // Running container linking to a container with --net host should have failed <del> assert.Assert(c, err != nil, "out: %s", out) <add> assert.Check(c, err != nil, "out: %s", out) <ide> // Running container linking to a container with --net host should have failed <del> assert.Assert(c, strings.Contains(out, runconfig.ErrConflictHostNetworkAndLinks.Error())) <add> assert.Check(c, is.Contains(out, runconfig.ErrConflictHostNetworkAndLinks.Error())) <ide> } <ide> <ide> func (s *DockerCLILinksSuite) TestLinksEtcHostsRegularFile(c *testing.T) { <ide> testRequires(c, DaemonIsLinux, NotUserNamespace) <ide> out, _ := dockerCmd(c, "run", "--net=host", "busybox", "ls", "-la", "/etc/hosts") <ide> // /etc/hosts should be a regular file <del> assert.Assert(c, cmp.Regexp("^-.+\n$", out)) <add> assert.Assert(c, is.Regexp("^-.+\n$", out)) <ide> } <ide> <ide> func (s *DockerCLILinksSuite) TestLinksMultipleWithSameName(c *testing.T) {
1
Java
Java
allow static modifier on @bean methods
52bef0b7b024e794186437dee78945fbb5bd209a
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/Bean.java <ide> * <ide> * <p>While a {@link #name()} attribute is available, the default strategy for determining <ide> * the name of a bean is to use the name of the Bean method. This is convenient and <del> * intuitive, but if explicit naming is desired, the {@link #name()} attribute may be used. <del> * Also note that {@link #name()} accepts an array of Strings. This is in order to allow <add> * intuitive, but if explicit naming is desired, the {@code name()} attribute may be used. <add> * Also note that {@code name()} accepts an array of Strings. This is in order to allow <ide> * for specifying multiple names (i.e., aliases) for a single bean. <ide> * <ide> * <p>The <code>@Bean</code> annotation may be used on any methods in an <code>@Component</code> <ide> * subclassing of each such configuration class at runtime. As a consequence, configuration <ide> * classes and their factory methods must not be marked as final or private in this mode. <ide> * <add> * <h3>A note on {@code BeanFactoryPostProcessor}-returning {@code @Bean} methods</h3> <add> * <p>Special consideration must be taken for {@code @Bean} methods that return Spring <add> * {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessor} <add> * ({@code BFPP}) types. Because {@code BFPP} objects must be instantiated very early in the <add> * container lifecycle, they can interfere with processing of annotations such as {@code @Autowired}, <add> * {@code @Value}, and {@code @PostConstruct} within {@code @Configuration} classes. To avoid these <add> * lifecycle issues, mark {@code BFPP}-returning {@code @Bean} methods as {@code static}. For example: <add> * <pre class="code"> <add> * &#064;Bean <add> * public static PropertyPlaceholderConfigurer ppc() { <add> * // instantiate, configure and return ppc ... <add> * } <add> * </pre> <add> * By marking this method as {@code static}, it can be invoked without causing instantiation of its <add> * declaring {@code @Configuration} class, thus avoiding the above-mentioned lifecycle conflicts. <add> * Note however that {@code static} {@code @Bean} methods will not be enhanced for scoping and AOP <add> * semantics as mentioned above. This works out in {@code BFPP} cases, as they are not typically <add> * referenced by other {@code @Bean} methods. As a reminder, a WARN-level log message will be <add> * issued for any non-static {@code @Bean} methods having a return type assignable to <add> * {@code BeanFactoryPostProcessor}. <add> * <ide> * @author Rod Johnson <ide> * @author Costin Leau <ide> * @author Chris Beams <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/BeanMethod.java <ide> public BeanMethod(MethodMetadata metadata, ConfigurationClass configurationClass <ide> <ide> @Override <ide> public void validate(ProblemReporter problemReporter) { <add> if (getMetadata().isStatic()) { <add> // static @Bean methods have no constraints to validate -> return immediately <add> return; <add> } <add> <ide> if (this.configurationClass.getMetadata().isAnnotated(Configuration.class.getName())) { <ide> if (!getMetadata().isOverridable()) { <add> // instance @Bean methods within @Configuration classes must be overridable to accommodate CGLIB <ide> problemReporter.error(new NonOverridableMethodError()); <ide> } <ide> } <del> else { <del> if (getMetadata().isStatic()) { <del> problemReporter.error(new StaticMethodError()); <del> } <del> } <ide> } <ide> <del> /** <del> * {@link Bean} methods must be overridable in order to accommodate CGLIB. <del> */ <add> <ide> private class NonOverridableMethodError extends Problem { <ide> <ide> public NonOverridableMethodError() { <del> super(String.format("Method '%s' must not be private, final or static; change the method's modifiers to continue", <del> getMetadata().getMethodName()), getResourceLocation()); <del> } <del> } <del> <del> <del> /** <del> * {@link Bean} methods must at least not be static in the non-CGLIB case. <del> */ <del> private class StaticMethodError extends Problem { <del> <del> public StaticMethodError() { <del> super(String.format("Method '%s' must not be static; remove the method's static modifier to continue", <add> super(String.format("@Bean method '%s' must not be private or final; change the method's modifiers to continue", <ide> getMetadata().getMethodName()), getResourceLocation()); <ide> } <ide> } <del> <ide> } <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java <ide> private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) { <ide> RootBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass); <ide> beanDef.setResource(configClass.getResource()); <ide> beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource())); <del> beanDef.setFactoryBeanName(configClass.getBeanName()); <del> beanDef.setUniqueFactoryMethodName(metadata.getMethodName()); <add> if (metadata.isStatic()) { <add> // static @Bean method <add> beanDef.setBeanClassName(configClass.getMetadata().getClassName()); <add> beanDef.setFactoryMethodName(metadata.getMethodName()); <add> } <add> else { <add> // instance @Bean method <add> beanDef.setFactoryBeanName(configClass.getBeanName()); <add> beanDef.setUniqueFactoryMethodName(metadata.getMethodName()); <add> } <ide> beanDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR); <ide> beanDef.setAttribute(RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE); <ide> <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java <ide> import org.springframework.beans.factory.BeanFactory; <ide> import org.springframework.beans.factory.DisposableBean; <ide> import org.springframework.beans.factory.FactoryBean; <add>import org.springframework.beans.factory.config.BeanFactoryPostProcessor; <ide> import org.springframework.beans.factory.config.ConfigurableBeanFactory; <ide> import org.springframework.core.annotation.AnnotationUtils; <ide> import org.springframework.util.Assert; <ide> public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object <ide> return this.beanFactory.getBean(beanName); <ide> } <ide> <add> if (BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) { <add> logger.warn(String.format("@Bean method %s.%s is non-static and returns an object " + <add> "assignable to Spring's BeanFactoryPostProcessor interface. This will " + <add> "result in a failure to process annotations such as @Autowired, " + <add> "@Resource and @PostConstruct within the method's declaring " + <add> "@Configuration class. Add the 'static' modifier to this method to avoid" + <add> "these container lifecycle issues; see @Bean Javadoc for complete details", <add> beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName())); <add> } <ide> return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs); <ide> } <ide> <ide><path>org.springframework.context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java <add>/* <add> * Copyright 2002-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.context.annotation; <add> <add>import static org.hamcrest.CoreMatchers.not; <add>import static org.hamcrest.CoreMatchers.notNullValue; <add>import static org.hamcrest.CoreMatchers.nullValue; <add>import static org.hamcrest.CoreMatchers.sameInstance; <add>import static org.junit.Assert.assertThat; <add> <add>import org.junit.Test; <add>import org.springframework.beans.BeansException; <add>import org.springframework.beans.TestBean; <add>import org.springframework.beans.factory.annotation.Autowired; <add>import org.springframework.beans.factory.config.BeanFactoryPostProcessor; <add>import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; <add> <add>/** <add> * Tests semantics of declaring {@link BeanFactoryPostProcessor}-returning @Bean <add> * methods, specifically as regards static @Bean methods and the avoidance of <add> * container lifecycle issues when BFPPs are in the mix. <add> * <add> * @author Chris Beams <add> * @since 3.1 <add> */ <add>public class ConfigurationClassAndBFPPTests { <add> <add> @Test <add> public void autowiringFailsWithBFPPAsInstanceMethod() { <add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <add> ctx.register(TestBeanConfig.class, AutowiredConfigWithBFPPAsInstanceMethod.class); <add> ctx.refresh(); <add> // instance method BFPP interferes with lifecycle -> autowiring fails! <add> // WARN-level logging should have been issued about returning BFPP from non-static @Bean method <add> assertThat(ctx.getBean(AutowiredConfigWithBFPPAsInstanceMethod.class).autowiredTestBean, nullValue()); <add> } <add> <add> @Test <add> public void autowiringSucceedsWithBFPPAsStaticMethod() { <add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <add> ctx.register(TestBeanConfig.class, AutowiredConfigWithBFPPAsStaticMethod.class); <add> ctx.refresh(); <add> // static method BFPP does not interfere with lifecycle -> autowiring succeeds <add> assertThat(ctx.getBean(AutowiredConfigWithBFPPAsStaticMethod.class).autowiredTestBean, notNullValue()); <add> } <add> <add> <add> @Configuration <add> static class TestBeanConfig { <add> @Bean <add> public TestBean testBean() { <add> return new TestBean(); <add> } <add> } <add> <add> <add> @Configuration <add> static class AutowiredConfigWithBFPPAsInstanceMethod { <add> @Autowired TestBean autowiredTestBean; <add> <add> @Bean <add> public BeanFactoryPostProcessor bfpp() { <add> return new BeanFactoryPostProcessor() { <add> public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { <add> // no-op <add> } <add> }; <add> } <add> } <add> <add> <add> @Configuration <add> static class AutowiredConfigWithBFPPAsStaticMethod { <add> @Autowired TestBean autowiredTestBean; <add> <add> @Bean <add> public static final BeanFactoryPostProcessor bfpp() { <add> return new BeanFactoryPostProcessor() { <add> public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { <add> // no-op <add> } <add> }; <add> } <add> } <add> <add> <add> @Test <add> @SuppressWarnings("static-access") <add> public void staticBeanMethodsDoNotRespectScoping() { <add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <add> ctx.register(ConfigWithStaticBeanMethod.class); <add> ctx.refresh(); <add> <add> ConfigWithStaticBeanMethod config = ctx.getBean(ConfigWithStaticBeanMethod.class); <add> assertThat(config.testBean(), not(sameInstance(config.testBean()))); <add> } <add> <add> <add> @Configuration <add> static class ConfigWithStaticBeanMethod { <add> @Bean <add> public static TestBean testBean() { <add> return new TestBean("foo"); <add> } <add> } <add> <add> <add>}
5
Text
Text
add a changelog entry for [ci skip]
d39db9da1a7e093f0248c9755fb8333d89dc1724
<ide><path>railties/CHANGELOG.md <add>* `config.assets.raise_runtime_errors` is set to true by default <add> <add> This option has been introduced in <add> [sprockets-rails#100][https://github.com/rails/sprockets-rails/pull/100] <add> and defaults to true in new applications in development. <add> <add> *Richard Schneeman* <add> <ide> * Generates `html` and `text` templates for mailers by default. <ide> <ide> *Kassio Borges*
1
Javascript
Javascript
add config test case
03144929c748f9f9c26a9a109275dd94f3f604ce
<ide><path>test/configCases/chunk-graph/issue-15173/commonAsync/index.js <add>import { commonUtil } from "../commonSync"; <add> <add>export function getCommonAsync() { <add> return commonUtil(); <add>} <ide><path>test/configCases/chunk-graph/issue-15173/commonSync/index.js <add>var EmptyObj = {}; <add> <add>export function commonUtil() { <add> return EmptyObj; <add>} <ide><path>test/configCases/chunk-graph/issue-15173/entries/entryA.js <add>import { commonUtil } from "../commonSync"; <add> <add>export default { <add> doSomethingInEntryA() { <add> return commonUtil("entryA"); <add> }, <add> getFeatureA() { <add> return import(/* webpackChunkName: 'featureA' */ "../featureA"); <add> }, <add> getFeatureB() { <add> return import(/* webpackChunkName: 'featureB' */ "../featureB"); <add> } <add>}; <add> <add>it("common async should contain self only", () => { <add> expect( <add> __STATS__.chunks.find(c => c.names.includes("commonAsync")).modules <add> ).toHaveLength(1); <add>}); <ide><path>test/configCases/chunk-graph/issue-15173/entries/entryB.js <add>import { commonUtil } from "../commonSync"; <add> <add>export default { <add> doSomethingInEntryB() { <add> return commonUtil("entryB"); <add> }, <add> getFeatureC() { <add> return import(/* webpackChunkName: 'featureC' */ "../featureC"); <add> } <add>}; <ide><path>test/configCases/chunk-graph/issue-15173/featureA/index.js <add>import(/* webpackChunkName: 'commonAsync' */ "../commonAsync"); <add> <add>export function getFeatureA() { <add> return "featureA"; <add>} <ide><path>test/configCases/chunk-graph/issue-15173/featureB/index.js <add>import(/* webpackChunkName: 'commonAsync' */ "../commonAsync"); <add> <add>export function getFeatureB() { <add> return "featureB"; <add>} <ide><path>test/configCases/chunk-graph/issue-15173/featureC/index.js <add>import(/* webpackChunkName: 'commonAsync' */ "../commonAsync"); <add> <add>export function getFeatureC() { <add> return "featuraC"; <add>} <ide><path>test/configCases/chunk-graph/issue-15173/test.config.js <add>module.exports = { <add> findBundle: function () { <add> return ["entryA.js"]; <add> } <add>}; <ide><path>test/configCases/chunk-graph/issue-15173/webpack.config.js <add>module.exports = { <add> entry: { <add> entryA: "./entries/entryA.js", <add> entryB: "./entries/entryB.js" <add> }, <add> output: { <add> filename: "[name].js" <add> } <add>};
9
Go
Go
add daemon.startnodewithbusybox function
ead3f4e7c8b7add7beb2de44649b38f41947180f
<ide><path>integration-cli/check_test.go <ide> func (s *DockerSwarmSuite) AddDaemon(c *testing.T, joinSwarm, manager bool) *dae <ide> d.StartAndSwarmInit(c) <ide> } <ide> } else { <del> d.StartNode(c) <add> d.StartNodeWithBusybox(c) <ide> } <ide> <ide> s.daemonsLock.Lock() <ide><path>internal/test/daemon/swarm.go <ide> var ( <ide> startArgs = []string{"--iptables=false", "--swarm-default-advertise-addr=lo"} <ide> ) <ide> <del>// StartNode starts daemon to be used as a swarm node <add>// StartNode (re)starts the daemon <ide> func (d *Daemon) StartNode(t testingT) { <ide> if ht, ok := t.(test.HelperT); ok { <ide> ht.Helper() <ide> } <del> // avoid networking conflicts <add> d.Start(t, startArgs...) <add>} <add> <add>// StartNodeWithBusybox starts daemon to be used as a swarm node, and loads the busybox image <add>func (d *Daemon) StartNodeWithBusybox(t testingT) { <add> if ht, ok := t.(test.HelperT); ok { <add> ht.Helper() <add> } <ide> d.StartWithBusybox(t, startArgs...) <ide> } <ide> <ide> func (d *Daemon) RestartNode(t testingT) { <ide> <ide> // StartAndSwarmInit starts the daemon (with busybox) and init the swarm <ide> func (d *Daemon) StartAndSwarmInit(t testingT) { <del> d.StartNode(t) <add> d.StartNodeWithBusybox(t) <ide> d.SwarmInit(t, swarm.InitRequest{}) <ide> } <ide> <ide> func (d *Daemon) StartAndSwarmJoin(t testingT, leader *Daemon, manager bool) { <ide> if th, ok := t.(test.HelperT); ok { <ide> th.Helper() <ide> } <del> d.StartNode(t) <add> d.StartNodeWithBusybox(t) <ide> <ide> tokens := leader.JoinTokens(t) <ide> token := tokens.Worker
2
Python
Python
add missing import
3a045572ed1608daa90dc92229c2da0524fa7f20
<ide><path>spacy/displacy/__init__.py <ide> """ <ide> from __future__ import unicode_literals <ide> <add>import warnings <add> <ide> from .render import DependencyRenderer, EntityRenderer <ide> from ..tokens import Doc, Span <ide> from ..compat import b_to_str
1
Ruby
Ruby
update version tests
4ae8029557cc3eba6dc99c1183a02c1a60b002d2
<ide><path>Library/Homebrew/test/test_versions.rb <ide> def test_pathname_version <ide> d.mkpath <ide> assert_equal '0.1.9', d.version <ide> end <del> <add> <ide> def test_no_version <ide> assert_nil Pathname.new("http://example.com/blah.tar").version <ide> assert_nil Pathname.new("arse").version <ide> end <del> <add> <ide> def test_bad_version <ide> assert_raises(RuntimeError) {f=TestBadVersion.new} <ide> end <del> <add> <ide> def check pathname, version <ide> r=MockFormula.new pathname <ide> assert_equal version, r.version <ide> end <del> <add> <ide> def test_version_all_dots <ide> check "http://example.com/foo.bar.la.1.14.zip", '1.14' <ide> end <ide> def test_boost_version_style <ide> def test_erlang_version_style <ide> check "http://erlang.org/download/otp_src_R13B.tar.gz", 'R13B' <ide> end <del> <add> <ide> def test_p7zip_version_style <ide> check "http://kent.dl.sourceforge.net/sourceforge/p7zip/p7zip_9.04_src_all.tar.bz2", <ide> '9.04' <ide> end <del> <add> <ide> def test_gloox_beta_style <ide> check "http://camaya.net/download/gloox-1.0-beta7.tar.bz2", '1.0-beta7' <ide> end <del> <add> <ide> def test_astyle_verson_style <ide> check "http://kent.dl.sourceforge.net/sourceforge/astyle/astyle_1.23_macosx.tar.gz", <ide> '1.23' <ide> end <del> <del> def test_version_libvorbis <del> check "http://downloads.xiph.org/releases/vorbis/libvorbis-1.2.2rc1.tar.bz2", <del> '1.2.2rc1' <del> end <del> <add> <ide> def test_version_dos2unix <ide> check "http://www.sfr-fresh.com/linux/misc/dos2unix-3.1.tar.gz", '3.1' <ide> end <ide> def test_lame_version_style <ide> check 'http://kent.dl.sourceforge.net/sourceforge/lame/lame-398-2.tar.gz', <ide> '398-2' <ide> end <del> <add> <ide> def test_ruby_version_style <ide> check 'ftp://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.1-p243.tar.gz', <ide> '1.9.1-p243' <ide> end <del> <add> <ide> def test_omega_version_style <ide> check 'http://www.alcyone.com/binaries/omega/omega-0.80.2-src.tar.gz', <ide> '0.80.2' <ide> end <ide> <del> def test_version_style_rc <add> def test_rc_style <add> check "http://downloads.xiph.org/releases/vorbis/libvorbis-1.2.2rc1.tar.bz2", <add> '1.2.2rc1' <add> end <add> <add> def test_dash_rc_style <ide> check 'http://ftp.mozilla.org/pub/mozilla.org/js/js-1.8.0-rc1.tar.gz', <ide> '1.8.0-rc1' <ide> end <del> <add> <ide> def test_angband_version_style <ide> check 'http://rephial.org/downloads/3.0/angband-3.0.9b-src.tar.gz', <ide> '3.0.9b' <ide> end <add> <add> def test_stable_suffix <add> check 'http://www.monkey.org/~provos/libevent-1.4.14b-stable.tar.gz', <add> '1.4.14b' <add> end <ide> end
1
Javascript
Javascript
add constructor check to async-hooks
6fb27af70a5e7f4eb074352aed578d349c81ceac
<ide><path>lib/async_hooks.js <ide> function fatalError(e) { <ide> <ide> class AsyncHook { <ide> constructor({ init, before, after, destroy }) { <del> if (init && typeof init !== 'function') <add> if (init !== undefined && typeof init !== 'function') <ide> throw new TypeError('init must be a function'); <del> if (before && typeof before !== 'function') <add> if (before !== undefined && typeof before !== 'function') <ide> throw new TypeError('before must be a function'); <del> if (after && typeof after !== 'function') <add> if (after !== undefined && typeof after !== 'function') <ide> throw new TypeError('after must be a function'); <del> if (destroy && typeof destroy !== 'function') <add> if (destroy !== undefined && typeof destroy !== 'function') <ide> throw new TypeError('destroy must be a function'); <ide> <ide> this[init_symbol] = init; <ide><path>test/parallel/test-async-wrap-constructor.js <add>'use strict'; <add>require('../common'); <add> <add>// This tests that using falsy values in createHook throws an error. <add> <add>const assert = require('assert'); <add>const async_hooks = require('async_hooks'); <add> <add>for (const badArg of [0, 1, false, true, null, 'hello']) { <add> for (const field of ['init', 'before', 'after', 'destroy']) { <add> assert.throws(() => { <add> async_hooks.createHook({ [field]: badArg }); <add> }, new RegExp(`^TypeError: ${field} must be a function$`)); <add> } <add>}
2
Text
Text
improve spanish translate
f577e7719edae558c2546d82807012724051c432
<ide><path>guide/spanish/git/difference-git-github/index.md <ide> localeTitle: Diferencia entre Git y GitHub <ide> --- <ide> ## Diferencia entre Git y GitHub <ide> <del>Git y Github son dos cosas diferentes. [Git](https://git-scm.com/) es el [sistema de control de versiones](https://en.wikipedia.org/wiki/Version_control) , mientras que [GitHub](https://github.com/) es un servicio para alojar repositorios de Git y ayudar a las personas a colaborar en la escritura de software. Sin embargo, a menudo se confunden por su nombre similar, debido al hecho de que GitHub se construye sobre Git, y porque muchos sitios web y artΓ­culos no hacen la diferencia entre ellos lo suficientemente clara. <add>Git y Github son dos cosas diferentes. [Git](https://git-scm.com/) es el [sistema de control de versiones](https://en.wikipedia.org/wiki/Version_control) , mientras que [GitHub](https://github.com/) es un servicio proporcionado para alojar repositorios de Git y ayudar a las personas a colaborar en la escritura de software. Sin embargo, ambos servicios a menudo se confunden por su contar con un nombre similar, debido al hecho de que GitHub se construye sobre Git, y porque muchos sitios web y artΓ­culos no hacen una diferencia lo suficientemente clara entre ambos conceptos. <ide> <ide> ![Git no es GitHub](https://i.imgur.com/EkjwJdr.png) <ide> <ide> ### Git <ide> <del>Git es el sistema de control de versiones distribuido. Git es responsable de realizar un seguimiento de los cambios en el contenido, generalmente los archivos de cΓ³digo fuente. <add>Git es el sistema de control de versiones distribuido. Git es el responsable de realizar el seguimiento de los cambios en el contenido, normalmente archivos de cΓ³digo fuente. <ide> <del>Para mΓ‘s informaciΓ³n, hay un [artΓ­culo completo sobre el propio Git](https://guide.freecodecamp.org/git) . <add>Para mΓ‘s informaciΓ³n, aquΓ­ hay un [artΓ­culo completo sobre el propio Git](https://guide.freecodecamp.org/git) . <ide> <ide> ### GitHub <ide> <del>GitHub es una empresa que proporciona hosting de repositorio Git. Eso significa que proporcionan una soluciΓ³n llave en mano para alojar repositorios Git en sus servidores. Eso puede ser ΓΊtil para mantener una copia de seguridad de su repositorio (Git solo rastrea los cambios realizados en sus archivos a lo largo del tiempo, todavΓ­a se debe hacer una copia de seguridad de la repo), y tener un lugar centralizado para guardar y compartir su cΓ³digo con otros. <add>GitHub es una empresa que proporciona hosting de repositorios Git. Eso significa que proporcionan una soluciΓ³n llave en mano para alojar repositorios Git en sus servidores. Esto puede ser ΓΊtil para mantener una copia de seguridad de su repositorio (Git solo rastrea los cambios realizados en sus archivos a lo largo del tiempo, todavΓ­aes necesario realizar una copia de seguridad de los repositorios), y tener un lugar centralizado para guardar y compartir su cΓ³digo con otros. <ide> <del>MΓ‘s que un simple servicio de alojamiento de repositorios Git, GitHub es una [forja de software](https://en.wikipedia.org/wiki/Forge_(software)) . Eso significa que tambiΓ©n proporciona un [rastreador de problemas](https://en.wikipedia.org/wiki/Issue_tracking_system) , herramientas para [revisar el cΓ³digo](https://en.wikipedia.org/wiki/Code_review) y otras herramientas para colaborar con otras personas y crear software. <add>MΓ‘s que un simple servicio de alojamiento de repositorios Git, GitHub es una [forja de software](https://es.wikipedia.org/wiki/Forge_(software)) . Eso significa que tambiΓ©n proporciona un [sistema de seguimiento de incidencias](https://es.wikipedia.org/wiki/Issue_tracking_system) , herramientas para [la revisiΓ³n de cΓ³digo](https://es.wikipedia.org/wiki/Code_review) y otras herramientas para colaborar con otras personas y crear software. <ide> <del>GitHub no es el ΓΊnico que ofrece este tipo de servicio. Uno de sus principales competidores es [GitLab](https://gitlab.com) . Para mΓ‘s informaciΓ³n sobre esto, consulte el [artΓ­culo sobre Git hosting](https://guide.freecodecamp.org/git/git-hosting) . <ide>\ No newline at end of file <add>GitHub no es el ΓΊnico que ofrece este tipo de servicio. Uno de sus principales competidores es [GitLab](https://gitlab.com) . Para mΓ‘s informaciΓ³n sobre esto, consulte el [artΓ­culo sobre el hosting de repositorios Git](https://guide.freecodecamp.org/git/git-hosting) .
1
PHP
PHP
pass the condition value to "when"
36b255013aeeb841d8fc441401825f9811b0993f
<ide><path>src/Illuminate/Database/Concerns/BuildsQueries.php <ide> public function when($value, $callback, $default = null) <ide> $builder = $this; <ide> <ide> if ($value) { <del> $builder = $callback($builder); <add> $builder = $callback($builder, $value); <ide> } elseif ($default) { <del> $builder = $default($builder); <add> $builder = $default($builder, $value); <ide> } <ide> <ide> return $builder; <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testBasicTableWrapping() <ide> <ide> public function testWhenCallback() <ide> { <del> $callback = function ($query) { <add> $callback = function ($query, $condition) { <add> $this->assertTrue($condition); <add> <ide> return $query->where('id', '=', 1); <ide> }; <ide> <ide> public function testWhenCallback() <ide> <ide> public function testWhenCallbackWithDefault() <ide> { <del> $callback = function ($query) { <add> $callback = function ($query, $condition) { <add> $this->assertEquals($condition, 'truthy'); <add> <ide> return $query->where('id', '=', 1); <ide> }; <ide> <del> $default = function ($query) { <add> $default = function ($query, $condition) { <add> $this->assertEquals($condition, 0); <add> <ide> return $query->where('id', '=', 2); <ide> }; <ide> <ide> $builder = $this->getBuilder(); <del> $builder->select('*')->from('users')->when(true, $callback, $default)->where('email', 'foo'); <add> $builder->select('*')->from('users')->when('truthy', $callback, $default)->where('email', 'foo'); <ide> $this->assertEquals('select * from "users" where "id" = ? and "email" = ?', $builder->toSql()); <ide> $this->assertEquals([0 => 1, 1 => 'foo'], $builder->getBindings()); <ide> <ide> $builder = $this->getBuilder(); <del> $builder->select('*')->from('users')->when(false, $callback, $default)->where('email', 'foo'); <add> $builder->select('*')->from('users')->when(0, $callback, $default)->where('email', 'foo'); <ide> $this->assertEquals('select * from "users" where "id" = ? and "email" = ?', $builder->toSql()); <ide> $this->assertEquals([0 => 2, 1 => 'foo'], $builder->getBindings()); <ide> }
2
Ruby
Ruby
remove unnecessary code
e53ccbc3cde32c38e584eb1a285cc09319d81653
<ide><path>Library/Homebrew/cask_dependent.rb <ide> def requirements <ide> end <ide> end <ide> <del> def recursive_dependencies(ignore_missing: false, &block) <del> Dependency.expand(self, ignore_missing: ignore_missing, &block) <add> def recursive_dependencies(&block) <add> Dependency.expand(self, &block) <ide> end <ide> <ide> def recursive_requirements(&block) <ide><path>Library/Homebrew/cmd/reinstall.rb <ide> def reinstall_args <ide> def reinstall <ide> args = reinstall_args.parse <ide> <del> # We need to use the bottle API instead of just using the formula file <del> # from an installed keg because it will not contain bottle information. <del> # As a consequence, `brew reinstall` will also upgrade outdated formulae <del> if Homebrew::EnvConfig.install_from_api? <del> args.named.each do |name| <del> formula = Formulary.factory(name) <del> next unless formula.any_version_installed? <del> next if formula.tap.present? && !formula.core_formula? <del> next unless Homebrew::API::Bottle.available?(name) <del> <del> Homebrew::API::Bottle.fetch_bottles(name) <del> rescue FormulaUnavailableError <del> next <del> end <del> end <del> <ide> formulae, casks = args.named.to_formulae_and_casks(method: :resolve) <ide> .partition { |o| o.is_a?(Formula) } <ide> <ide><path>Library/Homebrew/dependency.rb <ide> def to_formula <ide> formula <ide> end <ide> <del> def unavailable_core_formula? <del> to_formula <del> false <del> rescue CoreTapFormulaUnavailableError <del> true <del> rescue <del> false <del> end <del> <ide> def installed? <ide> to_formula.latest_version_installed? <ide> end <ide> class << self <ide> # the list. <ide> # The default filter, which is applied when a block is not given, omits <ide> # optionals and recommendeds based on what the dependent has asked for <del> def expand(dependent, deps = dependent.deps, cache_key: nil, ignore_missing: false, &block) <add> def expand(dependent, deps = dependent.deps, cache_key: nil, &block) <ide> # Keep track dependencies to avoid infinite cyclic dependency recursion. <ide> @expand_stack ||= [] <ide> @expand_stack.push dependent.name <ide> def expand(dependent, deps = dependent.deps, cache_key: nil, ignore_missing: fal <ide> # avoid downloading build dependency bottles <ide> next if dep.build? && dependent.pour_bottle? && Homebrew::EnvConfig.install_from_api? <ide> <del> case action(dependent, dep, ignore_missing: ignore_missing, &block) <add> case action(dependent, dep, &block) <ide> when :prune <ide> next <ide> when :skip <ide> next if @expand_stack.include? dep.name <ide> <del> expanded_deps.concat(expand(dep.to_formula, cache_key: cache_key, ignore_missing: ignore_missing, &block)) <add> expanded_deps.concat(expand(dep.to_formula, cache_key: cache_key, &block)) <ide> when :keep_but_prune_recursive_deps <ide> expanded_deps << dep <ide> else <ide> next if @expand_stack.include? dep.name <ide> <del> expanded_deps.concat(expand(dep.to_formula, cache_key: cache_key, ignore_missing: ignore_missing, &block)) <add> expanded_deps.concat(expand(dep.to_formula, cache_key: cache_key, &block)) <ide> expanded_deps << dep <ide> end <ide> end <ide> def expand(dependent, deps = dependent.deps, cache_key: nil, ignore_missing: fal <ide> @expand_stack.pop <ide> end <ide> <del> def action(dependent, dep, ignore_missing: false, &block) <add> def action(dependent, dep, &block) <ide> catch(:action) do <del> prune if ignore_missing && dep.unavailable_core_formula? <del> <ide> if block <ide> yield dependent, dep <ide> elsif dep.optional? || dep.recommended? <ide><path>Library/Homebrew/exceptions.rb <ide> def to_s <ide> end <ide> end <ide> <del># Raised when a formula in a the core tap is unavailable. <del>class CoreTapFormulaUnavailableError < TapFormulaUnavailableError <del> def initialize(name) <del> super CoreTap.instance, name <del> end <del>end <del> <ide> # Raised when a formula in a specific tap does not contain a formula class. <ide> class TapFormulaClassUnavailableError < TapFormulaUnavailableError <ide> include FormulaClassUnavailableErrorModule <ide><path>Library/Homebrew/formula_installer.rb <ide> def prelude <ide> def verify_deps_exist <ide> begin <ide> compute_dependencies <del> rescue CoreTapFormulaUnavailableError => e <del> raise unless Homebrew::API::Bottle.available? e.name <del> <del> Homebrew::API::Bottle.fetch_bottles(e.name) <del> retry <ide> rescue TapFormulaUnavailableError => e <ide> raise if e.tap.installed? <ide> <ide><path>Library/Homebrew/formulary.rb <ide> def get_formula(spec, alias_path: nil, force_bottle: false, flags: [], ignore_er <ide> rescue FormulaClassUnavailableError => e <ide> raise TapFormulaClassUnavailableError.new(tap, name, e.path, e.class_name, e.class_list), "", e.backtrace <ide> rescue FormulaUnavailableError => e <del> if tap.core_tap? && Homebrew::EnvConfig.install_from_api? <del> raise CoreTapFormulaUnavailableError.new(name), "", e.backtrace <del> end <del> <ide> raise TapFormulaUnavailableError.new(tap, name), "", e.backtrace <ide> end <ide> <ide> def initialize(name) <ide> end <ide> <ide> def get_formula(*) <del> if !CoreTap.instance.installed? && Homebrew::EnvConfig.install_from_api? <del> raise CoreTapFormulaUnavailableError, name <del> end <del> <ide> raise FormulaUnavailableError, name <ide> end <ide> end
6
Javascript
Javascript
add missing semicolons
d1d0f95585d1a9bcb2684edcab454cb49adbf4eb
<ide><path>lib/webpack.js <ide> const defineMissingPluginError = (pluginName, errorMessage) => { <ide> throw new Error(errorMessage); <ide> } <ide> }); <del>} <add>}; <ide> <ide> defineMissingPluginError( <ide> "UglifyJsPlugin", <ide> "webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." <del>) <add>); <ide> <ide> defineMissingPluginError( <ide> "CommonsChunkPlugin", <ide> "webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead." <del>) <add>);
1
Text
Text
add changelog info to the readme with a link
f06daafb641358ebb61e6cda554f9d7f309bc9d0
<ide><path>README.md <ide> Use [Github issues](https://github.com/facebook/immutable-js/issues) for request <ide> We actively welcome pull requests, learn how to [contribute](./CONTRIBUTING.md). <ide> <ide> <add>Changelog <add>--------- <add> <add>Changes are tracked as [Github releases](https://github.com/facebook/immutable-js/releases). <add> <add> <ide> Thanks <ide> ------ <ide>
1
Text
Text
add open data resources
e1bf16820c5da0f0890f6d38b67994f71f9734d9
<ide><path>guide/english/working-in-tech/open-data/index.md <ide> One way that you can use open data is through Civic Hacking in your local code f <ide> <!-- Please add any articles you think might be helpful to read before writing the article --> <ide> * [Open Data Wikipedia Page](https://en.wikipedia.org/wiki/Open_data) <ide> * [Find Your Brigade](http://brigade.codeforamerica.org/brigade/) <add>* [Kaggle datasets](https://www.kaggle.com/datasets) <add>* [US Government Open Data](https://www.data.gov/) <ide> * [Microsoft Research Open Data](https://msropendata.com/) <del>
1
Text
Text
add second part of the debugging guide
2cce36694d9a8554102f776be4ae5d42b6b6b7a9
<ide><path>docs/debugging.md <ide> # Debugging <ide> <del>Even though Atom is still in beta, minimizing problems is always a priority. Atom provides some tools to help you understand unexpected behavior, debug problems and solve them yourself in some cases. <del> <del>This guide describes some of those tools and a few approaches to help you debug and provide more helpful information when [submitting issues]. <add>Atom provides several tools to help you understand unexpected behavior and debug problems. This guide describes some of those tools and a few approaches to help you debug and provide more helpful information when [submitting issues]. <ide> <ide> ## Update to the latest version <ide> <ide> You might be running into an issue which was already fixed in a more recent version of Atom than the one you're using. <ide> <del>If you're **building Atom from source**, pull down the latest version of master and [re-build][building atom]. <add>If you're building Atom from source, pull down the latest version of master and [re-build][building atom]. <ide> <del>If you're **using released version**, check which version of Atom you're using: <add>If you're using released version, check which version of Atom you're using: <ide> <ide> ```shell <ide> $ atom --version <ide> Head on over to the [list of releases][atom releases] and see if there's a more <ide> <ide> In some cases, unexpected behavior might be caused by misconfigured or unconfigured settings in Atom or in one of the packages. <ide> <del>Open Atom's Settings View with <code>cmd-`</code> or the Atom > Preferences menu option. <add>Open Atom's Settings View with `cmd-,` or the Atom > Preferences menu option. <ide> <ide> ![Settings View] <ide> <del>Check **Atom's settings** in the Settings pane, there's a description of each configuration option [here][customizing guide]. For example, if you want Atom to use hard tabs (real tabs) and not soft tabs (spaces), disable the "Soft Tabs" option. <add>Check Atom's settings in the Settings pane, there's a description of each configuration option [here][customizing guide]. For example, if you want Atom to use hard tabs (real tabs) and not soft tabs (spaces), disable the "Soft Tabs" option. <ide> <del>Since Atom ships with a set of packages and you can install additional packages yourself, check **the list of packages and their settings**. For example, if you'd like to get rid of the vertical line in the middle of the editor, disable the [Wrap Guide package]. And if you don't like it when Atom strips trailing whitespace or ensures that there's a single trailing newline in the file, you can configure that in the [Whitespace packages'][whitespace package] settings. <add>Since Atom ships with a set of packages and you can install additional packages yourself, check the list of packages and their settings. For example, if you'd like to get rid of the vertical line in the middle of the editor, disable the [Wrap Guide package]. And if you don't like it when Atom strips trailing whitespace or ensures that there's a single trailing newline in the file, you can configure that in the [Whitespace packages'][whitespace package] settings. <ide> <ide> ![Package Settings] <ide> <del># Check the keybindings <add>## Check the keybindings <ide> <ide> If a command is not executing when you hit a keystroke or the wrong command is executing, there might be an issue with the keybindings for that keystroke. Atom ships with the [Keybinding resolver][keybinding resolver package], a neat package which helps you understand which keybindings are executed. <ide> <ide> The keybinding resolver shows you a list of keybindings that exist for the keyst <ide> * the CSS selector used to define the context in which the keybinding is valid, and <ide> * the file in which the keybinding is defined. <ide> <del>Of all the keybinding that are listed (grey color), at most one keybinding is matched and executed (green color). If **the command you wanted to trigger isn't listed**, then a keybinding for that command hasn't been defined. More keybindings are provided by [packages] and you can [define your own keybindings][customizing keybindings]. <add>Of all the keybinding that are listed (grey color), at most one keybinding is matched and executed (green color). If the command you wanted to trigger isn't listed, then a keybinding for that command hasn't been defined. More keybindings are provided by [packages] and you can [define your own keybindings][customizing keybindings]. <ide> <del>If multiple keybindings are matched, Atom determines which keybinding will be executed based on the [specificity of the selectors and the order in which they were loaded][specificity and order]. If **the command you wanted to trigger is listed in the Keybinding resolver, but wasn't the one that was executed**, this is normally explained by one of two causes: <add>If multiple keybindings are matched, Atom determines which keybinding will be executed based on the [specificity of the selectors and the order in which they were loaded][specificity and order]. If the command you wanted to trigger is listed in the Keybinding resolver, but wasn't the one that was executed, this is normally explained by one of two causes: <ide> * the keystroke was not used in the context defined by the keybinding's selector. For example, you can't trigger the "Tree View: Add File" command if the Tree View is not focused, or <del>* there is another keybinding running over it. This often happens when you install a package which defines keybinding that conflict with existing keybindings. If the package's keybindings have selectors with higher specificity or were loaded later, they'll have priority over existing ones. <add>* there is another keybinding that took precedence. This often happens when you install a package which defines keybinding that conflict with existing keybindings. If the package's keybindings have selectors with higher specificity or were loaded later, they'll have priority over existing ones. <add> <add>Atom loads core Atom keybindings and package keybindings first, and user-defined keybindings after last. Since user-defined keybindings are loaded last, you can use your `keymap.cson` file to tweak the keybindings and sort out problems like these. For example, you can remove keybindings with [the `unset!` directive][unset directive]. <add> <add>If you notice that a package's keybindings are taking precedence over core Atom keybindings, it might be a good idea to report the issue on the package's GitHub repository. <add> <add>## Check if the problem shows up in safe mode <add> <add>A large part of Atom's functionality comes from packages you can install. In some cases, these packages might be causing unexpected behavior, problems, or performance issues. <add> <add>To determine if a package you installed is causing problems, start Atom from the terminal in safe mode: <add> <add>``` <add>$ atom --safe <add>``` <add> <add>This starts Atom, but does not load packages from `~/.atom/packages` or `~/.atom/dev/packages`. If you can no longer reproduce the problem in safe mode, it's likely it was caused by one of the packages. <add> <add>To figure out which package is causing trouble, start Atom normally again and open Settings (`cmd-,`). Since Settings allow you to disable each installed package, you can disable packages one by one until you can no longer reproduce the issue. Restart (`cmd-q`) or reload (`cmd-ctrl-alt-l`) Atom after you disable each package to make sure it's completely gone. <add> <add>When you find the problematic package, you can disable or uninstall the package, and consider creating an issue on the package's GitHub repository. <add> <add>## Check your config files <add> <add>You might have defined some custom functionality or styles in Atom's [Init script or Stylesheet]. In some situations, these personal hacks might be causing problems so try clearing those files and restarting Atom. <add> <add>## Check for errors in the developer tools <add> <add>When an error is thrown in Atom, the developer tools are automatically shown with the error logged in the Console tab. However, if the dev tools are open before the error is triggered, a full stack trace for the error will be logged: <ide> <del>Since user-defined keybindings are loaded last, you can use your `keymap.cson` file to tweak the keybindings and sort out problems like these. For example, you can remove keybindings with [the `unset!` directive][unset directive]. <add>![devtools error] <ide> <del>If you notice a package running over core Atom keybindings, it might be a good idea to report the issue on the package's GitHub repository. <add>If you can reproduce the error, use this approach to get the full stack trace. The stack trace might point to a problem in your [Init script][init script or stylesheet] or a specific package you installed, which you can then disable and report an issue on its GitHub repository. <ide> <ide> [submitting issues]: https://github.com/atom/atom/blob/master/CONTRIBUTING.md#submitting-issues <ide> [building atom]: https://github.com/atom/atom#building <ide> If you notice a package running over core Atom keybindings, it might be a good i <ide> [packages]: https://atom.io/packages <ide> [specificity and order]: https://atom.io/docs/latest/advanced/keymaps#specificity-and-cascade-order <ide> [unset directive]: https://atom.io/docs/latest/advanced/keymaps#removing-bindings <add>[init script or stylesheet]: https://atom.io/docs/latest/customizing-atom#quick-personal-hacks <add>[devtools error]: https://cloud.githubusercontent.com/assets/38924/3177710/11b4e510-ec13-11e3-96db-a2e8a7891773.png
1
Go
Go
remove unused sandboxpath
2f038c25868727310992104b7b267fed6c7dad39
<ide><path>daemon/start_windows.go <ide> func (daemon *Daemon) getLibcontainerdCreateOptions(container *container.Contain <ide> if err != nil { <ide> return nil, fmt.Errorf("failed to get layer metadata - %s", err) <ide> } <del> if hvOpts.IsHyperV { <del> hvOpts.SandboxPath = filepath.Dir(m["dir"]) <del> } <del> <ide> layerOpts.LayerFolderPath = m["dir"] <ide> <ide> // Generate the layer paths of the layer options <ide><path>libcontainerd/client_windows.go <ide> const defaultOwner = "docker" <ide> // | VolumePath | \\?\\Volume{GUIDa} | | <ide> // | LayerFolderPath | %root%\windowsfilter\containerID | %root%\windowsfilter\containerID (servicing only) | <ide> // | Layers[] | ID=GUIDb;Path=%root%\windowsfilter\layerID | ID=GUIDb;Path=%root%\windowsfilter\layerID | <del>// | SandboxPath | | %root%\windowsfilter | <ide> // | HvRuntime | | ImagePath=%root%\BaseLayerID\UtilityVM | <ide> // +-----------------+--------------------------------------------+---------------------------------------------------+ <ide> // <ide> const defaultOwner = "docker" <ide> // }], <ide> // "HostName": "475c2c58933b", <ide> // "MappedDirectories": [], <del>// "SandboxPath": "C:\\\\control\\\\windowsfilter", <ide> // "HvPartition": true, <ide> // "EndpointList": ["e1bb1e61-d56f-405e-b75d-fd520cefa0cb"], <ide> // "DNSSearchList": "a.com,b.com,c.com", <ide> func (clnt *client) Create(containerID string, checkpoint string, checkpointDir <ide> } <ide> if h, ok := option.(*HyperVIsolationOption); ok { <ide> configuration.HvPartition = h.IsHyperV <del> configuration.SandboxPath = h.SandboxPath <ide> continue <ide> } <ide> if l, ok := option.(*LayerOption); ok { <ide><path>libcontainerd/types_windows.go <ide> type FlushOption struct { <ide> } <ide> <ide> // HyperVIsolationOption is a CreateOption that indicates whether the runtime <del>// should start the container as a Hyper-V container, and if so, the sandbox path. <add>// should start the container as a Hyper-V container. <ide> type HyperVIsolationOption struct { <del> IsHyperV bool <del> SandboxPath string `json:",omitempty"` <add> IsHyperV bool <ide> } <ide> <ide> // LayerOption is a CreateOption that indicates to the runtime the layer folder
3
Java
Java
add sseeventencoder to webreactiveconfiguration
13b6f4fee47c89f9602710ab1298722fe87504b3
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java <ide> import org.springframework.core.convert.support.ReactiveStreamsToRxJava1Converter; <ide> import org.springframework.format.Formatter; <ide> import org.springframework.http.MediaType; <add>import org.springframework.http.codec.SseEventEncoder; <ide> import org.springframework.http.converter.reactive.CodecHttpMessageConverter; <ide> import org.springframework.http.converter.reactive.HttpMessageConverter; <ide> import org.springframework.http.converter.reactive.ResourceHttpMessageConverter; <ide> protected void configureMessageConverters(List<HttpMessageConverter<?>> converte <ide> * {@link #configureMessageConverters(List)}. <ide> */ <ide> protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> converters) { <add> List<Encoder<?>> sseDataEncoders = new ArrayList<>(); <ide> converters.add(converter(new ByteBufferEncoder(), new ByteBufferDecoder())); <ide> converters.add(converter(new StringEncoder(), new StringDecoder())); <ide> converters.add(new ResourceHttpMessageConverter()); <ide> if (jaxb2Present) { <ide> converters.add(converter(new Jaxb2Encoder(), new Jaxb2Decoder())); <ide> } <ide> if (jackson2Present) { <del> JsonObjectDecoder objectDecoder = new JsonObjectDecoder(); <del> converters.add(converter(new JacksonJsonEncoder(), new JacksonJsonDecoder(objectDecoder))); <add> JacksonJsonEncoder jacksonEncoder = new JacksonJsonEncoder(); <add> JacksonJsonDecoder jacksonDecoder = new JacksonJsonDecoder(new JsonObjectDecoder()); <add> converters.add(converter(jacksonEncoder, jacksonDecoder)); <add> sseDataEncoders.add(jacksonEncoder); <add> } else { <add> <ide> } <add> converters.add(converter(new SseEventEncoder(sseDataEncoders), null)); <ide> } <ide> <ide> private static <T> HttpMessageConverter<T> converter(Encoder<T> encoder, Decoder<T> decoder) { <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/config/WebReactiveConfigurationTests.java <ide> <ide> import org.junit.Before; <ide> import org.junit.Test; <add>import static org.springframework.http.MediaType.*; <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> import rx.Observable; <ide> public void requestMappingHandlerAdapter() throws Exception { <ide> assertNotNull(adapter); <ide> <ide> List<HttpMessageConverter<?>> converters = adapter.getMessageConverters(); <del> assertEquals(5, converters.size()); <add> assertEquals(6, converters.size()); <ide> <del> assertHasConverter(converters, ByteBuffer.class, MediaType.APPLICATION_OCTET_STREAM); <del> assertHasConverter(converters, String.class, MediaType.TEXT_PLAIN); <del> assertHasConverter(converters, Resource.class, MediaType.IMAGE_PNG); <del> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_XML); <del> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_JSON); <add> assertHasConverter(converters, ByteBuffer.class, APPLICATION_OCTET_STREAM, APPLICATION_OCTET_STREAM); <add> assertHasConverter(converters, String.class, TEXT_PLAIN, TEXT_PLAIN); <add> assertHasConverter(converters, Resource.class, IMAGE_PNG, IMAGE_PNG); <add> assertHasConverter(converters, TestBean.class, APPLICATION_XML, APPLICATION_XML); <add> assertHasConverter(converters, TestBean.class, APPLICATION_JSON, APPLICATION_JSON); <add> assertHasConverter(converters, TestBean.class, null, MediaType.parseMediaType("text/event-stream")); <ide> <ide> name = "mvcConversionService"; <ide> ConversionService service = context.getBean(name, ConversionService.class); <ide> public void customMessageConverterConfig() throws Exception { <ide> List<HttpMessageConverter<?>> converters = adapter.getMessageConverters(); <ide> assertEquals(2, converters.size()); <ide> <del> assertHasConverter(converters, String.class, MediaType.TEXT_PLAIN); <del> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_XML); <add> assertHasConverter(converters, String.class, TEXT_PLAIN, TEXT_PLAIN); <add> assertHasConverter(converters, TestBean.class, APPLICATION_XML, APPLICATION_XML); <ide> } <ide> <ide> @Test <ide> public void responseEntityResultHandler() throws Exception { <ide> assertEquals(0, handler.getOrder()); <ide> <ide> List<HttpMessageConverter<?>> converters = handler.getMessageConverters(); <del> assertEquals(5, converters.size()); <add> assertEquals(6, converters.size()); <ide> <del> assertHasConverter(converters, ByteBuffer.class, MediaType.APPLICATION_OCTET_STREAM); <del> assertHasConverter(converters, String.class, MediaType.TEXT_PLAIN); <del> assertHasConverter(converters, Resource.class, MediaType.IMAGE_PNG); <del> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_XML); <del> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_JSON); <add> assertHasConverter(converters, ByteBuffer.class, APPLICATION_OCTET_STREAM, APPLICATION_OCTET_STREAM); <add> assertHasConverter(converters, String.class, TEXT_PLAIN, TEXT_PLAIN); <add> assertHasConverter(converters, Resource.class, IMAGE_PNG, IMAGE_PNG); <add> assertHasConverter(converters, TestBean.class, APPLICATION_XML, APPLICATION_XML); <add> assertHasConverter(converters, TestBean.class, APPLICATION_JSON, APPLICATION_JSON); <add> assertHasConverter(converters, TestBean.class, null, MediaType.parseMediaType("text/event-stream")); <ide> <ide> name = "mvcContentTypeResolver"; <ide> RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class); <ide> public void responseBodyResultHandler() throws Exception { <ide> assertEquals(100, handler.getOrder()); <ide> <ide> List<HttpMessageConverter<?>> converters = handler.getMessageConverters(); <del> assertEquals(5, converters.size()); <add> assertEquals(6, converters.size()); <ide> <del> assertHasConverter(converters, ByteBuffer.class, MediaType.APPLICATION_OCTET_STREAM); <del> assertHasConverter(converters, String.class, MediaType.TEXT_PLAIN); <del> assertHasConverter(converters, Resource.class, MediaType.IMAGE_PNG); <del> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_XML); <del> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_JSON); <add> assertHasConverter(converters, ByteBuffer.class, APPLICATION_OCTET_STREAM, APPLICATION_OCTET_STREAM); <add> assertHasConverter(converters, String.class, TEXT_PLAIN, TEXT_PLAIN); <add> assertHasConverter(converters, Resource.class, IMAGE_PNG, IMAGE_PNG); <add> assertHasConverter(converters, TestBean.class, APPLICATION_XML, APPLICATION_XML); <add> assertHasConverter(converters, TestBean.class, APPLICATION_JSON, APPLICATION_JSON); <add> assertHasConverter(converters, TestBean.class, null, MediaType.parseMediaType("text/event-stream")); <ide> <ide> name = "mvcContentTypeResolver"; <ide> RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class); <ide> public void viewResolutionResultHandler() throws Exception { <ide> } <ide> <ide> <del> private void assertHasConverter(List<HttpMessageConverter<?>> converters, Class<?> clazz, MediaType mediaType) { <add> private void assertHasConverter(List<HttpMessageConverter<?>> converters, Class<?> clazz, <add> MediaType readMediaType, MediaType writeMediaType) { <ide> ResolvableType type = ResolvableType.forClass(clazz); <ide> assertTrue(converters.stream() <del> .filter(c -> c.canRead(type, mediaType) && c.canWrite(type, mediaType)) <add> .filter(c -> (readMediaType == null || c.canRead(type, readMediaType)) <add> && (writeMediaType == null || c.canWrite(type, writeMediaType))) <ide> .findAny() <ide> .isPresent()); <ide> }
2
Python
Python
update gen_vocab.py to be python3 compatible
8c68bc0dae04afbfbfd0dab7808219248d52a840
<ide><path>research/adversarial_text/gen_vocab.py <ide> from __future__ import absolute_import <ide> from __future__ import division <ide> from __future__ import print_function <add>from six import iteritems <ide> <ide> from collections import defaultdict <ide> <ide> def main(_): <ide> fill_vocab_from_doc(doc, vocab_freqs, doc_counts) <ide> <ide> # Filter out low-occurring terms <del> vocab_freqs = dict((term, freq) for term, freq in vocab_freqs.iteritems() <add> vocab_freqs = dict((term, freq) for term, freq in iteritems(vocab_freqs) <ide> if doc_counts[term] > FLAGS.doc_count_threshold) <ide> <ide> # Sort by frequency
1
Ruby
Ruby
fix compiler map key
246b60573f8726e9304e263d13bcfe1095704645
<ide><path>Library/Homebrew/macos.rb <ide> def prefer_64_bit? <ide> "4.5" => { :llvm_build => 2336, :clang => "4.1", :clang_build => 421 }, <ide> "4.5.1" => { :llvm_build => 2336, :clang => "4.1", :clang_build => 421 }, <ide> "4.5.2" => { :llvm_build => 2336, :clang => "4.1", :clang_build => 421 }, <del> "4.6.0" => { :llvm_build => 2336, :clang => "4.1", :clang_build => 421 }, <add> "4.6" => { :llvm_build => 2336, :clang => "4.1", :clang_build => 421 }, <ide> } <ide> <ide> def compilers_standard?
1
PHP
PHP
fix bug in container isshared
7b32cb1eb991132f537a3349947cde711245c5fa
<ide><path>src/Illuminate/Container/Container.php <ide> protected function rebound($abstract) <ide> */ <ide> protected function getReboundCallbacks($abstract) <ide> { <del> return array_get($this->reboundCallbacks, $abstract, array()); <add> if (isset($this->reboundCallbacks[$abstract])) <add> { <add> return $this->reboundCallbacks[$abstract]; <add> } <add> else <add> { <add> return array(); <add> } <ide> } <ide> <ide> /** <ide> protected function fireCallbackArray($object, array $callbacks) <ide> */ <ide> public function isShared($abstract) <ide> { <del> $shared = array_get($this->bindings, "{$abstract}.shared"); <add> if (isset($this->bindings[$abstract]['shared'])) <add> { <add> $shared = $this->bindings[$abstract]['shared']; <add> } <add> else <add> { <add> $shared = false; <add> } <ide> <ide> return isset($this->instances[$abstract]) || $shared === true; <ide> }
1
Python
Python
update gpt2 docstring
fd10d79b55d159d845a30adb238cd7019965aa23
<ide><path>pytorch_transformers/tokenization_gpt2.py <ide> def get_pairs(word): <ide> class GPT2Tokenizer(PreTrainedTokenizer): <ide> """ <ide> GPT-2 BPE tokenizer. Peculiarities: <del> - Byte-level BPE <add> - Byte-level Byte-Pair-Encoding <add> - Requires a space to start the input string => will add a space is there isn't. <add> As a consequence, this tokenizer `encode` and `decode` method will not conserve <add> the absence of a space at the beginning of a string: `tokenizer.decode(tokenizer.encode("Hello")) = " Hello" <ide> """ <ide> vocab_files_names = VOCAB_FILES_NAMES <ide> pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
1
Javascript
Javascript
limit push check to http/3
344c5e4e508ee6c7fad98bb5a34daa98ff43df68
<ide><path>lib/internal/quic/core.js <ide> class QuicStream extends Duplex { <ide> <ide> validateObject(headers, 'headers'); <ide> <del> // Push streams are only supported on QUIC servers, and <del> // only if the original stream is bidirectional. <del> // TODO(@jasnell): This is really an http/3 specific <del> // requirement so if we end up later with another <del> // QUIC application protocol that has a similar <del> // notion of push streams without this restriction, <del> // then we'll need to check alpn value here also. <del> if (!this.clientInitiated && !this.bidirectional) { <add> // This is a small performance optimization for http/3, <add> // where push streams are only supported for client <add> // initiated, bidirectional streams. For any other alpn, <add> // we'll make the attempt to push and handle the failure <add> // after. <add> if (!this.clientInitiated && <add> !this.bidirectional && <add> this.session.alpnProtocol === 'h3-29') { <ide> throw new ERR_INVALID_STATE( <ide> 'Push streams are only supported on client-initiated, ' + <ide> 'bidirectional streams');
1
Python
Python
include type key in schema object properties dict.
79d37bce4cdc14c9642b206ad5690f2efe514d1a
<ide><path>rest_framework/schemas/openapi.py <ide> def _map_serializer(self, serializer): <ide> properties[field.field_name] = schema <ide> <ide> result = { <add> 'type': 'object', <ide> 'properties': properties <ide> } <ide> if required: <ide><path>tests/schemas/test_openapi.py <ide> class View(generics.GenericAPIView): <ide> 'schema': { <ide> 'type': 'array', <ide> 'items': { <add> 'type': 'object', <ide> 'properties': { <ide> 'text': { <ide> 'type': 'string', <ide> class View(generics.GenericAPIView): <ide> 'item': { <ide> 'type': 'array', <ide> 'items': { <add> 'type': 'object', <ide> 'properties': { <ide> 'text': { <ide> 'type': 'string', <ide> class View(generics.GenericAPIView): <ide> 'content': { <ide> 'application/json': { <ide> 'schema': { <add> 'type': 'object', <ide> 'properties': { <ide> 'text': { <ide> 'type': 'string',
2
Ruby
Ruby
add support for emitting sql subqueries
c001fadd2f2f420267db809439581e388684e9de
<ide><path>lib/arel/visitors/to_sql.rb <ide> def visit_Arel_Nodes_Grouping o <ide> "(#{visit o.expr})" <ide> end <ide> <add> def visit_Arel_SelectManager o <add> "(#{o.to_sql.rstrip})" <add> end <add> <ide> def visit_Arel_Nodes_Ascending o <ide> "#{visit o.expr} ASC" <ide> end <ide><path>test/visitors/test_to_sql.rb <ide> def dispatch <ide> @visitor.accept(nil).must_be_like "NULL" <ide> end <ide> <add> it "should visit_Arel_SelectManager, which is a subquery" do <add> mgr = Table.new(:foo).project(:bar) <add> @visitor.accept(mgr).must_be_like '(SELECT bar FROM "foo")' <add> end <add> <ide> it "should visit_Arel_Nodes_And" do <ide> node = Nodes::And.new [@attr.eq(10), @attr.eq(11)] <ide> @visitor.accept(node).must_be_like %{
2
Python
Python
fix duplicate task_ids in example_http.py
dc3a4938caa508f4a79985f5f6fa506adf4c29d4
<ide><path>airflow/providers/http/example_dags/example_http.py <ide> ) <ide> # [END howto_operator_http_task_get_op] <ide> # [START howto_operator_http_task_get_op_response_filter] <del>task_get_op = SimpleHttpOperator( <add>task_get_op_response_filter = SimpleHttpOperator( <ide> task_id='get_op_response_filter', <ide> method='GET', <ide> endpoint='get', <ide> dag=dag, <ide> ) <ide> # [END howto_operator_http_http_sensor_check] <del>task_http_sensor_check >> task_post_op >> task_get_op >> task_put_op >> task_del_op >> task_post_op_formenc <add>task_http_sensor_check >> task_post_op >> task_get_op >> task_get_op_response_filter <add>task_get_op_response_filter >> task_put_op >> task_del_op >> task_post_op_formenc
1
Ruby
Ruby
add helper method for explicit lazy load
c98a641ff402d3ca5b754f4621a0764f33eab155
<ide><path>railties/test/application/configuration_test.rb <ide> def create <ide> <ide> app "development" <ide> <del> ActionController::Base.object_id # force lazy load hooks to run <add> lazy_load { ActionController::Base } <ide> <ide> assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters <ide> <ide> def create <ide> test "config.action_controller.always_permitted_parameters are: controller, action by default" do <ide> app "development" <ide> <del> ActionController::Base.object_id # force lazy load hooks to run <add> lazy_load { ActionController::Base } <ide> <ide> assert_equal %w(controller action), ActionController::Parameters.always_permitted_parameters <ide> end <ide> def create <ide> <ide> app "development" <ide> <del> ActionController::Base.object_id # force lazy load hooks to run <add> lazy_load { ActionController::Base } <ide> <ide> assert_equal %w( controller action format ), ActionController::Parameters.always_permitted_parameters <ide> end <ide> def create <ide> <ide> app "development" <ide> <del> ActionController::Base.object_id # force lazy load hooks to run <add> lazy_load { ActionController::Base } <ide> <ide> assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters <ide> <ide> def create <ide> test "config.action_controller.action_on_unpermitted_parameters is :log by default on development" do <ide> app "development" <ide> <del> ActionController::Base.object_id # force lazy load hooks to run <add> lazy_load { ActionController::Base } <ide> <ide> assert_equal :log, ActionController::Parameters.action_on_unpermitted_parameters <ide> end <ide> <ide> test "config.action_controller.action_on_unpermitted_parameters is :log by default on test" do <ide> app "test" <ide> <del> ActionController::Base.object_id # force lazy load hooks to run <add> lazy_load { ActionController::Base } <ide> <ide> assert_equal :log, ActionController::Parameters.action_on_unpermitted_parameters <ide> end <ide> <ide> test "config.action_controller.action_on_unpermitted_parameters is false by default on production" do <ide> app "production" <ide> <del> ActionController::Base.object_id # force lazy load hooks to run <add> lazy_load { ActionController::Base } <ide> <ide> assert_equal false, ActionController::Parameters.action_on_unpermitted_parameters <ide> end <ide> def create <ide> <ide> app "development" <ide> <del> ActionController::Base.object_id # force lazy load hooks to run <add> lazy_load { ActionController::Base } <ide> assert_equal true, ActionController::Parameters.permit_all_parameters <ide> end <ide> <ide> def create <ide> <ide> app "development" <ide> <del> ActionController::Base.object_id # force lazy load hooks to run <add> lazy_load { ActionController::Base } <ide> assert_equal [], ActionController::Parameters.always_permitted_parameters <ide> end <ide> <ide> def create <ide> <ide> app "development" <ide> <del> ActionController::Base.object_id # force lazy load hooks to run <add> lazy_load { ActionController::Base } <ide> assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters <ide> end <ide> <ide> class Post < ActiveRecord::Base <ide> RUBY <ide> <ide> app "development" <del> Post.object_id # force lazy load hooks to run <add> lazy_load { Post } <ide> <ide> assert_not ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer <ide> end <ide> class Post < ActiveRecord::Base <ide> RUBY <ide> <ide> app "development" <del> Post.object_id # force lazy load hooks to run <add> lazy_load { Post } <ide> <ide> assert ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer <ide> end <ide> class Post < ActiveRecord::Base <ide> RUBY <ide> <ide> app "development" <del> Post.object_id # force lazy load hooks to run <add> lazy_load { Post } <ide> <ide> assert ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer <ide> end <ide> def index <ide> assert_equal 301, last_response.status <ide> assert_equal "https://example.org/", last_response.location <ide> end <add> <add> private <add> def lazy_load <add> yield # Tasty clarifying sugar, homie! We only need to reference a constant to load it. <add> end <ide> end <ide> end
1
Go
Go
change registry address to https from http
8be58d3a7f6020fe34281dbe27375005e248f0f5
<ide><path>auth/auth.go <ide> import ( <ide> const CONFIGFILE = "/var/lib/docker/.dockercfg" <ide> <ide> // the registry server we want to login against <del>const REGISTRY_SERVER = "http://registry.docker.io" <add>const REGISTRY_SERVER = "https://registry.docker.io" <ide> <ide> type AuthConfig struct { <ide> Username string `json:"username"`
1
PHP
PHP
modify dd() to conform to psr2
4ffb4a33c881e8e6443a3b09a66ccdc57e6ac028
<ide><path>src/Illuminate/Support/helpers.php <ide> function data_get($target, $key, $default = null) <ide> */ <ide> function dd() <ide> { <del> array_map(function ($x) { (new Dumper)->dump($x); }, func_get_args()); <add> array_map(function ($x) { <add> (new Dumper)->dump($x); <add> }, func_get_args()); <ide> <ide> die(1); <ide> }
1
PHP
PHP
attach dispatcher filters before firing events
94553a10c676da3a6c2ce3a86768fa935afcea61
<ide><path>src/Error/ExceptionRenderer.php <ide> protected function _shutdown() <ide> { <ide> $this->controller->dispatchEvent('Controller.shutdown'); <ide> $dispatcher = DispatcherFactory::create(); <add> $eventManager = $dispatcher->eventManager(); <add> foreach ($dispatcher->filters() as $filter) { <add> $eventManager->attach($filter); <add> } <ide> $args = [ <ide> 'request' => $this->controller->request, <ide> 'response' => $this->controller->response <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> use Cake\Network\Exception\SocketException; <ide> use Cake\Network\Request; <ide> use Cake\ORM\Exception\MissingBehaviorException; <add>use Cake\Routing\DispatcherFactory; <ide> use Cake\Routing\Exception\MissingControllerException; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <ide> public function testRenderShutdownEvents() <ide> $this->assertEquals($expected, $fired); <ide> } <ide> <add> /** <add> * Test that rendering exceptions triggers events <add> * on filters attached to dispatcherfactory <add> * <add> * @return void <add> */ <add> public function testRenderShutdownEventsOnDispatcherFacotry() <add> { <add> $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter') <add> ->setMethods(['afterDispatch']) <add> ->getMock(); <add> <add> $filter->expects($this->at(0)) <add> ->method('afterDispatch'); <add> <add> DispatcherFactory::add($filter); <add> <add> $exception = new Exception('Terrible'); <add> $renderer = new ExceptionRenderer($exception); <add> $renderer->render(); <add> } <add> <ide> /** <ide> * test that subclass methods fire shutdown events. <ide> *
2
Text
Text
fix a typo in docker-build man page
dcfa881a7b12e9a737b25ada98ec0c76e58c9c9c
<ide><path>docs/man/docker-build.1.md <ide> as context. <ide> <ide> # EXAMPLES <ide> <del>## Building an image using a Dockefile located inside the current directory <add>## Building an image using a Dockerfile located inside the current directory <ide> <ide> Docker images can be built using the build command and a Dockerfile: <ide>
1
Javascript
Javascript
add id to input element to fix e2e test
40319a4ce20abb2441882fa4e3f645c7d03336ae
<ide><path>src/ng/directive/input.js <ide> var inputType = { <ide> </script> <ide> <form name="myForm" ng-controller="DateController as dateCtrl"> <ide> <label>Pick a date between in 2013: <del> <input type="week" name="input" ng-model="example.value" <add> <input id="exampleInput" type="week" name="input" ng-model="example.value" <ide> placeholder="YYYY-W##" min="2012-W32" <ide> max="2013-W52" required /> <ide> </label>
1
Python
Python
add some debugging info when loglevel is debug
5713c2126caea8c4210b6d0dd600a11ac3528982
<ide><path>celery/worker/__init__.py <ide> def __init__(self, bucket_queue, hold_queue, logger): <ide> def start(self): <ide> """Start processing AMQP messages.""" <ide> task_consumer = self.reset_connection() <add> <add> self.logger.debug("AMQPListener: Starting message consumer...") <ide> it = task_consumer.iterconsume(limit=None) <ide> <add> self.logger.debug("AMQPListener: Ready to accept tasks!") <add> <ide> while True: <ide> it.next() <ide> <ide> def close_connection(self): <ide> self.task_consumer.close() <ide> self.task_consumer = None <ide> if self.amqp_connection: <add> self.logger.debug( <add> "AMQPListener: Closing connection to the broker...") <ide> self.amqp_connection.close() <ide> self.amqp_connection = None <ide> <ide> def reset_connection(self): <ide> Resets the task consumer in :attr:`task_consumer`. <ide> <ide> """ <add> self.logger.debug( <add> "AMQPListener: Re-establishing connection to the broker...") <ide> self.close_connection() <ide> self.amqp_connection = DjangoAMQPConnection() <ide> self.task_consumer = TaskConsumer(connection=self.amqp_connection) <ide> def __init__(self, concurrency=None, logfile=None, loglevel=None, <ide> self.bucket_queue = Queue() <ide> self.hold_queue = Queue() <ide> <add> self.logger.debug("Instantiating thread components...") <add> <ide> # Threads+Pool <ide> self.periodic_work_controller = PeriodicWorkController( <ide> self.bucket_queue, <ide> def start(self): <ide> self._state = "RUN" <ide> <ide> try: <del> [component.start() for component in self.components] <add> for component in self.components: <add> self.logger.debug("Starting thread %s..." % \ <add> component.__class__.__name__) <add> component.start() <ide> finally: <ide> self.stop() <ide>
1
Go
Go
remove deprecated syntax for docker commit
a0b229071394e6534808f16c4570ed8fd9ff3a1c
<ide><path>api/client/commands.go <ide> func (cli *DockerCli) CmdCommit(args ...string) error { <ide> return nil <ide> } <ide> <del> var name, repository, tag string <del> <del> if cmd.NArg() == 3 { <del> fmt.Fprintf(cli.err, "[DEPRECATED] The format 'CONTAINER [REPOSITORY [TAG]]' as been deprecated. Please use CONTAINER [REPOSITORY[:TAG]]\n") <del> name, repository, tag = cmd.Arg(0), cmd.Arg(1), cmd.Arg(2) <del> } else { <del> name = cmd.Arg(0) <add> var ( <add> name = cmd.Arg(0) <ide> repository, tag = utils.ParseRepositoryTag(cmd.Arg(1)) <del> } <add> ) <ide> <del> if name == "" { <add> if name == "" || len(cmd.Args()) > 2 { <ide> cmd.Usage() <ide> return nil <ide> }
1
Python
Python
convert sharded pt models
91e1f24ef3efd967871b2b81658db08c648275a6
<ide><path>src/transformers/commands/pt_to_tf.py <ide> is_tf_available, <ide> is_torch_available, <ide> ) <del>from ..utils import logging <add>from ..utils import TF2_WEIGHTS_INDEX_NAME, TF2_WEIGHTS_NAME, logging <ide> from . import BaseTransformersCLICommand <ide> <ide> <ide> <ide> <ide> MAX_ERROR = 5e-5 # larger error tolerance than in our internal tests, to avoid flaky user-facing errors <del>TF_WEIGHTS_NAME = "tf_model.h5" <ide> <ide> <ide> def convert_command_factory(args: Namespace): <ide> def convert_command_factory(args: Namespace): <ide> Returns: ServeCommand <ide> """ <ide> return PTtoTFCommand( <del> args.model_name, args.local_dir, args.new_weights, args.no_pr, args.push, args.extra_commit_description <add> args.model_name, <add> args.local_dir, <add> args.max_hidden_error, <add> args.new_weights, <add> args.no_pr, <add> args.push, <add> args.extra_commit_description, <ide> ) <ide> <ide> <ide> def register_subcommand(parser: ArgumentParser): <ide> default="", <ide> help="Optional local directory of the model repository. Defaults to /tmp/{model_name}", <ide> ) <add> train_parser.add_argument( <add> "--max-hidden-error", <add> type=float, <add> default=MAX_ERROR, <add> help=( <add> f"Maximum error tolerance for hidden layer outputs. Defaults to {MAX_ERROR}. If you suspect the hidden" <add> " layers outputs will be used for downstream applications, avoid increasing this tolerance." <add> ), <add> ) <ide> train_parser.add_argument( <ide> "--new-weights", <ide> action="store_true", <ide> def register_subcommand(parser: ArgumentParser): <ide> train_parser.set_defaults(func=convert_command_factory) <ide> <ide> @staticmethod <del> def find_pt_tf_differences(pt_model, pt_input, tf_model, tf_input): <add> def find_pt_tf_differences(pt_outputs, tf_outputs): <ide> """ <del> Compares the TensorFlow and PyTorch models, given their inputs, returning a dictionary with all tensor <del> differences. <add> Compares the TensorFlow and PyTorch outputs, returning a dictionary with all tensor differences. <ide> """ <del> pt_outputs = pt_model(**pt_input, output_hidden_states=True) <del> tf_outputs = tf_model(**tf_input, output_hidden_states=True) <del> <ide> # 1. All output attributes must be the same <ide> pt_out_attrs = set(pt_outputs.keys()) <ide> tf_out_attrs = set(tf_outputs.keys()) <ide> def __init__( <ide> self, <ide> model_name: str, <ide> local_dir: str, <add> max_hidden_error: float, <ide> new_weights: bool, <ide> no_pr: bool, <ide> push: bool, <ide> def __init__( <ide> self._logger = logging.get_logger("transformers-cli/pt_to_tf") <ide> self._model_name = model_name <ide> self._local_dir = local_dir if local_dir else os.path.join("/tmp", model_name) <add> self._max_hidden_error = max_hidden_error <ide> self._new_weights = new_weights <ide> self._no_pr = no_pr <ide> self._push = push <ide> def run(self): <ide> pt_model = pt_class.from_pretrained(self._local_dir) <ide> tf_from_pt_model = tf_class.from_pretrained(self._local_dir, from_pt=True) <ide> pt_input, tf_input = self.get_inputs(pt_model, config) <add> pt_outputs = pt_model(**pt_input, output_hidden_states=True) <add> del pt_model # will no longer be used, and may have a large memory footprint <add> <add> tf_from_pt_model = tf_class.from_pretrained(self._local_dir, from_pt=True) <add> tf_from_pt_outputs = tf_from_pt_model(**tf_input, output_hidden_states=True) <ide> <ide> # Confirms that cross loading PT weights into TF worked. <del> crossload_differences = self.find_pt_tf_differences(pt_model, pt_input, tf_from_pt_model, tf_input) <del> max_crossload_diff = max(crossload_differences.values()) <del> if max_crossload_diff > MAX_ERROR: <add> crossload_differences = self.find_pt_tf_differences(pt_outputs, tf_from_pt_outputs) <add> output_differences = {k: v for k, v in crossload_differences.items() if "hidden" not in k} <add> hidden_differences = {k: v for k, v in crossload_differences.items() if "hidden" in k} <add> max_crossload_output_diff = max(output_differences.values()) <add> max_crossload_hidden_diff = max(hidden_differences.values()) <add> if max_crossload_output_diff > MAX_ERROR or max_crossload_hidden_diff > self._max_hidden_error: <ide> raise ValueError( <del> "The cross-loaded TensorFlow model has different outputs, something went wrong! Exaustive list of" <del> f" maximum tensor differences above the error threshold ({MAX_ERROR}):\n" <del> + "\n".join( <del> [f"{key}: {value:.3e}" for key, value in crossload_differences.items() if value > MAX_ERROR] <del> ) <add> "The cross-loaded TensorFlow model has different outputs, something went wrong!\n" <add> + f"\nList of maximum output differences above the threshold ({MAX_ERROR}):\n" <add> + "\n".join([f"{k}: {v:.3e}" for k, v in output_differences.items() if v > MAX_ERROR]) <add> + f"\n\nList of maximum hidden layer differences above the threshold ({self._max_hidden_error}):\n" <add> + "\n".join([f"{k}: {v:.3e}" for k, v in hidden_differences.items() if v > self._max_hidden_error]) <ide> ) <ide> <ide> # Save the weights in a TF format (if needed) and confirms that the results are still good <del> tf_weights_path = os.path.join(self._local_dir, TF_WEIGHTS_NAME) <del> if not os.path.exists(tf_weights_path) or self._new_weights: <del> tf_from_pt_model.save_weights(tf_weights_path) <add> tf_weights_path = os.path.join(self._local_dir, TF2_WEIGHTS_NAME) <add> tf_weights_index_path = os.path.join(self._local_dir, TF2_WEIGHTS_INDEX_NAME) <add> if (not os.path.exists(tf_weights_path) and not os.path.exists(tf_weights_index_path)) or self._new_weights: <add> tf_from_pt_model.save_pretrained(self._local_dir) <ide> del tf_from_pt_model # will no longer be used, and may have a large memory footprint <add> <ide> tf_model = tf_class.from_pretrained(self._local_dir) <del> conversion_differences = self.find_pt_tf_differences(pt_model, pt_input, tf_model, tf_input) <del> max_conversion_diff = max(conversion_differences.values()) <del> if max_conversion_diff > MAX_ERROR: <add> tf_outputs = tf_model(**tf_input, output_hidden_states=True) <add> <add> conversion_differences = self.find_pt_tf_differences(pt_outputs, tf_outputs) <add> output_differences = {k: v for k, v in conversion_differences.items() if "hidden" not in k} <add> hidden_differences = {k: v for k, v in conversion_differences.items() if "hidden" in k} <add> max_conversion_output_diff = max(output_differences.values()) <add> max_conversion_hidden_diff = max(hidden_differences.values()) <add> if max_conversion_output_diff > MAX_ERROR or max_conversion_hidden_diff > self._max_hidden_error: <ide> raise ValueError( <del> "The converted TensorFlow model has different outputs, something went wrong! Exaustive list of maximum" <del> f" tensor differences above the error threshold ({MAX_ERROR}):\n" <del> + "\n".join( <del> [f"{key}: {value:.3e}" for key, value in conversion_differences.items() if value > MAX_ERROR] <del> ) <add> "The converted TensorFlow model has different outputs, something went wrong!\n" <add> + f"\nList of maximum output differences above the threshold ({MAX_ERROR}):\n" <add> + "\n".join([f"{k}: {v:.3e}" for k, v in output_differences.items() if v > MAX_ERROR]) <add> + f"\n\nList of maximum hidden layer differences above the threshold ({self._max_hidden_error}):\n" <add> + "\n".join([f"{k}: {v:.3e}" for k, v in hidden_differences.items() if v > self._max_hidden_error]) <ide> ) <ide> <ide> commit_message = "Update TF weights" if self._new_weights else "Add TF weights" <ide> def run(self): <ide> self._logger.warn("Uploading the weights into a new PR...") <ide> commit_descrition = ( <ide> "Model converted by the [`transformers`' `pt_to_tf`" <del> " CLI](https://github.com/huggingface/transformers/blob/main/src/transformers/commands/pt_to_tf.py)." <del> "\n\nAll converted model outputs and hidden layers were validated against its Pytorch counterpart." <del> f" Maximum crossload output difference={max_crossload_diff:.3e}; Maximum converted output" <del> f" difference={max_conversion_diff:.3e}." <add> " CLI](https://github.com/huggingface/transformers/blob/main/src/transformers/commands/pt_to_tf.py). " <add> "All converted model outputs and hidden layers were validated against its Pytorch counterpart.\n\n" <add> f"Maximum crossload output difference={max_crossload_output_diff:.3e}; " <add> f"Maximum crossload hidden layer difference={max_crossload_hidden_diff:.3e};\n" <add> f"Maximum conversion output difference={max_conversion_output_diff:.3e}; " <add> f"Maximum conversion hidden layer difference={max_conversion_hidden_diff:.3e};\n" <ide> ) <ide> if self._extra_commit_description: <ide> commit_descrition += "\n\n" + self._extra_commit_description <add> <add> # sharded model -> adds all related files (index and .h5 shards) <add> if os.path.exists(tf_weights_index_path): <add> operations = [ <add> CommitOperationAdd(path_in_repo=TF2_WEIGHTS_INDEX_NAME, path_or_fileobj=tf_weights_index_path) <add> ] <add> for shard_path in tf.io.gfile.glob(self._local_dir + "/tf_model-*.h5"): <add> operations += [ <add> CommitOperationAdd(path_in_repo=os.path.basename(shard_path), path_or_fileobj=shard_path) <add> ] <add> else: <add> operations = [CommitOperationAdd(path_in_repo=TF2_WEIGHTS_NAME, path_or_fileobj=tf_weights_path)] <add> <ide> hub_pr_url = create_commit( <ide> repo_id=self._model_name, <del> operations=[CommitOperationAdd(path_in_repo=TF_WEIGHTS_NAME, path_or_fileobj=tf_weights_path)], <add> operations=operations, <ide> commit_message=commit_message, <ide> commit_description=commit_descrition, <ide> repo_type="model", <ide><path>src/transformers/modeling_tf_pytorch_utils.py <ide> def load_pytorch_checkpoint_in_tf2_model( <ide> ) <ide> raise <ide> <del> pt_path = os.path.abspath(pytorch_checkpoint_path) <del> logger.info(f"Loading PyTorch weights from {pt_path}") <add> # Treats a single file as a collection of shards with 1 shard. <add> if isinstance(pytorch_checkpoint_path, str): <add> pytorch_checkpoint_path = [pytorch_checkpoint_path] <add> <add> # Loads all shards into a single state dictionary <add> pt_state_dict = {} <add> for path in pytorch_checkpoint_path: <add> pt_path = os.path.abspath(path) <add> logger.info(f"Loading PyTorch weights from {pt_path}") <add> pt_state_dict.update(torch.load(pt_path, map_location="cpu")) <ide> <del> pt_state_dict = torch.load(pt_path, map_location="cpu") <ide> logger.info(f"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values()):,} parameters") <ide> <ide> return load_pytorch_weights_in_tf2_model( <ide><path>src/transformers/modeling_tf_utils.py <ide> HUGGINGFACE_CO_RESOLVE_ENDPOINT, <ide> TF2_WEIGHTS_INDEX_NAME, <ide> TF2_WEIGHTS_NAME, <add> WEIGHTS_INDEX_NAME, <ide> WEIGHTS_NAME, <ide> EntryNotFoundError, <ide> ModelOutput, <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> if from_pt and os.path.isfile(os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME)): <ide> # Load from a PyTorch checkpoint in priority if from_pt <ide> archive_file = os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME) <add> elif from_pt and os.path.isfile(os.path.join(pretrained_model_name_or_path, WEIGHTS_INDEX_NAME)): <add> # Load from a sharded PyTorch checkpoint <add> archive_file = os.path.join(pretrained_model_name_or_path, WEIGHTS_INDEX_NAME) <add> is_sharded = True <ide> elif os.path.isfile(os.path.join(pretrained_model_name_or_path, TF2_WEIGHTS_NAME)): <ide> # Load from a TF 2.0 checkpoint <ide> archive_file = os.path.join(pretrained_model_name_or_path, TF2_WEIGHTS_NAME) <ide> elif os.path.isfile(os.path.join(pretrained_model_name_or_path, TF2_WEIGHTS_INDEX_NAME)): <del> # Load from a sharded PyTorch checkpoint <add> # Load from a sharded TF 2.0 checkpoint <ide> archive_file = os.path.join(pretrained_model_name_or_path, TF2_WEIGHTS_INDEX_NAME) <ide> is_sharded = True <ide> # At this stage we don't have a weight file so we will raise an error. <ide><path>tests/test_modeling_tf_common.py <ide> <ide> from datasets import Dataset <ide> <del>from huggingface_hub import HfFolder, delete_repo, set_access_token <add>from huggingface_hub import HfFolder, Repository, delete_repo, set_access_token <ide> from requests.exceptions import HTTPError <ide> from transformers import is_tf_available, is_torch_available <ide> from transformers.configuration_utils import PretrainedConfig <ide> def test_checkpoint_sharding_from_hub(self): <ide> for p1, p2 in zip(model.weights, ref_model.weights): <ide> assert np.allclose(p1.numpy(), p2.numpy()) <ide> <add> @is_pt_tf_cross_test <add> def test_checkpoint_sharding_local_from_pt(self): <add> with tempfile.TemporaryDirectory() as tmp_dir: <add> _ = Repository(local_dir=tmp_dir, clone_from="hf-internal-testing/tiny-random-bert-sharded") <add> model = TFBertModel.from_pretrained(tmp_dir, from_pt=True) <add> # the model above is the same as the model below, just a sharded pytorch version. <add> ref_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert") <add> for p1, p2 in zip(model.weights, ref_model.weights): <add> assert np.allclose(p1.numpy(), p2.numpy()) <add> <ide> def test_shard_checkpoint(self): <ide> # This is the model we will use, total size 340,000 bytes. <ide> model = tf.keras.Sequential(
4
Text
Text
fix links to issues/prs
ad0ba99d8a231da9796eb94adcfa670665ea0eed
<ide><path>CHANGELOG.md <ide> ## Bug Fixes <ide> - **$compile:** support transcluding multi-element directives <ide> ([789db8](https://github.com/angular/angular.js/commit/789db83a8ae0e2db5db13289b2c29e56093d967a), <del> [#15554](https://github.com/angular/angular.js.git/issues/15554), <del> [#15555](https://github.com/angular/angular.js.git/issues/15555)) <add> [#15554](https://github.com/angular/angular.js/issues/15554), <add> [#15555](https://github.com/angular/angular.js/issues/15555)) <ide> - **ngModel:** do not throw if view value changes on destroyed scope <ide> ([2b6c98](https://github.com/angular/angular.js/commit/2b6c9867369fd3ef1ddb687af1153478ab62ee1b), <del> [#16583](https://github.com/angular/angular.js.git/issues/16583), <del> [#16585](https://github.com/angular/angular.js.git/issues/16585)) <add> [#16583](https://github.com/angular/angular.js/issues/16583), <add> [#16585](https://github.com/angular/angular.js/issues/16585)) <ide> <ide> <ide> ## New Features <ide> - **$compile:** add one-way collection bindings <ide> ([f9d1ca](https://github.com/angular/angular.js/commit/f9d1ca20c38f065f15769fbe23aee5314cb58bd4), <del> [#14039](https://github.com/angular/angular.js.git/issues/14039), <del> [#16553](https://github.com/angular/angular.js.git/issues/16553), <del> [#15874](https://github.com/angular/angular.js.git/issues/15874)) <add> [#14039](https://github.com/angular/angular.js/issues/14039), <add> [#16553](https://github.com/angular/angular.js/issues/16553), <add> [#15874](https://github.com/angular/angular.js/issues/15874)) <ide> - **ngRef:** add directive to publish controller, or element into scope <ide> ([bf841d](https://github.com/angular/angular.js/commit/bf841d35120bf3c4655fde46af4105c85a0f1cdc), <del> [#16511](https://github.com/angular/angular.js.git/issues/16511)) <add> [#16511](https://github.com/angular/angular.js/issues/16511)) <ide> - **errorHandlingConfig:** add option to exclude error params from url <ide> ([3d6c45](https://github.com/angular/angular.js/commit/3d6c45d76e30b1b3c4eb9672cf4a93e5251c06b3), <del> [#14744](https://github.com/angular/angular.js.git/issues/14744), <del> [#15707](https://github.com/angular/angular.js.git/issues/15707), <del> [#16283](https://github.com/angular/angular.js.git/issues/16283), <del> [#16299](https://github.com/angular/angular.js.git/issues/16299), <del> [#16591](https://github.com/angular/angular.js.git/issues/16591)) <add> [#14744](https://github.com/angular/angular.js/issues/14744), <add> [#15707](https://github.com/angular/angular.js/issues/15707), <add> [#16283](https://github.com/angular/angular.js/issues/16283), <add> [#16299](https://github.com/angular/angular.js/issues/16299), <add> [#16591](https://github.com/angular/angular.js/issues/16591)) <ide> - **ngAria:** add support for ignoring a specific element <ide> ([7d9d38](https://github.com/angular/angular.js/commit/7d9d387195292cb5e04984602b752d31853cfea6), <del> [#14602](https://github.com/angular/angular.js.git/issues/14602), <del> [#14672](https://github.com/angular/angular.js.git/issues/14672), <del> [#14833](https://github.com/angular/angular.js.git/issues/14833)) <add> [#14602](https://github.com/angular/angular.js/issues/14602), <add> [#14672](https://github.com/angular/angular.js/issues/14672), <add> [#14833](https://github.com/angular/angular.js/issues/14833)) <ide> - **ngCookies:** support samesite option <ide> ([10a229](https://github.com/angular/angular.js/commit/10a229ce1befdeaf6295d1635dc11391c252a91a), <del> [#16543](https://github.com/angular/angular.js.git/issues/16543), <del> [#16544](https://github.com/angular/angular.js.git/issues/16544)) <add> [#16543](https://github.com/angular/angular.js/issues/16543), <add> [#16544](https://github.com/angular/angular.js/issues/16544)) <ide> - **ngMessages:** add support for default message <ide> ([a8c263](https://github.com/angular/angular.js/commit/a8c263c1947cc85ee60b4732f7e4bcdc7ba463e8), <del> [#12008](https://github.com/angular/angular.js.git/issues/12008), <del> [#12213](https://github.com/angular/angular.js.git/issues/12213), <del> [#16587](https://github.com/angular/angular.js.git/issues/16587)) <add> [#12008](https://github.com/angular/angular.js/issues/12008), <add> [#12213](https://github.com/angular/angular.js/issues/12213), <add> [#16587](https://github.com/angular/angular.js/issues/16587)) <ide> - **ngMock, ngMockE2E:** add option to match latest definition for `$httpBackend` request <ide> ([773f39](https://github.com/angular/angular.js/commit/773f39c9345479f5f8b6321236ce6ad96f77aa92), <del> [#16251](https://github.com/angular/angular.js.git/issues/16251), <del> [#11637](https://github.com/angular/angular.js.git/issues/11637), <del> [#16560](https://github.com/angular/angular.js.git/issues/16560)) <add> [#16251](https://github.com/angular/angular.js/issues/16251), <add> [#11637](https://github.com/angular/angular.js/issues/11637), <add> [#16560](https://github.com/angular/angular.js/issues/16560)) <ide> - **$route:** add support for the `reloadOnUrl` configuration option <ide> ([f4f571](https://github.com/angular/angular.js/commit/f4f571efdf86d6acbcd5c6b1de66b4b33a259125), <del> [#7925](https://github.com/angular/angular.js.git/issues/7925), <del> [#15002](https://github.com/angular/angular.js.git/issues/15002)) <add> [#7925](https://github.com/angular/angular.js/issues/7925), <add> [#15002](https://github.com/angular/angular.js/issues/15002)) <ide> <ide> <ide> <a name="1.7.0"></a>
1
Text
Text
match console.count()/countreset() signatures
cf44abbbfeae02505f2afe629f6cee325ef73e86
<ide><path>doc/api/console.md <ide> operates similarly to the `clear` shell command. On Windows, `console.clear()` <ide> will clear only the output in the current terminal viewport for the Node.js <ide> binary. <ide> <del>### console.count([label]) <add>### console.count([label='default']) <ide> <!-- YAML <ide> added: v8.3.0 <ide> -->
1
Ruby
Ruby
simplify a couple of comments
f052bcbd62fcb8cd3ccfc2adaf82944f27532eed
<ide><path>Library/Homebrew/formula.rb <ide> def installed? <ide> end <ide> <ide> def explicitly_requested? <del> <del> # `ARGV.formulae` will throw an exception if it comes up with an empty <del> # list. <del> # <add> # `ARGV.formulae` will throw an exception if it comes up with an empty list. <ide> # FIXME: `ARGV.formulae` shouldn't be throwing exceptions, see issue #8823 <ide> return false if ARGV.named.empty? <ide> ARGV.formulae.include? self <ide> def fails_with_llvm? <ide> # sometimes the clean process breaks things <ide> # skip cleaning paths in a formula with a class method like this: <ide> # skip_clean [bin+"foo", lib+"bar"] <del> # redefining skip_clean? in formulas is now deprecated <add> # redefining skip_clean? now deprecated <ide> def skip_clean? path <ide> return true if self.class.skip_clean_all? <ide> to_check = path.relative_path_from(prefix).to_s
1
PHP
PHP
fix error when no model scope is set
d16a9ab98eb18f63782fa2ae8800bcdc0715eaa6
<ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php <ide> public function testFormInputs() { <ide> $this->Form->create('Contact'); <ide> $result = $this->Form->inputs(null, null, array('legend' => 'Hello')); <ide> $this->assertTags($result, $expected); <add> $this->Form->end(); <add> <add> $this->Form->create(false); <add> $expected = array( <add> 'fieldset' => array(), <add> array('div' => array('class' => 'input text')), <add> 'label' => array('for' => 'foo'), <add> 'Foo', <add> '/label', <add> 'input' => array('type' => 'text', 'name' => 'data[foo]', 'id' => 'foo'), <add> '*/div', <add> '/fieldset' <add> ); <add> $result = $this->Form->inputs( <add> array('foo' => array('type' => 'text')), <add> array(), <add> array('legend' => false) <add> ); <add> $this->assertTags($result, $expected); <ide> } <ide> <ide> /** <ide><path>lib/Cake/View/Helper/FormHelper.php <ide> public function label($fieldName = null, $text = null, $options = array()) { <ide> */ <ide> public function inputs($fields = null, $blacklist = null, $options = array()) { <ide> $fieldset = $legend = true; <add> $modelFields = array(); <ide> $model = $this->model(); <del> $modelFields = array_keys($this->_introspectModel($model, 'fields')); <add> if ($model) { <add> $modelFields = array_keys($this->_introspectModel($model, 'fields')); <add> } <ide> if (is_array($fields)) { <ide> if (array_key_exists('legend', $fields) && !in_array('legend', $modelFields)) { <ide> $legend = $fields['legend'];
2
Java
Java
fix minor issue in exchangeresult
1c4babd410b88ab7543797d63c7f92fe719dbe00
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/ExchangeResult.java <ide> public HttpHeaders getResponseHeaders() { <ide> * Return response cookies received from the server. <ide> */ <ide> public MultiValueMap<String, ResponseCookie> getResponseCookies() { <del> return this.getResponseCookies(); <add> return this.response.getCookies(); <ide> } <ide> <ide> /**
1
Go
Go
fix race in read access to map
55564fda1d119bbbec46c0af98af96c30f37a355
<ide><path>libnetwork/network.go <ide> func (n *network) getSvcRecords(ep *endpoint) []etchosts.Record { <ide> epName := ep.Name() <ide> <ide> n.ctrlr.Lock() <add> defer n.ctrlr.Unlock() <ide> sr, _ := n.ctrlr.svcRecords[n.id] <del> n.ctrlr.Unlock() <ide> <ide> for h, ip := range sr.svcMap { <ide> if strings.Split(h, ".")[0] == epName {
1
Ruby
Ruby
avoid to_sym calls
5d58948fe72e3b0422790b8adc0fab7bbf9e6573
<ide><path>actionpack/lib/action_dispatch/http/response.rb <ide> def message <ide> alias_method :status_message, :message <ide> <ide> def respond_to?(method) <del> if method.to_sym == :to_path <add> if method.to_s == 'to_path' <ide> stream.respond_to?(:to_path) <ide> else <ide> super
1
Ruby
Ruby
eliminate dispatcher is_a checks
b6ec5e2c14e30bbb8a8dc434da36fc976440f2ca
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> class Mapper <ide> class Constraints #:nodoc: <ide> attr_reader :app, :constraints <ide> <del> def initialize(app, constraints, request) <add> def initialize(app, constraints, request, dispatcher_p) <ide> # Unwrap Constraints objects. I don't actually think it's possible <ide> # to pass a Constraints object to this constructor, but there were <ide> # multiple places that kept testing children of this object. I <ide> def initialize(app, constraints, request) <ide> app = app.app <ide> end <ide> <del> # Unwrap any constraints so we can see what's inside for route generation. <del> # This allows the formatter to skip over any mounted applications or redirects <del> # that shouldn't be matched when using a url_for without a route name. <del> @dispatcher = app.is_a?(Routing::RouteSet::Dispatcher) <add> @dispatcher = dispatcher_p <ide> <ide> @app, @constraints, @request = app, constraints, request <ide> end <ide> def normalize_conditions! <ide> end <ide> <ide> def app <del> endpoint = to.respond_to?(:call) ? to : dispatcher <add> # Unwrap any constraints so we can see what's inside for route generation. <add> # This allows the formatter to skip over any mounted applications or redirects <add> # that shouldn't be matched when using a url_for without a route name. <add> if to.respond_to?(:call) <add> dispatcher_p = false <add> endpoint = to <add> else <add> dispatcher_p = true <add> endpoint = dispatcher <add> end <ide> <ide> if blocks.any? <del> Constraints.new(endpoint, blocks, @set.request_class) <add> Constraints.new(endpoint, blocks, @set.request_class, dispatcher_p) <ide> else <del> Constraints.new(endpoint, blocks, @set.request_class) <add> Constraints.new(endpoint, blocks, @set.request_class, dispatcher_p) <ide> end <ide> end <ide>
1
Javascript
Javascript
fix simple/test-setproctitle on freebsd
9d02bfbc252ec24c3f8b26f6eaac2f28d8df3a6f
<ide><path>test/simple/test-setproctitle.js <ide> assert.equal(process.title, title); <ide> exec('ps -p ' + process.pid + ' -o args=', function(error, stdout, stderr) { <ide> assert.equal(error, null); <ide> assert.equal(stderr, ''); <add> <add> // freebsd always add ' (procname)' to the process title <add> if (process.platform === 'freebsd') title += ' (node)'; <add> <ide> // omitting trailing whitespace and \n <ide> assert.equal(stdout.replace(/\s+$/, ''), title); <ide> });
1
Java
Java
fix javadoc sentence warning
91346ce510b4f0a7dae0e9df30e0cb572f13a330
<ide><path>src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java <ide> public void uncaughtException(Thread t, Throwable e) { <ide> } <ide> <ide> /** <del> * Ensure set*() accepts a consumers/functions with wider bounds <add> * Ensure set*() accepts a consumers/functions with wider bounds. <ide> * @throws Exception on error <ide> */ <ide> @Test <ide><path>src/test/java/io/reactivex/schedulers/NewThreadSchedulerTest.java <ide> public void run() { <ide> } <ide> <ide> /** <del> * Regression test to ensure there is no NPE when the worker has been disposed <add> * Regression test to ensure there is no NPE when the worker has been disposed. <ide> * @throws Exception on error <ide> */ <ide> @Test
2
Text
Text
update license year for all packages
5e701daab9ed4fe0cfd7ae8aeacd7e3d9f314a04
<ide><path>license.md <ide> The MIT License (MIT) <ide> <del>Copyright (c) 2020 Vercel, Inc. <add>Copyright (c) 2021 Vercel, Inc. <ide> <ide> Permission is hereby granted, free of charge, to any person obtaining a copy <ide> of this software and associated documentation files (the "Software"), to deal <ide><path>packages/next-codemod/license.md <ide> The MIT License (MIT) <ide> <del>Copyright (c) 2020 Vercel, Inc. <add>Copyright (c) 2021 Vercel, Inc. <ide> <ide> Permission is hereby granted, free of charge, to any person obtaining a copy <ide> of this software and associated documentation files (the "Software"), to deal <ide><path>packages/next-mdx/license.md <ide> The MIT License (MIT) <ide> <del>Copyright (c) 2020 Vercel, Inc. <add>Copyright (c) 2021 Vercel, Inc. <ide> <ide> Permission is hereby granted, free of charge, to any person obtaining a copy <ide> of this software and associated documentation files (the "Software"), to deal <ide><path>packages/next/license.md <ide> The MIT License (MIT) <ide> <del>Copyright (c) 2020 Vercel, Inc. <add>Copyright (c) 2021 Vercel, Inc. <ide> <ide> Permission is hereby granted, free of charge, to any person obtaining a copy <ide> of this software and associated documentation files (the "Software"), to deal
4
Javascript
Javascript
fix typo in code comment
e679a4b6e2e3a468787827e3dfe89f13eae8486c
<ide><path>packages/react-reconciler/src/ReactFiberHooks.js <ide> type HookType = <ide> | 'useDebugValue'; <ide> <ide> // the first instance of a hook mismatch in a component, <del>// represented by a portion of it's stacktrace <add>// represented by a portion of its stacktrace <ide> let currentHookMismatchInDev = null; <ide> let isInHookUserCodeInDev = false; <ide>
1
Python
Python
add colorconsole for platform windows
78bc42d7651768e8321cffdb121007dbba9b1979
<ide><path>setup.py <ide> for mo in glob.glob('i18n/*/LC_MESSAGES/*.mo'): <ide> data_files.append((os.path.dirname(mo).replace('i18n/', 'share/locale/'), [mo])) <ide> <add>if sys.platform.startswith('win'): <add> requires = ['psutil>=0.5.1', 'colorconsole==0.6'] <add>else: <add> requires = ['psutil>=0.5.1'] <add> <ide> setup( <ide> name='Glances', <ide> version='1.7.1', <ide> # Alternative download_url='https://s3.amazonaws.com/glances/glances-1.7.1.tar.gz', <ide> license="LGPL", <ide> keywords="cli curses monitoring system", <del> install_requires=['psutil>=0.5.1'], <add> install_requires=requires, <ide> extras_require={ <ide> 'HTML': ['jinja2'], <ide> 'SENSORS': ['pysensors'],
1
Python
Python
add guillemets/chevrons to german orth variants
c39c13f26b119ad3fcac3b3d3669c3f28a7d5504
<ide><path>spacy/lang/de/__init__.py <ide> class GermanDefaults(Language.Defaults): <ide> resources = {"lemma_lookup": "lemma_lookup.json"} <ide> single_orth_variants = [{"tags": ["$("], "variants": ["…", "..."]}, <ide> {"tags": ["$("], "variants": ["-", "β€”", "–", "--", "---", "β€”β€”"]}] <del> paired_orth_variants = [{"tags": ["$("], "variants": [("'", "'"), (",", "'"), ("β€š", "β€˜")]}, <del> {"tags": ["$("], "variants": [("``", "''"), ('"', '"'), ("β€ž", "β€œ")]}] <add> paired_orth_variants = [{"tags": ["$("], "variants": [("'", "'"), (",", "'"), ("β€š", "β€˜"), ("β€Ί", "β€Ή"), ("β€Ή", "β€Ί")]}, <add> {"tags": ["$("], "variants": [("``", "''"), ('"', '"'), ("β€ž", "β€œ"), ("Β»", "Β«"), ("Β«", "Β»")]}] <ide> <ide> <ide> class German(Language):
1
Ruby
Ruby
add docs for `attr_readonly`
647f4bd17f6c1a3da51738b9da61af8567c87cc0
<ide><path>activerecord/lib/active_record/readonly_attributes.rb <ide> module ReadonlyAttributes <ide> module ClassMethods <ide> # Attributes listed as readonly will be used to create a new record but update operations will <ide> # ignore these fields. <add> # <add> # You can assign a new value to a readonly attribute, but it will be ignored when the record is updated. <add> # <add> # ==== Examples <add> # <add> # class Post < ActiveRecord::Base <add> # attr_readonly :title <add> # end <add> # <add> # post = Post.create!(title: "Introducing Ruby on Rails!") <add> # post.update(title: "a different title") # change to title will be ignored <ide> def attr_readonly(*attributes) <ide> self._attr_readonly = Set.new(attributes.map(&:to_s)) + (_attr_readonly || []) <ide> end
1
Javascript
Javascript
set statics on the navigationcard container
1343248bbe8e371ba4a4891901ec6f5ded52b7d4
<ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCard.js <ide> class NavigationCard extends React.Component<any, Props, any> { <ide> </Animated.View> <ide> ); <ide> } <del> <del> static CardStackPanResponder = NavigationCardStackPanResponder; <del> static CardStackStyleInterpolator = NavigationCardStackStyleInterpolator; <del> static PagerPanResponder = NavigationPagerPanResponder; <del> static PagerStyleInterpolator = NavigationPagerStyleInterpolator; <ide> } <ide> <ide> const styles = StyleSheet.create({ <ide> const styles = StyleSheet.create({ <ide> <ide> NavigationCard = NavigationPointerEventsContainer.create(NavigationCard); <ide> <add>// $FlowFixMe: Figure out how to declare these properties on the container class <add>NavigationCard.CardStackPanResponder = NavigationCardStackPanResponder; <add>// $FlowFixMe <add>NavigationCard.CardStackStyleInterpolator = NavigationCardStackStyleInterpolator; <add>// $FlowFixMe <add>NavigationCard.PagerPanResponder = NavigationPagerPanResponder; <add>// $FlowFixMe <add>NavigationCard.PagerStyleInterpolator = NavigationPagerStyleInterpolator; <add> <ide> module.exports = NavigationCard;
1
Javascript
Javascript
emit assets from modules during executing modules
33c862e07b3b47a79dc14f27d9c8f9a1f773dd28
<ide><path>lib/Compilation.js <ide> This prevents using hashes of each other and should be avoided.`); <ide> missingDependencies, <ide> buildDependencies <ide> ); <add> if (module.buildInfo && module.buildInfo.assets) { <add> const { assets: moduleAssets, assetsInfo } = module.buildInfo; <add> for (const assetName of Object.keys(moduleAssets)) { <add> assets.set(assetName, { <add> source: moduleAssets[assetName], <add> info: assetsInfo ? assetsInfo.get(assetName) : undefined <add> }); <add> } <add> } <ide> try { <ide> moduleCache.set(module, moduleObject); <ide> const codeGenerationResult = codeGenerationResults.get(
1
Ruby
Ruby
add elm option of webpack to generator description
038f1dc42f47e1abda8cb432bc6669616acf8611
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb <ide> module Generators <ide> RESERVED_NAMES = %w[application destroy plugin runner test] <ide> <ide> class AppGenerator < AppBase # :nodoc: <del> WEBPACKS = %w( react vue angular ) <add> WEBPACKS = %w( react vue angular elm ) <ide> <ide> add_shared_options_for "application" <ide>
1
Javascript
Javascript
hide pointlabels of hidden data
f1c99316a714df4637e3d983184c2b680cba2ae5
<ide><path>src/scales/scale.radialLinear.js <ide> function fitWithPointLabels(scale) { <ide> const labelSizes = []; <ide> const padding = []; <ide> <del> const valueCount = scale.getLabels().length; <add> const valueCount = scale._pointLabels.length; <ide> for (let i = 0; i < valueCount; i++) { <ide> const opts = scale.options.pointLabels.setContext(scale.getPointLabelContext(i)); <ide> padding[i] = opts.padding; <ide> function fitWithPointLabels(scale) { <ide> <ide> function buildPointLabelItems(scale, labelSizes, padding) { <ide> const items = []; <del> const valueCount = scale.getLabels().length; <add> const valueCount = scale._pointLabels.length; <ide> const opts = scale.options; <ide> const tickBackdropHeight = getTickBackdropHeight(opts); <ide> const outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max); <ide> export default class RadialLinearScale extends LinearScaleBase { <ide> LinearScaleBase.prototype.generateTickLabels.call(this, ticks); <ide> <ide> // Point labels <del> this._pointLabels = this.getLabels().map((value, index) => { <del> const label = callCallback(this.options.pointLabels.callback, [value, index], this); <del> return label || label === 0 ? label : ''; <del> }); <add> this._pointLabels = this.getLabels() <add> .map((value, index) => { <add> const label = callCallback(this.options.pointLabels.callback, [value, index], this); <add> return label || label === 0 ? label : ''; <add> }) <add> .filter((v, i) => this.chart.getDataVisibility(i)); <ide> } <ide> <ide> fit() { <ide> export default class RadialLinearScale extends LinearScaleBase { <ide> } <ide> <ide> getIndexAngle(index) { <del> const angleMultiplier = TAU / this.getLabels().length; <add> const angleMultiplier = TAU / this._pointLabels.length; <ide> const startAngle = this.options.startAngle || 0; <ide> return _normalizeAngle(index * angleMultiplier + toRadians(startAngle)); <ide> } <ide> export default class RadialLinearScale extends LinearScaleBase { <ide> const ctx = this.ctx; <ide> ctx.save(); <ide> ctx.beginPath(); <del> pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this.getLabels().length); <add> pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length); <ide> ctx.closePath(); <ide> ctx.fillStyle = backgroundColor; <ide> ctx.fill(); <ide> export default class RadialLinearScale extends LinearScaleBase { <ide> const ctx = this.ctx; <ide> const opts = this.options; <ide> const {angleLines, grid} = opts; <del> const labelCount = this.getLabels().length; <add> const labelCount = this._pointLabels.length; <ide> <ide> let i, offset, position; <ide> <ide> export default class RadialLinearScale extends LinearScaleBase { <ide> if (angleLines.display) { <ide> ctx.save(); <ide> <del> for (i = this.getLabels().length - 1; i >= 0; i--) { <add> for (i = labelCount - 1; i >= 0; i--) { <ide> const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i)); <ide> const {color, lineWidth} = optsAtIndex; <ide> <ide><path>test/specs/scale.radialLinear.tests.js <ide> describe('Test the radial linear scale', function() { <ide> expect(chart.scales.r._pointLabels).toEqual([0, '', '', '', '', '']); <ide> }); <ide> <add> it('Should build point labels considering hidden data', function() { <add> const chart = window.acquireChart({ <add> type: 'polarArea', <add> data: { <add> datasets: [{ <add> data: [10, 5, 0, 25, 78, 20] <add> }], <add> labels: ['a', 'b', 'c', 'd', 'e', 'f'] <add> } <add> }); <add> chart.toggleDataVisibility(3); <add> chart.update(); <add> <add> expect(chart.scales.r._pointLabels).toEqual(['a', 'b', 'c', 'e', 'f']); <add> }); <add> <ide> it('should correctly set the center point', function() { <ide> var chart = window.acquireChart({ <ide> type: 'radar',
2
Javascript
Javascript
use c-ares in lib/net.js
33e774eeba5a97af41fd17a8eb03b333a98ade33
<ide><path>lib/net.js <ide> var sys = require("sys"); <ide> var fs = require("fs"); <ide> var events = require("events"); <add>var dns = require('dns_cares'); <ide> <ide> var kMinPoolSpace = 128; <ide> var kPoolSize = 40*1024; <ide> var toRead = binding.toRead; <ide> var setNoDelay = binding.setNoDelay; <ide> var socketError = binding.socketError; <ide> var getsockname = binding.getsockname; <del>var getaddrinfo = binding.getaddrinfo; <del>var isIP = binding.isIP; <ide> var errnoException = binding.errnoException; <ide> var EINPROGRESS = binding.EINPROGRESS; <ide> var ENOENT = binding.ENOENT; <ide> Stream.prototype.connect = function () { <ide> // TODO dns resolution on arguments[1] <ide> var port = arguments[0]; <ide> self._resolving = true; <del> lookupDomainName(arguments[1], function (err, ip, isV4) { <add> dns.lookup(arguments[1], function (err, ip, addressType) { <ide> if (err) { <ide> self.emit('error', err); <ide> } else { <del> self.type = isV4 ? 'tcp4' : 'tcp6'; <add> self.type = addressType == 4 ? 'tcp4' : 'tcp6'; <ide> self.fd = socket(self.type); <ide> self._resolving = false; <ide> doConnect(self, port, ip); <ide> exports.createServer = function (listener) { <ide> return new Server(listener); <ide> }; <ide> <del>// This function does both an ipv4 and ipv6 look up. <del>// It first tries the ipv4 look up, if that fails, then it does the ipv6. <del>// callback(dn, isV4 <del>function lookupDomainName (dn, callback) { <del> var kind = isIP(dn); <del> if (kind) { <del> // Always wait until the next tick this is so people can do <del> // <del> // server.listen(8000); <del> // server.addListener('listening', fn); <del> // <del> // Marginally slower, but a lot fewer WTFs. <del> process.nextTick(function () { <del> callback(null, dn, kind == 4 ? true : false); <del> }); <del> } else { <del> debug("getaddrinfo 4 " + dn); <del> getaddrinfo(dn, 4, function (err, r4) { <del> if (err) { <del> callback(err); <del> } else if (r4.length > 0) { <del> debug("getaddrinfo 4 found " + r4); <del> callback(null, r4[0], true); <del> } else { <del> debug("getaddrinfo 6 " + dn); <del> getaddrinfo(dn, 6, function (err, r6) { <del> if (err) { <del> callback(err); <del> } else if (r6.length == 0) { <del> callback(new Error("No address associated with hostname " + dn)); <del> } else { <del> debug("getaddrinfo 6 found " + r6); <del> callback(null, r6[0], false); <del> } <del> }); <del> } <del> }); <del> } <del>} <del> <ide> <ide> // Listen on a UNIX socket <ide> // server.listen("/tmp/socket"); <ide> Server.prototype.listen = function () { <ide> } else { <ide> // the first argument is the port, the second an IP <ide> var port = arguments[0]; <del> lookupDomainName(arguments[1], function (err, ip, isV4) { <add> dns.lookup(arguments[1], function (err, ip, addressType) { <ide> if (err) { <ide> self.emit('error', err); <ide> } else { <del> self.type = isV4 ? 'tcp4' : 'tcp6'; <add> self.type = addressType == 4 ? 'tcp4' : 'tcp6'; <ide> self.fd = socket(self.type); <ide> bind(self.fd, port, ip); <ide> self._doListen();
1
Javascript
Javascript
calculate daysinmonth without date()
41d900cfd4e99b3025697e96ba4d3637dbcf632a
<ide><path>src/lib/units/month.js <ide> import { MONTH } from './constants'; <ide> import toInt from '../utils/to-int'; <ide> import isArray from '../utils/is-array'; <ide> import isNumber from '../utils/is-number'; <add>import mod from '../utils/mod'; <ide> import indexOf from '../utils/index-of'; <ide> import { createUTC } from '../create/utc'; <ide> import getParsingFlags from '../create/parsing-flags'; <add>import { isLeapYear } from '../units/year'; <ide> <ide> export function daysInMonth(year, month) { <del> return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); <add> if (isNaN(year) || isNaN(month)) { <add> return NaN; <add> } <add> var modMonth = mod(month, 12); <add> if (modMonth === month) { <add> return month === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - month % 7 % 2); <add> } <add> return daysInMonth(year + (month - modMonth) / 12, modMonth); <ide> } <ide> <ide> // FORMATTING <ide><path>src/lib/units/year.js <ide> export function daysInYear(year) { <ide> return isLeapYear(year) ? 366 : 365; <ide> } <ide> <del>function isLeapYear(year) { <add>export function isLeapYear(year) { <ide> return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; <ide> } <ide> <ide><path>src/lib/utils/mod.js <add>export default function mod(n, x) { <add> return ((n % x) + x) % x; <add>}
3
Python
Python
add words and seconds to train info
ba5f4c9b32fd2d625974af13be44677dcd75cf32
<ide><path>spacy/cli/train.py <ide> from typing import Optional, Dict, Any, Tuple, Union, Callable, List <add>from timeit import default_timer as timer <ide> import srsly <ide> import tqdm <ide> from pathlib import Path <ide> def train_while_improving( <ide> ] <ide> raw_batches = util.minibatch(raw_examples, size=8) <ide> <add> words_seen = 0 <add> start_time = timer() <ide> for step, (epoch, batch) in enumerate(train_data): <ide> dropout = next(dropouts) <ide> for subbatch in subdivide_batch(batch, accumulate_gradient): <add> <ide> nlp.update( <ide> subbatch, drop=dropout, losses=losses, sgd=False, exclude=exclude <ide> ) <ide> def train_while_improving( <ide> else: <ide> score, other_scores = (None, None) <ide> is_best_checkpoint = None <add> words_seen += sum(len(eg) for eg in batch) <ide> info = { <ide> "epoch": epoch, <ide> "step": step, <ide> "score": score, <ide> "other_scores": other_scores, <ide> "losses": losses, <ide> "checkpoints": results, <add> "seconds": int(timer() - start_time), <add> "words": words_seen, <ide> } <ide> yield batch, info, is_best_checkpoint <ide> if is_best_checkpoint is not None:
1
Ruby
Ruby
use string datatype for the setting attribute
05895c6c861597fcefb3114d78dc6cb676fec433
<ide><path>activerecord/test/schema/schema.rb <ide> def create_table(*args, &block) <ide> <ide> create_table :admin_users, :force => true do |t| <ide> t.string :name <del> t.text :settings, :null => true <add> t.string :settings, :null => true, :limit => 1024 <ide> # MySQL does not allow default values for blobs. Fake it out with a <ide> # big varchar below. <ide> t.string :preferences, :null => false, :default => '', :limit => 1024
1
Python
Python
fix minor comment typos
5444687f0f10319897d09e087258700252b1ca74
<ide><path>examples/research_projects/distillation/train.py <ide> def main(): <ide> "--alpha_mlm", <ide> default=0.0, <ide> type=float, <del> help="Linear weight for the MLM loss. Must be >=0. Should be used in coonjunction with `mlm` flag.", <add> help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.", <ide> ) <ide> parser.add_argument("--alpha_clm", default=0.5, type=float, help="Linear weight for the CLM loss. Must be >=0.") <ide> parser.add_argument("--alpha_mse", default=0.0, type=float, help="Linear weight of the MSE loss. Must be >=0.") <ide> def main(): <ide> parser.add_argument( <ide> "--restrict_ce_to_mask", <ide> action="store_true", <del> help="If true, compute the distilation loss only the [MLM] prediction distribution.", <add> help="If true, compute the distillation loss only the [MLM] prediction distribution.", <ide> ) <ide> parser.add_argument( <ide> "--freeze_pos_embs", <ide> def main(): <ide> help="Gradient accumulation for larger training batches.", <ide> ) <ide> parser.add_argument("--warmup_prop", default=0.05, type=float, help="Linear warmup proportion.") <del> parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight deay if we apply some.") <add> parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.") <ide> parser.add_argument("--learning_rate", default=5e-4, type=float, help="The initial learning rate for Adam.") <ide> parser.add_argument("--adam_epsilon", default=1e-6, type=float, help="Epsilon for Adam optimizer.") <ide> parser.add_argument("--max_grad_norm", default=5.0, type=float, help="Max gradient norm.")
1