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
|
---|---|---|---|---|---|
Ruby | Ruby | fix style of this file | 9015e37ce6335a227dd60fbfc505457a12481489 | <ide><path>actionpack/lib/action_dispatch/middleware/actionable_exceptions.rb
<ide> def redirect_to(location)
<ide> if uri.relative? || uri.scheme == "http" || uri.scheme == "https"
<ide> body = "<html><body>You are being <a href=\"#{ERB::Util.unwrapped_html_escape(location)}\">redirected</a>.</body></html>"
<ide> else
<del> return [400, {"Content-Type" => "text/plain"}, ["Invalid redirection URI"]]
<add> return [400, { "Content-Type" => "text/plain"}, ["Invalid redirection URI"]]
<ide> end
<ide>
<ide> [302, { | 1 |
PHP | PHP | remove middleware from password reset | 4036f17416549758816894dc52dc54eabcc13914 | <ide><path>app/Http/Controllers/Auth/ForgotPasswordController.php
<ide> class ForgotPasswordController extends Controller
<ide> */
<ide>
<ide> use SendsPasswordResetEmails;
<del>
<del> /**
<del> * Create a new controller instance.
<del> *
<del> * @return void
<del> */
<del> public function __construct()
<del> {
<del> $this->middleware('guest');
<del> }
<ide> }
<ide><path>app/Http/Controllers/Auth/ResetPasswordController.php
<ide> class ResetPasswordController extends Controller
<ide> * @var string
<ide> */
<ide> protected $redirectTo = '/home';
<del>
<del> /**
<del> * Create a new controller instance.
<del> *
<del> * @return void
<del> */
<del> public function __construct()
<del> {
<del> $this->middleware('guest');
<del> }
<ide> } | 2 |
PHP | PHP | add options argument to temporaryurl() | 868d6dc59b5512eddc9bceb9a81abadf1672366b | <ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php
<ide> protected function getLocalUrl($path)
<ide> *
<ide> * @param string $path
<ide> * @param \DateTimeInterface $expiration
<add> * @param array $options
<ide> * @return string
<ide> */
<del> public function temporaryUrl($path, $expiration)
<add> public function temporaryUrl($path, $expiration, array $options = [])
<ide> {
<ide> $adapter = $this->driver->getAdapter();
<ide>
<ide> public function temporaryUrl($path, $expiration)
<ide> throw new RuntimeException('This driver does not support creating temporary URLs.');
<ide> }
<ide>
<del> $command = $client->getCommand('GetObject', [
<add> $command = $client->getCommand('GetObject', array_merge([
<ide> 'Bucket' => $adapter->getBucket(),
<ide> 'Key' => $adapter->getPathPrefix().$path,
<del> ]);
<add> ], $options));
<ide>
<ide> return (string) $client->createPresignedRequest(
<ide> $command, $expiration | 1 |
Python | Python | make median work for empty arrays (issue ) | 5caf4c932e43c47d73fad761e3257bb0d4551cc2 | <ide><path>numpy/lib/function_base.py
<ide> def _median(a, axis=None, out=None, overwrite_input=False):
<ide> indexer[axis] = slice(index-1, index+1)
<ide>
<ide> # Check if the array contains any nan's
<del> if np.issubdtype(a.dtype, np.inexact):
<add> if np.issubdtype(a.dtype, np.inexact) and sz > 0:
<ide> # warn and return nans like mean would
<ide> rout = mean(part[indexer], axis=axis, out=out)
<ide> part = np.rollaxis(part, axis, part.ndim)
<ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_nan_behavior(self):
<ide> assert_equal(np.median(a, (0, 2)), b)
<ide> assert_equal(len(w), 1)
<ide>
<add> def test_empty(self):
<add> # empty arrays
<add> a = np.array([], dtype=float)
<add> with warnings.catch_warnings(record=True) as w:
<add> warnings.filterwarnings('always', '', RuntimeWarning)
<add> assert_equal(np.median(a), np.nan)
<add> assert_(w[0].category is RuntimeWarning)
<add>
<add> # multiple dimensions
<add> a = np.array([], dtype=float, ndmin=3)
<add> # no axis
<add> with warnings.catch_warnings(record=True) as w:
<add> warnings.filterwarnings('always', '', RuntimeWarning)
<add> assert_equal(np.median(a), np.nan)
<add> assert_(w[0].category is RuntimeWarning)
<add>
<add> # axis 0 and 1
<add> b = np.array([], dtype=float, ndmin=2)
<add> assert_equal(np.median(a, axis=0), b)
<add> assert_equal(np.median(a, axis=1), b)
<add>
<add> # axis 2
<add> b = np.array(np.nan, dtype=float, ndmin=2)
<add> with warnings.catch_warnings(record=True) as w:
<add> warnings.filterwarnings('always', '', RuntimeWarning)
<add> assert_equal(np.median(a, axis=2), b)
<add> assert_(w[0].category is RuntimeWarning)
<add>
<ide> def test_object(self):
<ide> o = np.arange(7.)
<ide> assert_(type(np.median(o.astype(object))), float) | 2 |
Javascript | Javascript | optimize speed of zerofill and add benchmarks | 89e3d05d45d44b8ad9aeb17c988e610853896bbd | <ide><path>benchmarks/zeroFill.js
<add>var Benchmark = require('benchmark');
<add>
<add>module.exports = {
<add> name: 'zeroFill',
<add> tests: {
<add> zeroFillMath: {
<add> setup: function() {
<add> var zeroFillMath = function(number, targetLength, forceSign) {
<add> var absNumber = '' + Math.abs(number),
<add> zerosToFill = targetLength - absNumber.length,
<add> sign = number >= 0;
<add> return (sign ? (forceSign ? '+' : '') : '-') +
<add> Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
<add> }
<add> },
<add> fn: function() {
<add> zeroFillMath(Math.random() * 1e5 | 0, 5);
<add> zeroFillMath(Math.random() * 1e5 | 0, 10);
<add> zeroFillMath(Math.random() * 1e10 | 0, 20);
<add> },
<add> async: true
<add> },
<add> zeroFillWhile: {
<add> setup: function() {
<add> var zeroFillWhile = function(number, targetLength, forceSign) {
<add> var output = '' + Math.abs(number),
<add> sign = number >= 0;
<add>
<add> while (output.length < targetLength) {
<add> output = '0' + output;
<add> }
<add> return (sign ? (forceSign ? '+' : '') : '-') + output;
<add> }
<add> },
<add> fn: function() {
<add> zeroFillWhile(Math.random() * 1e5 | 0, 5);
<add> zeroFillWhile(Math.random() * 1e5 | 0, 10);
<add> zeroFillWhile(Math.random() * 1e10 | 0, 20);
<add> },
<add> async: true
<add> }
<add> }
<add>};
<ide><path>src/lib/utils/zero-fill.js
<ide> export default function zeroFill(number, targetLength, forceSign) {
<del> var output = '' + Math.abs(number),
<add> var absNumber = '' + Math.abs(number),
<add> zerosToFill = targetLength - absNumber.length,
<ide> sign = number >= 0;
<del>
<del> while (output.length < targetLength) {
<del> output = '0' + output;
<del> }
<del> return (sign ? (forceSign ? '+' : '') : '-') + output;
<add> return (sign ? (forceSign ? '+' : '') : '-') +
<add> Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
<ide> } | 2 |
Javascript | Javascript | resolve junction targets relative to their parent | 764c5c7fd176c90513406797182cde1d0f24e1cf | <ide><path>lib/fs.js
<ide> fs.readlinkSync = function(path) {
<ide> return binding.readlink(pathModule._makeLong(path));
<ide> };
<ide>
<del>function preprocessSymlinkDestination(path, type) {
<add>function preprocessSymlinkDestination(path, type, linkPath) {
<ide> if (!isWindows) {
<ide> // No preprocessing is needed on Unix.
<ide> return path;
<ide> } else if (type === 'junction') {
<ide> // Junctions paths need to be absolute and \\?\-prefixed.
<add> // A relative target is relative to the link's parent directory.
<add> path = pathModule.resolve(linkPath, '..', path);
<ide> return pathModule._makeLong(path);
<ide> } else {
<ide> // Windows symlinks don't tolerate forward slashes.
<ide> fs.symlink = function(destination, path, type_, callback) {
<ide> if (!nullCheck(destination, callback)) return;
<ide> if (!nullCheck(path, callback)) return;
<ide>
<del> binding.symlink(preprocessSymlinkDestination(destination, type),
<add> binding.symlink(preprocessSymlinkDestination(destination, type, path),
<ide> pathModule._makeLong(path),
<ide> type,
<ide> callback);
<ide> fs.symlinkSync = function(destination, path, type) {
<ide> nullCheck(destination);
<ide> nullCheck(path);
<ide>
<del> return binding.symlink(preprocessSymlinkDestination(destination, type),
<add> return binding.symlink(preprocessSymlinkDestination(destination, type, path),
<ide> pathModule._makeLong(path),
<ide> type);
<ide> };
<ide><path>test/simple/test-fs-symlink-dir-junction-relative.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var path = require('path');
<add>var fs = require('fs');
<add>var completed = 0;
<add>var expected_tests = 4;
<add>
<add>// test creating and reading symbolic link
<add>var linkData = path.join(common.fixturesDir, 'cycles/');
<add>var linkPath = path.join(common.tmpDir, 'cycles_link');
<add>var relative = '../fixtures/cycles'
<add>
<add>// Delete previously created link
<add>try {
<add> fs.unlinkSync(linkPath);
<add>} catch (e) {}
<add>
<add>console.log('linkData: ' + linkData);
<add>console.log('linkPath: ' + linkPath);
<add>console.log('relative target: ' + relative)
<add>
<add>fs.symlink(relative, linkPath, 'junction', function(err) {
<add> if (err) throw err;
<add> completed++;
<add>
<add> fs.lstat(linkPath, function(err, stats) {
<add> if (err) throw err;
<add> assert.ok(stats.isSymbolicLink());
<add> completed++;
<add>
<add> fs.readlink(linkPath, function(err, destination) {
<add> if (err) throw err;
<add> assert.equal(destination, linkData);
<add> completed++;
<add>
<add> fs.unlink(linkPath, function(err) {
<add> if (err) throw err;
<add> assert(!fs.existsSync(linkPath));
<add> assert(fs.existsSync(linkData));
<add> completed++;
<add> });
<add> });
<add> });
<add>});
<add>
<add>process.on('exit', function() {
<add> assert.equal(completed, expected_tests);
<add>});
<add> | 2 |
Text | Text | add article for balanced-brackets | 90036cc711a81bf3f8c32b6ee568f333b55f100d | <ide><path>guide/english/certifications/coding-interview-prep/rosetta-code/balanced-brackets/index.md
<ide> This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/
<ide> <a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<ide>
<ide> <!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>### Basic Solution
<add>```js
<add>function isBalanced(str) {
<add> if (str === '') return true;
<add>
<add> str = str.split('');
<add> let stack = [];
<add> for (let i = 0; i < str.length; i++) {
<add> if (str[i] === '[') {
<add> stack.push('[');
<add> } else if (str[i] === ']' && stack[stack.length - 1] === '[') {
<add> stack.pop();
<add> }
<add> }
<add> return stack.length === 0;
<add>}
<add>```
<add>
<add>#### Code Explanation
<add>- Split the input string into individual characters & loop over them.
<add>- Push every `[` into a stack.
<add>- Check if the item stored on the stack is `[` when a `]` occurs. This makes it a pair & `[` can be removed from the stack.
<add>- The brackets are balanced if there is no item present in the stack. | 1 |
Javascript | Javascript | fix flakiness in test-http2-client-upload | 09b0b1bd484c3bcdfa932c8712680f0bfbc2db02 | <ide><path>test/parallel/test-http2-client-upload.js
<ide> fs.readFile(loc, common.mustCall((err, data) => {
<ide>
<ide> server.listen(0, common.mustCall(() => {
<ide> const client = http2.connect(`http://localhost:${server.address().port}`);
<add>
<add> let remaining = 2;
<add> function maybeClose() {
<add> if (--remaining === 0) {
<add> server.close();
<add> client.destroy();
<add> }
<add> }
<add>
<ide> const req = client.request({ ':method': 'POST' });
<ide> req.on('response', common.mustCall());
<ide> req.resume();
<del> req.on('end', common.mustCall(() => {
<del> server.close();
<del> client.destroy();
<del> }));
<del> fs.createReadStream(loc).pipe(req);
<add> req.on('end', common.mustCall(maybeClose));
<add> const str = fs.createReadStream(loc);
<add> str.on('end', common.mustCall(maybeClose));
<add> str.pipe(req);
<ide> }));
<ide> })); | 1 |
Mixed | Java | add various concatxdelayerror operators | 9283700d3a04d495b0845f947ed119c1ed10ee94 | <ide><path>docs/Operator-Matrix.md
<ide> Operator | |||||
<ide> <a name='concat'></a>`concat`||||||
<ide> <a name='concatArray'></a>`concatArray`||||||
<del><a name='concatArrayDelayError'></a>`concatArrayDelayError`||||||
<add><a name='concatArrayDelayError'></a>`concatArrayDelayError`||||||
<ide> <a name='concatArrayEager'></a>`concatArrayEager`||||| <sup title='No items to keep ordered. Use mergeArray().'>([24](#notes-24))</sup>|
<del><a name='concatArrayEagerDelayError'></a>`concatArrayEagerDelayError`||||| <sup title='No items to keep ordered. Use mergeArrayDelayError().'>([25](#notes-25))</sup>|
<del><a name='concatDelayError'></a>`concatDelayError`||||||
<add><a name='concatArrayEagerDelayError'></a>`concatArrayEagerDelayError`||||| <sup title='No items to keep ordered. Use mergeArrayDelayError().'>([25](#notes-25))</sup>|
<add><a name='concatDelayError'></a>`concatDelayError`||||||
<ide> <a name='concatEager'></a>`concatEager`||||| <sup title='No items to keep ordered. Use merge().'>([26](#notes-26))</sup>|
<ide> <a name='concatMap'></a>`concatMap`||||| <sup title='Always empty thus no items to map.'>([27](#notes-27))</sup>|
<ide> <a name='concatMapCompletable'></a>`concatMapCompletable`||||| <sup title='Always empty thus no items to map.'>([27](#notes-27))</sup>|
<ide> Operator | |||| <sup title='Use merge().'>([111](#notes-111))</sup>|
<ide> <a name='zipArray'></a>`zipArray`||||| <sup title='Use mergeArray().'>([112](#notes-112))</sup>|
<ide> <a name='zipWith'></a>`zipWith`||||| <sup title='Use mergeWith().'>([113](#notes-113))</sup>|
<del><a name='total'></a>**237 operators** | **215** | **209** | **115** | **100** | **78** |
<add><a name='total'></a>**237 operators** | **215** | **209** | **116** | **103** | **80** |
<ide>
<ide> #### Notes
<ide> <a name='notes-1'></a><sup>1</sup> Use [`contains()`](#contains).<br/>
<ide> Operator | 
<del>2. Completable.concatArrayDelayError()
<del>3. Maybe.concatArrayEagerDelayError()
<del>4. Single.concatArrayEagerDelayError()
<del>5. Single.concatDelayError()
<del>6. Completable.concatDelayError()
<del>7. Single.mergeArray()
<del>8. Single.mergeArrayDelayError()
<del>9. Completable.onErrorReturn()
<del>10. Completable.onErrorReturnItem()
<del>11. Maybe.safeSubscribe()
<del>12. Single.safeSubscribe()
<del>13. Completable.safeSubscribe()
<del>14. Completable.sequenceEqual()
<del>15. Maybe.startWith()
<del>16. Single.startWith()
<add>1. Single.mergeArray()
<add>2. Single.mergeArrayDelayError()
<add>3. Completable.onErrorReturn()
<add>4. Completable.onErrorReturnItem()
<add>5. Maybe.safeSubscribe()
<add>6. Single.safeSubscribe()
<add>7. Completable.safeSubscribe()
<add>8. Completable.sequenceEqual()
<add>9. Maybe.startWith()
<add>10. Single.startWith()
<ide><path>src/main/java/io/reactivex/rxjava3/core/Completable.java
<ide> public static Completable concatArray(@NonNull CompletableSource... sources) {
<ide> return RxJavaPlugins.onAssembly(new CompletableConcatArray(sources));
<ide> }
<ide>
<add> /**
<add> * Returns a {@code Completable} which completes only when all sources complete, one after another.
<add> * <p>
<add> * <img width="640" height="322" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.concatArrayDelayError.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param sources the sources to concatenate
<add> * @return the new {@code Completable} instance
<add> * @throws NullPointerException if {@code sources} is {@code null}
<add> * @since 3.0.0
<add> */
<add> @CheckReturnValue
<add> @NonNull
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @SafeVarargs
<add> public static Completable concatArrayDelayError(@NonNull CompletableSource... sources) {
<add> return Flowable.fromArray(sources).concatMapCompletableDelayError(Functions.identity(), true, 2);
<add> }
<add>
<ide> /**
<ide> * Returns a {@code Completable} which completes only when all sources complete, one after another.
<ide> * <p>
<ide> public static Completable concat(@NonNull Publisher<@NonNull ? extends Completab
<ide> return RxJavaPlugins.onAssembly(new CompletableConcat(sources, prefetch));
<ide> }
<ide>
<add> /**
<add> * Returns a {@code Completable} which completes only when all sources complete, one after another.
<add> * <p>
<add> * <img width="640" height="361" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.concatDelayError.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param sources the sources to concatenate
<add> * @return the new {@code Completable} instance
<add> * @throws NullPointerException if {@code sources} is {@code null}
<add> * @since 3.0.0
<add> */
<add> @CheckReturnValue
<add> @NonNull
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public static Completable concatDelayError(@NonNull Iterable<@NonNull ? extends CompletableSource> sources) {
<add> return Flowable.fromIterable(sources).concatMapCompletableDelayError(Functions.identity());
<add> }
<add>
<add> /**
<add> * Returns a {@code Completable} which completes only when all sources complete, one after another.
<add> * <p>
<add> * <img width="640" height="396" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.concatDelayError.p.png" alt="">
<add> * <dl>
<add> * <dt><b>Backpressure:</b></dt>
<add> * <dd>The returned {@code Completable} honors the backpressure of the downstream consumer
<add> * and expects the other {@link Publisher} to honor it as well.</dd>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param sources the sources to concatenate
<add> * @return the new {@code Completable} instance
<add> * @throws NullPointerException if {@code sources} is {@code null}
<add> * @since 3.0.0
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @NonNull
<add> public static Completable concatDelayError(@NonNull Publisher<@NonNull ? extends CompletableSource> sources) {
<add> return concatDelayError(sources, 2);
<add> }
<add>
<add> /**
<add> * Returns a {@code Completable} which completes only when all sources complete, one after another.
<add> * <p>
<add> * <img width="640" height="359" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.concatDelayError.pn.png" alt="">
<add> * <dl>
<add> * <dt><b>Backpressure:</b></dt>
<add> * <dd>The returned {@code Completable} honors the backpressure of the downstream consumer
<add> * and expects the other {@link Publisher} to honor it as well.</dd>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param sources the sources to concatenate
<add> * @param prefetch the number of sources to prefetch from the sources
<add> * @return the new {@code Completable} instance
<add> * @throws NullPointerException if {@code sources} is {@code null}
<add> * @throws IllegalArgumentException if {@code prefetch} is non-positive
<add> * @since 3.0.0
<add> */
<add> @CheckReturnValue
<add> @NonNull
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> public static Completable concatDelayError(@NonNull Publisher<@NonNull ? extends CompletableSource> sources, int prefetch) {
<add> return Flowable.fromPublisher(sources).concatMapCompletableDelayError(Functions.identity(), true, prefetch);
<add> }
<add>
<ide> /**
<ide> * Provides an API (via a cold {@code Completable}) that bridges the reactive world with the callback-style world.
<ide> * <p>
<ide><path>src/main/java/io/reactivex/rxjava3/core/Maybe.java
<ide> public static <T> Flowable<T> concatArrayDelayError(@NonNull MaybeSource<? exten
<ide> public static <T> Flowable<T> concatArrayEager(@NonNull MaybeSource<? extends T>... sources) {
<ide> return Flowable.fromArray(sources).concatMapEager((Function)MaybeToPublisher.instance());
<ide> }
<add> /**
<add> * Concatenates a sequence of {@link MaybeSource} eagerly into a {@link Flowable} sequence.
<add> * <p>
<add> * Eager concatenation means that once an observer subscribes, this operator subscribes to all of the
<add> * source {@code MaybeSource}s. The operator buffers the value emitted by these {@code MaybeSource}s and then drains them
<add> * in order, each one after the previous one completes.
<add> * <p>
<add> * <img width="640" height="428" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArrayEagerDelayError.png" alt="">
<add> * <dl>
<add> * <dt><b>Backpressure:</b></dt>
<add> * <dd>The operator honors backpressure from downstream.</dd>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <T> the value type
<add> * @param sources a sequence of {@code MaybeSource}s that need to be eagerly concatenated
<add> * @return the new {@code Flowable} instance with the specified concatenation behavior
<add> * @throws NullPointerException if {@code sources} is {@code null}
<add> * @since 3.0.0
<add> */
<add> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @NonNull
<add> @SafeVarargs
<add> public static <T> Flowable<T> concatArrayEagerDelayError(@NonNull MaybeSource<? extends T>... sources) {
<add> return Flowable.fromArray(sources).concatMapEagerDelayError((Function)MaybeToPublisher.instance(), true);
<add> }
<ide>
<ide> /**
<ide> * Concatenates the {@link Iterable} sequence of {@link MaybeSource}s into a single sequence by subscribing to each {@code MaybeSource},
<ide> * one after the other, one at a time and delays any errors till the all inner {@code MaybeSource}s terminate
<ide> * as a {@link Flowable} sequence.
<ide> * <p>
<del> * <img width="640" height="469" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatDelayError.i.png" alt="">
<add> * <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatDelayError3.i.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The operator honors backpressure from downstream.</dd>
<ide> public static <T> Flowable<T> concatArrayEager(@NonNull MaybeSource<? extends T>
<ide> * @return the new {@code Flowable} with the concatenating behavior
<ide> * @throws NullPointerException if {@code sources} is {@code null}
<ide> */
<del> @SuppressWarnings({ "unchecked", "rawtypes" })
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @CheckReturnValue
<ide> @NonNull
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public static <T> Flowable<T> concatDelayError(@NonNull Iterable<@NonNull ? extends MaybeSource<? extends T>> sources) {
<del> Objects.requireNonNull(sources, "sources is null");
<del> return Flowable.fromIterable(sources).concatMapDelayError((Function)MaybeToPublisher.instance());
<add> return Flowable.fromIterable(sources).concatMapMaybeDelayError(Functions.identity());
<ide> }
<ide>
<ide> /**
<ide> public static <T> Flowable<T> concatDelayError(@NonNull Iterable<@NonNull ? exte
<ide> * @return the new {@code Flowable} with the concatenating behavior
<ide> * @throws NullPointerException if {@code sources} is {@code null}
<ide> */
<del> @SuppressWarnings({ "unchecked", "rawtypes" })
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> @NonNull
<ide> public static <T> Flowable<T> concatDelayError(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources) {
<del> return Flowable.fromPublisher(sources).concatMapDelayError((Function)MaybeToPublisher.instance());
<add> return Flowable.fromPublisher(sources).concatMapMaybeDelayError(Functions.identity());
<add> }
<add> /**
<add> * Concatenates the {@link Publisher} sequence of {@link MaybeSource}s into a single sequence by subscribing to each inner {@code MaybeSource},
<add> * one after the other, one at a time and delays any errors till the all inner and the outer {@code Publisher} terminate
<add> * as a {@link Flowable} sequence.
<add> * <p>
<add> * <img width="640" height="299" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatDelayError.pn.png" alt="">
<add> * <dl>
<add> * <dt><b>Backpressure:</b></dt>
<add> * <dd>{@code concatDelayError} fully supports backpressure.</dd>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param <T> the common element base type
<add> * @param sources the {@code Publisher} sequence of {@code MaybeSource}s
<add> * @param prefetch The number of upstream items to prefetch so that fresh items are
<add> * ready to be mapped when a previous {@code MaybeSource} terminates.
<add> * The operator replenishes after half of the prefetch amount has been consumed
<add> * and turned into {@code MaybeSource}s.
<add> * @return the new {@code Flowable} with the concatenating behavior
<add> * @throws NullPointerException if {@code sources} is {@code null}
<add> * @throws IllegalArgumentException if {@code prefetch} is non-positive
<add> */
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @NonNull
<add> public static <T> Flowable<T> concatDelayError(@NonNull Publisher<@NonNull ? extends MaybeSource<? extends T>> sources, int prefetch) {
<add> return Flowable.fromPublisher(sources).concatMapMaybeDelayError(Functions.identity(), true, prefetch);
<ide> }
<ide>
<ide> /**
<ide><path>src/main/java/io/reactivex/rxjava3/core/Single.java
<ide> public static <T> Flowable<T> concat(
<ide> @NonNull
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @SuppressWarnings({ "unchecked", "rawtypes" })
<ide> @SafeVarargs
<ide> public static <T> Flowable<T> concatArray(@NonNull SingleSource<? extends T>... sources) {
<del> return RxJavaPlugins.onAssembly(new FlowableConcatMap(Flowable.fromArray(sources), SingleInternalHelper.toFlowable(), 2, ErrorMode.BOUNDARY));
<add> return Flowable.fromArray(sources).concatMap(SingleInternalHelper.toFlowable(), 2);
<add> }
<add>
<add> /**
<add> * Concatenate the single values, in a non-overlapping fashion, of the {@link SingleSource}s provided in
<add> * an array.
<add> * <p>
<add> * <img width="640" height="408" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatArrayDelayError.png" alt="">
<add> * <dl>
<add> * <dt><b>Backpressure:</b></dt>
<add> * <dd>The returned {@link Flowable} honors the backpressure of the downstream consumer.</dd>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <T> the value type
<add> * @param sources the array of {@code SingleSource} instances
<add> * @return the new {@code Flowable} instance
<add> * @throws NullPointerException if {@code sources} is {@code null}
<add> * @since 3.0.0
<add> */
<add> @CheckReturnValue
<add> @NonNull
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @SafeVarargs
<add> public static <T> Flowable<T> concatArrayDelayError(@NonNull SingleSource<? extends T>... sources) {
<add> return Flowable.fromArray(sources).concatMapDelayError(SingleInternalHelper.toFlowable(), true, 2);
<ide> }
<ide>
<ide> /**
<ide> public static <T> Flowable<T> concatArrayEager(@NonNull SingleSource<? extends T
<ide> return Flowable.fromArray(sources).concatMapEager(SingleInternalHelper.toFlowable());
<ide> }
<ide>
<add> /**
<add> * Concatenates a sequence of {@link SingleSource} eagerly into a single stream of values.
<add> * <p>
<add> * <img width="640" height="426" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatArrayEagerDelayError.png" alt="">
<add> * <p>
<add> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the
<add> * source {@code SingleSource}s. The operator buffers the value emitted by these {@code SingleSource}s and then drains them
<add> * in order, each one after the previous one succeeds.
<add> * <dl>
<add> * <dt><b>Backpressure:</b></dt>
<add> * <dd>The operator honors backpressure from downstream.</dd>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <T> the value type
<add> * @param sources a sequence of {@code SingleSource}s that need to be eagerly concatenated
<add> * @return the new {@link Flowable} instance with the specified concatenation behavior
<add> * @throws NullPointerException if {@code sources} is {@code null}
<add> * @since 3.0.0
<add> */
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @CheckReturnValue
<add> @NonNull
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @SafeVarargs
<add> public static <T> Flowable<T> concatArrayEagerDelayError(@NonNull SingleSource<? extends T>... sources) {
<add> return Flowable.fromArray(sources).concatMapEagerDelayError(SingleInternalHelper.toFlowable(), true);
<add> }
<add>
<ide> /**
<ide> * Concatenates a {@link Publisher} sequence of {@link SingleSource}s eagerly into a single stream of values.
<ide> * <p>
<ide> public static <T> Flowable<T> concatEager(@NonNull Publisher<@NonNull ? extends
<ide> return Flowable.fromPublisher(sources).concatMapEager(SingleInternalHelper.toFlowable());
<ide> }
<ide>
<add> /**
<add> * Concatenates the {@link Iterable} sequence of {@link SingleSource}s into a single sequence by subscribing to each {@code SingleSource},
<add> * one after the other, one at a time and delays any errors till the all inner {@code SingleSource}s terminate
<add> * as a {@link Flowable} sequence.
<add> * <p>
<add> * <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatDelayError.i.png" alt="">
<add> * <dl>
<add> * <dt><b>Backpressure:</b></dt>
<add> * <dd>The operator honors backpressure from downstream.</dd>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param <T> the common element base type
<add> * @param sources the {@code Iterable} sequence of {@code SingleSource}s
<add> * @return the new {@code Flowable} with the concatenating behavior
<add> * @throws NullPointerException if {@code sources} is {@code null}
<add> * @since 3.0.0
<add> */
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @CheckReturnValue
<add> @NonNull
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public static <T> Flowable<T> concatDelayError(@NonNull Iterable<@NonNull ? extends SingleSource<? extends T>> sources) {
<add> return Flowable.fromIterable(sources).concatMapSingleDelayError(Functions.identity());
<add> }
<add>
<add> /**
<add> * Concatenates the {@link Publisher} sequence of {@link SingleSource}s into a single sequence by subscribing to each inner {@code SingleSource},
<add> * one after the other, one at a time and delays any errors till the all inner and the outer {@code Publisher} terminate
<add> * as a {@link Flowable} sequence.
<add> * <p>
<add> * <img width="640" height="345" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatDelayError.p.png" alt="">
<add> * <dl>
<add> * <dt><b>Backpressure:</b></dt>
<add> * <dd>{@code concatDelayError} fully supports backpressure.</dd>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param <T> the common element base type
<add> * @param sources the {@code Publisher} sequence of {@code SingleSource}s
<add> * @return the new {@code Flowable} with the concatenating behavior
<add> * @throws NullPointerException if {@code sources} is {@code null}
<add> * @since 3.0.0
<add> */
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @NonNull
<add> public static <T> Flowable<T> concatDelayError(@NonNull Publisher<@NonNull ? extends SingleSource<? extends T>> sources) {
<add> return Flowable.fromPublisher(sources).concatMapSingleDelayError(Functions.identity());
<add> }
<add>
<add> /**
<add> * Concatenates the {@link Publisher} sequence of {@link SingleSource}s into a single sequence by subscribing to each inner {@code SingleSource},
<add> * one after the other, one at a time and delays any errors till the all inner and the outer {@code Publisher} terminate
<add> * as a {@link Flowable} sequence.
<add> * <p>
<add> * <img width="640" height="299" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatDelayError.pn.png" alt="">
<add> * <dl>
<add> * <dt><b>Backpressure:</b></dt>
<add> * <dd>{@code concatDelayError} fully supports backpressure.</dd>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param <T> the common element base type
<add> * @param sources the {@code Publisher} sequence of {@code SingleSource}s
<add> * @param prefetch The number of upstream items to prefetch so that fresh items are
<add> * ready to be mapped when a previous {@code SingleSource} terminates.
<add> * The operator replenishes after half of the prefetch amount has been consumed
<add> * and turned into {@code SingleSource}s.
<add> * @return the new {@code Flowable} with the concatenating behavior
<add> * @throws NullPointerException if {@code sources} is {@code null}
<add> * @throws IllegalArgumentException if {@code prefetch} is non-positive
<add> * @since 3.0.0
<add> */
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @NonNull
<add> public static <T> Flowable<T> concatDelayError(@NonNull Publisher<@NonNull ? extends SingleSource<? extends T>> sources, int prefetch) {
<add> return Flowable.fromPublisher(sources).concatMapSingleDelayError(Functions.identity(), true, prefetch);
<add> }
<add>
<ide> /**
<ide> * Concatenates an {@link Iterable} sequence of {@link SingleSource}s eagerly into a single stream of values.
<ide> * <p>
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/completable/CompletableConcatArrayDelayErrorTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.rxjava3.internal.operators.completable;
<add>
<add>import static org.mockito.Mockito.*;
<add>import org.junit.Test;
<add>
<add>import io.reactivex.rxjava3.core.Completable;
<add>import io.reactivex.rxjava3.exceptions.TestException;
<add>import io.reactivex.rxjava3.functions.Action;
<add>
<add>public class CompletableConcatArrayDelayErrorTest {
<add>
<add> @Test
<add> public void normal() throws Throwable {
<add> Action action1 = mock(Action.class);
<add> Action action2 = mock(Action.class);
<add>
<add> Completable.concatArrayDelayError(
<add> Completable.fromAction(action1),
<add> Completable.error(new TestException()),
<add> Completable.fromAction(action2)
<add> )
<add> .test()
<add> .assertFailure(TestException.class);
<add>
<add> verify(action1).run();
<add>
<add> verify(action2).run();
<add> }
<add>
<add>}
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/completable/CompletableConcatDelayErrorTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.rxjava3.internal.operators.completable;
<add>
<add>import static org.mockito.Mockito.*;
<add>
<add>import java.util.Arrays;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.rxjava3.core.*;
<add>import io.reactivex.rxjava3.exceptions.TestException;
<add>import io.reactivex.rxjava3.functions.Action;
<add>
<add>public class CompletableConcatDelayErrorTest {
<add>
<add> @Test
<add> public void normalIterable() throws Throwable {
<add> Action action1 = mock(Action.class);
<add> Action action2 = mock(Action.class);
<add>
<add> Completable.concatDelayError(Arrays.asList(
<add> Completable.fromAction(action1),
<add> Completable.error(new TestException()),
<add> Completable.fromAction(action2)
<add> ))
<add> .test()
<add> .assertFailure(TestException.class);
<add>
<add> verify(action1).run();
<add>
<add> verify(action2).run();
<add> }
<add>
<add> @Test
<add> public void normalPublisher() throws Throwable {
<add> Action action1 = mock(Action.class);
<add> Action action2 = mock(Action.class);
<add>
<add> Completable.concatDelayError(Flowable.fromArray(
<add> Completable.fromAction(action1),
<add> Completable.error(new TestException()),
<add> Completable.fromAction(action2)
<add> ))
<add> .test()
<add> .assertFailure(TestException.class);
<add>
<add> verify(action1).run();
<add>
<add> verify(action2).run();
<add> }
<add>
<add> @Test
<add> public void normalPublisherPrefetch() throws Throwable {
<add> Action action1 = mock(Action.class);
<add> Action action2 = mock(Action.class);
<add>
<add> Completable.concatDelayError(Flowable.fromArray(
<add> Completable.fromAction(action1),
<add> Completable.error(new TestException()),
<add> Completable.fromAction(action2)
<add> ), 1)
<add> .test()
<add> .assertFailure(TestException.class);
<add>
<add> verify(action1).run();
<add>
<add> verify(action2).run();
<add> }
<add>
<add>}
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeConcatArrayEagerDelayErrorTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.rxjava3.internal.operators.maybe;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.rxjava3.core.Maybe;
<add>import io.reactivex.rxjava3.exceptions.TestException;
<add>
<add>public class MaybeConcatArrayEagerDelayErrorTest {
<add>
<add> @Test
<add> public void normal() {
<add> Maybe.concatArrayEagerDelayError(
<add> Maybe.just(1),
<add> Maybe.<Integer>error(new TestException()),
<add> Maybe.empty(),
<add> Maybe.just(2)
<add> )
<add> .test()
<add> .assertFailure(TestException.class, 1, 2);
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/single/SingleConcatArrayDelayErrorTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.rxjava3.internal.operators.single;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.rxjava3.core.Single;
<add>import io.reactivex.rxjava3.exceptions.TestException;
<add>
<add>public class SingleConcatArrayDelayErrorTest {
<add>
<add> @Test
<add> public void normal() {
<add> Single.concatArrayDelayError(
<add> Single.just(1),
<add> Single.<Integer>error(new TestException()),
<add> Single.just(2)
<add> )
<add> .test()
<add> .assertFailure(TestException.class, 1, 2);
<add> }
<add>
<add>}
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/single/SingleConcatArrayEagerDelayErrorTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.rxjava3.internal.operators.single;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.rxjava3.core.Single;
<add>import io.reactivex.rxjava3.exceptions.TestException;
<add>
<add>public class SingleConcatArrayEagerDelayErrorTest {
<add>
<add> @Test
<add> public void normal() {
<add> Single.concatArrayEagerDelayError(
<add> Single.just(1),
<add> Single.<Integer>error(new TestException()),
<add> Single.just(2)
<add> )
<add> .test()
<add> .assertFailure(TestException.class, 1, 2);
<add> }
<add>
<add>}
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/single/SingleConcatDelayErrorTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.rxjava3.internal.operators.single;
<add>
<add>import java.util.Arrays;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.rxjava3.core.*;
<add>import io.reactivex.rxjava3.exceptions.TestException;
<add>
<add>public class SingleConcatDelayErrorTest {
<add>
<add> @Test
<add> public void normalIterable() {
<add> Single.concatDelayError(Arrays.asList(
<add> Single.just(1),
<add> Single.<Integer>error(new TestException()),
<add> Single.just(2)
<add> ))
<add> .test()
<add> .assertFailure(TestException.class, 1, 2);
<add> }
<add>
<add> @Test
<add> public void normalPublisher() {
<add> Single.concatDelayError(Flowable.fromArray(
<add> Single.just(1),
<add> Single.<Integer>error(new TestException()),
<add> Single.just(2)
<add> ))
<add> .test()
<add> .assertFailure(TestException.class, 1, 2);
<add> }
<add>
<add> @Test
<add> public void normalPublisherPrefetch() {
<add> Single.concatDelayError(Flowable.fromArray(
<add> Single.just(1),
<add> Single.<Integer>error(new TestException()),
<add> Single.just(2)
<add> ), 1)
<add> .test()
<add> .assertFailure(TestException.class, 1, 2);
<add> }
<add>
<add>}
<ide><path>src/test/java/io/reactivex/rxjava3/maybe/MaybeTest.java
<ide> public void concatPublisherDelayError() {
<ide> .assertFailure(TestException.class, 1);
<ide> }
<ide>
<add> @Test
<add> public void concatPublisherDelayErrorPrefetch() {
<add> Maybe.concatDelayError(Flowable.just(Maybe.empty(), Maybe.just(1), Maybe.error(new TestException())), 1)
<add> .test()
<add> .assertFailure(TestException.class, 1);
<add>
<add> Maybe.concatDelayError(Flowable.just(Maybe.error(new TestException()), Maybe.empty(), Maybe.just(1)), 1)
<add> .test()
<add> .assertFailure(TestException.class, 1);
<add> }
<add>
<ide> @Test
<ide> public void concatEagerArray() {
<ide> PublishProcessor<Integer> pp1 = PublishProcessor.create(); | 11 |
PHP | PHP | add `force` option to some generators | 897e48d14860db18c9285187ca6c29e150b9ff30 | <ide><path>src/Illuminate/Foundation/Console/MailMakeCommand.php
<ide> class MailMakeCommand extends GeneratorCommand
<ide> */
<ide> public function fire()
<ide> {
<del> if (parent::fire() === false) {
<add> if (parent::fire() === false && !$this->option('force')) {
<ide> return;
<ide> }
<ide>
<ide> protected function getOptions()
<ide> {
<ide> return [
<ide> ['markdown', 'm', InputOption::VALUE_OPTIONAL, 'Create a new Markdown template for the mailable.'],
<add>
<add> ['force', 'f', InputOption::VALUE_NONE, 'Force the generator to continue execution even if the mail already exists.'],
<ide> ];
<ide> }
<ide> }
<ide><path>src/Illuminate/Foundation/Console/ModelMakeCommand.php
<ide> class ModelMakeCommand extends GeneratorCommand
<ide> */
<ide> public function fire()
<ide> {
<del> if (parent::fire() === false) {
<add> if (parent::fire() === false && !$this->option('force')) {
<ide> return;
<ide> }
<ide>
<ide> protected function getOptions()
<ide>
<ide> ['controller', 'c', InputOption::VALUE_NONE, 'Create a new controller for the model.'],
<ide>
<del> ['resource', 'r', InputOption::VALUE_NONE, 'Indicates if the generated controller should be a resource controller'],
<add> ['resource', 'r', InputOption::VALUE_NONE, 'Indicates if the generated controller should be a resource controller.'],
<add>
<add> ['force', 'f', InputOption::VALUE_NONE, 'Force the generator to continue execution even if the model already exists.'],
<ide> ];
<ide> }
<ide> }
<ide><path>src/Illuminate/Foundation/Console/NotificationMakeCommand.php
<ide> class NotificationMakeCommand extends GeneratorCommand
<ide> */
<ide> public function fire()
<ide> {
<del> if (parent::fire() === false) {
<add> if (parent::fire() === false && !$this->option('force')) {
<ide> return;
<ide> }
<ide>
<ide> protected function getOptions()
<ide> {
<ide> return [
<ide> ['markdown', 'm', InputOption::VALUE_OPTIONAL, 'Create a new Markdown template for the notification.'],
<add>
<add> ['force', 'f', InputOption::VALUE_NONE, 'Force the generator to continue execution even if the notification already exists.'],
<ide> ];
<ide> }
<ide> } | 3 |
Python | Python | update train method | 9b55d97a8ff440ee5dcb591c9703a57af480ae1a | <ide><path>spacy/train.py
<ide> import random
<ide> from .gold import GoldParse
<ide> from .scorer import Scorer
<add>from .gold import merge_sents
<ide>
<ide>
<ide> class Trainer(object):
<ide> def __init__(self, nlp, gold_tuples):
<ide> self.nlp = nlp
<ide> self.gold_tuples = gold_tuples
<ide>
<del> def epochs(self, nr_epoch, augment_data=None):
<add> def epochs(self, nr_epoch, augment_data=None, gold_preproc=False):
<ide> def _epoch():
<ide> for raw_text, paragraph_tuples in self.gold_tuples:
<add> if gold_preproc:
<add> raw_text = None
<add> else:
<add> paragraph_tuples = merge_sents(paragraph_tuples)
<ide> if augment_data is not None:
<ide> raw_text, paragraph_tuples = augment_data(raw_text, paragraph_tuples)
<ide> docs = self.make_docs(raw_text, paragraph_tuples)
<ide> def update(self, doc, gold):
<ide> process(doc)
<ide> return doc
<ide>
<del> def evaluate(self, dev_sents):
<add> def evaluate(self, dev_sents, gold_preproc=False):
<ide> scorer = Scorer()
<ide> for raw_text, paragraph_tuples in dev_sents:
<add> if gold_preproc:
<add> raw_text = None
<add> else:
<add> paragraph_tuples = merge_sents(paragraph_tuples)
<ide> docs = self.make_docs(raw_text, paragraph_tuples)
<ide> golds = self.make_golds(docs, paragraph_tuples)
<ide> for doc, gold in zip(docs, golds): | 1 |
Go | Go | resolve the graphdriver to show | 7cf322dffc5e9a4ea495ec08e0b0594cad01da92 | <ide><path>docker/daemon.go
<ide> func mainDaemon() {
<ide> if err != nil {
<ide> log.Fatal(err)
<ide> }
<add> log.Infof("docker daemon: %s %s; execdriver: %s; graphdriver: %s",
<add> dockerversion.VERSION,
<add> dockerversion.GITCOMMIT,
<add> d.ExecutionDriver().Name(),
<add> d.GraphDriver().String(),
<add> )
<add>
<ide> if err := d.Install(eng); err != nil {
<ide> log.Fatal(err)
<ide> }
<ide> func mainDaemon() {
<ide> log.Fatal(err)
<ide> }
<ide> }()
<del> // TODO actually have a resolved graphdriver to show?
<del> log.Infof("docker daemon: %s %s; execdriver: %s; graphdriver: %s",
<del> dockerversion.VERSION,
<del> dockerversion.GITCOMMIT,
<del> daemonCfg.ExecDriver,
<del> daemonCfg.GraphDriver,
<del> )
<ide>
<ide> // Serve api
<ide> job := eng.Job("serveapi", flHosts...) | 1 |
Javascript | Javascript | use constant for global guid prefix | c384ba00af6ea1d8ddf85b932564d2cf57ff0b7e | <ide><path>packages/ember-metal/lib/utils.js
<ide> require('ember-metal/array');
<ide> @module ember-metal
<ide> */
<ide>
<add>/**
<add> @private
<add>
<add> Prefix used for guids through out Ember.
<add>
<add>*/
<add>Ember.GUID_PREFIX = 'ember';
<add>
<ide>
<ide> var o_defineProperty = Ember.platform.defineProperty,
<ide> o_create = Ember.create,
<ide> var GUID_DESC = {
<ide> @return {String} the guid
<ide> */
<ide> Ember.generateGuid = function generateGuid(obj, prefix) {
<del> if (!prefix) prefix = 'ember';
<add> if (!prefix) prefix = Ember.GUID_PREFIX;
<ide> var ret = (prefix + (uuid++));
<ide> if (obj) {
<ide> GUID_DESC.value = ret;
<ide> o_defineProperty(obj, GUID_KEY, GUID_DESC);
<ide> }
<del> return ret ;
<add> return ret;
<ide> };
<ide>
<ide> /**
<ide><path>packages/ember-metal/lib/watching.js
<ide> Ember.rewatch = function(obj) {
<ide>
<ide> // make sure the object has its own guid.
<ide> if (GUID_KEY in obj && !obj.hasOwnProperty(GUID_KEY)) {
<del> generateGuid(obj, 'ember');
<add> generateGuid(obj);
<ide> }
<ide>
<ide> // make sure any chained watchers update.
<ide><path>packages/ember-metal/tests/utils/generate_guid_test.js
<add>module("Ember.generateGuid");
<add>
<add>test("Prefix", function() {
<add> var a = {};
<add>
<add> ok( Ember.generateGuid(a, 'tyrell').indexOf('tyrell') > -1, "guid can be prefixed" );
<add>});
<ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> var ClassMixin = Mixin.create({
<ide>
<ide> proto = Class.prototype = o_create(this.prototype);
<ide> proto.constructor = Class;
<del> generateGuid(proto, 'ember');
<add> generateGuid(proto);
<ide> meta(proto).proto = proto; // this will disable observers on prototype
<ide>
<ide> Class.ClassMixin.apply(Class); | 4 |
Ruby | Ruby | remove a ruby_version check, add a fixme comment | cf4080a9e0517efc16a71b686e80c3ebcc38f5a2 | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def verify_checksum expected
<ide> raise ChecksumMismatchError.new(self, expected, actual) unless expected == actual
<ide> end
<ide>
<del> if '1.9' <= RUBY_VERSION
<del> alias_method :to_str, :to_s
<del> end
<add> # FIXME eliminate the places where we rely on this method
<add> alias_method :to_str, :to_s unless method_defined?(:to_str)
<ide>
<ide> def cd
<ide> Dir.chdir(self){ yield } | 1 |
Text | Text | remove misplaced summarization documentation | 4b82c485de187896a38c441587b7bd4d04f2821e | <ide><path>examples/README.md
<ide> pip install -r ./examples/requirements.txt
<ide> | [Multiple Choice](#multiple-choice) | Examples running BERT/XLNet/RoBERTa on the SWAG/RACE/ARC tasks.
<ide> | [Named Entity Recognition](#named-entity-recognition) | Using BERT for Named Entity Recognition (NER) on the CoNLL 2003 dataset, examples with distributed training. |
<ide> | [XNLI](#xnli) | Examples running BERT/XLM on the XNLI benchmark. |
<del>| [Abstractive summarization](#abstractive-summarization) | Using the BertAbs
<del>model finetuned on the CNN/DailyMail dataset to generate summaries. |
<ide>
<ide> ## TensorFlow 2.0 Bert models on GLUE
<ide>
<ide> micro avg 0.8722 0.8774 0.8748 13869
<ide> macro avg 0.8712 0.8774 0.8740 13869
<ide> ```
<ide>
<del>## Abstractive summarization
<del>
<del>Based on the script
<del>[`run_summarization_finetuning.py`](https://github.com/huggingface/transformers/blob/master/examples/run_summarization_finetuning.py).
<del>
<del>Before running this script you should download **both** CNN and Daily Mail
<del>datasets from [Kyunghyun Cho's website](https://cs.nyu.edu/~kcho/DMQA/) (the
<del>links next to "Stories") in the same folder. Then uncompress the archives by running:
<del>
<del>```bash
<del>tar -xvf cnn_stories.tgz && tar -xvf dailymail_stories.tgz
<del>```
<del>
<del>note that the finetuning script **will not work** if you do not download both
<del>datasets. We will refer as `$DATA_PATH` the path to where you uncompressed both
<del>archive.
<del>
<del>```bash
<del>export DATA_PATH=/path/to/dataset/
<del>
<del>python run_summarization_finetuning.py \
<del> --output_dir=output \
<del> --model_type=bert2bert \
<del> --model_name_or_path=bert2bert \
<del> --do_train \
<del> --data_path=$DATA_PATH \
<del>```
<del>
<ide> ## XNLI
<ide>
<ide> Based on the script [`run_xnli.py`](https://github.com/huggingface/transformers/blob/master/examples/run_xnli.py). | 1 |
Javascript | Javascript | throw an error for unexpected agent values | fc7025c9c011f266c6bd73e1fb634eb5f519c5cb | <ide><path>lib/_http_client.js
<ide> function ClientRequest(options, cb) {
<ide> var defaultAgent = options._defaultAgent || Agent.globalAgent;
<ide> if (agent === false) {
<ide> agent = new defaultAgent.constructor();
<del> } else if ((agent === null || agent === undefined) &&
<del> typeof options.createConnection !== 'function') {
<del> agent = defaultAgent;
<add> } else if (agent === null || agent === undefined) {
<add> if (typeof options.createConnection !== 'function') {
<add> agent = defaultAgent;
<add> }
<add> // Explicitly pass through this statement as agent will not be used
<add> // when createConnection is provided.
<add> } else if (!(agent instanceof Agent.Agent)) {
<add> throw new TypeError(
<add> 'Agent option must be an instance of http.Agent, undefined or false.'
<add> );
<ide> }
<ide> self.agent = agent;
<ide>
<ide><path>test/parallel/test-http-client-reject-unexpected-agent.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const http = require('http');
<add>
<add>const baseOptions = {
<add> method: 'GET',
<add> port: undefined,
<add> host: common.localhostIPv4,
<add>};
<add>
<add>const failingAgentOptions = [
<add> true,
<add> 'agent',
<add> {},
<add> 1,
<add> () => null,
<add> Symbol(),
<add>];
<add>
<add>const acceptableAgentOptions = [
<add> false,
<add> undefined,
<add> null,
<add> new http.Agent(),
<add>];
<add>
<add>const server = http.createServer((req, res) => {
<add> res.end('hello');
<add>});
<add>
<add>let numberOfResponses = 0;
<add>
<add>function createRequest(agent) {
<add> const options = Object.assign(baseOptions, {agent});
<add> const request = http.request(options);
<add> request.end();
<add> request.on('response', common.mustCall(() => {
<add> numberOfResponses++;
<add> if (numberOfResponses === acceptableAgentOptions.length) {
<add> server.close();
<add> }
<add> }));
<add>}
<add>
<add>server.listen(0, baseOptions.host, common.mustCall(function() {
<add> baseOptions.port = this.address().port;
<add>
<add> failingAgentOptions.forEach((agent) => {
<add> assert.throws(
<add> () => createRequest(agent),
<add> /^TypeError: Agent option must be an instance of http.Agent/,
<add> `Expected typeof agent: ${typeof agent} to be rejected`
<add> );
<add> });
<add>
<add> acceptableAgentOptions.forEach((agent) => {
<add> assert.doesNotThrow(() => createRequest(agent));
<add> });
<add>}));
<add>
<add>process.on('exit', () => {
<add> assert.strictEqual(numberOfResponses, acceptableAgentOptions.length);
<add>}); | 2 |
Python | Python | display docker command in the curses interface | ad5974962d082e1729da8545a3c26fa20d273f26 | <ide><path>glances/plugins/glances_docker.py
<ide> def msg_curse(self, args=None):
<ide> ret.append(self.curse_add_line(msg))
<ide> # Command
<ide> msg = ' {0}'.format(container['Command'])
<del> ret.append(self.curse_add_line(msg))
<add> ret.append(self.curse_add_line(msg, splittable=True))
<ide>
<ide> return ret
<ide> | 1 |
Javascript | Javascript | add test for circular refs in deepequals | 6394ba28c82335cdb6e3578728957cd3eb9f72f1 | <ide><path>test/simple/test-assert.js
<ide> a.throws(makeBlock(thrower, TypeError), function(err) {
<ide> return true;
<ide> }
<ide> });
<add>
<add>
<add>// GH-207. Make sure deepEqual doesn't loop forever on circular refs
<add>
<add>var b = {};
<add>b.b = b;
<add>
<add>var c = {};
<add>c.b = c;
<add>
<add>var gotError = false;
<add>try {
<add> assert.deepEqual(b, c);
<add>} catch(e) {
<add> gotError = true;
<add>}
<add>
<add>console.log('All OK');
<add>assert.ok(gotError);
<add> | 1 |
PHP | PHP | fix issue | 46fd7dd7d794eb5fe6406198880d06a1b33d85e7 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function morphTo($name = null, $type = null, $id = null)
<ide> // If the type value is null it is probably safe to assume we're eager loading
<ide> // the relationship. When that is the case we will pass in a dummy query as
<ide> // there are multiple types in the morph and we can't use single queries.
<del> if (is_null($class = $this->$type)) {
<add> if (empty($class = $this->$type)) {
<ide> return new MorphTo(
<ide> $this->newQuery(), $this, $id, null, $type, $name
<ide> ); | 1 |
Text | Text | make scope and naming of pull requests clearer | f0d907be664c848425cbde019f4291ee333105f5 | <ide><path>docs/how-to-open-a-pull-request.md
<add># How to open a Pull Request
<add>
<add>## How to prepare a good Pull Request title:
<add>
<add>When opening a Pull Request(PR), use the following scope table to decide what to title your PR in the following format:
<add>`fix/feat/chore/refactor/docs/perf (scope): PR Title`
<add>
<add>An example is `fix(learn): Fixed tests for the do...while loop challenge`.
<add>
<add>| Scope | Documentation |
<add>|---|---|
<add>| `learn`,`curriculum` | For Pull Requests making changes to the curriculum challenges. |
<add>| `client` | For Pull Requests making changes to client platform logic or user interface |
<add>| `guide` | For Pull Requests which make changes to the guide. |
<add>| `docs` | For Pull Requests making changes to the project's documentation. |
<add>
<add>## Proposing a Pull Request (PR)
<add>
<add>1. Once the edits have been committed, you will be prompted to create a pull request on your fork's GitHub Page.
<add>
<add> 
<add>
<add>2. By default, all pull requests should be against the freeCodeCamp main repo, `master` branch.
<add>
<add> Make sure that your Base Fork is set to freeCodeCamp/freeCodeCamp when raising a Pull Request.
<add>
<add> 
<add>
<add>3. Submit the pull request from your branch to freeCodeCamp's `master` branch.
<add>
<add>4. In the body of your PR include a more detailed summary of the changes you made and why.
<add>
<add> - You will be presented with a pull request template. This is a checklist that you should have followed before opening the pull request.
<add>
<add> - Fill in the details as they seem fit you. This information will be reviewed and decide whether or not, your pull request is going to be accepted.
<add>
<add> - If the PR is meant to fix an existing bug/issue then, at the end of
<add> your PR's description, append the keyword `closes` and #xxxx (where xxxx
<add> is the issue number). Example: `closes #1337`. This tells GitHub to
<add> automatically close the existing issue, if the PR is accepted and merged.
<add>
<add>5. Indicate if you have tested on a local copy of the site or not.
<add>
<add> This is very important when you are making changes that are not just making edits to text content such as a Guide article verbiage. Examples of changes needing local testing would include JavaScript, CSS, or HTML which could change the functionality or layout of a page.
<ide><path>docs/how-to-setup-freecodecamp-locally.md
<ide> Follow these steps:
<ide>
<ide> ## Proposing a Pull Request (PR)
<ide>
<del>1. Once the edits have been committed, you will be prompted to create a pull request on your fork's GitHub Page.
<del>
<del> 
<del>
<del>2. By default, all pull requests should be against the freeCodeCamp main repo, `master` branch.
<del>
<del> Make sure that your Base Fork is set to freeCodeCamp/freeCodeCamp when raising a Pull Request.
<del>
<del> 
<del>
<del>3. Submit the pull request from your branch to freeCodeCamp's `master` branch.
<del>
<del>4. In the body of your PR include a more detailed summary of the changes you made and why.
<del>
<del> - You will be presented with a pull request template. This is a checklist that you should have followed before opening the pull request.
<del>
<del> - Fill in the details as they seem fit you. This information will be reviewed and decide whether or not, your pull request is going to be accepted.
<del>
<del> - If the PR is meant to fix an existing bug/issue then, at the end of
<del> your PR's description, append the keyword `closes` and #xxxx (where xxxx
<del> is the issue number). Example: `closes #1337`. This tells GitHub to
<del> automatically close the existing issue, if the PR is accepted and merged.
<del>
<del>5. Indicate if you have tested on a local copy of the site or not.
<del>
<del> This is very important when you are making changes that are not copy editing markdown files. For example, changes to CSS or JavaScript code, etc.
<add>After you've committed your changes, check here for [how to open a Pull Request](/docs/how-to-open-a-pull-request.md).
<ide>
<ide> ## Getting Help
<ide> | 2 |
Python | Python | add test for sin/cos for strided large inputs | 02a7aee4adeb22ecc3a166811989ab9c5d5960f6 | <ide><path>numpy/core/tests/test_umath.py
<ide> def test_strided_float32(self):
<ide> sizes = np.arange(2,100)
<ide> for ii in sizes:
<ide> x_f32 = np.float32(np.random.uniform(low=0.01,high=88.1,size=ii))
<add> x_f32_large = x_f32.copy()
<add> x_f32_large[3:-1:4] = 120000.0
<ide> exp_true = np.exp(x_f32)
<ide> log_true = np.log(x_f32)
<del> sin_true = np.sin(x_f32)
<del> cos_true = np.cos(x_f32)
<add> sin_true = np.sin(x_f32_large)
<add> cos_true = np.cos(x_f32_large)
<ide> for jj in strides:
<ide> assert_array_almost_equal_nulp(np.exp(x_f32[::jj]), exp_true[::jj], nulp=2)
<ide> assert_array_almost_equal_nulp(np.log(x_f32[::jj]), log_true[::jj], nulp=2)
<del> assert_array_almost_equal_nulp(np.sin(x_f32[::jj]), sin_true[::jj], nulp=2)
<del> assert_array_almost_equal_nulp(np.cos(x_f32[::jj]), cos_true[::jj], nulp=2)
<add> assert_array_almost_equal_nulp(np.sin(x_f32_large[::jj]), sin_true[::jj], nulp=2)
<add> assert_array_almost_equal_nulp(np.cos(x_f32_large[::jj]), cos_true[::jj], nulp=2)
<ide>
<ide> class TestLogAddExp(_FilterInvalids):
<ide> def test_logaddexp_values(self): | 1 |
PHP | PHP | add typehint to setpdo method | 3d690c30a86a965d463f4c3410f57c198fd0d7a7 | <ide><path>src/Illuminate/Database/Connection.php
<ide> public function getPdo()
<ide> /**
<ide> * Change the value of the currently used PDO connection.
<ide> *
<del> * @param mixed $pdo
<add> * @param PDO|null $pdo
<ide> */
<del> public function setPdo($pdo)
<add> public function setPdo(PDO $pdo = null)
<ide> {
<ide> $this->pdo = $pdo;
<ide> } | 1 |
Python | Python | add maskedarray creation from non nd-array back in | b31a3a3fb05910abc2ee55d63255efdb2a2c383e | <ide><path>numpy/ma/core.py
<ide> def __new__(cls, data=None, mask=nomask, dtype=None, copy=False,
<ide> _data = ndarray.view(_data, type(data))
<ide> else:
<ide> _data = ndarray.view(_data, cls)
<add>
<add> # Handle the case where data is not a subclass of ndarray, but
<add> # still has the _mask attribute like MaskedArrays
<add> if hasattr(data, '_mask') and not isinstance(data, ndarray):
<add> _data._mask = data._mask
<add> # FIXME: should we set `_data._sharedmask = True`?
<ide> # Process mask.
<ide> # Type of the mask
<ide> mdtype = make_mask_descr(_data.dtype)
<ide><path>numpy/ma/tests/test_subclassing.py
<ide> def test_pure_subclass_info_preservation(self):
<ide> diff2 = arr1 - arr2
<ide> assert_('info' in diff2._optinfo)
<ide> assert_(diff2._optinfo['info'] == 'test')
<add>
<add>
<add>class ArrayNoInheritance:
<add> """Quantity-like class that does not inherit from ndarray"""
<add> def __init__(self, data, units):
<add> self.magnitude = data
<add> self.units = units
<add>
<add> def __getattr__(self, attr):
<add> return getattr(self.magnitude, attr)
<add>
<add>
<add>def test_array_no_inheritance():
<add> data_masked = np.ma.array([1, 2, 3], mask=[True, False, True])
<add> data_masked_units = ArrayNoInheritance(data_masked, 'meters')
<add>
<add> # Get the masked representation of the Quantity-like class
<add> new_array = np.ma.array(data_masked_units)
<add> assert_equal(data_masked.data, new_array.data)
<add> assert_equal(data_masked.mask, new_array.mask)
<add> # Test sharing the mask
<add> data_masked.mask = [True, False, False]
<add> assert_equal(data_masked.mask, new_array.mask)
<add> assert_(new_array.sharedmask)
<add>
<add> # Get the masked representation of the Quantity-like class
<add> new_array = np.ma.array(data_masked_units, copy=True)
<add> assert_equal(data_masked.data, new_array.data)
<add> assert_equal(data_masked.mask, new_array.mask)
<add> # Test that the mask is not shared when copy=True
<add> data_masked.mask = [True, False, True]
<add> assert_equal([True, False, False], new_array.mask)
<add> assert_(not new_array.sharedmask)
<add>
<add> # Get the masked representation of the Quantity-like class
<add> new_array = np.ma.array(data_masked_units, keep_mask=False)
<add> assert_equal(data_masked.data, new_array.data)
<add> # The change did not affect the original mask
<add> assert_equal(data_masked.mask, [True, False, True])
<add> # Test that the mask is False and not shared when keep_mask=False
<add> assert_(not new_array.mask)
<add> assert_(not new_array.sharedmask) | 2 |
Python | Python | allow relative paths in the filesystem backend | 3508e1f2c3bff01952fc004047fb3f1fa15f370d | <ide><path>celery/backends/filesystem.py
<ide> def __init__(self, url=None, open=open, unlink=os.unlink, sep=os.sep,
<ide> def _find_path(self, url):
<ide> if not url:
<ide> raise ImproperlyConfigured(E_NO_PATH_SET)
<del> if url.startswith('file:///'):
<del> return url[7:]
<ide> if url.startswith('file://localhost/'):
<ide> return url[16:]
<add> if url.startswith('file://'):
<add> return url[7:]
<ide> raise ImproperlyConfigured(E_PATH_NON_CONFORMING_SCHEME)
<ide>
<ide> def _do_directory_test(self, key): | 1 |
PHP | PHP | simplify class name | af91bb42e3a18bcf5d30fe451718200dea9563e8 | <ide><path>src/Datasource/QueryTrait.php
<ide> use BadMethodCallException;
<ide> use Cake\Collection\Iterator\MapReduce;
<ide> use Cake\Datasource\Exception\RecordNotFoundException;
<add>use Cake\Datasource\ResultSetDecorator;
<ide>
<ide> /**
<ide> * Contains the characteristics for an object that is attached to a repository and
<ide> protected function _decorateResults($result)
<ide> */
<ide> protected function _decoratorClass()
<ide> {
<del> return \Cake\Datasource\ResultSetDecorator::class;
<add> return ResultSetDecorator::class;
<ide> }
<ide> } | 1 |
Go | Go | fix merge issue | 42d1c36a5c775a37a0173cf315086fde1c1b7dd8 | <ide><path>tags_test.go
<ide> func TestLookupImage(t *testing.T) {
<ide> t.Errorf("Expected 1 image, none found")
<ide> }
<ide>
<del> if img, err := runtime.repositories.LookupImage(unitTestImageName + ":" + DEFAULT_TAG); err != nil {
<add> if img, err := runtime.repositories.LookupImage(unitTestImageName + ":" + DEFAULTTAG); err != nil {
<ide> t.Fatal(err)
<ide> } else if img == nil {
<ide> t.Errorf("Expected 1 image, none found") | 1 |
Javascript | Javascript | add hostcomponent type to reactnative | db8afe4f6318dba422177a2054204ef089570ad8 | <ide><path>packages/react-native-renderer/src/NativeMethodsMixin.js
<ide> export default function(
<ide> measureLayout: function(
<ide> relativeToNativeNode: number | Object,
<ide> onSuccess: MeasureLayoutOnSuccessCallback,
<del> onFail: () => void /* currently unused */,
<add> onFail?: () => void /* currently unused */,
<ide> ) {
<ide> let maybeInstance;
<ide>
<ide><path>packages/react-native-renderer/src/ReactFabricHostConfig.js
<ide> import type {
<ide> MeasureInWindowOnSuccessCallback,
<ide> MeasureLayoutOnSuccessCallback,
<ide> MeasureOnSuccessCallback,
<del> NativeMethodsMixinType,
<add> NativeMethods,
<ide> ReactNativeBaseComponentViewConfig,
<ide> ReactNativeResponderEvent,
<ide> ReactNativeResponderContext,
<ide> class ReactFabricHostComponent {
<ide> }
<ide>
<ide> measureLayout(
<del> relativeToNativeNode: number | Object,
<add> relativeToNativeNode: number | ReactFabricHostComponent,
<ide> onSuccess: MeasureLayoutOnSuccessCallback,
<del> onFail: () => void /* currently unused */,
<add> onFail?: () => void /* currently unused */,
<ide> ) {
<ide> if (
<ide> typeof relativeToNativeNode === 'number' ||
<ide> class ReactFabricHostComponent {
<ide> }
<ide>
<ide> // eslint-disable-next-line no-unused-expressions
<del>(ReactFabricHostComponent.prototype: NativeMethodsMixinType);
<add>(ReactFabricHostComponent.prototype: NativeMethods);
<ide>
<ide> export * from 'shared/HostConfigWithNoMutation';
<ide> export * from 'shared/HostConfigWithNoHydration';
<ide><path>packages/react-native-renderer/src/ReactNativeComponent.js
<ide> import type {
<ide> MeasureInWindowOnSuccessCallback,
<ide> MeasureLayoutOnSuccessCallback,
<ide> MeasureOnSuccessCallback,
<del> NativeMethodsMixinType,
<add> NativeMethods,
<ide> ReactNativeBaseComponentViewConfig,
<ide> } from './ReactNativeTypes';
<ide>
<ide> export default function(
<ide> measureLayout(
<ide> relativeToNativeNode: number | Object,
<ide> onSuccess: MeasureLayoutOnSuccessCallback,
<del> onFail: () => void /* currently unused */,
<add> onFail?: () => void /* currently unused */,
<ide> ): void {
<ide> let maybeInstance;
<ide>
<ide> export default function(
<ide> }
<ide>
<ide> // eslint-disable-next-line no-unused-expressions
<del> (ReactNativeComponent.prototype: NativeMethodsMixinType);
<add> (ReactNativeComponent.prototype: NativeMethods);
<ide>
<ide> return ReactNativeComponent;
<ide> }
<ide><path>packages/react-native-renderer/src/ReactNativeFiberHostComponent.js
<ide> import type {
<ide> MeasureInWindowOnSuccessCallback,
<ide> MeasureLayoutOnSuccessCallback,
<ide> MeasureOnSuccessCallback,
<del> NativeMethodsMixinType,
<add> NativeMethods,
<ide> ReactNativeBaseComponentViewConfig,
<ide> } from './ReactNativeTypes';
<ide> import type {Instance} from './ReactNativeHostConfig';
<ide> class ReactNativeFiberHostComponent {
<ide> }
<ide>
<ide> measureLayout(
<del> relativeToNativeNode: number | Object,
<add> relativeToNativeNode: number | ReactNativeFiberHostComponent,
<ide> onSuccess: MeasureLayoutOnSuccessCallback,
<del> onFail: () => void /* currently unused */,
<add> onFail?: () => void /* currently unused */,
<ide> ) {
<del> let relativeNode;
<add> let relativeNode: ?number;
<ide>
<ide> if (typeof relativeToNativeNode === 'number') {
<ide> // Already a node handle
<ide> relativeNode = relativeToNativeNode;
<ide> } else if (relativeToNativeNode._nativeTag) {
<ide> relativeNode = relativeToNativeNode._nativeTag;
<ide> } else if (
<add> /* $FlowFixMe canonical doesn't exist on the node.
<add> I think this branch is dead and will remove it in a followup */
<ide> relativeToNativeNode.canonical &&
<ide> relativeToNativeNode.canonical._nativeTag
<ide> ) {
<add> /* $FlowFixMe canonical doesn't exist on the node.
<add> I think this branch is dead and will remove it in a followup */
<ide> relativeNode = relativeToNativeNode.canonical._nativeTag;
<ide> }
<ide>
<ide> class ReactNativeFiberHostComponent {
<ide> }
<ide>
<ide> // eslint-disable-next-line no-unused-expressions
<del>(ReactNativeFiberHostComponent.prototype: NativeMethodsMixinType);
<add>(ReactNativeFiberHostComponent.prototype: NativeMethods);
<ide>
<ide> export default ReactNativeFiberHostComponent;
<ide><path>packages/react-native-renderer/src/ReactNativeTypes.js
<ide> * @flow
<ide> */
<ide>
<del>import React from 'react';
<add>import React, {type ElementRef, type AbstractComponent} from 'react';
<ide>
<ide> export type MeasureOnSuccessCallback = (
<ide> x: number,
<ide> class ReactNativeComponent<Props> extends React.Component<Props> {
<ide> measure(callback: MeasureOnSuccessCallback): void {}
<ide> measureInWindow(callback: MeasureInWindowOnSuccessCallback): void {}
<ide> measureLayout(
<del> relativeToNativeNode: number | Object,
<add> relativeToNativeNode: number | ElementRef<HostComponent<mixed>>,
<ide> onSuccess: MeasureLayoutOnSuccessCallback,
<ide> onFail?: () => void,
<ide> ): void {}
<ide> setNativeProps(nativeProps: Object): void {}
<ide> }
<ide>
<add>// This type is only used for FlowTests. It shouldn't be imported directly
<add>export type _InternalReactNativeComponentClass<Props> = Class<
<add> ReactNativeComponent<Props>,
<add>>;
<add>
<ide> /**
<ide> * This type keeps ReactNativeFiberHostComponent and NativeMethodsMixin in sync.
<ide> * It can also provide types for ReactNative applications that use NMM or refs.
<ide> */
<del>export type NativeMethodsMixinType = {
<add>export type NativeMethods = {
<ide> blur(): void,
<ide> focus(): void,
<ide> measure(callback: MeasureOnSuccessCallback): void,
<ide> measureInWindow(callback: MeasureInWindowOnSuccessCallback): void,
<ide> measureLayout(
<del> relativeToNativeNode: number | Object,
<add> relativeToNativeNode: number | ElementRef<HostComponent<mixed>>,
<ide> onSuccess: MeasureLayoutOnSuccessCallback,
<del> onFail: () => void,
<add> onFail?: () => void,
<ide> ): void,
<ide> setNativeProps(nativeProps: Object): void,
<ide> };
<ide>
<add>export type NativeMethodsMixinType = NativeMethods;
<add>export type HostComponent<T> = AbstractComponent<
<add> T,
<add> $ReadOnly<$Exact<NativeMethods>>,
<add>>;
<add>
<ide> type SecretInternalsType = {
<ide> NativeMethodsMixin: NativeMethodsMixinType,
<ide> computeComponentStackForErrorReporting(tag: number): string, | 5 |
Python | Python | add helpful error message in flatten | f2f4f4ec48a3ae49f3f345f5e0eda60084d606a8 | <ide><path>keras/layers/core.py
<ide> def __init__(self, **kwargs):
<ide> @property
<ide> def output_shape(self):
<ide> input_shape = self.input_shape
<add> if not all(input_shape[1:]):
<add> raise Exception('The shape of the input to "Flatten" '
<add> 'is not fully defined '
<add> '(got ' + str(input_shape[1:]) + '. '
<add> 'Make sure to pass a complete "input_shape" '
<add> 'or "batch_input_shape" argument to the first '
<add> 'layer in your model.')
<ide> return (input_shape[0], np.prod(input_shape[1:]))
<ide>
<ide> def get_output(self, train=False): | 1 |
Java | Java | update javadoc for throttlelast | b75b37c513b537025c939ced498d747c233bea38 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> public static Observable<Long> interval(long interval, TimeUnit unit, Scheduler
<ide> }
<ide>
<ide> /**
<del> * Throttles the {@link Observable} by dropping values which are followed by newer values before the timer has expired.
<del> *
<del> * @param timeout
<del> * The time each value has to be 'the most recent' of the {@link Observable} to ensure that it's not dropped.
<add> * Throttles to last value in each window.
<ide> *
<add> * @param windowDuration
<add> * Duration of windows within with the first value will be chosen.
<ide> * @param unit
<del> * The {@link TimeUnit} for the timeout.
<del> *
<del> * @return An {@link Observable} which filters out values which are too quickly followed up with newer values.
<add> * The unit of time for the specified timeout.
<add> * @return Observable which performs the throttle operation.
<ide> */
<ide> public Observable<T> throttleLast(long timeout, TimeUnit unit) {
<ide> return create(OperationThrottleLast.throttleLast(this, timeout, unit));
<ide> }
<ide>
<ide> /**
<del> * Throttles the {@link Observable} by dropping values which are followed by newer values before the timer has expired.
<add> * Throttles to last value in each window.
<ide> *
<del> * @param timeout
<del> * The time each value has to be 'the most recent' of the {@link Observable} to ensure that it's not dropped.
<add> * @param windowDuration
<add> * Duration of windows within with the first value will be chosen.
<ide> * @param unit
<del> * The {@link TimeUnit} for the timeout.
<add> * The unit of time for the specified timeout.
<ide> * @param scheduler
<del> * The {@link Scheduler} to use when timing incoming values.
<del> * @return An {@link Observable} which filters out values which are too quickly followed up with newer values.
<add> * The {@link Scheduler} to use internally to manage the timers which handle timeout for each event.
<add> * @return Observable which performs the throttle operation.
<ide> */
<ide> public Observable<T> throttleLast(long timeout, TimeUnit unit, Scheduler scheduler) {
<ide> return create(OperationThrottleLast.throttleLast(this, timeout, unit, scheduler)); | 1 |
Javascript | Javascript | fix problems with empty component id registration | 795290d1b080c5c5960c24389333870bfe5931b5 | <ide><path>src/core/ReactCompositeComponent.js
<ide> var ReactCompositeComponentMixin = assign({},
<ide> }
<ide> }
<ide>
<add> var renderedElement = this._renderValidatedComponent();
<add> if (renderedElement === ReactEmptyComponent.emptyElement) {
<add> ReactEmptyComponent.registerNullComponentID(this._rootNodeID);
<add> }
<add>
<ide> this._renderedComponent = this._instantiateReactComponent(
<del> this._renderValidatedComponent(),
<add> renderedElement,
<ide> this._currentElement.type // The wrapping type
<ide> );
<ide>
<ide> var ReactCompositeComponentMixin = assign({},
<ide> }
<ide> this._compositeLifeCycleState = null;
<ide>
<add> if (this._renderedComponent._currentElement ===
<add> ReactEmptyComponent.emptyElement) {
<add> ReactEmptyComponent.deregisterNullComponentID(this._rootNodeID);
<add> }
<add>
<ide> this._renderedComponent.unmountComponent();
<ide> this._renderedComponent = null;
<ide>
<ide> var ReactCompositeComponentMixin = assign({},
<ide> var thisID = this._rootNodeID;
<ide> var prevComponentID = prevComponentInstance._rootNodeID;
<ide> prevComponentInstance.unmountComponent();
<add>
<add> if (nextRenderedElement === ReactEmptyComponent.emptyElement) {
<add> ReactEmptyComponent.registerNullComponentID(this._rootNodeID);
<add> } else if (prevRenderedElement === ReactEmptyComponent.emptyElement) {
<add> ReactEmptyComponent.deregisterNullComponentID(this._rootNodeID);
<add> }
<add>
<ide> this._renderedComponent = this._instantiateReactComponent(
<ide> nextRenderedElement,
<ide> this._currentElement.type
<ide> var ReactCompositeComponentMixin = assign({},
<ide> }
<ide> }
<ide> if (renderedComponent === null || renderedComponent === false) {
<del> renderedComponent = ReactEmptyComponent.getEmptyComponent();
<del> ReactEmptyComponent.registerNullComponentID(this._rootNodeID);
<del> } else {
<del> ReactEmptyComponent.deregisterNullComponentID(this._rootNodeID);
<add> renderedComponent = ReactEmptyComponent.emptyElement;
<ide> }
<ide> } finally {
<ide> ReactContext.current = previousContext;
<ide><path>src/core/ReactEmptyComponent.js
<ide> var ReactEmptyComponentInjection = {
<ide> }
<ide> };
<ide>
<del>/**
<del> * @return {ReactComponent} component The injected empty component.
<del> */
<del>function getEmptyComponent() {
<add>var ReactEmptyComponentType = function() {};
<add>ReactEmptyComponentType.prototype.render = function() {
<ide> invariant(
<ide> component,
<ide> 'Trying to return null from a render, but no null placeholder component ' +
<ide> 'was injected.'
<ide> );
<ide> return component();
<del>}
<add>};
<add>
<add>var emptyElement = ReactElement.createElement(ReactEmptyComponentType);
<ide>
<ide> /**
<ide> * Mark the component as having rendered to null.
<ide> function isNullComponentID(id) {
<ide> }
<ide>
<ide> var ReactEmptyComponent = {
<del> deregisterNullComponentID: deregisterNullComponentID,
<del> getEmptyComponent: getEmptyComponent,
<add> emptyElement: emptyElement,
<ide> injection: ReactEmptyComponentInjection,
<add>
<add> deregisterNullComponentID: deregisterNullComponentID,
<ide> isNullComponentID: isNullComponentID,
<ide> registerNullComponentID: registerNullComponentID
<ide> };
<ide><path>src/core/__tests__/ReactCompositeComponent-test.js
<ide> var ReactMount;
<ide> var ReactPropTypes;
<ide> var ReactServerRendering;
<ide> var ReactTestUtils;
<del>var TogglingComponent;
<ide>
<ide> var cx;
<ide> var reactComponentExpect;
<ide> describe('ReactCompositeComponent', function() {
<ide> }
<ide> });
<ide>
<del> TogglingComponent = React.createClass({
<del> getInitialState: function() {
<del> return {component: this.props.firstComponent};
<del> },
<del> componentDidMount: function() {
<del> console.log(this.getDOMNode());
<del> this.setState({component: this.props.secondComponent});
<del> },
<del> componentDidUpdate: function() {
<del> console.log(this.getDOMNode());
<del> },
<del> render: function() {
<del> var Component = this.state.component;
<del> return Component ? <Component /> : null;
<del> }
<del> });
<del>
<ide> warn = console.warn;
<ide> console.warn = mocks.getMockFunction();
<ide> });
<ide> describe('ReactCompositeComponent', function() {
<ide> .toBeDOMComponentWithTag('a');
<ide> });
<ide>
<del> it('should render null and false as a noscript tag under the hood', () => {
<del> var Component1 = React.createClass({
<del> render: function() {
<del> return null;
<del> }
<del> });
<del> var Component2 = React.createClass({
<del> render: function() {
<del> return false;
<del> }
<del> });
<del>
<del> var instance1 = ReactTestUtils.renderIntoDocument(<Component1 />);
<del> var instance2 = ReactTestUtils.renderIntoDocument(<Component2 />);
<del> reactComponentExpect(instance1)
<del> .expectRenderedChild()
<del> .toBeDOMComponentWithTag('noscript');
<del> reactComponentExpect(instance2)
<del> .expectRenderedChild()
<del> .toBeDOMComponentWithTag('noscript');
<del> });
<del>
<del> it('should still throw when rendering to undefined', () => {
<del> var Component = React.createClass({
<del> render: function() {}
<del> });
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(<Component />);
<del> }).toThrow(
<del> 'Invariant Violation: Component.render(): A valid ReactComponent must ' +
<del> 'be returned. You may have returned undefined, an array or some other ' +
<del> 'invalid object.'
<del> );
<del> });
<del>
<del> it('should be able to switch between rendering null and a normal tag', () => {
<del> spyOn(console, 'log');
<del>
<del> var instance1 =
<del> <TogglingComponent
<del> firstComponent={null}
<del> secondComponent={'div'}
<del> />;
<del> var instance2 =
<del> <TogglingComponent
<del> firstComponent={'div'}
<del> secondComponent={null}
<del> />;
<del>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(instance1);
<del> ReactTestUtils.renderIntoDocument(instance2);
<del> }).not.toThrow();
<del>
<del> expect(console.log.argsForCall.length).toBe(4);
<del> expect(console.log.argsForCall[0][0]).toBe(null);
<del> expect(console.log.argsForCall[1][0].tagName).toBe('DIV');
<del> expect(console.log.argsForCall[2][0].tagName).toBe('DIV');
<del> expect(console.log.argsForCall[3][0]).toBe(null);
<del> });
<del>
<del> it('should distinguish between a script placeholder and an actual script tag',
<del> () => {
<del> spyOn(console, 'log');
<del>
<del> var instance1 =
<del> <TogglingComponent
<del> firstComponent={null}
<del> secondComponent={'script'}
<del> />;
<del> var instance2 =
<del> <TogglingComponent
<del> firstComponent={'script'}
<del> secondComponent={null}
<del> />;
<del>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(instance1);
<del> }).not.toThrow();
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(instance2);
<del> }).not.toThrow();
<del>
<del> expect(console.log.argsForCall.length).toBe(4);
<del> expect(console.log.argsForCall[0][0]).toBe(null);
<del> expect(console.log.argsForCall[1][0].tagName).toBe('SCRIPT');
<del> expect(console.log.argsForCall[2][0].tagName).toBe('SCRIPT');
<del> expect(console.log.argsForCall[3][0]).toBe(null);
<del> }
<del> );
<del>
<del> it('should have getDOMNode return null when multiple layers of composite ' +
<del> 'components render to the same null placeholder', () => {
<del> spyOn(console, 'log');
<del>
<del> var GrandChild = React.createClass({
<del> render: function() {
<del> return null;
<del> }
<del> });
<del>
<del> var Child = React.createClass({
<del> render: function() {
<del> return <GrandChild />;
<del> }
<del> });
<del>
<del> var instance1 =
<del> <TogglingComponent
<del> firstComponent={'div'}
<del> secondComponent={Child}
<del> />;
<del> var instance2 =
<del> <TogglingComponent
<del> firstComponent={Child}
<del> secondComponent={'div'}
<del> />;
<del>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(instance1);
<del> }).not.toThrow();
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(instance2);
<del> }).not.toThrow();
<del>
<del> expect(console.log.argsForCall.length).toBe(4);
<del> expect(console.log.argsForCall[0][0].tagName).toBe('DIV');
<del> expect(console.log.argsForCall[1][0]).toBe(null);
<del> expect(console.log.argsForCall[2][0]).toBe(null);
<del> expect(console.log.argsForCall[3][0].tagName).toBe('DIV');
<del> }
<del> );
<del>
<ide> it('should not thrash a server rendered layout with client side one', () => {
<ide> var Child = React.createClass({
<ide> render: function() {
<ide><path>src/core/__tests__/ReactEmptyComponent-test.js
<add>/**
<add> * Copyright 2014, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @emails react-core
<add> */
<add>
<add>"use strict";
<add>
<add>var React;
<add>var ReactEmptyComponent;
<add>var ReactTestUtils;
<add>var TogglingComponent;
<add>
<add>var reactComponentExpect;
<add>
<add>describe('ReactEmptyComponent', function() {
<add> beforeEach(function() {
<add> require('mock-modules').dumpCache();
<add>
<add> React = require('React');
<add> ReactEmptyComponent = require('ReactEmptyComponent');
<add> ReactTestUtils = require('ReactTestUtils');
<add>
<add> reactComponentExpect = require('reactComponentExpect');
<add>
<add> TogglingComponent = React.createClass({
<add> getInitialState: function() {
<add> return {component: this.props.firstComponent};
<add> },
<add> componentDidMount: function() {
<add> console.log(this.getDOMNode());
<add> this.setState({component: this.props.secondComponent});
<add> },
<add> componentDidUpdate: function() {
<add> console.log(this.getDOMNode());
<add> },
<add> render: function() {
<add> var Component = this.state.component;
<add> return Component ? <Component /> : null;
<add> }
<add> });
<add> });
<add>
<add> it('should render null and false as a noscript tag under the hood', () => {
<add> var Component1 = React.createClass({
<add> render: function() {
<add> return null;
<add> }
<add> });
<add> var Component2 = React.createClass({
<add> render: function() {
<add> return false;
<add> }
<add> });
<add>
<add> var instance1 = ReactTestUtils.renderIntoDocument(<Component1 />);
<add> var instance2 = ReactTestUtils.renderIntoDocument(<Component2 />);
<add> reactComponentExpect(instance1)
<add> .expectRenderedChild()
<add> .toBeComponentOfType(ReactEmptyComponent.emptyElement.type);
<add> reactComponentExpect(instance2)
<add> .expectRenderedChild()
<add> .toBeComponentOfType(ReactEmptyComponent.emptyElement.type);
<add> });
<add>
<add> it('should still throw when rendering to undefined', () => {
<add> var Component = React.createClass({
<add> render: function() {}
<add> });
<add> expect(function() {
<add> ReactTestUtils.renderIntoDocument(<Component />);
<add> }).toThrow(
<add> 'Invariant Violation: Component.render(): A valid ReactComponent must ' +
<add> 'be returned. You may have returned undefined, an array or some other ' +
<add> 'invalid object.'
<add> );
<add> });
<add>
<add> it('should be able to switch between rendering null and a normal tag', () => {
<add> spyOn(console, 'log');
<add>
<add> var instance1 =
<add> <TogglingComponent
<add> firstComponent={null}
<add> secondComponent={'div'}
<add> />;
<add> var instance2 =
<add> <TogglingComponent
<add> firstComponent={'div'}
<add> secondComponent={null}
<add> />;
<add>
<add> expect(function() {
<add> ReactTestUtils.renderIntoDocument(instance1);
<add> ReactTestUtils.renderIntoDocument(instance2);
<add> }).not.toThrow();
<add>
<add> expect(console.log.argsForCall.length).toBe(4);
<add> expect(console.log.argsForCall[0][0]).toBe(null);
<add> expect(console.log.argsForCall[1][0].tagName).toBe('DIV');
<add> expect(console.log.argsForCall[2][0].tagName).toBe('DIV');
<add> expect(console.log.argsForCall[3][0]).toBe(null);
<add> });
<add>
<add> it('should distinguish between a script placeholder and an actual script tag',
<add> () => {
<add> spyOn(console, 'log');
<add>
<add> var instance1 =
<add> <TogglingComponent
<add> firstComponent={null}
<add> secondComponent={'script'}
<add> />;
<add> var instance2 =
<add> <TogglingComponent
<add> firstComponent={'script'}
<add> secondComponent={null}
<add> />;
<add>
<add> expect(function() {
<add> ReactTestUtils.renderIntoDocument(instance1);
<add> }).not.toThrow();
<add> expect(function() {
<add> ReactTestUtils.renderIntoDocument(instance2);
<add> }).not.toThrow();
<add>
<add> expect(console.log.argsForCall.length).toBe(4);
<add> expect(console.log.argsForCall[0][0]).toBe(null);
<add> expect(console.log.argsForCall[1][0].tagName).toBe('SCRIPT');
<add> expect(console.log.argsForCall[2][0].tagName).toBe('SCRIPT');
<add> expect(console.log.argsForCall[3][0]).toBe(null);
<add> }
<add> );
<add>
<add> it('should have getDOMNode return null when multiple layers of composite ' +
<add> 'components render to the same null placeholder', () => {
<add> spyOn(console, 'log');
<add>
<add> var GrandChild = React.createClass({
<add> render: function() {
<add> return null;
<add> }
<add> });
<add>
<add> var Child = React.createClass({
<add> render: function() {
<add> return <GrandChild />;
<add> }
<add> });
<add>
<add> var instance1 =
<add> <TogglingComponent
<add> firstComponent={'div'}
<add> secondComponent={Child}
<add> />;
<add> var instance2 =
<add> <TogglingComponent
<add> firstComponent={Child}
<add> secondComponent={'div'}
<add> />;
<add>
<add> expect(function() {
<add> ReactTestUtils.renderIntoDocument(instance1);
<add> }).not.toThrow();
<add> expect(function() {
<add> ReactTestUtils.renderIntoDocument(instance2);
<add> }).not.toThrow();
<add>
<add> expect(console.log.argsForCall.length).toBe(4);
<add> expect(console.log.argsForCall[0][0].tagName).toBe('DIV');
<add> expect(console.log.argsForCall[1][0]).toBe(null);
<add> expect(console.log.argsForCall[2][0]).toBe(null);
<add> expect(console.log.argsForCall[3][0].tagName).toBe('DIV');
<add> }
<add> );
<add>
<add> it('works when switching components', function() {
<add> var assertions = 0;
<add> var Inner = React.createClass({
<add> render: function() {
<add> return <span />;
<add> },
<add> componentDidMount: function() {
<add> // Make sure the DOM node resolves properly even if we're replacing a
<add> // `null` component
<add> expect(this.getDOMNode()).not.toBe(null);
<add> assertions++;
<add> },
<add> componentWillUnmount: function() {
<add> // Even though we're getting replaced by `null`, we haven't been
<add> // replaced yet!
<add> expect(this.getDOMNode()).not.toBe(null);
<add> assertions++;
<add> }
<add> });
<add> var Wrapper = React.createClass({
<add> render: function() {
<add> return this.props.showInner ? <Inner /> : null;
<add> }
<add> });
<add>
<add> var el = document.createElement('div');
<add> var component;
<add>
<add> // Render the <Inner /> component...
<add> component = React.render(<Wrapper showInner={true} />, el);
<add> expect(component.getDOMNode()).not.toBe(null);
<add>
<add> // Switch to null...
<add> component = React.render(<Wrapper showInner={false} />, el);
<add> expect(component.getDOMNode()).toBe(null);
<add>
<add> // ...then switch back.
<add> component = React.render(<Wrapper showInner={true} />, el);
<add> expect(component.getDOMNode()).not.toBe(null);
<add>
<add> expect(assertions).toBe(3);
<add> });
<add>});
<add>
<ide><path>src/test/reactComponentExpect.js
<ide> assign(reactComponentExpect.prototype, {
<ide> expectRenderedChild: function() {
<ide> this.toBeCompositeComponent();
<ide> var child = this._instance._renderedComponent;
<add> // TODO: Hide ReactEmptyComponent instances here?
<ide> return new reactComponentExpect(child);
<ide> },
<ide> | 5 |
Text | Text | add babel version to blog post | 4b3b56f36a692722c59376a1140670968c9f8bef | <ide><path>docs/_posts/2015-09-10-react-v0.14-rc1.md
<ide> These builds are also available in the `react` and `react-dom` packages on bower
<ide>
<ide> - #### Compiler optimizations
<ide>
<del> React now supports two compiler optimizations that can be enabled in Babel. Both of these transforms **should be enabled only in production** (e.g., just before minifying your code) because although they improve runtime performance, they make warning messages more cryptic and skip important checks that happen in development mode, including propTypes.
<add> React now supports two compiler optimizations that can be enabled in Babel 5.8.23 and newer. Both of these transforms **should be enabled only in production** (e.g., just before minifying your code) because although they improve runtime performance, they make warning messages more cryptic and skip important checks that happen in development mode, including propTypes.
<ide>
<ide> **Inlining React elements:** The `optimisation.react.inlineElements` transform converts JSX elements to object literals like `{type: 'div', props: ...}` instead of calls to `React.createElement`.
<ide> | 1 |
Javascript | Javascript | improve assertion message in internet dgram test | f04f4aef1014e207356abc1f57c197732de118d2 | <ide><path>test/internet/test-dgram-send-cb-quelches-error.js
<ide> function callbackOnly(err) {
<ide> }
<ide>
<ide> function onEvent(err) {
<del> assert.fail('Error should not be emitted if there is callback');
<add> assert.fail(`Error should not be emitted if there is callback: ${err}`);
<ide> }
<ide>
<ide> function onError(err) { | 1 |
Javascript | Javascript | simplify the data stored on `pdfobjects`-instances | f4712bc0ad967af3b153e760749da935a7b1f448 | <ide><path>src/display/api.js
<ide> class PDFObjects {
<ide> return (this.#objs[objId] = {
<ide> capability: createPromiseCapability(),
<ide> data: null,
<del> resolved: false,
<ide> });
<ide> }
<ide>
<ide> class PDFObjects {
<ide> // If there is a callback, then the get can be async and the object is
<ide> // not required to be resolved right now.
<ide> if (callback) {
<del> this.#ensureObj(objId).capability.promise.then(callback);
<add> const obj = this.#ensureObj(objId);
<add> obj.capability.promise.then(() => callback(obj.data));
<ide> return null;
<ide> }
<ide> // If there isn't a callback, the user expects to get the resolved data
<ide> // directly.
<ide> const obj = this.#objs[objId];
<ide> // If there isn't an object yet or the object isn't resolved, then the
<ide> // data isn't ready yet!
<del> if (!obj?.resolved) {
<add> if (!obj?.capability.settled) {
<ide> throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
<ide> }
<ide> return obj.data;
<ide> }
<ide>
<ide> has(objId) {
<ide> const obj = this.#objs[objId];
<del> return obj?.resolved || false;
<add> return obj?.capability.settled || false;
<ide> }
<ide>
<ide> /**
<ide> * Resolves the object `objId` with optional `data`.
<ide> */
<ide> resolve(objId, data = null) {
<ide> const obj = this.#ensureObj(objId);
<del>
<del> obj.resolved = true;
<ide> obj.data = data;
<del> obj.capability.resolve(data);
<add> obj.capability.resolve();
<ide> }
<ide>
<ide> clear() { | 1 |
Ruby | Ruby | fix error message | 2f679153ee6c77ee1248047dad37d4070dd5f021 | <ide><path>Library/Contributions/cmd/brew-gist-logs.rb
<ide> def post path, data
<ide>
<ide> class HTTP_Error < RuntimeError
<ide> def initialize response
<del> super "Error: HTTP #{response.code} #{response.message}"
<add> super "HTTP #{response.code} #{response.message}"
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | fix clang version output on linux | 25fe428ed27e89cd5ff9f7c6aee9d32e2e73faa7 | <ide><path>Library/Homebrew/extend/os/mac/system_config.rb
<ide> module SystemConfig
<ide> class << self
<ide> include SystemCommand::Mixin
<ide>
<del> undef describe_homebrew_ruby
<add> undef describe_homebrew_ruby, describe_clang
<ide>
<ide> def describe_homebrew_ruby
<ide> s = describe_homebrew_ruby_version
<ide> def describe_homebrew_ruby
<ide> end
<ide> end
<ide>
<add> def describe_clang
<add> return "N/A" if clang.null?
<add>
<add> clang_build_info = clang_build.null? ? "(parse error)" : clang_build
<add> "#{clang} build #{clang_build_info}"
<add> end
<add>
<ide> def xcode
<ide> @xcode ||= if MacOS::Xcode.installed?
<ide> xcode = MacOS::Xcode.version.to_s
<ide><path>Library/Homebrew/system_config.rb
<ide> def core_tap_origin
<ide> def describe_clang
<ide> return "N/A" if clang.null?
<ide>
<del> clang_build_info = clang_build.null? ? "(parse error)" : clang_build
<del> "#{clang} build #{clang_build_info}"
<add> if clang_build.null?
<add> clang.to_s
<add> else
<add> "#{clang} build #{clang_build}"
<add> end
<ide> end
<ide>
<ide> def describe_path(path) | 2 |
Javascript | Javascript | fix exception in getfoldablerangefornode | 3d11c1726428766bf9e5b5ec292125950d123f72 | <ide><path>src/tree-sitter-language-mode.js
<ide> class TreeSitterLanguageMode {
<ide> if (index === -1) continue
<ide> foldStart = children[index].endPosition
<ide> }
<add> } else {
<add> foldStart = new Point(node.startPosition.row, Infinity)
<ide> }
<ide>
<ide> let foldEnd
<ide> class TreeSitterLanguageMode {
<ide> } else {
<ide> foldEnd = foldEndNode.startPosition
<ide> }
<del> }
<del>
<del> if (existenceOnly) return true
<del>
<del> if (!foldStart) {
<del> foldStart = new Point(node.startPosition.row, Infinity)
<del> }
<del>
<del> if (!foldEnd) {
<add> } else {
<ide> const {endPosition} = node
<ide> if (endPosition.column === 0) {
<ide> foldEnd = Point(endPosition.row - 1, Infinity)
<ide> class TreeSitterLanguageMode {
<ide> }
<ide> }
<ide>
<del> return new Range(foldStart, foldEnd)
<add> return existenceOnly ? true : new Range(foldStart, foldEnd)
<ide> }
<ide> }
<ide> | 1 |
Python | Python | remove remaining pylint disables | cad854288aec6f33cf5766d8098e90f3abf75878 | <ide><path>airflow/www/views.py
<ide> def index(self):
<ide> dags_query = dags_query.filter(DagModel.tags.any(DagTag.name.in_(arg_tags_filter)))
<ide>
<ide> dags_query = dags_query.filter(DagModel.dag_id.in_(filter_dag_ids))
<del> # pylint: enable=no-member
<ide>
<ide> all_dags = dags_query
<ide> active_dags = dags_query.filter(~DagModel.is_paused)
<ide> def task_stats(self, session=None):
<ide> .join(DagModel, DagModel.dag_id == DagRun.dag_id)
<ide> .filter(DagRun.state == State.RUNNING, DagModel.is_active)
<ide> )
<del> # pylint: enable=comparison-with-callable
<ide>
<ide> running_dag_run_query_result = running_dag_run_query_result.filter(DagRun.dag_id.in_(filter_dag_ids))
<del> # pylint: enable=no-member
<ide>
<ide> running_dag_run_query_result = running_dag_run_query_result.subquery('running_dag_run')
<ide>
<ide> def task_stats(self, session=None):
<ide> running_dag_run_query_result.c.execution_date == TaskInstance.execution_date,
<ide> ),
<ide> )
<del> # pylint: enable=no-member
<ide>
<ide> if conf.getboolean('webserver', 'SHOW_RECENT_STATS_FOR_COMPLETED_RUNS', fallback=True):
<ide>
<ide> def task_stats(self, session=None):
<ide> .filter(DagRun.state != State.RUNNING, DagModel.is_active)
<ide> .group_by(DagRun.dag_id)
<ide> )
<del> # pylint: enable=comparison-with-callable
<ide>
<ide> last_dag_run = last_dag_run.filter(DagRun.dag_id.in_(filter_dag_ids))
<ide> last_dag_run = last_dag_run.subquery('last_dag_run')
<del> # pylint: enable=no-member
<ide>
<ide> # Select all task_instances from active dag_runs.
<ide> # If no dag_run is active, return task instances from most recent dag_run.
<ide> def last_dagruns(self, session=None):
<ide> ).group_by(DagRun.dag_id)
<ide>
<ide> # Filter to only ask for accessible and selected dags
<del> query = query.filter(DagRun.dag_id.in_(filter_dag_ids)) # pylint: enable=no-member
<add> query = query.filter(DagRun.dag_id.in_(filter_dag_ids))
<ide>
<ide> resp = {
<ide> r.dag_id.replace('.', '__dot__'): {
<ide> def task(self):
<ide>
<ide> if type(attr) != type(self.task) and attr_name not in wwwutils.get_attr_renderer(): # noqa
<ide> task_attrs.append((attr_name, str(attr)))
<del> # pylint: enable=unidiomatic-typecheck
<ide>
<ide> # Color coding the special attributes that are code
<ide> special_attrs_rendered = {}
<ide> def blocked(self, session=None):
<ide> .filter(DagRun.dag_id.in_(filter_dag_ids))
<ide> .group_by(DagRun.dag_id)
<ide> )
<del> # pylint: enable=comparison-with-callable
<ide>
<ide> payload = []
<ide> for dag_id, active_dag_runs in dags:
<ide> def autocomplete(self, session=None):
<ide>
<ide> dag_ids_query = dag_ids_query.filter(DagModel.dag_id.in_(filter_dag_ids))
<ide> owners_query = owners_query.filter(DagModel.dag_id.in_(filter_dag_ids))
<del> # pylint: enable=no-member
<ide>
<ide> payload = [row[0] for row in dag_ids_query.union(owners_query).limit(10).all()]
<ide>
<ide><path>tests/providers/amazon/aws/hooks/test_base_aws.py
<ide> mock_sts = None
<ide> mock_iam = None
<ide>
<del># pylint: disable=line-too-long
<ide> SAML_ASSERTION = """
<ide> <?xml version="1.0"?>
<ide> <samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="_00000000-0000-0000-0000-000000000000" Version="2.0" IssueInstant="2012-01-01T12:00:00.000Z" Destination="https://signin.aws.amazon.com/saml" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified">
<ide> ).replace(
<ide> "\n", ""
<ide> )
<del># pylint: enable=line-too-long
<ide>
<ide>
<ide> class TestAwsBaseHook(unittest.TestCase): | 2 |
Javascript | Javascript | add lut loaders | 5e176f8f2887becd164873d6669457c02545c6f4 | <ide><path>examples/jsm/loaders/LUT3dlLoader.js
<add>// http://download.autodesk.com/us/systemdocs/help/2011/lustre/index.html?url=./files/WSc4e151a45a3b785a24c3d9a411df9298473-7ffd.htm,topicNumber=d0e9492
<add>
<add>import {
<add> Loader,
<add> FileLoader,
<add> Vector3,
<add> DataTexture,
<add> DataTexture3D,
<add> RGBFormat,
<add> UnsignedByteType,
<add> ClampToEdgeWrapping,
<add> LinearFilter,
<add>} from '//unpkg.com/[email protected]/build/three.module.js';
<add>
<add>export class LUT3dlLoader extends Loader {
<add>
<add> load( url, onLoad, onProgress, onError ) {
<add>
<add> const loader = new FileLoader( this.manager );
<add> loader.setPath( this.path );
<add> loader.setResponseType( 'text' );
<add> loader.load( url, text => {
<add>
<add> try {
<add>
<add> onLoad( this.parse( text ) );
<add>
<add> } catch ( e ) {
<add>
<add> if ( onError ) {
<add>
<add> onError( e );
<add>
<add> } else {
<add>
<add> console.error( e );
<add>
<add> }
<add>
<add> this.manager.itemError( url );
<add>
<add> }
<add>
<add> }, onProgress, onError );
<add>
<add> }
<add>
<add> parse( str ) {
<add>
<add> // remove empty lines and comment lints
<add> str = str
<add> .replace( /^#.*?(\n|\r)/gm, '' )
<add> .replace( /^\s*?(\n|\r)/gm, '' )
<add> .trim();
<add>
<add> const lines = str.split( /[\n\r]+/g );
<add>
<add> // first line is the positions on the grid that are provided by the LUT
<add> const gridLines = lines[ 0 ].trim().split( /\s+/g ).map( e => parseFloat( e ) );
<add> const gridStep = gridLines[ 1 ] - gridLines[ 0 ];
<add> const size = gridLines.length;
<add>
<add> for ( let i = 1, l = gridLines.length; i < l; i ++ ) {
<add>
<add> if ( gridStep !== ( gridLines[ i ] - gridLines[ i - 1 ] ) ) {
<add>
<add> throw new Error( 'LUT3dlLoader: Inconsistent grid size not supported.' );
<add>
<add> }
<add>
<add> }
<add>
<add> const dataArray = new Array( size * size * size * 3 );
<add> let index = 0;
<add> let maxOutputValue = 0.0;
<add> for ( let i = 1, l = lines.length; i < l; i ++ ) {
<add>
<add> const line = lines[ i ].trim();
<add> const split = line.split( /\s/g );
<add>
<add> const r = parseFloat( split[ 0 ] );
<add> const g = parseFloat( split[ 1 ] );
<add> const b = parseFloat( split[ 2 ] );
<add> maxOutputValue = Math.max( maxOutputValue, r, g, b );
<add>
<add> const bLayer = index % size;
<add> const gLayer = Math.floor( index / size ) % size;
<add> const rLayer = Math.floor( index / ( size * size ) ) % size;
<add>
<add> // b grows first, then g, then r
<add> const pixelIndex = bLayer * size * size + gLayer * size + rLayer;
<add> dataArray[ 3 * pixelIndex + 0 ] = r;
<add> dataArray[ 3 * pixelIndex + 1 ] = g;
<add> dataArray[ 3 * pixelIndex + 2 ] = b;
<add> index += 1;
<add>
<add> }
<add>
<add> // Find the apparent bit depth of the stored RGB values and scale the
<add> // values to [ 0, 255 ].
<add> const bits = Math.ceil( Math.log2( maxOutputValue ) );
<add> const maxBitValue = Math.pow( 2.0, bits );
<add> for ( let i = 0, l = dataArray.length; i < l; i ++ ) {
<add>
<add> const val = dataArray[ i ];
<add> dataArray[ i ] = 255 * val / maxBitValue;
<add>
<add> }
<add>
<add> const data = new Uint8Array( dataArray );
<add> const texture = new DataTexture();
<add> texture.image.data = data;
<add> texture.image.width = size;
<add> texture.image.height = size * size;
<add> texture.format = RGBFormat;
<add> texture.type = UnsignedByteType;
<add> texture.magFilter = LinearFilter;
<add> texture.wrapS = ClampToEdgeWrapping;
<add> texture.wrapT = ClampToEdgeWrapping;
<add> texture.generateMipmaps = false;
<add>
<add> const texture3D = new DataTexture3D();
<add> texture3D.image.data = data;
<add> texture3D.image.width = size;
<add> texture3D.image.height = size;
<add> texture3D.image.depth = size;
<add> texture3D.format = RGBFormat;
<add> texture3D.type = UnsignedByteType;
<add> texture3D.magFilter = LinearFilter;
<add> texture3D.wrapS = ClampToEdgeWrapping;
<add> texture3D.wrapT = ClampToEdgeWrapping;
<add> texture3D.wrapR = ClampToEdgeWrapping;
<add> texture3D.generateMipmaps = false;
<add>
<add> return {
<add> size,
<add> texture,
<add> texture3D,
<add> };
<add>
<add> }
<add>
<add>}
<ide><path>examples/jsm/loaders/LUTCubeLoader.js
<add>// https://wwwimages2.adobe.com/content/dam/acom/en/products/speedgrade/cc/pdfs/cube-lut-specification-1.0.pdf
<add>
<add>import {
<add> Loader,
<add> FileLoader,
<add> Vector3,
<add> DataTexture,
<add> DataTexture3D,
<add> RGBFormat,
<add> UnsignedByteType,
<add> ClampToEdgeWrapping,
<add> LinearFilter,
<add>} from '//unpkg.com/[email protected]/build/three.module.js';
<add>
<add>export class LUTCubeLoader extends Loader {
<add>
<add> load( url, onLoad, onProgress, onError ) {
<add>
<add> const loader = new FileLoader( this.manager );
<add> loader.setPath( this.path );
<add> loader.setResponseType( 'text' );
<add> loader.load( url, text => {
<add>
<add> try {
<add>
<add> onLoad( this.parse( text ) );
<add>
<add> } catch ( e ) {
<add>
<add> if ( onError ) {
<add>
<add> onError( e );
<add>
<add> } else {
<add>
<add> console.error( e );
<add>
<add> }
<add>
<add> this.manager.itemError( url );
<add>
<add> }
<add>
<add> }, onProgress, onError );
<add>
<add> }
<add>
<add> parse( str ) {
<add>
<add> // Remove empty lines and comments
<add> str = str
<add> .replace( /^#.*?(\n|\r)/gm, '' )
<add> .replace( /^\s*?(\n|\r)/gm, '' )
<add> .trim();
<add>
<add> let title = null;
<add> let size = null;
<add> const domainMin = new Vector3( 0, 0, 0 );
<add> const domainMax = new Vector3( 1, 1, 1 );
<add>
<add> const lines = str.split( /[\n\r]+/g );
<add> let data = null;
<add>
<add> let currIndex = 0;
<add> for ( let i = 0, l = lines.length; i < l; i ++ ) {
<add>
<add> const line = lines[ i ].trim();
<add> const split = line.split( /\s/g );
<add>
<add> switch ( split[ 0 ] ) {
<add>
<add> case 'TITLE':
<add> title = line.substring( 7, line.length - 1 );
<add> break;
<add> case 'LUT_3D_SIZE':
<add> // TODO: A .CUBE LUT file specifies floating point values and could be represented with
<add> // more precision than can be captured with Uint8Array.
<add> const sizeToken = split[ 1 ];
<add> size = parseFloat( sizeToken );
<add> data = new Uint8Array( size * size * size * 3 );
<add> break;
<add> case 'DOMAIN_MIN':
<add> domainMin.x = parseFloat( split[ 1 ] );
<add> domainMin.y = parseFloat( split[ 2 ] );
<add> domainMin.z = parseFloat( split[ 3 ] );
<add> break;
<add> case 'DOMAIN_MAX':
<add> domainMax.x = parseFloat( split[ 1 ] );
<add> domainMax.y = parseFloat( split[ 2 ] );
<add> domainMax.z = parseFloat( split[ 3 ] );
<add> break;
<add> default:
<add> const r = parseFloat( split[ 0 ] );
<add> const g = parseFloat( split[ 1 ] );
<add> const b = parseFloat( split[ 2 ] );
<add>
<add> if (
<add> r > 1.0 || r < 0.0 ||
<add> g > 1.0 || g < 0.0 ||
<add> b > 1.0 || b < 0.0
<add> ) {
<add>
<add> throw new Error( 'LUTCubeLoader : Non normalized values not supported.' );
<add>
<add> }
<add>
<add> data[ currIndex + 0 ] = r * 255;
<add> data[ currIndex + 1 ] = g * 255;
<add> data[ currIndex + 2 ] = b * 255;
<add> currIndex += 3;
<add>
<add> }
<add>
<add> }
<add>
<add> const texture = new DataTexture();
<add> texture.image.data = data;
<add> texture.image.width = size;
<add> texture.image.height = size * size;
<add> texture.format = RGBFormat;
<add> texture.type = UnsignedByteType;
<add> texture.magFilter = LinearFilter;
<add> texture.wrapS = ClampToEdgeWrapping;
<add> texture.wrapT = ClampToEdgeWrapping;
<add> texture.generateMipmaps = false;
<add>
<add> const texture3D = new DataTexture3D();
<add> texture3D.image.data = data;
<add> texture3D.image.width = size;
<add> texture3D.image.height = size;
<add> texture3D.image.depth = size;
<add> texture3D.format = RGBFormat;
<add> texture3D.type = UnsignedByteType;
<add> texture3D.magFilter = LinearFilter;
<add> texture3D.wrapS = ClampToEdgeWrapping;
<add> texture3D.wrapT = ClampToEdgeWrapping;
<add> texture3D.wrapR = ClampToEdgeWrapping;
<add> texture3D.generateMipmaps = false;
<add>
<add> return {
<add> title,
<add> size,
<add> domainMin,
<add> domainMax,
<add> texture,
<add> texture3D,
<add> };
<add>
<add> }
<add>
<add>} | 2 |
Go | Go | remove old tag format | 8228d0e2bbd3a42755a84e11455b51a5caf61a94 | <ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdTag(args ...string) error {
<ide> if err := cmd.Parse(args); err != nil {
<ide> return nil
<ide> }
<del> if cmd.NArg() != 2 && cmd.NArg() != 3 {
<add> if cmd.NArg() != 2 {
<ide> cmd.Usage()
<ide> return nil
<ide> }
<ide>
<del> var repository, tag string
<del>
<del> if cmd.NArg() == 3 {
<del> fmt.Fprintf(cli.err, "[DEPRECATED] The format 'IMAGE [REPOSITORY [TAG]]' as been deprecated. Please use IMAGE [REGISTRYHOST/][USERNAME/]NAME[:TAG]]\n")
<del> repository, tag = cmd.Arg(1), cmd.Arg(2)
<del> } else {
<add> var (
<ide> repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
<del> }
<del>
<del> v := url.Values{}
<add> v = url.Values{}
<add> )
<ide>
<ide> //Check if the given image name can be resolved
<ide> if _, _, err := registry.ResolveRepositoryName(repository); err != nil { | 1 |
PHP | PHP | add support for streamed reads | 06fa47c09419eacd7c82bfedaca41a0956ae6dc9 | <ide><path>src/Illuminate/Filesystem/FilesystemManager.php
<ide> public function createS3Driver(array $config)
<ide>
<ide> $options = $config['options'] ?? [];
<ide>
<add> $streamReads = $config['stream_reads'] ?? false;
<add>
<ide> return $this->adapt($this->createFlysystem(
<del> new S3Adapter(new S3Client($s3Config), $s3Config['bucket'], $root, $options), $config
<add> new S3Adapter(new S3Client($s3Config), $s3Config['bucket'], $root, $options, $streamReads), $config
<ide> ));
<ide> }
<ide> | 1 |
Javascript | Javascript | fix minor typographical error | 27a8824b50aa78e9a082b4377ca09250382a8655 | <ide><path>src/ng/filter/filters.js
<ide> var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+
<ide> * (e.g. `"h o''clock"`).
<ide> *
<ide> * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
<del> * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's
<add> * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
<ide> * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
<ide> * specified in the string input, the time is considered to be in the local timezone.
<ide> * @param {string=} format Formatting rules (see Description). If not specified, | 1 |
Ruby | Ruby | remove extra whitespace | 44f12bbba08071178ec256c03eecadacdf35dccf | <ide><path>actionpack/test/controller/flash_test.rb
<ide> def test_redirect_to_with_adding_flash_types
<ide>
<ide> class FlashIntegrationTest < ActionDispatch::IntegrationTest
<ide> SessionKey = '_myapp_session'
<del> Generator = ActiveSupport::DummyKeyGenerator.new('b3c631c314c0bbca50c1b2843150fe33')
<add> Generator = ActiveSupport::DummyKeyGenerator.new('b3c631c314c0bbca50c1b2843150fe33')
<ide>
<ide> class TestController < ActionController::Base
<ide> add_flash_types :bar | 1 |
Ruby | Ruby | remove dead code | e8210450ad141176efdc29895b835a0e132d14d5 | <ide><path>actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
<ide> def action_prefix(options)
<ide> def routing_type(options)
<ide> options[:routing_type] || :url
<ide> end
<del>
<del> def build_route_part(record, inflection)
<del> if record.is_a?(Symbol) || record.is_a?(String)
<del> record.to_s
<del> else
<del> if inflection == :singular
<del> model_name_from_record_or_class(record).singular_route_key
<del> else
<del> model_name_from_record_or_class(record).route_key
<del> end
<del> end
<del> end
<ide> end
<ide> end
<ide> end | 1 |
PHP | PHP | move nest() over | 239f52c48ca124ee51820a04619778a5f176c0ea | <ide><path>lib/Cake/Test/Case/Utility/Set2Test.php
<ide> public function testGet() {
<ide>
<ide> $result = Set2::get($data, '1.Article');
<ide> $this->assertEquals($data[1]['Article'], $result);
<add>
<add> $result = Set2::get($data, array('1', 'Article'));
<add> $this->assertEquals($data[1]['Article'], $result);
<ide> }
<ide>
<ide> /**
<ide> public function _mapCallback($value) {
<ide> public function _reduceCallback($one, $two) {
<ide> return $one + $two;
<ide> }
<add>
<add>/**
<add> * test Set nest with a normal model result set. For kicks rely on Set nest detecting the key names
<add> * automatically
<add> *
<add> * @return void
<add> */
<add> public function testNestModel() {
<add> $input = array(
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 1,
<add> 'parent_id' => null
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 2,
<add> 'parent_id' => 1
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 3,
<add> 'parent_id' => 1
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 4,
<add> 'parent_id' => 1
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 5,
<add> 'parent_id' => 1
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 6,
<add> 'parent_id' => null
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 7,
<add> 'parent_id' => 6
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 8,
<add> 'parent_id' => 6
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 9,
<add> 'parent_id' => 6
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 10,
<add> 'parent_id' => 6
<add> )
<add> )
<add> );
<add> $expected = array(
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 1,
<add> 'parent_id' => null
<add> ),
<add> 'children' => array(
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 2,
<add> 'parent_id' => 1
<add> ),
<add> 'children' => array()
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 3,
<add> 'parent_id' => 1
<add> ),
<add> 'children' => array()
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 4,
<add> 'parent_id' => 1
<add> ),
<add> 'children' => array()
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 5,
<add> 'parent_id' => 1
<add> ),
<add> 'children' => array()
<add> ),
<add>
<add> )
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 6,
<add> 'parent_id' => null
<add> ),
<add> 'children' => array(
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 7,
<add> 'parent_id' => 6
<add> ),
<add> 'children' => array()
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 8,
<add> 'parent_id' => 6
<add> ),
<add> 'children' => array()
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 9,
<add> 'parent_id' => 6
<add> ),
<add> 'children' => array()
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 10,
<add> 'parent_id' => 6
<add> ),
<add> 'children' => array()
<add> )
<add> )
<add> )
<add> );
<add> $result = Set2::nest($input);
<add> $this->assertEquals($expected, $result);
<add> }
<add>
<add>/**
<add> * test Set nest with a normal model result set, and a nominated root id
<add> *
<add> * @return void
<add> */
<add> public function testNestModelExplicitRoot() {
<add> $input = array(
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 1,
<add> 'parent_id' => null
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 2,
<add> 'parent_id' => 1
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 3,
<add> 'parent_id' => 1
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 4,
<add> 'parent_id' => 1
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 5,
<add> 'parent_id' => 1
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 6,
<add> 'parent_id' => null
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 7,
<add> 'parent_id' => 6
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 8,
<add> 'parent_id' => 6
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 9,
<add> 'parent_id' => 6
<add> ),
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 10,
<add> 'parent_id' => 6
<add> )
<add> )
<add> );
<add> $expected = array(
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 6,
<add> 'parent_id' => null
<add> ),
<add> 'children' => array(
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 7,
<add> 'parent_id' => 6
<add> ),
<add> 'children' => array()
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 8,
<add> 'parent_id' => 6
<add> ),
<add> 'children' => array()
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 9,
<add> 'parent_id' => 6
<add> ),
<add> 'children' => array()
<add> ),
<add> array(
<add> 'ModelName' => array(
<add> 'id' => 10,
<add> 'parent_id' => 6
<add> ),
<add> 'children' => array()
<add> )
<add> )
<add> )
<add> );
<add> $result = Set2::nest($input, array('root' => 6));
<add> $this->assertEquals($expected, $result);
<add> }
<add>
<add>/**
<add> * test Set nest with a 1d array - this method should be able to handle any type of array input
<add> *
<add> * @return void
<add> */
<add> public function testNest1Dimensional() {
<add> $input = array(
<add> array(
<add> 'id' => 1,
<add> 'parent_id' => null
<add> ),
<add> array(
<add> 'id' => 2,
<add> 'parent_id' => 1
<add> ),
<add> array(
<add> 'id' => 3,
<add> 'parent_id' => 1
<add> ),
<add> array(
<add> 'id' => 4,
<add> 'parent_id' => 1
<add> ),
<add> array(
<add> 'id' => 5,
<add> 'parent_id' => 1
<add> ),
<add> array(
<add> 'id' => 6,
<add> 'parent_id' => null
<add> ),
<add> array(
<add> 'id' => 7,
<add> 'parent_id' => 6
<add> ),
<add> array(
<add> 'id' => 8,
<add> 'parent_id' => 6
<add> ),
<add> array(
<add> 'id' => 9,
<add> 'parent_id' => 6
<add> ),
<add> array(
<add> 'id' => 10,
<add> 'parent_id' => 6
<add> )
<add> );
<add> $expected = array(
<add> array(
<add> 'id' => 1,
<add> 'parent_id' => null,
<add> 'children' => array(
<add> array(
<add> 'id' => 2,
<add> 'parent_id' => 1,
<add> 'children' => array()
<add> ),
<add> array(
<add> 'id' => 3,
<add> 'parent_id' => 1,
<add> 'children' => array()
<add> ),
<add> array(
<add> 'id' => 4,
<add> 'parent_id' => 1,
<add> 'children' => array()
<add> ),
<add> array(
<add> 'id' => 5,
<add> 'parent_id' => 1,
<add> 'children' => array()
<add> ),
<add>
<add> )
<add> ),
<add> array(
<add> 'id' => 6,
<add> 'parent_id' => null,
<add> 'children' => array(
<add> array(
<add> 'id' => 7,
<add> 'parent_id' => 6,
<add> 'children' => array()
<add> ),
<add> array(
<add> 'id' => 8,
<add> 'parent_id' => 6,
<add> 'children' => array()
<add> ),
<add> array(
<add> 'id' => 9,
<add> 'parent_id' => 6,
<add> 'children' => array()
<add> ),
<add> array(
<add> 'id' => 10,
<add> 'parent_id' => 6,
<add> 'children' => array()
<add> )
<add> )
<add> )
<add> );
<add> $result = Set2::nest($input, array('idPath' => '{n}.id', 'parentPath' => '{n}.parent_id'));
<add> $this->assertEquals($expected, $result);
<add> }
<add>
<add>/**
<add> * test Set nest with no specified parent data.
<add> *
<add> * The result should be the same as the input.
<add> * For an easier comparison, unset all the empty children arrays from the result
<add> *
<add> * @return void
<add> */
<add> public function testMissingParent() {
<add> $input = array(
<add> array(
<add> 'id' => 1,
<add> ),
<add> array(
<add> 'id' => 2,
<add> ),
<add> array(
<add> 'id' => 3,
<add> ),
<add> array(
<add> 'id' => 4,
<add> ),
<add> array(
<add> 'id' => 5,
<add> ),
<add> array(
<add> 'id' => 6,
<add> ),
<add> array(
<add> 'id' => 7,
<add> ),
<add> array(
<add> 'id' => 8,
<add> ),
<add> array(
<add> 'id' => 9,
<add> ),
<add> array(
<add> 'id' => 10,
<add> )
<add> );
<add>
<add> $result = Set2::nest($input, array('idPath' => '{n}.id', 'parentPath' => '{n}.parent_id'));
<add> foreach($result as &$row) {
<add> if (empty($row['children'])) {
<add> unset($row['children']);
<add> }
<add> }
<add> $this->assertEquals($input, $result);
<add> }
<ide> }
<ide><path>lib/Cake/Utility/Set2.php
<ide> public static function get(array $data, $path) {
<ide> if (empty($data) || empty($path)) {
<ide> return null;
<ide> }
<del> $parts = explode('.', $path);
<add> if (is_string($path)) {
<add> $parts = explode('.', $path);
<add> } else {
<add> $parts = $path;
<add> }
<ide> while (($key = array_shift($parts)) !== null) {
<ide> if (is_array($data) && isset($data[$key])) {
<ide> $data =& $data[$key];
<ide> public static function normalize(array $data, $assoc = true) {
<ide> return $data;
<ide> }
<ide>
<add>/**
<add> * Takes in a flat array and returns a nested array
<add> *
<add> * @param mixed $data
<add> * @param array $options Options are:
<add> * children - the key name to use in the resultset for children
<add> * idPath - the path to a key that identifies each entry
<add> * parentPath - the path to a key that identifies the parent of each entry
<add> * root - the id of the desired top-most result
<add> * @return array of results, nested
<add> * @link
<add> */
<add> public static function nest($data, $options = array()) {
<add> if (!$data) {
<add> return $data;
<add> }
<add>
<add> $alias = key(current($data));
<add> $options += array(
<add> 'idPath' => "{n}.$alias.id",
<add> 'parentPath' => "{n}.$alias.parent_id",
<add> 'children' => 'children',
<add> 'root' => null
<add> );
<add>
<add> $return = $idMap = array();
<add> $ids = self::extract($data, $options['idPath']);
<add>
<add> $idKeys = explode('.', $options['idPath']);
<add> array_shift($idKeys);
<add>
<add> $parentKeys = explode('.', $options['parentPath']);
<add> array_shift($parentKeys);
<add>
<add> foreach ($data as $result) {
<add> $result[$options['children']] = array();
<add>
<add> $id = self::get($result, $idKeys);
<add> $parentId = self::get($result, $parentKeys);
<add>
<add> if (isset($idMap[$id][$options['children']])) {
<add> $idMap[$id] = array_merge($result, (array)$idMap[$id]);
<add> } else {
<add> $idMap[$id] = array_merge($result, array($options['children'] => array()));
<add> }
<add> if (!$parentId || !in_array($parentId, $ids)) {
<add> $return[] =& $idMap[$id];
<add> } else {
<add> $idMap[$parentId][$options['children']][] =& $idMap[$id];
<add> }
<add> }
<add>
<add> if ($options['root']) {
<add> $root = $options['root'];
<add> } else {
<add> $root = self::get($return[0], $parentKeys);
<add> }
<add>
<add> foreach ($return as $i => $result) {
<add> $id = self::get($result, $idKeys);
<add> $parentId = self::get($result, $parentKeys);
<add> if ($id !== $root && $parentId != $root) {
<add> unset($return[$i]);
<add> }
<add> }
<add> return array_values($return);
<add> }
<add>
<ide> } | 2 |
Javascript | Javascript | avoid negative layout dimensions | 1a1e677699f7b466c970529bbb988dde81f0ad9c | <ide><path>src/core/core.layouts.js
<ide> export default {
<ide> }
<ide>
<ide> const padding = toPadding(chart.options.layout.padding);
<del> const availableWidth = width - padding.width;
<del> const availableHeight = height - padding.height;
<add> const availableWidth = Math.max(width - padding.width, 0);
<add> const availableHeight = Math.max(height - padding.height, 0);
<ide> const boxes = buildLayoutBoxes(chart.boxes);
<ide> const verticalBoxes = boxes.vertical;
<ide> const horizontalBoxes = boxes.horizontal;
<ide><path>test/specs/scale.linear.tests.js
<ide> describe('Linear Scale', function() {
<ide> expect(scale.getValueForPixel(end)).toBeCloseTo(min, 4);
<ide> expect(scale.getValueForPixel(start)).toBeCloseTo(max, 4);
<ide> });
<add>
<add> it('should not throw errors when chart size is negative', function() {
<add> function createChart() {
<add> return window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> labels: [0, 1, 2, 3, 4, 5, 6, 7, '7+'],
<add> datasets: [{
<add> data: [29.05, 4, 15.69, 11.69, 2.84, 4, 0, 3.84, 4],
<add> }],
<add> },
<add> options: {
<add> plugins: false,
<add> layout: {
<add> padding: {top: 30, left: 1, right: 1, bottom: 1}
<add> }
<add> }
<add> }, {
<add> canvas: {
<add> height: 0,
<add> width: 0
<add> }
<add> });
<add> }
<add>
<add> expect(createChart).not.toThrow();
<add> });
<ide> }); | 2 |
Javascript | Javascript | allow static classes in bindattr | ce385e3294be019215c555511c7f393aebc02e41 | <ide><path>packages/ember-handlebars/lib/helpers/binding.js
<ide> EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId)
<ide>
<ide> property = split[0];
<ide>
<del> var val = getPath(context, property);
<add> var val = property !== '' ? getPath(context, property) : true;
<ide>
<ide> // If value is a Boolean and true, return the dasherized property
<ide> // name.
<ide> EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId)
<ide> };
<ide>
<ide> var property = binding.split(':')[0];
<del> Ember.addObserver(context, property, invoker);
<add> if (property !== '') {
<add> Ember.addObserver(context, property, invoker);
<add> }
<ide>
<ide> // We've already setup the observer; now we just need to figure out the
<ide> // correct behavior right now on the first pass through.
<ide><path>packages/ember-handlebars/tests/handlebars_test.js
<ide> test("should be able to bind boolean element attributes using {{bindAttr}}", fun
<ide> });
<ide>
<ide> test("should be able to add multiple classes using {{bindAttr class}}", function() {
<del> var template = Ember.Handlebars.compile('<div {{bindAttr class="content.isAwesomeSauce content.isAlsoCool content.isAmazing:amazing"}}></div>');
<add> var template = Ember.Handlebars.compile('<div {{bindAttr class="content.isAwesomeSauce content.isAlsoCool content.isAmazing:amazing :is-super-duper"}}></div>');
<ide> var content = Ember.Object.create({
<ide> isAwesomeSauce: true,
<ide> isAlsoCool: true,
<ide> test("should be able to add multiple classes using {{bindAttr class}}", function
<ide> ok(view.$('div').hasClass('is-awesome-sauce'), "dasherizes first property and sets classname");
<ide> ok(view.$('div').hasClass('is-also-cool'), "dasherizes second property and sets classname");
<ide> ok(view.$('div').hasClass('amazing'), "uses alias for third property and sets classname");
<add> ok(view.$('div').hasClass('is-super-duper'), "static class is present");
<ide>
<ide> Ember.run(function() {
<ide> set(content, 'isAwesomeSauce', false);
<ide> test("should be able to add multiple classes using {{bindAttr class}}", function
<ide>
<ide> ok(!view.$('div').hasClass('is-awesome-sauce'), "removes dasherized class when property is set to false");
<ide> ok(!view.$('div').hasClass('amazing'), "removes aliased class when property is set to false");
<add> ok(view.$('div').hasClass('is-super-duper'), "static class is still present");
<ide> });
<ide>
<ide> test("should be able to bindAttr to 'this' in an {{#each}} block", function() { | 2 |
PHP | PHP | remove redundancy in regex | 49d11d3a7c34a4d00027602eb309b53d378cc98e | <ide><path>src/View/StringTemplate.php
<ide> protected function _compileTemplates(array $templates = []): void
<ide> }
<ide>
<ide> $template = str_replace('%', '%%', $template);
<del> preg_match_all('#\{\{([\w\._]+)\}\}#', $template, $matches);
<add> preg_match_all('#\{\{([\w\.]+)\}\}#', $template, $matches);
<ide> $this->_compiled[$name] = [
<ide> str_replace($matches[0], '%s', $template),
<ide> $matches[1], | 1 |
Mixed | Go | use argv0 as reexec implementation for dockerinit | 73210671764fc3de133a627205582e069e1ff43d | <ide><path>daemon/execdriver/driver.go
<ide> var (
<ide> ErrDriverNotFound = errors.New("The requested docker init has not been found")
<ide> )
<ide>
<del>var dockerInitFcts map[string]InitFunc
<del>
<del>type (
<del> StartCallback func(*Command)
<del> InitFunc func(i *InitArgs) error
<del>)
<del>
<del>func RegisterInitFunc(name string, fct InitFunc) error {
<del> if dockerInitFcts == nil {
<del> dockerInitFcts = make(map[string]InitFunc)
<del> }
<del> if _, ok := dockerInitFcts[name]; ok {
<del> return ErrDriverAlreadyRegistered
<del> }
<del> dockerInitFcts[name] = fct
<del> return nil
<del>}
<del>
<del>func GetInitFunc(name string) (InitFunc, error) {
<del> fct, ok := dockerInitFcts[name]
<del> if !ok {
<del> return nil, ErrDriverNotFound
<del> }
<del> return fct, nil
<del>}
<del>
<del>// Args provided to the init function for a driver
<del>type InitArgs struct {
<del> User string
<del> Gateway string
<del> Ip string
<del> WorkDir string
<del> Privileged bool
<del> Env []string
<del> Args []string
<del> Mtu int
<del> Driver string
<del> Console string
<del> Pipe int
<del> Root string
<del> CapAdd string
<del> CapDrop string
<del>}
<add>type StartCallback func(*Command)
<ide>
<ide> // Driver specific information based on
<ide> // processes registered with the driver
<ide><path>daemon/execdriver/lxc/driver.go
<ide> import (
<ide> "fmt"
<ide> "io"
<ide> "io/ioutil"
<del> "log"
<ide> "os"
<ide> "os/exec"
<ide> "path"
<ide> "path/filepath"
<del> "runtime"
<ide> "strconv"
<ide> "strings"
<ide> "syscall"
<ide> import (
<ide>
<ide> const DriverName = "lxc"
<ide>
<del>func init() {
<del> execdriver.RegisterInitFunc(DriverName, func(args *execdriver.InitArgs) error {
<del> runtime.LockOSThread()
<del> if err := setupEnv(args); err != nil {
<del> return err
<del> }
<del> if err := setupHostname(args); err != nil {
<del> return err
<del> }
<del> if err := setupNetworking(args); err != nil {
<del> return err
<del> }
<del> if err := finalizeNamespace(args); err != nil {
<del> return err
<del> }
<del>
<del> path, err := exec.LookPath(args.Args[0])
<del> if err != nil {
<del> log.Printf("Unable to locate %v", args.Args[0])
<del> os.Exit(127)
<del> }
<del> if err := syscall.Exec(path, args.Args, os.Environ()); err != nil {
<del> return fmt.Errorf("dockerinit unable to execute %s - %s", path, err)
<del> }
<del> panic("Unreachable")
<del> })
<del>}
<del>
<ide> type driver struct {
<ide> root string // root path for the driver to use
<ide> initPath string
<ide> func NewDriver(root, initPath string, apparmor bool) (*driver, error) {
<ide> if err := linkLxcStart(root); err != nil {
<ide> return nil, err
<ide> }
<add>
<ide> return &driver{
<ide> apparmor: apparmor,
<ide> root: root,
<ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba
<ide> "-f", configPath,
<ide> "--",
<ide> c.InitPath,
<del> "-driver",
<del> DriverName,
<ide> }
<ide>
<ide> if c.Network.Interface != nil {
<ide><path>daemon/execdriver/lxc/init.go
<ide> package lxc
<ide>
<ide> import (
<ide> "encoding/json"
<add> "flag"
<ide> "fmt"
<ide> "io/ioutil"
<add> "log"
<ide> "net"
<ide> "os"
<add> "os/exec"
<add> "runtime"
<ide> "strings"
<ide> "syscall"
<ide>
<del> "github.com/docker/docker/daemon/execdriver"
<add> "github.com/docker/docker/reexec"
<ide> "github.com/docker/libcontainer/netlink"
<ide> )
<ide>
<add>// Args provided to the init function for a driver
<add>type InitArgs struct {
<add> User string
<add> Gateway string
<add> Ip string
<add> WorkDir string
<add> Privileged bool
<add> Env []string
<add> Args []string
<add> Mtu int
<add> Console string
<add> Pipe int
<add> Root string
<add> CapAdd string
<add> CapDrop string
<add>}
<add>
<add>func init() {
<add> // like always lxc requires a hack to get this to work
<add> reexec.Register("/.dockerinit", dockerInititalizer)
<add>}
<add>
<add>func dockerInititalizer() {
<add> initializer()
<add>}
<add>
<add>// initializer is the lxc driver's init function that is run inside the namespace to setup
<add>// additional configurations
<add>func initializer() {
<add> runtime.LockOSThread()
<add>
<add> args := getArgs()
<add>
<add> if err := setupNamespace(args); err != nil {
<add> log.Fatal(err)
<add> }
<add>}
<add>
<add>func setupNamespace(args *InitArgs) error {
<add> if err := setupEnv(args); err != nil {
<add> return err
<add> }
<add> if err := setupHostname(args); err != nil {
<add> return err
<add> }
<add> if err := setupNetworking(args); err != nil {
<add> return err
<add> }
<add> if err := finalizeNamespace(args); err != nil {
<add> return err
<add> }
<add>
<add> path, err := exec.LookPath(args.Args[0])
<add> if err != nil {
<add> log.Printf("Unable to locate %v", args.Args[0])
<add> os.Exit(127)
<add> }
<add>
<add> if err := syscall.Exec(path, args.Args, os.Environ()); err != nil {
<add> return fmt.Errorf("dockerinit unable to execute %s - %s", path, err)
<add> }
<add>
<add> return nil
<add>}
<add>
<add>func getArgs() *InitArgs {
<add> var (
<add> // Get cmdline arguments
<add> user = flag.String("u", "", "username or uid")
<add> gateway = flag.String("g", "", "gateway address")
<add> ip = flag.String("i", "", "ip address")
<add> workDir = flag.String("w", "", "workdir")
<add> privileged = flag.Bool("privileged", false, "privileged mode")
<add> mtu = flag.Int("mtu", 1500, "interface mtu")
<add> capAdd = flag.String("cap-add", "", "capabilities to add")
<add> capDrop = flag.String("cap-drop", "", "capabilities to drop")
<add> )
<add>
<add> flag.Parse()
<add>
<add> return &InitArgs{
<add> User: *user,
<add> Gateway: *gateway,
<add> Ip: *ip,
<add> WorkDir: *workDir,
<add> Privileged: *privileged,
<add> Args: flag.Args(),
<add> Mtu: *mtu,
<add> CapAdd: *capAdd,
<add> CapDrop: *capDrop,
<add> }
<add>}
<add>
<ide> // Clear environment pollution introduced by lxc-start
<del>func setupEnv(args *execdriver.InitArgs) error {
<add>func setupEnv(args *InitArgs) error {
<ide> // Get env
<ide> var env []string
<ide> content, err := ioutil.ReadFile(".dockerenv")
<ide> func setupEnv(args *execdriver.InitArgs) error {
<ide> return nil
<ide> }
<ide>
<del>func setupHostname(args *execdriver.InitArgs) error {
<add>func setupHostname(args *InitArgs) error {
<ide> hostname := getEnv(args, "HOSTNAME")
<ide> if hostname == "" {
<ide> return nil
<ide> func setupHostname(args *execdriver.InitArgs) error {
<ide> }
<ide>
<ide> // Setup networking
<del>func setupNetworking(args *execdriver.InitArgs) error {
<add>func setupNetworking(args *InitArgs) error {
<ide> if args.Ip != "" {
<ide> // eth0
<ide> iface, err := net.InterfaceByName("eth0")
<ide> func setupNetworking(args *execdriver.InitArgs) error {
<ide> }
<ide>
<ide> // Setup working directory
<del>func setupWorkingDirectory(args *execdriver.InitArgs) error {
<add>func setupWorkingDirectory(args *InitArgs) error {
<ide> if args.WorkDir == "" {
<ide> return nil
<ide> }
<ide> func setupWorkingDirectory(args *execdriver.InitArgs) error {
<ide> return nil
<ide> }
<ide>
<del>func getEnv(args *execdriver.InitArgs, key string) string {
<add>func getEnv(args *InitArgs, key string) string {
<ide> for _, kv := range args.Env {
<ide> parts := strings.SplitN(kv, "=", 2)
<ide> if parts[0] == key && len(parts) == 2 {
<ide><path>daemon/execdriver/lxc/lxc_init_linux.go
<ide> func setHostname(hostname string) error {
<ide> return syscall.Sethostname([]byte(hostname))
<ide> }
<ide>
<del>func finalizeNamespace(args *execdriver.InitArgs) error {
<add>func finalizeNamespace(args *InitArgs) error {
<ide> if err := utils.CloseExecFrom(3); err != nil {
<ide> return err
<ide> }
<ide><path>daemon/execdriver/native/driver.go
<ide> import (
<ide> "github.com/docker/libcontainer/cgroups/systemd"
<ide> consolepkg "github.com/docker/libcontainer/console"
<ide> "github.com/docker/libcontainer/namespaces"
<del> "github.com/docker/libcontainer/syncpipe"
<ide> "github.com/docker/libcontainer/system"
<ide> )
<ide>
<ide> const (
<ide> Version = "0.2"
<ide> )
<ide>
<del>func init() {
<del> execdriver.RegisterInitFunc(DriverName, func(args *execdriver.InitArgs) error {
<del> var container *libcontainer.Config
<del> f, err := os.Open(filepath.Join(args.Root, "container.json"))
<del> if err != nil {
<del> return err
<del> }
<del>
<del> if err := json.NewDecoder(f).Decode(&container); err != nil {
<del> f.Close()
<del> return err
<del> }
<del> f.Close()
<del>
<del> rootfs, err := os.Getwd()
<del> if err != nil {
<del> return err
<del> }
<del>
<del> syncPipe, err := syncpipe.NewSyncPipeFromFd(0, uintptr(args.Pipe))
<del> if err != nil {
<del> return err
<del> }
<del>
<del> if err := namespaces.Init(container, rootfs, args.Console, syncPipe, args.Args); err != nil {
<del> return err
<del> }
<del>
<del> return nil
<del> })
<del>}
<del>
<ide> type activeContainer struct {
<ide> container *libcontainer.Config
<ide> cmd *exec.Cmd
<ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba
<ide> }
<ide>
<ide> return namespaces.Exec(container, c.Stdin, c.Stdout, c.Stderr, c.Console, c.Rootfs, dataPath, args, func(container *libcontainer.Config, console, rootfs, dataPath, init string, child *os.File, args []string) *exec.Cmd {
<del> // we need to join the rootfs because namespaces will setup the rootfs and chroot
<del> initPath := filepath.Join(c.Rootfs, c.InitPath)
<del>
<ide> c.Path = d.initPath
<ide> c.Args = append([]string{
<del> initPath,
<del> "-driver", DriverName,
<add> DriverName,
<ide> "-console", console,
<ide> "-pipe", "3",
<ide> "-root", filepath.Join(d.root, c.ID),
<ide><path>daemon/execdriver/native/init.go
<add>// +build linux
<add>
<add>package native
<add>
<add>import (
<add> "encoding/json"
<add> "flag"
<add> "fmt"
<add> "os"
<add> "path/filepath"
<add> "runtime"
<add>
<add> "github.com/docker/docker/reexec"
<add> "github.com/docker/libcontainer"
<add> "github.com/docker/libcontainer/namespaces"
<add> "github.com/docker/libcontainer/syncpipe"
<add>)
<add>
<add>func init() {
<add> reexec.Register(DriverName, initializer)
<add>}
<add>
<add>func initializer() {
<add> runtime.LockOSThread()
<add>
<add> var (
<add> pipe = flag.Int("pipe", 0, "sync pipe fd")
<add> console = flag.String("console", "", "console (pty slave) path")
<add> root = flag.String("root", ".", "root path for configuration files")
<add> )
<add>
<add> flag.Parse()
<add>
<add> var container *libcontainer.Config
<add> f, err := os.Open(filepath.Join(*root, "container.json"))
<add> if err != nil {
<add> writeError(err)
<add> }
<add>
<add> if err := json.NewDecoder(f).Decode(&container); err != nil {
<add> f.Close()
<add> writeError(err)
<add> }
<add> f.Close()
<add>
<add> rootfs, err := os.Getwd()
<add> if err != nil {
<add> writeError(err)
<add> }
<add>
<add> syncPipe, err := syncpipe.NewSyncPipeFromFd(0, uintptr(*pipe))
<add> if err != nil {
<add> writeError(err)
<add> }
<add>
<add> if err := namespaces.Init(container, rootfs, *console, syncPipe, flag.Args()); err != nil {
<add> writeError(err)
<add> }
<add>
<add> panic("Unreachable")
<add>}
<add>
<add>func writeError(err error) {
<add> fmt.Sprint(os.Stderr, err)
<add>}
<ide><path>docker/client.go
<ide> import (
<ide>
<ide> const CanDaemon = false
<ide>
<del>func mainSysinit() {
<del> log.Fatal("This is a client-only binary - running it as 'dockerinit' is not supported.")
<del>}
<del>
<ide> func mainDaemon() {
<ide> log.Fatal("This is a client-only binary - running the Docker daemon is not supported.")
<ide> }
<ide><path>docker/daemon.go
<ide> import (
<ide> "net"
<ide>
<ide> "github.com/docker/docker/builtins"
<add> _ "github.com/docker/docker/daemon/execdriver/lxc"
<add> _ "github.com/docker/docker/daemon/execdriver/native"
<ide> "github.com/docker/docker/dockerversion"
<ide> "github.com/docker/docker/engine"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/signal"
<del> "github.com/docker/docker/sysinit"
<ide> )
<ide>
<ide> const CanDaemon = true
<ide>
<del>func mainSysinit() {
<del> // Running in init mode
<del> sysinit.SysInit()
<del>}
<del>
<ide> func mainDaemon() {
<ide> if flag.NArg() != 0 {
<ide> flag.Usage()
<ide><path>docker/docker.go
<ide> import (
<ide> "github.com/docker/docker/api/client"
<ide> "github.com/docker/docker/dockerversion"
<ide> flag "github.com/docker/docker/pkg/mflag"
<add> "github.com/docker/docker/reexec"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide>
<ide> const (
<ide> )
<ide>
<ide> func main() {
<del> if selfPath := utils.SelfPath(); strings.Contains(selfPath, ".dockerinit") {
<del> mainSysinit()
<add> if reexec.Init() {
<ide> return
<ide> }
<ide>
<ide><path>dockerinit/dockerinit.go
<ide> package main
<ide>
<ide> import (
<del> "github.com/docker/docker/sysinit"
<add> _ "github.com/docker/docker/daemon/execdriver/lxc"
<add> _ "github.com/docker/docker/daemon/execdriver/native"
<add> "github.com/docker/docker/reexec"
<ide> )
<ide>
<ide> func main() {
<ide> // Running in init mode
<del> sysinit.SysInit()
<del> return
<add> reexec.Init()
<ide> }
<ide><path>reexec/README.md
<add>## reexec
<add>
<add>The `reexec` package facilitates the busybox style reexec of the docker binary that we require because
<add>of the forking limitations of using Go. Handlers can be registered with a name and the argv 0 of
<add>the exec of the binary will be used to find and execute custom init paths.
<ide><path>reexec/reexec.go
<add>package reexec
<add>
<add>import "os"
<add>
<add>var registeredInitializers = make(map[string]func())
<add>
<add>// Register adds an initialization func under the specified name
<add>func Register(name string, initializer func()) {
<add> registeredInitializers[name] = initializer
<add>}
<add>
<add>// Init is called as the first part of the exec process and returns true if an
<add>// initialization function was called.
<add>func Init() bool {
<add> initializer, exists := registeredInitializers[os.Args[0]]
<add> if exists {
<add> initializer()
<add>
<add> return true
<add> }
<add>
<add> return false
<add>}
<ide><path>sysinit/sysinit.go
<ide> package sysinit
<ide>
<ide> import (
<del> "flag"
<ide> "fmt"
<del> "log"
<ide> "os"
<ide> "runtime"
<del>
<del> "github.com/docker/docker/daemon/execdriver"
<del> _ "github.com/docker/docker/daemon/execdriver/lxc"
<del> _ "github.com/docker/docker/daemon/execdriver/native"
<ide> )
<ide>
<del>func executeProgram(args *execdriver.InitArgs) error {
<del> dockerInitFct, err := execdriver.GetInitFunc(args.Driver)
<del> if err != nil {
<del> panic(err)
<del> }
<del> return dockerInitFct(args)
<del>}
<del>
<ide> // Sys Init code
<ide> // This code is run INSIDE the container and is responsible for setting
<ide> // up the environment before running the actual process
<ide> func SysInit() {
<ide> os.Exit(1)
<ide> }
<ide>
<del> var (
<del> // Get cmdline arguments
<del> user = flag.String("u", "", "username or uid")
<del> gateway = flag.String("g", "", "gateway address")
<del> ip = flag.String("i", "", "ip address")
<del> workDir = flag.String("w", "", "workdir")
<del> privileged = flag.Bool("privileged", false, "privileged mode")
<del> mtu = flag.Int("mtu", 1500, "interface mtu")
<del> driver = flag.String("driver", "", "exec driver")
<del> pipe = flag.Int("pipe", 0, "sync pipe fd")
<del> console = flag.String("console", "", "console (pty slave) path")
<del> root = flag.String("root", ".", "root path for configuration files")
<del> capAdd = flag.String("cap-add", "", "capabilities to add")
<del> capDrop = flag.String("cap-drop", "", "capabilities to drop")
<del> )
<del> flag.Parse()
<del>
<del> args := &execdriver.InitArgs{
<del> User: *user,
<del> Gateway: *gateway,
<del> Ip: *ip,
<del> WorkDir: *workDir,
<del> Privileged: *privileged,
<del> Args: flag.Args(),
<del> Mtu: *mtu,
<del> Driver: *driver,
<del> Console: *console,
<del> Pipe: *pipe,
<del> Root: *root,
<del> CapAdd: *capAdd,
<del> CapDrop: *capDrop,
<del> }
<del>
<del> if err := executeProgram(args); err != nil {
<del> log.Fatal(err)
<del> }
<ide> } | 13 |
Ruby | Ruby | remove unused require | aec2b8b363dc907aa1a48cef3d7608ffae1ba2ab | <ide><path>activesupport/lib/active_support/test_case.rb
<ide> require "active_support/testing/constant_lookup"
<ide> require "active_support/testing/time_helpers"
<ide> require "active_support/testing/file_fixtures"
<del>require "active_support/core_ext/kernel/reporting"
<ide>
<ide> module ActiveSupport
<ide> class TestCase < ::Minitest::Test | 1 |
Go | Go | fix bind-mounts only partially removed | b4283209d55289abb2c5b63df949a27c2704f5af | <ide><path>volumes/repository.go
<ide> func (r *Repository) Delete(path string) error {
<ide> return err
<ide> }
<ide>
<del> if volume.IsBindMount {
<del> return nil
<del> }
<del>
<del> if err := r.driver.Remove(volume.ID); err != nil {
<del> if !os.IsNotExist(err) {
<del> return err
<add> if !volume.IsBindMount {
<add> if err := r.driver.Remove(volume.ID); err != nil {
<add> if !os.IsNotExist(err) {
<add> return err
<add> }
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | reinstate dom_id in controllers | ea4f8ef33f08a69a68f6b95f392e63ea9cc13602 | <ide><path>actionpack/lib/action_controller/base.rb
<ide> class Base < Metal
<ide> include ActionController::Verification
<ide> include ActionController::RequestForgeryProtection
<ide> include ActionController::Streaming
<add> include ActionController::RecordIdentifier
<ide> include ActionController::HttpAuthentication::Basic::ControllerMethods
<ide> include ActionController::HttpAuthentication::Digest::ControllerMethods
<ide>
<ide><path>actionpack/test/controller/base_test.rb
<ide> def url_options
<ide> end
<ide> end
<ide>
<add>class RecordIdentifierController < ActionController::Base
<add>end
<add>
<ide> class ControllerClassTests < ActiveSupport::TestCase
<ide> def test_controller_path
<ide> assert_equal 'empty', EmptyController.controller_path
<ide> def test_filter_parameter_logging
<ide>
<ide> assert_equal [:password], parameters
<ide> end
<add>
<add> def test_record_identifier
<add> assert_respond_to RecordIdentifierController.new, :dom_id
<add> assert_respond_to RecordIdentifierController.new, :dom_class
<add> end
<ide> end
<ide>
<ide> class ControllerInstanceTests < Test::Unit::TestCase | 2 |
Javascript | Javascript | remove unnecessary import | f884c987e29acef83a40164b681950a7fd8bf047 | <ide><path>src/auto-update-manager.js
<ide> 'use babel'
<ide>
<ide> import {Emitter, CompositeDisposable} from 'event-kit'
<del>import {ipcRenderer} from 'electron'
<ide>
<ide> export default class AutoUpdateManager {
<ide> constructor ({applicationDelegate}) { | 1 |
PHP | PHP | fix empty session | e9ed079a6a3b51508273488c1f90fe95a47e9dcc | <ide><path>src/Illuminate/Session/FileSessionHandler.php
<ide> public function read($sessionId)
<ide> {
<ide> if ($this->files->exists($path = $this->path.'/'.$sessionId)) {
<ide> if (filemtime($path) >= Carbon::now()->subMinutes($this->minutes)->getTimestamp()) {
<del> return $this->files->get($path);
<add> return $this->files->get($path, true);
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | add some implicit path tests to subscriber | 13d76b6170886493369f94693e61364044e4316a | <ide><path>actionpack/test/template/subscriber_test.rb
<ide> def test_render_partial_template
<ide> assert_match /Rendered test\/_customer.erb/, @logger.logged(:info).last
<ide> end
<ide>
<add> def test_render_partial_with_implicit_path
<add> @view.stubs(:controller_path).returns("test")
<add> @view.render(Customer.new("david"), :greeting => "hi")
<add> wait
<add>
<add> assert_equal 1, @logger.logged(:info).size
<add> assert_match /Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last
<add> end
<add>
<ide> def test_render_collection_template
<ide> @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ])
<ide> wait
<ide> def test_render_collection_template
<ide> assert_match /Rendered test\/_customer.erb/, @logger.logged(:info).last
<ide> end
<ide>
<add> def test_render_collection_with_implicit_path
<add> @view.stubs(:controller_path).returns("test")
<add> @view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi")
<add> wait
<add>
<add> assert_equal 1, @logger.logged(:info).size
<add> assert_match /Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last
<add> end
<add>
<ide> def test_render_collection_template_without_path
<ide> @view.stubs(:controller_path).returns("test")
<ide> @view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi")
<ide> def test_render_collection_template_without_path
<ide> assert_match /Rendered collection/, @logger.logged(:info).last
<ide> end
<ide>
<del>
<ide> class SyncSubscriberTest < ActiveSupport::TestCase
<ide> include Rails::Subscriber::SyncTestHelper
<ide> include ActionViewSubscriberTest | 1 |
Python | Python | fix documentation in projectedadaptivelogsoftmax | d7dabfeff515d8714adeb182107a74be87d77149 | <ide><path>src/transformers/modeling_transfo_xl_utilities.py
<ide> def forward(self, hidden, labels=None, keep_order=False):
<ide> labels :: [len*bsz]
<ide> Return:
<ide> if labels is None:
<del> out :: [len*bsz] Negative log likelihood
<del> else:
<ide> out :: [len*bsz x n_tokens] log probabilities of tokens over the vocabulary
<add> else:
<add> out :: [len*bsz] Negative log likelihood
<ide> We could replace this implementation by the native PyTorch one
<ide> if their's had an option to set bias on all clusters in the native one.
<ide> here: https://github.com/pytorch/pytorch/blob/dbe6a7a9ff1a364a8706bf5df58a1ca96d2fd9da/torch/nn/modules/adaptive.py#L138 | 1 |
Text | Text | add 3.4.6 and 3.5.1 to the changelog.md | 19f5c8919052d1acea9147b341dbbc8009c34f59 | <ide><path>CHANGELOG.md
<ide> - [#17025](https://github.com/emberjs/ember.js/pull/17025) / [#17034](https://github.com/emberjs/ember.js/pull/17034) / [#17036](https://github.com/emberjs/ember.js/pull/17036) / [#17038](https://github.com/emberjs/ember.js/pull/17038) / [#17040](https://github.com/emberjs/ember.js/pull/17040) / [#17041](https://github.com/emberjs/ember.js/pull/17041) / [#17061](https://github.com/emberjs/ember.js/pull/17061) [FEATURE] Final stage of the router service RFC (see [emberjs/rfcs#95](https://github.com/emberjs/rfcs/blob/master/text/0095-router-service.md)
<ide> - [#17051](https://github.com/emberjs/ember.js/pull/17051) Update glimmer-vm packages to 0.36.4
<ide>
<add>### v3.5.1 (October 29, 2018)
<add>
<add>- [#17028](https://github.com/emberjs/ember.js/pull/17028) Mark `defineProperty` as public (yet low level) API.
<add>- [#17115](https://github.com/emberjs/ember.js/pull/17115) [BUGFIX] Pass the event parameter to sendAction
<add>- [#17128](https://github.com/emberjs/ember.js/pull/17128) [BUGFIX] Fix sourcemaping issues due to multiple sourcemap directives.
<add>- [#17130](https://github.com/emberjs/ember.js/pull/17130) [BUGFIX] Ensure that timers scheduled after a system sleep are fired properly.
<add>
<ide> ### v3.5.0 (October 8, 2018)
<ide>
<ide> - [#16978](https://github.com/emberjs/ember.js/pull/16978) [BUGFIX] Properly teardown alias
<ide> - [#16877](https://github.com/emberjs/ember.js/pull/16877) [CLEANUP] Allow routes to be named "array" and "object"
<ide>
<add>### v3.4.6 (October 29, 2018)
<add>
<add>- [#17115](https://github.com/emberjs/ember.js/pull/17115) [BUGFIX] Ensure `{{input` continues to pass the event to the actions that it fires.
<add>- [#17128](https://github.com/emberjs/ember.js/pull/17128) [BUGFIX] Fix invalid sourcemap declarations.
<add>- [#17130](https://github.com/emberjs/ember.js/pull/17130) [BUGFIX] Ensure that timers scheduled after a system sleep are fired properly.
<add>
<ide> ### v3.4.5 (October 4, 2018)
<ide>
<ide> - [#17029](https://github.com/emberjs/ember.js/pull/17029) [BUGFIX] Update backburner.js to 2.4.0. | 1 |
Text | Text | update changelog with reverts | b5725434c6b01f5e25841d0d5165fd5b68187dca | <ide><path>CHANGELOG.md
<ide> be found.
<ide>
<ide> - Fix Docker client exiting with an "Unrecognized input header" error [#20706](https://github.com/docker/docker/pull/20706)
<ide> - Fix Docker exiting if Exec is started with both `AttachStdin` and `Detach` [#20647](https://github.com/docker/docker/pull/20647)
<del>- Fix loss of output in short-lived containers [#20729](https://github.com/docker/docker/pull/20729)
<del>- Fix an issue that caused the client to hang if the container process died [#20967](https://github.com/docker/docker/pull/20967)
<ide>
<ide> ### Distribution
<ide> | 1 |
Python | Python | adjust error message | 8ac5f222531dcb602d08118693618598bc0c045d | <ide><path>spacy/errors.py
<ide> class Errors:
<ide> "issue tracker: http://github.com/explosion/spaCy/issues")
<ide>
<ide> # TODO: fix numbering after merging develop into master
<del> E900 = ("Could not run the full 'nlp' pipeline for evaluation. If you specified "
<del> "frozen components, make sure they were already initialized and trained. ")
<add> E900 = ("Could not run the full pipeline for evaluation. If you specified "
<add> "frozen components, make sure they were already initialized and "
<add> "trained. Full pipeline: {pipeline}")
<ide> E901 = ("Failed to remove existing output directory: {path}. If your "
<ide> "config and the components you train change between runs, a "
<ide> "non-empty output directory can lead to stale pipeline data. To "
<ide><path>spacy/training/loop.py
<ide> def evaluate() -> Tuple[float, Dict[str, float]]:
<ide> try:
<ide> scores = nlp.evaluate(dev_examples)
<ide> except KeyError as e:
<del> raise KeyError(Errors.E900) from e
<add> raise KeyError(Errors.E900.format(pipeline=nlp.pipe_names)) from e
<ide> # Calculate a weighted sum based on score_weights for the main score.
<ide> # We can only consider scores that are ints/floats, not dicts like
<ide> # entity scores per type etc. | 2 |
Javascript | Javascript | use a plain object for the the error stack | 70b31adffabf0e7fb57c06e02b4f75bf1a212f5e | <ide><path>lib/console.js
<ide> Console.prototype.timeEnd = function timeEnd(label) {
<ide>
<ide>
<ide> Console.prototype.trace = function trace(...args) {
<del> // TODO probably can to do this better with V8's debug object once that is
<del> // exposed.
<del> var err = new Error();
<del> err.name = 'Trace';
<del> err.message = util.format.apply(null, args);
<add> const err = {
<add> name: 'Trace',
<add> message: util.format.apply(null, args)
<add> };
<ide> Error.captureStackTrace(err, trace);
<ide> this.error(err.stack);
<ide> }; | 1 |
PHP | PHP | add server and baseapplication | 91234f42b03054136d05dee14fa2427fb7cd4b34 | <ide><path>src/Http/BaseApplication.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 3.3.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Http;
<add>
<add>use Psr\Http\Message\ResponseInterface;
<add>use Psr\Http\Message\ServerRequestInterface;
<add>
<add>/**
<add> * Base class for application classes.
<add> *
<add> * The application class is responsible for bootstrapping the application,
<add> * and ensuring that middleware is attached. It is also invoked as the last piece
<add> * of middleware, and delegates request/response handling to the correct controller.
<add> */
<add>abstract class BaseApplication
<add>{
<add>
<add> /**
<add> * @var string Contains the path of the config directory
<add> */
<add> protected $configDir;
<add>
<add> /**
<add> * Constructor
<add> *
<add> * @param string $configDir The directory the bootstrap configuration is held in.
<add> */
<add> public function __construct($configDir)
<add> {
<add> $this->configDir = $configDir;
<add> }
<add>
<add> /**
<add> * @param \Cake\Http\MiddlewareStack $middleware The middleware stack to set in your App Class
<add> * @return \Cake\Http\MiddlewareStack
<add> */
<add> abstract public function middleware($middleware);
<add>
<add> /**
<add> * Load all the application configuration and bootstrap logic.
<add> *
<add> * @return void
<add> */
<add> public function bootstrap()
<add> {
<add> // Load traditional bootstrap file..
<add> require_once $this->configDir . '/bootstrap.php';
<add>
<add> // Load other config files your application needs.
<add> }
<add>
<add> /**
<add> * Invoke the application.
<add> *
<add> * - Convert the PSR request/response into CakePHP equivalents.
<add> * - Create the controller that will handle this request.
<add> * - Invoke the controller.
<add> *
<add> * @param \Psr\Http\Message\ServerRequestInterface $request The request
<add> * @param \Psr\Http\Message\ResponseInterface $response The response
<add> * @param callable $next The next middleware
<add> * @return \Psr\Http\Message\ResponseInterface
<add> */
<add> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
<add> {
<add> // Convert the request/response to CakePHP equivalents.
<add> $cakeRequest = RequestTransformer::toCake($request);
<add> $cakeResponse = ResponseTransformer::toCake($response);
<add>
<add> // Dispatch the request/response to CakePHP
<add> $cakeResponse = $this->getDispatcher()->dispatch($cakeRequest, $cakeResponse);
<add>
<add> // Convert the response back into a PSR7 object.
<add> return $next($request, ResponseTransformer::toPsr($cakeResponse));
<add> }
<add>
<add> /**
<add> * Get the ActionDispatcher.
<add> *
<add> * @return \Spekkoek\ActionDispatcher
<add> */
<add> protected function getDispatcher()
<add> {
<add> return new ActionDispatcher();
<add> }
<add>}
<ide><path>src/Http/Server.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 3.3.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Http;
<add>
<add>use Cake\Event\EventDispatcherTrait;
<add>use Psr\Http\Message\ResponseInterface;
<add>use Psr\Http\Message\ServerRequestInterface;
<add>use RuntimeException;
<add>use Zend\Diactoros\Response;
<add>use Zend\Diactoros\Response\EmitterInterface;
<add>use Zend\Diactoros\Response\SapiStreamEmitter;
<add>
<add>/**
<add> * Runs an application invoking all the PSR7 middleware and the registered application.
<add> */
<add>class Server
<add>{
<add>
<add> use EventDispatcherTrait;
<add>
<add> /**
<add> * @var \Cake\Http\BaseApplication
<add> */
<add> protected $app;
<add>
<add> /**
<add> * @var \Cake\Http\Runner
<add> */
<add> protected $runner;
<add>
<add> /**
<add> * Constructor
<add> *
<add> * @param \Cake\Http\BaseApplication $app The application to use.
<add> */
<add> public function __construct(BaseApplication $app)
<add> {
<add> $this->setApp($app);
<add> $this->setRunner(new Runner());
<add> }
<add>
<add> /**
<add> * Run the request/response through the Application and its middleware.
<add> *
<add> * This will invoke the following methods:
<add> *
<add> * - App->bootstrap() - Perform any bootstrapping logic for your application here.
<add> * - App->middleware() - Attach any application middleware here.
<add> * - Trigger the 'Server.buildMiddleware' event. You can use this to modify the
<add> * from event listeners.
<add> * - Run the middleware stack including the application.
<add> *
<add> * @param \Psr\Http\Message\ServerRequestInterface $request The request to use or null.
<add> * @param \Psr\Http\Message\ResponseInterface $response The response to use or null.
<add> * @return \Psr\Http\Message\ResponseInterface
<add> * @throws \RuntimeException When the application does not make a response.
<add> */
<add> public function run(ServerRequestInterface $request = null, ResponseInterface $response = null)
<add> {
<add> $this->app->bootstrap();
<add> $request = $request ?: ServerRequestFactory::fromGlobals();
<add> $response = $response ?: new Response();
<add>
<add> $middleware = $this->app->middleware(new MiddlewareStack());
<add> if (!($middleware instanceof MiddlewareStack)) {
<add> throw new RuntimeException('The application `middleware` method did not return a middleware stack.');
<add> }
<add> $middleware->push($this->app);
<add> $this->dispatchEvent('Server.buildMiddleware', ['middleware' => $middleware]);
<add> $response = $this->runner->run($middleware, $request, $response);
<add>
<add> if (!($response instanceof ResponseInterface)) {
<add> throw new RuntimeException(sprintf(
<add> 'Application did not create a response. Got "%s" instead.',
<add> is_object($response) ? get_class($response) : $response
<add> ));
<add> }
<add> return $response;
<add> }
<add>
<add> /**
<add> * Emit the response using the PHP SAPI.
<add> *
<add> * @param \Psr\Http\Message\ResponseInterface $response The response to emit
<add> * @param \Zend\Diactoros\Response\EmitterInterface $emitter The emitter to use.
<add> * When null, a SAPI Stream Emitter will be used.
<add> * @return void
<add> */
<add> public function emit(ResponseInterface $response, EmitterInterface $emitter = null)
<add> {
<add> if (!$emitter) {
<add> $emitter = new SapiStreamEmitter();
<add> }
<add> $emitter->emit($response);
<add> }
<add>
<add> /**
<add> * Set the application.
<add> *
<add> * @param BaseApplication $app The application to set.
<add> * @return $this
<add> */
<add> public function setApp(BaseApplication $app)
<add> {
<add> $this->app = $app;
<add> return $this;
<add> }
<add>
<add> /**
<add> * Get the current application.
<add> *
<add> * @return BaseApplication The application that will be run.
<add> */
<add> public function getApp()
<add> {
<add> return $this->app;
<add> }
<add>
<add> /**
<add> * Set the runner
<add> *
<add> * @param \Cake\Http\Runner $runner The runner to use.
<add> * @return $this
<add> */
<add> public function setRunner(Runner $runner)
<add> {
<add> $this->runner = $runner;
<add> return $this;
<add> }
<add>}
<ide><path>tests/TestCase/Http/BaseApplicationTest.php
<add><?php
<add>namespace Cake\Test\TestCase;
<add>
<add>use Cake\Core\Configure;
<add>use Cake\Http\BaseApplication;
<add>use Cake\Http\ServerRequestFactory;
<add>use Cake\TestSuite\TestCase;
<add>use Zend\Diactoros\Response;
<add>
<add>/**
<add> * Base application test.
<add> */
<add>class BaseApplicationTest extends TestCase
<add>{
<add> /**
<add> * Setup
<add> *
<add> * @return void
<add> */
<add> public function setUp()
<add> {
<add> parent::setUp();
<add> Configure::write('App.namespace', 'TestApp');
<add> }
<add>
<add> /**
<add> * Integration test for a simple controller.
<add> *
<add> * @return void
<add> */
<add> public function testInvoke()
<add> {
<add> $next = function ($req, $res) {
<add> return $res;
<add> };
<add> $response = new Response();
<add> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/cakes']);
<add> $request = $request->withAttribute('params', [
<add> 'controller' => 'Cakes',
<add> 'action' => 'index',
<add> 'plugin' => null,
<add> 'pass' => []
<add> ]);
<add>
<add> $path = dirname(dirname(__DIR__));
<add> $app = $this->getMockForAbstractClass('Cake\Http\BaseApplication', [$path]);
<add> $result = $app($request, $response, $next);
<add> $this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $result);
<add> $this->assertEquals('Hello Jane', '' . $result->getBody());
<add> }
<add>}
<ide><path>tests/TestCase/Http/ServerTest.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 3.3.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Test\TestCase;
<add>
<add>use Cake\Http\Server;
<add>use Cake\TestSuite\TestCase;
<add>use TestApp\Http\BadResponseApplication;
<add>use TestApp\Http\InvalidMiddlewareApplication;
<add>use TestApp\Http\MiddlewareApplication;
<add>use Zend\Diactoros\Response;
<add>use Zend\Diactoros\ServerRequestFactory;
<add>
<add>/**
<add> * Server test case
<add> */
<add>class ServerTest extends TestCase
<add>{
<add> /**
<add> * Setup
<add> *
<add> * @return void
<add> */
<add> public function setUp()
<add> {
<add> parent::setUp();
<add> $this->server = $_SERVER;
<add> $this->config = dirname(dirname(__DIR__));
<add> }
<add>
<add> /**
<add> * Teardown
<add> *
<add> * @return void
<add> */
<add> public function tearDown()
<add> {
<add> parent::tearDown();
<add> $_SERVER = $this->server;
<add> }
<add>
<add> /**
<add> * test get/set on the app
<add> *
<add> * @return void
<add> */
<add> public function testAppGetSet()
<add> {
<add> $app = $this->getMock('Cake\Http\BaseApplication', [], [$this->config]);
<add> $server = new Server($app);
<add> $this->assertSame($app, $server->getApp($app));
<add> }
<add>
<add> /**
<add> * test run building a response
<add> *
<add> * @return void
<add> */
<add> public function testRunWithRequestAndResponse()
<add> {
<add> $response = new Response('php://memory', 200, ['X-testing' => 'source header']);
<add> $request = ServerRequestFactory::fromGlobals();
<add> $request = $request->withHeader('X-pass', 'request header');
<add>
<add> $app = new MiddlewareApplication($this->config);
<add> $server = new Server($app);
<add> $res = $server->run($request, $response);
<add> $this->assertEquals(
<add> 'source header',
<add> $res->getHeaderLine('X-testing'),
<add> 'Input response is carried through out middleware'
<add> );
<add> $this->assertEquals(
<add> 'request header',
<add> $res->getHeaderLine('X-pass'),
<add> 'Request is used in middleware'
<add> );
<add> }
<add>
<add> /**
<add> * test run building a request from globals.
<add> *
<add> * @return void
<add> */
<add> public function testRunWithGlobals()
<add> {
<add> $_SERVER['HTTP_X_PASS'] = 'globalvalue';
<add>
<add> $app = new MiddlewareApplication($this->config);
<add> $server = new Server($app);
<add>
<add> $res = $server->run();
<add> $this->assertEquals(
<add> 'globalvalue',
<add> $res->getHeaderLine('X-pass'),
<add> 'Default request is made from server'
<add> );
<add> }
<add>
<add> /**
<add> * Test an application failing to build middleware properly
<add> *
<add> * @expectedException RuntimeException
<add> * @expectedExceptionMessage The application `middleware` method
<add> */
<add> public function testRunWithApplicationNotMakingMiddleware()
<add> {
<add> $app = new InvalidMiddlewareApplication($this->config);
<add> $server = new Server($app);
<add> $server->run();
<add> }
<add>
<add> /**
<add> * Test middleware being invoked.
<add> *
<add> * @return void
<add> */
<add> public function testRunMultipleMiddlewareSuccess()
<add> {
<add> $app = new MiddlewareApplication($this->config);
<add> $server = new Server($app);
<add> $res = $server->run();
<add> $this->assertSame('first', $res->getHeaderLine('X-First'));
<add> $this->assertSame('second', $res->getHeaderLine('X-Second'));
<add> }
<add>
<add> /**
<add> * Test middleware not creating a response.
<add> *
<add> * @expectedException RuntimeException
<add> * @expectedExceptionMessage Application did not create a response. Got "Not a response" instead.
<add> */
<add> public function testRunMiddlewareNoResponse()
<add> {
<add> $app = new BadResponseApplication($this->config);
<add> $server = new Server($app);
<add> $server->run();
<add> }
<add>
<add> /**
<add> * Test that emit invokes the appropriate methods on the emitter.
<add> *
<add> * @return void
<add> */
<add> public function testEmit()
<add> {
<add> $response = new Response('php://memory', 200, ['x-testing' => 'source header']);
<add> $final = $response
<add> ->withHeader('X-First', 'first')
<add> ->withHeader('X-Second', 'second');
<add>
<add> $emitter = $this->getMock('Zend\Diactoros\Response\EmitterInterface');
<add> $emitter->expects($this->once())
<add> ->method('emit')
<add> ->with($final);
<add>
<add> $app = new MiddlewareApplication($this->config);
<add> $server = new Server($app);
<add> $server->emit($server->run(null, $response), $emitter);
<add> }
<add>
<add> /**
<add> * Ensure that the Server.buildMiddleware event is fired.
<add> *
<add> * @return void
<add> */
<add> public function testBuildMiddlewareEvent()
<add> {
<add> $app = new MiddlewareApplication($this->config);
<add> $server = new Server($app);
<add> $called = false;
<add> $server->eventManager()->on('Server.buildMiddleware', function ($event, $middleware) use (&$called) {
<add> $called = true;
<add> $this->assertInstanceOf('Cake\Http\MiddlewareStack', $middleware);
<add> });
<add> $server->run();
<add> $this->assertTrue($called, 'Event not triggered.');
<add> }
<add>}
<ide><path>tests/test_app/TestApp/Http/BadResponseApplication.php
<add><?php
<add>namespace TestApp\Http;
<add>
<add>use Cake\Http\BaseApplication;
<add>use Psr\Http\Message\ResponseInterface;
<add>use Psr\Http\Message\ServerRequestInterface;
<add>
<add>class BadResponseApplication extends BaseApplication
<add>{
<add> /**
<add> * @param \Cake\Http\MiddlewareStack $middleware The middleware stack to set in your App Class
<add> * @return \Cake\Http\MiddlewareStack
<add> */
<add> public function middleware($middleware)
<add> {
<add> $middleware->push(function ($req, $res, $next) {
<add> return 'Not a response';
<add> });
<add> return $middleware;
<add> }
<add>
<add> /**
<add> * @param \Psr\Http\Message\ServerRequestInterface $request The request
<add> * @param \Psr\Http\Message\ResponseInterface $request The response
<add> * @param callable $next The next middleware
<add> * @return \Psr\Http\Message\ResponseInterface
<add> */
<add> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
<add> {
<add> return $res;
<add> }
<add>}
<ide><path>tests/test_app/TestApp/Http/InvalidMiddlewareApplication.php
<add><?php
<add>namespace TestApp\Http;
<add>
<add>use Cake\Http\BaseApplication;
<add>
<add>class InvalidMiddlewareApplication extends BaseApplication
<add>{
<add> /**
<add> * @param \Cake\Http\MiddlewareStack $middleware The middleware stack to set in your App Class
<add> * @return null
<add> */
<add> public function middleware($middleware)
<add> {
<add> return null;
<add> }
<add>}
<ide><path>tests/test_app/TestApp/Http/MiddlewareApplication.php
<add><?php
<add>namespace TestApp\Http;
<add>
<add>use Cake\Http\BaseApplication;
<add>use Psr\Http\Message\ResponseInterface;
<add>use Psr\Http\Message\ServerRequestInterface;
<add>
<add>class MiddlewareApplication extends BaseApplication
<add>{
<add> /**
<add> * @param \Cake\Http\MiddlewareStack $middleware The middleware stack to set in your App Class
<add> * @return \Cake\Http\MiddlewareStack
<add> */
<add> public function middleware($middleware)
<add> {
<add> $middleware
<add> ->push(function ($req, $res, $next) {
<add> $res = $res->withHeader('X-First', 'first');
<add> return $next($req, $res);
<add> })
<add> ->push(function ($req, $res, $next) {
<add> $res = $res->withHeader('X-Second', 'second');
<add> return $next($req, $res);
<add> })
<add> ->push(function ($req, $res, $next) {
<add> if ($req->hasHeader('X-pass')) {
<add> $res = $res->withHeader('X-pass', $req->getHeaderLine('X-pass'));
<add> }
<add> $res = $res->withHeader('X-Second', 'second');
<add> return $next($req, $res);
<add> });
<add> return $middleware;
<add> }
<add>
<add> /**
<add> * @param \Psr\Http\Message\ServerRequestInterface $request The request
<add> * @param \Psr\Http\Message\ResponseInterface $request The response
<add> * @param callable $next The next middleware
<add> * @return \Psr\Http\Message\ResponseInterface
<add> */
<add> public function __invoke(ServerRequestInterface $req, ResponseInterface $res, $next)
<add> {
<add> return $res;
<add> }
<add>} | 7 |
Ruby | Ruby | add missing require | fa132efe8232ad374f30532c9ed25f7414f89483 | <ide><path>activerecord/test/cases/associations/inverse_associations_test.rb
<ide> require "models/author"
<ide> require "models/post"
<ide> require "models/department"
<add>require "models/hotel"
<ide>
<ide> class AutomaticInverseFindingTests < ActiveRecord::TestCase
<ide> fixtures :ratings, :comments, :cars | 1 |
Ruby | Ruby | update doc (closes ) | b7aa22355413e4c160dbbe280006022bb193cce5 | <ide><path>actionpack/lib/action_view/helpers/capture_helper.rb
<ide> def capture(*args, &block)
<ide> # for elements that will be fragment cached.
<ide> #
<ide> # The deprecated way of accessing a content_for block is to use an instance variable
<del> # named <tt>@content_for_#{name_of_the_content_block}</tt>. So <tt><%= content_for :footer %></tt>
<del> # would be available as <tt><%= @content_for_footer %></tt>. The preferred usage is now
<add> # named <tt>@content_for_#{name_of_the_content_block}</tt>. The preferred usage is now
<ide> # <tt><%= yield :footer %></tt>.
<ide> def content_for(name, content = nil, &block)
<ide> existing_content_for = instance_variable_get("@content_for_#{name}").to_s | 1 |
Python | Python | replace assertion with valueerror exception | a5be95413f99ada138f9d396eb4bd6a7216f640a | <ide><path>src/transformers/generation_flax_logits_process.py
<ide> def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int, **
<ide> for processor in self:
<ide> function_args = inspect.signature(processor.__call__).parameters
<ide> if len(function_args) > 3:
<del> assert all(
<del> arg in kwargs for arg in list(function_args.keys())[2:]
<del> ), f"Make sure that all the required parameters: {list(function_args.keys())} for {processor.__class__} are passed to the logits processor."
<add> if not all(arg in kwargs for arg in list(function_args.keys())[2:]):
<add> raise ValueError(
<add> f"Make sure that all the required parameters: {list(function_args.keys())} for "
<add> f"{processor.__class__} are passed to the logits processor."
<add> )
<ide> scores = processor(input_ids, scores, cur_len, **kwargs)
<ide> else:
<ide> scores = processor(input_ids, scores, cur_len) | 1 |
Javascript | Javascript | add buffergeometry de-duplication to gltf parser | b3c37c589fc81781babc4d576ff512de5b97c8f8 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<add> function isPrimitiveEqual ( a, b ) {
<add>
<add> if ( a.indices !== b.indices ) {
<add>
<add> return false;
<add>
<add> }
<add>
<add> var attribA = a.attributes || {};
<add> var attribB = b.attributes || {};
<add> var keysA = Object.keys(attribA);
<add> var keysB = Object.keys(attribB);
<add> var i;
<add>
<add> for ( i = 0; i < keysA.length; i++ ) {
<add>
<add> var key = keysA[i];
<add>
<add> if ( attribA[key] !== attribB[key] ) {
<add>
<add> return false;
<add>
<add> }
<add> }
<add>
<add> for ( i = 0; i < keysB.length; i++ ) {
<add>
<add> var key = keysB[i];
<add>
<add> if ( attribA[key] !== attribB[key] ) {
<add>
<add> return false;
<add>
<add> }
<add> }
<add>
<add> return true;
<add> }
<add>
<add> function getCachedGeometry ( cache, newPrimitive ) {
<add>
<add> for ( var i = 0; i < cache.length; i++ ) {
<add> var cached = cache[i];
<add>
<add> if ( isPrimitiveEqual( cached.primitive, newPrimitive ) ) {
<add>
<add> return cached.geometry;
<add>
<add> }
<add> }
<add>
<add> return null;
<add> }
<add>
<ide> /* GLTF PARSER */
<ide>
<ide> function GLTFParser( json, extensions, options ) {
<ide> THREE.GLTFLoader = ( function () {
<ide> // loader object cache
<ide> this.cache = new GLTFRegistry();
<ide>
<add> // BufferGeometry caching
<add> this.primitiveCache = [];
<add>
<ide> this.textureLoader = new THREE.TextureLoader( this.options.manager );
<ide> this.textureLoader.setCrossOrigin( this.options.crossOrigin );
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> GLTFParser.prototype.loadGeometries = function ( primitives ) {
<ide>
<add> var cache = this.primitiveCache;
<add>
<ide> return this._withDependencies( [
<ide>
<ide> 'accessors',
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> return _each( primitives, function ( primitive ) {
<ide>
<add> // See if we've already created this geometry
<add> var cached = getCachedGeometry( cache, primitive );
<add>
<add> if (cached) {
<add>
<add> return cached;
<add>
<add> }
<add>
<ide> var geometry = new THREE.BufferGeometry();
<ide>
<ide> var attributes = primitive.attributes;
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<add> // Cache this geometry
<add> cache.push( {
<add>
<add> primitive: primitive,
<add> geometry: geometry
<add>
<add> } );
<add>
<ide> return geometry;
<ide>
<ide> } ); | 1 |
Javascript | Javascript | use await correctly | 9d44771895e25704be5841b32103927edf6eea43 | <ide><path>scripts/publish-native.js
<ide> const cwd = process.cwd()
<ide>
<ide> // Copy binaries to package folders, update version, and publish
<ide> let nativePackagesDir = path.join(cwd, 'packages/next/build/swc/npm')
<del> let platforms = await readdir(nativePackagesDir).filter(
<add> let platforms = (await readdir(nativePackagesDir)).filter(
<ide> (name) => name !== '.gitignore'
<ide> )
<ide> for (let platform of platforms) { | 1 |
Javascript | Javascript | add intersection to enumerable utils | f3789b7acdd9c025c33b0519304036ebc11769ef | <ide><path>packages/ember-metal/lib/array.js
<ide> /*jshint newcap:false*/
<add>require('ember-metal/enumerable_utils');
<ide>
<ide> /**
<ide> @module ember-metal
<ide> Ember.ArrayPolyfills = {
<ide> indexOf: arrayIndexOf
<ide> };
<ide>
<del>var utils = Ember.EnumerableUtils = {
<del> map: function(obj, callback, thisArg) {
<del> return obj.map ? obj.map.call(obj, callback, thisArg) : arrayMap.call(obj, callback, thisArg);
<del> },
<del>
<del> forEach: function(obj, callback, thisArg) {
<del> return obj.forEach ? obj.forEach.call(obj, callback, thisArg) : arrayForEach.call(obj, callback, thisArg);
<del> },
<del>
<del> indexOf: function(obj, element, index) {
<del> return obj.indexOf ? obj.indexOf.call(obj, element, index) : arrayIndexOf.call(obj, element, index);
<del> },
<del>
<del> indexesOf: function(obj, elements) {
<del> return elements === undefined ? [] : utils.map(elements, function(item) {
<del> return utils.indexOf(obj, item);
<del> });
<del> },
<del>
<del> addObject: function(array, item) {
<del> var index = utils.indexOf(array, item);
<del> if (index === -1) { array.push(item); }
<del> },
<del>
<del> removeObject: function(array, item) {
<del> var index = utils.indexOf(array, item);
<del> if (index !== -1) { array.splice(index, 1); }
<del> },
<del>
<del> replace: function(array, idx, amt, objects) {
<del> if (array.replace) {
<del> return array.replace(idx, amt, objects);
<del> } else {
<del> var args = Array.prototype.concat.apply([idx, amt], objects);
<del> return array.splice.apply(array, args);
<del> }
<del> }
<del>};
<del>
<del>
<ide> if (Ember.SHIM_ES5) {
<ide> if (!Array.prototype.map) {
<ide> Array.prototype.map = arrayMap;
<ide><path>packages/ember-metal/lib/enumerable_utils.js
<add>var utils = Ember.EnumerableUtils = {
<add> map: function(obj, callback, thisArg) {
<add> return obj.map ? obj.map.call(obj, callback, thisArg) : Array.prototype.map.call(obj, callback, thisArg);
<add> },
<add>
<add> forEach: function(obj, callback, thisArg) {
<add> return obj.forEach ? obj.forEach.call(obj, callback, thisArg) : Array.prototype.forEach.call(obj, callback, thisArg);
<add> },
<add>
<add> indexOf: function(obj, element, index) {
<add> return obj.indexOf ? obj.indexOf.call(obj, element, index) : Array.prototype.indexOf.call(obj, element, index);
<add> },
<add>
<add> indexesOf: function(obj, elements) {
<add> return elements === undefined ? [] : utils.map(elements, function(item) {
<add> return utils.indexOf(obj, item);
<add> });
<add> },
<add>
<add> addObject: function(array, item) {
<add> var index = utils.indexOf(array, item);
<add> if (index === -1) { array.push(item); }
<add> },
<add>
<add> removeObject: function(array, item) {
<add> var index = utils.indexOf(array, item);
<add> if (index !== -1) { array.splice(index, 1); }
<add> },
<add>
<add> replace: function(array, idx, amt, objects) {
<add> if (array.replace) {
<add> return array.replace(idx, amt, objects);
<add> } else {
<add> var args = Array.prototype.concat.apply([idx, amt], objects);
<add> return array.splice.apply(array, args);
<add> }
<add> },
<add>
<add> intersection: function(array1, array2) {
<add> var intersection = [];
<add>
<add> array1.forEach(function(element) {
<add> if (array2.indexOf(element) >= 0) {
<add> intersection.push(element);
<add> }
<add> });
<add>
<add> return intersection;
<add> }
<add>};
<ide><path>packages/ember-metal/tests/enumerable_utils_test.js
<add>module('Ember.EnumerableUtils.intersection');
<add>
<add>test('returns an array of objects that appear in both enumerables', function() {
<add> var a = [1,2,3], b = [2,3,4], result;
<add>
<add> result = Ember.EnumerableUtils.intersection(a, b);
<add>
<add> deepEqual(result, [2,3]);
<add>}); | 3 |
PHP | PHP | fix misspelling in mailer contract | c066baf94e8c28d0c4dc5728c2381ab5a3758d39 | <ide><path>src/Illuminate/Contracts/Mail/Mailer.php
<ide> public function to($users);
<ide> public function bcc($users);
<ide>
<ide> /**
<del> * Send a new message when only a raw text part.
<add> * Send a new message with only a raw text part.
<ide> *
<ide> * @param string $text
<ide> * @param mixed $callback | 1 |
Go | Go | fix the events, pull test to use v2 local server | be5de5bcb8d39515e374219aa95bd2ac855d6918 | <ide><path>integration-cli/docker_cli_events_test.go
<ide> func TestEventsImageUntagDelete(t *testing.T) {
<ide>
<ide> func TestEventsImagePull(t *testing.T) {
<ide> since := daemonTime(t).Unix()
<add> testRequires(t, Network)
<ide>
<ide> defer deleteImages("hello-world")
<ide> | 1 |
Javascript | Javascript | use common.mustnotcall in test-crypto-random | 112ef23bba80c947799f3cc85c407543acb6c703 | <ide><path>test/parallel/test-crypto-random.js
<ide> const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/;
<ide> [crypto.randomBytes, crypto.pseudoRandomBytes].forEach(function(f) {
<ide> [-1, undefined, null, false, true, {}, []].forEach(function(value) {
<ide> assert.throws(function() { f(value); }, expectedErrorRegexp);
<del> assert.throws(function() { f(value, common.noop); }, expectedErrorRegexp);
<add> assert.throws(function() { f(value, common.mustNotCall()); },
<add> expectedErrorRegexp);
<ide> });
<ide>
<ide> [0, 1, 2, 4, 16, 256, 1024].forEach(function(len) {
<ide> const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/;
<ide> }, /offset must be a number/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, 'test', common.noop);
<add> crypto.randomFill(buf, 'test', common.mustNotCall());
<ide> }, /offset must be a number/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, NaN, common.noop);
<add> crypto.randomFill(buf, NaN, common.mustNotCall());
<ide> }, /offset must be a number/);
<ide>
<ide> const max = require('buffer').kMaxLength + 1;
<ide> const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/;
<ide> }, /offset out of range/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, 11, common.noop);
<add> crypto.randomFill(buf, 11, common.mustNotCall());
<ide> }, /offset out of range/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, max, common.noop);
<add> crypto.randomFill(buf, max, common.mustNotCall());
<ide> }, /offset out of range/);
<ide>
<ide> assert.throws(() => {
<ide> const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/;
<ide> }, /size must be a number/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, 0, 'test', common.noop);
<add> crypto.randomFill(buf, 0, 'test', common.mustNotCall());
<ide> }, /size must be a number/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, 0, NaN, common.noop);
<add> crypto.randomFill(buf, 0, NaN, common.mustNotCall());
<ide> }, /size must be a number/);
<ide>
<ide> {
<ide> const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/;
<ide> }, /size must be a uint32/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, 0, -10, common.noop);
<add> crypto.randomFill(buf, 0, -10, common.mustNotCall());
<ide> }, /size must be a uint32/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, 0, size, common.noop);
<add> crypto.randomFill(buf, 0, size, common.mustNotCall());
<ide> }, /size must be a uint32/);
<ide> }
<ide>
<ide> const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/;
<ide> }, /offset must be a uint32/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, -10, common.noop);
<add> crypto.randomFill(buf, -10, common.mustNotCall());
<ide> }, /offset must be a uint32/);
<ide>
<ide> assert.throws(() => {
<ide> crypto.randomFillSync(buf, 1, 10);
<ide> }, /buffer too small/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, 1, 10, common.noop);
<add> crypto.randomFill(buf, 1, 10, common.mustNotCall());
<ide> }, /buffer too small/);
<ide>
<ide> assert.throws(() => {
<ide> crypto.randomFillSync(buf, 0, 12);
<ide> }, /buffer too small/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, 0, 12, common.noop);
<add> crypto.randomFill(buf, 0, 12, common.mustNotCall());
<ide> }, /buffer too small/);
<ide>
<ide> {
<ide> const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/;
<ide> }, /offset must be a uint32/);
<ide>
<ide> assert.throws(() => {
<del> crypto.randomFill(buf, offset, 10, common.noop);
<add> crypto.randomFill(buf, offset, 10, common.mustNotCall());
<ide> }, /offset must be a uint32/);
<ide> }
<ide> } | 1 |
Ruby | Ruby | fix failing asset test | dbe28f3cb0c3957b2fb5847b2b205a5359481924 | <ide><path>railties/test/application/assets_test.rb
<ide> def precompile!
<ide> app_file "app/assets/javascripts/app.js", "alert();"
<ide>
<ide> require "#{app_path}/config/environment"
<del> class ::PostsController < ActionController::Base ; end
<add> class ::PostsController < ActionController::Base
<add> def show_detailed_exceptions?() true end
<add> end
<ide>
<ide> get '/posts'
<ide> assert_match(/AssetNotPrecompiledError/, last_response.body) | 1 |
Javascript | Javascript | add usecreateindex to mongoose connection options | cf916f99061b3e72604bc4937a86a9c6b6274f35 | <ide><path>examples/with-mongodb-mongoose/utils/dbConnect.js
<ide> async function dbConnect() {
<ide> useNewUrlParser: true,
<ide> useUnifiedTopology: true,
<ide> useFindAndModify: false,
<add> useCreateIndex: true,
<ide> })
<ide> }
<ide> | 1 |
Javascript | Javascript | add broken test for | 74c02066fe0e963722b0d7d5a78c703fd14c0275 | <ide><path>test/simple/test-regress-GH-1726.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// 'Software'), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>// Open a chain of five Node processes each a child of the next. The final
<add>// process exits immediately. Each process in the chain is instructed to
<add>// exit when its child exits.
<add>// https://github.com/joyent/node/issues/1726
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var ch = require('child_process');
<add>
<add>var gen = +(process.argv[2] || 0);
<add>var maxGen = 5;
<add>
<add>
<add>if (gen === maxGen) {
<add> console.error('hit maxGen, exiting', maxGen);
<add> return;
<add>}
<add>
<add>var child = ch.spawn(process.execPath, [__filename, gen + 1], {
<add> customFds: [ 0, -1, 2]
<add>});
<add>assert.ok(!child.stdin);
<add>assert.ok(child.stdout);
<add>assert.ok(!child.stderr);
<add>
<add>console.error('gen=%d, pid=%d', gen, process.pid);
<add>
<add>/*
<add>var timer = setTimeout(function () {
<add> throw new Error('timeout! gen='+gen);
<add>}, 1000);
<add>*/
<add>
<add>child.on('exit', function (code) {
<add> console.error('exit %d from gen %d', code, gen + 1);
<add> //clearTimeout(timer);
<add>});
<add>
<add>child.stdout.pipe(process.stdout);
<add>
<add>child.stdout.on("close", function() {
<add> console.error("child.stdout close gen=%d", gen);
<add>}); | 1 |
PHP | PHP | fix bug in eloquent model update routine | eb8f512c44f8060a2f3043e6fcd6e7d1a5177c59 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function save()
<ide> */
<ide> protected function performUpdate($query)
<ide> {
<del> // If the updating event returns false, we will cancel the update operation so
<del> // developers can hook Validation systems into their models and cancel this
<del> // operation if the model does not pass validation. Otherwise, we update.
<del> if ($this->fireModelEvent('updating') === false)
<add> $dirty = $this->getDirty();
<add>
<add> if (count($dirty) > 0)
<ide> {
<del> return false;
<del> }
<add> // If the updating event returns false, we will cancel the update operation so
<add> // developers can hook Validation systems into their models and cancel this
<add> // operation if the model does not pass validation. Otherwise, we update.
<add> if ($this->fireModelEvent('updating') === false)
<add> {
<add> return false;
<add> }
<ide>
<del> $dirty = $this->getDirty();
<add> $dirty = $this->getDirty();
<ide>
<del> $this->setKeysForSaveQuery($query)->update($dirty);
<add> // Once we have run the update operation, we will fire the "updated" event for
<add> // this model instance. This will allow developers to hook into these after
<add> // models are updated, giving them a chance to do any special processing.
<add> $this->setKeysForSaveQuery($query)->update($dirty);
<ide>
<del> // Once we have run the update operation, we will fire the "updated" event for
<del> // this model instance. This will allow developers to hook into these after
<del> // models are updated, giving them a chance to do any special processing.
<del> $this->fireModelEvent('updated', false);
<add> $this->fireModelEvent('updated', false);
<add> }
<ide>
<ide> return true;
<ide> }
<ide><path>src/Illuminate/Workbench/Starter.php
<ide> public static function start($path, $finder = null, $files = null)
<ide> {
<ide> $finder = $finder ?: new \Symfony\Component\Finder\Finder;
<ide>
<del> $files = $files ?: new \Illuminate\Filesystem\Filesystem;
<del>
<ide> // We will use the finder to locate all "autoload.php" files in the workbench
<ide> // directory, then we will include them each so that they are able to load
<ide> // the appropriate classes and file used by the given workbench package.
<add> $files = $files ?: new \Illuminate\Filesystem\Filesystem;
<add>
<ide> $autoloads = $finder->in($path)->files()->name('autoload.php');
<ide>
<ide> foreach ($autoloads as $file)
<ide> public static function start($path, $finder = null, $files = null)
<ide> }
<ide> }
<ide>
<del>}
<add>} | 2 |
Javascript | Javascript | remove extraneous parentheses from `new` operator | 3941be193a3391ab90272738bc17337c0cf5f58e | <ide><path>d3.js
<ide> (function(){d3 = {version: "1.17.0"}; // semver
<ide> if (!Date.now) Date.now = function() {
<del> return +new Date();
<add> return +new Date;
<ide> };
<ide> if (!Object.create) Object.create = function(o) {
<ide> /** @constructor */ function f() {}
<ide> f.prototype = o;
<del> return new f();
<add> return new f;
<ide> };
<ide> var d3_array = d3_arraySlice; // conversion for NodeLists
<ide>
<ide> d3.round = function(x, n) {
<ide> : Math.round(x);
<ide> };
<ide> d3.xhr = function(url, mime, callback) {
<del> var req = new XMLHttpRequest();
<add> var req = new XMLHttpRequest;
<ide> if (arguments.length < 3) callback = mime;
<ide> else if (mime && req.overrideMimeType) req.overrideMimeType(mime);
<ide> req.open("GET", url, true);
<ide><path>examples/clock/clock.js
<ide> d3.timer(function() {
<ide>
<ide> // Generate the fields for the current date/time.
<ide> function fields() {
<del> var d = new Date();
<add> var d = new Date;
<ide>
<ide> function days() {
<ide> return 32 - new Date(d.getYear(), d.getMonth(), 32).getDate();
<ide><path>src/core/date.js
<ide> if (!Date.now) Date.now = function() {
<del> return +new Date();
<add> return +new Date;
<ide> };
<ide><path>src/core/object.js
<ide> if (!Object.create) Object.create = function(o) {
<ide> /** @constructor */ function f() {}
<ide> f.prototype = o;
<del> return new f();
<add> return new f;
<ide> };
<ide><path>src/core/xhr.js
<ide> d3.xhr = function(url, mime, callback) {
<del> var req = new XMLHttpRequest();
<add> var req = new XMLHttpRequest;
<ide> if (arguments.length < 3) callback = mime;
<ide> else if (mime && req.overrideMimeType) req.overrideMimeType(mime);
<ide> req.open("GET", url, true);
<ide><path>tests/test-keys.js
<ide> console.log(" " + d3.keys({a: 1, b: 2}).sort());
<ide> console.log("");
<ide>
<ide> console.log("inherited keys:");
<del>console.log(" " + d3.keys(new Abc()).sort());
<add>console.log(" " + d3.keys(new Abc).sort());
<ide> console.log(""); | 6 |
Ruby | Ruby | remove duplicate test | 96ac7e4cdee004bcd19cb63b3e3396329e3b39ed | <ide><path>activejob/test/cases/test_helper_test.rb
<ide> def test_assert_performed_jobs_with_except_and_queue_options
<ide> end
<ide> end
<ide>
<del> def test_assert_performed_jobs_with_except_and_queue_options_failuree
<add> def test_assert_performed_jobs_with_except_and_queue_options_failure
<ide> error = assert_raise ActiveSupport::TestCase::Assertion do
<ide> assert_performed_jobs 1, except: HelloJob, queue: :other_queue do
<ide> HelloJob.set(queue: :other_queue).perform_later("jeremy")
<ide> def test_assert_performed_jobs_without_block_with_except_and_queue_options
<ide> assert_performed_jobs 1, except: HelloJob, queue: :other_queue
<ide> end
<ide>
<del> def test_assert_performed_jobs_with_except_and_queue_options_failuree
<add> def test_assert_performed_jobs_without_block_with_except_and_queue_options_failure
<ide> HelloJob.set(queue: :other_queue).perform_later("jeremy")
<ide> LoggingJob.set(queue: :some_queue).perform_later("bogdan")
<ide> LoggingJob.set(queue: :some_queue).perform_later("jeremy") | 1 |
Python | Python | update all examples with new api | 2bd4c295d6cae124f2cffce0e7343dc2c18d7eee | <ide><path>examples/addition_rnn.py
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import print_function
<ide> from keras.models import Sequential, slice_X
<del>from keras.layers.core import Activation, Dense, RepeatVector
<add>from keras.layers.core import Activation, TimeDistributedDense, RepeatVector
<ide> from keras.layers import recurrent
<del>from sklearn.utils import shuffle
<ide> import numpy as np
<ide>
<ide> """
<ide> http://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf
<ide> Theoretically it introduces shorter term dependencies between source and target.
<ide>
<del>
<ide> Two digits inverted:
<ide> + One layer JZS1 (128 HN), 5k training examples = 99% train/test accuracy in 55 epochs
<ide>
<ide> Three digits inverted:
<ide> + One layer JZS1 (128 HN), 50k training examples = 99% train/test accuracy in 100 epochs
<ide>
<del>
<ide> Four digits inverted:
<ide> + One layer JZS1 (128 HN), 400k training examples = 99% train/test accuracy in 20 epochs
<ide>
<del>
<ide> Five digits inverted:
<ide> + One layer JZS1 (128 HN), 550k training examples = 99% train/test accuracy in 30 epochs
<ide>
<ide> class colors:
<ide> y[i] = ctable.encode(sentence, maxlen=DIGITS + 1)
<ide>
<ide> # Shuffle (X, y) in unison as the later parts of X will almost all be larger digits
<del>X, y = shuffle(X, y)
<add>indices = np.arange(len(y))
<add>np.random.shuffle(indices)
<add>X = X[indices]
<add>y = y[indices]
<ide> # Explicitly set apart 10% for validation data that we never train over
<ide> split_at = len(X) - len(X) / 10
<ide> (X_train, X_val) = (slice_X(X, 0, split_at), slice_X(X, split_at))
<ide> (y_train, y_val) = (y[:split_at], y[split_at:])
<ide>
<add>print(X_train.shape)
<add>print(y_train.shape)
<add>
<ide> print('Build model...')
<ide> model = Sequential()
<ide> # "Encode" the input sequence using an RNN, producing an output of HIDDEN_SIZE
<del>model.add(RNN(len(chars), HIDDEN_SIZE))
<add># note: in a situation where your input sequences have a variable length,
<add># use input_shape=(None, nb_feature).
<add>model.add(RNN(HIDDEN_SIZE, input_shape=(None, len(chars))))
<ide> # For the decoder's input, we repeat the encoded input for each time step
<ide> model.add(RepeatVector(DIGITS + 1))
<ide> # The decoder RNN could be multiple layers stacked or a single layer
<ide> for _ in xrange(LAYERS):
<del> model.add(RNN(HIDDEN_SIZE, HIDDEN_SIZE, return_sequences=True))
<add> model.add(RNN(HIDDEN_SIZE, return_sequences=True))
<add>
<ide> # For each of step of the output sequence, decide which character should be chosen
<del>model.add(Dense(HIDDEN_SIZE, len(chars)))
<add>model.add(TimeDistributedDense(len(chars)))
<ide> model.add(Activation('softmax'))
<ide>
<ide> model.compile(loss='categorical_crossentropy', optimizer='adam')
<ide> class colors:
<ide> print()
<ide> print('-' * 50)
<ide> print('Iteration', iteration)
<del> model.fit(X, y, batch_size=BATCH_SIZE, nb_epoch=1, validation_data=(X_val, y_val), show_accuracy=True)
<add> model.fit(X_train, y_train, batch_size=BATCH_SIZE, nb_epoch=1, validation_data=(X_val, y_val), show_accuracy=True)
<ide> ###
<ide> # Select 10 samples from the validation set at random so we can visualize errors
<ide> for i in xrange(10):
<ide><path>examples/babi_rnn.py
<ide> def vectorize_stories(data):
<ide>
<ide> sentrnn = Sequential()
<ide> sentrnn.add(Embedding(vocab_size, EMBED_HIDDEN_SIZE, mask_zero=True))
<del>sentrnn.add(RNN(EMBED_HIDDEN_SIZE, SENT_HIDDEN_SIZE, return_sequences=False))
<add>sentrnn.add(RNN(SENT_HIDDEN_SIZE, return_sequences=False))
<ide>
<ide> qrnn = Sequential()
<ide> qrnn.add(Embedding(vocab_size, EMBED_HIDDEN_SIZE))
<del>qrnn.add(RNN(EMBED_HIDDEN_SIZE, QUERY_HIDDEN_SIZE, return_sequences=False))
<add>qrnn.add(RNN(QUERY_HIDDEN_SIZE, return_sequences=False))
<ide>
<ide> model = Sequential()
<ide> model.add(Merge([sentrnn, qrnn], mode='concat'))
<del>model.add(Dense(SENT_HIDDEN_SIZE + QUERY_HIDDEN_SIZE, vocab_size, activation='softmax'))
<add>model.add(Dense(vocab_size, activation='softmax'))
<ide>
<ide> model.compile(optimizer='adam', loss='categorical_crossentropy', class_mode='categorical')
<ide>
<ide><path>examples/cifar10_cnn.py
<ide> nb_epoch = 200
<ide> data_augmentation = True
<ide>
<del># shape of the image (SHAPE x SHAPE)
<del>shapex, shapey = 32, 32
<del># number of convolutional filters to use at each layer
<del>nb_filters = [32, 64]
<del># level of pooling to perform at each layer (POOL x POOL)
<del>nb_pool = [2, 2]
<del># level of convolution to perform at each layer (CONV x CONV)
<del>nb_conv = [3, 3]
<add># input image dimensions
<add>img_rows, img_cols = 32, 32
<ide> # the CIFAR10 images are RGB
<del>image_dimensions = 3
<add>img_channels = 3
<ide>
<ide> # the data, shuffled and split between tran and test sets
<ide> (X_train, y_train), (X_test, y_test) = cifar10.load_data()
<ide>
<ide> model = Sequential()
<ide>
<del>model.add(Convolution2D(nb_filters[0], image_dimensions, nb_conv[0], nb_conv[0], border_mode='full'))
<add>model.add(Convolution2D(32, 3, 3, border_mode='full',
<add> input_shape=(img_channels, img_rows, img_cols)))
<ide> model.add(Activation('relu'))
<del>model.add(Convolution2D(nb_filters[0], nb_filters[0], nb_conv[0], nb_conv[0]))
<add>model.add(Convolution2D(32, 3, 3))
<ide> model.add(Activation('relu'))
<del>model.add(MaxPooling2D(pool_size=(nb_pool[0], nb_pool[0])))
<add>model.add(MaxPooling2D(pool_size=(2, 2)))
<ide> model.add(Dropout(0.25))
<ide>
<del>model.add(Convolution2D(nb_filters[1], nb_filters[0], nb_conv[0], nb_conv[0], border_mode='full'))
<add>model.add(Convolution2D(64, 3, 3, border_mode='full'))
<ide> model.add(Activation('relu'))
<del>model.add(Convolution2D(nb_filters[1], nb_filters[1], nb_conv[1], nb_conv[1]))
<add>model.add(Convolution2D(64, 3, 3))
<ide> model.add(Activation('relu'))
<del>model.add(MaxPooling2D(pool_size=(nb_pool[1], nb_pool[1])))
<add>model.add(MaxPooling2D(pool_size=(2, 2)))
<ide> model.add(Dropout(0.25))
<ide>
<ide> model.add(Flatten())
<del># the image dimensions are the original dimensions divided by any pooling
<del># each pixel has a number of filters, determined by the last Convolution2D layer
<del>model.add(Dense(nb_filters[-1] * (shapex / nb_pool[0] / nb_pool[1]) * (shapey / nb_pool[0] / nb_pool[1]), 512))
<add>model.add(Dense(512))
<ide> model.add(Activation('relu'))
<ide> model.add(Dropout(0.5))
<del>
<del>model.add(Dense(512, nb_classes))
<add>model.add(Dense(nb_classes))
<ide> model.add(Activation('softmax'))
<ide>
<ide> # let's train the model using SGD + momentum (how original).
<ide><path>examples/imdb_cnn.py
<ide> from __future__ import absolute_import
<ide> from __future__ import print_function
<ide> import numpy as np
<del>np.random.seed(1337) # for reproducibility
<add>np.random.seed(1337) # for reproducibility
<ide>
<ide> from keras.preprocessing import sequence
<ide> from keras.optimizers import RMSprop
<ide> maxlen = 100
<ide> batch_size = 32
<ide> embedding_dims = 100
<del>nb_filters = 250
<add>nb_filter = 250
<ide> filter_length = 3
<ide> hidden_dims = 250
<ide> nb_epoch = 3
<ide>
<ide> # we start off with an efficient embedding layer which maps
<ide> # our vocab indices into embedding_dims dimensions
<del>model.add(Embedding(max_features, embedding_dims))
<add>model.add(Embedding(max_features, embedding_dims, max_lenght=maxlen))
<ide> model.add(Dropout(0.25))
<ide>
<del># we add a Convolution1D, which will learn nb_filters
<add># we add a Convolution1D, which will learn nb_filter
<ide> # word group filters of size filter_length:
<del>model.add(Convolution1D(input_dim=embedding_dims,
<del> nb_filter=nb_filters,
<add>model.add(Convolution1D(nb_filter=nb_filter,
<ide> filter_length=filter_length,
<ide> border_mode="valid",
<ide> activation="relu",
<ide> subsample_length=1))
<del>
<ide> # we use standard max pooling (halving the output of the previous layer):
<ide> model.add(MaxPooling1D(pool_length=2))
<ide>
<ide> # We flatten the output of the conv layer, so that we can add a vanilla dense layer:
<ide> model.add(Flatten())
<ide>
<del># Computing the output shape of a conv layer can be tricky;
<del># for a good tutorial, see: http://cs231n.github.io/convolutional-networks/
<del>output_size = nb_filters * (((maxlen - filter_length) / 1) + 1) / 2
<del>
<ide> # We add a vanilla hidden layer:
<del>model.add(Dense(output_size, hidden_dims))
<add>model.add(Dense(hidden_dims))
<ide> model.add(Dropout(0.25))
<ide> model.add(Activation('relu'))
<ide>
<ide> # We project onto a single unit output layer, and squash it with a sigmoid:
<del>model.add(Dense(hidden_dims, 1))
<add>model.add(Dense(1))
<ide> model.add(Activation('sigmoid'))
<ide>
<ide> model.compile(loss='binary_crossentropy', optimizer='rmsprop', class_mode="binary")
<ide><path>examples/imdb_lstm.py
<ide> print('Build model...')
<ide> model = Sequential()
<ide> model.add(Embedding(max_features, 128))
<del>model.add(LSTM(128, 128)) # try using a GRU instead, for fun
<add>model.add(LSTM(128)) # try using a GRU instead, for fun
<ide> model.add(Dropout(0.5))
<del>model.add(Dense(128, 1))
<add>model.add(Dense(1))
<ide> model.add(Activation('sigmoid'))
<ide>
<ide> # try using different optimizers and different optimizer configs
<ide><path>examples/kaggle_otto_nn.py
<ide>
<ide> Compatible Python 2.7-3.4. Requires Scikit-Learn and Pandas.
<ide>
<del> Recommended to run on GPU:
<add> Recommended to run on GPU:
<ide> Command: THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python kaggle_otto_nn.py
<ide> On EC2 g2.2xlarge instance: 19s/epoch. 6-7 minutes total training time.
<ide>
<del> Best validation score at epoch 21: 0.4881
<add> Best validation score at epoch 21: 0.4881
<ide>
<ide> Try it at home:
<ide> - with/without BatchNormalization (BatchNormalization helps!)
<ide> def make_submission(y_prob, ids, encoder, fname):
<ide> f.write('\n')
<ide> print("Wrote submission to file {}.".format(fname))
<ide>
<del>
<ide> print("Loading data...")
<ide> X, labels = load_data('train.csv', train=True)
<ide> X, scaler = preprocess_data(X)
<ide> def make_submission(y_prob, ids, encoder, fname):
<ide> print("Building model...")
<ide>
<ide> model = Sequential()
<del>model.add(Dense(dims, 512, init='glorot_uniform'))
<del>model.add(PReLU((512,)))
<add>model.add(Dense(512, input_shape=(dims,)))
<add>model.add(PReLU())
<ide> model.add(BatchNormalization((512,)))
<ide> model.add(Dropout(0.5))
<ide>
<del>model.add(Dense(512, 512, init='glorot_uniform'))
<del>model.add(PReLU((512,)))
<del>model.add(BatchNormalization((512,)))
<add>model.add(Dense(512))
<add>model.add(PReLU())
<add>model.add(BatchNormalization())
<ide> model.add(Dropout(0.5))
<ide>
<del>model.add(Dense(512, 512, init='glorot_uniform'))
<del>model.add(PReLU((512,)))
<del>model.add(BatchNormalization((512,)))
<add>model.add(Dense(512))
<add>model.add(PReLU())
<add>model.add(BatchNormalization())
<ide> model.add(Dropout(0.5))
<ide>
<del>model.add(Dense(512, nb_classes, init='glorot_uniform'))
<add>model.add(Dense(nb_classes))
<ide> model.add(Activation('softmax'))
<ide>
<ide> model.compile(loss='categorical_crossentropy', optimizer="adam")
<ide>
<ide> print("Training model...")
<del>
<ide> model.fit(X, y, nb_epoch=20, batch_size=128, validation_split=0.15)
<ide>
<ide> print("Generating submission...")
<del>
<ide> proba = model.predict_proba(X_test)
<ide> make_submission(proba, ids, encoder, fname='keras-otto.csv')
<ide><path>examples/lstm_text_generation.py
<ide> from keras.layers.recurrent import LSTM
<ide> from keras.datasets.data_utils import get_file
<ide> import numpy as np
<del>import random, sys
<add>import random
<add>import sys
<ide>
<ide> '''
<ide> Example script to generate text from Nietzsche's writings.
<ide> It is recommended to run this script on GPU, as recurrent
<ide> networks are quite computationally intensive.
<ide>
<del> If you try this script on new data, make sure your corpus
<add> If you try this script on new data, make sure your corpus
<ide> has at least ~100k characters. ~1M is better.
<ide> '''
<ide>
<ide> sentences = []
<ide> next_chars = []
<ide> for i in range(0, len(text) - maxlen, step):
<del> sentences.append(text[i : i + maxlen])
<add> sentences.append(text[i: i + maxlen])
<ide> next_chars.append(text[i + maxlen])
<ide> print('nb sequences:', len(sentences))
<ide>
<ide> # build the model: 2 stacked LSTM
<ide> print('Build model...')
<ide> model = Sequential()
<del>model.add(LSTM(len(chars), 512, return_sequences=True))
<add>model.add(LSTM(512, return_sequences=True, input_shape=(maxlen, len(chars))))
<ide> model.add(Dropout(0.2))
<del>model.add(LSTM(512, 512, return_sequences=False))
<add>model.add(LSTM(512, return_sequences=False))
<ide> model.add(Dropout(0.2))
<del>model.add(Dense(512, len(chars)))
<add>model.add(Dense(len(chars)))
<ide> model.add(Activation('softmax'))
<ide>
<ide> model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
<ide>
<del># helper function to sample an index from a probability array
<add>
<ide> def sample(a, temperature=1.0):
<del> a = np.log(a)/temperature
<del> a = np.exp(a)/np.sum(np.exp(a))
<del> return np.argmax(np.random.multinomial(1,a,1))
<add> # helper function to sample an index from a probability array
<add> a = np.log(a) / temperature
<add> a = np.exp(a) / np.sum(np.exp(a))
<add> return np.argmax(np.random.multinomial(1, a, 1))
<ide>
<ide> # train the model, output generated text after each iteration
<ide> for iteration in range(1, 60):
<ide> def sample(a, temperature=1.0):
<ide> print('----- diversity:', diversity)
<ide>
<ide> generated = ''
<del> sentence = text[start_index : start_index + maxlen]
<add> sentence = text[start_index: start_index + maxlen]
<ide> generated += sentence
<ide> print('----- Generating with seed: "' + sentence + '"')
<ide> sys.stdout.write(generated)
<ide><path>examples/mnist_cnn.py
<ide> nb_classes = 10
<ide> nb_epoch = 12
<ide>
<del># shape of the image (SHAPE x SHAPE)
<del>shapex, shapey = 28, 28
<add># input image dimensions
<add>img_rows, img_cols = 28, 28
<ide> # number of convolutional filters to use
<ide> nb_filters = 32
<del># level of pooling to perform (POOL x POOL)
<add># size of pooling area for max pooling
<ide> nb_pool = 2
<del># level of convolution to perform (CONV x CONV)
<add># convolution kernel size
<ide> nb_conv = 3
<ide>
<ide> # the data, shuffled and split between tran and test sets
<ide> (X_train, y_train), (X_test, y_test) = mnist.load_data()
<ide>
<del>X_train = X_train.reshape(X_train.shape[0], 1, shapex, shapey)
<del>X_test = X_test.reshape(X_test.shape[0], 1, shapex, shapey)
<add>X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
<add>X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
<ide> X_train = X_train.astype("float32")
<ide> X_test = X_test.astype("float32")
<ide> X_train /= 255
<ide>
<ide> model = Sequential()
<ide>
<del>model.add(Convolution2D(nb_filters, 1, nb_conv, nb_conv, border_mode='full'))
<add>model.add(Convolution2D(nb_filters, nb_conv, nb_conv,
<add> border_mode='full',
<add> input_shape=(1, img_rows, img_cols)))
<ide> model.add(Activation('relu'))
<del>model.add(Convolution2D(nb_filters, nb_filters, nb_conv, nb_conv))
<add>model.add(Convolution2D(nb_filters, nb_conv, nb_conv))
<ide> model.add(Activation('relu'))
<ide> model.add(MaxPooling2D(pool_size=(nb_pool, nb_pool)))
<ide> model.add(Dropout(0.25))
<ide>
<ide> model.add(Flatten())
<del># the resulting image after conv and pooling is the original shape
<del># divided by the pooling with a number of filters for each "pixel"
<del># (the number of filters is determined by the last Conv2D)
<del>model.add(Dense(nb_filters * (shapex / nb_pool) * (shapey / nb_pool), 128))
<add>model.add(Dense(128))
<ide> model.add(Activation('relu'))
<ide> model.add(Dropout(0.5))
<del>
<del>model.add(Dense(128, nb_classes))
<add>model.add(Dense(nb_classes))
<ide> model.add(Activation('softmax'))
<ide>
<ide> model.compile(loss='categorical_crossentropy', optimizer='adadelta')
<ide><path>examples/mnist_irnn.py
<ide>
<ide> print('Evaluate IRNN...')
<ide> model = Sequential()
<del>model.add(SimpleRNN(input_dim=1, output_dim=hidden_units,
<add>model.add(SimpleRNN(output_dim=hidden_units,
<ide> init=lambda shape: normal(shape, scale=0.001),
<ide> inner_init=lambda shape: identity(shape, scale=1.0),
<del> activation='relu', truncate_gradient=BPTT_truncate))
<del>model.add(Dense(hidden_units, nb_classes))
<add> activation='relu', truncate_gradient=BPTT_truncate,
<add> input_shape=(None, 1)))
<add>model.add(Dense(nb_classes))
<ide> model.add(Activation('softmax'))
<ide> rmsprop = RMSprop(lr=learning_rate)
<ide> model.compile(loss='categorical_crossentropy', optimizer=rmsprop)
<ide>
<ide> print('Compare to LSTM...')
<ide> model = Sequential()
<del>model.add(LSTM(1, hidden_units))
<del>model.add(Dense(hidden_units, nb_classes))
<add>model.add(LSTM(hidden_units, input_shape=(None, 1)))
<add>model.add(Dense(nb_classes))
<ide> model.add(Activation('softmax'))
<ide> rmsprop = RMSprop(lr=learning_rate)
<ide> model.compile(loss='categorical_crossentropy', optimizer=rmsprop)
<ide><path>examples/mnist_mlp.py
<ide> Y_test = np_utils.to_categorical(y_test, nb_classes)
<ide>
<ide> model = Sequential()
<del>model.add(Dense(784, 128))
<add>model.add(Dense(128, input_shape=(784,)))
<ide> model.add(Activation('relu'))
<ide> model.add(Dropout(0.2))
<del>model.add(Dense(128, 128))
<add>model.add(Dense(128))
<ide> model.add(Activation('relu'))
<ide> model.add(Dropout(0.2))
<del>model.add(Dense(128, 10))
<add>model.add(Dense(10))
<ide> model.add(Activation('softmax'))
<ide>
<ide> rms = RMSprop()
<ide><path>examples/reuters_mlp.py
<ide>
<ide> print("Building model...")
<ide> model = Sequential()
<del>model.add(Dense(max_words, 512))
<add>model.add(Dense(512, input_shape=(max_words,)))
<ide> model.add(Activation('relu'))
<ide> model.add(Dropout(0.5))
<del>model.add(Dense(512, nb_classes))
<add>model.add(Dense(nb_classes))
<ide> model.add(Activation('softmax'))
<ide>
<ide> model.compile(loss='categorical_crossentropy', optimizer='adam')
<ide><path>examples/skipgram_word_embeddings.py
<ide> def text_generator(path=data_path):
<ide> reverse_word_index = dict([(v, k) for k, v in list(word_index.items())])
<ide>
<ide>
<del>
<ide> def embed_word(w):
<ide> i = word_index.get(w)
<ide> if (not i) or (i < skip_top) or (i >= max_features):
<ide><path>keras/layers/advanced_activations.py
<ide> class PReLU(MaskedLayer):
<ide> Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
<ide> http://arxiv.org/pdf/1502.01852v1.pdf
<ide> '''
<del> def __init__(self, input_shape, init='zero', weights=None, **kwargs):
<del> super(PReLU, self).__init__(**kwargs)
<add> def __init__(self, init='zero', weights=None, **kwargs):
<ide> self.init = initializations.get(init)
<add> self.initial_weights = weights
<add> super(PReLU, self).__init__(**kwargs)
<add>
<add> def build(self):
<add> input_shape = self.input_shape[1:]
<ide> self.alphas = self.init(input_shape)
<ide> self.params = [self.alphas]
<del> self.input_shape = input_shape
<ide>
<del> if weights is not None:
<del> self.set_weights(weights)
<add> if self.initial_weights is not None:
<add> self.set_weights(self.initial_weights)
<add> del self.initial_weights
<ide>
<ide> def get_output(self, train):
<ide> X = self.get_input(train)
<ide> def get_output(self, train):
<ide>
<ide> def get_config(self):
<ide> return {"name": self.__class__.__name__,
<del> "input_shape": self.input_shape,
<ide> "init": self.init.__name__}
<ide>
<ide>
<ide> class ParametricSoftplus(MaskedLayer):
<ide> Inferring Nonlinear Neuronal Computation Based on Physiologically Plausible Inputs
<ide> http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1003143
<ide> '''
<del> def __init__(self, input_shape, alpha_init=0.2,
<del> beta_init=5.0, weights=None, **kwargs):
<del>
<del> super(ParametricSoftplus, self).__init__(**kwargs)
<add> def __init__(self, alpha_init=0.2, beta_init=5.0,
<add> weights=None, **kwargs):
<ide> self.alpha_init = alpha_init
<ide> self.beta_init = beta_init
<del> self.alphas = sharedX(alpha_init * np.ones(input_shape))
<del> self.betas = sharedX(beta_init * np.ones(input_shape))
<add> self.initial_weights = weights
<add> super(ParametricSoftplus, self).__init__(**kwargs)
<add>
<add> def build(self):
<add> input_shape = self.input_shape[1:]
<add> self.alphas = sharedX(self.alpha_init * np.ones(input_shape))
<add> self.betas = sharedX(self.beta_init * np.ones(input_shape))
<ide> self.params = [self.alphas, self.betas]
<ide> self.input_shape = input_shape
<ide>
<del> if weights is not None:
<del> self.set_weights(weights)
<add> if self.initial_weights is not None:
<add> self.set_weights(self.initial_weights)
<add> del self.initial_weights
<ide>
<ide> def get_output(self, train):
<ide> X = self.get_input(train)
<ide> return T.nnet.softplus(self.betas * X) * self.alphas
<ide>
<ide> def get_config(self):
<ide> return {"name": self.__class__.__name__,
<del> "input_shape": self.input_shape,
<ide> "alpha_init": self.alpha_init,
<ide> "beta_init": self.beta_init}
<ide>
<ide><path>keras/layers/convolutional.py
<ide> def pool_output_length(input_length, pool_size, ignore_border, stride):
<ide> class Convolution1D(Layer):
<ide> input_ndim = 3
<ide>
<del> def __init__(self, input_dim, nb_filter, filter_length,
<add> def __init__(self, nb_filter, filter_length,
<ide> init='uniform', activation='linear', weights=None,
<ide> border_mode='valid', subsample_length=1,
<ide> W_regularizer=None, b_regularizer=None, activity_regularizer=None,
<ide> def __init__(self, input_dim, nb_filter, filter_length,
<ide> def build(self):
<ide> input_dim = self.input_shape[2]
<ide> self.input = T.tensor3()
<del> self.W_shape = (nb_filter, input_dim, filter_length, 1)
<add> self.W_shape = (self.nb_filter, input_dim, self.filter_length, 1)
<ide> self.W = self.init(self.W_shape)
<del> self.b = shared_zeros((nb_filter,))
<add> self.b = shared_zeros((self.nb_filter,))
<ide> self.params = [self.W, self.b]
<ide> self.regularizers = []
<ide>
<ide> def __init__(self, nb_filter, nb_row, nb_col,
<ide> def build(self):
<ide> stack_size = self.input_shape[1]
<ide> self.input = T.tensor4()
<del> self.W_shape = (nb_filter, stack_size, nb_row, nb_col)
<add> self.W_shape = (self.nb_filter, stack_size, self.nb_row, self.nb_col)
<ide> self.W = self.init(self.W_shape)
<del> self.b = shared_zeros((nb_filter,))
<add> self.b = shared_zeros((self.nb_filter,))
<ide> self.params = [self.W, self.b]
<ide> self.regularizers = []
<ide>
<ide><path>keras/layers/core.py
<ide> class Layer(object):
<ide> def __init__(self, **kwargs):
<ide> if 'input_shape' in kwargs:
<ide> self.set_input_shape(kwargs['input_shape'])
<del> self.params = []
<add> if not hasattr(self, 'params'):
<add> self.params = []
<ide>
<ide> def init_updates(self):
<ide> self.updates = []
<ide> def input_shape(self):
<ide> elif hasattr(self, '_input_shape'):
<ide> return self._input_shape
<ide> else:
<del> raise Exception('Layer is not connected.')
<add> raise Exception('Layer is not connected. Did you forget to set "input_shape"?')
<ide>
<ide> def set_input_shape(self, input_shape):
<ide> if type(input_shape) not in [tuple, list]:
<ide> def output_shape(self):
<ide> elif self.mode == 'concat':
<ide> output_shape = list(input_shapes[0])
<ide> for shape in input_shapes[1:]:
<del> output_shape[self.concat_axis] += shape[concat_axis]
<add> output_shape[self.concat_axis] += shape[self.concat_axis]
<ide> return tuple(output_shape)
<ide>
<ide> def get_params(self):
<ide> def build(self):
<ide>
<ide> self.input = T.matrix()
<ide> self.W = self.init((input_dim, self.output_dim))
<del> self.b = shared_zeros((self.output_dim))
<add> self.b = shared_zeros((self.output_dim,))
<ide>
<ide> self.params = [self.W, self.b]
<ide>
<ide><path>keras/layers/embeddings.py
<ide> class Embedding(Layer):
<ide> '''
<ide> input_ndim = 2
<ide>
<del> def __init__(self, input_dim, output_dim, init='uniform',
<add> def __init__(self, input_dim, output_dim, init='uniform', max_lenght=None,
<ide> W_regularizer=None, activity_regularizer=None, W_constraint=None,
<ide> mask_zero=False, weights=None, **kwargs):
<del>
<del> super(Embedding, self).__init__(**kwargs)
<del> self.init = initializations.get(init)
<ide> self.input_dim = input_dim
<ide> self.output_dim = output_dim
<del>
<del> self.input = T.imatrix()
<del> self.W = self.init((self.input_dim, self.output_dim))
<add> self.init = initializations.get(init)
<add> self.max_lenght = max_lenght
<ide> self.mask_zero = mask_zero
<ide>
<del> self.params = [self.W]
<del>
<ide> self.W_constraint = constraints.get(W_constraint)
<ide> self.constraints = [self.W_constraint]
<ide>
<del> self.regularizers = []
<del>
<ide> self.W_regularizer = regularizers.get(W_regularizer)
<add> self.activity_regularizer = regularizers.get(activity_regularizer)
<add>
<add> self.initial_weights = weights
<add> kwargs['input_shape'] = (self.input_dim,)
<add> super(Embedding, self).__init__(**kwargs)
<add>
<add> def build(self):
<add> self.input = T.imatrix()
<add> self.W = self.init((self.input_dim, self.output_dim))
<add> self.params = [self.W]
<add> self.regularizers = []
<ide> if self.W_regularizer:
<ide> self.W_regularizer.set_param(self.W)
<ide> self.regularizers.append(self.W_regularizer)
<ide>
<del> self.activity_regularizer = regularizers.get(activity_regularizer)
<ide> if self.activity_regularizer:
<ide> self.activity_regularizer.set_layer(self)
<ide> self.regularizers.append(self.activity_regularizer)
<ide>
<del> if weights is not None:
<del> self.set_weights(weights)
<add> if self.initial_weights is not None:
<add> self.set_weights(self.initial_weights)
<ide>
<ide> def get_output_mask(self, train=None):
<ide> X = self.get_input(train)
<ide> def get_output_mask(self, train=None):
<ide>
<ide> @property
<ide> def output_shape(self):
<del> return (self.input_shape[0], None, self.output_dim)
<add> return (self.input_shape[0], self.max_lenght, self.output_dim)
<ide>
<ide> def get_output(self, train=False):
<ide> X = self.get_input(train)
<ide> def get_config(self):
<ide> "input_dim": self.input_dim,
<ide> "output_dim": self.output_dim,
<ide> "init": self.init.__name__,
<add> "max_lenght": self.max_lenght,
<add> "mask_zero": self.mask_zero,
<ide> "activity_regularizer": self.activity_regularizer.get_config() if self.activity_regularizer else None,
<ide> "W_regularizer": self.W_regularizer.get_config() if self.W_regularizer else None,
<ide> "W_constraint": self.W_constraint.get_config() if self.W_constraint else None}
<ide><path>keras/layers/normalization.py
<ide> def __init__(self, epsilon=1e-6, mode=0, momentum=0.9, weights=None, **kwargs):
<ide> self.epsilon = epsilon
<ide> self.mode = mode
<ide> self.momentum = momentum
<add> self.initial_weights = weights
<ide> super(BatchNormalization, self).__init__(**kwargs)
<ide>
<ide> def build(self):
<ide> def build(self):
<ide> self.params = [self.gamma, self.beta]
<ide> self.running_mean = shared_zeros(input_shape)
<ide> self.running_std = shared_ones((input_shape))
<del> if weights is not None:
<del> self.set_weights(weights)
<add> if self.initial_weights is not None:
<add> self.set_weights(self.initial_weights)
<add> del self.initial_weights
<ide>
<ide> def get_weights(self):
<ide> return super(BatchNormalization, self).get_weights() + [self.running_mean.get_value(), self.running_std.get_value()] | 17 |
PHP | PHP | fix a docblock in the controller class | 958efea5bdfd9bd2076604af1b843c5a55e00d0a | <ide><path>laravel/routing/controller.php
<ide> public static function call($destination, $parameters = array())
<ide> /**
<ide> * Resolve a controller name to a controller instance.
<ide> *
<del> * @param Container $container
<add> * @param string $container
<ide> * @param string $controller
<ide> * @return Controller
<ide> */
<ide> public function __get($key)
<ide> throw new \OutOfBoundsException("Attempting to access undefined property [$key] on controller.");
<ide> }
<ide>
<del>}
<add>}
<ide>\ No newline at end of file | 1 |
Text | Text | fix position of `fs.readsync()` | 2011f2c6dc13c6148c5d581d636c809f796f7572 | <ide><path>doc/api/fs.md
<ide> object with an `encoding` property specifying the character encoding to use for
<ide> the link path passed to the callback. If the `encoding` is set to `'buffer'`,
<ide> the link path returned will be passed as a `Buffer` object.
<ide>
<add>## fs.readSync(fd, buffer, offset, length, position)
<add>
<add>* `fd` {Integer}
<add>* `buffer` {String | Buffer}
<add>* `offset` {Integer}
<add>* `length` {Integer}
<add>* `position` {Integer}
<add>
<add>Synchronous version of [`fs.read()`][]. Returns the number of `bytesRead`.
<add>
<ide> ## fs.realpath(path[, options], callback)
<ide>
<ide> * `path` {String | Buffer}
<ide> object with an `encoding` property specifying the character encoding to use for
<ide> the path passed to the callback. If the `encoding` is set to `'buffer'`,
<ide> the path returned will be passed as a `Buffer` object.
<ide>
<del>## fs.readSync(fd, buffer, offset, length, position)
<del>
<del>* `fd` {Integer}
<del>* `buffer` {String | Buffer}
<del>* `offset` {Integer}
<del>* `length` {Integer}
<del>* `position` {Integer}
<del>
<del>Synchronous version of [`fs.read()`][]. Returns the number of `bytesRead`.
<del>
<ide> ## fs.realpathSync(path[, options])
<ide>
<ide> * `path` {String | Buffer}; | 1 |
Javascript | Javascript | enable throwonmodulecollision for jest-haste-map | 122b239ce0c1df1918c17fbd8413c5d00d265465 | <ide><path>packager/src/node-haste/DependencyGraph.js
<ide> class DependencyGraph extends EventEmitter {
<ide> resetCache: opts.resetCache,
<ide> retainAllFiles: true,
<ide> roots: opts.roots,
<add> throwOnModuleCollision: true,
<ide> useWatchman: opts.useWatchman,
<ide> watch: opts.watch,
<ide> });
<ide><path>packager/src/node-haste/__tests__/DependencyGraph-test.js
<ide> describe('DependencyGraph', function() {
<ide>
<ide> return dgraph.catch(err => {
<ide> expect(err.message).toEqual(
<del> `Failed to build DependencyGraph: @providesModule naming collision:\n` +
<add> 'jest-haste-map: @providesModule naming collision:\n' +
<ide> ` Duplicate module name: index\n` +
<ide> ` Paths: /root/b.js collides with /root/index.js\n\n` +
<ide> 'This error is caused by a @providesModule declaration ' +
<ide> 'with the same name across two different files.',
<ide> );
<del> expect(err.type).toEqual('DependencyGraphError');
<del> expect(console.warn).toBeCalled();
<add> expect(console.warn).not.toBeCalled();
<ide> });
<ide> });
<ide> | 2 |
Ruby | Ruby | add uuid primary key support | bc8ebefe9825dbff2cffa29ff015a1e7a31f9812 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
<ide> def columns; @columns_hash.values; end
<ide>
<ide> # Appends a primary key definition to the table definition.
<ide> # Can be called multiple times, but this is probably not a good idea.
<del> def primary_key(name)
<del> column(name, :primary_key, primary_key: true)
<add> def primary_key(name, type = :primary_key, options = {})
<add> options[:primary_key] = true
<add> column(name, type, options)
<ide> end
<ide>
<ide> # Returns a ColumnDefinition for the column with name +name+.
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def create_table(table_name, options = {})
<ide> Base.get_primary_key table_name.to_s.singularize
<ide> }
<ide>
<del> td.primary_key pk
<add> td.primary_key pk, options.fetch(:id, :primary_key), options
<ide> end
<ide>
<ide> yield td if block_given?
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
<ide> def visit_AddColumn(o)
<ide> add_column_options!(sql, column_options(o))
<ide> end
<ide>
<add> def visit_ColumnDefinition(o)
<add> sql = super
<add> if o.primary_key? && o.type == :uuid
<add> sql << " PRIMARY KEY "
<add> add_column_options!(sql, column_options(o))
<add> end
<add> sql
<add> end
<add>
<ide> def add_column_options!(sql, options)
<ide> if options[:array] || options[:column].try(:array)
<ide> sql << '[]'
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def json(name, options = {})
<ide> class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
<ide> include ColumnMethods
<ide>
<add> def primary_key(name, type = :primary_key, options = {})
<add> return super unless type == :uuid
<add> options[:default] ||= 'uuid_generate_v4()'
<add> options[:primary_key] = true
<add> column name, type, options
<add> end
<add>
<ide> def column(name, type = nil, options = {})
<ide> super
<ide> column = self[name]
<ide><path>activerecord/test/cases/adapters/postgresql/uuid_test.rb
<ide> def teardown
<ide> @connection.execute 'drop table if exists pg_uuids'
<ide> end
<ide>
<add> def test_id_is_uuid
<add> assert_equal :uuid, UUID.columns_hash['id'].type
<add> assert UUID.primary_key
<add> end
<add>
<add> def test_id_has_a_default
<add> u = UUID.create
<add> assert_not_nil u.id
<add> end
<add>
<ide> def test_auto_create_uuid
<ide> u = UUID.create
<ide> u.reload | 5 |
Text | Text | add v3.3.0-beta.2 to changelog | 1de74dc28634cbfc14bab974d14db37ba0aab67e | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.3.0-beta.2 (June 11, 2018)
<add>- [#16709](https://github.com/emberjs/ember.js/pull/16709) [BUGFIX] Avoid ordered set deprecation in @ember/ordered-set addon
<add>- [#16715](https://github.com/emberjs/ember.js/pull/16715) [BUGFIX] Update glimmer-vm to 0.35.3
<add>- [#16729](https://github.com/emberjs/ember.js/pull/16729) [BUGFIX] Throw error if run.bind receives no method
<add>- [#16731](https://github.com/emberjs/ember.js/pull/16731) [BUGFIX] Better error when a route name is not valid
<add>
<ide> ### v3.3.0-beta.1 (May 31, 2018)
<ide>
<ide> - [#16687](https://github.com/emberjs/ember.js/pull/16687) [FEATURE] Implement optional jQuery integration (see [emberjs/rfcs#294](https://github.com/emberjs/rfcs/blob/master/text/0294-optional-jquery.md) for more details). | 1 |
Javascript | Javascript | use minerr to throw exception | aad29cbbf0b101bc5e793a66df7e368c7968cad8 | <ide><path>src/ngResource/resource.js
<ide> 'use strict';
<ide>
<add>var ngResourceMinErr = minErr('ngResource');
<add>
<ide> /**
<ide> * @ngdoc overview
<ide> * @name ngResource
<ide> angular.module('ngResource', ['ng']).
<ide> break;
<ide> case 0: break;
<ide> default:
<del> throw "Expected up to 4 arguments [params, data, success, error], got " +
<del> arguments.length + " arguments.";
<add> throw ngResourceMinErr('badargs',
<add> "Expected up to 4 arguments [params, data, success, error], got {0} arguments", arguments.length);
<ide> }
<ide>
<ide> var isInstanceCall = data instanceof Resource; | 1 |
Javascript | Javascript | add weeksinyear and isoweeksinyear | 3e0fd9d7d2b645f7a396dfe1a4d3334a8e438e16 | <ide><path>moment.js
<ide> return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
<ide> }
<ide>
<add> function weeksInYear(year, dow, doy) {
<add> return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
<add> }
<add>
<ide> function daysInYear(year) {
<ide> return isLeapYear(year) ? 366 : 365;
<ide> }
<ide> return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
<ide> },
<ide>
<add> isoWeeksInYear : function () {
<add> return weeksInYear(this.year(), 1, 4);
<add> },
<add>
<add> weeksInYear : function () {
<add> var weekInfo = this._lang._week;
<add> return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
<add> },
<add>
<ide> get : function (units) {
<ide> units = normalizeUnits(units);
<ide> return this[units]();
<ide><path>test/moment/weeks_in_year.js
<add>var moment = require("../../moment");
<add>
<add>exports.weeks_in_year = {
<add> "isoWeeksInYear": function (test) {
<add> test.equal(moment([2004]).isoWeeksInYear(), 53, "2004 has 53 iso weeks");
<add> test.equal(moment([2005]).isoWeeksInYear(), 52, "2005 has 53 iso weeks");
<add> test.equal(moment([2006]).isoWeeksInYear(), 52, "2006 has 53 iso weeks");
<add> test.equal(moment([2007]).isoWeeksInYear(), 52, "2007 has 52 iso weeks");
<add> test.equal(moment([2008]).isoWeeksInYear(), 52, "2008 has 53 iso weeks");
<add> test.equal(moment([2009]).isoWeeksInYear(), 53, "2009 has 53 iso weeks");
<add> test.equal(moment([2010]).isoWeeksInYear(), 52, "2010 has 52 iso weeks");
<add> test.equal(moment([2011]).isoWeeksInYear(), 52, "2011 has 52 iso weeks");
<add> test.equal(moment([2012]).isoWeeksInYear(), 52, "2012 has 52 iso weeks");
<add> test.equal(moment([2013]).isoWeeksInYear(), 52, "2013 has 52 iso weeks");
<add> test.equal(moment([2014]).isoWeeksInYear(), 52, "2014 has 52 iso weeks");
<add> test.equal(moment([2015]).isoWeeksInYear(), 53, "2015 has 53 iso weeks");
<add>
<add> test.done();
<add> },
<add>
<add> "weeksInYear doy/dow = 1/4": function (test) {
<add> moment.lang('1/4', {week: {dow: 1, doy: 4}});
<add>
<add> test.equal(moment([2004]).weeksInYear(), 53, "2004 has 53 weeks");
<add> test.equal(moment([2005]).weeksInYear(), 52, "2005 has 53 weeks");
<add> test.equal(moment([2006]).weeksInYear(), 52, "2006 has 53 weeks");
<add> test.equal(moment([2007]).weeksInYear(), 52, "2007 has 52 weeks");
<add> test.equal(moment([2008]).weeksInYear(), 52, "2008 has 53 weeks");
<add> test.equal(moment([2009]).weeksInYear(), 53, "2009 has 53 weeks");
<add> test.equal(moment([2010]).weeksInYear(), 52, "2010 has 52 weeks");
<add> test.equal(moment([2011]).weeksInYear(), 52, "2011 has 52 weeks");
<add> test.equal(moment([2012]).weeksInYear(), 52, "2012 has 52 weeks");
<add> test.equal(moment([2013]).weeksInYear(), 52, "2013 has 52 weeks");
<add> test.equal(moment([2014]).weeksInYear(), 52, "2014 has 52 weeks");
<add> test.equal(moment([2015]).weeksInYear(), 53, "2015 has 53 weeks");
<add>
<add> test.done();
<add> },
<add>
<add> "weeksInYear doy/dow = 6/12": function (test) {
<add> moment.lang('6/12', {week: {dow: 6, doy: 12}});
<add>
<add> test.equal(moment([2004]).weeksInYear(), 53, "2004 has 53 weeks");
<add> test.equal(moment([2005]).weeksInYear(), 52, "2005 has 53 weeks");
<add> test.equal(moment([2006]).weeksInYear(), 52, "2006 has 53 weeks");
<add> test.equal(moment([2007]).weeksInYear(), 52, "2007 has 52 weeks");
<add> test.equal(moment([2008]).weeksInYear(), 52, "2008 has 53 weeks");
<add> test.equal(moment([2009]).weeksInYear(), 52, "2009 has 53 weeks");
<add> test.equal(moment([2010]).weeksInYear(), 53, "2010 has 52 weeks");
<add> test.equal(moment([2011]).weeksInYear(), 52, "2011 has 52 weeks");
<add> test.equal(moment([2012]).weeksInYear(), 52, "2012 has 52 weeks");
<add> test.equal(moment([2013]).weeksInYear(), 52, "2013 has 52 weeks");
<add> test.equal(moment([2014]).weeksInYear(), 52, "2014 has 52 weeks");
<add> test.equal(moment([2015]).weeksInYear(), 52, "2015 has 53 weeks");
<add>
<add> test.done();
<add> },
<add>
<add> "weeksInYear doy/dow = 1/7": function (test) {
<add> moment.lang('1/7', {week: {dow: 1, doy: 7}});
<add>
<add> test.equal(moment([2004]).weeksInYear(), 52, "2004 has 53 weeks");
<add> test.equal(moment([2005]).weeksInYear(), 52, "2005 has 53 weeks");
<add> test.equal(moment([2006]).weeksInYear(), 53, "2006 has 53 weeks");
<add> test.equal(moment([2007]).weeksInYear(), 52, "2007 has 52 weeks");
<add> test.equal(moment([2008]).weeksInYear(), 52, "2008 has 53 weeks");
<add> test.equal(moment([2009]).weeksInYear(), 52, "2009 has 53 weeks");
<add> test.equal(moment([2010]).weeksInYear(), 52, "2010 has 52 weeks");
<add> test.equal(moment([2011]).weeksInYear(), 52, "2011 has 52 weeks");
<add> test.equal(moment([2012]).weeksInYear(), 53, "2012 has 52 weeks");
<add> test.equal(moment([2013]).weeksInYear(), 52, "2013 has 52 weeks");
<add> test.equal(moment([2014]).weeksInYear(), 52, "2014 has 52 weeks");
<add> test.equal(moment([2015]).weeksInYear(), 52, "2015 has 53 weeks");
<add>
<add> test.done();
<add> },
<add>
<add> "weeksInYear doy/dow = 0/6": function (test) {
<add> moment.lang('0/6', {week: {dow: 0, doy: 6}});
<add>
<add> test.equal(moment([2004]).weeksInYear(), 52, "2004 has 53 weeks");
<add> test.equal(moment([2005]).weeksInYear(), 53, "2005 has 53 weeks");
<add> test.equal(moment([2006]).weeksInYear(), 52, "2006 has 53 weeks");
<add> test.equal(moment([2007]).weeksInYear(), 52, "2007 has 52 weeks");
<add> test.equal(moment([2008]).weeksInYear(), 52, "2008 has 53 weeks");
<add> test.equal(moment([2009]).weeksInYear(), 52, "2009 has 53 weeks");
<add> test.equal(moment([2010]).weeksInYear(), 52, "2010 has 52 weeks");
<add> test.equal(moment([2011]).weeksInYear(), 53, "2011 has 52 weeks");
<add> test.equal(moment([2012]).weeksInYear(), 52, "2012 has 52 weeks");
<add> test.equal(moment([2013]).weeksInYear(), 52, "2013 has 52 weeks");
<add> test.equal(moment([2014]).weeksInYear(), 52, "2014 has 52 weeks");
<add> test.equal(moment([2015]).weeksInYear(), 52, "2015 has 53 weeks");
<add>
<add> test.done();
<add> }
<add>}; | 2 |
PHP | PHP | add throttle middleware | 1d0853b638a6fb0594cc0a3b5154072aa76e9e2e | <ide><path>app/Http/Kernel.php
<ide> class Kernel extends HttpKernel
<ide> 'auth' => \App\Http\Middleware\Authenticate::class,
<ide> 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
<ide> 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
<add> 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
<ide> ];
<ide> } | 1 |
Java | Java | remove support for declaring class proxies hints | 9846d28ae625fffb0105c0e15f175935aba64fa2 | <ide><path>spring-core/src/main/java/org/springframework/aot/hint/ClassProxyHint.java
<del>/*
<del> * Copyright 2002-2022 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * https://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.aot.hint;
<del>
<del>import java.util.Arrays;
<del>import java.util.LinkedList;
<del>import java.util.List;
<del>import java.util.Objects;
<del>
<del>import org.springframework.lang.Nullable;
<del>
<del>/**
<del> * A hint that describes the need for a proxy against a concrete class.
<del> *
<del> * @author Stephane Nicoll
<del> * @author Brian Clozel
<del> * @since 6.0
<del> */
<del>public final class ClassProxyHint implements ConditionalHint {
<del>
<del> private final TypeReference targetClass;
<del>
<del> private final List<TypeReference> proxiedInterfaces;
<del>
<del> @Nullable
<del> private final TypeReference reachableType;
<del>
<del>
<del> private ClassProxyHint(Builder builder) {
<del> this.targetClass = builder.targetClass;
<del> this.proxiedInterfaces = builder.proxiedInterfaces.stream().distinct().toList();
<del> this.reachableType = builder.reachableType;
<del> }
<del>
<del> /**
<del> * Initialize a builder with the target class to use.
<del> * @param typeReference the type reference for the target class of the proxy
<del> * @return a builder for the hint
<del> */
<del> public static Builder of(TypeReference typeReference) {
<del> return new Builder(typeReference);
<del> }
<del>
<del> /**
<del> * Initialize a builder with the target class to use.
<del> * @param targetClass the target class of the proxy
<del> * @return a builder for the hint
<del> */
<del> public static Builder of(Class<?> targetClass) {
<del> if (targetClass.isInterface()) {
<del> throw new IllegalArgumentException("Should not be an interface: " + targetClass);
<del> }
<del> return of(TypeReference.of(targetClass));
<del> }
<del>
<del> /**
<del> * Return the target class of the proxy.
<del> * @return the target class
<del> */
<del> public TypeReference getTargetClass() {
<del> return this.targetClass;
<del> }
<del>
<del> /**
<del> * Return the interfaces to be proxied.
<del> * @return the interfaces that the proxy should implement
<del> */
<del> public List<TypeReference> getProxiedInterfaces() {
<del> return this.proxiedInterfaces;
<del> }
<del>
<del> @Nullable
<del> @Override
<del> public TypeReference getReachableType() {
<del> return this.reachableType;
<del> }
<del>
<del> @Override
<del> public boolean equals(Object o) {
<del> if (this == o) {
<del> return true;
<del> }
<del> if (o == null || getClass() != o.getClass()) {
<del> return false;
<del> }
<del> ClassProxyHint that = (ClassProxyHint) o;
<del> return this.targetClass.equals(that.targetClass)
<del> && this.proxiedInterfaces.equals(that.proxiedInterfaces)
<del> && Objects.equals(this.reachableType, that.reachableType);
<del> }
<del>
<del> @Override
<del> public int hashCode() {
<del> return Objects.hash(this.targetClass, this.proxiedInterfaces);
<del> }
<del>
<del>
<del> /**
<del> * Builder for {@link ClassProxyHint}.
<del> */
<del> public static class Builder {
<del>
<del> private final TypeReference targetClass;
<del>
<del> private final LinkedList<TypeReference> proxiedInterfaces = new LinkedList<>();
<del>
<del> @Nullable
<del> private TypeReference reachableType;
<del>
<del>
<del> Builder(TypeReference targetClass) {
<del> this.targetClass = targetClass;
<del> }
<del>
<del> /**
<del> * Add the specified interfaces that the proxy should implement.
<del> * @param proxiedInterfaces the interfaces the proxy should implement
<del> * @return {@code this}, to facilitate method chaining
<del> */
<del> public Builder proxiedInterfaces(TypeReference... proxiedInterfaces) {
<del> this.proxiedInterfaces.addAll(Arrays.asList(proxiedInterfaces));
<del> return this;
<del> }
<del>
<del> /**
<del> * Add the specified interfaces that the proxy should implement.
<del> * @param proxiedInterfaces the interfaces the proxy should implement
<del> * @return {@code this}, to facilitate method chaining
<del> */
<del> public Builder proxiedInterfaces(Class<?>... proxiedInterfaces) {
<del> this.proxiedInterfaces.addAll(Arrays.stream(proxiedInterfaces)
<del> .map(TypeReference::of).toList());
<del> return this;
<del> }
<del>
<del> /**
<del> * Make this hint conditional on the fact that the specified type
<del> * can be resolved.
<del> * @param reachableType the type that should be reachable for this
<del> * hint to apply
<del> * @return {@code this}, to facilitate method chaining
<del> */
<del> public Builder onReachableType(TypeReference reachableType) {
<del> this.reachableType = reachableType;
<del> return this;
<del> }
<del>
<del> /**
<del> * Create a {@link ClassProxyHint} based on the state of this builder.
<del> * @return a class proxy hint
<del> */
<del> ClassProxyHint build() {
<del> return new ClassProxyHint(this);
<del> }
<del>
<del> }
<del>
<del>}
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/ProxyHints.java
<ide> import java.util.function.Consumer;
<ide> import java.util.stream.Stream;
<ide>
<del>import org.springframework.aot.hint.ClassProxyHint.Builder;
<del>
<ide> /**
<ide> * Gather the need for using proxies at runtime.
<ide> *
<ide> public class ProxyHints {
<ide>
<ide> private final Set<JdkProxyHint> jdkProxies = new LinkedHashSet<>();
<ide>
<del> private final Set<ClassProxyHint> classProxies = new LinkedHashSet<>();
<del>
<ide>
<ide> /**
<ide> * Return the interface-based proxies that are required.
<ide> public Stream<JdkProxyHint> jdkProxies() {
<ide> return this.jdkProxies.stream();
<ide> }
<ide>
<del> /**
<del> * Return the class-based proxies that are required.
<del> * @return a stream of {@link ClassProxyHint}
<del> */
<del> public Stream<ClassProxyHint> classProxies() {
<del> return this.classProxies.stream();
<del> }
<del>
<ide> /**
<ide> * Register a {@link JdkProxyHint}.
<ide> * @param jdkProxyHint the consumer of the hint builder
<ide> public ProxyHints registerJdkProxy(Class<?>... proxiedInterfaces) {
<ide> jdkProxyHint.proxiedInterfaces(proxiedInterfaces));
<ide> }
<ide>
<del> /**
<del> * Register that a class proxy is required for the class defined by the
<del> * specified {@link TypeReference}.
<del> * @param typeReference the type reference for the target class of the proxy
<del> * @param classProxyHint a builder to further customize the hint for that proxy
<del> * @return {@code this}, to facilitate method chaining
<del> */
<del> public ProxyHints registerClassProxy(TypeReference typeReference, Consumer<Builder> classProxyHint) {
<del> return addClassProxyHint(ClassProxyHint.of(typeReference), classProxyHint);
<del> }
<del>
<del> /**
<del> * Register that a class proxy is required for the specified class.
<del> * @param targetClass the target class of the proxy
<del> * @param classProxyHint a builder to further customize the hint for that proxy
<del> * @return {@code this}, to facilitate method chaining
<del> */
<del> public ProxyHints registerClassProxy(Class<?> targetClass, Consumer<Builder> classProxyHint) {
<del> return addClassProxyHint(ClassProxyHint.of(targetClass), classProxyHint);
<del> }
<del>
<del> private ProxyHints addClassProxyHint(ClassProxyHint.Builder builder, Consumer<ClassProxyHint.Builder> classProxyHint) {
<del> classProxyHint.accept(builder);
<del> this.classProxies.add(builder.build());
<del> return this;
<del> }
<del>
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/aot/hint/ClassProxyHintTests.java
<del>/*
<del> * Copyright 2002-2022 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * https://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.aot.hint;
<del>
<del>import java.io.Closeable;
<del>import java.io.Serializable;
<del>import java.util.Hashtable;
<del>import java.util.Properties;
<del>import java.util.function.Function;
<del>
<del>import org.junit.jupiter.api.Test;
<del>
<del>import org.springframework.aot.hint.JdkProxyHint.Builder;
<del>
<del>import static org.assertj.core.api.Assertions.assertThat;
<del>
<del>/**
<del> * Tests for {@link ClassProxyHint}.
<del> *
<del> * @author Stephane Nicoll
<del> * @author Brian Clozel
<del> */
<del>class ClassProxyHintTests {
<del>
<del> @Test
<del> void equalsWithSameInstanceIsTrue() {
<del> ClassProxyHint hint = ClassProxyHint.of(Properties.class).build();
<del> assertThat(hint).isEqualTo(hint);
<del> }
<del>
<del> @Test
<del> void equalsWithSameTargetClassIsTrue() {
<del> ClassProxyHint first = ClassProxyHint.of(Properties.class).build();
<del> ClassProxyHint second = ClassProxyHint.of(TypeReference.of(Properties.class)).build();
<del> assertThat(first).isEqualTo(second);
<del> }
<del>
<del> @Test
<del> void equalsWithSameProxiedInterfacesIsTrue() {
<del> ClassProxyHint first = ClassProxyHint.of(Properties.class)
<del> .proxiedInterfaces(Serializable.class).build();
<del> ClassProxyHint second = ClassProxyHint.of(Properties.class)
<del> .proxiedInterfaces(TypeReference.of(Serializable.class)).build();
<del> assertThat(first).isEqualTo(second);
<del> }
<del>
<del> @Test
<del> void equalsWithDifferentTargetClassIsFalse() {
<del> ClassProxyHint first = ClassProxyHint.of(Properties.class).build();
<del> ClassProxyHint second = ClassProxyHint.of(Hashtable.class).build();
<del> assertThat(first).isNotEqualTo(second);
<del> }
<del>
<del> @Test
<del> void equalsWithSameProxiedInterfacesDifferentOrderIsFalse() {
<del> ClassProxyHint first = ClassProxyHint.of(Properties.class)
<del> .proxiedInterfaces(Serializable.class, Closeable.class).build();
<del> ClassProxyHint second = ClassProxyHint.of(Properties.class)
<del> .proxiedInterfaces(TypeReference.of(Closeable.class), TypeReference.of(Serializable.class))
<del> .build();
<del> assertThat(first).isNotEqualTo(second);
<del> }
<del>
<del> @Test
<del> void equalsWithDifferentProxiedInterfacesIsFalse() {
<del> ClassProxyHint first = ClassProxyHint.of(Properties.class)
<del> .proxiedInterfaces(Serializable.class).build();
<del> ClassProxyHint second = ClassProxyHint.of(Properties.class)
<del> .proxiedInterfaces(TypeReference.of(Closeable.class)).build();
<del> assertThat(first).isNotEqualTo(second);
<del> }
<del>
<del> @Test
<del> void equalsWithNonClassProxyHintIsFalse() {
<del> ClassProxyHint first = ClassProxyHint.of(Properties.class).build();
<del> JdkProxyHint second = new Builder().proxiedInterfaces(Function.class).build();
<del> assertThat(first).isNotEqualTo(second);
<del> }
<del>
<del> @Test
<del> void equalsWithDifferentConditionIsFalse() {
<del> ClassProxyHint first = ClassProxyHint.of(Properties.class).build();
<del> ClassProxyHint second = ClassProxyHint.of(Properties.class).onReachableType(TypeReference.of("org.example.test")).build();
<del> assertThat(first).isNotEqualTo(second);
<del> }
<del>
<del>}
<ide><path>spring-core/src/test/java/org/springframework/aot/hint/ProxyHintsTests.java
<ide>
<ide> package org.springframework.aot.hint;
<ide>
<del>import java.io.Serializable;
<ide> import java.util.Arrays;
<del>import java.util.Properties;
<ide> import java.util.function.Consumer;
<ide> import java.util.function.Function;
<ide>
<ide> void registerJdkProxyTwiceExposesOneHint() {
<ide> assertThat(this.proxyHints.jdkProxies()).singleElement().satisfies(proxiedInterfaces(Function.class));
<ide> }
<ide>
<del> @Test
<del> void registerClassProxyWithTargetClassName() {
<del> this.proxyHints.registerClassProxy(TypeReference.of(Properties.class.getName()), classProxyHint ->
<del> classProxyHint.proxiedInterfaces(Serializable.class));
<del> assertThat(this.proxyHints.classProxies()).singleElement().satisfies(classProxyHint -> {
<del> assertThat(classProxyHint.getTargetClass()).isEqualTo(TypeReference.of(Properties.class));
<del> assertThat(classProxyHint.getProxiedInterfaces()).containsOnly(TypeReference.of(Serializable.class));
<del> });
<del> }
<del>
<del> @Test
<del> void registerClassProxyWithTargetClass() {
<del> this.proxyHints.registerClassProxy(Properties.class, classProxyHint ->
<del> classProxyHint.proxiedInterfaces(Serializable.class));
<del> assertThat(this.proxyHints.classProxies()).singleElement().satisfies(classProxyHint -> {
<del> assertThat(classProxyHint.getTargetClass()).isEqualTo(TypeReference.of(Properties.class));
<del> assertThat(classProxyHint.getProxiedInterfaces()).containsOnly(TypeReference.of(Serializable.class));
<del> });
<del> }
<del>
<del> @Test
<del> void registerClassProxyWithTargetInterface() {
<del> assertThatIllegalArgumentException()
<del> .isThrownBy(() -> this.proxyHints.registerClassProxy(Serializable.class, classProxyHint -> {}))
<del> .withMessageContaining(Serializable.class.getName());
<del> }
<del>
<ide>
<ide> private static Consumer<JdkProxyHint.Builder> springProxy(String proxiedInterface) {
<ide> return builder -> builder.proxiedInterfaces(toTypeReferences(
<ide> private static TypeReference[] toTypeReferences(Class<?>... proxiedInterfaces) {
<ide> sealed interface SealedInterface {
<ide> }
<ide>
<add> @SuppressWarnings("unused")
<ide> static final class SealedClass implements SealedInterface {
<ide> }
<ide> | 4 |
Python | Python | fix libcloud_debug mode | 4e382378fccb78702b85f357363f5c660f2d7c17 | <ide><path>libcloud/common/base.py
<ide> class fakesock:
<ide> def __init__(self, s):
<ide> self.s = s
<ide> def makefile(self, mode, foo):
<del> return StringIO.StringIO(self.s)
<add> return StringIO(self.s)
<ide> rr = r
<ide> if r.chunked:
<ide> ht += "%x\r\n" % (len(body)) | 1 |
Javascript | Javascript | parse certificates separately | 5fe16ada3d3cbf16431056c9f750180de007e496 | <ide><path>tools/challenge-md-parser/tests-to-data.js
<ide> function plugin() {
<ide> );
<ide> tests.question.text = mdToHTML(tests.question.text);
<ide> }
<del> if (tests.tests) {
<add> // since tests are overloaded (they're both a list of projects and
<add> // actual tests), it's necessary to check which they are:
<add> if (tests.tests && tests.tests[0] && tests.tests[0].text) {
<ide> tests.tests = tests.tests.map(({ text, testString }) => ({
<ide> text: mdToHTML(text),
<ide> testString | 1 |
PHP | PHP | apply fixes from styleci | 8a39838353ccd460a93252b9c7c114e9790d24a7 | <ide><path>src/Illuminate/Support/Testing/Fakes/MailFake.php
<ide>
<ide> namespace Illuminate\Support\Testing\Fakes;
<ide>
<del>use Illuminate\Support\Collection;
<del>use Illuminate\Container\Container;
<ide> use Illuminate\Contracts\Mail\Mailer;
<ide> use Illuminate\Contracts\Mail\Mailable;
<ide> use PHPUnit_Framework_Assert as PHPUnit; | 1 |
PHP | PHP | use expression instead of numeric value | 142a84d83793b84f644d4c0d495dea40e18514bf | <ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php
<ide> protected function whereNotExists(Builder $query, $where)
<ide> */
<ide> protected function whereIn(Builder $query, $where)
<ide> {
<del> if (empty($where['values'])) return '0';
<add> if (empty($where['values'])) return '0=1';
<ide>
<ide> $values = $this->parameterize($where['values']);
<ide>
<ide> protected function whereIn(Builder $query, $where)
<ide> */
<ide> protected function whereNotIn(Builder $query, $where)
<ide> {
<del> if (empty($where['values'])) return '1';
<add> if (empty($where['values'])) return '1=1';
<ide>
<ide> $values = $this->parameterize($where['values']);
<ide>
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testEmptyWhereIns()
<ide> {
<ide> $builder = $this->getBuilder();
<ide> $builder->select('*')->from('users')->whereIn('id', array());
<del> $this->assertEquals('select * from "users" where 0', $builder->toSql());
<add> $this->assertEquals('select * from "users" where 0=1', $builder->toSql());
<ide> $this->assertEquals(array(), $builder->getBindings());
<ide>
<ide> $builder = $this->getBuilder();
<ide> $builder->select('*')->from('users')->where('id', '=', 1)->orWhereIn('id', array());
<del> $this->assertEquals('select * from "users" where "id" = ? or 0', $builder->toSql());
<add> $this->assertEquals('select * from "users" where "id" = ? or 0=1', $builder->toSql());
<ide> $this->assertEquals(array(0 => 1), $builder->getBindings());
<ide> }
<ide>
<ide> public function testEmptyWhereNotIns()
<ide> {
<ide> $builder = $this->getBuilder();
<ide> $builder->select('*')->from('users')->whereNotIn('id', array());
<del> $this->assertEquals('select * from "users" where 1', $builder->toSql());
<add> $this->assertEquals('select * from "users" where 1=1', $builder->toSql());
<ide> $this->assertEquals(array(), $builder->getBindings());
<ide>
<ide> $builder = $this->getBuilder();
<ide> $builder->select('*')->from('users')->where('id', '=', 1)->orWhereNotIn('id', array());
<del> $this->assertEquals('select * from "users" where "id" = ? or 1', $builder->toSql());
<add> $this->assertEquals('select * from "users" where "id" = ? or 1=1', $builder->toSql());
<ide> $this->assertEquals(array(0 => 1), $builder->getBindings());
<ide> }
<ide> | 2 |
Java | Java | fix contextpath request matching with pathpatterns | 5a4a677fbd05373d4a63c9b161128cb61cbc9feb | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractUrlHandlerMapping.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> protected Object lookupHandler(
<ide> // Pattern match?
<ide> List<PathPattern> matches = null;
<ide> for (PathPattern pattern : this.pathPatternHandlerMap.keySet()) {
<del> if (pattern.matches(path)) {
<add> if (pattern.matches(path.pathWithinApplication())) {
<ide> matches = (matches != null ? matches : new ArrayList<>());
<ide> matches.add(pattern);
<ide> }
<ide> protected Object lookupHandler(
<ide> handler = obtainApplicationContext().getBean(handlerName);
<ide> }
<ide> validateHandler(handler, request);
<del> PathContainer pathWithinMapping = pattern.extractPathWithinPattern(path);
<add> PathContainer pathWithinMapping = pattern.extractPathWithinPattern(path.pathWithinApplication());
<ide> return buildPathExposingHandler(handler, pattern.getPatternString(), pathWithinMapping.value(), null);
<ide> }
<ide>
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMappingTests.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> void checkMappings(String beanName) throws Exception {
<ide> assertThat(request.getAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("welcome.x");
<ide> assertThat(request.getAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE)).isEqualTo(otherBean);
<ide>
<add> request = PathPatternsTestUtils.initRequest("GET", "/app", "/welcome.x", usePathPatterns);
<add> chain = getHandler(hm, request);
<add> assertThat(chain.getHandler()).isSameAs(otherBean);
<add> assertThat(request.getAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("welcome.x");
<add> assertThat(request.getAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE)).isEqualTo(otherBean);
<add>
<ide> request = PathPatternsTestUtils.initRequest("GET", "/welcome/", usePathPatterns);
<ide> chain = getHandler(hm, request);
<ide> assertThat(chain.getHandler()).isSameAs(otherBean);
<ide> void checkMappings(String beanName) throws Exception {
<ide> chain = getHandler(hm, request);
<ide> assertThat(chain.getHandler()).isSameAs(bean);
<ide>
<add>
<ide> request = PathPatternsTestUtils.initRequest("GET", "/show.html", usePathPatterns);
<ide> chain = getHandler(hm, request);
<ide> assertThat(chain.getHandler()).isSameAs(bean); | 2 |
Mixed | Go | provide option to enabled deferred device deletion | 51e059e7e90f37848596a0b6ec83f7835e6e4131 | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> var (
<ide> logLevel = devicemapper.LogLevelFatal
<ide> driverDeferredRemovalSupport = false
<ide> enableDeferredRemoval = false
<add> enableDeferredDeletion = false
<ide> )
<ide>
<ide> const deviceSetMetaFile string = "deviceset-metadata"
<ide> type DeviceSet struct {
<ide> transaction `json:"-"`
<ide> overrideUdevSyncCheck bool
<ide> deferredRemove bool // use deferred removal
<add> deferredDelete bool // use deferred deletion
<ide> BaseDeviceUUID string //save UUID of base device
<ide> }
<ide>
<ide> type Status struct {
<ide> UdevSyncSupported bool
<ide> // DeferredRemoveEnabled is true then the device is not unmounted.
<ide> DeferredRemoveEnabled bool
<add> // True if deferred deletion is enabled. This is different from
<add> // deferred removal. "removal" means that device mapper device is
<add> // deactivated. Thin device is still in thin pool and can be activated
<add> // again. But "deletion" means that thin device will be deleted from
<add> // thin pool and it can't be activated again.
<add> DeferredDeleteEnabled bool
<ide> }
<ide>
<ide> // Structure used to export image/container metadata in docker inspect.
<ide> func (devices *DeviceSet) initDevmapper(doInit bool) error {
<ide> return graphdriver.ErrNotSupported
<ide> }
<ide>
<del> // If user asked for deferred removal and both library and driver
<del> // supports deferred removal use it.
<del> if enableDeferredRemoval && driverDeferredRemovalSupport && devicemapper.LibraryDeferredRemovalSupport == true {
<add> // If user asked for deferred removal then check both libdm library
<add> // and kernel driver support deferred removal otherwise error out.
<add> if enableDeferredRemoval {
<add> if !driverDeferredRemovalSupport {
<add> return fmt.Errorf("devmapper: Deferred removal can not be enabled as kernel does not support it")
<add> }
<add> if !devicemapper.LibraryDeferredRemovalSupport {
<add> return fmt.Errorf("devmapper: Deferred removal can not be enabled as libdm does not support it")
<add> }
<ide> logrus.Debugf("devmapper: Deferred removal support enabled.")
<ide> devices.deferredRemove = true
<ide> }
<ide>
<add> if enableDeferredDeletion {
<add> if !devices.deferredRemove {
<add> return fmt.Errorf("devmapper: Deferred deletion can not be enabled as deferred removal is not enabled. Enable deferred removal using --storage-opt dm.use_deferred_removal=true parameter")
<add> }
<add> logrus.Debugf("devmapper: Deferred deletion support enabled.")
<add> devices.deferredDelete = true
<add> }
<add>
<ide> // https://github.com/docker/docker/issues/4036
<ide> if supported := devicemapper.UdevSetSyncSupport(true); !supported {
<ide> logrus.Warn("Udev sync is not supported. This will lead to unexpected behavior, data loss and errors. For more information, see https://docs.docker.com/reference/commandline/daemon/#daemon-storage-driver-option")
<ide> func (devices *DeviceSet) Status() *Status {
<ide> status.MetadataLoopback = devices.metadataLoopFile
<ide> status.UdevSyncSupported = devicemapper.UdevSyncSupported()
<ide> status.DeferredRemoveEnabled = devices.deferredRemove
<add> status.DeferredDeleteEnabled = devices.deferredDelete
<ide>
<ide> totalSizeInSectors, _, dataUsed, dataTotal, metadataUsed, metadataTotal, err := devices.poolStatus()
<ide> if err == nil {
<ide> func NewDeviceSet(root string, doInit bool, options []string) (*DeviceSet, error
<ide> return nil, err
<ide> }
<ide>
<add> case "dm.use_deferred_deletion":
<add> enableDeferredDeletion, err = strconv.ParseBool(val)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<ide> default:
<ide> return nil, fmt.Errorf("Unknown option %s\n", key)
<ide> }
<ide><path>daemon/graphdriver/devmapper/driver.go
<ide> func (d *Driver) Status() [][2]string {
<ide> {"Metadata Space Available", fmt.Sprintf("%s", units.HumanSize(float64(s.Metadata.Available)))},
<ide> {"Udev Sync Supported", fmt.Sprintf("%v", s.UdevSyncSupported)},
<ide> {"Deferred Removal Enabled", fmt.Sprintf("%v", s.DeferredRemoveEnabled)},
<add> {"Deferred Deletion Enabled", fmt.Sprintf("%v", s.DeferredDeleteEnabled)},
<ide> }
<ide> if len(s.DataLoopback) > 0 {
<ide> status = append(status, [2]string{"Data loop file", s.DataLoopback})
<ide><path>docs/reference/commandline/daemon.md
<ide> options for `zfs` start with `zfs`.
<ide> > Otherwise, set this flag for migrating existing Docker daemons to
<ide> > a daemon with a supported environment.
<ide>
<add> * `dm.use_deferred_removal`
<add>
<add> Enables use of deferred device removal if `libdm` and the kernel driver
<add> support the mechanism.
<add>
<add> Deferred device removal means that if device is busy when devices are
<add> being removed/deactivated, then a deferred removal is scheduled on
<add> device. And devices automatically go away when last user of the device
<add> exits.
<add>
<add> For example, when a container exits, its associated thin device is removed.
<add> If that device has leaked into some other mount namespace and can't be
<add> removed, the container exit still succeeds and this option causes the
<add> system to schedule the device for deferred removal. It does not wait in a
<add> loop trying to remove a busy device.
<add>
<add> Example use: `docker daemon --storage-opt dm.use_deferred_removal=true`
<add>
<add> * `dm.use_deferred_deletion`
<add>
<add> Enables use of deferred device deletion for thin pool devices. By default,
<add> thin pool device deletion is synchronous. Before a container is deleted,
<add> the Docker daemon removes any associated devices. If the storage driver
<add> can not remove a device, the container deletion fails and daemon returns.
<add>
<add> `Error deleting container: Error response from daemon: Cannot destroy container`
<add>
<add> To avoid this failure, enable both deferred device deletion and deferred
<add> device removal on the daemon.
<add>
<add> `docker daemon --storage-opt dm.use_deferred_deletion=true --storage-opt dm.use_deferred_removal=true`
<add>
<add> With these two options enabled, if a device is busy when the driver is
<add> deleting a container, the driver marks the device as deleted. Later, when
<add> the device isn't in use, the driver deletes it.
<add>
<add> In general it should be safe to enable this option by default. It will help
<add> when unintentional leaking of mount point happens across multiple mount
<add> namespaces.
<add>
<ide> Currently supported options of `zfs`:
<ide>
<ide> * `zfs.fsname`
<ide><path>man/docker-daemon.8.md
<ide> device.
<ide>
<ide> Example use: `docker daemon --storage-opt dm.use_deferred_removal=true`
<ide>
<add>#### dm.use_deferred_deletion
<add>
<add>Enables use of deferred device deletion for thin pool devices. By default,
<add>thin pool device deletion is synchronous. Before a container is deleted, the
<add>Docker daemon removes any associated devices. If the storage driver can not
<add>remove a device, the container deletion fails and daemon returns.
<add>
<add>`Error deleting container: Error response from daemon: Cannot destroy container`
<add>
<add>To avoid this failure, enable both deferred device deletion and deferred
<add>device removal on the daemon.
<add>
<add>`docker daemon --storage-opt dm.use_deferred_deletion=true --storage-opt dm.use_deferred_removal=true`
<add>
<add>With these two options enabled, if a device is busy when the driver is
<add>deleting a container, the driver marks the device as deleted. Later, when the
<add>device isn't in use, the driver deletes it.
<add>
<add>In general it should be safe to enable this option by default. It will help
<add>when unintentional leaking of mount point happens across multiple mount
<add>namespaces.
<add>
<ide> #### dm.loopdatasize
<ide>
<ide> **Note**: This option configures devicemapper loopback, which should not be used in production. | 4 |
PHP | PHP | fix failing test in databasesession | a2a3b02c10064c462dac34f741d484b2fe43f62c | <ide><path>Cake/Network/Session/DatabaseSession.php
<ide> public function __construct() {
<ide> $modelAlias = Configure::read('Session.handler.model');
<ide>
<ide> if (empty($modelAlias)) {
<del> $this->_table = TableRegistry::get('Sessions', [
<del> 'table' => 'cake_sessions',
<del> ]);
<add> $config = TableRegistry::exists('Sessions') ? [] : ['table' => 'cake_sessions'];
<add> $this->_table = TableRegistry::get('Sessions', $config);
<ide> } else {
<ide> $this->_table = TableRegistry::get($modelAlias);
<ide> } | 1 |
Python | Python | remove unused ioerror exception var | 90a0c9e6354c9a6da26f18675b0e8482c2a9e281 | <ide><path>libcloud/ssh.py
<ide> def put(self, path, contents=None, chmod=None):
<ide> if part != "":
<ide> try:
<ide> sftp.mkdir(part)
<del> except IOError, e:
<del> # so, there doens't seem to be a way to
<add> except IOError:
<add> # so, there doesn't seem to be a way to
<ide> # catch EEXIST consistently *sigh*
<ide> pass
<ide> sftp.chdir(part) | 1 |
Java | Java | add create shortcut to rsocketstrategies | c456950bc3d2611e34154afc87193b3cc9e1f7a8 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketStrategies.java
<ide> default <T> Decoder<T> decoder(ResolvableType elementType, @Nullable MimeType mi
<ide> */
<ide> ReactiveAdapterRegistry reactiveAdapterRegistry();
<ide>
<add> /**
<add> * Return a builder to create a new {@link RSocketStrategies} instance
<add> * replicated from the current instance.
<add> */
<add> default Builder mutate() {
<add> return new DefaultRSocketStrategies.DefaultRSocketStrategiesBuilder(this);
<add> }
<add>
<ide>
<ide> /**
<del> * Return a builder to build a new {@code RSocketStrategies} instance.
<add> * Create an {@code RSocketStrategies} instance with default settings.
<add> * Equivalent to {@code RSocketStrategies.builder().build()}.
<ide> */
<del> static Builder builder() {
<del> return new DefaultRSocketStrategies.DefaultRSocketStrategiesBuilder();
<add> static RSocketStrategies create() {
<add> return new DefaultRSocketStrategies.DefaultRSocketStrategiesBuilder().build();
<ide> }
<ide>
<ide> /**
<del> * Return a builder to create a new {@link RSocketStrategies} instance
<del> * replicated from the current instance.
<add> * Return a builder to build a new {@code RSocketStrategies} instance.
<add> * The builder applies default settings, see individual builder methods for
<add> * details.
<ide> */
<del> default Builder mutate() {
<del> return new DefaultRSocketStrategies.DefaultRSocketStrategiesBuilder(this);
<add> static Builder builder() {
<add> return new DefaultRSocketStrategies.DefaultRSocketStrategiesBuilder();
<ide> }
<ide>
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketBufferLeakTests.java
<ide> import io.rsocket.AbstractRSocket;
<ide> import io.rsocket.RSocket;
<ide> import io.rsocket.RSocketFactory;
<add>import io.rsocket.SocketAcceptor;
<ide> import io.rsocket.frame.decoder.PayloadDecoder;
<ide> import io.rsocket.plugins.RSocketInterceptor;
<ide> import io.rsocket.transport.netty.server.CloseableChannel;
<ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<del>import org.springframework.core.codec.CharSequenceEncoder;
<del>import org.springframework.core.codec.StringDecoder;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
<ide> import org.springframework.messaging.handler.annotation.MessageMapping;
<ide> public class RSocketBufferLeakTests {
<ide> @BeforeClass
<ide> @SuppressWarnings("ConstantConditions")
<ide> public static void setupOnce() {
<add>
<ide> context = new AnnotationConfigApplicationContext(ServerConfig.class);
<add> RSocketMessageHandler messageHandler = context.getBean(RSocketMessageHandler.class);
<add> SocketAcceptor responder = messageHandler.serverResponder();
<ide>
<ide> server = RSocketFactory.receive()
<ide> .frameDecoder(PayloadDecoder.ZERO_COPY)
<ide> .addResponderPlugin(payloadInterceptor) // intercept responding
<del> .acceptor(context.getBean(RSocketMessageHandler.class).serverResponder())
<add> .acceptor(responder)
<ide> .transport(TcpServerTransport.create("localhost", 7000))
<ide> .start()
<ide> .block();
<ide>
<ide> requester = RSocketRequester.builder()
<del> .rsocketFactory(factory -> {
<del> factory.frameDecoder(PayloadDecoder.ZERO_COPY);
<del> factory.addRequesterPlugin(payloadInterceptor); // intercept outgoing requests
<del> })
<add> .rsocketFactory(factory -> factory.addRequesterPlugin(payloadInterceptor))
<ide> .rsocketStrategies(context.getBean(RSocketStrategies.class))
<ide> .connectTcp("localhost", 7000)
<ide> .block();
<ide> public RSocketMessageHandler messageHandler() {
<ide> @Bean
<ide> public RSocketStrategies rsocketStrategies() {
<ide> return RSocketStrategies.builder()
<del> .decoder(StringDecoder.allMimeTypes())
<del> .encoder(CharSequenceEncoder.allMimeTypes())
<ide> .dataBufferFactory(new LeakAwareNettyDataBufferFactory(PooledByteBufAllocator.DEFAULT))
<ide> .build();
<ide> }
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketClientToServerIntegrationTests.java
<ide>
<ide> import java.time.Duration;
<ide>
<del>import io.netty.buffer.PooledByteBufAllocator;
<ide> import io.rsocket.RSocketFactory;
<add>import io.rsocket.SocketAcceptor;
<ide> import io.rsocket.frame.decoder.PayloadDecoder;
<ide> import io.rsocket.transport.netty.server.CloseableChannel;
<ide> import io.rsocket.transport.netty.server.TcpServerTransport;
<ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<del>import org.springframework.core.codec.CharSequenceEncoder;
<del>import org.springframework.core.codec.StringDecoder;
<del>import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
<ide> import org.springframework.messaging.handler.annotation.MessageMapping;
<ide> import org.springframework.messaging.rsocket.annotation.support.RSocketMessageHandler;
<ide> public class RSocketClientToServerIntegrationTests {
<ide> @BeforeClass
<ide> @SuppressWarnings("ConstantConditions")
<ide> public static void setupOnce() {
<add>
<ide> context = new AnnotationConfigApplicationContext(ServerConfig.class);
<add> RSocketMessageHandler messageHandler = context.getBean(RSocketMessageHandler.class);
<add> SocketAcceptor responder = messageHandler.serverResponder();
<ide>
<ide> server = RSocketFactory.receive()
<ide> .addResponderPlugin(interceptor)
<ide> .frameDecoder(PayloadDecoder.ZERO_COPY)
<del> .acceptor(context.getBean(RSocketMessageHandler.class).serverResponder())
<add> .acceptor(responder)
<ide> .transport(TcpServerTransport.create("localhost", 7000))
<ide> .start()
<ide> .block();
<ide>
<ide> requester = RSocketRequester.builder()
<del> .rsocketFactory(factory -> factory.frameDecoder(PayloadDecoder.ZERO_COPY))
<ide> .rsocketStrategies(context.getBean(RSocketStrategies.class))
<ide> .connectTcp("localhost", 7000)
<ide> .block();
<ide> public RSocketMessageHandler messageHandler() {
<ide>
<ide> @Bean
<ide> public RSocketStrategies rsocketStrategies() {
<del> return RSocketStrategies.builder()
<del> .decoder(StringDecoder.allMimeTypes())
<del> .encoder(CharSequenceEncoder.allMimeTypes())
<del> .dataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT))
<del> .build();
<add> return RSocketStrategies.create();
<ide> }
<ide> }
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketServerToClientIntegrationTests.java
<ide>
<ide> import java.time.Duration;
<ide>
<del>import io.netty.buffer.PooledByteBufAllocator;
<ide> import io.rsocket.RSocketFactory;
<add>import io.rsocket.SocketAcceptor;
<ide> import io.rsocket.frame.decoder.PayloadDecoder;
<ide> import io.rsocket.transport.netty.server.CloseableChannel;
<ide> import io.rsocket.transport.netty.server.TcpServerTransport;
<ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<del>import org.springframework.core.codec.CharSequenceEncoder;
<del>import org.springframework.core.codec.StringDecoder;
<del>import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.messaging.handler.annotation.MessageMapping;
<ide> import org.springframework.messaging.rsocket.annotation.ConnectMapping;
<ide> import org.springframework.messaging.rsocket.annotation.support.AnnotationClientResponderConfigurer;
<ide> public class RSocketServerToClientIntegrationTests {
<ide> @BeforeClass
<ide> @SuppressWarnings("ConstantConditions")
<ide> public static void setupOnce() {
<add>
<ide> context = new AnnotationConfigApplicationContext(RSocketConfig.class);
<add> RSocketMessageHandler messageHandler = context.getBean(RSocketMessageHandler.class);
<add> SocketAcceptor responder = messageHandler.serverResponder();
<ide>
<ide> server = RSocketFactory.receive()
<ide> .frameDecoder(PayloadDecoder.ZERO_COPY)
<del> .acceptor(context.getBean(RSocketMessageHandler.class).serverResponder())
<add> .acceptor(responder)
<ide> .transport(TcpServerTransport.create("localhost", 0))
<ide> .start()
<ide> .block();
<ide> private static void connectAndRunTest(String connectionRoute) {
<ide>
<ide> ServerController serverController = context.getBean(ServerController.class);
<ide> serverController.reset();
<del> RSocketStrategies strategies = context.getBean(RSocketStrategies.class);
<ide>
<ide> RSocketRequester requester = null;
<ide> try {
<del> ClientRSocketFactoryConfigurer responderConfigurer =
<del> AnnotationClientResponderConfigurer.withHandlers(new ClientHandler());
<del>
<ide> requester = RSocketRequester.builder()
<ide> .rsocketFactory(factory -> {
<ide> factory.metadataMimeType("text/plain");
<ide> factory.setupPayload(ByteBufPayload.create("", connectionRoute));
<del> factory.frameDecoder(PayloadDecoder.ZERO_COPY);
<ide> })
<del> .rsocketFactory(responderConfigurer)
<del> .rsocketStrategies(strategies)
<add> .rsocketFactory(AnnotationClientResponderConfigurer.withHandlers(new ClientHandler()))
<add> .rsocketStrategies(context.getBean(RSocketStrategies.class))
<ide> .connectTcp("localhost", server.address().getPort())
<ide> .block();
<ide>
<ide> public RSocketMessageHandler serverMessageHandler() {
<ide>
<ide> @Bean
<ide> public RSocketStrategies rsocketStrategies() {
<del> return RSocketStrategies.builder()
<del> .decoder(StringDecoder.allMimeTypes())
<del> .encoder(CharSequenceEncoder.allMimeTypes())
<del> .dataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT))
<del> .build();
<add> return RSocketStrategies.create();
<ide> }
<ide> }
<ide> | 4 |
Python | Python | specialize loadtxt packer for uniform-dtype data | 009e4cad006f705635d35309fdeac434dd734c17 | <ide><path>numpy/lib/npyio.py
<ide> def floatconv(x):
<ide>
<ide> # not to be confused with the flatten_dtype we import...
<ide> def _loadtxt_flatten_dtype_internal(dt):
<del> """Unpack a structured data-type, and produce re-packing info."""
<add> """Unpack a structured data-type, and produce a packer function."""
<ide> if dt.names is None:
<ide> # If the dtype is flattened, return.
<ide> # If the dtype has a shape, the dtype occurs
<ide> def _loadtxt_flatten_dtype_internal(dt):
<ide> if len(shape) > 1:
<ide> for dim in dt.shape[-2::-1]:
<ide> packing = [(dim*packing[0][0], packing*dim)]
<del> return ([dt.base] * int(np.prod(dt.shape)), packing)
<add> return ([dt.base] * int(np.prod(dt.shape)),
<add> functools.partial(_loadtxt_pack_items, packing))
<ide> else:
<ide> types = []
<ide> packing = []
<ide> for field in dt.names:
<ide> tp, bytes = dt.fields[field]
<del> flat_dt, flat_packing = _loadtxt_flatten_dtype_internal(tp)
<add> flat_dt, flat_packer = _loadtxt_flatten_dtype_internal(tp)
<ide> types.extend(flat_dt)
<add> flat_packing = flat_packer.args[0] if flat_packer else None
<ide> # Avoid extra nesting for subarrays
<ide> if tp.ndim > 0:
<ide> packing.extend(flat_packing)
<ide> else:
<ide> packing.append((len(flat_dt), flat_packing))
<del> return (types, packing)
<add> return (types, functools.partial(_loadtxt_pack_items, packing))
<ide>
<ide>
<del>def _loadtxt_pack_items(items, packing):
<add>def _loadtxt_pack_items(packing, items):
<ide> """Pack items into nested lists based on re-packing info."""
<ide> if packing is None:
<ide> return items[0]
<ide> def _loadtxt_pack_items(items, packing):
<ide> ret = []
<ide> for length, subpacking in packing:
<ide> ret.append(
<del> _loadtxt_pack_items(items[start:start+length], subpacking))
<add> _loadtxt_pack_items(subpacking, items[start:start+length]))
<ide> start += length
<ide> return tuple(ret)
<ide>
<ide> def read_data(chunk_size):
<ide> items = [conv(val) for (conv, val) in zip(converters, vals)]
<ide>
<ide> # Then pack it according to the dtype's nesting
<del> items = _loadtxt_pack_items(items, packing)
<add> items = packer(items)
<ide> X.append(items)
<ide> if len(X) > chunk_size:
<ide> yield X
<ide> def read_data(chunk_size):
<ide> dtype = np.dtype(dtype)
<ide> defconv = _getconv(dtype)
<ide>
<del> dtype_types, packing = _loadtxt_flatten_dtype_internal(dtype)
<add> dtype_types, packer = _loadtxt_flatten_dtype_internal(dtype)
<ide>
<ide> fown = False
<ide> try:
<ide> def read_data(chunk_size):
<ide> # the dtype matches a column
<ide> converters = [_getconv(dt) for dt in dtype_types]
<ide> else:
<del> # All fields have the same dtype
<add> # All fields have the same dtype; use specialized packers which are
<add> # much faster than those using _loadtxt_pack_items.
<ide> converters = [defconv for i in range(N)]
<del> if N > 1:
<del> packing = [(N, tuple)]
<add> if N == 1:
<add> packer = itemgetter(0)
<add> else:
<add> def packer(row): return row
<ide>
<ide> # By preference, use the converters specified by the user
<ide> for i, conv in (user_converters or {}).items(): | 1 |
Javascript | Javascript | handle undefined input to mergekeyset | 5b1e4c0324c984be96d4792b1ed13d457862a5bd | <ide><path>src/addons/transitions/ReactTransitionGroup.js
<ide> var ReactTransitionGroupMixin = {
<ide> 'getTransitionConfig() method.'
<ide> );
<ide>
<del> // don't animate undefined children
<del> if (typeof sourceChildren === 'undefined') {
<del> return;
<del> }
<del>
<ide> var children = {};
<ide> var childMapping = ReactTransitionKeySet.getChildMapping(sourceChildren);
<add>
<ide> var transitionConfig = this.getTransitionConfig();
<ide> var currentKeys = ReactTransitionKeySet.mergeKeySets(
<ide> this._transitionGroupCurrentKeys,
<ide><path>src/addons/transitions/ReactTransitionKeySet.js
<ide> var ReactTransitionKeySet = {
<ide> * in `next` in a reasonable order.
<ide> */
<ide> mergeKeySets: function(prev, next) {
<add> prev = prev || {};
<add> next = next || {};
<add>
<ide> var keySet = {};
<ide> var prevKeys = Object.keys(prev).concat([MERGE_KEY_SETS_TAIL_SENTINEL]);
<ide> var nextKeys = Object.keys(next).concat([MERGE_KEY_SETS_TAIL_SENTINEL]);
<ide><path>src/addons/transitions/__tests__/ReactTransitionKeySet-test.js
<ide> describe('ReactTransitionKeySet', function() {
<ide> five: true
<ide> });
<ide> });
<add>
<add> it('should support mergeKeySets with undefined input', function () {
<add> var prev = {
<add> one: true,
<add> two: true
<add> };
<add>
<add> var next = undefined;
<add>
<add> expect(ReactTransitionKeySet.mergeKeySets(prev, next)).toEqual({
<add> one: true,
<add> two: true
<add> });
<add>
<add> prev = undefined;
<add>
<add> next = {
<add> three: true,
<add> four: true
<add> };
<add>
<add> expect(ReactTransitionKeySet.mergeKeySets(prev, next)).toEqual({
<add> three: true,
<add> four: true
<add> });
<add> });
<ide> }); | 3 |
Text | Text | fix typo in doughnut documentation | faad02331393b5ae4f07eafc119002fa21966118 | <ide><path>docs/charts/doughnut.md
<ide> The following values are supported for `borderAlign`.
<ide> * `'center'` (default)
<ide> * `'inner'`
<ide>
<del>When `'center'` is set, the borders of arcs next to each other will overlap. When `'inner'` is set, it is guaranteed that all the borders are not overlap.
<add>When `'center'` is set, the borders of arcs next to each other will overlap. When `'inner'` is set, it is guaranteed that all borders will not overlap.
<ide>
<ide> ### Interactions
<ide> | 1 |
Javascript | Javascript | move resource acquisition to mutation phase | 71f2c8cf1583f65224bce37bb2ef69e533671183 | <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js
<ide> function commitLayoutEffectOnFiber(
<ide> committedLanes,
<ide> );
<ide>
<del> if (flags & Update) {
<del> const newResource = finishedWork.memoizedState;
<del> if (current !== null) {
<del> const currentResource = current.memoizedState;
<del> if (currentResource !== newResource) {
<del> releaseResource(currentResource);
<del> }
<del> }
<del> finishedWork.stateNode = newResource
<del> ? acquireResource(newResource)
<del> : null;
<del> }
<del>
<ide> if (flags & Ref) {
<ide> safelyAttachRef(finishedWork, finishedWork.return);
<ide> }
<ide> function commitMutationEffectsOnFiber(
<ide> safelyDetachRef(current, current.return);
<ide> }
<ide> }
<add>
<add> if (flags & Update) {
<add> const newResource = finishedWork.memoizedState;
<add> if (current !== null) {
<add> const currentResource = current.memoizedState;
<add> if (currentResource !== newResource) {
<add> releaseResource(currentResource);
<add> }
<add> }
<add> finishedWork.stateNode = newResource
<add> ? acquireResource(newResource)
<add> : null;
<add> }
<ide> return;
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.old.js
<ide> function commitLayoutEffectOnFiber(
<ide> committedLanes,
<ide> );
<ide>
<del> if (flags & Update) {
<del> const newResource = finishedWork.memoizedState;
<del> if (current !== null) {
<del> const currentResource = current.memoizedState;
<del> if (currentResource !== newResource) {
<del> releaseResource(currentResource);
<del> }
<del> }
<del> finishedWork.stateNode = newResource
<del> ? acquireResource(newResource)
<del> : null;
<del> }
<del>
<ide> if (flags & Ref) {
<ide> safelyAttachRef(finishedWork, finishedWork.return);
<ide> }
<ide> function commitMutationEffectsOnFiber(
<ide> safelyDetachRef(current, current.return);
<ide> }
<ide> }
<add>
<add> if (flags & Update) {
<add> const newResource = finishedWork.memoizedState;
<add> if (current !== null) {
<add> const currentResource = current.memoizedState;
<add> if (currentResource !== newResource) {
<add> releaseResource(currentResource);
<add> }
<add> }
<add> finishedWork.stateNode = newResource
<add> ? acquireResource(newResource)
<add> : null;
<add> }
<ide> return;
<ide> }
<ide> } | 2 |
Javascript | Javascript | use shorthand properties | db9c556f507ea2510a603ca526d6cd1e79cfac2d | <ide><path>test/fixtures/tls-connect.js
<ide> exports.connect = function connect(options, callback) {
<ide>
<ide> const server = {};
<ide> const client = {};
<del> const pair = {
<del> server: server,
<del> client: client,
<del> };
<add> const pair = { server, client };
<ide>
<ide> tls.createServer(options.server, function(conn) {
<ide> server.conn = conn;
<ide><path>test/internet/test-tls-reuse-host-from-socket.js
<ide> const tls = require('tls');
<ide> const net = require('net');
<ide>
<ide> const socket = net.connect(443, 'www.example.org', common.mustCall(() => {
<del> const secureSocket = tls.connect({ socket: socket }, common.mustCall(() => {
<add> const secureSocket = tls.connect({ socket }, common.mustCall(() => {
<ide> secureSocket.destroy();
<ide> console.log('ok');
<ide> }));
<ide><path>test/parallel/test-child-process-env.js
<ide> Object.setPrototypeOf(env, {
<ide> let child;
<ide> if (common.isWindows) {
<ide> child = spawn('cmd.exe', ['/c', 'set'],
<del> Object.assign({}, process.env, { env: env }));
<add> Object.assign({}, process.env, { env }));
<ide> } else {
<ide> child = spawn('/usr/bin/env', [],
<del> Object.assign({}, process.env, { env: env }));
<add> Object.assign({}, process.env, { env }));
<ide> }
<ide>
<ide>
<ide><path>test/parallel/test-cluster-dgram-1.js
<ide> function worker() {
<ide>
<ide> // Every 10 messages, notify the master.
<ide> if (received === PACKETS_PER_WORKER) {
<del> process.send({ received: received });
<add> process.send({ received });
<ide> socket.close();
<ide> }
<ide> }, PACKETS_PER_WORKER));
<ide><path>test/parallel/test-cluster-worker-no-exit.js
<ide> if (cluster.isMaster) {
<ide>
<ide> worker = cluster.fork()
<ide> .on('online', function() {
<del> this.send({ port: port });
<add> this.send({ port });
<ide> });
<ide> });
<ide> process.on('exit', function() {
<ide><path>test/parallel/test-fs-realpath-buffer-encoding.js
<ide> for (encoding in expected) {
<ide> const expected_value = expected[encoding];
<ide> let result;
<ide>
<del> result = fs.realpathSync(string_dir, { encoding: encoding });
<add> result = fs.realpathSync(string_dir, { encoding });
<ide> assert.strictEqual(result, expected_value);
<ide>
<ide> result = fs.realpathSync(string_dir, encoding);
<ide> assert.strictEqual(result, expected_value);
<ide>
<del> result = fs.realpathSync(buffer_dir, { encoding: encoding });
<add> result = fs.realpathSync(buffer_dir, { encoding });
<ide> assert.strictEqual(result, expected_value);
<ide>
<ide> result = fs.realpathSync(buffer_dir, encoding);
<ide> for (encoding in expected) {
<ide>
<ide> fs.realpath(
<ide> string_dir,
<del> { encoding: encoding },
<add> { encoding },
<ide> common.mustCall((err, res) => {
<ide> assert.ifError(err);
<ide> assert.strictEqual(res, expected_value);
<ide> for (encoding in expected) {
<ide> }));
<ide> fs.realpath(
<ide> buffer_dir,
<del> { encoding: encoding },
<add> { encoding },
<ide> common.mustCall((err, res) => {
<ide> assert.ifError(err);
<ide> assert.strictEqual(res, expected_value);
<ide><path>test/parallel/test-fs-write-file-sync.js
<ide> common.refreshTmpDir();
<ide> // Test writeFileSync
<ide> const file1 = path.join(common.tmpDir, 'testWriteFileSync.txt');
<ide>
<del>fs.writeFileSync(file1, '123', { mode: mode });
<add>fs.writeFileSync(file1, '123', { mode });
<ide>
<ide> content = fs.readFileSync(file1, { encoding: 'utf8' });
<ide> assert.strictEqual(content, '123');
<ide> assert.strictEqual(fs.statSync(file1).mode & 0o777, mode);
<ide> // Test appendFileSync
<ide> const file2 = path.join(common.tmpDir, 'testAppendFileSync.txt');
<ide>
<del>fs.appendFileSync(file2, 'abc', { mode: mode });
<add>fs.appendFileSync(file2, 'abc', { mode });
<ide>
<ide> content = fs.readFileSync(file2, { encoding: 'utf8' });
<ide> assert.strictEqual(content, 'abc');
<ide><path>test/parallel/test-http-client-read-in-error.js
<ide> class Agent extends http.Agent {
<ide> const agent = new Agent();
<ide>
<ide> http.request({
<del> agent: agent
<add> agent
<ide> }).once('error', function() {
<ide> console.log('ignore');
<ide> });
<ide><path>test/parallel/test-http-pipeline-flood.js
<ide> function child() {
<ide> const net = require('net');
<ide>
<ide> const port = +process.argv[3];
<del> const conn = net.connect({ port: port });
<add> const conn = net.connect({ port });
<ide>
<ide> let req = `GET / HTTP/1.1\r\nHost: localhost:${port}\r\nAccept: */*\r\n\r\n`;
<ide>
<ide><path>test/parallel/test-http2-create-client-connect.js
<ide> const URL = url.URL;
<ide> [`http://localhost:${port}`],
<ide> [new URL(`http://localhost:${port}`)],
<ide> [url.parse(`http://localhost:${port}`)],
<del> [{ port: port }, { protocol: 'http:' }],
<del> [{ port: port, hostname: '127.0.0.1' }, { protocol: 'http:' }]
<add> [{ port }, { protocol: 'http:' }],
<add> [{ port, hostname: '127.0.0.1' }, { protocol: 'http:' }]
<ide> ];
<ide>
<ide> const serverClose = new Countdown(items.length + 1,
<ide><path>test/parallel/test-https-agent-create-connection.js
<ide> function createServer() {
<ide> port: port,
<ide> host: host,
<ide> rejectUnauthorized: false,
<del> _agentKey: agent.getName({
<del> port: port,
<del> host: host,
<del> }),
<add> _agentKey: agent.getName({ port, host })
<ide> };
<ide>
<ide> const socket = agent.createConnection(options);
<ide> function createServer() {
<ide> const host = 'localhost';
<ide> const options = {
<ide> rejectUnauthorized: false,
<del> _agentKey: agent.getName({
<del> port: port,
<del> host: host,
<del> }),
<add> _agentKey: agent.getName({ port, host })
<ide> };
<ide> const socket = agent.createConnection(port, options);
<ide> checkRequest(socket, server);
<ide> function createServer() {
<ide> const host = 'localhost';
<ide> const options = {
<ide> rejectUnauthorized: false,
<del> _agentKey: agent.getName({
<del> port: port,
<del> host: host,
<del> }),
<add> _agentKey: agent.getName({ port, host })
<ide> };
<ide> const socket = agent.createConnection(port, host, options);
<ide> checkRequest(socket, server);
<ide><path>test/parallel/test-https-strict.js
<ide> function listening() {
<ide>
<ide> function makeReq(path, port, error, host, ca) {
<ide> pending++;
<del> const options = {
<del> port: port,
<del> path: path,
<del> ca: ca
<del> };
<add> const options = { port, path, ca };
<ide>
<ide> if (!ca) {
<ide> options.agent = agent0;
<ide> function makeReq(path, port, error, host, ca) {
<ide> }
<ide>
<ide> if (host) {
<del> options.headers = { host: host };
<add> options.headers = { host };
<ide> }
<ide> const req = https.get(options);
<ide> const server = port === server1.address().port ? server1 :
<ide><path>test/parallel/test-https-truncate.js
<ide> const data = Buffer.alloc(1024 * 32 + 1);
<ide> httpsTest();
<ide>
<ide> function httpsTest() {
<del> const sopt = { key: key, cert: cert };
<add> const sopt = { key, cert };
<ide>
<ide> const server = https.createServer(sopt, function(req, res) {
<ide> res.setHeader('content-length', data.length);
<ide><path>test/parallel/test-net-connect-options-port.js
<ide> const net = require('net');
<ide> {
<ide> // connect({hint}, cb) and connect({hint})
<ide> const hints = (dns.ADDRCONFIG | dns.V4MAPPED) + 42;
<del> const hintOptBlocks = doConnect([{ hints: hints }],
<add> const hintOptBlocks = doConnect([{ hints }],
<ide> () => common.mustNotCall());
<ide> for (const block of hintOptBlocks) {
<ide> common.expectsError(block, {
<ide><path>test/parallel/test-net-server-listen-handle.js
<ide> if (!common.isWindows) { // Windows doesn't support {fd: <n>}
<ide> // Test invalid fd
<ide> const fd = fs.openSync(__filename, 'r');
<ide> net.createServer()
<del> .listen({ fd: fd }, common.mustNotCall())
<add> .listen({ fd }, common.mustNotCall())
<ide> .on('error', common.mustCall(function(err) {
<ide> assert.strictEqual(String(err), 'Error: listen EINVAL');
<ide> this.close();
<ide><path>test/parallel/test-net-server-listen-options.js
<ide> function close() { this.close(); }
<ide> .on('listening', common.mustCall(close));
<ide> }
<ide>
<del>// Test listen(port, cb) and listen({port: port}, cb) combinations
<add>// Test listen(port, cb) and listen({ port }, cb) combinations
<ide> const listenOnPort = [
<ide> (port, cb) => net.createServer().listen({ port }, cb),
<ide> (port, cb) => net.createServer().listen(port, cb)
<ide><path>test/parallel/test-stream2-readable-wrap.js
<ide> const EE = require('events').EventEmitter;
<ide> function runTest(highWaterMark, objectMode, produce) {
<ide>
<ide> const old = new EE();
<del> const r = new Readable({ highWaterMark: highWaterMark,
<del> objectMode: objectMode });
<add> const r = new Readable({ highWaterMark, objectMode });
<ide> assert.strictEqual(r, r.wrap(old));
<ide>
<ide> r.on('end', common.mustCall());
<ide> function runTest(highWaterMark, objectMode, produce) {
<ide> }
<ide>
<ide> const w = new Writable({ highWaterMark: highWaterMark * 2,
<del> objectMode: objectMode });
<add> objectMode });
<ide> const written = [];
<ide> w._write = function(chunk, encoding, cb) {
<ide> written.push(chunk);
<ide><path>test/parallel/test-tls-cert-regression.js
<ide> sPWhSOb9VQjMXekI4Y2l8fqAVTS2Fn6+8jkVKxXBywSVCw==
<ide>
<ide> function test(cert, key, cb) {
<ide> const server = tls.createServer({
<del> cert: cert,
<del> key: key
<add> cert,
<add> key
<ide> }).listen(0, function() {
<ide> server.close(cb);
<ide> });
<ide><path>test/parallel/test-tls-connect-no-host.js
<ide> const key = fixtures.readSync('test_key.pem');
<ide> // tls.connect(options) with no options.host should accept a cert with
<ide> // CN:'localhost'
<ide> tls.createServer({
<del> key: key,
<del> cert: cert
<add> key,
<add> cert
<ide> }).listen(0, function() {
<ide> const socket = tls.connect({
<ide> port: this.address().port,
<ide><path>test/parallel/test-tls-ecdh-multiple.js
<ide> process.on('exit', function() {
<ide> unsupportedCurves.push('brainpoolP256r1');
<ide>
<ide> unsupportedCurves.forEach((ecdhCurve) => {
<del> assert.throws(() => tls.createServer({ ecdhCurve: ecdhCurve }),
<add> assert.throws(() => tls.createServer({ ecdhCurve }),
<ide> /Error: Failed to set ECDH curve/);
<ide> });
<ide> });
<ide><path>test/parallel/test-tls-env-extra-ca.js
<ide> const server = tls.createServer(options, common.mustCall(function(s) {
<ide> NODE_EXTRA_CA_CERTS: fixtures.path('keys', 'ca1-cert.pem')
<ide> });
<ide>
<del> fork(__filename, { env: env }).on('exit', common.mustCall(function(status) {
<add> fork(__filename, { env }).on('exit', common.mustCall(function(status) {
<ide> assert.strictEqual(status, 0, 'client did not succeed in connecting');
<ide> }));
<ide> }));
<ide><path>test/parallel/test-tls-friendly-error-message.js
<ide> const tls = require('tls');
<ide> const key = fixtures.readKey('agent1-key.pem');
<ide> const cert = fixtures.readKey('agent1-cert.pem');
<ide>
<del>tls.createServer({ key: key, cert: cert }, common.mustCall(function(conn) {
<add>tls.createServer({ key, cert }, common.mustCall(function(conn) {
<ide> conn.end();
<ide> this.close();
<ide> })).listen(0, common.mustCall(function() {
<ide><path>test/parallel/test-tls-no-sslv3.js
<ide> const fixtures = require('../common/fixtures');
<ide>
<ide> const cert = fixtures.readSync('test_cert.pem');
<ide> const key = fixtures.readSync('test_key.pem');
<del>const server = tls.createServer({ cert: cert, key: key }, common.mustNotCall());
<add>const server = tls.createServer({ cert, key }, common.mustNotCall());
<ide> const errors = [];
<ide> let stderr = '';
<ide>
<ide><path>test/parallel/test-tls-over-http-tunnel.js
<ide> let gotRequest = false;
<ide> const key = fixtures.readKey('agent1-key.pem');
<ide> const cert = fixtures.readKey('agent1-cert.pem');
<ide>
<del>const options = {
<del> key: key,
<del> cert: cert
<del>};
<add>const options = { key, cert };
<ide>
<ide> const server = https.createServer(options, function(req, res) {
<ide> console.log('SERVER: got request');
<ide><path>test/parallel/test-tls-securepair-server.js
<ide> function log(a) {
<ide>
<ide> const server = net.createServer(common.mustCall(function(socket) {
<ide> log(`connection fd=${socket.fd}`);
<del> const sslcontext = tls.createSecureContext({ key: key, cert: cert });
<add> const sslcontext = tls.createSecureContext({ key, cert });
<ide> sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA');
<ide>
<ide> const pair = tls.createSecurePair(sslcontext, true);
<ide><path>test/parallel/test-tls-session-cache.js
<ide> function doTest(testOptions, callback) {
<ide> // Emulate asynchronous store
<ide> setTimeout(function() {
<ide> assert.ok(!session);
<del> session = {
<del> id: id,
<del> data: data
<del> };
<add> session = { id, data };
<ide> cb();
<ide> }, 1000);
<ide> });
<ide><path>test/parallel/test-tls-starttls-server.js
<ide> const server = net.createServer(common.mustCall((s) => {
<ide> isServer: true,
<ide> server: server,
<ide>
<del> secureContext: tls.createSecureContext({
<del> key: key,
<del> cert: cert
<del> }),
<add> secureContext: tls.createSecureContext({ key, cert }),
<ide>
<ide> SNICallback: common.mustCall((hostname, callback) => {
<ide> assert.strictEqual(hostname, 'test.test');
<ide><path>test/parallel/test-tls-zero-clear-in.js
<ide> const cert = fixtures.readSync('test_cert.pem');
<ide> const key = fixtures.readSync('test_key.pem');
<ide>
<ide> const server = tls.createServer({
<del> cert: cert,
<del> key: key
<add> cert,
<add> key
<ide> }, function(c) {
<ide> // Nop
<ide> setTimeout(function() {
<ide><path>test/parallel/test-util-inspect.js
<ide> for (const showHidden of [true, false]) {
<ide> // Now do the same checks but from a different context
<ide> for (const showHidden of [true, false]) {
<ide> const ab = vm.runInNewContext('new ArrayBuffer(4)');
<del> const dv = vm.runInNewContext('new DataView(ab, 1, 2)', { ab: ab });
<add> const dv = vm.runInNewContext('new DataView(ab, 1, 2)', { ab });
<ide> assert.strictEqual(
<ide> util.inspect(ab, showHidden),
<ide> 'ArrayBuffer { byteLength: 4 }'
<ide><path>test/parallel/test-vm-access-process-env.js
<ide> const assert = require('assert');
<ide> const vm = require('vm');
<ide>
<ide> assert.doesNotThrow(function() {
<del> const context = vm.createContext({ process: process });
<add> const context = vm.createContext({ process });
<ide> const result = vm.runInContext('process.env["PATH"]', context);
<ide> assert.notStrictEqual(undefined, result);
<ide> });
<ide><path>test/parallel/test-vm-context.js
<ide> const contextifiedSandboxErrorMsg =
<ide> script = vm.createScript('const assert = require(\'assert\'); assert.throws(' +
<ide> 'function() { throw "hello world"; }, /hello/);',
<ide> 'some.js');
<del>script.runInNewContext({ require: require });
<add>script.runInNewContext({ require });
<ide>
<ide> // Issue GH-7529
<ide> script = vm.createScript('delete b');
<ide><path>test/parallel/test-vm-function-declaration.js
<ide> require('../common');
<ide> const assert = require('assert');
<ide>
<ide> const vm = require('vm');
<del>const o = vm.createContext({ console: console });
<add>const o = vm.createContext({ console });
<ide>
<ide> // Function declaration and expression should both be copied to the
<ide> // sandboxed context.
<ide><path>test/parallel/test-vm-global-define-property.js
<ide> const code =
<ide> 'f;\n';
<ide>
<ide> const x = {};
<del>const o = vm.createContext({ console: console, x: x });
<add>const o = vm.createContext({ console, x });
<ide>
<ide> const res = vm.runInContext(code, o, 'test');
<ide>
<ide><path>test/parallel/test-vm-harmony-symbols.js
<ide> assert.strictEqual(typeof sandbox.Symbol, 'function');
<ide> assert.notStrictEqual(sandbox.Symbol, Symbol);
<ide>
<ide> // Unless we copy the Symbol constructor explicitly, of course.
<del>sandbox = { Symbol: Symbol };
<add>sandbox = { Symbol };
<ide> vm.runInNewContext('this.Symbol = Symbol', sandbox);
<ide> assert.strictEqual(typeof sandbox.Symbol, 'function');
<ide> assert.strictEqual(sandbox.Symbol, Symbol);
<ide><path>test/parallel/test-vm-new-script-new-context.js
<ide> const Script = require('vm').Script;
<ide> {
<ide> const script = new Script('f.a = 2');
<ide> const f = { a: 1 };
<del> script.runInNewContext({ f: f });
<add> script.runInNewContext({ f });
<ide> assert.strictEqual(f.a, 2);
<ide>
<ide> assert.throws(() => {
<ide><path>test/parallel/test-vm-proxies.js
<ide> assert.strictEqual(typeof sandbox.Proxy, 'function');
<ide> assert.notStrictEqual(sandbox.Proxy, Proxy);
<ide>
<ide> // Unless we copy the Proxy object explicitly, of course.
<del>sandbox = { Proxy: Proxy };
<add>sandbox = { Proxy };
<ide> vm.runInNewContext('this.Proxy = Proxy', sandbox);
<ide> assert.strictEqual(typeof sandbox.Proxy, 'function');
<ide> assert.strictEqual(sandbox.Proxy, Proxy);
<ide><path>test/parallel/test-vm-run-in-new-context.js
<ide> assert.strictEqual(global.foo, 100);
<ide>
<ide> // Modify an object by reference
<ide> const f = { a: 1 };
<del>vm.runInNewContext('f.a = 2', { f: f });
<add>vm.runInNewContext('f.a = 2', { f });
<ide> assert.strictEqual(f.a, 2);
<ide>
<ide> // Use function in context without referencing context
<ide><path>test/parallel/test-vm-timeout.js
<ide> assert.throws(function() {
<ide> const context = {
<ide> log: console.log,
<ide> runInVM: function(timeout) {
<del> vm.runInNewContext('while(true) {}', context, { timeout: timeout });
<add> vm.runInNewContext('while(true) {}', context, { timeout });
<ide> }
<ide> };
<ide> vm.runInNewContext('runInVM(10)', context, { timeout: 10000 });
<ide> assert.throws(function() {
<ide> assert.throws(function() {
<ide> const context = {
<ide> runInVM: function(timeout) {
<del> vm.runInNewContext('while(true) {}', context, { timeout: timeout });
<add> vm.runInNewContext('while(true) {}', context, { timeout });
<ide> }
<ide> };
<ide> vm.runInNewContext('runInVM(10000)', context, { timeout: 100 });
<ide> assert.throws(function() {
<ide> assert.throws(function() {
<ide> const context = {
<ide> runInVM: function(timeout) {
<del> vm.runInNewContext('throw new Error(\'foobar\')', context, {
<del> timeout: timeout
<del> });
<add> vm.runInNewContext('throw new Error(\'foobar\')', context, { timeout });
<ide> }
<ide> };
<ide> vm.runInNewContext('runInVM(10000)', context, { timeout: 100000 });
<ide><path>test/parallel/test-zlib.js
<ide> testKeys.forEach(common.mustCall((file) => {
<ide> zlibPairs.forEach(common.mustCall((pair) => {
<ide> const Def = pair[0];
<ide> const Inf = pair[1];
<del> const opts = { level: level,
<del> windowBits: windowBits,
<del> memLevel: memLevel,
<del> strategy: strategy };
<add> const opts = { level, windowBits, memLevel, strategy };
<ide>
<ide> const def = new Def(opts);
<ide> const inf = new Inf(opts);
<ide><path>test/pummel/test-tls-securepair-client.js
<ide> function test(keyfn, certfn, check, next) {
<ide> function startClient() {
<ide> const s = new net.Stream();
<ide>
<del> const sslcontext = tls.createSecureContext({ key: key, cert: cert });
<add> const sslcontext = tls.createSecureContext({ key, cert });
<ide> sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA');
<ide>
<ide> const pair = tls.createSecurePair(sslcontext, false); | 40 |
Ruby | Ruby | remove trailing whitespace | 69054b06b583da2bd13fc4b784c6802ee92d25be | <ide><path>Library/Homebrew/cmd/tap.rb
<ide> def tap
<ide> opoo "`brew tap --full` is now a no-op!"
<ide> # odeprecated "`brew tap --full`"
<ide> end
<del>
<add>
<ide> if args.shallow?
<ide> opoo "`brew tap --shallow` is now a no-op!"
<ide> # odeprecated "`brew tap --shallow`" | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.