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
Text
Text
add v3.9.0-beta.2 to changelog
8628f37fc96ca656b4d8de18f21bcb398ad86c8b
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.9.0-beta.2 (February 26, 2019) <add> <add>- [#17618](https://github.com/emberjs/ember.js/pull/17618) [BUGFIX] Migrate autorun microtask queue to Promise.then <add>- [#17649](https://github.com/emberjs/ember.js/pull/17649) [BUGFIX] Revert decorator refactors <add> <ide> ### v3.9.0-beta.1 (February 18, 2019) <ide> <ide> - [#17470](https://github.com/emberjs/ember.js/pull/17470) [DEPRECATION] Implements the Computed Property Modifier deprecation RFCs
1
Java
Java
remove unused file
c57d7eaf43b531834eacb38a1e47f1ece4023c64
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ProxyQueueThreadExceptionHandler.java <del>/** <del> * Copyright (c) 2015-present, Facebook, Inc. <del> * All rights reserved. <del> * <del> * This source code is licensed under the BSD-style license found in the <del> * LICENSE file in the root directory of this source tree. An additional grant <del> * of patent rights can be found in the PATENTS file in the same directory. <del> */ <del> <del>package com.facebook.react.bridge.queue; <del> <del>/** <del> * An Exception handler that posts the Exception to be thrown on the given delegate <del> * MessageQueueThread. <del> */ <del>public class ProxyQueueThreadExceptionHandler implements QueueThreadExceptionHandler { <del> <del> private final MessageQueueThread mDelegateThread; <del> <del> public ProxyQueueThreadExceptionHandler(MessageQueueThread delegateThread) { <del> mDelegateThread = delegateThread; <del> } <del> <del> @Override <del> public void handleException(final Exception e) { <del> mDelegateThread.runOnQueue( <del> new Runnable() { <del> @Override <del> public void run() { <del> throw new RuntimeException(e); <del> } <del> }); <del> } <del>}
1
Go
Go
use assert statement to replace condition judgment
ee7fdbe8b9ff6ed48d183d2160c4ad5a2d713261
<ide><path>integration-cli/docker_hub_pull_suite_test.go <ide> import ( <ide> "runtime" <ide> "strings" <ide> <add> "github.com/docker/docker/pkg/integration/checker" <ide> "github.com/go-check/check" <ide> ) <ide> <ide> func newDockerHubPullSuite() *DockerHubPullSuite { <ide> func (s *DockerHubPullSuite) SetUpSuite(c *check.C) { <ide> testRequires(c, DaemonIsLinux) <ide> s.d = NewDaemon(c) <del> if err := s.d.Start(); err != nil { <del> c.Fatalf("starting push/pull test daemon: %v", err) <del> } <add> err := s.d.Start() <add> c.Assert(err, checker.IsNil, check.Commentf("starting push/pull test daemon: %v", err)) <ide> } <ide> <ide> // TearDownSuite stops the suite daemon. <ide> func (s *DockerHubPullSuite) TearDownSuite(c *check.C) { <ide> if s.d != nil { <del> if err := s.d.Stop(); err != nil { <del> c.Fatalf("stopping push/pull test daemon: %v", err) <del> } <add> err := s.d.Stop() <add> c.Assert(err, checker.IsNil, check.Commentf("stopping push/pull test daemon: %v", err)) <ide> } <ide> } <ide> <ide> func (s *DockerHubPullSuite) TearDownTest(c *check.C) { <ide> // output. The function fails the test when the command returns an error. <ide> func (s *DockerHubPullSuite) Cmd(c *check.C, name string, arg ...string) string { <ide> out, err := s.CmdWithError(name, arg...) <del> c.Assert(err, check.IsNil, check.Commentf("%q failed with errors: %s, %v", strings.Join(arg, " "), out, err)) <add> c.Assert(err, checker.IsNil, check.Commentf("%q failed with errors: %s, %v", strings.Join(arg, " "), out, err)) <ide> return out <ide> } <ide>
1
Javascript
Javascript
simulate support of data uris for ie10
96c2f5c6ae05a5f184dfd6a8ff558f798a119d2c
<ide><path>web/compatibility.js <ide> }; <ide> })(); <ide> <del>// IE9 text/html data URI <del>(function checkDocumentDocumentModeCompatibility() { <del> if (!('documentMode' in document) || document.documentMode !== 9) <add>// IE9/10 text/html data URI <add>(function checkDataURICompatibility() { <add> if (!('documentMode' in document) || <add> document.documentMode !== 9 && document.documentMode !== 10) <ide> return; <ide> // overriding the src property <ide> var originalSrcDescriptor = Object.getOwnPropertyDescriptor(
1
Text
Text
add changelogs for process
3f3d62a21c30daec479d82986445ba8773a14263
<ide><path>doc/api/process.md <ide> to detect application failures and recover or restart as needed. <ide> ### Event: 'unhandledRejection' <ide> <!-- YAML <ide> added: v1.4.1 <add>changes: <add> - version: v7.0.0 <add> pr-url: https://github.com/nodejs/node/pull/8217 <add> description: Not handling Promise rejections has been deprecated. <add> - version: v6.6.0 <add> pr-url: https://github.com/nodejs/node/pull/8223 <add> description: Unhandled Promise rejections have been will now emit <add> a process warning. <ide> --> <ide> <ide> The `'unhandledRejection`' event is emitted whenever a `Promise` is rejected and <ide> is no entry script. <ide> ## process.memoryUsage() <ide> <!-- YAML <ide> added: v0.1.16 <add>changes: <add> - version: v7.2.0 <add> pr-url: https://github.com/nodejs/node/pull/9587 <add> description: Added `external` to the returned object. <ide> --> <ide> <ide> * Returns: {Object} <ide> objects managed by V8. <ide> ## process.nextTick(callback[, ...args]) <ide> <!-- YAML <ide> added: v0.1.26 <add>changes: <add> - version: v1.8.1 <add> pr-url: https://github.com/nodejs/node/pull/1077 <add> description: Additional arguments after `callback` are now supported. <ide> --> <ide> <ide> * `callback` {Function} <ide> console.log(`This platform is ${process.platform}`); <ide> ## process.release <ide> <!-- YAML <ide> added: v3.0.0 <add>changes: <add> - version: v4.2.0 <add> pr-url: https://github.com/nodejs/node/pull/3212 <add> description: The `lts` property is now supported. <ide> --> <ide> <ide> The `process.release` property returns an Object containing metadata related to <ide> console.log(`Version: ${process.version}`); <ide> ## process.versions <ide> <!-- YAML <ide> added: v0.2.0 <add>changes: <add> - version: v4.2.0 <add> pr-url: https://github.com/nodejs/node/pull/3102 <add> description: The `icu` property is now supported. <ide> --> <ide> <ide> * {Object}
1
PHP
PHP
fire an event on cache clear
d8c60efe2cd5692e1b667873a85522a5b6f4101c
<ide><path>src/Illuminate/Cache/Console/ClearCommand.php <ide> public function fire() <ide> $this->cache->flush(); <ide> <ide> $this->files->delete($this->laravel['config']['app.manifest'].'/services.json'); <add> <add> $this->laravel['events']->fire('cache:clear'); <ide> <ide> $this->info('Application cache cleared!'); <ide> }
1
PHP
PHP
throw exception instead of logging in debug mode
c193ce708a7920535b4e8aaab7499518e6f9fcde
<ide><path>lib/Cake/View/Helper/CacheHelper.php <ide> protected function _parseContent($file, $out) { <ide> * @param string $out output to cache <ide> * @return string view output <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html <add> * @throws Exception If debug mode is enabled and writing to cache file fails. <ide> */ <ide> public function cache($file, $out) { <ide> $cacheTime = 0; <ide> public function cache($file, $out) { <ide> try { <ide> $this->_writeFile($cached, $cacheTime, $useCallbacks); <ide> } catch (Exception $e) { <add> if (Configure::read('debug')) { <add> throw $e; <add> } <add> <ide> $message = __d( <ide> 'cake_dev', <ide> 'Unable to write view cache file: "%s" for "%s"',
1
Python
Python
relax version contstraint
417f430d23cf2c1ffcc16a886694d27b62c0e04e
<ide><path>setup.py <ide> def setup_package(): <ide> 'dill>=0.2,<0.3', <ide> 'requests>=2.13.0,<3.0.0', <ide> 'regex==2017.4.5', <del> 'ftfy == 4.4.2'], <add> 'ftfy>=4.4.2,<5.0.0'], <ide> classifiers=[ <ide> 'Development Status :: 5 - Production/Stable', <ide> 'Environment :: Console',
1
Ruby
Ruby
add license header to update.rb
9d63bf9e142ac82bdd8371c5dd3d566b181a53e0
<ide><path>Library/Homebrew/update.rb <add># Copyright 2009 Max Howell and other contributors. <add># <add># Redistribution and use in source and binary forms, with or without <add># modification, are permitted provided that the following conditions <add># are met: <add># <add># 1. Redistributions of source code must retain the above copyright <add># notice, this list of conditions and the following disclaimer. <add># 2. Redistributions in binary form must reproduce the above copyright <add># notice, this list of conditions and the following disclaimer in the <add># documentation and/or other materials provided with the distribution. <add># <add># THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR <add># IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES <add># OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. <add># IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, <add># INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT <add># NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, <add># DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY <add># THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT <add># (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF <add># THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <add># <ide> class RefreshBrew <ide> CHECKOUT_COMMAND = 'git checkout masterbrew' <ide> UPDATE_COMMAND = 'git pull origin masterbrew' <ide> def git_checkout_masterbrew! <ide> def git_pull! <ide> in_prefix { execute UPDATE_COMMAND } <ide> end <del>end <ide>\ No newline at end of file <add>end
1
Javascript
Javascript
declare a dependency on the manipulation module
c18c6229c84cd2f0c9fe9f6fc3749e2c93608cc7
<ide><path>src/wrap.js <ide> define([ <ide> "./core", <ide> "./core/init", <add> "./manipulation", // clone <ide> "./traversing" // parent, contents <ide> ], function( jQuery ) { <ide>
1
Javascript
Javascript
add multiline support
443071db5749603f816199b9ec8bc512fb441d98
<ide><path>lib/readline.js <ide> function Interface(input, output, completer) { <ide> this.history = []; <ide> this.historyIndex = -1; <ide> <add> // a number of lines used by current command <add> this.usedLines = 1; <add> <ide> var winSize = output.getWindowSize(); <ide> exports.columns = winSize[0]; <add> exports.rows = winSize[1]; <ide> <ide> if (process.listeners('SIGWINCH').length === 0) { <ide> process.on('SIGWINCH', function() { <ide> var winSize = output.getWindowSize(); <ide> exports.columns = winSize[0]; <add> exports.rows = winSize[1]; <ide> }); <ide> } <ide> } <ide> Interface.prototype.__defineGetter__('columns', function() { <ide> return exports.columns; <ide> }); <ide> <add>Interface.prototype.__defineGetter__('rows', function() { <add> return exports.rows; <add>}); <add> <ide> Interface.prototype.setPrompt = function(prompt, length) { <ide> this._prompt = prompt; <ide> if (length) { <ide> Interface.prototype._addHistory = function() { <ide> }; <ide> <ide> <add>Interface.prototype._recalcUsedLines = function() { <add> var line = this._prompt + this.line; <add> var newcount = Math.ceil(line.length / this.columns); <add> if (newcount > this.usedLines) this.usedLines = newcount; <add>}; <add> <add> <ide> Interface.prototype._refreshLine = function() { <add> var columns = this.columns; <add> if (!columns) columns = Infinity; <add> <add> // See if a number of used lines has changed <add> var oldLines = this.usedLines; <add> this._recalcUsedLines(); <add> if (oldLines != this.usedLines) { <add> this.output.cursorTo(0, this.rows - 1); <add> for (var i = oldLines; i < this.usedLines; i++) { <add> this.output.write('\r\n'); <add> } <add> } <add> <ide> // Cursor to left edge. <del> this.output.cursorTo(0); <add> if (this.usedLines === 1) { <add> this.output.cursorTo(0); <add> } else { <add> this.output.cursorTo(0, this.rows - this.usedLines); <add> } <ide> <ide> // Write the prompt and the current buffer content. <del> this.output.write(this._prompt); <del> this.output.write(this.line); <add> var buffer = this._prompt + this.line; <add> this.output.write(buffer); <ide> <ide> // Erase to right. <ide> this.output.clearLine(1); <add> var clearLinesCnt = this.usedLines - Math.floor(buffer.length / columns) - 1; <add> for (var i = this.rows - clearLinesCnt; i < this.rows; i++) { <add> this.output.cursorTo(0, i); <add> this.output.clearLine(0); <add> } <ide> <ide> // Move cursor to original position. <del> this.output.cursorTo(this._promptLength + this.cursor); <add> var curPos = this._getCursorPos(); <add> if (this.usedLines === 1) { <add> this.output.cursorTo(curPos[0]); <add> } else { <add> this.output.cursorTo(curPos[0], this.rows - this.usedLines + curPos[1]); <add> } <ide> }; <ide> <ide> <ide> Interface.prototype._insertString = function(c) { <ide> this.line += c; <ide> this.cursor += c.length; <ide> this.output.write(c); <add> this._recalcUsedLines(); <ide> } <ide> }; <ide> <ide> Interface.prototype._deleteLineRight = function() { <ide> Interface.prototype._line = function() { <ide> var line = this._addHistory(); <ide> this.output.write('\r\n'); <add> this.usedLines = 1; <ide> this._onLine(line); <ide> }; <ide> <ide> Interface.prototype._historyPrev = function() { <ide> }; <ide> <ide> <add>// Returns current cursor's position and line <add>Interface.prototype._getCursorPos = function() { <add> var columns = this.columns; <add> var pos = this.cursor + this._promptLength; <add> if (!columns) return [pos, 0]; <add> <add> var lineNum = Math.floor(pos / columns); <add> var colNum = pos - lineNum * columns; <add> return [colNum, lineNum]; <add>}; <add> <add> <add>Interface.prototype._moveCursor = function(dx) { <add> var oldcursor = this.cursor; <add> var oldLine = this._getCursorPos()[1]; <add> this.cursor += dx; <add> var newLine = this._getCursorPos()[1]; <add> <add> // check if cursors are in the same line <add> if (oldLine == newLine) { <add> this.output.moveCursor(dx, 0); <add> } else { <add> this._refreshLine(); <add> } <add>}; <add> <add> <ide> // handle a write from the tty <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> var next_word, next_non_word, previous_word, previous_non_word; <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> <ide> case 'left': <ide> if (this.cursor > 0) { <del> this.cursor--; <del> this.output.moveCursor(-1, 0); <add> this._moveCursor(-1); <ide> } <ide> break; <ide> <ide> case 'right': <ide> if (this.cursor != this.line.length) { <del> this.cursor++; <del> this.output.moveCursor(1, 0); <add> this._moveCursor(1); <ide> } <ide> break; <ide>
1
PHP
PHP
use key instead of password
c03924a76733f9c120f5bab566f52007d4b1de0c
<ide><path>src/Illuminate/Filesystem/FilesystemManager.php <ide> public function createS3Driver(array $config) <ide> public function createRackspaceDriver(array $config) <ide> { <ide> $client = new Rackspace($config['endpoint'], [ <del> 'username' => $config['username'], 'apiKey' => $config['password'], <add> 'username' => $config['username'], 'apiKey' => $config['key'], <ide> ]); <ide> <ide> return $this->decorate(new Flysystem(
1
Python
Python
correct an issue on unitest with py3
3c42bb929b511569d6cc40804ac5fa073f3da500
<ide><path>unitest.py <ide> from glances import __version__ <ide> from glances.globals import WINDOWS, LINUX <ide> from glances.outputs.glances_bars import Bar <add>from glances.compat import PY3 <ide> from glances.thresholds import GlancesThresholdOk <ide> from glances.thresholds import GlancesThresholdCareful <ide> from glances.thresholds import GlancesThresholdWarning <ide> def test_013_gpu(self): <ide> self.assertTrue(type(stats_grab) is list, msg='GPU stats is not a list') <ide> print('INFO: GPU stats: %s' % stats_grab) <ide> <add> @unittest.skipIf(PY3, True) <ide> def test_094_thresholds(self): <ide> """Test thresholds classes""" <ide> print('INFO: [TEST_094] Thresholds')
1
Python
Python
show stdout/stderr for timed out tests
169756b15dc8f6c2974a8ef3f095c055dcd47159
<ide><path>tools/test.py <ide> def HasRun(self, output): <ide> (total_seconds, duration.microseconds / 1000)) <ide> if self.severity is not 'ok' or self.traceback is not '': <ide> if output.HasTimedOut(): <del> self.traceback = 'timeout' <add> self.traceback = 'timeout\n' + output.output.stdout + output.output.stderr <ide> self._printDiagnostic() <ide> logger.info(' ...') <ide>
1
Text
Text
unify `fixes` notes in ar changelog. [ci skip]
dfe40cdcab1758003e243838a3c5aa0056d82cf7
<ide><path>activerecord/CHANGELOG.md <ide> * Objects intiantiated using a null relationship will now retain the <ide> attributes of the where clause. <ide> <del> Fixes: #11676, #11675, #11376 <add> Fixes #11676, #11675, #11376. <ide> <ide> *Paul Nikitochkin*, *Peter Brown*, *Nthalk* <ide> <ide> * `ActiveRecord::ConnectionAdapters.string_to_time` respects <ide> string with timezone (e.g. Wed, 04 Sep 2013 20:30:00 JST). <ide> <del> Fixes: #12278 <add> Fixes #12278. <ide> <ide> *kennyj* <ide> <ide> where constraints and at least of them is not `Arel::Nodes::Equality`, <ide> generates invalid SQL expression. <ide> <del> Fixes: #11963 <add> Fixes #11963. <ide> <ide> *Paul Nikitochkin* <ide> <ide> to allow the connection adapter to properly determine how to quote the value. This was <ide> affecting certain databases that use specific column types. <ide> <del> Fixes: #6763 <add> Fixes #6763. <ide> <ide> *Alfred Wong* <ide> <ide> * rescue from all exceptions in `ConnectionManagement#call` <ide> <del> Fixes #11497 <add> Fixes #11497. <ide> <ide> As `ActiveRecord::ConnectionAdapters::ConnectionManagement` middleware does <ide> not rescue from Exception (but only from StandardError), the Connection <ide> <ide> * Remove extra decrement of transaction deep level. <ide> <del> Fixes: #4566 <add> Fixes #4566. <ide> <ide> *Paul Nikitochkin* <ide> <ide> * Remove extra select and update queries on save/touch/destroy ActiveRecord model <ide> with belongs to reflection with option `touch: true`. <ide> <del> Fixes: #11288 <add> Fixes #11288. <ide> <ide> *Paul Nikitochkin* <ide>
1
Javascript
Javascript
throw error when trying to dispatch from action
848bb8e175715bedaccd10bbcbe62b1dbbe09ffa
<ide><path>src/createStore.js <ide> export default function createStore(reducer, initialState) { <ide> var currentReducer = reducer; <ide> var currentState = initialState; <ide> var listeners = []; <add> var isDispatching = false; <ide> <ide> /** <ide> * Reads the state tree managed by the store. <ide> export default function createStore(reducer, initialState) { <ide> 'Actions must be plain objects. Use custom middleware for async actions.' <ide> ); <ide> <del> currentState = currentReducer(currentState, action); <add> invariant( <add> isDispatching === false, <add> 'Reducers may not dispatch actions.' <add> ); <add> <add> try { <add> isDispatching = true; <add> currentState = currentReducer(currentState, action); <add> } finally { <add> isDispatching = false; <add> } <add> <ide> listeners.forEach(listener => listener()); <ide> return action; <ide> } <ide><path>test/createStore.spec.js <ide> import expect from 'expect'; <ide> import { createStore, combineReducers } from '../src/index'; <del>import { addTodo } from './helpers/actionCreators'; <add>import { addTodo, dispatchInMiddle, throwError } from './helpers/actionCreators'; <ide> import * as reducers from './helpers/reducers'; <ide> <ide> describe('createStore', () => { <ide> describe('createStore', () => { <ide> bar: 2 <ide> }); <ide> }); <add> <add> it('should not allow dispatch() from within a reducer', () => { <add> const store = createStore(reducers.dispatchInTheMiddleOfReducer); <add> <add> expect(() => <add> store.dispatch(dispatchInMiddle(store.dispatch.bind(store, {}))) <add> ).toThrow(/may not dispatch/); <add> }); <add> <add> it('recovers from an error within a reducer', () => { <add> const store = createStore(reducers.errorThrowingReducer); <add> expect(() => <add> store.dispatch(throwError()) <add> ).toThrow(); <add> <add> expect(() => <add> store.dispatch({}) <add> ).toNotThrow(); <add> }); <ide> }); <ide><path>test/helpers/actionCreators.js <del>import { ADD_TODO } from './actionTypes'; <add>import { ADD_TODO, DISPATCH_IN_MIDDLE, THROW_ERROR } from './actionTypes'; <ide> <ide> export function addTodo(text) { <ide> return { type: ADD_TODO, text }; <ide> export function addTodoIfEmpty(text) { <ide> } <ide> }; <ide> } <add> <add>export function dispatchInMiddle(boundDispatchFn) { <add> return { <add> type: DISPATCH_IN_MIDDLE, <add> boundDispatchFn <add> }; <add>} <add> <add>export function throwError() { <add> return { <add> type: THROW_ERROR <add> }; <add>} <ide><path>test/helpers/actionTypes.js <ide> export const ADD_TODO = 'ADD_TODO'; <add>export const DISPATCH_IN_MIDDLE = 'DISPATCH_IN_MIDDLE'; <add>export const THROW_ERROR = 'THROW_ERROR'; <ide><path>test/helpers/reducers.js <del>import { ADD_TODO } from './actionTypes'; <add>import { ADD_TODO, DISPATCH_IN_MIDDLE, THROW_ERROR } from './actionTypes'; <ide> <ide> <ide> function id(state = []) { <ide> export function todosReverse(state = [], action) { <ide> return state; <ide> } <ide> } <add> <add>export function dispatchInTheMiddleOfReducer(state = [], action) { <add> switch (action.type) { <add> case DISPATCH_IN_MIDDLE: <add> action.boundDispatchFn(); <add> return state; <add> default: <add> return state; <add> } <add>} <add> <add>export function errorThrowingReducer(state = [], action) { <add> switch (action.type) { <add> case THROW_ERROR: <add> throw new Error(); <add> default: <add> return state; <add> } <add>}
5
Java
Java
ensure filename is written
283811b16b3b568230ace382f9d16c1c6b662b7a
<ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartHttpMessageWriter.java <ide> private <T> Flux<DataBuffer> encodePart(byte[] boundary, String name, T value) { <ide> resolvableType = ResolvableType.forClass(body.getClass()); <ide> } <ide> <del> String filename = (body instanceof Resource ? ((Resource) body).getFilename() : null); <del> outputMessage.getHeaders().setContentDispositionFormData(name, filename); <add> if (body instanceof Resource) { <add> outputMessage.getHeaders().setContentDispositionFormData(name, ((Resource) body).getFilename()); <add> } <add> else if (Resource.class.equals(resolvableType.getRawClass())) { <add> body = (T) Mono.from((Publisher<?>) body).doOnNext(o -> { <add> outputMessage.getHeaders().setContentDispositionFormData(name, ((Resource) o).getFilename()); <add> }); <add> } <add> else { <add> outputMessage.getHeaders().setContentDispositionFormData(name, null); <add> } <ide> <ide> MediaType contentType = outputMessage.getHeaders().getContentType(); <ide> <ide><path>spring-web/src/test/java/org/springframework/http/codec/multipart/MultipartHttpMessageWriterTests.java <ide> public void singleSubscriberWithResource() throws IOException { <ide> <ide> Part part = requestParts.getFirst("logo"); <ide> assertEquals("logo", part.name()); <del>// TODO: a Resource written as an async part doesn't have a file name in the contentDisposition <del>// assertTrue(part instanceof FilePart); <del>// assertEquals("logo.jpg", ((FilePart) part).filename()); <add> assertTrue(part instanceof FilePart); <add> assertEquals("logo.jpg", ((FilePart) part).filename()); <ide> assertEquals(MediaType.IMAGE_JPEG, part.headers().getContentType()); <ide> assertEquals(logo.getFile().length(), part.headers().getContentLength()); <ide> }
2
Mixed
Javascript
improve os.setpriority documentation
6e746f1a55e5d94f1a8330d3436a64ed8d6f639b
<ide><path>doc/api/os.md <ide> priority classes, `priority` is mapped to one of six priority constants in <ide> mapping may cause the return value to be slightly different on Windows. To avoid <ide> confusion, it is recommended to set `priority` to one of the priority constants. <ide> <add>On Windows setting priority to `PRIORITY_HIGHEST` requires elevated user, <add>otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. <add> <ide> ## os.tmpdir() <ide> <!-- YAML <ide> added: v0.9.9 <ide><path>test/parallel/test-os-process-priority.js <ide> function checkPriority(pid, expected) { <ide> return; <ide> } <ide> <add> // On Windows setting PRIORITY_HIGHEST will only work for elevated user, <add> // for others it will be silently reduced to PRIORITY_HIGH <ide> if (expected < PRIORITY_HIGH) <del> assert.strictEqual(priority, PRIORITY_HIGHEST); <add> assert.ok(priority === PRIORITY_HIGHEST || priority === PRIORITY_HIGH); <ide> else if (expected < PRIORITY_ABOVE_NORMAL) <ide> assert.strictEqual(priority, PRIORITY_HIGH); <ide> else if (expected < PRIORITY_NORMAL)
2
Python
Python
display version selector for production docs
74dc6fbc585f0b175f6fa922c62d63e0f33d099a
<ide><path>docs/build_docs.py <ide> def _get_parser(): <ide> available_packages_list = " * " + "\n * ".join(get_available_packages()) <ide> parser = argparse.ArgumentParser( <ide> description='Builds documentation and runs spell checking', <del> epilog=f"List of supported documentation packages:\n{available_packages_list}" "", <add> epilog=f"List of supported documentation packages:\n{available_packages_list}", <ide> ) <ide> parser.formatter_class = argparse.RawTextHelpFormatter <ide> parser.add_argument( <ide><path>docs/conf.py <ide> <ide> CONF_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__))) <ide> ROOT_DIR = os.path.abspath(os.path.join(CONF_DIR, os.pardir)) <add>FOR_PRODUCTION = os.environ.get('AIRFLOW_FOR_PRODUCTION', 'false') == 'true' <ide> <ide> # By default (e.g. on RTD), build docs for `airflow` package <ide> PACKAGE_NAME = os.environ.get('AIRFLOW_PACKAGE_NAME', 'apache-airflow') <ide> def _get_rst_filepath_from_path(filepath: str): <ide> # Custom sidebar templates, maps document names to template names. <ide> html_sidebars = { <ide> '**': [ <del> # TODO(mik-laj): TODO: Add again on production version of documentation <del> # 'version-selector.html', <add> 'version-selector.html', <add> 'searchbox.html', <add> 'globaltoc.html', <add> ] <add> if FOR_PRODUCTION <add> else [ <ide> 'searchbox.html', <ide> 'globaltoc.html', <ide> ] <ide> def _get_rst_filepath_from_path(filepath: str): <ide> html_theme_options: Dict[str, Any] = { <ide> 'hide_website_buttons': True, <ide> } <del>if os.environ.get('AIRFLOW_FOR_PRODUCTION', 'false') == 'true': <add>if FOR_PRODUCTION: <ide> html_theme_options['navbar_links'] = [ <ide> {'href': '/community/', 'text': 'Community'}, <ide> {'href': '/meetups/', 'text': 'Meetups'},
2
Ruby
Ruby
remove repeated conditional
634d67690bbb2f0d6520c2f87a1cf8c7e4ceb089
<ide><path>Library/Homebrew/formula_installer.rb <ide> def print_check_output(output) <ide> end <ide> <ide> def audit_bin <del> print_check_output(check_PATH(f.bin)) unless f.keg_only? <add> print_check_output(check_PATH(f.bin)) <ide> print_check_output(check_non_executables(f.bin)) <ide> print_check_output(check_generic_executables(f.bin)) <ide> end <ide> <ide> def audit_sbin <del> print_check_output(check_PATH(f.sbin)) unless f.keg_only? <add> print_check_output(check_PATH(f.sbin)) <ide> print_check_output(check_non_executables(f.sbin)) <ide> print_check_output(check_generic_executables(f.sbin)) <ide> end
1
Python
Python
remove dsome import *
b9a90b371c90a987ed57f7a4a7cc1274c432b438
<ide><path>django/contrib/gis/db/backends/mysql/base.py <del>from django.db.backends.mysql.base import * <ide> from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper <ide> from django.contrib.gis.db.backends.mysql.creation import MySQLCreation <ide> from django.contrib.gis.db.backends.mysql.introspection import MySQLIntrospection <ide> from django.contrib.gis.db.backends.mysql.operations import MySQLOperations <ide> <del>class DatabaseWrapper(MySQLDatabaseWrapper): <ide> <add>class DatabaseWrapper(MySQLDatabaseWrapper): <ide> def __init__(self, *args, **kwargs): <ide> super(DatabaseWrapper, self).__init__(*args, **kwargs) <ide> self.creation = MySQLCreation(self) <ide><path>django/contrib/gis/db/backends/oracle/base.py <del>from django.db.backends.oracle.base import * <ide> from django.db.backends.oracle.base import DatabaseWrapper as OracleDatabaseWrapper <ide> from django.contrib.gis.db.backends.oracle.creation import OracleCreation <ide> from django.contrib.gis.db.backends.oracle.introspection import OracleIntrospection <ide> from django.contrib.gis.db.backends.oracle.operations import OracleOperations <ide> <add> <ide> class DatabaseWrapper(OracleDatabaseWrapper): <ide> def __init__(self, *args, **kwargs): <ide> super(DatabaseWrapper, self).__init__(*args, **kwargs) <ide><path>django/contrib/gis/db/backends/postgis/base.py <del>from django.db.backends.postgresql_psycopg2.base import * <ide> from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper <ide> from django.contrib.gis.db.backends.postgis.creation import PostGISCreation <ide> from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection <ide> from django.contrib.gis.db.backends.postgis.operations import PostGISOperations <ide> <add> <ide> class DatabaseWrapper(Psycopg2DatabaseWrapper): <ide> def __init__(self, *args, **kwargs): <ide> super(DatabaseWrapper, self).__init__(*args, **kwargs)
3
Ruby
Ruby
imporve revision check logic
d4c7dedf1246e31daca2aa9be22f8f6e4a6c528f
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_revision <ide> revision_map = fv.revision_map("origin/master") <ide> if (revisions = revision_map[formula.version]).any? <ide> problem "revision should not decrease" if formula.revision < revisions.max <del> else <del> problem "revision should be removed" unless formula.revision == 0 <add> elsif formula.revision != 0 <add> if formula.stable <add> if revision_map[formula.stable.version].empty? # check stable spec <add> problem "revision should be removed" <add> end <add> else # head/devel-only formula <add> problem "revision should be removed" <add> end <ide> end <ide> end <ide>
1
PHP
PHP
fix doc block
7cde02d2b7cc6bdd415b33a0f3d54b579c41ebe8
<ide><path>src/Illuminate/Notifications/Messages/MailMessage.php <ide> protected function arrayOfAddresses($address) <ide> /** <ide> * Render the mail notification message into an HTML string. <ide> * <del> * @return string <add> * @return \Illuminate\Support\HtmlString <ide> */ <ide> public function render() <ide> {
1
Text
Text
fix typo in readme
bd2bd51b5d48911fdaefa14162b02b545562df1e
<ide><path>README.md <ide> Keras is compatible with: __Python 2.7-3.5__. <ide> <ide> ## Getting started: 30 seconds to Keras <ide> <del>The core data structure of Keras is a __model__, a way to organize layers. The main type of model is the [`Sequential`](http://keras.io/getting-started/sequential-model-guide) model, a linear stack of layers. For more complex architectures, you should use the [Keras function API](http://keras.io/getting-started/functional-api-guide). <add>The core data structure of Keras is a __model__, a way to organize layers. The main type of model is the [`Sequential`](http://keras.io/getting-started/sequential-model-guide) model, a linear stack of layers. For more complex architectures, you should use the [Keras functional API](http://keras.io/getting-started/functional-api-guide). <ide> <ide> Here's the `Sequential` model: <ide>
1
Ruby
Ruby
fix script name in watchr-docs.rb
9f6c5db2a6ed10d3152fcb4aed8733043833362b
<ide><path>watchr-docs.rb <ide> # note: make sure that you have jstd server running (server.sh) and a browser captured <ide> <ide> watch( '^src/|^docs/' ) do <del> %x{ echo "\n\ndoc run started @ `date`" > logs/docs.log; node docs/collect.js &> logs/docs.log & } <add> %x{ echo "\n\ndoc run started @ `date`" > logs/docs.log; node docs/src/gen-docs.js &> logs/docs.log & } <ide> end
1
Text
Text
update doc with usage of the scratch image
77bd53adfe6877acd1ff8f07cf148f1dbe0b425d
<ide><path>docs/sources/articles/baseimages.md <ide> GitHub Repo: <ide> - [Debian / Ubuntu]( <ide> https://github.com/docker/docker/blob/master/contrib/mkimage-debootstrap.sh) <ide> <del>## Creating a simple base image using `scratch` <add>## Creating a simple base image using scratch <ide> <del>There is a special repository in the Docker registry called `scratch`, which <del>was created using an empty tar file: <add>You can use Docker's reserved, minimal image, `scratch`, as a starting point for building containers. Using the `scratch` "image" signals to the build process that you want the next command in the `Dockerfile` to be the first filesystem layer in your image. <ide> <del> $ tar cv --files-from /dev/null | docker import - scratch <del> <del>which you can `docker pull`. You can then use that <del>image to base your new minimal containers `FROM`: <add>While `scratch` appears in Docker's repository on the hub, you can't pull it, run it, or tag any image with the name `scratch`. Instead, you can refer to it in your `Dockerfile`. For example, to create a minimal container using `scratch`: <ide> <ide> FROM scratch <del> COPY true-asm /true <del> CMD ["/true"] <add> ADD hello / <add> CMD ["/hello"] <add> <add>This example creates the hello-world image used in the tutorials. <add>If you want to test it out, you can clone [the image repo](https://github.com/docker-library/hello-world) <ide> <del>The `Dockerfile` above is from an extremely minimal image - [tianon/true]( <del>https://github.com/tianon/dockerfiles/tree/master/true). <ide> <ide> ## More resources <ide>
1
PHP
PHP
fix email testsendrenderwithhelpers() test
3d6c949f21db29c750586c16a4867e52e0292fd4
<ide><path>Cake/Test/TestCase/Network/Email/EmailTest.php <ide> public function testSendRenderWithHelpers() { <ide> $this->assertInstanceOf('Cake\Network\Email\Email', $result); <ide> <ide> $result = $this->CakeEmail->send(); <del> $this->assertTrue((bool)strpos($result['message'], 'Right now: ' . date('Y-m-d\TH:i:s\Z', $timestamp))); <add> $dateTime = new \DateTime; <add> $dateTime->setTimestamp($timestamp); <add> $this->assertTrue((bool)strpos($result['message'], 'Right now: ' . $dateTime->format($dateTime::ATOM))); <ide> <ide> $result = $this->CakeEmail->helpers(); <ide> $this->assertEquals(array('Time'), $result);
1
PHP
PHP
simplify eloquent collections
d050a1b64004fb4f5db48cd046b0b0f932b6d5b6
<ide><path>src/Illuminate/Database/Eloquent/Collection.php <ide> <ide> class Collection extends BaseCollection { <ide> <del> /** <del> * A dictionary of available primary keys. <del> * <del> * @var array <del> */ <del> protected $dictionary = array(); <del> <ide> /** <ide> * Find a model in the collection by key. <ide> * <ide> class Collection extends BaseCollection { <ide> */ <ide> public function find($key, $default = null) <ide> { <del> if (count($this->dictionary) == 0) <add> return array_first($this->items, function($key, $model) use ($key) <ide> { <del> $this->buildDictionary(); <del> } <add> return $model->getKey() == $key; <ide> <del> return array_get($this->dictionary, $key, $default); <add> }, $default); <ide> } <ide> <ide> /** <ide> public function add($item) <ide> { <ide> $this->items[] = $item; <ide> <del> // If the dictionary is empty, we will re-build it upon adding the item so <del> // we can quickly search it from the "contains" method. This dictionary <del> // will give us faster look-up times while searching for given items. <del> if (count($this->dictionary) == 0) <del> { <del> $this->buildDictionary(); <del> } <del> <del> // If this dictionary has already been initially hydrated, we just need to <del> // add an entry for the added item, which we will do here so that we'll <del> // be able to quickly determine it is in the array when asked for it. <del> elseif ($item instanceof Model) <del> { <del> $this->dictionary[$item->getKey()] = true; <del> } <del> <ide> return $this; <ide> } <ide> <ide> public function add($item) <ide> */ <ide> public function contains($key) <ide> { <del> if (count($this->dictionary) == 0) <del> { <del> $this->buildDictionary(); <del> } <del> <del> return isset($this->dictionary[$key]); <del> } <del> <del> /** <del> * Build the dictionary of primary keys. <del> * <del> * @return void <del> */ <del> protected function buildDictionary() <del> { <del> $this->dictionary = array(); <del> <del> // By building the dictionary of items by key, we are able to more quickly <del> // access the array and examine it for certain items. This is useful on <del> // the contain method which searches through the list by primary key. <del> foreach ($this->items as $item) <del> { <del> if ($item instanceof Model) <del> { <del> $this->dictionary[$item->getKey()] = $item; <del> } <del> } <add> return ! is_null($this->find($key)); <ide> } <ide> <ide> /** <ide> protected function buildDictionary() <ide> */ <ide> public function modelKeys() <ide> { <del> if (count($this->dictionary) === 0) $this->buildDictionary(); <del> <del> return array_keys($this->dictionary); <add> return array_map(function($m) { return $m->getKey(); }, $this->items); <ide> } <ide> <ide> }
1
Go
Go
find a free device id to use for device creation
e28a419e1197bf50bbb378b02f0226c3115edeaa
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> func (devices *DeviceSet) incNextDeviceId() { <ide> devices.NextDeviceId = (devices.NextDeviceId + 1) & MaxDeviceId <ide> } <ide> <del>func (devices *DeviceSet) getNextDeviceId() int { <add>func (devices *DeviceSet) getNextFreeDeviceId() (int, error) { <ide> devices.incNextDeviceId() <del> return devices.NextDeviceId <add> for i := 0; i <= MaxDeviceId; i++ { <add> if devices.isDeviceIdFree(devices.NextDeviceId) { <add> devices.markDeviceIdUsed(devices.NextDeviceId) <add> return devices.NextDeviceId, nil <add> } <add> devices.incNextDeviceId() <add> } <add> <add> return 0, fmt.Errorf("Unable to find a free device Id") <ide> } <ide> <ide> func (devices *DeviceSet) createRegisterDevice(hash string) (*DevInfo, error) { <del> deviceId := devices.getNextDeviceId() <add> deviceId, err := devices.getNextFreeDeviceId() <add> if err != nil { <add> return nil, err <add> } <add> <ide> for { <ide> if err := devicemapper.CreateDevice(devices.getPoolDevName(), deviceId); err != nil { <ide> if devicemapper.DeviceIdExists(err) { <del> // Device Id already exists. Try a new one. <del> deviceId = devices.getNextDeviceId() <add> // Device Id already exists. This should not <add> // happen. Now we have a mechianism to find <add> // a free device Id. So something is not right. <add> // Give a warning and continue. <add> log.Errorf("Warning: Device Id %d exists in pool but it is supposed to be unused", deviceId) <add> deviceId, err = devices.getNextFreeDeviceId() <add> if err != nil { <add> return nil, err <add> } <ide> continue <ide> } <ide> log.Debugf("Error creating device: %s", err) <add> devices.markDeviceIdFree(deviceId) <ide> return nil, err <ide> } <ide> break <ide> func (devices *DeviceSet) createRegisterDevice(hash string) (*DevInfo, error) { <ide> info, err := devices.registerDevice(deviceId, hash, devices.baseFsSize, transactionId) <ide> if err != nil { <ide> _ = devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId) <add> devices.markDeviceIdFree(deviceId) <ide> return nil, err <ide> } <ide> <ide> if err := devices.updatePoolTransactionId(); err != nil { <ide> devices.unregisterDevice(deviceId, hash) <ide> devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId) <add> devices.markDeviceIdFree(deviceId) <ide> return nil, err <ide> } <ide> return info, nil <ide> } <ide> <ide> func (devices *DeviceSet) createRegisterSnapDevice(hash string, baseInfo *DevInfo) error { <del> deviceId := devices.getNextDeviceId() <add> deviceId, err := devices.getNextFreeDeviceId() <add> if err != nil { <add> return err <add> } <add> <ide> for { <ide> if err := devicemapper.CreateSnapDevice(devices.getPoolDevName(), deviceId, baseInfo.Name(), baseInfo.DeviceId); err != nil { <ide> if devicemapper.DeviceIdExists(err) { <del> // Device Id already exists. Try a new one. <del> deviceId = devices.getNextDeviceId() <add> // Device Id already exists. This should not <add> // happen. Now we have a mechianism to find <add> // a free device Id. So something is not right. <add> // Give a warning and continue. <add> log.Errorf("Warning: Device Id %d exists in pool but it is supposed to be unused", deviceId) <add> deviceId, err = devices.getNextFreeDeviceId() <add> if err != nil { <add> return err <add> } <ide> continue <ide> } <ide> log.Debugf("Error creating snap device: %s", err) <add> devices.markDeviceIdFree(deviceId) <ide> return err <ide> } <ide> break <ide> func (devices *DeviceSet) createRegisterSnapDevice(hash string, baseInfo *DevInf <ide> transactionId := devices.allocateTransactionId() <ide> if _, err := devices.registerDevice(deviceId, hash, baseInfo.Size, transactionId); err != nil { <ide> devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId) <add> devices.markDeviceIdFree(deviceId) <ide> log.Debugf("Error registering device: %s", err) <ide> return err <ide> } <ide> <ide> if err := devices.updatePoolTransactionId(); err != nil { <ide> devices.unregisterDevice(deviceId, hash) <ide> devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId) <add> devices.markDeviceIdFree(deviceId) <ide> return err <ide> } <ide> return nil <ide> func (devices *DeviceSet) deleteDevice(info *DevInfo) error { <ide> return err <ide> } <ide> <add> devices.markDeviceIdFree(info.DeviceId) <add> <ide> return nil <ide> } <ide>
1
Ruby
Ruby
fix two mimetype failing test cases
00c46b5eeb858629ef1c7ab50f022aecccca42c3
<ide><path>actionpack/lib/action_controller/mime_type.rb <ide> module Mime <ide> # end <ide> class Type <ide> @@html_types = Set.new [:html, :url_encoded_form, :multipart_form, :all] <add> cattr_reader :html_types <add> <add> # UNUSED, deprecate? <ide> @@unverifiable_types = Set.new [:text, :json, :csv, :xml, :rss, :atom, :yaml] <del> cattr_reader :html_types, :unverifiable_types <add> cattr_reader :unverifiable_types <ide> <ide> # A simple helper class used in parsing the accept header <ide> class AcceptItem #:nodoc: <ide><path>actionpack/test/controller/mime_type_test.rb <ide> def test_type_convenience_methods <ide> types.each do |type| <ide> mime = Mime.const_get(type.to_s.upcase) <ide> assert mime.send("#{type}?"), "#{mime.inspect} is not #{type}?" <del> (types - [type]).each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" } <add> invalid_types = types - [type] <add> invalid_types.delete(:html) if Mime::Type.html_types.include?(type) <add> invalid_types.each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" } <ide> end <ide> end <ide> <ide> def test_mime_all_is_html <ide> end <ide> <ide> def test_verifiable_mime_types <del> unverified_types = Mime::Type.unverifiable_types <ide> all_types = Mime::SET.to_a.map(&:to_sym) <ide> all_types.uniq! <ide> # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE <ide> all_types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) } <del> <del> unverified, verified = all_types.partition { |type| Mime::Type.unverifiable_types.include? type } <del> assert verified.all? { |type| Mime.const_get(type.to_s.upcase).verify_request? }, "Not all Mime Types are verified: #{verified.inspect}" <del> assert unverified.all? { |type| !Mime.const_get(type.to_s.upcase).verify_request? }, "Some Mime Types are verified: #{unverified.inspect}" <add> verified, unverified = all_types.partition { |type| Mime::Type.html_types.include? type } <add> assert verified.each { |type| assert Mime.const_get(type.to_s.upcase).verify_request?, "Mime Type is not verified: #{type.inspect}" } <add> assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Mime Type is verified: #{type.inspect}" } <ide> end <ide> end
2
Text
Text
add missing spaces
a5528b86386e5c35cf90c863758812a7724e2008
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/hash-and-compare-passwords-asynchronously.md <ide> bcrypt.hash(myPlaintextPassword, saltRounds, (err, hash) => { <ide> <ide> # --instructions-- <ide> <del>Add this hashing function to your server(we've already defined the variables used in the function for you to use) and log it to the console for you to see! At this point you would normally save the hash to your database. <add>Add this hashing function to your server (we've already defined the variables used in the function for you to use) and log it to the console for you to see! At this point you would normally save the hash to your database. <ide> <ide> Now when you need to figure out if a new input is the same data as the hash you would just use the compare function. <ide> <ide> bcrypt.compare(myPlaintextPassword, hash, (err, res) => { <ide> }); <ide> ``` <ide> <del>Add this into your existing hash function(since you need to wait for the hash to complete before calling the compare function) after you log the completed hash and log 'res' to the console within the compare. You should see in the console a hash then 'true' is printed! If you change 'myPlaintextPassword' in the compare function to 'someOtherPlaintextPassword' then it should say false. <add>Add this into your existing hash function (since you need to wait for the hash to complete before calling the compare function) after you log the completed hash and log 'res' to the console within the compare. You should see in the console a hash then 'true' is printed! If you change 'myPlaintextPassword' in the compare function to 'someOtherPlaintextPassword' then it should say false. <ide> <ide> ```js <ide> bcrypt.hash('passw0rd!', 13, (err, hash) => {
1
Ruby
Ruby
remove useless || operation
ee314a5e5aa2b29978b78fbe1b272bcfff865d4a
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def process(*args) <ide> # # assert that the "_customer" partial was rendered with a specific object <ide> # assert_template partial: '_customer', locals: { customer: @customer } <ide> def assert_template(options = {}, message = nil) <del> # Force body to be read in case the <del> # template is being streamed <add> # Force body to be read in case the template is being streamed. <ide> response.body <ide> <ide> case options <ide><path>actionpack/test/controller/layout_test.rb <ide> class DefaultLayoutController < LayoutTest <ide> <ide> class StreamingLayoutController < LayoutTest <ide> def render(*args) <del> options = args.extract_options! || {} <add> options = args.extract_options! <ide> super(*args, options.merge(:stream => true)) <ide> end <ide> end
2
PHP
PHP
use singleton method for binding shared instance
15ccd0bb8ade9b54e9bc776344de0515408d9ff0
<ide><path>src/Illuminate/Events/EventServiceProvider.php <ide> class EventServiceProvider extends ServiceProvider { <ide> */ <ide> public function register() <ide> { <del> $this->app['events'] = $this->app->share(function($app) <add> $this->app->singleton('events', function($app) <ide> { <ide> return new Dispatcher($app); <ide> });
1
Java
Java
remove trailing whitespace
89a4c291c3feae04798d1fc234cdbd82bb7ad9a9
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/BufferingStompDecoderTests.java <ide> public void basic() throws InterruptedException { <ide> assertEquals(0, stompDecoder.getBufferSize()); <ide> assertNull(stompDecoder.getExpectedContentLength()); <ide> } <del> <add> <ide> @Test <ide> public void oneMessageInTwoChunks() throws InterruptedException { <ide> <ide><path>spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java <ide> public static String readScript(LineNumberReader lineNumberReader) throws IOExce <ide> * @param commentPrefix the prefix that identifies comments in the SQL script &mdash; typically "--" <ide> * @return a {@code String} containing the script lines <ide> * @deprecated as of Spring 4.0.3, in favor of using <del> * {@link org.springframework.jdbc.datasource.init.ScriptUtils#readScript(LineNumberReader, String, String)} <add> * {@link org.springframework.jdbc.datasource.init.ScriptUtils#readScript(LineNumberReader, String, String)} <ide> */ <ide> @Deprecated <ide> public static String readScript(LineNumberReader lineNumberReader, String commentPrefix) throws IOException { <ide> public static boolean containsSqlScriptDelimiters(String script, char delim) { <ide> * @param delim character delimiting each statement &mdash; typically a ';' character <ide> * @param statements the list that will contain the individual statements <ide> * @deprecated as of Spring 4.0.3, in favor of using <del> * {@link org.springframework.jdbc.datasource.init.ScriptUtils#splitSqlScript(String, char, List)} <add> * {@link org.springframework.jdbc.datasource.init.ScriptUtils#splitSqlScript(String, char, List)} <ide> */ <ide> @Deprecated <ide> public static void splitSqlScript(String script, char delim, List<String> statements) {
2
Go
Go
add cgo or osusergo buildtag constraints for unix
023b072288eab3c9e768d4aeeb917f27f06034c7
<ide><path>pkg/homedir/homedir_unix.go <del>// +build !windows <add>// +build !windows,cgo !windows,osusergo <ide> <ide> package homedir // import "github.com/docker/docker/pkg/homedir" <ide>
1
Ruby
Ruby
call to_s on ohai parameters
e1995d60efa90f05fa3292d758e47ac20f33d9e7
<ide><path>Library/Homebrew/utils.rb <ide> def escape n <ide> <ide> # args are additional inputs to puts until a nil arg is encountered <ide> def ohai title, *sput <del> title = title[0, `/usr/bin/tput cols`.strip.to_i-4] unless ARGV.verbose? <add> title = title.to_s[0, `/usr/bin/tput cols`.strip.to_i-4] unless ARGV.verbose? <ide> puts "#{Tty.blue}==>#{Tty.white} #{title}#{Tty.reset}" <ide> puts *sput unless sput.empty? <ide> end
1
PHP
PHP
convert assertions to assetcontains
bbef4aa36d6383c7ee481ce18fdd437bc32a18fd
<ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> public function testSendRender() { <ide> $this->CakeEmail->template('default', 'default'); <ide> $result = $this->CakeEmail->send(); <ide> <del> $this->assertTrue((bool)strpos($result['message'], 'This email was sent using the CakePHP Framework')); <del> $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: ')); <del> $this->assertTrue((bool)strpos($result['headers'], 'To: ')); <add> $this->assertContains('This email was sent using the CakePHP Framework', $result['message']); <add> $this->assertContains('Message-ID: ', $result['headers']); <add> $this->assertContains('To: ', $result['headers']); <ide> } <ide> <ide> /** <ide> public function testSendRenderJapanese() { <ide> $result = $this->CakeEmail->send(); <ide> <ide> $expected = mb_convert_encoding('CakePHP Framework を使って送信したメールです。 http://cakephp.org.','ISO-2022-JP'); <del> $this->assertTrue((bool)strpos($result['message'], $expected)); <del> $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: ')); <del> $this->assertTrue((bool)strpos($result['headers'], 'To: ')); <add> $this->assertContains($expected, $result['message']); <add> $this->assertContains('Message-ID: ', $result['headers']); <add> $this->assertContains('To: ', $result['headers']); <ide> } <ide> <ide> /** <ide> public function testSendRenderWithVars() { <ide> $this->CakeEmail->viewVars(array('value' => 12345)); <ide> $result = $this->CakeEmail->send(); <ide> <del> $this->assertTrue((bool)strpos($result['message'], 'Here is your value: 12345')); <add> $this->assertContains('Here is your value: 12345', $result['message']); <ide> } <ide> <ide> /** <ide> public function testSendRenderPlugin() { <ide> $this->CakeEmail->config(array('empty')); <ide> <ide> $result = $this->CakeEmail->template('TestPlugin.test_plugin_tpl', 'default')->send(); <del> $this->assertTrue((bool)strpos($result['message'], 'Into TestPlugin.')); <del> $this->assertTrue((bool)strpos($result['message'], 'This email was sent using the CakePHP Framework')); <add> $this->assertContains('Into TestPlugin.', $result['message']); <add> $this->assertContains('This email was sent using the CakePHP Framework', $result['message']); <ide> <ide> $result = $this->CakeEmail->template('TestPlugin.test_plugin_tpl', 'TestPlugin.plug_default')->send(); <del> $this->assertTrue((bool)strpos($result['message'], 'Into TestPlugin.')); <del> $this->assertTrue((bool)strpos($result['message'], 'This email was sent using the TestPlugin.')); <add> $this->assertContains('Into TestPlugin.', $result['message']); <add> $this->assertContains('This email was sent using the TestPlugin.', $result['message']); <ide> <ide> $result = $this->CakeEmail->template('TestPlugin.test_plugin_tpl', 'plug_default')->send(); <del> $this->assertTrue((bool)strpos($result['message'], 'Into TestPlugin.')); <del> $this->assertTrue((bool)strpos($result['message'], 'This email was sent using the TestPlugin.')); <add> $this->assertContains('Into TestPlugin.', $result['message']); <add> $this->assertContains('This email was sent using the TestPlugin.', $result['message']); <ide> <ide> $this->CakeEmail->viewVars(array('value' => 12345)); <ide> $result = $this->CakeEmail->template('custom', 'TestPlugin.plug_default')->send(); <del> $this->assertTrue((bool)strpos($result['message'], 'Here is your value: 12345')); <del> $this->assertTrue((bool)strpos($result['message'], 'This email was sent using the TestPlugin.')); <add> $this->assertContains('Here is your value: 12345', $result['message']); <add> $this->assertContains('This email was sent using the TestPlugin.', $result['message']); <ide> <ide> $this->setExpectedException('MissingViewException'); <ide> $this->CakeEmail->template('test_plugin_tpl', 'plug_default')->send(); <ide> public function testSendMultipleMIME() { <ide> $message = $this->CakeEmail->message(); <ide> $boundary = $this->CakeEmail->getBoundary(); <ide> $this->assertFalse(empty($boundary)); <del> $this->assertFalse(in_array('--' . $boundary, $message)); <del> $this->assertFalse(in_array('--' . $boundary . '--', $message)); <del> $this->assertTrue(in_array('--alt-' . $boundary, $message)); <del> $this->assertTrue(in_array('--alt-' . $boundary . '--', $message)); <add> $this->assertNotContains('--' . $boundary, $message); <add> $this->assertNotContains('--' . $boundary . '--', $message); <add> $this->assertContains('--alt-' . $boundary, $message); <add> $this->assertContains('--alt-' . $boundary . '--', $message); <ide> <ide> $this->CakeEmail->attachments(array('fake.php' => __FILE__)); <ide> $this->CakeEmail->send(); <ide> <ide> $message = $this->CakeEmail->message(); <ide> $boundary = $this->CakeEmail->getBoundary(); <ide> $this->assertFalse(empty($boundary)); <del> $this->assertTrue(in_array('--' . $boundary, $message)); <del> $this->assertTrue(in_array('--' . $boundary . '--', $message)); <del> $this->assertTrue(in_array('--alt-' . $boundary, $message)); <del> $this->assertTrue(in_array('--alt-' . $boundary . '--', $message)); <add> $this->assertContains('--' . $boundary, $message); <add> $this->assertContains('--' . $boundary . '--', $message); <add> $this->assertContains('--alt-' . $boundary, $message); <add> $this->assertContains('--alt-' . $boundary . '--', $message); <ide> } <ide> <ide> /** <ide> public function testMessage() { <ide> $result = $this->CakeEmail->send(); <ide> <ide> $expected = '<p>This email was sent using the <a href="http://cakephp.org">CakePHP Framework</a></p>'; <del> $this->assertTrue((bool)strpos($this->CakeEmail->message(CakeEmail::MESSAGE_HTML), $expected)); <add> $this->assertContains($expected, $this->CakeEmail->message(CakeEmail::MESSAGE_HTML)); <ide> <ide> $expected = 'This email was sent using the CakePHP Framework, http://cakephp.org.'; <del> $this->assertTrue((bool)strpos($this->CakeEmail->message(CakeEmail::MESSAGE_TEXT), $expected)); <add> $this->assertContains($expected, $this->CakeEmail->message(CakeEmail::MESSAGE_TEXT)); <ide> <ide> $message = $this->CakeEmail->message(); <del> $this->assertTrue(in_array('Content-Type: text/plain; charset=UTF-8', $message)); <del> $this->assertTrue(in_array('Content-Type: text/html; charset=UTF-8', $message)); <add> $this->assertContains('Content-Type: text/plain; charset=UTF-8', $message); <add> $this->assertContains('Content-Type: text/html; charset=UTF-8', $message); <ide> <ide> // UTF-8 is 8bit <ide> $this->assertTrue($this->checkContentTransferEncoding($message, '8bit')); <ide> public function testMessage() { <ide> $this->CakeEmail->charset = 'ISO-2022-JP'; <ide> $this->CakeEmail->send(); <ide> $message = $this->CakeEmail->message(); <del> $this->assertTrue(in_array('Content-Type: text/plain; charset=ISO-2022-JP', $message)); <del> $this->assertTrue(in_array('Content-Type: text/html; charset=ISO-2022-JP', $message)); <add> $this->assertContains('Content-Type: text/plain; charset=ISO-2022-JP', $message); <add> $this->assertContains('Content-Type: text/html; charset=ISO-2022-JP', $message); <ide> <ide> // ISO-2022-JP is 7bit <ide> $this->assertTrue($this->checkContentTransferEncoding($message, '7bit'));
1
PHP
PHP
extend()`
3f0645cf38f51b235ec280b35922e3fe84f0be96
<ide><path>src/Illuminate/Support/Facades/Storage.php <ide> * @method static bool delete(string|array $paths) <ide> * @method static bool deleteDirectory(string $directory) <ide> * @method static bool exists(string $path) <add> * @method static \Illuminate\Filesystem\FilesystemManager extend(string $driver, \Closure $callback) <ide> * @method static bool makeDirectory(string $path) <ide> * @method static bool move(string $from, string $to) <ide> * @method static bool prepend(string $path, string $data)
1
Javascript
Javascript
add tool to format/sort code in files
beaded63c34740af536532ea94ffbf30adcfeb1f
<ide><path>tooling/format-file-header.js <add>const path = require("path"); <add>const fs = require("fs"); <add> <add>// When --write is set, files will be written in place <add>// Elsewise it only prints outdated files <add>const doWrite = process.argv.includes("--write"); <add> <add>const allFiles = new Set(); <add>const findFiles = p => { <add> const s = fs.statSync(p); <add> if (s.isDirectory()) { <add> for (const name of fs.readdirSync(p)) { <add> if (name.startsWith(".")) continue; <add> findFiles(path.join(p, name)); <add> } <add> } else if (s.isFile()) { <add> allFiles.add(p); <add> } <add>}; <add>findFiles(path.resolve(__dirname, "../lib")); <add> <add>let canUpdateWithWrite = false; <add> <add>const sortImport = (a, b) => { <add> if (!a.key.startsWith(".") && b.key.startsWith(".")) return -1; <add> if (a.key.startsWith(".") && !b.key.startsWith(".")) return 1; <add> if (a.key < b.key) return -1; <add> if (a.key > b.key) return 1; <add> return 0; <add>}; <add> <add>const execToArray = (content, regexp) => { <add> const items = []; <add> let match = regexp.exec(content); <add> while (match) { <add> items.push({ <add> content: match[0], <add> key: match[1] + match[2] <add> }); <add> match = regexp.exec(content); <add> } <add> return items; <add>}; <add> <add>const schema = [ <add> { <add> title: "license comment", <add> regexp: /\/\*\n\s*MIT License http:\/\/www\.opensource\.org\/licenses\/mit-license\.php\n\s*(?:(Authors? .+)\n)?\s*\*\/\n/g, <add> updateMessage: "update the license comment", <add> update(content, author) { <add> return ( <add> [ <add> "/*", <add> "\tMIT License http://www.opensource.org/licenses/mit-license.php", <add> author && `\t${author}`, <add> "*/" <add> ] <add> .filter(Boolean) <add> .join("\n") + "\n" <add> ); <add> } <add> }, <add> { <add> title: "new line after license comment", <add> regexp: /\n?/g, <add> updateMessage: "insert a new line after the license comment", <add> update() { <add> return "\n"; <add> } <add> }, <add> { <add> title: "strict mode", <add> regexp: /"use strict";\n/g <add> }, <add> { <add> title: "new line after strict mode", <add> regexp: /\n?/g, <add> updateMessage: 'insert a new line after "use strict"', <add> update() { <add> return "\n"; <add> } <add> }, <add> { <add> title: "imports", <add> regexp: /(const (\{\s+\w+(,\s+\w+)*\s+\}|\w+) = require\("[^"]+"\)(\.\w+)*;\n)+\n/g, <add> updateMessage: "sort imports alphabetically", <add> update(content) { <add> const items = execToArray( <add> content, <add> /const (?:\{\s+\w+(?:,\s+\w+)*\s+\}|\w+) = require\("([^"]+)"\)((?:\.\w+)*);\n/g <add> ); <add> items.sort(sortImport); <add> return items.map(item => item.content).join("") + "\n"; <add> }, <add> optional: true, <add> repeat: true <add> }, <add> { <add> title: "type imports", <add> regexp: /(\/\*\* @typedef \{import\("[^"]+"\)(\.\w+)*\} \w+ \*\/\n)+\n/g, <add> updateMessage: "sort type imports alphabetically", <add> update(content) { <add> const items = execToArray( <add> content, <add> /\/\*\* @typedef \{import\("([^"]+)"\)((?:\.\w+)*)\} \w+ \*\/\n/g <add> ); <add> items.sort(sortImport); <add> return items.map(item => item.content).join("") + "\n"; <add> }, <add> optional: true, <add> repeat: true <add> } <add>]; <add> <add>for (const filePath of allFiles) { <add> let content = fs.readFileSync(filePath, "utf-8"); <add> const nl = /(\r?\n)/.exec(content); <add> content = content.replace(/\r?\n/g, "\n"); <add> let newContent = content; <add> <add> let state = 0; <add> let pos = 0; <add> // eslint-disable-next-line no-constant-condition <add> while (true) { <add> const current = schema[state]; <add> if (!current) break; <add> current.regexp.lastIndex = pos; <add> const match = current.regexp.exec(newContent); <add> if (!match) { <add> if (current.optional) { <add> state++; <add> continue; <add> } <add> console.log(`${filePath}: Missing ${current.title} at ${pos}`); <add> process.exitCode = 1; <add> break; <add> } <add> if (match.index !== pos) { <add> console.log( <add> `${filePath}: Unexpected code at ${pos}-${match.index}, expected ${ <add> current.title <add> }` <add> ); <add> process.exitCode = 1; <add> pos = match.index; <add> } <add> if (!current.repeat) { <add> state++; <add> } <add> if (current.update) { <add> const update = current.update(...match); <add> if (update !== match[0]) { <add> newContent = <add> newContent.substr(0, pos) + <add> update + <add> newContent.slice(pos + match[0].length); <add> pos += update.length; <add> if (!doWrite) { <add> const updateMessage = <add> current.updateMessage || `${current.title} need to be updated`; <add> console.log(`${filePath}: ${updateMessage}`); <add> } <add> continue; <add> } <add> } <add> pos += match[0].length; <add> } <add> <add> if (newContent !== content) { <add> if (doWrite) { <add> if (nl) { <add> newContent = newContent.replace(/\n/g, nl[0]); <add> } <add> fs.writeFileSync(filePath, newContent, "utf-8"); <add> console.log(filePath); <add> } else { <add> canUpdateWithWrite = true; <add> process.exitCode = 1; <add> } <add> } <add>} <add> <add>if (canUpdateWithWrite) { <add> console.log("Run 'yarn fix' to try to fix the problem automatically"); <add>}
1
PHP
PHP
add missing docblock
6884c5442095175cc042f42ef2066204c0d35a96
<ide><path>src/Illuminate/Auth/CreatesUserProviders.php <ide> trait CreatesUserProviders <ide> * <ide> * @param string $provider <ide> * @return \Illuminate\Contracts\Auth\UserProvider <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> protected function createUserProvider($provider) <ide> {
1
PHP
PHP
add test case
9e3b24a93d0216568ab7ac07165f6877ae4d1ba4
<ide><path>tests/TestCase/Utility/TextTest.php <ide> public function testTransliterate($string, $transliterator, $expected) <ide> $this->assertSame($expected, $result); <ide> } <ide> <del> public function slugInputProvider() <add> /** <add> * @return array <add> */ <add> public function slugInputProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/View/Helper/TextHelperTest.php <ide> public function testAutoParagraph() <ide> $result = $this->Text->autoParagraph(null); <ide> $this->assertTextEquals($expected, $result); <ide> } <add> <add> /** <add> * testSlug method <add> * <add> * @param string $string String <add> * @param array $options Options <add> * @param String $expected Expected string <add> * @return void <add> * @dataProvider slugInputProvider <add> */ <add> public function testSlug($string, $options, $expected) <add> { <add> $result = $this->Text->slug($string, $options); <add> $this->assertSame($expected, $result); <add> } <add> <add> /** <add> * @return array <add> */ <add> public function slugInputProvider(): array <add> { <add> return [ <add> [ <add> 'Foo Bar: Not just for breakfast any-more', [], <add> 'Foo-Bar-Not-just-for-breakfast-any-more', <add> ], <add> [ <add> 'Foo Bar: Not just for breakfast any-more', ['replacement' => false], <add> 'FooBarNotjustforbreakfastanymore', <add> ], <add> ]; <add> } <ide> }
2
Python
Python
remove extra pipe config values before merging
91a6637f74aa4b88c203a56d2358f77d77ec75d5
<ide><path>spacy/language.py <ide> def get_pipe_config(self, name: str) -> Config: <ide> if name not in self._pipe_configs: <ide> raise ValueError(Errors.E960.format(name=name)) <ide> pipe_config = self._pipe_configs[name] <del> pipe_config.pop("nlp", None) <del> pipe_config.pop("name", None) <ide> return pipe_config <ide> <ide> @classmethod <ide> def create_pipe( <ide> filled = Config(filled[factory_name]) <ide> filled["factory"] = factory_name <ide> filled.pop("@factories", None) <add> # Remove the extra values we added because we don't want to keep passing <add> # them around, copying them etc. <add> filled.pop("nlp", None) <add> filled.pop("name", None) <ide> # Merge the final filled config with the raw config (including non- <ide> # interpolated variables) <ide> if raw_config: <ide><path>spacy/tests/pipeline/test_pipe_factories.py <ide> def test_pipe_factories_decorator_idempotent(): <ide> nlp = Language() <ide> nlp.add_pipe(name) <ide> Language.component(name2, func=func2) <add> <add> <add>def test_pipe_factories_config_excludes_nlp(): <add> """Test that the extra values we temporarily add to component config <add> blocks/functions are removed and not copied around. <add> """ <add> name = "test_pipe_factories_config_excludes_nlp" <add> func = lambda nlp, name: lambda doc: doc <add> Language.factory(name, func=func) <add> config = { <add> "nlp": {"lang": "en", "pipeline": [name]}, <add> "components": {name: {"factory": name}}, <add> } <add> nlp = English.from_config(config) <add> assert nlp.pipe_names == [name] <add> pipe_cfg = nlp.get_pipe_config(name) <add> pipe_cfg == {"factory": name} <add> assert nlp._pipe_configs[name] == {"factory": name}
2
Javascript
Javascript
remove pm2 memory fanciness
f710fa1af60159b1c1bc9db8c398a1638ee8e233
<ide><path>pm2Start.js <ide> pm2.connect(function() { <ide> script: 'server/production-start.js', <ide> 'exec_mode': 'cluster', <ide> instances: process.env.INSTANCES || 1, <del> 'max_memory_restart': <del> (process.env.MAX_MEMORY / process.env.INSTANCES || 1) || '300M', <add> 'max_memory_restart': process.env.MAX_MEMORY || '300M', <ide> 'NODE_ENV': 'production' <ide> }, function() { <ide> pm2.disconnect();
1
Ruby
Ruby
replace hash#delete_if with hash#compact!
aa5d471abd11d6e80f8a2741d59a1d8472a86dd4
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> module ActiveRecord <ide> module ConnectionHandling # :nodoc: <ide> # Establishes a connection to the database that's used by all Active Record objects <ide> def postgresql_connection(config) <del> conn_params = config.symbolize_keys <del> <del> conn_params.delete_if { |_, v| v.nil? } <add> conn_params = config.symbolize_keys.compact <ide> <ide> # Map ActiveRecords param names to PGs. <ide> conn_params[:user] = conn_params.delete(:username) if conn_params[:username]
1
Text
Text
apply suggestions from code review
8d945e22fa4ef70305122bd4aff89be0548b493f
<ide><path>README.md <ide> <ide> </p> <ide> <del>**Ember** is <add>**Ember.js** is a JavaScript framework that greatly reduces the time, effort and resources needed to build any web application. It is focused on making you, the developer, as productive as possible by doing all the common, repetitive, yet essential, tasks involved in most web development projects. <add> <add>With Ember, you get all of these things: <ide> <ide> * [**A Welcoming Community**](https://emberjs.com/community/) - Get the help you need, when you need it. <del>* [**Timeless**](https://en.wikipedia.org/wiki/Ember.js) - There are apps that used the first version of Ember almost a decade ago, and have successfully used Ember this entire time. <del>* [**Reliable & Secure**](https://emberjs.com/releases/) - With regular LTS Releases and 30 weeks of security fixes, you can rely on Ember.js to care about the stability and security of your app. <del>* [**Modern**](https://guides.emberjs.com/release/upgrading/current-edition/) - Use modern JavaScript features that you're already familiar with like classes, decorators, & generators. <del>* [**Documented**](https://guides.emberjs.com) - Rely on top-notch documentation for each Ember version and a team that is focused on the documentation and learning experience. <add>* [**An Enduring Foundation for your Apps**](https://en.wikipedia.org/wiki/Ember.js) - There are apps that used the first version of Ember almost a decade ago, and successfully still use Ember today. <add>* [**Reliability & Security**](https://emberjs.com/releases/) - With regular LTS Releases and 30 weeks of security fixes, you can rely on Ember.js to care about the stability [and security](https://emberjs.com/security/) of your app. <add>* [**Modern JavaScript**](https://guides.emberjs.com/release/upgrading/current-edition/) - Use modern JavaScript features that you're already familiar with like classes, decorators, & generators. <add>* [**Documentation**](https://guides.emberjs.com) - Rely on top-notch documentation for each Ember version and a team that is focused on the documentation and learning experience. <ide> * [**Component-Based**](https://guides.emberjs.com/release/components/introducing-components/) - Any HTML is a valid component! Start with valid, semantic HTML and layer in the app functionality that you need- giving your team the space for specialized markup experts. <del>* [**Routed**](https://guides.emberjs.com/release/routing/) - Ember routes respect URLs while layering in extra functionality like rendering templates, loading data models, handling actions, and conditionally redirecting. <del>* [**DSL**](https://guides.emberjs.com/release/models/) - Ember Data is a powerful data management tool. <del>* [**Flexible**](https://guides.emberjs.com/release/models/customizing-adapters/) Use _**any**_ backend stack with your Ember apps, thanks to the flexibility of adapters and serializers. <del>* [**Autotracked (Ember's reactivity model)**](https://guides.emberjs.com/release/in-depth-topics/autotracking-in-depth/) - Ember makes it easier to decide what to automatically update, and when. <add>* [**Routing**](https://guides.emberjs.com/release/routing/) - Ember routes respect URLs while layering in extra functionality like rendering templates, loading data models, handling actions, and conditionally redirecting. <add>* [**Data Layer**](https://guides.emberjs.com/release/models/) - Ember Data is a powerful data management tool that comes with Ember apps by default. Want to use something else? We support that, too! <add>* [**Flexibility**](https://guides.emberjs.com/release/models/customizing-adapters/) Use _**any**_ backend stack with your Ember apps, thanks to the flexibility of adapters and serializers. <add>* [**Autotracking**](https://guides.emberjs.com/release/in-depth-topics/autotracking-in-depth/) - Ember's reactivity model makes it easier to decide what to automatically update, and when. <ide> * [**Bytecode Templates**](https://yehudakatz.com/2017/04/05/the-glimmer-vm-boots-fast-and-stays-fast/) and other compile-time optimizations. <ide> * [**Zero config apps**](https://guides.emberjs.com/release/configuring-ember/) - With strong defaults, you may never need to configure anything in your app, but the options are there if you need it! <ide> * [**Quality addon ecosystem**](https://emberobserver.com/) - high-quality, rated addons with the ability to [search by source code](https://emberobserver.com/code-search?codeQuery=task). Many require no additional configuration, making it easier than ever to supercharge your apps. <ide> <del>Used By [**Linkedin**](https://engineering.linkedin.com/blog/topic/ember), [**Apple**](http://builtwithember.io/featured/2015/07/04/apple-music/), [**Crowdstrike**](https://www.crowdstrike.com/),[**Hashicorp**](https://github.com/hashicorp/vault), [**Travis CI**](https://github.com/travis-ci/travis-web), [**DigitalOcean**](http://builtwithember.io/2018/02/08/digital-ocean/), [**Percy**](https://github.com/percy/percy-web) and [more](http://builtwithember.io/). <ide> <ide> <ide> - [Website](https://emberjs.com)
1
Javascript
Javascript
remove my example
eeb2fd0c96d82dd9a3b2ec35ce4bad04410aa44c
<ide><path>examples/sven/src/a.js <del>export const two = 2; <ide><path>examples/sven/src/b.js <del>export function logFoo() { <del> console.log("log foo"); <del>} <ide><path>examples/sven/src/index.js <del>// Before transformation: <del>// <del>// (module <del>// (import "./b" "logFoo" (func $a)) <del>// (import "./a" "two" (global i32)) <del>// (func (export "getTwo") (result i32) <del>// (get_global 0) <del>// ) <del>// (func (export "logFoo") <del>// (call $a) <del>// ) <del>// ) <del>// <del>// ---- <del>// <del>// After transformation: <del>// <del> <del>import("./test.wasm").then(({getTwo, logFoo}) => { <del> console.log("getTwo", getTwo()); <del> console.log(logFoo()); <del>})
3
Text
Text
fix incorrect newline in
da7e73b721f37924fb4f0bd55ad93430d7951d16
<ide><path>examples/pytorch/text-generation/README.md <ide> limitations under the License. <ide> <ide> ## Language generation <ide> <del>Based on the script [`run_generation.py`](https://github.com/huggingface/transformers/blob/master/examples/pytorch <del>/text-generation/run_generation.py). <add>Based on the script [`run_generation.py`](https://github.com/huggingface/transformers/blob/master/examples/pytorch/text-generation/run_generation.py). <ide> <ide> Conditional text generation using the auto-regressive models of the library: GPT, GPT-2, Transformer-XL, XLNet, CTRL. <ide> A similar script is used for our official demo [Write With Transfomer](https://transformer.huggingface.co), where you
1
Text
Text
fix a typo
5f155541007e33d8cdb8c9a9d729995925bbcc46
<ide><path>docs/IntegrationWithExistingApps.md <ide> The keys to integrating React Native components into your Android application ar <ide> 1. Understand what React Native components you want to integrate. <ide> 2. Install `react-native` in your Android application root directory to create `node_modules/` directory. <ide> 3. Create your actual React Native components in JavaScript. <del>4. Add `com.facebook.react:react-native:+` and a `maven` pointing to the `react-native` binaries in `node_nodules/` to your `build.gradle` file. <add>4. Add `com.facebook.react:react-native:+` and a `maven` pointing to the `react-native` binaries in `node_modules/` to your `build.gradle` file. <ide> 4. Create a custom React Native specific `Activity` that creates a `ReactRootView`. <ide> 5. Start the React Native server and run your native application. <ide> 6. Optionally add more React Native components.
1
Text
Text
allow travis results for doc/comment changes
e44d73f0117b9a1f7e5f9af759871b24638331a6
<ide><path>COLLABORATOR_GUIDE.md <ide> the comment anyway to avoid any doubt. <ide> All fixes must have a test case which demonstrates the defect. The test should <ide> fail before the change, and pass after the change. <ide> <del>All pull requests must pass continuous integration tests on the <del>[project CI server](https://ci.nodejs.org/). <add>All pull requests must pass continuous integration tests. Code changes must pass <add>on [project CI server](https://ci.nodejs.org/). Pull requests that only change <add>documentation and comments can use Travis CI results. <ide> <ide> Do not land any pull requests without passing (green or yellow) CI runs. If <ide> there are CI failures unrelated to the change in the pull request, try "Resume <ide> everything else. <ide> is the CI job to test pull requests. It runs the `build-ci` and `test-ci` <ide> targets on all supported platforms. <ide> <del>* [`node-test-pull-request-lite-pipeline`](https://ci.nodejs.org/job/node-test-pull-request-lite-pipeline/) <del>runs the linter job. It also runs the tests on a very fast host. This is useful <del>for changes that only affect comments or documentation. <del> <ide> * [`citgm-smoker`](https://ci.nodejs.org/job/citgm-smoker/) <ide> uses [`CitGM`](https://github.com/nodejs/citgm) to allow you to run <ide> `npm install && npm test` on a large selection of common modules. This is
1
Python
Python
fix bert layernorm
dcddf498c8b34cfeb99fb563e771877a1bc7ded5
<ide><path>pytorch_transformers/modeling_tf_pytorch_utils.py <ide> def load_pytorch_state_dict_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None <ide> "https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.") <ide> raise e <ide> <add> # Adapt state dict - TODO remove this and update the AWS weights files instead <add> for key in pt_state_dict.keys(): <add> new_key = None <add> if 'gamma' in key: <add> new_key = key.replace('gamma', 'weight') <add> if 'beta' in key: <add> new_key = key.replace('beta', 'bias') <add> if new_key: <add> old_keys.append(key) <add> new_keys.append(new_key) <add> for old_key, new_key in zip(old_keys, new_keys): <add> pt_state_dict[new_key] = pt_state_dict.pop(old_key) <add> <ide> symbolic_weights = tf_model.trainable_weights + tf_model.non_trainable_weights <ide> <ide> weight_value_tuples = []
1
Text
Text
fix typo in doc/tls.md
9428854b96c686ee46de869905a29ef0d21ccc83
<ide><path>doc/api/tls.md <ide> added: v0.11.3 <ide> to be used when checking the server's hostname against the certificate. <ide> This should throw an error if verification fails. The method should return <ide> `undefined` if the `servername` and `cert` are verified. <del> * `secureProtocol` {string} The SSL method to use, e.g., `SSLv3_method` to <add> * `secureProtocol` {string} The SSL method to use, e.g. `SSLv3_method` to <ide> force SSL version 3. The possible values depend on the version of OpenSSL <ide> installed in the environment and are defined in the constant <ide> [SSL_METHODS][]. <ide> added: v0.11.3 <ide> to be used when checking the server's hostname against the certificate. <ide> This should throw an error if verification fails. The method should return <ide> `undefined` if the `servername` and `cert` are verified. <del> * `secureProtocol` {string} The SSL method to use, e.g., `SSLv3_method` to <add> * `secureProtocol` {string} The SSL method to use, e.g. `SSLv3_method` to <ide> force SSL version 3. The possible values depend on the version of OpenSSL <ide> installed in the environment and are defined in the constant <ide> [SSL_METHODS][]. <ide> added: v0.3.2 <ide> session resumption. If `requestCert` is `true`, the default is a 128 bit <ide> truncated SHA1 hash value generated from the command-line. Otherwise, a <ide> default is not provided. <del> * `secureProtocol` {string} The SSL method to use, e.g., `SSLv3_method` to <add> * `secureProtocol` {string} The SSL method to use, e.g. `SSLv3_method` to <ide> force SSL version 3. The possible values depend on the version of OpenSSL <ide> installed in the environment and are defined in the constant <ide> [SSL_METHODS][].
1
Javascript
Javascript
improve future relative time
194e64daff528b1661ba3eb4ac723fa01ae7674b
<ide><path>src/locale/it.js <ide> export default moment.defineLocale('it', { <ide> sameElse: 'L', <ide> }, <ide> relativeTime: { <del> future: function (s) { <del> return (/^[0-9].+$/.test(s) ? 'tra' : 'in') + ' ' + s; <del> }, <add> future: 'tra %s', <ide> past: '%s fa', <ide> s: 'alcuni secondi', <ide> ss: '%d secondi', <ide><path>src/test/locale/it.js <ide> test('from', function (assert) { <ide> }); <ide> <ide> test('suffix', function (assert) { <del> assert.equal(moment(30000).from(0), 'in alcuni secondi', 'prefix'); <add> assert.equal(moment(30000).from(0), 'tra alcuni secondi', 'prefix'); <ide> assert.equal(moment(0).from(30000), 'alcuni secondi fa', 'suffix'); <ide> }); <ide> <ide> test('fromNow', function (assert) { <ide> assert.equal( <ide> moment().add({ s: 30 }).fromNow(), <del> 'in alcuni secondi', <del> 'in seconds' <add> 'tra alcuni secondi', <add> 'tra seconds' <ide> ); <ide> assert.equal(moment().add({ d: 5 }).fromNow(), 'tra 5 giorni', 'in 5 days'); <ide> });
2
Python
Python
kill mx.texttools with fire
222a956ecc5b163420d524a675ed01d75622ea6b
<ide><path>django/http/multipartparser.py <ide> def __init__(self, stream, boundary): <ide> if not unused_char: <ide> raise InputStreamExhausted() <ide> self._stream.unget(unused_char) <del> try: <del> from mx.TextTools import FS <del> self._fs = FS(boundary).find <del> except ImportError: <del> self._fs = lambda data: data.find(boundary) <ide> <ide> def __iter__(self): <ide> return self <ide> def _find_boundary(self, data, eof = False): <ide> * the end of current encapsulation <ide> * the start of the next encapsulation <ide> """ <del> index = self._fs(data) <add> index = data.find(self._boundary) <ide> if index < 0: <ide> return None <ide> else:
1
Javascript
Javascript
replace string concatenation with template
97bfeff084d1c035a01381249394a64ee99e8a1e
<ide><path>lib/_http_agent.js <ide> Agent.prototype.getName = function getName(options) { <ide> // Pacify parallel/test-http-agent-getname by only appending <ide> // the ':' when options.family is set. <ide> if (options.family === 4 || options.family === 6) <del> name += ':' + options.family; <add> name += `:${options.family}`; <ide> <ide> if (options.socketPath) <del> name += ':' + options.socketPath; <add> name += `:${options.socketPath}`; <ide> <ide> return name; <ide> };
1
PHP
PHP
fix mistakes in api docs
c8108074f35166639d50657106f301d660c4a5b7
<ide><path>src/ORM/Query.php <ide> public function matching($assoc, callable $builder = null) <ide> * ->select(['total_articles' => $query->func()->count('Articles.id')]) <ide> * ->leftJoinWith('Articles') <ide> * ->group(['Users.id']) <del> * ->setAutoFields(true); <add> * ->enableAutoFields(true); <ide> * ``` <ide> * <ide> * You can also customize the conditions passed to the LEFT JOIN: <ide> public function matching($assoc, callable $builder = null) <ide> * return $q->where(['Articles.votes >=' => 5]); <ide> * }) <ide> * ->group(['Users.id']) <del> * ->setAutoFields(true); <add> * ->enableAutoFields(true); <ide> * ``` <ide> * <ide> * This will create the following SQL:
1
Python
Python
add files via upload
fe7b86c9ffed033d3ee47445e288819828c05537
<ide><path>sorts/external-sort.py <add>#!/usr/bin/env python <add> <add># <add># Sort large text files in a minimum amount of memory <add># <add>import os <add>import sys <add>import argparse <add> <add>class FileSplitter(object): <add> BLOCK_FILENAME_FORMAT = 'block_{0}.dat' <add> <add> def __init__(self, filename): <add> self.filename = filename <add> self.block_filenames = [] <add> <add> def write_block(self, data, block_number): <add> filename = self.BLOCK_FILENAME_FORMAT.format(block_number) <add> file = open(filename, 'w') <add> file.write(data) <add> file.close() <add> self.block_filenames.append(filename) <add> <add> def get_block_filenames(self): <add> return self.block_filenames <add> <add> def split(self, block_size, sort_key=None): <add> file = open(self.filename, 'r') <add> i = 0 <add> <add> while True: <add> lines = file.readlines(block_size) <add> <add> if lines == []: <add> break <add> <add> if sort_key is None: <add> lines.sort() <add> else: <add> lines.sort(key=sort_key) <add> <add> self.write_block(''.join(lines), i) <add> i += 1 <add> <add> def cleanup(self): <add> map(lambda f: os.remove(f), self.block_filenames) <add> <add> <add>class NWayMerge(object): <add> def select(self, choices): <add> min_index = -1 <add> min_str = None <add> <add> for i in range(len(choices)): <add> if min_str is None or choices[i] < min_str: <add> min_index = i <add> <add> return min_index <add> <add> <add>class FilesArray(object): <add> def __init__(self, files): <add> self.files = files <add> self.empty = set() <add> self.num_buffers = len(files) <add> self.buffers = {i: None for i in range(self.num_buffers)} <add> <add> def get_dict(self): <add> return {i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty} <add> <add> def refresh(self): <add> for i in range(self.num_buffers): <add> if self.buffers[i] is None and i not in self.empty: <add> self.buffers[i] = self.files[i].readline() <add> <add> if self.buffers[i] == '': <add> self.empty.add(i) <add> <add> if len(self.empty) == self.num_buffers: <add> return False <add> <add> return True <add> <add> def unshift(self, index): <add> value = self.buffers[index] <add> self.buffers[index] = None <add> <add> return value <add> <add> <add>class FileMerger(object): <add> def __init__(self, merge_strategy): <add> self.merge_strategy = merge_strategy <add> <add> def merge(self, filenames, outfilename, buffer_size): <add> outfile = open(outfilename, 'w', buffer_size) <add> buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) <add> <add> while buffers.refresh(): <add> min_index = self.merge_strategy.select(buffers.get_dict()) <add> outfile.write(buffers.unshift(min_index)) <add> <add> def get_file_handles(self, filenames, buffer_size): <add> files = {} <add> <add> for i in range(len(filenames)): <add> files[i] = open(filenames[i], 'r', buffer_size) <add> <add> return files <add> <add> <add> <add>class ExternalSort(object): <add> def __init__(self, block_size): <add> self.block_size = block_size <add> <add> def sort(self, filename, sort_key=None): <add> num_blocks = self.get_number_blocks(filename, self.block_size) <add> splitter = FileSplitter(filename) <add> splitter.split(self.block_size, sort_key) <add> <add> merger = FileMerger(NWayMerge()) <add> buffer_size = self.block_size / (num_blocks + 1) <add> merger.merge(splitter.get_block_filenames(), filename + '.out', buffer_size) <add> <add> splitter.cleanup() <add> <add> def get_number_blocks(self, filename, block_size): <add> return (os.stat(filename).st_size / block_size) + 1 <add> <add> <add>def parse_memory(string): <add> if string[-1].lower() == 'k': <add> return int(string[:-1]) * 1024 <add> elif string[-1].lower() == 'm': <add> return int(string[:-1]) * 1024 * 1024 <add> elif string[-1].lower() == 'g': <add> return int(string[:-1]) * 1024 * 1024 * 1024 <add> else: <add> return int(string) <add> <add> <add> <add>def main(): <add> parser = argparse.ArgumentParser() <add> parser.add_argument('-m', <add> '--mem', <add> help='amount of memory to use for sorting', <add> default='100M') <add> parser.add_argument('filename', <add> metavar='<filename>', <add> nargs=1, <add> help='name of file to sort') <add> args = parser.parse_args() <add> <add> sorter = ExternalSort(parse_memory(args.mem)) <add> sorter.sort(args.filename[0]) <add> <add> <add>if __name__ == '__main__': <add>main() <ide>\ No newline at end of file
1
Javascript
Javascript
add webpack 5 comments
01b02e6e494274507134091b47845abd84db0bc1
<ide><path>lib/Dependency.js <ide> const DependencyReference = require("./dependencies/DependencyReference"); <ide> class Dependency { <ide> constructor() { <ide> this.module = null; <add> // TODO remove in webpack 5 <ide> this.weak = false; <ide> this.optional = false; <ide> this.loc = undefined; <ide><path>lib/FlagDependencyUsagePlugin.js <ide> class FlagDependencyUsagePlugin { <ide> }; <ide> <ide> const processDependency = dep => { <add> // TODO remove dep.getReference existance check in webpack 5 <ide> const reference = dep.getReference && dep.getReference(); <ide> if (!reference) return; <ide> const module = reference.module;
2
Text
Text
update url for react hydration documentation
194b6ad1c136a8c75a68bf82a5b80504703ec162
<ide><path>errors/react-hydration-error.md <ide> Common causes with css-in-js libraries: <ide> <ide> ### Useful Links <ide> <del>- [React Hydration Documentation](https://reactjs.org/docs/react-dom.html#hydrate) <add>- [React Hydration Documentation](https://reactjs.org/docs/react-dom-client.html#hydrateroot) <ide> - [Josh Comeau's article on React Hydration](https://www.joshwcomeau.com/react/the-perils-of-rehydration/)
1
PHP
PHP
add some more transaction tests
cb376bf420a7414ef573d4d7c4ff7d23ef0a4514
<ide><path>lib/Cake/Model/Model.php <ide> public function saveMany($data = null, $options = array()) { <ide> $options['validate'] = false; <ide> } <ide> <add> $transactionBegun = false; <ide> if ($options['atomic']) { <ide> $db = $this->getDataSource(); <ide> $transactionBegun = $db->begin(); <del> } else { <del> $transactionBegun = false; <ide> } <ide> <ide> try { <ide> public function saveAssociated($data = null, $options = array()) { <ide> $options['validate'] = false; <ide> } <ide> <add> $transactionBegun = false; <ide> if ($options['atomic']) { <ide> $db = $this->getDataSource(); <ide> $transactionBegun = $db->begin(); <del> } else { <del> $transactionBegun = false; <ide> } <ide> <ide> try { <ide><path>lib/Cake/Test/Case/Model/ModelWriteTest.php <ide> class TestAuthor extends Author { <ide> <ide> protected $_dataSourceObject; <ide> <add> public $dataForAfterSave; <add> <ide> /** <ide> * Helper method to set a datasource object <ide> * <ide> class TestPost extends Post { <ide> <ide> protected $_dataSourceObject; <ide> <add> public $dataForAfterSave; <add> <ide> /** <ide> * Helper method to set a datasource object <ide> * <ide> protected function _getMockDboSource($methods = array()) { <ide> <ide> return $db; <ide> } <add> <add>/** <add> * Test that transactions behave correctly on nested saveMany calls. <add> * <add> * @return void <add> */ <add> public function testTransactionOnNestedSaveMany() { <add> $this->loadFixtures('Post'); <add> $Post = new TestPost(); <add> $Post->getEventManager()->attach(array($this, 'nestedSaveMany'), 'Model.afterSave'); <add> <add> // begin -> [ begin -> commit ] -> commit <add> $db = $this->_getMockDboSource(array('begin', 'commit', 'rollback')); <add> $db->expects($this->exactly(2))->method('begin')->will($this->returnValue(true)); <add> $db->expects($this->exactly(2))->method('commit'); <add> $db->expects($this->never())->method('rollback'); <add> $Post->setDataSourceObject($db); <add> <add> $data = array( <add> array('author_id' => 1, 'title' => 'Outer Post'), <add> ); <add> $Post->dataForAfterSave = array( <add> array('author_id' => 1, 'title' => 'Inner Post'), <add> ); <add> $this->assertTrue($Post->saveMany($data)); <add> <add> // begin -> [ begin(false) ] -> commit <add> $db = $this->_getMockDboSource(array('begin', 'commit', 'rollback')); <add> $db->expects($this->at(0))->method('begin')->will($this->returnValue(true)); <add> $db->expects($this->at(1))->method('begin')->will($this->returnValue(false)); <add> $db->expects($this->once())->method('commit'); <add> $db->expects($this->never())->method('rollback'); <add> $Post->setDataSourceObject($db); <add> <add> $data = array( <add> array('author_id' => 1, 'title' => 'Outer Post'), <add> ); <add> $Post->dataForAfterSave = array( <add> array('author_id' => 1, 'title' => 'Inner Post'), <add> ); <add> $this->assertTrue($Post->saveMany($data)); <add> <add> // begin -> [ begin -> rollback ] -> rollback <add> $db = $this->_getMockDboSource(array('begin', 'commit', 'rollback')); <add> $db->expects($this->exactly(2))->method('begin')->will($this->returnValue(true)); <add> $db->expects($this->never())->method('commit'); <add> $db->expects($this->exactly(2))->method('rollback'); <add> $Post->setDataSourceObject($db); <add> $data = array( <add> array('author_id' => 1, 'title' => 'Outer Post'), <add> ); <add> $Post->dataForAfterSave = array( <add> array('author_id' => 1, 'title' => 'Inner Post', 'body' => $db->expression('PDO_EXCEPTION()')), <add> ); <add> <add> try { <add> $Post->saveMany($data); <add> $this->fail('No exception thrown'); <add> } catch(Exception $e) { <add> } <add> } <add> <add>/** <add> * Test that transaction behaves correctly on nested saveAssociated calls. <add> * <add> * @return void <add> */ <add> public function testTransactionOnNestedSaveAssociated() { <add> $this->loadFixtures('Author', 'Post'); <add> <add> $Author = new TestAuthor(); <add> $Author->getEventManager()->attach(array($this, 'nestedSaveAssociated'), 'Model.afterSave'); <add> <add> // begin -> [ begin -> commit ] -> commit <add> $db = $this->_getMockDboSource(array('begin', 'commit', 'rollback')); <add> $db->expects($this->exactly(2))->method('begin')->will($this->returnValue(true)); <add> $db->expects($this->exactly(2))->method('commit'); <add> $db->expects($this->never())->method('rollback'); <add> $Author->setDataSourceObject($db); <add> $Author->Post->setDataSourceObject($db); <add> <add> $data = array( <add> 'Author' => array('user' => 'outer'), <add> 'Post' => array( <add> array('title' => 'Outer Post'), <add> ) <add> ); <add> $Author->dataForAfterSave = array( <add> 'Author' => array('user' => 'inner'), <add> 'Post' => array( <add> array('title' => 'Inner Post'), <add> ) <add> ); <add> $this->assertTrue($Author->saveAssociated($data)); <add> <add> // begin -> [ begin(false) ] -> commit <add> $db = $this->_getMockDboSource(array('begin', 'commit', 'rollback')); <add> $db->expects($this->at(0))->method('begin')->will($this->returnValue(true)); <add> $db->expects($this->at(1))->method('begin')->will($this->returnValue(false)); <add> $db->expects($this->once())->method('commit'); <add> $db->expects($this->never())->method('rollback'); <add> $Author->setDataSourceObject($db); <add> $Author->Post->setDataSourceObject($db); <add> $data = array( <add> 'Author' => array('user' => 'outer'), <add> 'Post' => array( <add> array('title' => 'Outer Post'), <add> ) <add> ); <add> $Author->dataForAfterSave = array( <add> 'Author' => array('user' => 'inner'), <add> 'Post' => array( <add> array('title' => 'Inner Post'), <add> ) <add> ); <add> $this->assertTrue($Author->saveAssociated($data)); <add> <add> // begin -> [ begin -> rollback ] -> rollback <add> $db = $this->_getMockDboSource(array('begin', 'commit', 'rollback')); <add> $db->expects($this->exactly(2))->method('begin')->will($this->returnValue(true)); <add> $db->expects($this->never())->method('commit'); <add> $db->expects($this->exactly(2))->method('rollback'); <add> $Author->setDataSourceObject($db); <add> $Author->Post->setDataSourceObject($db); <add> $data = array( <add> 'Author' => array('user' => 'outer'), <add> 'Post' => array( <add> array('title' => 'Outer Post'), <add> ) <add> ); <add> $Author->dataForAfterSave = array( <add> 'Author' => array('user' => 'inner', 'password' => $db->expression('PDO_EXCEPTION()')), <add> 'Post' => array( <add> array('title' => 'Inner Post'), <add> ) <add> ); <add> <add> try { <add> $Author->saveAssociated($data); <add> $this->fail('No exception thrown'); <add> } catch(Exception $e) { <add> } <add> } <add> <add>/** <add> * A callback for testing nested saveMany. <add> * <add> * @param CakeEvent $event containing the Model <add> * @return void <add> */ <add> public function nestedSaveMany($event) { <add> $Model = $event->subject; <add> $Model->saveMany($Model->dataForAfterSave, array('callbacks' => false)); <add> } <add> <add>/** <add> * A callback for testing nested saveAssociated. <add> * <add> * @param CakeEvent $event containing the Model <add> * @return void <add> */ <add> public function nestedSaveAssociated($event) { <add> $Model = $event->subject; <add> $Model->saveAssociated($Model->dataForAfterSave, array('callbacks' => false)); <add> } <ide> }
2
Javascript
Javascript
handle extra whitespace
12024a76a25f6424b56063165841c7d6153ed265
<ide><path>threejs/resources/editor.js <ide> function fixSourceLinks(url, source) { <ide> const srcRE = /(src=)"(.*?)"/g; <ide> const linkRE = /(href=)"(.*?")/g; <ide> const imageSrcRE = /((?:image|img)\.src = )"(.*?)"/g; <del> const loaderLoadRE = /(loader\.load[a-z]*\()('|")(.*?)('|")/ig; <add> const loaderLoadRE = /(loader\.load[a-z]*\s*\(\s*)('|")(.*?)('|")/ig; <ide> const loaderArrayLoadRE = /(loader\.load[a-z]*\(\[)([\s\S]*?)(\])/ig; <ide> const arrayLineRE = /^(\s*["|'])([\s\S]*?)(["|']*$)/; <ide> const urlPropRE = /(url:\s*)('|")(.*?)('|")/g;
1
PHP
PHP
display messages during running migrator
18dc89b3434367946d7e62e5d684dbbae49d0431
<ide><path>src/Illuminate/Database/Console/Migrations/MigrateCommand.php <ide> public function handle() <ide> // Next, we will check to see if a path option has been defined. If it has <ide> // we will use the path relative to the root of this installation folder <ide> // so that migrations may be run for any path within the applications. <del> $this->migrator->run($this->getMigrationPaths(), [ <add> $this->migrator->setOutput($this->output)->run($this->getMigrationPaths(), [ <ide> 'pretend' => $this->option('pretend'), <ide> 'step' => $this->option('step'), <ide> ]); <ide> <del> // Once the migrator has run we will grab the note output and send it out to <del> // the console screen, since the migrator itself functions without having <del> // any instances of the OutputInterface contract passed into the class. <del> foreach ($this->migrator->getNotes() as $note) { <del> $this->output->writeln($note); <del> } <del> <ide> // Finally, if the "seed" option has been given, we will re-run the database <ide> // seed task to re-populate the database, which is convenient when adding <ide> // a migration and a seed at the same time, as it is only this command. <ide><path>src/Illuminate/Database/Console/Migrations/ResetCommand.php <ide> public function handle() <ide> return $this->comment('Migration table not found.'); <ide> } <ide> <del> $this->migrator->reset( <add> $this->migrator->setOutput($this->output)->reset( <ide> $this->getMigrationPaths(), $this->option('pretend') <ide> ); <del> <del> // Once the migrator has run we will grab the note output and send it out to <del> // the console screen, since the migrator itself functions without having <del> // any instances of the OutputInterface contract passed into the class. <del> foreach ($this->migrator->getNotes() as $note) { <del> $this->output->writeln($note); <del> } <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Database/Console/Migrations/RollbackCommand.php <ide> public function handle() <ide> <ide> $this->migrator->setConnection($this->option('database')); <ide> <del> $this->migrator->rollback( <add> $this->migrator->setOutput($this->output)->rollback( <ide> $this->getMigrationPaths(), [ <ide> 'pretend' => $this->option('pretend'), <ide> 'step' => (int) $this->option('step'), <ide> ] <ide> ); <del> <del> // Once the migrator has run we will grab the note output and send it out to <del> // the console screen, since the migrator itself functions without having <del> // any instances of the OutputInterface contract passed into the class. <del> foreach ($this->migrator->getNotes() as $note) { <del> $this->output->writeln($note); <del> } <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Database/Migrations/Migrator.php <ide> <ide> namespace Illuminate\Database\Migrations; <ide> <add>use Illuminate\Console\OutputStyle; <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Str; <ide> use Illuminate\Support\Collection; <ide> class Migrator <ide> protected $connection; <ide> <ide> /** <del> * The notes for the current operation. <add> * The paths to all of the migration files. <ide> * <ide> * @var array <ide> */ <del> protected $notes = []; <add> protected $paths = []; <ide> <ide> /** <del> * The paths to all of the migration files. <add> * The output interface implementation. <ide> * <del> * @var array <add> * @var \Illuminate\Console\OutputStyle <ide> */ <del> protected $paths = []; <add> protected $output; <ide> <ide> /** <ide> * Create a new migrator instance. <ide> public function __construct(MigrationRepositoryInterface $repository, <ide> $this->repository = $repository; <ide> } <ide> <add> /** <add> * Set output. <add> * <add> * @param \Illuminate\Console\OutputStyle $output <add> * <add> * @return $this <add> */ <add> public function setOutput(OutputStyle $output) <add> { <add> $this->output = $output; <add> <add> return $this; <add> } <add> <ide> /** <ide> * Run the pending migrations at a given path. <ide> * <ide> public function getFilesystem() <ide> */ <ide> protected function note($message) <ide> { <del> $this->notes[] = $message; <del> } <del> <del> /** <del> * Get the notes for the last operation. <del> * <del> * @return array <del> */ <del> public function getNotes() <del> { <del> return $this->notes; <add> $this->output->writeln($message); <ide> } <ide> } <ide><path>tests/Database/DatabaseMigrationMigrateCommandTest.php <ide> public function testBasicMigrationsCallMigratorWithProperArguments() <ide> $command->setLaravel($app); <ide> $migrator->shouldReceive('paths')->once()->andReturn([]); <ide> $migrator->shouldReceive('setConnection')->once()->with(null); <add> $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); <ide> $migrator->shouldReceive('run')->once()->with([__DIR__.DIRECTORY_SEPARATOR.'migrations'], ['pretend' => false, 'step' => false]); <ide> $migrator->shouldReceive('getNotes')->andReturn([]); <ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true); <ide> public function testMigrationRepositoryCreatedWhenNecessary() <ide> $command->setLaravel($app); <ide> $migrator->shouldReceive('paths')->once()->andReturn([]); <ide> $migrator->shouldReceive('setConnection')->once()->with(null); <add> $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); <ide> $migrator->shouldReceive('run')->once()->with([__DIR__.DIRECTORY_SEPARATOR.'migrations'], ['pretend' => false, 'step' => false]); <del> $migrator->shouldReceive('getNotes')->andReturn([]); <ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(false); <ide> $command->expects($this->once())->method('call')->with($this->equalTo('migrate:install'), $this->equalTo(['--database' => null])); <ide> <ide> public function testTheCommandMayBePretended() <ide> $command->setLaravel($app); <ide> $migrator->shouldReceive('paths')->once()->andReturn([]); <ide> $migrator->shouldReceive('setConnection')->once()->with(null); <add> $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); <ide> $migrator->shouldReceive('run')->once()->with([__DIR__.DIRECTORY_SEPARATOR.'migrations'], ['pretend' => true, 'step' => false]); <del> $migrator->shouldReceive('getNotes')->andReturn([]); <ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true); <ide> <ide> $this->runCommand($command, ['--pretend' => true]); <ide> public function testTheDatabaseMayBeSet() <ide> $command->setLaravel($app); <ide> $migrator->shouldReceive('paths')->once()->andReturn([]); <ide> $migrator->shouldReceive('setConnection')->once()->with('foo'); <add> $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); <ide> $migrator->shouldReceive('run')->once()->with([__DIR__.DIRECTORY_SEPARATOR.'migrations'], ['pretend' => false, 'step' => false]); <del> $migrator->shouldReceive('getNotes')->andReturn([]); <ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true); <ide> <ide> $this->runCommand($command, ['--database' => 'foo']); <ide> public function testStepMayBeSet() <ide> $command->setLaravel($app); <ide> $migrator->shouldReceive('paths')->once()->andReturn([]); <ide> $migrator->shouldReceive('setConnection')->once()->with(null); <add> $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); <ide> $migrator->shouldReceive('run')->once()->with([__DIR__.DIRECTORY_SEPARATOR.'migrations'], ['pretend' => false, 'step' => true]); <del> $migrator->shouldReceive('getNotes')->andReturn([]); <ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true); <ide> <ide> $this->runCommand($command, ['--step' => true]); <ide><path>tests/Database/DatabaseMigrationResetCommandTest.php <ide> public function testResetCommandCallsMigratorWithProperArguments() <ide> $migrator->shouldReceive('paths')->once()->andReturn([]); <ide> $migrator->shouldReceive('setConnection')->once()->with(null); <ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true); <add> $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); <ide> $migrator->shouldReceive('reset')->once()->with([__DIR__.'/migrations'], false); <del> $migrator->shouldReceive('getNotes')->andReturn([]); <ide> <ide> $this->runCommand($command); <ide> } <ide> public function testResetCommandCanBePretended() <ide> $migrator->shouldReceive('paths')->once()->andReturn([]); <ide> $migrator->shouldReceive('setConnection')->once()->with('foo'); <ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true); <add> $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); <ide> $migrator->shouldReceive('reset')->once()->with([__DIR__.'/migrations'], true); <del> $migrator->shouldReceive('getNotes')->andReturn([]); <ide> <ide> $this->runCommand($command, ['--pretend' => true, '--database' => 'foo']); <ide> } <ide><path>tests/Database/DatabaseMigrationRollbackCommandTest.php <ide> public function testRollbackCommandCallsMigratorWithProperArguments() <ide> $command->setLaravel($app); <ide> $migrator->shouldReceive('paths')->once()->andReturn([]); <ide> $migrator->shouldReceive('setConnection')->once()->with(null); <add> $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); <ide> $migrator->shouldReceive('rollback')->once()->with([__DIR__.'/migrations'], ['pretend' => false, 'step' => 0]); <del> $migrator->shouldReceive('getNotes')->andReturn([]); <ide> <ide> $this->runCommand($command); <ide> } <ide> public function testRollbackCommandCallsMigratorWithStepOption() <ide> $command->setLaravel($app); <ide> $migrator->shouldReceive('paths')->once()->andReturn([]); <ide> $migrator->shouldReceive('setConnection')->once()->with(null); <add> $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); <ide> $migrator->shouldReceive('rollback')->once()->with([__DIR__.'/migrations'], ['pretend' => false, 'step' => 2]); <del> $migrator->shouldReceive('getNotes')->andReturn([]); <ide> <ide> $this->runCommand($command, ['--step' => 2]); <ide> } <ide> public function testRollbackCommandCanBePretended() <ide> $command->setLaravel($app); <ide> $migrator->shouldReceive('paths')->once()->andReturn([]); <ide> $migrator->shouldReceive('setConnection')->once()->with('foo'); <add> $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); <ide> $migrator->shouldReceive('rollback')->once()->with([__DIR__.'/migrations'], true); <del> $migrator->shouldReceive('getNotes')->andReturn([]); <ide> <ide> $this->runCommand($command, ['--pretend' => true, '--database' => 'foo']); <ide> } <ide> public function testRollbackCommandCanBePretendedWithStepOption() <ide> $command->setLaravel($app); <ide> $migrator->shouldReceive('paths')->once()->andReturn([]); <ide> $migrator->shouldReceive('setConnection')->once()->with('foo'); <add> $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); <ide> $migrator->shouldReceive('rollback')->once()->with([__DIR__.'/migrations'], ['pretend' => true, 'step' => 2]); <del> $migrator->shouldReceive('getNotes')->andReturn([]); <ide> <ide> $this->runCommand($command, ['--pretend' => true, '--database' => 'foo', '--step' => 2]); <ide> } <ide><path>tests/Database/DatabaseMigratorIntegrationTest.php <ide> namespace Illuminate\Tests\Database; <ide> <ide> use Illuminate\Support\Str; <add>use Mockery; <ide> use PHPUnit\Framework\TestCase; <ide> use Illuminate\Filesystem\Filesystem; <ide> use Illuminate\Database\Migrations\Migrator; <ide> public function setUp() <ide> new Filesystem <ide> ); <ide> <add> $output = Mockery::mock('\Illuminate\Console\OutputStyle'); <add> $output->shouldReceive('writeln'); <add> <add> $this->migrator->setOutput($output); <add> <ide> if (! $repository->repositoryExists()) { <ide> $repository->createRepository(); <ide> }
8
Java
Java
improve handling of empty response with mono<t>
abf9ce8a34d8e386a36d265fc558ee21a02d5d16
<ide><path>spring-web/src/main/java/org/springframework/http/codec/EncoderHttpMessageWriter.java <ide> public Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType eleme <ide> if (inputStream instanceof Mono) { <ide> HttpHeaders headers = message.getHeaders(); <ide> return Mono.from(body) <del> .defaultIfEmpty(message.bufferFactory().wrap(new byte[0])) <add> .switchIfEmpty(Mono.defer(() -> { <add> headers.setContentLength(0); <add> return message.setComplete().then(Mono.empty()); <add> })) <ide> .flatMap(buffer -> { <ide> headers.setContentLength(buffer.readableByteCount()); <ide> return message.writeWith(Mono.just(buffer)); <ide><path>spring-web/src/test/java/org/springframework/http/codec/EncoderHttpMessageWriterTests.java <ide> import org.springframework.core.codec.Encoder; <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory; <del>import org.springframework.core.io.buffer.support.DataBufferTestUtils; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse; <ide> import org.springframework.util.MimeType; <ide> import org.springframework.util.MimeTypeUtils; <ide> <del>import static java.nio.charset.StandardCharsets.ISO_8859_1; <del>import static java.nio.charset.StandardCharsets.UTF_8; <del>import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertFalse; <del>import static org.junit.Assert.assertTrue; <add>import static java.nio.charset.StandardCharsets.*; <add>import static org.junit.Assert.*; <ide> import static org.mockito.ArgumentMatchers.any; <del>import static org.mockito.Mockito.when; <del>import static org.springframework.core.ResolvableType.forClass; <del>import static org.springframework.http.MediaType.TEXT_HTML; <del>import static org.springframework.http.MediaType.TEXT_PLAIN; <del>import static org.springframework.http.MediaType.TEXT_XML; <add>import static org.mockito.Mockito.*; <add>import static org.springframework.core.ResolvableType.*; <add>import static org.springframework.http.MediaType.*; <ide> <ide> /** <ide> * Unit tests for {@link EncoderHttpMessageWriter}. <ide> public void setContentLengthForMonoBody() { <ide> public void emptyBodyWritten() { <ide> HttpMessageWriter<String> writer = getWriter(MimeTypeUtils.TEXT_PLAIN); <ide> writer.write(Mono.empty(), forClass(String.class), TEXT_PLAIN, this.response, NO_HINTS).block(); <del> StepVerifier.create(this.response.getBody()).expectNextCount(1).verifyComplete(); <add> StepVerifier.create(this.response.getBody()).expectComplete(); <ide> assertEquals(0, this.response.getHeaders().getContentLength()); <ide> } <ide> <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java <ide> public void personResponseBodyWithMono() throws Exception { <ide> assertEquals(expected, responseEntity.getBody()); <ide> } <ide> <add> @Test // SPR-17506 <add> public void personResponseBodyWithEmptyMono() throws Exception { <add> ResponseEntity<Person> responseEntity = performGet("/person-response/mono-empty", JSON, Person.class); <add> assertEquals(0, responseEntity.getHeaders().getContentLength()); <add> assertNull(responseEntity.getBody()); <add> <add> // As we're on the same connection, the 2nd request proves server response handling <add> // did complete after the 1st request.. <add> responseEntity = performGet("/person-response/mono-empty", JSON, Person.class); <add> assertEquals(0, responseEntity.getHeaders().getContentLength()); <add> assertNull(responseEntity.getBody()); <add> } <add> <ide> @Test <ide> public void personResponseBodyWithMonoDeclaredAsObject() throws Exception { <ide> Person expected = new Person("Robert"); <ide> public Mono<Person> getMono() { <ide> return Mono.just(new Person("Robert")); <ide> } <ide> <add> @GetMapping("/mono-empty") <add> public Mono<Person> getMonoEmpty() { <add> return Mono.empty(); <add> } <add> <ide> @GetMapping("/mono-declared-as-object") <ide> public Object getMonoDeclaredAsObject() { <ide> return Mono.just(new Person("Robert"));
3
Text
Text
update the way of starting packager on windows
27a0ce3ead8235b53c2081f820063af36401831d
<ide><path>docs/LinuxWindowsSupport.md <ide> As of **version 0.14** Android development with React native is mostly possible <ide> <ide> On Windows the packager won't be started automatically when you run `react-native run-android`. You can start it manually using: <ide> <add> #For React Native version < 0.14 <ide> cd MyAwesomeApp <ide> node node_modules/react-native/packager/packager.js <add> <add> <add> #For React Native version >= 0.14 (which had removed packager.js) <add> cd MyAwesomeApp <add> react-native start <add> <add>If you hit a `ERROR Watcher took too long to load` on Windows, try increasing the [timeout](https://github.com/facebook/react-native/blob/master/packager/react-packager/src/FileWatcher/index.js#L17) in this file (under your node_modules/react-native). <add> <add>
1
Python
Python
remove unnecessary commented code
1fdcc370b6d9a71483bc968d5a0f3d259e07a78e
<ide><path>examples/neural_style_transfer.py <ide> It is preferrable to run this script on GPU, for speed. <ide> If running on CPU, prefer the TensorFlow backend (much faster). <ide> <add>Example result: https://twitter.com/fchollet/status/686631033085677568 <add> <ide> # Details <ide> <ide> Style transfer consists in generating an image <ide> parser.add_argument('result_prefix', metavar='res_prefix', type=str, <ide> help='Prefix for the saved results.') <ide> <del># base_image_path = 'tuebingen.jpg' <del># style_reference_image_path = 'starry_night.jpg' <del># result_prefix = 'my_result_th' <ide> args = parser.parse_args() <ide> base_image_path = args.base_image_path <ide> style_reference_image_path = args.style_reference_image_path
1
Text
Text
fix typo in language-modeling readme.md
734afa37f675c3adc6665e6996d97589406b1eb5
<ide><path>examples/language-modeling/README.md <ide> python run_mlm.py \ <ide> To run on your own training and validation files, use the following command: <ide> <ide> ```bash <del>python run_clm.py \ <add>python run_mlm.py \ <ide> --model_name_or_path roberta-base \ <ide> --train_file path_to_train_file \ <ide> --validation_file path_to_validation_file \ <ide> --do_train \ <ide> --do_eval \ <del> --output_dir /tmp/test-clm <add> --output_dir /tmp/test-mlm <ide> ``` <ide> <ide> If your dataset is organized with one sample per line, you can use the `--line_by_line` flag (otherwise the script
1
Javascript
Javascript
fix conflict handling
8835751cb39c1928483e20e1d7e542dc01380b66
<ide><path>lib/optimize/ConcatenatedModule.js <ide> class ConcatenatedModule extends Module { <ide> } else if(dep instanceof HarmonyExportImportedSpecifierDependency) { <ide> const exportName = dep.name; <ide> const importName = dep.id; <del> const importModule = dep.importDependency.module; <del> const innerReexport = modulesSet.has(importModule); <add> const importedModule = dep.importDependency.module; <ide> if(exportName && importName) { <ide> reexportMap.set(exportName, { <del> module: importModule, <add> module: importedModule, <ide> exportName: importName, <ide> dependency: dep <ide> }); <ide> } else if(exportName) { <ide> reexportMap.set(exportName, { <del> module: importModule, <add> module: importedModule, <ide> exportName: true, <ide> dependency: dep <ide> }); <del> } else if(Array.isArray(importModule.providedExports)) { <add> } else { <ide> var activeExports = new Set(HarmonyModulesHelpers.getActiveExports(dep.originModule, dep)); <del> importModule.providedExports.forEach(name => { <add> importedModule.providedExports.forEach(name => { <ide> if(activeExports.has(name) || name === "default") <ide> return; <ide> reexportMap.set(name, { <del> module: importModule, <add> module: importedModule, <ide> exportName: name, <ide> dependency: dep <ide> }); <ide> }); <del> } else if(innerReexport) { <del> throw new Error(`Module "${importModule.readableIdentifier(requestShortener)}" doesn't provide static exports for "export *" in ${info.module.readableIdentifier(requestShortener)}`); <ide> } <ide> } <ide> }); <ide> class ConcatenatedModule extends Module { <ide> <ide> // List of all used names to avoid conflicts <ide> const allUsedNames = new Set([ <add> "__WEBPACK_MODULE_DEFAULT_EXPORT__", // avoid using this internal name <add> <ide> "abstract", "arguments", "await", "boolean", "break", "byte", "case", "catch", "char", "class", <ide> "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "eval", <ide> "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", <ide> class ConcatenatedModule extends Module { <ide> name = ""; <ide> <ide> // Remove uncool stuff <del> extraInfo = extraInfo.replace(/(\/index)?\.([a-zA-Z0-9]{1,4})$/, ""); <add> extraInfo = extraInfo.replace(/\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})$/g, ""); <ide> <ide> const splittedInfo = extraInfo.split("/"); <ide> while(splittedInfo.length) { <ide> class ConcatenatedModule extends Module { <ide> if(!usedNamed1.has(nameIdent) && (!usedNamed2 || !usedNamed2.has(nameIdent))) return nameIdent; <ide> } <ide> <del> while(usedNamed1.has(name = name + "_") || (usedNamed2 && usedNamed2.has(name))) { /* do nothing */ } <del> return name; <add> let i = 0, nameWithNumber; <add> do { <add> i++; <add> nameWithNumber = Template.toIdentifier(`${name}_${i}`); <add> } while(usedNamed1.has(nameWithNumber) || (usedNamed2 && usedNamed2.has(nameWithNumber))); <add> return nameWithNumber; <ide> } <ide> <ide> updateHash(hash) { <ide><path>test/cases/scope-hoisting/name-conflicts/index.js <add>import value1 from "./module?("; <add>import value2 from "./module?)"; <add>import value3 from "./module?["; <add>import value4 from "./module?]"; <add>import value5 from "./module?{"; <add>import value6 from "./module?}"; <add> <add>it("should not break on name conflicts", function() { <add> value1.should.be.eql("a"); <add> value2.should.be.eql("a"); <add> value3.should.be.eql("a"); <add> value4.should.be.eql("a"); <add> value5.should.be.eql("a"); <add> value6.should.be.eql("a"); <add>}); <ide><path>test/cases/scope-hoisting/name-conflicts/module.js <add>export default "a";
3
Python
Python
add oversize examples before stopiteration returns
ec52e7f886ad3839bb509c38707a8ae4e955b7d4
<ide><path>spacy/util.py <ide> def minibatch_by_words(examples, size, tuples=True, count_words=len, tolerance=0 <ide> try: <ide> example = next(examples) <ide> except StopIteration: <add> if oversize: <add> example = oversize.pop(0) <add> batch.append(example) <ide> if batch: <ide> yield batch <ide> return
1
Javascript
Javascript
fix debug-signal-cluster after da update
25e8adefa34f530951e3a71f6f7d08e12e752830
<ide><path>test/fixtures/clustered-server/app.js <ide> if (cluster.isMaster) { <ide> } <ide> }); <ide> <add> process.on('message', function(msg) { <add> if (msg.type === 'getpids') { <add> var pids = []; <add> pids.push(process.pid); <add> for (var key in cluster.workers) <add> pids.push(cluster.workers[key].process.pid); <add> process.send({ type: 'pids', pids: pids }); <add> } <add> }); <add> <ide> for (var i = 0; i < NUMBER_OF_WORKERS; i++) { <ide> cluster.fork(); <ide> } <ide><path>test/simple/test-debug-signal-cluster.js <ide> var assert = require('assert'); <ide> var spawn = require('child_process').spawn; <ide> <ide> var args = [ common.fixturesDir + '/clustered-server/app.js' ]; <del>var child = spawn(process.execPath, args); <add>var child = spawn(process.execPath, args, { <add> stdio: [ 'pipe', 'pipe', 'pipe', 'ipc' ] <add>}); <ide> var outputLines = []; <ide> var outputTimerId; <ide> var waitingForDebuggers = false; <ide> <add>var pids = null; <add> <ide> child.stderr.on('data', function(data) { <ide> var lines = data.toString().replace(/\r/g, '').trim().split('\n'); <ide> var line = lines[0]; <ide> child.stderr.on('data', function(data) { <ide> outputLines = outputLines.concat(lines); <ide> outputTimerId = setTimeout(onNoMoreLines, 800); <ide> } else if (line === 'all workers are running') { <del> waitingForDebuggers = true; <del> process._debugProcess(child.pid); <add> child.on('message', function(msg) { <add> if (msg.type !== 'pids') <add> return; <add> <add> pids = msg.pids; <add> console.error('got pids %j', pids); <add> <add> waitingForDebuggers = true; <add> process._debugProcess(child.pid); <add> }); <add> <add> child.send({ <add> type: 'getpids' <add> }); <ide> } <ide> }); <ide> <ide> setTimeout(function testTimedOut() { <ide> }, 6000); <ide> <ide> process.on('exit', function onExit() { <del> child.kill(); <add> pids.forEach(function(pid) { <add> process.kill(pid); <add> }); <ide> }); <ide> <ide> function assertOutputLines() {
2
Java
Java
fix lints and clean up interfaces
78e7311cd50e32ebe4404c986d7f29d35180b510
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/IViewManagerWithChildren.java <ide> public interface IViewManagerWithChildren { <ide> * of automatically laying out children without going through the ViewGroup's onLayout method. In <ide> * that case, onLayout for this View type must *not* call layout on its children. <ide> */ <del> public boolean needsCustomLayoutForChildren(); <add> boolean needsCustomLayoutForChildren(); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/RCTEventEmitter.java <ide> public interface RCTEventEmitter extends JavaScriptModule { <ide> /** <ide> * Deprecated in favor of RCTModernEventEmitter.receiveEvent. <ide> * <del> * @param targetTag <del> * @param eventName <del> * @param event <add> * @param targetReactTag react tag of the view that receives the event <add> * @param eventName name of event <add> * @param event event params <ide> */ <ide> @Deprecated <del> void receiveEvent(int targetTag, String eventName, @Nullable WritableMap event); <add> void receiveEvent(int targetReactTag, String eventName, @Nullable WritableMap event); <ide> <ide> /** <ide> * Receive and process touches <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/util/ReactFindViewUtil.java <ide> public interface OnViewFoundListener { <ide> public interface OnMultipleViewsFoundListener { <ide> <ide> void onViewFound(View view, String nativeId); <del> /** <del> * Called when all teh views have been found <del> * <del> * @param map <del> */ <ide> } <ide> <ide> /**
3
PHP
PHP
close mockery in the teardown method
7bdd8007a2785330f9c60955676707d45d0ab5ef
<ide><path>tests/Redis/RedisManagerExtensionTest.php <ide> protected function setUp(): void <ide> }); <ide> } <ide> <add> protected function tearDown(): void <add> { <add> m::close(); <add> } <add> <ide> public function test_using_custom_redis_connector_with_single_redis_instance() <ide> { <ide> $this->assertEquals(
1
Text
Text
remove openssl 1.x reference
45a4fdbfb4ffbd721965882cd111600bcbec8da6
<ide><path>doc/contributing/maintaining-openssl.md <ide> NASM version 2.11.08 <ide> <ide> ## 1. Obtain and extract new OpenSSL sources <ide> <del>Get a new source from <https://github.com/quictls/openssl/tree/OpenSSL_1_1_1j+quic> <add>Get a new source from <https://github.com/quictls/openssl/tree/openssl-3.0.5+quic> <ide> and copy all files into `deps/openssl/openssl`. Then add all files and commit <ide> them. (The link above, and the branch, will change with each new OpenSSL <ide> release). <ide> <del>### OpenSSL 1.1.1 <del> <del>```console <del>% git clone https://github.com/quictls/openssl <del>% cd openssl <del>% git checkout OpenSSL_1_1_1j+quic <del>% cd ../node/deps/openssl <del>% rm -rf openssl <del>% cp -R ../../../openssl openssl <del>% rm -rf openssl/.git* openssl/.travis* <del>% git add --all openssl <del>% git commit openssl <del>``` <del> <del>The commit message can be written as (with the openssl version set <del>to the relevant value): <del> <del>```text <del>deps: upgrade openssl sources to OpenSSL_1_1_1j <del> <del>This updates all sources in deps/openssl/openssl by: <del> $ git clone https://github.com/quictls/openssl <del> $ cd openssl <del> $ git checkout OpenSSL_1_1_1j+quic <del> $ cd ../node/deps/openssl <del> $ rm -rf openssl <del> $ cp -R ../openssl openssl <del> $ rm -rf openssl/.git* openssl/.travis* <del> $ git add --all openssl <del> $ git commit openssl <del>``` <del> <ide> ### OpenSSL 3.x.x <ide> <ide> ```console <ide> This updates all sources in deps/openssl/openssl by: <ide> ``` <ide> <ide> ```text <del>deps: upgrade openssl sources to quictls/openssl-3.0.2 <add>deps: upgrade openssl sources to quictls/openssl-3.0.5+quic <ide> <ide> This updates all sources in deps/openssl/openssl by: <ide> $ git clone git@github.com:quictls/openssl.git <ide> $ cd openssl <del> $ git checkout openssl-3.0.2+quic <add> $ git checkout openssl-3.0.5+quic <ide> $ cd ../node/deps/openssl <ide> $ rm -rf openssl <ide> $ cp -R ../../../openssl openssl <ide> files if they are changed before committing: <ide> <ide> ```console <ide> % git add deps/openssl/config/archs <del>% git add deps/openssl/openssl/include/crypto/bn_conf.h <del>% git add deps/openssl/openssl/include/crypto/dso_conf.h <del>% git add deps/openssl/openssl/include/openssl/opensslconf.h <add>% git add deps/openssl/openssl <ide> % git commit <ide> ``` <ide> <ide> The commit message can be written as (with the openssl version set <ide> to the relevant value): <ide> <del>### OpenSSL 1.1.1 <del> <del>```text <del> deps: update archs files for OpenSSL-1.1.1 <del> <del> After an OpenSSL source update, all the config files need to be <del> regenerated and committed by: <del> $ make -C deps/openssl/config <del> $ git add deps/openssl/config/archs <del> $ git add deps/openssl/openssl/include/crypto/bn_conf.h <del> $ git add deps/openssl/openssl/include/crypto/dso_conf.h <del> $ git add deps/openssl/openssl/include/openssl/opensslconf.h <del> $ git commit <del>``` <del> <del>### OpenSSL 3.0.x <add>### OpenSSL 3.x.x <ide> <ide> ```text <del>deps: update archs files for quictls/openssl-3.0.0-alpha-16 <add>deps: update archs files for quictls/openssl-3.0.5+quic <ide> <ide> After an OpenSSL source update, all the config files need to be <ide> regenerated and committed by:
1
Python
Python
prefer earlier spans in entityruler
ac14ce7c30c2f6da4a71dee7978f5b765af4d966
<ide><path>spacy/pipeline/entityruler.py <ide> def __call__(self, doc): <ide> matches = set( <ide> [(m_id, start, end) for m_id, start, end in matches if start != end] <ide> ) <del> get_sort_key = lambda m: (m[2] - m[1], m[1]) <add> get_sort_key = lambda m: (m[2] - m[1], -m[1]) <ide> matches = sorted(matches, key=get_sort_key, reverse=True) <ide> entities = list(doc.ents) <ide> new_entities = [] <ide><path>spacy/tests/pipeline/test_entity_ruler.py <ide> def test_entity_ruler_properties(nlp, patterns): <ide> ruler = EntityRuler(nlp, patterns=patterns, overwrite_ents=True) <ide> assert sorted(ruler.labels) == sorted(["HELLO", "BYE", "COMPLEX", "TECH_ORG"]) <ide> assert sorted(ruler.ent_ids) == ["a1", "a2"] <add> <add> <add>def test_entity_ruler_overlapping_spans(nlp): <add> ruler = EntityRuler(nlp) <add> patterns = [ <add> {"label": "FOOBAR", "pattern": "foo bar"}, <add> {"label": "BARBAZ", "pattern": "bar baz"}, <add> ] <add> ruler.add_patterns(patterns) <add> doc = ruler(nlp.make_doc("foo bar baz")) <add> assert len(doc.ents) == 1 <add> assert doc.ents[0].label_ == "FOOBAR"
2
Python
Python
remove docversion related
067c772588f69f397eeff70019320506b47bb239
<ide><path>docs/conf.py <ide> import inspect <ide> import re <ide> <del>from pallets_sphinx_themes import DocVersion, ProjectLink, get_version <add>from pallets_sphinx_themes import ProjectLink, get_version <ide> <ide> # Project -------------------------------------------------------------- <ide> <ide> ProjectLink( <ide> 'Issue Tracker', 'https://github.com/pallets/flask/issues/'), <ide> ], <del> 'versions': [ <del> DocVersion('dev', 'Development', 'unstable'), <del> DocVersion('1.0', 'Flask 1.0', 'stable'), <del> DocVersion('0.12', 'Flask 0.12'), <del> ], <ide> 'canonical_url': 'http://flask.pocoo.org/docs/{}/'.format(version), <ide> 'carbon_ads_args': 'zoneid=1673&serve=C6AILKT&placement=pocooorg', <ide> }
1
Ruby
Ruby
move dead recompile_template? also
2d6562d51b96af518c1eb2947d6d34d5dd5bad12
<ide><path>actionpack/lib/action_view/renderable.rb <ide> def #{render_symbol}(local_assigns) <ide> # The template will be compiled if the file has not been compiled yet, or <ide> # if local_assigns has a new key, which isn't supported by the compiled code yet. <ide> def recompile?(symbol) <del> unless Base::CompiledTemplates.instance_methods.include?(symbol) && Base.cache_template_loading <del> true <del> else <del> false <del> end <add> meth = Base::CompiledTemplates.instance_method(template.method) rescue nil <add> !(meth && Base.cache_template_loading) <ide> end <ide> end <ide> end <ide><path>actionpack/lib/action_view/template_handlers/compilable.rb <ide> def compilable? <ide> def render(template, local_assigns = {}) <ide> @view.send(:execute, template, local_assigns) <ide> end <del> <del> private <del> # Method to check whether template compilation is necessary. <del> # The template will be compiled if the inline template or file has not been compiled yet, <del> # if local_assigns has a new key, which isn't supported by the compiled code yet. <del> def recompile_template?(template) <del> # Unless the template has been compiled yet, compile <del> # If template caching is disabled, compile <del> # Always recompile inline templates <del> meth = Base::CompiledTemplates.instance_method(template.method) rescue nil <del> !meth || !Base.cache_template_loading || template.is_a?(InlineTemplate) <del> end <ide> end <ide> end <ide> end
2
Text
Text
fix indentation of sample code
2869e35be71b96d2d2112e9b8241e28aa123b072
<ide><path>guide/portuguese/javascript/es6/spread-operator/index.md <ide> --- <ide> title: Spread Operator <ide> localeTitle: Operador de spread <del>--- <ide>## Operador de spread <del> <del>O operador de spread ( `...` ), permite obter os elementos de uma coleção. <del> <del>Um dos usos mais comuns é para objetos de `Node` , ao usar seletores de consulta no navegador, para torná-los objetos de matriz iteráveis: <del> <del>```javascript <del>const paragraphs = document.querySelectorAll('p.paragraph'); <del> const arr = [...paragraphs]; <del>``` <del> <del>Outro uso do operador de spread é para concatenação de matriz: <del> <del>```javascript <del>const arr_1 = [1, 2, 3, 4] <del> const arr_2 = [5, 6, 7, 8] <del> const arr_final = [...arr_1, ...arr_2] <del> // arr_final = [1, 2, 3, 4, 5, 6, 7, 8] <del> <del>``` <ide>\ No newline at end of file <add>--- <add>## Operador de spread <add> <add>O operador de spread ( `...` ), permite obter os elementos de uma coleção. <add> <add>Um dos usos mais comuns é para objetos de `Node` , ao usar seletores de consulta no navegador, para torná-los objetos de matriz iteráveis: <add> <add>```javascript <add>const paragraphs = document.querySelectorAll('p.paragraph'); <add>const arr = [...paragraphs]; <add>``` <add> <add>Outro uso do operador de spread é para concatenação de matriz: <add> <add>```javascript <add>const arr_1 = [1, 2, 3, 4] <add>const arr_2 = [5, 6, 7, 8] <add>const arr_final = [...arr_1, ...arr_2] <add>// arr_final = [1, 2, 3, 4, 5, 6, 7, 8] <add> <add>```
1
PHP
PHP
add lazycollection tests
9c31b1e0e1eb80086952952003b33ce1a29e7da9
<ide><path>tests/Support/SupportLazyCollectionTest.php <ide> namespace Illuminate\Tests\Support; <ide> <ide> use PHPUnit\Framework\TestCase; <add>use Illuminate\Support\Collection; <ide> use Illuminate\Support\LazyCollection; <ide> <ide> class SupportLazyCollectionTest extends TestCase <ide> { <add> public function testCanCreateEmptyCollection() <add> { <add> $this->assertSame([], LazyCollection::make()->all()); <add> $this->assertSame([], LazyCollection::empty()->all()); <add> } <add> <add> public function testCanCreateCollectionFromArray() <add> { <add> $array = [1, 2, 3]; <add> <add> $data = LazyCollection::make($array); <add> <add> $this->assertSame($array, $data->all()); <add> <add> $array = ['a' => 1, 'b' => 2, 'c' => 3]; <add> <add> $data = LazyCollection::make($array); <add> <add> $this->assertSame($array, $data->all()); <add> } <add> <add> public function testCanCreateCollectionFromArrayable() <add> { <add> $array = [1, 2, 3]; <add> <add> $data = LazyCollection::make(Collection::make($array)); <add> <add> $this->assertSame($array, $data->all()); <add> <add> $array = ['a' => 1, 'b' => 2, 'c' => 3]; <add> <add> $data = LazyCollection::make(Collection::make($array)); <add> <add> $this->assertSame($array, $data->all()); <add> } <add> <add> public function testCanCreateCollectionFromClosure() <add> { <add> $data = LazyCollection::make(function () { <add> yield 1; <add> yield 2; <add> yield 3; <add> }); <add> <add> $this->assertSame([1, 2, 3], $data->all()); <add> <add> $data = LazyCollection::make(function () { <add> yield 'a' => 1; <add> yield 'b' => 2; <add> yield 'c' => 3; <add> }); <add> <add> $this->assertSame([ <add> 'a' => 1, <add> 'b' => 2, <add> 'c' => 3, <add> ], $data->all()); <add> } <add> <add> public function testCollect() <add> { <add> $data = LazyCollection::make(function () { <add> yield 'a' => 1; <add> yield 'b' => 2; <add> yield 'c' => 3; <add> })->collect(); <add> <add> $this->assertInstanceOf(Collection::class, $data); <add> <add> $this->assertSame([ <add> 'a' => 1, <add> 'b' => 2, <add> 'c' => 3, <add> ], $data->all()); <add> } <add> <ide> public function testTapEach() <ide> { <ide> $data = LazyCollection::times(10);
1
Javascript
Javascript
fix lint warnings in server implementation
934de2d94a0c4b7f475186746de4fb77b5e93580
<ide><path>packager/react-packager/src/Server/MultipartResponse.js <ide> class MultipartResponse { <ide> if (!headers) { <ide> return; <ide> } <del> for (let key in headers) { <add> for (const key in headers) { <ide> this.setHeader(key, headers[key]); <ide> } <ide> } <ide> class MultipartResponse { <ide> } <ide> <ide> function acceptsMultipartResponse(req) { <del> return req.headers && req.headers['accept'] === 'multipart/mixed'; <add> return req.headers && req.headers.accept === 'multipart/mixed'; <ide> } <ide> <ide> module.exports = MultipartResponse;
1
Javascript
Javascript
add libs to tern
d76aa36c5ba962c5186975a9d2e2c81ca1fefbb3
<ide><path>server/services/map.js <ide> function mapChallengeToLang({ translations = {}, ...challenge }, lang) { <ide> if (!supportedLanguages[lang]) { <ide> lang = 'en'; <ide> } <add> const translation = translations[lang] || {}; <ide> if (lang !== 'en') { <del> challenge.title = <del> translations[lang] && translations[lang].title || <del> challenge.title; <del> <del> challenge.description = <del> translations[lang] && translations[lang].description || <del> challenge.description; <add> challenge = { <add> ...challenge, <add> ...translation <add> }; <ide> } <ide> return challenge; <ide> } <ide> function getMapForLang(lang) { <ide> return ({ entities: { challenge: challengeMap, ...entities }, result }) => { <ide> entities.challenge = Object.keys(challengeMap) <ide> .reduce((translatedChallengeMap, key) => { <del> translatedChallengeMap[key] = <del> mapChallengeToLang(challengeMap[key], lang); <add> translatedChallengeMap[key] = mapChallengeToLang( <add> challengeMap[key], <add> lang <add> ); <ide> return translatedChallengeMap; <ide> }, {}); <ide> return { result, entities };
1
Java
Java
fix method order in channelsendoperator
fbcd554f428c8c5233db550463d0aeaded98fc91
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ChannelSendOperator.java <ide> private final class WriteWithBarrier <ide> } <ide> <ide> <del> @Override <del> public void cancel() { <del> Subscription s = this.subscription; <del> if (s != null) { <del> this.subscription = null; <del> s.cancel(); <del> } <del> } <add> // CoreSubscriber<T> methods (we're the subscriber to the write source).. <ide> <ide> @Override <del> public Context currentContext() { <del> return completionSubscriber.currentContext(); <add> public final void onSubscribe(Subscription s) { <add> if (Operators.validate(this.subscription, s)) { <add> this.subscription = s; <add> this.completionSubscriber.onSubscribe(this); <add> s.request(1); <add> } <ide> } <ide> <ide> @Override <del> public final void onComplete() { <add> public final void onNext(T item) { <ide> if (this.readyToWrite) { <del> requiredWriteSubscriber().onComplete(); <add> requiredWriteSubscriber().onNext(item); <ide> return; <ide> } <add> //FIXME revisit in case of reentrant sync deadlock <ide> synchronized (this) { <ide> if (this.readyToWrite) { <del> requiredWriteSubscriber().onComplete(); <add> requiredWriteSubscriber().onNext(item); <ide> } <ide> else if (this.beforeFirstEmission) { <del> this.completed = true; <add> this.item = item; <ide> this.beforeFirstEmission = false; <ide> writeFunction.apply(this).subscribe(new DownstreamBridge(this.completionSubscriber)); <ide> } <ide> else { <del> this.completed = true; <add> if (this.subscription != null) { <add> this.subscription.cancel(); <add> } <add> this.completionSubscriber.onError(new IllegalStateException("Unexpected item.")); <ide> } <ide> } <ide> } <ide> <add> private Subscriber<? super T> requiredWriteSubscriber() { <add> Assert.state(this.writeSubscriber != null, "No write subscriber"); <add> return this.writeSubscriber; <add> } <add> <ide> @Override <ide> public final void onError(Throwable ex) { <ide> if (this.readyToWrite) { <ide> else if (this.beforeFirstEmission) { <ide> } <ide> <ide> @Override <del> public final void onNext(T item) { <add> public final void onComplete() { <ide> if (this.readyToWrite) { <del> requiredWriteSubscriber().onNext(item); <add> requiredWriteSubscriber().onComplete(); <ide> return; <ide> } <del> //FIXME revisit in case of reentrant sync deadlock <ide> synchronized (this) { <ide> if (this.readyToWrite) { <del> requiredWriteSubscriber().onNext(item); <add> requiredWriteSubscriber().onComplete(); <ide> } <ide> else if (this.beforeFirstEmission) { <del> this.item = item; <add> this.completed = true; <ide> this.beforeFirstEmission = false; <ide> writeFunction.apply(this).subscribe(new DownstreamBridge(this.completionSubscriber)); <ide> } <ide> else { <del> if (this.subscription != null) { <del> this.subscription.cancel(); <del> } <del> this.completionSubscriber.onError(new IllegalStateException("Unexpected item.")); <add> this.completed = true; <ide> } <ide> } <ide> } <ide> <ide> @Override <del> public final void onSubscribe(Subscription s) { <del> if (Operators.validate(this.subscription, s)) { <del> this.subscription = s; <del> this.completionSubscriber.onSubscribe(this); <del> s.request(1); <del> } <add> public Context currentContext() { <add> return this.completionSubscriber.currentContext(); <ide> } <ide> <del> @Override <del> public void subscribe(Subscriber<? super T> writeSubscriber) { <del> synchronized (this) { <del> Assert.state(this.writeSubscriber == null, "Only one write subscriber supported"); <del> this.writeSubscriber = writeSubscriber; <del> if (this.error != null || this.completed) { <del> this.writeSubscriber.onSubscribe(Operators.emptySubscription()); <del> emitCachedSignals(); <del> } <del> else { <del> this.writeSubscriber.onSubscribe(this); <del> } <del> } <del> } <ide> <del> /** <del> * Emit cached signals to the write subscriber. <del> * @return true if no more signals expected <del> */ <del> private boolean emitCachedSignals() { <del> if (this.item != null) { <del> requiredWriteSubscriber().onNext(this.item); <del> } <del> if (this.error != null) { <del> requiredWriteSubscriber().onError(this.error); <del> return true; <del> } <del> if (this.completed) { <del> requiredWriteSubscriber().onComplete(); <del> return true; <del> } <del> return false; <del> } <add> // Subscription methods (we're the subscription to completion~ and writeSubscriber).. <ide> <ide> @Override <ide> public void request(long n) { <ide> public void request(long n) { <ide> s.request(n); <ide> } <ide> <del> private Subscriber<? super T> requiredWriteSubscriber() { <del> Assert.state(this.writeSubscriber != null, "No write subscriber"); <del> return this.writeSubscriber; <add> private boolean emitCachedSignals() { <add> if (this.item != null) { <add> requiredWriteSubscriber().onNext(this.item); <add> } <add> if (this.error != null) { <add> requiredWriteSubscriber().onError(this.error); <add> return true; <add> } <add> if (this.completed) { <add> requiredWriteSubscriber().onComplete(); <add> return true; <add> } <add> return false; <add> } <add> <add> @Override <add> public void cancel() { <add> Subscription s = this.subscription; <add> if (s != null) { <add> this.subscription = null; <add> s.cancel(); <add> } <add> } <add> <add> <add> // Publisher<T> methods (we're the Publisher to the write subscriber)... <add> <add> @Override <add> public void subscribe(Subscriber<? super T> writeSubscriber) { <add> synchronized (this) { <add> Assert.state(this.writeSubscriber == null, "Only one write subscriber supported"); <add> this.writeSubscriber = writeSubscriber; <add> if (this.error != null || this.completed) { <add> this.writeSubscriber.onSubscribe(Operators.emptySubscription()); <add> emitCachedSignals(); <add> } <add> else { <add> this.writeSubscriber.onSubscribe(this); <add> } <add> } <ide> } <ide> } <ide>
1
Java
Java
add core javapoet utilities
b3ceb0f625a5b40d1007bb4dfe673be497fc2c9e
<ide><path>spring-core/src/main/java/org/springframework/javapoet/support/CodeSnippet.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.javapoet.support; <add> <add>import java.io.IOException; <add>import java.io.StringWriter; <add>import java.util.function.Consumer; <add>import java.util.stream.Collectors; <add> <add>import javax.lang.model.element.Modifier; <add> <add>import org.springframework.javapoet.CodeBlock; <add>import org.springframework.javapoet.JavaFile; <add>import org.springframework.javapoet.MethodSpec; <add>import org.springframework.javapoet.TypeSpec; <add> <add>/** <add> * A code snippet using tabs indentation that is fully processed by JavaPoet so <add> * that imports are resolved. <add> * <add> * @author Stephane Nicoll <add> * @since 6.0 <add> */ <add>public final class CodeSnippet { <add> <add> private static final String START_SNIPPET = "// start-snippet\n"; <add> <add> private static final String END_SNIPPET = "// end-snippet"; <add> <add> private final String fileContent; <add> <add> private final String snippet; <add> <add> <add> CodeSnippet(String fileContent, String snippet) { <add> this.fileContent = fileContent; <add> this.snippet = snippet; <add> } <add> <add> <add> String getFileContent() { <add> return this.fileContent; <add> } <add> <add> /** <add> * Return the rendered code snippet. <add> * @return a code snippet where imports have been resolved <add> */ <add> public String getSnippet() { <add> return this.snippet; <add> } <add> <add> /** <add> * Specify if an import statement for the specified type is present. <add> * @param type the type to check <add> * @return true if this type has an import statement, false otherwise <add> */ <add> public boolean hasImport(Class<?> type) { <add> return hasImport(type.getName()); <add> } <add> <add> /** <add> * Specify if an import statement for the specified class name is present. <add> * @param className the name of the class to check <add> * @return true if this type has an import statement, false otherwise <add> */ <add> public boolean hasImport(String className) { <add> return getFileContent().lines().anyMatch(candidate -> <add> candidate.equals(String.format("import %s;", className))); <add> } <add> <add> /** <add> * Return a new {@link CodeSnippet} where the specified number of indentations <add> * have been removed. <add> * @param indent the number of indent to remove <add> * @return a CodeSnippet instance with the number of indentations removed <add> */ <add> public CodeSnippet removeIndent(int indent) { <add> return new CodeSnippet(this.fileContent, this.snippet.lines().map(line -> <add> removeIndent(line, indent)).collect(Collectors.joining("\n"))); <add> } <add> <add> /** <add> * Create a {@link CodeSnippet} using the specified code. <add> * @param code the code snippet <add> * @return a {@link CodeSnippet} instance <add> */ <add> public static CodeSnippet of(CodeBlock code) { <add> return new Builder().build(code); <add> } <add> <add> /** <add> * Process the specified code and return a fully-processed code snippet <add> * as a String. <add> * @param code a consumer to use to generate the code snippet <add> * @return a resolved code snippet <add> */ <add> public static String process(Consumer<CodeBlock.Builder> code) { <add> CodeBlock.Builder body = CodeBlock.builder(); <add> code.accept(body); <add> return process(body.build()); <add> } <add> <add> /** <add> * Process the specified {@link CodeBlock code} and return a <add> * fully-processed code snippet as a String. <add> * @param code the code snippet <add> * @return a resolved code snippet <add> */ <add> public static String process(CodeBlock code) { <add> return of(code).getSnippet(); <add> } <add> <add> private String removeIndent(String line, int indent) { <add> for (int i = 0; i < indent; i++) { <add> if (line.startsWith("\t")) { <add> line = line.substring(1); <add> } <add> } <add> return line; <add> } <add> <add> private static final class Builder { <add> <add> private static final String INDENT = "\t"; <add> <add> private static final String SNIPPET_INDENT = INDENT + INDENT; <add> <add> public CodeSnippet build(CodeBlock code) { <add> MethodSpec.Builder method = MethodSpec.methodBuilder("test") <add> .addModifiers(Modifier.PUBLIC); <add> CodeBlock.Builder body = CodeBlock.builder(); <add> body.add(START_SNIPPET); <add> body.add(code); <add> body.add(END_SNIPPET); <add> method.addCode(body.build()); <add> String fileContent = write(createTestJavaFile(method.build())); <add> String snippet = isolateGeneratedContent(fileContent); <add> return new CodeSnippet(fileContent, snippet); <add> } <add> <add> private String isolateGeneratedContent(String javaFile) { <add> int start = javaFile.indexOf(START_SNIPPET); <add> String tmp = javaFile.substring(start + START_SNIPPET.length()); <add> int end = tmp.indexOf(END_SNIPPET); <add> tmp = tmp.substring(0, end); <add> // Remove indent <add> return tmp.lines().map(line -> { <add> if (!line.startsWith(SNIPPET_INDENT)) { <add> throw new IllegalStateException("Missing indent for " + line); <add> } <add> return line.substring(SNIPPET_INDENT.length()); <add> }).collect(Collectors.joining("\n")); <add> } <add> <add> private JavaFile createTestJavaFile(MethodSpec method) { <add> return JavaFile.builder("example", TypeSpec.classBuilder("Test") <add> .addModifiers(Modifier.PUBLIC) <add> .addMethod(method).build()).indent(INDENT).build(); <add> } <add> <add> private String write(JavaFile file) { <add> try { <add> StringWriter out = new StringWriter(); <add> file.writeTo(out); <add> return out.toString(); <add> } <add> catch (IOException ex) { <add> throw new IllegalStateException("Failed to write " + file, ex); <add> } <add> } <add> <add> } <add>} <ide><path>spring-core/src/main/java/org/springframework/javapoet/support/MultiCodeBlock.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.javapoet.support; <add> <add>import java.util.ArrayList; <add>import java.util.List; <add>import java.util.function.Consumer; <add> <add>import org.springframework.javapoet.CodeBlock; <add>import org.springframework.javapoet.CodeBlock.Builder; <add> <add> <add>/** <add> * A {@link CodeBlock} wrapper for joining multiple blocks. <add> * <add> * @author Stephane Nicoll <add> * @since 6.0 <add> */ <add>public class MultiCodeBlock { <add> <add> private final List<CodeBlock> codeBlocks = new ArrayList<>(); <add> <add> <add> /** <add> * Add the specified {@link CodeBlock}. <add> * @param code the code block to add <add> */ <add> public void add(CodeBlock code) { <add> if (code.isEmpty()) { <add> throw new IllegalArgumentException("Could not add empty CodeBlock"); <add> } <add> this.codeBlocks.add(code); <add> } <add> <add> /** <add> * Add a {@link CodeBlock} using the specified callback. <add> * @param code the callback to use <add> */ <add> public void add(Consumer<Builder> code) { <add> Builder builder = CodeBlock.builder(); <add> code.accept(builder); <add> add(builder.build()); <add> } <add> <add> /** <add> * Add a code block using the specified formatted String and the specified <add> * arguments. <add> * @param code the code <add> * @param arguments the arguments <add> * @see Builder#add(String, Object...) <add> */ <add> public void add(String code, Object... arguments) { <add> add(CodeBlock.of(code, arguments)); <add> } <add> <add> /** <add> * Return a {@link CodeBlock} that joins the different blocks registered in <add> * this instance with the specified delimiter. <add> * @param delimiter the delimiter to use (not {@literal null}) <add> * @return a {@link CodeBlock} joining the blocks of this instance with the <add> * specified {@code delimiter} <add> * @see CodeBlock#join(Iterable, String) <add> */ <add> public CodeBlock join(String delimiter) { <add> return CodeBlock.join(this.codeBlocks, delimiter); <add> } <add> <add>} <ide><path>spring-core/src/main/java/org/springframework/javapoet/support/MultiStatement.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.javapoet.support; <add> <add>import java.util.ArrayList; <add>import java.util.List; <add>import java.util.function.Consumer; <add>import java.util.function.Function; <add> <add>import org.springframework.javapoet.CodeBlock; <add>import org.springframework.javapoet.CodeBlock.Builder; <add> <add> <add>/** <add> * A {@link CodeBlock} wrapper for multiple statements. <add> * <add> * @author Stephane Nicoll <add> * @since 6.0 <add> */ <add>public final class MultiStatement { <add> <add> private final List<Statement> statements = new ArrayList<>(); <add> <add> <add> /** <add> * Specify if this instance is empty. <add> * @return {@code true} if no statement is registered, {@code false} otherwise <add> */ <add> public boolean isEmpty() { <add> return this.statements.isEmpty(); <add> } <add> <add> /** <add> * Add the specified {@link CodeBlock codeblock} rendered as-is. <add> * @param codeBlock the code block to add <add> * @see #addStatement(CodeBlock) to add a code block that represents <add> * a statement <add> */ <add> public void add(CodeBlock codeBlock) { <add> this.statements.add(Statement.of(codeBlock)); <add> } <add> <add> /** <add> * Add a {@link CodeBlock} rendered as-is using the specified callback. <add> * @param code the callback to use <add> * @see #addStatement(CodeBlock) to add a code block that represents <add> * a statement <add> */ <add> public void add(Consumer<Builder> code) { <add> CodeBlock.Builder builder = CodeBlock.builder(); <add> code.accept(builder); <add> add(builder.build()); <add> } <add> <add> /** <add> * Add a statement. <add> * @param statement the statement to add <add> */ <add> public void addStatement(CodeBlock statement) { <add> this.statements.add(Statement.ofStatement(statement)); <add> } <add> <add> /** <add> * Add a statement using the specified callback. <add> * @param code the callback to use <add> */ <add> public void addStatement(Consumer<Builder> code) { <add> CodeBlock.Builder builder = CodeBlock.builder(); <add> code.accept(builder); <add> addStatement(builder.build()); <add> } <add> <add> /** <add> * Add a statement using the specified formatted String and the specified <add> * arguments. <add> * @param code the code of the statement <add> * @param args the arguments for placeholders <add> * @see CodeBlock#of(String, Object...) <add> */ <add> public void addStatement(String code, Object... args) { <add> addStatement(CodeBlock.of(code, args)); <add> } <add> <add> /** <add> * Add the statements produced from the {@code itemGenerator} applied on the specified <add> * items. <add> * @param items the items to handle, each item is represented as a statement <add> * @param itemGenerator the item generator <add> * @param <T> the type of the item <add> */ <add> public <T> void addAll(Iterable<T> items, Function<T, CodeBlock> itemGenerator) { <add> items.forEach(element -> addStatement(itemGenerator.apply(element))); <add> } <add> <add> /** <add> * Return a {@link CodeBlock} that applies all the {@code statements} of this <add> * instance. If only one statement is available, it is not completed using the <add> * {@code ;} termination so that it can be used in the context of a lambda. <add> * @return the statement(s) <add> */ <add> public CodeBlock toCodeBlock() { <add> Builder code = CodeBlock.builder(); <add> for (int i = 0; i < this.statements.size(); i++) { <add> Statement statement = this.statements.get(i); <add> statement.contribute(code, this.isMulti(), i == this.statements.size() - 1); <add> } <add> return code.build(); <add> } <add> <add> /** <add> * Return a {@link CodeBlock} that applies all the {@code statements} of this <add> * instance in the context of a lambda. <add> * @param lambda the context of the lambda, must end with {@code ->} <add> * @return the lambda body <add> */ <add> public CodeBlock toCodeBlock(CodeBlock lambda) { <add> Builder code = CodeBlock.builder(); <add> code.add(lambda); <add> if (isMulti()) { <add> code.beginControlFlow(""); <add> } <add> else { <add> code.add(" "); <add> } <add> code.add(toCodeBlock()); <add> if (isMulti()) { <add> code.add("\n").unindent().add("}"); <add> } <add> return code.build(); <add> } <add> <add> /** <add> * Return a {@link CodeBlock} that applies all the {@code statements} of this <add> * instance in the context of a lambda. <add> * @param lambda the context of the lambda, must end with {@code ->} <add> * @return the lambda body <add> */ <add> public CodeBlock toCodeBlock(String lambda) { <add> return toCodeBlock(CodeBlock.of(lambda)); <add> } <add> <add> private boolean isMulti() { <add> return this.statements.size() > 1; <add> } <add> <add> <add> private static class Statement { <add> <add> private final CodeBlock codeBlock; <add> <add> private final boolean addStatementTermination; <add> <add> Statement(CodeBlock codeBlock, boolean addStatementTermination) { <add> this.codeBlock = codeBlock; <add> this.addStatementTermination = addStatementTermination; <add> } <add> <add> void contribute(CodeBlock.Builder code, boolean multi, boolean isLastStatement) { <add> code.add(this.codeBlock); <add> if (this.addStatementTermination) { <add> if (!isLastStatement) { <add> code.add(";\n"); <add> } <add> else if (multi) { <add> code.add(";"); <add> } <add> } <add> } <add> <add> static Statement ofStatement(CodeBlock codeBlock) { <add> return new Statement(codeBlock, true); <add> } <add> <add> static Statement of(CodeBlock codeBlock) { <add> return new Statement(codeBlock, false); <add> } <add> <add> } <add> <add>} <ide><path>spring-core/src/main/java/org/springframework/javapoet/support/package-info.java <add>/** <add> * Support classes for JavaPoet usage. <add> */ <add>@NonNullApi <add>@NonNullFields <add>package org.springframework.javapoet.support; <add> <add>import org.springframework.lang.NonNullApi; <add>import org.springframework.lang.NonNullFields; <ide><path>spring-core/src/test/java/org/springframework/javapoet/support/CodeSnippetTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.javapoet.support; <add> <add>import java.util.ArrayList; <add>import java.util.List; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import org.springframework.javapoet.CodeBlock; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add> <add>/** <add> * Tests for {@link CodeSnippet}. <add> * <add> * @author Stephane Nicoll <add> */ <add>class CodeSnippetTests { <add> <add> @Test <add> void snippetUsesTabs() { <add> CodeBlock.Builder code = CodeBlock.builder(); <add> code.beginControlFlow("if (condition)"); <add> code.addStatement("bean.doThis()"); <add> code.endControlFlow(); <add> CodeSnippet codeSnippet = CodeSnippet.of(code.build()); <add> assertThat(codeSnippet.getSnippet()).isEqualTo(""" <add> if (condition) { <add> bean.doThis(); <add> } <add> """); <add> } <add> <add> @Test <add> void snippetResolvesImports() { <add> CodeSnippet codeSnippet = CodeSnippet.of( <add> CodeBlock.of("$T list = new $T<>()", List.class, ArrayList.class)); <add> assertThat(codeSnippet.getSnippet()).isEqualTo("List list = new ArrayList<>()"); <add> assertThat(codeSnippet.hasImport(List.class)).isTrue(); <add> assertThat(codeSnippet.hasImport(ArrayList.class)).isTrue(); <add> } <add> <add> @Test <add> void removeIndent() { <add> CodeBlock.Builder code = CodeBlock.builder(); <add> code.beginControlFlow("if (condition)"); <add> code.addStatement("doStuff()"); <add> code.endControlFlow(); <add> CodeSnippet snippet = CodeSnippet.of(code.build()); <add> assertThat(snippet.getSnippet().lines()).contains("\tdoStuff();"); <add> assertThat(snippet.removeIndent(1).getSnippet().lines()).contains("doStuff();"); <add> } <add> <add> @Test <add> void processProvidesSnippet() { <add> assertThat(CodeSnippet.process(code -> code.add("$T list;", List.class))) <add> .isEqualTo("List list;"); <add> } <add> <add>} <ide><path>spring-core/src/test/java/org/springframework/javapoet/support/MultiCodeBlockTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.javapoet.support; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import org.springframework.javapoet.CodeBlock; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <add> <add>/** <add> * Tests for {@link MultiCodeBlock}. <add> * <add> * @author Stephane Nicoll <add> */ <add>class MultiCodeBlockTests { <add> <add> @Test <add> void joinWithNoElement() { <add> MultiCodeBlock multi = new MultiCodeBlock(); <add> assertThat(multi.join(", ").isEmpty()).isTrue(); <add> } <add> <add> @Test <add> void joinWithEmptyElement() { <add> MultiCodeBlock multi = new MultiCodeBlock(); <add> assertThatIllegalArgumentException().isThrownBy(() -> multi.add(CodeBlock.builder().build())); <add> } <add> <add> @Test <add> void joinWithSingleElement() { <add> MultiCodeBlock multi = new MultiCodeBlock(); <add> multi.add(CodeBlock.of("$S", "Hello")); <add> assertThat(multi.join(", ")).hasToString("\"Hello\""); <add> } <add> <add> @Test <add> void joinWithSeveralElement() { <add> MultiCodeBlock multi = new MultiCodeBlock(); <add> multi.add(CodeBlock.of("$S", "Hello")); <add> multi.add(code -> code.add("42")); <add> multi.add("null"); <add> assertThat(multi.join(", ")).hasToString("\"Hello\", 42, null"); <add> } <add> <add>} <ide><path>spring-core/src/test/java/org/springframework/javapoet/support/MultiStatementTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.javapoet.support; <add> <add>import java.util.List; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import org.springframework.javapoet.CodeBlock; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add> <add>/** <add> * Tests for {@link MultiStatement}. <add> * <add> * @author Stephane Nicoll <add> */ <add>class MultiStatementTests { <add> <add> @Test <add> void isEmptyWithNoStatement() { <add> assertThat(new MultiStatement().isEmpty()).isTrue(); <add> } <add> <add> @Test <add> void isEmptyWithStatement() { <add> MultiStatement statements = new MultiStatement(); <add> statements.addStatement(CodeBlock.of("int i = 0")); <add> assertThat(statements.isEmpty()).isFalse(); <add> } <add> <add> @Test <add> void singleStatement() { <add> MultiStatement statements = new MultiStatement(); <add> statements.addStatement("field.method($S)", "hello"); <add> CodeBlock codeBlock = statements.toCodeBlock(); <add> assertThat(codeBlock.toString()).isEqualTo("field.method(\"hello\")"); <add> } <add> <add> @Test <add> void singleStatementWithCallback() { <add> MultiStatement statements = new MultiStatement(); <add> statements.addStatement(code -> code.add("field.method($S)", "hello")); <add> CodeBlock codeBlock = statements.toCodeBlock(); <add> assertThat(codeBlock.toString()).isEqualTo("field.method(\"hello\")"); <add> } <add> <add> @Test <add> void singleStatementWithCodeBlock() { <add> MultiStatement statements = new MultiStatement(); <add> statements.addStatement(CodeBlock.of("field.method($S)", "hello")); <add> CodeBlock codeBlock = statements.toCodeBlock(); <add> assertThat(codeBlock.toString()).isEqualTo("field.method(\"hello\")"); <add> } <add> <add> @Test <add> void multiStatements() { <add> MultiStatement statements = new MultiStatement(); <add> statements.addStatement("field.method($S)", "hello"); <add> statements.addStatement("field.anotherMethod($S)", "hello"); <add> CodeBlock codeBlock = statements.toCodeBlock(); <add> assertThat(codeBlock.toString()).isEqualTo(""" <add> field.method("hello"); <add> field.anotherMethod("hello");"""); <add> } <add> <add> @Test <add> void multiStatementsWithCodeBlockRenderedAsIs() { <add> MultiStatement statements = new MultiStatement(); <add> statements.addStatement("field.method($S)", "hello"); <add> statements.add(CodeBlock.of(("// Hello\n"))); <add> statements.add(code -> code.add("// World\n")); <add> statements.addStatement("field.anotherMethod($S)", "hello"); <add> CodeBlock codeBlock = statements.toCodeBlock(); <add> assertThat(codeBlock.toString()).isEqualTo(""" <add> field.method("hello"); <add> // Hello <add> // World <add> field.anotherMethod("hello");"""); <add> } <add> <add> @Test <add> void singleStatementWithLambda() { <add> MultiStatement statements = new MultiStatement(); <add> statements.addStatement("field.method($S)", "hello"); <add> CodeBlock codeBlock = statements.toCodeBlock(CodeBlock.of("() ->")); <add> assertThat(codeBlock.toString()).isEqualTo("() -> field.method(\"hello\")"); <add> } <add> <add> @Test <add> void multiStatementsWithLambda() { <add> MultiStatement statements = new MultiStatement(); <add> statements.addStatement("field.method($S)", "hello"); <add> statements.addStatement("field.anotherMethod($S)", "hello"); <add> CodeBlock codeBlock = statements.toCodeBlock(CodeBlock.of("() ->")); <add> assertThat(codeBlock.toString().lines()).containsExactly( <add> "() -> {", <add> " field.method(\"hello\");", <add> " field.anotherMethod(\"hello\");", <add> "}"); <add> } <add> <add> @Test <add> void multiStatementsWithAddAll() { <add> MultiStatement statements = new MultiStatement(); <add> statements.addAll(List.of(0, 1, 2), <add> index -> CodeBlock.of("field[$L] = $S", index, "hello")); <add> CodeBlock codeBlock = statements.toCodeBlock("() ->"); <add> assertThat(codeBlock.toString().lines()).containsExactly( <add> "() -> {", <add> " field[0] = \"hello\";", <add> " field[1] = \"hello\";", <add> " field[2] = \"hello\";", <add> "}"); <add> } <add> <add>}
7
Python
Python
add files via upload
92e0aa29b9c0db1590b0ec032177dd8dced750ff
<ide><path>Project Euler/Problem 02/sol2.py <add>def fib(n): <add> ls = [] <add> a,b = 0,1 <add> n += 1 <add> for i in range(n): <add> if (b % 2 == 0): <add> ls.append(b) <add> else: <add> pass <add> a,b = b, a+b <add> print (sum(ls)) <add> return None <add>fib(10)
1
Javascript
Javascript
provide all jquery functions as futures
675978f41fbd05a7ed3481a79b772877a59a1c15
<ide><path>src/scenario/DSL.js <ide> angular.scenario.dsl.repeater = function(selector) { <ide> }; <ide> <ide> angular.scenario.dsl.element = function(selector) { <del> var nameSuffix = "element '" + selector + "'"; <del> return $scenario.addFuture('Find ' + nameSuffix, function(done) { <del> var self = this, repeaterArray = [], ngBindPattern; <del> var startIndex = selector.search(angular.scenario.dsl.NG_BIND_PATTERN); <del> if (startIndex >= 0) { <del> ngBindPattern = selector.substring(startIndex + 2, selector.length - 2); <del> var element = this.testDocument.find('*').filter(function() { <del> return self.jQuery(this).attr('ng:bind') == ngBindPattern; <del> }); <del> done(element); <del> } else { <del> done(this.testDocument.find(selector)); <del> } <del> }); <add> var namePrefix = "Element '" + selector + "'"; <add> var futureJquery = {}; <add> for (key in _jQuery.fn) { <add> (function(){ <add> var jqFnName = key; <add> var jqFn = _jQuery.fn[key]; <add> futureJquery[key] = function() { <add> var jqArgs = arguments; <add> return $scenario.addFuture(namePrefix + "." + jqFnName + "()", <add> function(done) { <add> var self = this, repeaterArray = [], ngBindPattern; <add> var startIndex = selector.search(angular.scenario.dsl.NG_BIND_PATTERN); <add> if (startIndex >= 0) { <add> ngBindPattern = selector.substring(startIndex + 2, selector.length - 2); <add> var element = this.testDocument.find('*').filter(function() { <add> return self.jQuery(this).attr('ng:bind') == ngBindPattern; <add> }); <add> done(jqFn.apply(element, jqArgs)); <add> } else { <add> done(jqFn.apply(this.testDocument.find(selector), jqArgs)); <add> } <add> }); <add> }; <add> })(); <add> } <add> return futureJquery; <ide> }; <ide><path>test/scenario/DSLSpec.js <ide> describe("DSL", function() { <ide> expect(future.fulfilled).toBeTruthy(); <ide> } <ide> it('should find elements on the page and provide jquery api', function() { <del> var future = element('.reports-detail'); <del> expect(future.name).toEqual("Find element '.reports-detail'"); <add> var future = element('.reports-detail').text(); <add> expect(future.name).toEqual("Element '.reports-detail'.text()"); <ide> timeTravel(future); <del> expect(future.value.text()). <add> expect(future.value). <ide> toEqual('Description : Details...Date created: 01/01/01'); <del> expect(future.value.find('.desc').text()). <del> toEqual('Description : Details...'); <add>// expect(future.value.find('.desc').text()). <add>// toEqual('Description : Details...'); <ide> }); <ide> it('should find elements with angular syntax', function() { <del> var future = element('{{report.description}}'); <del> expect(future.name).toEqual("Find element '{{report.description}}'"); <add> var future = element('{{report.description}}').text(); <add> expect(future.name).toEqual("Element '{{report.description}}'.text()"); <ide> timeTravel(future); <del> expect(future.value.text()).toEqual('Details...'); <del> expect(future.value.attr('ng:bind')).toEqual('report.description'); <add> expect(future.value).toEqual('Details...'); <add>// expect(future.value.attr('ng:bind')).toEqual('report.description'); <add> }); <add> it('should be able to click elements', function(){ <add> var future = element('.link-class').click(); <add> expect(future.name).toEqual("Element '.link-class'.click()"); <add> executeFuture(future, html, function(value) { future.fulfill(value); }); <add> expect(future.fulfilled).toBeTruthy(); <add> // TODO(rajat): look for some side effect from click happening? <ide> }); <ide> }); <ide> });
2
Text
Text
remove unnecessary path to file
6bb8488ffb475337ed757f05681a031b60a5db5e
<ide><path>docs/api/compose.md <ide> This example demonstrates how to use `compose` to enhance a [store](Store.md) wi <ide> import { createStore, applyMiddleware, compose } from 'redux' <ide> import thunk from 'redux-thunk' <ide> import DevTools from './containers/DevTools' <del>import reducer from '../reducers/index' <add>import reducer from '../reducers' <ide> <ide> const store = createStore( <ide> reducer,
1
Javascript
Javascript
handle timeout on xhr requests
893c061dd60feb6daf31ab18dc0675ca39752c29
<ide><path>lib/adapters/xhr.js <ide> module.exports = function xhrAdapter(resolve, reject, config) { <ide> request = null; <ide> }; <ide> <add> // Handle timeout <add> request.ontimeout = function handleTimeout() { <add> reject(new Error('Timeout')); <add> <add> // Clean up request <add> request = null; <add> }; <add> <ide> // Add xsrf header <ide> // This is only done if running in a standard browser environment. <ide> // Specifically not if we're in a web worker, or react-native.
1
Javascript
Javascript
use const instead of var in async_hooks
435fe977e038ca5b778e39056a7a5ee69a5031df
<ide><path>benchmark/async_hooks/async-resource-vs-destroy.js <ide> function buildCurrentResource(getServe) { <ide> } <ide> <ide> function init(asyncId, type, triggerAsyncId, resource) { <del> var cr = executionAsyncResource(); <add> const cr = executionAsyncResource(); <ide> if (cr !== null) { <ide> resource[cls] = cr[cls]; <ide> }
1
PHP
PHP
fix coding standards
0ed675211007031dfc6a6368680e066b23e2c1c2
<ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> class CakeEmail { <ide> protected $_charset8bit = array('UTF-8', 'SHIFT_JIS'); <ide> <ide> /** <del> * define Content-Type charset name <add> * Define Content-Type charset name <ide> * <ide> * @var array <ide> */ <del> protected $_contentTypeCharset = array('ISO-2022-JP-MS' => 'ISO-2022-JP'); <del> <add> protected $_contentTypeCharset = array( <add> 'ISO-2022-JP-MS' => 'ISO-2022-JP' <add> ); <ide> <ide> /** <ide> * Constructor <ide> protected function _getContentTransferEncoding() { <ide> } <ide> <ide> /** <del> * Return charset value for Content-Type <add> * Return charset value for Content-Type. <add> * <add> * Checks fallback/compatibility types which include workarounds <add> * for legacy japanese character sets. <ide> * <ide> * @return string <ide> */ <ide> protected function _getContentTypeCharset() { <ide> return strtoupper($this->charset); <ide> } <ide> } <del>} <ide>\ No newline at end of file <add> <add>} <ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> public function testBodyEncodingIso2022JpMs() { <ide> $this->assertContains(mb_convert_encoding('①㈱','ISO-2022-JP-MS'), $result['message']); <ide> } <ide> <del> <ide> protected function _checkContentTransferEncoding($message, $charset) { <ide> $boundary = '--alt-' . $this->CakeEmail->getBoundary(); <ide> $result['text'] = false;
2
Python
Python
remove duplicate calls to get_output
1aaab7a228fdd6f3ef53e888e08bc2afd6b4213b
<ide><path>keras/models.py <ide> def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None): <ide> self.y_train = self.get_output(train=True) <ide> self.y_test = self.get_output(train=False) <ide> <del> self.y_train = self.get_output(train=True) <del> self.y_test = self.get_output(train=False) <del> <ide> # target of model <ide> self.y = T.zeros_like(self.y_train) <ide>
1
Text
Text
add information on interfaces and lambdas.
5e7c9a18075bd623ef4f955e815c8381c9c60a56
<ide><path>guide/english/java/lambda-expressions/index.md <ide> The terminal `collect` operation collects the stream as a list of strings. <ide> <ide> This is only one use of the Streams API used in Java 8. There are many other applications of streams utilizing other operations as seen here in the <ide> [documentation](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html). <add> <add>### Lambda Expressions and Interfaces <add> <add>Suppose you have an interface that looks something like this: <add> <add>```java <add>interface MathInterface { <add> int operation(int x, int y); <add>} <add>``` <add> <add>You can create an instance of this interface in one line using lambdas provided that the interface only has one method. <add> <add>```java <add>MathInterface multiply = ((int x, int y) -> x * y); <add>MathInterface add = ((x, y) -> x + y); <add>MathInterface subtraction = ((x, y) -> x - y); <add>MathInterface division = (((x, y) -> x / y)); <add> <add>multiply.operation(1, 2); // == 2 <add>add.operation(1, 2); // == 3 <add>``` <add> <add>Note that in some of these interfaces, we don't specify the type of each parameter. This is valid and will still work the same as specifying the types such as `(int x, int y) -> x * y`. If you specify one type, however, you must specify all types of the lambda function. <ide> <ide> #### More Information: <ide> <!-- Please add any articles you think might be helpful to read before writing the article -->
1
Text
Text
add changelog entry for
6d83ed71295e38afe332ecad51f686513eeb99cf
<ide><path>actionview/CHANGELOG.md <add>* Add `to_sentence` helper that is a HTML-safe aware version of `Array#to_sentence`. <add> <add> *Neil Matatall* <add> <ide> * Deprecate `datetime_field` and `datetime_field_tag` helpers. <ide> Datetime input type was removed from HTML specification. <ide> One can use `datetime_local_field` and `datetime_local_field_tag` instead.
1
Javascript
Javascript
add more notes about ngrepeat and clean up style
d7a78e420adad0869cf811ea14a6d801695dbfa0
<ide><path>src/ng/directive/select.js <ide> var ngOptionsMinErr = minErr('ngOptions'); <ide> * elements for the `<select>` element using the array or object obtained by evaluating the <ide> * `ngOptions` comprehension_expression. <ide> * <add> * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a <add> * similar result. However, the `ngOptions` provides some benefits such as reducing memory and <add> * increasing speed by not creating a new scope for each repeated instance, as well as providing <add> * more flexibility in how the `select`'s model is assigned via `select as`. `ngOptions should be <add> * used when the `select` model needs to be bound to a non-string value. This is because an option <add> * element can only be bound to string values at present. <add> * <ide> * When an item in the `<select>` menu is selected, the array element or object property <ide> * represented by the selected option will be bound to the model identified by the `ngModel` <ide> * directive. <ide> * <del> * <div class="alert alert-warning"> <del> * **Note:** `ngModel` compares by reference, not value. This is important when binding to an <del> * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/). <del> * </div> <del> * <ide> * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can <ide> * be nested into the `<select>` element. This element will then represent the `null` or "not selected" <ide> * option. See example below for demonstration. <ide> * <ide> * <div class="alert alert-warning"> <del> * **Note:** `ngOptions` provides an iterator facility for the `<option>` element which should be used instead <del> * of {@link ng.directive:ngRepeat ngRepeat} when you want the <del> * `select` model to be bound to a non-string value. This is because an option element can only <del> * be bound to string values at present. <add> * **Note:** `ngModel` compares by reference, not value. This is important when binding to an <add> * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/). <ide> * </div> <ide> * <del> * <div class="alert alert-info"> <del> * **Note:** Using `select as` will bind the result of the `select as` expression to the model, but <add> * ## `select as` <add> * <add> * Using `select as` will bind the result of the `select as` expression to the model, but <ide> * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources) <del> * or property name (for object data sources) of the value within the collection. <del> * </div> <add> * or property name (for object data sources) of the value within the collection. If a `track by` expression <add> * is used, the result of that expression will be set as the value of the `option` and `select` elements. <add> * <add> * ### `select as` with `trackexpr` <add> * <add> * Using `select as` together with `trackexpr` is not recommended. Reasoning: <ide> * <del> * **Note:** Using `select as` together with `trackexpr` is not recommended. <del> * Reasoning: <ide> * - Example: &lt;select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected"&gt; <ide> * values: [{id: 1, label: 'aLabel', subItem: {name: 'aSubItem'}}, {id: 2, label: 'bLabel', subItem: {name: 'bSubItem'}}], <ide> * $scope.selected = {name: 'aSubItem'};
1
Go
Go
remove unused variable
f5557f4f43ba89a448131fbca8094f9cf8ddb097
<ide><path>daemon/logger/logger.go <ide> package logger <ide> <ide> import ( <ide> "errors" <del> "sync" <ide> "time" <ide> <ide> "github.com/docker/docker/pkg/timeutils" <ide> type LogWatcher struct { <ide> // For sending error messages that occur while while reading logs. <ide> Err chan error <ide> closeNotifier chan struct{} <del> closeOnce sync.Once <ide> } <ide> <ide> // NewLogWatcher returns a new LogWatcher.
1
PHP
PHP
add deprecation warnings to hasmany
b0ebd2969e7fb809e78601ad3c129768c28594db
<ide><path>src/ORM/Association/HasMany.php <ide> public function getSaveStrategy() <ide> */ <ide> public function saveStrategy($strategy = null) <ide> { <add> deprecationWarning( <add> 'HasMany::saveStrategy() is deprecated. ' . <add> 'Use setSaveStrategy()/getSaveStrategy() instead.' <add> ); <ide> if ($strategy !== null) { <ide> $this->setSaveStrategy($strategy); <ide> } <ide> public function getSort() <ide> */ <ide> public function sort($sort = null) <ide> { <add> deprecationWarning( <add> 'HasMany::sort() is deprecated. ' . <add> 'Use setSort()/getSort() instead.' <add> ); <ide> if ($sort !== null) { <ide> $this->setSort($sort); <ide> } <ide><path>tests/TestCase/ORM/Association/HasManyTest.php <ide> public function testCanBeJoined() <ide> /** <ide> * Tests sort() method <ide> * <add> * @group deprecated <ide> * @return void <ide> */ <ide> public function testSort() <add> { <add> $this->deprecated(function () { <add> $assoc = new HasMany('Test'); <add> $this->assertNull($assoc->sort()); <add> $assoc->sort(['id' => 'ASC']); <add> $this->assertEquals(['id' => 'ASC'], $assoc->sort()); <add> }); <add> } <add> <add> /** <add> * Tests setSort() method <add> * <add> * @return void <add> */ <add> public function testSetSort() <ide> { <ide> $assoc = new HasMany('Test'); <del> $this->assertNull($assoc->sort()); <del> $assoc->sort(['id' => 'ASC']); <del> $this->assertEquals(['id' => 'ASC'], $assoc->sort()); <add> $this->assertNull($assoc->getSort()); <add> $assoc->setSort(['id' => 'ASC']); <add> $this->assertEquals(['id' => 'ASC'], $assoc->getSort()); <ide> } <ide> <ide> /**
2
PHP
PHP
fix cs errors
3e88be4194a71c14a03a0e05685f000607fcfa17
<ide><path>src/Database/Driver.php <ide> <ide> use Cake\Database\Exception\MissingConnectionException; <ide> use Cake\Database\Schema\BaseSchema; <del>use Cake\Database\Query; <ide> use Cake\Database\Schema\TableSchema; <ide> use Cake\Database\Statement\PDOStatement; <ide> use Closure; <ide><path>src/ORM/Table.php <ide> use Cake\Database\Connection; <ide> use Cake\Database\Schema\TableSchemaInterface; <ide> use Cake\Database\TypeFactory; <del>use Cake\Datasource\ConnectionInterface; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Datasource\Exception\InvalidPrimaryKeyException; <ide><path>src/TestSuite/Constraint/Response/HeaderContains.php <ide> public function matches($other): bool <ide> */ <ide> public function toString(): string <ide> { <del> return sprintf('is in header \'%s\' (`%s`)', $this->headerName, $this->response->getHeaderLine($this->headerName)); <add> return sprintf( <add> 'is in header \'%s\' (`%s`)', <add> $this->headerName, <add> $this->response->getHeaderLine($this->headerName) <add> ); <ide> } <ide> } <ide><path>src/TestSuite/Constraint/Response/HeaderNotContains.php <ide> public function matches($other): bool <ide> */ <ide> public function toString(): string <ide> { <del> return sprintf("is not in header '%s' (`%s`)", $this->headerName, $this->response->getHeaderLine($this->headerName)); <add> return sprintf( <add> "is not in header '%s' (`%s`)", <add> $this->headerName, <add> $this->response->getHeaderLine($this->headerName) <add> ); <ide> } <ide> } <ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php <ide> public static function columnSqlProvider() <ide> [ <ide> 'value', <ide> ['type' => 'decimal', 'length' => 11, 'unsigned' => true], <del> '`value` DECIMAL(11) UNSIGNED' <add> '`value` DECIMAL(11) UNSIGNED', <ide> ], <ide> [ <ide> 'value',
5
Javascript
Javascript
simplify code and remove obsolete checks
e68b0d6fb333ae487bd04bd945342b2c63e4ead6
<ide><path>lib/path.js <ide> const win32 = { <ide> } <ide> } <ide> <del> if (startDot === -1 || <del> end === -1 || <del> // We saw a non-dot character immediately before the dot <del> preDotState === 0 || <del> // The (right-most) trimmed path component is exactly '..' <del> (preDotState === 1 && <del> startDot === end - 1 && <del> startDot === startPart + 1)) { <del> if (end !== -1) { <add> if (end !== -1) { <add> if (startDot === -1 || <add> // We saw a non-dot character immediately before the dot <add> preDotState === 0 || <add> // The (right-most) trimmed path component is exactly '..' <add> (preDotState === 1 && <add> startDot === end - 1 && <add> startDot === startPart + 1)) { <ide> ret.base = ret.name = path.slice(startPart, end); <add> } else { <add> ret.name = path.slice(startPart, startDot); <add> ret.base = path.slice(startPart, end); <add> ret.ext = path.slice(startDot, end); <ide> } <del> } else { <del> ret.name = path.slice(startPart, startDot); <del> ret.base = path.slice(startPart, end); <del> ret.ext = path.slice(startDot, end); <ide> } <ide> <ide> // If the directory is the root, use the entire root as the `dir` including <ide> const posix = { <ide> } <ide> } <ide> <del> if (startDot === -1 || <del> end === -1 || <del> // We saw a non-dot character immediately before the dot <del> preDotState === 0 || <del> // The (right-most) trimmed path component is exactly '..' <del> (preDotState === 1 && <del> startDot === end - 1 && <del> startDot === startPart + 1)) { <del> if (end !== -1) { <del> if (startPart === 0 && isAbsolute) <del> ret.base = ret.name = path.slice(1, end); <del> else <del> ret.base = ret.name = path.slice(startPart, end); <del> } <del> } else { <del> if (startPart === 0 && isAbsolute) { <del> ret.name = path.slice(1, startDot); <del> ret.base = path.slice(1, end); <add> if (end !== -1) { <add> const start = startPart === 0 && isAbsolute ? 1 : startPart; <add> if (startDot === -1 || <add> // We saw a non-dot character immediately before the dot <add> preDotState === 0 || <add> // The (right-most) trimmed path component is exactly '..' <add> (preDotState === 1 && <add> startDot === end - 1 && <add> startDot === startPart + 1)) { <add> ret.base = ret.name = path.slice(start, end); <ide> } else { <del> ret.name = path.slice(startPart, startDot); <del> ret.base = path.slice(startPart, end); <add> ret.name = path.slice(start, startDot); <add> ret.base = path.slice(start, end); <add> ret.ext = path.slice(startDot, end); <ide> } <del> ret.ext = path.slice(startDot, end); <ide> } <ide> <ide> if (startPart > 0)
1
Javascript
Javascript
fix merge issue
821c350bf7e2a796cb4a2cae05be4bd168005e9f
<ide><path>test/configCases/dll-plugin-side-effects/0-create-dll/webpack.config.js <ide> module.exports = { <ide> path: path.resolve( <ide> __dirname, <ide> "../../../js/config/dll-plugin-side-effects/manifest0.json" <del> ) <add> ), <add> entryOnly: false <ide> }) <ide> ] <ide> };
1
Python
Python
improve docs formatting
c400d0e798275ac79f84fd2f974a8c01cd7deb15
<ide><path>docs/autogen.py <ide> 'all_module_functions': [utils], <ide> 'classes': [utils.CustomObjectScope, <ide> utils.HDF5Matrix, <del> utils.Sequence, <del> utils.multi_gpu_model] <add> utils.Sequence], <ide> }, <ide> ] <ide> <ide> def get_function_signature(function, method=True): <ide> else: <ide> kwargs = [] <ide> st = '%s.%s(' % (function.__module__, function.__name__) <add> <ide> for a in args: <ide> st += str(a) + ', ' <ide> for a, v in kwargs: <ide> if isinstance(v, str): <ide> v = '\'' + v + '\'' <ide> st += str(a) + '=' + str(v) + ', ' <ide> if kwargs or args: <del> return st[:-2] + ')' <add> signature = st[:-2] + ')' <ide> else: <del> return st + ')' <add> signature = st + ')' <add> return signature <ide> <ide> <ide> def get_class_signature(cls): <ide> def process_class_docstring(docstring): <ide> docstring = re.sub(r'\n # (.*)\n', <ide> r'\n __\1__\n\n', <ide> docstring) <del> <ide> docstring = re.sub(r' ([^\s\\\(]+):(.*)\n', <ide> r' - __\1__:\2\n', <ide> docstring) <ide> def process_function_docstring(docstring): <ide> docstring = re.sub(r'\n # (.*)\n', <ide> r'\n __\1__\n\n', <ide> docstring) <del> docstring = re.sub(r'\n # (.*)\n', <del> r'\n __\1__\n\n', <del> docstring) <del> <ide> docstring = re.sub(r' ([^\s\\\(]+):(.*)\n', <ide> r' - __\1__:\2\n', <ide> docstring) <ide><path>keras/layers/core.py <ide> class Flatten(Layer): <ide> ```python <ide> model = Sequential() <ide> model.add(Conv2D(64, 3, 3, <del> border_mode='same', <del> input_shape=(3, 32, 32))) <add> border_mode='same', <add> input_shape=(3, 32, 32))) <ide> # now: model.output_shape == (None, 64, 32, 32) <ide> <ide> model.add(Flatten()) <ide><path>keras/utils/data_utils.py <ide> def _hash_file(fpath, algorithm='sha256', chunk_size=65535): <ide> # Example <ide> <ide> ```python <del> >>> from keras.data_utils import _hash_file <del> >>> _hash_file('/path/to/file.zip') <del> 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' <add> >>> from keras.data_utils import _hash_file <add> >>> _hash_file('/path/to/file.zip') <add> 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' <ide> ``` <ide> <ide> # Arguments <ide> class Sequence(object): <ide> # Examples <ide> <ide> ```python <del> from skimage.io import imread <del> from skimage.transform import resize <del> import numpy as np <add> from skimage.io import imread <add> from skimage.transform import resize <add> import numpy as np <ide> <del> # Here, `x_set` is list of path to the images <del> # and `y_set` are the associated classes. <add> # Here, `x_set` is list of path to the images <add> # and `y_set` are the associated classes. <ide> <del> class CIFAR10Sequence(Sequence): <add> class CIFAR10Sequence(Sequence): <ide> <del> def __init__(self, x_set, y_set, batch_size): <del> self.x, self.y = x_set, y_set <del> self.batch_size = batch_size <add> def __init__(self, x_set, y_set, batch_size): <add> self.x, self.y = x_set, y_set <add> self.batch_size = batch_size <ide> <del> def __len__(self): <del> return len(self.x) // self.batch_size <add> def __len__(self): <add> return len(self.x) // self.batch_size <ide> <del> def __getitem__(self, idx): <del> batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size] <del> batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size] <add> def __getitem__(self, idx): <add> batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size] <add> batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size] <ide> <del> return np.array([ <del> resize(imread(file_name), (200, 200)) <del> for file_name in batch_x]), np.array(batch_y) <add> return np.array([ <add> resize(imread(file_name), (200, 200)) <add> for file_name in batch_x]), np.array(batch_y) <ide> ``` <ide> """ <ide> <ide> class SequenceEnqueuer(object): <ide> # Examples <ide> <ide> ```python <del> enqueuer = SequenceEnqueuer(...) <del> enqueuer.start() <del> datas = enqueuer.get() <del> for data in datas: <del> # Use the inputs; training, evaluating, predicting. <del> # ... stop sometime. <del> enqueuer.close() <add> enqueuer = SequenceEnqueuer(...) <add> enqueuer.start() <add> datas = enqueuer.get() <add> for data in datas: <add> # Use the inputs; training, evaluating, predicting. <add> # ... stop sometime. <add> enqueuer.close() <ide> ``` <ide> <ide> The `enqueuer.get()` should be an infinite stream of datas.
3
Ruby
Ruby
remove call to sanitize_sql_hash_for_conditions
4bd089f1d93fa168b0ae17dd8c92a5157a2537d7
<ide><path>activerecord/lib/active_record/sanitization.rb <ide> def sanitize_sql_for_conditions(condition, table_name = self.table_name) <ide> <ide> case condition <ide> when Array; sanitize_sql_array(condition) <del> when Hash; sanitize_sql_hash_for_conditions(condition, table_name) <ide> else condition <ide> end <ide> end
1
Text
Text
add license information
df5aac8b092f6552b065aa68c09e034b3e5e71e0
<ide><path>docs/Formula-Cookbook.md <ide> class Foo < Formula <ide> homepage "" <ide> url "https://example.com/foo-0.1.tar.gz" <ide> sha256 "85cc828a96735bdafcf29eb6291ca91bac846579bcef7308536e0c875d6c81d7" <add> license "" <ide> <ide> # depends_on "cmake" => :build <ide> <ide> An SSL/TLS (https) [`homepage`](https://rubydoc.brew.sh/Formula#homepage%3D-clas <ide> <ide> Try to summarise from the [`homepage`](https://rubydoc.brew.sh/Formula#homepage%3D-class_method) what the formula does in the [`desc`](https://rubydoc.brew.sh/Formula#desc%3D-class_method)ription. Note that the [`desc`](https://rubydoc.brew.sh/Formula#desc%3D-class_method)ription is automatically prepended with the formula name. <ide> <add>### Fill in the `license` <add> <add>**We don’t accept formulae without a [`license`](https://rubydoc.brew.sh/Formula#license-class_method)!** <add> <add>Find the license identifier from the [SPDX License List](https://spdx.org/licenses/). Note that we don't accept licenses that don't appear on the list. <add> <add>If the formula gives the user the option to choose which license to use, you should list them all in an array: <add> <add>```ruby <add>license ["MIT", "GPL-2.0"] <add>``` <add> <add>Note: only specify multiple licenses if the formula gives the user a choice between the licenses. Formulae that have different licenses for different parts of their software should specify only the more restrictive license. <add> <ide> ### Check the build system <ide> <ide> ```sh
1
PHP
PHP
input() phpdoc @return
db8950690187d49d5096e12b255e94de1017c5e4
<ide><path>src/Illuminate/Http/Request.php <ide> public function all() <ide> * <ide> * @param string $key <ide> * @param mixed $default <del> * @return string <add> * @return string|array <ide> */ <ide> public function input($key = null, $default = null) <ide> {
1
Ruby
Ruby
fix syntax error
fab6b6c19d3be7a2ded5b7aa050064c5d66c5340
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def brew_update <ide> elsif ENV["TRAVIS_COMMIT_RANGE"] <ide> diff_start_sha1, diff_end_sha1 = ENV["TRAVIS_COMMIT_RANGE"].split "..." <ide> diff_end_sha1 = ENV["TRAVIS_COMMIT"] if travis_pr <del> elseif ENV["ghprbPullLink"] <add> elsif ENV["ghprbPullLink"] <ide> # Handle Jenkins pull request builder plugin. <ide> @url = ENV["ghprbPullLink"] <ide> @hash = nil
1