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
PHP
PHP
fix bug in form builder
105541d3540aba4485f651ff7cec27745c920b53
<ide><path>src/Illuminate/Html/FormBuilder.php <ide> protected function getAction(array $options) <ide> */ <ide> protected function getAppendage($method) <ide> { <add> $method = strtoupper($method); <add> <ide> if ($method == 'PUT' or $method == 'DELETE') <ide> { <del> $append = $this->hidden('_method', $method); <add> return $this->hidden('_method', $method); <ide> } <ide> <ide> return '';
1
Text
Text
add my focus
cd045b33c750011016c6c49456987d5156d26c93
<ide><path>docs/focus/2018-03-19.md <ide> - Adjusted teletype-server's caching directives in an effort to reduce or eliminate package initialization errors ([atom/teletype-server#47](https://github.com/atom/teletype-server/pull/47), [atom/teletype#318](https://github.com/atom/teletype/issues/318)) <ide> - Published first draft of RFC for streamlining collaboration set-up, including the ability to give guests a URL that they can use to join your portal, and a "buddy list" for more quickly collaborating with coworkers and friends ([atom/teletype#344](https://github.com/atom/teletype/pull/344)) <ide> - Tree-sitter <add> - Fixed some remaining issues with last week's optimizations related to parser size & compile time (https://github.com/tree-sitter/tree-sitter/pull/148) <ide> - Xray <del> - Optimized selections. We're moving 1k selections in a document with 10k edits in ~2ms, and we think there's still room for improvement. <del> - Made significant progress on a switch to a client/server architecture. <del> - See [this week's in-depth Xray update](https://github.com/atom/xray/blob/master/docs/updates/2018_03_19.md) for more details. <add> - Optimized selections. We're moving 1k selections in a document with 10k edits in ~2ms, and we think there's still room for improvement. <add> - Made significant progress on a switch to a client/server architecture. <add> - See [this week's in-depth Xray update](https://github.com/atom/xray/blob/master/docs/updates/2018_03_19.md) for more details. <ide> - Engineering Improvements <ide> - Process `.tsx` files within Atom as TypeScript in a kind of hacky way. [atom/atom#16944](https://github.com/atom/atom/pull/16944) <ide> - Reactor Duty <ide> - Update RFC for streamlining collaboration set-up to incorporate feedback from core dev team, and then request comments from the public ([atom/teletype#344](https://github.com/atom/teletype/pull/344)) <ide> - Add preliminary support for joining a portal via URL ([atom/teletype#109](https://github.com/atom/teletype/issues/109)) <ide> - Tree-sitter <add> - Address bugs reported now that Tree-sitter is in stable Atom. <ide> - Xray <del> - Continue to make progress on the [PR switching Xray to a client/server architecture](https://github.com/atom/xray/pull/46). Hopefully we can merge it this week. <del> - Investigate a switch from JSON to protocol buffers. <add> - Continue to make progress on the [PR switching Xray to a client/server architecture](https://github.com/atom/xray/pull/46). Hopefully we can merge it this week. <add> - Investigate a switch from JSON to protocol buffers. <ide> - Engineering Improvements <ide> - Reactor Duty
1
Mixed
Javascript
capitalize comment sentences
50dd555910ed0338c35f27ee57e947b9ec95724c
<ide><path>.eslintrc.js <ide> module.exports = { <ide> 'brace-style': ['error', '1tbs', { allowSingleLine: true }], <ide> 'capitalized-comments': ['error', 'always', { <ide> line: { <del> // Ignore all lines that have less characters than 62 and all lines that <add> // Ignore all lines that have less characters than 50 and all lines that <ide> // start with something that looks like a variable name or code. <del> ignorePattern: '^.{0,62}$|^ [a-z]+ ?[0-9A-Z_.(/=:-]', <add> ignorePattern: '^.{0,50}$|^ [a-z]+ ?[0-9A-Z_.(/=:[#-]', <ide> ignoreInlineComments: true, <ide> ignoreConsecutiveComments: true <ide> }, <ide><path>benchmark/_benchmark_progress.js <ide> class BenchmarkProgress { <ide> this.completedConfig = 0; <ide> // Total number of configurations for the current file <ide> this.scheduledConfig = 0; <del> this.interval = 0; // result of setInterval for updating the elapsed time <add> this.interval; // Updates the elapsed time. <ide> } <ide> <ide> startQueue(index) { <ide><path>benchmark/napi/function_args/index.js <del>// show the difference between calling a V8 binding C++ function <add>// Show the difference between calling a V8 binding C++ function <ide> // relative to a comparable N-API C++ function, <ide> // in various types/numbers of arguments. <ide> // Reports n of calls per second. <ide><path>benchmark/napi/function_call/index.js <del>// show the difference between calling a short js function <add>// Show the difference between calling a short js function <ide> // relative to a comparable C++ function. <ide> // Reports n of calls per second. <ide> // Note that JS speed goes up, while cxx speed stays about the same. <ide><path>benchmark/net/net-pipe.js <ide> function main({ dur, len, type }) { <ide> socket.pipe(writer); <ide> <ide> setTimeout(function() { <del> // multiply by 2 since we're sending it first one way <add> // Multiply by 2 since we're sending it first one way <ide> // then then back again. <ide> const bytes = writer.received * 2; <ide> const gbits = (bytes * 8) / (1024 * 1024 * 1024); <ide><path>benchmark/net/tcp-raw-c2s.js <ide> function main({ dur, len, type }) { <ide> }, dur * 1000); <ide> <ide> clientHandle.onread = function(buffer) { <del> // we're not expecting to ever get an EOF from the client. <del> // just lots of data forever. <add> // We're not expecting to ever get an EOF from the client. <add> // Just lots of data forever. <ide> if (!buffer) <ide> fail('read'); <ide> <del> // don't slice the buffer. the point of this is to isolate, not <add> // Don't slice the buffer. The point of this is to isolate, not <ide> // simulate real traffic. <ide> bytes += buffer.byteLength; <ide> }; <ide><path>benchmark/net/tcp-raw-pipe.js <ide> function main({ dur, len, type }) { <ide> fail(err, 'connect'); <ide> <ide> clientHandle.onread = function(buffer) { <del> // we're not expecting to ever get an EOF from the client. <del> // just lots of data forever. <add> // We're not expecting to ever get an EOF from the client. <add> // Just lots of data forever. <ide> if (!buffer) <ide> fail('read'); <ide> <ide> function main({ dur, len, type }) { <ide> clientHandle.readStart(); <ide> <ide> setTimeout(function() { <del> // multiply by 2 since we're sending it first one way <add> // Multiply by 2 since we're sending it first one way <ide> // then then back again. <ide> bench.end(2 * (bytes * 8) / (1024 * 1024 * 1024)); <ide> process.exit(0); <ide><path>benchmark/net/tcp-raw-s2c.js <ide> function main({ dur, len, type }) { <ide> connectReq.oncomplete = function() { <ide> var bytes = 0; <ide> clientHandle.onread = function(buffer) { <del> // we're not expecting to ever get an EOF from the client. <del> // just lots of data forever. <add> // We're not expecting to ever get an EOF from the client. <add> // Just lots of data forever. <ide> if (!buffer) <ide> fail('read'); <ide> <del> // don't slice the buffer. the point of this is to isolate, not <add> // Don't slice the buffer. The point of this is to isolate, not <ide> // simulate real traffic. <ide> bytes += buffer.byteLength; <ide> }; <ide><path>benchmark/tls/tls-connect.js <ide> function makeConnection() { <ide> <ide> function done() { <ide> running = false; <del> // it's only an established connection if they both saw it. <add> // It's only an established connection if they both saw it. <ide> // because we destroy the server somewhat abruptly, these <ide> // don't always match. Generally, serverConn will be <ide> // the smaller number, but take the min just to be sure. <ide><path>doc/api/async_hooks.md <ide> function before(asyncId) { } <ide> // After is called just after the resource's callback has finished. <ide> function after(asyncId) { } <ide> <del>// destroy is called when an AsyncWrap instance is destroyed. <add>// Destroy is called when an AsyncWrap instance is destroyed. <ide> function destroy(asyncId) { } <ide> <ide> // promiseResolve is called only for promise resources, when the <ide><path>doc/api/cluster.md <ide> if (cluster.isMaster) { <ide> <ide> process.on('message', (msg) => { <ide> if (msg === 'shutdown') { <del> // initiate graceful close of any connections to server <add> // Initiate graceful close of any connections to server <ide> } <ide> }); <ide> } <ide><path>doc/api/domain.md <ide> const serverDomain = domain.create(); <ide> serverDomain.run(() => { <ide> // server is created in the scope of serverDomain <ide> http.createServer((req, res) => { <del> // req and res are also created in the scope of serverDomain <add> // Req and res are also created in the scope of serverDomain <ide> // however, we'd prefer to have a separate domain for each request. <ide> // create it first thing, and add req and res to it. <ide> const reqd = domain.create(); <ide> const d = domain.create(); <ide> <ide> function readSomeFile(filename, cb) { <ide> fs.readFile(filename, 'utf8', d.bind((er, data) => { <del> // if this throws, it will also be passed to the domain <add> // If this throws, it will also be passed to the domain <ide> return cb(er, data ? JSON.parse(data) : null); <ide> })); <ide> } <ide><path>doc/api/esm.md <ide> export async function dynamicInstantiate(url) { <ide> return { <ide> exports: ['customExportName'], <ide> execute: (exports) => { <del> // get and set functions provided for pre-allocated export names <add> // Get and set functions provided for pre-allocated export names <ide> exports.customExportName.set('value'); <ide> } <ide> }; <ide><path>doc/api/events.md <ide> const logFnWrapper = listeners[0]; <ide> // Logs "log once" to the console and does not unbind the `once` event <ide> logFnWrapper.listener(); <ide> <del>// logs "log once" to the console and removes the listener <add>// Logs "log once" to the console and removes the listener <ide> logFnWrapper(); <ide> <ide> emitter.on('log', () => console.log('log persistently')); <ide><path>doc/api/path.md <ide> path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); <ide> // Returns: '/foo/bar/baz/asdf' <ide> <ide> path.join('foo', {}, 'bar'); <del>// throws 'TypeError: Path must be a string. Received {}' <add>// Throws 'TypeError: Path must be a string. Received {}' <ide> ``` <ide> <ide> A [`TypeError`][] is thrown if any of the path segments is not a string. <ide> path.resolve('/foo/bar', '/tmp/file/'); <ide> // Returns: '/tmp/file' <ide> <ide> path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); <del>// if the current working directory is /home/myself/node, <add>// If the current working directory is /home/myself/node, <ide> // this returns '/home/myself/node/wwwroot/static_files/gif/image.gif' <ide> ``` <ide> <ide><path>doc/api/perf_hooks.md <ide> const { <ide> } = require('perf_hooks'); <ide> <ide> const obs = new PerformanceObserver((list, observer) => { <del> // called three times synchronously. list contains one item <add> // Called three times synchronously. list contains one item <ide> }); <ide> obs.observe({ entryTypes: ['mark'] }); <ide> <ide><path>doc/api/stream.md <ide> that implements an HTTP server: <ide> const http = require('http'); <ide> <ide> const server = http.createServer((req, res) => { <del> // req is an http.IncomingMessage, which is a Readable Stream <del> // res is an http.ServerResponse, which is a Writable Stream <add> // `req` is an http.IncomingMessage, which is a Readable Stream <add> // `res` is an http.ServerResponse, which is a Writable Stream <ide> <ide> let body = ''; <ide> // Get the data as utf8 strings. <ide> function parseHeader(stream, callback) { <ide> stream.removeListener('readable', onReadable); <ide> if (buf.length) <ide> stream.unshift(buf); <del> // now the body of the message can be read from the stream. <add> // Now the body of the message can be read from the stream. <ide> callback(null, header, stream); <ide> } else { <ide> // still reading the header. <ide> pause/resume mechanism, and a data callback, the low-level source can be wrapped <ide> by the custom `Readable` instance: <ide> <ide> ```js <del>// source is an object with readStop() and readStart() methods, <add>// `_source` is an object with readStop() and readStart() methods, <ide> // and an `ondata` member that gets called when it has data, and <ide> // an `onend` member that gets called when the data is over. <ide> <ide> class SourceWrapper extends Readable { <ide> constructor(options) { <ide> super(options); <ide> <del> this._source = getLowlevelSourceObject(); <add> this._source = getLowLevelSourceObject(); <ide> <ide> // Every time there's data, push it into the internal buffer. <ide> this._source.ondata = (chunk) => { <del> // if push() returns false, then stop reading from source <add> // If push() returns false, then stop reading from source <ide> if (!this.push(chunk)) <ide> this._source.readStop(); <ide> }; <ide> For example, consider the following code: <ide> // WARNING! BROKEN! <ide> net.createServer((socket) => { <ide> <del> // we add an 'end' listener, but never consume the data <add> // We add an 'end' listener, but never consume the data <ide> socket.on('end', () => { <ide> // It will never get here. <ide> socket.end('The message was received but was not processed.\n'); <ide><path>doc/api/tracing.md <ide> t2.enable(); <ide> // Prints 'node,node.perf,v8' <ide> console.log(trace_events.getEnabledCategories()); <ide> <del>t2.disable(); // will only disable emission of the 'node.perf' category <add>t2.disable(); // Will only disable emission of the 'node.perf' category <ide> <ide> // Prints 'node,v8' <ide> console.log(trace_events.getEnabledCategories()); <ide><path>doc/api/vm.md <ide> const sandbox = { x: 2 }; <ide> vm.createContext(sandbox); // Contextify the sandbox. <ide> <ide> const code = 'x += 40; var y = 17;'; <del>// x and y are global variables in the sandboxed environment. <add>// `x` and `y` are global variables in the sandboxed environment. <ide> // Initially, x has the value 2 because that is the value of sandbox.x. <ide> vm.runInContext(code, sandbox); <ide> <ide><path>doc/api/zlib.md <ide> request.on('response', (response) => { <ide> const output = fs.createWriteStream('example.com_index.html'); <ide> <ide> switch (response.headers['content-encoding']) { <del> // or, just use zlib.createUnzip() to handle both cases <add> // Or, just use zlib.createUnzip() to handle both cases <ide> case 'gzip': <ide> response.pipe(zlib.createGunzip()).pipe(output); <ide> break; <ide><path>doc/guides/writing-and-running-benchmarks.md <ide> const options = { <ide> flags: ['--zero-fill-buffers'] <ide> }; <ide> <del>// main and configs are required, options is optional. <add>// `main` and `configs` are required, `options` is optional. <ide> const bench = common.createBenchmark(main, configs, options); <ide> <ide> // Note that any code outside main will be run twice, <ide><path>lib/_http_client.js <ide> function parserOnIncomingClient(res, shouldKeepAlive) { <ide> req.res = res; <ide> res.req = req; <ide> <del> // add our listener first, so that we guarantee socket cleanup <add> // Add our listener first, so that we guarantee socket cleanup <ide> res.on('end', responseOnEnd); <ide> req.on('prefinish', requestOnPrefinish); <ide> var handled = req.emit('response', res); <ide><path>lib/_http_common.js <ide> function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, <ide> function parserOnBody(b, start, len) { <ide> const stream = this.incoming; <ide> <del> // if the stream has already been removed, then drop it. <add> // If the stream has already been removed, then drop it. <ide> if (stream === null) <ide> return; <ide> <del> // pretend this was the result of a stream._read call. <add> // Pretend this was the result of a stream._read call. <ide> if (len > 0 && !stream._dumped) { <ide> var slice = b.slice(start, start + len); <ide> var ret = stream.push(slice); <ide><path>lib/_http_incoming.js <ide> function IncomingMessage(socket) { <ide> this.client = socket; <ide> <ide> this._consuming = false; <del> // flag for when we decide that this message cannot possibly be <add> // Flag for when we decide that this message cannot possibly be <ide> // read by the user, so there's no point continuing to handle it. <ide> this._dumped = false; <ide> } <ide><path>lib/_http_server.js <ide> function resOnFinish(req, res, socket, state, server) { <ide> <ide> state.incoming.shift(); <ide> <del> // if the user never called req.read(), and didn't pipe() or <add> // If the user never called req.read(), and didn't pipe() or <ide> // .resume() or .on('data'), then we call req._dump() so that the <ide> // bytes will be pulled off the wire. <ide> if (!req._consuming && !req._readableState.resumeScheduled) <ide><path>lib/_stream_duplex.js <ide> function Duplex(options) { <ide> } <ide> <ide> Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide> Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { <ide> }); <ide> <ide> Object.defineProperty(Duplex.prototype, 'writableBuffer', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide> Object.defineProperty(Duplex.prototype, 'writableBuffer', { <ide> }); <ide> <ide> Object.defineProperty(Duplex.prototype, 'writableLength', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide> function onEndNT(self) { <ide> } <ide> <ide> Object.defineProperty(Duplex.prototype, 'destroyed', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide><path>lib/_stream_readable.js <ide> function ReadableState(options, stream, isDuplex) { <ide> if (typeof isDuplex !== 'boolean') <ide> isDuplex = stream instanceof Stream.Duplex; <ide> <del> // object stream flag. Used to make read(n) ignore n and to <add> // Object stream flag. Used to make read(n) ignore n and to <ide> // make all the buffer merging and length checks go away <ide> this.objectMode = !!options.objectMode; <ide> <ide> function ReadableState(options, stream, isDuplex) { <ide> // not happen before the first read call. <ide> this.sync = true; <ide> <del> // whenever we return null, then we set a flag to say <add> // Whenever we return null, then we set a flag to say <ide> // that we're awaiting a 'readable' event emission. <ide> this.needReadable = false; <ide> this.emittedReadable = false; <ide> function Readable(options) { <ide> } <ide> <ide> Object.defineProperty(Readable.prototype, 'destroyed', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide> Readable.prototype.setEncoding = function(enc) { <ide> if (!StringDecoder) <ide> StringDecoder = require('string_decoder').StringDecoder; <ide> this._readableState.decoder = new StringDecoder(enc); <del> // if setEncoding(null), decoder.encoding equals utf8 <add> // If setEncoding(null), decoder.encoding equals utf8 <ide> this._readableState.encoding = this._readableState.decoder.encoding; <ide> return this; <ide> }; <ide> Readable.prototype.read = function(n) { <ide> if (n !== 0) <ide> state.emittedReadable = false; <ide> <del> // if we're doing read(0) to trigger a readable event, but we <add> // If we're doing read(0) to trigger a readable event, but we <ide> // already have a bunch of data in the buffer, then just trigger <ide> // the 'readable' event and move on. <ide> if (n === 0 && <ide> Readable.prototype.read = function(n) { <ide> <ide> n = howMuchToRead(n, state); <ide> <del> // if we've ended, and we're now clear, then finish it up. <add> // If we've ended, and we're now clear, then finish it up. <ide> if (n === 0 && state.ended) { <ide> if (state.length === 0) <ide> endReadable(this); <ide> function onEofChunk(stream, state) { <ide> state.ended = true; <ide> <ide> if (state.sync) { <del> // if we are sync, wait until next tick to emit the data. <add> // If we are sync, wait until next tick to emit the data. <ide> // Otherwise we risk emitting data in the flow() <ide> // the readable code triggers during a read() call <ide> emitReadable(stream); <ide> } else { <del> // emit 'readable' now to make sure it gets picked up. <add> // Emit 'readable' now to make sure it gets picked up. <ide> state.needReadable = false; <ide> if (!state.emittedReadable) { <ide> state.emittedReadable = true; <ide> Readable.prototype.pipe = function(dest, pipeOpts) { <ide> dest.end(); <ide> } <ide> <del> // when the dest drains, it reduces the awaitDrain counter <add> // When the dest drains, it reduces the awaitDrain counter <ide> // on the source. This would be more elegant with a .once() <ide> // handler in flow(), but adding and removing repeatedly is <ide> // too slow. <ide> Readable.prototype.pipe = function(dest, pipeOpts) { <ide> <ide> cleanedUp = true; <ide> <del> // if the reader is waiting for a drain event from this <add> // If the reader is waiting for a drain event from this <ide> // specific writer, then it would cause it to never start <ide> // flowing again. <ide> // So, if this is awaiting a drain, then we just call it now. <ide> Readable.prototype.pipe = function(dest, pipeOpts) { <ide> } <ide> } <ide> <del> // if the dest has an error, then stop piping into it. <del> // however, don't suppress the throwing behavior for this. <add> // If the dest has an error, then stop piping into it. <add> // However, don't suppress the throwing behavior for this. <ide> function onerror(er) { <ide> debug('onerror', er); <ide> unpipe(); <ide> Readable.prototype.on = function(ev, fn) { <ide> const state = this._readableState; <ide> <ide> if (ev === 'data') { <del> // update readableListening so that resume() may be a no-op <add> // Update readableListening so that resume() may be a no-op <ide> // a few lines down. This is needed to support once('readable'). <ide> state.readableListening = this.listenerCount('readable') > 0; <ide> <ide> function flow(stream) { <ide> while (state.flowing && stream.read() !== null); <ide> } <ide> <del>// wrap an old-style stream as the async data source. <add>// Wrap an old-style stream as the async data source. <ide> // This is *not* part of the readable stream interface. <ide> // It is an ugly unfortunate mess of history. <ide> Readable.prototype.wrap = function(stream) { <ide> Readable.prototype.wrap = function(stream) { <ide> stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); <ide> } <ide> <del> // when we try to consume some more bytes, simply unpause the <add> // When we try to consume some more bytes, simply unpause the <ide> // underlying stream. <ide> this._read = (n) => { <ide> debug('wrapped _read', n); <ide> Readable.prototype[Symbol.asyncIterator] = function() { <ide> }; <ide> <ide> Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide> Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { <ide> }); <ide> <ide> Object.defineProperty(Readable.prototype, 'readableBuffer', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide> Object.defineProperty(Readable.prototype, 'readableBuffer', { <ide> }); <ide> <ide> Object.defineProperty(Readable.prototype, 'readableFlowing', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide> Object.defineProperty(Readable.prototype, 'readableFlowing', { <ide> Readable._fromList = fromList; <ide> <ide> Object.defineProperty(Readable.prototype, 'readableLength', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide><path>lib/_stream_transform.js <ide> function afterTransform(er, data) { <ide> ts.writechunk = null; <ide> ts.writecb = null; <ide> <del> if (data != null) // single equals check for both `null` and `undefined` <add> if (data != null) // Single equals check for both `null` and `undefined` <ide> this.push(data); <ide> <ide> cb(er); <ide> Transform.prototype._read = function(n) { <ide> ts.transforming = true; <ide> this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); <ide> } else { <del> // mark that we need a transform, so that any data that comes in <add> // Mark that we need a transform, so that any data that comes in <ide> // will get processed, now that we've asked for it. <ide> ts.needTransform = true; <ide> } <ide> function done(stream, er, data) { <ide> if (er) <ide> return stream.emit('error', er); <ide> <del> if (data != null) // single equals check for both `null` and `undefined` <add> if (data != null) // Single equals check for both `null` and `undefined` <ide> stream.push(data); <ide> <ide> // TODO(BridgeAR): Write a test for these two error cases <ide><path>lib/_stream_writable.js <ide> function WritableState(options, stream, isDuplex) { <ide> if (typeof isDuplex !== 'boolean') <ide> isDuplex = stream instanceof Stream.Duplex; <ide> <del> // object stream flag to indicate whether or not this stream <add> // Object stream flag to indicate whether or not this stream <ide> // contains buffers or objects. <ide> this.objectMode = !!options.objectMode; <ide> <ide> function WritableState(options, stream, isDuplex) { <ide> // Everything else in the universe uses 'utf8', though. <ide> this.defaultEncoding = options.defaultEncoding || 'utf8'; <ide> <del> // not an actual buffer we keep track of, but a measurement <add> // Not an actual buffer we keep track of, but a measurement <ide> // of how much we're waiting to get pushed to some underlying <ide> // socket or file. <ide> this.length = 0; <ide> <del> // a flag to see when we're in the middle of a write. <add> // A flag to see when we're in the middle of a write. <ide> this.writing = false; <ide> <del> // when true all writes will be buffered until .uncork() call <add> // When true all writes will be buffered until .uncork() call <ide> this.corked = 0; <ide> <ide> // A flag to be able to tell if the onwrite cb is called immediately, <ide> function WritableState(options, stream, isDuplex) { <ide> // The callback that the user supplies to write(chunk,encoding,cb) <ide> this.writecb = null; <ide> <del> // the amount that is being written when _write is called. <add> // The amount that is being written when _write is called. <ide> this.writelen = 0; <ide> <ide> this.bufferedRequest = null; <ide> Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { <ide> }; <ide> <ide> Object.defineProperty(Writable.prototype, 'writableBuffer', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide> function decodeChunk(state, chunk, encoding) { <ide> } <ide> <ide> Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide> Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { <ide> } <ide> }); <ide> <del>// if we're already writing something, then just put this <add>// If we're already writing something, then just put this <ide> // in the queue, and wait our turn. Otherwise, call _write <ide> // If we return false, then we need a drain event, so set that flag. <ide> function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { <ide> function onwriteError(stream, state, sync, er, cb) { <ide> --state.pendingcb; <ide> <ide> if (sync) { <del> // defer the callback if we are being called synchronously <add> // Defer the callback if we are being called synchronously <ide> // to avoid piling up things on the stack <ide> process.nextTick(cb, er); <ide> // this can emit finish, and it will always happen <ide> function onwriteDrain(stream, state) { <ide> } <ide> } <ide> <del>// if there's something in the buffer waiting, then process it <add>// If there's something in the buffer waiting, then process it <ide> function clearBuffer(stream, state) { <ide> state.bufferProcessing = true; <ide> var entry = state.bufferedRequest; <ide> Writable.prototype.end = function(chunk, encoding, cb) { <ide> }; <ide> <ide> Object.defineProperty(Writable.prototype, 'writableLength', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide> function onCorkedFinish(corkReq, state, err) { <ide> } <ide> <ide> Object.defineProperty(Writable.prototype, 'destroyed', { <del> // making it explicit this property is not enumerable <add> // Making it explicit this property is not enumerable <ide> // because otherwise some prototype manipulation in <ide> // userland will fail <ide> enumerable: false, <ide><path>lib/async_hooks.js <ide> class AsyncResource { <ide> <ide> this[async_id_symbol] = newAsyncId(); <ide> this[trigger_async_id_symbol] = triggerAsyncId; <del> // this prop name (destroyed) has to be synchronized with C++ <add> // This prop name (destroyed) has to be synchronized with C++ <ide> this[destroyedSymbol] = { destroyed: false }; <ide> <ide> emitInit( <ide><path>lib/dgram.js <ide> function doSend(ex, self, ip, list, address, port, callback) { <ide> !!callback); <ide> <ide> if (err && callback) { <del> // don't emit as error, dgram_legacy.js compatibility <add> // Don't emit as error, dgram_legacy.js compatibility <ide> const ex = exceptionWithHostPort(err, 'send', address, port); <ide> process.nextTick(callback, ex); <ide> } <ide><path>lib/domain.js <ide> const pairing = new Map(); <ide> const asyncHook = createHook({ <ide> init(asyncId, type, triggerAsyncId, resource) { <ide> if (process.domain !== null && process.domain !== undefined) { <del> // if this operation is created while in a domain, let's mark it <add> // If this operation is created while in a domain, let's mark it <ide> pairing.set(asyncId, process.domain); <ide> resource.domain = process.domain; <ide> } <ide> exports.create = exports.createDomain = function createDomain() { <ide> return new Domain(); <ide> }; <ide> <del>// the active domain is always the one that we're currently in. <add>// The active domain is always the one that we're currently in. <ide> exports.active = null; <ide> Domain.prototype.members = undefined; <ide> <ide> Domain.prototype._errorHandler = function(er) { <ide> } <ide> } <ide> } else { <del> // wrap this in a try/catch so we don't get infinite throwing <add> // Wrap this in a try/catch so we don't get infinite throwing <ide> try { <ide> // One of three things will happen here. <ide> // <ide> Domain.prototype._errorHandler = function(er) { <ide> <ide> <ide> Domain.prototype.enter = function() { <del> // note that this might be a no-op, but we still need <add> // Note that this might be a no-op, but we still need <ide> // to push it onto the stack so that we can pop it later. <ide> exports.active = process.domain = this; <ide> stack.push(this); <ide> Domain.prototype.enter = function() { <ide> <ide> <ide> Domain.prototype.exit = function() { <del> // don't do anything if this domain is not on the stack. <add> // Don't do anything if this domain is not on the stack. <ide> var index = stack.lastIndexOf(this); <ide> if (index === -1) return; <ide> <ide><path>lib/events.js <ide> EventEmitter.prototype.removeAllListeners = <ide> return this; <ide> } <ide> <del> // emit removeListener for all listeners on all events <add> // Emit removeListener for all listeners on all events <ide> if (arguments.length === 0) { <ide> var keys = Object.keys(events); <ide> var key; <ide><path>lib/fs.js <ide> function appendFile(path, data, options, callback) { <ide> // Don't make changes directly on options object <ide> options = copyObject(options); <ide> <del> // force append behavior when using a supplied file descriptor <add> // Force append behavior when using a supplied file descriptor <ide> if (!options.flag || isFd(path)) <ide> options.flag = 'a'; <ide> <ide> function appendFileSync(path, data, options) { <ide> // Don't make changes directly on options object <ide> options = copyObject(options); <ide> <del> // force append behavior when using a supplied file descriptor <add> // Force append behavior when using a supplied file descriptor <ide> if (!options.flag || isFd(path)) <ide> options.flag = 'a'; <ide> <ide> function realpathSync(p, options) { <ide> <ide> // current character position in p <ide> let pos; <del> // the partial path so far, including a trailing slash if any <add> // The partial path so far, including a trailing slash if any <ide> let current; <ide> // The partial path without a trailing slash (except when pointing at a root) <ide> let base; <del> // the partial path scanned in the previous round, with slash <add> // The partial path scanned in the previous round, with slash <ide> let previous; <ide> <ide> // Skip over roots <ide> function realpath(p, options, callback) { <ide> <ide> // current character position in p <ide> let pos; <del> // the partial path so far, including a trailing slash if any <add> // The partial path so far, including a trailing slash if any <ide> let current; <ide> // The partial path without a trailing slash (except when pointing at a root) <ide> let base; <del> // the partial path scanned in the previous round, with slash <add> // The partial path scanned in the previous round, with slash <ide> let previous; <ide> <ide> current = base = splitRoot(p); <ide><path>lib/internal/child_process.js <ide> const handleConversion = { <ide> var firstTime = !this.channel.sockets.send[message.key]; <ide> var socketList = getSocketList('send', this, message.key); <ide> <del> // the server should no longer expose a .connection property <add> // The server should no longer expose a .connection property <ide> // and when asked to close it should query the socket status from <ide> // the workers <ide> if (firstTime) socket.server._setupWorker(socketList); <ide> function ChildProcess() { <ide> this.emit('exit', this.exitCode, this.signalCode); <ide> } <ide> <del> // if any of the stdio streams have not been touched, <add> // If any of the stdio streams have not been touched, <ide> // then pull all the data through so that it can get the <ide> // eof and emit a 'close' event. <ide> // Do it on nextTick so that the user has one last chance <ide><path>lib/internal/console/constructor.js <ide> function Console(options /* or: stdout, stderr, ignoreErrors = true */) { <ide> optionsMap.set(this, inspectOptions); <ide> } <ide> <del> // bind the prototype functions to this Console instance <add> // Bind the prototype functions to this Console instance <ide> var keys = Object.keys(Console.prototype); <ide> for (var v = 0; v < keys.length; v++) { <ide> var k = keys[v]; <ide><path>lib/internal/fs/streams.js <ide> function ReadStream(path, options) { <ide> if (!(this instanceof ReadStream)) <ide> return new ReadStream(path, options); <ide> <del> // a little bit bigger buffer and water marks by default <add> // A little bit bigger buffer and water marks by default <ide> options = copyObject(getOptions(options, {})); <ide> if (options.highWaterMark === undefined) <ide> options.highWaterMark = 64 * 1024; <ide> <del> // for backwards compat do not emit close on destroy. <add> // For backwards compat do not emit close on destroy. <ide> options.emitClose = false; <ide> <ide> Readable.call(this, options); <ide> <del> // path will be ignored when fd is specified, so it can be falsy <add> // Path will be ignored when fd is specified, so it can be falsy <ide> this.path = toPathIfFileURL(path); <ide> this.fd = options.fd === undefined ? null : options.fd; <ide> this.flags = options.flags === undefined ? 'r' : options.flags; <ide> ReadStream.prototype._read = function(n) { <ide> } <ide> }); <ide> <del> // move the pool positions, and internal position for reading. <add> // Move the pool positions, and internal position for reading. <ide> if (this.pos !== undefined) <ide> this.pos += toRead; <ide> pool.used += toRead; <ide> function WriteStream(path, options) { <ide> <ide> options = copyObject(getOptions(options, {})); <ide> <del> // for backwards compat do not emit close on destroy. <add> // For backwards compat do not emit close on destroy. <ide> options.emitClose = false; <ide> <ide> Writable.call(this, options); <ide> <del> // path will be ignored when fd is specified, so it can be falsy <add> // Path will be ignored when fd is specified, so it can be falsy <ide> this.path = toPathIfFileURL(path); <ide> this.fd = options.fd === undefined ? null : options.fd; <ide> this.flags = options.flags === undefined ? 'w' : options.flags; <ide><path>lib/internal/http2/compat.js <ide> class Http2ServerResponse extends Stream { <ide> } <ide> <ide> get socket() { <del> // this is compatible with http1 which removes socket reference <add> // This is compatible with http1 which removes socket reference <ide> // only from ServerResponse but not IncomingMessage <ide> if (this[kState].closed) <ide> return; <ide><path>lib/internal/http2/core.js <ide> function requestOnConnect(headers, options) { <ide> if (options.waitForTrailers) <ide> streamOptions |= STREAM_OPTION_GET_TRAILERS; <ide> <del> // ret will be either the reserved stream ID (if positive) <add> // `ret` will be either the reserved stream ID (if positive) <ide> // or an error code (if negative) <ide> const ret = session[kHandle].request(headers, <ide> streamOptions, <ide> function startFilePipe(self, fd, offset, length) { <ide> pipe.onunpipe = onFileUnpipe; <ide> pipe.start(); <ide> <del> // exact length of the file doesn't matter here, since the <add> // Exact length of the file doesn't matter here, since the <ide> // stream is closing anyway - just use 1 to signify that <ide> // a write does exist <ide> trackWriteState(self, 1); <ide><path>lib/internal/modules/cjs/loader.js <ide> function tryExtensions(p, exts, isMain) { <ide> return false; <ide> } <ide> <del>// find the longest (possibly multi-dot) extension registered in <add>// Find the longest (possibly multi-dot) extension registered in <ide> // Module._extensions <ide> function findLongestRegisteredExtension(filename) { <ide> const name = path.basename(filename); <ide> Module._resolveFilename = function(request, parent, isMain, options) { <ide> paths = Module._resolveLookupPaths(request, parent, true); <ide> } <ide> <del> // look up the filename first, since that's the cache key. <add> // Look up the filename first, since that's the cache key. <ide> var filename = Module._findPath(request, paths, isMain); <ide> if (!filename) { <ide> // eslint-disable-next-line no-restricted-syntax <ide> Module.prototype._compile = function(content, filename) { <ide> var inspectorWrapper = null; <ide> if (process._breakFirstLine && process._eval == null) { <ide> if (!resolvedArgv) { <del> // we enter the repl if we're not given a filename argument. <add> // We enter the repl if we're not given a filename argument. <ide> if (process.argv[1]) { <ide> resolvedArgv = Module._resolveFilename(process.argv[1], null, false); <ide> } else { <ide><path>lib/internal/modules/esm/loader.js <ide> const debug = require('util').debuglog('esm'); <ide> * the main module and everything in its dependency graph. */ <ide> class Loader { <ide> constructor() { <del> // methods which translate input code or other information <add> // Methods which translate input code or other information <ide> // into es modules <ide> this.translators = translators; <ide> <del> // registry of loaded modules, akin to `require.cache` <add> // Registry of loaded modules, akin to `require.cache` <ide> this.moduleMap = new ModuleMap(); <ide> <ide> // The resolver has the signature <ide><path>lib/internal/process/next_tick.js <ide> function setupNextTick(_setupNextTick, _setupPromises) { <ide> <ide> class TickObject { <ide> constructor(callback, args, triggerAsyncId) { <del> // this must be set to null first to avoid function tracking <add> // This must be set to null first to avoid function tracking <ide> // on the hidden class, revisit in V8 versions after 6.2 <ide> this.callback = null; <ide> this.callback = callback; <ide><path>lib/internal/process/stdio.js <ide> function getMainThreadStdio() { <ide> // For supporting legacy API we put the FD here. <ide> stdin.fd = fd; <ide> <del> // stdin starts out life in a paused state, but node doesn't <del> // know yet. Explicitly to readStop() it to put it in the <add> // `stdin` starts out life in a paused state, but node doesn't <add> // know yet. Explicitly to readStop() it to put it in the <ide> // not-reading state. <ide> if (stdin._handle && stdin._handle.readStop) { <ide> stdin._handle.reading = false; <ide><path>lib/internal/streams/destroy.js <ide> 'use strict'; <ide> <del>// undocumented cb() API, needed for core, not for public API <add>// Undocumented cb() API, needed for core, not for public API <ide> function destroy(err, cb) { <ide> const readableDestroyed = this._readableState && <ide> this._readableState.destroyed; <ide><path>lib/internal/timers.js <ide> function Timeout(callback, after, args, isRepeat) { <ide> this._idlePrev = this; <ide> this._idleNext = this; <ide> this._idleStart = null; <del> // this must be set to null first to avoid function tracking <add> // This must be set to null first to avoid function tracking <ide> // on the hidden class, revisit in V8 versions after 6.2 <ide> this._onTimeout = null; <ide> this._onTimeout = callback; <ide><path>lib/net.js <ide> function Socket(options) { <ide> // handle strings directly <ide> this._writableState.decodeStrings = false; <ide> <del> // if we have a handle, then start the flow of data into the <add> // If we have a handle, then start the flow of data into the <ide> // buffer. if not, then this will happen when we connect <ide> if (this._handle && options.readable !== false) { <ide> if (options.pauseOnCreate) { <ide> Socket.prototype._unrefTimer = function _unrefTimer() { <ide> }; <ide> <ide> <del>// the user has called .end(), and all the bytes have been <add>// The user has called .end(), and all the bytes have been <ide> // sent out to the other side. <ide> Socket.prototype._final = function(cb) { <ide> // If still connecting - defer handling `_final` until 'connect' will happen <ide> Socket.prototype.setNoDelay = function(enable) { <ide> return this; <ide> } <ide> <del> // backwards compatibility: assume true when `enable` is omitted <add> // Backwards compatibility: assume true when `enable` is omitted <ide> if (this._handle.setNoDelay) <ide> this._handle.setNoDelay(enable === undefined ? true : !!enable); <ide> <ide> protoGetter('bytesWritten', function bytesWritten() { <ide> }); <ide> <ide> if (Array.isArray(data)) { <del> // was a writev, iterate over chunks to get total length <add> // Was a writev, iterate over chunks to get total length <ide> for (var i = 0; i < data.length; i++) { <ide> const chunk = data[i]; <ide> <ide> function toNumber(x) { return (x = Number(x)) >= 0 ? x : false; } <ide> // Returns handle if it can be created, or error code if it can't <ide> function createServerHandle(address, port, addressType, fd, flags) { <ide> var err = 0; <del> // assign handle in listen, and clean up if bind or listen fails <add> // Assign handle in listen, and clean up if bind or listen fails <ide> var handle; <ide> <ide> var isTCP = false; <ide><path>lib/readline.js <ide> function Interface(input, output, completer, terminal) { <ide> throw new ERR_INVALID_OPT_VALUE.RangeError('historySize', historySize); <ide> } <ide> <del> // backwards compat; check the isTTY prop of the output stream <add> // Backwards compat; check the isTTY prop of the output stream <ide> // when `terminal` was not specified <ide> if (terminal === undefined && !(output === null || output === undefined)) { <ide> terminal = !!output.isTTY; <ide> Interface.prototype._normalWrite = function(b) { <ide> if (newPartContainsEnding) { <ide> this._sawReturnAt = string.endsWith('\r') ? Date.now() : 0; <ide> <del> // got one or more newlines; process into "line" events <add> // Got one or more newlines; process into "line" events <ide> var lines = string.split(lineEnding); <ide> // Either '' or (conceivably) the unfinished portion of the next line <ide> string = lines.pop(); <ide> this._line_buffer = string; <ide> for (var n = 0; n < lines.length; n++) <ide> this._onLine(lines[n]); <ide> } else if (string) { <del> // no newlines this time, save what we have for next time <add> // No newlines this time, save what we have for next time <ide> this._line_buffer = string; <ide> } <ide> }; <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> self.pause(); <ide> self.emit('SIGCONT'); <ide> } <del> // explicitly re-enable "raw mode" and move the cursor to <add> // Explicitly re-enable "raw mode" and move the cursor to <ide> // the correct position. <ide> // See https://github.com/joyent/node/issues/3295. <ide> self._setRawMode(true); <ide> function emitKeypressEvents(stream, iface) { <ide> ); <ide> } <ide> } catch (err) { <del> // if the generator throws (it could happen in the `keypress` <add> // If the generator throws (it could happen in the `keypress` <ide> // event), we need to restart it. <ide> stream[ESCAPE_DECODER] = emitKeys(stream); <ide> stream[ESCAPE_DECODER].next(); <ide><path>lib/repl.js <ide> exports.REPLServer = REPLServer; <ide> exports.REPL_MODE_SLOPPY = Symbol('repl-sloppy'); <ide> exports.REPL_MODE_STRICT = Symbol('repl-strict'); <ide> <del>// prompt is a string to print on each line for the prompt, <add>// Prompt is a string to print on each line for the prompt, <ide> // source is a stream to use for I/O, defaulting to stdin/stdout. <ide> exports.start = function(prompt, <ide> source, <ide> function _memory(cmd) { <ide> }()); <ide> } <ide> <del> // it is possible to determine a syntax error at this point. <add> // It is possible to determine a syntax error at this point. <ide> // if the REPL still has a bufferedCommand and <ide> // self.lines.level.length === 0 <ide> // TODO? keep a log of level so that any syntax breaking lines can <ide><path>lib/timers.js <ide> const Immediate = class Immediate { <ide> constructor(callback, args) { <ide> this._idleNext = null; <ide> this._idlePrev = null; <del> // this must be set to null first to avoid function tracking <add> // This must be set to null first to avoid function tracking <ide> // on the hidden class, revisit in V8 versions after 6.2 <ide> this._onImmediate = null; <ide> this._onImmediate = callback; <ide><path>lib/url.js <ide> const hostPattern = /^\/\/[^@/]+@[^@/]+/; <ide> const simplePathPattern = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/; <ide> <ide> const hostnameMaxLen = 255; <del>// protocols that can allow "unsafe" and "unwise" chars. <add>// Protocols that can allow "unsafe" and "unwise" chars. <ide> const unsafeProtocol = new SafeSet([ <ide> 'javascript', <ide> 'javascript:' <ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { <ide> this.query = querystring.parse(this.query); <ide> } <ide> } else if (parseQueryString) { <del> // no query string, but parseQueryString still requested <add> // No query string, but parseQueryString still requested <ide> this.search = null; <ide> this.query = Object.create(null); <ide> } <ide> Url.prototype.resolveObject = function resolveObject(relative) { <ide> return result; <ide> } <ide> <del> // if a url ENDs in . or .., then it must get a trailing slash. <add> // If a url ENDs in . or .., then it must get a trailing slash. <ide> // however, if it ends in anything else non-slashy, <ide> // then it must NOT get a trailing slash. <ide> var last = srcPath.slice(-1)[0]; <ide> var hasTrailingSlash = ( <ide> (result.host || relative.host || srcPath.length > 1) && <ide> (last === '.' || last === '..') || last === ''); <ide> <del> // strip single dots, resolve double dots to parent dir <add> // Strip single dots, resolve double dots to parent dir <ide> // if the path tries to go above the root, `up` ends up > 0 <ide> var up = 0; <ide> for (var i = srcPath.length - 1; i >= 0; i--) { <ide><path>test/async-hooks/test-callback-error.js <ide> assert.ok(!arg); <ide> assert.strictEqual(signal, null); <ide> } else { <ide> assert.strictEqual(code, null); <del> // most posix systems will show 'SIGABRT', but alpine34 does not <add> // Most posix systems will show 'SIGABRT', but alpine34 does not <ide> if (signal !== 'SIGABRT') { <ide> console.log(`parent received signal ${signal}\nchild's stderr:`); <ide> console.log(stderr); <ide><path>test/async-hooks/test-getaddrinforeqwrap.js <ide> const hooks = initHooks(); <ide> hooks.enable(); <ide> dns.lookup('www.google.com', 4, common.mustCall(onlookup)); <ide> function onlookup() { <del> // we don't care about the error here in order to allow <add> // We don't care about the error here in order to allow <ide> // tests to run offline (lookup will fail in that case and the err be set); <ide> <ide> const as = hooks.activitiesOfTypes('GETADDRINFOREQWRAP'); <ide><path>test/async-hooks/test-getnameinforeqwrap.js <ide> const hooks = initHooks(); <ide> hooks.enable(); <ide> dns.lookupService('127.0.0.1', 80, common.mustCall(onlookupService)); <ide> function onlookupService() { <del> // we don't care about the error here in order to allow <add> // We don't care about the error here in order to allow <ide> // tests to run offline (lookup will fail in that case and the err be set) <ide> <ide> const as = hooks.activitiesOfTypes('GETNAMEINFOREQWRAP'); <ide><path>test/async-hooks/test-querywrap.js <ide> const dns = require('dns'); <ide> const hooks = initHooks(); <ide> <ide> hooks.enable(); <del>// uses cares for queryA which in turn uses QUERYWRAP <add>// Uses cares for queryA which in turn uses QUERYWRAP <ide> dns.resolve('localhost', common.mustCall(onresolved)); <ide> <ide> function onresolved() { <ide><path>test/async-hooks/test-udpsendwrap.js <ide> function onlistening() { <ide> Buffer.alloc(2), 0, 2, sock.address().port, <ide> undefined, common.mustCall(onsent)); <ide> <del> // init not called synchronously because dns lookup always wraps <add> // Init not called synchronously because dns lookup always wraps <ide> // callback in a next tick even if no lookup is needed <ide> // TODO (trevnorris) submit patch to fix creation of tick objects and instead <ide> // create the send wrap synchronously. <ide><path>test/async-hooks/verify-graph.js <ide> function findInGraph(graph, type, n) { <ide> } <ide> <ide> function pruneTickObjects(activities) { <del> // remove one TickObject on each pass until none is left anymore <add> // Remove one TickObject on each pass until none is left anymore <ide> // not super efficient, but simplest especially to handle <ide> // multiple TickObjects in a row <ide> let foundTickObject = true; <ide> function pruneTickObjects(activities) { <ide> if (tickObjectIdx >= 0) { <ide> foundTickObject = true; <ide> <del> // point all triggerAsyncIds that point to the tickObject <add> // Point all triggerAsyncIds that point to the tickObject <ide> // to its triggerAsyncId and finally remove it from the activities <ide> const tickObject = activities[tickObjectIdx]; <ide> const newTriggerId = tickObject.triggerAsyncId; <ide> function pruneTickObjects(activities) { <ide> module.exports = function verifyGraph(hooks, graph) { <ide> pruneTickObjects(hooks); <ide> <del> // map actual ids to standin ids defined in the graph <add> // Map actual ids to standin ids defined in the graph <ide> const idtouid = {}; <ide> const uidtoid = {}; <ide> const typeSeen = {}; <ide><path>test/common/index.js <ide> if (process.env.NODE_TEST_WITH_ASYNC_HOOKS) { <ide> const async_wrap = internalBinding('async_wrap'); <ide> <ide> process.on('exit', () => { <del> // iterate through handles to make sure nothing crashes <add> // Iterate through handles to make sure nothing crashes <ide> for (const k in initHandles) <ide> util.inspect(initHandles[k]); <ide> }); <ide> module.exports = { <ide> // use external command <ide> opensslCli = 'openssl'; <ide> } else { <del> // use command built from sources included in Node.js repository <add> // Use command built from sources included in Node.js repository <ide> opensslCli = path.join(path.dirname(process.execPath), 'openssl-cli'); <ide> } <ide> <ide><path>test/js-native-api/test_constructor/test.js <ide> assert.strictEqual(test_object.readonlyAccessor2, 2); <ide> assert.throws(() => { test_object.readonlyAccessor2 = 3; }, <ide> /^TypeError: Cannot assign to read only property 'readonlyAccessor2' of object '#<MyObject>'$/); <ide> <del>// validate that static properties are on the class as opposed <add>// Validate that static properties are on the class as opposed <ide> // to the instance <ide> assert.strictEqual(TestConstructor.staticReadonlyAccessor1, 10); <ide> assert.strictEqual(test_object.staticReadonlyAccessor1, undefined); <ide><path>test/js-native-api/test_general/testInstanceOf.js <ide> const fs = require('fs'); <ide> const common = require('../../common'); <ide> const assert = require('assert'); <ide> <del>// addon is referenced through the eval expression in testFile <add>// Addon is referenced through the eval expression in testFile <ide> // eslint-disable-next-line no-unused-vars <ide> const addon = require(`./build/${common.buildType}/test_general`); <ide> const path = require('path'); <ide><path>test/js-native-api/test_general/testNapiRun.js <ide> const common = require('../../common'); <ide> const assert = require('assert'); <ide> <del>// addon is referenced through the eval expression in testFile <add>// `addon` is referenced through the eval expression in testFile <ide> // eslint-disable-next-line no-unused-vars <ide> const addon = require(`./build/${common.buildType}/test_general`); <ide> <ide><path>test/parallel/test-async-wrap-tlssocket-asyncreset.js <ide> server.listen( <ide> res.on('error', (err) => assert.fail(err)); <ide> res.socket.on('error', (err) => assert.fail(err)); <ide> res.resume(); <del> // drain the socket and wait for it to be free to reuse <add> // Drain the socket and wait for it to be free to reuse <ide> res.socket.once('free', () => { <ide> // This is the pain point. Internally the Agent will call <ide> // `socket._handle.asyncReset()` and if the _handle does not implement <ide><path>test/parallel/test-buffer-alloc.js <ide> const outOfRangeError = { <ide> type: RangeError <ide> }; <ide> <del>// try to write a 0-length string beyond the end of b <add>// Try to write a 0-length string beyond the end of b <ide> common.expectsError(() => b.write('', 2048), outOfBoundsError); <ide> <ide> // throw when writing to negative offset <ide> common.expectsError(() => b.write('a', 2048), outOfBoundsError); <ide> // throw when writing to negative offset <ide> common.expectsError(() => b.write('a', -1), outOfBoundsError); <ide> <del>// try to copy 0 bytes worth of data into an empty buffer <add>// Try to copy 0 bytes worth of data into an empty buffer <ide> b.copy(Buffer.alloc(0), 0, 0, 0); <ide> <del>// try to copy 0 bytes past the end of the target buffer <add>// Try to copy 0 bytes past the end of the target buffer <ide> b.copy(Buffer.alloc(0), 1, 1, 1); <ide> b.copy(Buffer.alloc(1), 1, 1, 1); <ide> <del>// try to copy 0 bytes from past the end of the source buffer <add>// Try to copy 0 bytes from past the end of the source buffer <ide> b.copy(Buffer.alloc(1), 0, 2048, 2048); <ide> <ide> // Testing for smart defaults and ability to pass string values as offset <ide> Buffer.alloc(1).write('', 1, 0); <ide> } <ide> <ide> { <del> // make sure only top level parent propagates from allocPool <add> // Make sure only top level parent propagates from allocPool <ide> const b = Buffer.allocUnsafe(5); <ide> const c = b.slice(0, 4); <ide> const d = c.slice(0, 2); <ide> assert.strictEqual((Buffer.from('Man')).toString('base64'), 'TWFu'); <ide> assert.strictEqual(quote.length, bytesWritten); <ide> assert.strictEqual(quote, b.toString('ascii', 0, quote.length)); <ide> <del> // check that the base64 decoder on the constructor works <add> // Check that the base64 decoder on the constructor works <ide> // even in the presence of whitespace. <ide> b = Buffer.from(expectedWhite, 'base64'); <ide> assert.strictEqual(quote.length, b.length); <ide> assert.strictEqual(quote, b.toString('ascii', 0, quote.length)); <ide> <del> // check that the base64 decoder ignores illegal chars <add> // Check that the base64 decoder ignores illegal chars <ide> const expectedIllegal = expected.slice(0, 60) + ' \x80' + <ide> expected.slice(60, 120) + ' \xff' + <ide> expected.slice(120, 180) + ' \x00' + <ide> assert.strictEqual(x.inspect(), '<Buffer 81 a3 66 6f 6f a3 62 61 72>'); <ide> } <ide> <ide> { <del> // test unmatched surrogates not producing invalid utf8 output <add> // Test unmatched surrogates not producing invalid utf8 output <ide> // ef bf bd = utf-8 representation of unicode replacement character <ide> // see https://codereview.chromium.org/121173009/ <ide> const buf = Buffer.from('ab\ud800cd', 'utf8'); <ide><path>test/parallel/test-buffer-bytelength.js <ide> assert.strictEqual(Buffer.byteLength('𠝹𠱓𠱸', 'UTF8'), 12); <ide> assert.strictEqual(Buffer.byteLength('hey there'), 9); <ide> assert.strictEqual(Buffer.byteLength('𠱸挶νξ#xx :)'), 17); <ide> assert.strictEqual(Buffer.byteLength('hello world', ''), 11); <del>// it should also be assumed with unrecognized encoding <add>// It should also be assumed with unrecognized encoding <ide> assert.strictEqual(Buffer.byteLength('hello world', 'abc'), 11); <ide> assert.strictEqual(Buffer.byteLength('ßœ∑≈', 'unkn0wn enc0ding'), 10); <ide> <ide><path>test/parallel/test-buffer-copy.js <ide> let cntr = 0; <ide> } <ide> <ide> { <del> // copy longer buffer b to shorter c without targetStart <add> // Copy longer buffer b to shorter c without targetStart <ide> b.fill(++cntr); <ide> c.fill(++cntr); <ide> const copied = b.copy(c); <ide> let cntr = 0; <ide> } <ide> <ide> { <del> // try to copy 513 bytes, and check we don't overrun c <add> // Try to copy 513 bytes, and check we don't overrun c <ide> b.fill(++cntr); <ide> c.fill(++cntr); <ide> const copied = b.copy(c, 0, 0, 513); <ide> let cntr = 0; <ide> } <ide> } <ide> <del>// copy string longer than buffer length (failure will segfault) <add>// Copy string longer than buffer length (failure will segfault) <ide> const bb = Buffer.allocUnsafe(10); <ide> bb.fill('hello crazy world'); <ide> <ide> common.expectsError( <ide> common.expectsError( <ide> () => b.copy(c, 0, -1), errorProperty); <ide> <del>// when sourceStart is greater than sourceEnd, zero copied <add>// When sourceStart is greater than sourceEnd, zero copied <ide> assert.strictEqual(b.copy(c, 0, 100, 10), 0); <ide> <ide> // when targetStart > targetLength, zero copied <ide><path>test/parallel/test-buffer-includes.js <ide> for (let i = 66; i < 76; i++) { // from 'B' to 'K' <ide> <ide> const longBufferString = Buffer.from(longString); <ide> <del>// pattern of 15 chars, repeated every 16 chars in long <add>// Pattern of 15 chars, repeated every 16 chars in long <ide> let pattern = 'ABACABADABACABA'; <ide> for (let i = 0; i < longBufferString.length - pattern.length; i += 7) { <ide> const includes = longBufferString.includes(pattern, i); <ide><path>test/parallel/test-buffer-indexof.js <ide> for (let i = 66; i < 76; i++) { // from 'B' to 'K' <ide> <ide> const longBufferString = Buffer.from(longString); <ide> <del>// pattern of 15 chars, repeated every 16 chars in long <add>// Pattern of 15 chars, repeated every 16 chars in long <ide> let pattern = 'ABACABADABACABA'; <ide> for (let i = 0; i < longBufferString.length - pattern.length; i += 7) { <ide> const index = longBufferString.indexOf(pattern, i); <ide><path>test/parallel/test-buffer-read.js <ide> read(buf, 'readInt16LE', [1], 0x48fd); <ide> read(buf, 'readInt32BE', [1], -45552945); <ide> read(buf, 'readInt32LE', [1], -806729475); <ide> <del>// testing basic functionality of readIntBE() and readIntLE() <add>// Testing basic functionality of readIntBE() and readIntLE() <ide> read(buf, 'readIntBE', [1, 1], -3); <ide> read(buf, 'readIntLE', [2, 1], 0x48); <ide> <ide> read(buf, 'readUInt16LE', [2], 0xea48); <ide> read(buf, 'readUInt32BE', [1], 0xfd48eacf); <ide> read(buf, 'readUInt32LE', [1], 0xcfea48fd); <ide> <del>// testing basic functionality of readUIntBE() and readUIntLE() <add>// Testing basic functionality of readUIntBE() and readUIntLE() <ide> read(buf, 'readUIntBE', [2, 2], 0x48ea); <ide> read(buf, 'readUIntLE', [2, 2], 0xea48); <ide> <ide><path>test/parallel/test-buffer-slow.js <ide> try { <ide> assert.strictEqual(SlowBuffer('6').length, 6); <ide> assert.strictEqual(SlowBuffer(true).length, 1); <ide> <del>// should create zero-length buffer if parameter is not a number <add>// Should create zero-length buffer if parameter is not a number <ide> assert.strictEqual(SlowBuffer().length, 0); <ide> assert.strictEqual(SlowBuffer(NaN).length, 0); <ide> assert.strictEqual(SlowBuffer({}).length, 0); <ide><path>test/parallel/test-buffer-tostring-range.js <ide> const assert = require('assert'); <ide> <ide> const rangeBuffer = Buffer.from('abc'); <ide> <del>// if start >= buffer's length, empty string will be returned <add>// If start >= buffer's length, empty string will be returned <ide> assert.strictEqual(rangeBuffer.toString('ascii', 3), ''); <ide> assert.strictEqual(rangeBuffer.toString('ascii', +Infinity), ''); <ide> assert.strictEqual(rangeBuffer.toString('ascii', 3.14, 3), ''); <ide> assert.strictEqual(rangeBuffer.toString('ascii', '-1', 3), 'abc'); <ide> assert.strictEqual(rangeBuffer.toString('ascii', '-1.99', 3), 'abc'); <ide> assert.strictEqual(rangeBuffer.toString('ascii', '-Infinity', 3), 'abc'); <ide> <del>// if start is an invalid integer, start will be taken as zero <add>// If start is an invalid integer, start will be taken as zero <ide> assert.strictEqual(rangeBuffer.toString('ascii', 'node.js', 3), 'abc'); <ide> assert.strictEqual(rangeBuffer.toString('ascii', {}, 3), 'abc'); <ide> assert.strictEqual(rangeBuffer.toString('ascii', [], 3), 'abc'); <ide><path>test/parallel/test-child-process-disconnect.js <ide> if (process.argv[2] === 'child') { <ide> socket.end((process.connected).toString()); <ide> }); <ide> <del> // when the socket is closed, we will close the server <add> // When the socket is closed, we will close the server <ide> // allowing the process to self terminate <ide> socket.on('end', function() { <ide> server.close(); <ide> if (process.argv[2] === 'child') { <ide> parentFlag = child.connected; <ide> })); <ide> <del> // the process should also self terminate without using signals <add> // The process should also self terminate without using signals <ide> child.on('exit', common.mustCall()); <ide> <ide> // when child is listening <ide> child.on('message', function(obj) { <ide> if (obj && obj.msg === 'ready') { <ide> <del> // connect to child using TCP to know if disconnect was emitted <add> // Connect to child using TCP to know if disconnect was emitted <ide> const socket = net.connect(obj.port); <ide> <ide> socket.on('data', function(data) { <ide><path>test/parallel/test-child-process-validate-stdio.js <ide> const _validateStdio = require('internal/child_process')._validateStdio; <ide> const expectedError = <ide> common.expectsError({ code: 'ERR_INVALID_OPT_VALUE', type: TypeError }, 2); <ide> <del>// should throw if string and not ignore, pipe, or inherit <add>// Should throw if string and not ignore, pipe, or inherit <ide> assert.throws(() => _validateStdio('foo'), expectedError); <ide> <ide> // should throw if not a string or array <ide><path>test/parallel/test-cli-syntax-piped-good.js <ide> const syntaxArgs = [ <ide> ['--check'] <ide> ]; <ide> <del>// should not execute code piped from stdin with --check <del>// loop each possible option, `-c` or `--check` <add>// Should not execute code piped from stdin with --check. <add>// Loop each possible option, `-c` or `--check`. <ide> syntaxArgs.forEach(function(args) { <ide> const stdin = 'throw new Error("should not get run");'; <ide> const c = spawnSync(node, args, { encoding: 'utf8', input: stdin }); <ide><path>test/parallel/test-cluster-disconnect.js <ide> if (cluster.isWorker) { <ide> } <ide> }; <ide> <del> // start two workers and execute callback when both is listening <add> // Start two workers and execute callback when both is listening <ide> const startCluster = (cb) => { <ide> const workers = 8; <ide> let online = 0; <ide><path>test/parallel/test-cluster-eaccess.js <ide> if (cluster.isMaster && process.argv.length !== 3) { <ide> worker.on('online', common.mustCall()); <ide> <ide> worker.on('message', common.mustCall(function(err) { <del> // disconnect first, so that we will not leave zombies <add> // Disconnect first, so that we will not leave zombies <ide> worker.disconnect(); <ide> assert.strictEqual(err.code, 'EADDRINUSE'); <ide> })); <ide> if (cluster.isMaster && process.argv.length !== 3) { <ide> const PIPE_NAME = process.env.PIPE_NAME; <ide> const cp = fork(__filename, [PIPE_NAME], { stdio: 'inherit' }); <ide> <del> // message from the child indicates it's ready and listening <add> // Message from the child indicates it's ready and listening <ide> cp.on('message', common.mustCall(function() { <ide> const server = net.createServer().listen(PIPE_NAME, function() { <ide> // message child process so that it can exit <ide><path>test/parallel/test-cluster-worker-no-exit.js <ide> if (cluster.isMaster) { <ide> }); <ide> } else { <ide> process.on('message', function(msg) { <del> // we shouldn't exit, not while a network connection exists <add> // We shouldn't exit, not while a network connection exists <ide> net.connect(msg.port); <ide> }); <ide> } <ide><path>test/parallel/test-cluster-worker-wait-server-close.js <ide> if (cluster.isWorker) { <ide> socket.on('connect', function() { <ide> socket.on('data', function() { <ide> console.log('got data from client'); <del> // socket definitely connected to worker if we got data <add> // Socket definitely connected to worker if we got data <ide> worker.disconnect(); <ide> socket.end(); <ide> }); <ide><path>test/parallel/test-console.js <ide> console.trace('This is a %j %d', { formatted: 'trace' }, 10, 'foo'); <ide> console.time('label'); <ide> console.timeEnd('label'); <ide> <del>// verify that Object.prototype properties can be used as labels <add>// Verify that Object.prototype properties can be used as labels <ide> console.time('__proto__'); <ide> console.timeEnd('__proto__'); <ide> console.time('constructor'); <ide> assert.strictEqual(errStrings.length, process.stderr.writeTimes); <ide> restoreStdout(); <ide> restoreStderr(); <ide> <del>// verify that console.timeEnd() doesn't leave dead links <add>// Verify that console.timeEnd() doesn't leave dead links <ide> const timesMapSize = console._times.size; <ide> console.time('label1'); <ide> console.time('label2'); <ide> assert.strictEqual(strings.length, 0); <ide> assert.strictEqual(errStrings.shift().split('\n').shift(), <ide> 'Trace: This is a {"formatted":"trace"} 10 foo'); <ide> <del>// hijack stderr to catch `process.emitWarning` which is using <add>// Hijack stderr to catch `process.emitWarning` which is using <ide> // `process.nextTick` <ide> hijackStderr(common.mustCall(function(data) { <ide> restoreStderr(); <ide><path>test/parallel/test-crypto-authenticated.js <ide> for (const test of TEST_CASES) { <ide> msg += decrypt.final(outputEncoding); <ide> assert.strictEqual(msg, test.plain); <ide> } else { <del> // assert that final throws if input data could not be verified! <add> // Assert that final throws if input data could not be verified! <ide> assert.throws(function() { decrypt.final('hex'); }, errMessages.auth); <ide> } <ide> } <ide> for (const test of TEST_CASES) { <ide> msg += decrypt.final('ascii'); <ide> assert.strictEqual(msg, test.plain); <ide> } else { <del> // assert that final throws if input data could not be verified! <add> // Assert that final throws if input data could not be verified! <ide> assert.throws(function() { decrypt.final('ascii'); }, errMessages.auth); <ide> } <ide> } <ide><path>test/parallel/test-crypto-cipher-decipher.js <ide> testCipher2(Buffer.from('0123456789abcdef')); <ide> assert.strictEqual(decipher.setAAD(aadbuf), decipher); <ide> } <ide> <del>// error throwing in setAAD/setAuthTag/getAuthTag/setAutoPadding <add>// Error throwing in setAAD/setAuthTag/getAuthTag/setAutoPadding <ide> { <ide> const key = '0123456789'; <ide> const aadbuf = Buffer.from('aadbuf'); <ide><path>test/parallel/test-crypto-from-binary.js <ide> const crypto = require('crypto'); <ide> <ide> const EXTERN_APEX = 0xFBEE9; <ide> <del>// manually controlled string for checking binary output <add>// Manually controlled string for checking binary output <ide> let ucs2_control = 'a\u0000'; <ide> <ide> // grow the strings to proper length <ide><path>test/parallel/test-crypto.js <ide> assert.throws(function() { <ide> // Then open private_key.pem and change its header and footer. <ide> const sha1_privateKey = fixtures.readSync('test_bad_rsa_privkey.pem', <ide> 'ascii'); <del> // this would inject errors onto OpenSSL's error stack <add> // This would inject errors onto OpenSSL's error stack <ide> crypto.createSign('sha1').sign(sha1_privateKey); <ide> }, (err) => { <ide> // Throws crypto error, so there is an opensslErrorStack property. <ide><path>test/parallel/test-dgram-close-in-listening.js <ide> socket.on('listening', function() { <ide> // get a random port for send <ide> const portGetter = dgram.createSocket('udp4') <ide> .bind(0, 'localhost', common.mustCall(() => { <del> // adds a listener to 'listening' to send the data when <add> // Adds a listener to 'listening' to send the data when <ide> // the socket is available <ide> socket.send(buf, 0, buf.length, <ide> portGetter.address().port, <ide><path>test/parallel/test-dgram-close-is-not-callback.js <ide> const portGetter = dgram.createSocket('udp4') <ide> portGetter.address().port, <ide> portGetter.address().address); <ide> <del> // if close callback is not function, ignore the argument. <add> // If close callback is not function, ignore the argument. <ide> socket.close('bad argument'); <ide> portGetter.close(); <ide> <ide><path>test/parallel/test-domain-ee-implicit.js <ide> d.run(common.mustCall(() => { <ide> })); <ide> <ide> setTimeout(common.mustCall(() => { <del> // escape from the domain, but implicit is still bound to it. <add> // Escape from the domain, but implicit is still bound to it. <ide> implicit.emit('error', new Error('foobar')); <ide> }), 1); <ide><path>test/parallel/test-domain-implicit-fs.js <ide> d.on('error', common.mustCall(function(er) { <ide> })); <ide> <ide> <del>// implicit handling of thrown errors while in a domain, via the <add>// Implicit handling of thrown errors while in a domain, via the <ide> // single entry points of ReqWrap and MakeCallback. Even if <ide> // we try very hard to escape, there should be no way to, even if <ide> // we go many levels deep through timeouts and multiple IO calls. <ide><path>test/parallel/test-domain-multi.js <ide> const server = http.createServer((req, res) => { <ide> const b = domain.create(); <ide> a.add(b); <ide> <del> // treat these EE objects as if they are a part of the b domain <add> // Treat these EE objects as if they are a part of the b domain <ide> // so, an 'error' event on them propagates to the domain, rather <ide> // than being thrown. <ide> b.add(req); <ide><path>test/parallel/test-fs-append-file-sync.js <ide> const data = '南越国是前203年至前111年存在于岭南地区的一个国 <ide> const tmpdir = require('../common/tmpdir'); <ide> tmpdir.refresh(); <ide> <del>// test that empty file will be created and have content added <add>// Test that empty file will be created and have content added <ide> const filename = join(tmpdir.path, 'append-sync.txt'); <ide> <ide> fs.appendFileSync(filename, data); <ide><path>test/parallel/test-fs-append-file.js <ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; <ide> .catch(throwNextTick); <ide> } <ide> <del>// test that appends data to a non-empty file (callback API) <add>// Test that appends data to a non-empty file (callback API) <ide> { <ide> const filename = join(tmpdir.path, 'append-non-empty.txt'); <ide> fs.writeFileSync(filename, currentFileData); <ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; <ide> })); <ide> } <ide> <del>// test that appends data to a non-empty file (promise API) <add>// Test that appends data to a non-empty file (promise API) <ide> { <ide> const filename = join(tmpdir.path, 'append-non-empty-promise.txt'); <ide> fs.writeFileSync(filename, currentFileData); <ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; <ide> .catch(throwNextTick); <ide> } <ide> <del>// test that appendFile accepts buffers (callback API) <add>// Test that appendFile accepts buffers (callback API) <ide> { <ide> const filename = join(tmpdir.path, 'append-buffer.txt'); <ide> fs.writeFileSync(filename, currentFileData); <ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; <ide> })); <ide> } <ide> <del>// test that appendFile accepts buffers (promises API) <add>// Test that appendFile accepts buffers (promises API) <ide> { <ide> const filename = join(tmpdir.path, 'append-buffer-promises.txt'); <ide> fs.writeFileSync(filename, currentFileData); <ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; <ide> .catch(throwNextTick); <ide> } <ide> <del>// test that appendFile accepts numbers (callback API) <add>// Test that appendFile accepts numbers (callback API) <ide> { <ide> const filename = join(tmpdir.path, 'append-numbers.txt'); <ide> fs.writeFileSync(filename, currentFileData); <ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; <ide> })); <ide> } <ide> <del>// test that appendFile accepts numbers (promises API) <add>// Test that appendFile accepts numbers (promises API) <ide> { <ide> const filename = join(tmpdir.path, 'append-numbers-promises.txt'); <ide> fs.writeFileSync(filename, currentFileData); <ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; <ide> .catch(throwNextTick); <ide> } <ide> <del>// test that appendFile accepts file descriptors (callback API) <add>// Test that appendFile accepts file descriptors (callback API) <ide> { <ide> const filename = join(tmpdir.path, 'append-descriptors.txt'); <ide> fs.writeFileSync(filename, currentFileData); <ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; <ide> })); <ide> } <ide> <del>// test that appendFile accepts file descriptors (promises API) <add>// Test that appendFile accepts file descriptors (promises API) <ide> { <ide> const filename = join(tmpdir.path, 'append-descriptors-promises.txt'); <ide> fs.writeFileSync(filename, currentFileData); <ide><path>test/parallel/test-fs-non-number-arguments-throw.js <ide> const tempFile = path.join(tmpdir.path, 'fs-non-number-arguments-throw'); <ide> tmpdir.refresh(); <ide> fs.writeFileSync(tempFile, 'abc\ndef'); <ide> <del>// a sanity check when using numbers instead of strings <add>// A sanity check when using numbers instead of strings <ide> const sanity = 'def'; <ide> const saneEmitter = fs.createReadStream(tempFile, { start: 4, end: 6 }); <ide> <ide><path>test/parallel/test-fs-null-bytes.js <ide> check(null, fs.watch, fileUrl2, assert.fail); <ide> check(null, fs.watchFile, fileUrl2, assert.fail); <ide> check(fs.writeFile, fs.writeFileSync, fileUrl2, 'abc'); <ide> <del>// an 'error' for exists means that it doesn't exist. <del>// one of many reasons why this file is the absolute worst. <add>// An 'error' for exists means that it doesn't exist. <add>// One of many reasons why this file is the absolute worst. <ide> fs.exists('foo\u0000bar', common.mustCall((exists) => { <ide> assert(!exists); <ide> })); <ide><path>test/parallel/test-fs-promises-file-handle-chmod.js <ide> async function validateFilePermission() { <ide> const newPermissions = 0o765; <ide> <ide> if (common.isWindows) { <del> // chmod in Windows will only toggle read only/write access. the <add> // Chmod in Windows will only toggle read only/write access. The <ide> // fs.Stats.mode in Windows is computed using read/write <del> // bits (not exec). read only at best returns 444; r/w 666. <del> // refer: /deps/uv/src/win/fs.cfs; <add> // bits (not exec). Read-only at best returns 444; r/w 666. <add> // Refer: /deps/uv/src/win/fs.cfs; <ide> expectedAccess = 0o664; <ide> } else { <ide> expectedAccess = newPermissions; <ide><path>test/parallel/test-fs-promises.js <ide> async function getHandle(dest) { <ide> await handle.sync(); <ide> } <ide> <del> // test fs.read promises when length to read is zero bytes <add> // Test fs.read promises when length to read is zero bytes <ide> { <ide> const dest = path.resolve(tmpDir, 'test1.js'); <ide> const handle = await getHandle(dest); <ide><path>test/parallel/test-fs-realpath-on-substed-drive.js <ide> for (i = 0; i < driveLetters.length; ++i) { <ide> if (i === driveLetters.length) <ide> common.skip('Cannot create subst drive'); <ide> <del>// schedule cleanup (and check if all callbacks where called) <add>// Schedule cleanup (and check if all callbacks where called) <ide> process.on('exit', function() { <ide> spawnSync('subst', ['/d', drive]); <ide> }); <ide><path>test/parallel/test-fs-realpath.js <ide> function test_simple_relative_symlink(realpath, realpathSync, callback) { <ide> function test_simple_absolute_symlink(realpath, realpathSync, callback) { <ide> console.log('test_simple_absolute_symlink'); <ide> <del> // this one should still run, even if skipSymlinks is set, <add> // This one should still run, even if skipSymlinks is set, <ide> // because it uses a junction. <ide> const type = skipSymlinks ? 'junction' : 'dir'; <ide> <ide> function test_up_multiple(realpath, realpathSync, cb) { <ide> function test_abs_with_kids(realpath, realpathSync, cb) { <ide> console.log('test_abs_with_kids'); <ide> <del> // this one should still run, even if skipSymlinks is set, <add> // This one should still run, even if skipSymlinks is set, <ide> // because it uses a junction. <ide> const type = skipSymlinks ? 'junction' : 'dir'; <ide> <ide><path>test/parallel/test-fs-utimes.js <ide> if (!process.arch.includes('arm') && !common.isOpenBSD && !common.isSunOS) { <ide> } <ide> <ide> if (common.isWindows) { <del> // this value would get converted to (double)1713037251359.9998 <add> // This value would get converted to (double)1713037251359.9998 <ide> const truncate_mtime = 1713037251360; <ide> fs.utimesSync(path, truncate_mtime / 1000, truncate_mtime / 1000); <ide> const truncate_stats = fs.statSync(path); <ide><path>test/parallel/test-fs-whatwg-url.js <ide> common.expectsError( <ide> <ide> // pct-encoded characters in the path will be decoded and checked <ide> if (common.isWindows) { <del> // encoded back and forward slashes are not permitted on windows <add> // Encoded back and forward slashes are not permitted on windows <ide> ['%2f', '%2F', '%5c', '%5C'].forEach((i) => { <ide> common.expectsError( <ide> () => { <ide> if (common.isWindows) { <ide> } <ide> ); <ide> } else { <del> // encoded forward slashes are not permitted on other platforms <add> // Encoded forward slashes are not permitted on other platforms <ide> ['%2f', '%2F'].forEach((i) => { <ide> common.expectsError( <ide> () => { <ide><path>test/parallel/test-handle-wrap-isrefed.js <ide> const { kStateSymbol } = require('internal/dgram'); <ide> } <ide> <ide> <del>// see also test/pseudo-tty/test-handle-wrap-isrefed-tty.js <add>// See also test/pseudo-tty/test-handle-wrap-isrefed-tty.js <ide><path>test/parallel/test-http-addrequest-localaddress.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const agent = require('http').globalAgent; <ide> <del>// small stub just so we can call addRequest directly <add>// Small stub just so we can call addRequest directly <ide> const req = { <ide> getHeader: () => {} <ide> }; <ide><path>test/parallel/test-http-agent-destroyed-socket.js <ide> const server = http.createServer(common.mustCall((req, res) => { <ide> // assert request2 was removed from the queue <ide> assert(!agent.requests[key]); <ide> process.nextTick(() => { <del> // assert that the same socket was not assigned to request2, <add> // Assert that the same socket was not assigned to request2, <ide> // since it was destroyed. <ide> assert.notStrictEqual(request1.socket, request2.socket); <ide> assert(!request2.socket.destroyed, 'the socket is destroyed'); <ide> const server = http.createServer(common.mustCall((req, res) => { <ide> const request2 = http.get(requestOptions, common.mustCall((response) => { <ide> assert(!request2.socket.destroyed); <ide> assert(request1.socket.destroyed); <del> // assert not reusing the same socket, since it was destroyed. <add> // Assert not reusing the same socket, since it was destroyed. <ide> assert.notStrictEqual(request1.socket, request2.socket); <ide> const countdown = new Countdown(2, () => server.close()); <ide> request2.socket.on('close', common.mustCall(() => countdown.dec())); <ide><path>test/parallel/test-http-client-pipe-end.js <ide> server.listen(common.PIPE, function() { <ide> sched(function() { req.end(); }, 5); <ide> }); <ide> <del>// schedule a callback after `ticks` event loop ticks <add>// Schedule a callback after `ticks` event loop ticks <ide> function sched(cb, ticks) { <ide> function fn() { <ide> if (--ticks) <ide><path>test/parallel/test-http-client-spurious-aborted.js <ide> function download() { <ide> _handle._close = res.socket._handle.close; <ide> _handle.close = function(callback) { <ide> _handle._close(); <del> // set readable to true even though request is complete <add> // Set readable to true even though request is complete <ide> if (res.complete) res.readable = true; <ide> callback(); <ide> }; <ide><path>test/parallel/test-http-client-timeout-agent.js <ide> server.listen(0, options.host, function() { <ide> <ide> process.on('exit', () => { <ide> console.error(`done=${requests_done} sent=${requests_sent}`); <del> // check that timeout on http request was not called too much <add> // Check that timeout on http request was not called too much <ide> assert.strictEqual(requests_done, requests_sent); <ide> }); <ide><path>test/parallel/test-http-connect-req-res.js <ide> server.listen(0, common.mustCall(function() { <ide> <ide> let data = firstBodyChunk.toString(); <ide> <del> // test that the firstBodyChunk was not parsed as HTTP <add> // Test that the firstBodyChunk was not parsed as HTTP <ide> assert.strictEqual(data, 'Head'); <ide> <ide> socket.on('data', function(buf) { <ide><path>test/parallel/test-http-outgoing-finish.js <ide> function write(out) { <ide> // first, write until it gets some backpressure <ide> while (out.write(buf)) {} <ide> <del> // now end, and make sure that we don't get the 'finish' event <add> // Now end, and make sure that we don't get the 'finish' event <ide> // before the tick where the cb gets called. We give it until <ide> // nextTick because this is added as a listener before the endcb <ide> // is registered. The order is not what we're testing here, just <ide><path>test/parallel/test-http-remove-header-stays-removed.js <ide> const server = http.createServer(function(request, response) { <ide> response.removeHeader('transfer-encoding'); <ide> response.removeHeader('content-length'); <ide> <del> // make sure that removing and then setting still works: <add> // Make sure that removing and then setting still works: <ide> response.removeHeader('date'); <ide> response.setHeader('date', 'coffee o clock'); <ide> <ide><path>test/parallel/test-http-request-dont-override-options.js <ide> server.listen(0, function() { <ide> const agent = new http.Agent(); <ide> agent.defaultPort = this.address().port; <ide> <del> // options marked as explicitly undefined for readability <add> // Options marked as explicitly undefined for readability <ide> // in this test, they should STAY undefined as options should not <ide> // be mutable / modified <ide> const options = { <ide><path>test/parallel/test-http-response-multiheaders.js <ide> const server = http.createServer(function(req, res) { <ide> server.listen(0, common.mustCall(function() { <ide> const countdown = new Countdown(runCount, () => server.close()); <ide> for (let n = 1; n <= runCount; n++) { <del> // this runs twice, the first time, the server will use <add> // This runs twice, the first time, the server will use <ide> // setHeader, the second time it uses writeHead. The <ide> // result on the client side should be the same in <ide> // either case -- only the first instance of the header <ide><path>test/parallel/test-http-server-multiheaders2.js <ide> const multipleAllowed = [ <ide> // not a special case, just making sure it's parsed correctly <ide> 'X-Forwarded-For', <ide> <del> // make sure that unspecified headers is treated as multiple <add> // Make sure that unspecified headers is treated as multiple <ide> 'Some-Random-Header', <ide> 'X-Some-Random-Header', <ide> ]; <ide><path>test/parallel/test-http-server-response-standalone.js <ide> const { ServerResponse } = require('http'); <ide> const { Writable } = require('stream'); <ide> const assert = require('assert'); <ide> <del>// check that ServerResponse can be used without a proper Socket <add>// Check that ServerResponse can be used without a proper Socket <ide> // Fixes: https://github.com/nodejs/node/issues/14386 <ide> // Fixes: https://github.com/nodejs/node/issues/14381 <ide> <ide><path>test/parallel/test-http-url.parse-basic.js <ide> let testURL; <ide> function check(request) { <ide> // default method should still be get <ide> assert.strictEqual(request.method, 'GET'); <del> // there are no URL params, so you should not see any <add> // There are no URL params, so you should not see any <ide> assert.strictEqual(request.url, '/'); <ide> // the host header should use the url.parse.hostname <ide> assert.strictEqual(request.headers.host, <ide><path>test/parallel/test-http-wget.js <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> const http = require('http'); <ide> <del>// wget sends an HTTP/1.0 request with Connection: Keep-Alive <add>// `wget` sends an HTTP/1.0 request with Connection: Keep-Alive <ide> // <ide> // Sending back a chunked response to an HTTP/1.0 client would be wrong, <ide> // so what has to happen in this case is that the connection is closed <ide><path>test/parallel/test-http-write-callbacks.js <ide> server.listen(0, function() { <ide> }); <ide> }); <ide> req.on('response', (res) => { <del> // this should not come until after the end is flushed out <add> // This should not come until after the end is flushed out <ide> assert(clientEndCb); <ide> res.setEncoding('ascii'); <ide> res.on('data', (c) => { <ide><path>test/parallel/test-http-zero-length-write.js <ide> function getSrc() { <ide> // The Readable class prevents this behavior. <ide> const src = new Stream(); <ide> <del> // start out paused, just so we don't miss anything yet. <add> // Start out paused, just so we don't miss anything yet. <ide> let paused = false; <ide> src.pause = function() { <ide> paused = true; <ide><path>test/parallel/test-http2-altsvc.js <ide> server.on('session', common.mustCall((session) => { <ide> ); <ide> }); <ide> <del> // arguments + origin are too long for an ALTSVC frame <add> // Arguments + origin are too long for an ALTSVC frame <ide> assert.throws( <ide> () => { <ide> session.altsvc('h2=":8000"', <ide><path>test/parallel/test-http2-client-set-priority.js <ide> checkWeight(1, 1); <ide> checkWeight(16, 16); <ide> checkWeight(256, 256); <ide> <del>// when client weight is higher than 256, weight is 256 <add>// When client weight is higher than 256, weight is 256 <ide> checkWeight(257, 256); <ide> checkWeight(512, 256); <ide> <del>// when client weight is undefined, weight is default 16 <add>// When client weight is undefined, weight is default 16 <ide> checkWeight(undefined, 16); <ide><path>test/parallel/test-http2-compat-expect-continue-check.js <ide> server.on('checkContinue', common.mustCall((req, res) => { <ide> res.writeContinue(); <ide> res.writeHead(200, {}); <ide> res.end(testResBody); <del> // should simply return false if already too late to write <add> // Should simply return false if already too late to write <ide> assert.strictEqual(res.writeContinue(), false); <ide> res.on('finish', common.mustCall( <ide> () => process.nextTick(() => assert.strictEqual(res.writeContinue(), false)) <ide><path>test/parallel/test-http2-compat-serverrequest-pause.js <ide> server.on('request', common.mustCall((req, res) => { <ide> res.end(); <ide> })); <ide> <del> // shouldn't throw if underlying Http2Stream no longer exists <add> // Shouldn't throw if underlying Http2Stream no longer exists <ide> res.on('finish', common.mustCall(() => process.nextTick(() => { <ide> req.pause(); <ide> req.resume(); <ide><path>test/parallel/test-http2-compat-serverrequest-pipe.js <ide> const http2 = require('http2'); <ide> const fs = require('fs'); <ide> const path = require('path'); <ide> <del>// piping should work as expected with createWriteStream <add>// Piping should work as expected with createWriteStream <ide> <ide> const tmpdir = require('../common/tmpdir'); <ide> tmpdir.refresh(); <ide><path>test/parallel/test-http2-compat-socket.js <ide> server.on('request', common.mustCall(function(request, response) { <ide> common.expectsError(() => request.socket.pause(), errMsg); <ide> common.expectsError(() => request.socket.resume(), errMsg); <ide> <del> // should have correct this context for socket methods & getters <add> // Should have correct this context for socket methods & getters <ide> assert.ok(request.socket.address() != null); <ide> assert.ok(request.socket.remotePort); <ide> <ide> server.on('request', common.mustCall(function(request, response) { <ide> assert.ok(request.socket._server); <ide> assert.strictEqual(request.socket.connecting, false); <ide> <del> // socket events are bound and emitted on Http2Stream <add> // Socket events are bound and emitted on Http2Stream <ide> request.socket.on('close', common.mustCall()); <ide> request.socket.once('close', common.mustCall()); <ide> request.socket.on('testEvent', common.mustCall()); <ide><path>test/parallel/test-http2-connect.js <ide> const { connect: netConnect } = require('net'); <ide> connect(authority).on('error', () => {}); <ide> } <ide> <del>// check for error for an invalid protocol (not http or https) <add>// Check for error for an invalid protocol (not http or https) <ide> { <ide> const authority = 'ssh://localhost'; <ide> expectsError(() => { <ide><path>test/parallel/test-http2-dont-override.js <ide> const options = {}; <ide> <ide> const server = http2.createServer(options); <ide> <del>// options are defaulted but the options are not modified <add>// Options are defaulted but the options are not modified <ide> assert.deepStrictEqual(Object.keys(options), []); <ide> <ide> server.on('stream', common.mustCall((stream) => { <ide><path>test/parallel/test-http2-pipe.js <ide> const http2 = require('http2'); <ide> const fs = require('fs'); <ide> const path = require('path'); <ide> <del>// piping should work as expected with createWriteStream <add>// Piping should work as expected with createWriteStream <ide> <ide> const tmpdir = require('../common/tmpdir'); <ide> tmpdir.refresh(); <ide><path>test/parallel/test-http2-respond-file-304.js <ide> server.on('stream', (stream) => { <ide> [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' <ide> }, { <ide> statCheck(stat, headers) { <del> // abort the send and return a 304 Not Modified instead <add> // Abort the send and return a 304 Not Modified instead <ide> stream.respond({ [HTTP2_HEADER_STATUS]: 304 }); <ide> return false; <ide> } <ide><path>test/parallel/test-http2-timeouts.js <ide> server.on('stream', common.mustCall((stream) => { <ide> stream.end('hello world'); <ide> })); <ide> <del> // check that expected errors are thrown with wrong args <add> // Check that expected errors are thrown with wrong args <ide> common.expectsError( <ide> () => stream.setTimeout('100'), <ide> { <ide><path>test/parallel/test-https-agent-create-connection.js <ide> function createServer() { <ide> })); <ide> } <ide> <del>// use port and host and option does not have agentKey <add>// Use port and host and option does not have agentKey <ide> { <ide> const server = createServer(); <ide> server.listen(0, common.mustCall(() => { <ide><path>test/parallel/test-https-argument-of-creating.js <ide> const dftProtocol = {}; <ide> } <ide> <ide> <del>// validate that `createServer` can work with no arguments <add>// Validate that `createServer` can work with no arguments <ide> { <ide> const server = https.createServer(); <ide> <ide><path>test/parallel/test-https-client-get-url.js <ide> const fixtures = require('../common/fixtures'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> <del>// disable strict server certificate validation by the client <add>// Disable strict server certificate validation by the client <ide> process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; <ide> <ide> const assert = require('assert'); <ide><path>test/parallel/test-https-slow-headers.js <ide> let sendCharEvery = 1000; <ide> // 40 seconds is the default <ide> assert.strictEqual(server.headersTimeout, 40 * 1000); <ide> <del>// pass a REAL env variable to shortening up the default <add>// Pass a REAL env variable to shortening up the default <ide> // value which is 40s otherwise <ide> // this is useful for manual testing <ide> if (!process.env.REAL) { <ide><path>test/parallel/test-https-strict.js <ide> const fixtures = require('../common/fixtures'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> <del>// disable strict server certificate validation by the client <add>// Disable strict server certificate validation by the client <ide> process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; <ide> <ide> common.expectWarning( <ide><path>test/parallel/test-https-truncate.js <ide> const https = require('https'); <ide> const key = fixtures.readKey('agent1-key.pem'); <ide> const cert = fixtures.readKey('agent1-cert.pem'); <ide> <del>// number of bytes discovered empirically to trigger the bug <add>// Number of bytes discovered empirically to trigger the bug <ide> const data = Buffer.alloc(1024 * 32 + 1); <ide> <ide> httpsTest(); <ide><path>test/parallel/test-listen-fd-detached-inherit.js <ide> function test() { <ide> s += c.toString(); <ide> }); <ide> res.on('end', function() { <del> // kill the subprocess before we start doing asserts. <del> // it's really annoying when tests leave orphans! <add> // Kill the subprocess before we start doing asserts. <add> // It's really annoying when tests leave orphans! <ide> process.kill(child.pid, 'SIGKILL'); <ide> try { <ide> parent.kill(); <ide><path>test/parallel/test-listen-fd-detached.js <ide> function test() { <ide> s += c.toString(); <ide> }); <ide> res.on('end', function() { <del> // kill the subprocess before we start doing asserts. <add> // Kill the subprocess before we start doing asserts. <ide> // it's really annoying when tests leave orphans! <ide> process.kill(child.pid, 'SIGKILL'); <ide> try { <ide><path>test/parallel/test-module-version.js <ide> const assert = require('assert'); <ide> // check for existence <ide> assert(process.config.variables.hasOwnProperty('node_module_version')); <ide> <del>// ensure that `node_module_version` is an Integer > 0 <add>// Ensure that `node_module_version` is an Integer > 0 <ide> assert(Number.isInteger(process.config.variables.node_module_version)); <ide> assert(process.config.variables.node_module_version > 0); <ide><path>test/parallel/test-net-connect-immediate-finish.js <ide> const { <ide> <ide> const client = net.connect({ <ide> host: addresses.INVALID_HOST, <del> port: 80, // port number doesn't matter because host name is invalid <add> port: 80, // Port number doesn't matter because host name is invalid <ide> lookup: common.mustCall(errorLookupMock()) <ide> }, common.mustNotCall()); <ide> <ide><path>test/parallel/test-net-connect-options-allowhalfopen.js <ide> const net = require('net'); <ide> client.resume(); <ide> client.on('end', common.mustCall(function clientOnEnd() { <ide> setTimeout(function closeServer() { <del> // when allowHalfOpen is true, client must still be writable <add> // When allowHalfOpen is true, client must still be writable <ide> // after the server closes the connections, but not readable <ide> console.log(`client ${index} received FIN`); <ide> assert(!client.readable); <ide><path>test/parallel/test-net-timeout-no-handle.js <ide> socket.on('timeout', common.mustCall(() => { <ide> <ide> socket.on('connect', common.mustNotCall()); <ide> <del>// since the timeout is unrefed, the code will exit without this <add>// Since the timeout is unrefed, the code will exit without this <ide> setTimeout(() => {}, common.platformTimeout(200)); <ide><path>test/parallel/test-next-tick-intentional-starvation.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> <del>// this is the inverse of test-next-tick-starvation. it verifies <add>// This is the inverse of test-next-tick-starvation. it verifies <ide> // that process.nextTick will *always* come before other events <ide> <ide> let ran = false; <ide><path>test/parallel/test-path.js <ide> typeErrorTests.forEach((test) => { <ide> fail(namespace.basename, test); <ide> fail(namespace.extname, test); <ide> <del> // undefined is a valid value as the second argument to basename <add> // Undefined is a valid value as the second argument to basename <ide> if (test !== undefined) { <ide> fail(namespace.basename, 'foo', test); <ide> } <ide><path>test/parallel/test-preload.js <ide> replProc.on('close', function(code) { <ide> assert.strictEqual(replStdout, output); <ide> }); <ide> <del>// test that preload placement at other points in the cmdline <add>// Test that preload placement at other points in the cmdline <ide> // also test that duplicated preload only gets loaded once <ide> childProcess.exec( <ide> `"${nodeBinary}" ${preloadOption([fixtureA])}-e "console.log('hello');" ${ <ide><path>test/parallel/test-process-emitwarning.js <ide> class CustomWarning extends Error { <ide> [testMsg, { type: testType, code: testCode }], <ide> [testMsg, { type: testType, code: testCode, detail: testDetail }], <ide> [new CustomWarning()], <del> // detail will be ignored for the following. No errors thrown <add> // Detail will be ignored for the following. No errors thrown <ide> [testMsg, { type: testType, code: testCode, detail: true }], <ide> [testMsg, { type: testType, code: testCode, detail: [] }], <ide> [testMsg, { type: testType, code: testCode, detail: null }], <ide><path>test/parallel/test-process-env-allowed-flags.js <ide> require('../common'); <ide> }); <ide> } <ide> <del>// assert immutability of process.allowedNodeEnvironmentFlags <add>// Assert immutability of process.allowedNodeEnvironmentFlags <ide> { <ide> assert.strictEqual(Object.isFrozen(process.allowedNodeEnvironmentFlags), <ide> true); <ide><path>test/parallel/test-process-env.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> <del>// changes in environment should be visible to child processes <add>// Changes in environment should be visible to child processes <ide> if (process.argv[2] === 'you-are-the-child') { <ide> assert.strictEqual('NODE_PROCESS_ENV_DELETED' in process.env, false); <ide> assert.strictEqual(process.env.NODE_PROCESS_ENV, '42'); <ide><path>test/parallel/test-promises-unhandled-rejections.js <ide> asyncTest('While inside setImmediate, catching a rejected promise derived ' + <ide> onUnhandledFail(done); <ide> <ide> setImmediate(function() { <del> // reproduces on first tick and inside of setImmediate <add> // Reproduces on first tick and inside of setImmediate <ide> Promise <ide> .resolve('resolve') <ide> .then(function() { <ide><path>test/parallel/test-querystring.js <ide> qsColonTestCases.forEach((testCase) => { <ide> check(qs.parse(testCase[0], ';', ':'), testCase[2], testCase[0]); <ide> }); <ide> <del>// test the weird objects, that they get parsed properly <add>// Test the weird objects, that they get parsed properly <ide> qsWeirdObjects.forEach((testCase) => { <ide> check(qs.parse(testCase[1]), testCase[2], testCase[1]); <ide> }); <ide><path>test/parallel/test-readline-interface.js <ide> function isWarned(emitter) { <ide> rli.close(); <ide> } <ide> <del> // sending a single character with no newline and then a newline <add> // Sending a single character with no newline and then a newline <ide> { <ide> const fi = new FakeInput(); <ide> const rli = new readline.Interface( <ide> function isWarned(emitter) { <ide> }); <ide> } <ide> <del> // constructor throws if historySize is not a positive number <add> // Constructor throws if historySize is not a positive number <ide> { <ide> const fi = new FakeInput(); <ide> common.expectsError(function() { <ide> function isWarned(emitter) { <ide> rli.close(); <ide> } <ide> <del> // sending a multi-byte utf8 char over multiple writes <add> // Sending a multi-byte utf8 char over multiple writes <ide> { <ide> const buf = Buffer.from('☮', 'utf8'); <ide> const fi = new FakeInput(); <ide><path>test/parallel/test-repl-tab-complete.js <ide> testMe.complete('inner.o', common.mustCall(function(error, data) { <ide> <ide> putIn.run(['.clear']); <ide> <del>// currently does not work, but should not break, not the { <add>// Currently does not work, but should not break, not the { <ide> putIn.run([ <ide> 'var top = function() {', <ide> 'r = function test ()', <ide> testMe.complete('toSt', common.mustCall(function(error, data) { <ide> assert.deepStrictEqual(data, [['toString'], 'toSt']); <ide> })); <ide> <del>// own properties should shadow properties on the prototype <add>// Own properties should shadow properties on the prototype <ide> putIn.run(['.clear']); <ide> putIn.run([ <ide> 'var x = Object.create(null);', <ide><path>test/parallel/test-repl-underscore.js <ide> function testResetContextGlobal() { <ide> '10', <ide> ]); <ide> <del> // delete globals leaked by REPL when `useGlobal` is `true` <add> // Delete globals leaked by REPL when `useGlobal` is `true` <ide> delete global.module; <ide> delete global.require; <ide> } <ide><path>test/parallel/test-repl-use-global.js <ide> const processTest = (useGlobal, cb, output) => (err, repl) => { <ide> let str = ''; <ide> output.on('data', (data) => (str += data)); <ide> <del> // if useGlobal is false, then `let process` should work <add> // If useGlobal is false, then `let process` should work <ide> repl.write('let process;\n'); <ide> repl.write('21 * 2;\n'); <ide> repl.close(); <ide><path>test/parallel/test-repl.js <ide> async function runReplTests(socket, prompt, tests) { <ide> socket.write(`${send}\n`); <ide> <ide> for (let expectedLine of expectedLines) { <del> // special value: kSource refers to last sent source text <add> // Special value: kSource refers to last sent source text <ide> if (expectedLine === kSource) <ide> expectedLine = send; <ide> <ide> const errorTests = [ <ide> send: 'new RegExp("foo", "wrong modifier");', <ide> expect: [/^SyntaxError: /, ''] <ide> }, <del> // strict mode syntax errors should be caught (GH-5178) <add> // Strict mode syntax errors should be caught (GH-5178) <ide> { <ide> send: '(function() { "use strict"; return 0755; })()', <ide> expect: [ <ide> const errorTests = [ <ide> '' <ide> ] <ide> }, <del> // do not fail when a String is created with line continuation <add> // Do not fail when a String is created with line continuation <ide> { <ide> send: '\'the\\\nfourth\\\neye\'', <ide> expect: ['... ... \'thefourtheye\''] <ide> const errorTests = [ <ide> send: ' \t .break \t ', <ide> expect: '' <ide> }, <del> // multiline strings preserve whitespace characters in them <add> // Multiline strings preserve whitespace characters in them <ide> { <ide> send: '\'the \\\n fourth\t\t\\\n eye \'', <ide> expect: '... ... \'the fourth\\t\\t eye \'' <ide><path>test/parallel/test-setproctitle.js <ide> exec(cmd, common.mustCall((error, stdout, stderr) => { <ide> assert.ifError(error); <ide> assert.strictEqual(stderr, ''); <ide> <del> // freebsd always add ' (procname)' to the process title <add> // Freebsd always add ' (procname)' to the process title <ide> if (common.isFreeBSD || common.isOpenBSD) <ide> title += ` (${path.basename(process.execPath)})`; <ide> <ide><path>test/parallel/test-stdio-pipe-stderr.js <ide> const spawn = require('child_process').spawnSync; <ide> tmpdir.refresh(); <ide> const fakeModulePath = join(tmpdir.path, 'batman.js'); <ide> const stderrOutputPath = join(tmpdir.path, 'stderr-output.txt'); <del>// we need to redirect stderr to a file to produce #11257 <add>// We need to redirect stderr to a file to produce #11257 <ide> const stream = fs.createWriteStream(stderrOutputPath); <ide> <del>// the error described in #11257 only happens when we require a <add>// The error described in #11257 only happens when we require a <ide> // non-built-in module. <ide> fs.writeFileSync(fakeModulePath, '', 'utf8'); <ide> <ide><path>test/parallel/test-stream-big-push.js <ide> chunk = r.read(); <ide> assert.strictEqual(chunk, null); <ide> <ide> r.once('readable', () => { <del> // this time, we'll get *all* the remaining data, because <add> // This time, we'll get *all* the remaining data, because <ide> // it's been added synchronously, as the read WOULD take <ide> // us below the hwm, and so it triggered a _read() again, <ide> // which synchronously added more, which we then return. <ide><path>test/parallel/test-stream-duplex-destroy.js <ide> const { inherits } = require('util'); <ide> duplex.destroyed = true; <ide> assert.strictEqual(duplex.destroyed, true); <ide> <del> // the internal destroy() mechanism should not be triggered <add> // The internal destroy() mechanism should not be triggered <ide> duplex.on('finish', common.mustNotCall()); <ide> duplex.on('end', common.mustNotCall()); <ide> duplex.destroy(); <ide><path>test/parallel/test-stream-pipe-after-end.js <ide> class TestWritable extends Writable { <ide> } <ide> } <ide> <del>// this one should not emit 'end' until we read() from it later. <add>// This one should not emit 'end' until we read() from it later. <ide> const ender = new TestReadable(); <ide> <del>// what happens when you pipe() a Readable that's already ended? <add>// What happens when you pipe() a Readable that's already ended? <ide> const piper = new TestReadable(); <ide> // pushes EOF null, and length=0, so this will trigger 'end' <ide> piper.read(); <ide><path>test/parallel/test-stream-readable-async-iterators.js <ide> async function tests() { <ide> } <ide> } <ide> <del>// to avoid missing some tests if a promise does not resolve <add>// To avoid missing some tests if a promise does not resolve <ide> tests().then(common.mustCall()); <ide><path>test/parallel/test-stream-readable-destroy.js <ide> const { inherits } = require('util'); <ide> read.destroyed = true; <ide> assert.strictEqual(read.destroyed, true); <ide> <del> // the internal destroy() mechanism should not be triggered <add> // The internal destroy() mechanism should not be triggered <ide> read.on('end', common.mustNotCall()); <ide> read.destroy(); <ide> } <ide><path>test/parallel/test-stream-readable-event.js <ide> const Readable = require('stream').Readable; <ide> } <ide> <ide> { <del> // second test, make sure that readable is re-emitted if there's <add> // Second test, make sure that readable is re-emitted if there's <ide> // already a length, while it IS reading. <ide> <ide> const r = new Readable({ <ide><path>test/parallel/test-stream-readable-flow-recursion.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> <del>// this test verifies that passing a huge number to read(size) <add>// This test verifies that passing a huge number to read(size) <ide> // will push up the highWaterMark, and cause the stream to read <ide> // more data continuously, but without triggering a nextTick <ide> // warning or RangeError. <ide> process.on('exit', function(code) { <ide> assert.strictEqual(reads, 2); <ide> // we pushed up the high water mark <ide> assert.strictEqual(stream.readableHighWaterMark, 8192); <del> // length is 0 right now, because we pulled it all out. <add> // Length is 0 right now, because we pulled it all out. <ide> assert.strictEqual(stream.readableLength, 0); <ide> assert(!code); <ide> assert.strictEqual(depth, 0); <ide><path>test/parallel/test-stream-readable-hwm-0.js <ide> const assert = require('assert'); <ide> const { Readable } = require('stream'); <ide> <ide> const r = new Readable({ <del> // must be called only once upon setting 'readable' listener <add> // Must be called only once upon setting 'readable' listener <ide> read: common.mustCall(), <ide> highWaterMark: 0, <ide> }); <ide><path>test/parallel/test-stream-readable-reading-readingMore.js <ide> const Readable = require('stream').Readable; <ide> assert.strictEqual(state.readingMore, false); <ide> <ide> readable.on('data', common.mustCall((data) => { <del> // while in a flowing state with a 'readable' listener <add> // While in a flowing state with a 'readable' listener <ide> // we should not be reading more <ide> if (readable.readableFlowing) <ide> assert.strictEqual(state.readingMore, true); <ide> const Readable = require('stream').Readable; <ide> <ide> const expectedReadingMore = [true, false]; <ide> readable.on('readable', common.mustCall(() => { <del> // there is only one readingMore scheduled from on('data'), <add> // There is only one readingMore scheduled from on('data'), <ide> // after which everything is governed by the .read() call <ide> assert.strictEqual(state.readingMore, expectedReadingMore.shift()); <ide> <ide> const Readable = require('stream').Readable; <ide> assert.strictEqual(state.readingMore, false); <ide> <ide> readable.on('data', common.mustCall((data) => { <del> // while in a flowing state without a 'readable' listener <add> // While in a flowing state without a 'readable' listener <ide> // we should be reading more <ide> if (readable.readableFlowing) <ide> assert.strictEqual(state.readingMore, true); <ide> const Readable = require('stream').Readable; <ide> // We are still not flowing, we will be resuming in the next tick <ide> assert.strictEqual(state.flowing, false); <ide> <del> // wait for nextTick, so the readableListener flag resets <add> // Wait for nextTick, so the readableListener flag resets <ide> process.nextTick(function() { <ide> readable.resume(); <ide> <ide><path>test/parallel/test-stream-readable-resumeScheduled.js <ide> const { Readable, Writable } = require('stream'); <ide> // resumeScheduled should start = `false`. <ide> assert.strictEqual(r._readableState.resumeScheduled, false); <ide> <del> // calling pipe() should change the state value = true. <add> // Calling pipe() should change the state value = true. <ide> r.pipe(w); <ide> assert.strictEqual(r._readableState.resumeScheduled, true); <ide> <ide> const { Readable, Writable } = require('stream'); <ide> <ide> r.push(Buffer.from([1, 2, 3])); <ide> <del> // adding 'data' listener should change the state value <add> // Adding 'data' listener should change the state value <ide> r.on('data', common.mustCall(() => { <ide> assert.strictEqual(r._readableState.resumeScheduled, false); <ide> })); <ide><path>test/parallel/test-stream-unshift-empty-chunk.js <ide> r.on('readable', () => { <ide> let chunk; <ide> while (chunk = r.read()) { <ide> seen.push(chunk.toString()); <del> // simulate only reading a certain amount of the data, <add> // Simulate only reading a certain amount of the data, <ide> // and then putting the rest of the chunk back into the <ide> // stream, like a parser might do. We just fill it with <ide> // 'y' so that it's easy to see which bits were touched, <ide><path>test/parallel/test-stream-writable-destroy.js <ide> const { inherits } = require('util'); <ide> write.destroyed = true; <ide> assert.strictEqual(write.destroyed, true); <ide> <del> // the internal destroy() mechanism should not be triggered <add> // The internal destroy() mechanism should not be triggered <ide> write.on('close', common.mustNotCall()); <ide> write.destroy(); <ide> } <ide><path>test/parallel/test-stream-writable-write-writev-finish.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const stream = require('stream'); <ide> <del>// ensure consistency between the finish event when using cork() <add>// Ensure consistency between the finish event when using cork() <ide> // and writev and when not using them <ide> <ide> { <ide><path>test/parallel/test-stream2-basic.js <ide> class TestWriter extends EE { <ide> // Verify unpipe <ide> const r = new TestReader(5); <ide> <del> // unpipe after 3 writes, then write to another stream instead. <add> // Unpipe after 3 writes, then write to another stream instead. <ide> let expect = [ 'xxxxx', <ide> 'xxxxx', <ide> 'xxxxx', <ide> class TestWriter extends EE { <ide> // Verify multi-unpipe <ide> const r = new TestReader(5); <ide> <del> // unpipe after 3 writes, then write to another stream instead. <add> // Unpipe after 3 writes, then write to another stream instead. <ide> let expect = [ 'xxxxx', <ide> 'xxxxx', <ide> 'xxxxx', <ide><path>test/parallel/test-stream2-transform.js <ide> const Transform = require('_stream_transform'); <ide> // Verify asymmetric transform (compress) <ide> const pt = new Transform(); <ide> <del> // each output is the first char of 3 consecutive chunks, <add> // Each output is the first char of 3 consecutive chunks, <ide> // or whatever's left. <ide> pt.state = ''; <ide> <ide> const Transform = require('_stream_transform'); <ide> })); <ide> } <ide> <del>// this tests for a stall when data is written to a full stream <add>// This tests for a stall when data is written to a full stream <ide> // that has empty transforms. <ide> { <ide> // Verify complex transform behavior <ide><path>test/parallel/test-stream3-cork-end.js <ide> let seenEnd = false; <ide> const w = new Writable(); <ide> // lets arrange to store the chunks <ide> w._write = function(chunk, encoding, cb) { <del> // stream end event is not seen before the last write <add> // Stream end event is not seen before the last write <ide> assert.ok(!seenEnd); <ide> // default encoding given none was specified <ide> assert.strictEqual(encoding, 'buffer'); <ide><path>test/parallel/test-stream3-pause-then-read.js <ide> function read1234() { <ide> <ide> function resumePause() { <ide> console.error('resumePause'); <del> // don't read anything, just resume and re-pause a whole bunch <add> // Don't read anything, just resume and re-pause a whole bunch <ide> r.resume(); <ide> r.pause(); <ide> r.resume(); <ide><path>test/parallel/test-stringbytes-external.js <ide> 'use strict'; <ide> require('../common'); <ide> const assert = require('assert'); <del>// minimum string size to overflow into external string space <add>// Minimum string size to overflow into external string space <ide> const EXTERN_APEX = 0xFBEE9; <ide> <del>// manually controlled string for checking binary output <add>// Manually controlled string for checking binary output <ide> let ucs2_control = 'a\u0000'; <ide> let write_str = 'a'; <ide> <ide> for (let i = 0; i < b.length; i += 2) { <ide> assert.strictEqual(b[i + 1], 0); <ide> } <ide> <del>// create another string to create an external string <add>// Create another string to create an external string <ide> const b_ucs = b.toString('ucs2'); <ide> <ide> // check control against external binary string <ide><path>test/parallel/test-timers-immediate-unref.js <ide> function secondStep() { <ide> const immA = setImmediate(() => { <ide> clearImmediate(immA); <ide> clearImmediate(immB); <del> // this should not keep the event loop open indefinitely <add> // This should not keep the event loop open indefinitely <ide> // or do anything else weird <ide> immA.ref(); <ide> immB.ref(); <ide><path>test/parallel/test-timers-reset-process-domain-on-throw.js <ide> function err() { <ide> d.run(err2); <ide> <ide> function err2() { <del> // this function doesn't exist, and throws an error as a result. <add> // This function doesn't exist, and throws an error as a result. <ide> err3(); // eslint-disable-line no-undef <ide> } <ide> <ide><path>test/parallel/test-timers.js <ide> const inputs = [ <ide> 0.5, <ide> 1, <ide> 1.0, <del> 2147483648, // browser behavior: timeouts > 2^31-1 run on next tick <add> 2147483648, // Browser behavior: timeouts > 2^31-1 run on next tick <ide> 12345678901234 // ditto <ide> ]; <ide> <ide><path>test/parallel/test-tls-client-mindhsize.js <ide> function test(size, err, next) { <ide> }); <ide> <ide> server.listen(0, '127.0.0.1', function() { <del> // client set minimum DH parameter size to 2048 bits so that <add> // Client set minimum DH parameter size to 2048 bits so that <ide> // it fails when it make a connection to the tls server where <ide> // dhparams is 1024 bits <ide> const client = tls.connect({ <ide><path>test/parallel/test-tls-socket-close.js <ide> function connectClient(server) { <ide> assert(netSocket); <ide> netSocket.setTimeout(1, common.mustCall(() => { <ide> assert(tlsSocket); <del> // this breaks if TLSSocket is already managing the socket: <add> // This breaks if TLSSocket is already managing the socket: <ide> netSocket.destroy(); <ide> const interval = setInterval(() => { <ide> // Checking this way allows us to do the write at a time that causes a <ide><path>test/parallel/test-url-format.js <ide> const formatTests = { <ide> pathname: '/' <ide> }, <ide> <del> // more than 255 characters in hostname which exceeds the limit <add> // More than 255 characters in hostname which exceeds the limit <ide> [`http://${'a'.repeat(255)}.com/node`]: { <ide> href: 'http:///node', <ide> protocol: 'http:', <ide> const formatTests = { <ide> path: '/node' <ide> }, <ide> <del> // greater than or equal to 63 characters after `.` in hostname <add> // Greater than or equal to 63 characters after `.` in hostname <ide> [`http://www.${'z'.repeat(63)}example.com/node`]: { <ide> href: `http://www.${'z'.repeat(63)}example.com/node`, <ide> protocol: 'http:', <ide><path>test/parallel/test-url-parse-format.js <ide> const parseTests = { <ide> path: ';a/b/c?d=e' <ide> }, <ide> <del> // make sure that we don't accidentally lcast the path parts. <add> // Make sure that we don't accidentally lcast the path parts. <ide> 'HtTp://x.y.cOm;A/b/c?d=e#f g<h>i': { <ide> href: 'http://x.y.com/;A/b/c?d=e#f%20g%3Ch%3Ei', <ide> protocol: 'http:', <ide><path>test/parallel/test-v8-coverage.js <ide> function nextdir() { <ide> assert.strictEqual(fixtureCoverage.functions[1].ranges[1].count, 0); <ide> } <ide> <del>// outputs coverage when process.exit(1) exits process. <add>// Outputs coverage when process.exit(1) exits process. <ide> { <ide> const coverageDirectory = path.join(tmpdir.path, nextdir()); <ide> const output = spawnSync(process.execPath, [ <ide> function nextdir() { <ide> assert.strictEqual(fixtureCoverage.functions[2].ranges[1].count, 0); <ide> } <ide> <del>// does not output coverage if NODE_V8_COVERAGE is empty. <add>// Does not output coverage if NODE_V8_COVERAGE is empty. <ide> { <ide> const coverageDirectory = path.join(tmpdir.path, nextdir()); <ide> const output = spawnSync(process.execPath, [ <ide> function nextdir() { <ide> assert.strictEqual(fixtureCoverage.functions[1].ranges[0].count, 1); <ide> } <ide> <del>// extracts the coverage object for a given fixture name. <add>// Extracts the coverage object for a given fixture name. <ide> function getFixtureCoverage(fixtureFile, coverageDirectory) { <ide> const coverageFiles = fs.readdirSync(coverageDirectory); <ide> for (const coverageFile of coverageFiles) { <ide><path>test/parallel/test-whatwg-url-custom-properties.js <ide> const expected = ['toString', <ide> <ide> assert.deepStrictEqual(props, expected); <ide> <del>// href is writable (not readonly) and is stringifier <add>// `href` is writable (not readonly) and is stringifier <ide> assert.strictEqual(url.toString(), url.href); <ide> url.href = 'http://user:pass@foo.bar.com:21/aaa/zzz?l=25#test'; <ide> assert.strictEqual(url.href, <ide><path>test/parallel/test-worker-uncaught-exception-async.js <ide> if (!process.env.HAS_STARTED_WORKER) { <ide> assert.strictEqual(code, 1); <ide> })); <ide> } else { <del> // cannot use common.mustCall as it cannot catch this <add> // Cannot use common.mustCall as it cannot catch this <ide> let called = false; <ide> process.on('exit', (code) => { <ide> if (!called) { <ide><path>test/parallel/test-worker-uncaught-exception.js <ide> if (!process.env.HAS_STARTED_WORKER) { <ide> assert.strictEqual(code, 1); <ide> })); <ide> } else { <del> // cannot use common.mustCall as it cannot catch this <add> // Cannot use common.mustCall as it cannot catch this <ide> let called = false; <ide> process.on('exit', (code) => { <ide> if (!called) { <ide><path>test/parallel/test-zlib-convenience-methods.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> 'use strict'; <del>// test convenience methods with and without options supplied <add>// Test convenience methods with and without options supplied <ide> <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide><path>test/parallel/test-zlib-destroy-pipe.js <ide> const common = require('../common'); <ide> const zlib = require('zlib'); <ide> const { Writable } = require('stream'); <ide> <del>// verify that the zlib transform does not error in case <add>// Verify that the zlib transform does not error in case <ide> // it is destroyed with data still in flight <ide> <ide> const ts = zlib.createGzip(); <ide><path>test/parallel/test-zlib-flush-drain.js <ide> const opts = { <ide> <ide> const deflater = zlib.createDeflate(opts); <ide> <del>// shim deflater.flush so we can count times executed <add>// Shim deflater.flush so we can count times executed <ide> let flushCount = 0; <ide> let drainCount = 0; <ide> <ide><path>test/parallel/test-zlib-from-concatenated-gzip.js <ide> fs.createReadStream(pmmFileGz) <ide> ); <ide> })); <ide> <del> // first write: write "abc" + the first bytes of "def" <add> // First write: write "abc" + the first bytes of "def" <ide> unzip.write(Buffer.concat([ <ide> abcEncoded, defEncoded.slice(0, offset) <ide> ])); <ide><path>test/parallel/test-zlib-from-gzip-with-trailing-garbage.js <ide> 'use strict'; <del>// test unzipping a gzip file that has trailing garbage <add>// Test unzipping a gzip file that has trailing garbage <ide> <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide><path>test/parallel/test-zlib-from-string.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> 'use strict'; <del>// test compressing and uncompressing a string with zlib <add>// Test compressing and uncompressing a string with zlib <ide> <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide><path>test/parallel/test-zlib-truncated.js <ide> 'use strict'; <del>// tests zlib streams with truncated compressed input <add>// Tests zlib streams with truncated compressed input <ide> <ide> require('../common'); <ide> const assert = require('assert'); <ide> const errMessage = /unexpected end of file/; <ide> <ide> const syncFlushOpt = { finishFlush: zlib.constants.Z_SYNC_FLUSH }; <ide> <del> // sync truncated input test, finishFlush = Z_SYNC_FLUSH <add> // Sync truncated input test, finishFlush = Z_SYNC_FLUSH <ide> const result = toUTF8(zlib[methods.decompSync](truncated, syncFlushOpt)); <ide> assert.strictEqual(result, inputString.substr(0, result.length)); <ide> <del> // async truncated input test, finishFlush = Z_SYNC_FLUSH <add> // Async truncated input test, finishFlush = Z_SYNC_FLUSH <ide> zlib[methods.decomp](truncated, syncFlushOpt, function(err, decompressed) { <ide> assert.ifError(err); <ide> const result = toUTF8(decompressed); <ide><path>test/parallel/test-zlib-write-after-flush.js <ide> gunz.on('end', common.mustCall(() => { <ide> assert.strictEqual(gzip._nextFlush, -1); <ide> })); <ide> <del>// make sure that flush/write doesn't trigger an assert failure <add>// Make sure that flush/write doesn't trigger an assert failure <ide> gzip.flush(); <ide> gzip.write(input); <ide> gzip.end(); <ide><path>test/parallel/test-zlib.js <ide> let windowBits = [8, 9, 10, 11, 12, 13, 14, 15]; <ide> let memLevel = [1, 2, 3, 4, 5, 6, 7, 8, 9]; <ide> let strategy = [0, 1, 2, 3, 4]; <ide> <del>// it's nice in theory to test every combination, but it <add>// It's nice in theory to test every combination, but it <ide> // takes WAY too long. Maybe a pummel test could do this? <ide> if (!process.env.PUMMEL) { <ide> trickle = [1024]; <ide> zlib.createDeflateRaw({ windowBits: 8 }); <ide> () => assert(Buffer.concat(raw).equals(Buffer.concat(reinflated))))); <ide> } <ide> <del>// for each of the files, make sure that compressing and <add>// For each of the files, make sure that compressing and <ide> // decompressing results in the same data, for every combination <ide> // of the options set above. <ide> <ide> testKeys.forEach(common.mustCall((file) => { <ide> const ss = new SlowStream(trickle); <ide> const buf = new BufferStream(); <ide> <del> // verify that the same exact buffer comes out the other end. <add> // Verify that the same exact buffer comes out the other end. <ide> buf.on('data', common.mustCall((c) => { <ide> const msg = `${file} ${chunkSize} ${ <ide> JSON.stringify(opts)} ${Def.name} -> ${Inf.name}`; <ide><path>test/pseudo-tty/test-async-wrap-getasyncid-tty.js <ide> // Flags: --expose-internals --no-warnings <ide> 'use strict'; <ide> <del>// see also test/sequential/test-async-wrap-getasyncid.js <add>// See also test/sequential/test-async-wrap-getasyncid.js <ide> <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide><path>test/pseudo-tty/test-handle-wrap-isrefed-tty.js <ide> // Flags: --expose-internals --no-warnings <ide> 'use strict'; <ide> <del>// see also test/parallel/test-handle-wrap-isrefed.js <add>// See also test/parallel/test-handle-wrap-isrefed.js <ide> <ide> const common = require('../common'); <ide> const strictEqual = require('assert').strictEqual; <ide><path>test/pummel/test-exec.js <ide> const killMeTwice = exec(SLEEP3_COMMAND, { timeout: 1000 }, <ide> <ide> process.nextTick(function() { <ide> console.log(`kill pid ${killMeTwice.pid}`); <del> // make sure there is no race condition in starting the process <add> // Make sure there is no race condition in starting the process <ide> // the PID SHOULD exist directly following the exec() call. <ide> assert.strictEqual(typeof killMeTwice._handle.pid, 'number'); <ide> // Kill the process <ide><path>test/pummel/test-process-hrtime.js <ide> while (Date.now() - now < 2000); <ide> // get a diff reading <ide> const diff = process.hrtime(start); <ide> <del>// should be at least 1 second, at most 2 seconds later <add>// Should be at least 1 second, at most 2 seconds later <ide> // (the while loop will usually exit a few nanoseconds before 2) <ide> assert(diff[0] >= 1); <ide> assert(diff[0] <= 2); <ide><path>test/sequential/test-cli-syntax-file-not-found.js <ide> const notFoundRE = /^Error: Cannot find module/m; <ide> // no stdout should be produced <ide> assert.strictEqual(stdout, ''); <ide> <del> // stderr should have a module not found error message <add> // `stderr` should have a module not found error message. <ide> assert(notFoundRE.test(stderr), `${notFoundRE} === ${stderr}`); <ide> <ide> assert.strictEqual(err.code, 1, <ide><path>test/sequential/test-fs-watch.js <ide> tmpdir.refresh(); <ide> fs.watch(__filename, { persistent: false }, common.mustNotCall()); <ide> } <ide> <del>// whitebox test to ensure that wrapped FSEvent is safe <add>// Whitebox test to ensure that wrapped FSEvent is safe <ide> // https://github.com/joyent/node/issues/6690 <ide> { <ide> let oldhandle; <ide><path>test/sequential/test-http-max-http-headers.js <ide> const timeout = common.platformTimeout(10); <ide> function writeHeaders(socket, headers) { <ide> const array = []; <ide> <del> // this is off from 1024 so that \r\n does not get split <add> // This is off from 1024 so that \r\n does not get split <ide> const chunkSize = 1000; <ide> let last = 0; <ide> <ide><path>test/sequential/test-module-loading.js <ide> assert.strictEqual(require.main.id, '.'); <ide> assert.strictEqual(require.main, module); <ide> assert.strictEqual(process.mainModule, module); <ide> <del>// assert that it's *not* the main module in the required module. <add>// Assert that it's *not* the main module in the required module. <ide> require('../fixtures/not-main-module.js'); <ide> <ide> { <del> // require a file with a request that includes the extension <add> // Require a file with a request that includes the extension <ide> const a_js = require('../fixtures/a.js'); <ide> assert.strictEqual(a_js.number, 42); <ide> } <ide> require('../fixtures/node_modules/foo'); <ide> <ide> { <ide> console.error('test name clashes'); <del> // this one exists and should import the local module <add> // This one exists and should import the local module <ide> const my_path = require('../fixtures/path'); <ide> assert.ok(my_path.path_func instanceof Function); <ide> // this one does not exist and should throw <ide> try { <ide> <ide> <ide> { <del> // now verify that module.children contains all the different <add> // Now verify that module.children contains all the different <ide> // modules that we've required, and that all of them contain <ide> // the appropriate children, and so on. <ide> <ide><path>test/sequential/test-next-tick-error-spin.js <ide> if (process.argv[2] !== 'child') { <ide> const domain = require('domain'); <ide> const d = domain.create(); <ide> <del> // in the error handler, we trigger several MakeCallback events <add> // In the error handler, we trigger several MakeCallback events <ide> d.on('error', function() { <ide> console.log('a'); <ide> console.log('b'); <ide><path>test/sequential/test-timers-set-interval-excludes-callback-duration.js <ide> const t = setInterval(() => { <ide> cntr++; <ide> if (cntr === 1) { <ide> common.busyLoop(100); <del> // ensure that the event loop passes before the second interval <add> // Ensure that the event loop passes before the second interval <ide> setImmediate(() => assert.strictEqual(cntr, 1)); <ide> first = Date.now(); <ide> } else if (cntr === 2) { <ide><path>tools/doc/html.js <ide> function preprocessElements({ filename }) { <ide> const noLinking = filename.includes('documentation') && <ide> heading !== null && heading.children[0].value === 'Stability Index'; <ide> <del> // collapse blockquote and paragraph into a single node <add> // Collapse blockquote and paragraph into a single node <ide> node.type = 'paragraph'; <ide> node.children.shift(); <ide> node.children.unshift(...paragraph.children);
200
Ruby
Ruby
kick boot_test back to life
94a83007b60f6e7cdadd05513ccda9bfe689c719
<ide><path>railties/test/boot_test.rb <ide> require 'abstract_unit' <ide> require 'initializer' <del>require "#{File.dirname(__FILE__)}/../environments/boot" <add>require "#{File.dirname(__FILE__)}/../lib/generator/templates/app/config/boot" <ide> require 'rails/gem_dependency' <ide> <ide> class BootTest < Test::Unit::TestCase
1
Go
Go
add test on archive.go
c4fe5dad1deb45ecde460d7627523dbf032dc205
<ide><path>pkg/archive/archive.go <ide> func Tar(path string, compression Compression) (io.ReadCloser, error) { <ide> return TarWithOptions(path, &TarOptions{Compression: compression}) <ide> } <ide> <del>func escapeName(name string) string { <del> escaped := make([]byte, 0) <del> for i, c := range []byte(name) { <del> if i == 0 && c == '/' { <del> continue <del> } <del> // all printable chars except "-" which is 0x2d <del> if (0x20 <= c && c <= 0x7E) && c != 0x2d { <del> escaped = append(escaped, c) <del> } else { <del> escaped = append(escaped, fmt.Sprintf("\\%03o", c)...) <del> } <del> } <del> return string(escaped) <del>} <del> <ide> // TarWithOptions creates an archive from the directory at `path`, only including files whose relative <ide> // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { <ide><path>pkg/archive/archive_test.go <ide> import ( <ide> "testing" <ide> "time" <ide> <add> "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar" <ide> ) <ide> <add>func TestIsArchiveNilHeader(t *testing.T) { <add> out := IsArchive(nil) <add> if out { <add> t.Fatalf("isArchive should return false as nil is not a valid archive header") <add> } <add>} <add> <add>func TestIsArchiveInvalidHeader(t *testing.T) { <add> header := []byte{0x00, 0x01, 0x02} <add> out := IsArchive(header) <add> if out { <add> t.Fatalf("isArchive should return false as %s is not a valid archive header", header) <add> } <add>} <add> <add>func TestIsArchiveBzip2(t *testing.T) { <add> header := []byte{0x42, 0x5A, 0x68} <add> out := IsArchive(header) <add> if !out { <add> t.Fatalf("isArchive should return true as %s is a bz2 header", header) <add> } <add>} <add> <add>func TestIsArchive7zip(t *testing.T) { <add> header := []byte{0x50, 0x4b, 0x03, 0x04} <add> out := IsArchive(header) <add> if out { <add> t.Fatalf("isArchive should return false as %s is a 7z header and it is not supported", header) <add> } <add>} <add> <add>func TestDecompressStreamGzip(t *testing.T) { <add> cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && gzip -f /tmp/archive") <add> output, err := cmd.CombinedOutput() <add> if err != nil { <add> t.Fatalf("Fail to create an archive file for test : %s.", output) <add> } <add> archive, err := os.Open("/tmp/archive.gz") <add> _, err = DecompressStream(archive) <add> if err != nil { <add> t.Fatalf("Failed to decompress a gzip file.") <add> } <add>} <add> <add>func TestDecompressStreamBzip2(t *testing.T) { <add> cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && bzip2 -f /tmp/archive") <add> output, err := cmd.CombinedOutput() <add> if err != nil { <add> t.Fatalf("Fail to create an archive file for test : %s.", output) <add> } <add> archive, err := os.Open("/tmp/archive.bz2") <add> _, err = DecompressStream(archive) <add> if err != nil { <add> t.Fatalf("Failed to decompress a bzip2 file.") <add> } <add>} <add> <add>func TestDecompressStreamXz(t *testing.T) { <add> cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && xz -f /tmp/archive") <add> output, err := cmd.CombinedOutput() <add> if err != nil { <add> t.Fatalf("Fail to create an archive file for test : %s.", output) <add> } <add> archive, err := os.Open("/tmp/archive.xz") <add> _, err = DecompressStream(archive) <add> if err != nil { <add> t.Fatalf("Failed to decompress a xz file.") <add> } <add>} <add> <add>func TestCompressStreamXzUnsuported(t *testing.T) { <add> dest, err := os.Create("/tmp/dest") <add> if err != nil { <add> t.Fatalf("Fail to create the destination file") <add> } <add> _, err = CompressStream(dest, Xz) <add> if err == nil { <add> t.Fatalf("Should fail as xz is unsupported for compression format.") <add> } <add>} <add> <add>func TestCompressStreamBzip2Unsupported(t *testing.T) { <add> dest, err := os.Create("/tmp/dest") <add> if err != nil { <add> t.Fatalf("Fail to create the destination file") <add> } <add> _, err = CompressStream(dest, Xz) <add> if err == nil { <add> t.Fatalf("Should fail as xz is unsupported for compression format.") <add> } <add>} <add> <add>func TestCompressStreamInvalid(t *testing.T) { <add> dest, err := os.Create("/tmp/dest") <add> if err != nil { <add> t.Fatalf("Fail to create the destination file") <add> } <add> _, err = CompressStream(dest, -1) <add> if err == nil { <add> t.Fatalf("Should fail as xz is unsupported for compression format.") <add> } <add>} <add> <add>func TestExtensionInvalid(t *testing.T) { <add> compression := Compression(-1) <add> output := compression.Extension() <add> if output != "" { <add> t.Fatalf("The extension of an invalid compression should be an empty string.") <add> } <add>} <add> <add>func TestExtensionUncompressed(t *testing.T) { <add> compression := Uncompressed <add> output := compression.Extension() <add> if output != "tar" { <add> t.Fatalf("The extension of a uncompressed archive should be 'tar'.") <add> } <add>} <add>func TestExtensionBzip2(t *testing.T) { <add> compression := Bzip2 <add> output := compression.Extension() <add> if output != "tar.bz2" { <add> t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'") <add> } <add>} <add>func TestExtensionGzip(t *testing.T) { <add> compression := Gzip <add> output := compression.Extension() <add> if output != "tar.gz" { <add> t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'") <add> } <add>} <add>func TestExtensionXz(t *testing.T) { <add> compression := Xz <add> output := compression.Extension() <add> if output != "tar.xz" { <add> t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'") <add> } <add>} <add> <ide> func TestCmdStreamLargeStderr(t *testing.T) { <ide> cmd := exec.Command("/bin/sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello") <ide> out, err := CmdStream(cmd, nil) <ide> func TestTarUntar(t *testing.T) { <ide> } <ide> } <ide> <add>func TestTarUntarWithXattr(t *testing.T) { <add> origin, err := ioutil.TempDir("", "docker-test-untar-origin") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(origin) <add> if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { <add> t.Fatal(err) <add> } <add> if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { <add> t.Fatal(err) <add> } <add> if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil { <add> t.Fatal(err) <add> } <add> if err := system.Lsetxattr(path.Join(origin, "2"), "security.capability", []byte{0x00}, 0); err != nil { <add> t.Fatal(err) <add> } <add> <add> for _, c := range []Compression{ <add> Uncompressed, <add> Gzip, <add> } { <add> changes, err := tarUntar(t, origin, &TarOptions{ <add> Compression: c, <add> ExcludePatterns: []string{"3"}, <add> }) <add> <add> if err != nil { <add> t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err) <add> } <add> <add> if len(changes) != 1 || changes[0].Path != "/3" { <add> t.Fatalf("Unexpected differences after tarUntar: %v", changes) <add> } <add> capability, _ := system.Lgetxattr(path.Join(origin, "2"), "security.capability") <add> if capability == nil && capability[0] != 0x00 { <add> t.Fatalf("Untar should have kept the 'security.capability' xattr.") <add> } <add> } <add>} <add> <ide> func TestTarWithOptions(t *testing.T) { <ide> origin, err := ioutil.TempDir("", "docker-test-untar-origin") <ide> if err != nil { <ide> t.Fatal(err) <ide> } <add> if _, err := ioutil.TempDir(origin, "folder"); err != nil { <add> t.Fatal(err) <add> } <ide> defer os.RemoveAll(origin) <ide> if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { <ide> t.Fatal(err) <ide> func TestTarWithOptions(t *testing.T) { <ide> opts *TarOptions <ide> numChanges int <ide> }{ <del> {&TarOptions{IncludeFiles: []string{"1"}}, 1}, <add> {&TarOptions{IncludeFiles: []string{"1"}}, 2}, <ide> {&TarOptions{ExcludePatterns: []string{"2"}}, 1}, <add> {&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2}, <add> {&TarOptions{IncludeFiles: []string{"1", "1"}}, 2}, <add> {&TarOptions{Name: "test", IncludeFiles: []string{"1"}}, 4}, <ide> } <ide> for _, testCase := range cases { <ide> changes, err := tarUntar(t, origin, testCase.opts) <ide> func TestUntarUstarGnuConflict(t *testing.T) { <ide> } <ide> } <ide> <add>func TestTarWithBlockCharFifo(t *testing.T) { <add> origin, err := ioutil.TempDir("", "docker-test-tar-hardlink") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(origin) <add> if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { <add> t.Fatal(err) <add> } <add> if err := system.Mknod(path.Join(origin, "2"), syscall.S_IFBLK, int(system.Mkdev(int64(12), int64(5)))); err != nil { <add> t.Fatal(err) <add> } <add> if err := system.Mknod(path.Join(origin, "3"), syscall.S_IFCHR, int(system.Mkdev(int64(12), int64(5)))); err != nil { <add> t.Fatal(err) <add> } <add> if err := system.Mknod(path.Join(origin, "4"), syscall.S_IFIFO, int(system.Mkdev(int64(12), int64(5)))); err != nil { <add> t.Fatal(err) <add> } <add> <add> dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(dest) <add> <add> // we'll do this in two steps to separate failure <add> fh, err := Tar(origin, Uncompressed) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> // ensure we can read the whole thing with no error, before writing back out <add> buf, err := ioutil.ReadAll(fh) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> bRdr := bytes.NewReader(buf) <add> err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed}) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> changes, err := ChangesDirs(origin, dest) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if len(changes) > 0 { <add> t.Fatalf("Tar with special device (block, char, fifo) should keep them (recreate them when untar) : %s", changes) <add> } <add>} <add> <ide> func TestTarWithHardLink(t *testing.T) { <ide> origin, err := ioutil.TempDir("", "docker-test-tar-hardlink") <ide> if err != nil {
2
Java
Java
fix issue with requestbody(required=true)
de1a41ac275da81ead9dfd241c6ca1266adab75a
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, <ide> final HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); <ide> HttpInputMessage inputMessage = new ServletServerHttpRequest(servletRequest); <ide> <del> RequestBody annot = methodParam.getParameterAnnotation(RequestBody.class); <del> if (!annot.required()) { <del> InputStream inputStream = inputMessage.getBody(); <del> if (inputStream == null) { <del> return null; <add> InputStream inputStream = inputMessage.getBody(); <add> if (inputStream == null) { <add> return handleEmptyBody(methodParam); <add> } <add> else if (inputStream.markSupported()) { <add> inputStream.mark(1); <add> if (inputStream.read() == -1) { <add> return handleEmptyBody(methodParam); <ide> } <del> else if (inputStream.markSupported()) { <del> inputStream.mark(1); <del> if (inputStream.read() == -1) { <del> return null; <del> } <del> inputStream.reset(); <add> inputStream.reset(); <add> } <add> else { <add> final PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream); <add> int b = pushbackInputStream.read(); <add> if (b == -1) { <add> return handleEmptyBody(methodParam); <ide> } <ide> else { <del> final PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream); <del> int b = pushbackInputStream.read(); <del> if (b == -1) { <del> return null; <del> } <del> else { <del> pushbackInputStream.unread(b); <del> } <del> inputMessage = new ServletServerHttpRequest(servletRequest) { <del> @Override <del> public InputStream getBody() throws IOException { <del> // Form POST should not get here <del> return pushbackInputStream; <del> } <del> }; <add> pushbackInputStream.unread(b); <ide> } <add> inputMessage = new ServletServerHttpRequest(servletRequest) { <add> @Override <add> public InputStream getBody() throws IOException { <add> // Form POST should not get here <add> return pushbackInputStream; <add> } <add> }; <ide> } <ide> <ide> return super.readWithMessageConverters(inputMessage, methodParam, paramType); <ide> } <ide> <add> private Object handleEmptyBody(MethodParameter param) { <add> if (param.getParameterAnnotation(RequestBody.class).required()) { <add> throw new HttpMessageNotReadableException("Required request body content is missing: " + param); <add> } <add> return null; <add> } <add> <ide> @Override <ide> public void handleReturnValue(Object returnValue, MethodParameter returnType, <ide> ModelAndViewContainer mavContainer, NativeWebRequest webRequest) <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import java.io.IOException; <ide> import java.lang.reflect.Method; <add>import java.nio.charset.Charset; <ide> import java.util.Arrays; <ide> import java.util.Collections; <ide> import java.util.List; <ide> import org.springframework.http.HttpOutputMessage; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.converter.HttpMessageConverter; <add>import org.springframework.http.converter.HttpMessageNotReadableException; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.mock.web.test.MockHttpServletResponse; <ide> import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; <ide> public void resolveArgument() throws Exception { <ide> servletRequest.addHeader("Content-Type", contentType.toString()); <ide> <ide> String body = "Foo"; <del> servletRequest.setContent(body.getBytes()); <add> servletRequest.setContent(body.getBytes(Charset.forName("UTF-8"))); <ide> <ide> given(messageConverter.canRead(String.class, contentType)).willReturn(true); <ide> given(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body); <ide> public void resolveArgumentNotValid() throws Exception { <ide> try { <ide> testResolveArgumentWithValidation(new SimpleBean(null)); <ide> fail("Expected exception"); <del> } catch (MethodArgumentNotValidException e) { <add> } <add> catch (MethodArgumentNotValidException e) { <ide> assertEquals("simpleBean", e.getBindingResult().getObjectName()); <ide> assertEquals(1, e.getBindingResult().getErrorCount()); <ide> assertNotNull(e.getBindingResult().getFieldError("name")); <ide> public void resolveArgumentValid() throws Exception { <ide> private void testResolveArgumentWithValidation(SimpleBean simpleBean) throws IOException, Exception { <ide> MediaType contentType = MediaType.TEXT_PLAIN; <ide> servletRequest.addHeader("Content-Type", contentType.toString()); <del> servletRequest.setContent(new byte[] {}); <add> servletRequest.setContent("payload".getBytes(Charset.forName("UTF-8"))); <ide> <ide> @SuppressWarnings("unchecked") <ide> HttpMessageConverter<SimpleBean> beanConverter = mock(HttpMessageConverter.class); <ide> private void testResolveArgumentWithValidation(SimpleBean simpleBean) throws IOE <ide> public void resolveArgumentCannotRead() throws Exception { <ide> MediaType contentType = MediaType.TEXT_PLAIN; <ide> servletRequest.addHeader("Content-Type", contentType.toString()); <add> servletRequest.setContent("payload".getBytes(Charset.forName("UTF-8"))); <ide> <ide> given(messageConverter.canRead(String.class, contentType)).willReturn(false); <ide> <ide> public void resolveArgumentCannotRead() throws Exception { <ide> <ide> @Test <ide> public void resolveArgumentNoContentType() throws Exception { <add> servletRequest.setContent("payload".getBytes(Charset.forName("UTF-8"))); <ide> given(messageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false); <ide> try { <ide> processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); <ide> public void resolveArgumentNoContentType() throws Exception { <ide> @Test(expected = HttpMediaTypeNotSupportedException.class) <ide> public void resolveArgumentInvalidContentType() throws Exception { <ide> this.servletRequest.setContentType("bad"); <add> servletRequest.setContent("payload".getBytes(Charset.forName("UTF-8"))); <ide> processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); <ide> } <ide> <add> // SPR-9942 <add> <add> @Test(expected = HttpMessageNotReadableException.class) <add> public void resolveArgumentRequiredNoContent() throws Exception { <add> servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE); <add> servletRequest.setContent(new byte[0]); <add> given(messageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true); <add> given(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(null); <add> assertNull(processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, new ValidatingBinderFactory())); <add> } <add> <ide> @Test <ide> public void resolveArgumentNotRequiredNoContent() throws Exception { <del> servletRequest.setContent(null); <del> assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, new ValidatingBinderFactory())); <del> <ide> servletRequest.setContent(new byte[0]); <ide> assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, new ValidatingBinderFactory())); <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.http.ResponseEntity; <ide> import org.springframework.http.converter.ByteArrayHttpMessageConverter; <ide> import org.springframework.http.converter.HttpMessageConverter; <add>import org.springframework.http.converter.HttpMessageNotReadableException; <ide> import org.springframework.http.converter.StringHttpMessageConverter; <ide> import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; <ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; <ide> public void resolveArgumentClassString() throws Exception { <ide> assertEquals("foobarbaz", result); <ide> } <ide> <add> // SPR-9942 <add> <add> @Test(expected = HttpMessageNotReadableException.class) <add> public void resolveArgumentRequiredNoContent() throws Exception { <add> this.servletRequest.setContent(new byte[0]); <add> this.servletRequest.setContentType("text/plain"); <add> List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); <add> converters.add(new StringHttpMessageConverter()); <add> RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters); <add> processor.resolveArgument(paramString, mavContainer, webRequest, binderFactory); <add> } <add> <ide> // SPR-9964 <ide> <ide> @Test
3
Javascript
Javascript
improve template value for test message
f7436ba1358f6af30d7d9baffdbef8754573f0e5
<ide><path>test/parallel/test-cluster-master-kill.js <ide> if (cluster.isWorker) { <ide> process.once('exit', () => { <ide> assert.strictEqual(typeof pid, 'number', <ide> `got ${pid} instead of a worker pid`); <del> assert.strictEqual(alive, false, 'worker was alive after master died'); <add> assert.strictEqual(alive, false, <add> `worker was alive after master died (alive = ${alive})`); <ide> }); <ide> <ide> }
1
Javascript
Javascript
update numberkeyframetrack inheritance
aaf9f49525dd42599b8729564691923749fc6d55
<ide><path>src/animation/tracks/NumberKeyframeTrack.js <del>import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype.js'; <del>import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor.js'; <add>import { KeyframeTrack } from '../KeyframeTrack.js'; <ide> <ide> /** <ide> * <ide> import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor.js'; <ide> <ide> function NumberKeyframeTrack( name, times, values, interpolation ) { <ide> <del> KeyframeTrackConstructor.call( this, name, times, values, interpolation ); <add> KeyframeTrack.call( this, name, times, values, interpolation ); <ide> <ide> } <ide> <del>NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrackPrototype ), { <add>NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { <ide> <ide> constructor: NumberKeyframeTrack, <ide>
1
Ruby
Ruby
move llvm method to failswithllvm
962f4fa9ef4492fa62fc4c8aa6d827fa6d3f3590
<ide><path>Library/Homebrew/formula.rb <ide> def brew <ide> validate_variable :name <ide> validate_variable :version <ide> <del> handle_llvm_failure(fails_with_llvm?) if fails_with_llvm? <add> fails_with_llvm?.handle_failure if fails_with_llvm? <ide> <ide> stage do <ide> begin <ide> def std_cmake_parameters <ide> "-DCMAKE_INSTALL_PREFIX='#{prefix}' -DCMAKE_BUILD_TYPE=None -Wno-dev" <ide> end <ide> <del> def handle_llvm_failure llvm <del> if ENV.compiler == :llvm <del> # version 2336 is the latest version as of Xcode 4.2, so it is the <del> # latest version we have tested against so we will switch to GCC and <del> # bump this integer when Xcode 4.3 is released. TODO do that! <del> if llvm.build.to_i >= 2336 <del> if MacOS.xcode_version < "4.2" <del> opoo "Formula will not build with LLVM, using GCC" <del> ENV.gcc <del> else <del> opoo "Formula will not build with LLVM, trying Clang" <del> ENV.clang <del> end <del> return <del> end <del> opoo "Building with LLVM, but this formula is reported to not work with LLVM:" <del> puts <del> puts llvm.reason <del> puts <del> puts <<-EOS.undent <del> We are continuing anyway so if the build succeeds, please open a ticket with <del> the following information: #{MacOS.llvm_build_version}-#{MACOS_VERSION}. So <del> that we can update the formula accordingly. Thanks! <del> EOS <del> puts <del> if MacOS.xcode_version < "4.2" <del> puts "If it doesn't work you can: brew install --use-gcc" <del> else <del> puts "If it doesn't work you can try: brew install --use-clang" <del> end <del> puts <del> end <del> end <del> <ide> def self.class_s name <ide> #remove invalid characters and then camelcase it <ide> name.capitalize.gsub(/[-_.\s]([a-zA-Z0-9])/) { $1.upcase } \ <ide><path>Library/Homebrew/formula_support.rb <ide> def reason <ide> s += "\n" <ide> return s <ide> end <add> <add> def handle_failure <add> return unless ENV.compiler == :llvm <add> <add> # version 2336 is the latest version as of Xcode 4.2, so it is the <add> # latest version we have tested against so we will switch to GCC and <add> # bump this integer when Xcode 4.3 is released. TODO do that! <add> if build.to_i >= 2336 <add> if MacOS.xcode_version < "4.2" <add> opoo "Formula will not build with LLVM, using GCC" <add> ENV.gcc <add> else <add> opoo "Formula will not build with LLVM, trying Clang" <add> ENV.clang <add> end <add> return <add> end <add> opoo "Building with LLVM, but this formula is reported to not work with LLVM:" <add> puts <add> puts reason <add> puts <add> puts <<-EOS.undent <add> We are continuing anyway so if the build succeeds, please open a ticket with <add> the following information: #{MacOS.llvm_build_version}-#{MACOS_VERSION}. So <add> that we can update the formula accordingly. Thanks! <add> EOS <add> puts <add> if MacOS.xcode_version < "4.2" <add> puts "If it doesn't work you can: brew install --use-gcc" <add> else <add> puts "If it doesn't work you can try: brew install --use-clang" <add> end <add> puts <add> end <ide> end
2
PHP
PHP
use less inflection on aliasing. add tests
a85f9573e3eee515cc6a4ba1b5c56200f9aaa1cc
<ide><path>src/ORM/Locator/TableLocator.php <ide> public function getConfig(?string $alias = null): array <ide> * key in the registry. This means that if two plugins, or a plugin and app provide <ide> * the same alias, the registry will only store the first instance. <ide> * <del> * @param string $alias The alias name you want to get. Must be in CamelCase format. <add> * @param string $alias The alias name you want to get. Should be in CamelCase format. <ide> * @param array $options The options you want to build the table with. <ide> * If a table has already been loaded the options will be ignored. <ide> * @return \Cake\ORM\Table <ide> public function get(string $alias, array $options = []): Table <ide> /** <ide> * Gets the table class name. <ide> * <del> * @param string $alias The alias name you want to get. Must be in CamelCase format. <add> * @param string $alias The alias name you want to get. Should be in CamelCase format. <ide> * @param array $options Table options array. <ide> * @return string|null <ide> */ <ide><path>tests/TestCase/ORM/Locator/TableLocatorTest.php <ide> public function testExists() <ide> $this->assertTrue($this->_locator->exists('Articles')); <ide> } <ide> <add> /** <add> * Tests the casing and locator. Using table name directly is not <add> * the same as using conventional aliases anymore. <add> * <add> * @return void <add> */ <add> public function testCasing() <add> { <add> $this->assertFalse($this->_locator->exists('Articles')); <add> <add> $Article = $this->_locator->get('Articles', ['table' => 'articles']); <add> $this->assertTrue($this->_locator->exists('Articles')); <add> <add> $this->assertFalse($this->_locator->exists('articles')); <add> <add> $article = $this->_locator->get('articles'); <add> $this->assertTrue($this->_locator->exists('articles')); <add> <add> $this->assertNotSame($Article, $article); <add> } <add> <ide> /** <ide> * Test the exists() method with plugin-prefixed models. <ide> *
2
Text
Text
clarify ambiguous rdev description
584fc7e965d0425346325a03c3288c6f885ae649
<ide><path>doc/api/fs.md <ide> The numeric group identifier of the group that owns the file (POSIX). <ide> <ide> * {number|bigint} <ide> <del>A numeric device identifier if the file is considered "special". <add>A numeric device identifier if the file represents a device. <ide> <ide> ### `stats.size` <ide>
1
Go
Go
move "unpause" to daemon/pause.go
63bd4ad9d6d0c55691ff33cbfd24684ef91649e4
<ide><path>daemon/daemon.go <ide> func (daemon *Daemon) Install(eng *engine.Engine) error { <ide> if err := eng.Register("pause", daemon.ContainerPause); err != nil { <ide> return err <ide> } <add> if err := eng.Register("unpause", daemon.ContainerUnpause); err != nil { <add> return err <add> } <ide> return nil <ide> } <ide> <ide><path>daemon/pause.go <ide> func (daemon *Daemon) ContainerPause(job *engine.Job) engine.Status { <ide> job.Eng.Job("log", "pause", container.ID, daemon.Repositories().ImageName(container.Image)).Run() <ide> return engine.StatusOK <ide> } <add> <add>func (daemon *Daemon) ContainerUnpause(job *engine.Job) engine.Status { <add> if n := len(job.Args); n < 1 || n > 2 { <add> return job.Errorf("Usage: %s CONTAINER", job.Name) <add> } <add> name := job.Args[0] <add> container := daemon.Get(name) <add> if container == nil { <add> return job.Errorf("No such container: %s", name) <add> } <add> if err := container.Unpause(); err != nil { <add> return job.Errorf("Cannot unpause container %s: %s", name, err) <add> } <add> job.Eng.Job("log", "unpause", container.ID, daemon.Repositories().ImageName(container.Image)).Run() <add> return engine.StatusOK <add>} <ide><path>server/container.go <ide> import ( <ide> "github.com/docker/docker/utils" <ide> ) <ide> <del>func (srv *Server) ContainerUnpause(job *engine.Job) engine.Status { <del> if n := len(job.Args); n < 1 || n > 2 { <del> return job.Errorf("Usage: %s CONTAINER", job.Name) <del> } <del> name := job.Args[0] <del> container := srv.daemon.Get(name) <del> if container == nil { <del> return job.Errorf("No such container: %s", name) <del> } <del> if err := container.Unpause(); err != nil { <del> return job.Errorf("Cannot unpause container %s: %s", name, err) <del> } <del> srv.LogEvent("unpause", container.ID, srv.daemon.Repositories().ImageName(container.Image)) <del> return engine.StatusOK <del>} <del> <ide> // ContainerKill send signal to the container <ide> // If no signal is given (sig 0), then Kill with SIGKILL and wait <ide> // for the container to exit. <ide><path>server/init.go <ide> func InitServer(job *engine.Job) engine.Status { <ide> "restart": srv.ContainerRestart, <ide> "start": srv.ContainerStart, <ide> "kill": srv.ContainerKill, <del> "unpause": srv.ContainerUnpause, <ide> "wait": srv.ContainerWait, <ide> "tag": srv.ImageTag, // FIXME merge with "image_tag" <ide> "resize": srv.ContainerResize,
4
Javascript
Javascript
fix clicks in mobile safari
4deb0d619c06e8f0d30f972a6412d65f19b7f921
<ide><path>src/core/ReactDefaultInjection.js <ide> var ChangeEventPlugin = require('ChangeEventPlugin'); <ide> var EventPluginHub = require('EventPluginHub'); <ide> var ReactInstanceHandles = require('ReactInstanceHandles'); <ide> var SimpleEventPlugin = require('SimpleEventPlugin'); <add>var MobileSafariClickEventPlugin = require('MobileSafariClickEventPlugin'); <ide> <ide> function inject() { <ide> /** <ide> function inject() { <ide> EventPluginHub.injection.injectEventPluginsByName({ <ide> 'SimpleEventPlugin': SimpleEventPlugin, <ide> 'EnterLeaveEventPlugin': EnterLeaveEventPlugin, <del> 'ChangeEventPlugin': ChangeEventPlugin <add> 'ChangeEventPlugin': ChangeEventPlugin, <add> 'MobileSafariClickEventPlugin': MobileSafariClickEventPlugin <ide> }); <ide> <ide> ReactDOM.injection.injectComponentClasses({ <ide><path>src/eventPlugins/DefaultEventPluginOrder.js <ide> var DefaultEventPluginOrder = [ <ide> keyOf({TapEventPlugin: null}), <ide> keyOf({EnterLeaveEventPlugin: null}), <ide> keyOf({ChangeEventPlugin: null}), <del> keyOf({AnalyticsEventPlugin: null}) <add> keyOf({AnalyticsEventPlugin: null}), <add> keyOf({MobileSafariClickEventPlugin: null}) <ide> ]; <ide> <ide> module.exports = DefaultEventPluginOrder; <ide><path>src/eventPlugins/MobileSafariClickEventPlugin.js <add>/** <add> * Copyright 2013 Facebook, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> * <add> * @providesModule MobileSafariClickEventPlugin <add> * @typechecks static-only <add> */ <add> <add>"use strict"; <add> <add>var EventConstants = require('EventConstants'); <add> <add>var emptyFunction = require('emptyFunction'); <add> <add>var topLevelTypes = EventConstants.topLevelTypes; <add> <add>/** <add> * Mobile Safari does not fire properly bubble click events on non-interactive <add> * elements, which means delegated click listeners do not fire. The workaround <add> * for this bug involves attaching an empty click listener on the target node. <add> * <add> * This particular plugin works around the bug by attaching an empty click <add> * listener on `touchstart` (which does fire on every element). <add> */ <add>var MobileSafariClickEventPlugin = { <add> <add> eventTypes: null, <add> <add> /** <add> * @param {string} topLevelType Record from `EventConstants`. <add> * @param {DOMEventTarget} topLevelTarget The listening component root node. <add> * @param {string} topLevelTargetID ID of `topLevelTarget`. <add> * @param {object} nativeEvent Native browser event. <add> * @return {*} An accumulation of synthetic events. <add> * @see {EventPluginHub.extractEvents} <add> */ <add> extractEvents: function( <add> topLevelType, <add> topLevelTarget, <add> topLevelTargetID, <add> nativeEvent) { <add> if (topLevelType === topLevelTypes.topTouchStart) { <add> var target = nativeEvent.target; <add> if (target && !target.onclick) { <add> target.onclick = emptyFunction; <add> } <add> } <add> } <add> <add>}; <add> <add>module.exports = MobileSafariClickEventPlugin;
3
Text
Text
update urls in readme.md to point to v7.3.0
79edf5b9f11bfa04232481f4654e8396286528f5
<ide><path>README.md <ide> Thanks to the awesome folks over at [Fastly][fastly], there's a free, CDN hosted version of Video.js that anyone can use. Add these tags to your document's `<head>`: <ide> <ide> ```html <del><link href="//vjs.zencdn.net/7.2/video-js.min.css" rel="stylesheet"> <del><script src="//vjs.zencdn.net/7.2/video.min.js"></script> <add><link href="//vjs.zencdn.net/7.3.0/video-js.min.css" rel="stylesheet"> <add><script src="//vjs.zencdn.net/7.3.0/video.min.js"></script> <ide> ``` <ide> <ide> > For the latest version of video.js and URLs to use, check out the [Getting Started][getting-started] page on our website.
1
PHP
PHP
add missing methods to the job contract
a38141968d3ce58f9b54b31ee970c14c7d48edbe
<ide><path>src/Illuminate/Contracts/Queue/Job.php <ide> public function getName(); <ide> * @return string <ide> */ <ide> public function getQueue(); <add> <add> /** <add> * Determine if the job has been deleted or released. <add> * <add> * @return bool <add> */ <add> public function isDeletedOrReleased(); <add> <add> /** <add> * Determine if the job has been deleted. <add> * <add> * @return bool <add> */ <add> public function isDeleted(); <add> <add> /** <add> * Get the raw body string for the job. <add> * <add> * @return string <add> */ <add> public function getRawBody(); <add> <add> /** <add> * Call the failed method on the job instance. <add> * <add> * @return void <add> */ <add> public function failed(); <ide> }
1
PHP
PHP
fix typo and cs error
b9f0f3c4e22026615b98db7b2ac416504e845604
<ide><path>tests/TestCase/Console/Command/Task/TestTaskTest.php <ide> public function testExecuteWithTwoArgs() { <ide> $this->Task->execute(); <ide> } <ide> <del> <ide> /** <ide> * Test generating class options for table. <ide> * <ide> public function testGetRealClassname($type, $name, $expected) { <ide> * @return void <ide> */ <ide> public function testGetRealClassnamePlugin() { <del> Plugin::load('TestPLugin'); <add> Plugin::load('TestPlugin'); <ide> $this->Task->plugin = 'TestPlugin'; <ide> $result = $this->Task->getRealClassname('Helper', 'Asset'); <ide> $expected = 'TestPlugin\View\Helper\AssetHelper';
1
Go
Go
remove engine from links
7560018541192ebdfe16e39515f9a04b44635d84
<ide><path>daemon/container.go <ide> func (container *Container) setupLinkedContainers() ([]string, error) { <ide> linkAlias, <ide> child.Config.Env, <ide> child.Config.ExposedPorts, <del> daemon.eng) <add> ) <ide> <ide> if err != nil { <ide> rollback() <ide><path>links/links.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/docker/docker/daemon/networkdriver/bridge" <del> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/nat" <ide> ) <ide> <ide> type Link struct { <ide> ChildEnvironment []string <ide> Ports []nat.Port <ide> IsEnabled bool <del> eng *engine.Engine <ide> } <ide> <del>func NewLink(parentIP, childIP, name string, env []string, exposedPorts map[nat.Port]struct{}, eng *engine.Engine) (*Link, error) { <add>func NewLink(parentIP, childIP, name string, env []string, exposedPorts map[nat.Port]struct{}) (*Link, error) { <ide> <ide> var ( <ide> i int <ide> func NewLink(parentIP, childIP, name string, env []string, exposedPorts map[nat. <ide> ParentIP: parentIP, <ide> ChildEnvironment: env, <ide> Ports: ports, <del> eng: eng, <ide> } <ide> return l, nil <ide> <ide><path>links/links_test.go <ide> package links <ide> <ide> import ( <ide> "fmt" <del> "github.com/docker/docker/nat" <ide> "strings" <ide> "testing" <add> <add> "github.com/docker/docker/nat" <ide> ) <ide> <ide> func TestLinkNaming(t *testing.T) { <ide> ports := make(nat.PortSet) <ide> ports[nat.Port("6379/tcp")] = struct{}{} <ide> <del> link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker-1", nil, ports, nil) <add> link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker-1", nil, ports) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestLinkNew(t *testing.T) { <ide> ports := make(nat.PortSet) <ide> ports[nat.Port("6379/tcp")] = struct{}{} <ide> <del> link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", nil, ports, nil) <add> link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", nil, ports) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestLinkEnv(t *testing.T) { <ide> ports := make(nat.PortSet) <ide> ports[nat.Port("6379/tcp")] = struct{}{} <ide> <del> link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", []string{"PASSWORD=gordon"}, ports, nil) <add> link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", []string{"PASSWORD=gordon"}, ports) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestLinkMultipleEnv(t *testing.T) { <ide> ports[nat.Port("6380/tcp")] = struct{}{} <ide> ports[nat.Port("6381/tcp")] = struct{}{} <ide> <del> link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", []string{"PASSWORD=gordon"}, ports, nil) <add> link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", []string{"PASSWORD=gordon"}, ports) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestLinkPortRangeEnv(t *testing.T) { <ide> ports[nat.Port("6380/tcp")] = struct{}{} <ide> ports[nat.Port("6381/tcp")] = struct{}{} <ide> <del> link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", []string{"PASSWORD=gordon"}, ports, nil) <add> link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", []string{"PASSWORD=gordon"}, ports) <ide> if err != nil { <ide> t.Fatal(err) <ide> }
3
Javascript
Javascript
use more `for...of` loops in the code-base
60f6272ed9e5c81af12785334dac43babdba5f09
<ide><path>src/core/catalog.js <ide> class Catalog { <ide> <ide> const kidPromises = []; <ide> let found = false; <del> for (let i = 0, ii = kids.length; i < ii; i++) { <del> const kid = kids[i]; <add> for (const kid of kids) { <ide> if (!(kid instanceof Ref)) { <ide> throw new FormatError("Kid must be a reference."); <ide> } <ide><path>src/core/cff_parser.js <ide> class CFFParser { <ide> <ide> createDict(Type, dict, strings) { <ide> const cffDict = new Type(strings); <del> for (let i = 0, ii = dict.length; i < ii; ++i) { <del> const pair = dict[i]; <del> const key = pair[0]; <del> const value = pair[1]; <add> for (const [key, value] of dict) { <ide> cffDict.setByKey(key, value); <ide> } <ide> return cffDict; <ide> class CFFDict { <ide> if (!(key in this.keyToNameMap)) { <ide> return false; <ide> } <del> const valueLength = value.length; <ide> // ignore empty values <del> if (valueLength === 0) { <add> if (value.length === 0) { <ide> return true; <ide> } <ide> // Ignore invalid values (fixes bug1068432.pdf and bug1308536.pdf). <del> for (let i = 0; i < valueLength; i++) { <del> if (isNaN(value[i])) { <del> warn('Invalid CFFDict value: "' + value + '" for key "' + key + '".'); <add> for (const val of value) { <add> if (isNaN(val)) { <add> warn(`Invalid CFFDict value: "${value}" for key "${key}".`); <ide> return true; <ide> } <ide> } <ide> class CFFDict { <ide> opcodes: {}, <ide> order: [], <ide> }; <del> for (let i = 0, ii = layout.length; i < ii; ++i) { <del> const entry = layout[i]; <add> for (const entry of layout) { <ide> const key = Array.isArray(entry[0]) <ide> ? (entry[0][0] << 8) + entry[0][1] <ide> : entry[0]; <ide> class CFFCompiler { <ide> if (cff.topDict.hasName("FontMatrix")) { <ide> const base = cff.topDict.getByName("FontMatrix"); <ide> cff.topDict.removeByName("FontMatrix"); <del> for (let i = 0, ii = cff.fdArray.length; i < ii; i++) { <del> const subDict = cff.fdArray[i]; <add> for (const subDict of cff.fdArray) { <ide> let matrix = base.slice(0); <ide> if (subDict.hasName("FontMatrix")) { <ide> matrix = Util.transform(matrix, subDict.getByName("FontMatrix")); <ide> class CFFCompiler { <ide> <ide> compileNameIndex(names) { <ide> const nameIndex = new CFFIndex(); <del> for (let i = 0, ii = names.length; i < ii; ++i) { <del> const name = names[i]; <add> for (const name of names) { <ide> // OTS doesn't allow names to be over 127 characters. <ide> const length = Math.min(name.length, 127); <ide> let sanitizedName = new Array(length); <ide> class CFFCompiler { <ide> compileTopDicts(dicts, length, removeCidKeys) { <ide> const fontDictTrackers = []; <ide> let fdArrayIndex = new CFFIndex(); <del> for (let i = 0, ii = dicts.length; i < ii; ++i) { <del> const fontDict = dicts[i]; <add> for (const fontDict of dicts) { <ide> if (removeCidKeys) { <ide> fontDict.removeByName("CIDFontVersion"); <ide> fontDict.removeByName("CIDFontRevision"); <ide> class CFFCompiler { <ide> <ide> compileStringIndex(strings) { <ide> const stringIndex = new CFFIndex(); <del> for (let i = 0, ii = strings.length; i < ii; ++i) { <del> stringIndex.add(stringToBytes(strings[i])); <add> for (const string of strings) { <add> stringIndex.add(stringToBytes(string)); <ide> } <ide> return this.compileIndex(stringIndex); <ide> } <ide> class CFFCompiler { <ide> if (trackers[i]) { <ide> trackers[i].offset(data.length); <ide> } <del> for (let j = 0, jj = objects[i].length; j < jj; j++) { <del> data.push(objects[i][j]); <del> } <add> data.push(...objects[i]); <ide> } <ide> return data; <ide> } <ide><path>src/core/document.js <ide> class PDFDocument { <ide> <ide> function hexString(hash) { <ide> const buf = []; <del> for (let i = 0, ii = hash.length; i < ii; i++) { <del> const hex = hash[i].toString(16); <add> for (const num of hash) { <add> const hex = num.toString(16); <ide> buf.push(hex.padStart(2, "0")); <ide> } <ide> return buf.join(""); <ide><path>src/core/evaluator.js <ide> const deferred = Promise.resolve(); <ide> function normalizeBlendMode(value, parsingArray = false) { <ide> if (Array.isArray(value)) { <ide> // Use the first *supported* BM value in the Array (fixes issue11279.pdf). <del> for (let i = 0, ii = value.length; i < ii; i++) { <del> const maybeBM = normalizeBlendMode(value[i], /* parsingArray = */ true); <add> for (const val of value) { <add> const maybeBM = normalizeBlendMode(val, /* parsingArray = */ true); <ide> if (maybeBM) { <ide> return maybeBM; <ide> } <ide> class PartialEvaluator { <ide> let isSimpleGState = true; <ide> // This array holds the converted/processed state data. <ide> const gStateObj = []; <del> const gStateKeys = gState.getKeys(); <ide> let promise = Promise.resolve(); <del> for (let i = 0, ii = gStateKeys.length; i < ii; i++) { <del> const key = gStateKeys[i]; <add> for (const key of gState.getKeys()) { <ide> const value = gState.get(key); <ide> switch (key) { <ide> case "Type": <ide> class PartialEvaluator { <ide> if (encoding.has("Differences")) { <ide> const diffEncoding = encoding.get("Differences"); <ide> let index = 0; <del> for (let j = 0, jj = diffEncoding.length; j < jj; j++) { <del> const data = xref.fetchIfRef(diffEncoding[j]); <add> for (const entry of diffEncoding) { <add> const data = xref.fetchIfRef(entry); <ide> if (typeof data === "number") { <ide> index = data; <ide> } else if (data instanceof Name) { <ide> class PartialEvaluator { <ide> if (widths) { <ide> const glyphWidths = []; <ide> let j = firstChar; <del> for (let i = 0, ii = widths.length; i < ii; i++) { <del> glyphWidths[j++] = this.xref.fetchIfRef(widths[i]); <add> for (const width of widths) { <add> glyphWidths[j++] = this.xref.fetchIfRef(width); <ide> } <ide> newProperties.widths = glyphWidths; <ide> } else { <ide><path>src/core/fonts.js <ide> class Font { <ide> const cmapPlatformId = cmapTable.platformId; <ide> const cmapEncodingId = cmapTable.encodingId; <ide> const cmapMappings = cmapTable.mappings; <del> const cmapMappingsLength = cmapMappings.length; <ide> let baseEncoding = [], <ide> forcePostTable = false; <ide> if ( <ide> class Font { <ide> } <ide> } <ide> <del> for (let i = 0; i < cmapMappingsLength; ++i) { <del> if (cmapMappings[i].charCode !== unicodeOrCharCode) { <add> for (const mapping of cmapMappings) { <add> if (mapping.charCode !== unicodeOrCharCode) { <ide> continue; <ide> } <del> charCodeToGlyphId[charCode] = cmapMappings[i].glyphId; <add> charCodeToGlyphId[charCode] = mapping.glyphId; <ide> break; <ide> } <ide> } <ide> } else if (cmapPlatformId === 0) { <ide> // Default Unicode semantics, use the charcodes as is. <del> for (let i = 0; i < cmapMappingsLength; ++i) { <del> charCodeToGlyphId[cmapMappings[i].charCode] = cmapMappings[i].glyphId; <add> for (const mapping of cmapMappings) { <add> charCodeToGlyphId[mapping.charCode] = mapping.glyphId; <ide> } <ide> // Always prefer the BaseEncoding/Differences arrays, when they exist <ide> // (fixes issue13433.pdf). <ide> class Font { <ide> // special range since some PDFs have char codes outside of this range <ide> // (e.g. 0x2013) which when masked would overwrite other values in the <ide> // cmap. <del> for (let i = 0; i < cmapMappingsLength; ++i) { <del> let charCode = cmapMappings[i].charCode; <add> for (const mapping of cmapMappings) { <add> let charCode = mapping.charCode; <ide> if ( <ide> cmapPlatformId === 3 && <ide> charCode >= 0xf000 && <ide> charCode <= 0xf0ff <ide> ) { <ide> charCode &= 0xff; <ide> } <del> charCodeToGlyphId[charCode] = cmapMappings[i].glyphId; <add> charCodeToGlyphId[charCode] = mapping.glyphId; <ide> } <ide> } <ide> <ide> class Font { <ide> // to begin with. <ide> continue; <ide> } <del> for (let i = 0, ii = charCodes.length; i < ii; i++) { <del> const charCode = charCodes[i]; <add> for (const charCode of charCodes) { <ide> // Find a fontCharCode that maps to the base and accent glyphs. <ide> // If one doesn't exists, create it. <ide> const charCodeToGlyphId = newMapping.charCodeToGlyphId; <ide> class Font { <ide> // trying to estimate space character width <ide> const possibleSpaceReplacements = ["space", "minus", "one", "i", "I"]; <ide> let width; <del> for (let i = 0, ii = possibleSpaceReplacements.length; i < ii; i++) { <del> const glyphName = possibleSpaceReplacements[i]; <add> for (const glyphName of possibleSpaceReplacements) { <ide> // if possible, getting width by glyph name <ide> if (glyphName in this.widths) { <ide> width = this.widths[glyphName]; <ide><path>src/core/function.js <ide> class PDFFunction { <ide> } <ide> <ide> const fnArray = []; <del> for (let j = 0, jj = fnObj.length; j < jj; j++) { <add> for (const fn of fnObj) { <ide> fnArray.push( <del> this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fnObj[j]) }) <add> this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fn) }) <ide> ); <ide> } <ide> return function (src, srcOffset, dest, destOffset) { <ide> class PDFFunction { <ide> throw new FormatError("Bad domain for stiched function"); <ide> } <ide> <del> const fnRefs = dict.get("Functions"); <ide> const fns = []; <del> for (let i = 0, ii = fnRefs.length; i < ii; ++i) { <del> fns.push( <del> this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fnRefs[i]) }) <del> ); <add> for (const fn of dict.get("Functions")) { <add> fns.push(this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fn) })); <ide> } <ide> <ide> const bounds = toNumberArray(dict.getArray("Bounds")); <ide><path>src/core/jpg.js <ide> class JpegImage { <ide> function prepareComponents(frame) { <ide> const mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH); <ide> const mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV); <del> for (let i = 0, ii = frame.components.length; i < ii; i++) { <del> const component = frame.components[i]; <add> for (const component of frame.components) { <ide> const blocksPerLine = Math.ceil( <ide> (Math.ceil(frame.samplesPerLine / 8) * component.h) / frame.maxH <ide> ); <ide> class JpegImage { <ide> this.jfif = jfif; <ide> this.adobe = adobe; <ide> this.components = []; <del> for (let i = 0, ii = frame.components.length; i < ii; i++) { <del> const component = frame.components[i]; <del> <add> for (const component of frame.components) { <ide> // Prevent errors when DQT markers are placed after SOF{n} markers, <ide> // by assigning the `quantizationTable` entry after the entire image <ide> // has been parsed (fixes issue7406.pdf). <ide> class JpegImage { <ide> const data = this._getLinearizedBlockData(width, height, isSourcePDF); <ide> <ide> if (this.numComponents === 1 && forceRGB) { <del> const dataLength = data.length; <del> const rgbData = new Uint8ClampedArray(dataLength * 3); <add> const rgbData = new Uint8ClampedArray(data.length * 3); <ide> let offset = 0; <del> for (let i = 0; i < dataLength; i++) { <del> const grayColor = data[i]; <add> for (const grayColor of data) { <ide> rgbData[offset++] = grayColor; <ide> rgbData[offset++] = grayColor; <ide> rgbData[offset++] = grayColor; <ide><path>src/core/object_loader.js <ide> class ObjectLoader { <ide> this.refSet = new RefSet(); <ide> // Setup the initial nodes to visit. <ide> const nodesToVisit = []; <del> for (let i = 0, ii = keys.length; i < ii; i++) { <del> const rawValue = dict.getRaw(keys[i]); <add> for (const key of keys) { <add> const rawValue = dict.getRaw(key); <ide> // Skip nodes that are guaranteed to be empty. <ide> if (rawValue !== undefined) { <ide> nodesToVisit.push(rawValue); <ide><path>src/core/opentype_file_builder.js <ide> function writeData(dest, offset, data) { <ide> } <ide> } else { <ide> // treating everything else as array <del> for (let i = 0, ii = data.length; i < ii; i++) { <del> dest[offset++] = data[i] & 0xff; <add> for (const num of data) { <add> dest[offset++] = num & 0xff; <ide> } <ide> } <ide> } <ide><path>src/core/type1_font.js <ide> class Type1Font { <ide> <ide> getType2Charstrings(type1Charstrings) { <ide> const type2Charstrings = []; <del> for (let i = 0, ii = type1Charstrings.length; i < ii; i++) { <del> type2Charstrings.push(type1Charstrings[i].charstring); <add> for (const type1Charstring of type1Charstrings) { <add> type2Charstrings.push(type1Charstring.charstring); <ide> } <ide> return type2Charstrings; <ide> } <ide><path>src/core/xml_parser.js <ide> class SimpleXMLParser extends XMLParserBase { <ide> if (!lastElement) { <ide> return null; <ide> } <del> for (let i = 0, ii = lastElement.childNodes.length; i < ii; i++) { <del> lastElement.childNodes[i].parentNode = lastElement; <add> for (const childNode of lastElement.childNodes) { <add> childNode.parentNode = lastElement; <ide> } <ide> return lastElement; <ide> } <ide><path>src/core/xref.js <ide> class XRef { <ide> } <ide> } <ide> // reading XRef streams <del> for (let i = 0, ii = xrefStms.length; i < ii; ++i) { <del> this.startXRefQueue.push(xrefStms[i]); <add> for (const xrefStm of xrefStms) { <add> this.startXRefQueue.push(xrefStm); <ide> this.readXRef(/* recoveryMode */ true); <ide> } <ide> // finding main trailer <ide> let trailerDict; <del> for (let i = 0, ii = trailers.length; i < ii; ++i) { <del> stream.pos = trailers[i]; <add> for (const trailer of trailers) { <add> stream.pos = trailer; <ide> const parser = new Parser({ <ide> lexer: new Lexer(stream), <ide> xref: this, <ide><path>src/display/canvas.js <ide> function copyCtxState(sourceCtx, destCtx) { <ide> "globalCompositeOperation", <ide> "font", <ide> ]; <del> for (let i = 0, ii = properties.length; i < ii; i++) { <del> const property = properties[i]; <add> for (const property of properties) { <ide> if (sourceCtx[property] !== undefined) { <ide> destCtx[property] = sourceCtx[property]; <ide> } <ide> class CanvasGraphics { <ide> } <ide> <ide> setGState(states) { <del> for (let i = 0, ii = states.length; i < ii; i++) { <del> const state = states[i]; <del> const key = state[0]; <del> const value = state[1]; <del> <add> for (const [key, value] of states) { <ide> switch (key) { <ide> case "LW": <ide> this.setLineWidth(value); <ide> class CanvasGraphics { <ide> this.setFont(value[0], value[1]); <ide> break; <ide> case "CA": <del> this.current.strokeAlpha = state[1]; <add> this.current.strokeAlpha = value; <ide> break; <ide> case "ca": <del> this.current.fillAlpha = state[1]; <del> this.ctx.globalAlpha = state[1]; <add> this.current.fillAlpha = value; <add> this.ctx.globalAlpha = value; <ide> break; <ide> case "BM": <ide> this.ctx.globalCompositeOperation = value; <ide><path>src/display/editor/freetext.js <ide> class FreeTextEditor extends AnnotationEditor { <ide> return this.editorDiv.innerText; <ide> } <ide> const buffer = []; <del> for (let i = 0, ii = divs.length; i < ii; i++) { <del> const div = divs[i]; <add> for (const div of divs) { <ide> const first = div.firstChild; <ide> if (first?.nodeName === "#text") { <ide> buffer.push(first.data); <ide><path>src/display/text_layer.js <ide> function render(task) { <ide> } <ide> <ide> if (!task._textContentStream) { <del> for (let i = 0; i < textDivsLength; i++) { <del> task._layoutText(textDivs[i]); <add> for (const textDiv of textDivs) { <add> task._layoutText(textDiv); <ide> } <ide> } <ide> <ide> class TextLayerRenderTask { <ide> * @private <ide> */ <ide> _processItems(items, styleCache) { <del> for (let i = 0, len = items.length; i < len; i++) { <del> if (items[i].str === undefined) { <add> for (const item of items) { <add> if (item.str === undefined) { <ide> if ( <del> items[i].type === "beginMarkedContentProps" || <del> items[i].type === "beginMarkedContent" <add> item.type === "beginMarkedContentProps" || <add> item.type === "beginMarkedContent" <ide> ) { <ide> const parent = this._container; <ide> this._container = document.createElement("span"); <ide> this._container.classList.add("markedContent"); <del> if (items[i].id !== null) { <del> this._container.setAttribute("id", `${items[i].id}`); <add> if (item.id !== null) { <add> this._container.setAttribute("id", `${item.id}`); <ide> } <ide> parent.append(this._container); <del> } else if (items[i].type === "endMarkedContent") { <add> } else if (item.type === "endMarkedContent") { <ide> this._container = this._container.parentNode; <ide> } <ide> continue; <ide> } <del> this._textContentItemsStr.push(items[i].str); <del> appendText(this, items[i], styleCache, this._layoutTextCtx); <add> this._textContentItemsStr.push(item.str); <add> appendText(this, item, styleCache, this._layoutTextCtx); <ide> } <ide> } <ide> <ide><path>web/text_highlighter.js <ide> class TextHighlighter { <ide> let clearedUntilDivIdx = -1; <ide> <ide> // Clear all current matches. <del> for (let i = 0, ii = matches.length; i < ii; i++) { <del> const match = matches[i]; <add> for (const match of matches) { <ide> const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); <ide> for (let n = begin, end = match.end.divIdx; n <= end; n++) { <ide> const div = textDivs[n];
16
Mixed
Ruby
restore original remote_ip algorithm
75dcdbc84e53cd824c4f1c3e4cb82c40f27010c8
<ide><path>actionpack/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* Return the last valid, non-private IP address from the X-Forwarded-For, <add> Client-IP and Remote-Addr headers, in that order. Document the rationale <add> for that decision, and describe the options that can be passed to the <add> RemoteIp middleware to change it. <add> Fix #7979 <add> <add> *André Arko*, *Steve Klabnik*, *Alexey Gaziev* <add> <ide> * Do not append second slash to `root_url` when using `trailing_slash: true` <ide> Fix #8700 <ide> <ide><path>actionpack/lib/action_dispatch/middleware/remote_ip.rb <ide> module ActionDispatch <add> # This middleware calculates the IP address of the remote client that is <add> # making the request. It does this by checking various headers that could <add> # contain the address, and then picking the last-set address that is not <add> # on the list of trusted IPs. This follows the precendent set by e.g. <add> # {the Tomcat server}[https://issues.apache.org/bugzilla/show_bug.cgi?id=50453], <add> # with {reasoning explained at length}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection] <add> # by @gingerlime. A more detailed explanation of the algorithm is given <add> # at GetIp#calculate_ip. <add> # <add> # Some Rack servers concatenate repeated headers, like {HTTP RFC 2616}[http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2] <add> # requires. Some Rack servers simply drop preceeding headers, and only report <add> # the value that was {given in the last header}[http://andre.arko.net/2011/12/26/repeated-headers-and-ruby-web-servers]. <add> # If you are behind multiple proxy servers (like Nginx to HAProxy to Unicorn) <add> # then you should test your Rack server to make sure your data is good. <add> # <add> # IF YOU DON'T USE A PROXY, THIS MAKES YOU VULNERABLE TO IP SPOOFING. <add> # This middleware assumes that there is at least one proxy sitting around <add> # and setting headers with the client's remote IP address. If you don't use <add> # a proxy, because you are hosted on e.g. Heroku, any client can claim to <add> # have any IP address by setting the X-Forwarded-For header. If you care <add> # about that, please take precautions. <ide> class RemoteIp <del> class IpSpoofAttackError < StandardError ; end <add> class IpSpoofAttackError < StandardError; end <ide> <del> # IP addresses that are "trusted proxies" that can be stripped from <del> # the comma-delimited list in the X-Forwarded-For header. See also: <del> # http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces <del> # http://en.wikipedia.org/wiki/Private_network#Private_IPv6_addresses. <add> # The default trusted IPs list simply includes IP addresses that are <add> # guaranteed by the IP specification to be private addresses. Those will <add> # not be the ultimate client IP in production, and so are discarded. See <add> # http://en.wikipedia.org/wiki/Private_network for details. <ide> TRUSTED_PROXIES = %r{ <del> ^127\.0\.0\.1$ | # localhost <del> ^::1$ | <del> ^(10 | # private IP 10.x.x.x <del> 172\.(1[6-9]|2[0-9]|3[0-1]) | # private IP in the range 172.16.0.0 .. 172.31.255.255 <del> 192\.168 | # private IP 192.168.x.x <del> fc00:: # private IP fc00 <del> )\. <add> ^127\.0\.0\.1$ | # localhost IPv4 <add> ^::1$ | # localhost IPv6 <add> ^fc00: | # private IPv6 range fc00 <add> ^10\. | # private IPv4 range 10.x.x.x <add> ^172\.(1[6-9]|2[0-9]|3[0-1])\.| # private IPv4 range 172.16.0.0 .. 172.31.255.255 <add> ^192\.168\. # private IPv4 range 192.168.x.x <ide> }x <ide> <ide> attr_reader :check_ip, :proxies <ide> <add> # Create a new +RemoteIp+ middleware instance. <add> # <add> # The +check_ip_spoofing+ option is on by default. When on, an exception <add> # is raised if it looks like the client is trying to lie about its own IP <add> # address. It makes sense to turn off this check on sites aimed at non-IP <add> # clients (like WAP devices), or behind proxies that set headers in an <add> # incorrect or confusing way (like AWS ELB). <add> # <add> # The +custom_trusted+ argument can take a regex, which will be used <add> # instead of +TRUSTED_PROXIES+, or a string, which will be used in addition <add> # to +TRUSTED_PROXIES+. Any proxy setup will put the value you want in the <add> # middle (or at the beginning) of the X-Forwarded-For list, with your proxy <add> # servers after it. If your proxies aren't removed, pass them in via the <add> # +custom_trusted+ parameter. That way, the middleware will ignore those <add> # IP addresses, and return the one that you want. <ide> def initialize(app, check_ip_spoofing = true, custom_proxies = nil) <ide> @app = app <ide> @check_ip = check_ip_spoofing <ide> def initialize(app, check_ip_spoofing = true, custom_proxies = nil) <ide> end <ide> end <ide> <add> # Since the IP address may not be needed, we store the object here <add> # without calculating the IP to keep from slowing down the majority of <add> # requests. For those requests that do need to know the IP, the <add> # GetIp#calculate_ip method will calculate the memoized client IP address. <ide> def call(env) <ide> env["action_dispatch.remote_ip"] = GetIp.new(env, self) <ide> @app.call(env) <ide> end <ide> <add> # The GetIp class exists as a way to defer processing of the request data <add> # into an actual IP address. If the ActionDispatch::Request#remote_ip method <add> # is called, this class will calculate the value and then memoize it. <ide> class GetIp <ide> <del> # IP v4 and v6 (with compression) validation regexp <del> # https://gist.github.com/1289635 <add> # This constant contains a regular expression that validates every known <add> # form of IP v4 and v6 address, with or without abbreviations, adapted <add> # from {this gist}[https://gist.github.com/1289635]. <ide> VALID_IP = %r{ <ide> (^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$) | # ip v4 <ide> (^( <ide> class GetIp <ide> }x <ide> <ide> def initialize(env, middleware) <del> @env = env <del> @middleware = middleware <del> @ip = nil <add> @env = env <add> @check_ip = middleware.check_ip <add> @proxies = middleware.proxies <ide> end <ide> <del> # Determines originating IP address. REMOTE_ADDR is the standard <del> # but will be wrong if the user is behind a proxy. Proxies will set <del> # HTTP_CLIENT_IP and/or HTTP_X_FORWARDED_FOR, so we prioritize those. <del> # HTTP_X_FORWARDED_FOR may be a comma-delimited list in the case of <del> # multiple chained proxies. The first address which is in this list <del> # if it's not a known proxy will be the originating IP. <del> # Format of HTTP_X_FORWARDED_FOR: <del> # client_ip, proxy_ip1, proxy_ip2... <del> # http://en.wikipedia.org/wiki/X-Forwarded-For <add> # Sort through the various IP address headers, looking for the IP most <add> # likely to be the address of the actual remote client making this <add> # request. <add> # <add> # REMOTE_ADDR will be correct if the request is made directly against the <add> # Ruby process, on e.g. Heroku. When the request is proxied by another <add> # server like HAProxy or Nginx, the IP address that made the original <add> # request will be put in an X-Forwarded-For header. If there are multiple <add> # proxies, that header may contain a list of IPs. Other proxy services <add> # set the Client-Ip header instead, so we check that too. <add> # <add> # As discussed in {this post about Rails IP Spoofing}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/], <add> # while the first IP in the list is likely to be the "originating" IP, <add> # it could also have been set by the client maliciously. <add> # <add> # In order to find the first address that is (probably) accurate, we <add> # take the list of IPs, remove known and trusted proxies, and then take <add> # the last address left, which was presumably set by one of those proxies. <ide> def calculate_ip <del> client_ip = @env['HTTP_CLIENT_IP'] <del> forwarded_ip = ips_from('HTTP_X_FORWARDED_FOR').first <del> remote_addrs = ips_from('REMOTE_ADDR') <del> <del> check_ip = client_ip && @middleware.check_ip <del> if check_ip && forwarded_ip != client_ip <add> # Set by the Rack web server, this is a single value. <add> remote_addr = ips_from('REMOTE_ADDR').last <add> <add> # Could be a CSV list and/or repeated headers that were concatenated. <add> client_ips = ips_from('HTTP_CLIENT_IP').reverse <add> forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR').reverse <add> <add> # +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set. <add> # If they are both set, it means that this request passed through two <add> # proxies with incompatible IP header conventions, and there is no way <add> # for us to determine which header is the right one after the fact. <add> # Since we have no idea, we give up and explode. <add> should_check_ip = @check_ip && client_ips.last <add> if should_check_ip && !forwarded_ips.include?(client_ips.last) <ide> # We don't know which came from the proxy, and which from the user <del> raise IpSpoofAttackError, "IP spoofing attack?!" \ <del> "HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect}" \ <add> raise IpSpoofAttackError, "IP spoofing attack?! " + <add> "HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect} " + <ide> "HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}" <ide> end <ide> <del> client_ips = remove_proxies [client_ip, forwarded_ip, remote_addrs].flatten <del> if client_ips.present? <del> client_ips.first <del> else <del> # If there is no client ip we can return first valid proxy ip from REMOTE_ADDR <del> remote_addrs.find { |ip| valid_ip? ip } <del> end <add> # We assume these things about the IP headers: <add> # <add> # - X-Forwarded-For will be a list of IPs, one per proxy, or blank <add> # - Client-Ip is propagated from the outermost proxy, or is blank <add> # - REMOTE_ADDR will be the IP that made the request to Rack <add> ips = [forwarded_ips, client_ips, remote_addr].flatten.compact <add> <add> # If every single IP option is in the trusted list, just return REMOTE_ADDR <add> filter_proxies(ips).first || remote_addr <ide> end <ide> <add> # Memoizes the value returned by #calculate_ip and returns it for <add> # ActionDispatch::Request to use. <ide> def to_s <ide> @ip ||= calculate_ip <ide> end <ide> <del> private <add> protected <ide> <ide> def ips_from(header) <del> @env[header] ? @env[header].strip.split(/[,\s]+/) : [] <del> end <del> <del> def valid_ip?(ip) <del> ip =~ VALID_IP <del> end <del> <del> def not_a_proxy?(ip) <del> ip !~ @middleware.proxies <add> # Split the comma-separated list into an array of strings <add> ips = @env[header] ? @env[header].strip.split(/[,\s]+/) : [] <add> # Only return IPs that are valid according to the regex <add> ips.select{ |ip| ip =~ VALID_IP } <ide> end <ide> <del> def remove_proxies(ips) <del> ips.select { |ip| valid_ip?(ip) && not_a_proxy?(ip) } <add> def filter_proxies(ips) <add> ips.reject { |ip| ip =~ @proxies } <ide> end <ide> <ide> end <ide><path>actionpack/test/dispatch/request_test.rb <ide> def url_for(options = {}) <ide> assert_equal '1.2.3.4', request.remote_ip <ide> <ide> request = stub_request 'REMOTE_ADDR' => '1.2.3.4,3.4.5.6' <del> assert_equal '1.2.3.4', request.remote_ip <add> assert_equal '3.4.5.6', request.remote_ip <ide> <ide> request = stub_request 'REMOTE_ADDR' => '1.2.3.4', <ide> 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' <ide> def url_for(options = {}) <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6,unknown' <ide> assert_equal '3.4.5.6', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '172.16.0.1,3.4.5.6' <del> assert_equal nil, request.remote_ip <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6,172.16.0.1' <add> assert_equal '3.4.5.6', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '192.168.0.1,3.4.5.6' <del> assert_equal nil, request.remote_ip <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6,192.168.0.1' <add> assert_equal '3.4.5.6', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1,3.4.5.6' <del> assert_equal nil, request.remote_ip <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6,10.0.0.1' <add> assert_equal '3.4.5.6', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1, 10.0.0.1, 3.4.5.6' <del> assert_equal nil, request.remote_ip <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6, 10.0.0.1, 10.0.0.1' <add> assert_equal '3.4.5.6', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '127.0.0.1,3.4.5.6' <del> assert_equal nil, request.remote_ip <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6,127.0.0.1' <add> assert_equal '3.4.5.6', request.remote_ip <ide> <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,192.168.0.1' <ide> assert_equal nil, request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6, 9.9.9.9, 10.0.0.1, 172.31.4.4' <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 172.31.4.4, 10.0.0.1' <ide> assert_equal '3.4.5.6', request.remote_ip <ide> <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'not_ip_address' <ide> assert_equal nil, request.remote_ip <add> end <ide> <add> test "remote ip spoof detection" do <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1', <ide> 'HTTP_CLIENT_IP' => '2.2.2.2' <ide> e = assert_raise(ActionDispatch::RemoteIp::IpSpoofAttackError) { <ide> def url_for(options = {}) <ide> assert_match(/IP spoofing attack/, e.message) <ide> assert_match(/HTTP_X_FORWARDED_FOR="1.1.1.1"/, e.message) <ide> assert_match(/HTTP_CLIENT_IP="2.2.2.2"/, e.message) <add> end <ide> <del> # turn IP Spoofing detection off. <del> # This is useful for sites that are aimed at non-IP clients. The typical <del> # example is WAP. Since the cellular network is not IP based, it's a <del> # leap of faith to assume that their proxies are ever going to set the <del> # HTTP_CLIENT_IP/HTTP_X_FORWARDED_FOR headers properly. <add> test "remote ip with spoof detection disabled" do <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1', <ide> 'HTTP_CLIENT_IP' => '2.2.2.2', <ide> :ip_spoofing_check => false <del> assert_equal '2.2.2.2', request.remote_ip <del> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 8.8.8.8' <del> assert_equal '9.9.9.9', request.remote_ip <add> assert_equal '1.1.1.1', request.remote_ip <ide> end <ide> <ide> test "remote ip v6" do <ide> request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334' <ide> assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip <ide> <del> request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' <add> request = stub_request 'REMOTE_ADDR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,2001:0db8:85a3:0000:0000:8a2e:0370:7334' <ide> assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip <ide> <ide> request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334', <ide> def url_for(options = {}) <ide> 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329' <ide> assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' <del> assert_equal nil, request.remote_ip <del> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '::1,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' <del> assert_equal nil, request.remote_ip <del> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '::1,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' <del> assert_equal nil, request.remote_ip <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,unknown' <add> assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '::1,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' <del> assert_equal nil, request.remote_ip <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,::1' <add> assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '::1, ::1, fe80:0000:0000:0000:0202:b3ff:fe1e:8329' <del> assert_equal nil, request.remote_ip <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329, ::1, ::1' <add> assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip <ide> <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,::1' <ide> assert_equal nil, request.remote_ip <ide> <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334, fe80:0000:0000:0000:0202:b3ff:fe1e:8329, ::1, fc00::' <del> assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip <add> assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip <ide> <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'not_ip_address' <ide> assert_equal nil, request.remote_ip <add> end <ide> <add> test "remote ip v6 spoof detection" do <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', <ide> 'HTTP_CLIENT_IP' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334' <ide> e = assert_raise(ActionDispatch::RemoteIp::IpSpoofAttackError) { <ide> def url_for(options = {}) <ide> assert_match(/IP spoofing attack/, e.message) <ide> assert_match(/HTTP_X_FORWARDED_FOR="fe80:0000:0000:0000:0202:b3ff:fe1e:8329"/, e.message) <ide> assert_match(/HTTP_CLIENT_IP="2001:0db8:85a3:0000:0000:8a2e:0370:7334"/, e.message) <add> end <ide> <del> # Turn IP Spoofing detection off. <del> # This is useful for sites that are aimed at non-IP clients. The typical <del> # example is WAP. Since the cellular network is not IP based, it's a <del> # leap of faith to assume that their proxies are ever going to set the <del> # HTTP_CLIENT_IP/HTTP_X_FORWARDED_FOR headers properly. <add> test "remote ip v6 spoof detection disabled" do <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', <ide> 'HTTP_CLIENT_IP' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334', <ide> :ip_spoofing_check => false <del> assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip <del> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329, 2001:0db8:85a3:0000:0000:8a2e:0370:7334' <ide> assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip <ide> end <ide> <del> test "remote ip when the remote ip middleware returns nil" do <del> request = stub_request 'REMOTE_ADDR' => '127.0.0.1' <del> assert_equal '127.0.0.1', request.remote_ip <del> end <del> <ide> test "remote ip with user specified trusted proxies String" do <ide> @trusted_proxies = "67.205.106.73" <ide> <ide> def url_for(options = {}) <ide> <ide> request = stub_request 'REMOTE_ADDR' => '172.16.0.1,67.205.106.73', <ide> 'HTTP_X_FORWARDED_FOR' => '67.205.106.73' <del> assert_equal '172.16.0.1', request.remote_ip <add> assert_equal '67.205.106.73', request.remote_ip <ide> <ide> request = stub_request 'REMOTE_ADDR' => '67.205.106.73,3.4.5.6', <ide> 'HTTP_X_FORWARDED_FOR' => '67.205.106.73' <ide> assert_equal '3.4.5.6', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,67.205.106.73' <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '67.205.106.73,unknown' <ide> assert_equal nil, request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6, 9.9.9.9, 10.0.0.1, 67.205.106.73' <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 67.205.106.73' <ide> assert_equal '3.4.5.6', request.remote_ip <ide> end <ide> <ide> def url_for(options = {}) <ide> <ide> request = stub_request 'REMOTE_ADDR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,::1', <ide> 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329' <del> assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip <add> assert_equal '::1', request.remote_ip <ide> <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' <ide> assert_equal nil, request.remote_ip <ide> <ide> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,2001:0db8:85a3:0000:0000:8a2e:0370:7334' <del> assert_equal nil, request.remote_ip <add> assert_equal "2001:0db8:85a3:0000:0000:8a2e:0370:7334", request.remote_ip <ide> end <ide> <ide> test "remote ip with user specified trusted proxies Regexp" do <ide> def url_for(options = {}) <ide> 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' <ide> assert_equal '3.4.5.6', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => '67.205.106.73, 10.0.0.1, 9.9.9.9, 3.4.5.6' <del> assert_equal nil, request.remote_ip <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1, 9.9.9.9, 3.4.5.6, 67.205.106.73' <add> assert_equal '3.4.5.6', request.remote_ip <ide> end <ide> <ide> test "remote ip v6 with user specified trusted proxies Regexp" do <ide> def url_for(options = {}) <ide> 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329' <ide> assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip <ide> <del> request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329, 2001:0db8:85a3:0000:0000:8a2e:0370:7334' <del> assert_equal nil, request.remote_ip <add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334, fe80:0000:0000:0000:0202:b3ff:fe1e:8329' <add> assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip <add> end <add> <add> test "remote ip middleware not present still returns an IP" do <add> request = ActionDispatch::Request.new({'REMOTE_ADDR' => '127.0.0.1'}) <add> assert_equal '127.0.0.1', request.remote_ip <ide> end <ide> <ide> test "domains" do <ide> def url_for(options = {}) <ide> assert_equal request.format.xml?, false <ide> assert_equal request.format.json?, false <ide> end <del> <add> <ide> test "formats with xhr request" do <ide> request = stub_request 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest" <ide> request.expects(:parameters).at_least_once.returns({}) <ide><path>guides/source/configuring.md <ide> Every Rails application comes with a standard set of middleware which it uses in <ide> * `Rails::Rack::Logger` notifies the logs that the request has began. After request is complete, flushes all the logs. <ide> * `ActionDispatch::ShowExceptions` rescues any exception returned by the application and renders nice exception pages if the request is local or if `config.consider_all_requests_local` is set to `true`. If `config.action_dispatch.show_exceptions` is set to `false`, exceptions will be raised regardless. <ide> * `ActionDispatch::RequestId` makes a unique X-Request-Id header available to the response and enables the `ActionDispatch::Request#uuid` method. <del>* `ActionDispatch::RemoteIp` checks for IP spoofing attacks. Configurable with the `config.action_dispatch.ip_spoofing_check` and `config.action_dispatch.trusted_proxies` settings. <add>* `ActionDispatch::RemoteIp` checks for IP spoofing attacks and gets valid `client_ip` from request headers. Configurable with the `config.action_dispatch.ip_spoofing_check`, and `config.action_dispatch.trusted_proxies` options. <ide> * `Rack::Sendfile` intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. Configurable with `config.action_dispatch.x_sendfile_header`. <ide> * `ActionDispatch::Callbacks` runs the prepare callbacks before serving the request. <ide> * `ActiveRecord::ConnectionAdapters::ConnectionManagement` cleans active connections after each request, unless the `rack.test` key in the request environment is set to `true`. <ide><path>railties/test/application/middleware/remote_ip_test.rb <ide> def remote_ip(env = {}) <ide> end <ide> <ide> assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do <del> assert_equal "1.1.1.2", remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2") <add> assert_equal "1.1.1.1", remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2") <ide> end <ide> end <ide>
5
Text
Text
fix incorrect bit of tutorial
921c5840aa64c184bcfa6cc2344d0fdca406548b
<ide><path>docs/tutorial/3-class-based-views.md <ide> So far, so good. It looks pretty similar to the previous case, but we've got be <ide> comment = self.get_object(pk) <ide> serializer = CommentSerializer(request.DATA, instance=comment) <ide> if serializer.is_valid(): <del> comment = serializer.deserialized <add> comment = serializer.object <ide> comment.save() <ide> return Response(serializer.data) <ide> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
1
Python
Python
fix a comment string
a36ce17c317f8f56f44242714e33b16b37e051ea
<ide><path>numpy/lib/utils.py <ide> def memory_bounds(a): <ide> nd_a = len(ashape) <ide> bytes_a = int(ai['typestr'][2:]) <ide> <del> # a_low points to first element of array <del> # a_high points to last element of the array <del> <ide> a_low = a_high = a_data <ide> if astrides is None: # contiguous case <ide> a_high += product(ashape, dtype=int)*bytes_a
1
Go
Go
allow additional media-types
a6a539497ad4ff879d10ed8b588fb4dca0418fb4
<ide><path>distribution/pull_v2.go <ide> func (p *puller) pullSchema1(ctx context.Context, ref reference.Reference, unver <ide> } <ide> <ide> func checkSupportedMediaType(mediaType string) error { <del> supportedMediaTypes := []string{ <del> "application/vnd.oci.image.", <del> "application/vnd.docker.", <del> } <del> <ide> lowerMt := strings.ToLower(mediaType) <ide> for _, mt := range supportedMediaTypes { <del> if strings.HasPrefix(lowerMt, mt) { <add> // The should either be an exact match, or have a valid prefix <add> // we append a "." when matching prefixes to exclude "false positives"; <add> // for example, we don't want to match "application/vnd.oci.images_are_fun_yolo". <add> if lowerMt == mt || strings.HasPrefix(lowerMt, mt+".") { <ide> return nil <ide> } <ide> } <ide><path>distribution/registry.go <ide> import ( <ide> ) <ide> <ide> var ( <add> // supportedMediaTypes represents acceptable media-type(-prefixes) <add> // we use this list to prevent obscure errors when trying to pull <add> // OCI artifacts. <add> supportedMediaTypes = []string{ <add> // valid prefixes <add> "application/vnd.oci.image", <add> "application/vnd.docker", <add> <add> // these types may occur on old images, and are copied from <add> // defaultImageTypes below. <add> "application/octet-stream", <add> "application/json", <add> "text/html", <add> "", <add> } <add> <ide> // defaultImageTypes represents the schema2 config types for images <ide> defaultImageTypes = []string{ <ide> schema2.MediaTypeImageConfig,
2
Javascript
Javascript
add missing geometries to objectloader
4e2ead55f8699af5f9bf72f89312af01194dc79e
<ide><path>src/loaders/ObjectLoader.js <ide> Object.assign( ObjectLoader.prototype, { <ide> break; <ide> <ide> case 'DodecahedronGeometry': <add> case 'DodecahedronBufferGeometry': <ide> case 'IcosahedronGeometry': <add> case 'IcosahedronBufferGeometry': <ide> case 'OctahedronGeometry': <add> case 'OctahedronBufferGeometry': <ide> case 'TetrahedronGeometry': <add> case 'TetrahedronBufferGeometry': <ide> <ide> geometry = new Geometries[ data.type ]( <ide> data.radius, <ide> Object.assign( ObjectLoader.prototype, { <ide> <ide> break; <ide> <add> case 'PolyhedronGeometry': <add> case 'PolyhedronBufferGeometry': <add> <add> geometry = new Geometries[ data.type ]( <add> data.vertices, <add> data.indices, <add> data.radius, <add> data.details <add> ); <add> <add> break; <add> <ide> case 'BufferGeometry': <ide> <ide> geometry = bufferGeometryLoader.parse( data );
1
Java
Java
use resolvabletype in genericcollectntyperesolver
fdf0ef40c0735e2b5b48330e29f4d8914c838e3b
<ide><path>spring-core/src/main/java/org/springframework/core/GenericCollectionTypeResolver.java <ide> <ide> package org.springframework.core; <ide> <del>import java.lang.reflect.Array; <ide> import java.lang.reflect.Field; <del>import java.lang.reflect.GenericArrayType; <del>import java.lang.reflect.MalformedParameterizedTypeException; <ide> import java.lang.reflect.Method; <del>import java.lang.reflect.ParameterizedType; <del>import java.lang.reflect.Type; <del>import java.lang.reflect.TypeVariable; <del>import java.lang.reflect.WildcardType; <ide> import java.util.Collection; <ide> import java.util.Map; <ide> <ide> * (to be able to attempt type conversion if appropriate). <ide> * <ide> * @author Juergen Hoeller <add> * @author Phillip Webb <ide> * @since 2.0 <add> * @see ResolvableType <ide> */ <ide> public abstract class GenericCollectionTypeResolver { <ide> <ide> public abstract class GenericCollectionTypeResolver { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getCollectionType(Class<? extends Collection> collectionClass) { <del> return extractTypeFromClass(collectionClass, Collection.class, 0); <add> return ResolvableType.forClass(collectionClass).asCollection().resolveGeneric(); <ide> } <ide> <ide> /** <ide> public static Class<?> getCollectionType(Class<? extends Collection> collectionC <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapKeyType(Class<? extends Map> mapClass) { <del> return extractTypeFromClass(mapClass, Map.class, 0); <add> return ResolvableType.forClass(mapClass).asMap().resolveGeneric(0); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapKeyType(Class<? extends Map> mapClass) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapValueType(Class<? extends Map> mapClass) { <del> return extractTypeFromClass(mapClass, Map.class, 1); <add> return ResolvableType.forClass(mapClass).asMap().resolveGeneric(1); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapValueType(Class<? extends Map> mapClass) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getCollectionFieldType(Field collectionField) { <del> return getGenericFieldType(collectionField, Collection.class, 0, null, 1); <add> return ResolvableType.forField(collectionField).asCollection().resolveGeneric(); <ide> } <ide> <ide> /** <ide> public static Class<?> getCollectionFieldType(Field collectionField) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getCollectionFieldType(Field collectionField, int nestingLevel) { <del> return getGenericFieldType(collectionField, Collection.class, 0, null, nestingLevel); <add> return ResolvableType.forField(collectionField).getNested(nestingLevel).asCollection().resolveGeneric(); <ide> } <ide> <ide> /** <ide> public static Class<?> getCollectionFieldType(Field collectionField, int nesting <ide> * @param typeIndexesPerLevel Map keyed by nesting level, with each value <ide> * expressing the type index for traversal at that level <ide> * @return the generic type, or {@code null} if none <add> * @deprecated as of 4.0 in favor of using {@link ResolvableType} for arbitrary nesting levels <ide> */ <add> @Deprecated <ide> public static Class<?> getCollectionFieldType(Field collectionField, int nestingLevel, Map<Integer, Integer> typeIndexesPerLevel) { <del> return getGenericFieldType(collectionField, Collection.class, 0, typeIndexesPerLevel, nestingLevel); <add> return ResolvableType.forField(collectionField).getNested(nestingLevel, typeIndexesPerLevel).asCollection().resolveGeneric(); <ide> } <ide> <ide> /** <ide> public static Class<?> getCollectionFieldType(Field collectionField, int nesting <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapKeyFieldType(Field mapField) { <del> return getGenericFieldType(mapField, Map.class, 0, null, 1); <add> return ResolvableType.forField(mapField).asMap().resolveGeneric(0); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapKeyFieldType(Field mapField) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapKeyFieldType(Field mapField, int nestingLevel) { <del> return getGenericFieldType(mapField, Map.class, 0, null, nestingLevel); <add> return ResolvableType.forField(mapField).getNested(nestingLevel).asMap().resolveGeneric(0); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapKeyFieldType(Field mapField, int nestingLevel) { <ide> * @param typeIndexesPerLevel Map keyed by nesting level, with each value <ide> * expressing the type index for traversal at that level <ide> * @return the generic type, or {@code null} if none <add> * @deprecated as of 4.0 in favor of using {@link ResolvableType} for arbitrary nesting levels <ide> */ <add> @Deprecated <ide> public static Class<?> getMapKeyFieldType(Field mapField, int nestingLevel, Map<Integer, Integer> typeIndexesPerLevel) { <del> return getGenericFieldType(mapField, Map.class, 0, typeIndexesPerLevel, nestingLevel); <add> return ResolvableType.forField(mapField).getNested(nestingLevel, typeIndexesPerLevel).asMap().resolveGeneric(0); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapKeyFieldType(Field mapField, int nestingLevel, Map< <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapValueFieldType(Field mapField) { <del> return getGenericFieldType(mapField, Map.class, 1, null, 1); <add> return ResolvableType.forField(mapField).asMap().resolveGeneric(1); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapValueFieldType(Field mapField) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapValueFieldType(Field mapField, int nestingLevel) { <del> return getGenericFieldType(mapField, Map.class, 1, null, nestingLevel); <add> return ResolvableType.forField(mapField).getNested(nestingLevel).asMap().resolveGeneric(1); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapValueFieldType(Field mapField, int nestingLevel) { <ide> * @param typeIndexesPerLevel Map keyed by nesting level, with each value <ide> * expressing the type index for traversal at that level <ide> * @return the generic type, or {@code null} if none <add> * @deprecated as of 4.0 in favor of using {@link ResolvableType} for arbitrary nesting levels <ide> */ <add> @Deprecated <ide> public static Class<?> getMapValueFieldType(Field mapField, int nestingLevel, Map<Integer, Integer> typeIndexesPerLevel) { <del> return getGenericFieldType(mapField, Map.class, 1, typeIndexesPerLevel, nestingLevel); <add> return ResolvableType.forField(mapField).getNested(nestingLevel, typeIndexesPerLevel).asMap().resolveGeneric(1); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapValueFieldType(Field mapField, int nestingLevel, Ma <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getCollectionParameterType(MethodParameter methodParam) { <del> return getGenericParameterType(methodParam, Collection.class, 0); <add> return forMethodParameter(methodParam).asCollection().resolveGeneric(); <ide> } <ide> <ide> /** <ide> public static Class<?> getCollectionParameterType(MethodParameter methodParam) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapKeyParameterType(MethodParameter methodParam) { <del> return getGenericParameterType(methodParam, Map.class, 0); <add> return forMethodParameter(methodParam).asMap().resolveGeneric(0); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapKeyParameterType(MethodParameter methodParam) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapValueParameterType(MethodParameter methodParam) { <del> return getGenericParameterType(methodParam, Map.class, 1); <add> return forMethodParameter(methodParam).asMap().resolveGeneric(1); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapValueParameterType(MethodParameter methodParam) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getCollectionReturnType(Method method) { <del> return getGenericReturnType(method, Collection.class, 0, 1); <add> return ResolvableType.forMethodReturn(method).asCollection().resolveGeneric(); <ide> } <ide> <ide> /** <ide> public static Class<?> getCollectionReturnType(Method method) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getCollectionReturnType(Method method, int nestingLevel) { <del> return getGenericReturnType(method, Collection.class, 0, nestingLevel); <add> return ResolvableType.forMethodReturn(method).getNested(nestingLevel).asCollection().resolveGeneric(); <ide> } <ide> <ide> /** <ide> public static Class<?> getCollectionReturnType(Method method, int nestingLevel) <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapKeyReturnType(Method method) { <del> return getGenericReturnType(method, Map.class, 0, 1); <add> return ResolvableType.forMethodReturn(method).asMap().resolveGeneric(0); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapKeyReturnType(Method method) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapKeyReturnType(Method method, int nestingLevel) { <del> return getGenericReturnType(method, Map.class, 0, nestingLevel); <add> return ResolvableType.forMethodReturn(method).getNested(nestingLevel).asMap().resolveGeneric(0); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapKeyReturnType(Method method, int nestingLevel) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapValueReturnType(Method method) { <del> return getGenericReturnType(method, Map.class, 1, 1); <add> return ResolvableType.forMethodReturn(method).asMap().resolveGeneric(1); <ide> } <ide> <ide> /** <ide> public static Class<?> getMapValueReturnType(Method method) { <ide> * @return the generic type, or {@code null} if none <ide> */ <ide> public static Class<?> getMapValueReturnType(Method method, int nestingLevel) { <del> return getGenericReturnType(method, Map.class, 1, nestingLevel); <add> return ResolvableType.forMethodReturn(method).getNested(nestingLevel).asMap().resolveGeneric(1); <ide> } <ide> <del> <del> /** <del> * Extract the generic parameter type from the given method or constructor. <del> * @param methodParam the method parameter specification <del> * @param source the source class/interface defining the generic parameter types <del> * @param typeIndex the index of the type (e.g. 0 for Collections, <del> * 0 for Map keys, 1 for Map values) <del> * @return the generic type, or {@code null} if none <del> */ <del> private static Class<?> getGenericParameterType(MethodParameter methodParam, Class<?> source, int typeIndex) { <del> return extractType(GenericTypeResolver.getTargetType(methodParam), source, typeIndex, <del> methodParam.typeVariableMap, methodParam.typeIndexesPerLevel, methodParam.getNestingLevel(), 1); <del> } <del> <del> /** <del> * Extract the generic type from the given field. <del> * @param field the field to check the type for <del> * @param source the source class/interface defining the generic parameter types <del> * @param typeIndex the index of the type (e.g. 0 for Collections, <del> * 0 for Map keys, 1 for Map values) <del> * @param nestingLevel the nesting level of the target type <del> * @return the generic type, or {@code null} if none <del> */ <del> private static Class<?> getGenericFieldType(Field field, Class<?> source, int typeIndex, <del> Map<Integer, Integer> typeIndexesPerLevel, int nestingLevel) { <del> return extractType(field.getGenericType(), source, typeIndex, null, typeIndexesPerLevel, nestingLevel, 1); <del> } <del> <del> /** <del> * Extract the generic return type from the given method. <del> * @param method the method to check the return type for <del> * @param source the source class/interface defining the generic parameter types <del> * @param typeIndex the index of the type (e.g. 0 for Collections, <del> * 0 for Map keys, 1 for Map values) <del> * @param nestingLevel the nesting level of the target type <del> * @return the generic type, or {@code null} if none <del> */ <del> private static Class<?> getGenericReturnType(Method method, Class<?> source, int typeIndex, int nestingLevel) { <del> return extractType(method.getGenericReturnType(), source, typeIndex, null, null, nestingLevel, 1); <del> } <del> <del> /** <del> * Extract the generic type from the given Type object. <del> * @param type the Type to check <del> * @param source the source collection/map Class that we check <del> * @param typeIndex the index of the actual type argument <del> * @param nestingLevel the nesting level of the target type <del> * @param currentLevel the current nested level <del> * @return the generic type as Class, or {@code null} if none <del> */ <del> private static Class<?> extractType(Type type, Class<?> source, int typeIndex, <del> Map<TypeVariable, Type> typeVariableMap, Map<Integer, Integer> typeIndexesPerLevel, <del> int nestingLevel, int currentLevel) { <del> <del> Type resolvedType = type; <del> if (type instanceof TypeVariable && typeVariableMap != null) { <del> Type mappedType = typeVariableMap.get(type); <del> if (mappedType != null) { <del> resolvedType = mappedType; <del> } <add> private static ResolvableType forMethodParameter(MethodParameter methodParam) { <add> if (methodParam.resolveClass != null) { <add> return ResolvableType.forMethodParameter(methodParam, methodParam.resolveClass); <ide> } <del> if (resolvedType instanceof ParameterizedType) { <del> return extractTypeFromParameterizedType((ParameterizedType) resolvedType, source, typeIndex, typeVariableMap, typeIndexesPerLevel, <del> nestingLevel, currentLevel); <del> } <del> else if (resolvedType instanceof Class) { <del> return extractTypeFromClass((Class) resolvedType, source, typeIndex, typeVariableMap, typeIndexesPerLevel, <del> nestingLevel, currentLevel); <del> } <del> else if (resolvedType instanceof GenericArrayType) { <del> Type compType = ((GenericArrayType) resolvedType).getGenericComponentType(); <del> return extractType(compType, source, typeIndex, typeVariableMap, typeIndexesPerLevel, nestingLevel, currentLevel + 1); <del> } <del> else { <del> return null; <del> } <del> } <del> <del> /** <del> * Extract the generic type from the given ParameterizedType object. <del> * @param ptype the ParameterizedType to check <del> * @param source the expected raw source type (can be {@code null}) <del> * @param typeIndex the index of the actual type argument <del> * @param nestingLevel the nesting level of the target type <del> * @param currentLevel the current nested level <del> * @return the generic type as Class, or {@code null} if none <del> */ <del> private static Class<?> extractTypeFromParameterizedType(ParameterizedType ptype, Class<?> source, int typeIndex, <del> Map<TypeVariable, Type> typeVariableMap, Map<Integer, Integer> typeIndexesPerLevel, <del> int nestingLevel, int currentLevel) { <del> <del> if (!(ptype.getRawType() instanceof Class)) { <del> return null; <del> } <del> Class rawType = (Class) ptype.getRawType(); <del> Type[] paramTypes = ptype.getActualTypeArguments(); <del> if (nestingLevel - currentLevel > 0) { <del> int nextLevel = currentLevel + 1; <del> Integer currentTypeIndex = (typeIndexesPerLevel != null ? typeIndexesPerLevel.get(nextLevel) : null); <del> // Default is last parameter type: Collection element or Map value. <del> int indexToUse = (currentTypeIndex != null ? currentTypeIndex : paramTypes.length - 1); <del> Type paramType = paramTypes[indexToUse]; <del> return extractType(paramType, source, typeIndex, typeVariableMap, typeIndexesPerLevel, nestingLevel, nextLevel); <del> } <del> if (source != null && !source.isAssignableFrom(rawType)) { <del> return null; <del> } <del> Class fromSuperclassOrInterface = extractTypeFromClass(rawType, source, typeIndex, typeVariableMap, typeIndexesPerLevel, <del> nestingLevel, currentLevel); <del> if (fromSuperclassOrInterface != null) { <del> return fromSuperclassOrInterface; <del> } <del> if (paramTypes == null || typeIndex >= paramTypes.length) { <del> return null; <del> } <del> Type paramType = paramTypes[typeIndex]; <del> if (paramType instanceof TypeVariable && typeVariableMap != null) { <del> Type mappedType = typeVariableMap.get(paramType); <del> if (mappedType != null) { <del> paramType = mappedType; <del> } <del> } <del> if (paramType instanceof WildcardType) { <del> WildcardType wildcardType = (WildcardType) paramType; <del> Type[] upperBounds = wildcardType.getUpperBounds(); <del> if (upperBounds != null && upperBounds.length > 0 && !Object.class.equals(upperBounds[0])) { <del> paramType = upperBounds[0]; <del> } <del> else { <del> Type[] lowerBounds = wildcardType.getLowerBounds(); <del> if (lowerBounds != null && lowerBounds.length > 0 && !Object.class.equals(lowerBounds[0])) { <del> paramType = lowerBounds[0]; <del> } <del> } <del> } <del> if (paramType instanceof ParameterizedType) { <del> paramType = ((ParameterizedType) paramType).getRawType(); <del> } <del> if (paramType instanceof GenericArrayType) { <del> // A generic array type... Let's turn it into a straight array type if possible. <del> Type compType = ((GenericArrayType) paramType).getGenericComponentType(); <del> if (compType instanceof Class) { <del> return Array.newInstance((Class) compType, 0).getClass(); <del> } <del> } <del> else if (paramType instanceof Class) { <del> // We finally got a straight Class... <del> return (Class) paramType; <del> } <del> return null; <del> } <del> <del> /** <del> * Extract the generic type from the given Class object. <del> * @param clazz the Class to check <del> * @param source the expected raw source type (can be {@code null}) <del> * @param typeIndex the index of the actual type argument <del> * @return the generic type as Class, or {@code null} if none <del> */ <del> private static Class<?> extractTypeFromClass(Class<?> clazz, Class<?> source, int typeIndex) { <del> return extractTypeFromClass(clazz, source, typeIndex, null, null, 1, 1); <del> } <del> <del> /** <del> * Extract the generic type from the given Class object. <del> * @param clazz the Class to check <del> * @param source the expected raw source type (can be {@code null}) <del> * @param typeIndex the index of the actual type argument <del> * @param nestingLevel the nesting level of the target type <del> * @param currentLevel the current nested level <del> * @return the generic type as Class, or {@code null} if none <del> */ <del> private static Class<?> extractTypeFromClass(Class<?> clazz, Class<?> source, int typeIndex, <del> Map<TypeVariable, Type> typeVariableMap, Map<Integer, Integer> typeIndexesPerLevel, <del> int nestingLevel, int currentLevel) { <del> <del> if (clazz.getName().startsWith("java.util.")) { <del> return null; <del> } <del> if (clazz.getSuperclass() != null && isIntrospectionCandidate(clazz.getSuperclass())) { <del> try { <del> return extractType(clazz.getGenericSuperclass(), source, typeIndex, typeVariableMap, <del> typeIndexesPerLevel, nestingLevel, currentLevel); <del> } <del> catch (MalformedParameterizedTypeException ex) { <del> // from getGenericSuperclass() - ignore and continue with interface introspection <del> } <del> } <del> Type[] ifcs = clazz.getGenericInterfaces(); <del> if (ifcs != null) { <del> for (Type ifc : ifcs) { <del> Type rawType = ifc; <del> if (ifc instanceof ParameterizedType) { <del> rawType = ((ParameterizedType) ifc).getRawType(); <del> } <del> if (rawType instanceof Class && isIntrospectionCandidate((Class) rawType)) { <del> return extractType(ifc, source, typeIndex, typeVariableMap, typeIndexesPerLevel, nestingLevel, currentLevel); <del> } <del> } <del> } <del> return null; <del> } <del> <del> /** <del> * Determine whether the given class is a potential candidate <del> * that defines generic collection or map types. <del> * @param clazz the class to check <del> * @return whether the given class is assignable to Collection or Map <del> */ <del> private static boolean isIntrospectionCandidate(Class clazz) { <del> return (Collection.class.isAssignableFrom(clazz) || Map.class.isAssignableFrom(clazz)); <add> return ResolvableType.forMethodParameter(methodParam); <ide> } <ide> <ide> }
1
Python
Python
use better variable names, move check to the top
2ebdee24775b13d02b985ed146594357c89bec44
<ide><path>libcloud/compute/base.py <ide> def delete_key_pair(self, key_pair): <ide> def wait_until_running(self, nodes, wait_period=3, timeout=600, <ide> ssh_interface='public_ips', force_ipv4=True): <ide> """ <del> Block until the provided nodes are considered running <add> Block until the provided nodes are considered running. <ide> <ide> Node is considered running when it's state is "running" and when it has <ide> at least one IP address assigned. <ide> def wait_until_running(self, nodes, wait_period=3, timeout=600, <ide> """ <ide> def is_supported(address): <ide> """ <del> Return True for supported address <add> Return True for supported address. <ide> """ <ide> if force_ipv4 and not is_valid_ip_address(address=address, <ide> family=socket.AF_INET): <ide> def is_supported(address): <ide> <ide> def filter_addresses(addresses): <ide> """ <del> Return list of supported addresses <add> Return list of supported addresses. <ide> """ <del> return [a for a in addresses if is_supported(a)] <del> <del> start = time.time() <del> end = start + timeout <add> return [address for address in addresses if is_supported(address)] <ide> <ide> if ssh_interface not in ['public_ips', 'private_ips']: <ide> raise ValueError('ssh_interface argument must either be' + <ide> 'public_ips or private_ips') <ide> <del> uuids = set([n.uuid for n in nodes]) <add> start = time.time() <add> end = start + timeout <add> <add> uuids = set([node.uuid for node in nodes]) <add> <ide> while time.time() < end: <del> nodes = self.list_nodes() <del> nodes = list([n for n in nodes if n.uuid in uuids]) <add> all_nodes = self.list_nodes() <add> matching_nodes = list([node for node in all_nodes <add> if node.uuid in uuids]) <ide> <del> if len(nodes) > len(uuids): <del> found_uuids = [n.uuid for n in nodes] <add> if len(matching_nodes) > len(uuids): <add> found_uuids = [node.uuid for node in matching_nodes] <ide> msg = ('Unable to match specified uuids ' + <ide> '(%s) with existing nodes. Found ' % (uuids) + <ide> 'multiple nodes with same uuid: (%s)' % (found_uuids)) <ide> raise LibcloudError(value=msg, driver=self) <ide> <del> running_nodes = [n for n in nodes if n.state == NodeState.RUNNING] <del> addresses = [filter_addresses(getattr(n, ssh_interface)) for n in <del> running_nodes] <add> running_nodes = [node for node in matching_nodes <add> if node.state == NodeState.RUNNING] <add> addresses = [filter_addresses(getattr(node, ssh_interface)) <add> for node in running_nodes] <add> <ide> if len(running_nodes) == len(uuids) == len(addresses): <ide> return list(zip(running_nodes, addresses)) <ide> else:
1
Text
Text
improve common.mustcall() explanation
9cfeccec4506f9a3c3cbd394db90f8fc1691b392
<ide><path>test/README.md <ide> Array of IPV6 hosts. <ide> ### mustCall(fn[, expected]) <ide> * fn [&lt;Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) <ide> * expected [&lt;Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = 1 <add>* return [&lt;Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) <ide> <del>Number of times `fn` should be called. <add>Returns a function that calls `fn`. If the returned function has not been called <add>exactly `expected` number of times when the test is complete, then the test will <add>fail. <ide> <ide> ### nodeProcessAborted(exitCode, signal) <ide> * `exitCode` [&lt;Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
1
Text
Text
add model card
326e6ebae78572a3136223156f78abbd8f499773
<ide><path>model_cards/mrm8488/spanbert-base-finetuned-squadv1/README.md <add>--- <add>language: english <add>thumbnail: <add>--- <add> <add># SpanBERT base fine-tuned on SQuAD v1 <add> <add>[SpanBERT](https://github.com/facebookresearch/SpanBERT) created by [Facebook Research](https://github.com/facebookresearch) and fine-tuned on [SQuAD 1.1](https://rajpurkar.github.io/SQuAD-explorer/explore/1.1/dev/) for **Q&A** downstream task ([by them](https://github.com/facebookresearch/SpanBERT#finetuned-models-squad-1120-relation-extraction-coreference-resolution)). <add> <add>## Details of SpanBERT <add> <add>[SpanBERT: Improving Pre-training by Representing and Predicting Spans](https://arxiv.org/abs/1907.10529) <add> <add>## Details of the downstream task (Q&A) - Dataset 📚 🧐 ❓ <add> <add>[SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) <add> <add>## Model fine-tuning 🏋️‍ <add> <add>You can get the fine-tuning script [here](https://github.com/facebookresearch/SpanBERT) <add> <add>```bash <add>python code/run_squad.py \ <add> --do_train \ <add> --do_eval \ <add> --model spanbert-base-cased \ <add> --train_file train-v1.1.json \ <add> --dev_file dev-v1.1.json \ <add> --train_batch_size 32 \ <add> --eval_batch_size 32 \ <add> --learning_rate 2e-5 \ <add> --num_train_epochs 4 \ <add> --max_seq_length 512 \ <add> --doc_stride 128 \ <add> --eval_metric f1 \ <add> --output_dir squad_output \ <add> --fp16 <add>``` <add> <add>## Results Comparison 📝 <add> <add>| | SQuAD 1.1 | SQuAD 2.0 | Coref | TACRED | <add>| ---------------------- | ------------- | --------- | ------- | ------ | <add>| | F1 | F1 | avg. F1 | F1 | <add>| BERT (base) | 88.5 | 76.5 | 73.1 | 67.7 | <add>| SpanBERT (base) | **92.4** (this one) | [83.6](https://huggingface.co/mrm8488/spanbert-base-finetuned-squadv2) | 77.4 | [68.2](https://huggingface.co/mrm8488/spanbert-base-finetuned-tacred) | <add>| BERT (large) | 91.3 | 83.3 | 77.1 | 66.4 | <add>| SpanBERT (large) | [94.6](https://huggingface.co/mrm8488/spanbert-large-finetuned-squadv1) | [88.7](https://huggingface.co/mrm8488/spanbert-large-finetuned-squadv2) | 79.6 | [70.8](https://huggingface.co/mrm8488/spanbert-large-finetuned-tacred) | <add> <add> <add>Note: The numbers marked as * are evaluated on the development sets becaus those models were not submitted to the official SQuAD leaderboard. All the other numbers are test numbers. <add> <add>## Model in action <add> <add>Fast usage with **pipelines**: <add> <add>```python <add>from transformers import pipeline <add> <add>qa_pipeline = pipeline( <add> "question-answering", <add> model="mrm8488/spanbert-base-finetuned-squadv1", <add> tokenizer="SpanBERT/spanbert-base-cased" <add>) <add> <add>qa_pipeline({ <add> 'context': "Manuel Romero has been working very hard in the repository hugginface/transformers lately", <add> 'question': "How has been working Manuel Romero lately?" <add> <add>}) <add> <add># Output: {'answer': 'very hard in the repository hugginface/transformers', <add> 'end': 82, <add> 'score': 0.327230326857725, <add> 'start': 31} <add>``` <add> <add>> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) <add> <add>> Made with <span style="color: #e25555;">&hearts;</span> in Spain
1
Ruby
Ruby
fix install_name massaging for keg-only brews
870f36769ef747b4f8eb8d5444eb2739affb73a1
<ide><path>Library/Homebrew/keg_fix_install_names.rb <ide> class Keg <ide> def fix_install_names <ide> dylibs.each do |dylib| <ide> bad_install_names_for dylib do |id, bad_names| <del> # avoid the chmod change if unecessary—I'm not convinced it reverses right <del> next if bad_names.empty? and id.to_s == dylib.to_s <del> <ide> dylib.ensure_writable do <ide> system "install_name_tool", "-id", id, dylib <ide> bad_names.each do |bad_name|
1
Java
Java
add generic composite filter
47f45ff7435cc9be7a2ad0fbfe6e65312f348599
<ide><path>org.springframework.web/src/main/java/org/springframework/web/filter/CompositeFilter.java <add>/* <add> * Copyright 2002-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.filter; <add> <add>import java.io.IOException; <add>import java.util.ArrayList; <add>import java.util.List; <add> <add>import javax.servlet.Filter; <add>import javax.servlet.FilterChain; <add>import javax.servlet.FilterConfig; <add>import javax.servlet.ServletException; <add>import javax.servlet.ServletRequest; <add>import javax.servlet.ServletResponse; <add> <add>/** <add> * A generic composite servlet {@link Filter} that just delegates its behaviour to a chain (list) of user supplied <add> * filters, achieving the functionality of a {@link FilterChain}, but conveniently using only {@link Filter} instances. <add> * This is useful for filters that require dependency injection, and can therefore be set up in a Spring application <add> * context. Typically this composite would be used in conjunction with {@link DelegatingFilterProxy}, so that it can be <add> * declared in Spring but applied to a servlet context. <add> * <add> * @since 3.1 <add> * <add> * @author Dave Syer <add> * <add> */ <add>public class CompositeFilter implements Filter { <add> <add> private List<? extends Filter> filters = new ArrayList<Filter>(); <add> <add> public void setFilters(List<? extends Filter> filters) { <add> this.filters = new ArrayList<Filter>(filters); <add> } <add> <add> /** <add> * Clean up all the filters supplied, calling each one's destroy method in turn, but in reverse order. <add> * <add> * @see Filter#init(FilterConfig) <add> */ <add> public void destroy() { <add> for (int i = filters.size(); i-- > 0;) { <add> Filter filter = filters.get(i); <add> filter.destroy(); <add> } <add> } <add> <add> /** <add> * Initialize all the filters, calling each one's init method in turn in the order supplied. <add> * <add> * @see Filter#init(FilterConfig) <add> */ <add> public void init(FilterConfig config) throws ServletException { <add> for (Filter filter : filters) { <add> filter.init(config); <add> } <add> } <add> <add> /** <add> * Forms a temporary chain from the list of delegate filters supplied ({@link #setFilters(List)}) and executes them <add> * in order. Each filter delegates to the next one in the list, achieving the normal behaviour of a <add> * {@link FilterChain}, despite the fact that this is a {@link Filter}. <add> * <add> * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) <add> */ <add> public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, <add> ServletException { <add> new VirtualFilterChain(chain, filters).doFilter(request, response); <add> } <add> <add> private static class VirtualFilterChain implements FilterChain { <add> private final FilterChain originalChain; <add> private final List<? extends Filter> additionalFilters; <add> private int currentPosition = 0; <add> <add> private VirtualFilterChain(FilterChain chain, List<? extends Filter> additionalFilters) { <add> this.originalChain = chain; <add> this.additionalFilters = additionalFilters; <add> } <add> <add> public void doFilter(final ServletRequest request, final ServletResponse response) throws IOException, <add> ServletException { <add> if (currentPosition == additionalFilters.size()) { <add> originalChain.doFilter(request, response); <add> } else { <add> currentPosition++; <add> Filter nextFilter = additionalFilters.get(currentPosition - 1); <add> nextFilter.doFilter(request, response, this); <add> } <add> } <add> <add> } <add> <add>} <ide><path>org.springframework.web/src/test/java/org/springframework/web/filter/CompositeFilterTests.java <add>/* <add> * Copyright 2004, 2005 Acegi Technology Pty Limited <add> * Copyright 2006-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.filter; <add> <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertNotNull; <add>import static org.junit.Assert.assertNull; <add> <add>import java.io.IOException; <add>import java.util.Arrays; <add> <add>import javax.servlet.Filter; <add>import javax.servlet.FilterChain; <add>import javax.servlet.FilterConfig; <add>import javax.servlet.ServletContext; <add>import javax.servlet.ServletException; <add>import javax.servlet.ServletRequest; <add>import javax.servlet.ServletResponse; <add> <add>import org.junit.Test; <add>import org.springframework.mock.web.MockFilterConfig; <add>import org.springframework.mock.web.MockHttpServletRequest; <add>import org.springframework.mock.web.MockHttpServletResponse; <add>import org.springframework.mock.web.MockServletContext; <add> <add>/** <add> * @author Dave Syer <add> */ <add>public class CompositeFilterTests { <add> <add> @Test <add> public void testCompositeFilter() throws ServletException, IOException { <add> ServletContext sc = new MockServletContext(); <add> <add> MockFilter targetFilter = new MockFilter(); <add> <add> MockFilterConfig proxyConfig = new MockFilterConfig(sc); <add> <add> CompositeFilter filterProxy = new CompositeFilter(); <add> filterProxy.setFilters(Arrays.asList(targetFilter)); <add> filterProxy.init(proxyConfig); <add> <add> MockHttpServletRequest request = new MockHttpServletRequest(); <add> MockHttpServletResponse response = new MockHttpServletResponse(); <add> filterProxy.doFilter(request, response, null); <add> <add> assertNotNull(targetFilter.filterConfig); <add> assertEquals(Boolean.TRUE, request.getAttribute("called")); <add> <add> filterProxy.destroy(); <add> assertNull(targetFilter.filterConfig); <add> } <add> <add> <add> public static class MockFilter implements Filter { <add> <add> public FilterConfig filterConfig; <add> <add> public void init(FilterConfig filterConfig) throws ServletException { <add> this.filterConfig = filterConfig; <add> } <add> <add> public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { <add> request.setAttribute("called", Boolean.TRUE); <add> } <add> <add> public void destroy() { <add> this.filterConfig = null; <add> } <add> } <add> <add>}
2
Python
Python
add missing deprecation dates and versions
566c84bfda3ac656232600445442cdf74bc84569
<ide><path>numpy/lib/function_base.py <ide> def delete(arr, obj, axis=None): <ide> # After removing the special handling of booleans and out of <ide> # bounds values, the conversion to the array can be removed. <ide> if obj.dtype == bool: <add> # 2012-10-11, NumPy 1.8 <ide> warnings.warn("in the future insert will treat boolean arrays and " <ide> "array-likes as boolean index instead of casting it " <ide> "to integer", FutureWarning, stacklevel=3) <ide> def delete(arr, obj, axis=None): <ide> # Test if there are out of bound indices, this is deprecated <ide> inside_bounds = (obj < N) & (obj >= -N) <ide> if not inside_bounds.all(): <del> # 2013-09-24, 1.9 <add> # 2013-09-24, NumPy 1.9 <ide> warnings.warn( <ide> "in the future out of bounds indices will raise an error " <ide> "instead of being ignored by `numpy.delete`.", <ide> DeprecationWarning, stacklevel=3) <ide> obj = obj[inside_bounds] <ide> positive_indices = obj >= 0 <ide> if not positive_indices.all(): <add> # 2013-04-11, NumPy 1.8 <ide> warnings.warn( <ide> "in the future negative indices will not be ignored by " <ide> "`numpy.delete`.", FutureWarning, stacklevel=3) <ide> def insert(arr, obj, values, axis=None): <ide> indices = np.array(obj) <ide> if indices.dtype == bool: <ide> # See also delete <add> # 2012-10-11, NumPy 1.8 <ide> warnings.warn( <ide> "in the future insert will treat boolean arrays and " <ide> "array-likes as a boolean index instead of casting it to "
1
Javascript
Javascript
avoid reserved property under es
f3a37ce8f8fef541f29a39c788d480a247aa3c5c
<ide><path>lib/util/propertyAccess.js <ide> "use strict"; <ide> <ide> const SAFE_IDENTIFIER = /^[_a-zA-Z$][_a-zA-Z$0-9]*$/; <add>const RESERVED_IDENTIFER = [ <add> "break", <add> "case", <add> "catch", <add> "class", <add> "const", <add> "continue", <add> "debugger", <add> "default", <add> "delete", <add> "do", <add> "else", <add> "export", <add> "extends", <add> "finally", <add> "for", <add> "function", <add> "if", <add> "import", <add> "in", <add> "instanceof", <add> "new", <add> "return", <add> "super", <add> "switch", <add> "this", <add> "throw", <add> "try", <add> "typeof", <add> "var", <add> "void", <add> "while", <add> "with", <add> "enum", <add> // strict mode <add> "implements", <add> "interface", <add> "let", <add> "package", <add> "private", <add> "protected", <add> "public", <add> "static", <add> "yield", <add> "yield", <add> // module code <add> "await", <add> // skip future reserved keywords defined under ES1 till ES3 <add> // additional <add> "null", <add> "true", <add> "false" <add>]; <ide> <ide> const propertyAccess = (properties, start = 0) => { <ide> let str = ""; <ide> for (let i = start; i < properties.length; i++) { <ide> const p = properties[i]; <ide> if (`${+p}` === p) { <ide> str += `[${p}]`; <del> } else if (SAFE_IDENTIFIER.test(p)) { <add> } else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFER.includes(p)) { <ide> str += `.${p}`; <ide> } else { <ide> str += `[${JSON.stringify(p)}]`;
1
Javascript
Javascript
remove dublicate classname from head (followup)
4c6ec18d89150f0a8dcaf56bbc7a17d669be8342
<ide><path>lib/head.js <ide> function reduceComponents (components) { <ide> return a.concat(b) <ide> }, []) <ide> .reverse() <del> .concat(defaultHead()) <add> .concat(defaultHead('')) <ide> .filter(Boolean) <ide> .filter(unique()) <ide> .reverse() <ide><path>test/integration/basic/pages/default-head.js <add>import React from 'react' <add>import Head from 'next/head' <add> <add>export default () => <div> <add> <Head /> <add> <h1>next-head, but only once.</h1> <add></div> <ide><path>test/integration/basic/test/index.test.js <ide> describe('Basic Features', () => { <ide> // pre-build all pages at the start <ide> await Promise.all([ <ide> renderViaHTTP(context.appPort, '/async-props'), <add> renderViaHTTP(context.appPort, '/default-head'), <ide> renderViaHTTP(context.appPort, '/empty-get-initial-props'), <ide> renderViaHTTP(context.appPort, '/error'), <ide> renderViaHTTP(context.appPort, '/finish-response'), <ide><path>test/integration/basic/test/rendering.js <ide> export default function ({ app }, suiteName, render, fetch) { <ide> expect(answer.text()).toBe('The answer is 42') <ide> }) <ide> <add> // default-head contains an empty <Head />. <add> test('header renders default charset', async () => { <add> const html = await (render('/default-head')) <add> expect(html.includes('<meta charSet="utf-8" class="next-head"/>')).toBeTruthy() <add> expect(html.includes('next-head, but only once.')).toBeTruthy() <add> }) <add> <ide> test('header helper renders header information', async () => { <ide> const html = await (render('/head')) <ide> expect(html.includes('<meta charSet="iso-8859-5" class="next-head"/>')).toBeTruthy()
4
Javascript
Javascript
fix tab completion of inspector module
a6f3e8f3fe653c48a48c877feec1c24306c3248e
<ide><path>lib/internal/modules/cjs/helpers.js <ide> const builtinLibs = [ <ide> 'stream', 'string_decoder', 'tls', 'tty', 'url', 'util', 'v8', 'vm', 'zlib' <ide> ]; <ide> <del>if (typeof process.binding('inspector').connect === 'function') { <add>if (typeof process.binding('inspector').open === 'function') { <ide> builtinLibs.push('inspector'); <ide> builtinLibs.sort(); <ide> } <ide><path>test/parallel/test-module-cjs-helpers.js <add>'use strict'; <add>// Flags: --expose-internals <add> <add>require('../common'); <add>const assert = require('assert'); <add>const { builtinLibs } = require('internal/modules/cjs/helpers'); <add> <add>const hasInspector = process.config.variables.v8_enable_inspector === 1; <add> <add>const expectedLibs = hasInspector ? 32 : 31; <add>assert.strictEqual(builtinLibs.length, expectedLibs);
2
Python
Python
fix prediction with structured output
677726b9d967bbdc354bb3bf9c350d360e59ab36
<ide><path>keras/engine/training.py <ide> def predict_function(iterator): <ide> outputs = step_function(self, iterator) <ide> for _ in tf.range(self._steps_per_execution - 1): <ide> tf.autograph.experimental.set_loop_options( <del> shape_invariants=[( <del> t, tf_utils.get_tensor_spec(t, dynamic_batch=True).shape) <del> for t in tf.nest.flatten(outputs)]) <add> shape_invariants=[(outputs, tf.nest.map_structure( <add> lambda t: tf_utils.get_tensor_spec( <add> t, dynamic_batch=True).shape, <add> outputs))]) <ide> step_outputs = step_function(self, iterator) <ide> outputs = tf.nest.map_structure(lambda t1, t2: concat([t1, t2]), <ide> outputs, step_outputs)
1
Java
Java
fix javadoc in standardservletasyncwebrequest
c82a4450949287c7d426aa53fe198de2968be312
<ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequest.java <ide> * <ide> * <p>The servlet and all filters involved in an async request must have async <ide> * support enabled using the Servlet API or by adding an <del> * <code>&ltasync-supported&gttrue&lt/async-supported&gt</code> element to servlet and filter <add> * <code>&lt;async-supported&gt;true&lt;/async-supported&gt;</code> element to servlet and filter <ide> * declarations in {@code web.xml}. <ide> * <ide> * @author Rossen Stoyanchev
1
Text
Text
remove the docs readme
dde69f8da44a9bca11929a386983991fae5f806a
<ide><path>docs/README.md <del># Welcome to the Atom API Documentation <add># Welcome to the Atom Docs <ide> <ide> ![Atom](https://cloud.githubusercontent.com/assets/72919/2874231/3af1db48-d3dd-11e3-98dc-6066f8bc766f.png) <ide> <del>## FAQ <del> <del>### Where do I start? <del> <del>Check out [EditorView][EditorView] and [Editor][Editor] classes for a good <del>overview of the main editor API. <del> <del>### How do I access these classes? <del> <del>Check out the [Atom][Atom] class docs to see what globals are available and <del>what they provide. <del> <del>You can also require many of these classes in your package via: <del> <del>```coffee <del>{EditorView} = require 'atom' <del>``` <del> <del>The classes available from `require 'atom'` are: <del> * [BufferedProcess][BufferedProcess] <del> * [BufferedNodeProcess][BufferedNodeProcess] <del> * [EditorView][EditorView] <del> * [Git][Git] <del> * [Point][Point] <del> * [Range][Range] <del> * [ScrollView][ScrollView] <del> * [SelectListView][SelectListView] <del> * [View][View] <del> * [WorkspaceView][WorkspaceView] <del> * [Workspace][Workspace] <del> <del>### How do I create a package? <del> <del>You probably want to read the [creating a package][creating-a-package] <del>doc first and come back here when you are done. <del> <del>### Where are the node docs? <del> <del>Atom ships with node 0.11.10 and the comprehensive node API docs are available <del>[here][node-docs]. <del> <del>[Atom]: ../classes/Atom.html <del>[BufferedProcess]: ../classes/BufferedProcess.html <del>[BufferedNodeProcess]: ../classes/BufferedNodeProcess.html <del>[Editor]: ../classes/Editor.html <del>[EditorView]: ../classes/EditorView.html <del>[Git]: ../classes/Git.html <del>[Point]: ../classes/Point.html <del>[Range]: ../classes/Range.html <del>[ScrollView]: ../classes/ScrollView.html <del>[SelectListView]: ../classes/SelectListView.html <del>[View]: ../classes/View.html <del>[WorkspaceView]: ../classes/WorkspaceView.html <del>[Workspace]: ../classes/Workspace.html <del>[creating-a-package]: https://atom.io/docs/latest/creating-a-package <del>[node-docs]: http://nodejs.org/docs/v0.11.10/api <add>TODO: Write when docs move to a dedicated repo.
1
Java
Java
fix standard multipart binding + polish
cc4faa59902a18e22c9e554b7576883b89c6b36e
<ide><path>spring-web/src/main/java/org/springframework/web/bind/support/WebRequestDataBinder.java <ide> package org.springframework.web.bind.support; <ide> <ide> import java.io.IOException; <add>import java.util.List; <add>import java.util.Map; <ide> <ide> import javax.servlet.ServletException; <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.Part; <ide> <ide> import org.springframework.beans.MutablePropertyValues; <ide> import org.springframework.util.ClassUtils; <add>import org.springframework.util.LinkedMultiValueMap; <add>import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.validation.BindException; <ide> import org.springframework.web.bind.WebDataBinder; <ide> public void bind(WebRequest request) { <ide> } <ide> else if (ClassUtils.hasMethod(HttpServletRequest.class, "getParts")) { <ide> HttpServletRequest serlvetRequest = ((NativeWebRequest) request).getNativeRequest(HttpServletRequest.class); <del> new Servlet3MultipartHelper().bindParts(serlvetRequest, mpvs); <add> new Servlet3MultipartHelper(isBindEmptyMultipartFiles()).bindParts(serlvetRequest, mpvs); <ide> } <ide> } <ide> doBind(mpvs); <ide> private boolean isMultipartRequest(WebRequest request) { <ide> */ <ide> private static class Servlet3MultipartHelper { <ide> <add> private final boolean bindEmptyMultipartFiles; <add> <add> <add> public Servlet3MultipartHelper(boolean bindEmptyMultipartFiles) { <add> this.bindEmptyMultipartFiles = bindEmptyMultipartFiles; <add> } <add> <add> <ide> public void bindParts(HttpServletRequest request, MutablePropertyValues mpvs) { <ide> try { <del> for(Part part : request.getParts()) { <del> mpvs.add(part.getName(), part); <add> MultiValueMap<String, Part> map = new LinkedMultiValueMap<String, Part>(); <add> for (Part part : request.getParts()) { <add> map.add(part.getName(), part); <add> } <add> for (Map.Entry<String, List<Part>> entry: map.entrySet()) { <add> if (entry.getValue().size() == 1) { <add> Part part = entry.getValue().get(0); <add> if (this.bindEmptyMultipartFiles || part.getSize() > 0) { <add> mpvs.add(entry.getKey(), part); <add> } <add> } <add> else { <add> mpvs.add(entry.getKey(), entry.getValue()); <add> } <ide> } <ide> } <ide> catch (IOException ex) { <ide><path>spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderIntegrationTests.java <ide> <ide> import javax.servlet.MultipartConfigElement; <ide> import javax.servlet.ServletException; <del>import javax.servlet.annotation.MultipartConfig; <ide> import javax.servlet.http.HttpServlet; <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; <del>import org.springframework.mock.web.test.MockMultipartFile; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.SocketUtils; <ide> public void testPartsBinding() { <ide> partsServlet.setBean(bean); <ide> <ide> MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>(); <del> MockMultipartFile firstPart = new MockMultipartFile("fileName", "aValue".getBytes()); <add> Resource firstPart = new ClassPathResource("/org/springframework/http/converter/logo.jpg"); <ide> parts.add("firstPart", firstPart); <ide> parts.add("secondPart", "secondValue"); <ide> <ide> public void testPartListBinding() { <ide> template.postForLocation(baseUrl + "/partlist", parts); <ide> <ide> assertNotNull(bean.getPartList()); <del> assertEquals(parts.size(), bean.getPartList().size()); <add> assertEquals(parts.get("partList").size(), bean.getPartList().size()); <ide> } <ide> <ide> <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java <ide> import java.net.URI; <ide> import java.util.Arrays; <ide> <add>import javax.servlet.MultipartConfigElement; <add> <ide> import org.eclipse.jetty.server.Server; <ide> import org.eclipse.jetty.servlet.ServletContextHandler; <ide> import org.eclipse.jetty.servlet.ServletHolder; <ide> import org.junit.AfterClass; <ide> import org.junit.Before; <ide> import org.junit.BeforeClass; <del>import org.junit.Ignore; <ide> import org.junit.Test; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <ide> * Test access to parts of a multipart request with {@link RequestPart}. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Brian Clozel <ide> */ <ide> public class RequestPartIntegrationTests { <ide> <ide> public static void startServer() throws Exception { <ide> ServletHolder standardResolverServlet = new ServletHolder(DispatcherServlet.class); <ide> standardResolverServlet.setInitParameter("contextConfigLocation", config.getName()); <ide> standardResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName()); <add> standardResolverServlet.getRegistration().setMultipartConfig(new MultipartConfigElement("")); <ide> handler.addServlet(standardResolverServlet, "/standard-resolver/*"); <ide> <del> // TODO: add Servlet 3.0 test case without MultipartResolver <del> <ide> server.setHandler(handler); <ide> server.start(); <ide> } <ide> public void commonsMultipartResolver() throws Exception { <ide> } <ide> <ide> @Test <del> @Ignore("jetty 6.1.9 doesn't support Servlet 3.0") <ide> public void standardMultipartResolver() throws Exception { <ide> testCreate(baseUrl + "/standard-resolver/test"); <ide> }
3
Mixed
Ruby
stringify variables names for mysql connections
7e8b06282354da82518f96e0aab38f04788237fa
<ide><path>activerecord/CHANGELOG.md <add>* Stringify all variables keys of mysql connection configuration. <add> <add> When `sql_mode` variable for mysql adapters set in configuration as `String` <add> was ignored and overwritten by strict mode option. <add> <add> Fixes #14895 <add> <add> *Paul Nikitochkin* <add> <ide> * When using a custom `join_table` name on a `habtm`, rails was not saving it <ide> on Reflections. This causes a problem when rails loads fixtures, because it <ide> uses the reflections to set database with fixtures. <ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def column_for(table_name, column_name) <ide> end <ide> <ide> def configure_connection <del> variables = @config[:variables] || {} <add> variables = @config.fetch(:variables, {}).stringify_keys <ide> <ide> # By default, MySQL 'where id is null' selects the last inserted id. <ide> # Turn this off. http://dev.rubyonrails.org/ticket/6778 <del> variables[:sql_auto_is_null] = 0 <add> variables['sql_auto_is_null'] = 0 <ide> <ide> # Increase timeout so the server doesn't disconnect us. <ide> wait_timeout = @config[:wait_timeout] <ide> wait_timeout = 2147483 unless wait_timeout.is_a?(Fixnum) <del> variables[:wait_timeout] = self.class.type_cast_config_to_integer(wait_timeout) <add> variables['wait_timeout'] = self.class.type_cast_config_to_integer(wait_timeout) <ide> <ide> # Make MySQL reject illegal values rather than truncating or blanking them, see <ide> # http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_strict_all_tables <ide> # If the user has provided another value for sql_mode, don't replace it. <del> if strict_mode? && !variables.has_key?(:sql_mode) <del> variables[:sql_mode] = 'STRICT_ALL_TABLES' <add> if strict_mode? && !variables.has_key?('sql_mode') <add> variables['sql_mode'] = 'STRICT_ALL_TABLES' <ide> end <ide> <ide> # NAMES does not have an equals sign, see <ide><path>activerecord/test/cases/adapters/mysql/connection_test.rb <ide> def test_mysql_set_session_variable <ide> end <ide> end <ide> <add> def test_mysql_sql_mode_variable_overides_strict_mode <add> run_without_connection do |orig_connection| <add> ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { 'sql_mode' => 'ansi' })) <add> result = ActiveRecord::Base.connection.exec_query 'SELECT @@SESSION.sql_mode' <add> assert_not_equal [['STRICT_ALL_TABLES']], result.rows <add> end <add> end <add> <ide> def test_mysql_set_session_variable_to_default <ide> run_without_connection do |orig_connection| <ide> ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => :default}})) <ide><path>activerecord/test/cases/adapters/mysql2/connection_test.rb <ide> def test_mysql_set_session_variable <ide> end <ide> end <ide> <add> def test_mysql_sql_mode_variable_overides_strict_mode <add> run_without_connection do |orig_connection| <add> ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { 'sql_mode' => 'ansi' })) <add> result = ActiveRecord::Base.connection.exec_query 'SELECT @@SESSION.sql_mode' <add> assert_not_equal [['STRICT_ALL_TABLES']], result.rows <add> end <add> end <add> <ide> def test_mysql_set_session_variable_to_default <ide> run_without_connection do |orig_connection| <ide> ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => :default}}))
4
Go
Go
fix cross compile for make cross
93ed15075c43d521f05f4b8f96264efb7fe174e4
<ide><path>execdriver/native/driver.go <ide> import ( <ide> "github.com/dotcloud/docker/pkg/cgroups" <ide> "github.com/dotcloud/docker/pkg/libcontainer" <ide> "github.com/dotcloud/docker/pkg/libcontainer/nsinit" <add> "github.com/dotcloud/docker/pkg/system" <ide> "io/ioutil" <ide> "os" <ide> "os/exec" <ide> func (d *dockerCommandFactory) Create(container *libcontainer.Container, console <ide> "-pipe", fmt.Sprint(syncFd), <ide> "-root", filepath.Join(d.driver.root, d.c.ID), <ide> }, args...) <del> d.c.SysProcAttr = &syscall.SysProcAttr{ <del> Cloneflags: uintptr(nsinit.GetNamespaceFlags(container.Namespaces)), <del> } <add> <add> // set this to nil so that when we set the clone flags anything else is reset <add> d.c.SysProcAttr = nil <add> system.SetCloneFlags(&d.c.Cmd, uintptr(nsinit.GetNamespaceFlags(container.Namespaces))) <add> <ide> d.c.Env = container.Env <ide> d.c.Dir = d.c.Rootfs <ide> <ide><path>pkg/libcontainer/nsinit/command.go <ide> package nsinit <ide> import ( <ide> "fmt" <ide> "github.com/dotcloud/docker/pkg/libcontainer" <add> "github.com/dotcloud/docker/pkg/system" <ide> "os" <ide> "os/exec" <del> "syscall" <ide> ) <ide> <ide> // CommandFactory takes the container's configuration and options passed by the <ide> type CommandFactory interface { <ide> Create(container *libcontainer.Container, console string, syncFd uintptr, args []string) *exec.Cmd <ide> } <ide> <del>type DefaultCommandFactory struct{} <add>type DefaultCommandFactory struct { <add> Root string <add>} <ide> <ide> // Create will return an exec.Cmd with the Cloneflags set to the proper namespaces <ide> // defined on the container's configuration and use the current binary as the init with the <ide> // args provided <ide> func (c *DefaultCommandFactory) Create(container *libcontainer.Container, console string, pipe uintptr, args []string) *exec.Cmd { <del> // get our binary name so we can always reexec ourself <del> name := os.Args[0] <del> command := exec.Command(name, append([]string{ <add> // get our binary name from arg0 so we can always reexec ourself <add> command := exec.Command(os.Args[0], append([]string{ <ide> "-console", console, <ide> "-pipe", fmt.Sprint(pipe), <add> "-root", c.Root, <ide> "init"}, args...)...) <ide> <del> command.SysProcAttr = &syscall.SysProcAttr{ <del> Cloneflags: uintptr(GetNamespaceFlags(container.Namespaces)), <del> } <add> system.SetCloneFlags(command, uintptr(GetNamespaceFlags(container.Namespaces))) <ide> command.Env = container.Env <ide> return command <ide> } <add> <add>// GetNamespaceFlags parses the container's Namespaces options to set the correct <add>// flags on clone, unshare, and setns <add>func GetNamespaceFlags(namespaces libcontainer.Namespaces) (flag int) { <add> for _, ns := range namespaces { <add> flag |= ns.Value <add> } <add> return flag <add>} <ide><path>pkg/libcontainer/nsinit/execin.go <add>// +build linux <add> <ide> package nsinit <ide> <ide> import ( <ide><path>pkg/libcontainer/nsinit/ns_linux.go <del>package nsinit <del> <del>import ( <del> "github.com/dotcloud/docker/pkg/libcontainer" <del>) <del> <del>// getNamespaceFlags parses the container's Namespaces options to set the correct <del>// flags on clone, unshare, and setns <del>func GetNamespaceFlags(namespaces libcontainer.Namespaces) (flag int) { <del> for _, ns := range namespaces { <del> flag |= ns.Value <del> } <del> return flag <del>} <ide><path>pkg/libcontainer/nsinit/nsinit/main.go <ide> package main <ide> <ide> import ( <ide> "encoding/json" <del> "errors" <ide> "flag" <ide> "github.com/dotcloud/docker/pkg/libcontainer" <ide> "github.com/dotcloud/docker/pkg/libcontainer/nsinit" <ide> var ( <ide> pipeFd int <ide> ) <ide> <del>var ( <del> ErrUnsupported = errors.New("Unsupported method") <del> ErrWrongArguments = errors.New("Wrong argument count") <del>) <del> <ide> func registerFlags() { <ide> flag.StringVar(&console, "console", "", "console (pty slave) path") <ide> flag.IntVar(&pipeFd, "pipe", 0, "sync pipe fd") <ide> func main() { <ide> registerFlags() <ide> <ide> if flag.NArg() < 1 { <del> log.Fatal(ErrWrongArguments) <add> log.Fatalf("wrong number of argments %d", flag.NArg()) <ide> } <ide> container, err := loadContainer() <ide> if err != nil { <ide> func main() { <ide> log.Fatal(err) <ide> } <ide> if flag.NArg() < 2 { <del> log.Fatal(ErrWrongArguments) <add> log.Fatalf("wrong number of argments %d", flag.NArg()) <ide> } <ide> syncPipe, err := nsinit.NewSyncPipeFromFd(0, uintptr(pipeFd)) <ide> if err != nil { <ide> func readPid() (int, error) { <ide> } <ide> <ide> func newNsInit() (nsinit.NsInit, error) { <del> return nsinit.NewNsInit(&nsinit.DefaultCommandFactory{}, &nsinit.DefaultStateWriter{root}), nil <add> return nsinit.NewNsInit(&nsinit.DefaultCommandFactory{root}, &nsinit.DefaultStateWriter{root}), nil <ide> } <ide><path>pkg/libcontainer/nsinit/unsupported.go <add>// +build !linux <add> <add>package nsinit <add> <add>import ( <add> "github.com/dotcloud/docker/pkg/libcontainer" <add>) <add> <add>func (ns *linuxNs) Exec(container *libcontainer.Container, term Terminal, args []string) (int, error) { <add> return -1, libcontainer.ErrUnsupported <add>} <add> <add>func (ns *linuxNs) ExecIn(container *libcontainer.Container, nspid int, args []string) (int, error) { <add> return -1, libcontainer.ErrUnsupported <add>} <add> <add>func (ns *linuxNs) Init(container *libcontainer.Container, uncleanRootfs, console string, syncPipe *SyncPipe, args []string) error { <add> return libcontainer.ErrUnsupported <add>} <ide><path>pkg/libcontainer/types.go <ide> import ( <ide> "errors" <ide> "github.com/syndtr/gocapability/capability" <ide> "os" <del> "syscall" <ide> ) <ide> <ide> var ( <del> ErrUnkownNamespace error = errors.New("Unkown namespace") <add> ErrUnkownNamespace = errors.New("Unknown namespace") <add> ErrUnkownCapability = errors.New("Unknown capability") <add> ErrUnsupported = errors.New("Unsupported method") <ide> ) <ide> <ide> // namespaceList is used to convert the libcontainer types <ide> // into the names of the files located in /proc/<pid>/ns/* for <ide> // each namespace <ide> var ( <del> namespaceList = Namespaces{ <del> {Key: "NEWNS", Value: syscall.CLONE_NEWNS, File: "mnt"}, <del> {Key: "NEWUTS", Value: syscall.CLONE_NEWUTS, File: "uts"}, <del> {Key: "NEWIPC", Value: syscall.CLONE_NEWIPC, File: "ipc"}, <del> {Key: "NEWUSER", Value: syscall.CLONE_NEWUSER, File: "user"}, <del> {Key: "NEWPID", Value: syscall.CLONE_NEWPID, File: "pid"}, <del> {Key: "NEWNET", Value: syscall.CLONE_NEWNET, File: "net"}, <del> } <add> namespaceList = Namespaces{} <add> <ide> capabilityList = Capabilities{ <ide> {Key: "SETPCAP", Value: capability.CAP_SETPCAP}, <ide> {Key: "SYS_MODULE", Value: capability.CAP_SYS_MODULE}, <ide> type ( <ide> Namespaces []*Namespace <ide> ) <ide> <add>func (ns *Namespace) String() string { <add> return ns.Key <add>} <add> <ide> func (ns *Namespace) MarshalJSON() ([]byte, error) { <ide> return json.Marshal(ns.Key) <ide> } <ide> type ( <ide> Capabilities []*Capability <ide> ) <ide> <del>func (ns *Capability) MarshalJSON() ([]byte, error) { <del> return json.Marshal(ns.Key) <add>func (c *Capability) String() string { <add> return c.Key <ide> } <ide> <del>func (ns *Capability) UnmarshalJSON(src []byte) error { <add>func (c *Capability) MarshalJSON() ([]byte, error) { <add> return json.Marshal(c.Key) <add>} <add> <add>func (c *Capability) UnmarshalJSON(src []byte) error { <ide> var capName string <ide> if err := json.Unmarshal(src, &capName); err != nil { <ide> return err <ide> } <ide> ret := GetCapability(capName) <ide> if ret == nil { <del> return ErrUnkownNamespace <add> return ErrUnkownCapability <ide> } <del> *ns = *ret <add> *c = *ret <ide> return nil <ide> } <ide> <ide> func GetCapability(key string) *Capability { <ide> } <ide> } <ide> if os.Getenv("DEBUG") != "" { <del> panic("Unreachable: Namespace not found") <add> panic("Unreachable: Capability not found") <ide> } <ide> return nil <ide> } <ide><path>pkg/libcontainer/types_linux.go <add>package libcontainer <add> <add>import ( <add> "syscall" <add>) <add> <add>func init() { <add> namespaceList = Namespaces{ <add> {Key: "NEWNS", Value: syscall.CLONE_NEWNS, File: "mnt"}, <add> {Key: "NEWUTS", Value: syscall.CLONE_NEWUTS, File: "uts"}, <add> {Key: "NEWIPC", Value: syscall.CLONE_NEWIPC, File: "ipc"}, <add> {Key: "NEWUSER", Value: syscall.CLONE_NEWUSER, File: "user"}, <add> {Key: "NEWPID", Value: syscall.CLONE_NEWPID, File: "pid"}, <add> {Key: "NEWNET", Value: syscall.CLONE_NEWNET, File: "net"}, <add> } <add>} <ide><path>pkg/system/calls_linux.go <ide> func Mkfifo(name string, mode uint32) error { <ide> func Umask(mask int) int { <ide> return syscall.Umask(mask) <ide> } <add> <add>func SetCloneFlags(cmd *exec.Cmd, flag uintptr) { <add> if cmd.SysProcAttr == nil { <add> cmd.SysProcAttr = &syscall.SysProcAttr{} <add> } <add> cmd.SysProcAttr.Cloneflags = flag <add>} <ide><path>pkg/system/errors.go <add>package system <add> <add>import ( <add> "errors" <add>) <add> <add>var ( <add> ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") <add>) <ide><path>pkg/system/setns_linux.go <ide> package system <ide> <ide> import ( <del> "errors" <ide> "fmt" <ide> "runtime" <ide> "syscall" <ide> ) <ide> <del>var ( <del> ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") <del>) <del> <ide> // Via http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=7b21fddd087678a70ad64afc0f632e0f1071b092 <ide> // <ide> // We need different setns values for the different platforms and arch <ide><path>pkg/system/unsupported.go <add>// +build !linux <add> <add>package system <add> <add>import ( <add> "os/exec" <add>) <add> <add>func SetCloneFlags(cmd *exec.Cmd, flag uintptr) { <add> <add>} <add> <add>func UsetCloseOnExec(fd uintptr) error { <add> return ErrNotSupportedPlatform <add>} <ide><path>runtime.go <ide> func NewRuntimeFromDirectory(config *DaemonConfig, eng *engine.Engine) (*Runtime <ide> <ide> switch config.ExecDriver { <ide> case "lxc": <add> // we want to five the lxc driver the full docker root because it needs <add> // to access and write config and template files in /var/lib/docker/containers/* <add> // to be backwards compatible <ide> ed, err = lxc.NewDriver(config.Root, sysInfo.AppArmor) <ide> case "native": <del> ed, err = native.NewDriver(path.Join(config.Root, "native")) <add> ed, err = native.NewDriver(path.Join(config.Root, "execdriver", "native")) <ide> default: <ide> return nil, fmt.Errorf("unknown exec driver %s", config.ExecDriver) <ide> }
13
Python
Python
add the algorithms of image augmentation
2f6a7ae1fa44514f52f9a97f83d7bbb2b18e53f2
<ide><path>computer_vision/flip_augmentation.py <add>import glob <add>import os <add>import random <add>from string import ascii_lowercase, digits <add> <add>import cv2 <add> <add>""" <add>Flip image and bounding box for computer vision task <add>https://paperswithcode.com/method/randomhorizontalflip <add>""" <add> <add># Params <add>LABEL_DIR = "" <add>IMAGE_DIR = "" <add>OUTPUT_DIR = "" <add>FLIP_TYPE = 1 # (0 is vertical, 1 is horizontal) <add> <add> <add>def main() -> None: <add> """ <add> Get images list and annotations list from input dir. <add> Update new images and annotations. <add> Save images and annotations in output dir. <add> >>> pass # A doctest is not possible for this function. <add> """ <add> img_paths, annos = get_dataset(LABEL_DIR, IMAGE_DIR) <add> print("Processing...") <add> new_images, new_annos, paths = update_image_and_anno(img_paths, annos, FLIP_TYPE) <add> <add> for index, image in enumerate(new_images): <add> # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' <add> letter_code = random_chars(32) <add> file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0] <add> file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}" <add> cv2.imwrite(f"/{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85]) <add> print(f"Success {index+1}/{len(new_images)} with {file_name}") <add> annos_list = [] <add> for anno in new_annos[index]: <add> obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}" <add> annos_list.append(obj) <add> with open(f"/{file_root}.txt", "w") as outfile: <add> outfile.write("\n".join(line for line in annos_list)) <add> <add> <add>def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: <add> """ <add> - label_dir <type: str>: Path to label include annotation of images <add> - img_dir <type: str>: Path to folder contain images <add> Return <type: list>: List of images path and labels <add> >>> pass # A doctest is not possible for this function. <add> """ <add> img_paths = [] <add> labels = [] <add> for label_file in glob.glob(os.path.join(label_dir, "*.txt")): <add> label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] <add> with open(label_file) as in_file: <add> obj_lists = in_file.readlines() <add> img_path = os.path.join(img_dir, f"{label_name}.jpg") <add> <add> boxes = [] <add> for obj_list in obj_lists: <add> obj = obj_list.rstrip("\n").split(" ") <add> boxes.append( <add> [ <add> int(obj[0]), <add> float(obj[1]), <add> float(obj[2]), <add> float(obj[3]), <add> float(obj[4]), <add> ] <add> ) <add> if not boxes: <add> continue <add> img_paths.append(img_path) <add> labels.append(boxes) <add> return img_paths, labels <add> <add> <add>def update_image_and_anno( <add> img_list: list, anno_list: list, flip_type: int = 1 <add>) -> tuple[list, list, list]: <add> """ <add> - img_list <type: list>: list of all images <add> - anno_list <type: list>: list of all annotations of specific image <add> - flip_type <type: int>: 0 is vertical, 1 is horizontal <add> Return: <add> - new_imgs_list <type: narray>: image after resize <add> - new_annos_lists <type: list>: list of new annotation after scale <add> - path_list <type: list>: list the name of image file <add> >>> pass # A doctest is not possible for this function. <add> """ <add> new_annos_lists = [] <add> path_list = [] <add> new_imgs_list = [] <add> for idx in range(len(img_list)): <add> new_annos = [] <add> path = img_list[idx] <add> path_list.append(path) <add> img_annos = anno_list[idx] <add> img = cv2.imread(path) <add> if flip_type == 1: <add> new_img = cv2.flip(img, flip_type) <add> for bbox in img_annos: <add> x_center_new = 1 - bbox[1] <add> new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]]) <add> elif flip_type == 0: <add> new_img = cv2.flip(img, flip_type) <add> for bbox in img_annos: <add> y_center_new = 1 - bbox[2] <add> new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]]) <add> new_annos_lists.append(new_annos) <add> new_imgs_list.append(new_img) <add> return new_imgs_list, new_annos_lists, path_list <add> <add> <add>def random_chars(number_char: int = 32) -> str: <add> """ <add> Automatic generate random 32 characters. <add> Get random string code: '7b7ad245cdff75241935e4dd860f3bad' <add> >>> len(random_chars(32)) <add> 32 <add> """ <add> assert number_char > 1, "The number of character should greater than 1" <add> letter_code = ascii_lowercase + digits <add> return "".join(random.choice(letter_code) for _ in range(number_char)) <add> <add> <add>if __name__ == "__main__": <add> main() <add> print("DONE ✅") <ide><path>computer_vision/mosaic_augmentation.py <add>"""Source: https://github.com/jason9075/opencv-mosaic-data-aug""" <add> <add>import glob <add>import os <add>import random <add>from string import ascii_lowercase, digits <add> <add>import cv2 <add>import numpy as np <add> <add># Parrameters <add>OUTPUT_SIZE = (720, 1280) # Height, Width <add>SCALE_RANGE = (0.4, 0.6) # if height or width lower than this scale, drop it. <add>FILTER_TINY_SCALE = 1 / 100 <add>LABEL_DIR = "" <add>IMG_DIR = "" <add>OUTPUT_DIR = "" <add>NUMBER_IMAGES = 250 <add> <add> <add>def main() -> None: <add> """ <add> Get images list and annotations list from input dir. <add> Update new images and annotations. <add> Save images and annotations in output dir. <add> >>> pass # A doctest is not possible for this function. <add> """ <add> img_paths, annos = get_dataset(LABEL_DIR, IMG_DIR) <add> for index in range(NUMBER_IMAGES): <add> idxs = random.sample(range(len(annos)), 4) <add> new_image, new_annos, path = update_image_and_anno( <add> img_paths, <add> annos, <add> idxs, <add> OUTPUT_SIZE, <add> SCALE_RANGE, <add> filter_scale=FILTER_TINY_SCALE, <add> ) <add> <add> # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' <add> letter_code = random_chars(32) <add> file_name = path.split(os.sep)[-1].rsplit(".", 1)[0] <add> file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}" <add> cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85]) <add> print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}") <add> annos_list = [] <add> for anno in new_annos: <add> width = anno[3] - anno[1] <add> height = anno[4] - anno[2] <add> x_center = anno[1] + width / 2 <add> y_center = anno[2] + height / 2 <add> obj = f"{anno[0]} {x_center} {y_center} {width} {height}" <add> annos_list.append(obj) <add> with open(f"{file_root}.txt", "w") as outfile: <add> outfile.write("\n".join(line for line in annos_list)) <add> <add> <add>def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: <add> """ <add> - label_dir <type: str>: Path to label include annotation of images <add> - img_dir <type: str>: Path to folder contain images <add> Return <type: list>: List of images path and labels <add> >>> pass # A doctest is not possible for this function. <add> """ <add> img_paths = [] <add> labels = [] <add> for label_file in glob.glob(os.path.join(label_dir, "*.txt")): <add> label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] <add> with open(label_file) as in_file: <add> obj_lists = in_file.readlines() <add> img_path = os.path.join(img_dir, f"{label_name}.jpg") <add> <add> boxes = [] <add> for obj_list in obj_lists: <add> obj = obj_list.rstrip("\n").split(" ") <add> xmin = float(obj[1]) - float(obj[3]) / 2 <add> ymin = float(obj[2]) - float(obj[4]) / 2 <add> xmax = float(obj[1]) + float(obj[3]) / 2 <add> ymax = float(obj[2]) + float(obj[4]) / 2 <add> <add> boxes.append([int(obj[0]), xmin, ymin, xmax, ymax]) <add> if not boxes: <add> continue <add> img_paths.append(img_path) <add> labels.append(boxes) <add> return img_paths, labels <add> <add> <add>def update_image_and_anno( <add> all_img_list: list, <add> all_annos: list, <add> idxs: list[int], <add> output_size: tuple[int, int], <add> scale_range: tuple[float, float], <add> filter_scale: float = 0.0, <add>) -> tuple[list, list, str]: <add> """ <add> - all_img_list <type: list>: list of all images <add> - all_annos <type: list>: list of all annotations of specific image <add> - idxs <type: list>: index of image in list <add> - output_size <type: tuple>: size of output image (Height, Width) <add> - scale_range <type: tuple>: range of scale image <add> - filter_scale <type: float>: the condition of downscale image and bounding box <add> Return: <add> - output_img <type: narray>: image after resize <add> - new_anno <type: list>: list of new annotation after scale <add> - path[0] <type: string>: get the name of image file <add> >>> pass # A doctest is not possible for this function. <add> """ <add> output_img = np.zeros([output_size[0], output_size[1], 3], dtype=np.uint8) <add> scale_x = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) <add> scale_y = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) <add> divid_point_x = int(scale_x * output_size[1]) <add> divid_point_y = int(scale_y * output_size[0]) <add> <add> new_anno = [] <add> path_list = [] <add> for i, index in enumerate(idxs): <add> path = all_img_list[index] <add> path_list.append(path) <add> img_annos = all_annos[index] <add> img = cv2.imread(path) <add> if i == 0: # top-left <add> img = cv2.resize(img, (divid_point_x, divid_point_y)) <add> output_img[:divid_point_y, :divid_point_x, :] = img <add> for bbox in img_annos: <add> xmin = bbox[1] * scale_x <add> ymin = bbox[2] * scale_y <add> xmax = bbox[3] * scale_x <add> ymax = bbox[4] * scale_y <add> new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) <add> elif i == 1: # top-right <add> img = cv2.resize(img, (output_size[1] - divid_point_x, divid_point_y)) <add> output_img[:divid_point_y, divid_point_x : output_size[1], :] = img <add> for bbox in img_annos: <add> xmin = scale_x + bbox[1] * (1 - scale_x) <add> ymin = bbox[2] * scale_y <add> xmax = scale_x + bbox[3] * (1 - scale_x) <add> ymax = bbox[4] * scale_y <add> new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) <add> elif i == 2: # bottom-left <add> img = cv2.resize(img, (divid_point_x, output_size[0] - divid_point_y)) <add> output_img[divid_point_y : output_size[0], :divid_point_x, :] = img <add> for bbox in img_annos: <add> xmin = bbox[1] * scale_x <add> ymin = scale_y + bbox[2] * (1 - scale_y) <add> xmax = bbox[3] * scale_x <add> ymax = scale_y + bbox[4] * (1 - scale_y) <add> new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) <add> else: # bottom-right <add> img = cv2.resize( <add> img, (output_size[1] - divid_point_x, output_size[0] - divid_point_y) <add> ) <add> output_img[ <add> divid_point_y : output_size[0], divid_point_x : output_size[1], : <add> ] = img <add> for bbox in img_annos: <add> xmin = scale_x + bbox[1] * (1 - scale_x) <add> ymin = scale_y + bbox[2] * (1 - scale_y) <add> xmax = scale_x + bbox[3] * (1 - scale_x) <add> ymax = scale_y + bbox[4] * (1 - scale_y) <add> new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) <add> <add> # Remove bounding box small than scale of filter <add> if 0 < filter_scale: <add> new_anno = [ <add> anno <add> for anno in new_anno <add> if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) <add> ] <add> <add> return output_img, new_anno, path_list[0] <add> <add> <add>def random_chars(number_char: int) -> str: <add> """ <add> Automatic generate random 32 characters. <add> Get random string code: '7b7ad245cdff75241935e4dd860f3bad' <add> >>> len(random_chars(32)) <add> 32 <add> """ <add> assert number_char > 1, "The number of character should greater than 1" <add> letter_code = ascii_lowercase + digits <add> return "".join(random.choice(letter_code) for _ in range(number_char)) <add> <add> <add>if __name__ == "__main__": <add> main() <add> print("DONE ✅")
2
Javascript
Javascript
remove ie10 launcher from karma config
7b6f541e9dd03ec8554b9f0c0739f4966c4a7e68
<ide><path>karma.conf.js <ide> module.exports = function(config) { <ide> <ide> // IE <ide> if (runAll || process.env.SAUCE_IE) { <del> customLaunchers.SL_IE10 = createCustomLauncher('internet explorer', 10, 'Windows 2012'); <ide> customLaunchers.SL_IE11 = createCustomLauncher('internet explorer', 11, 'Windows 8.1'); <ide> } <ide>
1
Text
Text
fix small typos in readme
571948434bf78ee1f270bb28d4b01d88f7955195
<ide><path>README.md <ide> or packaging just about any resource or asset. <ide> <ide> **TL; DR** <ide> <del>* Bundles both [CommonJs](http://wiki.commonjs.org/) and [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) modules (even combined). <add>* Bundles both [CommonJS](http://wiki.commonjs.org/) and [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) modules (even combined). <ide> * Can create a single bundle or multiple chunks that are asynchronously loaded at runtime (to reduce initial loading time). <ide> * Dependencies are resolved during compilation reducing the runtime size. <ide> * Loaders can preprocess files while compiling, e.g. coffeescript to JavaScript, handlebars strings to compiled functions, images to Base64, etc. <ide> friendly** by using hashes. <ide> // This means webpack takes modules with dependencies <ide> // and emits static assets representing those modules. <ide> <del>// Dependencies can be written in CommonJs <add>// Dependencies can be written in CommonJS <ide> var commonjs = require("./commonjs"); <ide> // or in AMD <ide> define(["amd-module", "../file"], function (amdModule, file) {
1
Javascript
Javascript
fix flaky interval test
b88da496ef3ac9bf2a9dab101bb5827d9f41df04
<ide><path>test/sequential/test-timers-set-interval-excludes-callback-duration.js <ide> let first; <ide> const t = setInterval(() => { <ide> cntr++; <ide> if (cntr === 1) { <del> first = Timer.now(); <ide> common.busyLoop(100); <add> first = Timer.now(); <ide> } else if (cntr === 2) { <del> assert(Timer.now() - first < 120); <add> assert(Timer.now() - first < 100); <ide> clearInterval(t); <ide> } <ide> }, 100);
1
Python
Python
fix url escaping
650a91ac24cbd3e5b4ad5d7d7c6706fdf6160a78
<ide><path>rest_framework/templatetags/rest_framework.py <ide> def replace_query_param(url, key, val): <ide> query_dict = QueryDict(query).copy() <ide> query_dict[key] = val <ide> query = query_dict.urlencode() <del> return escape(urlparse.urlunsplit((scheme, netloc, path, query, fragment))) <add> return urlparse.urlunsplit((scheme, netloc, path, query, fragment)) <ide> <ide> <ide> # Regex for adding classes to html snippets <ide> def add_query_param(request, key, val): <ide> """ <ide> iri = request.get_full_path() <ide> uri = iri_to_uri(iri) <del> return replace_query_param(uri, key, val) <add> return escape(replace_query_param(uri, key, val)) <ide> <ide> <ide> @register.filter
1
PHP
PHP
consolidate model/alias shuffling
62cfe3c97ddee77849a85160d12665304b3f0a9f
<ide><path>src/ORM/Behavior/TranslateBehavior.php <ide> class TranslateBehavior extends Behavior <ide> */ <ide> public function __construct(Table $table, array $config = []) <ide> { <del> $config += ['defaultLocale' => I18n::defaultLocale()]; <add> $config += [ <add> 'defaultLocale' => I18n::defaultLocale(), <add> 'model' => $table->alias() <add> ]; <ide> parent::__construct($table, $config); <ide> } <ide> <ide> public function initialize(array $config) <ide> $this->setupFieldAssociations( <ide> $this->_config['fields'], <ide> $this->_config['translationTable'], <del> $this->_config['model'] ?: $this->_table->alias(), <add> $this->_config['model'], <ide> $this->_config['strategy'] <ide> ); <ide> } <ide> public function beforeSave(Event $event, Entity $entity, ArrayObject $options) <ide> $fields = array_keys($values); <ide> $primaryKey = (array)$this->_table->primaryKey(); <ide> $key = $entity->get(current($primaryKey)); <del> $model = $this->_config['model'] ?: $this->_table->alias(); <add> $model = $this->_config['model']; <ide> <ide> $preexistent = $this->_translationTable->find() <ide> ->select(['id', 'field']) <ide> protected function _bundleTranslatedFields($entity) <ide> } <ide> <ide> $results = $this->_findExistingTranslations($find); <del> $model = $this->_config['model'] ?: $this->_table->alias(); <ide> <ide> foreach ($find as $i => $translation) { <ide> if (!empty($results[$i])) { <ide> $contents[$i]->set('id', $results[$i], ['setter' => false]); <ide> $contents[$i]->isNew(false); <ide> } else { <del> $translation['model'] = $model; <add> $translation['model'] = $this->_config['model']; <ide> $contents[$i]->set($translation, ['setter' => false, 'guard' => false]); <ide> $contents[$i]->isNew(true); <ide> }
1
Go
Go
move rest of cgroups functions into cgroups pkg
7020e208c70dfca5ebc97d699553e4bf1c6ab0bb
<ide><path>pkg/cgroups/cgroups.go <ide> func parseCgroupFile(subsystem string, r io.Reader) (string, error) { <ide> func writeFile(dir, file, data string) error { <ide> return ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700) <ide> } <add> <add>func (c *Cgroup) Apply(pid int) error { <add> // We have two implementation of cgroups support, one is based on <add> // systemd and the dbus api, and one is based on raw cgroup fs operations <add> // following the pre-single-writer model docs at: <add> // http://www.freedesktop.org/wiki/Software/systemd/PaxControlGroups/ <add> // <add> // we can pick any subsystem to find the root <add> cgroupRoot, err := FindCgroupMountpoint("memory") <add> if err != nil { <add> return err <add> } <add> cgroupRoot = filepath.Dir(cgroupRoot) <add> <add> if _, err := os.Stat(cgroupRoot); err != nil { <add> return fmt.Errorf("cgroups fs not found") <add> } <add> if err := c.setupDevices(cgroupRoot, pid); err != nil { <add> return err <add> } <add> if err := c.setupMemory(cgroupRoot, pid); err != nil { <add> return err <add> } <add> if err := c.setupCpu(cgroupRoot, pid); err != nil { <add> return err <add> } <add> return nil <add>} <add> <add>func (c *Cgroup) setupDevices(cgroupRoot string, pid int) (err error) { <add> if !c.DeviceAccess { <add> dir, err := c.Join(cgroupRoot, "devices", pid) <add> if err != nil { <add> return err <add> } <add> <add> defer func() { <add> if err != nil { <add> os.RemoveAll(dir) <add> } <add> }() <add> <add> if err := writeFile(dir, "devices.deny", "a"); err != nil { <add> return err <add> } <add> <add> allow := []string{ <add> // /dev/null, zero, full <add> "c 1:3 rwm", <add> "c 1:5 rwm", <add> "c 1:7 rwm", <add> <add> // consoles <add> "c 5:1 rwm", <add> "c 5:0 rwm", <add> "c 4:0 rwm", <add> "c 4:1 rwm", <add> <add> // /dev/urandom,/dev/random <add> "c 1:9 rwm", <add> "c 1:8 rwm", <add> <add> // /dev/pts/ - pts namespaces are "coming soon" <add> "c 136:* rwm", <add> "c 5:2 rwm", <add> <add> // tuntap <add> "c 10:200 rwm", <add> } <add> <add> for _, val := range allow { <add> if err := writeFile(dir, "devices.allow", val); err != nil { <add> return err <add> } <add> } <add> } <add> return nil <add>} <add> <add>func (c *Cgroup) setupMemory(cgroupRoot string, pid int) (err error) { <add> if c.Memory != 0 || c.MemorySwap != 0 { <add> dir, err := c.Join(cgroupRoot, "memory", pid) <add> if err != nil { <add> return err <add> } <add> defer func() { <add> if err != nil { <add> os.RemoveAll(dir) <add> } <add> }() <add> <add> if c.Memory != 0 { <add> if err := writeFile(dir, "memory.limit_in_bytes", strconv.FormatInt(c.Memory, 10)); err != nil { <add> return err <add> } <add> if err := writeFile(dir, "memory.soft_limit_in_bytes", strconv.FormatInt(c.Memory, 10)); err != nil { <add> return err <add> } <add> } <add> if c.MemorySwap != 0 { <add> if err := writeFile(dir, "memory.memsw.limit_in_bytes", strconv.FormatInt(c.MemorySwap, 10)); err != nil { <add> return err <add> } <add> } <add> } <add> return nil <add>} <add> <add>func (c *Cgroup) setupCpu(cgroupRoot string, pid int) (err error) { <add> // We always want to join the cpu group, to allow fair cpu scheduling <add> // on a container basis <add> dir, err := c.Join(cgroupRoot, "cpu", pid) <add> if err != nil { <add> return err <add> } <add> if c.CpuShares != 0 { <add> if err := writeFile(dir, "cpu.shares", strconv.FormatInt(c.CpuShares, 10)); err != nil { <add> return err <add> } <add> } <add> return nil <add>} <ide><path>pkg/libcontainer/cgroup/cgroup.go <del>package cgroup <del> <del>import ( <del> "fmt" <del> "github.com/dotcloud/docker/pkg/cgroups" <del> "github.com/dotcloud/docker/pkg/libcontainer" <del> "io/ioutil" <del> "os" <del> "path/filepath" <del> "strconv" <del>) <del> <del>func ApplyCgroup(container *libcontainer.Container, pid int) (err error) { <del> if container.Cgroups == nil { <del> return nil <del> } <del> <del> // We have two implementation of cgroups support, one is based on <del> // systemd and the dbus api, and one is based on raw cgroup fs operations <del> // following the pre-single-writer model docs at: <del> // http://www.freedesktop.org/wiki/Software/systemd/PaxControlGroups/ <del> // <del> // we can pick any subsystem to find the root <del> cgroupRoot, err := cgroups.FindCgroupMountpoint("memory") <del> if err != nil { <del> return err <del> } <del> cgroupRoot = filepath.Dir(cgroupRoot) <del> if _, err := os.Stat(cgroupRoot); err != nil { <del> return fmt.Errorf("cgroups fs not found") <del> } <del> if err := setupDevices(container, cgroupRoot, pid); err != nil { <del> return err <del> } <del> if err := setupMemory(container, cgroupRoot, pid); err != nil { <del> return err <del> } <del> if err := setupCpu(container, cgroupRoot, pid); err != nil { <del> return err <del> } <del> return nil <del>} <del> <del>func setupDevices(container *libcontainer.Container, cgroupRoot string, pid int) (err error) { <del> if !container.Cgroups.DeviceAccess { <del> dir, err := container.Cgroups.Join(cgroupRoot, "devices", pid) <del> if err != nil { <del> return err <del> } <del> <del> defer func() { <del> if err != nil { <del> os.RemoveAll(dir) <del> } <del> }() <del> <del> if err := writeFile(dir, "devices.deny", "a"); err != nil { <del> return err <del> } <del> <del> allow := []string{ <del> // /dev/null, zero, full <del> "c 1:3 rwm", <del> "c 1:5 rwm", <del> "c 1:7 rwm", <del> <del> // consoles <del> "c 5:1 rwm", <del> "c 5:0 rwm", <del> "c 4:0 rwm", <del> "c 4:1 rwm", <del> <del> // /dev/urandom,/dev/random <del> "c 1:9 rwm", <del> "c 1:8 rwm", <del> <del> // /dev/pts/ - pts namespaces are "coming soon" <del> "c 136:* rwm", <del> "c 5:2 rwm", <del> <del> // tuntap <del> "c 10:200 rwm", <del> } <del> <del> for _, val := range allow { <del> if err := writeFile(dir, "devices.allow", val); err != nil { <del> return err <del> } <del> } <del> } <del> return nil <del>} <del> <del>func setupMemory(container *libcontainer.Container, cgroupRoot string, pid int) (err error) { <del> if container.Cgroups.Memory != 0 || container.Cgroups.MemorySwap != 0 { <del> dir, err := container.Cgroups.Join(cgroupRoot, "memory", pid) <del> if err != nil { <del> return err <del> } <del> defer func() { <del> if err != nil { <del> os.RemoveAll(dir) <del> } <del> }() <del> <del> if container.Cgroups.Memory != 0 { <del> if err := writeFile(dir, "memory.limit_in_bytes", strconv.FormatInt(container.Cgroups.Memory, 10)); err != nil { <del> return err <del> } <del> if err := writeFile(dir, "memory.soft_limit_in_bytes", strconv.FormatInt(container.Cgroups.Memory, 10)); err != nil { <del> return err <del> } <del> } <del> if container.Cgroups.MemorySwap != 0 { <del> if err := writeFile(dir, "memory.memsw.limit_in_bytes", strconv.FormatInt(container.Cgroups.MemorySwap, 10)); err != nil { <del> return err <del> } <del> } <del> } <del> return nil <del>} <del> <del>func setupCpu(container *libcontainer.Container, cgroupRoot string, pid int) (err error) { <del> // We always want to join the cpu group, to allow fair cpu scheduling <del> // on a container basis <del> dir, err := container.Cgroups.Join(cgroupRoot, "cpu", pid) <del> if err != nil { <del> return err <del> } <del> if container.Cgroups.CpuShares != 0 { <del> if err := writeFile(dir, "cpu.shares", strconv.FormatInt(container.Cgroups.CpuShares, 10)); err != nil { <del> return err <del> } <del> } <del> return nil <del>} <del> <del>func writeFile(dir, file, data string) error { <del> return ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700) <del>} <ide><path>pkg/libcontainer/nsinit/exec.go <ide> package main <ide> import ( <ide> "fmt" <ide> "github.com/dotcloud/docker/pkg/libcontainer" <del> "github.com/dotcloud/docker/pkg/libcontainer/cgroup" <ide> "github.com/dotcloud/docker/pkg/libcontainer/network" <ide> "github.com/dotcloud/docker/pkg/libcontainer/utils" <ide> "github.com/dotcloud/docker/pkg/system" <ide> func execCommand(container *libcontainer.Container, args []string) (int, error) <ide> <ide> // Do this before syncing with child so that no children <ide> // can escape the cgroup <del> if err := cgroup.ApplyCgroup(container, command.Process.Pid); err != nil { <del> command.Process.Kill() <del> return -1, err <add> if container.Cgroups != nil { <add> if err := container.Cgroups.Apply(command.Process.Pid); err != nil { <add> command.Process.Kill() <add> return -1, err <add> } <ide> } <ide> <ide> if container.Network != nil {
3
Java
Java
refine @testpropertysource merged annotation calls
c9479ff20f9e4ad2641928cd6a842ec55f2260d0
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceAttributes.java <ide> <ide> package org.springframework.test.context.support; <ide> <add>import java.util.ArrayList; <add>import java.util.Arrays; <ide> import java.util.List; <ide> <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <add> <add>import org.springframework.core.annotation.MergedAnnotation; <add>import org.springframework.core.io.ClassPathResource; <add>import org.springframework.core.log.LogMessage; <ide> import org.springframework.core.style.ToStringCreator; <ide> import org.springframework.test.context.TestPropertySource; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.ClassUtils; <ide> import org.springframework.util.ObjectUtils; <add>import org.springframework.util.ResourceUtils; <ide> <ide> /** <ide> * {@code TestPropertySourceAttributes} encapsulates attributes declared <ide> */ <ide> class TestPropertySourceAttributes { <ide> <add> private static final Log logger = LogFactory.getLog(TestPropertySourceAttributes.class); <add> <add> <add> private final int aggregateIndex; <add> <ide> private final Class<?> declaringClass; <ide> <del> private final String[] locations; <add> private final List<String> locations; <ide> <ide> private final boolean inheritLocations; <ide> <del> private final String[] properties; <add> private final List<String> properties; <ide> <ide> private final boolean inheritProperties; <ide> <ide> <del> /** <del> * Create a new {@code TestPropertySourceAttributes} instance for the supplied <del> * values and enforce configuration rules. <del> * @param declaringClass the class that declared {@code @TestPropertySource} <del> * @param locations the merged {@link TestPropertySource#locations()} <del> * @param inheritLocations the {@link TestPropertySource#inheritLocations()} flag <del> * @param properties the merged {@link TestPropertySource#properties()} <del> * @param inheritProperties the {@link TestPropertySource#inheritProperties()} flag <del> * @since 5.2 <del> */ <del> TestPropertySourceAttributes(Class<?> declaringClass, List<String> locations, boolean inheritLocations, <del> List<String> properties, boolean inheritProperties) { <add> TestPropertySourceAttributes(MergedAnnotation<TestPropertySource> annotation) { <add> this.aggregateIndex = annotation.getAggregateIndex(); <add> this.declaringClass = (Class<?>) annotation.getSource(); <add> this.inheritLocations = annotation.getBoolean("inheritLocations"); <add> this.inheritProperties = annotation.getBoolean("inheritProperties"); <add> this.properties = new ArrayList<>(); <add> this.locations = new ArrayList<>(); <add> mergePropertiesAndLocations(annotation); <add> } <ide> <del> this(declaringClass, locations.toArray(new String[0]), inheritLocations, properties.toArray(new String[0]), <del> inheritProperties); <add> <add> boolean canMerge(MergedAnnotation<TestPropertySource> annotation) { <add> return annotation.getAggregateIndex() == this.aggregateIndex; <add> } <add> <add> void merge(MergedAnnotation<TestPropertySource> annotation) { <add> Assert.state((Class<?>) annotation.getSource() == this.declaringClass, <add> () -> "Detected @TestPropertySource declarations within an aggregate index " <add> + "with different source: " + this.declaringClass + " and " <add> + annotation.getSource()); <add> logger.trace(LogMessage.format("Retrieved %s for declaring class [%s].", <add> annotation, this.declaringClass.getName())); <add> assertSameBooleanAttribute(this.inheritLocations, annotation, "inheritLocations"); <add> assertSameBooleanAttribute(this.inheritProperties, annotation, "inheritProperties"); <add> mergePropertiesAndLocations(annotation); <ide> } <ide> <del> private TestPropertySourceAttributes(Class<?> declaringClass, String[] locations, boolean inheritLocations, <del> String[] properties, boolean inheritProperties) { <add> private void assertSameBooleanAttribute(boolean expected, <add> MergedAnnotation<TestPropertySource> annotation, String attribute) { <add> Assert.isTrue(expected == annotation.getBoolean(attribute), () -> String.format( <add> "Classes %s and %s must declare the same value for '%s' as other directly " + <add> "present or meta-present @TestPropertySource annotations", this.declaringClass.getName(), <add> ((Class<?>) annotation.getSource()).getName(), attribute)); <add> } <ide> <del> Assert.notNull(declaringClass, "'declaringClass' must not be null"); <del> Assert.isTrue(!ObjectUtils.isEmpty(locations) || !ObjectUtils.isEmpty(properties), <del> "Either 'locations' or 'properties' are required"); <add> private void mergePropertiesAndLocations( <add> MergedAnnotation<TestPropertySource> annotation) { <add> String[] locations = annotation.getStringArray("locations"); <add> String[] properties = annotation.getStringArray("properties"); <add> boolean prepend = annotation.getDistance() > 0; <add> if (ObjectUtils.isEmpty(locations) && ObjectUtils.isEmpty(properties)) { <add> addAll(prepend, this.locations, detectDefaultPropertiesFile(annotation)); <add> } <add> else { <add> addAll(prepend, this.locations, locations); <add> addAll(prepend, this.properties, properties); <add> } <add> } <ide> <del> this.declaringClass = declaringClass; <del> this.locations = locations; <del> this.inheritLocations = inheritLocations; <del> this.properties = properties; <del> this.inheritProperties = inheritProperties; <add> private void addAll(boolean prepend, List<String> list, String... additions) { <add> list.addAll(prepend ? 0 : list.size(), Arrays.asList(additions)); <ide> } <ide> <add> private String detectDefaultPropertiesFile( <add> MergedAnnotation<TestPropertySource> annotation) { <add> Class<?> testClass = (Class<?>) annotation.getSource(); <add> String resourcePath = ClassUtils.convertClassNameToResourcePath(testClass.getName()) + ".properties"; <add> ClassPathResource classPathResource = new ClassPathResource(resourcePath); <add> if (!classPathResource.exists()) { <add> String msg = String.format( <add> "Could not detect default properties file for test class [%s]: " <add> + "%s does not exist. Either declare the 'locations' or 'properties' attributes " <add> + "of @TestPropertySource or make the default properties file available.", <add> testClass.getName(), classPathResource); <add> logger.error(msg); <add> throw new IllegalStateException(msg); <add> } <add> String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath; <add> if (logger.isInfoEnabled()) { <add> logger.info(String.format("Detected default properties file \"%s\" for test class [%s]", <add> prefixedResourcePath, testClass.getName())); <add> } <add> return prefixedResourcePath; <add> } <ide> <ide> /** <ide> * Get the {@linkplain Class class} that declared {@code @TestPropertySource}. <ide> Class<?> getDeclaringClass() { <ide> * @see TestPropertySource#locations <ide> */ <ide> String[] getLocations() { <del> return this.locations; <add> return this.locations.toArray(new String[0]); <ide> } <ide> <ide> /** <ide> boolean isInheritLocations() { <ide> * @see TestPropertySource#properties <ide> */ <ide> String[] getProperties() { <del> return this.properties; <add> return this.properties.toArray(new String[0]); <ide> } <ide> <ide> /** <ide> boolean isInheritProperties() { <ide> @Override <ide> public String toString() { <ide> return new ToStringCreator(this)// <del> .append("declaringClass", this.declaringClass.getName())// <del> .append("locations", ObjectUtils.nullSafeToString(this.locations))// <del> .append("inheritLocations", this.inheritLocations)// <del> .append("properties", ObjectUtils.nullSafeToString(this.properties))// <del> .append("inheritProperties", this.inheritProperties)// <del> .toString(); <add> .append("declaringClass", this.declaringClass.getName()) <add> .append("locations", this.locations) <add> .append("inheritLocations", this.inheritLocations) <add> .append("properties", this.properties) <add> .append("inheritProperties", this.inheritProperties) <add> .toString(); <ide> } <ide> <ide> } <ide><path>spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceUtils.java <ide> import java.io.StringReader; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <del>import java.util.Collections; <del>import java.util.Comparator; <ide> import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Properties; <del>import java.util.TreeMap; <del>import java.util.stream.Collectors; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.core.env.MapPropertySource; <ide> import org.springframework.core.env.PropertySource; <ide> import org.springframework.core.env.PropertySources; <del>import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.core.io.ResourceLoader; <ide> import org.springframework.core.io.support.ResourcePropertySource; <ide> import org.springframework.test.context.TestPropertySource; <ide> import org.springframework.test.context.util.TestContextResourceUtils; <ide> import org.springframework.util.Assert; <del>import org.springframework.util.ClassUtils; <ide> import org.springframework.util.ObjectUtils; <del>import org.springframework.util.ResourceUtils; <ide> import org.springframework.util.StringUtils; <ide> <ide> /** <ide> public abstract class TestPropertySourceUtils { <ide> <ide> private static final Log logger = LogFactory.getLog(TestPropertySourceUtils.class); <ide> <del> /** <del> * Compares {@link MergedAnnotation} instances (presumably within the same <del> * aggregate index) by their meta-distance, in reverse order. <del> * <p>Using this {@link Comparator} to sort according to reverse meta-distance <del> * ensures that directly present annotations take precedence over meta-present <del> * annotations (within a given aggregate index). In other words, this follows <del> * the last-one-wins principle of overriding properties. <del> * @see MergedAnnotation#getAggregateIndex() <del> * @see MergedAnnotation#getDistance() <del> */ <del> private static final Comparator<? super MergedAnnotation<?>> reversedMetaDistanceComparator = <del> Comparator.<MergedAnnotation<?>> comparingInt(MergedAnnotation::getDistance).reversed(); <del> <ide> <ide> static MergedTestPropertySources buildMergedTestPropertySources(Class<?> testClass) { <ide> MergedAnnotations mergedAnnotations = MergedAnnotations.from(testClass, SearchStrategy.EXHAUSTIVE); <ide> private static MergedTestPropertySources mergeTestPropertySources(MergedAnnotati <ide> private static List<TestPropertySourceAttributes> resolveTestPropertySourceAttributes( <ide> MergedAnnotations mergedAnnotations) { <ide> <del> // Group by aggregate index to ensure proper separation of inherited and local annotations. <del> Map<Integer, List<MergedAnnotation<TestPropertySource>>> aggregateIndexMap = mergedAnnotations <del> .stream(TestPropertySource.class) <del> .collect(Collectors.groupingBy(MergedAnnotation::getAggregateIndex, TreeMap::new, <del> Collectors.mapping(x -> x, Collectors.toList()))); <del> <del> // Stream the lists of annotations per aggregate index, merge each list into a <del> // single TestPropertySourceAttributes instance, and collect the results. <del> return aggregateIndexMap.values().stream() <del> .map(TestPropertySourceUtils::createTestPropertySourceAttributes) <del> .collect(Collectors.toList()); <add> List<TestPropertySourceAttributes> result = new ArrayList<>(); <add> mergedAnnotations.stream(TestPropertySource.class) <add> .forEach(annotation -> addOrMergeTestPropertySourceAttributes(result, annotation)); <add> return result; <ide> } <ide> <del> /** <del> * Create a merged {@link TestPropertySourceAttributes} instance from all <del> * annotations in the supplied list for a given aggregate index as if there <del> * were only one such annotation. <del> * <p>Within the supplied list, sort according to reversed meta-distance of <del> * the annotations from the declaring class. This ensures that directly present <del> * annotations take precedence over meta-present annotations within the current <del> * aggregate index. <del> * <p>If a given {@link TestPropertySource @TestPropertySource} does not <del> * declare properties or locations, an attempt will be made to detect a default <del> * properties file. <del> */ <del> private static TestPropertySourceAttributes createTestPropertySourceAttributes( <del> List<MergedAnnotation<TestPropertySource>> list) { <del> <del> list.sort(reversedMetaDistanceComparator); <del> <del> List<String> locations = new ArrayList<>(); <del> List<String> properties = new ArrayList<>(); <del> Class<?> declaringClass = null; <del> Boolean inheritLocations = null; <del> Boolean inheritProperties = null; <del> <del> // Merge all @TestPropertySource annotations within the current <del> // aggregate index into a single TestPropertySourceAttributes instance, <del> // simultaneously ensuring that all such annotations have the same <del> // declaringClass, inheritLocations, and inheritProperties values. <del> for (MergedAnnotation<TestPropertySource> mergedAnnotation : list) { <del> Class<?> currentDeclaringClass = (Class<?>) mergedAnnotation.getSource(); <del> if (declaringClass != null && !declaringClass.equals(currentDeclaringClass)) { <del> throw new IllegalStateException("Detected @TestPropertySource declarations within an aggregate index " + <del> "with different declaring classes: " + declaringClass.getName() + " and " + <del> currentDeclaringClass.getName()); <del> } <del> declaringClass = currentDeclaringClass; <del> <del> TestPropertySource testPropertySource = mergedAnnotation.synthesize(); <del> if (logger.isTraceEnabled()) { <del> logger.trace(String.format("Retrieved %s for declaring class [%s].", testPropertySource, <del> declaringClass.getName())); <del> } <del> <del> Boolean currentInheritLocations = testPropertySource.inheritLocations(); <del> assertConsistentValues(testPropertySource, declaringClass, "inheritLocations", inheritLocations, <del> currentInheritLocations); <del> inheritLocations = currentInheritLocations; <add> private static void addOrMergeTestPropertySourceAttributes( <add> List<TestPropertySourceAttributes> result, <add> MergedAnnotation<TestPropertySource> annotation) { <ide> <del> Boolean currentInheritProperties = testPropertySource.inheritProperties(); <del> assertConsistentValues(testPropertySource, declaringClass, "inheritProperties", inheritProperties, <del> currentInheritProperties); <del> inheritProperties = currentInheritProperties; <del> <del> String[] currentLocations = testPropertySource.locations(); <del> String[] currentProperties = testPropertySource.properties(); <del> if (ObjectUtils.isEmpty(currentLocations) && ObjectUtils.isEmpty(currentProperties)) { <del> locations.add(detectDefaultPropertiesFile(declaringClass)); <del> } <del> else { <del> Collections.addAll(locations, currentLocations); <del> Collections.addAll(properties, currentProperties); <del> } <del> } <del> <del> TestPropertySourceAttributes attributes = new TestPropertySourceAttributes(declaringClass, locations, <del> inheritLocations, properties, inheritProperties); <del> if (logger.isTraceEnabled()) { <del> logger.trace(String.format("Resolved @TestPropertySource attributes %s for declaring class [%s].", <del> attributes, declaringClass.getName())); <del> } <del> return attributes; <del> } <del> <del> private static void assertConsistentValues(TestPropertySource testPropertySource, Class<?> declaringClass, <del> String attributeName, Object trackedValue, Object currentValue) { <del> <del> Assert.isTrue((trackedValue == null || trackedValue.equals(currentValue)), <del> () -> String.format("%s on class [%s] must declare the same value for '%s' " + <del> "as other directly present or meta-present @TestPropertySource annotations on [%2$s].", <del> testPropertySource, declaringClass.getName(), attributeName)); <del> } <del> <del> /** <del> * Detect a default properties file for the supplied class, as specified <del> * in the class-level Javadoc for {@link TestPropertySource}. <del> */ <del> private static String detectDefaultPropertiesFile(Class<?> testClass) { <del> String resourcePath = ClassUtils.convertClassNameToResourcePath(testClass.getName()) + ".properties"; <del> ClassPathResource classPathResource = new ClassPathResource(resourcePath); <del> <del> if (classPathResource.exists()) { <del> String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath; <del> if (logger.isInfoEnabled()) { <del> logger.info(String.format("Detected default properties file \"%s\" for test class [%s]", <del> prefixedResourcePath, testClass.getName())); <del> } <del> return prefixedResourcePath; <add> if (result.isEmpty() || !result.get(result.size()-1).canMerge(annotation)) { <add> result.add(new TestPropertySourceAttributes(annotation)); <ide> } <ide> else { <del> String msg = String.format("Could not detect default properties file for test class [%s]: " + <del> "%s does not exist. Either declare the 'locations' or 'properties' attributes " + <del> "of @TestPropertySource or make the default properties file available.", testClass.getName(), <del> classPathResource); <del> logger.error(msg); <del> throw new IllegalStateException(msg); <add> result.get(result.size() - 1).merge(annotation); <ide> } <ide> } <ide>
2
Ruby
Ruby
prefer string#== over string#=== for clarity
4257ea756b0a5fbec4719aebf5ff846105833e73
<ide><path>actionpack/lib/action_dispatch/journey/route.rb <ide> def initialize(verb) <ide> @verb = verb <ide> end <ide> <del> def call(request); @verb === request.request_method; end <add> def call(request); @verb == request.request_method; end <ide> end <ide> <ide> class All
1
Javascript
Javascript
remove unused vars in childprocess tests
2b1999b7c7b32931b14cc8df554fc4fa46950ecc
<ide><path>test/parallel/test-child-process-buffering.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> <del>var spawn = require('child_process').spawn; <del> <ide> var pwd_called = false; <ide> var childClosed = false; <ide> var childExited = false; <ide><path>test/parallel/test-child-process-cwd.js <ide> 'use strict'; <ide> var common = require('../common'); <ide> var assert = require('assert'); <del>var spawn = require('child_process').spawn; <del>var path = require('path'); <ide> <ide> var returns = 0; <ide> <ide><path>test/parallel/test-child-process-exec-buffer.js <ide> var success_count = 0; <ide> var str = 'hello'; <ide> <ide> // default encoding <del>var child = exec('echo ' + str, function(err, stdout, stderr) { <add>exec('echo ' + str, function(err, stdout, stderr) { <ide> assert.ok('string', typeof(stdout), 'Expected stdout to be a string'); <ide> assert.ok('string', typeof(stderr), 'Expected stderr to be a string'); <ide> assert.equal(str + os.EOL, stdout); <ide><path>test/parallel/test-child-process-exec-cwd.js <ide> if (common.isWindows) { <ide> dir = '/dev'; <ide> } <ide> <del>var child = exec(pwdcommand, {cwd: dir}, function(err, stdout, stderr) { <add>exec(pwdcommand, {cwd: dir}, function(err, stdout, stderr) { <ide> if (err) { <ide> error_count++; <ide> console.log('error!: ' + err.code); <ide><path>test/parallel/test-child-process-fork-dgram.js <ide> if (common.isWindows) { <ide> } <ide> <ide> if (process.argv[2] === 'child') { <del> var childCollected = 0; <ide> var server; <ide> <ide> process.on('message', function removeMe(msg, clusterServer) { <ide><path>test/parallel/test-child-process-fork-exec-path.js <ide> 'use strict'; <ide> var assert = require('assert'); <del>var cp = require('child_process'); <ide> var fs = require('fs'); <ide> var path = require('path'); <ide> var common = require('../common'); <ide><path>test/parallel/test-child-process-fork-ref2.js <ide> 'use strict'; <ide> require('../common'); <del>var assert = require('assert'); <ide> var fork = require('child_process').fork; <ide> <ide> if (process.argv[2] === 'child') { <ide><path>test/parallel/test-child-process-spawn-error.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var fs = require('fs'); <ide> var spawn = require('child_process').spawn; <ide> var assert = require('assert'); <ide> <ide><path>test/parallel/test-child-process-stdin.js <ide> var response = ''; <ide> var exitStatus = -1; <ide> var closed = false; <ide> <del>var gotStdoutEOF = false; <del> <ide> cat.stdout.setEncoding('utf8'); <ide> cat.stdout.on('data', function(chunk) { <ide> console.log('stdout: ' + chunk); <ide> response += chunk; <ide> }); <ide> <del>cat.stdout.on('end', function() { <del> gotStdoutEOF = true; <del>}); <del> <del> <del>var gotStderrEOF = false; <add>cat.stdout.on('end', common.mustCall(function() {})); <ide> <ide> cat.stderr.on('data', function(chunk) { <ide> // shouldn't get any stderr output <ide> assert.ok(false); <ide> }); <ide> <del>cat.stderr.on('end', function(chunk) { <del> gotStderrEOF = true; <del>}); <del> <add>cat.stderr.on('end', common.mustCall(function() {})); <ide> <ide> cat.on('exit', function(status) { <ide> console.log('exit event'); <ide><path>test/parallel/test-child-process-stdio-inherit.js <ide> function grandparent() { <ide> <ide> function parent() { <ide> // should not immediately exit. <del> var child = common.spawnCat({ stdio: 'inherit' }); <add> common.spawnCat({ stdio: 'inherit' }); <ide> } <ide><path>test/parallel/test-child-process-stdio.js <ide> 'use strict'; <ide> var common = require('../common'); <ide> var assert = require('assert'); <del>var spawn = require('child_process').spawn; <ide> <ide> var options = {stdio: ['pipe']}; <ide> var child = common.spawnPwd(options); <ide><path>test/parallel/test-child-process-stdout-flush-exit.js <ide> 'use strict'; <ide> var common = require('../common'); <ide> var assert = require('assert'); <del>var path = require('path'); <ide> <ide> // if child process output to console and exit <ide> if (process.argv[2] === 'child') {
12
Python
Python
add a new ovh driver for storage
ff9a5aa752705197476d885235f2ade8956911b8
<ide><path>libcloud/storage/drivers/ovh.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <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>from libcloud.storage.drivers.s3 import ( <add> S3SignatureV4Connection, <add> S3StorageDriver, <add> S3_CDN_URL_EXPIRY_HOURS, <add>) <add>from libcloud.storage.drivers.s3 import BaseS3StorageDriver <add> <add>__all__ = ["OvhStorageDriver"] <add> <add>OVH_FR_SBG_HOST = "s3.sbg.perf.cloud.ovh.net" <add>OVH_FR_GRA_HOST = "s3.gra.perf.cloud.ovh.net" <add> <add># Maps OVH region name to connection hostname <add>REGION_TO_HOST_MAP = { <add> "sbg": OVH_FR_SBG_HOST, <add> "gra": OVH_FR_GRA_HOST, <add>} <add> <add>NO_CDN_SUPPORT_ERROR = "CDN feature not implemented" <add> <add> <add>class OvhStorageDriver(BaseS3StorageDriver): <add> name = "Ovh Storage Driver" <add> website = "https://www.ovhcloud.com/en/public-cloud/object-storage/" <add> connectionCls = S3SignatureV4Connection <add> region_name = "sbg" <add> <add> def __init__( <add> self, <add> key, <add> secret=None, <add> secure=True, <add> host=None, <add> port=None, <add> region="sbg", <add> url=None, <add> **kwargs, <add> ): <add> # Here for backward compatibility for old and deprecated driver class <add> # per region approach <add> if hasattr(self, "region_name") and not region: <add> region = self.region_name # pylint: disable=no-member <add> <add> self.region_name = region <add> <add> if region and region not in REGION_TO_HOST_MAP.keys(): <add> raise ValueError("Invalid or unsupported region: %s" % (region)) <add> <add> self.name = "Ovh Object Storage (%s)" % (region) <add> <add> if host is None: <add> self.connectionCls.host = REGION_TO_HOST_MAP[region] <add> else: <add> self.connectionCls.host = host <add> <add> super(OvhStorageDriver, self).__init__( <add> key=key, <add> secret=secret, <add> secure=secure, <add> host=host, <add> port=port, <add> region=region, <add> url=url, <add> **kwargs, <add> ) <add> <add> @classmethod <add> def list_regions(self): <add> return REGION_TO_HOST_MAP.keys() <add> <add> def get_object_cdn_url(self, obj, ex_expiry=S3_CDN_URL_EXPIRY_HOURS): <add> # In order to download (private) objects we need to be able to generate a valid CDN URL, <add> # hence shamefully just use the working code from the S3StorageDriver. <add> return S3StorageDriver.get_object_cdn_url(self, obj, ex_expiry=ex_expiry) <ide><path>libcloud/storage/providers.py <ide> ), <ide> Provider.MINIO: ("libcloud.storage.drivers.minio", "MinIOStorageDriver"), <ide> Provider.SCALEWAY: ("libcloud.storage.drivers.scaleway", "ScalewayStorageDriver"), <add> Provider.OVH: ("libcloud.storage.drivers.ovh", "OvhStorageDriver"), <ide> } <ide> <del> <ide> def get_driver(provider): <ide> # type: (Union[Provider, str]) -> Type[StorageDriver] <ide> deprecated_constants = OLD_CONSTANT_TO_NEW_MAPPING <ide><path>libcloud/storage/types.py <ide> class Provider(object): <ide> S3_RGW_OUTSCALE = "s3_rgw_outscale" <ide> MINIO = "minio" <ide> SCALEWAY = "scaleway" <add> OVH="ovh" <ide> <ide> # Deperecated <ide> CLOUDFILES_US = "cloudfiles_us"
3
PHP
PHP
add option to inline slot content
f6a24ada98c683f49a1606757f7cb0242226057b
<ide><path>src/Illuminate/View/Concerns/ManagesComponents.php <ide> protected function componentData($name) <ide> * Start the slot rendering process. <ide> * <ide> * @param string $name <add> * @param string|null $content <ide> * @return void <ide> */ <del> public function slot($name) <add> public function slot($name, $content = null) <ide> { <del> if (ob_start()) { <del> $this->slots[$this->currentComponent()][$name] = ''; <del> <del> $this->slotStack[$this->currentComponent()][] = $name; <add> if ($content !== null) { <add> $this->slots[$this->currentComponent()][$name] = $content; <add> } else { <add> if (ob_start()) { <add> $this->slots[$this->currentComponent()][$name] = ''; <add> <add> $this->slotStack[$this->currentComponent()][] = $name; <add> } <ide> } <ide> } <ide> <ide><path>tests/View/ViewFactoryTest.php <ide> public function testComponentHandling() <ide> $factory->getDispatcher()->shouldReceive('fire'); <ide> $factory->startComponent('component', ['name' => 'Taylor']); <ide> $factory->slot('title'); <add> $factory->slot('website', 'laravel.com'); <ide> echo 'title<hr>'; <ide> $factory->endSlot(); <ide> echo 'component'; <ide> $contents = $factory->renderComponent(); <del> $this->assertEquals('title<hr> component Taylor', $contents); <add> $this->assertEquals('title<hr> component Taylor laravel.com', $contents); <ide> } <ide> <ide> public function testTranslation() <ide><path>tests/View/fixtures/component.php <del><?php echo $title; ?> <?php echo $slot; ?> <?php echo $name; ?> <add><?php echo $title; ?> <?php echo $slot; ?> <?php echo $name; ?> <?php echo $website; ?>
3
Javascript
Javascript
use hashooks function internally
1c816f0c591cd0242930e8605c5473416cc94241
<ide><path>lib/internal/async_hooks.js <ide> function defaultTriggerAsyncIdScope(triggerAsyncId, block, ...args) { <ide> } <ide> } <ide> <add>function hasHooks(key) { <add> return async_hook_fields[key] > 0; <add>} <add> <ide> function enabledHooksExist() { <del> return async_hook_fields[kCheck] > 0; <add> return hasHooks(kCheck); <ide> } <ide> <ide> function initHooksExist() { <del> return async_hook_fields[kInit] > 0; <add> return hasHooks(kInit); <ide> } <ide> <ide> function afterHooksExist() { <del> return async_hook_fields[kAfter] > 0; <add> return hasHooks(kAfter); <ide> } <ide> <ide> function destroyHooksExist() { <del> return async_hook_fields[kDestroy] > 0; <add> return hasHooks(kDestroy); <ide> } <ide> <ide> <ide> function emitInitScript(asyncId, type, triggerAsyncId, resource) { <ide> // Short circuit all checks for the common case. Which is that no hooks have <ide> // been set. Do this to remove performance impact for embedders (and core). <del> if (async_hook_fields[kInit] === 0) <add> if (!hasHooks(kInit)) <ide> return; <ide> <ide> if (triggerAsyncId === null) { <ide> function emitInitScript(asyncId, type, triggerAsyncId, resource) { <ide> function emitBeforeScript(asyncId, triggerAsyncId, resource) { <ide> pushAsyncContext(asyncId, triggerAsyncId, resource); <ide> <del> if (async_hook_fields[kBefore] > 0) <add> if (hasHooks(kBefore)) <ide> emitBeforeNative(asyncId); <ide> } <ide> <ide> <ide> function emitAfterScript(asyncId) { <del> if (async_hook_fields[kAfter] > 0) <add> if (hasHooks(kAfter)) <ide> emitAfterNative(asyncId); <ide> <ide> popAsyncContext(asyncId); <ide> function emitAfterScript(asyncId) { <ide> <ide> function emitDestroyScript(asyncId) { <ide> // Return early if there are no destroy callbacks, or invalid asyncId. <del> if (async_hook_fields[kDestroy] === 0 || asyncId <= 0) <add> if (!hasHooks(kDestroy) || asyncId <= 0) <ide> return; <ide> async_wrap.queueDestroyAsyncId(asyncId); <ide> } <ide> function clearAsyncIdStack() { <ide> <ide> <ide> function hasAsyncIdStack() { <del> return async_hook_fields[kStackLength] > 0; <add> return hasHooks(kStackLength); <ide> } <ide> <ide>
1
Text
Text
adjust table alignment for remark v13
dbdd234e4bada1d006c5b62b99406383272f20e8
<ide><path>BUILDING.md <ide> Depending on the host platform, the selection of toolchains may vary. <ide> <ide> Binaries at <https://nodejs.org/download/release/> are produced on: <ide> <del>| Binary package | Platform and Toolchain | <del>| --------------------- | ------------------------------------------------------------------------ | <del>| aix-ppc64 | AIX 7.1 TL05 on PPC64BE with GCC 6 | <del>| darwin-x64 (and .pkg) | macOS 10.15, Xcode Command Line Tools 11 with -mmacosx-version-min=10.13 | <del>| linux-arm64 | CentOS 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> | <del>| linux-armv7l | Cross-compiled on Ubuntu 18.04 x64 with [custom GCC toolchain](https://github.com/rvagg/rpi-newer-crosstools) | <del>| linux-ppc64le | CentOS 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> | <del>| linux-s390x | RHEL 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> | <del>| linux-x64 | CentOS 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> | <del>| win-x64 and win-x86 | Windows 2012 R2 (x64) with Visual Studio 2019 | <add>| Binary package | Platform and Toolchain | <add>| --------------------- | ------------------------------------------------------------------------------------------------------------- | <add>| aix-ppc64 | AIX 7.1 TL05 on PPC64BE with GCC 6 | <add>| darwin-x64 (and .pkg) | macOS 10.15, Xcode Command Line Tools 11 with -mmacosx-version-min=10.13 | <add>| linux-arm64 | CentOS 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> | <add>| linux-armv7l | Cross-compiled on Ubuntu 18.04 x64 with [custom GCC toolchain](https://github.com/rvagg/rpi-newer-crosstools) | <add>| linux-ppc64le | CentOS 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> | <add>| linux-s390x | RHEL 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> | <add>| linux-x64 | CentOS 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> | <add>| win-x64 and win-x86 | Windows 2012 R2 (x64) with Visual Studio 2019 | <ide> <ide> <em id="fn8">8</em>: The Enterprise Linux devtoolset-8 allows us to compile <ide> binaries with GCC 8 but linked to the glibc and libstdc++ versions of the host <ide><path>doc/api/fs.md <ide> the permissions for the file owner. The middle digit (`6` in the example), <ide> specifies permissions for the group. The right-most digit (`5` in the example), <ide> specifies the permissions for others. <ide> <del>| Number | Description | <del>| ------- | ------------------------ | <del>| `7` | read, write, and execute | <del>| `6` | read and write | <del>| `5` | read and execute | <del>| `4` | read only | <del>| `3` | write and execute | <del>| `2` | write only | <del>| `1` | execute only | <del>| `0` | no permission | <add>| Number | Description | <add>| ------ | ------------------------ | <add>| `7` | read, write, and execute | <add>| `6` | read and write | <add>| `5` | read and execute | <add>| `4` | read only | <add>| `3` | write and execute | <add>| `2` | write only | <add>| `1` | execute only | <add>| `0` | no permission | <ide> <ide> For example, the octal value `0o765` means: <ide> <ide><path>doc/api/util.md <ide> Different Node.js build configurations support different sets of encodings. <ide> <ide> #### Encodings supported when Node.js is built with the `small-icu` option <ide> <del>| Encoding | Aliases | <del>| ----------- | --------------------------------- | <del>| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | <del>| `'utf-16le'` | `'utf-16'` | <del>| `'utf-16be'` | | <add>| Encoding | Aliases | <add>| ----------- | ------------------------------- | <add>| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | <add>| `'utf-16le'` | `'utf-16'` | <add>| `'utf-16be'` | | <ide> <ide> #### Encodings supported when ICU is disabled <ide> <del>| Encoding | Aliases | <del>| ----------- | --------------------------------- | <del>| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | <del>| `'utf-16le'` | `'utf-16'` | <add>| Encoding | Aliases | <add>| ----------- | ------------------------------- | <add>| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | <add>| `'utf-16le'` | `'utf-16'` | <ide> <ide> The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] <ide> is not supported. <ide><path>doc/guides/diagnostic-tooling-support-tiers.md <ide> The tools are currently assigned to Tiers as follows: <ide> <ide> ## Tier 1 <ide> <del> | Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <del> |-----------|---------------------------|-------------------------------|-------------------------|-------------| <del> | FFDC | diagnostic report | Yes | Yes | 1 | <del> | | | | | | <add>| Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <add>|-----------|---------------------------|-------------------------------|-------------------------|-------------| <add>| FFDC | diagnostic report | Yes | Yes | 1 | <add>| | | | | | <ide> <ide> ## Tier 2 <ide> <del> | Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <del> |-----------|---------------------------|-------------------------------|-------------------------|-------------| <del> | | | | | | <add>| Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <add>|-----------|---------------|-------------------------------|-------------------------|-------------| <add>| | | | | | <ide> <ide> ## Tier 3 <ide> <del> | Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <del> |-----------|--------------------------------------|-------------------------------|-------------------------|-------------| <del> | Profiling | V8 CPU profiler | Partial (V8 Tests) | Yes | 1 | <del> | Profiling | --prof/--prof-process flags | Yes | Yes | 1 | <del> | Profiling | V8 CodeEventHandler API | Partial (V8 Tests) | Yes | 2 | <del> | Profiling | V8 --interpreted-frames-native-stack | Yes | Yes | 2 | <del> | Profiling | Linux perf | Yes | Partial | 2 | <add>| Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <add>|-----------|--------------------------------------|-------------------------------|-------------------------|-------------| <add>| Profiling | V8 CPU profiler | Partial (V8 Tests) | Yes | 1 | <add>| Profiling | --prof/--prof-process flags | Yes | Yes | 1 | <add>| Profiling | V8 CodeEventHandler API | Partial (V8 Tests) | Yes | 2 | <add>| Profiling | V8 --interpreted-frames-native-stack | Yes | Yes | 2 | <add>| Profiling | Linux perf | Yes | Partial | 2 | <ide> <ide> ## Tier 4 <ide> <del> | Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <del> |-----------|---------------------------|-------------------------------|-------------------------|-------------| <del> | | | | | | <add>| Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <add>|-----------|---------------|-------------------------------|-------------------------|-------------| <add>| | | | | | <ide> <ide> ## Not yet classified <ide> <del> | Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <del> |-----------|---------------------------|-------------------------------|-------------------------|-------------| <del> | FFDC | node-report | No | No | 1 | <del> | Memory | mdb_V8 | No | No | 4 | <del> | Memory | node-heapdump | No | No | 2 | <del> | Memory | V8 heap profiler | No | Yes | 1 | <del> | Memory | V8 sampling heap profiler | No | Yes | 1 | <del> | AsyncFlow | Async Hooks (API) | ? | Yes | 1 | <del> | Debugger | V8 Debug protocol (API) | No | Yes | 1 | <del> | Debugger | Command line Debug Client | ? | Yes | 1 | <del> | Debugger | llnode | ? | No | 2 | <del> | Debugger | Chrome Dev tools | ? | No | 3 | <del> | Debugger | Chakracore - time-travel | No | Data source only | too early | <del> | Tracing | trace_events (API) | No | Yes | 1 | <del> | Tracing | DTrace | No | Partial | 3 | <del> | Tracing | LTTng | No | Removed? | N/A | <del> | Tracing | ETW | No | Partial | 3 | <del> | Tracing | Systemtap | No | Partial | ? | <del> | Profiling | DTrace | No | Partial | 3 | <del> | Profiling | Windows Xperf | No | ? | ? | <del> | Profiling | 0x | No | No | 4 | <del> | Profiling | node-clinic | No | No | too early | <del> | F/P/T | appmetrics | No | No | ? | <del> | M/T | eBPF tracing tool | No | No | ? | <add>| Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <add>|-----------|---------------------------|-------------------------------|-------------------------|-------------| <add>| FFDC | node-report | No | No | 1 | <add>| Memory | mdb_V8 | No | No | 4 | <add>| Memory | node-heapdump | No | No | 2 | <add>| Memory | V8 heap profiler | No | Yes | 1 | <add>| Memory | V8 sampling heap profiler | No | Yes | 1 | <add>| AsyncFlow | Async Hooks (API) | ? | Yes | 1 | <add>| Debugger | V8 Debug protocol (API) | No | Yes | 1 | <add>| Debugger | Command line Debug Client | ? | Yes | 1 | <add>| Debugger | llnode | ? | No | 2 | <add>| Debugger | Chrome Dev tools | ? | No | 3 | <add>| Debugger | Chakracore - time-travel | No | Data source only | too early | <add>| Tracing | trace_events (API) | No | Yes | 1 | <add>| Tracing | DTrace | No | Partial | 3 | <add>| Tracing | LTTng | No | Removed? | N/A | <add>| Tracing | ETW | No | Partial | 3 | <add>| Tracing | Systemtap | No | Partial | ? | <add>| Profiling | DTrace | No | Partial | 3 | <add>| Profiling | Windows Xperf | No | ? | ? | <add>| Profiling | 0x | No | No | 4 | <add>| Profiling | node-clinic | No | No | too early | <add>| F/P/T | appmetrics | No | No | ? | <add>| M/T | eBPF tracing tool | No | No | ? | <ide><path>doc/guides/doc-style-guide.md <ide> this guide. <ide> * Use [language][]-aware fences. (<code>```js</code>) <ide> * For the [info string][], use one of the following. <ide> <del> | Meaning | Info string | <del> | ------------- | ----------------- | <del> | Bash | `bash` | <del> | C | `c` | <del> | C++ | `cpp` | <del> | CoffeeScript | `coffee` | <del> | Diff | `diff` | <del> | HTTP | `http` | <del> | JavaScript | `js` | <del> | JSON | `json` | <del> | Markdown | `markdown` | <del> | Plaintext | `text` | <del> | Powershell | `powershell` | <del> | R | `r` | <del> | Shell Session | `console` | <add> | Meaning | Info string | <add> | ------------- | ------------ | <add> | Bash | `bash` | <add> | C | `c` | <add> | C++ | `cpp` | <add> | CoffeeScript | `coffee` | <add> | Diff | `diff` | <add> | HTTP | `http` | <add> | JavaScript | `js` | <add> | JSON | `json` | <add> | Markdown | `markdown` | <add> | Plaintext | `text` | <add> | Powershell | `powershell` | <add> | R | `r` | <add> | Shell Session | `console` | <ide> <ide> If one of your language-aware fences needs an info string that is not <ide> already on this list, you may use `text` until the grammar gets added to <ide><path>test/async-hooks/coverage.md <ide> <ide> Showing which kind of async resource is covered by which test: <ide> <del>| Resource Type | Test | <del>|----------------------|--------------------------------------------| <del>| CONNECTION | test-connection.ssl.js | <del>| FSEVENTWRAP | test-fseventwrap.js | <del>| FSREQCALLBACK | test-fsreqcallback-{access,readFile}.js | <del>| GETADDRINFOREQWRAP | test-getaddrinforeqwrap.js | <del>| GETNAMEINFOREQWRAP | test-getnameinforeqwrap.js | <del>| HTTPINCOMINGMESSAGE | test-httpparser.request.js | <del>| HTTPCLIENTREQUEST | test-httpparser.response.js | <del>| Immediate | test-immediate.js | <del>| JSSTREAM | TODO (crashes when accessing directly) | <del>| PBKDF2REQUEST | test-crypto-pbkdf2.js | <del>| PIPECONNECTWRAP | test-pipeconnectwrap.js | <del>| PIPEWRAP | test-pipewrap.js | <del>| PROCESSWRAP | test-pipewrap.js | <del>| QUERYWRAP | test-querywrap.js | <del>| RANDOMBYTESREQUEST | test-crypto-randomBytes.js | <del>| SHUTDOWNWRAP | test-shutdownwrap.js | <del>| SIGNALWRAP | test-signalwrap.js | <del>| STATWATCHER | test-statwatcher.js | <del>| TCPCONNECTWRAP | test-tcpwrap.js | <del>| TCPWRAP | test-tcpwrap.js | <del>| TLSWRAP | test-tlswrap.js | <del>| TTYWRAP | test-ttywrap.{read,write}stream.js | <del>| UDPSENDWRAP | test-udpsendwrap.js | <del>| UDPWRAP | test-udpwrap.js | <del>| WRITEWRAP | test-writewrap.js | <del>| ZLIB | test-zlib.zlib-binding.deflate.js | <add>| Resource Type | Test | <add>|---------------------|-----------------------------------------| <add>| CONNECTION | test-connection.ssl.js | <add>| FSEVENTWRAP | test-fseventwrap.js | <add>| FSREQCALLBACK | test-fsreqcallback-{access,readFile}.js | <add>| GETADDRINFOREQWRAP | test-getaddrinforeqwrap.js | <add>| GETNAMEINFOREQWRAP | test-getnameinforeqwrap.js | <add>| HTTPINCOMINGMESSAGE | test-httpparser.request.js | <add>| HTTPCLIENTREQUEST | test-httpparser.response.js | <add>| Immediate | test-immediate.js | <add>| JSSTREAM | TODO (crashes when accessing directly) | <add>| PBKDF2REQUEST | test-crypto-pbkdf2.js | <add>| PIPECONNECTWRAP | test-pipeconnectwrap.js | <add>| PIPEWRAP | test-pipewrap.js | <add>| PROCESSWRAP | test-pipewrap.js | <add>| QUERYWRAP | test-querywrap.js | <add>| RANDOMBYTESREQUEST | test-crypto-randomBytes.js | <add>| SHUTDOWNWRAP | test-shutdownwrap.js | <add>| SIGNALWRAP | test-signalwrap.js | <add>| STATWATCHER | test-statwatcher.js | <add>| TCPCONNECTWRAP | test-tcpwrap.js | <add>| TCPWRAP | test-tcpwrap.js | <add>| TLSWRAP | test-tlswrap.js | <add>| TTYWRAP | test-ttywrap.{read,write}stream.js | <add>| UDPSENDWRAP | test-udpsendwrap.js | <add>| UDPWRAP | test-udpwrap.js | <add>| WRITEWRAP | test-writewrap.js | <add>| ZLIB | test-zlib.zlib-binding.deflate.js |
6
Java
Java
cleanup the worker
1f8389fdc53253747ad9d961b29ad42179a9941f
<ide><path>src/test/java/rx/schedulers/NewThreadSchedulerTest.java <ide> public final void testHandledErrorIsNotDeliveredToThreadHandler() throws Interru <ide> @Test(timeout = 3000) <ide> public void testNoSelfInterrupt() throws InterruptedException { <ide> Scheduler.Worker worker = Schedulers.newThread().createWorker(); <del> <del> final CountDownLatch run = new CountDownLatch(1); <del> final CountDownLatch done = new CountDownLatch(1); <del> final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); <del> final AtomicBoolean interruptFlag = new AtomicBoolean(); <del> <del> ScheduledAction sa = (ScheduledAction)worker.schedule(new Action0() { <del> @Override <del> public void call() { <del> try { <del> run.await(); <del> } catch (InterruptedException ex) { <del> exception.set(ex); <add> try { <add> final CountDownLatch run = new CountDownLatch(1); <add> final CountDownLatch done = new CountDownLatch(1); <add> final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); <add> final AtomicBoolean interruptFlag = new AtomicBoolean(); <add> <add> ScheduledAction sa = (ScheduledAction)worker.schedule(new Action0() { <add> @Override <add> public void call() { <add> try { <add> run.await(); <add> } catch (InterruptedException ex) { <add> exception.set(ex); <add> } <ide> } <del> } <del> }); <del> <del> sa.add(Subscriptions.create(new Action0() { <del> @Override <del> public void call() { <del> interruptFlag.set(Thread.currentThread().isInterrupted()); <del> done.countDown(); <del> } <del> })); <del> <del> run.countDown(); <del> <del> done.await(); <del> <del> Assert.assertEquals(null, exception.get()); <del> Assert.assertFalse("Interrupted?!", interruptFlag.get()); <add> }); <add> <add> sa.add(Subscriptions.create(new Action0() { <add> @Override <add> public void call() { <add> interruptFlag.set(Thread.currentThread().isInterrupted()); <add> done.countDown(); <add> } <add> })); <add> <add> run.countDown(); <add> <add> done.await(); <add> <add> Assert.assertEquals(null, exception.get()); <add> Assert.assertFalse("Interrupted?!", interruptFlag.get()); <add> } finally { <add> worker.unsubscribe(); <add> } <ide> } <ide> }
1
Javascript
Javascript
remove some useless var
df406d43a170de0da12b89637c3f541182d1dd46
<ide><path>fonts.js <ide> var Font = (function () { <ide> <ide> /** CMAP */ <ide> var charstrings = font.charstrings; <del> cmap = createCMapTable(font.charstrings); <add> cmap = createCMapTable(charstrings); <ide> createTableEntry(otf, offsets, "cmap", cmap); <ide> <ide> /** HEAD */ <ide> CFF.prototype = { <ide> <ide> wrap: function wrap(name, charstrings, subrs, properties) { <ide> // Starts the conversion of the Type1 charstrings to Type2 <del> var charstringsCount = 0; <del> var charstringsDataLength = 0; <del> var glyphs = []; <del> for (var i = 0; i < charstrings.length; i++) { <del> var charstring = charstrings[i].charstring; <del> var glyph = charstrings[i].glyph; <del> <del> var flattened = this.flattenCharstring(glyph, charstring, subrs); <del> glyphs.push(flattened); <del> charstringsCount++; <del> charstringsDataLength += flattened.length; <add> var glyphs = charstrings.slice(); <add> var glyphsCount = glyphs.length; <add> for (var i = 0; i < glyphs.length; i++) { <add> var charstring = glyphs[i]; <add> glyphs[i] = this.flattenCharstring(charstring.glyph, charstring.charstring, subrs); <ide> } <ide> <ide> // Create a CFF font data <ide> CFF.prototype = { <ide> <ide> // Fill the charset header (first byte is the encoding) <ide> var charset = [0x00]; <del> for (var i = 0; i < glyphs.length; i++) { <add> for (var i = 0; i < glyphsCount; i++) { <ide> var index = CFFStrings.indexOf(charstrings[i].glyph); <ide> if (index == -1) <del> index = CFFStrings.length + strings.indexOf(glyph); <add> index = CFFStrings.length + strings.indexOf(charstrings[i].glyph); <ide> var bytes = FontsUtils.integerToBytes(index, 2); <ide> charset.push(bytes[0]); <ide> charset.push(bytes[1]); <ide> CFF.prototype = { <ide> <ide> topDictIndex = topDictIndex.concat([28, 0, 0, 16]) // Encoding <ide> <del> var charstringsOffset = charsetOffset + (charstringsCount * 2) + 1; <add> var charstringsOffset = charsetOffset + (glyphsCount * 2) + 1; <ide> topDictIndex = topDictIndex.concat(this.encodeNumber(charstringsOffset)); <ide> topDictIndex.push(17); // charstrings <ide>
1
Java
Java
remove duplicate word in javadoc
bc261fd9950aa34c4fabae77a9677fd6083be428
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java <ide> public MutablePropertyValues getPropertyValues() { <ide> } <ide> <ide> /** <del> * Return if there are property values values defined for this bean. <add> * Return if there are property values defined for this bean. <ide> * @since 5.0.2 <ide> */ <ide> @Override
1
Text
Text
fix image displayment
061491460d12f0ec1de3172d9f29decbeaf77640
<ide><path>im2txt/README.md <ide> Full text available at: http://arxiv.org/abs/1609.06647 <ide> The *Show and Tell* model is a deep neural network that learns how to describe <ide> the content of images. For example: <ide> <del><center> <ide> ![Example captions](g3doc/example_captions.jpg) <del></center> <ide> <ide> ### Architecture <ide> <ide> learned during training. <ide> <ide> The following diagram illustrates the model architecture. <ide> <del><center> <ide> ![Show and Tell Architecture](g3doc/show_and_tell_architecture.png) <del></center> <ide> <ide> In this diagram, \{*s*<sub>0</sub>, *s*<sub>1</sub>, ..., *s*<sub>*N*-1</sub>\} <ide> are the words of the caption and \{*w*<sub>*e*</sub>*s*<sub>0</sub>,
1
Ruby
Ruby
reduce object allocation during ar instantiation
02f45d6e0ca0a3e6f5fc30b2c99bedee27484197
<ide><path>activerecord/lib/active_record/base.rb <ide> def convert_number_column_value(value) <ide> end <ide> <ide> def populate_with_current_scope_attributes <add> return unless self.class.scope_attributes? <add> <ide> self.class.scope_attributes.each do |att,value| <ide> send("#{att}=", value) if respond_to?("#{att}=") <ide> end <ide><path>activerecord/lib/active_record/named_scope.rb <ide> def scope_attributes # :nodoc: <ide> if current_scope <ide> current_scope.scope_for_create <ide> else <del> # Return an empty hash in the simple case <del> return {} unless default_scopes.any? <del> <ide> scope = relation.clone <ide> scope.default_scoped = true <ide> scope.scope_for_create <ide> end <ide> end <ide> <add> ## <add> # Are there default attributes associated with this scope? <add> def scope_attributes? # :nodoc: <add> current_scope || default_scopes.any? <add> end <add> <ide> # Adds a class method for retrieving and querying objects. A \scope represents a narrowing of a database query, <ide> # such as <tt>where(:color => :red).select('shirts.*').includes(:washing_instructions)</tt>. <ide> #
2
PHP
PHP
add decimal translation
39f4830e92a7467b2a7fe6bc23d0ec14bc3b46a6
<ide><path>lang/en/validation.php <ide> 'date' => 'The :attribute is not a valid date.', <ide> 'date_equals' => 'The :attribute must be a date equal to :date.', <ide> 'date_format' => 'The :attribute does not match the format :format.', <add> 'decimal' => 'The :attribute must have :decimal decimal places.', <ide> 'declined' => 'The :attribute must be declined.', <ide> 'declined_if' => 'The :attribute must be declined when :other is :value.', <ide> 'different' => 'The :attribute and :other must be different.',
1
PHP
PHP
update response to handle json requests as well
dfa2915aea00cd3f296e458c5f73b62824a86195
<ide><path>src/Illuminate/Foundation/Http/FormRequest.php <ide> protected function failedAuthorization() <ide> */ <ide> public function response(array $errors) <ide> { <del> if ($this->ajax()) <add> if ($this->ajax() || $this->wantsJson()) <ide> { <ide> return new JsonResponse($errors, 422); <ide> }
1
Javascript
Javascript
simplify annotation data passing
995c5ba20509876b90edb76666fe4c75a0b7d0c7
<ide><path>src/core/annotation.js <ide> var Annotation = (function AnnotationClosure() { <ide> } <ide> }, <ide> <del> getData: function Annotation_getData() { <del> return this.data; <del> }, <del> <ide> isInvisible: function Annotation_isInvisible() { <ide> var data = this.data; <ide> if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) { <ide><path>src/core/core.js <ide> var Page = (function PageClosure() { <ide> return shadow(this, 'view', cropBox); <ide> }, <ide> <del> get annotationRefs() { <del> return shadow(this, 'annotationRefs', <del> this.getInheritedPageProp('Annots')); <del> }, <del> <ide> get rotate() { <ide> var rotate = this.getInheritedPageProp('Rotate') || 0; <ide> // Normalize rotation so it's a multiple of 90 and between 0 and 270 <ide> var Page = (function PageClosure() { <ide> var annotations = this.annotations; <ide> var annotationsData = []; <ide> for (var i = 0, n = annotations.length; i < n; ++i) { <del> annotationsData.push(annotations[i].getData()); <add> annotationsData.push(annotations[i].data); <ide> } <ide> return annotationsData; <ide> }, <ide> <ide> get annotations() { <ide> var annotations = []; <del> var annotationRefs = (this.annotationRefs || []); <add> var annotationRefs = this.getInheritedPageProp('Annots') || []; <ide> for (var i = 0, n = annotationRefs.length; i < n; ++i) { <ide> var annotationRef = annotationRefs[i]; <ide> var annotation = Annotation.fromRef(this.xref, annotationRef); <ide><path>src/display/api.js <ide> var PDFPageProxy = (function PDFPageProxyClosure() { <ide> * annotation objects. <ide> */ <ide> getAnnotations: function PDFPageProxy_getAnnotations() { <del> if (this.annotationsPromise) { <del> return this.annotationsPromise; <add> if (!this.annotationsPromise) { <add> this.annotationsPromise = this.transport.getAnnotations(this.pageIndex); <ide> } <del> <del> var promise = this.transport.getAnnotations(this.pageIndex); <del> this.annotationsPromise = promise; <del> return promise; <add> return this.annotationsPromise; <ide> }, <ide> /** <ide> * Begins the process of rendering a page to the desired context.
3
PHP
PHP
remove @throws tags from i18n functions
e83159f3ff56b155f79002240bd42e2753d0a7a9
<ide><path>src/I18n/functions.php <ide> * @param string $singular Text to translate. <ide> * @param array ...$args Array with arguments or multiple arguments in function. <ide> * @return string|null The translated text, or null if invalid. <del> * @throws \Aura\Intl\Exception <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__ <ide> */ <ide> function __($singular, ...$args) <ide> function __($singular, ...$args) <ide> * @param int $count Count. <ide> * @param array ...$args Array with arguments or multiple arguments in function. <ide> * @return string|null Plural form of translated string, or null if invalid. <del> * @throws \Aura\Intl\Exception <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__n <ide> */ <ide> function __n($singular, $plural, $count, ...$args) <ide> function __n($singular, $plural, $count, ...$args) <ide> * @param string $msg String to translate. <ide> * @param array ...$args Array with arguments or multiple arguments in function. <ide> * @return string|null Translated string. <del> * @throws \Aura\Intl\Exception <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__d <ide> */ <ide> function __d($domain, $msg, ...$args) <ide> function __d($domain, $msg, ...$args) <ide> * @param int $count Count. <ide> * @param array ...$args Array with arguments or multiple arguments in function. <ide> * @return string|null Plural form of translated string. <del> * @throws \Aura\Intl\Exception <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__dn <ide> */ <ide> function __dn($domain, $singular, $plural, $count, ...$args) <ide> function __dn($domain, $singular, $plural, $count, ...$args) <ide> * @param string $singular Text to translate. <ide> * @param array ...$args Array with arguments or multiple arguments in function. <ide> * @return string|null Translated string. <del> * @throws \Aura\Intl\Exception <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__x <ide> */ <ide> function __x($context, $singular, ...$args) <ide> function __x($context, $singular, ...$args) <ide> * @param int $count Count. <ide> * @param array ...$args Array with arguments or multiple arguments in function. <ide> * @return string|null Plural form of translated string. <del> * @throws \Aura\Intl\Exception <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__xn <ide> */ <ide> function __xn($context, $singular, $plural, $count, ...$args) <ide> function __xn($context, $singular, $plural, $count, ...$args) <ide> * @param string $msg String to translate. <ide> * @param array ...$args Array with arguments or multiple arguments in function. <ide> * @return string|null Translated string. <del> * @throws \Aura\Intl\Exception <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__dx <ide> */ <ide> function __dx($domain, $context, $msg, ...$args) <ide> function __dx($domain, $context, $msg, ...$args) <ide> * @param int $count Count. <ide> * @param array ...$args Array with arguments or multiple arguments in function. <ide> * @return string|null Plural form of translated string. <del> * @throws \Aura\Intl\Exception <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__dxn <ide> */ <ide> function __dxn($domain, $context, $singular, $plural, $count, ...$args)
1
Javascript
Javascript
remove blocking mode and blocking root
553440bd1578ef71982c4a10e2cc8c462f33d9be
<ide><path>packages/react-dom/index.classic.fb.js <ide> export { <ide> unmountComponentAtNode, <ide> createRoot, <ide> createRoot as unstable_createRoot, <del> createBlockingRoot, <del> createBlockingRoot as unstable_createBlockingRoot, <ide> unstable_flushControlled, <ide> unstable_scheduleHydration, <ide> unstable_runWithPriority, <ide><path>packages/react-dom/index.experimental.js <ide> export { <ide> unmountComponentAtNode, <ide> // exposeConcurrentModeAPIs <ide> createRoot as unstable_createRoot, <del> createBlockingRoot as unstable_createBlockingRoot, <ide> unstable_flushControlled, <ide> unstable_scheduleHydration, <ide> // DO NOT USE: Temporarily exposing this to migrate off of Scheduler.runWithPriority. <ide><path>packages/react-dom/index.js <ide> export { <ide> unmountComponentAtNode, <ide> createRoot, <ide> createRoot as unstable_createRoot, <del> createBlockingRoot, <del> createBlockingRoot as unstable_createBlockingRoot, <ide> unstable_flushControlled, <ide> unstable_scheduleHydration, <ide> unstable_runWithPriority, <ide><path>packages/react-dom/index.modern.fb.js <ide> export { <ide> version, <ide> createRoot, <ide> createRoot as unstable_createRoot, <del> createBlockingRoot, <del> createBlockingRoot as unstable_createBlockingRoot, <ide> unstable_flushControlled, <ide> unstable_scheduleHydration, <ide> unstable_runWithPriority, <ide><path>packages/react-dom/src/__tests__/ReactDOMFiberAsync-test.js <ide> describe('ReactDOMFiberAsync', () => { <ide> expect(containerC.textContent).toEqual('Finished'); <ide> }); <ide> <del> describe('createBlockingRoot', () => { <del> // @gate experimental <del> it('updates flush without yielding in the next event', () => { <del> const root = ReactDOM.unstable_createBlockingRoot(container); <del> <del> function Text(props) { <del> Scheduler.unstable_yieldValue(props.text); <del> return props.text; <del> } <del> <del> root.render( <del> <> <del> <Text text="A" /> <del> <Text text="B" /> <del> <Text text="C" /> <del> </>, <del> ); <del> <del> // Nothing should have rendered yet <del> expect(container.textContent).toEqual(''); <del> <del> // Everything should render immediately in the next event <del> expect(Scheduler).toFlushExpired(['A', 'B', 'C']); <del> expect(container.textContent).toEqual('ABC'); <del> }); <del> }); <del> <ide> // @gate experimental <ide> it('unmounted roots should never clear newer root content from a container', () => { <ide> const ref = React.createRef(); <ide><path>packages/react-dom/src/__tests__/ReactDOMServerPartialHydration-test.internal.js <ide> describe('ReactDOMServerPartialHydration', () => { <ide> }).toErrorDev( <ide> 'Warning: Cannot hydrate Suspense in legacy mode. Switch from ' + <ide> 'ReactDOM.hydrate(element, container) to ' + <del> 'ReactDOM.createBlockingRoot(container, { hydrate: true })' + <add> 'ReactDOM.createRoot(container, { hydrate: true })' + <ide> '.render(element) or remove the Suspense components from the server ' + <ide> 'rendered components.' + <ide> '\n in Suspense (at **)' + <ide><path>packages/react-dom/src/__tests__/ReactDOMServerSuspense-test.internal.js <ide> describe('ReactDOMServerSuspense', () => { <ide> expect(divB.textContent).toBe('B'); <ide> <ide> act(() => { <del> const root = ReactDOM.createBlockingRoot(parent, {hydrate: true}); <add> const root = ReactDOM.createRoot(parent, {hydrate: true}); <ide> root.render(example); <ide> }); <ide> <ide><path>packages/react-dom/src/__tests__/ReactTestUtilsAct-test.js <ide> describe('ReactTestUtils.act()', () => { <ide> <ide> runActTests('legacy mode', renderLegacy, unmountLegacy, rerenderLegacy); <ide> <del> // and then in blocking mode <del> if (__EXPERIMENTAL__) { <del> let blockingRoot = null; <del> const renderBatched = (el, dom) => { <del> blockingRoot = ReactDOM.unstable_createBlockingRoot(dom); <del> blockingRoot.render(el); <del> }; <del> <del> const unmountBatched = dom => { <del> if (blockingRoot !== null) { <del> blockingRoot.unmount(); <del> blockingRoot = null; <del> } <del> }; <del> <del> const rerenderBatched = el => { <del> blockingRoot.render(el); <del> }; <del> <del> runActTests( <del> 'blocking mode', <del> renderBatched, <del> unmountBatched, <del> rerenderBatched, <del> ); <del> } <del> <ide> describe('unacted effects', () => { <ide> function App() { <ide> React.useEffect(() => {}, []); <ide> describe('ReactTestUtils.act()', () => { <ide> ]); <ide> }); <ide> <del> // @gate experimental <del> it('warns in blocking mode', () => { <del> expect(() => { <del> const root = ReactDOM.unstable_createBlockingRoot( <del> document.createElement('div'), <del> ); <del> root.render(<App />); <del> Scheduler.unstable_flushAll(); <del> }).toErrorDev([ <del> 'An update to App ran an effect, but was not wrapped in act(...)', <del> ]); <del> }); <del> <ide> // @gate experimental <ide> it('warns in concurrent mode', () => { <ide> expect(() => { <ide> function runActTests(label, render, unmount, rerender) { <ide> <ide> it('triggers fallbacks if available', async () => { <ide> if (label !== 'legacy mode') { <del> // FIXME: Support for Blocking* and Concurrent Mode were <del> // intentionally removed from the public version of `act`. It will <del> // be added back in a future major version, before Blocking and and <del> // Concurrent Mode are officially released. Consider disabling all <del> // non-Legacy tests in this suite until then. <del> // <del> // *Blocking Mode actually does happen to work, though <del> // not "officially" since it's an unreleased feature. <add> // FIXME: Support for Concurrent Root intentionally removed <add> // from the public version of `act`. It will be added back in <add> // a future major version, Concurrent Root officially released. <add> // Consider skipping all non-Legacy tests in this suite until then. <ide> return; <ide> } <ide> <ide> function runActTests(label, render, unmount, rerender) { <ide> // In Concurrent Mode, refresh transitions delay indefinitely. <ide> expect(document.querySelector('[data-test-id=spinner]')).toBeNull(); <ide> } else { <del> // In Legacy Mode and Blocking Mode, all fallbacks are forced to <del> // display, even during a refresh transition. <del> // TODO: Consider delaying indefinitely in Blocking Mode, to match <del> // Concurrent Mode semantics. <add> // In Legacy Mode, all fallbacks are forced to display, <add> // even during a refresh transition. <ide> expect( <ide> document.querySelector('[data-test-id=spinner]'), <ide> ).not.toBeNull(); <ide><path>packages/react-dom/src/__tests__/ReactUnmockedSchedulerWarning-test.js <ide> it('should warn when rendering in concurrent mode', () => { <ide> ReactDOM.unstable_createRoot(document.createElement('div')).render(<App />); <ide> }).toErrorDev([]); <ide> }); <del> <del>// @gate experimental <del>it('should warn when rendering in blocking mode', () => { <del> expect(() => { <del> ReactDOM.unstable_createBlockingRoot(document.createElement('div')).render( <del> <App />, <del> ); <del> }).toErrorDev( <del> 'In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' + <del> 'to guarantee consistent behaviour across tests and browsers.', <del> {withoutStack: true}, <del> ); <del> // does not warn twice <del> expect(() => { <del> ReactDOM.unstable_createBlockingRoot(document.createElement('div')).render( <del> <App />, <del> ); <del> }).toErrorDev([]); <del>}); <ide><path>packages/react-dom/src/client/ReactDOM.js <ide> import { <ide> unstable_renderSubtreeIntoContainer, <ide> unmountComponentAtNode, <ide> } from './ReactDOMLegacy'; <del>import {createRoot, createBlockingRoot, isValidContainer} from './ReactDOMRoot'; <add>import {createRoot, isValidContainer} from './ReactDOMRoot'; <ide> import {createEventHandle} from './ReactDOMEventHandle'; <ide> <ide> import { <ide> export { <ide> unmountComponentAtNode, <ide> // exposeConcurrentModeAPIs <ide> createRoot, <del> createBlockingRoot, <ide> flushControlled as unstable_flushControlled, <ide> scheduleHydration as unstable_scheduleHydration, <ide> // Disabled behind disableUnstableRenderSubtreeIntoContainer <ide><path>packages/react-dom/src/client/ReactDOMRoot.js <ide> import { <ide> registerMutableSourceForHydration, <ide> } from 'react-reconciler/src/ReactFiberReconciler'; <ide> import invariant from 'shared/invariant'; <del>import { <del> BlockingRoot, <del> ConcurrentRoot, <del> LegacyRoot, <del>} from 'react-reconciler/src/ReactRootTags'; <add>import {ConcurrentRoot, LegacyRoot} from 'react-reconciler/src/ReactRootTags'; <ide> <ide> function ReactDOMRoot(container: Container, options: void | RootOptions) { <ide> this._internalRoot = createRootImpl(container, ConcurrentRoot, options); <ide> } <ide> <del>function ReactDOMBlockingRoot( <del> container: Container, <del> tag: RootTag, <del> options: void | RootOptions, <del>) { <del> this._internalRoot = createRootImpl(container, tag, options); <add>function ReactDOMLegacyRoot(container: Container, options: void | RootOptions) { <add> this._internalRoot = createRootImpl(container, LegacyRoot, options); <ide> } <ide> <del>ReactDOMRoot.prototype.render = ReactDOMBlockingRoot.prototype.render = function( <add>ReactDOMRoot.prototype.render = ReactDOMLegacyRoot.prototype.render = function( <ide> children: ReactNodeList, <ide> ): void { <ide> const root = this._internalRoot; <ide> ReactDOMRoot.prototype.render = ReactDOMBlockingRoot.prototype.render = function <ide> updateContainer(children, root, null, null); <ide> }; <ide> <del>ReactDOMRoot.prototype.unmount = ReactDOMBlockingRoot.prototype.unmount = function(): void { <add>ReactDOMRoot.prototype.unmount = ReactDOMLegacyRoot.prototype.unmount = function(): void { <ide> if (__DEV__) { <ide> if (typeof arguments[0] === 'function') { <ide> console.error( <ide> export function createRoot( <ide> return new ReactDOMRoot(container, options); <ide> } <ide> <del>export function createBlockingRoot( <del> container: Container, <del> options?: RootOptions, <del>): RootType { <del> invariant( <del> isValidContainer(container), <del> 'createRoot(...): Target container is not a DOM element.', <del> ); <del> warnIfReactDOMContainerInDEV(container); <del> return new ReactDOMBlockingRoot(container, BlockingRoot, options); <del>} <del> <ide> export function createLegacyRoot( <ide> container: Container, <ide> options?: RootOptions, <ide> ): RootType { <del> return new ReactDOMBlockingRoot(container, LegacyRoot, options); <add> return new ReactDOMLegacyRoot(container, options); <ide> } <ide> <ide> export function isValidContainer(node: mixed): boolean { <ide><path>packages/react-noop-renderer/src/ReactNoop.js <ide> export const { <ide> getPendingChildren, <ide> getOrCreateRootContainer, <ide> createRoot, <del> createBlockingRoot, <ide> createLegacyRoot, <ide> getChildrenAsJSX, <ide> getPendingChildrenAsJSX, <ide><path>packages/react-noop-renderer/src/ReactNoopPersistent.js <ide> export const { <ide> getPendingChildren, <ide> getOrCreateRootContainer, <ide> createRoot, <del> createBlockingRoot, <ide> createLegacyRoot, <ide> getChildrenAsJSX, <ide> getPendingChildrenAsJSX, <ide><path>packages/react-noop-renderer/src/createReactNoop.js <ide> import type {RootTag} from 'react-reconciler/src/ReactRootTags'; <ide> <ide> import * as Scheduler from 'scheduler/unstable_mock'; <ide> import {REACT_FRAGMENT_TYPE, REACT_ELEMENT_TYPE} from 'shared/ReactSymbols'; <del>import { <del> ConcurrentRoot, <del> BlockingRoot, <del> LegacyRoot, <del>} from 'react-reconciler/src/ReactRootTags'; <add>import {ConcurrentRoot, LegacyRoot} from 'react-reconciler/src/ReactRootTags'; <ide> <ide> import { <ide> enableNativeEventPriorityInference, <ide> function createReactNoop(reconciler: Function, useMutation: boolean) { <ide> }; <ide> }, <ide> <del> createBlockingRoot() { <del> const container = { <del> rootID: '' + idCounter++, <del> pendingChildren: [], <del> children: [], <del> }; <del> const fiberRoot = NoopRenderer.createContainer( <del> container, <del> BlockingRoot, <del> false, <del> null, <del> null, <del> ); <del> return { <del> _Scheduler: Scheduler, <del> render(children: ReactNodeList) { <del> NoopRenderer.updateContainer(children, fiberRoot, null, null); <del> }, <del> getChildren() { <del> return getChildren(container); <del> }, <del> getChildrenAsJSX() { <del> return getChildrenAsJSX(container); <del> }, <del> }; <del> }, <del> <ide> createLegacyRoot() { <ide> const container = { <ide> rootID: '' + idCounter++, <ide><path>packages/react-reconciler/src/ReactFiber.new.js <ide> import { <ide> enableScopeAPI, <ide> } from 'shared/ReactFeatureFlags'; <ide> import {NoFlags, Placement, StaticMask} from './ReactFiberFlags'; <del>import {ConcurrentRoot, BlockingRoot} from './ReactRootTags'; <add>import {ConcurrentRoot} from './ReactRootTags'; <ide> import { <ide> IndeterminateComponent, <ide> ClassComponent, <ide> import { <ide> ProfileMode, <ide> StrictLegacyMode, <ide> StrictEffectsMode, <del> BlockingMode, <ide> } from './ReactTypeOfMode'; <ide> import { <ide> REACT_FORWARD_REF_TYPE, <ide> export function createHostRootFiber( <ide> ): Fiber { <ide> let mode; <ide> if (tag === ConcurrentRoot) { <del> mode = ConcurrentMode | BlockingMode; <del> if (strictModeLevelOverride !== null) { <del> if (strictModeLevelOverride >= 1) { <del> mode |= StrictLegacyMode; <del> } <del> if (enableStrictEffects) { <del> if (strictModeLevelOverride >= 2) { <del> mode |= StrictEffectsMode; <del> } <del> } <del> } else { <del> if (enableStrictEffects && createRootStrictEffectsByDefault) { <del> mode |= StrictLegacyMode | StrictEffectsMode; <del> } else { <del> mode |= StrictLegacyMode; <del> } <del> } <del> } else if (tag === BlockingRoot) { <del> mode = BlockingMode; <add> mode = ConcurrentMode; <ide> if (strictModeLevelOverride !== null) { <ide> if (strictModeLevelOverride >= 1) { <ide> mode |= StrictLegacyMode; <ide><path>packages/react-reconciler/src/ReactFiber.old.js <ide> import { <ide> enableScopeAPI, <ide> } from 'shared/ReactFeatureFlags'; <ide> import {NoFlags, Placement, StaticMask} from './ReactFiberFlags'; <del>import {ConcurrentRoot, BlockingRoot} from './ReactRootTags'; <add>import {ConcurrentRoot} from './ReactRootTags'; <ide> import { <ide> IndeterminateComponent, <ide> ClassComponent, <ide> import { <ide> ProfileMode, <ide> StrictLegacyMode, <ide> StrictEffectsMode, <del> BlockingMode, <ide> } from './ReactTypeOfMode'; <ide> import { <ide> REACT_FORWARD_REF_TYPE, <ide> export function createHostRootFiber( <ide> ): Fiber { <ide> let mode; <ide> if (tag === ConcurrentRoot) { <del> mode = ConcurrentMode | BlockingMode; <del> if (strictModeLevelOverride !== null) { <del> if (strictModeLevelOverride >= 1) { <del> mode |= StrictLegacyMode; <del> } <del> if (enableStrictEffects) { <del> if (strictModeLevelOverride >= 2) { <del> mode |= StrictEffectsMode; <del> } <del> } <del> } else { <del> if (enableStrictEffects && createRootStrictEffectsByDefault) { <del> mode |= StrictLegacyMode | StrictEffectsMode; <del> } else { <del> mode |= StrictLegacyMode; <del> } <del> } <del> } else if (tag === BlockingRoot) { <del> mode = BlockingMode; <add> mode = ConcurrentMode; <ide> if (strictModeLevelOverride !== null) { <ide> if (strictModeLevelOverride >= 1) { <ide> mode |= StrictLegacyMode; <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.new.js <ide> import { <ide> NoMode, <ide> ProfileMode, <ide> StrictLegacyMode, <del> BlockingMode, <ide> } from './ReactTypeOfMode'; <ide> import { <ide> shouldSetTextContent, <ide> function updateOffscreenComponent( <ide> // Rendering a hidden tree. <ide> if ((workInProgress.mode & ConcurrentMode) === NoMode) { <ide> // In legacy sync mode, don't defer the subtree. Render it now. <del> // TODO: Figure out what we should do in Blocking mode. <ide> const nextState: OffscreenState = { <ide> baseLanes: NoLanes, <ide> cachePool: null, <ide> function mountSuspenseFallbackChildren( <ide> <ide> let primaryChildFragment; <ide> let fallbackChildFragment; <del> if ((mode & BlockingMode) === NoMode && progressedPrimaryFragment !== null) { <add> if ( <add> (mode & ConcurrentMode) === NoMode && <add> progressedPrimaryFragment !== null <add> ) { <ide> // In legacy mode, we commit the primary tree as if it successfully <ide> // completed, even though it's in an inconsistent state. <ide> primaryChildFragment = progressedPrimaryFragment; <ide> function updateSuspensePrimaryChildren( <ide> children: primaryChildren, <ide> }, <ide> ); <del> if ((workInProgress.mode & BlockingMode) === NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) === NoMode) { <ide> primaryChildFragment.lanes = renderLanes; <ide> } <ide> primaryChildFragment.return = workInProgress; <ide> function updateSuspenseFallbackChildren( <ide> if ( <ide> // In legacy mode, we commit the primary tree as if it successfully <ide> // completed, even though it's in an inconsistent state. <del> (mode & BlockingMode) === NoMode && <add> (mode & ConcurrentMode) === NoMode && <ide> // Make sure we're on the second pass, i.e. the primary child fragment was <ide> // already cloned. In legacy mode, the only case where this isn't true is <ide> // when DevTools forces us to display a fallback; we skip the first render <ide> function mountSuspenseFallbackAfterRetryWithoutHydrating( <ide> primaryChildFragment.sibling = fallbackChildFragment; <ide> workInProgress.child = primaryChildFragment; <ide> <del> if ((workInProgress.mode & BlockingMode) !== NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) !== NoMode) { <ide> // We will have dropped the effect list which contains the <ide> // deletion. We need to reconcile to delete the current child. <ide> reconcileChildFibers(workInProgress, current.child, null, renderLanes); <ide> function mountDehydratedSuspenseComponent( <ide> ): null | Fiber { <ide> // During the first pass, we'll bail out and not drill into the children. <ide> // Instead, we'll leave the content in place and try to hydrate it later. <del> if ((workInProgress.mode & BlockingMode) === NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) === NoMode) { <ide> if (__DEV__) { <ide> console.error( <ide> 'Cannot hydrate Suspense in legacy mode. Switch from ' + <ide> 'ReactDOM.hydrate(element, container) to ' + <del> 'ReactDOM.createBlockingRoot(container, { hydrate: true })' + <add> 'ReactDOM.createRoot(container, { hydrate: true })' + <ide> '.render(element) or remove the Suspense components from ' + <ide> 'the server rendered components.', <ide> ); <ide> function updateDehydratedSuspenseComponent( <ide> ); <ide> } <ide> <del> if ((workInProgress.mode & BlockingMode) === NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) === NoMode) { <ide> return retrySuspenseComponentWithoutHydrating( <ide> current, <ide> workInProgress, <ide> function updateSuspenseListComponent( <ide> } <ide> pushSuspenseContext(workInProgress, suspenseContext); <ide> <del> if ((workInProgress.mode & BlockingMode) === NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) === NoMode) { <ide> // In legacy mode, SuspenseList doesn't work so we just <ide> // use make it a noop by treating it as the default revealOrder. <ide> workInProgress.memoizedState = null; <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.old.js <ide> import { <ide> NoMode, <ide> ProfileMode, <ide> StrictLegacyMode, <del> BlockingMode, <ide> } from './ReactTypeOfMode'; <ide> import { <ide> shouldSetTextContent, <ide> function updateOffscreenComponent( <ide> // Rendering a hidden tree. <ide> if ((workInProgress.mode & ConcurrentMode) === NoMode) { <ide> // In legacy sync mode, don't defer the subtree. Render it now. <del> // TODO: Figure out what we should do in Blocking mode. <ide> const nextState: OffscreenState = { <ide> baseLanes: NoLanes, <ide> cachePool: null, <ide> function mountSuspenseFallbackChildren( <ide> <ide> let primaryChildFragment; <ide> let fallbackChildFragment; <del> if ((mode & BlockingMode) === NoMode && progressedPrimaryFragment !== null) { <add> if ( <add> (mode & ConcurrentMode) === NoMode && <add> progressedPrimaryFragment !== null <add> ) { <ide> // In legacy mode, we commit the primary tree as if it successfully <ide> // completed, even though it's in an inconsistent state. <ide> primaryChildFragment = progressedPrimaryFragment; <ide> function updateSuspensePrimaryChildren( <ide> children: primaryChildren, <ide> }, <ide> ); <del> if ((workInProgress.mode & BlockingMode) === NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) === NoMode) { <ide> primaryChildFragment.lanes = renderLanes; <ide> } <ide> primaryChildFragment.return = workInProgress; <ide> function updateSuspenseFallbackChildren( <ide> if ( <ide> // In legacy mode, we commit the primary tree as if it successfully <ide> // completed, even though it's in an inconsistent state. <del> (mode & BlockingMode) === NoMode && <add> (mode & ConcurrentMode) === NoMode && <ide> // Make sure we're on the second pass, i.e. the primary child fragment was <ide> // already cloned. In legacy mode, the only case where this isn't true is <ide> // when DevTools forces us to display a fallback; we skip the first render <ide> function mountSuspenseFallbackAfterRetryWithoutHydrating( <ide> primaryChildFragment.sibling = fallbackChildFragment; <ide> workInProgress.child = primaryChildFragment; <ide> <del> if ((workInProgress.mode & BlockingMode) !== NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) !== NoMode) { <ide> // We will have dropped the effect list which contains the <ide> // deletion. We need to reconcile to delete the current child. <ide> reconcileChildFibers(workInProgress, current.child, null, renderLanes); <ide> function mountDehydratedSuspenseComponent( <ide> ): null | Fiber { <ide> // During the first pass, we'll bail out and not drill into the children. <ide> // Instead, we'll leave the content in place and try to hydrate it later. <del> if ((workInProgress.mode & BlockingMode) === NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) === NoMode) { <ide> if (__DEV__) { <ide> console.error( <ide> 'Cannot hydrate Suspense in legacy mode. Switch from ' + <ide> 'ReactDOM.hydrate(element, container) to ' + <del> 'ReactDOM.createBlockingRoot(container, { hydrate: true })' + <add> 'ReactDOM.createRoot(container, { hydrate: true })' + <ide> '.render(element) or remove the Suspense components from ' + <ide> 'the server rendered components.', <ide> ); <ide> function updateDehydratedSuspenseComponent( <ide> ); <ide> } <ide> <del> if ((workInProgress.mode & BlockingMode) === NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) === NoMode) { <ide> return retrySuspenseComponentWithoutHydrating( <ide> current, <ide> workInProgress, <ide> function updateSuspenseListComponent( <ide> } <ide> pushSuspenseContext(workInProgress, suspenseContext); <ide> <del> if ((workInProgress.mode & BlockingMode) === NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) === NoMode) { <ide> // In legacy mode, SuspenseList doesn't work so we just <ide> // use make it a noop by treating it as the default revealOrder. <ide> workInProgress.memoizedState = null; <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.new.js <ide> import { <ide> LegacyHiddenComponent, <ide> CacheComponent, <ide> } from './ReactWorkTags'; <del>import { <del> NoMode, <del> BlockingMode, <del> ConcurrentMode, <del> ProfileMode, <del>} from './ReactTypeOfMode'; <add>import {NoMode, ConcurrentMode, ProfileMode} from './ReactTypeOfMode'; <ide> import { <ide> Ref, <ide> Update, <ide> function completeWork( <ide> } <ide> <ide> if (nextDidTimeout && !prevDidTimeout) { <del> // If this subtree is running in blocking mode we can suspend, <del> // otherwise we won't suspend. <ide> // TODO: This will still suspend a synchronous tree if anything <ide> // in the concurrent tree already suspended during this render. <ide> // This is a known bug. <del> if ((workInProgress.mode & BlockingMode) !== NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) !== NoMode) { <ide> // TODO: Move this back to throwException because this is too late <ide> // if this is a large tree which is common for initial loads. We <ide> // don't know if we should restart a render or not until we get <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.old.js <ide> import { <ide> LegacyHiddenComponent, <ide> CacheComponent, <ide> } from './ReactWorkTags'; <del>import { <del> NoMode, <del> BlockingMode, <del> ConcurrentMode, <del> ProfileMode, <del>} from './ReactTypeOfMode'; <add>import {NoMode, ConcurrentMode, ProfileMode} from './ReactTypeOfMode'; <ide> import { <ide> Ref, <ide> Update, <ide> function completeWork( <ide> } <ide> <ide> if (nextDidTimeout && !prevDidTimeout) { <del> // If this subtree is running in blocking mode we can suspend, <del> // otherwise we won't suspend. <ide> // TODO: This will still suspend a synchronous tree if anything <ide> // in the concurrent tree already suspended during this render. <ide> // This is a known bug. <del> if ((workInProgress.mode & BlockingMode) !== NoMode) { <add> if ((workInProgress.mode & ConcurrentMode) !== NoMode) { <ide> // TODO: Move this back to throwException because this is too late <ide> // if this is a large tree which is common for initial loads. We <ide> // don't know if we should restart a render or not until we get <ide><path>packages/react-reconciler/src/ReactFiberHooks.new.js <ide> import { <ide> <ide> import { <ide> NoMode, <del> BlockingMode, <add> ConcurrentMode, <ide> DebugTracingMode, <ide> StrictEffectsMode, <ide> } from './ReactTypeOfMode'; <ide> function mountOpaqueIdentifier(): OpaqueIDType | void { <ide> <ide> const setId = mountState(id)[1]; <ide> <del> if ((currentlyRenderingFiber.mode & BlockingMode) === NoMode) { <add> if ((currentlyRenderingFiber.mode & ConcurrentMode) === NoMode) { <ide> if ( <ide> __DEV__ && <ide> enableStrictEffects && <ide><path>packages/react-reconciler/src/ReactFiberHooks.old.js <ide> import { <ide> <ide> import { <ide> NoMode, <del> BlockingMode, <add> ConcurrentMode, <ide> DebugTracingMode, <ide> StrictEffectsMode, <ide> } from './ReactTypeOfMode'; <ide> function mountOpaqueIdentifier(): OpaqueIDType | void { <ide> <ide> const setId = mountState(id)[1]; <ide> <del> if ((currentlyRenderingFiber.mode & BlockingMode) === NoMode) { <add> if ((currentlyRenderingFiber.mode & ConcurrentMode) === NoMode) { <ide> if ( <ide> __DEV__ && <ide> enableStrictEffects && <ide><path>packages/react-reconciler/src/ReactFiberRoot.new.js <ide> import { <ide> } from 'shared/ReactFeatureFlags'; <ide> import {unstable_getThreadID} from 'scheduler/tracing'; <ide> import {initializeUpdateQueue} from './ReactUpdateQueue.new'; <del>import {LegacyRoot, BlockingRoot, ConcurrentRoot} from './ReactRootTags'; <add>import {LegacyRoot, ConcurrentRoot} from './ReactRootTags'; <ide> <ide> function FiberRootNode(containerInfo, tag, hydrate) { <ide> this.tag = tag; <ide> function FiberRootNode(containerInfo, tag, hydrate) { <ide> <ide> if (__DEV__) { <ide> switch (tag) { <del> case BlockingRoot: <del> this._debugRootType = 'createBlockingRoot()'; <del> break; <ide> case ConcurrentRoot: <ide> this._debugRootType = 'createRoot()'; <ide> break; <ide><path>packages/react-reconciler/src/ReactFiberRoot.old.js <ide> import { <ide> } from 'shared/ReactFeatureFlags'; <ide> import {unstable_getThreadID} from 'scheduler/tracing'; <ide> import {initializeUpdateQueue} from './ReactUpdateQueue.old'; <del>import {LegacyRoot, BlockingRoot, ConcurrentRoot} from './ReactRootTags'; <add>import {LegacyRoot, ConcurrentRoot} from './ReactRootTags'; <ide> <ide> function FiberRootNode(containerInfo, tag, hydrate) { <ide> this.tag = tag; <ide> function FiberRootNode(containerInfo, tag, hydrate) { <ide> <ide> if (__DEV__) { <ide> switch (tag) { <del> case BlockingRoot: <del> this._debugRootType = 'createBlockingRoot()'; <del> break; <ide> case ConcurrentRoot: <ide> this._debugRootType = 'createRoot()'; <ide> break; <ide><path>packages/react-reconciler/src/ReactFiberThrow.new.js <ide> import { <ide> ForceUpdateForLegacySuspense, <ide> } from './ReactFiberFlags'; <ide> import {shouldCaptureSuspense} from './ReactFiberSuspenseComponent.new'; <del>import {NoMode, BlockingMode, DebugTracingMode} from './ReactTypeOfMode'; <add>import {NoMode, ConcurrentMode, DebugTracingMode} from './ReactTypeOfMode'; <ide> import { <ide> enableDebugTracing, <ide> enableSchedulingProfiler, <ide> function throwException( <ide> // A legacy mode Suspense quirk, only relevant to hook components. <ide> const tag = sourceFiber.tag; <ide> if ( <del> (sourceFiber.mode & BlockingMode) === NoMode && <add> (sourceFiber.mode & ConcurrentMode) === NoMode && <ide> (tag === FunctionComponent || <ide> tag === ForwardRef || <ide> tag === SimpleMemoComponent) <ide> function throwException( <ide> wakeables.add(wakeable); <ide> } <ide> <del> // If the boundary is outside of blocking mode, we should *not* <add> // If the boundary is in legacy mode, we should *not* <ide> // suspend the commit. Pretend as if the suspended component rendered <ide> // null and keep rendering. In the commit phase, we'll schedule a <ide> // subsequent synchronous update to re-render the Suspense. <ide> // <ide> // Note: It doesn't matter whether the component that suspended was <del> // inside a blocking mode tree. If the Suspense is outside of it, we <add> // inside a concurrent mode tree. If the Suspense is outside of it, we <ide> // should *not* suspend the commit. <ide> // <ide> // If the suspense boundary suspended itself suspended, we don't have to <ide> // do this trick because nothing was partially started. We can just <ide> // directly do a second pass over the fallback in this render and <ide> // pretend we meant to render that directly. <ide> if ( <del> (workInProgress.mode & BlockingMode) === NoMode && <add> (workInProgress.mode & ConcurrentMode) === NoMode && <ide> workInProgress !== returnFiber <ide> ) { <ide> workInProgress.flags |= DidCapture; <ide><path>packages/react-reconciler/src/ReactFiberThrow.old.js <ide> import { <ide> ForceUpdateForLegacySuspense, <ide> } from './ReactFiberFlags'; <ide> import {shouldCaptureSuspense} from './ReactFiberSuspenseComponent.old'; <del>import {NoMode, BlockingMode, DebugTracingMode} from './ReactTypeOfMode'; <add>import {NoMode, ConcurrentMode, DebugTracingMode} from './ReactTypeOfMode'; <ide> import { <ide> enableDebugTracing, <ide> enableSchedulingProfiler, <ide> function throwException( <ide> // A legacy mode Suspense quirk, only relevant to hook components. <ide> const tag = sourceFiber.tag; <ide> if ( <del> (sourceFiber.mode & BlockingMode) === NoMode && <add> (sourceFiber.mode & ConcurrentMode) === NoMode && <ide> (tag === FunctionComponent || <ide> tag === ForwardRef || <ide> tag === SimpleMemoComponent) <ide> function throwException( <ide> wakeables.add(wakeable); <ide> } <ide> <del> // If the boundary is outside of blocking mode, we should *not* <add> // If the boundary is in legacy mode, we should *not* <ide> // suspend the commit. Pretend as if the suspended component rendered <ide> // null and keep rendering. In the commit phase, we'll schedule a <ide> // subsequent synchronous update to re-render the Suspense. <ide> // <ide> // Note: It doesn't matter whether the component that suspended was <del> // inside a blocking mode tree. If the Suspense is outside of it, we <add> // inside a concurrent mode tree. If the Suspense is outside of it, we <ide> // should *not* suspend the commit. <ide> // <ide> // If the suspense boundary suspended itself suspended, we don't have to <ide> // do this trick because nothing was partially started. We can just <ide> // directly do a second pass over the fallback in this render and <ide> // pretend we meant to render that directly. <ide> if ( <del> (workInProgress.mode & BlockingMode) === NoMode && <add> (workInProgress.mode & ConcurrentMode) === NoMode && <ide> workInProgress !== returnFiber <ide> ) { <ide> workInProgress.flags |= DidCapture; <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> import { <ide> NoMode, <ide> StrictLegacyMode, <ide> ProfileMode, <del> BlockingMode, <ide> ConcurrentMode, <ide> } from './ReactTypeOfMode'; <ide> import { <ide> export function getCurrentTime() { <ide> export function requestUpdateLane(fiber: Fiber): Lane { <ide> // Special cases <ide> const mode = fiber.mode; <del> if ((mode & BlockingMode) === NoMode) { <add> if ((mode & ConcurrentMode) === NoMode) { <ide> return (SyncLane: Lane); <ide> } else if ((mode & ConcurrentMode) === NoMode) { <ide> return getCurrentPriorityLevel() === ImmediateSchedulerPriority <ide> function requestRetryLane(fiber: Fiber) { <ide> <ide> // Special cases <ide> const mode = fiber.mode; <del> if ((mode & BlockingMode) === NoMode) { <add> if ((mode & ConcurrentMode) === NoMode) { <ide> return (SyncLane: Lane); <ide> } else if ((mode & ConcurrentMode) === NoMode) { <ide> return getCurrentPriorityLevel() === ImmediateSchedulerPriority <ide> export function isInterleavedUpdate(fiber: Fiber, lane: Lane) { <ide> // Requires some refactoring. Not a big deal though since it's rare for <ide> // concurrent apps to have more than a single root. <ide> workInProgressRoot !== null && <del> (fiber.mode & BlockingMode) !== NoMode && <add> (fiber.mode & ConcurrentMode) !== NoMode && <ide> // If this is a render phase update (i.e. UNSAFE_componentWillReceiveProps), <ide> // then don't treat this as an interleaved update. This pattern is <ide> // accompanied by a warning but we haven't fully deprecated it yet. We can <ide> function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { <ide> return; <ide> } <ide> <del> if (!(fiber.mode & (BlockingMode | ConcurrentMode))) { <add> if (!(fiber.mode & ConcurrentMode)) { <ide> return; <ide> } <ide> <ide> export function warnIfUnmockedScheduler(fiber: Fiber) { <ide> didWarnAboutUnmockedScheduler === false && <ide> Scheduler.unstable_flushAllWithoutAsserting === undefined <ide> ) { <del> if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) { <add> if (fiber.mode & ConcurrentMode) { <ide> didWarnAboutUnmockedScheduler = true; <ide> console.error( <ide> 'In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' + <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js <ide> import { <ide> NoMode, <ide> StrictLegacyMode, <ide> ProfileMode, <del> BlockingMode, <ide> ConcurrentMode, <ide> } from './ReactTypeOfMode'; <ide> import { <ide> export function getCurrentTime() { <ide> export function requestUpdateLane(fiber: Fiber): Lane { <ide> // Special cases <ide> const mode = fiber.mode; <del> if ((mode & BlockingMode) === NoMode) { <add> if ((mode & ConcurrentMode) === NoMode) { <ide> return (SyncLane: Lane); <ide> } else if ((mode & ConcurrentMode) === NoMode) { <ide> return getCurrentPriorityLevel() === ImmediateSchedulerPriority <ide> function requestRetryLane(fiber: Fiber) { <ide> <ide> // Special cases <ide> const mode = fiber.mode; <del> if ((mode & BlockingMode) === NoMode) { <add> if ((mode & ConcurrentMode) === NoMode) { <ide> return (SyncLane: Lane); <ide> } else if ((mode & ConcurrentMode) === NoMode) { <ide> return getCurrentPriorityLevel() === ImmediateSchedulerPriority <ide> export function isInterleavedUpdate(fiber: Fiber, lane: Lane) { <ide> // Requires some refactoring. Not a big deal though since it's rare for <ide> // concurrent apps to have more than a single root. <ide> workInProgressRoot !== null && <del> (fiber.mode & BlockingMode) !== NoMode && <add> (fiber.mode & ConcurrentMode) !== NoMode && <ide> // If this is a render phase update (i.e. UNSAFE_componentWillReceiveProps), <ide> // then don't treat this as an interleaved update. This pattern is <ide> // accompanied by a warning but we haven't fully deprecated it yet. We can <ide> function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { <ide> return; <ide> } <ide> <del> if (!(fiber.mode & (BlockingMode | ConcurrentMode))) { <add> if (!(fiber.mode & ConcurrentMode)) { <ide> return; <ide> } <ide> <ide> export function warnIfUnmockedScheduler(fiber: Fiber) { <ide> didWarnAboutUnmockedScheduler === false && <ide> Scheduler.unstable_flushAllWithoutAsserting === undefined <ide> ) { <del> if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) { <add> if (fiber.mode & ConcurrentMode) { <ide> didWarnAboutUnmockedScheduler = true; <ide> console.error( <ide> 'In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' + <ide><path>packages/react-reconciler/src/ReactRootTags.js <ide> * @flow <ide> */ <ide> <del>export type RootTag = 0 | 1 | 2; <add>export type RootTag = 0 | 1; <ide> <ide> export const LegacyRoot = 0; <del>export const BlockingRoot = 1; <del>export const ConcurrentRoot = 2; <add>export const ConcurrentRoot = 1; <ide><path>packages/react-reconciler/src/ReactTypeOfMode.js <ide> export type TypeOfMode = number; <ide> <ide> export const NoMode = /* */ 0b000000; <del>// TODO: Remove BlockingMode and ConcurrentMode by reading from the root tag instead <del>export const BlockingMode = /* */ 0b000001; <del>export const ConcurrentMode = /* */ 0b000010; <del>export const ProfileMode = /* */ 0b000100; <del>export const DebugTracingMode = /* */ 0b001000; <del>export const StrictLegacyMode = /* */ 0b010000; <del>export const StrictEffectsMode = /* */ 0b100000; <add>// TODO: Remove ConcurrentMode by reading from the root tag instead <add>export const ConcurrentMode = /* */ 0b000001; <add>export const ProfileMode = /* */ 0b000010; <add>export const DebugTracingMode = /* */ 0b000100; <add>export const StrictLegacyMode = /* */ 0b001000; <add>export const StrictEffectsMode = /* */ 0b010000; <ide><path>packages/react-reconciler/src/__tests__/ReactBatchedMode-test.internal.js <del>let React; <del>let ReactFeatureFlags; <del>let ReactNoop; <del>let Scheduler; <del>let ReactCache; <del>let Suspense; <del>let TextResource; <del> <del>describe('ReactBlockingMode', () => { <del> beforeEach(() => { <del> jest.resetModules(); <del> ReactFeatureFlags = require('shared/ReactFeatureFlags'); <del> <del> ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false; <del> React = require('react'); <del> ReactNoop = require('react-noop-renderer'); <del> Scheduler = require('scheduler'); <del> ReactCache = require('react-cache'); <del> Suspense = React.Suspense; <del> <del> TextResource = ReactCache.unstable_createResource( <del> ([text, ms = 0]) => { <del> return new Promise((resolve, reject) => <del> setTimeout(() => { <del> Scheduler.unstable_yieldValue(`Promise resolved [${text}]`); <del> resolve(text); <del> }, ms), <del> ); <del> }, <del> ([text, ms]) => text, <del> ); <del> }); <del> <del> function Text(props) { <del> Scheduler.unstable_yieldValue(props.text); <del> return props.text; <del> } <del> <del> function AsyncText(props) { <del> const text = props.text; <del> try { <del> TextResource.read([props.text, props.ms]); <del> Scheduler.unstable_yieldValue(text); <del> return props.text; <del> } catch (promise) { <del> if (typeof promise.then === 'function') { <del> Scheduler.unstable_yieldValue(`Suspend! [${text}]`); <del> } else { <del> Scheduler.unstable_yieldValue(`Error! [${text}]`); <del> } <del> throw promise; <del> } <del> } <del> <del> it('updates flush without yielding in the next event', () => { <del> const root = ReactNoop.createBlockingRoot(); <del> <del> root.render( <del> <> <del> <Text text="A" /> <del> <Text text="B" /> <del> <Text text="C" /> <del> </>, <del> ); <del> <del> // Nothing should have rendered yet <del> expect(root).toMatchRenderedOutput(null); <del> <del> // Everything should render immediately in the next event <del> expect(Scheduler).toFlushExpired(['A', 'B', 'C']); <del> expect(root).toMatchRenderedOutput('ABC'); <del> }); <del> <del> it('layout updates flush synchronously in same event', () => { <del> const {useLayoutEffect} = React; <del> <del> function App() { <del> useLayoutEffect(() => { <del> Scheduler.unstable_yieldValue('Layout effect'); <del> }); <del> return <Text text="Hi" />; <del> } <del> <del> const root = ReactNoop.createBlockingRoot(); <del> root.render(<App />); <del> expect(root).toMatchRenderedOutput(null); <del> <del> expect(Scheduler).toFlushExpired(['Hi', 'Layout effect']); <del> expect(root).toMatchRenderedOutput('Hi'); <del> }); <del> <del> it('uses proper Suspense semantics, not legacy ones', async () => { <del> const root = ReactNoop.createBlockingRoot(); <del> root.render( <del> <Suspense fallback={<Text text="Loading..." />}> <del> <span> <del> <Text text="A" /> <del> </span> <del> <span> <del> <AsyncText text="B" /> <del> </span> <del> <span> <del> <Text text="C" /> <del> </span> <del> </Suspense>, <del> ); <del> <del> expect(Scheduler).toFlushExpired(['A', 'Suspend! [B]', 'C', 'Loading...']); <del> // In Legacy Mode, A and B would mount in a hidden primary tree. In Batched <del> // and Concurrent Mode, nothing in the primary tree should mount. But the <del> // fallback should mount immediately. <del> expect(root).toMatchRenderedOutput('Loading...'); <del> <del> await jest.advanceTimersByTime(1000); <del> expect(Scheduler).toHaveYielded(['Promise resolved [B]']); <del> expect(Scheduler).toFlushExpired(['A', 'B', 'C']); <del> expect(root).toMatchRenderedOutput( <del> <> <del> <span>A</span> <del> <span>B</span> <del> <span>C</span> <del> </>, <del> ); <del> }); <del> <del> it('flushSync does not flush batched work', () => { <del> const {useState, forwardRef, useImperativeHandle} = React; <del> const root = ReactNoop.createBlockingRoot(); <del> <del> const Foo = forwardRef(({label}, ref) => { <del> const [step, setStep] = useState(0); <del> useImperativeHandle(ref, () => ({setStep})); <del> return <Text text={label + step} />; <del> }); <del> <del> const foo1 = React.createRef(null); <del> const foo2 = React.createRef(null); <del> root.render( <del> <> <del> <Foo label="A" ref={foo1} /> <del> <Foo label="B" ref={foo2} /> <del> </>, <del> ); <del> <del> // Mount <del> expect(Scheduler).toFlushExpired(['A0', 'B0']); <del> expect(root).toMatchRenderedOutput('A0B0'); <del> <del> // Schedule a batched update to the first sibling <del> ReactNoop.batchedUpdates(() => foo1.current.setStep(1)); <del> <del> // Before it flushes, update the second sibling inside flushSync <del> ReactNoop.batchedUpdates(() => <del> ReactNoop.flushSync(() => { <del> foo2.current.setStep(1); <del> }), <del> ); <del> <del> // Only the second update should have flushed synchronously <del> expect(Scheduler).toHaveYielded(['B1']); <del> expect(root).toMatchRenderedOutput('A0B1'); <del> <del> // Now flush the first update <del> expect(Scheduler).toFlushExpired(['A1']); <del> expect(root).toMatchRenderedOutput('A1B1'); <del> }); <del>}); <ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalErrorHandling-test.internal.js <ide> describe('ReactIncrementalErrorHandling', () => { <ide> const root = ReactNoop.createRoot(); <ide> root.render('Error when completing root'); <ide> expect(Scheduler).toFlushAndThrow('Error when completing root'); <del> <del> const blockingRoot = ReactNoop.createBlockingRoot(); <del> blockingRoot.render('Error when completing root'); <del> expect(Scheduler).toFlushAndThrow('Error when completing root'); <ide> }); <ide> } <ide> }); <ide><path>packages/react-reconciler/src/__tests__/ReactOffscreen-test.js <ide> describe('ReactOffscreen', () => { <ide> </>, <ide> ); <ide> }); <del> <del> // @gate experimental <del> it('does not defer in blocking mode', async () => { <del> let setState; <del> function Foo() { <del> const [state, _setState] = useState('A'); <del> setState = _setState; <del> return <Text text={state} />; <del> } <del> <del> const root = ReactNoop.createBlockingRoot(); <del> await ReactNoop.act(async () => { <del> root.render( <del> <> <del> <LegacyHidden mode="hidden"> <del> <Foo /> <del> </LegacyHidden> <del> <Text text="Outside" /> <del> </>, <del> ); <del> // Should not defer the hidden tree <del> expect(Scheduler).toFlushUntilNextPaint(['A', 'Outside']); <del> }); <del> expect(root).toMatchRenderedOutput( <del> <> <del> <span prop="A" /> <del> <span prop="Outside" /> <del> </>, <del> ); <del> <del> // Test that the children can be updated <del> await ReactNoop.act(async () => { <del> setState('B'); <del> }); <del> expect(Scheduler).toHaveYielded(['B']); <del> expect(root).toMatchRenderedOutput( <del> <> <del> <span prop="B" /> <del> <span prop="Outside" /> <del> </>, <del> ); <del> }); <ide> }); <ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseFuzz-test.internal.js <ide> describe('ReactSuspenseFuzz', () => { <ide> expect(legacyOutput).toEqual(expectedOutput); <ide> ReactNoop.renderLegacySyncRoot(null); <ide> <del> resetCache(); <del> const batchedBlockingRoot = ReactNoop.createBlockingRoot(); <del> batchedBlockingRoot.render(children); <del> resolveAllTasks(); <del> const batchedSyncOutput = batchedBlockingRoot.getChildrenAsJSX(); <del> expect(batchedSyncOutput).toEqual(expectedOutput); <del> <ide> resetCache(); <ide> const concurrentRoot = ReactNoop.createRoot(); <ide> concurrentRoot.render(children); <ide><path>packages/react/src/__tests__/ReactStrictMode-test.internal.js <ide> describe('ReactStrictMode', () => { <ide> ]); <ide> }); <ide> <del> // @gate experimental <del> it('should support overriding default via createBlockingRoot option', () => { <del> act(() => { <del> const container = document.createElement('div'); <del> const root = ReactDOM.createBlockingRoot(container, { <del> unstable_strictModeLevel: 0, <del> }); <del> root.render(<Component label="A" />); <del> }); <del> <del> expect(log).toEqual([ <del> 'A: render', <del> 'A: useLayoutEffect mount', <del> 'A: useEffect mount', <del> ]); <del> }); <del> <ide> // @gate experimental <ide> it('should disable strict mode if level 0 is specified', () => { <ide> act(() => { <ide><path>packages/shared/ReactFeatureFlags.js <ide> export const debugRenderPhaseSideEffectsForStrictMode = __DEV__; <ide> // this feature flag only impacts StrictEffectsMode. <ide> export const enableStrictEffects = false; <ide> <del>// If TRUE, trees rendered with createRoot (and createBlockingRoot) APIs will be StrictEffectsMode. <add>// If TRUE, trees rendered with createRoot will be StrictEffectsMode. <ide> // If FALSE, these trees will be StrictLegacyMode. <ide> export const createRootStrictEffectsByDefault = false; <ide>
36
PHP
PHP
apply fixes from styleci
4df49b483b3d7747f5bedcf396457ebe1dbf40b5
<ide><path>tests/Mail/MailMailableDataTest.php <ide> public function testMailableDataIsNotLost() <ide> $testData = ['first_name' => 'James']; <ide> <ide> $mailable = new MailableStub; <del> $mailable->build(function($m) use ($testData) { <add> $mailable->build(function ($m) use ($testData) { <ide> $m->view('view', $testData); <ide> }); <ide> $this->assertSame($testData, $mailable->buildViewData()); <ide> <ide> $mailable = new MailableStub; <del> $mailable->build(function($m) use ($testData) { <add> $mailable->build(function ($m) use ($testData) { <ide> $m->view('view', $testData) <ide> ->text('text-view'); <ide> }); <ide> public function build($builder) <ide> { <ide> $builder($this); <ide> } <del>} <ide>\ No newline at end of file <add>}
1
Javascript
Javascript
fix typo in image.android.js & image.ios.js
58c3bc490143b8d7831a00289e2565f49f5389ef
<ide><path>Libraries/Image/Image.android.js <ide> var Image = createReactClass({ <ide> } <ide> <ide> if (this.props.children) { <del> throw new Error('The <Image> component cannot contain children. If you want to render content on top of the image, consider using aboslute positioning.'); <add> throw new Error('The <Image> component cannot contain children. If you want to render content on top of the image, consider using absolute positioning.'); <ide> } <ide> <ide> if (source && (source.uri || Array.isArray(source))) { <ide><path>Libraries/Image/Image.ios.js <ide> const Image = createReactClass({ <ide> } <ide> <ide> if (this.props.children) { <del> throw new Error('The <Image> component cannot contain children. If you want to render content on top of the image, consider using aboslute positioning.'); <add> throw new Error('The <Image> component cannot contain children. If you want to render content on top of the image, consider using absolute positioning.'); <ide> } <ide> <ide> return (
2
PHP
PHP
remove annotation for deprecated components
d37e378b76a99f38488cb5f2a074f4751061c582
<ide><path>src/Controller/Controller.php <ide> * - `afterFilter(EventInterface $event)` <ide> * Called after each action is complete and after the view is rendered. <ide> * <del> * @property \Cake\Controller\Component\AuthComponent $Auth <ide> * @property \Cake\Controller\Component\FlashComponent $Flash <ide> * @property \Cake\Controller\Component\PaginatorComponent $Paginator <ide> * @property \Cake\Controller\Component\RequestHandlerComponent $RequestHandler <del> * @property \Cake\Controller\Component\SecurityComponent $Security <del> * @method bool isAuthorized($user) <add> * @property \Cake\Controller\Component\FormProtectionComponent $FormProtection <ide> * @link https://book.cakephp.org/4/en/controllers.html <ide> */ <ide> class Controller implements EventListenerInterface, EventDispatcherInterface
1
Python
Python
fix tf.name_scope support for keras nested layers
7379f454e5c03d0e8c47bd2d94468839ec0c03d3
<ide><path>keras/engine/base_layer.py <ide> import tensorflow.compat.v2 as tf <ide> <ide> import collections <del>import contextlib <ide> import copy <ide> import functools <ide> import itertools <ide> <ide> _is_name_scope_on_model_declaration_enabled = False <ide> <del>_name_scope_unnester_stack = threading.local() <del> <del> <del>@contextlib.contextmanager <del>def _name_scope_unnester(full_name_scope): <del> """Helper to get relative name scope from fully specified nested name scopes. <del> <del> Args: <del> full_name_scope: full(absolute) name scope path. <del> <del> Yields: <del> Relative name scope path from the parent `_name_scope_unnester` context <del> manager. <del> <del> Example: <del> ``` <del> with _name_scope_unnester('a') as name1: # name1 == 'a' <del> with _name_scope_unnester('a/b') as name2: # name2 == 'b' <del> with _name_scope_unnester('a/b/c') as name3: # name3 == 'c' <del> pass <del> ``` <del> """ <del> if not getattr(_name_scope_unnester_stack, 'value', None): <del> _name_scope_unnester_stack.value = [''] <del> <del> _name_scope_unnester_stack.value.append(full_name_scope) <del> <del> try: <del> full_name_scope = _name_scope_unnester_stack.value[-1] <del> outer_name_scope = _name_scope_unnester_stack.value[-2] <del> relative_name_scope = full_name_scope.lstrip(outer_name_scope) <del> relative_name_scope = relative_name_scope.lstrip('/') <del> yield relative_name_scope <del> finally: <del> _name_scope_unnester_stack.value.pop() <del> <ide> <ide> @keras_export('keras.layers.Layer') <ide> class Layer(tf.Module, version_utils.LayerVersionSelector): <ide> def __init__(self, <ide> <ide> # Save outer name scope at layer declaration so that it is preserved at <ide> # the actual layer construction. <del> self._name_scope_on_declaration = tf.get_current_name_scope() <add> self._outer_name_scope = tf.get_current_name_scope() <ide> <ide> @tf.__internal__.tracking.no_automatic_dependency_tracking <ide> @generic_utils.default <ide> def __call__(self, *args, **kwargs): <ide> training=training_mode): <ide> <ide> input_spec.assert_input_compatibility(self.input_spec, inputs, self.name) <del> <ide> if eager: <ide> call_fn = self.call <ide> name_scope = self._name <ide> else: <del> name_scope = self._get_unnested_name_scope() <add> name_scope = self._name_scope() # Avoid autoincrementing. # pylint: disable=not-callable <ide> call_fn = self._autographed_call() <del> <ide> call_fn = traceback_utils.inject_argument_info_in_traceback( <ide> call_fn, <ide> object_name=f'layer "{self.name}" (type {self.__class__.__name__})') <del> with contextlib.ExitStack() as namescope_stack: <del> if _is_name_scope_on_model_declaration_enabled: <del> namescope_stack.enter_context(_name_scope_unnester( <del> self._name_scope_on_declaration)) <del> namescope_stack.enter_context(tf.name_scope(name_scope)) <ide> <add> with tf.name_scope(name_scope): <ide> if not self.built: <ide> self._maybe_build(inputs) <ide> <ide> def __call__(self, *args, **kwargs): <ide> <ide> return outputs <ide> <del> def _get_unnested_name_scope(self): <del> if _is_name_scope_on_model_declaration_enabled: <del> with _name_scope_unnester(self._name_scope_on_declaration <del> ) as relative_name_scope_on_declaration: <del> # To avoid `tf.name_scope` autoincrement, use absolute path. <del> relative_name_scope = filter( <del> None, <del> [tf.get_current_name_scope(), relative_name_scope_on_declaration]) <del> current_name_scope = '/'.join(relative_name_scope) + '/' <del> with tf.name_scope(current_name_scope): <del> name_scope = self._name_scope() # Avoid autoincrementing. # pylint: disable=not-callable <del> else: <del> name_scope = self._name_scope() <del> <del> return name_scope <del> <ide> def _functional_construction_call(self, inputs, args, kwargs, input_list): <ide> call_context = base_layer_utils.call_context() <ide> <ide> def _name_scope(self): # pylint: disable=method-hidden <ide> if not tf.__internal__.tf2.enabled(): <ide> return self.name <ide> name_scope = self.name <add> if _is_name_scope_on_model_declaration_enabled and self._outer_name_scope: <add> name_scope = self._outer_name_scope + '/' + name_scope <ide> current_name_scope = tf.__internal__.get_name_scope() <ide> if current_name_scope: <ide> name_scope = current_name_scope + '/' + name_scope <ide><path>keras/engine/base_layer_test.py <ide> def test_apply_name_scope_on_model_declaration(self): <ide> ]) <ide> base_layer._apply_name_scope_on_model_declaration(False) <ide> <del> @testing_utils.run_v2_only <del> def test_apply_name_scope_on_nested_layer_model_declaration(self): <del> if not tf.executing_eagerly(): <del> self.skipTest('`apply_name_scope_on_model_declaration` API is supported' <del> ' only for V2 eager') <del> <del> base_layer._apply_name_scope_on_model_declaration(True) <del> <del> class ThreeDenses(layers.Layer): <del> <del> def __init__(self, name='ThreeDenses', **kwargs): <del> super().__init__(name=name, **kwargs) <del> self.inner_dense_1 = layers.Dense(10, name='NestedDense1') <del> with tf.name_scope('inner1/inner2'): <del> self.inner_dense_2 = layers.Dense(20, name='NestedDense2') <del> self.inner_dense_3 = layers.Dense(30, name='NestedDense3') <del> <del> def call(self, x): <del> x = self.inner_dense_1(x) <del> x = self.inner_dense_2(x) <del> x = self.inner_dense_3(x) <del> return x <del> <del> inputs = input_layer.Input((3,)) <del> with tf.name_scope('outer'): <del> x = ThreeDenses()(inputs) <del> outputs = layers.Dense(10, name='OuterDense')(x) <del> <del> model = training_lib.Model(inputs, outputs) <del> node_names = self._get_model_node_names(model, np.random.random((1, 3)), <del> 'call_scope') <del> <del> self.assertListEqual(node_names, [ <del> 'call_scope/Const', 'call_scope/model/Cast', <del> 'call_scope/model/outer/ThreeDenses/NestedDense1/MatMul/ReadVariableOp/resource', <del> 'call_scope/model/outer/ThreeDenses/NestedDense1/MatMul/ReadVariableOp', <del> 'call_scope/model/outer/ThreeDenses/NestedDense1/MatMul', <del> 'call_scope/model/outer/ThreeDenses/NestedDense1/BiasAdd/ReadVariableOp/resource', <del> 'call_scope/model/outer/ThreeDenses/NestedDense1/BiasAdd/ReadVariableOp', <del> 'call_scope/model/outer/ThreeDenses/NestedDense1/BiasAdd', <del> 'call_scope/model/outer/ThreeDenses/inner1/inner2/NestedDense2/MatMul/ReadVariableOp/resource', <del> 'call_scope/model/outer/ThreeDenses/inner1/inner2/NestedDense2/MatMul/ReadVariableOp', <del> 'call_scope/model/outer/ThreeDenses/inner1/inner2/NestedDense2/MatMul', <del> 'call_scope/model/outer/ThreeDenses/inner1/inner2/NestedDense2/BiasAdd/ReadVariableOp/resource', <del> 'call_scope/model/outer/ThreeDenses/inner1/inner2/NestedDense2/BiasAdd/ReadVariableOp', <del> 'call_scope/model/outer/ThreeDenses/inner1/inner2/NestedDense2/BiasAdd', <del> 'call_scope/model/outer/ThreeDenses/NestedDense3/MatMul/ReadVariableOp/resource', <del> 'call_scope/model/outer/ThreeDenses/NestedDense3/MatMul/ReadVariableOp', <del> 'call_scope/model/outer/ThreeDenses/NestedDense3/MatMul', <del> 'call_scope/model/outer/ThreeDenses/NestedDense3/BiasAdd/ReadVariableOp/resource', <del> 'call_scope/model/outer/ThreeDenses/NestedDense3/BiasAdd/ReadVariableOp', <del> 'call_scope/model/outer/ThreeDenses/NestedDense3/BiasAdd', <del> 'call_scope/model/OuterDense/MatMul/ReadVariableOp/resource', <del> 'call_scope/model/OuterDense/MatMul/ReadVariableOp', <del> 'call_scope/model/OuterDense/MatMul', <del> 'call_scope/model/OuterDense/BiasAdd/ReadVariableOp/resource', <del> 'call_scope/model/OuterDense/BiasAdd/ReadVariableOp', <del> 'call_scope/model/OuterDense/BiasAdd', 'Identity', 'NoOp' <del> ]) <del> base_layer._apply_name_scope_on_model_declaration(False) <del> <ide> def _get_model_node_names(self, model, inputs, call_name_scope): <ide> """Returns a list of model's node names.""" <ide>
2
Python
Python
remove incubator from the path
c0a792308fdff86b0c6d1a6e8236538668003375
<ide><path>setup.py <ide> import libcloud.utils <ide> libcloud.utils.SHOW_DEPRECATION_WARNING = False <ide> <del>HTML_VIEWSOURCE_BASE = 'https://svn.apache.org/viewvc/incubator/libcloud/trunk' <add>HTML_VIEWSOURCE_BASE = 'https://svn.apache.org/viewvc/libcloud/trunk' <ide> PROJECT_BASE_DIR = 'http://incubator.apache.org/libcloud/' <ide> TEST_PATHS = [ 'test', 'test/compute', 'test/storage' , 'test/loadbalancer'] <ide> DOC_TEST_MODULES = [ 'libcloud.compute.drivers.dummy',
1
PHP
PHP
add integration test
6d1f8ce635c4ef8a71abf4f733d08ced092c0d1f
<ide><path>src/Illuminate/Database/Eloquent/Collection.php <ide> public function load($relations) <ide> return $this; <ide> } <ide> <del> /** <add> /** <ide> * Load a set of relationship counts onto the collection. <ide> * <ide> * @param array|string $relations <ide><path>tests/Integration/Database/EloquentCollectionLoadCountTest.php <add><?php <add> <add>namespace App\Integration\Database; <add> <add>use Illuminate\Support\Facades\DB; <add>use Illuminate\Support\Facades\Schema; <add>use Illuminate\Database\Eloquent\Model; <add>use Illuminate\Database\Schema\Blueprint; <add>use Illuminate\Database\Eloquent\Collection; <add>use Illuminate\Database\Eloquent\SoftDeletes; <add>use Illuminate\Tests\Integration\Database\DatabaseTestCase; <add> <add>/** <add> * @group integration <add> */ <add>class EloquentCollectionLoadCountTest extends DatabaseTestCase <add>{ <add> public function setUp() <add> { <add> parent::setUp(); <add> <add> Schema::create('posts', function (Blueprint $table) { <add> $table->increments('id'); <add> $table->unsignedInteger('some_default_value'); <add> $table->softDeletes(); <add> }); <add> <add> Schema::create('comments', function (Blueprint $table) { <add> $table->increments('id'); <add> $table->unsignedInteger('post_id'); <add> }); <add> <add> Schema::create('likes', function (Blueprint $table) { <add> $table->increments('id'); <add> $table->unsignedInteger('post_id'); <add> }); <add> <add> $post = Post::create(); <add> $post->comments()->saveMany([new Comment, new Comment]); <add> <add> $post->likes()->save(new Like); <add> <add> Post::create(); <add> } <add> <add> public function testLoadCount() <add> { <add> $posts = Post::all(); <add> <add> DB::enableQueryLog(); <add> <add> $posts->loadCount('comments'); <add> <add> $this->assertCount(1, DB::getQueryLog()); <add> $this->assertSame('2', $posts[0]->comments_count); <add> $this->assertSame('0', $posts[1]->comments_count); <add> } <add> <add> public function testLoadCountOnDeletedModels() <add> { <add> $posts = Post::all()->each->delete(); <add> <add> DB::enableQueryLog(); <add> <add> $posts->loadCount('comments'); <add> <add> $this->assertCount(1, DB::getQueryLog()); <add> $this->assertSame('2', $posts[0]->comments_count); <add> $this->assertSame('0', $posts[1]->comments_count); <add> } <add> <add> public function testLoadCountWithArrayOfRelations() <add> { <add> $posts = Post::all(); <add> <add> DB::enableQueryLog(); <add> <add> $posts->loadCount(['comments', 'likes']); <add> <add> $this->assertCount(1, DB::getQueryLog()); <add> $this->assertSame('2', $posts[0]->comments_count); <add> $this->assertSame('1', $posts[0]->likes_count); <add> $this->assertSame('0', $posts[1]->comments_count); <add> $this->assertSame('0', $posts[1]->likes_count); <add> } <add> <add> public function testLoadCountDoesNotOverrideAttributesWithDefaultValue() <add> { <add> $post = Post::first(); <add> $post->some_default_value = 200; <add> <add> Collection::make([$post])->loadCount('comments'); <add> <add> $this->assertSame(200, $post->some_default_value); <add> $this->assertSame('2', $post->comments_count); <add> } <add>} <add> <add>class Post extends Model <add>{ <add> use SoftDeletes; <add> <add> protected $attributes = [ <add> 'some_default_value' => 100, <add> ]; <add> <add> public $timestamps = false; <add> <add> public function comments() <add> { <add> return $this->hasMany(Comment::class); <add> } <add> <add> public function likes() <add> { <add> return $this->hasMany(Like::class); <add> } <add>} <add> <add>class Comment extends Model <add>{ <add> public $timestamps = false; <add>} <add> <add>class Like extends Model <add>{ <add> public $timestamps = false; <add>}
2
PHP
PHP
apply fixes from styleci
96ebdd6aed761d83eeedfb3e7bf11ed5aa5cc0ff
<ide><path>tests/Integration/Queue/JobChainingTest.php <ide> use Orchestra\Testbench\TestCase; <ide> use Illuminate\Support\Facades\Queue; <ide> use Illuminate\Queue\InteractsWithQueue; <del>use Illuminate\Foundation\Bus\Dispatchable; <ide> use Illuminate\Contracts\Queue\ShouldQueue; <add>use Illuminate\Foundation\Bus\Dispatchable; <ide> <ide> /** <ide> * @group integration <ide> public function tearDown() <ide> JobChainingTestSecondJob::$ran = false; <ide> } <ide> <del> <ide> public function test_jobs_can_be_chained_on_success() <ide> { <ide> JobChainingTestFirstJob::dispatch()->then([ <del> new JobChainingTestSecondJob <add> new JobChainingTestSecondJob, <ide> ]); <ide> <ide> $this->assertTrue(JobChainingTestFirstJob::$ran); <ide> $this->assertTrue(JobChainingTestSecondJob::$ran); <ide> } <ide> <del> <ide> public function test_jobs_can_be_chained_via_queue() <ide> { <ide> Queue::connection('sync')->push((new JobChainingTestFirstJob)->then([ <del> new JobChainingTestSecondJob <add> new JobChainingTestSecondJob, <ide> ])); <ide> <ide> $this->assertTrue(JobChainingTestFirstJob::$ran); <ide> $this->assertTrue(JobChainingTestSecondJob::$ran); <ide> } <ide> <del> <ide> public function test_second_job_is_not_fired_if_first_was_already_deleted() <ide> { <ide> Queue::connection('sync')->push((new JobChainingTestFailingJob)->then([ <del> new JobChainingTestSecondJob <add> new JobChainingTestSecondJob, <ide> ])); <ide> <ide> $this->assertFalse(JobChainingTestSecondJob::$ran); <ide> } <ide> } <ide> <del> <ide> class JobChainingTestFirstJob implements ShouldQueue <ide> { <ide> use Dispatchable, Queueable; <ide> public function handle() <ide> } <ide> } <ide> <del> <ide> class JobChainingTestSecondJob implements ShouldQueue <ide> { <ide> use Dispatchable, Queueable; <ide> public function handle() <ide> } <ide> } <ide> <del> <ide> class JobChainingTestFailingJob implements ShouldQueue <ide> { <ide> use Dispatchable, InteractsWithQueue, Queueable;
1
PHP
PHP
add the setcacheheaders middleware
6e9c0c885257d73d6af0dd60cf75a76266d3c66d
<ide><path>app/Http/Kernel.php <ide> class Kernel extends HttpKernel <ide> 'can' => \Illuminate\Auth\Middleware\Authorize::class, <ide> 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, <ide> 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, <add> 'cache' => \Illuminate\Http\Middleware\SetCacheHeaders::class, <ide> ]; <ide> }
1
Go
Go
fix flakyness in testdockernetworkinternalmode
a2bb2144b3e0d49ac615976bfac462a307d85f0e
<ide><path>integration-cli/docker_cli_network_unix_test.go <ide> func (s *DockerSuite) TestDockerNetworkInternalMode(c *check.C) { <ide> c.Assert(waitRun("first"), check.IsNil) <ide> dockerCmd(c, "run", "-d", "--net=internal", "--name=second", "busybox:glibc", "top") <ide> c.Assert(waitRun("second"), check.IsNil) <del> out, _, err := dockerCmdWithError("exec", "first", "ping", "-W", "4", "-c", "1", "www.google.com") <add> out, _, err := dockerCmdWithError("exec", "first", "ping", "-W", "4", "-c", "1", "8.8.8.8") <ide> c.Assert(err, check.NotNil) <del> c.Assert(out, checker.Contains, "ping: bad address") <add> c.Assert(out, checker.Contains, "100% packet loss") <ide> _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") <ide> c.Assert(err, check.IsNil) <ide> }
1
Javascript
Javascript
fix more lint issues
892056bf97842b1bfe6a2e328df67d5a0043b79e
<ide><path>test/common.js <ide> exports.indirectInstanceOf = function(obj, cls) { <ide> exports.ddCommand = function(filename, kilobytes) { <ide> if (process.platform == 'win32') { <ide> return '"' + process.argv[0] + '" "' + path.resolve(exports.fixturesDir, <del> 'create-file.js') + '" "' + filename + '" ' + (kilobytes * 1024); <add> 'create-file.js') + '" "' + filename + '" ' + (kilobytes * 1024); <ide> } else { <ide> return 'dd if=/dev/zero of="' + filename + '" bs=1024 count=' + kilobytes; <ide> } <ide><path>test/simple/test-child-process-double-pipe.js <ide> var assert = require('assert'), <ide> // We're trying to reproduce: <ide> // $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/ <ide> <del>var echo = is_windows ? spawn('cmd.exe', ['/c', 'echo', 'hello&&', 'echo', <del> 'node&&', 'echo', 'and&&', 'echo', 'world']) : <del> spawn('echo', ['hello\nnode\nand\nworld\n']), <del> grep = spawn('grep', ['o']), <del> sed = spawn('sed', ['s/o/O/']); <add>var grep = spawn('grep', ['o']), <add> sed = spawn('sed', ['s/o/O/']), <add> echo; <add> <add>if (is_windows) { <add> echo = spawn('cmd.exe', ['/c', 'echo', 'hello&&', 'echo', <add> 'node&&', 'echo', 'and&&', 'echo', 'world']); <add>} else { <add> echo = spawn('echo', ['hello\nnode\nand\nworld\n']); <add>} <ide> <ide> /* <ide> * grep and sed hang if the spawn function leaks file descriptors to child <ide><path>test/simple/test-executable-path.js <ide> var match = false; <ide> <ide> var isDebug = process.features.debug; <ide> <del>var debugPaths = [ path.normalize(path.join(__dirname, '..', '..', <del> 'out', 'Debug', 'node')), <del> path.normalize(path.join(__dirname, '..', '..', <del> 'Debug', 'node'))]; <del>var defaultPaths = [ path.normalize(path.join(__dirname, '..', '..', <del> 'out', 'Release', 'node')), <del> path.normalize(path.join(__dirname, '..', '..', <del> 'Release', 'node'))]; <add>var debugPaths = [path.normalize(path.join(__dirname, '..', '..', <add> 'out', 'Debug', 'node')), <add> path.normalize(path.join(__dirname, '..', '..', <add> 'Debug', 'node'))]; <add>var defaultPaths = [path.normalize(path.join(__dirname, '..', '..', <add> 'out', 'Release', 'node')), <add> path.normalize(path.join(__dirname, '..', '..', <add> 'Release', 'node'))]; <ide> <ide> console.error('debugPaths: ' + debugPaths); <ide> console.error('defaultPaths: ' + defaultPaths); <ide><path>test/simple/test-http-1.0.js <ide> function test(handler, request_generator, response_validator) { <ide> <ide> function request_generator() { <ide> return ('GET / HTTP/1.0\r\n' + <del> 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + <add> 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + <add> 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + <ide> 'Host: 127.0.0.1:1337\r\n' + <ide> 'Accept: */*\r\n' + <ide> '\r\n'); <ide> function test(handler, request_generator, response_validator) { <ide> <ide> function request_generator() { <ide> return ('GET / HTTP/1.1\r\n' + <del> 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + <add> 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + <add> 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + <ide> 'Connection: close\r\n' + <ide> 'Host: 127.0.0.1:1337\r\n' + <ide> 'Accept: */*\r\n' + <ide><path>test/simple/test-path-makelong.js <ide> if (process.platform === 'win32') { <ide> <ide> var file = path.join(common.fixturesDir, 'a.js'); <ide> var resolvedFile = path.resolve(file); <del> var networkFile = '\\\\someserver\\someshare\\somefile'; <ide> <ide> assert.equal('\\\\?\\' + resolvedFile, path._makeLong(file)); <ide> assert.equal('\\\\?\\' + resolvedFile, path._makeLong('\\\\?\\' + file)); <ide> assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', <del> path._makeLong('\\\\someserver\\someshare\\somefile')); <add> path._makeLong('\\\\someserver\\someshare\\somefile')); <ide> assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', <del> path._makeLong('\\\\?\\UNC\\someserver\\someshare\\somefile')); <del> assert.equal('\\\\.\\pipe\\somepipe', path._makeLong('\\\\.\\pipe\\somepipe')); <add> path._makeLong('\\\\?\\UNC\\someserver\\someshare\\somefile')); <add> assert.equal('\\\\.\\pipe\\somepipe', <add> path._makeLong('\\\\.\\pipe\\somepipe')); <ide> } <ide><path>test/simple/test-repl-tab-complete.js <ide> var repl = require('repl'); <ide> <ide> // A stream to push an array into a REPL <ide> function ArrayStream() { <del> this.run = function (data) { <add> this.run = function(data) { <ide> var self = this; <del> data.forEach(function (line) { <add> data.forEach(function(line) { <ide> self.emit('data', line); <ide> }); <ide> } <ide> } <ide> util.inherits(ArrayStream, require('stream').Stream); <ide> ArrayStream.prototype.readable = true; <ide> ArrayStream.prototype.writable = true; <del>ArrayStream.prototype.resume = function () {}; <del>ArrayStream.prototype.write = function () {}; <add>ArrayStream.prototype.resume = function() {}; <add>ArrayStream.prototype.write = function() {}; <ide> <del>var works = [ [ 'inner.one' ], 'inner.o' ]; <del>var doesNotBreak = [ [], 'inner.o' ]; <add>var works = [['inner.one'], 'inner.o']; <add>var doesNotBreak = [[], 'inner.o']; <ide> <ide> var putIn = new ArrayStream(); <ide> var testMe = repl.start('', putIn); <ide> var testMe = repl.start('', putIn); <ide> putIn.run(['.clear']); <ide> putIn.run([ <ide> 'var inner = {', <del> 'one:1']); <del>testMe.complete('inner.o', function (error, data) { <add> 'one:1' <add>]); <add>testMe.complete('inner.o', function(error, data) { <ide> assert.deepEqual(data, doesNotBreak); <ide> }); <ide> <ide> // Tab Complete will return globaly scoped variables <ide> putIn.run(['};']); <del>testMe.complete('inner.o', function (error, data) { <add>testMe.complete('inner.o', function(error, data) { <ide> assert.deepEqual(data, works); <ide> }); <ide> <ide> putIn.run(['.clear']); <ide> putIn.run([ <ide> 'var inner = ( true ' , <ide> '?', <del> '{one: 1} : ']); <del>testMe.complete('inner.o', function (error, data) { <add> '{one: 1} : ' <add>]); <add>testMe.complete('inner.o', function(error, data) { <ide> assert.deepEqual(data, doesNotBreak); <ide> }); <ide> <ide> putIn.run(['.clear']); <ide> // Tab Complete will return a simple local variable <ide> putIn.run([ <ide> 'var top = function () {', <del> 'var inner = {one:1};']); <del>testMe.complete('inner.o', function (error, data) { <add> 'var inner = {one:1};' <add>]); <add>testMe.complete('inner.o', function(error, data) { <ide> assert.deepEqual(data, works); <ide> }); <ide> <ide> // When you close the function scope tab complete will not return the <ide> // locally scoped variable <ide> putIn.run(['};']); <del>testMe.complete('inner.o', function (error, data) { <add>testMe.complete('inner.o', function(error, data) { <ide> assert.deepEqual(data, doesNotBreak); <ide> }); <ide> <ide> putIn.run(['.clear']); <ide> // Tab Complete will return a complex local variable <ide> putIn.run([ <ide> 'var top = function () {', <del> 'var inner = {', <del> ' one:1', <del> '};']); <del>testMe.complete('inner.o', function (error, data) { <add> 'var inner = {', <add> ' one:1', <add> '};' <add>]); <add>testMe.complete('inner.o', function(error, data) { <ide> assert.deepEqual(data, works); <ide> }); <ide> <ide> putIn.run(['.clear']); <ide> // has paramaters <ide> putIn.run([ <ide> 'var top = function (one, two) {', <del> 'var inner = {', <del> ' one:1', <del> '};']); <del>testMe.complete('inner.o', function (error, data) { <add> 'var inner = {', <add> ' one:1', <add> '};' <add>]); <add>testMe.complete('inner.o', function(error, data) { <ide> assert.deepEqual(data, works); <ide> }); <ide> <ide> putIn.run(['.clear']); <ide> // scope is nested inside an immediately executed function <ide> putIn.run([ <ide> 'var top = function () {', <del> '(function test () {', <del> 'var inner = {', <del> ' one:1', <del> '};']); <del>testMe.complete('inner.o', function (error, data) { <add> '(function test () {', <add> 'var inner = {', <add> ' one:1', <add> '};' <add>]); <add>testMe.complete('inner.o', function(error, data) { <ide> assert.deepEqual(data, works); <ide> }); <ide> <ide> putIn.run(['.clear']); <ide> // def has the params and { on a seperate line <ide> putIn.run([ <ide> 'var top = function () {', <del> 'r = function test (', <del> ' one, two) {', <del> 'var inner = {', <del> ' one:1', <del> '};']); <del>testMe.complete('inner.o', function (error, data) { <add> 'r = function test (', <add> ' one, two) {', <add> 'var inner = {', <add> ' one:1', <add> '};' <add>]); <add>testMe.complete('inner.o', function(error, data) { <ide> assert.deepEqual(data, doesNotBreak); <ide> }); <ide> <ide> putIn.run(['.clear']); <ide> // currently does not work, but should not break, not the { <ide> putIn.run([ <ide> 'var top = function () {', <del> 'r = function test ()', <del> '{', <del> 'var inner = {', <del> ' one:1', <del> '};']); <del>testMe.complete('inner.o', function (error, data) { <add> 'r = function test ()', <add> '{', <add> 'var inner = {', <add> ' one:1', <add> '};' <add>]); <add>testMe.complete('inner.o', function(error, data) { <ide> assert.deepEqual(data, doesNotBreak); <ide> }); <ide> <ide> putIn.run(['.clear']); <ide> // currently does not work, but should not break <ide> putIn.run([ <ide> 'var top = function () {', <del> 'r = function test (', <del> ')', <del> '{', <del> 'var inner = {', <del> ' one:1', <del> '};']); <del>testMe.complete('inner.o', function (error, data) { <add> 'r = function test (', <add> ')', <add> '{', <add> 'var inner = {', <add> ' one:1', <add> '};' <add>]); <add>testMe.complete('inner.o', function(error, data) { <ide> assert.deepEqual(data, doesNotBreak); <ide> }); <ide> <ide><path>test/simple/test-script-context.js <ide> try { <ide> } <ide> catch (e) { <ide> gh1140Exception = e; <del> assert.ok(/expected-filename/.test(e.stack), 'expected appearance of filename in Error stack'); <add> assert.ok(/expected-filename/.test(e.stack), <add> 'expected appearance of filename in Error stack'); <ide> } <del>assert.ok(gh1140Exception, 'expected exception from runInContext signature test'); <add>assert.ok(gh1140Exception, <add> 'expected exception from runInContext signature test'); <ide> <ide> // GH-558, non-context argument segfaults / raises assertion <ide> function isTypeError(o) { <ide><path>test/simple/test-stdin-child-proc.js <ide> var child_process = require('child_process'); <ide> var path = require('path'); <ide> child_process.spawn(process.execPath, <del> [ path.resolve(__dirname, 'test-stdin-pause-resume.js') ]); <add> [path.resolve(__dirname, 'test-stdin-pause-resume.js')]);
8
Go
Go
fix typo 'woudld' to 'would'
d92acd59108565ac2e552e9f04e873decd192e6d
<ide><path>daemon/build.go <ide> func (rl *releaseableLayer) Commit(os string) (builder.ReleaseableLayer, error) <ide> if err != nil { <ide> return nil, err <ide> } <del> // TODO: An optimization woudld be to handle empty layers before returning <add> // TODO: An optimization would be to handle empty layers before returning <ide> return &releaseableLayer{layerStore: rl.layerStore, roLayer: newLayer}, nil <ide> } <ide>
1
Javascript
Javascript
check queue size before starting animated batch
75fb346e74a27f114486237a3626c3f2dee44e45
<ide><path>Libraries/Animated/NativeAnimatedHelper.js <ide> const API = { <ide> }, <ide> disableQueue: function (): void { <ide> invariant(NativeAnimatedModule, 'Native animated module is not available'); <del> const queueLength = queue.length; <del> if (queueLength > 0) { <del> if (Platform.OS === 'android') { <del> NativeAnimatedModule.startOperationBatch(); <del> } <del> for (let i = 0; i < queueLength; i++) { <del> queue[i](); <del> } <del> queue.length = 0; <del> if (Platform.OS === 'android') { <del> NativeAnimatedModule.finishOperationBatch(); <del> } <add> <add> if (Platform.OS === 'android') { <add> NativeAnimatedModule.startOperationBatch(); <add> } <add> for (let q = 0, l = queue.length; q < l; q++) { <add> queue[q](); <add> } <add> queue.length = 0; <add> if (Platform.OS === 'android') { <add> NativeAnimatedModule.finishOperationBatch(); <ide> } <ide> }, <ide> queueOperation: (fn: () => void): void => {
1
Java
Java
fix typo in flowableretrytest.java
cea706672d5f44f9be36c6e3914528ce9be86ced
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableRetryTest.java <ide> public void run() { <ide> } <ide> } <ide> <del> /** Observer for listener on seperate thread. */ <add> /** Observer for listener on separate thread. */ <ide> static final class AsyncSubscriber<T> extends DefaultSubscriber<T> { <ide> <ide> protected CountDownLatch latch = new CountDownLatch(1);
1
Java
Java
raise ise if @requestbody is used for form data
e9819b7535841a27586edfcbe83c5ab1adf47339
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractMessageReaderArgumentResolver.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> protected Mono<Object> readBody(MethodParameter bodyParam, @Nullable MethodParam <ide> MediaType mediaType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM); <ide> Object[] hints = extractValidationHints(bodyParam); <ide> <add> if (mediaType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)) { <add> return Mono.error(new IllegalStateException( <add> "In a WebFlux application, form data is accessed via ServerWebExchange.getFormData().")); <add> } <add> <ide> if (logger.isDebugEnabled()) { <ide> logger.debug(exchange.getLogPrefix() + (contentType != null ? <ide> "Content-Type:" + contentType :
1
Ruby
Ruby
add variants to template class
c63b18de1865182e027a97ea4186717a71792b81
<ide><path>actionview/lib/action_view/template.rb <ide> class Template <ide> <ide> extend Template::Handlers <ide> <del> attr_accessor :locals, :formats, :virtual_path <add> attr_accessor :locals, :formats, :variants, :virtual_path <ide> <ide> attr_reader :source, :identifier, :handler, :original_encoding, :updated_at <ide> <ide> def initialize(source, identifier, handler, details) <ide> @virtual_path = details[:virtual_path] <ide> @updated_at = details[:updated_at] || Time.now <ide> @formats = Array(format).map { |f| f.respond_to?(:ref) ? f.ref : f } <add> @variants = [details[:variant]] <ide> @compile_mutex = Mutex.new <ide> end <ide> <ide><path>actionview/lib/action_view/template/resolver.rb <ide> def decorate(templates, path_info, details, locals) #:nodoc: <ide> cached = nil <ide> templates.each do |t| <ide> t.locals = locals <del> t.formats = details[:formats] || [:html] if t.formats.empty? <add> t.formats = details[:formats] || [:html] if t.formats.empty? <add> t.variants = details[:variants] || [] if t.variants.empty? <ide> t.virtual_path ||= (cached ||= build_path(*path_info)) <ide> end <ide> end <ide> def query(path, details, formats) <ide> } <ide> <ide> template_paths.map { |template| <del> handler, format = extract_handler_and_format(template, formats) <del> contents = File.binread template <add> handler, format, variant = extract_handler_and_format_and_variant(template, formats) <add> contents = File.binread(template) <ide> <ide> Template.new(contents, File.expand_path(template), handler, <ide> :virtual_path => path.virtual, <ide> :format => format, <del> :updated_at => mtime(template)) <add> :variant => variant, <add> :updated_at => mtime(template) <add> ) <ide> } <ide> end <ide> <ide> def mtime(p) <ide> # Extract handler and formats from path. If a format cannot be a found neither <ide> # from the path, or the handler, we should return the array of formats given <ide> # to the resolver. <del> def extract_handler_and_format(path, default_formats) <add> def extract_handler_and_format_and_variant(path, default_formats) <ide> pieces = File.basename(path).split(".") <ide> pieces.shift <ide> <ide> def extract_handler_and_format(path, default_formats) <ide> end <ide> <ide> handler = Template.handler_for_extension(extension) <del> format = pieces.last && pieces.last.split(EXTENSIONS[:variants], 2).first # remove variant from format <add> format, variant = pieces.last.split(EXTENSIONS[:variants], 2) if pieces.last <ide> format &&= Template::Types[format] <ide> <del> [handler, format] <add> [handler, format, variant] <ide> end <ide> end <ide> <ide><path>actionview/lib/action_view/testing/resolvers.rb <ide> def query(path, exts, formats) <ide> @hash.each do |_path, array| <ide> source, updated_at = array <ide> next unless _path =~ query <del> handler, format = extract_handler_and_format(_path, formats) <add> handler, format, variant = extract_handler_and_format_and_variant(_path, formats) <ide> templates << Template.new(source, _path, handler, <del> :virtual_path => path.virtual, :format => format, :updated_at => updated_at) <add> :virtual_path => path.virtual, <add> :format => format, <add> :variant => variant, <add> :updated_at => updated_at <add> ) <ide> end <ide> <ide> templates.sort_by {|t| -t.identifier.match(/^#{query}$/).captures.reject(&:blank?).size } <ide> def query(path, exts, formats) <ide> <ide> class NullResolver < PathResolver <ide> def query(path, exts, formats) <del> handler, format = extract_handler_and_format(path, formats) <del> [ActionView::Template.new("Template generated by Null Resolver", path, handler, :virtual_path => path, :format => format)] <add> handler, format, variant = extract_handler_and_format_and_variant(path, formats) <add> [ActionView::Template.new("Template generated by Null Resolver", path, handler, :virtual_path => path, :format => format, :variant => variant)] <ide> end <ide> end <ide>
3
Text
Text
update command example for commandregistry
b6c86ea2179027e06f834d7569a6110beb76e72f
<ide><path>docs/advanced/keymaps.md <ide> can be expressed as keystroke patterns separated by spaces. <ide> Commands are custom DOM events that are triggered when a keystroke matches a <ide> binding. This allows user interface code to listen for named commands without <ide> specifying the specific keybinding that triggers it. For example, the following <del>code sets up {EditorView} to listen for commands to move the cursor to the first <del>character of the current line: <add>code creates a command to insert the current date in an editor: <ide> <ide> ```coffee <del>class EditorView <del> listenForEvents: -> <del> @command 'editor:move-to-first-character-of-line', => <del> @editor.moveToFirstCharacterOfLine() <add>atom.commands.add 'atom-text-editor', <add> 'user:insert-date': (event) -> <add> editor = @getModel() <add> editor.insertText(new Date().toLocaleString()) <ide> ``` <ide> <del>The `::command` method is basically an enhanced version of jQuery's `::on` <del>method that listens for a custom DOM event and adds some metadata to the DOM, <del>which is read by the command palette. <add>`atom.commands` refers to the global {CommandRegistry} instance where all commands <add>are set and consequently picked up by the command palette. <ide> <ide> When you are looking to bind new keys, it is often useful to use the command <ide> palette (`ctrl-shift-p`) to discover what commands are being listened for in a
1
Javascript
Javascript
remove unnecessary task config
22829b552993cb7f751259e29448b37b054b29f5
<ide><path>grunt/config/jsx/jsx.js <ide> var debug = { <ide> outputDir: "build/modules" <ide> }; <ide> <del>var jasmine = { <del> rootIDs: [ <del> "all" <del> ], <del> getConfig: getDebugConfig, <del> sourceDir: "vendor/jasmine", <del> outputDir: "build/jasmine" <del>}; <del> <ide> var test = { <ide> rootIDs: rootIDs.concat([ <ide> "test/all.js", <ide> var release = { <ide> <ide> module.exports = { <ide> debug: debug, <del> jasmine: jasmine, <ide> test: test, <ide> release: release <ide> };
1
Javascript
Javascript
add type support for template base class
6a919ba8ddfcd7b12aa1080d523fe5f7dfcd30af
<ide><path>lib/Chunk.js <ide> class Chunk { <ide> this.chunkReason = undefined; <ide> /** @type {boolean} */ <ide> this.extraAsync = false; <add> this.removedModules = undefined; <ide> } <ide> <ide> /** <ide><path>lib/Module.js <ide> const ModuleReason = require("./ModuleReason"); <ide> const SortableSet = require("./util/SortableSet"); <ide> const Template = require("./Template"); <ide> <del>/** @typedef {typeof import("./Chunk")} Chunk */ <del>/** @typedef {typeof import("./RequestShortener")} RequestShortener */ <add>/** @typedef {import("./Chunk")} Chunk */ <add>/** @typedef {import("./RequestShortener")} RequestShortener */ <ide> <ide> const EMPTY_RESOLVE_OPTIONS = {}; <ide> <ide> class Module extends DependenciesBlock { <ide> this._chunks = new SortableSet(undefined, sortById); <ide> <ide> // Info from Compilation (per Compilation) <del> /** @type {number | string} */ <add> /** @type {number|string} */ <ide> this.id = null; <ide> /** @type {number} */ <ide> this.index = null; <ide><path>lib/Template.js <ide> const stringifyIdSortPredicate = (a, b) => { <ide> return 0; <ide> }; <ide> <del>//TODO: Change type to Module when import works <del>//https://github.com/Microsoft/TypeScript/issues/23375 <ide> /** <del> * @param {HasId} module the module to compare against <add> * @param {Module} module the module to compare against <ide> * @return {boolean} return true if module.id is equal to type "number" <ide> */ <ide> const moduleIdIsNumber = module => { <ide> class Template { <ide> <ide> /** <ide> * <del> * @param {string | string[]} str string to convert to identity <add> * @param {string[] | string} str string to convert to identity <ide> * @return {string} converted identity <ide> */ <ide> static indent(str) { <ide> class Template { <ide> <ide> /** <ide> * <del> * @param {HasId[]} modules - a collection of modules to get array bounds for <add> * @param {Module[]} modules a collection of modules to get array bounds for <ide> * @return {[number, number] | false} returns the upper and lower array bounds <ide> * or false if not every module has a number based id <ide> */ <ide> static getModulesArrayBounds(modules) { <add> // Typeguards don't work for .every() with predicate functions <add> // https://github.com/Microsoft/TypeScript/issues/23799 <ide> if (!modules.every(moduleIdIsNumber)) return false; <ide> var maxId = -Infinity; <ide> var minId = Infinity; <ide> for (const module of modules) { <del> if (maxId < module.id) maxId = module.id; <del> if (minId > module.id) minId = module.id; <add> if (maxId < module.id) maxId = /** @type {number} */ (module.id); <add> if (minId > module.id) minId = /** @type {number} */ (module.id); <ide> } <ide> if (minId < 16 + ("" + minId).length) { <ide> // add minId x ',' instead of 'Array(minId).concat(…)' <ide> class Template { <ide> } <ide> <ide> /** <del> * <ide> * @param {Chunk} chunk chunk whose modules will be rendered <ide> * @param {ModuleFilterPredicate} filterFn function used to filter modules from chunk to render <ide> * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance used to render modules
3
Javascript
Javascript
update ssaarenderpass.js
8bf2f2186eb3967b182b00910b5994112bae3dc3
<ide><path>examples/jsm/postprocessing/SSAARenderPass.js <ide> import { <ide> UniformsUtils, <ide> WebGLRenderTarget <ide> } from '../../../build/three.module.js'; <del>import { Pass, FullScreenQuad } from '../postprocessing/Pass.js'; <add>import { Pass, FullScreenQuad } from './Pass.js'; <ide> import { CopyShader } from '../shaders/CopyShader.js'; <ide> <ide> /**
1
Python
Python
resolve line-too-long in distribute
b1105dca17670dcac229271e63d5073fe445b84c
<ide><path>keras/distribute/collective_all_reduce_strategy_test.py <ide> def _model_fn(): <ide> def _get_dataset(): <ide> inputs = tf.expand_dims(tf.constant(range(10)), axis=1) <ide> targets = tf.expand_dims(tf.constant(range(10)), axis=1) <del> # Make global batch size 12 for 2 replicas and a non-repeated dataset <del> # with 10 elements so that we have partial batch <add> # Make global batch size 12 for 2 replicas and a non-repeated <add> # dataset with 10 elements so that we have partial batch <ide> dataset = tf.data.Dataset.from_tensor_slices( <ide> (inputs, targets) <ide> ).batch(12, drop_remainder=False) <ide><path>keras/distribute/ctl_correctness_test.py <ide> def test_dnn_correctness_minus_tpus( <ide> sync_batchnorm, <ide> jit_compile, <ide> ): <del> # TODO(anjs): Identify why this particular V1 optimizer needs a higher tol. <add> # TODO(anjs): Identify why this particular V1 optimizer needs a higher <add> # tol. <ide> if ( <ide> "FtrlV1" in optimizer_fn._name <ide> and "TPU" in type(distribution).__name__ <ide> def dnn_correctness( <ide> def test_fused_batch_norm_uneven_batch(self, distribution): <ide> """Test that fused batch norm works when the last device may get empty data. <ide> <del> Adapted from https://www.tensorflow.org/tutorials/distribute/custom_training <add> Adapted from <add> https://www.tensorflow.org/tutorials/distribute/custom_training <ide> but using ResNet, which uses fused batchnorm, as the model. <ide> <ide> Arguments: <ide> distribution: distribute test configuration <ide> """ <ide> (train_images, train_labels), _ = fashion_mnist.load_data() <del> # add channel dimension to make 2D data into 3D, since some ops of the model <del> # require it. <add> # add channel dimension to make 2D data into 3D, since some ops of the <add> # model require it. <ide> train_images = train_images[..., None] <ide> train_images = train_images / np.float32(255) <ide> <ide> def test_fused_batch_norm_uneven_batch(self, distribution): <ide> <ide> epochs = 2 <ide> <del> # Keep only the first images, so that the last GPU receives an empty batch <add> # Keep only the first images, so that the last GPU receives an empty <add> # batch <ide> padded_train_images = padded_train_images[:num_samples] <ide> train_labels = train_labels[:num_samples] <ide> <ide> def create_model(): <ide> return keras.Model(inputs, features) <ide> <ide> with distribution.scope(): <del> # Set reduction to `none` so we can do the reduction afterwards and divide <del> # by global batch size. <add> # Set reduction to `none` so we can do the reduction afterwards and <add> # divide by global batch size. <ide> loss_object = keras.losses.SparseCategoricalCrossentropy( <ide> from_logits=True, reduction=losses_impl.Reduction.NONE <ide> ) <ide><path>keras/distribute/custom_training_loop_metrics_test.py <ide> def step_fn(i): <ide> for i in dataset: <ide> distribution.run(step_fn, args=(i,)) <ide> <del> # This should be the mean of integers 0-9 which has a sum of 45 and a count <del> # of 10 resulting in mean of 4.5. <add> # This should be the mean of integers 0-9 which has a sum of 45 and a <add> # count of 10 resulting in mean of 4.5. <ide> self.assertEqual(metric.result().numpy(), 4.5) <ide> <ide> @tf.__internal__.distribute.combinations.generate( <ide> def test_update_keras_metric_outside_strategy_scope_cross_replica( <ide> for i in range(10): <ide> metric.update_state(i) <ide> <del> # This should be the mean of integers 0-9 which has a sum of 45 and a count <del> # of 10 resulting in mean of 4.5. <add> # This should be the mean of integers 0-9 which has a sum of 45 and a <add> # count of 10 resulting in mean of 4.5. <ide> self.assertEqual(metric.result().numpy(), 4.5) <ide> <ide> @tf.__internal__.distribute.combinations.generate( <ide> def step_fn(i): <ide> <ide> train_fn(dataset) <ide> <del> # This should be the mean of integers 0-9 which has a sum of 45 and a count <del> # of 10 resulting in mean of 4.5. <add> # This should be the mean of integers 0-9 which has a sum of 45 and a <add> # count of 10 resulting in mean of 4.5. <ide> self.assertEqual(metric.result().numpy(), 4.5) <ide> <ide> <ide><path>keras/distribute/custom_training_loop_models_test.py <ide> def test_lstm(self, distribution): <ide> <ide> def create_lstm_model(): <ide> model = keras.models.Sequential() <del> # We only have LSTM variables so we can detect no gradient issues more <del> # easily. <add> # We only have LSTM variables so we can detect no gradient issues <add> # more easily. <ide> model.add( <ide> keras.layers.LSTM( <ide> 1, return_sequences=False, input_shape=(10, 1) <ide> def step_fn(inputs): <ide> def test_nested_tf_functions(self, distribution): <ide> # The test builds two computations with keras layers, one with nested <ide> # tf.function, and the other without nested tf.function. We run these <del> # computations independently on the model with same weights, and make sure <del> # the variables are still the same after one training step. <add> # computations independently on the model with same weights, and make <add> # sure the variables are still the same after one training step. <ide> <ide> inputs = np.random.random((10, 3)).astype(np.float32) <ide> targets = np.ones((10, 4), dtype=np.float32) <ide> def step_fn(inputs): <ide> loss = distribution.reduce(tf.distribute.ReduceOp.MEAN, loss, axis=0) <ide> <ide> def test_variable_run_argument(self, distribution): <del> # Test that variables passed to run() remain variables. Previous behavior <del> # in TPUStrategy was to cast to Tensor. <add> # Test that variables passed to run() remain variables. Previous <add> # behavior in TPUStrategy was to cast to Tensor. <ide> <ide> with distribution.scope(): <ide> optimizer = gradient_descent.SGD(0.1) <ide><path>keras/distribute/dataset_creator_model_fit_test.py <ide> def testModelEvaluateWithNoStepsPerEpoch(self, strategy): <ide> <ide> def testModelPredict(self, strategy): <ide> _, predictions = self._model_predict(strategy, steps=3) <del> # Check the first (0th index), fourth (3rd index) and the last predictions <del> # because the first, fourth and the last input are the same in <del> # `model.predict` so there predictions should match. <add> # Check the first (0th index), fourth (3rd index) and the last <add> # predictions because the first, fourth and the last input are the same <add> # in `model.predict` so there predictions should match. <ide> self.assertTrue( <ide> all(predictions[0] == predictions[i] for i in [0, 3, 5]) <ide> ) <ide> def testModelPredictWithNormalizationLayer(self, strategy): <ide> _, predictions = self._model_predict( <ide> strategy, with_normalization_layer=True, steps=3 <ide> ) <del> # Check the first (0th index), fourth (3rd index) and the last predictions <del> # because the first, fourth and the last input is the same in <del> # `model.predict` so there predictions should match. <add> # Check the first (0th index), fourth (3rd index) and the last <add> # predictions because the first, fourth and the last input is the same <add> # in `model.predict` so there predictions should match. <ide> self.assertTrue( <ide> all(predictions[0] == predictions[i] for i in [0, 3, 5]) <ide> ) <ide> def testModelPredictWithStepsPerExecution(self, strategy): <ide> strategy, steps_per_execution=3, steps=3 <ide> ) <ide> <del> # Check the first (0th index), fourth (3rd index) and the last predictions <del> # because the first, fourth and the last input is the same in <del> # `model.predict` so there predictions should match. <add> # Check the first (0th index), fourth (3rd index) and the last <add> # predictions because the first, fourth and the last input is the same <add> # in `model.predict` so there predictions should match. <ide> self.assertTrue( <ide> all(predictions[0] == predictions[i] for i in [0, 3, 5]) <ide> ) <ide> def fit_dataset_fn(input_context): <ide> model = self._model_fit(strategy, x=x, validation_data=validation_data) <ide> _, predictions = self._model_predict(strategy, model, steps=3) <ide> <del> # Check the first (0th index), fourth (3rd index) and the last predictions <del> # because the first, fourth and the last input is the same in <del> # `model.predict` so there predictions should match. <add> # Check the first (0th index), fourth (3rd index) and the last <add> # predictions because the first, fourth and the last input is the same <add> # in `model.predict` so there predictions should match. <ide> self.assertTrue( <ide> all(predictions[0] == predictions[i] for i in [0, 3, 5]) <ide> ) <ide> def _dataset_fn(input_context): <ide> test_data=dataset_creator.DatasetCreator(_dataset_fn), <ide> ) <ide> <del> # Check the first (0th index), fourth (3rd index) and the last predictions <del> # because the first, fourth and the last input is the same in <del> # `model.predict` so there predictions should match. <add> # Check the first (0th index), fourth (3rd index) and the last <add> # predictions because the first, fourth and the last input is the same <add> # in `model.predict` so there predictions should match. <ide> self.assertTrue( <ide> all(predictions[0] == predictions[i] for i in [0, 3, 5]) <ide> ) <ide><path>keras/distribute/distribute_coordinator_utils.py <ide> class _WorkerContext: <ide> """The worker context class. <ide> <ide> This context object provides configuration information for each task. One <del> context manager with a worker context object will be created per <del> invocation to the `worker_fn` where `get_current_worker_context` can be called <del> to access the worker context object. <add> context manager with a worker context object will be created per invocation <add> to the `worker_fn` where `get_current_worker_context` can be called to <add> access the worker context object. <ide> """ <ide> <ide> def __init__( <ide> def __init__( <ide> <ide> Args: <ide> strategy: a `DistributionStrategy` object. <del> cluster_spec: a ClusterSpec object. It can be empty or None in the local <del> training case. <del> task_type: a string indicating the role of the corresponding task, such as <del> "worker" or "ps". It can be None if it is local training or in-graph <del> replicated training. <add> cluster_spec: a ClusterSpec object. It can be empty or None in the <add> local training case. <add> task_type: a string indicating the role of the corresponding task, <add> such as "worker" or "ps". It can be None if it is local training or <add> in-graph replicated training. <ide> task_id: an integer indicating id of the corresponding task. It can be <ide> None if it is local training or in-graph replicated training. <ide> session_config: an optional `tf.compat.v1.ConfigProto` object. <del> rpc_layer: optional string specifying the RPC protocol for communication <del> with worker masters. If None or empty, hosts in the `cluster_spec` will <del> be used directly. <del> worker_barrier: optional, the barrier object for worker synchronization. <add> rpc_layer: optional string specifying the RPC protocol for <add> communication with worker masters. If None or empty, hosts in the <add> `cluster_spec` will be used directly. <add> worker_barrier: optional, the barrier object for worker <add> synchronization. <ide> """ <ide> self._strategy = strategy <ide> self._cluster_spec = cluster_spec <ide> def _is_chief(self): <ide> ]: <ide> return True <ide> <del> # If not local and chief not in the cluster_spec, use the first worker as <del> # chief. <add> # If not local and chief not in the cluster_spec, use the first worker <add> # as chief. <ide> if ( <ide> _TaskType.CHIEF not in self._cluster_spec.jobs <ide> and self._task_type == _TaskType.WORKER <ide> def wait_for_other_workers(self): <ide> ValueError: if `worker_barrier` is not passed to the __init__ method. <ide> """ <ide> if not self._worker_barrier: <del> # TODO(yuefengz): we should throw an error in independent worker mode. <add> # TODO(yuefengz): we should throw an error in independent worker <add> # mode. <ide> return <ide> self._worker_barrier.wait() <ide> <ide> def session_creator( <ide> """Returns a session creator. <ide> <ide> The returned session creator will be configured with the correct master <del> target and session configs. It will also run either init ops or ready ops <del> by querying the `strategy` object when `create_session` is called on it. <add> target and session configs. It will also run either init ops or ready <add> ops by querying the `strategy` object when `create_session` is called on <add> it. <ide> <ide> Args: <del> scaffold: A `Scaffold` used for gathering or building supportive ops. If <del> not specified a default one is created. It's used to finalize the graph. <add> scaffold: A `Scaffold` used for gathering or building supportive ops. <add> If not specified a default one is created. It's used to finalize the <add> graph. <ide> config: `ConfigProto` proto used to configure the session. <del> checkpoint_dir: A string. Optional path to a directory where to restore <del> variables. <del> checkpoint_filename_with_path: Full file name path to the checkpoint file. <del> Only one of `checkpoint_dir` or `checkpoint_filename_with_path` can be <del> specified. <del> max_wait_secs: Maximum time to wait for the session to become available. <add> checkpoint_dir: A string. Optional path to a directory where to <add> restore variables. <add> checkpoint_filename_with_path: Full file name path to the checkpoint <add> file. Only one of `checkpoint_dir` or <add> `checkpoint_filename_with_path` can be specified. <add> max_wait_secs: Maximum time to wait for the session to become <add> available. <ide> <ide> Returns: <ide> a descendant of SessionCreator. <ide> def task_id(self): <ide> <ide> @property <ide> def master_target(self): <del> """Returns the session master for the corresponding task to connect to.""" <add> """Returns the session master for the corresponding task to connect <add> to.""" <ide> return self._master_target <ide> <ide> @property <ide> def _run_single_worker( <ide> <ide> def _split_cluster_for_evaluator(cluster_spec, task_type): <ide> """Split the cluster for evaluator since it needn't talk to other tasks.""" <del> # Splitting the cluster is important to prevent the evaluator from talking to <del> # other tasks in the cluster. Since we allow evaluator not to use <add> # Splitting the cluster is important to prevent the evaluator from talking <add> # to other tasks in the cluster. Since we allow evaluator not to use <ide> # distribution strategies and as a result ops in the evaluator task may have <ide> # unspecified devices. Those ops may end up on other tasks if we don't split <ide> # the cluster. <ide> def _run_std_server( <ide> environment=None, <ide> ): <ide> """Runs a standard server.""" <del> # Check if the Server is already running. If so, assert that no configuration <del> # options have changed, and return the existing Server. This allows us to <del> # call `run_distribute_coordinator` multiple times. <add> # Check if the Server is already running. If so, assert that no <add> # configuration options have changed, and return the existing Server. This <add> # allows us to call `run_distribute_coordinator` multiple times. <ide> if getattr(_thread_local, "server", None) is not None: <ide> assert _thread_local.cluster_spec == cluster_spec <ide> assert _thread_local.task_type == task_type <ide> def join(self): <ide> else: <ide> if session_config: <ide> logging.info( <del> "Starting standard TensorFlow server, target = %r, session_config= " <del> "%r", <add> "Starting standard TensorFlow server, target = %r, " <add> "session_config = %r", <ide> target, <ide> session_config, <ide> ) <ide> def run_distribute_coordinator( <ide> default mode, i.e the STANDALONE_CLIENT mode. Given a `cluster_spec` <ide> specifying server addresses and their roles in a cluster, this coordinator <ide> will figure out how to set them up, give the underlying function the right <del> targets for master sessions via a scope object and coordinate their training. <del> The cluster consisting of standard servers needs to be brought up either with <del> the standard server binary or with a binary running distribute coordinator <del> with `task_type` set to non-client type which will then turn into standard <del> servers. <add> targets for master sessions via a scope object and coordinate their <add> training. The cluster consisting of standard servers needs to be brought up <add> either with the standard server binary or with a binary running distribute <add> coordinator with `task_type` set to non-client type which will then turn <add> into standard servers. <ide> <ide> In addition to be the distribute coordinator, this is also the source of <del> configurations for each job in the distributed training. As there are multiple <del> ways to configure a distributed TensorFlow cluster, its context object <del> provides these configurations so that users or higher-level APIs don't have to <del> figure out the configuration for each job by themselves. <add> configurations for each job in the distributed training. As there are <add> multiple ways to configure a distributed TensorFlow cluster, its context <add> object provides these configurations so that users or higher-level APIs <add> don't have to figure out the configuration for each job by themselves. <ide> <ide> In the between-graph replicated training, this coordinator will create <ide> multiple threads and each calls the `worker_fn` which is supposed to create <del> its own graph and connect to one worker master given by its context object. In <del> the in-graph replicated training, it has only one thread calling this <add> its own graph and connect to one worker master given by its context object. <add> In the in-graph replicated training, it has only one thread calling this <ide> `worker_fn`. <ide> <ide> Another mode is the INDEPENDENT_WORKER mode where each server runs a <del> distribute coordinator which will start a standard server and optionally runs <del> `worker_fn` depending whether it is between-graph training or in-graph <add> distribute coordinator which will start a standard server and optionally <add> runs `worker_fn` depending whether it is between-graph training or in-graph <ide> replicated training. <ide> <ide> The `strategy` object is expected to be a DistributionStrategy object which <ide> has implemented methods needed by distributed coordinator such as <del> `configure(session_config, cluster_spec, task_type, task_id)` which configures <del> the strategy object for a specific task and `experimental_should_init` <del> property which instructs the distribute coordinator whether to run init ops <del> for a task. The distribute coordinator will make a copy of the `strategy` <del> object, call its `configure` method and pass it to `worker_fn` as an argument. <add> `configure(session_config, cluster_spec, task_type, task_id)` which <add> configures the strategy object for a specific task and <add> `experimental_should_init` property which instructs the distribute <add> coordinator whether to run init ops for a task. The distribute coordinator <add> will make a copy of the `strategy` object, call its `configure` method and <add> pass it to `worker_fn` as an argument. <ide> <ide> The `worker_fn` defines the training logic and is called under its own <ide> worker context which can be accessed to via `get_current_worker_context`. A <ide> worker context provides access to configurations for each task, e.g. the <del> task_type, task_id, master target and so on. Since `worker_fn` will be called <del> in a thread and possibly multiple times, caller should be careful when it <del> accesses global data. For example, it is unsafe to define flags in a <add> task_type, task_id, master target and so on. Since `worker_fn` will be <add> called in a thread and possibly multiple times, caller should be careful <add> when it accesses global data. For example, it is unsafe to define flags in a <ide> `worker_fn` or to define different environment variables for different <ide> `worker_fn`s. <ide> <ide> def run_distribute_coordinator( <ide> example, when training with parameter servers, it assigns variables to <ide> parameter servers and all other operations to that worker. In the in-graph <ide> replication case, the `worker_fn` has to define operations for all worker <del> jobs. Using a distribution strategy can simplify the `worker_fn` by not having <del> to worry about the replication and device assignment of variables and <add> jobs. Using a distribution strategy can simplify the `worker_fn` by not <add> having to worry about the replication and device assignment of variables and <ide> operations. <ide> <ide> This method is intended to be invoked by high-level APIs so that users don't <ide> have to explicitly call it to run this coordinator. For those who don't use <del> high-level APIs, to change a program to use this coordinator, wrap everything <del> in a the program after global data definitions such as commandline flag <del> definition into the `worker_fn` and get task-specific configurations from <del> the worker context. <add> high-level APIs, to change a program to use this coordinator, wrap <add> everything in a the program after global data definitions such as <add> commandline flag definition into the `worker_fn` and get task-specific <add> configurations from the worker context. <ide> <ide> The `cluster_spec` can be either passed by the argument or parsed from the <ide> "TF_CONFIG" environment variable. Example of a TF_CONFIG: <ide> def run_distribute_coordinator( <ide> this coordinator will connect to a local session. <ide> <ide> For evaluation, if "evaluator" exists in the cluster_spec, a separate thread <del> will be created to call `eval_fn` with its `task_type` set to "evaluator". If <del> `eval_fn` is not defined, fall back to `worker_fn`. This implies that <add> will be created to call `eval_fn` with its `task_type` set to "evaluator". <add> If `eval_fn` is not defined, fall back to `worker_fn`. This implies that <ide> evaluation will be done on a single machine if there is an "evaluator" task. <ide> If "evaluator" doesn't exist in the cluster_spec, it entirely depends on the <ide> `worker_fn` for how to do evaluation. <ide> def run_distribute_coordinator( <ide> between-graph replicated training or not, whether to run init ops, etc. <ide> This object will also be configured given `session_config`, <ide> `cluster_spec`, `task_type` and `task_id`. <del> eval_fn: optional function for "evaluator" task. If `eval_fn` is not passed <del> in but a "evaluator" task is found in the `cluster_spec`, the `worker_fn` <del> will be used for this task. <add> eval_fn: optional function for "evaluator" task. If `eval_fn` is not <add> passed in but a "evaluator" task is found in the `cluster_spec`, the <add> `worker_fn` will be used for this task. <ide> eval_strategy: optional DistributionStrategy object for "evaluator" task. <del> cluster_spec: a dict, ClusterDef or ClusterSpec specifying servers and roles <del> in a cluster. If not set or empty, fall back to local training. <add> cluster_spec: a dict, ClusterDef or ClusterSpec specifying servers and <add> roles in a cluster. If not set or empty, fall back to local training. <ide> task_type: the current task type, optional if this is a client. <ide> task_id: the current task id, optional if this is a client. <del> session_config: an optional `tf.compat.v1.ConfigProto` object which will be <del> passed to `strategy`'s `configure` method and used to create a session. <add> session_config: an optional `tf.compat.v1.ConfigProto` object which will <add> be passed to `strategy`'s `configure` method and used to create a <add> session. <ide> rpc_layer: optional string, the protocol for RPC, e.g. "grpc". <ide> <ide> Raises: <del> ValueError: if `cluster_spec` is supplied but not a dict or a ClusterDef or <del> a ClusterSpec. <add> ValueError: if `cluster_spec` is supplied but not a dict or a ClusterDef <add> or a ClusterSpec. <ide> <ide> Returns: <ide> In the client job, return the value returned by `worker_fn` if <ide> def run_distribute_coordinator( <ide> "strategy will be used for evaluation." <ide> ) <ide> <del> # Every one starts a standard server, get session config from `configure` <del> # method. <add> # Every one starts a standard server, get session config from <add> # `configure` method. <ide> _configure_session_config_for_std_servers( <ide> strategy, <ide> eval_strategy, <ide> def run_distribute_coordinator( <ide> if task_type != _TaskType.EVALUATOR and not getattr( <ide> strategy.extended, "_std_server_started", False <ide> ): <del> # Right now, with eager mode, context is configured with a std server at <del> # the very beginning while with graph mode the std server is started when <del> # distribute coordinator is called. We should consolidate these two paths. <add> # Right now, with eager mode, context is configured with a std <add> # server at the very beginning while with graph mode the std server <add> # is started when distribute coordinator is called. We should <add> # consolidate these two paths. <ide> server = _run_std_server( <ide> cluster_spec=cluster_spec, <ide> task_type=task_type, <ide><path>keras/distribute/distribute_strategy_test.py <ide> def test_calculating_input_params_no_steps_no_batch_size( <ide> replica_scale_factor = distribution.num_replicas_in_sync <ide> <ide> with self.cached_session(): <del> # Default global batch size 32 for input with 64 samples run in 2 steps <add> # Default global batch size 32 for input with 64 samples run in 2 <add> # steps <ide> steps, batch_size = distributed_training_utils_v1.get_input_params( <ide> distribution, 64, steps=None, batch_size=None <ide> ) <ide> self.assertEqual(batch_size, 32 // replica_scale_factor) <ide> self.assertEqual(steps, 2) <ide> <del> # Computed global batch size 20 is lower than 32 if we pass less samples. <add> # Computed global batch size 20 is lower than 32 if we pass less <add> # samples. <ide> steps, batch_size = distributed_training_utils_v1.get_input_params( <ide> distribution, 20, steps=None, batch_size=None <ide> ) <ide> def test_calculating_input_params_with_steps_no_batch_size( <ide> replica_scale_factor = distribution.num_replicas_in_sync <ide> <ide> with self.cached_session(): <del> # Computed global batch size is correct for number of specified 1 step <add> # Computed global batch size is correct for number of specified 1 <add> # step <ide> steps, batch_size = distributed_training_utils_v1.get_input_params( <ide> distribution, 64, steps=1, batch_size=None <ide> ) <ide> self.assertEqual(batch_size, 64 // replica_scale_factor) <ide> self.assertEqual(steps, 1) <ide> <del> # Computed global batch size is correct for number of specified 2 steps <add> # Computed global batch size is correct for number of specified 2 <add> # steps <ide> steps, batch_size = distributed_training_utils_v1.get_input_params( <ide> distribution, 64, steps=2, batch_size=None <ide> ) <ide> def test_calling_model_with_numpy_arrays(self, distribution): <ide> validation_data=(inputs, targets), <ide> ) <ide> <del> # TODO(anjalisridhar): We need tests for when the batch size and steps <del> # are smaller and results in a 0 batch_size and steps value. <add> # TODO(anjalisridhar): We need tests for when the batch size and <add> # steps are smaller and results in a 0 batch_size and steps <add> # value. <ide> model.evaluate(inputs, targets) <ide> model.evaluate(inputs, targets, batch_size=8) <ide> <ide> def test_calling_model_with_mixed_precision(self, distribution): <ide> metrics = ["mae"] <ide> model.compile(optimizer, loss, metrics=metrics) <ide> <del> # We need to pass float32 since TPUs do not support float64, even though <del> # these arrays will immediately be casted to bfloat16 on TPUs. We also <del> # cannot pass bfloat16, as Numpy does not support it. <add> # We need to pass float32 since TPUs do not support float64, even <add> # though these arrays will immediately be casted to bfloat16 on <add> # TPUs. We also cannot pass bfloat16, as Numpy does not support it. <ide> inputs = np.zeros((64, 3), dtype="float32") <ide> targets = np.zeros((64, 4), dtype="float32") <ide> <ide> def test_calling_model_with_mixed_precision(self, distribution): <ide> ) <ide> def test_operator_overload_mixed_precision(self, distribution): <ide> # Regression test that tests a fixed bug does not reoccur. Adding an <del> # AutoCastVariable to a tensor on a TPU, where the variable was the LHS of <del> # the '+' operator, used to cause the gradient w.r.t. the variable to be <del> # None. <add> # AutoCastVariable to a tensor on a TPU, where the variable was the LHS <add> # of the '+' operator, used to cause the gradient w.r.t. the variable to <add> # be None. <ide> if isinstance( <ide> distribution, <ide> ( <ide> def test_calling_model_with_nested_numpy_arrays(self, distribution): <ide> # Call fit with validation data <ide> model.fit(inputs, targets, epochs=1, batch_size=8, verbose=0) <ide> <del> # TODO(anjalisridhar): We need tests for when the batch size and steps are <del> # smaller and results in a 0 batch_size and steps value. <add> # TODO(anjalisridhar): We need tests for when the batch size and <add> # steps are smaller and results in a 0 batch_size and steps value. <ide> model.evaluate(inputs, targets) <ide> model.evaluate(inputs, targets, batch_size=8) <ide> <ide> def test_numpy_with_sample_weights(self, distribution): <ide> verbose=1, <ide> ) <ide> <del> # The per sample loss is multiplied by the corresponding sample weight. <del> # The average of these weighted losses is the return value of the <del> # `evaluate` call. For example, in the test above the average weighted <del> # loss is calculated in the following manner: <add> # The per sample loss is multiplied by the corresponding sample <add> # weight. The average of these weighted losses is the return value <add> # of the `evaluate` call. For example, in the test above the average <add> # weighted loss is calculated in the following manner: <ide> <del> # batch_1 = (((2-0)^2) * 0.25 + ((4-1)^2) * 0.5) / 2 = 5.5 / 2 = 2.75 <add> # batch_1 = (((2-0)^2) * 0.25 + ((4-1)^2) * 0.5) / 2 = 5.5 / 2 = <add> # 2.75 <ide> # batch_2 = (((6-2)^2 * 0.75) + ((8-3)^2 * 1)) / 2 = 37 / 2 = 18.5 <ide> # final result = (batch_1 + batch_2) / 2 = 10.625. <del> # The first time we divide by number of input samples and the second time <del> # we divide by number of steps/batches that the loss is aggregated over. <add> # The first time we divide by number of input samples and the second <add> # time we divide by number of steps/batches that the loss is <add> # aggregated over. <ide> self.assertAllClose(result, 10.625) <ide> <ide> # We now test without passing sample_weights: <ide> def test_flatten_predict_outputs(self, distribution): <ide> loss = "mse" <ide> model.compile(optimizer, loss) <ide> <del> # We take 6 input samples with each input having a dimension of 3 or 5. <add> # We take 6 input samples with each input having a dimension of 3 or <add> # 5. <ide> input_a_np = np.asarray(np.random.random((6, 3)), dtype=np.float32) <ide> input_b_np = np.asarray(np.random.random((6, 5)), dtype=np.float32) <ide> inputs = [input_a_np, input_b_np] <ide> <ide> outs = model.predict(inputs) <del> # `predict` a list that is equal in length to the number of model outputs. <del> # In this test our model has two outputs and each element of `outs` <del> # corresponds to all the samples of one of the model outputs. <add> # `predict` a list that is equal in length to the number of model <add> # outputs. In this test our model has two outputs and each element <add> # of `outs` corresponds to all the samples of one of the model <add> # outputs. <ide> self.assertLen(outs, 2) <del> # Each of the output samples have a dimension of 7. We should process all <del> # the available input samples(6). <add> # Each of the output samples have a dimension of 7. We should <add> # process all the available input samples(6). <ide> self.assertAllEqual([6, 7], outs[0].shape) <ide> self.assertAllEqual([6, 7], outs[1].shape) <ide> <ide> def test_evaluate_with_partial_batch(self, distribution, batch_size): <ide> x = np.random.random((10, 3)).astype("float32") <ide> y = np.random.random((10, 4)).astype("float32") <ide> <del> # As sample size is 10, we batch by 4 so that the last batch is <del> # a partial batch. Also `evaluate()` using numpy array as inputs without <del> # distribution strategy uses entire sample as a single batch. As so, <del> # we remove parameters `batch_size` and `steps`. <add> # As sample size is 10, we batch by 4 so that the last batch is a <add> # partial batch. Also `evaluate()` using numpy array as inputs <add> # without distribution strategy uses entire sample as a single <add> # batch. As so, we remove parameters `batch_size` and `steps`. <ide> cpu_model.set_weights(model_with_ds_strategy.get_weights()) <ide> evaluate_ground_truth = cpu_model.evaluate(x, y) <ide> <del> # We don't compare the loss as loss is currently not computed as metric <del> # in Keras, the loss value is inaccurate for last partial batch due to <del> # more weights for the last batch samples. <add> # We don't compare the loss as loss is currently not computed as <add> # metric in Keras, the loss value is inaccurate for last partial <add> # batch due to more weights for the last batch samples. <ide> steps = np.ceil(10.0 / batch_size) <ide> self.assertAllClose( <ide> model_with_ds_strategy.evaluate( <ide> def test_evaluate_with_partial_batch(self, distribution, batch_size): <ide> atol=1e-5, <ide> rtol=1e-5, <ide> ) <del> # Test that `steps` is inferred correctly when final partial batch exists. <add> # Test that `steps` is inferred correctly when final partial batch <add> # exists. <ide> self.assertAllClose( <ide> model_with_ds_strategy.evaluate(x, y, batch_size=batch_size)[ <ide> 1: <ide> def test_predict_with_partial_batch(self, distribution): <ide> inputs = np.random.random((10, 3)).astype(np.float32) <ide> <ide> # As sample size is 10, we batch by 4 so that the last batch is <del> # a partial batch. Also `predict()` using numpy array as inputs without <del> # distribution strategy uses entire sample as a single batch. As so, <del> # we remove parameters `batch_size` and `steps`. <add> # a partial batch. Also `predict()` using numpy array as inputs <add> # without distribution strategy uses entire sample as a single <add> # batch. As so, we remove parameters `batch_size` and `steps`. <ide> cpu_model.set_weights(model_with_ds_strategy.get_weights()) <ide> predict_ground_truth = cpu_model.predict(inputs) <ide> self.assertAllClose( <ide> def test_predict_with_partial_batch(self, distribution): <ide> atol=1e-5, <ide> rtol=1e-5, <ide> ) <del> # Test that `steps` is inferred correctly when final partial batch exists. <add> # Test that `steps` is inferred correctly when final partial batch <add> # exists. <ide> self.assertAllClose( <ide> model_with_ds_strategy.predict(inputs, batch_size=4), <ide> predict_ground_truth, <ide> def test_predict_on_dataset_with_unknown_cardinality_without_steps( <ide> def test_on_dataset_with_unknown_cardinality_without_steps( <ide> self, distribution, mode <ide> ): <del> # TODO(b/155867206): Investigate why this test occasionally segfaults on TPU <del> # in eager mode. <add> # TODO(b/155867206): Investigate why this test occasionally segfaults on <add> # TPU in eager mode. <ide> if mode == "eager" and backend.is_tpu_strategy(distribution): <ide> self.skipTest("caused segfault with TPU in eager mode.") <ide> <ide> def test_dataset_external_batch_input_validation(self, distribution): <ide> ) <ide> ) <ide> def test_learning_phase_value(self, distribution): <del> # TODO(anjalisridhar): Modify this test to use Lambdas since we can compare <del> # meaningful values. Currently we don't pass the learning phase if the <del> # Lambda layer uses the learning phase. <add> # TODO(anjalisridhar): Modify this test to use Lambdas since we can <add> # compare meaningful values. Currently we don't pass the learning phase <add> # if the Lambda layer uses the learning phase. <ide> with self.cached_session(): <ide> with distribution.scope(): <ide> x = keras.layers.Input(shape=(1,), name="input") <ide> def test_learning_phase_value(self, distribution): <ide> <ide> with distribution.scope(): <ide> model.set_weights(initial_weights) <del> # TODO(psv/anjalisridhar): Enable these lines after we fix b/117431185. <del> # evaluate_output = model.evaluate(dataset, steps=20) <add> # TODO(psv/anjalisridhar): Enable these lines after we fix <add> # b/117431185. evaluate_output = model.evaluate(dataset, steps=20) <ide> # self.assertAlmostEqual(evaluate_output[1], 1, 0) <ide> <ide> inputs = np.ones((10, 1), dtype=np.float32) <ide> def test_evaluate_with_dataset_with_partial_batch( <ide> cpu_model.set_weights(model_with_ds_strategy.get_weights()) <ide> dataset_with_partial_batch = dataset.batch(batch_size) <ide> <del> # We don't compare the loss as loss is currently not computed as metric <del> # in Keras, the loss value is inaccurate for last partial batch due to <del> # more weights for the last batch samples. <add> # We don't compare the loss as loss is currently not computed as <add> # metric in Keras, the loss value is inaccurate for last partial <add> # batch due to more weights for the last batch samples. <ide> steps = np.ceil(10.0 / batch_size) <ide> self.assertAllClose( <ide> model_with_ds_strategy.evaluate( <ide> def _create_model_input_output_tensors(): <ide> with self.cached_session(): <ide> with distribution.scope(): <ide> input_a, input_b, output = _create_model_input_output_tensors() <del> # `input_a`, which has input name that comes last in alphanumeric <del> # order, is the first input of the model input layers. If tensors <del> # from `input_dict` is blindly flattened and passed to model <del> # inputs incorrectly, this would result in `input_a` input layer <del> # matching with tensor `a_input_sorted_first` and would result in <del> # shape mismatch. <add> # `input_a`, which has input name that comes last in <add> # alphanumeric order, is the first input of the model input <add> # layers. If tensors from `input_dict` is blindly flattened and <add> # passed to model inputs incorrectly, this would result in <add> # `input_a` input layer matching with tensor <add> # `a_input_sorted_first` and would result in shape mismatch. <ide> model_with_array_input = keras.models.Model( <ide> inputs=[input_a, input_b], outputs=output <ide> ) <ide> def test_dataset_with_sample_weights(self, distribution): <ide> ).batch(2) <ide> result = model.evaluate(ds, verbose=1) <ide> <del> # The per sample loss is multiplied by the corresponding sample weight. <del> # The average of these weighted losses is the return value of the <del> # `evaluate` call. For example, in the test above the average weighted <del> # loss is calculated in the following manner: <del> # batch_1 = (((2-0)^2) * 0.25 + ((4-1)^2) * 0.5) / 2 = 5.5 / 2 = 2.75 <add> # The per sample loss is multiplied by the corresponding sample <add> # weight. The average of these weighted losses is the return value <add> # of the `evaluate` call. For example, in the test above the average <add> # weighted loss is calculated in the following manner: <add> # batch_1 = (((2-0)^2) * 0.25 + ((4-1)^2) * 0.5) / 2 = 5.5 / 2 = <add> # 2.75 <ide> # batch_2 = (((6-2)^2 * 0.75) + ((8-3)^2 * 1)) / 2 = 37 / 2 = 18.5 <ide> # final result = (batch_1 + batch_2) / 2 = 10.625. <del> # The first time we divide by number of input samples and the second time <del> # we divide by number of steps/batches that the loss is aggregated over. <add> # The first time we divide by number of input samples and the second <add> # time we divide by number of steps/batches that the loss is <add> # aggregated over. <ide> self.assertAllClose(result, 10.625) <ide> <ide> # We now test without passing sample_weights: <ide> def setUp(self): <ide> def test_predict_on_dataset_shard_options_file_multi_worker_mirrored( <ide> self, distribution, mode <ide> ): <del> # This test is to verify if we successfully switch auto_shard_policy of a <del> # input dataset inside model.predict with MultiWorkerMirroredStrategy to <del> # AutoShardPolicy.DATA. Since there is only one input file for multiple <del> # workers, AutoShardPolicy.AUTO or AutoShardPolicy.FILE will lead to an <del> # error. However, since we switch to AutoShardPolicy.DATA in model.predict, <del> # no error is raised. <add> # This test is to verify if we successfully switch auto_shard_policy of <add> # a input dataset inside model.predict with MultiWorkerMirroredStrategy <add> # to AutoShardPolicy.DATA. Since there is only one input file for <add> # multiple workers, AutoShardPolicy.AUTO or AutoShardPolicy.FILE will <add> # lead to an error. However, since we switch to AutoShardPolicy.DATA in <add> # model.predict, no error is raised. <ide> del mode <ide> with distribution.scope(): <ide> optimizer_fn = gradient_descent_keras.SGD <ide> def test_regularizer_loss(self, distribution): <ide> ): <ide> batch_size //= distribution.num_replicas_in_sync <ide> <del> # Given an input x, which is always 1, and variable v, this model computes <del> # Loss=x+v+regularizer_loss, where regularizer_loss=v and the variable is <del> # initialized to 1. Therefore, this model computes Loss=1+2v, and so the <del> # gradient dLoss/dv = 2. This gradient of 2 is averaged over all examples <del> # in a batch and then multiplied by the learning rate of 1. As a result, <del> # the model update for one batch should subtract 2 from v, resulting in v <del> # being -1. If the regularizer loss is not scaled correctly by number of <del> # replicas, the variable value will be incorrect when number of replicas <del> # >1. For e.g. it will be -2 if num replicas = 2. <add> # Given an input x, which is always 1, and variable v, this model <add> # computes Loss=x+v+regularizer_loss, where regularizer_loss=v and <add> # the variable is initialized to 1. Therefore, this model computes <add> # Loss=1+2v, and so the gradient dLoss/dv = 2. This gradient of 2 is <add> # averaged over all examples in a batch and then multiplied by the <add> # learning rate of 1. As a result, the model update for one batch <add> # should subtract 2 from v, resulting in v being -1. If the <add> # regularizer loss is not scaled correctly by number of replicas, <add> # the variable value will be incorrect when number of replicas >1. <add> # For e.g. it will be -2 if num replicas = 2. <ide> with distribution.scope(): <ide> x = keras.layers.Input(shape=(1,), batch_size=batch_size) <ide> y = TestRegularizerLoss.AddLayer()(x) <ide> def step_fn(inputs): <ide> loss, global_batch_size=batch_size <ide> ) <ide> <del> # Verify that the loss computed in this loop is equivalent to the <del> # loss from the model that was added via add_loss. <add> # Verify that the loss computed in this loop is <add> # equivalent to the loss from the model that was added <add> # via add_loss. <ide> tf.compat.v1.assert_equal(loss, loss_from_model) <ide> <ide> grads = tape.gradient(loss, model.trainable_variables) <ide> def _functional_with_add_loss_and_metric(input_shape, num_classes, l1, l2): <ide> x = keras.layers.MaxPooling2D(pool_size=2)(x) <ide> x = keras.layers.Conv2D(64, kernel_size=5, activation="relu")(x) <ide> x = keras.layers.MaxPooling2D(pool_size=2)(x) <del> # Apply L2 regularization to embedding. Use a mix of TensorFlow ops and layers <del> # to exercise all code paths. <add> # Apply L2 regularization to embedding. Use a mix of TensorFlow ops and <add> # layers to exercise all code paths. <ide> x = keras.layers.Flatten(name="embedding")(x) <ide> l2_loss = tf.reduce_mean(tf.reduce_sum(tf.square(x), -1)) <ide> # Apply L1 regularization to next layer. <ide> def test_fit_and_evaluate(self, distribution, model_fn, l1, l2): <ide> dataset = dataset.shuffle(64).batch( <ide> 8 * distribution.num_replicas_in_sync, drop_remainder=True <ide> ) <del> # Make model with distribution strategy and initialize with dataset shape. <add> # Make model with distribution strategy and initialize with dataset <add> # shape. <ide> input_shape = tf.data.experimental.get_structure(dataset)[0].shape[1:] <ide> with distribution.scope(): <ide> model = model_fn(input_shape, 10, l1, l2) <ide> def test_fit_and_evaluate(self, distribution): <ide> model = DeterministicModel(distribution) <ide> optimizer = keras.optimizers.adam_v2.Adam(1e-4) <ide> <del> # Compile & evaluate the model outside of the distribution strategy scope <add> # Compile & evaluate the model outside of the distribution strategy <add> # scope <ide> model.compile( <ide> optimizer=optimizer, <ide> loss=keras.losses.MeanSquaredError(), <ide><path>keras/distribute/distributed_file_utils.py <ide> def write_dirpath(dirpath, strategy): <ide> # Infer strategy from `distribution_strategy_context` if not given. <ide> strategy = tf.distribute.get_strategy() <ide> if strategy is None: <del> # If strategy is still not available, this is not in distributed training. <del> # Fallback to original dirpath. <add> # If strategy is still not available, this is not in distributed <add> # training. Fallback to original dirpath. <ide> return dirpath <ide> if ( <ide> not strategy.extended._in_multi_worker_mode() <ide> def remove_temp_dirpath(dirpath, strategy): <ide> # Infer strategy from `distribution_strategy_context` if not given. <ide> strategy = tf.distribute.get_strategy() <ide> if strategy is None: <del> # If strategy is still not available, this is not in distributed training. <del> # Fallback to no-op. <add> # If strategy is still not available, this is not in distributed <add> # training. Fallback to no-op. <ide> return <del> # TODO(anjalisridhar): Consider removing the check for multi worker mode since <del> # it is redundant when used with the should_checkpoint property. <add> # TODO(anjalisridhar): Consider removing the check for multi worker mode <add> # since it is redundant when used with the should_checkpoint property. <ide> if ( <ide> strategy.extended._in_multi_worker_mode() <del> and not strategy.extended.should_checkpoint # pylint: disable=protected-access <add> and not strategy.extended.should_checkpoint <ide> ): <ide> # If this worker is not chief and hence should not save file, remove <ide> # the temporary directory. <ide><path>keras/distribute/distributed_training_utils_v1.py <ide> def unwrap_values( <ide> <ide> This function calls `flatten_per_replica_values` to parse each of the input <ide> parameters into a list of values on the different devices. If we set <del> `with_loss_tensor` to be True, we also call `reduce` on the list of losses on <del> the different devices to give us one loss tensor. <add> `with_loss_tensor` to be True, we also call `reduce` on the list of losses <add> on the different devices to give us one loss tensor. <ide> <ide> Args: <del> distribution_strategy: DistributionStrategy used to distribute training and <del> validation. <add> distribution_strategy: DistributionStrategy used to distribute training <add> and validation. <ide> grouped_inputs: PerReplica inputs returned from the train or test function <ide> that we ran on each device. <del> grouped_outputs: PerReplica outputs returned from the train or test function <del> that we ran on each device. <del> grouped_updates: PerReplica updates returned from the train or test function <del> that we ran on each device. <add> grouped_outputs: PerReplica outputs returned from the train or test <add> function that we ran on each device. <add> grouped_updates: PerReplica updates returned from the train or test <add> function that we ran on each device. <ide> grouped_session_args: PerReplica session args returned from the train or <ide> test function that we ran on each device. <del> with_loss_tensor: Boolean that indicates if we need to add the reduced loss <del> tensor as one of the outputs. <add> with_loss_tensor: Boolean that indicates if we need to add the reduced <add> loss tensor as one of the outputs. <ide> <ide> Returns: <ide> Values of each of the PerReplica parameters. <ide> def unwrap_output_dict(strategy, grouped_outputs, mode): <ide> if mode == ModeKeys.PREDICT: <ide> return flatten_per_replica_values(strategy, grouped_outputs) <ide> <del> # In the case of fit/eval, the grouped_outputs is a dict, whereas in predict, <del> # the output is as same structure as model output. They need to be treated <del> # differently <add> # In the case of fit/eval, the grouped_outputs is a dict, whereas in <add> # predict, the output is as same structure as model output. They need to be <add> # treated differently <ide> total_loss = strategy.reduce( <ide> tf.distribute.ReduceOp.SUM, grouped_outputs["total_loss"][0], axis=None <ide> ) <ide> def unwrap_output_dict(strategy, grouped_outputs, mode): <ide> backend.is_tpu_strategy(strategy) <ide> and tf.compat.v1.executing_eagerly_outside_functions() <ide> ): <del> # Choose 1 value per replica in the TPU case since all replicas produce the <del> # same output. <add> # Choose 1 value per replica in the TPU case since all replicas produce <add> # the same output. <ide> # We only do this in eager mode for now since this function is used in <ide> # both graph and eager mode and in the graph case we currently don't use <del> # experimental_run so would need to be removed when we converge the graph <del> # code path as well. <add> # experimental_run so would need to be removed when we converge the <add> # graph code path as well. <ide> output_losses = output_losses[:: strategy.num_replicas_in_sync] <ide> metrics = metrics[:: strategy.num_replicas_in_sync] <ide> return { <ide> def unwrap_outputs( <ide> <ide> This function calls `flatten_per_replica_values` to parse each of the input <ide> parameters into a list of outputs on the different devices. If we set <del> `with_loss_tensor` to be True, we also call `reduce` on the list of losses on <del> the different devices to give us one loss tensor. <add> `with_loss_tensor` to be True, we also call `reduce` on the list of losses <add> on the different devices to give us one loss tensor. <ide> <ide> Args: <del> distribution_strategy: DistributionStrategy used to distribute training and <del> validation. <del> grouped_outputs: PerReplica outputs returned from the train or test function <del> that we ran on each device. <del> with_loss_tensor: Boolean that indicates if we need to add the reduced loss <del> tensor as one of the outputs. <add> distribution_strategy: DistributionStrategy used to distribute training <add> and validation. <add> grouped_outputs: PerReplica outputs returned from the train or test <add> function that we ran on each device. <add> with_loss_tensor: Boolean that indicates if we need to add the reduced <add> loss tensor as one of the outputs. <ide> <ide> Returns: <ide> Values of each of the PerReplica outputs. <ide> def unwrap_outputs( <ide> backend.is_tpu_strategy(distribution_strategy) <ide> and tf.compat.v1.executing_eagerly_outside_functions() <ide> ): <del> # Choose 1 value per replica in the TPU case since all replicas produce the <del> # same output. <add> # Choose 1 value per replica in the TPU case since all replicas produce <add> # the same output. <ide> # We only do this in eager mode for now since this function is used in <ide> # both graph and eager mode and in the graph case we currently don't use <del> # experimental_run so would need to be removed when we converge the graph <del> # code path as well. <add> # experimental_run so would need to be removed when we converge the <add> # graph code path as well. <ide> all_outputs = all_outputs[:: distribution_strategy.num_replicas_in_sync] <ide> return [loss] + all_outputs <ide> <ide> def flatten_per_replica_values(distribution_strategy, per_replica_values): <ide> of PerReplica values and return all the values in the PerReplica dict. <ide> <ide> Args: <del> distribution_strategy: DistributionStrategy used to distribute training and <del> validation. <del> per_replica_values: List of PerReplica object or a single PerReplica object. <add> distribution_strategy: DistributionStrategy used to distribute training <add> and validation. <add> per_replica_values: List of PerReplica object or a single PerReplica <add> object. <ide> <ide> Returns: <ide> List of values of all the PerReplica objects. <ide> <ide> """ <ide> # pylint: disable=g-complex-comprehension <del> # This function takes a PerReplica object or a list of PerReplica objects and <del> # returns all the values associated with it. <add> # This function takes a PerReplica object or a list of PerReplica objects <add> # and returns all the values associated with it. <ide> return [ <ide> e <ide> for flattened in tf.nest.flatten(per_replica_values) <ide> def validate_callbacks(input_callbacks, optimizer): <ide> optimizer: Optimizer instance used to train the model. <ide> <ide> Raises: <del> ValueError: If `LearningRateScheduler` or `ReduceLROnPlateau` is one of the <del> callbacks passed. <del> ValueError: If `write_grads` is one of the parameters passed as part of the <del> TensorBoard callback. <add> ValueError: If `LearningRateScheduler` or `ReduceLROnPlateau` is one of <add> the callbacks passed. <add> ValueError: If `write_grads` is one of the parameters passed as part of <add> the TensorBoard callback. <ide> """ <ide> if input_callbacks: <ide> for callback in input_callbacks: <ide> def validate_callbacks(input_callbacks, optimizer): <ide> "%s callback with DistributionStrategy." % callback <ide> ) <ide> <del> # If users want to use the TensorBoard callback they cannot use certain <del> # features of the callback that involve accessing model attributes and <del> # running ops. <add> # If users want to use the TensorBoard callback they cannot use <add> # certain features of the callback that involve accessing model <add> # attributes and running ops. <ide> if isinstance(callback, callbacks.TensorBoard): <ide> if getattr(callback, "write_grads", False): <ide> logging.warning( <ide> UserWarning( <del> "`write_grads` in the TensorBoard callback is not supported " <del> "when using DistributionStrategy. Setting `write_grads` " <del> "to `False`." <add> "`write_grads` in the TensorBoard callback is not " <add> "supported when using DistributionStrategy. " <add> "Setting `write_grads` to `False`." <ide> ) <ide> ) <ide> callback.write_grads = False <ide> def validate_distributed_dataset_inputs( <ide> `MirroredStrategy` this is a PerReplica object with a tensor for each <ide> device set in the dict. y can also be a tuple or dict. The keys of the <ide> dict should match the names of the output layers of the model. <del> sample_weights: Sample weights Dataset DistributedValue object. For example, <del> when we use `MirroredStrategy` this is a PerReplica object with a tensor <del> for each device set in the dict. <add> sample_weights: Sample weights Dataset DistributedValue object. For <add> example, when we use `MirroredStrategy` this is a PerReplica object <add> with a tensor for each device set in the dict. <ide> <ide> Returns: <ide> The unwrapped values list of the x and y DistributedValues inputs. <ide> def validate_per_replica_inputs(distribution_strategy, x): <ide> the input list. <ide> <ide> Raises: <del> ValueError: If any of the objects in the `per_replica_list` is not a tensor. <add> ValueError: If any of the objects in the `per_replica_list` is not a <add> tensor. <ide> <ide> """ <ide> # Convert the inputs and targets into a list of PerReplica objects. <ide> def validate_per_replica_inputs(distribution_strategy, x): <ide> ) <ide> <ide> if not tf.executing_eagerly(): <del> # Validate that the shape and dtype of all the elements in x are the same. <add> # Validate that the shape and dtype of all the elements in x are the <add> # same. <ide> validate_all_tensor_shapes(x, x_values) <ide> validate_all_tensor_types(x, x_values) <ide> <ide> def _wait_for_variable_initialization(session): <ide> <ide> <ide> def init_restore_or_wait_for_variables(): <del> """Initialize or restore variables or wait for variables to be initialized.""" <add> """Initialize or restore variables or wait for variables to be <add> initialized.""" <ide> backend._initialize_variables( <ide> backend._get_session() <ide> ) # pylint: disable=protected-access <ide> def get_input_params( <ide> distribution_strategy <ide> ) <ide> <del> # TODO(b/128995245): In eager mode, uneven batch sizes are allowed except for <del> # `fit()` on TPUStrategy. <add> # TODO(b/128995245): In eager mode, uneven batch sizes are allowed except <add> # for `fit()` on TPUStrategy. <ide> # In graph mode, the zero batch case in batch norm is not handled due to <ide> # XLA-GPU regression. Uneven batch sizes are not allowed except <ide> # for `test()` and `predict()` on TPUStrategy. <ide> def get_input_params( <ide> <ide> if steps is None: <ide> if batch_size is None: <del> # If neither the batch size or number of steps are set. We choose the <del> # global batch size as the minimum of number of samples and 32. 32 is <del> # chosen to provide backward compatibility. <add> # If neither the batch size or number of steps are set. We choose <add> # the global batch size as the minimum of number of samples and 32. <add> # 32 is chosen to provide backward compatibility. <ide> global_batch_size = min(num_samples, 32) <ide> else: <ide> # If the user provided the batch size we need to handle the case <del> # between different strategies that use the global/per-replica batch size <add> # between different strategies that use the global/per-replica batch <add> # size <ide> global_batch_size = batch_size <ide> if use_per_replica_batch: <ide> global_batch_size *= distribution_strategy.num_replicas_in_sync <ide> def get_input_params( <ide> global_batch_size = num_samples // steps <ide> else: <ide> # If the user provided the batch size we need to handle the case <del> # between different strategies that use the global/per-replica batch size <add> # between different strategies that use the global/per-replica batch <add> # size <ide> global_batch_size = batch_size <ide> if use_per_replica_batch: <ide> global_batch_size *= distribution_strategy.num_replicas_in_sync <ide> def get_input_params( <ide> % (num_samples, global_batch_size, steps) <ide> ) <ide> <del> # We need to return the per replica or global batch size based on the strategy <add> # We need to return the per replica or global batch size based on the <add> # strategy <ide> if use_per_replica_batch: <ide> if global_batch_size % distribution_strategy.num_replicas_in_sync: <ide> raise ValueError( <del> "The batch size (%s) could not be sharded evenly across the sync " <del> "replicas (%s) in the distribution strategy." <add> "The batch size (%s) could not be sharded evenly across the " <add> "sync replicas (%s) in the distribution strategy." <ide> % ( <ide> global_batch_size, <ide> distribution_strategy.num_replicas_in_sync, <ide> def _get_input_from_iterator(iterator, model): <ide> next_element = iterator.get_next() <ide> <ide> # `len(nest.flatten(x))` is going to not count empty elements such as {}. <del> # len(nest.flatten([[0,1,2], {}])) is 3 and not 4. The `next_element` is <del> # going to get flattened in `_prepare_feed_values` to work around that. Empty <del> # elements are going to get filtered out as part of the flattening. <add> # len(nest.flatten([[0,1,2], {}])) is 3 and not 4. The `next_element` is <add> # going to get flattened in `_prepare_feed_values` to work around that. <add> # Empty elements are going to get filtered out as part of the flattening. <ide> if len(tf.nest.flatten(next_element)) == len(model.inputs): <ide> x = next_element <ide> y = None <ide> def _prepare_feed_values(model, inputs, targets, sample_weights, mode): <ide> inputs = flatten_per_replica_values(strategy, inputs) <ide> targets = flatten_per_replica_values(strategy, targets) <ide> # Expand 1-dimensional inputs. <del> # TODO(b/124535720): Remove once this standarize data logic is shared with <del> # main flow. <add> # TODO(b/124535720): Remove once this standarize data logic is shared <add> # with main flow. <ide> inputs, targets = tf.nest.map_structure( <ide> training_utils_v1.standardize_single_array, (inputs, targets) <ide> ) <ide> def _custom_compile_for_predict(model): <ide> """Custom compile for TPU predict mode.""" <ide> if not model.built: <ide> # Model is not compilable because it does not know its number of inputs <del> # and outputs, nor their shapes and names. We will compile after the first <del> # time the model gets called on training data. <add> # and outputs, nor their shapes and names. We will compile after the <add> # first time the model gets called on training data. <ide> return <ide> model._is_compiled = True <ide> model.total_loss = None <ide> def _build_network_on_replica(model, mode, inputs=None, targets=None): <ide> placeholders for the input and the output that are not accessible till we <ide> call iterator.get_next() inside the step_fn for `fit`/`evaluate`/`predict`. <ide> <del> The sharing of weights and layers between the old and the new model guarantee <del> that we're using Strategy variables and any updates on either model are <del> reflected correctly in callbacks and loop iterations. <add> The sharing of weights and layers between the old and the new model <add> guarantee that we're using Strategy variables and any updates on either <add> model are reflected correctly in callbacks and loop iterations. <ide> <del> We need to make sure we share the optimizers between the old and the new model <del> as well so that optimizer state is not lost if the user is running fit <add> We need to make sure we share the optimizers between the old and the new <add> model as well so that optimizer state is not lost if the user is running fit <ide> multiple times. <ide> <ide> Args: <ide> def _build_network_on_replica(model, mode, inputs=None, targets=None): <ide> from keras import models # pylint: disable=g-import-not-at-top <ide> from keras.engine import sequential # pylint: disable=g-import-not-at-top <ide> <del> # We rely on the internal methods to avoid having share_weights weights in the <del> # public API. <add> # We rely on the internal methods to avoid having share_weights weights in <add> # the public API. <ide> if isinstance(model, sequential.Sequential): <ide> updated_model = models._clone_sequential_model( <ide> model, input_tensors=inputs, layer_fn=models.share_weights <ide> def _build_network_on_replica(model, mode, inputs=None, targets=None): <ide> # here. <ide> updated_model._callable_losses = model._callable_losses <ide> <del> # Recast all low precision outputs back to float32 since we only casted <del> # the inputs to bfloat16 and not targets. This is done so that we can preserve <add> # Recast all low precision outputs back to float32 since we only casted the <add> # inputs to bfloat16 and not targets. This is done so that we can preserve <ide> # precision when calculating the loss value. <ide> def _upcast_low_precision_outputs(output): <ide> if output.dtype == tf.bfloat16: <ide> def _clone_and_build_model(model, mode, inputs=None, targets=None): <ide> optimizer = model.optimizer.__class__.from_config(optimizer_config) <ide> <ide> # Recast all low precision outputs back to float32 since we only casted <del> # the inputs to bfloat16 and not targets. This is done so that we can preserve <del> # precision when calculating the loss value. <add> # the inputs to bfloat16 and not targets. This is done so that we can <add> # preserve precision when calculating the loss value. <ide> def _upcast_low_precision_outputs(output): <ide> if output.dtype == tf.bfloat16: <ide> return tf.cast(output, tf.float32) <ide> def clone_model_on_replicas(model, strategy, mode, inputs=None, targets=None): <ide> <ide> <ide> def _make_execution_function(model, mode): <del> """Makes or reuses function to run one step of distributed model execution.""" <add> """Makes or reuses function to run one step of distributed model <add> execution.""" <ide> if is_distributing_by_cloning(model): <ide> return _make_execution_function_with_cloning(model, mode) <ide> <ide> def _make_execution_function_without_cloning(model, mode): <ide> def distributed_function(input_fn): <ide> """A single step of the distributed execution across replicas.""" <ide> x, y, sample_weights = input_fn() <del> # Call `Model.{train,test,predict}_on_batch` on every replica passing <del> # PerReplicas as arguments. On every replica inside this call, each <del> # PerReplica object will return the value for that replica. The outputs <del> # are PerReplicas too. <add> # Call `Model.{train,test,predict}_on_batch` on every replica <add> # passing PerReplicas as arguments. On every replica inside this <add> # call, each PerReplica object will return the value for that <add> # replica. The outputs are PerReplicas too. <ide> outputs = strategy.run( <ide> per_replica_function, args=(x, y, sample_weights) <ide> ) <ide> def _make_replicated_models_with_cloning(model, mode): <ide> <ide> <ide> def _make_execution_function_with_cloning(model, mode): <del> """Clones or re-uses models to run one step of distributed model execution.""" <add> """Clones or re-uses models to run one step of distributed model <add> execution.""" <ide> distributed_model = get_distributed_model(model, mode) <ide> # TODO(b/134069401): Create a cache for the distributed model and exec <del> # function that incorporates additional attributes to be part of the cache key <del> # than just the mode. <add> # function that incorporates additional attributes to be part of the cache <add> # key than just the mode. <ide> # If distributed model for a particular `mode` is already built, use the <ide> # `_distribution_function` on that distributed model. <del> # If you have updated the sample_weight_mode on the model, then you will need <del> # to recompile metrics and recreate the execution function. This is indicated <del> # by the `_recompile_exec_function` property. <add> # If you have updated the sample_weight_mode on the model, then you will <add> # need to recompile metrics and recreate the execution function. This is <add> # indicated by the `_recompile_exec_function` property. <ide> if ( <ide> distributed_model <ide> and hasattr(distributed_model, "_distribution_function") <ide> def _per_replica_function(model): <ide> _per_replica_function, args=(get_distributed_model(model, mode),) <ide> ) <ide> <del> # Initialize the variables in the replicated model. This is necessary for <del> # multi-worker training because on some workers, initialization is not <del> # needed. This method does initialization or waiting for initialization <del> # according to the context object of distribute coordinator. <add> # Initialize the variables in the replicated model. This is necessary <add> # for multi-worker training because on some workers, initialization is <add> # not needed. This method does initialization or waiting for <add> # initialization according to the context object of distribute <add> # coordinator. <ide> init_restore_or_wait_for_variables() <ide> <del> # Unwrap all the per device values returned from `call_for_each_replica`. <del> # Unwrapping per device values gives you a list of values that can be <del> # used to construct a new train function that is composed of update ops on <del> # all the devices over which the model is distributed. <add> # Unwrap all the per device values returned from <add> # `call_for_each_replica`. Unwrapping per device values gives you a <add> # list of values that can be used to construct a new train function that <add> # is composed of update ops on all the devices over which the model is <add> # distributed. <ide> ( <ide> all_inputs, <ide> all_outputs, <ide> def _per_replica_function(model): <ide> f = model._make_execution_function(mode) <ide> return (f.inputs, f.outputs) <ide> <del> # NOTE(priyag): Try creating a new FuncGraph within DS scope instead of using <del> # the global one. <add> # NOTE(priyag): Try creating a new FuncGraph within DS scope instead of <add> # using the global one. <ide> strategy = model._distribution_strategy <ide> global_graph = backend.get_graph() <ide> <ide> with global_graph.as_default(), strategy.scope(): <del> # First we gather the relevant portions of the model across all replicas. <del> # `backend._scratch_graph(global_graph)` signals to Keras that it should not <del> # lift to a separate graph when creating the per-replica functions. <add> # First we gather the relevant portions of the model across all <add> # replicas. `backend._scratch_graph(global_graph)` signals to Keras <add> # that it should not lift to a separate graph when creating the <add> # per-replica functions. <ide> with backend._scratch_graph(global_graph): <ide> # Create train ops on each of the devices when we call <ide> # `_per_replica_fit_function`. <ide> def _per_replica_function(model): <ide> ) <ide> grouped_inputs, grouped_outputs = grouped <ide> <del> # Unwrap all the per device values returned from `call_for_each_replica`. <del> # Unwrapping per device values gives you a list of values that can be <del> # used to construct a new train function that is composed of <del> # inputs/outputs on all the devices over which the model is distributed. <add> # Unwrap all the per device values returned from <add> # `call_for_each_replica`. Unwrapping per device values gives you a <add> # list of values that can be used to construct a new train function <add> # that is composed of inputs/outputs on all the devices over which <add> # the model is distributed. <ide> (all_inputs, all_outputs, _, _) = unwrap_values( <ide> strategy, <ide> grouped_inputs, <ide> grouped_outputs, <ide> with_loss_tensor=(mode != ModeKeys.PREDICT), <ide> ) <ide> <del> # Finally, a joint Keras function is created; this one will be created in <del> # a separate FuncGraph. <add> # Finally, a joint Keras function is created; this one will be created <add> # in a separate FuncGraph. <ide> return backend.function( <ide> all_inputs, <ide> all_outputs, <ide> def _copy_weights_to_original_model(model, mode): <ide> <ide> <ide> def _per_replica_aggregate_batch(strategy, batch_outs, model, mode): <del> """Aggregates the per-replica batch-level outputs from a distributed step.""" <add> """Aggregates the per-replica batch-level outputs from a distributed <add> step.""" <ide> if strategy is not None and mode == ModeKeys.PREDICT: <ide> total_batch_outs = [] <ide> for i in range(len(model.outputs)): <ide> def _update_sample_weight_modes(model, mode, sample_weights): <ide> distributed_models = flatten_per_replica_values( <ide> model._distribution_strategy, distributed_model <ide> ) <del> # sample_weights is a tuple of 1 list where the number of elements in the <del> # list is equal to the number of replicas in sync. <add> # sample_weights is a tuple of 1 list where the number of elements <add> # in the list is equal to the number of replicas in sync. <ide> sample_weights = sample_weights[0] <ide> if sample_weights and None not in sample_weights: <ide> for m, sw in zip(distributed_models, sample_weights): <ide><path>keras/distribute/keras_correctness_test_base.py <ide> def compare_results( <ide> # We relax the tolerance a lot in the partial last batch case as <ide> # 1. the examples in uneven batches may have different weights when <ide> # applying the gradients in the distributed case. <del> # 2. TF Keras and TF Keras DS have different ways to handle the case when <del> # training with epochs > 1 with numpy inputs. In TF Keras, every epoch <del> # may have a partial batch. While in TF Keras DS, as we convert <del> # numpy inputs into dataset, it will do a repeat() first and calculate <del> # steps_per_epoch, so it will at most have one partial batch. This <del> # makes the 1-CPU result even different. <add> # 2. TF Keras and TF Keras DS have different ways to handle the case <add> # when training with epochs > 1 with numpy inputs. In TF Keras, <add> # every epoch may have a partial batch. While in TF Keras DS, as we <add> # convert numpy inputs into dataset, it will do a repeat() first <add> # and calculate steps_per_epoch, so it will at most have one <add> # partial batch. This makes the 1-CPU result even different. <ide> default_tolerance = 1e-3 <ide> relaxed_tolerance = 1e-3 <ide> else: <ide> def get_data_with_partial_last_batch_eval(self): <ide> def get_input_for_correctness_test(self, **kwargs): <ide> """Generates inputs that are dictionaries. <ide> <del> We only provide a default implementation of this method here. If you need <del> more customized way of providing input to your model, overwrite this method. <add> We only provide a default implementation of this method here. If you <add> need more customized way of providing input to your model, overwrite <add> this method. <ide> <ide> Args: <del> **kwargs: key word arguments about how to create the input dictionaries <add> **kwargs: key word arguments about how to create the input <add> dictionaries <ide> <ide> Returns: <ide> Three dictionaries representing the input for fit(), evaluate() and <ide> def run_correctness_test( <ide> ) <ide> <ide> # First, special case, for multi-replica distributed training, batch <del> # norm is not aggregated globally. So it is expected to have different <del> # weights. <add> # norm is not aggregated globally. So it is expected to have <add> # different weights. <ide> if ( <ide> self.with_batch_norm == "regular" <ide> and distribution.num_replicas_in_sync > 1 <ide> def run_correctness_test( <ide> def get_input_for_dynamic_lr_test(self, **kwargs): <ide> """Generates inputs that are dictionaries. <ide> <del> We only provide a default implementation of this method here. If you need <del> more customized way of providing input to your model, overwrite this method. <add> We only provide a default implementation of this method here. If you <add> need more customized way of providing input to your model, overwrite <add> this method. <ide> <ide> Args: <del> **kwargs: key word arguments about how to create the input dictionaries <add> **kwargs: key word arguments about how to create the input <add> dictionaries <ide> <ide> Returns: <ide> Three dictionaries representing the input for fit(), evaluate() and <ide> def run_dynamic_lr_test(self, distribution): <ide> ) <ide> and distribution.extended.steps_per_run > 1 <ide> ): <del> # For TPUStrategy with steps_per_run > 1, the callback is not invoked <del> # every step. So, to compare the CPU/TPU, we let the CPU to behave the <del> # same as TPU. <add> # For TPUStrategy with steps_per_run > 1, the callback is not <add> # invoked every step. So, to compare the CPU/TPU, we let the CPU <add> # to behave the same as TPU. <ide> update_freq = distribution.extended.steps_per_run <ide> <ide> training_epochs = 2 <ide><path>keras/distribute/keras_dnn_correctness_test.py <ide> def test_dnn_correctness( <ide> ): <ide> with self.assertRaisesRegex( <ide> ValueError, <del> "Expected `model` argument to be a functional `Model` instance, " <del> "but got a subclassed model instead.", <add> "Expected `model` argument to be a functional `Model` " <add> "instance, but got a subclassed model instead.", <ide> ): <ide> self.run_correctness_test( <ide> distribution, use_numpy, use_validation_data <ide> def test_dnn_with_dynamic_learning_rate(self, distribution): <ide> elif backend.is_tpu_strategy(distribution): <ide> with self.assertRaisesRegex( <ide> ValueError, <del> "Expected `model` argument to be a functional `Model` instance, " <del> "but got a subclassed model instead.", <add> "Expected `model` argument to be a functional `Model` " <add> "instance, but got a subclassed model instead.", <ide> ): <ide> self.run_dynamic_lr_test(distribution) <ide> else: <ide><path>keras/distribute/keras_embedding_model_correctness_test.py <ide> def submodel(embedding, word_ids): <ide> if initial_weights: <ide> model.set_weights(initial_weights) <ide> <del> # TODO(b/130808953): Switch back to the V1 optimizer after global_step <del> # is made mirrored. <add> # TODO(b/130808953): Switch back to the V1 optimizer after <add> # global_step is made mirrored. <ide> model.compile( <ide> optimizer=gradient_descent_keras.SGD(learning_rate=0.1), <ide> loss="mse", <ide><path>keras/distribute/keras_metrics_test.py <ide> class MetricLayer(base_layer.Layer): <ide> def __init__(self): <ide> super().__init__(name="metric_layer") <ide> self.sum = metrics.Sum(name="sum") <del> # Using aggregation for jit_compile results in failure. Thus only set <del> # aggregation for PS Strategy for multi-gpu tests. <add> # Using aggregation for jit_compile results in failure. Thus <add> # only set aggregation for PS Strategy for multi-gpu tests. <ide> if isinstance( <ide> distribution, <ide> tf.distribute.experimental.ParameterServerStrategy, <ide><path>keras/distribute/keras_optimizer_v2_test.py <ide> def train_fn(): <ide> <ide> # first step. <ide> train_fn() <del> # var(1) = var(0) - lr * m(1) * sqrt(1 - beta2) / sqrt(v(1)) / (1 - beta1) <add> # var(1) = var(0) - lr * m(1) * sqrt(1 - beta2) / sqrt(v(1)) / (1 - <add> # beta1) <ide> # = 2.0 - 0.01 * 1.2 * sqrt(0.8) / sqrt(1.8) / 0.8 <ide> self.assertAllClose(1.99, self.evaluate(all_vars[0])) <del> # m(1) = beta1 * m(0) + (1-beta1) * grad = 0.2 * 0 + 0.8 * (1 + 2) / 2 <add> # m(1) = beta1 * m(0) + (1-beta1) * grad = 0.2 * 0 + 0.8 * (1 + 2) / <add> # 2 <ide> self.assertAllClose(1.2, self.evaluate(all_vars[1])) <ide> # v(1) = beta2 * v(0) + (1-beta2) * grad^2 = 0.2 * 0 + 0.8 * 2.25 <ide> self.assertAllClose(1.8, self.evaluate(all_vars[2])) <ide><path>keras/distribute/keras_premade_models_test.py <ide> def test_linear_model(self, distribution, use_dataset_creator, data_fn): <ide> distribution, tf.distribute.experimental.ParameterServerStrategy <ide> ): <ide> self.skipTest( <del> "Parameter Server strategy requires dataset creator to be used in " <del> "model.fit." <add> "Parameter Server strategy requires dataset creator to be used " <add> "in model.fit." <ide> ) <ide> if ( <ide> not tf.__internal__.tf2.enabled() <ide> def test_linear_model(self, distribution, use_dataset_creator, data_fn): <ide> ) <ide> ): <ide> self.skipTest( <del> "Parameter Server strategy with dataset creator needs to be run when " <del> "eager execution is enabled." <add> "Parameter Server strategy with dataset creator needs to be " <add> "run when eager execution is enabled." <ide> ) <ide> with distribution.scope(): <ide> model = linear.LinearModel() <ide> def test_wide_deep_model(self, distribution, use_dataset_creator, data_fn): <ide> distribution, tf.distribute.experimental.ParameterServerStrategy <ide> ): <ide> self.skipTest( <del> "Parameter Server strategy requires dataset creator to be used in " <del> "model.fit." <add> "Parameter Server strategy requires dataset creator to be used " <add> "in model.fit." <ide> ) <ide> if ( <ide> not tf.__internal__.tf2.enabled() <ide> def test_wide_deep_model(self, distribution, use_dataset_creator, data_fn): <ide> ) <ide> ): <ide> self.skipTest( <del> "Parameter Server strategy with dataset creator needs to be run when " <del> "eager execution is enabled." <add> "Parameter Server strategy with dataset creator needs to be " <add> "run when eager execution is enabled." <ide> ) <ide> with distribution.scope(): <ide> linear_model = linear.LinearModel(units=1) <ide><path>keras/distribute/keras_utils_test.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> # ============================================================================== <del>"""Tests for tf.keras models with callbacks, checkpointing with dist strategy.""" <add>"""Tests for tf.keras models with callbacks, checkpointing with dist <add>strategy.""" <ide> <ide> import collections <ide> import tempfile <ide> def test_callbacks_in_fit(self, distribution): <ide> ) <ide> and not tf.executing_eagerly() <ide> ): <del> # TPU Strategy can have multi step training, from extended.steps_per_run <del> # if steps_per_run = 1, then num_batch_call_per_epoch = steps_per_epoch <add> # TPU Strategy can have multi step training, from <add> # extended.steps_per_run if steps_per_run = 1, then <add> # num_batch_call_per_epoch = steps_per_epoch <ide> steps_per_run = distribution.extended.steps_per_run <ide> num_batch_call_per_epoch = steps_per_epoch // steps_per_run <ide> if steps_per_epoch % steps_per_run: <ide> def run(): <ide> <ide> x = distribution.run(run) <ide> <del> # Removed device and input tensor shape details from the error message <del> # since the order of the device and the corresponding input tensor shape <del> # is not deterministic over different runs. <add> # Removed device and input tensor shape details from the error <add> # message since the order of the device and the corresponding input <add> # tensor shape is not deterministic over different runs. <ide> with self.assertRaisesRegex( <ide> ValueError, <ide> "Input tensor shapes do not match for " <ide> def run(): <ide> <ide> x = distribution.run(run) <ide> <del> # Removed device and input tensor dtype details from the error message <del> # since the order of the device and the corresponding input tensor dtype <del> # is not deterministic over different runs. <add> # Removed device and input tensor dtype details from the error <add> # message since the order of the device and the corresponding input <add> # tensor dtype is not deterministic over different runs. <ide> with self.assertRaisesRegex( <ide> ValueError, <ide> "Input tensor dtypes do not match for " <ide> def test_unsupported_features(self, distribution, mode): <ide> sample_weight=sample_weight, <ide> ) <ide> <del> # Test with not specifying the `steps` argument for dataset with infinite <del> # cardinality. <add> # Test with not specifying the `steps` argument for dataset with <add> # infinite cardinality. <ide> dataset = dataset.repeat() <ide> with self.assertRaises(ValueError): <ide> model.fit(dataset, epochs=1, verbose=0) <ide><path>keras/distribute/minimize_loss_test.py <ide> def testOptimizerInsideModelFn(self, distribution, optimizer_fn): <ide> <ide> def appending_creator(next_creator, **kwargs): <ide> v = next_creator(**kwargs) <del> # Skip the StateVar created in the tf.random.Generator, which is used by <del> # keras initializers. <add> # Skip the StateVar created in the tf.random.Generator, which is <add> # used by keras initializers. <ide> if "StateVar" in v.name: <ide> return v <ide> created_variables.append(v.name) <ide> def run_step(): <ide> expected_moving_means = [0.0] * 8 <ide> <ide> def averaged_batch_mean(i): <del> # Each batch has shape [16, 8] where the ith element in jth list is <del> # (8 * j + i + replica_id * 100). So the batch mean in each replica is <del> # (60 + i + replica_id * 100). So here comes its batch mean over all <del> # replicas: <add> # Each batch has shape [16, 8] where the ith element in jth list <add> # is (8 * j + i + replica_id * 100). So the batch mean in each <add> # replica is (60 + i + replica_id * 100). So here comes its <add> # batch mean over all replicas: <ide> return 60.0 + i + (num_replicas - 1.0) / 2.0 * 100.0 <ide> <ide> for _ in range(10): <ide> run_step() <ide> moving_means = self.evaluate(batchnorm.moving_mean) <ide> <del> # We make sure that the moving_mean is updated as if the sample mean is <del> # calculated over all replicas. <add> # We make sure that the moving_mean is updated as if the sample <add> # mean is calculated over all replicas. <ide> for i, expected_moving_mean in enumerate(expected_moving_means): <ide> expected_moving_means[i] -= ( <ide> expected_moving_mean - averaged_batch_mean(i) <ide> def run_step(): <ide> # predict = [4, 14] <ide> # predict - y = [-2, -7] <ide> # dloss/dw = 2 <[2, 7], [-2, -7]> = - 2(4 + 49) = -106 <del> # So unreplicated the update to w with lr=0.001 is -0.2 * -106 = 0.106 <del> # with sum loss reduction, or 0.053 with mean. <add> # So unreplicated the update to w with lr=0.001 is -0.2 * -106 = <add> # 0.106 with sum loss reduction, or 0.053 with mean. <ide> if loss_reduction == tf.compat.v1.losses.Reduction.SUM: <del> # Note that the "distribution.num_replicas_in_sync" factor will go away <del> # once we split the input across replicas, instead of pulling a complete <del> # batch of input per replica. <add> # Note that the "distribution.num_replicas_in_sync" factor will <add> # go away once we split the input across replicas, instead of <add> # pulling a complete batch of input per replica. <ide> self.assertNear( <ide> weight, <ide> 2 + 0.106 * distribution.num_replicas_in_sync, <ide> def testRunStepsWithOutputContext(self, distribution, optimizer_fn, is_tpu): <ide> <ide> def dataset_fn(): <ide> dataset = tf.data.Dataset.from_tensors([[1.0]]).repeat() <del> # TODO(priyag): batch with drop_remainder=True causes shapes to be <del> # fully defined for TPU. Remove this when XLA supports dynamic shapes. <add> # TODO(priyag): batch with drop_remainder=True causes shapes to <add> # be fully defined for TPU. Remove this when XLA supports <add> # dynamic shapes. <ide> return dataset.batch(batch_size=1, drop_remainder=True) <ide> <ide> optimizer = optimizer_fn() <ide> def run_step(): <ide> initial_loss = lambda: tf.constant(1e7) <ide> # Initial values corresponding to reduced losses are just single <ide> # tensors. But for non reduced losses, we need to have initial <del> # values that are of the same structure as non reduced losses. In <del> # MirroredStrategy, this will be a list of losses, in TPUStrategy <del> # it will be single tensor. Using `call_for_each_replica` followed <del> # by `experimental_local_results` gives us the desired initial <add> # values that are of the same structure as non reduced losses. <add> # In MirroredStrategy, this will be a list of losses, in <add> # TPUStrategy it will be single tensor. Using <add> # `call_for_each_replica` followed by <add> # `experimental_local_results` gives us the desired initial <ide> # value structure. <ide> not_reduced = distribution.experimental_local_results( <ide> distribution.extended.call_for_each_replica(initial_loss) <ide><path>keras/distribute/mirrored_variable_test.py <ide> def model_fn(features): <ide> layer1(features) <ide> layer2 = core.Dense(1) <ide> layer2(features) <del> # We rely on names and orders to make sure replica references the same <del> # MirroredVariable. Uniquifying names may involve global states, <del> # merge_call switches threads so we need to test things work after <del> # merge_call. <add> # We rely on names and orders to make sure replica references the <add> # same MirroredVariable. Uniquifying names may involve global <add> # states, merge_call switches threads so we need to test things work <add> # after merge_call. <ide> tf.distribute.get_replica_context().merge_call(lambda _: _) <ide> layer3 = core.Dense(1) <ide> layer3(features) <ide><path>keras/distribute/multi_worker_callback_tf2_test.py <ide> def proc_model_checkpoint_saves_on_chief_but_not_otherwise( <ide> num_epoch = 2 <ide> extension = os.path.splitext(saving_filepath)[1] <ide> <del> # Incorporate type/index information and thread id in saving_filepath to <del> # ensure every worker has a unique path. Note that in normal use case the <del> # saving_filepath will be the same for all workers, but we use different <del> # ones here just to test out chief saves checkpoint but non-chief doesn't. <add> # Incorporate type/index information and thread id in <add> # saving_filepath to ensure every worker has a unique path. Note <add> # that in normal use case the saving_filepath will be the same for <add> # all workers, but we use different ones here just to test out chief <add> # saves checkpoint but non-chief doesn't. <ide> task_config = get_tf_config_task() <ide> saving_filepath = os.path.join( <ide> test_obj.get_temp_dir(), <ide> "checkpoint_%s_%d%s" <ide> % (task_config["type"], task_config["index"], extension), <ide> ) <ide> <del> # The saving_filepath shouldn't exist at the beginning (as it's unique). <add> # The saving_filepath shouldn't exist at the beginning (as it's <add> # unique). <ide> test_obj.assertFalse(checkpoint_exists(saving_filepath)) <ide> <ide> model.fit( <ide> def proc_model_checkpoint_saves_on_chief_but_not_otherwise( <ide> ], <ide> ) <ide> <del> # If it's chief, the model should be saved; if not, the model shouldn't. <add> # If it's chief, the model should be saved; if not, the model <add> # shouldn't. <ide> test_obj.assertEqual(checkpoint_exists(saving_filepath), is_chief()) <ide> <ide> # If it's chief, the model should be saved (`write_filepath` should <del> # simply return `saving_filepath`); if not, i.e. for non-chief workers, <del> # the temporary path generated by `write_filepath` should no longer <del> # contain the checkpoint that has been deleted. <add> # simply return `saving_filepath`); if not, i.e. for non-chief <add> # workers, the temporary path generated by `write_filepath` should <add> # no longer contain the checkpoint that has been deleted. <ide> test_obj.assertEqual( <ide> checkpoint_exists( <ide> distributed_file_utils.write_filepath( <ide> def proc_model_checkpoint_works_with_same_file_path( <ide> model, _, train_ds, steps = _model_setup(test_obj, file_format="") <ide> num_epoch = 2 <ide> <del> # The saving_filepath shouldn't exist at the beginning (as it's unique). <add> # The saving_filepath shouldn't exist at the beginning (as it's <add> # unique). <ide> test_obj.assertFalse(tf.io.gfile.exists(saving_filepath)) <ide> <ide> model.fit( <ide> def on_epoch_begin(self, epoch, logs=None): <ide> class AssertCallback(callbacks.Callback): <ide> def on_epoch_begin(self, epoch, logs=None): <ide> # the interruption happened on epoch 2 as specified in <del> # InterruptingCallback, so the initial epoch after restart will begin <del> # at 2. <add> # InterruptingCallback, so the initial epoch after restart will <add> # begin at 2. <ide> assert epoch > 1 <ide> <ide> def proc_model_checkpoint_works_with_same_file_path( <ide> def proc_model_checkpoint_works_with_same_file_path( <ide> model, _, train_ds, steps = _model_setup(test_obj, file_format="") <ide> num_epoch = 4 <ide> <del> # The saving_filepath shouldn't exist at the beginning (as it's unique). <add> # The saving_filepath shouldn't exist at the beginning (as it's <add> # unique). <ide> test_obj.assertFalse(tf.io.gfile.exists(saving_filepath)) <ide> bar_dir = os.path.join(os.path.dirname(saving_filepath), "backup") <ide> <ide> def proc_profiler_saves_on_both_chief_and_non_chief(test_obj): <ide> "logfile_%s_%d" % (task_config["type"], task_config["index"]), <ide> ) <ide> <del> # The saving_filepath shouldn't exist at the beginning (as it's unique). <add> # The saving_filepath shouldn't exist at the beginning (as it's <add> # unique). <ide> test_obj.assertFalse(tf.io.gfile.exists(saving_filepath)) <ide> <ide> model.fit( <ide> def proc_tensorboard_saves_on_chief_but_not_otherwise(test_obj): <ide> model, _, train_ds, steps = _model_setup(test_obj, file_format="") <ide> num_epoch = 2 <ide> <del> # Incorporate type/index information and thread id in saving_filepath to <del> # ensure every worker has a unique path. Note that in normal use case the <del> # saving_filepath will be the same for all workers, but we use different <del> # ones here just to test out chief saves summaries but non-chief doesn't. <add> # Incorporate type/index information and thread id in <add> # saving_filepath to ensure every worker has a unique path. Note <add> # that in normal use case the saving_filepath will be the same for <add> # all workers, but we use different ones here just to test out chief <add> # saves summaries but non-chief doesn't. <ide> task_config = get_tf_config_task() <ide> saving_filepath = os.path.join( <ide> test_obj.get_temp_dir(), <ide> "logfile_%s_%d" % (task_config["type"], task_config["index"]), <ide> ) <ide> <del> # The saving_filepath shouldn't exist at the beginning (as it's unique). <add> # The saving_filepath shouldn't exist at the beginning (as it's <add> # unique). <ide> test_obj.assertFalse(tf.io.gfile.exists(saving_filepath)) <ide> <ide> model.fit( <ide> def proc_tensorboard_saves_on_chief_but_not_otherwise(test_obj): <ide> ], <ide> ) <ide> <del> # If it's chief, the summaries should be saved in the filepath; if not, <del> # the directory should be empty (although created). Using <del> # `file_io.list_directory()` since the directory may be created at this <del> # point. <add> # If it's chief, the summaries should be saved in the filepath; if <add> # not, the directory should be empty (although created). Using <add> # `file_io.list_directory()` since the directory may be created at <add> # this point. <ide> test_obj.assertEqual( <ide> bool(tf.io.gfile.listdir(saving_filepath)), is_chief() <ide> ) <ide> def proc_tensorboard_can_still_save_to_temp_even_if_it_exists(test_obj): <ide> os.mkdir(saving_filepath) <ide> os.mkdir(saving_filepath_for_temp) <ide> <del> # Verifies that even if `saving_filepath_for_temp` exists, tensorboard <del> # can still save to temporary directory. <add> # Verifies that even if `saving_filepath_for_temp` exists, <add> # tensorboard can still save to temporary directory. <ide> test_obj.assertTrue(tf.io.gfile.exists(saving_filepath_for_temp)) <ide> <ide> model.fit( <ide> def proc_tensorboard_works_with_same_file_path( <ide> model, _, train_ds, steps = _model_setup(test_obj, file_format="") <ide> num_epoch = 2 <ide> <del> # The saving_filepath shouldn't exist at the beginning (as it's unique). <add> # The saving_filepath shouldn't exist at the beginning (as it's <add> # unique). <ide> test_obj.assertFalse(tf.io.gfile.exists(saving_filepath)) <ide> <ide> tf.__internal__.distribute.multi_process_runner.get_barrier().wait() <ide> def on_epoch_begin(self, epoch, logs): <ide> epoch_counter_cbk, <ide> ] <ide> <del> # Empirically, it is expected that `model.fit()` terminates around the <del> # 22th epoch. Asserting that it should have been stopped before the 50th <del> # epoch to avoid flakiness and be more predictable. <add> # Empirically, it is expected that `model.fit()` terminates around <add> # the 22th epoch. Asserting that it should have been stopped before <add> # the 50th epoch to avoid flakiness and be more predictable. <ide> model.fit( <ide> x=train_ds, epochs=100, steps_per_epoch=steps, callbacks=cbks <ide> ) <ide><path>keras/distribute/multi_worker_test.py <ide> def _clone_and_build_model(model, strategy): <ide> <ide> # TODO(b/123918215): Possibly merge this Callback with keras_test.Counter. <ide> class MultiWorkerVerificationCallback(callbacks.Callback): <del> """MultiWorkerVerificationCallback verifies the callbacks in multi-worker scheme. <add> """MultiWorkerVerificationCallback verifies the callbacks in multi-worker <add> scheme. <ide> <ide> This Callback is intended to be used for verifying the callback is indeed <ide> called the correct number of times in various task types. <ide> <ide> Attributes: <ide> _task_dict: A nested dictionary storing the number of times a callback has <del> been called in specific task type, task index, and method name. <del> Look up structure is <add> been called in specific task type, task index, and method <add> name. Look up structure is <ide> task_name -> task_id -> tracking_method_name -> invoke_count <ide> For example, a _task_dict of <ide> { <ide> class MultiWorkerVerificationCallback(callbacks.Callback): <ide> } <ide> } <ide> } <del> indicates the ps task has 'on_epoch_begin' called twice on each <del> of the two indices, and likewise for worker task. <add> indicates the ps task has 'on_epoch_begin' called twice on <add> each of the two indices, and likewise for worker task. <ide> """ <ide> <ide> # TODO(rchao): Add other method calls to verify. <ide> def __init__(self, num_epoch, num_worker): <ide> """Initialize a MultiWorkerVerificationCallback. <ide> <ide> Args: <del> num_epoch: Number of epochs this Callback is expected to be called for. <del> num_worker: Number of workers this Callback is expected to be called from. <add> num_epoch: Number of epochs this Callback is expected to be called <add> for. <add> num_worker: Number of workers this Callback is expected to be called <add> from. <ide> """ <ide> super().__init__() <ide> self._num_epoch = num_epoch <ide> def verify(self, test_case): <ide> } <ide> assert self._is_between_graph is not None <ide> if self._is_between_graph: <del> # TODO(b/124171024): In between-graph replication, by default only the <del> # chief calls callback. Fix this test to cover that, as well as the rare <del> # cases where all workers call. <add> # TODO(b/124171024): In between-graph replication, by default only <add> # the chief calls callback. Fix this test to cover that, as well as <add> # the rare cases where all workers call. <ide> worker_call_count = { <ide> i: method_count_dict for i in range(0, self._num_worker) <ide> } <ide> def step_fn(inputs): <ide> <ide> <ide> if __name__ == "__main__": <del> # Enable manual variable initialization to make sure variables are initialized <del> # by `init_restore_or_wait_for_variables`. <add> # Enable manual variable initialization to make sure variables are <add> # initialized by `init_restore_or_wait_for_variables`. <ide> backend.manual_variable_initialization(True) <ide> with tf.compat.v1.test.mock.patch.object(sys, "exit", os._exit): <ide> tf.__internal__.distribute.multi_process_runner.test_main() <ide><path>keras/distribute/multi_worker_testing_utils.py <ide> def create_in_process_cluster( <ide> eval_config = tf.compat.v1.ConfigProto() <ide> eval_config.experimental.collective_group_leader = "" <ide> <del> # Create in-process servers. Once an in-process tensorflow server is created, <del> # there is no way to terminate it. So we create one cluster per test process. <del> # We could've started the server in another process, we could then kill that <del> # process to terminate the server. The reasons why we don"t want multiple <del> # processes are <add> # Create in-process servers. Once an in-process tensorflow server is <add> # created, there is no way to terminate it. So we create one cluster per <add> # test process. We could've started the server in another process, we could <add> # then kill that process to terminate the server. The reasons why we don"t <add> # want multiple processes are <ide> # 1) it is more difficult to manage these processes; <del> # 2) there is something global in CUDA such that if we initialize CUDA in the <del> # parent process, the child process cannot initialize it again and thus cannot <del> # use GPUs (https://stackoverflow.com/questions/22950047). <add> # 2) there is something global in CUDA such that if we initialize CUDA in <add> # the parent process, the child process cannot initialize it again and thus <add> # cannot use GPUs (https://stackoverflow.com/questions/22950047). <ide> cluster = None <ide> try: <ide> cluster = _create_cluster( <ide><path>keras/distribute/optimizer_combinations.py <ide> <ide> <ide> def distributions_and_v1_optimizers(): <del> """A common set of combination with DistributionStrategies and Optimizers.""" <add> """A common set of combination with DistributionStrategies and <add> Optimizers.""" <ide> return tf.__internal__.test.combinations.combine( <ide> distribution=[ <ide> tf.__internal__.distribute.combinations.one_device_strategy, <ide> def distributions_and_v1_optimizers(): <ide> <ide> <ide> def distributions_and_v2_optimizers(): <del> """A common set of combination with DistributionStrategies and Optimizers.""" <add> """A common set of combination with DistributionStrategies and <add> Optimizers.""" <ide> return tf.__internal__.test.combinations.combine( <ide> distribution=[ <ide> tf.__internal__.distribute.combinations.one_device_strategy, <ide> def distributions_and_v2_optimizers(): <ide> <ide> <ide> def distributions_and_v1_and_v2_optimizers(): <del> """A common set of combination with DistributionStrategies and Optimizers.""" <add> """A common set of combination with DistributionStrategies and <add> Optimizers.""" <ide> return tf.__internal__.test.combinations.combine( <ide> distribution=[ <ide> tf.__internal__.distribute.combinations.one_device_strategy, <ide><path>keras/distribute/parameter_server_evaluation_test.py <ide> def testModelEvaluatePrototype(self): <ide> def metric_fn(): <ide> return MeanMetricAsCompositeTensor() <ide> <del> # TODO(yuefengz): make _create_per_worker_resources public and get rid of <del> # the type_spec hack. <add> # TODO(yuefengz): make _create_per_worker_resources public and get rid <add> # of the type_spec hack. <ide> per_worker_metric = self.cluster_coord._create_per_worker_resources( <ide> metric_fn <ide> ) <ide> def eval_fn(total_shard, shard_id, metric): <ide> for i in dataset_shard: <ide> metric.update_state(i) <ide> <del> # TODO(yuefengz): we should return the internal state of the metric and <del> # then use the combiner API. <add> # TODO(yuefengz): we should return the internal state of the metric <add> # and then use the combiner API. <ide> return metric.result() <ide> <ide> total_shards = 128 <ide><path>keras/distribute/saved_model_save_load_test.py <ide> def test_save_load_io_device(self, model_and_input, distribution): <ide> load_options = tf.saved_model.LoadOptions( <ide> experimental_io_device="/job:localhost" <ide> ) <del> # Check that the model can be loaded and training continued without error. <add> # Check that the model can be loaded and training continued without <add> # error. <ide> with distribution.scope(): <ide> loaded_model = tf.saved_model.load(saved_dir, options=load_options) <ide> self._train_model(loaded_model, x_train, y_train, batch_size) <ide><path>keras/distribute/saved_model_test_base.py <ide> def _load_and_run_model( <ide> This method must be implemented by the subclasses. <ide> <ide> Args: <del> distribution: the distribution strategy used to load the model. None if no <del> distribution strategy is used <add> distribution: the distribution strategy used to load the model. None <add> if no distribution strategy is used <ide> saved_dir: the string representing the path where the model is saved. <ide> predict_dataset: the data used to do the predict on the model for <ide> cross_replica context. <del> output_name: the string representing the name of the output layer of the <del> model. <add> output_name: the string representing the name of the output layer of <add> the model. <ide> """ <ide> <ide> raise NotImplementedError("must be implemented in descendants") <ide> def run_test_save_strategy_restore_strategy( <ide> distribution_for_restoring, <ide> save_in_scope, <ide> ): <del> """Save a model with DS, and restore it with potentially different DS.""" <add> """Save a model with DS, and restore it with potentially different <add> DS.""" <ide> saved_dir = os.path.join(self.get_temp_dir(), "2") <ide> <ide> with distribution_for_saving.scope(): <ide><path>keras/distribute/sharded_variable_test.py <ide> def test_saved_model_combined(self, shard_config, model_type): <ide> """Test saving and loading models with various fixed numbers of shards. <ide> <ide> Args: <del> shard_config: The number of shards to use per variable before and after <del> loading. For example, [1, 3] means to create and save the model with 1 <del> shard (i.e., no variable partitioning), and load it into 3 shards per <del> variable. <add> shard_config: The number of shards to use per variable before and <add> after loading. For example, [1, 3] means to create and save the <add> model with 1 shard (i.e., no variable partitioning), and load it <add> into 3 shards per variable. <ide> model_type: Either 'dense' or 'embedding', which simple model to test. <ide> """ <ide> <ide> def create_dense_model(): <ide> ) <ide> expect = model(x) <ide> <del> # Dense layers have two variables (kernel and bias), embedding layers have 1 <add> # Dense layers have two variables (kernel and bias), embedding layers <add> # have 1 <ide> n_expected_variables = shard_config[0] * ( <ide> 2 if model_type == "dense" else 1 <ide> ) <ide> def create_dense_model(): <ide> def test_slot_variable_checkpointing(self): <ide> <ide> with self.strategy.scope(): <del> # Set a name so the ShardedVariable is well-named for slot var keying <add> # Set a name so the ShardedVariable is well-named for slot var <add> # keying <ide> var = tf.Variable([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name="test") <ide> <ide> opt = keras.optimizers.optimizer_v2.adam.Adam() <ide> <del> # Run once to trigger apply_gradients to populate optimizer slot variables. <add> # Run once to trigger apply_gradients to populate optimizer slot <add> # variables. <ide> def train_step(): <ide> with tf.GradientTape() as tape: <ide> loss = sum(var) <ide> def train_step(): <ide> <ide> ckpt = tf.train.Checkpoint(var=var, opt=opt) <ide> <del> # Assert that checkpoint has slots for each shard and the ShardedVariable <add> # Assert that checkpoint has slots for each shard and the <add> # ShardedVariable <ide> self.assertLen(ckpt.opt._slots, 3) <ide> for var_name in ckpt.opt._slots.keys(): <ide> self.assertLen(ckpt.opt._slots[var_name], 2) <ide> def train_step(): <ide> def test_slot_variable_checkpoint_load_with_diff_shards(self): <ide> <ide> with self.strategy.scope(): <del> # Set a name so the ShardedVariable is well-named for slot var keying <add> # Set a name so the ShardedVariable is well-named for slot var <add> # keying <ide> var = tf.Variable([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name="test") <ide> <ide> opt = keras.optimizers.optimizer_v2.adam.Adam() <ide> <del> # Run once to trigger apply_gradients to populate optimizer slot variables. <add> # Run once to trigger apply_gradients to populate optimizer slot <add> # variables. <ide> def train_step(): <ide> with tf.GradientTape() as tape: <ide> loss = sum(var) <ide> def train_step(): <ide> var = tf.Variable([0.0, 1.0, 2.0, 3.0, 4.0, 5.0], name="test") <ide> <ide> opt = keras.optimizers.optimizer_v2.adam.Adam() <del> # Run once to trigger apply_gradients to populate optimizer slot variables. <add> # Run once to trigger apply_gradients to populate optimizer slot <add> # variables. <ide> strategy2.run(train_step) <ide> <ide> new_ckpt = tf.train.Checkpoint(var=var, opt=opt) <ide> def train_step(): <ide> class ShardedVariableMixedPartitioningTest(tf.test.TestCase): <ide> def test_saved_model_min_size_partitioner(self): <ide> <del> # set min_shard_bytes such that Dense kernel is split into 2 and bias into 1 <add> # set min_shard_bytes such that Dense kernel is split into 2 and bias <add> # into 1 <ide> partitioner = ( <ide> tf.distribute.experimental.partitioners.MinSizePartitioner( <ide> min_shard_bytes=(6 * 6 * 4) // 2, max_shards=2 <ide> def create_dense_model(): <ide> saved_dir = self.get_temp_dir() <ide> model.save(saved_dir) <ide> <del> # set min_shard_bytes such that Dense kernel is split into 3 and bias into 1 <add> # set min_shard_bytes such that Dense kernel is split into 3 and bias <add> # into 1 <ide> partitioner2 = ( <ide> tf.distribute.experimental.partitioners.MinSizePartitioner( <ide> min_shard_bytes=(6 * 6 * 4) // 3, max_shards=3 <ide><path>keras/distribute/sidecar_evaluator.py <ide> class SidecarEvaluator: <ide> evaluator, evaluating the metric results of a training cluster which has one <ide> or more workers performing the training, and saving checkpoints. <ide> <del> The `SidecarEvaluator` API is compatible with both Custom Training Loop (CTL), <del> and Keras `Model.fit` to be used in the training cluster. Using the model <del> (with compiled metrics) provided at `__init__`, `SidecarEvaluator` repeatedly <del> performs evaluation "epochs" when it finds a checkpoint that has not yet been <del> used. Depending on the `steps` argument, an eval epoch is evaluation over all <del> eval data, or up to certain number of steps (batches). See examples below for <del> how the training program should save the checkpoints in order to be recognized <del> by `SidecarEvaluator`. <del> <del> Since under the hood, `SidecarEvaluator` uses `model.evaluate` for evaluation, <del> it also supports arbitrary Keras callbacks. That is, if one or more callbacks <del> are provided, their `on_test_batch_begin` and `on_test_batch_end` methods are <del> called at the start and end of a batch, and their `on_test_begin` and <del> `on_test_end` are called at the start and end of an evaluation epoch. Note <del> that `SidecarEvaluator` may skip some checkpoints because it always picks up <del> the latest checkpoint available, and during an evaluation epoch, multiple <del> checkpoints can be produced from the training side. <add> The `SidecarEvaluator` API is compatible with both Custom Training Loop <add> (CTL), and Keras `Model.fit` to be used in the training cluster. Using the <add> model (with compiled metrics) provided at `__init__`, `SidecarEvaluator` <add> repeatedly performs evaluation "epochs" when it finds a checkpoint that has <add> not yet been used. Depending on the `steps` argument, an eval epoch is <add> evaluation over all eval data, or up to certain number of steps (batches). <add> See examples below for how the training program should save the checkpoints <add> in order to be recognized by `SidecarEvaluator`. <add> <add> Since under the hood, `SidecarEvaluator` uses `model.evaluate` for <add> evaluation, it also supports arbitrary Keras callbacks. That is, if one or <add> more callbacks are provided, their `on_test_batch_begin` and <add> `on_test_batch_end` methods are called at the start and end of a batch, and <add> their `on_test_begin` and `on_test_end` are called at the start and end of <add> an evaluation epoch. Note that `SidecarEvaluator` may skip some checkpoints <add> because it always picks up the latest checkpoint available, and during an <add> evaluation epoch, multiple checkpoints can be produced from the training <add> side. <ide> <ide> Example: <ide> ```python <ide> class SidecarEvaluator: <ide> tf.keras.SidecarEvaluator( <ide> model=model, <ide> data=data, <del> checkpoint_dir='/tmp/checkpoint_dir', # dir for training-saved checkpoint <add> # dir for training-saved checkpoint <add> checkpoint_dir='/tmp/checkpoint_dir', <ide> steps=None, # Eval until dataset is exhausted <ide> max_evaluations=None, # The evaluation needs to be stopped manually <ide> callbacks=[tf.keras.callbacks.TensorBoard(log_dir='/tmp/log_dir')] <ide> ).start() <ide> ``` <ide> <del> `SidecarEvaluator.start` writes a series of summary <del> files which can be visualized by tensorboard (which provides a webpage link): <add> `SidecarEvaluator.start` writes a series of summary files which can be <add> visualized by tensorboard (which provides a webpage link): <ide> <ide> ```bash <ide> $ tensorboard --logdir=/tmp/log_dir/validation <ide> class SidecarEvaluator: <ide> `tf.train.Checkpoint` and a `tf.train.CheckpointManager`: <ide> <ide> ```python <del> checkpoint_dir = ... # Same `checkpoint_dir` supplied to `SidecarEvaluator`. <add> # Same `checkpoint_dir` supplied to `SidecarEvaluator`. <add> checkpoint_dir = ... <ide> checkpoint = tf.train.Checkpoint(model=model, optimizer=optimizer) <ide> checkpoint_manager = tf.train.CheckpointManager( <ide> checkpoint, checkpoint_dir=..., max_to_keep=...) <ide> class SidecarEvaluator: <ide> appended: <ide> <ide> ```python <del> checkpoint_dir = ... # Same `checkpoint_dir` supplied to `SidecarEvaluator`. <add> # Same `checkpoint_dir` supplied to `SidecarEvaluator`. <add> checkpoint_dir = ... <ide> model_checkpoint = tf.keras.callbacks.ModelCheckpoint( <ide> filepath=os.path.join(checkpoint_dir, 'ckpt-{epoch}'), <ide> save_weights_only=True) <ide> def __init__( <ide> """Initializes an `SidecarEvaluator` object. <ide> <ide> Args: <del> model: Model to use for evaluation. The model object used here should be a <del> `tf.keras.Model`, and should be the same as the one that is used in <del> training, where `tf.keras.Model`s are checkpointed. The model should <del> have one or more metrics compiled before using `SidecarEvaluator`. <del> data: The input data for evaluation. `SidecarEvaluator` supports all data <del> types that Keras `model.evaluate` supports as the input data `x`, such <del> as a `tf.data.Dataset`. <add> model: Model to use for evaluation. The model object used here should <add> be a `tf.keras.Model`, and should be the same as the one that is <add> used in training, where `tf.keras.Model`s are checkpointed. The <add> model should have one or more metrics compiled before using <add> `SidecarEvaluator`. <add> data: The input data for evaluation. `SidecarEvaluator` supports all <add> data types that Keras `model.evaluate` supports as the input data <add> `x`, such as a `tf.data.Dataset`. <ide> checkpoint_dir: Directory where checkpoint files are saved. <del> steps: Number of steps to perform evaluation for, when evaluating a single <del> checkpoint file. If `None`, evaluation continues until the dataset is <del> exhausted. For repeated evaluation dataset, user must specify `steps` to <del> avoid infinite evaluation loop. <del> max_evaluations: Maximum number of the checkpoint file to be evaluated, <del> for `SidecarEvaluator` to know when to stop. The evaluator will stop <del> after it evaluates a checkpoint filepath ending with <del> '<ckpt_name>-<max_evaluations>'. If using <del> `tf.train.CheckpointManager.save` for saving checkpoints, the kth saved <del> checkpoint has the filepath suffix '<ckpt_name>-<k>' (k=1 for the first <del> saved), and if checkpoints are saved every epoch after training, the <del> filepath saved at the kth epoch would end with '<ckpt_name>-<k>. Thus, <del> if training runs for n epochs, and the evaluator should end after the <del> training finishes, use n for this parameter. Note that this is not <del> necessarily equal to the number of total evaluations, since some <del> checkpoints may be skipped if evaluation is slower than checkpoint <del> creation. If `None`, `SidecarEvaluator` will evaluate indefinitely, and <del> the user must terminate evaluator program themselves. <del> callbacks: List of `keras.callbacks.Callback` instances to apply during <del> evaluation. See [callbacks](/api_docs/python/tf/keras/callbacks). <add> steps: Number of steps to perform evaluation for, when evaluating a <add> single checkpoint file. If `None`, evaluation continues until the <add> dataset is exhausted. For repeated evaluation dataset, user must <add> specify `steps` to avoid infinite evaluation loop. <add> max_evaluations: Maximum number of the checkpoint file to be <add> evaluated, for `SidecarEvaluator` to know when to stop. The <add> evaluator will stop after it evaluates a checkpoint filepath ending <add> with '<ckpt_name>-<max_evaluations>'. If using <add> `tf.train.CheckpointManager.save` for saving checkpoints, the kth <add> saved checkpoint has the filepath suffix '<ckpt_name>-<k>' (k=1 for <add> the first saved), and if checkpoints are saved every epoch after <add> training, the filepath saved at the kth epoch would end with <add> '<ckpt_name>-<k>. Thus, if training runs for n epochs, and the <add> evaluator should end after the training finishes, use n for this <add> parameter. Note that this is not necessarily equal to the number of <add> total evaluations, since some checkpoints may be skipped if <add> evaluation is slower than checkpoint creation. If `None`, <add> `SidecarEvaluator` will evaluate indefinitely, and the user must <add> terminate evaluator program themselves. <add> callbacks: List of `keras.callbacks.Callback` instances to apply <add> during evaluation. See <add> [callbacks](/api_docs/python/tf/keras/callbacks). <ide> """ <ide> self.model = model <ide> self.data = data <ide> def __init__( <ide> <ide> def _timeout_fn(self): <ide> logging.info( <del> f"No checkpoints appear to be found after {_CHECKPOINT_TIMEOUT_SEC} " <del> "seconds. Please check if you are properly using a " <add> "No checkpoints appear to be found after " <add> f"{_CHECKPOINT_TIMEOUT_SEC} seconds. " <add> "Please check if you are properly using a " <ide> "`tf.train.Checkpoint/CheckpointManager` or " <del> "`tf.keras.callbacks.ModelCheckpoint(save_weights_only=True)` to save " <del> "checkpoints by the training. See " <add> "`tf.keras.callbacks.ModelCheckpoint(save_weights_only=True)` to " <add> "save checkpoints by the training. See " <ide> "`tf.keras.SidecarEvaluator` doc for recommended flows " <ide> "of saving checkpoints." <ide> ) <ide> def start(self): <ide> timeout_fn=self._timeout_fn, <ide> ): <ide> try: <del> # `expect_partial` because the checkpoint can have other `Trackable`s <del> # such as `optimizer`. <add> # `expect_partial` because the checkpoint can have other <add> # `Trackable`s such as `optimizer`. <ide> checkpoint.restore(latest_checkpoint).expect_partial() <ide> checkpoint_attributes = list_checkpoint_attributes( <ide> latest_checkpoint <ide> ) <del> # The checkpoint should contain model and optimizer for SidecarEvaluator <del> # to work. But the model weights saved by ModelCheckpoint callback does <del> # not contain model as an attribute. To make SidecarEvaluator compatibly <del> # work in this case, use model.load_weights to load the model's weights, <del> # while self._iterations is still restored by checkpoint variable. <add> # The checkpoint should contain model and optimizer for <add> # SidecarEvaluator to work. But the model weights saved by <add> # ModelCheckpoint callback does not contain model as an <add> # attribute. To make SidecarEvaluator compatibly work in this <add> # case, use model.load_weights to load the model's weights, <add> # while self._iterations is still restored by checkpoint <add> # variable. <ide> if "model" not in checkpoint_attributes: <ide> self.model.load_weights(latest_checkpoint) <del> # The model checkpoint might not include optimizer in cases, e.g. <del> # using a custom training loop. Directly assign the iterations <del> # property to be used in callbacks. <add> # The model checkpoint might not include optimizer in cases, <add> # e.g. using a custom training loop. Directly assign the <add> # iterations property to be used in callbacks. <ide> if self.model.optimizer: <ide> self.model.optimizer.iterations.assign(self._iterations) <ide> except (tf.errors.OpError,) as e: <del> # A couple errors can happen here with the coordinator racing to write <del> # checkpoint: <del> # 1) OpError: open failed for <file path>: No such file or directory <add> # A couple errors can happen here with the coordinator racing to <add> # write checkpoint: <add> # 1) OpError: open failed for <file path>: No such file or <add> # directory <ide> # 2) NotFoundError (subclass of OpError): Unsuccessful <ide> # TensorSliceReader constructor. <del> # TODO(rchao): Remove this except block once b/150954027 is resolved. <add> # TODO(rchao): Remove this except block once b/150954027 is <add> # resolved. <ide> logging.info( <del> "SidecarEvaluator encountered an error when loading the checkpoint " <del> f"at {latest_checkpoint}. Retrying. " <add> "SidecarEvaluator encountered an error when loading the " <add> f"checkpoint at {latest_checkpoint}. Retrying. " <ide> f"Error: {e.__class__.__name__}: {e}" <ide> ) <ide> continue <ide> def start(self): <ide> if self.max_evaluations and ( <ide> self.max_evaluations <= int(latest_checkpoint.split("-")[-1]) <ide> ): <del> # Exit the loop because we have evaluated the final checkpoint file. <add> # Exit the loop because we have evaluated the final checkpoint <add> # file. <ide> logging.info( <ide> "Last checkpoint evaluated. SidecarEvaluator stops." <ide> ) <ide><path>keras/distribute/sidecar_evaluator_test.py <ide> def testSidecarEvaluatorOutputsSummary(self, model_type, build_model): <ide> callbacks=[keras.callbacks.TensorBoard(log_dir=log_dir)], <ide> ) <ide> sidecar_evaluator.start() <del> # Eval model has been restored to the same state as the original model, so <del> # their weights should match. If not, restoration of the model didn't <add> # Eval model has been restored to the same state as the original model, <add> # so their weights should match. If not, restoration of the model didn't <ide> # work. <ide> self.assertModelsSameVariables(model, eval_model) <ide> <ide> def testSidecarEvaluatorOutputsSummarySavedWithCallback( <ide> for metric_name in expected_logged_metrics: <ide> self.assertRegex(metrics_logging[0], f"{metric_name}=") <ide> <del> # Eval model has been restored to the same state as the original model, so <del> # their weights should match. If not, restoration of the model didn't <add> # Eval model has been restored to the same state as the original model, <add> # so their weights should match. If not, restoration of the model didn't <ide> # work. <ide> self.assertModelsSameVariables(model, eval_model) <ide> <ide><path>keras/distribute/test_example.py <ide> def batchnorm_example( <ide> renorm=False, <ide> update_ops_in_replica_mode=False, <ide> ): <del> """Example of non-distribution-aware legacy code with batch normalization.""" <add> """Example of non-distribution-aware legacy code with batch <add> normalization.""" <ide> <ide> def dataset_fn(): <del> # input shape is [16, 8], input values are increasing in both dimensions. <add> # input shape is [16, 8], input values are increasing in both <add> # dimensions. <ide> return tf.data.Dataset.from_tensor_slices( <ide> [ <ide> [ <ide> def loss_fn(): <ide> loss = tf.reduce_mean( <ide> tf.reduce_sum(layer(y)) - tf.constant(1.0) <ide> ) <del> # `x` and `y` will be fetched by the gradient computation, but not `loss`. <add> # `x` and `y` will be fetched by the gradient computation, but not <add> # `loss`. <ide> return loss <ide> <ide> if isinstance(optimizer, optimizer_v2.OptimizerV2): <ide><path>keras/distribute/worker_training_state.py <ide> def __init__(self, model, checkpoint_dir): <ide> # If this is single-worker training, checkpoint_dir are the same for <ide> # write_checkpoint_manager and read_checkpoint_manager. <ide> # <del> # If this is multi-worker training, and this worker should not <del> # save checkpoint, we replace the write_checkpoint_manager's checkpoint_dir <del> # with a temp filepath, so it writes to a file that will be removed at the <del> # end of back_up() call. This is necessary because the SyncOnReadVariable <del> # needs to be synced across all the workers in order to be read, and all <del> # workers need to perform `save()`. <del> # But all workers should restore from the same checkpoint_dir as passed in <add> # If this is multi-worker training, and this worker should not save <add> # checkpoint, we replace the write_checkpoint_manager's checkpoint_dir <add> # with a temp filepath, so it writes to a file that will be removed at <add> # the end of back_up() call. This is necessary because the <add> # SyncOnReadVariable needs to be synced across all the workers in order <add> # to be read, and all workers need to perform `save()`. But all workers <add> # should restore from the same checkpoint_dir as passed in <ide> # read_checkpoint_manager. <ide> self.read_checkpoint_manager = tf.train.CheckpointManager( <ide> checkpoint, <ide> def restore(self): <ide> """Restore the training state from the backed up checkpoint file. <ide> <ide> Returns: <del> True if the training state is successfully restored. False if the training <del> state doesn't need to be restored, or error occurred so it can't. <add> True if the training state is successfully restored. False if the <add> training state doesn't need to be restored, or error occurred so it <add> can't. <ide> """ <ide> self.read_checkpoint_manager.restore_or_initialize() <ide> <ide> def maybe_load_initial_epoch_from_ckpt(self, initial_epoch, mode): <ide> """Maybe load initial epoch from ckpt considering possible worker recovery. <ide> <ide> When `_ckpt_saved_epoch` attribute exists and is not <del> `CKPT_SAVED_EPOCH_UNUSED_VALUE`, this is under multi-worker training setting <del> and indicates the worker is recovering from previous failure. In this case, <del> infer `initial_epoch` from `self._ckpt_saved_epoch` to continue previous <del> unfinished training from certain epoch. <add> `CKPT_SAVED_EPOCH_UNUSED_VALUE`, this is under multi-worker training <add> setting and indicates the worker is recovering from previous failure. In <add> this case, infer `initial_epoch` from `self._ckpt_saved_epoch` to <add> continue previous unfinished training from certain epoch. <ide> <ide> Args: <ide> initial_epoch: The original initial_epoch user passes in in `fit()`. <ide> mode: The mode for running `model.fit()`. <ide> <ide> Returns: <ide> If the training is recovering from previous failure under multi-worker <del> training setting, return the epoch the training is supposed to continue <del> at. Otherwise, return the `initial_epoch` the user passes in. <add> training setting, return the epoch the training is supposed to <add> continue at. Otherwise, return the `initial_epoch` the user passes in. <ide> """ <ide> <ide> epoch = backend.eval(self._ckpt_saved_epoch) <ide> if mode == mode_keys.ModeKeys.TRAIN and epoch >= 0: <ide> # The most recently saved epoch is one epoch prior to the epoch it <del> # failed at, so return the value of 'self._ckpt_saved_epoch' plus one. <add> # failed at, so return the value of 'self._ckpt_saved_epoch' plus <add> # one. <ide> return epoch + 1 <ide> return initial_epoch
30
Ruby
Ruby
remove blank else branch
eceabc8355905ae7c92d2182921441fe0ff11773
<ide><path>activesupport/test/xml_mini/jdom_engine_test.rb <ide> def assert_equal_rexml(xml) <ide> assert_equal(hash, parsed_xml) <ide> end <ide> end <del> <del>else <del> # don't run these test because we aren't running in JRuby <ide> end
1
Javascript
Javascript
fix typeerror in eventemitter warning
254ab63832186ba2cfd87c9f2dfc0ce7a41a1989
<ide><path>lib/events.js <ide> function _addListener(target, type, listener, prepend) { <ide> if (m && m > 0 && existing.length > m) { <ide> existing.warned = true; <ide> const w = new Error('Possible EventEmitter memory leak detected. ' + <del> `${existing.length} ${type} listeners added. ` + <del> 'Use emitter.setMaxListeners() to increase limit'); <add> `${existing.length} ${String(type)} listeners ` + <add> 'added. Use emitter.setMaxListeners() to ' + <add> 'increase limit'); <ide> w.name = 'MaxListenersExceededWarning'; <ide> w.emitter = target; <ide> w.type = type; <ide><path>test/parallel/test-event-emitter-check-listener-leaks.js <ide> 'use strict'; <ide> require('../common'); <del>var assert = require('assert'); <del>var events = require('events'); <add>const assert = require('assert'); <add>const events = require('events'); <ide> <ide> var e = new events.EventEmitter(); <ide> <ide> assert.ok(!e._events['default'].hasOwnProperty('warned')); <ide> e.on('default', function() {}); <ide> assert.ok(e._events['default'].warned); <ide> <add>// symbol <add>const symbol = Symbol('symbol'); <add>e.setMaxListeners(1); <add>e.on(symbol, function() {}); <add>assert.ok(!e._events[symbol].hasOwnProperty('warned')); <add>e.on(symbol, function() {}); <add>assert.ok(e._events[symbol].hasOwnProperty('warned')); <add> <ide> // specific <ide> e.setMaxListeners(5); <ide> for (let i = 0; i < 5; i++) { <ide><path>test/parallel/test-event-emitter-max-listeners-warning-for-null.js <add>// Flags: --no-warnings <add>// The flag suppresses stderr output but the warning event will still emit <add>'use strict'; <add> <add>const common = require('../common'); <add>const events = require('events'); <add>const assert = require('assert'); <add> <add>const e = new events.EventEmitter(); <add>e.setMaxListeners(1); <add> <add>process.on('warning', common.mustCall((warning) => { <add> assert.ok(warning instanceof Error); <add> assert.strictEqual(warning.name, 'MaxListenersExceededWarning'); <add> assert.strictEqual(warning.emitter, e); <add> assert.strictEqual(warning.count, 2); <add> assert.strictEqual(warning.type, null); <add> assert.ok(warning.message.includes('2 null listeners added.')); <add>})); <add> <add>e.on(null, function() {}); <add>e.on(null, function() {}); <ide><path>test/parallel/test-event-emitter-max-listeners-warning-for-symbol.js <add>// Flags: --no-warnings <add>// The flag suppresses stderr output but the warning event will still emit <add>'use strict'; <add> <add>const common = require('../common'); <add>const events = require('events'); <add>const assert = require('assert'); <add> <add>const symbol = Symbol('symbol'); <add> <add>const e = new events.EventEmitter(); <add>e.setMaxListeners(1); <add> <add>process.on('warning', common.mustCall((warning) => { <add> assert.ok(warning instanceof Error); <add> assert.strictEqual(warning.name, 'MaxListenersExceededWarning'); <add> assert.strictEqual(warning.emitter, e); <add> assert.strictEqual(warning.count, 2); <add> assert.strictEqual(warning.type, symbol); <add> assert.ok(warning.message.includes('2 Symbol(symbol) listeners added.')); <add>})); <add> <add>e.on(symbol, function() {}); <add>e.on(symbol, function() {}); <ide><path>test/parallel/test-event-emitter-max-listeners-warning.js <ide> process.on('warning', common.mustCall((warning) => { <ide> assert.strictEqual(warning.emitter, e); <ide> assert.strictEqual(warning.count, 2); <ide> assert.strictEqual(warning.type, 'event-type'); <add> assert.ok(warning.message.includes('2 event-type listeners added.')); <ide> })); <ide> <ide> e.on('event-type', function() {});
5
PHP
PHP
fix typehints in basic auth adapter
e2646b06332b934bcf93d1cc342b6c88a88bd84f
<ide><path>src/Http/Client/Auth/Basic.php <ide> */ <ide> namespace Cake\Http\Client\Auth; <ide> <del>use Cake\Network\Http\Request; <add>use Cake\Http\Client\Request; <ide> <ide> /** <ide> * Basic authentication adapter for Cake\Network\Http\Client
1
Python
Python
pass flake8 tests
4adf3b9492d2b9f6c049e302c853049d62583a31
<ide><path>other/password_generator.py <ide> password = ''.join(random.choice(chars) for x in range(random.randint(min_length, max_length))) <ide> print('Password: ' + password) <ide> print('[ If you are thinking of using this passsword, You better save it. ]') <add> <add> <ide> # ALTERNATIVE METHODS <ide> # ctbi= characters that must be in password <ide> # i= how many letters or characters the password length will be <ide> def password_generator(ctbi, i): <ide> # Password generator = full boot with random_number, random_letters, and random_character FUNCTIONS <add> pass # Put your code here... <add> <add> <ide> def random_number(ctbi, i): <del> <del> <del> <add> pass # Put your code here... <add> <add> <ide> def random_letters(ctbi, i): <del> <del> <del> <add> pass # Put your code here... <add> <add> <ide> def random_characters(ctbi, i): <add> pass # Put your code here...
1
Go
Go
add refcounts to graphdrivers that use fsdiff
7342060b070df67481f8da4f394a57cac1671d56
<ide><path>daemon/graphdriver/counter.go <add>package graphdriver <add> <add>import "sync" <add> <add>// RefCounter is a generic counter for use by graphdriver Get/Put calls <add>type RefCounter struct { <add> counts map[string]int <add> mu sync.Mutex <add>} <add> <add>// NewRefCounter returns a new RefCounter <add>func NewRefCounter() *RefCounter { <add> return &RefCounter{counts: make(map[string]int)} <add>} <add> <add>// Increment increaes the ref count for the given id and returns the current count <add>func (c *RefCounter) Increment(id string) int { <add> c.mu.Lock() <add> c.counts[id]++ <add> count := c.counts[id] <add> c.mu.Unlock() <add> return count <add>} <add> <add>// Decrement decreases the ref count for the given id and returns the current count <add>func (c *RefCounter) Decrement(id string) int { <add> c.mu.Lock() <add> c.counts[id]-- <add> count := c.counts[id] <add> c.mu.Unlock() <add> return count <add>} <ide><path>daemon/graphdriver/devmapper/driver.go <ide> type Driver struct { <ide> home string <ide> uidMaps []idtools.IDMap <ide> gidMaps []idtools.IDMap <add> ctr *graphdriver.RefCounter <ide> } <ide> <ide> // Init creates a driver with the given home and the set of options. <ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap <ide> home: home, <ide> uidMaps: uidMaps, <ide> gidMaps: gidMaps, <add> ctr: graphdriver.NewRefCounter(), <ide> } <ide> <ide> return graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps), nil <ide> func (d *Driver) Remove(id string) error { <ide> // Get mounts a device with given id into the root filesystem <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> mp := path.Join(d.home, "mnt", id) <add> if count := d.ctr.Increment(id); count > 1 { <add> return mp, nil <add> } <ide> <ide> uid, gid, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps) <ide> if err != nil { <add> d.ctr.Decrement(id) <ide> return "", err <ide> } <add> <ide> // Create the target directories if they don't exist <ide> if err := idtools.MkdirAllAs(path.Join(d.home, "mnt"), 0755, uid, gid); err != nil && !os.IsExist(err) { <add> d.ctr.Decrement(id) <ide> return "", err <ide> } <ide> if err := idtools.MkdirAs(mp, 0755, uid, gid); err != nil && !os.IsExist(err) { <add> d.ctr.Decrement(id) <ide> return "", err <ide> } <ide> <ide> // Mount the device <ide> if err := d.DeviceSet.MountDevice(id, mp, mountLabel); err != nil { <add> d.ctr.Decrement(id) <ide> return "", err <ide> } <ide> <ide> rootFs := path.Join(mp, "rootfs") <ide> if err := idtools.MkdirAllAs(rootFs, 0755, uid, gid); err != nil && !os.IsExist(err) { <add> d.ctr.Decrement(id) <ide> d.DeviceSet.UnmountDevice(id, mp) <ide> return "", err <ide> } <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> // Create an "id" file with the container/image id in it to help reconstruct this in case <ide> // of later problems <ide> if err := ioutil.WriteFile(idFile, []byte(id), 0600); err != nil { <add> d.ctr.Decrement(id) <ide> d.DeviceSet.UnmountDevice(id, mp) <ide> return "", err <ide> } <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> <ide> // Put unmounts a device and removes it. <ide> func (d *Driver) Put(id string) error { <add> if count := d.ctr.Decrement(id); count > 0 { <add> return nil <add> } <ide> mp := path.Join(d.home, "mnt", id) <ide> err := d.DeviceSet.UnmountDevice(id, mp) <ide> if err != nil { <ide><path>daemon/graphdriver/overlay/overlay.go <ide> type Driver struct { <ide> pathCache map[string]string <ide> uidMaps []idtools.IDMap <ide> gidMaps []idtools.IDMap <add> ctr *graphdriver.RefCounter <ide> } <ide> <ide> var backingFs = "<unknown>" <ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap <ide> pathCache: make(map[string]string), <ide> uidMaps: uidMaps, <ide> gidMaps: gidMaps, <add> ctr: graphdriver.NewRefCounter(), <ide> } <ide> <ide> return NaiveDiffDriverWithApply(d, uidMaps, gidMaps), nil <ide> func (d *Driver) Get(id string, mountLabel string) (string, error) { <ide> workDir := path.Join(dir, "work") <ide> mergedDir := path.Join(dir, "merged") <ide> <add> if count := d.ctr.Increment(id); count > 1 { <add> return mergedDir, nil <add> } <add> <ide> opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir) <ide> <ide> // if it's mounted already, just return <ide> mounted, err := d.mounted(mergedDir) <ide> if err != nil { <add> d.ctr.Decrement(id) <ide> return "", err <ide> } <ide> if mounted { <add> d.ctr.Decrement(id) <ide> return mergedDir, nil <ide> } <ide> <ide> if err := syscall.Mount("overlay", mergedDir, "overlay", 0, label.FormatMountLabel(opts, mountLabel)); err != nil { <add> d.ctr.Decrement(id) <ide> return "", fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err) <ide> } <ide> // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a <ide> // user namespace requires this to move a directory from lower to upper. <ide> rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps) <ide> if err != nil { <add> d.ctr.Decrement(id) <add> syscall.Unmount(mergedDir, 0) <ide> return "", err <ide> } <ide> <ide> if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil { <add> d.ctr.Decrement(id) <add> syscall.Unmount(mergedDir, 0) <ide> return "", err <ide> } <ide> <ide> func (d *Driver) mounted(dir string) (bool, error) { <ide> <ide> // Put unmounts the mount path created for the give id. <ide> func (d *Driver) Put(id string) error { <add> if count := d.ctr.Decrement(id); count > 0 { <add> return nil <add> } <ide> d.pathCacheLock.Lock() <ide> mountpoint, exists := d.pathCache[id] <ide> d.pathCacheLock.Unlock() <ide><path>daemon/graphdriver/zfs/zfs.go <ide> func Init(base string, opt []string, uidMaps, gidMaps []idtools.IDMap) (graphdri <ide> filesystemsCache: filesystemsCache, <ide> uidMaps: uidMaps, <ide> gidMaps: gidMaps, <add> ctr: graphdriver.NewRefCounter(), <ide> } <ide> return graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps), nil <ide> } <ide> type Driver struct { <ide> filesystemsCache map[string]bool <ide> uidMaps []idtools.IDMap <ide> gidMaps []idtools.IDMap <add> ctr *graphdriver.RefCounter <ide> } <ide> <ide> func (d *Driver) String() string { <ide> func (d *Driver) Remove(id string) error { <ide> // Get returns the mountpoint for the given id after creating the target directories if necessary. <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> mountpoint := d.mountPath(id) <add> if count := d.ctr.Increment(id); count > 1 { <add> return mountpoint, nil <add> } <add> <ide> filesystem := d.zfsPath(id) <ide> options := label.FormatMountLabel("", mountLabel) <ide> logrus.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, options) <ide> <ide> rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps) <ide> if err != nil { <add> d.ctr.Decrement(id) <ide> return "", err <ide> } <ide> // Create the target directories if they don't exist <ide> if err := idtools.MkdirAllAs(mountpoint, 0755, rootUID, rootGID); err != nil { <add> d.ctr.Decrement(id) <ide> return "", err <ide> } <ide> <ide> if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil { <add> d.ctr.Decrement(id) <ide> return "", fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err) <ide> } <add> <ide> // this could be our first mount after creation of the filesystem, and the root dir may still have root <ide> // permissions instead of the remapped root uid:gid (if user namespaces are enabled): <ide> if err := os.Chown(mountpoint, rootUID, rootGID); err != nil { <add> mount.Unmount(mountpoint) <add> d.ctr.Decrement(id) <ide> return "", fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err) <ide> } <ide> <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> <ide> // Put removes the existing mountpoint for the given id if it exists. <ide> func (d *Driver) Put(id string) error { <add> if count := d.ctr.Decrement(id); count > 0 { <add> return nil <add> } <ide> mountpoint := d.mountPath(id) <ide> mounted, err := graphdriver.Mounted(graphdriver.FsMagicZfs, mountpoint) <ide> if err != nil || !mounted {
4
Text
Text
fix a typo in docs/basics/usagewithreact.md
070f0659928b91ffabb550bcc4982a0b63c72b6e
<ide><path>docs/basics/UsageWithReact.md <ide> I see the following presentational components and their props emerge from this b <ide> - `onTodoClick(id: number)` is a callback to invoke when a todo is clicked. <ide> * **`Todo`** is a single todo item. <ide> - `text: string` is the text to show. <del> - `completed: boolean` is whether todo should appear crossed out. <del> - `onClick()` is a callback to invoke when a todo is clicked. <add> - `completed: boolean` is whether the todo should appear crossed out. <add> - `onClick()` is a callback to invoke when the todo is clicked. <ide> * **`Link`** is a link with a callback. <del> - `onClick()` is a callback to invoke when link is clicked. <add> - `onClick()` is a callback to invoke when the link is clicked. <ide> * **`Footer`** is where we let the user change currently visible todos. <ide> * **`App`** is the root component that renders everything else. <ide>
1
Javascript
Javascript
avoid empty fixture in fs test
de8ef3f954622422ddb41775c06b278f0c8361a5
<ide><path>test/parallel/test-fs-error-messages.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> const fixtures = require('../common/fixtures'); <add>const tmpdir = require('../common/tmpdir'); <ide> const assert = require('assert'); <ide> const fs = require('fs'); <add> <add>tmpdir.refresh(); <add> <ide> const nonexistentFile = fixtures.path('non-existent'); <ide> const nonexistentDir = fixtures.path('non-existent', 'foo', 'bar'); <ide> const existingFile = fixtures.path('exit.js'); <ide> const existingFile2 = fixtures.path('create-file.js'); <del>const existingDir = fixtures.path('empty'); <add>const existingDir = tmpdir.path; <ide> const existingDir2 = fixtures.path('keys'); <ide> const { COPYFILE_EXCL } = fs.constants; <ide> const uv = process.binding('uv');
1
Ruby
Ruby
update xcode chceck
126b1c77e36cc2336f26dcaef4512418353b5562
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_for_latest_xcode <ide> latest_xcode = case MacOS.version <ide> when 10.5 then "3.1.4" <ide> when 10.6 then "3.2.6" <del> else "4.3" <add> when 10.7 then "4.3.3" <add> else nil <add> end <add> if latest_xcode.nil? <add> return <<-EOS.undent <add> Not sure what version of Xcode is the latest for OS X #{MacOS.version}. <add> EOS <ide> end <ide> if MacOS.xcode_installed? and MacOS.xcode_version < latest_xcode then <<-EOS.undent <ide> You have Xcode-#{MacOS.xcode_version}, which is outdated.
1
PHP
PHP
add returntypewillchange to count method
1638472a7a5ee02dc9e808bc203b733785ac1468
<ide><path>src/Illuminate/Database/Eloquent/Factories/Sequence.php <ide> public function __construct(...$sequence) <ide> * <ide> * @return int <ide> */ <add> #[\ReturnTypeWillChange] <ide> public function count() <ide> { <ide> return $this->count;
1
Ruby
Ruby
set exit code to failed always
92e68049d1e09757d498021426a650dfc6405cc3
<ide><path>Library/Homebrew/formula_installer.rb <ide> def link(keg) <ide> onoe "Failed to create #{f.opt_prefix}" <ide> puts "Things that depend on #{f.name} will probably not build." <ide> puts e <add> Homebrew.failed = true <ide> end <ide> return <ide> end <ide> def link(keg) <ide> mode = OpenStruct.new(:dry_run => true, :overwrite => true) <ide> keg.link(mode) <ide> @show_summary_heading = true <add> Homebrew.failed = true <ide> rescue Keg::LinkError => e <ide> onoe "The `brew link` step did not complete successfully" <ide> puts "The formula built, but is not symlinked into #{HOMEBREW_PREFIX}" <ide> def link(keg) <ide> puts "You can try again using:" <ide> puts " brew link #{f.name}" <ide> @show_summary_heading = true <add> Homebrew.failed = true <ide> rescue Exception => e <ide> onoe "An unexpected error occurred during the `brew link` step" <ide> puts "The formula built, but is not symlinked into #{HOMEBREW_PREFIX}" <ide> puts e <ide> puts e.backtrace if debug? <ide> @show_summary_heading = true <ide> ignore_interrupts { keg.unlink } <add> Homebrew.failed = true <ide> raise <ide> end <ide> end <ide> def install_plist <ide> rescue Exception => e <ide> onoe "Failed to install plist file" <ide> ohai e, e.backtrace if debug? <add> Homebrew.failed = true <ide> end <ide> <ide> def fix_install_names(keg) <ide> def fix_install_names(keg) <ide> puts "The formula built, but you may encounter issues using it or linking other" <ide> puts "formula against it." <ide> ohai e, e.backtrace if debug? <add> Homebrew.failed = true <ide> @show_summary_heading = true <ide> end <ide> <ide> def clean <ide> opoo "The cleaning step did not complete successfully" <ide> puts "Still, the installation was successful, so we will link it into your prefix" <ide> ohai e, e.backtrace if debug? <add> Homebrew.failed = true <ide> @show_summary_heading = true <ide> end <ide> <ide> def post_install <ide> opoo "The post-install step did not complete successfully" <ide> puts "You can try again using `brew postinstall #{f.name}`" <ide> ohai e, e.backtrace if debug? <add> Homebrew.failed = true <ide> @show_summary_heading = true <ide> end <ide>
1
Text
Text
add proposed rfc 'updateable bundled packages'
f05a8b8e5e21ced254f9c075de7a0981ff634597
<ide><path>docs/rfcs/001-updateable-bundled-packages.md <add># Updateable Bundled Packages <add> <add>## Status <add> <add>Proposed <add> <add>## Summary <add> <add>> One paragraph explanation of the feature. <add> <add>This feature will enable an opt-in subset of bundled Atom packages to be updated with `apm` outside of the Atom release cycle. This will enable users to receive new functionality and bug fixes for some bundled packages as regularly as needed without waiting for them to be included in a new Atom release. This is especially important for packages like [GitHub](https://github.com/atom/github/) and [Teletype](https://github.com/atom/teletype/) which provide essential Atom functionality and could be improved independently of Atom. <add> <add>## Motivation <add> <add>> Why are we doing this? What use cases does it support? What is the expected outcome? <add> <add>Atom currently uses a monthly release cycle with staged Stable and Beta releases so that major issues get caught early in Beta before reaching the Stable release. Because Atom releases updates monthly, this means that a new feature merged into `master` right after a new Atom release could take one month to reach the next Beta and then another month to reach Stable. <add> <add>Since a large part of Atom's built-in functionality is provided by bundled packages, it makes sense to allow some of those packages to be updated independently of Atom's monthly release cycle so that users can receive new features and fixes whenever they become available. <add> <add>The primary use case for this improvement is enabling the GitHub package to ship improvements more frequently than Atom's release cycle since many of its improvements can be done without changes to Atom itself. If this approach is proven to work well for the GitHub package, we might also consider using it to ship Teletype as a bundled Atom package. <add> <add>## Explanation <add> <add>> Explain the proposal as if it was already implemented in Atom and you were describing it to an Atom user. That generally means: <add>> - Introducing new named concepts. <add>> - Explaining the feature largely in terms of examples. <add>> - Explaining any changes to existing workflows. <add> <add>Bundled packages are treated differently than community packages that you can install using `apm`: <add> <add>- You are not prompted to update them when new versions are released on `apm` <add>- `apm` will warn you at the command line when you try to install or update a bundled package <add>- If a user intentionally installs a bundled package from `apm` the [Dalek package](https://github.com/atom/dalek/) will show a warning in the "deprecations" view asking the user to remove the offending package <add> <add>Despite all this, if the user *does* install a bundled package using `apm`, it will be loaded into the editor and updated dutifully as releases occur. <add> <add>### Implementation Details <add> <add>Because the necessary infrastructure is already in place to enable updates to bundled packages using `apm`, the only work required is to provide a way for packages to opt in to this behavior and for `apm` to include those packages in its update checks if they haven't already been installed in the user's packages folder. <add> <add>Any bundled Atom package will be able to opt in to updates by adding `"updateable": true` to its `package.json` file. This will cause `apm` to consider it as part of the list of packages it checks for updates. If a community (non-bundled) package sets this field to `true` or `false` it will be ignored as it's only relevant to bundled packages. <add> <add>`apm` will be updated to include the list of bundled packages with `"updateable": true` set in their `package.json` so that the user will be notified of new package versions that support the engine version of their current Atom build. <add> <add>### User Experience Examples <add> <add>1. The user downloads Atom 1.28.0 from atom.io which includes GitHub package version 0.15.0. After Atom 1.28.0 was released, a hotfix release was shipped for the GitHub package as 0.15.1. When the user installs and starts Atom, they are prompted to install the update to the GitHub package. <add> <add>2. The user downloads and installs Atom 1.28.0 from atom.io which includes GitHub package version 0.15.0. Two weeks later, GitHub package 0.16.0 is released with a few new features. The user is prompted to update to the new version and gets the new features even though Atom 1.29.0 hasn't been released yet. <add> <add>3. In the future, a user has an old install of Atom 1.28.0 and waits a long time between installing Atom updates. The GitHub package releases version 0.25.0 but the user is not prompted to install it because the GitHub package has set `engines` in `package.json` to restrict to Atom 1.32.0 and above. <add> <add>### Rules for Updateable Bundled Packages <add> <add>Any package that opts into this behavior must follow one rule: **its `engines` field must be regularly updated to reflect the necessary Atom version for the Atom, Electron, and Node.js APIs used in the package**. This field defines the range of Atom versions in which the package is expected to work. The field should always be set to the lowest possible Atom version that the package supports. <add> <add>If a package wants to use API features of a newer version of Atom while still supporting older Atom versions, it must do so in a way that is aware of the user's version and adjust itself accordingly. <add> <add>## Drawbacks <add> <add>> Why should we *not* do this? <add> <add>The primary drawback of this approach is that updateable bundled packages might exhibit problems on older Atom versions due to missing or changed APIs in Atom, Electron, or Node.js. The solution for these packages is to keep their `engines` field updated appropriately, but there's still a chance that some updates will slip through without the necessary engine version changes. <add> <add>One other possible drawback is that an updated version of a bundled package might not be compatible across two different Atom channels. For example, if the user installs a new update to a bundled package that only supports the current Atom Beta release or higher, the user will no longer have access to that package if they open Atom Stable. <add> <add>However, this drawback is no different than what the user would face today installing a community package under the same circumstances, so this could be considered a general problem in the Atom package ecosystem. <add> <add>## Rationale and alternatives <add> <add>> - Why is this approach the best in the space of possible approaches? <add>> - What other approaches have been considered and what is the rationale for not choosing them? <add>> - What is the impact of not doing this? <add> <add>This is the best approach for updating bundled packages because it allows those packages to take control of their own release cycle so long as they manage their Atom engine version correctly. It also does so in a way that allows us to decide which packages can be updated independently, reducing the likelihood of problems for users. <add> <add>The primary alternative to this approach is to speed up the Atom release cycle so that bundled Atom package updates will reach users more frequently. This approach will be investigated independently of this RFC as it may still be valuable even with updateable bundled packages. <add> <add>## Unresolved questions <add> <add>> - What unresolved questions do you expect to resolve through the RFC process before this gets merged? <add> <add>Is it enough to just depend on the `engines` field of `package.json` to protect users from installing a package update that doesn't work with their version of Atom? <add> <add>Is `updateable` the right name for the field in `package.json`? Is there a clearer name? <add> <add>> - What unresolved questions do you expect to resolve through the implementation of this feature before it is released in a new version of Atom? <add> <add>Can package authors ship updates to stable-only and beta-only versions of their packages simultaneously? For example, can the GitHub package keep shipping hotfixes to 0.14.x which targets Atom >=1.27.0 while also shipping updates to 0.15.x which targets >=1.28.0? <add> <add>> - What related issues do you consider out of scope for this RFC that could be addressed in the future independently of the solution that comes out of this RFC? <add> <add>One issue that's out of scope for this RFC is how we ship new features and fixes to the core components of Atom (not its bundled packages) more frequently. There are two options we can investigate to accomplish this: <add> <add>- **Ship Atom updates more frequently, possibly every two weeks** <add> <add>- **Introduce a channel for nightly builds which surface the latest changes every day** <add> <add>Both of these possibilities will be covered in future RFCs as they could be implemented independently of the feature described in this RFC.
1
Java
Java
fix typos in javadoc in assertthrows
cb59d43a5fea8e541f30bb40b39e2c01ec8fcbc7
<ide><path>spring-test/src/main/java/org/springframework/test/AssertThrows.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * test will also fail, this time with a message similar to the following: <ide> * <ide> * <pre class="code"> <del> * "junit.framework.AssertionFailedError: Was expecting a [class java.lang.UnsupportedOperationException] to be thrown, but instead a [class java.lang.IllegalArgumentException] was thrown"</pre> <add> * "java.lang.AssertionError: Was expecting a [class java.lang.UnsupportedOperationException] to be thrown, but instead a [class java.lang.IllegalArgumentException] was thrown"</pre> <ide> * <ide> * The test for the correct {@link Exception} respects polymorphism, <ide> * so you can test that any old {@link Exception} is thrown like so: <ide> protected String getFailureMessage() { <ide> * Subclass must override this {@code abstract} method and <ide> * provide the test logic. <ide> * @throws Exception if an error occurs during the execution of the <del> * aformentioned test logic <add> * aforementioned test logic <ide> */ <ide> public abstract void test() throws Exception; <ide> <ide> public void runTest() { <ide> * {@link java.lang.Exception} is <b>not</b> thrown. <ide> * <p>The default implementation simply fails the test via a call to <ide> * {@link org.junit.Assert#fail(String)}. <del> * <p>If you want to customise the failure message, consider overriding <add> * <p>If you want to customize the failure message, consider overriding <ide> * {@link #createMessageForNoExceptionThrown()}, and / or supplying an <ide> * extra, contextual failure message via the appropriate constructor overload. <ide> * @see #getFailureMessage() <ide> protected String createMessageForNoExceptionThrown() { <ide> * {@link Exception} that was thrown in the body of a test is <ide> * an instance of the {@link #getExpectedException()} class (or an <ide> * instance of a subclass). <del> * <p>If you want to customise the failure message, consider overriding <add> * <p>If you want to customize the failure message, consider overriding <ide> * {@link #createMessageForWrongThrownExceptionType(Exception)}. <ide> * @param actualException the {@link Exception} that has been thrown <ide> * in the body of a test method (will never be {@code null})
1
Go
Go
use unique names for container/rename_test.go
90b514922bb6405bc06428702b1a55bb248bdac3
<ide><path>integration/container/rename_test.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <add> containertypes "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/api/types/network" <ide> "github.com/docker/docker/integration/internal/container" <ide> "github.com/docker/docker/integration/internal/request" <ide> func TestRenameLinkedContainer(t *testing.T) { <ide> ctx := context.Background() <ide> client := request.NewAPIClient(t) <ide> <del> aID := container.Run(t, ctx, client, container.WithName("a0")) <del> bID := container.Run(t, ctx, client, container.WithName("b0"), container.WithLinks("a0")) <add> aName := "a0" + t.Name() <add> bName := "b0" + t.Name() <add> aID := container.Run(t, ctx, client, container.WithName(aName)) <add> bID := container.Run(t, ctx, client, container.WithName(bName), container.WithLinks(aName)) <ide> <del> err := client.ContainerRename(ctx, aID, "a1") <add> err := client.ContainerRename(ctx, aID, "a1"+t.Name()) <ide> assert.NilError(t, err) <ide> <del> container.Run(t, ctx, client, container.WithName("a0")) <add> container.Run(t, ctx, client, container.WithName(aName)) <ide> <ide> err = client.ContainerRemove(ctx, bID, types.ContainerRemoveOptions{Force: true}) <ide> assert.NilError(t, err) <ide> <del> bID = container.Run(t, ctx, client, container.WithName("b0"), container.WithLinks("a0")) <add> bID = container.Run(t, ctx, client, container.WithName(bName), container.WithLinks(aName)) <ide> <ide> inspect, err := client.ContainerInspect(ctx, bID) <ide> assert.NilError(t, err) <del> assert.Check(t, is.DeepEqual([]string{"/a0:/b0/a0"}, inspect.HostConfig.Links)) <add> assert.Check(t, is.DeepEqual([]string{"/" + aName + ":/" + bName + "/" + aName}, inspect.HostConfig.Links)) <ide> } <ide> <ide> func TestRenameStoppedContainer(t *testing.T) { <ide> defer setupTest(t)() <ide> ctx := context.Background() <ide> client := request.NewAPIClient(t) <ide> <del> oldName := "first_name" <add> oldName := "first_name" + t.Name() <ide> cID := container.Run(t, ctx, client, container.WithName(oldName), container.WithCmd("sh")) <ide> poll.WaitOn(t, container.IsInState(ctx, client, cID, "exited"), poll.WithDelay(100*time.Millisecond)) <ide> <ide> func TestRenameRunningContainerAndReuse(t *testing.T) { <ide> ctx := context.Background() <ide> client := request.NewAPIClient(t) <ide> <del> oldName := "first_name" <add> oldName := "first_name" + t.Name() <ide> cID := container.Run(t, ctx, client, container.WithName(oldName)) <ide> poll.WaitOn(t, container.IsInState(ctx, client, cID, "running"), poll.WithDelay(100*time.Millisecond)) <ide> <ide> func TestRenameInvalidName(t *testing.T) { <ide> ctx := context.Background() <ide> client := request.NewAPIClient(t) <ide> <del> oldName := "first_name" <add> oldName := "first_name" + t.Name() <ide> cID := container.Run(t, ctx, client, container.WithName(oldName)) <ide> poll.WaitOn(t, container.IsInState(ctx, client, cID, "running"), poll.WithDelay(100*time.Millisecond)) <ide> <ide> func TestRenameAnonymousContainer(t *testing.T) { <ide> ctx := context.Background() <ide> client := request.NewAPIClient(t) <ide> <del> _, err := client.NetworkCreate(ctx, "network1", types.NetworkCreate{}) <add> networkName := "network1" + t.Name() <add> _, err := client.NetworkCreate(ctx, networkName, types.NetworkCreate{}) <add> <ide> assert.NilError(t, err) <ide> cID := container.Run(t, ctx, client, func(c *container.TestContainerConfig) { <ide> c.NetworkingConfig.EndpointsConfig = map[string]*network.EndpointSettings{ <del> "network1": {}, <add> networkName: {}, <ide> } <del> c.HostConfig.NetworkMode = "network1" <add> c.HostConfig.NetworkMode = containertypes.NetworkMode(networkName) <ide> }) <del> err = client.ContainerRename(ctx, cID, "container1") <add> <add> container1Name := "container1" + t.Name() <add> err = client.ContainerRename(ctx, cID, container1Name) <ide> assert.NilError(t, err) <ide> // Stop/Start the container to get registered <ide> // FIXME(vdemeester) this is a really weird behavior as it fails otherwise <del> err = client.ContainerStop(ctx, "container1", nil) <add> err = client.ContainerStop(ctx, container1Name, nil) <ide> assert.NilError(t, err) <del> err = client.ContainerStart(ctx, "container1", types.ContainerStartOptions{}) <add> err = client.ContainerStart(ctx, container1Name, types.ContainerStartOptions{}) <ide> assert.NilError(t, err) <ide> <ide> poll.WaitOn(t, container.IsInState(ctx, client, cID, "running"), poll.WithDelay(100*time.Millisecond)) <ide> func TestRenameAnonymousContainer(t *testing.T) { <ide> } <ide> cID = container.Run(t, ctx, client, func(c *container.TestContainerConfig) { <ide> c.NetworkingConfig.EndpointsConfig = map[string]*network.EndpointSettings{ <del> "network1": {}, <add> networkName: {}, <ide> } <del> c.HostConfig.NetworkMode = "network1" <del> }, container.WithCmd("ping", count, "1", "container1")) <add> c.HostConfig.NetworkMode = containertypes.NetworkMode(networkName) <add> }, container.WithCmd("ping", count, "1", container1Name)) <ide> poll.WaitOn(t, container.IsInState(ctx, client, cID, "exited"), poll.WithDelay(100*time.Millisecond)) <ide> <ide> inspect, err := client.ContainerInspect(ctx, cID) <ide> func TestRenameContainerWithSameName(t *testing.T) { <ide> ctx := context.Background() <ide> client := request.NewAPIClient(t) <ide> <del> cID := container.Run(t, ctx, client, container.WithName("old")) <add> oldName := "old" + t.Name() <add> cID := container.Run(t, ctx, client, container.WithName(oldName)) <add> <ide> poll.WaitOn(t, container.IsInState(ctx, client, cID, "running"), poll.WithDelay(100*time.Millisecond)) <del> err := client.ContainerRename(ctx, "old", "old") <add> err := client.ContainerRename(ctx, oldName, oldName) <ide> testutil.ErrorContains(t, err, "Renaming a container with the same name") <del> err = client.ContainerRename(ctx, cID, "old") <add> err = client.ContainerRename(ctx, cID, oldName) <ide> testutil.ErrorContains(t, err, "Renaming a container with the same name") <ide> } <ide> <ide> func TestRenameContainerWithLinkedContainer(t *testing.T) { <ide> ctx := context.Background() <ide> client := request.NewAPIClient(t) <ide> <del> db1ID := container.Run(t, ctx, client, container.WithName("db1")) <add> db1Name := "db1" + t.Name() <add> db1ID := container.Run(t, ctx, client, container.WithName(db1Name)) <ide> poll.WaitOn(t, container.IsInState(ctx, client, db1ID, "running"), poll.WithDelay(100*time.Millisecond)) <ide> <del> app1ID := container.Run(t, ctx, client, container.WithName("app1"), container.WithLinks("db1:/mysql")) <add> app1Name := "app1" + t.Name() <add> app2Name := "app2" + t.Name() <add> app1ID := container.Run(t, ctx, client, container.WithName(app1Name), container.WithLinks(db1Name+":/mysql")) <ide> poll.WaitOn(t, container.IsInState(ctx, client, app1ID, "running"), poll.WithDelay(100*time.Millisecond)) <ide> <del> err := client.ContainerRename(ctx, "app1", "app2") <add> err := client.ContainerRename(ctx, app1Name, app2Name) <ide> assert.NilError(t, err) <ide> <del> inspect, err := client.ContainerInspect(ctx, "app2/mysql") <add> inspect, err := client.ContainerInspect(ctx, app2Name+"/mysql") <ide> assert.NilError(t, err) <ide> assert.Check(t, is.Equal(db1ID, inspect.ID)) <ide> }
1
Python
Python
improve german tokenization
d1f703d78d1fa20078787d8655addd4a31c7c6a4
<ide><path>spacy/lang/de/__init__.py <ide> <ide> from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS <ide> from .norm_exceptions import NORM_EXCEPTIONS <add>from .punctuation import TOKENIZER_PREFIXES, TOKENIZER_SUFFIXES <ide> from .punctuation import TOKENIZER_INFIXES <ide> from .tag_map import TAG_MAP <ide> from .stop_words import STOP_WORDS <ide> class GermanDefaults(Language.Defaults): <ide> Language.Defaults.lex_attr_getters[NORM], NORM_EXCEPTIONS, BASE_NORMS <ide> ) <ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) <add> prefixes = TOKENIZER_PREFIXES <add> suffixes = TOKENIZER_SUFFIXES <ide> infixes = TOKENIZER_INFIXES <ide> tag_map = TAG_MAP <ide> stop_words = STOP_WORDS <ide><path>spacy/lang/de/punctuation.py <ide> # coding: utf8 <ide> from __future__ import unicode_literals <ide> <del>from ..char_classes import LIST_ELLIPSES, LIST_ICONS <add>from ..char_classes import LIST_ELLIPSES, LIST_ICONS, LIST_PUNCT, LIST_QUOTES <add>from ..char_classes import LIST_CURRENCY, CURRENCY, UNITS, PUNCT <ide> from ..char_classes import CONCAT_QUOTES, ALPHA, ALPHA_LOWER, ALPHA_UPPER <add>from ..punctuation import _prefixes, _suffixes <ide> <ide> <add>_prefixes = ["``",] + list(_prefixes) <add> <add>_suffixes = ( <add> ["''", "/"] <add> + LIST_PUNCT <add> + LIST_ELLIPSES <add> + LIST_QUOTES <add> + LIST_ICONS <add> + [ <add> r"(?<=[0-9])\+", <add> r"(?<=°[FfCcKk])\.", <add> r"(?<=[0-9])(?:{c})".format(c=CURRENCY), <add> r"(?<=[0-9])(?:{u})".format(u=UNITS), <add> r"(?<=[{al}{e}{p}(?:{q})])\.".format( <add> al=ALPHA_LOWER, e=r"%²\-\+", q=CONCAT_QUOTES, p=PUNCT <add> ), <add> r"(?<=[{au}][{au}])\.".format(au=ALPHA_UPPER), <add> ] <add>) <add> <ide> _quotes = CONCAT_QUOTES.replace("'", "") <ide> <ide> _infixes = ( <ide> r"(?<=[{a}])[,!?](?=[{a}])".format(a=ALPHA), <ide> r"(?<=[{a}])[:<>=](?=[{a}])".format(a=ALPHA), <ide> r"(?<=[{a}]),(?=[{a}])".format(a=ALPHA), <add> r"(?<=[0-9{a}])\/(?=[0-9{a}])".format(a=ALPHA), <ide> r"(?<=[{a}])([{q}\)\]\(\[])(?=[{a}])".format(a=ALPHA, q=_quotes), <ide> r"(?<=[{a}])--(?=[{a}])".format(a=ALPHA), <ide> r"(?<=[0-9])-(?=[0-9])", <ide> ] <ide> ) <ide> <ide> <add>TOKENIZER_PREFIXES = _prefixes <add>TOKENIZER_SUFFIXES = _suffixes <ide> TOKENIZER_INFIXES = _infixes <ide><path>spacy/lang/de/tokenizer_exceptions.py <ide> <ide> <ide> for orth in [ <add> "``", <add> "''", <ide> "A.C.", <ide> "a.D.", <ide> "A.D.", <ide> "biol.", <ide> "Biol.", <ide> "ca.", <add> "CDU/CSU", <ide> "Chr.", <ide> "Cie.", <add> "c/o", <ide> "co.", <ide> "Co.", <add> "d'", <ide> "D.C.", <ide> "Dipl.-Ing.", <ide> "Dipl.", <ide> "i.G.", <ide> "i.Tr.", <ide> "i.V.", <add> "I.", <add> "II.", <add> "III.", <add> "IV.", <add> "Inc.", <ide> "Ing.", <ide> "jr.", <ide> "Jr.", <ide> "jun.", <ide> "jur.", <ide> "K.O.", <add> "L'", <ide> "L.A.", <ide> "lat.", <ide> "M.A.",
3
Text
Text
move changelog entry to the top
855c9897eb98ea4d77ec5036d15cdd1764698838
<ide><path>activejob/CHANGELOG.md <add>* While using `perform_enqueued_jobs` test helper enqueued jobs must be stored for the later check with <add> `assert_enqueued_with`. <add> <add> *Dmitry Polushkin* <add> <ide> * `ActiveJob::TestCase#perform_enqueued_jobs` without a block removes performed jobs from the queue. <ide> <ide> That way the helper can be called multiple times and not perform a job invocation multiple times. <ide> <ide> *Anthony Ross* <ide> <del>* While using `perform_enqueued_jobs` test helper enqueued jobs must be stored for the later check with `assert_enqueued_with`. <del> <del> *Dmitry Polushkin* <del> <ide> <ide> Please check [6-0-stable](https://github.com/rails/rails/blob/6-0-stable/activejob/CHANGELOG.md) for previous changes.
1
Text
Text
improve arabic translation
bea165b460c7875d9e5b21ad1835f30a3c2f55c2
<ide><path>guide/arabic/react/jsx/index.md <ide> localeTitle: JSX <ide> --- <ide> # JSX <ide> <del>> JSX مختصرة لـ JavaScript XML. <add>> JSX اختصاراً لـ JavaScript XML. <ide> <del>JSX هو تعبير يستخدم عبارات HTML صالحة داخل JavaScript. يمكنك تعيين هذا التعبير لمتغير واستخدامه في مكان آخر. يمكنك الجمع بين تعبيرات JavaScript سارية أخرى و JSX في عبارات HTML هذه من خلال وضعها ضمن أقواس ( `{}` ). تقوم بابل كذلك بتجميع JSX إلى كائن من النوع `React.createElement()` . <add>JSX هو تعبير يستخدم عبارات HTML صالحة داخل JavaScript. يمكنك تعيين هذا التعبير لمتغير واستخدامه في مكان آخر. يمكنك الجمع بين تعبيرات JavaScript سارية أخرى و JSX في عبارات HTML هذه من خلال وضعها ضمن أقواس ( `{}` ). تقوم Babel كذلك بتجميع JSX إلى مكوّن من النوع `React.createElement()` . <ide> <ide> ### تعبيرات أحادية السطر ومتعددة الأسطر <ide> <del>تعبير سطر مفرد سهل الاستخدام. <add>تعبير في سطر مفرد سهل الاستخدام. <ide> <ide> `const one = <h1>Hello World!</h1>; <ide> ` <ide> <del>عندما تحتاج إلى استخدام أسطر متعددة في تعبير JSX واحد ، اكتب الرمز داخل قوس واحد. <add>عندما تحتاج إلى استخدام أسطر متعددة في تعبير JSX واحد ، اكتب شفرتك داخل قوس واحد. <ide> <ide> `const two = ( <ide> <ul> <ide> JSX هو تعبير يستخدم عبارات HTML صالحة داخل JavaScrip <ide> ); <ide> ` <ide> <del>### باستخدام علامات HTML فقط <add>### بإمكانك استخدام علامات HTML فقط <ide> <ide> `const greet = <h1>Hello World!</h1>; <ide> ` <ide> <ide> ### الجمع بين تعبير JavaScript مع علامات HTML <ide> <del>يمكننا استخدام متغيرات جافا سكريبت في الأقواس. <add>يمكننا استخدام متغيرات JavaScript في الأقواس. <ide> <ide> `const who = "Quincy Larson"; <ide> const greet = <h1>Hello {who}!</h1>; <ide> JSX هو تعبير يستخدم عبارات HTML صالحة داخل JavaScrip <ide> <ide> ### يُسمح فقط بعلامة أصل واحدة <ide> <del>يجب أن يحتوي تعبير JSX على علامة رئيسية واحدة فقط. يمكننا إضافة عدة علامات متداخلة داخل العنصر الأصل فقط. <add>يجب أن يحيط تعبير JSX على عنصر رئيسي واحد فقط. يمكننا إضافة عدة علامات متداخلة داخل العنصر الأصل فقط. <ide> <ide> `// This is valid. <ide> const tags = ( <ide> JSX هو تعبير يستخدم عبارات HTML صالحة داخل JavaScrip <ide> <ide> ### معلومات اكثر <ide> <del>* [تقديم JSX](https://reactjs.org/docs/introducing-jsx.html) <ide>\ No newline at end of file <add>* [تقديم JSX](https://reactjs.org/docs/introducing-jsx.html)
1
Python
Python
add typehints ciphers and bool alg
9d745b6156636f9e3b35f1560ae9abec29d48772
<ide><path>boolean_algebra/quine_mc_cluskey.py <del>def compare_string(string1, string2): <add>def compare_string(string1: str, string2: str) -> str: <ide> """ <ide> >>> compare_string('0010','0110') <ide> '0_10' <ide> def compare_string(string1, string2): <ide> return "".join(l1) <ide> <ide> <del>def check(binary): <add>def check(binary: [str]) -> [str]: <ide> """ <ide> >>> check(['0.00.01.5']) <ide> ['0.00.01.5'] <ide> def check(binary): <ide> binary = list(set(temp)) <ide> <ide> <del>def decimal_to_binary(no_of_variable, minterms): <add>def decimal_to_binary(no_of_variable: int, minterms: [float]) -> [str]: <ide> """ <ide> >>> decimal_to_binary(3,[1.5]) <ide> ['0.00.01.5'] <ide> def decimal_to_binary(no_of_variable, minterms): <ide> return temp <ide> <ide> <del>def is_for_table(string1, string2, count): <add>def is_for_table(string1: str, string2: str, count: int) -> bool: <ide> """ <ide> >>> is_for_table('__1','011',2) <ide> True <ide> def is_for_table(string1, string2, count): <ide> return False <ide> <ide> <del>def selection(chart, prime_implicants): <add>def selection(chart: [[int]], prime_implicants: [str]) -> [str]: <ide> """ <ide> >>> selection([[1]],['0.00.01.5']) <ide> ['0.00.01.5'] <ide> def selection(chart, prime_implicants): <ide> chart[j][i] = 0 <ide> <ide> <del>def prime_implicant_chart(prime_implicants, binary): <add>def prime_implicant_chart(prime_implicants: [str], binary: [str]) -> [[int]]: <ide> """ <ide> >>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5']) <ide> [[1]] <ide><path>ciphers/affine_cipher.py <ide> def main(): <ide> print(f"\n{mode.title()}ed text: \n{translated}") <ide> <ide> <del>def check_keys(keyA, keyB, mode): <add>def check_keys(keyA: int, keyB: int, mode: str) -> None: <ide> if mode == "encrypt": <ide> if keyA == 1: <ide> sys.exit( <ide> def decrypt_message(key: int, message: str) -> str: <ide> return plainText <ide> <ide> <del>def get_random_key(): <add>def get_random_key() -> int: <ide> while True: <ide> keyA = random.randint(2, len(SYMBOLS)) <ide> keyB = random.randint(2, len(SYMBOLS)) <ide><path>ciphers/base64_cipher.py <del>def encode_base64(text): <add>def encode_base64(text: str) -> str: <ide> r""" <ide> >>> encode_base64('WELCOME to base64 encoding 😁') <ide> 'V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ==' <ide> def encode_base64(text): <ide> return r[0 : len(r) - len(p)] + p <ide> <ide> <del>def decode_base64(text): <add>def decode_base64(text: str) -> str: <ide> r""" <ide> >>> decode_base64('V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ==') <ide> 'WELCOME to base64 encoding 😁' <ide><path>ciphers/brute_force_caesar_cipher.py <del>def decrypt(message): <add>def decrypt(message: str) -> None: <ide> """ <ide> >>> decrypt('TMDETUX PMDVU') <ide> Decryption using Key #0: TMDETUX PMDVU <ide><path>ciphers/cryptomath_module.py <del>def gcd(a, b): <add>def gcd(a: int, b: int) -> int: <ide> while a != 0: <ide> a, b = b % a, a <ide> return b <ide> <ide> <del>def findModInverse(a, m): <add>def findModInverse(a: int, m: int) -> int: <ide> if gcd(a, m) != 1: <ide> return None <ide> u1, u2, u3 = 1, 0, a <ide><path>ciphers/decrypt_caesar_with_chi_squared.py <ide> #!/usr/bin/env python3 <ide> <add>from typing import Tuple <add> <ide> <ide> def decrypt_caesar_with_chi_squared( <ide> ciphertext: str, <del> cipher_alphabet=None, <del> frequencies_dict=None, <add> cipher_alphabet: str = None, <add> frequencies_dict: str = None, <ide> case_sensetive: bool = False, <del>) -> tuple: <add>) -> Tuple[int, float, str]: <ide> """ <ide> Basic Usage <ide> =========== <ide><path>ciphers/deterministic_miller_rabin.py <ide> """ <ide> <ide> <del>def miller_rabin(n, allow_probable=False): <add>def miller_rabin(n: int, allow_probable: bool = False) -> bool: <ide> """Deterministic Miller-Rabin algorithm for primes ~< 3.32e24. <ide> <ide> Uses numerical analysis results to return whether or not the passed number <ide> def miller_rabin(n, allow_probable=False): <ide> return True <ide> <ide> <del>def test_miller_rabin(): <add>def test_miller_rabin() -> None: <ide> """Testing a nontrivial (ends in 1, 3, 7, 9) composite <ide> and a prime in each range. <ide> """ <ide><path>ciphers/diffie.py <del>def find_primitive(n): <add>def find_primitive(n: int) -> int: <ide> for r in range(1, n): <ide> li = [] <ide> for x in range(n - 1): <ide><path>ciphers/elgamal_key_generator.py <ide> def main(): <ide> # so I used 4.80 Algorithm in <ide> # Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996) <ide> # and it seems to run nicely! <del>def primitiveRoot(p_val): <add>def primitiveRoot(p_val: int) -> int: <ide> print("Generating primitive root of p") <ide> while True: <ide> g = random.randrange(3, p_val) <ide> def primitiveRoot(p_val): <ide> return g <ide> <ide> <del>def generateKey(keySize): <add>def generateKey(keySize: int) -> ((int, int, int, int), (int, int)): <ide> print("Generating prime p...") <ide> p = rabinMiller.generateLargePrime(keySize) # select large prime number. <ide> e_1 = primitiveRoot(p) # one primitive root on modulo p. <ide> def generateKey(keySize): <ide> return publicKey, privateKey <ide> <ide> <del>def makeKeyFiles(name, keySize): <add>def makeKeyFiles(name: str, keySize: int): <ide> if os.path.exists("%s_pubkey.txt" % name) or os.path.exists( <ide> "%s_privkey.txt" % name <ide> ): <ide><path>ciphers/hill_cipher.py <ide> class HillCipher: <ide> <ide> to_int = numpy.vectorize(lambda x: round(x)) <ide> <del> def __init__(self, encrypt_key): <add> def __init__(self, encrypt_key: int): <ide> """ <ide> encrypt_key is an NxN numpy array <ide> """ <ide><path>ciphers/mixed_keyword_cypher.py <del>def mixed_keyword(key="college", pt="UNIVERSITY"): <add>def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str: <ide> """ <ide> <ide> For key:hello <ide><path>ciphers/morse_code_implementation.py <ide> } <ide> <ide> <del>def encrypt(message): <add>def encrypt(message: str) -> str: <ide> cipher = "" <ide> for letter in message: <ide> if letter != " ": <ide> def encrypt(message): <ide> return cipher[:-1] <ide> <ide> <del>def decrypt(message): <add>def decrypt(message: str) -> str: <ide> decipher = "" <ide> letters = message.split(" ") <ide> for letter in letters: <ide><path>ciphers/onepad_cipher.py <ide> <ide> <ide> class Onepad: <del> def encrypt(self, text): <add> def encrypt(self, text: str) -> ([str], [int]): <ide> """Function to encrypt text using pseudo-random numbers""" <ide> plain = [ord(i) for i in text] <ide> key = [] <ide> def encrypt(self, text): <ide> key.append(k) <ide> return cipher, key <ide> <del> def decrypt(self, cipher, key): <add> def decrypt(self, cipher: [str], key: [int]) -> str: <ide> """Function to decrypt text using pseudo-random numbers.""" <ide> plain = [] <ide> for i in range(len(key)): <ide><path>ciphers/playfair_cipher.py <ide> def chunker(seq, size): <ide> yield chunk <ide> <ide> <del>def prepare_input(dirty): <add>def prepare_input(dirty: str) -> str: <ide> """ <ide> Prepare the plaintext by up-casing it <ide> and separating repeated letters with X's <ide> def prepare_input(dirty): <ide> return clean <ide> <ide> <del>def generate_table(key): <add>def generate_table(key: str) -> [str]: <ide> <ide> # I and J are used interchangeably to allow <ide> # us to use a 5x5 table (25 letters) <ide> def generate_table(key): <ide> return table <ide> <ide> <del>def encode(plaintext, key): <add>def encode(plaintext: str, key: str) -> str: <ide> table = generate_table(key) <ide> plaintext = prepare_input(plaintext) <ide> ciphertext = "" <ide> def encode(plaintext, key): <ide> return ciphertext <ide> <ide> <del>def decode(ciphertext, key): <add>def decode(ciphertext: str, key: str) -> str: <ide> table = generate_table(key) <ide> plaintext = "" <ide> <ide><path>ciphers/porta_cipher.py <ide> } <ide> <ide> <del>def generate_table(key): <add>def generate_table(key: str) -> [(str, str)]: <ide> """ <ide> >>> generate_table('marvin') # doctest: +NORMALIZE_WHITESPACE <ide> [('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'), <ide> def generate_table(key): <ide> return [alphabet[char] for char in key.upper()] <ide> <ide> <del>def encrypt(key, words): <add>def encrypt(key: str, words: str) -> str: <ide> """ <ide> >>> encrypt('marvin', 'jessica') <ide> 'QRACRWU' <ide> def encrypt(key, words): <ide> return cipher <ide> <ide> <del>def decrypt(key, words): <add>def decrypt(key: str, words: str) -> str: <ide> """ <ide> >>> decrypt('marvin', 'QRACRWU') <ide> 'JESSICA' <ide> """ <ide> return encrypt(key, words) <ide> <ide> <del>def get_position(table, char): <add>def get_position(table: [(str, str)], char: str) -> (int, int) or (None, None): <ide> """ <ide> >>> table = [ <ide> ... ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'), <ide> def get_position(table, char): <ide> return (None, None) if row == -1 else (row, table[row].index(char)) <ide> <ide> <del>def get_opponent(table, char): <add>def get_opponent(table: [(str, str)], char: str) -> str: <ide> """ <ide> >>> table = [ <ide> ... ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'), <ide><path>ciphers/rabin_miller.py <ide> import random <ide> <ide> <del>def rabinMiller(num): <add>def rabinMiller(num: int) -> bool: <ide> s = num - 1 <ide> t = 0 <ide> <ide> def rabinMiller(num): <ide> return True <ide> <ide> <del>def isPrime(num): <add>def isPrime(num: int) -> bool: <ide> if num < 2: <ide> return False <ide> <ide> def isPrime(num): <ide> return rabinMiller(num) <ide> <ide> <del>def generateLargePrime(keysize=1024): <add>def generateLargePrime(keysize: int = 1024) -> int: <ide> while True: <ide> num = random.randrange(2 ** (keysize - 1), 2 ** (keysize)) <ide> if isPrime(num): <ide><path>ciphers/rot13.py <del>def dencrypt(s: str, n: int = 13): <add>def dencrypt(s: str, n: int = 13) -> str: <ide> """ <ide> https://en.wikipedia.org/wiki/ROT13 <ide> <ide><path>ciphers/rsa_cipher.py <ide> def main(): <ide> print(decryptedText) <ide> <ide> <del>def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE): <add>def getBlocksFromText(message: int, blockSize: int = DEFAULT_BLOCK_SIZE) -> [int]: <ide> messageBytes = message.encode("ascii") <ide> <ide> blockInts = [] <ide> def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE): <ide> return blockInts <ide> <ide> <del>def getTextFromBlocks(blockInts, messageLength, blockSize=DEFAULT_BLOCK_SIZE): <add>def getTextFromBlocks( <add> blockInts: [int], messageLength: int, blockSize: int = DEFAULT_BLOCK_SIZE <add>) -> str: <ide> message = [] <ide> for blockInt in blockInts: <ide> blockMessage = [] <ide> def getTextFromBlocks(blockInts, messageLength, blockSize=DEFAULT_BLOCK_SIZE): <ide> return "".join(message) <ide> <ide> <del>def encryptMessage(message, key, blockSize=DEFAULT_BLOCK_SIZE): <add>def encryptMessage( <add> message: str, key: (int, int), blockSize: int = DEFAULT_BLOCK_SIZE <add>) -> [int]: <ide> encryptedBlocks = [] <ide> n, e = key <ide> <ide> def encryptMessage(message, key, blockSize=DEFAULT_BLOCK_SIZE): <ide> return encryptedBlocks <ide> <ide> <del>def decryptMessage(encryptedBlocks, messageLength, key, blockSize=DEFAULT_BLOCK_SIZE): <add>def decryptMessage( <add> encryptedBlocks: [int], <add> messageLength: int, <add> key: (int, int), <add> blockSize: int = DEFAULT_BLOCK_SIZE, <add>) -> str: <ide> decryptedBlocks = [] <ide> n, d = key <ide> for block in encryptedBlocks: <ide> decryptedBlocks.append(pow(block, d, n)) <ide> return getTextFromBlocks(decryptedBlocks, messageLength, blockSize) <ide> <ide> <del>def readKeyFile(keyFilename): <add>def readKeyFile(keyFilename: str) -> (int, int, int): <ide> with open(keyFilename) as fo: <ide> content = fo.read() <ide> keySize, n, EorD = content.split(",") <ide> return (int(keySize), int(n), int(EorD)) <ide> <ide> <ide> def encryptAndWriteToFile( <del> messageFilename, keyFilename, message, blockSize=DEFAULT_BLOCK_SIZE <del>): <add> messageFilename: str, <add> keyFilename: str, <add> message: str, <add> blockSize: int = DEFAULT_BLOCK_SIZE, <add>) -> str: <ide> keySize, n, e = readKeyFile(keyFilename) <ide> if keySize < blockSize * 8: <ide> sys.exit( <ide> def encryptAndWriteToFile( <ide> return encryptedContent <ide> <ide> <del>def readFromFileAndDecrypt(messageFilename, keyFilename): <add>def readFromFileAndDecrypt(messageFilename: str, keyFilename: str) -> str: <ide> keySize, n, d = readKeyFile(keyFilename) <ide> with open(messageFilename) as fo: <ide> content = fo.read() <ide><path>ciphers/rsa_factorization.py <ide> import random <ide> <ide> <del>def rsafactor(d: int, e: int, N: int) -> list[int]: <add>def rsafactor(d: int, e: int, N: int) -> [int]: <ide> """ <ide> This function returns the factors of N, where p*q=N <ide> Return: [p, q] <ide><path>ciphers/rsa_key_generator.py <ide> import os <ide> import random <ide> import sys <add>from typing import Tuple <ide> <ide> from . import cryptomath_module as cryptoMath <ide> from . import rabin_miller as rabinMiller <ide> def main(): <ide> print("Key files generation successful.") <ide> <ide> <del>def generateKey(keySize): <add>def generateKey(keySize: int) -> Tuple[Tuple[int, int], Tuple[int, int]]: <ide> print("Generating prime p...") <ide> p = rabinMiller.generateLargePrime(keySize) <ide> print("Generating prime q...") <ide> def generateKey(keySize): <ide> return (publicKey, privateKey) <ide> <ide> <del>def makeKeyFiles(name, keySize): <add>def makeKeyFiles(name: int, keySize: int) -> None: <ide> if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists( <ide> "%s_privkey.txt" % (name) <ide> ): <ide><path>ciphers/simple_substitution_cipher.py <ide> def main(): <ide> print("\n{}ion: \n{}".format(mode.title(), translated)) <ide> <ide> <del>def checkValidKey(key): <add>def checkValidKey(key: str) -> None: <ide> keyList = list(key) <ide> lettersList = list(LETTERS) <ide> keyList.sort() <ide> def checkValidKey(key): <ide> sys.exit("Error in the key or symbol set.") <ide> <ide> <del>def encryptMessage(key, message): <add>def encryptMessage(key: str, message: str) -> str: <ide> """ <ide> >>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji') <ide> 'Ilcrism Olcvs' <ide> """ <ide> return translateMessage(key, message, "encrypt") <ide> <ide> <del>def decryptMessage(key, message): <add>def decryptMessage(key: str, message: str) -> str: <ide> """ <ide> >>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs') <ide> 'Harshil Darji' <ide> """ <ide> return translateMessage(key, message, "decrypt") <ide> <ide> <del>def translateMessage(key, message, mode): <add>def translateMessage(key: str, message: str, mode: str) -> str: <ide> translated = "" <ide> charsA = LETTERS <ide> charsB = key <ide><path>ciphers/trafid_cipher.py <ide> # https://en.wikipedia.org/wiki/Trifid_cipher <ide> <ide> <del>def __encryptPart(messagePart, character2Number): <add>def __encryptPart(messagePart: str, character2Number: dict) -> str: <ide> one, two, three = "", "", "" <ide> tmp = [] <ide> <ide> def __encryptPart(messagePart, character2Number): <ide> return one + two + three <ide> <ide> <del>def __decryptPart(messagePart, character2Number): <add>def __decryptPart(messagePart: str, character2Number: dict) -> (str, str, str): <ide> tmp, thisPart = "", "" <ide> result = [] <ide> <ide> def __decryptPart(messagePart, character2Number): <ide> return result[0], result[1], result[2] <ide> <ide> <del>def __prepare(message, alphabet): <add>def __prepare(message: str, alphabet: str) -> (str, str, dict, dict): <ide> # Validate message and alphabet, set to upper and remove spaces <ide> alphabet = alphabet.replace(" ", "").upper() <ide> message = message.replace(" ", "").upper() <ide> def __prepare(message, alphabet): <ide> return message, alphabet, character2Number, number2Character <ide> <ide> <del>def encryptMessage(message, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5): <add>def encryptMessage( <add> message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 <add>) -> str: <ide> message, alphabet, character2Number, number2Character = __prepare(message, alphabet) <ide> encrypted, encrypted_numeric = "", "" <ide> <ide> def encryptMessage(message, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5): <ide> return encrypted <ide> <ide> <del>def decryptMessage(message, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5): <add>def decryptMessage( <add> message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 <add>) -> str: <ide> message, alphabet, character2Number, number2Character = __prepare(message, alphabet) <ide> decrypted_numeric = [] <ide> decrypted = "" <ide><path>ciphers/transposition_cipher.py <ide> def main(): <ide> print("Output:\n%s" % (text + "|")) <ide> <ide> <del>def encryptMessage(key, message): <add>def encryptMessage(key: int, message: str) -> str: <ide> """ <ide> >>> encryptMessage(6, 'Harshil Darji') <ide> 'Hlia rDsahrij' <ide> def encryptMessage(key, message): <ide> return "".join(cipherText) <ide> <ide> <del>def decryptMessage(key, message): <add>def decryptMessage(key: int, message: str) -> str: <ide> """ <ide> >>> decryptMessage(6, 'Hlia rDsahrij') <ide> 'Harshil Darji' <ide><path>ciphers/vigenere_cipher.py <ide> def main(): <ide> print(translated) <ide> <ide> <del>def encryptMessage(key, message): <add>def encryptMessage(key: str, message: str) -> str: <ide> """ <ide> >>> encryptMessage('HDarji', 'This is Harshil Darji from Dharmaj.') <ide> 'Akij ra Odrjqqs Gaisq muod Mphumrs.' <ide> """ <ide> return translateMessage(key, message, "encrypt") <ide> <ide> <del>def decryptMessage(key, message): <add>def decryptMessage(key: str, message: str) -> str: <ide> """ <ide> >>> decryptMessage('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.') <ide> 'This is Harshil Darji from Dharmaj.' <ide> """ <ide> return translateMessage(key, message, "decrypt") <ide> <ide> <del>def translateMessage(key, message, mode): <add>def translateMessage(key: str, message: str, mode: str) -> str: <ide> translated = [] <ide> keyIndex = 0 <ide> key = key.upper() <ide><path>ciphers/xor_cipher.py <ide> <ide> <ide> class XORCipher: <del> def __init__(self, key=0): <add> def __init__(self, key: int = 0): <ide> """ <ide> simple constructor that receives a key or uses <ide> default key = 0 <ide> def __init__(self, key=0): <ide> # private field <ide> self.__key = key <ide> <del> def encrypt(self, content, key): <add> def encrypt(self, content: str, key: int) -> [str]: <ide> """ <ide> input: 'content' of type string and 'key' of type int <ide> output: encrypted string 'content' as a list of chars <ide> def encrypt(self, content, key): <ide> <ide> return ans <ide> <del> def decrypt(self, content, key): <add> def decrypt(self, content: str, key: int) -> [str]: <ide> """ <ide> input: 'content' of type list and 'key' of type int <ide> output: decrypted string 'content' as a list of chars <ide> def decrypt(self, content, key): <ide> <ide> return ans <ide> <del> def encrypt_string(self, content, key=0): <add> def encrypt_string(self, content: str, key: int = 0) -> str: <ide> """ <ide> input: 'content' of type string and 'key' of type int <ide> output: encrypted string 'content' <ide> def encrypt_string(self, content, key=0): <ide> <ide> return ans <ide> <del> def decrypt_string(self, content, key=0): <add> def decrypt_string(self, content: str, key: int = 0) -> str: <ide> """ <ide> input: 'content' of type string and 'key' of type int <ide> output: decrypted string 'content' <ide> def decrypt_string(self, content, key=0): <ide> <ide> return ans <ide> <del> def encrypt_file(self, file, key=0): <add> def encrypt_file(self, file: str, key: int = 0) -> bool: <ide> """ <ide> input: filename (str) and a key (int) <ide> output: returns true if encrypt process was <ide> def encrypt_file(self, file, key=0): <ide> <ide> return True <ide> <del> def decrypt_file(self, file, key): <add> def decrypt_file(self, file: str, key: int) -> bool: <ide> """ <ide> input: filename (str) and a key (int) <ide> output: returns true if decrypt process was
25