content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
|---|---|---|---|---|---|
Ruby
|
Ruby
|
call update-python-resources for --python
|
c1ba64677fdfd53e58af42311ea3a6551786454e
|
<ide><path>Library/Homebrew/dev-cmd/create.rb
<ide> require "formula_creator"
<ide> require "missing_formula"
<ide> require "cli/parser"
<add>require "utils/pypi"
<ide>
<ide> module Homebrew
<ide> module_function
<ide> def create
<ide>
<ide> fc.generate!
<ide>
<add> PyPI.update_python_resources! Formula[fc.name], ignore_non_pypi_packages: true if args.python?
<add>
<ide> puts "Please run `brew audit --new-formula #{fc.name}` before submitting, thanks."
<ide> exec_editor fc.path
<ide> end
<ide><path>Library/Homebrew/formula_creator.rb
<ide> class #{Formulary.class_s(name)} < Formula
<ide> # depends_on "cmake" => :build
<ide> <% end %>
<ide>
<del> <% if mode == :perl || mode == :python %>
<add> <% if mode == :perl %>
<ide> # Additional dependency
<ide> # resource "" do
<ide> # url ""
| 2
|
Ruby
|
Ruby
|
fix end of day
|
6c271a98dc3004e43bc6aaf7db6fe7c044b0bb3d
|
<ide><path>activesupport/lib/active_support/core_ext/time/calculations.rb
<ide> def beginning_of_day
<ide>
<ide> # Returns a new Time representing the end of the day (23:59:59)
<ide> def end_of_day
<del> change(:hour => 23, :minute => 59, :sec => 59)
<add> change(:hour => 23, :min => 59, :sec => 59)
<ide> end
<ide>
<ide> # Returns a new Time representing the start of the month (1st of the month, 0:00)
| 1
|
Javascript
|
Javascript
|
fix $flowfixme in appcontainer
|
a956551af73cf785ee4345e92e71fd5b17c5644e
|
<ide><path>Libraries/ReactNative/AppContainer.js
<ide> const View = require('View');
<ide> type Context = {
<ide> rootTag: number,
<ide> };
<del>type Props = {|
<del> /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment
<del> * suppresses an error when upgrading Flow's support for React. To see the
<del> * error delete this comment and run Flow. */
<del> children?: React.Children,
<add>
<add>type Props = $ReadOnly<{|
<add> children?: React.Node,
<ide> rootTag: number,
<del> WrapperComponent?: ?React.ComponentType<*>,
<del>|};
<del>type State = {
<del> inspector: ?React.Element<any>,
<add> WrapperComponent?: ?React.ComponentType<any>,
<add>|}>;
<add>
<add>type State = {|
<add> inspector: ?React.Node,
<ide> mainKey: number,
<del>};
<add>|};
<ide>
<ide> class AppContainer extends React.Component<Props, State> {
<ide> state: State = {
<ide> inspector: null,
<ide> mainKey: 1,
<ide> };
<del> _mainRef: ?React.Element<any>;
<add> _mainRef: ?React.ElementRef<typeof View>;
<ide> _subscription: ?EmitterSubscription = null;
<ide>
<ide> static childContextTypes = {
<ide> class AppContainer extends React.Component<Props, State> {
<ide> }
<ide>
<ide> componentWillUnmount(): void {
<del> if (this._subscription) {
<add> if (this._subscription != null) {
<ide> this._subscription.remove();
<ide> }
<ide> }
<ide> class AppContainer extends React.Component<Props, State> {
<ide> pointerEvents="box-none"
<ide> style={styles.appContainer}
<ide> ref={ref => {
<del> // $FlowFixMe - Typing ReactNativeComponent revealed errors
<ide> this._mainRef = ref;
<ide> }}>
<ide> {this.props.children}
<ide> </View>
<ide> );
<ide>
<ide> const Wrapper = this.props.WrapperComponent;
<del> if (Wrapper) {
<add> if (Wrapper != null) {
<ide> innerView = <Wrapper>{innerView}</Wrapper>;
<ide> }
<ide> return (
| 1
|
Python
|
Python
|
fix bugs of s2t fairseq model converting
|
7cc2c9c6b0a6086eafdf48945aac9855cfec6e21
|
<ide><path>src/transformers/models/speech_to_text/convert_s2t_fairseq_to_tfms.py
<ide> def convert_fairseq_s2t_checkpoint_to_tfms(checkpoint_path, pytorch_dump_folder_
<ide> )
<ide>
<ide> model = Speech2TextForConditionalGeneration(config)
<del> model.model.load_state_dict(state_dict)
<add> missing, unexpected = model.model.load_state_dict(state_dict, strict=False)
<add> if len(missing) > 0 and not set(missing) <= set(
<add> [
<add> "encoder.embed_positions.weights",
<add> "decoder.embed_positions.weights",
<add> ]
<add> ):
<add> raise ValueError(
<add> f"Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing, but all the following weights are missing {missing}"
<add> )
<add>
<ide> if tie_embeds:
<ide> model.lm_head = make_linear_from_emb(model.model.decoder.embed_tokens)
<ide> else:
<ide> def convert_fairseq_s2t_checkpoint_to_tfms(checkpoint_path, pytorch_dump_folder_
<ide> if __name__ == "__main__":
<ide> parser = argparse.ArgumentParser()
<ide> # Required parameters
<del> parser.add_argument("fairseq_path", type=str, help="Path to the fairseq model (.pt) file.")
<del> parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
<add> parser.add_argument("--fairseq_path", type=str, help="Path to the fairseq model (.pt) file.")
<add> parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
<ide> args = parser.parse_args()
<ide> convert_fairseq_s2t_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
| 1
|
Javascript
|
Javascript
|
improve simple assert
|
43ee4d692afb7bae224e529c6088d3890b4ea31f
|
<ide><path>lib/assert.js
<ide> const { NativeModule } = require('internal/bootstrap/loaders');
<ide>
<ide> let isDeepEqual;
<ide> let isDeepStrictEqual;
<add>let parseExpressionAt;
<add>let findNodeAround;
<add>let columnOffset = 0;
<add>let decoder;
<ide>
<ide> function lazyLoadComparison() {
<ide> const comparison = require('internal/util/comparisons');
<ide> function fail(actual, expected, message, operator, stackStartFn) {
<ide> assert.fail = fail;
<ide>
<ide> // The AssertionError is defined in internal/error.
<del>// new assert.AssertionError({ message: message,
<del>// actual: actual,
<del>// expected: expected });
<ide> assert.AssertionError = AssertionError;
<ide>
<del>function getBuffer(fd, assertLine) {
<add>function findColumn(fd, column, code) {
<add> if (code.length > column + 100) {
<add> try {
<add> return parseCode(code, column);
<add> } catch {
<add> // End recursion in case no code could be parsed. The expression should
<add> // have been found after 2500 characters, so stop trying.
<add> if (code.length - column > 2500) {
<add> // eslint-disable-next-line no-throw-literal
<add> throw null;
<add> }
<add> }
<add> }
<add> // Read up to 2500 bytes more than necessary in columns. That way we address
<add> // multi byte characters and read enough data to parse the code.
<add> const bytesToRead = column - code.length + 2500;
<add> const buffer = Buffer.allocUnsafe(bytesToRead);
<add> const bytesRead = readSync(fd, buffer, 0, bytesToRead);
<add> code += decoder.write(buffer.slice(0, bytesRead));
<add> // EOF: fast path.
<add> if (bytesRead < bytesToRead) {
<add> return parseCode(code, column);
<add> }
<add> // Read potentially missing code.
<add> return findColumn(fd, column, code);
<add>}
<add>
<add>function getCode(fd, line, column) {
<add> let bytesRead = 0;
<add> if (line === 0) {
<add> // Special handle line number one. This is more efficient and simplifies the
<add> // rest of the algorithm. Read more than the regular column number in bytes
<add> // to prevent multiple reads in case multi byte characters are used.
<add> return findColumn(fd, column, '');
<add> }
<ide> let lines = 0;
<ide> // Prevent blocking the event loop by limiting the maximum amount of
<ide> // data that may be read.
<ide> let maxReads = 64; // bytesPerRead * maxReads = 512 kb
<del> let bytesRead = 0;
<del> let startBuffer = 0; // Start reading from that char on
<ide> const bytesPerRead = 8192;
<del> const buffers = [];
<del> do {
<del> const buffer = Buffer.allocUnsafe(bytesPerRead);
<add> // Use a single buffer up front that is reused until the call site is found.
<add> let buffer = Buffer.allocUnsafe(bytesPerRead);
<add> while (maxReads-- !== 0) {
<add> // Only allocate a new buffer in case the needed line is found. All data
<add> // before that can be discarded.
<add> buffer = lines < line ? buffer : Buffer.allocUnsafe(bytesPerRead);
<ide> bytesRead = readSync(fd, buffer, 0, bytesPerRead);
<add> // Read the buffer until the required code line is found.
<ide> for (var i = 0; i < bytesRead; i++) {
<del> if (buffer[i] === 10) {
<del> lines++;
<del> if (lines === assertLine) {
<del> startBuffer = i + 1;
<del> // Read up to 15 more lines to make sure all code gets matched
<del> } else if (lines === assertLine + 16) {
<del> buffers.push(buffer.slice(startBuffer, i));
<del> return buffers;
<add> if (buffer[i] === 10 && ++lines === line) {
<add> // If the end of file is reached, directly parse the code and return.
<add> if (bytesRead < bytesPerRead) {
<add> return parseCode(buffer.toString('utf8', i + 1, bytesRead), column);
<ide> }
<add> // Check if the read code is sufficient or read more until the whole
<add> // expression is read. Make sure multi byte characters are preserved
<add> // properly by using the decoder.
<add> const code = decoder.write(buffer.slice(i + 1, bytesRead));
<add> return findColumn(fd, column, code);
<ide> }
<ide> }
<del> if (lines >= assertLine) {
<del> buffers.push(buffer.slice(startBuffer, bytesRead));
<del> // Reset the startBuffer in case we need more than one chunk
<del> startBuffer = 0;
<add> }
<add>}
<add>
<add>function parseCode(code, offset) {
<add> // Lazy load acorn.
<add> if (parseExpressionAt === undefined) {
<add> ({ parseExpressionAt } = require('internal/deps/acorn/dist/acorn'));
<add> ({ findNodeAround } = require('internal/deps/acorn/dist/walk'));
<add> }
<add> let node;
<add> let start = 0;
<add> // Parse the read code until the correct expression is found.
<add> do {
<add> try {
<add> node = parseExpressionAt(code, start);
<add> start = node.end + 1 || start;
<add> // Find the CallExpression in the tree.
<add> node = findNodeAround(node, offset, 'CallExpression');
<add> } catch (err) {
<add> // Unexpected token error and the like.
<add> start += err.raisedAt || 1;
<add> if (start > offset) {
<add> // No matching expression found. This could happen if the assert
<add> // expression is bigger than the provided buffer.
<add> // eslint-disable-next-line no-throw-literal
<add> throw null;
<add> }
<ide> }
<del> } while (--maxReads !== 0 && bytesRead !== 0);
<del> return buffers;
<add> } while (node === undefined || node.node.end < offset);
<add>
<add> return [
<add> node.node.start,
<add> code.slice(node.node.start, node.node.end)
<add> .replace(escapeSequencesRegExp, escapeFn)
<add> ];
<ide> }
<ide>
<del>function getErrMessage(call) {
<add>function getErrMessage(message, fn) {
<add> const tmpLimit = Error.stackTraceLimit;
<add> // Make sure the limit is set to 1. Otherwise it could fail (<= 0) or it
<add> // does to much work.
<add> Error.stackTraceLimit = 1;
<add> // We only need the stack trace. To minimize the overhead use an object
<add> // instead of an error.
<add> const err = {};
<add> Error.captureStackTrace(err, fn);
<add> Error.stackTraceLimit = tmpLimit;
<add>
<add> const tmpPrepare = Error.prepareStackTrace;
<add> Error.prepareStackTrace = (_, stack) => stack;
<add> const call = err.stack[0];
<add> Error.prepareStackTrace = tmpPrepare;
<add>
<ide> const filename = call.getFileName();
<add>
<ide> if (!filename) {
<del> return;
<add> return message;
<ide> }
<ide>
<ide> const line = call.getLineNumber() - 1;
<del> const column = call.getColumnNumber() - 1;
<add> let column = call.getColumnNumber() - 1;
<add>
<add> // Line number one reports the wrong column due to being wrapped in a
<add> // function. Remove that offset to get the actual call.
<add> if (line === 0) {
<add> if (columnOffset === 0) {
<add> const { wrapper } = require('internal/modules/cjs/loader');
<add> columnOffset = wrapper[0].length;
<add> }
<add> column -= columnOffset;
<add> }
<add>
<ide> const identifier = `${filename}${line}${column}`;
<ide>
<ide> if (errorCache.has(identifier)) {
<ide> function getErrMessage(call) {
<ide> return;
<ide> }
<ide>
<del> let fd, message;
<add> let fd;
<ide> try {
<add> // Set the stack trace limit to zero. This makes sure unexpected token
<add> // errors are handled faster.
<add> Error.stackTraceLimit = 0;
<add>
<add> if (decoder === undefined) {
<add> const { StringDecoder } = require('string_decoder');
<add> decoder = new StringDecoder('utf8');
<add> }
<add>
<ide> fd = openSync(filename, 'r', 0o666);
<del> const buffers = getBuffer(fd, line);
<del> const code = Buffer.concat(buffers).toString('utf8');
<del> // Lazy load acorn.
<del> const { parseExpressionAt } = require('internal/deps/acorn/dist/acorn');
<del> const nodes = parseExpressionAt(code, column);
<del> // Node type should be "CallExpression" and some times
<del> // "SequenceExpression".
<del> const node = nodes.type === 'CallExpression' ? nodes : nodes.expressions[0];
<del> const name = node.callee.name;
<del> // Calling `ok` with .apply or .call is uncommon but we use a simple
<del> // safeguard nevertheless.
<del> if (name !== 'apply' && name !== 'call') {
<del> // Only use `assert` and `assert.ok` to reference the "real API" and
<del> // not user defined function names.
<del> const ok = name === 'ok' ? '.ok' : '';
<del> const args = node.arguments;
<del> message = code
<del> .slice(args[0].start, args[args.length - 1].end)
<del> .replace(escapeSequencesRegExp, escapeFn);
<add> // Reset column and message.
<add> [column, message] = getCode(fd, line, column);
<add> // Flush unfinished multi byte characters.
<add> decoder.end();
<add> // Always normalize indentation, otherwise the message could look weird.
<add> if (message.indexOf('\n') !== -1) {
<ide> if (EOL === '\r\n') {
<ide> message = message.replace(/\r\n/g, '\n');
<ide> }
<del> // Always normalize indentation, otherwise the message could look weird.
<del> if (message.indexOf('\n') !== -1) {
<del> const tmp = message.split('\n');
<del> message = tmp[0];
<del> for (var i = 1; i < tmp.length; i++) {
<del> let pos = 0;
<del> while (pos < column &&
<del> (tmp[i][pos] === ' ' || tmp[i][pos] === '\t')) {
<del> pos++;
<del> }
<del> message += `\n ${tmp[i].slice(pos)}`;
<add> const frames = message.split('\n');
<add> message = frames.shift();
<add> for (const frame of frames) {
<add> let pos = 0;
<add> while (pos < column && (frame[pos] === ' ' || frame[pos] === '\t')) {
<add> pos++;
<ide> }
<add> message += `\n ${frame.slice(pos)}`;
<ide> }
<del> message = 'The expression evaluated to a falsy value:' +
<del> `\n\n assert${ok}(${message})\n`;
<ide> }
<add> message = `The expression evaluated to a falsy value:\n\n ${message}\n`;
<ide> // Make sure to always set the cache! No matter if the message is
<ide> // undefined or not
<ide> errorCache.set(identifier, message);
<ide>
<ide> return message;
<del>
<ide> } catch (e) {
<ide> // Invalidate cache to prevent trying to read this part again.
<ide> errorCache.set(identifier, undefined);
<ide> } finally {
<add> // Reset limit.
<add> Error.stackTraceLimit = tmpLimit;
<ide> if (fd !== undefined)
<ide> closeSync(fd);
<ide> }
<ide> function innerOk(fn, argLen, value, message) {
<ide> generatedMessage = true;
<ide> message = 'No value argument passed to `assert.ok()`';
<ide> } else if (message == null) {
<del> // Use the call as error message if possible.
<del> // This does not work with e.g. the repl.
<del> // eslint-disable-next-line no-restricted-syntax
<del> const err = new Error();
<del> // Make sure the limit is set to 1. Otherwise it could fail (<= 0) or it
<del> // does to much work.
<del> const tmpLimit = Error.stackTraceLimit;
<del> Error.stackTraceLimit = 1;
<del> Error.captureStackTrace(err, fn);
<del> Error.stackTraceLimit = tmpLimit;
<del>
<del> const tmpPrepare = Error.prepareStackTrace;
<del> Error.prepareStackTrace = (_, stack) => stack;
<del> const call = err.stack[0];
<del> Error.prepareStackTrace = tmpPrepare;
<del>
<del> // Make sure it would be "null" in case that is used.
<del> message = getErrMessage(call) || message;
<ide> generatedMessage = true;
<add> message = getErrMessage(message, fn);
<ide> } else if (message instanceof Error) {
<ide> throw message;
<ide> }
<ide><path>test/fixtures/assert-first-line.js
<add>'use strict'; const ässört = require('assert'); ässört(true); ässört.ok(''); ässört(null);
<add>// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(false);
<ide><path>test/fixtures/assert-long-line.js
<add>'use strict'; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */ const assert = require('assert'); assert(true); assert.ok(''); assert(null);
<ide><path>test/parallel/test-assert-first-line.js
<add>'use strict';
<add>
<add>// Verify that asserting in the very first line produces the expected result.
<add>
<add>require('../common');
<add>const assert = require('assert');
<add>const { path } = require('../common/fixtures');
<add>
<add>assert.throws(
<add> () => require(path('assert-first-line')),
<add> {
<add> name: 'AssertionError [ERR_ASSERTION]',
<add> message: "The expression evaluated to a falsy value:\n\n ässört.ok('')\n"
<add> }
<add>);
<add>
<add>assert.throws(
<add> () => require(path('assert-long-line')),
<add> {
<add> name: 'AssertionError [ERR_ASSERTION]',
<add> message: "The expression evaluated to a falsy value:\n\n assert.ok('')\n"
<add> }
<add>);
<ide><path>test/parallel/test-assert.js
<ide> assert.throws(
<ide> code: 'ERR_ASSERTION',
<ide> type: assert.AssertionError,
<ide> message: 'The expression evaluated to a falsy value:\n\n ' +
<del> "assert.ok(typeof 123 === 'string')\n"
<add> "assert.ok(\n typeof 123 === 'string'\n )\n"
<ide> }
<ide> );
<ide> Error.stackTraceLimit = tmpLimit;
<ide> common.expectsError(
<ide> code: 'ERR_ASSERTION',
<ide> type: assert.AssertionError,
<ide> message: 'The expression evaluated to a falsy value:\n\n ' +
<del> "assert(Buffer.from('test') instanceof Error)\n"
<add> "assert(\n (Buffer.from('test') instanceof Error)\n )\n"
<ide> }
<ide> );
<ide> common.expectsError(
<ide> common.expectsError(
<ide> code: 'ERR_ASSERTION',
<ide> type: assert.AssertionError,
<ide> message: 'The expression evaluated to a falsy value:\n\n ' +
<del> "assert(Buffer.from('test') instanceof Error)\n"
<add> "assert(\n (Buffer.from('test') instanceof Error)\n )\n"
<ide> }
<ide> );
<ide> fs.close = tmp;
<ide> common.expectsError(
<ide> code: 'ERR_ASSERTION',
<ide> type: assert.AssertionError,
<ide> message: 'The expression evaluated to a falsy value:\n\n' +
<del> ' assert((() => \'string\')()\n' +
<add> ' a(\n' +
<add> ' (() => \'string\')()\n' +
<ide> ' // eslint-disable-next-line\n' +
<ide> ' ===\n' +
<ide> ' 123 instanceof\n' +
<del> ' Buffer)\n'
<add> ' Buffer\n' +
<add> ' )\n'
<ide> }
<ide> );
<ide>
<ide> common.expectsError(
<ide> code: 'ERR_ASSERTION',
<ide> type: assert.AssertionError,
<ide> message: 'The expression evaluated to a falsy value:\n\n' +
<del> ' assert((() => \'string\')()\n' +
<add> ' a(\n' +
<add> ' (() => \'string\')()\n' +
<ide> ' // eslint-disable-next-line\n' +
<ide> ' ===\n' +
<ide> ' 123 instanceof\n' +
<del> ' Buffer)\n'
<add> ' Buffer\n' +
<add> ' )\n'
<ide> }
<ide> );
<ide>
<ide> Buffer
<ide> code: 'ERR_ASSERTION',
<ide> type: assert.AssertionError,
<ide> message: 'The expression evaluated to a falsy value:\n\n' +
<del> ' assert((\n' +
<add> ' a((\n' +
<ide> ' () => \'string\')() ===\n' +
<ide> ' 123 instanceof\n' +
<del> ' Buffer)\n'
<add> ' Buffer\n' +
<add> ' )\n'
<ide> }
<ide> );
<ide> /* eslint-enable indent */
<ide>
<ide> common.expectsError(
<del> () => assert(null, undefined),
<add> () => {
<add> assert(true); assert(null, undefined);
<add> },
<ide> {
<ide> code: 'ERR_ASSERTION',
<ide> type: assert.AssertionError,
<ide> common.expectsError(
<ide> );
<ide>
<ide> common.expectsError(
<del> () => assert.ok.apply(null, [0]),
<add> () => {
<add> assert
<add> .ok(null, undefined);
<add> },
<ide> {
<ide> code: 'ERR_ASSERTION',
<ide> type: assert.AssertionError,
<del> message: '0 == true'
<add> message: 'The expression evaluated to a falsy value:\n\n ' +
<add> 'ok(null, undefined)\n'
<add> }
<add>);
<add>
<add>common.expectsError(
<add> // eslint-disable-next-line dot-notation, quotes
<add> () => assert['ok']["apply"](null, [0]),
<add> {
<add> code: 'ERR_ASSERTION',
<add> type: assert.AssertionError,
<add> message: 'The expression evaluated to a falsy value:\n\n ' +
<add> 'assert[\'ok\']["apply"](null, [0])\n'
<add> }
<add>);
<add>
<add>common.expectsError(
<add> () => {
<add> const wrapper = (fn, value) => fn(value);
<add> wrapper(assert, false);
<add> },
<add> {
<add> code: 'ERR_ASSERTION',
<add> type: assert.AssertionError,
<add> message: 'The expression evaluated to a falsy value:\n\n fn(value)\n'
<ide> }
<ide> );
<ide>
<ide> common.expectsError(
<ide> {
<ide> code: 'ERR_ASSERTION',
<ide> type: assert.AssertionError,
<del> message: '0 == true',
<add> message: 'The expression evaluated to a falsy value:\n\n ' +
<add> 'assert.ok.call(null, 0)\n',
<ide> generatedMessage: true
<ide> }
<ide> );
<ide> common.expectsError(
<ide> }
<ide> );
<ide>
<del>// works in eval
<add>// Works in eval.
<ide> common.expectsError(
<ide> () => new Function('assert', 'assert(1 === 2);')(assert),
<ide> {
| 5
|
Python
|
Python
|
add parser for adam
|
a7ba27b1b4c10462221f915a4cc4f91beb73eafc
|
<ide><path>examples/lm_finetuning/finetune_on_pregenerated.py
<ide> def main():
<ide> default=0,
<ide> type=int,
<ide> help="Linear warmup over warmup_steps.")
<add> parser.add_argument("--adam_epsilon",
<add> default=1e-8,
<add> type=float,
<add> help="Epsilon for Adam optimizer.")
<ide> parser.add_argument("--learning_rate",
<ide> default=3e-5,
<ide> type=float,
<ide><path>examples/lm_finetuning/simple_lm_finetuning.py
<ide> def main():
<ide> default=3e-5,
<ide> type=float,
<ide> help="The initial learning rate for Adam.")
<add> parser.add_argument("--adam_epsilon",
<add> default=1e-8,
<add> type=float,
<add> help="Epsilon for Adam optimizer.")
<ide> parser.add_argument("--num_train_epochs",
<ide> default=3.0,
<ide> type=float,
| 2
|
Text
|
Text
|
remove submodule documentation
|
edf6f51c27d9a721ed6640ef926ae8878fd95048
|
<ide><path>README.md
<ide> To get a local copy of the current code, clone it using git:
<ide>
<ide> $ git clone git://github.com/mozilla/pdf.js.git pdfjs
<ide> $ cd pdfjs
<del> $ git submodule init
<del> $ git submodule update
<ide>
<ide> Next, you need to start a local web server as some browsers don't allow opening
<ide> PDF files for a file:// url:
| 1
|
Ruby
|
Ruby
|
remove the magic parameter from `#where`
|
c34ab58b1ccc84ff09d6863d72b6462c3594f538
|
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def left_outer_joins!(*args) # :nodoc:
<ide> #
<ide> # If the condition is any blank-ish object, then #where is a no-op and returns
<ide> # the current relation.
<del> def where(opts = :chain, *rest)
<del> if :chain == opts
<add> def where(*args)
<add> if args.empty?
<ide> WhereChain.new(spawn)
<del> elsif opts.blank?
<add> elsif args.length == 1 && args.first.blank?
<ide> self
<ide> else
<del> spawn.where!(opts, *rest)
<add> spawn.where!(*args)
<ide> end
<ide> end
<ide>
| 1
|
Go
|
Go
|
add domainname support
|
0a436e03b8289510ad191a89fcbd5ec06fb8865d
|
<ide><path>container.go
<ide> import (
<ide> "io"
<ide> "io/ioutil"
<ide> "log"
<add> "net"
<ide> "os"
<ide> "os/exec"
<ide> "path"
<ide> import (
<ide> "strings"
<ide> "syscall"
<ide> "time"
<del> "net"
<ide> )
<ide>
<ide> type Container struct {
<ide> type Container struct {
<ide>
<ide> type Config struct {
<ide> Hostname string
<add> Domainname string
<ide> User string
<ide> Memory int64 // Memory limit (in bytes)
<ide> MemorySwap int64 // Total memory usage (memory + swap); set `-1' to disable swap
<ide> func ParseRun(args []string, capabilities *Capabilities) (*Config, *HostConfig,
<ide> return nil, nil, cmd, err
<ide> }
<ide>
<add> hostname := *flHostname
<add> domainname := ""
<add>
<add> parts := strings.SplitN(hostname, ".", 2)
<add> if len(parts) > 1 {
<add> hostname = parts[0]
<add> domainname = parts[1]
<add> }
<ide> config := &Config{
<del> Hostname: *flHostname,
<add> Hostname: hostname,
<add> Domainname: domainname,
<ide> PortSpecs: flPorts,
<ide> User: *flUser,
<ide> Tty: *flTty,
<ide> func (container *Container) Start(hostConfig *HostConfig) error {
<ide> params = append(params, "-e", "TERM=xterm")
<ide> }
<ide>
<add> params = append(params, "-h", container.Config.Hostname)
<add> params = append(params, "-d", container.Config.Domainname)
<add>
<ide> // Setup environment
<ide> params = append(params,
<ide> "-e", "HOME=/",
<ide> func (container *Container) allocateNetwork() error {
<ide> iface = &NetworkInterface{disabled: true}
<ide> } else {
<ide> iface = &NetworkInterface{
<del> IPNet: net.IPNet{IP: net.ParseIP(container.NetworkSettings.IPAddress), Mask: manager.bridgeNetwork.Mask},
<add> IPNet: net.IPNet{IP: net.ParseIP(container.NetworkSettings.IPAddress), Mask: manager.bridgeNetwork.Mask},
<ide> Gateway: manager.bridgeNetwork.IP,
<ide> manager: manager,
<del> }
<add> }
<ide> ipNum := ipToInt(iface.IPNet.IP)
<ide> manager.ipAllocator.inUse[ipNum] = struct{}{}
<ide> }
<ide> func (container *Container) allocateNetwork() error {
<ide> portSpecs = container.Config.PortSpecs
<ide> } else {
<ide> for backend, frontend := range container.NetworkSettings.PortMapping["Tcp"] {
<del> portSpecs = append(portSpecs, fmt.Sprintf("%s:%s/tcp",frontend, backend))
<add> portSpecs = append(portSpecs, fmt.Sprintf("%s:%s/tcp", frontend, backend))
<ide> }
<ide> for backend, frontend := range container.NetworkSettings.PortMapping["Udp"] {
<del> portSpecs = append(portSpecs, fmt.Sprintf("%s:%s/udp",frontend, backend))
<add> portSpecs = append(portSpecs, fmt.Sprintf("%s:%s/udp", frontend, backend))
<ide> }
<ide> }
<ide>
<ide><path>sysinit.go
<ide> import (
<ide> "flag"
<ide> "fmt"
<ide> "github.com/dotcloud/docker/utils"
<add> "io/ioutil"
<ide> "log"
<ide> "os"
<ide> "os/exec"
<ide> func SysInit() {
<ide> var u = flag.String("u", "", "username or uid")
<ide> var gw = flag.String("g", "", "gateway address")
<ide> var workdir = flag.String("w", "", "workdir")
<del>
<add> var hostname = flag.String("h", "", "hostname")
<add> var domainname = flag.String("d", "", "domainname")
<ide> var flEnv ListOpts
<ide> flag.Var(&flEnv, "e", "Set environment variables")
<ide>
<ide> func SysInit() {
<ide> cleanupEnv(flEnv)
<ide> setupNetworking(*gw)
<ide> setupWorkingDirectory(*workdir)
<add> setupHostname(*hostname, *domainname)
<ide> changeUser(*u)
<ide> executeProgram(flag.Arg(0), flag.Args())
<ide> }
| 2
|
PHP
|
PHP
|
use mb_* throughout crypto classes
|
615707e57ff7fd672f61e79153aa6e5d0a53b640
|
<ide><path>src/Utility/Crypto/Mcrypt.php
<ide> public static function rijndael($text, $key, $operation)
<ide> $mode = MCRYPT_MODE_CBC;
<ide> $ivSize = mcrypt_get_iv_size($algorithm, $mode);
<ide>
<del> $cryptKey = substr($key, 0, 32);
<add> $cryptKey = mb_substr($key, 0, 32, '8bit');
<ide>
<ide> if ($operation === 'encrypt') {
<ide> $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
<ide> return $iv . '$$' . mcrypt_encrypt($algorithm, $cryptKey, $text, $mode, $iv);
<ide> }
<del> $iv = substr($text, 0, $ivSize);
<del> $text = substr($text, $ivSize + 2);
<add> $iv = mb_substr($text, 0, $ivSize, '8bit');
<add> $text = mb_substr($text, $ivSize + 2, null, '8bit');
<ide> return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
<ide> }
<ide>
<ide> public static function encrypt($plain, $key)
<ide> $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
<ide>
<ide> // Pad out plain to make it AES compatible.
<del> $pad = ($ivSize - (strlen($plain) % $ivSize));
<add> $pad = ($ivSize - (mb_strlen($plain, '8bit') % $ivSize));
<ide> $plain .= str_repeat(chr($pad), $pad);
<ide>
<ide> return $iv . mcrypt_encrypt($algorithm, $key, $plain, $mode, $iv);
<ide> public static function decrypt($cipher, $key)
<ide> $mode = MCRYPT_MODE_CBC;
<ide> $ivSize = mcrypt_get_iv_size($algorithm, $mode);
<ide>
<del> $iv = substr($cipher, 0, $ivSize);
<del> $cipher = substr($cipher, $ivSize);
<add> $iv = mb_substr($cipher, 0, $ivSize, '8bit');
<add> $cipher = mb_substr($cipher, $ivSize, null, '8bit');
<ide> $plain = mcrypt_decrypt($algorithm, $key, $cipher, $mode, $iv);
<ide>
<ide> // Remove PKCS#7 padding or Null bytes
<ide> // Newer values will be PKCS#7 padded, while old
<ide> // mcrypt values will be null byte padded.
<del> $padChar = substr($plain, -1);
<add> $padChar = mb_substr($plain, -1, null, '8bit');
<ide> if ($padChar === "\0") {
<ide> return trim($plain, "\0");
<ide> }
<ide> $padLen = ord($padChar);
<del> return substr($plain, 0, -$padLen);
<add> $result = mb_substr($plain, 0, -$padLen, '8bit');
<add> return $result === '' ? false : $result;
<ide> }
<ide> }
<ide><path>src/Utility/Crypto/OpenSsl.php
<ide> public static function decrypt($cipher, $key)
<ide> $method = 'AES-256-CBC';
<ide> $ivSize = openssl_cipher_iv_length($method);
<ide>
<del> $iv = substr($cipher, 0, $ivSize);
<add> $iv = mb_substr($cipher, 0, $ivSize, '8bit');
<ide>
<del> $cipher = substr($cipher, $ivSize);
<add> $cipher = mb_substr($cipher, $ivSize, null, '8bit');
<ide> return openssl_decrypt($cipher, $method, $key, true, $iv);
<ide> }
<ide> }
<ide><path>src/Utility/Security.php
<ide> public static function rijndael($text, $key, $operation)
<ide> if (empty($operation) || !in_array($operation, ['encrypt', 'decrypt'])) {
<ide> throw new InvalidArgumentException('You must specify the operation for Security::rijndael(), either encrypt or decrypt');
<ide> }
<del> if (strlen($key) < 32) {
<add> if (mb_strlen($key, '8bit') < 32) {
<ide> throw new InvalidArgumentException('You must use a key larger than 32 bytes for Security::rijndael()');
<ide> }
<ide> $crypto = static::engine();
<ide> public static function encrypt($plain, $key, $hmacSalt = null)
<ide> $hmacSalt = static::$_salt;
<ide> }
<ide> // Generate the encryption and hmac key.
<del> $key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
<add> $key = mb_substr(hash('sha256', $key . $hmacSalt), 0, 32, '8bit');
<ide>
<ide> $crypto = static::engine();
<ide> $ciphertext = $crypto->encrypt($plain, $key);
<ide> public static function encrypt($plain, $key, $hmacSalt = null)
<ide> */
<ide> protected static function _checkKey($key, $method)
<ide> {
<del> if (strlen($key) < 32) {
<add> if (mb_strlen($key, '8bit') < 32) {
<ide> throw new InvalidArgumentException(
<ide> sprintf('Invalid key for %s, key must be at least 256 bits (32 bytes) long.', $method)
<ide> );
<ide> public static function decrypt($cipher, $key, $hmacSalt = null)
<ide> }
<ide>
<ide> // Generate the encryption and hmac key.
<del> $key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
<add> $key = mb_substr(hash('sha256', $key . $hmacSalt), 0, 32, '8bit');
<ide>
<ide> // Split out hmac for comparison
<ide> $macSize = 64;
<del> $hmac = substr($cipher, 0, $macSize);
<del> $cipher = substr($cipher, $macSize);
<add> $hmac = mb_substr($cipher, 0, $macSize, '8bit');
<add> $cipher = mb_substr($cipher, $macSize, null, '8bit');
<ide>
<ide> $compareHmac = hash_hmac('sha256', $cipher, $key);
<ide> if (!static::_constantEquals($hmac, $compareHmac)) {
| 3
|
Javascript
|
Javascript
|
add compilerstatus type
|
3d72d6144e24d0878fab74da78863adff5769481
|
<ide><path>lib/MultiCompiler.js
<ide> const MultiWatching = require("./MultiWatching");
<ide>
<ide> /** @typedef {import("./Compiler")} Compiler */
<ide>
<add>/** @typedef {number} CompilerStatus */
<add>
<ide> const STATUS_PENDING = 0;
<ide> const STATUS_DONE = 1;
<ide> const STATUS_NEW = 2;
<ide> module.exports = class MultiCompiler {
<ide>
<ide> const watchings = [];
<ide> const allStats = this.compilers.map(() => null);
<add>
<add> /** @type {CompilerStatus[]} */
<ide> const compilerStatus = this.compilers.map(() => STATUS_PENDING);
<ide>
<ide> if (this.validateDependencies(handler)) {
| 1
|
Ruby
|
Ruby
|
add syntax sugar for mpidependency
|
919aac0b8969550e1db4a21d10ab404bff88e4ed
|
<ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_deps
<ide> when 'open-mpi', 'mpich2'
<ide> problem <<-EOS.undent
<ide> There are multiple conflicting ways to install MPI. Use an MPIDependency:
<del> depends_on MPIDependency.new(<lang list>)
<add> depends_on :mpi => [<lang list>]
<ide> Where <lang list> is a comma delimited list that can include:
<del> :cc, :cxx, :f90, :f77
<add> :cc, :cxx, :f77, :f90
<ide> EOS
<ide> end
<ide> end
<ide><path>Library/Homebrew/dependency_collector.rb
<ide> def parse_symbol_spec(spec, tags)
<ide> when :mysql then MysqlDependency.new(tags)
<ide> when :postgresql then PostgresqlDependency.new(tags)
<ide> when :fortran then FortranDependency.new(tags)
<add> when :mpi then MPIDependency.new(*tags)
<ide> when :tex then TeXDependency.new(tags)
<ide> when :clt then CLTDependency.new(tags)
<ide> when :arch then ArchRequirement.new(tags)
<ide><path>Library/Homebrew/requirements/mpi_dependency.rb
<ide> class MPIDependency < Requirement
<ide>
<ide> env :userpaths
<ide>
<del> def initialize *lang_list
<del> @lang_list = lang_list
<add> # This method must accept varargs rather than an array for
<add> # backwards compatibility with formulae that call it directly.
<add> def initialize(*tags)
<ide> @non_functional = []
<ide> @unknown_langs = []
<del> super()
<add> @lang_list = [:cc, :cxx, :f77, :f90] & tags
<add> tags -= @lang_list
<add> super(tags)
<ide> end
<ide>
<ide> def mpi_wrapper_works? compiler
<ide><path>Library/Homebrew/test/test_mpi_dependency.rb
<add>require 'testing_env'
<add>require 'requirements/mpi_dependency'
<add>
<add>class MPIDependencyTests < Test::Unit::TestCase
<add> def test_initialize_untangles_tags_and_wrapper_symbols
<add> wrappers = [:cc, :cxx, :f77]
<add> tags = [:optional, 'some-other-tag']
<add> dep = MPIDependency.new(*wrappers + tags)
<add> assert_equal wrappers, dep.lang_list
<add> assert_equal tags, dep.tags
<add> end
<add>end
| 4
|
PHP
|
PHP
|
update documentation and typehint
|
f30b43b4c998761ce126db573865d72c23f9e517
|
<ide><path>lib/Cake/Model/Datasource/DboSource.php
<ide> protected function _fetchHasAndBelongsToMany(Model $Model, $query, $ids, $associ
<ide> }
<ide>
<ide> /**
<del> * Merge the results of hasMany relations.
<add> * Merge the results of 'hasMany' associations.
<add> *
<add> * Note: this function also deals with the formatting of the data.
<ide> *
<ide> * @param array $resultSet Data to merge into.
<del> * @param array $merge Data to merge.
<add> * @param array $assocResultSet Data to merge.
<ide> * @param string $association Name of Model being merged.
<ide> * @param Model $Model Model being merged onto.
<ide> * @return void
<ide> */
<del> protected function _mergeHasMany(&$resultSet, $merge, $association, $Model) {
<add> protected function _mergeHasMany(&$resultSet, $assocResultSet, $association, Model $Model) {
<ide> $modelAlias = $Model->alias;
<ide> $primaryKey = $Model->primaryKey;
<ide> $foreignKey = $Model->hasMany[$association]['foreignKey'];
<ide> protected function _mergeHasMany(&$resultSet, $merge, $association, $Model) {
<ide> $resultPrimaryKey = $result[$modelAlias][$primaryKey];
<ide>
<ide> $merged = array();
<del> foreach ($merge as $data) {
<add> foreach ($assocResultSet as $data) {
<ide> if ($resultPrimaryKey !== $data[$association][$foreignKey]) {
<ide> continue;
<ide> }
<ide> public function buildAssociationQuery(Model $Model, $queryData) {
<ide> * @param boolean $external Whether or not the association query is on an external datasource.
<ide> * @return mixed
<ide> * String representing a query.
<del> * True. when $external is false and association $type is 'hasOne' or 'belongsTo'.
<add> * True, when $external is false and association $type is 'hasOne' or 'belongsTo'.
<ide> */
<ide> public function generateAssociationQuery(Model $Model, Model $LinkModel, $type, $association, $assocData, &$queryData, $external) {
<ide> $assocData = $this->_scrubQueryData($assocData);
| 1
|
Text
|
Text
|
fix sentence [ci skip]
|
a1e4aca267ecc175184bd9d70bbee051d798f168
|
<ide><path>website/docs/usage/v3-1.md
<ide> your own.
<ide>
<ide> ### Resizable text classification architectures {#resizable-textcat}
<ide>
<del>Previously, a trained [`TextCategorizer`](/api/textcategorizer) architectures
<del>could not be resized, meaning that you couldn't add new labels to an already
<del>trained text classifier. In spaCy v3.1, the
<del>[TextCatCNN](/api/architectures#TextCatCNN) and
<add>Previously, the [`TextCategorizer`](/api/textcategorizer) architectures could
<add>not be resized, meaning that you couldn't add new labels to an already trained
<add>model. In spaCy v3.1, the [TextCatCNN](/api/architectures#TextCatCNN) and
<ide> [TextCatBOW](/api/architectures#TextCatBOW) architectures are now resizable,
<ide> while ensuring that the predictions for the old labels remain the same.
<ide>
| 1
|
Python
|
Python
|
make tok2vec.remove_listener return bool
|
2102082478e04ce3e1de96c6fafcc8a935fb4693
|
<ide><path>spacy/pipeline/tok2vec.py
<ide> def add_listener(self, listener: "Tok2VecListener", component_name: str) -> None
<ide> self.listener_map.setdefault(component_name, [])
<ide> self.listener_map[component_name].append(listener)
<ide>
<del> def remove_listener(self, listener: "Tok2VecListener", component_name: str) -> None:
<add> def remove_listener(self, listener: "Tok2VecListener", component_name: str) -> bool:
<ide> """Remove a listener for a downstream component. Usually internals."""
<ide> if component_name in self.listener_map:
<ide> if listener in self.listener_map[component_name]:
<ide> self.listener_map[component_name].remove(listener)
<ide> # If no listeners are left, remove entry
<ide> if not self.listener_map[component_name]:
<ide> del self.listener_map[component_name]
<add> return True
<add> return False
<ide>
<ide> def find_listeners(self, component) -> None:
<ide> """Walk over a model of a processing component, looking for layers that
| 1
|
Javascript
|
Javascript
|
test all styles of top-level element in <gc>
|
92d4854ca35b010541730053eae5810c8fe0a0eb
|
<ide><path>packages/ember-htmlbars/tests/integration/component_invocation_test.js
<ide> if (isEnabled('ember-htmlbars-component-generation')) {
<ide> }, `You cannot use triple curlies (e.g. style={{{ ... }}}) in the top-level element of the <non-block> template because it is a GlimmerComponent.`);
<ide> });
<ide>
<del> QUnit.test('non-block without properties replaced with a div', function() {
<del> // The whitespace is added intentionally to verify that the heuristic is not "a single node" but
<del> // rather "a single non-whitespace, non-comment node"
<del> registry.register('template:components/non-block', compile(' <div>In layout</div> '));
<add> let styles = [{
<add> name: 'a div',
<add> tagName: 'div'
<add> }, {
<add> name: 'an identity element',
<add> tagName: 'non-block'
<add> }, {
<add> name: 'a web component',
<add> tagName: 'not-an-ember-component'
<add> }];
<add>
<add> styles.forEach(style => {
<add> QUnit.test(`non-block without attributes replaced with ${style.name}`, function() {
<add> // The whitespace is added intentionally to verify that the heuristic is not "a single node" but
<add> // rather "a single non-whitespace, non-comment node"
<add> registry.register('template:components/non-block', compile(` <${style.tagName}>In layout</${style.tagName}> `));
<ide>
<del> view = appendViewFor('<non-block />');
<del>
<del> equal(view.$().text(), ' In layout ');
<del> ok(view.$().html().match(/^ <div id="[^"]*" class="ember-view">In layout<\/div> $/), 'The root element has gotten the default class and ids');
<del> ok(view.$('div.ember-view[id]').length === 1, 'The div became an Ember view');
<del>
<del> run(view, 'rerender');
<add> view = appendViewFor('<non-block />');
<ide>
<del> equal(view.$().text(), ' In layout ');
<del> ok(view.$().html().match(/^ <div id="[^"]*" class="ember-view">In layout<\/div> $/), 'The root element has gotten the default class and ids');
<del> ok(view.$('div.ember-view[id]').length === 1, 'The non-block tag name was used');
<del> });
<add> let node = view.element.firstElementChild;
<add> equalsElement(node, style.tagName, { class: 'ember-view', id: regex(/^ember\d*$/) }, 'In layout');
<ide>
<del> QUnit.test('non-block without properties replaced with identity element', function() {
<del> registry.register('template:components/non-block', compile('<non-block such="{{attrs.stability}}">In layout</non-block>'));
<add> run(view, 'rerender');
<ide>
<del> view = appendViewFor('<non-block stability={{view.stability}} />', {
<del> stability: 'stability'
<add> strictEqual(node, view.element.firstElementChild, 'The inner element has not changed');
<add> equalsElement(node, style.tagName, { class: 'ember-view', id: regex(/^ember\d*$/) }, 'In layout');
<ide> });
<ide>
<del> let node = view.$()[0];
<del> equal(view.$().text(), 'In layout');
<del> equalsElement(node.firstElementChild, 'non-block', { such: 'stability', class: 'ember-view', id: regex(/^ember\d*$/) }, 'In layout');
<del> ok(view.$('non-block.ember-view[id][such=stability]').length === 1, 'The non-block tag name was used');
<add> QUnit.test(`non-block with attributes replaced with ${style.name}`, function() {
<add> registry.register('template:components/non-block', compile(` <${style.tagName} such="{{attrs.stability}}">In layout</${style.tagName}> `));
<ide>
<del> run(() => view.set('stability', 'changed!!!'));
<add> view = appendViewFor('<non-block stability={{view.stability}} />', {
<add> stability: 'stability'
<add> });
<ide>
<del> strictEqual(view.$()[0], node, 'the DOM node has remained stable');
<del> equal(view.$().text(), 'In layout');
<del> equalsElement(node.firstElementChild, 'non-block', { such: 'changed!!!', class: 'ember-view', id: regex(/^ember\d*$/) }, 'In layout');
<del> });
<add> let node = view.element.firstElementChild;
<add> equalsElement(node, style.tagName, { such: 'stability', class: 'ember-view', id: regex(/^ember\d*$/) }, 'In layout');
<ide>
<del> QUnit.test('non-block without properties replaced with identity element (regression if identity element has a single child element)', function() {
<del> registry.register('template:components/non-block', compile('<non-block such="{{attrs.stability}}"><p>In layout</p></non-block>'));
<add> run(() => view.set('stability', 'changed!!!'));
<ide>
<del> view = appendViewFor('<non-block stability={{view.stability}} />', {
<del> stability: 'stability'
<add> strictEqual(node, view.element.firstElementChild, 'The inner element has not changed');
<add> equalsElement(node, style.tagName, { such: 'changed!!!', class: 'ember-view', id: regex(/^ember\d*$/) }, 'In layout');
<ide> });
<ide>
<del> let node = view.$()[0];
<del> equal(view.$().text(), 'In layout');
<del> equalsElement(node.firstElementChild, 'non-block', { such: 'stability', class: 'ember-view', id: regex(/^ember\d*$/) }, '<p>In layout</p>');
<del> ok(view.$('non-block.ember-view[id][such=stability]').length === 1, 'The non-block tag name was used');
<add> QUnit.test(`non-block replaced with ${style.name} (regression with single element in the root element)`, function() {
<add> registry.register('template:components/non-block', compile(` <${style.tagName} such="{{attrs.stability}}"><p>In layout</p></${style.tagName}> `));
<ide>
<del> run(() => view.set('stability', 'changed!!!'));
<add> view = appendViewFor('<non-block stability={{view.stability}} />', {
<add> stability: 'stability'
<add> });
<ide>
<del> strictEqual(view.$()[0], node, 'the DOM node has remained stable');
<del> equal(view.$().text(), 'In layout');
<del> equalsElement(node.firstElementChild, 'non-block', { such: 'changed!!!', class: 'ember-view', id: regex(/^ember\d*$/) }, '<p>In layout</p>');
<del> });
<add> let node = view.element.firstElementChild;
<add> equalsElement(node, style.tagName, { such: 'stability', class: 'ember-view', id: regex(/^ember\d*$/) }, '<p>In layout</p>');
<ide>
<del> QUnit.test('non-block with class replaced with a div merges classes', function() {
<del> registry.register('template:components/non-block', compile('<div class="inner-class" />'));
<add> run(() => view.set('stability', 'changed!!!'));
<ide>
<del> view = appendViewFor('<non-block class="{{view.outer}}" />', {
<del> outer: 'outer'
<add> strictEqual(node, view.element.firstElementChild, 'The inner element has not changed');
<add> equalsElement(node, style.tagName, { such: 'changed!!!', class: 'ember-view', id: regex(/^ember\d*$/) }, '<p>In layout</p>');
<ide> });
<ide>
<del> equal(view.$('div').attr('class'), 'inner-class outer ember-view', 'the classes are merged');
<add> QUnit.test(`non-block with class replaced with ${style.name} merges classes`, function() {
<add> registry.register('template:components/non-block', compile(`<${style.tagName} class="inner-class" />`));
<ide>
<del> run(() => view.set('outer', 'new-outer'));
<add> view = appendViewFor('<non-block class="{{view.outer}}" />', {
<add> outer: 'outer'
<add> });
<ide>
<del> equal(view.$('div').attr('class'), 'inner-class new-outer ember-view', 'the classes are merged');
<del> });
<add> equal(view.$(style.tagName).attr('class'), 'inner-class outer ember-view', 'the classes are merged');
<ide>
<del> QUnit.test('non-block with class replaced with identity element merges classes', function() {
<del> registry.register('template:components/non-block', compile('<non-block class="inner-class" />'));
<add> run(() => view.set('outer', 'new-outer'));
<ide>
<del> view = appendViewFor('<non-block class="{{view.outer}}" />', {
<del> outer: 'outer'
<add> equal(view.$(style.tagName).attr('class'), 'inner-class new-outer ember-view', 'the classes are merged');
<ide> });
<ide>
<del> equal(view.$('non-block').attr('class'), 'inner-class outer ember-view', 'the classes are merged');
<del>
<del> run(() => view.set('outer', 'new-outer'));
<del>
<del> equal(view.$('non-block').attr('class'), 'inner-class new-outer ember-view', 'the classes are merged');
<del> });
<del>
<del> QUnit.test('non-block with outer attributes replaced with a div shadows inner attributes', function() {
<del> registry.register('template:components/non-block', compile('<div data-static="static" data-dynamic="{{internal}}" />'));
<del>
<del> view = appendViewFor('<non-block data-static="outer" data-dynamic="outer" />');
<del>
<del> equal(view.$('div').attr('data-static'), 'outer', 'the outer attribute wins');
<del> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer attribute wins');
<del>
<del> let component = view.childViews[0]; // HAX
<del>
<del> run(() => component.set('internal', 'changed'));
<del>
<del> equal(view.$('div').attr('data-static'), 'outer', 'the outer attribute wins');
<del> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer attribute wins');
<del> });
<del>
<del> QUnit.test('non-block with outer attributes replaced with identity element shadows inner attributes', function() {
<del> registry.register('template:components/non-block', compile('<non-block data-static="static" data-dynamic="{{internal}}" />'));
<del>
<del> view = appendViewFor('<non-block data-static="outer" data-dynamic="outer" />');
<del>
<del> equal(view.$('non-block').attr('data-static'), 'outer', 'the outer attribute wins');
<del> equal(view.$('non-block').attr('data-dynamic'), 'outer', 'the outer attribute wins');
<del>
<del> let component = view.childViews[0]; // HAX
<del>
<del> run(() => component.set('internal', 'changed'));
<del>
<del> equal(view.$('non-block').attr('data-static'), 'outer', 'the outer attribute wins');
<del> equal(view.$('non-block').attr('data-dynamic'), 'outer', 'the outer attribute wins');
<del> });
<add> QUnit.test(`non-block with outer attributes replaced with ${style.name} shadows inner attributes`, function() {
<add> registry.register('template:components/non-block', compile(`<${style.tagName} data-static="static" data-dynamic="{{internal}}" />`));
<ide>
<del> QUnit.skip('non-block recursive invocations with outer attributes replaced with a div shadows inner attributes', function() {
<del> registry.register('template:components/non-block-wrapper', compile('<non-block />'));
<del> registry.register('template:components/non-block', compile('<div data-static="static" data-dynamic="{{internal}}" />'));
<add> view = appendViewFor('<non-block data-static="outer" data-dynamic="outer" />');
<ide>
<del> view = appendViewFor('<non-block-wrapper data-static="outer" data-dynamic="outer" />');
<add> equal(view.$(style.tagName).attr('data-static'), 'outer', 'the outer attribute wins');
<add> equal(view.$(style.tagName).attr('data-dynamic'), 'outer', 'the outer attribute wins');
<ide>
<del> equal(view.$('div').attr('data-static'), 'outer', 'the outer-most attribute wins');
<del> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer-most attribute wins');
<add> let component = view.childViews[0]; // HAX
<ide>
<del> let component = view.childViews[0].childViews[0]; // HAX
<add> run(() => component.set('internal', 'changed'));
<ide>
<del> run(() => component.set('internal', 'changed'));
<del>
<del> equal(view.$('div').attr('data-static'), 'outer', 'the outer-most attribute wins');
<del> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer-most attribute wins');
<del> });
<del>
<del> QUnit.skip('non-block recursive invocations with outer attributes replaced with identity element shadows inner attributes', function() {
<del> registry.register('template:components/non-block-wrapper', compile('<non-block />'));
<del> registry.register('template:components/non-block', compile('<non-block data-static="static" data-dynamic="{{internal}}" />'));
<del>
<del> view = appendViewFor('<non-block-wrapper data-static="outer" data-dynamic="outer" />');
<del>
<del> equal(view.$('div').attr('data-static'), 'outer', 'the outer-most attribute wins');
<del> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer-most attribute wins');
<del>
<del> let component = view.childViews[0].childViews[0]; // HAX
<del>
<del> run(() => component.set('internal', 'changed'));
<del>
<del> equal(view.$('div').attr('data-static'), 'outer', 'the outer-most attribute wins');
<del> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer-most attribute wins');
<del> });
<del>
<del> QUnit.test('non-block replaced with a div should have correct scope', function() {
<del> registry.register('template:components/non-block', compile('<div>{{internal}}</div>'));
<del>
<del> registry.register('component:non-block', GlimmerComponent.extend({
<del> init() {
<del> this._super(...arguments);
<del> this.set('internal', 'stuff');
<del> }
<del> }));
<del>
<del> view = appendViewFor('<non-block />');
<del>
<del> equal(view.$().text(), 'stuff');
<del> });
<add> equal(view.$(style.tagName).attr('data-static'), 'outer', 'the outer attribute wins');
<add> equal(view.$(style.tagName).attr('data-dynamic'), 'outer', 'the outer attribute wins');
<add> });
<ide>
<del> QUnit.test('non-block replaced with identity element should have correct scope', function() {
<del> registry.register('template:components/non-block', compile('<non-block>{{internal}}</non-block>'));
<add> // TODO: When un-skipping, fix this so it handles all styles
<add> QUnit.skip('non-block recursive invocations with outer attributes replaced with a div shadows inner attributes', function() {
<add> registry.register('template:components/non-block-wrapper', compile('<non-block />'));
<add> registry.register('template:components/non-block', compile('<div data-static="static" data-dynamic="{{internal}}" />'));
<ide>
<del> registry.register('component:non-block', GlimmerComponent.extend({
<del> init() {
<del> this._super(...arguments);
<del> this.set('internal', 'stuff');
<del> }
<del> }));
<add> view = appendViewFor('<non-block-wrapper data-static="outer" data-dynamic="outer" />');
<ide>
<del> view = appendViewFor('<non-block />');
<add> equal(view.$('div').attr('data-static'), 'outer', 'the outer-most attribute wins');
<add> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer-most attribute wins');
<ide>
<del> equal(view.$().text(), 'stuff');
<del> });
<add> let component = view.childViews[0].childViews[0]; // HAX
<ide>
<del> QUnit.test('non-block replaced with a div should have correct `element`', function() {
<del> registry.register('template:components/non-block', compile('<div />'));
<add> run(() => component.set('internal', 'changed'));
<ide>
<del> let component;
<add> equal(view.$('div').attr('data-static'), 'outer', 'the outer-most attribute wins');
<add> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer-most attribute wins');
<add> });
<ide>
<del> registry.register('component:non-block', GlimmerComponent.extend({
<del> init() {
<del> this._super(...arguments);
<del> component = this;
<del> }
<del> }));
<add> QUnit.test(`non-block replaced with ${style.name} should have correct scope`, function() {
<add> registry.register('template:components/non-block', compile(`<${style.tagName}>{{internal}}</${style.tagName}>`));
<ide>
<del> view = appendViewFor('<non-block />');
<add> registry.register('component:non-block', GlimmerComponent.extend({
<add> init() {
<add> this._super(...arguments);
<add> this.set('internal', 'stuff');
<add> }
<add> }));
<ide>
<del> equal(component.element, view.$('div')[0]);
<del> });
<add> view = appendViewFor('<non-block />');
<ide>
<del> QUnit.test('non-block replaced with identity element should have correct `element`', function() {
<del> registry.register('template:components/non-block', compile('<non-block />'));
<add> equal(view.$().text(), 'stuff');
<add> });
<ide>
<del> let component;
<add> QUnit.test(`non-block replaced with ${style.name} should have correct 'element'`, function() {
<add> registry.register('template:components/non-block', compile(`<${style.tagName} />`));
<ide>
<del> registry.register('component:non-block', GlimmerComponent.extend({
<del> init() {
<del> this._super(...arguments);
<del> component = this;
<del> }
<del> }));
<add> let component;
<ide>
<del> view = appendViewFor('<non-block />');
<add> registry.register('component:non-block', GlimmerComponent.extend({
<add> init() {
<add> this._super(...arguments);
<add> component = this;
<add> }
<add> }));
<ide>
<del> equal(component.element, view.$('non-block')[0]);
<del> });
<add> view = appendViewFor('<non-block />');
<ide>
<del> QUnit.test('non-block replaced with a div should have inner attributes', function() {
<del> registry.register('template:components/non-block', compile('<div data-static="static" data-dynamic="{{internal}}" />'));
<add> equal(component.element, view.$(style.tagName)[0]);
<add> });
<ide>
<del> registry.register('component:non-block', GlimmerComponent.extend({
<del> init() {
<del> this._super(...arguments);
<del> this.set('internal', 'stuff');
<del> }
<del> }));
<add> QUnit.test(`non-block replaced with ${style.name} should have inner attributes`, function() {
<add> registry.register('template:components/non-block', compile(`<${style.tagName} data-static="static" data-dynamic="{{internal}}" />`));
<ide>
<del> view = appendViewFor('<non-block />');
<add> registry.register('component:non-block', GlimmerComponent.extend({
<add> init() {
<add> this._super(...arguments);
<add> this.set('internal', 'stuff');
<add> }
<add> }));
<ide>
<del> equal(view.$('div').attr('data-static'), 'static');
<del> equal(view.$('div').attr('data-dynamic'), 'stuff');
<del> });
<add> view = appendViewFor('<non-block />');
<ide>
<del> QUnit.test('non-block replaced with identity element should have inner attributes', function() {
<del> registry.register('template:components/non-block', compile('<non-block data-static="static" data-dynamic="{{internal}}" />'));
<add> equal(view.$(style.tagName).attr('data-static'), 'static');
<add> equal(view.$(style.tagName).attr('data-dynamic'), 'stuff');
<add> });
<ide>
<del> registry.register('component:non-block', GlimmerComponent.extend({
<del> init() {
<del> this._super(...arguments);
<del> this.set('internal', 'stuff');
<del> }
<del> }));
<add> QUnit.test(`only text attributes are reflected on the underlying DOM element (${style.name})`, function() {
<add> registry.register('template:components/non-block', compile(`<${style.tagName}>In layout</${style.tagName}>`));
<ide>
<del> view = appendViewFor('<non-block />');
<add> view = appendViewFor('<non-block static-prop="static text" concat-prop="{{view.dynamic}} text" dynamic-prop={{view.dynamic}} />', {
<add> dynamic: 'dynamic'
<add> });
<ide>
<del> equal(view.$('non-block').attr('data-static'), 'static');
<del> equal(view.$('non-block').attr('data-dynamic'), 'stuff');
<add> let el = view.$(style.tagName);
<add> ok(el, 'precond - the view was rendered');
<add> equal(el.attr('static-prop'), 'static text');
<add> equal(el.attr('concat-prop'), 'dynamic text');
<add> equal(el.attr('dynamic-prop'), undefined);
<add> });
<ide> });
<ide>
<ide> QUnit.skip('[FRAGMENT] non-block rendering a fragment', function() {
<ide> if (isEnabled('ember-htmlbars-component-generation')) {
<ide> equal(view.$('with-block.ember-view').text(), 'In layout - In template', 'Both the layout and template are rendered');
<ide> });
<ide>
<del> QUnit.test('non-block with properties on attrs', function() {
<del> registry.register('template:components/non-block', compile('<non-block>In layout</non-block>'));
<del>
<del> view = appendViewFor('<non-block static-prop="static text" concat-prop="{{view.dynamic}} text" dynamic-prop={{view.dynamic}} />', {
<del> dynamic: 'dynamic'
<del> });
<del>
<del> let el = view.$('non-block.ember-view');
<del> ok(el, 'precond - the view was rendered');
<del> equal(el.attr('static-prop'), 'static text');
<del> equal(el.attr('concat-prop'), 'dynamic text');
<del> equal(el.attr('dynamic-prop'), undefined);
<del>
<del> //equal(jQuery('#qunit-fixture').text(), 'In layout - someProp: something here');
<del> });
<del>
<ide> QUnit.test('attributes are not installed on the top level', function() {
<ide> let component;
<ide>
| 1
|
Text
|
Text
|
add missed import
|
afa22d15f15ea28806642255b5b19e7a5eb125aa
|
<ide><path>docs/recipes/ConfiguringYourStore.md
<ide> Let's add these to our existing `index.js`.
<ide> import React from 'react'
<ide> import { render } from 'react-dom'
<ide> import { Provider } from 'react-redux'
<del>import { createStore } from 'redux'
<add>import { createStore, compose } from 'redux'
<ide> import thunkMiddleware from 'redux-thunk'
<ide> import rootReducer from './reducers'
<ide> import loggerMiddleware from './middleware/logger'
| 1
|
Javascript
|
Javascript
|
remove unused inclusion of fs
|
f92188fc2702a53c1ad99b1174356845e3b28287
|
<ide><path>static/index.js
<ide> (function () {
<del> var fs = require('fs-plus')
<ide> var path = require('path')
<ide> var FileSystemBlobStore = require('../src/file-system-blob-store')
<ide> var NativeCompileCache = require('../src/native-compile-cache')
| 1
|
Go
|
Go
|
check mounts at start
|
92899ffac8ca1136e807dd234e8fa1dd49db7801
|
<ide><path>daemon/cluster/executor/container/adapter.go
<ide> import (
<ide> "errors"
<ide> "fmt"
<ide> "io"
<add> "os"
<ide> "strings"
<ide> "syscall"
<ide> "time"
<ide> func (c *containerAdapter) create(ctx context.Context) error {
<ide> return nil
<ide> }
<ide>
<add>// checkMounts ensures that the provided mounts won't have any host-specific
<add>// problems at start up. For example, we disallow bind mounts without an
<add>// existing path, which slightly different from the container API.
<add>func (c *containerAdapter) checkMounts() error {
<add> spec := c.container.spec()
<add> for _, mount := range spec.Mounts {
<add> switch mount.Type {
<add> case api.MountTypeBind:
<add> if _, err := os.Stat(mount.Source); os.IsNotExist(err) {
<add> return fmt.Errorf("invalid bind mount source, source path not found: %s", mount.Source)
<add> }
<add> }
<add> }
<add>
<add> return nil
<add>}
<add>
<ide> func (c *containerAdapter) start(ctx context.Context) error {
<add> if err := c.checkMounts(); err != nil {
<add> return err
<add> }
<add>
<ide> return c.backend.ContainerStart(c.container.name(), nil, "", "")
<ide> }
<ide>
<ide><path>daemon/cluster/executor/container/validate.go
<ide> package container
<ide> import (
<ide> "errors"
<ide> "fmt"
<del> "os"
<ide> "path/filepath"
<ide>
<ide> "github.com/docker/swarmkit/api"
<ide> func validateMounts(mounts []api.Mount) error {
<ide> if !filepath.IsAbs(mount.Source) {
<ide> return fmt.Errorf("invalid bind mount source, must be an absolute path: %s", mount.Source)
<ide> }
<del> if _, err := os.Stat(mount.Source); os.IsNotExist(err) {
<del> return fmt.Errorf("invalid bind mount source, source path not found: %s", mount.Source)
<del> }
<ide> case api.MountTypeVolume:
<ide> if filepath.IsAbs(mount.Source) {
<ide> return fmt.Errorf("invalid volume mount source, must not be an absolute path: %s", mount.Source)
<ide><path>daemon/cluster/executor/container/validate_test.go
<ide> func TestControllerValidateMountBind(t *testing.T) {
<ide> // with non-existing source
<ide> if _, err := newTestControllerWithMount(api.Mount{
<ide> Type: api.MountTypeBind,
<del> Source: "/some-non-existing-host-path/",
<add> Source: testAbsNonExistent,
<ide> Target: testAbsPath,
<del> }); err == nil || !strings.Contains(err.Error(), "invalid bind mount source") {
<del> t.Fatalf("expected error, got: %v", err)
<add> }); err != nil {
<add> t.Fatalf("controller should not error at creation: %v", err)
<ide> }
<ide>
<ide> // with proper source
<ide><path>daemon/cluster/executor/container/validate_unix_test.go
<ide> package container
<ide>
<ide> const (
<del> testAbsPath = "/foo"
<add> testAbsPath = "/foo"
<add> testAbsNonExistent = "/some-non-existing-host-path/"
<ide> )
<ide><path>daemon/cluster/executor/container/validate_windows_test.go
<add>// +build windows
<add>
<ide> package container
<ide>
<ide> const (
<del> testAbsPath = `c:\foo`
<add> testAbsPath = `c:\foo`
<add> testAbsNonExistent = `c:\some-non-existing-host-path\`
<ide> )
| 5
|
Javascript
|
Javascript
|
remove dangling comma
|
5a1b3e045f624fc3e96701c4e9b7193a49accfdd
|
<ide><path>examples/async/store/configureStore.js
<ide> export default function configureStore(initialState) {
<ide> const store = createStore(
<ide> rootReducer,
<ide> initialState,
<del> applyMiddleware(thunkMiddleware, createLogger()),
<add> applyMiddleware(thunkMiddleware, createLogger())
<ide> )
<ide>
<ide> if (module.hot) {
| 1
|
Go
|
Go
|
use new libcontainer.state api
|
262d45e0fe483dbc6d27bc6af51590a8be42d55f
|
<ide><path>daemon/execdriver/native/driver.go
<ide> func (d *driver) Unpause(c *execdriver.Command) error {
<ide>
<ide> func (d *driver) Terminate(p *execdriver.Command) error {
<ide> // lets check the start time for the process
<del> started, err := d.readStartTime(p)
<add> state, err := libcontainer.GetState(filepath.Join(d.root, p.ID))
<ide> if err != nil {
<ide> // if we don't have the data on disk then we can assume the process is gone
<ide> // because this is only removed after we know the process has stopped
<ide> func (d *driver) Terminate(p *execdriver.Command) error {
<ide> if err != nil {
<ide> return err
<ide> }
<del> if started == currentStartTime {
<add> if state.InitStartTime == currentStartTime {
<ide> err = syscall.Kill(p.Process.Pid, 9)
<ide> syscall.Wait4(p.Process.Pid, nil, 0, nil)
<ide> }
<ide> func (d *driver) Terminate(p *execdriver.Command) error {
<ide>
<ide> }
<ide>
<del>func (d *driver) readStartTime(p *execdriver.Command) (string, error) {
<del> data, err := ioutil.ReadFile(filepath.Join(d.root, p.ID, "start"))
<del> if err != nil {
<del> return "", err
<del> }
<del> return string(data), nil
<del>}
<del>
<ide> func (d *driver) Info(id string) execdriver.Info {
<ide> return &info{
<ide> ID: id,
<ide><path>daemon/execdriver/native/info.go
<ide> package native
<ide>
<ide> import (
<del> "os"
<ide> "path/filepath"
<add>
<add> "github.com/docker/libcontainer"
<ide> )
<ide>
<ide> type info struct {
<ide> type info struct {
<ide> // pid file for a container. If the file exists then the
<ide> // container is currently running
<ide> func (i *info) IsRunning() bool {
<del> if _, err := os.Stat(filepath.Join(i.driver.root, i.ID, "pid")); err == nil {
<add> if _, err := libcontainer.GetState(filepath.Join(i.driver.root, i.ID)); err == nil {
<ide> return true
<ide> }
<ide> return false
| 2
|
Javascript
|
Javascript
|
fix makeas to work with zoned moments
|
b822111d6cc806b8da11cdf4aaa309a3fcd9091c
|
<ide><path>moment.js
<ide>
<ide> // Return a moment from input, that is local/utc/zone equivalent to model.
<ide> function makeAs(input, model) {
<del> return model._isUTC ? moment(input).zone(model._offset || 0) :
<del> moment(input).local();
<add> var res, diff;
<add> if (model._isUTC) {
<add> res = model.clone();
<add> diff = (moment.isMoment(input) || isDate(input) ?
<add> +input : +moment(input)) - (+res);
<add> // Use low-level api, because this fn is low-level api.
<add> res._d.setTime(+res._d + diff);
<add> moment.updateOffset(res, false);
<add> return res;
<add> } else {
<add> return moment(input).local();
<add> }
<ide> }
<ide>
<ide> /************************************
| 1
|
Python
|
Python
|
forbid tuple inputs entirely
|
642f7e841d2f9900b3793c9b140f8c1adc56b899
|
<ide><path>numpy/core/shape_base.py
<ide> def block(arrays):
<ide>
<ide> Parameters
<ide> ----------
<del> arrays : nested list of ndarrays or scalars
<add> arrays : nested list of array_like or scalars (but not tuples)
<ide> If passed a single ndarray or scalar (a nested list of depth 0), this
<ide> is returned unmodified (and not copied).
<ide>
<ide> def format_index(index):
<ide> list_ndim = None
<ide> any_empty = False
<ide> for index, value, entering in rec.walk(arrays):
<add> if type(value) is tuple:
<add> # not strictly necessary, but saves us from:
<add> # - more than one way to do things - no point treating tuples like
<add> # lists
<add> # - horribly confusing behaviour that results when tuples are
<add> # treated like ndarray
<add> raise TypeError(
<add> '{} is a tuple. '
<add> 'Only lists can be used to arrange blocks, and np.block does '
<add> 'not allow implicit conversion from tuple to ndarray.'.format(
<add> format_index(index)
<add> )
<add> )
<ide> if not entering:
<ide> curr_depth = len(index)
<ide> elif len(value) == 0:
<ide><path>numpy/core/tests/test_shape_base.py
<ide> def test_block_simple_row_wise(self):
<ide> [1, 1, 2, 2]])
<ide> result = block([a_2d, b_2d])
<ide> assert_equal(desired, result)
<del> # with tuples
<del> result = block((a_2d, b_2d))
<del> assert_equal(desired, result)
<ide>
<ide> def test_block_simple_column_wise(self):
<ide> a_2d = np.ones((2, 2))
<ide> def test_3d(self):
<ide> def test_block_with_mismatched_shape(self):
<ide> a = np.array([0, 0])
<ide> b = np.eye(2)
<del> assert_raises(ValueError, np.block, (a, b))
<del> assert_raises(ValueError, np.block, (b, a))
<add> assert_raises(ValueError, np.block, [a, b])
<add> assert_raises(ValueError, np.block, [b, a])
<ide>
<ide> def test_no_lists(self):
<ide> assert_equal(np.block(1), np.array(1))
<ide> def test_empty_lists(self):
<ide> assert_raises_regex(ValueError, 'empty', np.block, [[]])
<ide> assert_raises_regex(ValueError, 'empty', np.block, [[1], []])
<ide>
<add> def test_tuple(self):
<add> assert_raises_regex(TypeError, 'tuple', np.block, ([1, 2], [3, 4]))
<add> assert_raises_regex(TypeError, 'tuple', np.block, [(1, 2), (3, 4)])
<add>
<ide>
<ide> if __name__ == "__main__":
<ide> run_module_suite()
| 2
|
Javascript
|
Javascript
|
escape html entities in code editor log
|
c6a11dd50ad37595d2fec70705424752d804b52e
|
<ide><path>client/src/templates/Challenges/redux/execute-challenge-saga.js
<ide> import {
<ide> getContext
<ide> } from 'redux-saga/effects';
<ide> import { channel } from 'redux-saga';
<add>import escape from 'lodash/escape';
<ide>
<ide> import {
<ide> challengeDataSelector,
<ide> export function* executeChallengeSaga() {
<ide>
<ide> function* logToConsole(channel) {
<ide> yield takeEvery(channel, function*(args) {
<del> yield put(updateLogs(args));
<add> yield put(updateLogs(escape(args)));
<ide> });
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
use the correct owner for each template lookup
|
02814c2da26a1558fb06eb527ef83e829dae7016
|
<ide><path>packages/ember-application/lib/system/engine-instance.js
<ide> import { getEngineParent, setEngineParent } from 'ember-application/system/engin
<ide> import { assert } from 'ember-metal/debug';
<ide> import run from 'ember-metal/run_loop';
<ide> import RSVP from 'ember-runtime/ext/rsvp';
<add>import { guidFor } from 'ember-metal/utils';
<ide> import isEnabled from 'ember-metal/features';
<ide>
<ide> /**
<ide> const EngineInstance = EmberObject.extend(RegistryProxy, ContainerProxy, {
<ide> init() {
<ide> this._super(...arguments);
<ide>
<add> guidFor(this);
<add>
<ide> let base = this.base;
<ide>
<ide> if (!base) {
<ide><path>packages/ember-glimmer/lib/environment.js
<add>import { guidFor } from 'ember-metal/utils';
<ide> import lookupPartial, { hasPartial } from 'ember-views/system/lookup_partial';
<ide> import {
<ide> Environment as GlimmerEnvironment,
<ide> export default class Environment extends GlimmerEnvironment {
<ide> return new CurlyComponentDefinition(name, ComponentClass, layout);
<ide> }
<ide> }, ({ name, source, owner }) => {
<del> return source && owner._resolveLocalLookupName(name, source) || name;
<add> let expandedName = source && owner._resolveLocalLookupName(name, source) || name;
<add> let ownerGuid = guidFor(owner);
<add>
<add> return ownerGuid + '|' + expandedName;
<ide> });
<ide>
<del> this._templateCache = new Cache(1000, Template => {
<del> return Template.create({ env: this });
<del> }, template => template.id);
<add> this._templateCache = new Cache(1000, ({ Template, owner }) => {
<add> return Template.create({ env: this, [OWNER]: owner });
<add> }, ({ Template, owner }) => guidFor(owner) + '|' + Template.id);
<ide>
<ide> this._compilerCache = new Cache(10, Compiler => {
<ide> return new Cache(2000, template => {
<ide> export default class Environment extends GlimmerEnvironment {
<ide> // normally templates should be exported at the proper module name
<ide> // and cached in the container, but this cache supports templates
<ide> // that have been set directly on the component's layout property
<del> getTemplate(Template) {
<del> return this._templateCache.get(Template);
<add> getTemplate(Template, owner) {
<add> return this._templateCache.get({ Template, owner });
<ide> }
<ide>
<ide> // a Compiler can wrap the template so it needs its own cache
<del> getCompiledBlock(Compiler, template) {
<add> getCompiledBlock(Compiler, template, owner) {
<ide> let compilerCache = this._compilerCache.get(Compiler);
<del> return compilerCache.get(template);
<add> return compilerCache.get(template, owner);
<ide> }
<ide>
<ide> hasPartial(name) {
<ide><path>packages/ember-glimmer/lib/syntax/curly-component.js
<ide> import get from 'ember-metal/property_get';
<ide> import { _instrumentStart } from 'ember-metal/instrumentation';
<ide> import { ComponentDefinition } from 'glimmer-runtime';
<ide> import Component from '../component';
<add>import { OWNER } from 'container/owner';
<ide>
<ide> const DEFAULT_LAYOUT = P`template:components/-default`;
<ide>
<ide> class CurlyComponentManager {
<ide>
<ide> templateFor(component, env) {
<ide> let Template = component.layout;
<add> let owner = component[OWNER];
<ide> if (Template) {
<del> return env.getTemplate(Template);
<add> return env.getTemplate(Template, owner);
<ide> }
<del> let { owner } = env;
<ide> let layoutName = get(component, 'layoutName');
<ide> if (layoutName) {
<ide> let template = owner.lookup('template:' + layoutName);
<ide><path>packages/ember-glimmer/lib/template.js
<ide> import { Template } from 'glimmer-runtime';
<add>import { OWNER } from 'container/owner';
<ide>
<ide> class Wrapper {
<del> constructor(id, env, spec) {
<del> let { owner } = env;
<add> constructor(id, env, owner, spec) {
<ide> if (spec.meta) {
<ide> spec.meta.owner = owner;
<ide> } else {
<ide> export default function template(json) {
<ide> let id = ++templateId;
<ide> return {
<ide> id,
<del> create({ env }) {
<del> return new Wrapper(id, env, JSON.parse(json));
<add> create(options) {
<add> let env = options.env;
<add> let owner = options[OWNER];
<add>
<add> return new Wrapper(id, env, owner, JSON.parse(json));
<ide> }
<ide> };
<ide> }
<ide><path>packages/ember-glimmer/tests/integration/application/engine-test.js
<add>import packageName from '../../utils/package-name';
<add>import { moduleFor, ApplicationTest } from '../../utils/test-case';
<add>import { strip } from '../../utils/abstract-test-case';
<add>import { compile } from '../../utils/helpers';
<add>import Controller from 'ember-runtime/controllers/controller';
<add>import Engine from 'ember-application/system/engine';
<add>import isEnabled from 'ember-metal/features';
<add>
<add>// only run these tests for ember-glimmer when the feature is enabled, or for
<add>// ember-htmlbars when the feature is not enabled
<add>const shouldRun = isEnabled('ember-application-engines') && (
<add> (
<add> (isEnabled('ember-glimmer') && packageName === 'glimmer') ||
<add> (!isEnabled('ember-glimmer') && packageName === 'htmlbars')
<add> )
<add>);
<add>
<add>if (shouldRun) {
<add> moduleFor('Application test: engine rendering', class extends ApplicationTest {
<add> ['@test sharing a template between engine and application has separate refinements']() {
<add> this.assert.expect(1);
<add>
<add> let sharedTemplate = compile(strip`
<add> <h1>{{contextType}}</h1>
<add> {{ambiguous-curlies}}
<add>
<add> {{outlet}}
<add> `);
<add>
<add> this.application.register('template:application', sharedTemplate);
<add> this.registerController('application', Controller.extend({
<add> contextType: 'Application',
<add> 'ambiguous-curlies': 'Controller Data!'
<add> }));
<add>
<add> this.router.map(function() {
<add> this.mount('blog');
<add> });
<add> this.application.register('route-map:blog', function() { });
<add>
<add> this.registerEngine('blog', Engine.extend({
<add> init() {
<add> this._super(...arguments);
<add>
<add> this.register('controller:application', Controller.extend({
<add> contextType: 'Engine'
<add> }));
<add> this.register('template:application', sharedTemplate);
<add> this.register('template:components/ambiguous-curlies', compile(strip`
<add> <p>Component!</p>
<add> `));
<add> }
<add> }));
<add>
<add> return this.visit('/blog').then(() => {
<add> this.assertText('ApplicationController Data!EngineComponent!');
<add> });
<add> }
<add> });
<add>}
<ide><path>packages/ember-glimmer/tests/unit/layout-cache-test.js
<ide> moduleFor('Layout cache test', class extends RenderingTest {
<ide>
<ide> templateFor(content) {
<ide> let Factory = this.compile(content);
<del> return this.env.getTemplate(Factory);
<add> return this.env.getTemplate(Factory, this.owner);
<ide> }
<ide>
<ide> ['@test each template is only compiled once'](assert) {
<ide><path>packages/ember-glimmer/tests/unit/template-factory-test.js
<ide> moduleFor('Template factory test', class extends RenderingTest {
<ide> assert.equal(env._templateCache.misses, 0, 'misses 0');
<ide> assert.equal(env._templateCache.hits, 0, 'hits 0');
<ide>
<del> let precompiled = env.getTemplate(Precompiled);
<add> let precompiled = env.getTemplate(Precompiled, env.owner);
<ide>
<ide> assert.equal(env._templateCache.misses, 1, 'misses 1');
<ide> assert.equal(env._templateCache.hits, 0, 'hits 0');
<ide>
<del> let compiled = env.getTemplate(Compiled);
<add> let compiled = env.getTemplate(Compiled, env.owner);
<ide>
<ide> assert.equal(env._templateCache.misses, 2, 'misses 2');
<ide> assert.equal(env._templateCache.hits, 0, 'hits 0');
<ide><path>packages/ember-glimmer/tests/utils/abstract-test-case.js
<ide> export class AbstractApplicationTest extends TestCase {
<ide> registerController(name, controller) {
<ide> this.application.register(`controller:${name}`, controller);
<ide> }
<add>
<add> registerEngine(name, engine) {
<add> this.application.register(`engine:${name}`, engine);
<add> }
<ide> }
<ide>
<ide> export class AbstractRenderingTest extends TestCase {
| 8
|
Javascript
|
Javascript
|
expand test coverage of fs.js
|
b19334e566650c381c4a49277b214f6ebcc55001
|
<ide><path>test/parallel/test-fs-read-file-assert-encoding.js
<add>'use strict';
<add>require('../common');
<add>
<add>const assert = require('assert');
<add>const fs = require('fs');
<add>
<add>const encoding = 'foo-8';
<add>const filename = 'bar.txt';
<add>
<add>assert.throws(
<add> fs.readFile.bind(fs, filename, { encoding }, () => {}),
<add> new RegExp(`Error: Unknown encoding: ${encoding}$`)
<add>);
| 1
|
Text
|
Text
|
remove reference to obsolete security program
|
ce1c53665e5bca0efec8d09513ed276752cc31ac
|
<ide><path>SECURITY.md
<ide> the HackerOne platform. See <https://hackerone.com/nodejs> for further details.
<ide> ## Reporting a bug in a third party module
<ide>
<ide> Security bugs in third party modules should be reported to their respective
<del>maintainers and should also be coordinated through the Node.js Ecosystem
<del>Security Team via [HackerOne](https://hackerone.com/nodejs-ecosystem).
<del>
<del>Details regarding this process can be found in the
<del>[Security Working Group repository](https://github.com/nodejs/security-wg/blob/HEAD/processes/third_party_vuln_process.md).
<del>
<del>Thank you for improving the security of Node.js and its ecosystem. Your efforts
<del>and responsible disclosure are greatly appreciated and will be acknowledged.
<add>maintainers.
<ide>
<ide> ## Disclosure policy
<ide>
| 1
|
Java
|
Java
|
add feature flag for spannable cache
|
b2454f9e669d2972ae1900fc2431b54697c68031
|
<ide><path>ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java
<ide> public static boolean doesUseOverflowInset() {
<ide> * JNI.
<ide> */
<ide> public static boolean enableLargeTextMeasureCache = true;
<add>
<add> /** TODO: T113245006 Delete this flag. Enables caching of spannables for text */
<add> public static boolean enableSpannableCache = false;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.java
<ide> import com.facebook.react.bridge.ReadableNativeMap;
<ide> import com.facebook.react.bridge.WritableArray;
<ide> import com.facebook.react.common.build.ReactBuildConfig;
<add>import com.facebook.react.config.ReactFeatureFlags;
<ide> import com.facebook.react.uimanager.PixelUtil;
<ide> import com.facebook.react.uimanager.ReactAccessibilityDelegate;
<ide> import com.facebook.react.uimanager.ReactStylesDiffMap;
<ide> public static Spannable getOrCreateSpannableForText(
<ide>
<ide> Spannable preparedSpannableText;
<ide>
<del> synchronized (sSpannableCacheLock) {
<del> preparedSpannableText = sSpannableCache.get((ReadableNativeMap) attributedString);
<del> if (preparedSpannableText != null) {
<del> return preparedSpannableText;
<add> if (ReactFeatureFlags.enableSpannableCache) {
<add> synchronized (sSpannableCacheLock) {
<add> preparedSpannableText = sSpannableCache.get((ReadableNativeMap) attributedString);
<add> if (preparedSpannableText != null) {
<add> return preparedSpannableText;
<add> }
<ide> }
<del> }
<ide>
<del> preparedSpannableText =
<del> createSpannableFromAttributedString(
<del> context, attributedString, reactTextViewManagerCallback);
<add> preparedSpannableText =
<add> createSpannableFromAttributedString(
<add> context, attributedString, reactTextViewManagerCallback);
<ide>
<del> synchronized (sSpannableCacheLock) {
<del> sSpannableCache.put((ReadableNativeMap) attributedString, preparedSpannableText);
<add> synchronized (sSpannableCacheLock) {
<add> sSpannableCache.put((ReadableNativeMap) attributedString, preparedSpannableText);
<add> }
<add> } else {
<add> preparedSpannableText =
<add> createSpannableFromAttributedString(
<add> context, attributedString, reactTextViewManagerCallback);
<ide> }
<ide>
<ide> return preparedSpannableText;
| 2
|
Javascript
|
Javascript
|
add missing constructors for all classes needed
|
13322ca35c14ca0bbe5676bae9b1aa145842e479
|
<ide><path>lib/AsyncDependenciesBlock.js
<ide> function AsyncDependenciesBlock(name, module, loc) {
<ide> module.exports = AsyncDependenciesBlock;
<ide>
<ide> AsyncDependenciesBlock.prototype = Object.create(DependenciesBlock.prototype);
<add>AsyncDependenciesBlock.prototype.constructor = AsyncDependenciesBlock;
<ide>
<ide> AsyncDependenciesBlock.prototype.updateHash = function updateHash(hash) {
<ide> hash.update(this.chunkName || "");
<ide><path>lib/CaseSensitiveModulesWarning.js
<ide> function CaseSensitiveModulesWarning(modules) {
<ide> module.exports = CaseSensitiveModulesWarning;
<ide>
<ide> CaseSensitiveModulesWarning.prototype = Object.create(Error.prototype);
<add>CaseSensitiveModulesWarning.prototype.constructor = CaseSensitiveModulesWarning;
<ide><path>lib/ChunkRenderError.js
<ide> function ChunkRenderError(chunk, file, error) {
<ide> module.exports = ChunkRenderError;
<ide>
<ide> ChunkRenderError.prototype = Object.create(Error.prototype);
<add>ChunkRenderError.prototype.constructor = ChunkRenderError;
<ide><path>lib/ChunkTemplate.js
<ide> function ChunkTemplate(outputOptions) {
<ide> module.exports = ChunkTemplate;
<ide>
<ide> ChunkTemplate.prototype = Object.create(Template.prototype);
<add>ChunkTemplate.prototype.constructor = ChunkTemplate;
<add>
<ide> ChunkTemplate.prototype.render = function(chunk, moduleTemplate, dependencyTemplates) {
<ide> var modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates);
<ide> var core = this.applyPluginsWaterfall("modules", modules, chunk, moduleTemplate, dependencyTemplates);
<ide><path>lib/ContextModule.js
<ide> function ContextModule(resolveDependencies, context, recursive, regExp, addon, a
<ide> module.exports = ContextModule;
<ide>
<ide> ContextModule.prototype = Object.create(Module.prototype);
<add>ContextModule.prototype.constructor = ContextModule;
<ide>
<ide> ContextModule.prototype.identifier = function() {
<ide> var identifier = "";
<ide><path>lib/CriticalDependenciesWarning.js
<ide> function CriticalDependenciesWarning(module, dependencies) {
<ide> module.exports = CriticalDependenciesWarning;
<ide>
<ide> CriticalDependenciesWarning.prototype = Object.create(Error.prototype);
<add>CriticalDependenciesWarning.prototype.constructor = CriticalDependenciesWarning;
<ide><path>lib/DelegatedModule.js
<ide> function DelegatedModule(sourceRequest, request, type, userRequest) {
<ide> module.exports = DelegatedModule;
<ide>
<ide> DelegatedModule.prototype = Object.create(Module.prototype);
<add>DelegatedModule.prototype.constructor = DelegatedModule;
<ide>
<ide> DelegatedModule.prototype.delegated = true;
<ide>
<ide><path>lib/DllModule.js
<ide> function DllModule(context, dependencies, name, type) {
<ide> module.exports = DllModule;
<ide>
<ide> DllModule.prototype = Object.create(Module.prototype);
<add>DllModule.prototype.constructor = DllModule;
<ide>
<ide> DllModule.prototype.identifier = function() {
<ide> return "dll " + this.name;
<ide><path>lib/EntryModuleNotFoundError.js
<ide> function EntryModuleNotFoundError(err) {
<ide> module.exports = EntryModuleNotFoundError;
<ide>
<ide> EntryModuleNotFoundError.prototype = Object.create(Error.prototype);
<add>EntryModuleNotFoundError.prototype.constructor = EntryModuleNotFoundError;
<ide><path>lib/ExternalModule.js
<ide> function ExternalModule(request, type) {
<ide> module.exports = ExternalModule;
<ide>
<ide> ExternalModule.prototype = Object.create(Module.prototype);
<add>ExternalModule.prototype.constructor = ExternalModule;
<ide>
<ide> ExternalModule.prototype.external = true;
<ide>
<ide><path>lib/HotUpdateChunkTemplate.js
<ide> function HotUpdateChunkTemplate(outputOptions) {
<ide> module.exports = HotUpdateChunkTemplate;
<ide>
<ide> HotUpdateChunkTemplate.prototype = Object.create(Template.prototype);
<add>HotUpdateChunkTemplate.prototype.constructor = HotUpdateChunkTemplate;
<add>
<ide> HotUpdateChunkTemplate.prototype.render = function(id, modules, hash, moduleTemplate, dependencyTemplates) {
<ide> var modulesSource = this.renderChunkModules({
<ide> id: id,
<ide><path>lib/MainTemplate.js
<ide> function MainTemplate(outputOptions) {
<ide> module.exports = MainTemplate;
<ide>
<ide> MainTemplate.prototype = Object.create(Template.prototype);
<add>MainTemplate.prototype.constructor = MainTemplate;
<ide> MainTemplate.prototype.requireFn = "__webpack_require__";
<ide> MainTemplate.prototype.render = function(hash, chunk, moduleTemplate, dependencyTemplates) {
<ide> var buf = [];
<ide><path>lib/ModuleBuildError.js
<ide> function ModuleBuildError(module, err) {
<ide> module.exports = ModuleBuildError;
<ide>
<ide> ModuleBuildError.prototype = Object.create(Error.prototype);
<add>ModuleBuildError.prototype.constructor = ModuleBuildError;
<ide><path>lib/ModuleError.js
<ide> function ModuleError(module, err) {
<ide> module.exports = ModuleError;
<ide>
<ide> ModuleError.prototype = Object.create(Error.prototype);
<add>ModuleError.prototype.constructor = ModuleError;
<ide><path>lib/ModuleNotFoundError.js
<ide> function ModuleNotFoundError(module, err) {
<ide> module.exports = ModuleNotFoundError;
<ide>
<ide> ModuleNotFoundError.prototype = Object.create(Error.prototype);
<add>ModuleNotFoundError.prototype.constructor = ModuleNotFoundError;
<ide><path>lib/ModuleParseError.js
<ide> function ModuleParseError(module, source, err) {
<ide> module.exports = ModuleParseError;
<ide>
<ide> ModuleParseError.prototype = Object.create(Error.prototype);
<add>ModuleParseError.prototype.constructor = ModuleParseError;
<ide><path>lib/ModuleTemplate.js
<ide> function ModuleTemplate(outputOptions) {
<ide> module.exports = ModuleTemplate;
<ide>
<ide> ModuleTemplate.prototype = Object.create(Template.prototype);
<add>ModuleTemplate.prototype.constructor = ModuleTemplate;
<ide> ModuleTemplate.prototype.render = function(module, dependencyTemplates, chunk) {
<ide> var moduleSource = module.source(dependencyTemplates, this.outputOptions, this.requestShortener);
<ide> moduleSource = this.applyPluginsWaterfall("module", moduleSource, module, chunk, dependencyTemplates);
<ide><path>lib/ModuleWarning.js
<ide> function ModuleWarning(module, warning) {
<ide> module.exports = ModuleWarning;
<ide>
<ide> ModuleWarning.prototype = Object.create(Error.prototype);
<add>ModuleWarning.prototype.constructor = ModuleWarning;
<ide><path>lib/MultiModule.js
<ide> function MultiModule(context, dependencies, name) {
<ide> module.exports = MultiModule;
<ide>
<ide> MultiModule.prototype = Object.create(Module.prototype);
<add>MultiModule.prototype.constructor = MultiModule;
<ide>
<ide> MultiModule.prototype.identifier = function() {
<ide> return "multi " + this.name;
<ide><path>lib/NormalModule.js
<ide> function NormalModule(request, userRequest, rawRequest, loaders, resource, parse
<ide> module.exports = NormalModule;
<ide>
<ide> NormalModule.prototype = Object.create(Module.prototype);
<add>NormalModule.prototype.constructor = NormalModule;
<ide>
<ide> NormalModule.prototype.identifier = function() {
<ide> return this.request;
<ide><path>lib/RawModule.js
<ide> function RawModule(source, identifier, readableIdentifier) {
<ide> module.exports = RawModule;
<ide>
<ide> RawModule.prototype = Object.create(Module.prototype);
<add>RawModule.prototype.constructor = RawModule;
<ide>
<ide> RawModule.prototype.identifier = function() {
<ide> return this.identifierStr;
<ide><path>lib/UnsupportedFeatureWarning.js
<ide> function UnsupportedFeatureWarning(module, message) {
<ide> module.exports = UnsupportedFeatureWarning;
<ide>
<ide> UnsupportedFeatureWarning.prototype = Object.create(Error.prototype);
<add>UnsupportedFeatureWarning.prototype.constructor = UnsupportedFeatureWarning;
<ide><path>lib/WebpackOptionsApply.js
<ide> function WebpackOptionsApply() {
<ide> module.exports = WebpackOptionsApply;
<ide>
<ide> WebpackOptionsApply.prototype = Object.create(OptionsApply.prototype);
<add>WebpackOptionsApply.prototype.constructor = WebpackOptionsApply;
<add>
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> var ExternalsPlugin;
<ide> compiler.context = options.context;
<ide><path>lib/dependencies/AMDRequireDependenciesBlock.js
<ide> function AMDRequireDependenciesBlock(expr, arrayRange, functionRange, module, lo
<ide> module.exports = AMDRequireDependenciesBlock;
<ide>
<ide> AMDRequireDependenciesBlock.prototype = Object.create(AsyncDependenciesBlock.prototype);
<add>AMDRequireDependenciesBlock.prototype.constructor = AMDRequireDependenciesBlock;
<ide><path>lib/dependencies/RequireEnsureDependenciesBlock.js
<ide> function RequireEnsureDependenciesBlock(expr, fnExpression, chunkName, chunkName
<ide> module.exports = RequireEnsureDependenciesBlock;
<ide>
<ide> RequireEnsureDependenciesBlock.prototype = Object.create(AsyncDependenciesBlock.prototype);
<add>RequireEnsureDependenciesBlock.prototype.constructor = RequireEnsureDependenciesBlock;
<ide><path>lib/dependencies/SystemImportDependenciesBlock.js
<ide> function SystemImportDependenciesBlock(request, range, module, loc) {
<ide> module.exports = SystemImportDependenciesBlock;
<ide>
<ide> SystemImportDependenciesBlock.prototype = Object.create(AsyncDependenciesBlock.prototype);
<add>SystemImportDependenciesBlock.prototype.constructor = SystemImportDependenciesBlock;
| 26
|
Python
|
Python
|
add new un/packbits signature to documentation
|
296b0879436e892e3b5fbb6ef6d43519e8bfe97a
|
<ide><path>numpy/core/multiarray.py
<ide> def putmask(a, mask, values):
<ide> @array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits)
<ide> def packbits(a, axis=None, bitorder='big'):
<ide> """
<del> packbits(a, axis=None)
<add> packbits(a, axis=None, bitorder='big')
<ide>
<ide> Packs the elements of a binary-valued array into bits in a uint8 array.
<ide>
<ide> def packbits(a, axis=None, bitorder='big'):
<ide> @array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits)
<ide> def unpackbits(a, axis=None, count=None, bitorder='big'):
<ide> """
<del> unpackbits(a, axis=None, count=None)
<add> unpackbits(a, axis=None, count=None, bitorder='big')
<ide>
<ide> Unpacks elements of a uint8 array into a binary-valued output array.
<ide>
| 1
|
PHP
|
PHP
|
fix cs error
|
0a1b538d54281464b094d17f55deecabf0d7441c
|
<ide><path>src/Shell/Task/ModelTask.php
<ide> public function bakeTable($model, array $data = []) {
<ide> // Work around composer caching that classes/files do not exist.
<ide> // Check for the file as it might not exist in tests.
<ide> if (file_exists($filename)) {
<del> require_once($filename);
<add> require_once ($filename);
<ide> }
<ide> TableRegistry::clear();
<ide>
| 1
|
Python
|
Python
|
manage training example & refactor the refactor
|
e0e55bc550a16289763b4f656790e30ed86e428f
|
<ide><path>transformers/data/processors/squad.py
<ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length,
<ide> features = []
<ide> new_features = []
<ide> for (example_index, example) in enumerate(tqdm(examples)):
<del>
<del> doc_tokens = []
<del> char_to_word_offset = []
<del> prev_is_whitespace = True
<del>
<del> # Split on whitespace so that different tokens may be attributed to their original position.
<del> for c in example.context_text:
<del> if _is_whitespace(c):
<del> prev_is_whitespace = True
<del> else:
<del> if prev_is_whitespace:
<del> doc_tokens.append(c)
<del> else:
<del> doc_tokens[-1] += c
<del> prev_is_whitespace = False
<del> char_to_word_offset.append(len(doc_tokens) - 1)
<del>
<ide> if is_training:
<ide> # Get start and end position
<ide> answer_length = len(example.answer_text)
<del> start_position = char_to_word_offset[example.start_position]
<del> end_position = char_to_word_offset[example.start_position + answer_length - 1]
<add> start_position = example.start_position
<add> end_position = example.end_position
<ide>
<ide> # If the answer cannot be found in the text, then skip this example.
<del> actual_text = " ".join(doc_tokens[start_position:(end_position + 1)])
<add> actual_text = " ".join(example.doc_tokens[start_position:(end_position + 1)])
<ide> cleaned_answer_text = " ".join(whitespace_tokenize(example.answer_text))
<ide> if actual_text.find(cleaned_answer_text) == -1:
<ide> logger.warning("Could not find answer: '%s' vs. '%s'", actual_text, cleaned_answer_text)
<ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length,
<ide> tok_to_orig_index = []
<ide> orig_to_tok_index = []
<ide> all_doc_tokens = []
<del> for (i, token) in enumerate(doc_tokens):
<add> for (i, token) in enumerate(example.doc_tokens):
<ide> orig_to_tok_index.append(len(all_doc_tokens))
<ide> sub_tokens = tokenizer.tokenize(token)
<ide> for sub_token in sub_tokens:
<ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length,
<ide> sequence_added_tokens = tokenizer.max_len - tokenizer.max_len_single_sentence
<ide> sequence_pair_added_tokens = tokenizer.max_len - tokenizer.max_len_sentences_pair
<ide>
<del> encoded_dict = tokenizer.encode_plus(
<del> truncated_query if not sequence_a_is_doc else all_doc_tokens,
<del> all_doc_tokens if not sequence_a_is_doc else truncated_query,
<del> max_length=max_seq_length,
<del> padding_strategy='right',
<del> stride=max_seq_length - doc_stride - len(truncated_query) - sequence_pair_added_tokens,
<del> return_overflowing_tokens=True,
<del> truncation_strategy='only_second' if not sequence_a_is_doc else 'only_first'
<del> )
<del>
<del> ids = encoded_dict['input_ids']
<del> non_padded_ids = ids[:ids.index(tokenizer.pad_token_id)] if tokenizer.pad_token_id in ids else ids
<del> paragraph_len = min(len(all_doc_tokens) - len(spans) * doc_stride, max_seq_length - len(truncated_query) - sequence_pair_added_tokens)
<del> tokens = tokenizer.convert_ids_to_tokens(non_padded_ids)
<del>
<del> token_to_orig_map = {}
<del> for i in range(paragraph_len):
<del> index = len(truncated_query) + sequence_added_tokens + i if not sequence_a_is_doc else i
<del> token_to_orig_map[index] = tok_to_orig_index[0 + i]
<del>
<del> encoded_dict["paragraph_len"] = paragraph_len
<del> encoded_dict["tokens"] = tokens
<del> encoded_dict["token_to_orig_map"] = token_to_orig_map
<del> encoded_dict["truncated_query_with_special_tokens_length"] = len(truncated_query) + sequence_added_tokens
<del> encoded_dict["token_is_max_context"] = {}
<del> encoded_dict["start"] = 0
<del> encoded_dict["length"] = paragraph_len
<del>
<del> spans.append(encoded_dict)
<del> # print("YESSIR", len(spans) * doc_stride < len(all_doc_tokens), "overflowing_tokens" in encoded_dict)
<del>
<del> while len(spans) * doc_stride < len(all_doc_tokens) and "overflowing_tokens" in encoded_dict:
<del> overflowing_tokens = encoded_dict["overflowing_tokens"]
<add> span_doc_tokens = all_doc_tokens
<add> while len(spans) * doc_stride < len(all_doc_tokens):
<add>
<ide> encoded_dict = tokenizer.encode_plus(
<del> truncated_query if not sequence_a_is_doc else overflowing_tokens,
<del> overflowing_tokens if not sequence_a_is_doc else truncated_query,
<add> truncated_query if not sequence_a_is_doc else span_doc_tokens,
<add> span_doc_tokens if not sequence_a_is_doc else truncated_query,
<ide> max_length=max_seq_length,
<ide> return_overflowing_tokens=True,
<ide> padding_strategy='right',
<ide> stride=max_seq_length - doc_stride - len(truncated_query) - sequence_pair_added_tokens,
<ide> truncation_strategy='only_second' if not sequence_a_is_doc else 'only_first'
<ide> )
<del> ids = encoded_dict['input_ids']
<del> # print("Ids computes; position of the first padding", ids.index(tokenizer.pad_token_id) if tokenizer.pad_token_id in ids else None)
<ide>
<del> # print(encoded_dict["input_ids"].index(tokenizer.pad_token_id) if tokenizer.pad_token_id in encoded_dict["input_ids"] else None)
<del> # print(len(spans) * doc_stride, len(all_doc_tokens))
<del>
<del>
<del> # Length of the document without the query
<ide> paragraph_len = min(len(all_doc_tokens) - len(spans) * doc_stride, max_seq_length - len(truncated_query) - sequence_pair_added_tokens)
<ide>
<ide> if tokenizer.pad_token_id in encoded_dict['input_ids']:
<ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length,
<ide>
<ide> spans.append(encoded_dict)
<ide>
<add> if "overflowing_tokens" not in encoded_dict:
<add> break
<add> span_doc_tokens = encoded_dict["overflowing_tokens"]
<add>
<ide> for doc_span_index in range(len(spans)):
<ide> for j in range(spans[doc_span_index]["paragraph_len"]):
<ide> is_max_context = _new_check_is_max_context(spans, doc_span_index, doc_span_index * doc_stride + j)
<ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length,
<ide>
<ide> unique_id += 1
<ide>
<del> # tokenize ...
<del> query_tokens = tokenizer.tokenize(example.question_text)
<del>
<del> if len(query_tokens) > max_query_length:
<del> query_tokens = query_tokens[0:max_query_length]
<del>
<del> tok_start_position = None
<del> tok_end_position = None
<del> if is_training and example.is_impossible:
<del> tok_start_position = -1
<del> tok_end_position = -1
<del> if is_training and not example.is_impossible:
<del> tok_start_position = orig_to_tok_index[example.start_position]
<del> if example.end_position < len(doc_tokens) - 1:
<del> tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
<del> else:
<del> tok_end_position = len(all_doc_tokens) - 1
<del> (tok_start_position, tok_end_position) = _improve_answer_span(
<del> all_doc_tokens, tok_start_position, tok_end_position, tokenizer,
<del> example.orig_answer_text)
<del>
<del> # The -3 accounts for [CLS], [SEP] and [SEP]
<del> max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
<del>
<del> # We can have documents that are longer than the maximum sequence length.
<del> # To deal with this we do a sliding window approach, where we take chunks
<del> # of the up to our max length with a stride of `doc_stride`.
<del> _DocSpan = collections.namedtuple( # pylint: disable=invalid-name
<del> "DocSpan", ["start", "length"])
<del> doc_spans = []
<del> start_offset = 0
<del> while start_offset < len(all_doc_tokens):
<del> length = len(all_doc_tokens) - start_offset
<del> if length > max_tokens_for_doc:
<del> length = max_tokens_for_doc
<del> # print("Start offset is", start_offset, len(all_doc_tokens), "length is", length)
<del> doc_spans.append(_DocSpan(start=start_offset, length=length))
<del> if start_offset + length == len(all_doc_tokens):
<del> break
<del> start_offset += min(length, doc_stride)
<del>
<del> for (doc_span_index, doc_span) in enumerate(doc_spans):
<del> tokens = []
<del> token_to_orig_map = {}
<del> token_is_max_context = {}
<del> segment_ids = []
<del>
<del> # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer)
<del> # Original TF implem also keep the classification token (set to 0) (not sure why...)
<del> p_mask = []
<del>
<del> # CLS token at the beginning
<del> if not cls_token_at_end:
<del> tokens.append(cls_token)
<del> segment_ids.append(cls_token_segment_id)
<del> p_mask.append(0)
<del> cls_index = 0
<del>
<del> # XLNet: P SEP Q SEP CLS
<del> # Others: CLS Q SEP P SEP
<del> if not sequence_a_is_doc:
<del> # Query
<del> tokens += query_tokens
<del> segment_ids += [sequence_a_segment_id] * len(query_tokens)
<del> p_mask += [1] * len(query_tokens)
<del>
<del> # SEP token
<del> tokens.append(sep_token)
<del> segment_ids.append(sequence_a_segment_id)
<del> p_mask.append(1)
<del>
<del> # Paragraph
<del> for i in range(doc_span.length):
<del> split_token_index = doc_span.start + i
<del> token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]
<del>
<del> is_max_context = _check_is_max_context(doc_spans, doc_span_index,
<del> split_token_index)
<del> token_is_max_context[len(tokens)] = is_max_context
<del> tokens.append(all_doc_tokens[split_token_index])
<del> if not sequence_a_is_doc:
<del> segment_ids.append(sequence_b_segment_id)
<del> else:
<del> segment_ids.append(sequence_a_segment_id)
<del> p_mask.append(0)
<del> paragraph_len = doc_span.length
<del>
<del> if sequence_a_is_doc:
<del> # SEP token
<del> tokens.append(sep_token)
<del> segment_ids.append(sequence_a_segment_id)
<del> p_mask.append(1)
<del>
<del> tokens += query_tokens
<del> segment_ids += [sequence_b_segment_id] * len(query_tokens)
<del> p_mask += [1] * len(query_tokens)
<del>
<del> # SEP token
<del> tokens.append(sep_token)
<del> segment_ids.append(sequence_b_segment_id)
<del> p_mask.append(1)
<del>
<del> # CLS token at the end
<del> if cls_token_at_end:
<del> tokens.append(cls_token)
<del> segment_ids.append(cls_token_segment_id)
<del> p_mask.append(0)
<del> cls_index = len(tokens) - 1 # Index of classification token
<del>
<del> input_ids = tokenizer.convert_tokens_to_ids(tokens)
<del>
<del> # The mask has 1 for real tokens and 0 for padding tokens. Only real
<del> # tokens are attended to.
<del> input_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
<del>
<del>
<del>
<del> # Zero-pad up to the sequence length.
<del> while len(input_ids) < max_seq_length:
<del> input_ids.append(pad_token)
<del> input_mask.append(0 if mask_padding_with_zero else 1)
<del> segment_ids.append(pad_token_segment_id)
<del> p_mask.append(1)
<del>
<del> assert len(input_ids) == max_seq_length
<del> assert len(input_mask) == max_seq_length
<del> assert len(segment_ids) == max_seq_length
<del>
<del> span_is_impossible = example.is_impossible if hasattr(example, "is_impossible") else False
<del> start_position = None
<del> end_position = None
<del> if is_training and not span_is_impossible:
<del> # For training, if our document chunk does not contain an annotation
<del> # we throw it out, since there is nothing to predict.
<del> doc_start = doc_span.start
<del> doc_end = doc_span.start + doc_span.length - 1
<del> out_of_span = False
<del> if not (tok_start_position >= doc_start and
<del> tok_end_position <= doc_end):
<del> out_of_span = True
<del> if out_of_span:
<del> start_position = 0
<del> end_position = 0
<del> span_is_impossible = True
<del> else:
<del> if sequence_a_is_doc:
<del> doc_offset = 0
<del> else:
<del> doc_offset = len(query_tokens) + 2
<del> start_position = tok_start_position - doc_start + doc_offset
<del> end_position = tok_end_position - doc_start + doc_offset
<del>
<del> if is_training and span_is_impossible:
<del> start_position = cls_index
<del> end_position = cls_index
<del>
<del> # if example_index < 20:
<del> # logger.info("*** Example ***")
<del> # logger.info("unique_id: %s" % (unique_id))
<del> # logger.info("example_index: %s" % (example_index))
<del> # logger.info("doc_span_index: %s" % (doc_span_index))
<del> # logger.info("tokens: %s" % str(tokens))
<del> # logger.info("token_to_orig_map: %s" % " ".join([
<del> # "%d:%d" % (x, y) for (x, y) in token_to_orig_map.items()]))
<del> # logger.info("token_is_max_context: %s" % " ".join([
<del> # "%d:%s" % (x, y) for (x, y) in token_is_max_context.items()
<del> # ]))
<del> # logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
<del> # logger.info(
<del> # "input_mask: %s" % " ".join([str(x) for x in input_mask]))
<del> # logger.info(
<del> # "segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
<del> # if is_training and span_is_impossible:
<del> # logger.info("impossible example")
<del> # if is_training and not span_is_impossible:
<del> # answer_text = " ".join(tokens[start_position:(end_position + 1)])
<del> # logger.info("start_position: %d" % (start_position))
<del> # logger.info("end_position: %d" % (end_position))
<del> # logger.info(
<del> # "answer: %s" % (answer_text))
<del>
<del> features.append(
<del> SquadFeatures(
<del> unique_id=unique_id,
<del> example_index=example_index,
<del> doc_span_index=doc_span_index,
<del> tokens=tokens,
<del> token_to_orig_map=token_to_orig_map,
<del> token_is_max_context=token_is_max_context,
<del> input_ids=input_ids,
<del> input_mask=input_mask,
<del> segment_ids=segment_ids,
<del> cls_index=cls_index,
<del> p_mask=p_mask,
<del> paragraph_len=paragraph_len,
<del> start_position=start_position,
<del> end_position=end_position,
<del> is_impossible=span_is_impossible))
<del> unique_id += 1
<del>
<del> assert len(features) == len(new_features)
<del>
<del> assert len(features) == len(new_features)
<del> for i in range(len(features)):
<del> feature, new_feature = features[i], new_features[i]
<del>
<del> input_ids = [f if f not in [3,4,5] else 0 for f in feature.input_ids ]
<del> input_mask = feature.input_mask
<del> segment_ids = feature.segment_ids
<del> cls_index = feature.cls_index
<del> p_mask = feature.p_mask
<del> example_index = feature.example_index
<del> paragraph_len = feature.paragraph_len
<del> token_is_max_context = feature.token_is_max_context
<del> tokens = feature.tokens
<del> token_to_orig_map = feature.token_to_orig_map
<del>
<del> new_input_ids = [f if f not in [3,4,5] else 0 for f in new_feature.input_ids]
<del> new_input_mask = new_feature.attention_mask
<del> new_segment_ids = new_feature.token_type_ids
<del> new_cls_index = new_feature.cls_index
<del> new_p_mask = new_feature.p_mask
<del> new_example_index = new_feature.example_index
<del> new_paragraph_len = new_feature.paragraph_len
<del> new_token_is_max_context = new_feature.token_is_max_context
<del> new_tokens = new_feature.tokens
<del> new_token_to_orig_map = new_feature.token_to_orig_map
<del>
<del> assert input_ids == new_input_ids
<del> assert input_mask == new_input_mask
<del> assert segment_ids == new_segment_ids
<del> assert cls_index == new_cls_index
<del> assert p_mask == new_p_mask
<del> assert example_index == new_example_index
<del> assert paragraph_len == new_paragraph_len
<del> assert token_is_max_context == new_token_is_max_context
<del>
<del> tokens = [t if tokenizer.convert_tokens_to_ids(t) is not tokenizer.unk_token_id else tokenizer.unk_token for t in tokens]
<del>
<del> assert tokens == new_tokens
<del> assert token_to_orig_map == new_token_to_orig_map
<del>
<del>
<ide> return new_features
<ide>
<ide>
<ide> def get_example_from_tensor_dict(self, tensor_dict):
<ide> tensor_dict['title'].numpy().decode('utf-8')
<ide> )
<ide>
<del> def get_train_examples(self, data_dir):
<add> def get_train_examples(self, data_dir, only_first=None):
<ide> """See base class."""
<ide> with open(os.path.join(data_dir, "train-v1.1.json"), "r", encoding='utf-8') as reader:
<ide> input_data = json.load(reader)["data"]
<del> return self._create_examples(input_data, "train")
<add> return self._create_examples(input_data, "train", only_first)
<ide>
<del> def get_dev_examples(self, data_dir):
<add> def get_dev_examples(self, data_dir, only_first=None):
<ide> """See base class."""
<ide> with open(os.path.join(data_dir, "dev-v1.1.json"), "r", encoding='utf-8') as reader:
<ide> input_data = json.load(reader)["data"]
<del> return self._create_examples(input_data, "dev")
<add> return self._create_examples(input_data, "dev", only_first)
<ide>
<ide> def get_labels(self):
<ide> """See base class."""
<ide> return ["0", "1"]
<ide>
<del> def _create_examples(self, input_data, set_type):
<add> def _create_examples(self, input_data, set_type, only_first=None):
<ide> """Creates examples for the training and dev sets."""
<ide>
<ide> is_training = set_type == "train"
<ide> examples = []
<del> for entry in input_data:
<add> for entry in tqdm(input_data):
<ide> title = entry['title']
<ide> for paragraph in entry["paragraphs"]:
<ide> context_text = paragraph["context"]
<ide> for qa in paragraph["qas"]:
<ide> qas_id = qa["id"]
<ide> question_text = qa["question"]
<del> start_position = None
<add> start_position_character = None
<ide> answer_text = None
<ide> if is_training:
<ide> if (len(qa["answers"]) != 1):
<ide> raise ValueError(
<ide> "For training, each question should have exactly 1 answer.")
<ide> answer = qa["answers"][0]
<ide> answer_text = answer['text']
<del> start_position = answer['answer_start']
<add> start_position_character = answer['answer_start']
<ide>
<ide> example = NewSquadExample(
<ide> qas_id=qas_id,
<ide> question_text=question_text,
<ide> context_text=context_text,
<ide> answer_text=answer_text,
<del> start_position=start_position,
<add> start_position_character=start_position_character,
<ide> title=title
<ide> )
<ide> examples.append(example)
<add>
<add> if only_first is not None and len(examples) > only_first:
<add> return examples
<ide> return examples
<ide>
<ide>
<ide> def __init__(self,
<ide> question_text,
<ide> context_text,
<ide> answer_text,
<del> start_position,
<add> start_position_character,
<ide> title):
<ide> self.qas_id = qas_id
<ide> self.question_text = question_text
<ide> self.context_text = context_text
<ide> self.answer_text = answer_text
<del> self.start_position = start_position
<ide> self.title = title
<add> self.is_impossible = False
<add>
<add> doc_tokens = []
<add> char_to_word_offset = []
<add> prev_is_whitespace = True
<add>
<add> # Split on whitespace so that different tokens may be attributed to their original position.
<add> for c in self.context_text:
<add> if _is_whitespace(c):
<add> prev_is_whitespace = True
<add> else:
<add> if prev_is_whitespace:
<add> doc_tokens.append(c)
<add> else:
<add> doc_tokens[-1] += c
<add> prev_is_whitespace = False
<add> char_to_word_offset.append(len(doc_tokens) - 1)
<add>
<add> self.doc_tokens = doc_tokens
<add> self.char_to_word_offset = char_to_word_offset
<add>
<add> # Start end end positions only has a value during evaluation.
<add> if start_position_character is not None:
<add> self.start_position = char_to_word_offset[start_position_character]
<add> self.end_position = char_to_word_offset[start_position_character + len(answer_text) - 1]
<ide>
<ide>
<ide> class NewSquadFeatures(object):
| 1
|
Mixed
|
Javascript
|
create proper public api for `channel`
|
e65bed1b7e273d1db6ba5905c8f68338b06cd27a
|
<ide><path>doc/api/child_process.md
<ide> See [Advanced Serialization][] for more details.
<ide> ### `subprocess.channel`
<ide> <!-- YAML
<ide> added: v7.1.0
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/30165
<add> description: The object no longer accidentally exposes native C++ bindings.
<ide> -->
<ide>
<ide> * {Object} A pipe representing the IPC channel to the child process.
<ide>
<ide> The `subprocess.channel` property is a reference to the child's IPC channel. If
<ide> no IPC channel currently exists, this property is `undefined`.
<ide>
<add>#### `subprocess.channel.ref()`
<add><!-- YAML
<add>added: v7.1.0
<add>-->
<add>
<add>This method makes the IPC channel keep the event loop of the parent process
<add>running if `.unref()` has been called before.
<add>
<add>#### `subprocess.channel.unref()`
<add><!-- YAML
<add>added: v7.1.0
<add>-->
<add>
<add>This method makes the IPC channel not keep the event loop of the parent process
<add>running, and lets it finish even while the channel is open.
<add>
<ide> ### `subprocess.connected`
<ide> <!-- YAML
<ide> added: v0.7.2
<ide><path>doc/api/process.md
<ide> $ bash -c 'exec -a customArgv0 ./node'
<ide> ## `process.channel`
<ide> <!-- YAML
<ide> added: v7.1.0
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/30165
<add> description: The object no longer accidentally exposes native C++ bindings.
<ide> -->
<ide>
<ide> * {Object}
<ide> If the Node.js process was spawned with an IPC channel (see the
<ide> property is a reference to the IPC channel. If no IPC channel exists, this
<ide> property is `undefined`.
<ide>
<add>### `process.channel.ref()`
<add><!-- YAML
<add>added: v7.1.0
<add>-->
<add>
<add>This method makes the IPC channel keep the event loop of the process
<add>running if `.unref()` has been called before.
<add>
<add>Typically, this is managed through the number of `'disconnect'` and `'message'`
<add>listeners on the `process` object. However, this method can be used to
<add>explicitly request a specific behavior.
<add>
<add>### `process.channel.unref()`
<add><!-- YAML
<add>added: v7.1.0
<add>-->
<add>
<add>This method makes the IPC channel not keep the event loop of the process
<add>running, and lets it finish even while the channel is open.
<add>
<add>Typically, this is managed through the number of `'disconnect'` and `'message'`
<add>listeners on the `process` object. However, this method can be used to
<add>explicitly request a specific behavior.
<add>
<ide> ## `process.chdir(directory)`
<ide> <!-- YAML
<ide> added: v0.1.17
<ide><path>lib/child_process.js
<ide> function _forkChild(fd, serializationMode) {
<ide> p.unref();
<ide> const control = setupChannel(process, p, serializationMode);
<ide> process.on('newListener', function onNewListener(name) {
<del> if (name === 'message' || name === 'disconnect') control.ref();
<add> if (name === 'message' || name === 'disconnect') control.refCounted();
<ide> });
<ide> process.on('removeListener', function onRemoveListener(name) {
<del> if (name === 'message' || name === 'disconnect') control.unref();
<add> if (name === 'message' || name === 'disconnect') control.unrefCounted();
<ide> });
<ide> }
<ide>
<ide><path>lib/internal/bootstrap/switches/is_main_thread.js
<ide> function createWritableStdioStream(fd) {
<ide> // an error when trying to use it again. In that case, create the socket
<ide> // using the existing handle instead of the fd.
<ide> if (process.channel && process.channel.fd === fd) {
<add> const { kChannelHandle } = require('internal/child_process');
<ide> stream = new net.Socket({
<del> handle: process.channel,
<add> handle: process[kChannelHandle],
<ide> readable: false,
<ide> writable: true
<ide> });
<ide><path>lib/internal/child_process.js
<ide> let freeParser;
<ide> let HTTPParser;
<ide>
<ide> const MAX_HANDLE_RETRANSMISSIONS = 3;
<add>const kChannelHandle = Symbol('kChannelHandle');
<ide> const kIsUsedAsStdio = Symbol('kIsUsedAsStdio');
<ide>
<ide> // This object contain function to convert TCP objects to native handle objects
<ide> const handleConversion = {
<ide> // The worker should keep track of the socket
<ide> message.key = socket.server._connectionKey;
<ide>
<del> const firstTime = !this.channel.sockets.send[message.key];
<add> const firstTime = !this[kChannelHandle].sockets.send[message.key];
<ide> const socketList = getSocketList('send', this, message.key);
<ide>
<ide> // The server should no longer expose a .connection property
<ide> ChildProcess.prototype.unref = function() {
<ide> };
<ide>
<ide> class Control extends EventEmitter {
<add> #channel = null;
<add> #refs = 0;
<add> #refExplicitlySet = false;
<add>
<ide> constructor(channel) {
<ide> super();
<del> this.channel = channel;
<del> this.refs = 0;
<add> this.#channel = channel;
<ide> }
<del> ref() {
<del> if (++this.refs === 1) {
<del> this.channel.ref();
<add>
<add> // The methods keeping track of the counter are being used to track the
<add> // listener count on the child process object as well as when writes are
<add> // in progress. Once the user has explicitly requested a certain state, these
<add> // methods become no-ops in order to not interfere with the user's intentions.
<add> refCounted() {
<add> if (++this.#refs === 1 && !this.#refExplicitlySet) {
<add> this.#channel.ref();
<ide> }
<ide> }
<del> unref() {
<del> if (--this.refs === 0) {
<del> this.channel.unref();
<add>
<add> unrefCounted() {
<add> if (--this.#refs === 0 && !this.#refExplicitlySet) {
<add> this.#channel.unref();
<ide> this.emit('unref');
<ide> }
<ide> }
<add>
<add> ref() {
<add> this.#refExplicitlySet = true;
<add> this.#channel.ref();
<add> }
<add>
<add> unref() {
<add> this.#refExplicitlySet = true;
<add> this.#channel.unref();
<add> }
<add>
<add> get fd() {
<add> return this.#channel ? this.#channel.fd : undefined;
<add> }
<ide> }
<ide>
<ide> const channelDeprecationMsg = '_channel is deprecated. ' +
<ide> 'Use ChildProcess.channel instead.';
<ide>
<ide> let serialization;
<ide> function setupChannel(target, channel, serializationMode) {
<del> target.channel = channel;
<add> const control = new Control(channel);
<add> target.channel = control;
<add> target[kChannelHandle] = channel;
<ide>
<ide> ObjectDefineProperty(target, '_channel', {
<ide> get: deprecate(() => {
<ide> function setupChannel(target, channel, serializationMode) {
<ide> target._handleQueue = null;
<ide> target._pendingMessage = null;
<ide>
<del> const control = new Control(channel);
<del>
<ide> if (serialization === undefined)
<ide> serialization = require('internal/child_process/serialization');
<ide> const {
<ide> function setupChannel(target, channel, serializationMode) {
<ide>
<ide> if (wasAsyncWrite) {
<ide> req.oncomplete = () => {
<del> control.unref();
<add> control.unrefCounted();
<ide> if (typeof callback === 'function')
<ide> callback(null);
<ide> };
<del> control.ref();
<add> control.refCounted();
<ide> } else if (typeof callback === 'function') {
<ide> process.nextTick(callback, null);
<ide> }
<ide> function setupChannel(target, channel, serializationMode) {
<ide>
<ide> // This marks the fact that the channel is actually disconnected.
<ide> this.channel = null;
<add> this[kChannelHandle] = null;
<ide>
<ide> if (this._pendingMessage)
<ide> closePendingHandle(this);
<ide> function getValidStdio(stdio, sync) {
<ide>
<ide>
<ide> function getSocketList(type, worker, key) {
<del> const sockets = worker.channel.sockets[type];
<add> const sockets = worker[kChannelHandle].sockets[type];
<ide> let socketList = sockets[key];
<ide> if (!socketList) {
<ide> const Construct = type === 'send' ? SocketListSend : SocketListReceive;
<ide> function spawnSync(options) {
<ide>
<ide> module.exports = {
<ide> ChildProcess,
<add> kChannelHandle,
<ide> setupChannel,
<ide> getValidStdio,
<ide> stdioStringToArray,
<ide><path>test/parallel/test-child-process-recv-handle.js
<ide> else
<ide> function master() {
<ide> // spawn() can only create one IPC channel so we use stdin/stdout as an
<ide> // ad-hoc command channel.
<del> const proc = spawn(process.execPath, [__filename, 'worker'], {
<add> const proc = spawn(process.execPath, [
<add> '--expose-internals', __filename, 'worker'
<add> ], {
<ide> stdio: ['pipe', 'pipe', 'pipe', 'ipc']
<ide> });
<ide> let handle = null;
<ide> function master() {
<ide> }
<ide>
<ide> function worker() {
<del> process.channel.readStop(); // Make messages batch up.
<add> const { kChannelHandle } = require('internal/child_process');
<add> process[kChannelHandle].readStop(); // Make messages batch up.
<ide> process.stdout.ref();
<ide> process.stdout.write('ok\r\n');
<ide> process.stdin.once('data', common.mustCall((data) => {
<ide> assert.strictEqual(data.toString(), 'ok\r\n');
<del> process.channel.readStart();
<add> process[kChannelHandle].readStart();
<ide> }));
<ide> let n = 0;
<ide> process.on('message', common.mustCall((msg, handle) => {
<ide><path>test/parallel/test-child-process-silent.js
<ide> if (process.argv[2] === 'pipe') {
<ide> const child = childProcess.fork(process.argv[1], ['pipe'], { silent: true });
<ide>
<ide> // Allow child process to self terminate
<del> child.channel.close();
<del> child.channel = null;
<add> child.disconnect();
<ide>
<ide> child.on('exit', function() {
<ide> process.exit(0);
| 7
|
Ruby
|
Ruby
|
use env instead of headers on those tests
|
38b676181b7cce5191b1877ad6781c490d38436d
|
<ide><path>actionpack/test/dispatch/show_exceptions_test.rb
<ide> def call(env)
<ide> test "skip exceptions app if not showing exceptions" do
<ide> @app = ProductionApp
<ide> assert_raise RuntimeError do
<del> get "/", headers: { "action_dispatch.show_exceptions" => false }
<add> get "/", env: { "action_dispatch.show_exceptions" => false }
<ide> end
<ide> end
<ide>
<ide> test "rescue with error page" do
<ide> @app = ProductionApp
<ide>
<del> get "/", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_response 500
<ide> assert_equal "500 error fixture\n", body
<ide>
<del> get "/bad_params", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/bad_params", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_response 400
<ide> assert_equal "400 error fixture\n", body
<ide>
<del> get "/not_found", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/not_found", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_response 404
<ide> assert_equal "404 error fixture\n", body
<ide>
<del> get "/method_not_allowed", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/method_not_allowed", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_response 405
<ide> assert_equal "", body
<ide>
<del> get "/unknown_http_method", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/unknown_http_method", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_response 405
<ide> assert_equal "", body
<ide> end
<ide> def call(env)
<ide> begin
<ide> @app = ProductionApp
<ide>
<del> get "/", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_response 500
<ide> assert_equal "500 localized error fixture\n", body
<ide>
<del> get "/not_found", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/not_found", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_response 404
<ide> assert_equal "404 error fixture\n", body
<ide> ensure
<ide> def call(env)
<ide> test "sets the HTTP charset parameter" do
<ide> @app = ProductionApp
<ide>
<del> get "/", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_equal "text/html; charset=utf-8", response.headers["Content-Type"]
<ide> end
<ide>
<ide> test "show registered original exception for wrapped exceptions" do
<ide> @app = ProductionApp
<ide>
<del> get "/not_found_original_exception", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/not_found_original_exception", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_response 404
<ide> assert_match(/404 error/, body)
<ide> end
<ide> def call(env)
<ide> end
<ide>
<ide> @app = ActionDispatch::ShowExceptions.new(Boomer.new, exceptions_app)
<del> get "/not_found_original_exception", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/not_found_original_exception", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_response 404
<ide> assert_equal "YOU FAILED", body
<ide> end
<ide> def call(env)
<ide> end
<ide>
<ide> @app = ActionDispatch::ShowExceptions.new(Boomer.new, exceptions_app)
<del> get "/method_not_allowed", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/method_not_allowed", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_response 405
<ide> assert_equal "", body
<ide> end
<ide>
<ide> test "bad params exception is returned in the correct format" do
<ide> @app = ProductionApp
<ide>
<del> get "/bad_params", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/bad_params", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_equal "text/html; charset=utf-8", response.headers["Content-Type"]
<ide> assert_response 400
<ide> assert_match(/400 error/, body)
<ide>
<del> get "/bad_params.json", headers: { "action_dispatch.show_exceptions" => true }
<add> get "/bad_params.json", env: { "action_dispatch.show_exceptions" => true }
<ide> assert_equal "application/json; charset=utf-8", response.headers["Content-Type"]
<ide> assert_response 400
<ide> assert_equal("{\"status\":400,\"error\":\"Bad Request\"}", body)
| 1
|
PHP
|
PHP
|
continue work on grammars
|
ab1627d4c08ad9437419f669ab4858f2683d7a1c
|
<ide><path>src/Illuminate/Database/Grammar.php
<ide> public function wrapArray(array $values)
<ide> */
<ide> public function wrapTable($table)
<ide> {
<del> if ($this->isExpression($table)) {
<del> return $this->getValue($table);
<add> if (! $this->isExpression($table)) {
<add> return $this->wrap($this->tablePrefix.$table, true);
<ide> }
<ide>
<del> return $this->wrap($this->tablePrefix.$table, true);
<add> return $this->getValue($table);
<ide> }
<ide>
<ide> /**
<ide> public function wrap($value, $prefixAlias = false)
<ide> // the pieces so we can wrap each of the segments of the expression on it
<ide> // own, and then joins them both back together with the "as" connector.
<ide> if (strpos(strtolower($value), ' as ') !== false) {
<del> $segments = explode(' ', $value);
<del>
<del> if ($prefixAlias) {
<del> $segments[2] = $this->tablePrefix.$segments[2];
<del> }
<del>
<del> return $this->wrap($segments[0]).' as '.$this->wrapValue($segments[2]);
<add> return $this->wrapAliasedValue($value, $prefixAlias);
<ide> }
<ide>
<del> $wrapped = [];
<add> return $this->wrapSegments(explode('.', $value));
<add> }
<ide>
<del> $segments = explode('.', $value);
<add> /**
<add> * Wrap a value that has an alias.
<add> *
<add> * @param string $value
<add> * @param bool $prefixAlias
<add> * @return string
<add> */
<add> protected function wrapAliasedValue($value, $prefixAlias = false)
<add> {
<add> $segments = explode(' ', $value);
<ide>
<del> // If the value is not an aliased table expression, we'll just wrap it like
<del> // normal, so if there is more than one segment, we will wrap the first
<del> // segments as if it was a table and the rest as just regular values.
<del> foreach ($segments as $key => $segment) {
<del> if ($key == 0 && count($segments) > 1) {
<del> $wrapped[] = $this->wrapTable($segment);
<del> } else {
<del> $wrapped[] = $this->wrapValue($segment);
<del> }
<add> // If we are wrapping a table we need to prefix the alias with the table prefix
<add> // as well in order to generate proper syntax. If this is a column of course
<add> // no prefix is necessary. The condition will be true when from wrapTable.
<add> if ($prefixAlias) {
<add> $segments[2] = $this->tablePrefix.$segments[2];
<ide> }
<ide>
<del> return implode('.', $wrapped);
<add> return $this->wrap(
<add> $segments[0]).' as '.$this->wrapValue($segments[2]
<add> );
<add> }
<add>
<add> /**
<add> * Wrap the given value segments.
<add> *
<add> * @param array $segments
<add> * @return string
<add> */
<add> protected function wrapSegments($segments)
<add> {
<add> return collect($segments)->map(function ($segment, $key) use ($segments) {
<add> return $key == 0 && count($segments) > 1
<add> ? $this->wrapTable($segment)
<add> : $this->wrapValue($segment);
<add> })->implode('.');
<ide> }
<ide>
<ide> /**
<ide> public function wrap($value, $prefixAlias = false)
<ide> */
<ide> protected function wrapValue($value)
<ide> {
<del> if ($value === '*') {
<del> return $value;
<add> if ($value !== '*') {
<add> return '"'.str_replace('"', '""', $value).'"';
<ide> }
<ide>
<del> return '"'.str_replace('"', '""', $value).'"';
<add> return $value;
<ide> }
<ide>
<ide> /**
<ide> public function parameter($value)
<ide> }
<ide>
<ide> /**
<del> * Get the value of a raw expression.
<add> * Determine if the given value is a raw expression.
<ide> *
<del> * @param \Illuminate\Database\Query\Expression $expression
<del> * @return string
<add> * @param mixed $value
<add> * @return bool
<ide> */
<del> public function getValue($expression)
<add> public function isExpression($value)
<ide> {
<del> return $expression->getValue();
<add> return $value instanceof Expression;
<ide> }
<ide>
<ide> /**
<del> * Determine if the given value is a raw expression.
<add> * Get the value of a raw expression.
<ide> *
<del> * @param mixed $value
<del> * @return bool
<add> * @param \Illuminate\Database\Query\Expression $expression
<add> * @return string
<ide> */
<del> public function isExpression($value)
<add> public function getValue($expression)
<ide> {
<del> return $value instanceof Expression;
<add> return $expression->getValue();
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Schema/Blueprint.php
<ide> public function toSql(Connection $connection, Grammar $grammar)
<ide> }
<ide>
<ide> /**
<del> * Add the commands that are implied by the blueprint.
<add> * Add the commands that are implied by the blueprint's state.
<ide> *
<ide> * @return void
<ide> */
<ide> protected function addFluentIndexes()
<ide> {
<ide> foreach ($this->columns as $column) {
<ide> foreach (['primary', 'unique', 'index'] as $index) {
<del> // If the index has been specified on the given column, but is simply
<del> // equal to "true" (boolean), no name has been specified for this
<del> // index, so we will simply call the index methods without one.
<del> if ($column->$index === true) {
<del> $this->$index($column->name);
<add> // If the index has been specified on the given column, but is simply equal
<add> // to "true" (boolean), no name has been specified for this index so the
<add> // index method can be called without a name and it will generate one.
<add> if ($column->{$index} === true) {
<add> $this->{$index}($column->name);
<ide>
<ide> continue 2;
<ide> }
<ide>
<del> // If the index has been specified on the column and it is something
<del> // other than boolean true, we will assume a name was provided on
<del> // the index specification, and pass in the name to the method.
<del> elseif (isset($column->$index)) {
<del> $this->$index($column->name, $column->$index);
<add> // If the index has been specified on the given column, and it has a string
<add> // value, we'll go ahead and call the index method and pass the name for
<add> // the index since the developer specified the explicit name for this.
<add> elseif (isset($column->{$index})) {
<add> $this->{$index}($column->name, $column->{$index});
<ide>
<ide> continue 2;
<ide> }
<ide> protected function addFluentIndexes()
<ide> */
<ide> protected function creating()
<ide> {
<del> foreach ($this->commands as $command) {
<del> if ($command->name == 'create') {
<del> return true;
<del> }
<del> }
<del>
<del> return false;
<add> return collect($this->commands)->contains(function ($command) {
<add> return $command->name == 'create';
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function bigInteger($column, $autoIncrement = false, $unsigned = false)
<ide> }
<ide>
<ide> /**
<del> * Create a new unsigned tiny integer (1-byte) column on the table.
<add> * Create a new unsigned integer (4-byte) column on the table.
<ide> *
<ide> * @param string $column
<ide> * @param bool $autoIncrement
<ide> * @return \Illuminate\Support\Fluent
<ide> */
<del> public function unsignedTinyInteger($column, $autoIncrement = false)
<add> public function unsignedInteger($column, $autoIncrement = false)
<ide> {
<del> return $this->tinyInteger($column, $autoIncrement, true);
<add> return $this->integer($column, $autoIncrement, true);
<ide> }
<ide>
<ide> /**
<del> * Create a new unsigned small integer (2-byte) column on the table.
<add> * Create a new unsigned tiny integer (1-byte) column on the table.
<ide> *
<ide> * @param string $column
<ide> * @param bool $autoIncrement
<ide> * @return \Illuminate\Support\Fluent
<ide> */
<del> public function unsignedSmallInteger($column, $autoIncrement = false)
<add> public function unsignedTinyInteger($column, $autoIncrement = false)
<ide> {
<del> return $this->smallInteger($column, $autoIncrement, true);
<add> return $this->tinyInteger($column, $autoIncrement, true);
<ide> }
<ide>
<ide> /**
<del> * Create a new unsigned medium integer (3-byte) column on the table.
<add> * Create a new unsigned small integer (2-byte) column on the table.
<ide> *
<ide> * @param string $column
<ide> * @param bool $autoIncrement
<ide> * @return \Illuminate\Support\Fluent
<ide> */
<del> public function unsignedMediumInteger($column, $autoIncrement = false)
<add> public function unsignedSmallInteger($column, $autoIncrement = false)
<ide> {
<del> return $this->mediumInteger($column, $autoIncrement, true);
<add> return $this->smallInteger($column, $autoIncrement, true);
<ide> }
<ide>
<ide> /**
<del> * Create a new unsigned integer (4-byte) column on the table.
<add> * Create a new unsigned medium integer (3-byte) column on the table.
<ide> *
<ide> * @param string $column
<ide> * @param bool $autoIncrement
<ide> * @return \Illuminate\Support\Fluent
<ide> */
<del> public function unsignedInteger($column, $autoIncrement = false)
<add> public function unsignedMediumInteger($column, $autoIncrement = false)
<ide> {
<del> return $this->integer($column, $autoIncrement, true);
<add> return $this->mediumInteger($column, $autoIncrement, true);
<ide> }
<ide>
<ide> /**
<ide> public function timestampTz($column)
<ide> /**
<ide> * Add nullable creation and update timestamps to the table.
<ide> *
<del> * Alias for self::timestamps().
<del> *
<ide> * @return void
<ide> */
<del> public function nullableTimestamps()
<add> public function timestamps()
<ide> {
<del> $this->timestamps();
<add> $this->timestamp('created_at')->nullable();
<add>
<add> $this->timestamp('updated_at')->nullable();
<ide> }
<ide>
<ide> /**
<ide> * Add nullable creation and update timestamps to the table.
<ide> *
<add> * Alias for self::timestamps().
<add> *
<ide> * @return void
<ide> */
<del> public function timestamps()
<add> public function nullableTimestamps()
<ide> {
<del> $this->timestamp('created_at')->nullable();
<del>
<del> $this->timestamp('updated_at')->nullable();
<add> $this->timestamps();
<ide> }
<ide>
<ide> /**
<ide> public function rememberToken()
<ide> return $this->string('remember_token', 100)->nullable();
<ide> }
<ide>
<add> /**
<add> * Add a new index command to the blueprint.
<add> *
<add> * @param string $type
<add> * @param string|array $columns
<add> * @param string $index
<add> * @param string|null $algorithm
<add> * @return \Illuminate\Support\Fluent
<add> */
<add> protected function indexCommand($type, $columns, $index, $algorithm = null)
<add> {
<add> $columns = (array) $columns;
<add>
<add> // If no name was specified for this index, we will create one using a basic
<add> // convention of the table name, followed by the columns, followed by an
<add> // index type, such as primary or index, which makes the index unique.
<add> $index = $index ?: $this->createIndexName($type, $columns);
<add>
<add> return $this->addCommand(
<add> $type, compact('index', 'columns', 'algorithm')
<add> );
<add> }
<add>
<ide> /**
<ide> * Create a new drop index command on the blueprint.
<ide> *
<ide> protected function dropIndexCommand($command, $type, $index)
<ide> // to drop an index merely by specifying the columns involved without the
<ide> // conventional name, so we will build the index name from the columns.
<ide> if (is_array($index)) {
<del> $columns = $index;
<del>
<del> $index = $this->createIndexName($type, $columns);
<add> $index = $this->createIndexName($type, $columns = $index);
<ide> }
<ide>
<ide> return $this->indexCommand($command, $columns, $index);
<ide> }
<ide>
<del> /**
<del> * Add a new index command to the blueprint.
<del> *
<del> * @param string $type
<del> * @param string|array $columns
<del> * @param string $index
<del> * @param string|null $algorithm
<del> * @return \Illuminate\Support\Fluent
<del> */
<del> protected function indexCommand($type, $columns, $index, $algorithm = null)
<del> {
<del> $columns = (array) $columns;
<del>
<del> // If no name was specified for this index, we will create one using a basic
<del> // convention of the table name, followed by the columns, followed by an
<del> // index type, such as primary or index, which makes the index unique.
<del> if (is_null($index)) {
<del> $index = $this->createIndexName($type, $columns);
<del> }
<del>
<del> return $this->addCommand($type, compact('index', 'columns', 'algorithm'));
<del> }
<del>
<ide> /**
<ide> * Create a default index name for the table.
<ide> *
<ide> protected function createIndexName($type, array $columns)
<ide> */
<ide> public function addColumn($type, $name, array $parameters = [])
<ide> {
<del> $attributes = array_merge(compact('type', 'name'), $parameters);
<del>
<del> $this->columns[] = $column = new Fluent($attributes);
<add> $this->columns[] = $column = new Fluent(
<add> array_merge(compact('type', 'name'), $parameters)
<add> );
<ide>
<ide> return $column;
<ide> }
<ide><path>src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php
<ide> protected function modifyComment(Blueprint $blueprint, Fluent $column)
<ide> */
<ide> protected function wrapValue($value)
<ide> {
<del> if ($value === '*') {
<del> return $value;
<add> if ($value !== '*') {
<add> return '`'.str_replace('`', '``', $value).'`';
<ide> }
<ide>
<del> return '`'.str_replace('`', '``', $value).'`';
<add> return $value;
<ide> }
<ide> }
| 3
|
Javascript
|
Javascript
|
upgrade prettier from 1.17 to 2.0.2
|
cf44650b3f4f13df8208ceded60ec5c48bd6baf3
|
<ide><path>IntegrationTests/AccessibilityManagerTest.js
<ide> class AccessibilityManagerTest extends React.Component<{...}> {
<ide> accessibilityExtraExtraLarge: 11.0,
<ide> accessibilityExtraExtraExtraLarge: 12.0,
<ide> });
<del> RCTDeviceEventEmitter.addListener('didUpdateDimensions', update => {
<add> RCTDeviceEventEmitter.addListener('didUpdateDimensions', (update) => {
<ide> TestModule.markTestPassed(update.window.fontScale === 4.0);
<ide> });
<ide> }
<ide><path>IntegrationTests/AsyncStorageTest.js
<ide> function expectAsyncNoError(place, err) {
<ide> }
<ide>
<ide> function testSetAndGet() {
<del> AsyncStorage.setItem(KEY_1, VAL_1, err1 => {
<add> AsyncStorage.setItem(KEY_1, VAL_1, (err1) => {
<ide> expectAsyncNoError('testSetAndGet/setItem', err1);
<ide> AsyncStorage.getItem(KEY_1, (err2, result) => {
<ide> expectAsyncNoError('testSetAndGet/getItem', err2);
<ide> function testRemoveItem() {
<ide> 'Missing KEY_1 or KEY_2 in ' + '(' + result + ')',
<ide> );
<ide> updateMessage('testRemoveItem - add two items');
<del> AsyncStorage.removeItem(KEY_1, err2 => {
<add> AsyncStorage.removeItem(KEY_1, (err2) => {
<ide> expectAsyncNoError('testRemoveItem/removeItem', err2);
<ide> updateMessage('delete successful ');
<ide> AsyncStorage.getItem(KEY_1, (err3, result2) => {
<ide> function testRemoveItem() {
<ide> }
<ide>
<ide> function testMerge() {
<del> AsyncStorage.setItem(KEY_MERGE, JSON.stringify(VAL_MERGE_1), err1 => {
<add> AsyncStorage.setItem(KEY_MERGE, JSON.stringify(VAL_MERGE_1), (err1) => {
<ide> expectAsyncNoError('testMerge/setItem', err1);
<del> AsyncStorage.mergeItem(KEY_MERGE, JSON.stringify(VAL_MERGE_2), err2 => {
<add> AsyncStorage.mergeItem(KEY_MERGE, JSON.stringify(VAL_MERGE_2), (err2) => {
<ide> expectAsyncNoError('testMerge/mergeItem', err2);
<ide> AsyncStorage.getItem(KEY_MERGE, (err3, result) => {
<ide> expectAsyncNoError('testMerge/setItem', err3);
<ide> function testMerge() {
<ide> }
<ide>
<ide> function testOptimizedMultiGet() {
<del> let batch = [[KEY_1, VAL_1], [KEY_2, VAL_2]];
<add> let batch = [
<add> [KEY_1, VAL_1],
<add> [KEY_2, VAL_2],
<add> ];
<ide> let keys = batch.map(([key, value]) => key);
<del> AsyncStorage.multiSet(batch, err1 => {
<add> AsyncStorage.multiSet(batch, (err1) => {
<ide> // yes, twice on purpose
<del> [1, 2].forEach(i => {
<add> [1, 2].forEach((i) => {
<ide> expectAsyncNoError(`${i} testOptimizedMultiGet/multiSet`, err1);
<ide> AsyncStorage.multiGet(keys, (err2, result) => {
<ide> expectAsyncNoError(`${i} testOptimizedMultiGet/multiGet`, err2);
<ide> class AsyncStorageTest extends React.Component<{...}, $FlowFixMeState> {
<ide> this.setState({done: true}, () => {
<ide> TestModule.markTestCompleted();
<ide> });
<del> updateMessage = msg => {
<add> updateMessage = (msg) => {
<ide> this.setState({messages: this.state.messages.concat('\n' + msg)});
<ide> DEBUG && console.log(msg);
<ide> };
<ide><path>IntegrationTests/ImageCachePolicyTest.js
<ide> class ImageCachePolicyTest extends React.Component<Props, $FlowFixMeState> {
<ide> state: $FlowFixMe | {...} = {};
<ide>
<ide> shouldComponentUpdate(nextProps: Props, nextState: State): boolean {
<del> const results: Array<?boolean> = TESTS.map(x => nextState[x]);
<add> const results: Array<?boolean> = TESTS.map((x) => nextState[x]);
<ide>
<ide> if (!results.includes(undefined)) {
<ide> const result: boolean = results.reduce(
<ide><path>IntegrationTests/IntegrationTestsApp.js
<ide> TESTS.forEach(
<ide> /* $FlowFixMe(>=0.54.0 site=react_native_fb,react_native_oss) This comment
<ide> * suppresses an error found when Flow v0.54 was deployed. To see the error
<ide> * delete this comment and run Flow. */
<del> test => AppRegistry.registerComponent(test.displayName, () => test),
<add> (test) => AppRegistry.registerComponent(test.displayName, () => test),
<ide> );
<ide>
<ide> // Modules required for integration tests
<ide> class IntegrationTestsApp extends React.Component<{...}, $FlowFixMeState> {
<ide> </Text>
<ide> <View style={styles.separator} />
<ide> <ScrollView>
<del> {TESTS.map(test => [
<add> {TESTS.map((test) => [
<ide> <TouchableOpacity
<ide> onPress={() => this.setState({test})}
<ide> /* $FlowFixMe(>=0.115.0 site=react_native_fb) This comment
<ide><path>IntegrationTests/LayoutEventsTest.js
<ide> class LayoutEventsTest extends React.Component<Props, State> {
<ide> return (
<ide> <View style={[styles.container, this.state.containerStyle]}>
<ide> <View
<del> ref={ref => {
<add> ref={(ref) => {
<ide> this._view = ref;
<ide> }}
<ide> onLayout={this.onViewLayout}
<ide> style={viewStyle}>
<ide> <Image
<del> ref={ref => {
<add> ref={(ref) => {
<ide> this._img = ref;
<ide> }}
<ide> onLayout={this.onImageLayout}
<ide> style={styles.image}
<ide> source={{uri: 'uie_thumb_big.png'}}
<ide> />
<ide> <Text
<del> ref={ref => {
<add> ref={(ref) => {
<ide> this._txt = ref;
<ide> }}
<ide> onLayout={this.onTextLayout}
<ide><path>IntegrationTests/LoggingTestModule.js
<ide> const warning = require('fbjs/lib/warning');
<ide> const invariant = require('invariant');
<ide>
<ide> const LoggingTestModule = {
<del> logToConsole: function(str) {
<add> logToConsole: function (str) {
<ide> console.log(str);
<ide> },
<del> logToConsoleAfterWait: function(str, timeout_ms) {
<del> setTimeout(function() {
<add> logToConsoleAfterWait: function (str, timeout_ms) {
<add> setTimeout(function () {
<ide> console.log(str);
<ide> }, timeout_ms);
<ide> },
<del> warning: function(str) {
<add> warning: function (str) {
<ide> warning(false, str);
<ide> },
<del> invariant: function(str) {
<add> invariant: function (str) {
<ide> invariant(false, str);
<ide> },
<del> logErrorToConsole: function(str) {
<add> logErrorToConsole: function (str) {
<ide> console.error(str);
<ide> },
<del> throwError: function(str) {
<add> throwError: function (str) {
<ide> throw new Error(str);
<ide> },
<ide> };
<ide><path>IntegrationTests/RCTRootViewIntegrationTestApp.js
<ide> const TESTS = [
<ide> require('./SizeFlexibilityUpdateTest'),
<ide> ];
<ide>
<del>TESTS.forEach(test =>
<add>TESTS.forEach((test) =>
<ide> AppRegistry.registerComponent(test.displayName, () => test),
<ide> );
<ide>
<ide> class RCTRootViewIntegrationTestApp extends React.Component {
<ide> </Text>
<ide> <View style={styles.separator} />
<ide> <ScrollView>
<del> {TESTS.map(test => [
<add> {TESTS.map((test) => [
<ide> <TouchableOpacity
<ide> onPress={() => this.setState({test})}
<ide> style={styles.row}>
<ide><path>IntegrationTests/SyncMethodTest.js
<ide> class SyncMethodTest extends React.Component<{...}> {
<ide> throw new Error('Something wrong with methodThatReturnsNil sync method');
<ide> }
<ide> let response;
<del> RNTesterTestModule.methodThatCallsCallbackWithString('test', echo => {
<add> RNTesterTestModule.methodThatCallsCallbackWithString('test', (echo) => {
<ide> response = echo;
<ide> });
<ide> requestAnimationFrame(() => {
<ide><path>IntegrationTests/TimersTest.js
<ide> class TimersTest extends React.Component<Props, State> {
<ide> fails.push(this.setTimeout(() => this._fail('testClearMulti-4'), 0));
<ide> fails.push(this.setTimeout(() => this._fail('testClearMulti-5'), 10));
<ide>
<del> fails.forEach(timeout => this.clearTimeout(timeout));
<add> fails.forEach((timeout) => this.clearTimeout(timeout));
<ide> this.setTimeout(() => this.clearTimeout(delayClear), 20);
<ide>
<ide> this.setTimeout(this.testOrdering, 50);
<ide><path>IntegrationTests/WebSocketTest.js
<ide> class WebSocketTest extends React.Component<{...}, State> {
<ide>
<ide> _waitFor = (condition: any, timeout: any, callback: any) => {
<ide> let remaining = timeout;
<del> const timeoutFunction = function() {
<add> const timeoutFunction = function () {
<ide> if (condition()) {
<ide> callback(true);
<ide> return;
<ide> class WebSocketTest extends React.Component<{...}, State> {
<ide>
<ide> _connect = () => {
<ide> const socket = new WebSocket(this.state.url);
<del> WS_EVENTS.forEach(ev => socket.addEventListener(ev, this._onSocketEvent));
<add> WS_EVENTS.forEach((ev) => socket.addEventListener(ev, this._onSocketEvent));
<ide> this.setState({
<ide> socket,
<ide> socketState: socket.readyState,
<ide> class WebSocketTest extends React.Component<{...}, State> {
<ide>
<ide> testConnect: () => void = () => {
<ide> this._connect();
<del> this._waitFor(this._socketIsConnected, 5, connectSucceeded => {
<add> this._waitFor(this._socketIsConnected, 5, (connectSucceeded) => {
<ide> if (!connectSucceeded) {
<ide> TestModule.markTestPassed(false);
<ide> return;
<ide> class WebSocketTest extends React.Component<{...}, State> {
<ide>
<ide> testSendAndReceive: () => void = () => {
<ide> this._sendTestMessage();
<del> this._waitFor(this._receivedTestExpectedResponse, 5, messageReceived => {
<add> this._waitFor(this._receivedTestExpectedResponse, 5, (messageReceived) => {
<ide> if (!messageReceived) {
<ide> TestModule.markTestPassed(false);
<ide> return;
<ide> class WebSocketTest extends React.Component<{...}, State> {
<ide>
<ide> testDisconnect: () => void = () => {
<ide> this._disconnect();
<del> this._waitFor(this._socketIsDisconnected, 5, disconnectSucceeded => {
<add> this._waitFor(this._socketIsDisconnected, 5, (disconnectSucceeded) => {
<ide> TestModule.markTestPassed(disconnectSucceeded);
<ide> });
<ide> };
<ide><path>Libraries/Alert/Alert.js
<ide> class Alert {
<ide> options && options.onDismiss && options.onDismiss();
<ide> }
<ide> };
<del> const onError = errorMessage => console.warn(errorMessage);
<add> const onError = (errorMessage) => console.warn(errorMessage);
<ide> NativeDialogManagerAndroid.showAlert(config, onError, onAction);
<ide> }
<ide> }
<ide><path>Libraries/Alert/RCTAlertManager.android.js
<ide> import NativeDialogManagerAndroid from '../NativeModules/specs/NativeDialogManag
<ide> function emptyCallback() {}
<ide>
<ide> module.exports = {
<del> alertWithArgs: function(args, callback) {
<add> alertWithArgs: function (args, callback) {
<ide> // TODO(5998984): Polyfill it correctly with DialogManagerAndroid
<ide> if (!NativeDialogManagerAndroid) {
<ide> return;
<ide><path>Libraries/Animated/release/gulpfile.js
<ide> var babelOpts = {
<ide> }),
<ide> };
<ide>
<del>var buildDist = function(opts) {
<add>var buildDist = function (opts) {
<ide> var webpackOpts = {
<ide> debug: opts.debug,
<ide> externals: {
<ide> var buildDist = function(opts) {
<ide> }),
<ide> );
<ide> }
<del> return webpackStream(webpackOpts, null, function(err, stats) {
<add> return webpackStream(webpackOpts, null, function (err, stats) {
<ide> if (err) {
<ide> throw new gulpUtil.PluginError('webpack', err);
<ide> }
<ide> var paths = {
<ide> ],
<ide> };
<ide>
<del>gulp.task('clean', function(cb) {
<add>gulp.task('clean', function (cb) {
<ide> del([paths.dist, paths.lib], cb);
<ide> });
<ide>
<del>gulp.task('modules', function() {
<add>gulp.task('modules', function () {
<ide> return gulp
<ide> .src(paths.src, {cwd: '../'})
<ide> .pipe(babel(babelOpts))
<ide> .pipe(flatten())
<ide> .pipe(gulp.dest(paths.lib));
<ide> });
<ide>
<del>gulp.task('dist', ['modules'], function() {
<add>gulp.task('dist', ['modules'], function () {
<ide> var distOpts = {
<ide> debug: true,
<ide> output: 'animated.js',
<ide> gulp.task('dist', ['modules'], function() {
<ide> .pipe(gulp.dest(paths.dist));
<ide> });
<ide>
<del>gulp.task('dist:min', ['modules'], function() {
<add>gulp.task('dist:min', ['modules'], function () {
<ide> var distOpts = {
<ide> debug: false,
<ide> output: 'animated.min.js',
<ide> gulp.task('dist:min', ['modules'], function() {
<ide> .pipe(gulp.dest(paths.dist));
<ide> });
<ide>
<del>gulp.task('watch', function() {
<add>gulp.task('watch', function () {
<ide> gulp.watch(paths.src, ['modules']);
<ide> });
<ide>
<del>gulp.task('default', function(cb) {
<add>gulp.task('default', function (cb) {
<ide> runSequence('clean', 'modules', ['dist', 'dist:min'], cb);
<ide> });
<ide><path>Libraries/Animated/src/AnimatedEvent.js
<ide> function attachNativeEvent(
<ide>
<ide> const viewTag = ReactNative.findNodeHandle(viewRef);
<ide> if (viewTag != null) {
<del> eventMappings.forEach(mapping => {
<add> eventMappings.forEach((mapping) => {
<ide> NativeAnimatedHelper.API.addAnimatedEventToView(
<ide> viewTag,
<ide> eventName,
<ide> function attachNativeEvent(
<ide> return {
<ide> detach() {
<ide> if (viewTag != null) {
<del> eventMappings.forEach(mapping => {
<add> eventMappings.forEach((mapping) => {
<ide> NativeAnimatedHelper.API.removeAnimatedEventFromView(
<ide> viewTag,
<ide> eventName,
<ide> class AnimatedEvent {
<ide> }
<ide>
<ide> __removeListener(callback: Function): void {
<del> this._listeners = this._listeners.filter(listener => listener !== callback);
<add> this._listeners = this._listeners.filter(
<add> (listener) => listener !== callback,
<add> );
<ide> }
<ide>
<ide> __attach(viewRef: any, eventName: string) {
<ide> class AnimatedEvent {
<ide> }
<ide>
<ide> _callListeners(...args: any) {
<del> this._listeners.forEach(listener => listener(...args));
<add> this._listeners.forEach((listener) => listener(...args));
<ide> }
<ide> }
<ide>
<ide><path>Libraries/Animated/src/AnimatedImplementation.js
<ide> export type CompositeAnimation = {
<ide> ...
<ide> };
<ide>
<del>const add = function(
<add>const add = function (
<ide> a: AnimatedNode | number,
<ide> b: AnimatedNode | number,
<ide> ): AnimatedAddition {
<ide> return new AnimatedAddition(a, b);
<ide> };
<ide>
<del>const subtract = function(
<add>const subtract = function (
<ide> a: AnimatedNode | number,
<ide> b: AnimatedNode | number,
<ide> ): AnimatedSubtraction {
<ide> return new AnimatedSubtraction(a, b);
<ide> };
<ide>
<del>const divide = function(
<add>const divide = function (
<ide> a: AnimatedNode | number,
<ide> b: AnimatedNode | number,
<ide> ): AnimatedDivision {
<ide> return new AnimatedDivision(a, b);
<ide> };
<ide>
<del>const multiply = function(
<add>const multiply = function (
<ide> a: AnimatedNode | number,
<ide> b: AnimatedNode | number,
<ide> ): AnimatedMultiplication {
<ide> return new AnimatedMultiplication(a, b);
<ide> };
<ide>
<del>const modulo = function(a: AnimatedNode, modulus: number): AnimatedModulo {
<add>const modulo = function (a: AnimatedNode, modulus: number): AnimatedModulo {
<ide> return new AnimatedModulo(a, modulus);
<ide> };
<ide>
<del>const diffClamp = function(
<add>const diffClamp = function (
<ide> a: AnimatedNode,
<ide> min: number,
<ide> max: number,
<ide> ): AnimatedDiffClamp {
<ide> return new AnimatedDiffClamp(a, min, max);
<ide> };
<ide>
<del>const _combineCallbacks = function(
<add>const _combineCallbacks = function (
<ide> callback: ?EndCallback,
<ide> config: {...AnimationConfig, ...},
<ide> ) {
<ide> const _combineCallbacks = function(
<ide> }
<ide> };
<ide>
<del>const maybeVectorAnim = function(
<add>const maybeVectorAnim = function (
<ide> value: AnimatedValue | AnimatedValueXY,
<ide> config: Object,
<ide> anim: (value: AnimatedValue, config: Object) => CompositeAnimation,
<ide> const maybeVectorAnim = function(
<ide> return null;
<ide> };
<ide>
<del>const spring = function(
<add>const spring = function (
<ide> value: AnimatedValue | AnimatedValueXY,
<ide> config: SpringAnimationConfig,
<ide> ): CompositeAnimation {
<del> const start = function(
<add> const start = function (
<ide> animatedValue: AnimatedValue | AnimatedValueXY,
<ide> configuration: SpringAnimationConfig,
<ide> callback?: ?EndCallback,
<ide> const spring = function(
<ide> };
<ide> return (
<ide> maybeVectorAnim(value, config, spring) || {
<del> start: function(callback?: ?EndCallback): void {
<add> start: function (callback?: ?EndCallback): void {
<ide> start(value, config, callback);
<ide> },
<ide>
<del> stop: function(): void {
<add> stop: function (): void {
<ide> value.stopAnimation();
<ide> },
<ide>
<del> reset: function(): void {
<add> reset: function (): void {
<ide> value.resetAnimation();
<ide> },
<ide>
<del> _startNativeLoop: function(iterations?: number): void {
<add> _startNativeLoop: function (iterations?: number): void {
<ide> const singleConfig = {...config, iterations};
<ide> start(value, singleConfig);
<ide> },
<ide>
<del> _isUsingNativeDriver: function(): boolean {
<add> _isUsingNativeDriver: function (): boolean {
<ide> return config.useNativeDriver || false;
<ide> },
<ide> }
<ide> );
<ide> };
<ide>
<del>const timing = function(
<add>const timing = function (
<ide> value: AnimatedValue | AnimatedValueXY,
<ide> config: TimingAnimationConfig,
<ide> ): CompositeAnimation {
<del> const start = function(
<add> const start = function (
<ide> animatedValue: AnimatedValue | AnimatedValueXY,
<ide> configuration: TimingAnimationConfig,
<ide> callback?: ?EndCallback,
<ide> const timing = function(
<ide>
<ide> return (
<ide> maybeVectorAnim(value, config, timing) || {
<del> start: function(callback?: ?EndCallback): void {
<add> start: function (callback?: ?EndCallback): void {
<ide> start(value, config, callback);
<ide> },
<ide>
<del> stop: function(): void {
<add> stop: function (): void {
<ide> value.stopAnimation();
<ide> },
<ide>
<del> reset: function(): void {
<add> reset: function (): void {
<ide> value.resetAnimation();
<ide> },
<ide>
<del> _startNativeLoop: function(iterations?: number): void {
<add> _startNativeLoop: function (iterations?: number): void {
<ide> const singleConfig = {...config, iterations};
<ide> start(value, singleConfig);
<ide> },
<ide>
<del> _isUsingNativeDriver: function(): boolean {
<add> _isUsingNativeDriver: function (): boolean {
<ide> return config.useNativeDriver || false;
<ide> },
<ide> }
<ide> );
<ide> };
<ide>
<del>const decay = function(
<add>const decay = function (
<ide> value: AnimatedValue | AnimatedValueXY,
<ide> config: DecayAnimationConfig,
<ide> ): CompositeAnimation {
<del> const start = function(
<add> const start = function (
<ide> animatedValue: AnimatedValue | AnimatedValueXY,
<ide> configuration: DecayAnimationConfig,
<ide> callback?: ?EndCallback,
<ide> const decay = function(
<ide>
<ide> return (
<ide> maybeVectorAnim(value, config, decay) || {
<del> start: function(callback?: ?EndCallback): void {
<add> start: function (callback?: ?EndCallback): void {
<ide> start(value, config, callback);
<ide> },
<ide>
<del> stop: function(): void {
<add> stop: function (): void {
<ide> value.stopAnimation();
<ide> },
<ide>
<del> reset: function(): void {
<add> reset: function (): void {
<ide> value.resetAnimation();
<ide> },
<ide>
<del> _startNativeLoop: function(iterations?: number): void {
<add> _startNativeLoop: function (iterations?: number): void {
<ide> const singleConfig = {...config, iterations};
<ide> start(value, singleConfig);
<ide> },
<ide>
<del> _isUsingNativeDriver: function(): boolean {
<add> _isUsingNativeDriver: function (): boolean {
<ide> return config.useNativeDriver || false;
<ide> },
<ide> }
<ide> );
<ide> };
<ide>
<del>const sequence = function(
<add>const sequence = function (
<ide> animations: Array<CompositeAnimation>,
<ide> ): CompositeAnimation {
<ide> let current = 0;
<ide> return {
<del> start: function(callback?: ?EndCallback) {
<del> const onComplete = function(result) {
<add> start: function (callback?: ?EndCallback) {
<add> const onComplete = function (result) {
<ide> if (!result.finished) {
<ide> callback && callback(result);
<ide> return;
<ide> const sequence = function(
<ide> }
<ide> },
<ide>
<del> stop: function() {
<add> stop: function () {
<ide> if (current < animations.length) {
<ide> animations[current].stop();
<ide> }
<ide> },
<ide>
<del> reset: function() {
<add> reset: function () {
<ide> animations.forEach((animation, idx) => {
<ide> if (idx <= current) {
<ide> animation.reset();
<ide> const sequence = function(
<ide> current = 0;
<ide> },
<ide>
<del> _startNativeLoop: function() {
<add> _startNativeLoop: function () {
<ide> throw new Error(
<ide> 'Loops run using the native driver cannot contain Animated.sequence animations',
<ide> );
<ide> },
<ide>
<del> _isUsingNativeDriver: function(): boolean {
<add> _isUsingNativeDriver: function (): boolean {
<ide> return false;
<ide> },
<ide> };
<ide> type ParallelConfig = {
<ide> stopTogether?: boolean,
<ide> ...
<ide> };
<del>const parallel = function(
<add>const parallel = function (
<ide> animations: Array<CompositeAnimation>,
<ide> config?: ?ParallelConfig,
<ide> ): CompositeAnimation {
<ide> const parallel = function(
<ide> const stopTogether = !(config && config.stopTogether === false);
<ide>
<ide> const result = {
<del> start: function(callback?: ?EndCallback) {
<add> start: function (callback?: ?EndCallback) {
<ide> if (doneCount === animations.length) {
<ide> callback && callback({finished: true});
<ide> return;
<ide> }
<ide>
<ide> animations.forEach((animation, idx) => {
<del> const cb = function(endResult) {
<add> const cb = function (endResult) {
<ide> hasEnded[idx] = true;
<ide> doneCount++;
<ide> if (doneCount === animations.length) {
<ide> const parallel = function(
<ide> });
<ide> },
<ide>
<del> stop: function(): void {
<add> stop: function (): void {
<ide> animations.forEach((animation, idx) => {
<ide> !hasEnded[idx] && animation.stop();
<ide> hasEnded[idx] = true;
<ide> });
<ide> },
<ide>
<del> reset: function(): void {
<add> reset: function (): void {
<ide> animations.forEach((animation, idx) => {
<ide> animation.reset();
<ide> hasEnded[idx] = false;
<ide> doneCount = 0;
<ide> });
<ide> },
<ide>
<del> _startNativeLoop: function() {
<add> _startNativeLoop: function () {
<ide> throw new Error(
<ide> 'Loops run using the native driver cannot contain Animated.parallel animations',
<ide> );
<ide> },
<ide>
<del> _isUsingNativeDriver: function(): boolean {
<add> _isUsingNativeDriver: function (): boolean {
<ide> return false;
<ide> },
<ide> };
<ide>
<ide> return result;
<ide> };
<ide>
<del>const delay = function(time: number): CompositeAnimation {
<add>const delay = function (time: number): CompositeAnimation {
<ide> // Would be nice to make a specialized implementation
<ide> return timing(new AnimatedValue(0), {
<ide> toValue: 0,
<ide> const delay = function(time: number): CompositeAnimation {
<ide> });
<ide> };
<ide>
<del>const stagger = function(
<add>const stagger = function (
<ide> time: number,
<ide> animations: Array<CompositeAnimation>,
<ide> ): CompositeAnimation {
<ide> type LoopAnimationConfig = {
<ide> ...
<ide> };
<ide>
<del>const loop = function(
<add>const loop = function (
<ide> animation: CompositeAnimation,
<ide> {iterations = -1, resetBeforeIteration = true}: LoopAnimationConfig = {},
<ide> ): CompositeAnimation {
<ide> let isFinished = false;
<ide> let iterationsSoFar = 0;
<ide> return {
<del> start: function(callback?: ?EndCallback) {
<del> const restart = function(result: EndResult = {finished: true}): void {
<add> start: function (callback?: ?EndCallback) {
<add> const restart = function (result: EndResult = {finished: true}): void {
<ide> if (
<ide> isFinished ||
<ide> iterationsSoFar === iterations ||
<ide> const loop = function(
<ide> }
<ide> },
<ide>
<del> stop: function(): void {
<add> stop: function (): void {
<ide> isFinished = true;
<ide> animation.stop();
<ide> },
<ide>
<del> reset: function(): void {
<add> reset: function (): void {
<ide> iterationsSoFar = 0;
<ide> isFinished = false;
<ide> animation.reset();
<ide> },
<ide>
<del> _startNativeLoop: function() {
<add> _startNativeLoop: function () {
<ide> throw new Error(
<ide> 'Loops run using the native driver cannot contain Animated.loop animations',
<ide> );
<ide> },
<ide>
<del> _isUsingNativeDriver: function(): boolean {
<add> _isUsingNativeDriver: function (): boolean {
<ide> return animation._isUsingNativeDriver();
<ide> },
<ide> };
<ide> function unforkEvent(
<ide> }
<ide> }
<ide>
<del>const event = function(
<add>const event = function (
<ide> argMapping: $ReadOnlyArray<?Mapping>,
<ide> config: EventConfig,
<ide> ): any {
<ide><path>Libraries/Animated/src/AnimatedMock.js
<ide> const emptyAnimation = {
<ide> },
<ide> };
<ide>
<del>const spring = function(
<add>const spring = function (
<ide> value: AnimatedValue | AnimatedValueXY,
<ide> config: SpringAnimationConfig,
<ide> ): CompositeAnimation {
<ide> const spring = function(
<ide> };
<ide> };
<ide>
<del>const timing = function(
<add>const timing = function (
<ide> value: AnimatedValue | AnimatedValueXY,
<ide> config: TimingAnimationConfig,
<ide> ): CompositeAnimation {
<ide> const timing = function(
<ide> };
<ide> };
<ide>
<del>const decay = function(
<add>const decay = function (
<ide> value: AnimatedValue | AnimatedValueXY,
<ide> config: DecayAnimationConfig,
<ide> ): CompositeAnimation {
<ide> return emptyAnimation;
<ide> };
<ide>
<del>const sequence = function(
<add>const sequence = function (
<ide> animations: Array<CompositeAnimation>,
<ide> ): CompositeAnimation {
<ide> return emptyAnimation;
<ide> };
<ide>
<ide> type ParallelConfig = {stopTogether?: boolean, ...};
<del>const parallel = function(
<add>const parallel = function (
<ide> animations: Array<CompositeAnimation>,
<ide> config?: ?ParallelConfig,
<ide> ): CompositeAnimation {
<ide> return emptyAnimation;
<ide> };
<ide>
<del>const delay = function(time: number): CompositeAnimation {
<add>const delay = function (time: number): CompositeAnimation {
<ide> return emptyAnimation;
<ide> };
<ide>
<del>const stagger = function(
<add>const stagger = function (
<ide> time: number,
<ide> animations: Array<CompositeAnimation>,
<ide> ): CompositeAnimation {
<ide> type LoopAnimationConfig = {
<ide> ...
<ide> };
<ide>
<del>const loop = function(
<add>const loop = function (
<ide> animation: CompositeAnimation,
<ide> {iterations = -1}: LoopAnimationConfig = {},
<ide> ): CompositeAnimation {
<ide> return emptyAnimation;
<ide> };
<ide>
<del>const event = function(argMapping: Array<?Mapping>, config: EventConfig): any {
<add>const event = function (argMapping: Array<?Mapping>, config: EventConfig): any {
<ide> return null;
<ide> };
<ide>
<ide><path>Libraries/Animated/src/Easing.js
<ide> class Easing {
<ide> */
<ide> static elastic(bounciness: number = 1): (t: number) => number {
<ide> const p = bounciness * Math.PI;
<del> return t => 1 - Math.pow(Math.cos((t * Math.PI) / 2), 3) * Math.cos(t * p);
<add> return (t) =>
<add> 1 - Math.pow(Math.cos((t * Math.PI) / 2), 3) * Math.cos(t * p);
<ide> }
<ide>
<ide> /**
<ide> class Easing {
<ide> * - http://tiny.cc/back_default (s = 1.70158, default)
<ide> */
<ide> static back(s: number = 1.70158): (t: number) => number {
<del> return t => t * t * ((s + 1) * t - s);
<add> return (t) => t * t * ((s + 1) * t - s);
<ide> }
<ide>
<ide> /**
<ide> class Easing {
<ide> * Runs an easing function backwards.
<ide> */
<ide> static out(easing: (t: number) => number): (t: number) => number {
<del> return t => 1 - easing(1 - t);
<add> return (t) => 1 - easing(1 - t);
<ide> }
<ide>
<ide> /**
<ide> class Easing {
<ide> * duration.
<ide> */
<ide> static inOut(easing: (t: number) => number): (t: number) => number {
<del> return t => {
<add> return (t) => {
<ide> if (t < 0.5) {
<ide> return easing(t * 2) / 2;
<ide> }
<ide><path>Libraries/Animated/src/NativeAnimatedHelper.js
<ide> let queue = [];
<ide> * the native module methods
<ide> */
<ide> const API = {
<del> enableQueue: function(): void {
<add> enableQueue: function (): void {
<ide> queueConnections = true;
<ide> },
<del> disableQueue: function(): void {
<add> disableQueue: function (): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> queueConnections = false;
<ide> for (let q = 0, l = queue.length; q < l; q++) {
<ide> const API = {
<ide> }
<ide> queue.length = 0;
<ide> },
<del> createAnimatedNode: function(tag: number, config: AnimatedNodeConfig): void {
<add> createAnimatedNode: function (tag: number, config: AnimatedNodeConfig): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.createAnimatedNode(tag, config);
<ide> },
<del> startListeningToAnimatedNodeValue: function(tag: number) {
<add> startListeningToAnimatedNodeValue: function (tag: number) {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.startListeningToAnimatedNodeValue(tag);
<ide> },
<del> stopListeningToAnimatedNodeValue: function(tag: number) {
<add> stopListeningToAnimatedNodeValue: function (tag: number) {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.stopListeningToAnimatedNodeValue(tag);
<ide> },
<del> connectAnimatedNodes: function(parentTag: number, childTag: number): void {
<add> connectAnimatedNodes: function (parentTag: number, childTag: number): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> if (queueConnections) {
<ide> queue.push([parentTag, childTag]);
<ide> return;
<ide> }
<ide> NativeAnimatedModule.connectAnimatedNodes(parentTag, childTag);
<ide> },
<del> disconnectAnimatedNodes: function(parentTag: number, childTag: number): void {
<add> disconnectAnimatedNodes: function (
<add> parentTag: number,
<add> childTag: number,
<add> ): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.disconnectAnimatedNodes(parentTag, childTag);
<ide> },
<del> startAnimatingNode: function(
<add> startAnimatingNode: function (
<ide> animationId: number,
<ide> nodeTag: number,
<ide> config: AnimatingNodeConfig,
<ide> const API = {
<ide> endCallback,
<ide> );
<ide> },
<del> stopAnimation: function(animationId: number) {
<add> stopAnimation: function (animationId: number) {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.stopAnimation(animationId);
<ide> },
<del> setAnimatedNodeValue: function(nodeTag: number, value: number): void {
<add> setAnimatedNodeValue: function (nodeTag: number, value: number): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.setAnimatedNodeValue(nodeTag, value);
<ide> },
<del> setAnimatedNodeOffset: function(nodeTag: number, offset: number): void {
<add> setAnimatedNodeOffset: function (nodeTag: number, offset: number): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.setAnimatedNodeOffset(nodeTag, offset);
<ide> },
<del> flattenAnimatedNodeOffset: function(nodeTag: number): void {
<add> flattenAnimatedNodeOffset: function (nodeTag: number): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.flattenAnimatedNodeOffset(nodeTag);
<ide> },
<del> extractAnimatedNodeOffset: function(nodeTag: number): void {
<add> extractAnimatedNodeOffset: function (nodeTag: number): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.extractAnimatedNodeOffset(nodeTag);
<ide> },
<del> connectAnimatedNodeToView: function(nodeTag: number, viewTag: number): void {
<add> connectAnimatedNodeToView: function (nodeTag: number, viewTag: number): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.connectAnimatedNodeToView(nodeTag, viewTag);
<ide> },
<del> disconnectAnimatedNodeFromView: function(
<add> disconnectAnimatedNodeFromView: function (
<ide> nodeTag: number,
<ide> viewTag: number,
<ide> ): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.disconnectAnimatedNodeFromView(nodeTag, viewTag);
<ide> },
<del> restoreDefaultValues: function(nodeTag: number): void {
<add> restoreDefaultValues: function (nodeTag: number): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> // Backwards compat with older native runtimes, can be removed later.
<ide> if (NativeAnimatedModule.restoreDefaultValues != null) {
<ide> NativeAnimatedModule.restoreDefaultValues(nodeTag);
<ide> }
<ide> },
<del> dropAnimatedNode: function(tag: number): void {
<add> dropAnimatedNode: function (tag: number): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.dropAnimatedNode(tag);
<ide> },
<del> addAnimatedEventToView: function(
<add> addAnimatedEventToView: function (
<ide> viewTag: number,
<ide> eventName: string,
<ide> eventMapping: EventMapping,
<ide> function validateTransform(
<ide> },
<ide> >,
<ide> ): void {
<del> configs.forEach(config => {
<add> configs.forEach((config) => {
<ide> if (!TRANSFORM_WHITELIST.hasOwnProperty(config.property)) {
<ide> throw new Error(
<del> `Property '${
<del> config.property
<del> }' is not supported by native animated module`,
<add> `Property '${config.property}' is not supported by native animated module`,
<ide> );
<ide> }
<ide> });
<ide><path>Libraries/Animated/src/__tests__/AnimatedMock-test.js
<ide> describe('Animated Mock', () => {
<ide> Object.keys(AnimatedImplementation),
<ide> );
<ide> });
<del> it('matches implementation params', done => {
<del> Object.keys(AnimatedImplementation).forEach(key => {
<add> it('matches implementation params', (done) => {
<add> Object.keys(AnimatedImplementation).forEach((key) => {
<ide> if (AnimatedImplementation[key].length !== AnimatedMock[key].length) {
<ide> done(
<ide> new Error(
<ide><path>Libraries/Animated/src/__tests__/AnimatedNative-test.js
<ide> describe('Native Animated', () => {
<ide> {type: 'addition', input: expect.any(Array)},
<ide> );
<ide> const additionCalls = NativeAnimatedModule.createAnimatedNode.mock.calls.filter(
<del> call => call[1].type === 'addition',
<add> (call) => call[1].type === 'addition',
<ide> );
<ide> expect(additionCalls.length).toBe(1);
<ide> const additionCall = additionCalls[0];
<ide> const additionNodeTag = additionCall[0];
<ide> const additionConnectionCalls = NativeAnimatedModule.connectAnimatedNodes.mock.calls.filter(
<del> call => call[1] === additionNodeTag,
<add> (call) => call[1] === additionNodeTag,
<ide> );
<ide> expect(additionConnectionCalls.length).toBe(2);
<ide> expect(NativeAnimatedModule.createAnimatedNode).toBeCalledWith(
<ide> additionCall[1].input[0],
<del> {type: 'value', value: 1, offset: 0},
<add> {
<add> type: 'value',
<add> value: 1,
<add> offset: 0,
<add> },
<ide> );
<ide> expect(NativeAnimatedModule.createAnimatedNode).toBeCalledWith(
<ide> additionCall[1].input[1],
<del> {type: 'value', value: 2, offset: 0},
<add> {
<add> type: 'value',
<add> value: 2,
<add> offset: 0,
<add> },
<ide> );
<ide> });
<ide>
<ide> describe('Native Animated', () => {
<ide> {type: 'subtraction', input: expect.any(Array)},
<ide> );
<ide> const subtractionCalls = NativeAnimatedModule.createAnimatedNode.mock.calls.filter(
<del> call => call[1].type === 'subtraction',
<add> (call) => call[1].type === 'subtraction',
<ide> );
<ide> expect(subtractionCalls.length).toBe(1);
<ide> const subtractionCall = subtractionCalls[0];
<ide> const subtractionNodeTag = subtractionCall[0];
<ide> const subtractionConnectionCalls = NativeAnimatedModule.connectAnimatedNodes.mock.calls.filter(
<del> call => call[1] === subtractionNodeTag,
<add> (call) => call[1] === subtractionNodeTag,
<ide> );
<ide> expect(subtractionConnectionCalls.length).toBe(2);
<ide> expect(NativeAnimatedModule.createAnimatedNode).toBeCalledWith(
<ide> subtractionCall[1].input[0],
<del> {type: 'value', value: 2, offset: 0},
<add> {
<add> type: 'value',
<add> value: 2,
<add> offset: 0,
<add> },
<ide> );
<ide> expect(NativeAnimatedModule.createAnimatedNode).toBeCalledWith(
<ide> subtractionCall[1].input[1],
<del> {type: 'value', value: 1, offset: 0},
<add> {
<add> type: 'value',
<add> value: 1,
<add> offset: 0,
<add> },
<ide> );
<ide> });
<ide>
<ide> describe('Native Animated', () => {
<ide> {type: 'multiplication', input: expect.any(Array)},
<ide> );
<ide> const multiplicationCalls = NativeAnimatedModule.createAnimatedNode.mock.calls.filter(
<del> call => call[1].type === 'multiplication',
<add> (call) => call[1].type === 'multiplication',
<ide> );
<ide> expect(multiplicationCalls.length).toBe(1);
<ide> const multiplicationCall = multiplicationCalls[0];
<ide> const multiplicationNodeTag = multiplicationCall[0];
<ide> const multiplicationConnectionCalls = NativeAnimatedModule.connectAnimatedNodes.mock.calls.filter(
<del> call => call[1] === multiplicationNodeTag,
<add> (call) => call[1] === multiplicationNodeTag,
<ide> );
<ide> expect(multiplicationConnectionCalls.length).toBe(2);
<ide> expect(NativeAnimatedModule.createAnimatedNode).toBeCalledWith(
<ide> multiplicationCall[1].input[0],
<del> {type: 'value', value: 2, offset: 0},
<add> {
<add> type: 'value',
<add> value: 2,
<add> offset: 0,
<add> },
<ide> );
<ide> expect(NativeAnimatedModule.createAnimatedNode).toBeCalledWith(
<ide> multiplicationCall[1].input[1],
<del> {type: 'value', value: 1, offset: 0},
<add> {
<add> type: 'value',
<add> value: 1,
<add> offset: 0,
<add> },
<ide> );
<ide> });
<ide>
<ide> describe('Native Animated', () => {
<ide> {type: 'division', input: expect.any(Array)},
<ide> );
<ide> const divisionCalls = NativeAnimatedModule.createAnimatedNode.mock.calls.filter(
<del> call => call[1].type === 'division',
<add> (call) => call[1].type === 'division',
<ide> );
<ide> expect(divisionCalls.length).toBe(1);
<ide> const divisionCall = divisionCalls[0];
<ide> const divisionNodeTag = divisionCall[0];
<ide> const divisionConnectionCalls = NativeAnimatedModule.connectAnimatedNodes.mock.calls.filter(
<del> call => call[1] === divisionNodeTag,
<add> (call) => call[1] === divisionNodeTag,
<ide> );
<ide> expect(divisionConnectionCalls.length).toBe(2);
<ide> expect(NativeAnimatedModule.createAnimatedNode).toBeCalledWith(
<ide> divisionCall[1].input[0],
<del> {type: 'value', value: 4, offset: 0},
<add> {
<add> type: 'value',
<add> value: 4,
<add> offset: 0,
<add> },
<ide> );
<ide> expect(NativeAnimatedModule.createAnimatedNode).toBeCalledWith(
<ide> divisionCall[1].input[1],
<del> {type: 'value', value: 2, offset: 0},
<add> {
<add> type: 'value',
<add> value: 2,
<add> offset: 0,
<add> },
<ide> );
<ide> });
<ide>
<ide> describe('Native Animated', () => {
<ide> {type: 'modulus', modulus: 4, input: expect.any(Number)},
<ide> );
<ide> const moduloCalls = NativeAnimatedModule.createAnimatedNode.mock.calls.filter(
<del> call => call[1].type === 'modulus',
<add> (call) => call[1].type === 'modulus',
<ide> );
<ide> expect(moduloCalls.length).toBe(1);
<ide> const moduloCall = moduloCalls[0];
<ide> const moduloNodeTag = moduloCall[0];
<ide> const moduloConnectionCalls = NativeAnimatedModule.connectAnimatedNodes.mock.calls.filter(
<del> call => call[1] === moduloNodeTag,
<add> (call) => call[1] === moduloNodeTag,
<ide> );
<ide> expect(moduloConnectionCalls.length).toBe(1);
<ide> expect(NativeAnimatedModule.createAnimatedNode).toBeCalledWith(
<ide> moduloCall[1].input,
<del> {type: 'value', value: 4, offset: 0},
<add> {
<add> type: 'value',
<add> value: 4,
<add> offset: 0,
<add> },
<ide> );
<ide> });
<ide>
<ide> describe('Native Animated', () => {
<ide> },
<ide> );
<ide> const interpolationNodeTag = NativeAnimatedModule.createAnimatedNode.mock.calls.find(
<del> call => call[1].type === 'interpolation',
<add> (call) => call[1].type === 'interpolation',
<ide> )[0];
<ide> const valueNodeTag = NativeAnimatedModule.createAnimatedNode.mock.calls.find(
<del> call => call[1].type === 'value',
<add> (call) => call[1].type === 'value',
<ide> )[0];
<ide> expect(NativeAnimatedModule.connectAnimatedNodes).toBeCalledWith(
<ide> valueNodeTag,
<ide> describe('Native Animated', () => {
<ide> {type: 'diffclamp', input: expect.any(Number), max: 20, min: 0},
<ide> );
<ide> const diffClampCalls = NativeAnimatedModule.createAnimatedNode.mock.calls.filter(
<del> call => call[1].type === 'diffclamp',
<add> (call) => call[1].type === 'diffclamp',
<ide> );
<ide> expect(diffClampCalls.length).toBe(1);
<ide> const diffClampCall = diffClampCalls[0];
<ide> const diffClampNodeTag = diffClampCall[0];
<ide> const diffClampConnectionCalls = NativeAnimatedModule.connectAnimatedNodes.mock.calls.filter(
<del> call => call[1] === diffClampNodeTag,
<add> (call) => call[1] === diffClampNodeTag,
<ide> );
<ide> expect(diffClampConnectionCalls.length).toBe(1);
<ide> expect(NativeAnimatedModule.createAnimatedNode).toBeCalledWith(
<ide> diffClampCall[1].input,
<del> {type: 'value', value: 2, offset: 0},
<add> {
<add> type: 'value',
<add> value: 2,
<add> offset: 0,
<add> },
<ide> );
<ide> });
<ide>
<ide><path>Libraries/Animated/src/__tests__/Easing-test.js
<ide> describe('Easing', () => {
<ide> ],
<ide> };
<ide>
<del> Object.keys(Samples).forEach(function(type) {
<del> it('should ease ' + type, function() {
<add> Object.keys(Samples).forEach(function (type) {
<add> it('should ease ' + type, function () {
<ide> const [modeName, easingName, isFunction] = type.split('_');
<ide> let easing = Easing[easingName];
<ide> if (isFunction !== undefined) {
<ide><path>Libraries/Animated/src/__tests__/bezier-test.js
<ide>
<ide> const bezier = require('../bezier');
<ide>
<del>const identity = function(x) {
<add>const identity = function (x) {
<ide> return x;
<ide> };
<ide>
<ide> function assertClose(a, b, precision = 3) {
<ide> }
<ide>
<ide> function makeAssertCloseWithPrecision(precision) {
<del> return function(a, b) {
<add> return function (a, b) {
<ide> assertClose(a, b, precision);
<ide> };
<ide> }
<ide> function allEquals(be1, be2, samples, assertion) {
<ide> }
<ide>
<ide> function repeat(n) {
<del> return function(f) {
<add> return function (f) {
<ide> for (let i = 0; i < n; ++i) {
<ide> f();
<ide> }
<ide> };
<ide> }
<ide>
<del>describe('bezier', function() {
<del> it('should be a function', function() {
<add>describe('bezier', function () {
<add> it('should be a function', function () {
<ide> expect(typeof bezier === 'function').toBe(true);
<ide> });
<del> it('should creates an object', function() {
<add> it('should creates an object', function () {
<ide> expect(typeof bezier(0, 0, 1, 1) === 'function').toBe(true);
<ide> });
<del> it('should fail with wrong arguments', function() {
<del> expect(function() {
<add> it('should fail with wrong arguments', function () {
<add> expect(function () {
<ide> bezier(0.5, 0.5, -5, 0.5);
<ide> }).toThrow();
<del> expect(function() {
<add> expect(function () {
<ide> bezier(0.5, 0.5, 5, 0.5);
<ide> }).toThrow();
<del> expect(function() {
<add> expect(function () {
<ide> bezier(-2, 0.5, 0.5, 0.5);
<ide> }).toThrow();
<del> expect(function() {
<add> expect(function () {
<ide> bezier(2, 0.5, 0.5, 0.5);
<ide> }).toThrow();
<ide> });
<del> describe('linear curves', function() {
<del> it('should be linear', function() {
<add> describe('linear curves', function () {
<add> it('should be linear', function () {
<ide> allEquals(bezier(0, 0, 1, 1), bezier(1, 1, 0, 0), 100);
<ide> allEquals(bezier(0, 0, 1, 1), identity, 100);
<ide> });
<ide> });
<del> describe('common properties', function() {
<del> it('should be the right value at extremes', function() {
<del> repeat(10)(function() {
<add> describe('common properties', function () {
<add> it('should be the right value at extremes', function () {
<add> repeat(10)(function () {
<ide> const a = Math.random(),
<ide> b = 2 * Math.random() - 0.5,
<ide> c = Math.random(),
<ide> describe('bezier', function() {
<ide> });
<ide> });
<ide>
<del> it('should approach the projected value of its x=y projected curve', function() {
<del> repeat(10)(function() {
<add> it('should approach the projected value of its x=y projected curve', function () {
<add> repeat(10)(function () {
<ide> const a = Math.random(),
<ide> b = Math.random(),
<ide> c = Math.random(),
<ide> d = Math.random();
<ide> const easing = bezier(a, b, c, d);
<ide> const projected = bezier(b, a, d, c);
<del> const composed = function(x) {
<add> const composed = function (x) {
<ide> return projected(easing(x));
<ide> };
<ide> allEquals(identity, composed, 100, makeAssertCloseWithPrecision(2));
<ide> });
<ide> });
<ide> });
<del> describe('two same instances', function() {
<del> it('should be strictly equals', function() {
<del> repeat(10)(function() {
<add> describe('two same instances', function () {
<add> it('should be strictly equals', function () {
<add> repeat(10)(function () {
<ide> const a = Math.random(),
<ide> b = 2 * Math.random() - 0.5,
<ide> c = Math.random(),
<ide> describe('bezier', function() {
<ide> });
<ide> });
<ide> });
<del> describe('symmetric curves', function() {
<del> it('should have a central value y~=0.5 at x=0.5', function() {
<del> repeat(10)(function() {
<add> describe('symmetric curves', function () {
<add> it('should have a central value y~=0.5 at x=0.5', function () {
<add> repeat(10)(function () {
<ide> const a = Math.random(),
<ide> b = 2 * Math.random() - 0.5,
<ide> c = 1 - a,
<ide> describe('bezier', function() {
<ide> assertClose(easing(0.5), 0.5, 2);
<ide> });
<ide> });
<del> it('should be symmetrical', function() {
<del> repeat(10)(function() {
<add> it('should be symmetrical', function () {
<add> repeat(10)(function () {
<ide> const a = Math.random(),
<ide> b = 2 * Math.random() - 0.5,
<ide> c = 1 - a,
<ide> d = 1 - b;
<ide> const easing = bezier(a, b, c, d);
<del> const sym = function(x) {
<add> const sym = function (x) {
<ide> return 1 - easing(1 - x);
<ide> };
<ide> allEquals(easing, sym, 100, makeAssertCloseWithPrecision(2));
<ide><path>Libraries/Animated/src/createAnimatedComponent.js
<ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>(
<ide> }
<ide>
<ide> _detachNativeEvents() {
<del> this._eventDetachers.forEach(remove => remove());
<add> this._eventDetachers.forEach((remove) => remove());
<ide> this._eventDetachers = [];
<ide> }
<ide>
<ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>(
<ide>
<ide> _setComponentRef = setAndForwardRef({
<ide> getForwardedRef: () => this.props.forwardedRef,
<del> setLocalRef: ref => {
<add> setLocalRef: (ref) => {
<ide> this._prevComponent = this._component;
<ide> this._component = ref;
<ide>
<ide><path>Libraries/Animated/src/nodes/AnimatedInterpolation.js
<ide> export type InterpolationConfigType = {
<ide> extrapolateRight?: ExtrapolateType,
<ide> };
<ide>
<del>const linear = t => t;
<add>const linear = (t) => t;
<ide>
<ide> /**
<ide> * Very handy helper to map input ranges to output ranges with an easing
<ide> function createInterpolation(
<ide> extrapolateRight = config.extrapolate;
<ide> }
<ide>
<del> return input => {
<add> return (input) => {
<ide> invariant(
<ide> typeof input === 'number',
<ide> 'Cannot interpolation an input which is not a number',
<ide> function createInterpolationFromStringOutputRange(
<ide> * guard against this possibility.
<ide> */
<ide> const outputRanges = outputRange[0].match(stringShapeRegex).map(() => []);
<del> outputRange.forEach(value => {
<add> outputRange.forEach((value) => {
<ide> /* $FlowFixMe(>=0.18.0): `value.match()` can return `null`. Need to guard
<ide> * against this possibility.
<ide> */
<ide> function createInterpolationFromStringOutputRange(
<ide> // round the opacity (4th column).
<ide> const shouldRound = isRgbOrRgba(outputRange[0]);
<ide>
<del> return input => {
<add> return (input) => {
<ide> let i = 0;
<ide> // 'rgba(0, 100, 200, 0)'
<ide> // ->
<ide><path>Libraries/Animated/src/nodes/AnimatedNode.js
<ide> class AnimatedNode {
<ide> NativeAnimatedAPI.startListeningToAnimatedNodeValue(this.__getNativeTag());
<ide> this.__nativeAnimatedValueListener = NativeAnimatedHelper.nativeEventEmitter.addListener(
<ide> 'onAnimatedValueUpdate',
<del> data => {
<add> (data) => {
<ide> if (data.tag !== this.__getNativeTag()) {
<ide> return;
<ide> }
<ide><path>Libraries/Animated/src/nodes/AnimatedTransform.js
<ide> class AnimatedTransform extends AnimatedWithChildren {
<ide> }
<ide>
<ide> __makeNative() {
<del> this._transforms.forEach(transform => {
<add> this._transforms.forEach((transform) => {
<ide> for (const key in transform) {
<ide> const value = transform[key];
<ide> if (value instanceof AnimatedNode) {
<ide> class AnimatedTransform extends AnimatedWithChildren {
<ide> }
<ide>
<ide> __getValue(): $ReadOnlyArray<Object> {
<del> return this._transforms.map(transform => {
<add> return this._transforms.map((transform) => {
<ide> const result = {};
<ide> for (const key in transform) {
<ide> const value = transform[key];
<ide> class AnimatedTransform extends AnimatedWithChildren {
<ide> }
<ide>
<ide> __getAnimatedValue(): $ReadOnlyArray<Object> {
<del> return this._transforms.map(transform => {
<add> return this._transforms.map((transform) => {
<ide> const result = {};
<ide> for (const key in transform) {
<ide> const value = transform[key];
<ide> class AnimatedTransform extends AnimatedWithChildren {
<ide> }
<ide>
<ide> __attach(): void {
<del> this._transforms.forEach(transform => {
<add> this._transforms.forEach((transform) => {
<ide> for (const key in transform) {
<ide> const value = transform[key];
<ide> if (value instanceof AnimatedNode) {
<ide> class AnimatedTransform extends AnimatedWithChildren {
<ide> }
<ide>
<ide> __detach(): void {
<del> this._transforms.forEach(transform => {
<add> this._transforms.forEach((transform) => {
<ide> for (const key in transform) {
<ide> const value = transform[key];
<ide> if (value instanceof AnimatedNode) {
<ide> class AnimatedTransform extends AnimatedWithChildren {
<ide> __getNativeConfig(): any {
<ide> const transConfigs = [];
<ide>
<del> this._transforms.forEach(transform => {
<add> this._transforms.forEach((transform) => {
<ide> for (const key in transform) {
<ide> const value = transform[key];
<ide> if (value instanceof AnimatedNode) {
<ide><path>Libraries/Animated/src/nodes/AnimatedValue.js
<ide> function _flush(rootNode: AnimatedValue): void {
<ide> }
<ide> findAnimatedStyles(rootNode);
<ide> /* $FlowFixMe */
<del> animatedStyles.forEach(animatedStyle => animatedStyle.update());
<add> animatedStyles.forEach((animatedStyle) => animatedStyle.update());
<ide> }
<ide>
<ide> /**
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide> this._animation = animation;
<ide> animation.start(
<ide> this._value,
<del> value => {
<add> (value) => {
<ide> // Natively driven animations will never call into that callback, therefore we can always
<ide> // pass flush = true to allow the updated value to propagate to native with setNativeProps
<ide> this._updateValue(value, true /* flush */);
<ide> },
<del> result => {
<add> (result) => {
<ide> this._animation = null;
<ide> if (handle !== null) {
<ide> InteractionManager.clearInteractionHandle(handle);
<ide><path>Libraries/Animated/src/polyfills/InteractionManager.js
<ide> 'use strict';
<ide>
<ide> module.exports = {
<del> createInteractionHandle: function() {},
<del> clearInteractionHandle: function() {},
<add> createInteractionHandle: function () {},
<add> clearInteractionHandle: function () {},
<ide> };
<ide><path>Libraries/Animated/src/polyfills/Set.js
<ide> function SetPolyfill() {
<ide> this._cache = [];
<ide> }
<ide>
<del>SetPolyfill.prototype.add = function(e) {
<add>SetPolyfill.prototype.add = function (e) {
<ide> if (this._cache.indexOf(e) === -1) {
<ide> this._cache.push(e);
<ide> }
<ide> };
<ide>
<del>SetPolyfill.prototype.forEach = function(cb) {
<add>SetPolyfill.prototype.forEach = function (cb) {
<ide> this._cache.forEach(cb);
<ide> };
<ide>
<ide><path>Libraries/Animated/src/polyfills/flattenStyle.js
<ide> */
<ide>
<ide> 'use strict';
<del>module.exports = function(style) {
<add>module.exports = function (style) {
<ide> return style;
<ide> };
<ide><path>Libraries/AppState/AppState.js
<ide> class AppState extends NativeEventEmitter {
<ide> // prop is up to date, we have to register an observer that updates it
<ide> // whenever the state changes, even if nobody cares. We should just
<ide> // deprecate the `currentState` property and get rid of this.
<del> this.addListener('appStateDidChange', appStateData => {
<add> this.addListener('appStateDidChange', (appStateData) => {
<ide> eventUpdated = true;
<ide> this.currentState = appStateData.app_state;
<ide> });
<ide>
<ide> // TODO: see above - this request just populates the value of `currentState`
<ide> // when the module is first initialized. Would be better to get rid of the
<ide> // prop and expose `getCurrentAppState` method directly.
<del> NativeAppState.getCurrentAppState(appStateData => {
<add> NativeAppState.getCurrentAppState((appStateData) => {
<ide> // It's possible that the state will have changed here & listeners need to be notified
<ide> if (!eventUpdated && this.currentState !== appStateData.app_state) {
<ide> this.currentState = appStateData.app_state;
<ide> class AppState extends NativeEventEmitter {
<ide> case 'change': {
<ide> this._eventHandlers[type].set(
<ide> handler,
<del> this.addListener('appStateDidChange', appStateData => {
<add> this.addListener('appStateDidChange', (appStateData) => {
<ide> handler(appStateData.app_state);
<ide> }),
<ide> );
<ide> class AppState extends NativeEventEmitter {
<ide> case 'focus': {
<ide> this._eventHandlers[type].set(
<ide> handler,
<del> this.addListener('appStateFocusChange', hasFocus => {
<add> this.addListener('appStateFocusChange', (hasFocus) => {
<ide> if (type === 'blur' && !hasFocus) {
<ide> handler();
<ide> }
<ide><path>Libraries/BatchedBridge/MessageQueue.js
<ide> class MessageQueue {
<ide>
<ide> static spy(spyOrToggle: boolean | ((data: SpyData) => void)) {
<ide> if (spyOrToggle === true) {
<del> MessageQueue.prototype.__spy = info => {
<add> MessageQueue.prototype.__spy = (info) => {
<ide> console.log(
<ide> `${info.type === TO_JS ? 'N->JS' : 'JS->N'} : ` +
<ide> `${info.module ? info.module + '.' : ''}${info.method}` +
<ide> class MessageQueue {
<ide> this._lazyCallableModules[name] = () => module;
<ide> }
<ide>
<del> registerLazyCallableModule(name: string, factory: void => Object) {
<add> registerLazyCallableModule(name: string, factory: (void) => Object) {
<ide> let module: Object;
<ide> let getValue: ?(void) => Object = factory;
<ide> this._lazyCallableModules[name] = () => {
<ide> class MessageQueue {
<ide> // folly-convertible. As a special case, if a prop value is a
<ide> // function it is permitted here, and special-cased in the
<ide> // conversion.
<del> const isValidArgument = val => {
<add> const isValidArgument = (val) => {
<ide> const t = typeof val;
<ide> if (
<ide> t === 'undefined' ||
<ide><path>Libraries/BatchedBridge/NativeModules.js
<ide> function genMethod(moduleID: number, methodID: number, type: MethodType) {
<ide> moduleID,
<ide> methodID,
<ide> args,
<del> data => resolve(data),
<del> errorData =>
<add> (data) => resolve(data),
<add> (errorData) =>
<ide> reject(updateErrorWithErrorData(errorData, enqueueingFrameError)),
<ide> );
<ide> });
<ide><path>Libraries/BatchedBridge/__mocks__/MessageQueueTestModule.js
<ide> * cases.
<ide> */
<ide> const MessageQueueTestModule = {
<del> testHook1: function() {},
<del> testHook2: function() {},
<add> testHook1: function () {},
<add> testHook2: function () {},
<ide> };
<ide>
<ide> module.exports = MessageQueueTestModule;
<ide><path>Libraries/BatchedBridge/__tests__/MessageQueue-test.js
<ide> const assertQueue = (flushedQueue, index, moduleID, methodID, params) => {
<ide> //
<ide> // [ ] Local modules that throw exceptions are gracefully caught. In that case
<ide> // local callbacks stored by IDs are cleaned up.
<del>describe('MessageQueue', function() {
<del> beforeEach(function() {
<add>describe('MessageQueue', function () {
<add> beforeEach(function () {
<ide> jest.resetModules();
<ide> MessageQueue = require('../MessageQueue');
<ide> MessageQueueTestModule = require('../__mocks__/MessageQueueTestModule');
<ide> describe('MessageQueue', function() {
<ide> });
<ide>
<ide> it('should throw when calling the same callback twice', () => {
<del> queue.enqueueNativeCall(0, 1, [], () => {}, () => {});
<add> queue.enqueueNativeCall(
<add> 0,
<add> 1,
<add> [],
<add> () => {},
<add> () => {},
<add> );
<ide> queue.__invokeCallback(1, []);
<ide> expect(() => queue.__invokeCallback(1, [])).toThrow();
<ide> });
<ide>
<ide> it('should throw when calling both success and failure callback', () => {
<del> queue.enqueueNativeCall(0, 1, [], () => {}, () => {});
<add> queue.enqueueNativeCall(
<add> 0,
<add> 1,
<add> [],
<add> () => {},
<add> () => {},
<add> );
<ide> queue.__invokeCallback(1, []);
<ide> expect(() => queue.__invokeCallback(0, [])).toThrow();
<ide> });
<ide> describe('MessageQueue', function() {
<ide>
<ide> it('should check if the global error handler is not overridden by the DebuggerInternal object', () => {
<ide> const dummyModule = {
<del> dummy: function() {},
<add> dummy: function () {},
<ide> };
<ide> const name = 'emptyModuleName';
<ide> const factory = jest.fn(() => dummyModule);
<ide> describe('MessageQueue', function() {
<ide>
<ide> it('should check if the global error handler is overridden by the DebuggerInternal object', () => {
<ide> const dummyModule = {
<del> dummy: function() {},
<add> dummy: function () {},
<ide> };
<ide> const name = 'emptyModuleName';
<ide> const factory = jest.fn(() => dummyModule);
<ide><path>Libraries/BatchedBridge/__tests__/NativeModules-test.js
<ide> const assertQueue = (flushedQueue, index, moduleID, methodID, params) => {
<ide> // success callbacks are cleaned up.
<ide> //
<ide> // [ ] Remote invocation throws if not supplying an error callback.
<del>describe('MessageQueue', function() {
<del> beforeEach(function() {
<add>describe('MessageQueue', function () {
<add> beforeEach(function () {
<ide> jest.resetModules();
<ide>
<ide> global.__fbBatchedBridgeConfig = require('../__mocks__/MessageQueueTestConfig');
<ide> describe('MessageQueue', function() {
<ide> assertQueue(flushedQueue, 0, 0, 0, ['foo']);
<ide> });
<ide>
<del> it('should make round trip and clear memory', function() {
<add> it('should make round trip and clear memory', function () {
<ide> const onFail = jest.fn();
<ide> const onSucc = jest.fn();
<ide>
<ide> describe('MessageQueue', function() {
<ide> // Handle the first remote invocation by signaling failure.
<ide> BatchedBridge.__invokeCallback(firstFailCBID, ['firstFailure']);
<ide> // The failure callback was already invoked, the success is no longer valid
<del> expect(function() {
<add> expect(function () {
<ide> BatchedBridge.__invokeCallback(firstSuccCBID, ['firstSucc']);
<ide> }).toThrow();
<ide> expect(onFail.mock.calls.length).toBe(1);
<ide> describe('MessageQueue', function() {
<ide> // Handle the second remote invocation by signaling success.
<ide> BatchedBridge.__invokeCallback(secondSuccCBID, ['secondSucc']);
<ide> // The success callback was already invoked, the fail cb is no longer valid
<del> expect(function() {
<add> expect(function () {
<ide> BatchedBridge.__invokeCallback(secondFailCBID, ['secondFail']);
<ide> }).toThrow();
<ide> expect(onFail.mock.calls.length).toBe(1);
<ide> expect(onSucc.mock.calls.length).toBe(1);
<ide> });
<ide>
<del> it('promise-returning methods (type=promise)', async function() {
<add> it('promise-returning methods (type=promise)', async function () {
<ide> // Perform communication
<ide> const promise1 = NativeModules.RemoteModule1.promiseReturningMethod(
<ide> 'paloAlto',
<ide> describe('MessageQueue', function() {
<ide> // Handle the first remote invocation by signaling failure.
<ide> BatchedBridge.__invokeCallback(firstFailCBID, [{message: 'firstFailure'}]);
<ide> // The failure callback was already invoked, the success is no longer valid
<del> expect(function() {
<add> expect(function () {
<ide> BatchedBridge.__invokeCallback(firstSuccCBID, ['firstSucc']);
<ide> }).toThrow();
<ide> await expect(promise1).rejects.toBeInstanceOf(Error);
<ide> describe('MessageQueue', function() {
<ide> // Handle the second remote invocation by signaling success.
<ide> BatchedBridge.__invokeCallback(secondSuccCBID, ['secondSucc']);
<ide> // The success callback was already invoked, the fail cb is no longer valid
<del> expect(function() {
<add> expect(function () {
<ide> BatchedBridge.__invokeCallback(secondFailCBID, ['secondFail']);
<ide> }).toThrow();
<ide> await promise2;
<ide> });
<ide>
<ide> describe('sync methods', () => {
<del> afterEach(function() {
<add> afterEach(function () {
<ide> delete global.nativeCallSyncHook;
<ide> });
<ide>
<del> it('throwing an exception', function() {
<add> it('throwing an exception', function () {
<ide> global.nativeCallSyncHook = jest.fn(() => {
<ide> throw new Error('firstFailure');
<ide> });
<ide> describe('MessageQueue', function() {
<ide> });
<ide> });
<ide>
<del> it('returning a value', function() {
<add> it('returning a value', function () {
<ide> global.nativeCallSyncHook = jest.fn(() => {
<ide> return 'secondSucc';
<ide> });
<ide><path>Libraries/Blob/BlobManager.js
<ide> import invariant from 'invariant';
<ide> * http://stackoverflow.com/questions/105034
<ide> */
<ide> function uuidv4(): string {
<del> return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
<add> return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
<ide> const r = (Math.random() * 16) | 0,
<ide> v = c == 'x' ? r : (r & 0x3) | 0x8;
<ide> return v.toString(16);
<ide> class BlobManager {
<ide> invariant(NativeBlobModule, 'NativeBlobModule is available.');
<ide>
<ide> const blobId = uuidv4();
<del> const items = parts.map(part => {
<add> const items = parts.map((part) => {
<ide> if (
<ide> part instanceof ArrayBuffer ||
<ide> (global.ArrayBufferView && part instanceof global.ArrayBufferView)
<ide><path>Libraries/Blob/FileReader.js
<ide> class FileReader extends (EventTarget(...READER_EVENTS): any) {
<ide> }
<ide>
<ide> _clearSubscriptions(): void {
<del> this._subscriptions.forEach(sub => sub.remove());
<add> this._subscriptions.forEach((sub) => sub.remove());
<ide> this._subscriptions = [];
<ide> }
<ide>
<ide> class FileReader extends (EventTarget(...READER_EVENTS): any) {
<ide> this._result = text;
<ide> this._setReadyState(DONE);
<ide> },
<del> error => {
<add> (error) => {
<ide> if (this._aborted) {
<ide> return;
<ide> }
<ide> class FileReader extends (EventTarget(...READER_EVENTS): any) {
<ide> this._result = text;
<ide> this._setReadyState(DONE);
<ide> },
<del> error => {
<add> (error) => {
<ide> if (this._aborted) {
<ide> return;
<ide> }
<ide><path>Libraries/Blob/URL.js
<ide> export class URLSearchParams {
<ide>
<ide> constructor(params: any) {
<ide> if (typeof params === 'object') {
<del> Object.keys(params).forEach(key => this.append(key, params[key]));
<add> Object.keys(params).forEach((key) => this.append(key, params[key]));
<ide> }
<ide> }
<ide>
<ide> export class URL {
<ide> if (BLOB_URL_PREFIX === null) {
<ide> throw new Error('Cannot create URL for blob!');
<ide> }
<del> return `${BLOB_URL_PREFIX}${blob.data.blobId}?offset=${
<del> blob.data.offset
<del> }&size=${blob.size}`;
<add> return `${BLOB_URL_PREFIX}${blob.data.blobId}?offset=${blob.data.offset}&size=${blob.size}`;
<ide> }
<ide>
<ide> static revokeObjectURL(url: string) {
<ide><path>Libraries/Blob/__tests__/Blob-test.js
<ide> jest.setMock('../../BatchedBridge/NativeModules', {
<ide>
<ide> const Blob = require('../Blob');
<ide>
<del>describe('Blob', function() {
<add>describe('Blob', function () {
<ide> it('should create empty blob', () => {
<ide> const blob = new Blob();
<ide> expect(blob).toBeInstanceOf(Blob);
<ide><path>Libraries/Blob/__tests__/BlobManager-test.js
<ide> jest.setMock('../../BatchedBridge/NativeModules', {
<ide> const Blob = require('../Blob');
<ide> const BlobManager = require('../BlobManager');
<ide>
<del>describe('BlobManager', function() {
<add>describe('BlobManager', function () {
<ide> it('should create blob from parts', () => {
<ide> const blob = BlobManager.createFromParts([], {type: 'text/html'});
<ide> expect(blob).toBeInstanceOf(Blob);
<ide><path>Libraries/Blob/__tests__/File-test.js
<ide> jest.setMock('../../BatchedBridge/NativeModules', {
<ide> const Blob = require('../Blob');
<ide> const File = require('../File');
<ide>
<del>describe('babel 7 smoke test', function() {
<del> it('should be able to extend a class with native name', function() {
<add>describe('babel 7 smoke test', function () {
<add> it('should be able to extend a class with native name', function () {
<ide> let called = false;
<ide> class Array {
<ide> constructor() {
<ide> describe('babel 7 smoke test', function() {
<ide> });
<ide> });
<ide>
<del>describe('Blob', function() {
<del> it('regression caused by circular dep && babel 7', function() {
<add>describe('Blob', function () {
<add> it('regression caused by circular dep && babel 7', function () {
<ide> const blob = new Blob([], {type: 'image/jpeg'});
<ide> expect(blob).toBeInstanceOf(Blob);
<ide> });
<ide> });
<ide>
<del>describe('File', function() {
<add>describe('File', function () {
<ide> it('should create empty file', () => {
<ide> const file = new File([], 'test.jpg');
<ide> expect(file).toBeInstanceOf(File);
<ide><path>Libraries/Blob/__tests__/FileReader-test.js
<ide> jest.unmock('event-target-shim').setMock('../../BatchedBridge/NativeModules', {
<ide> const Blob = require('../Blob');
<ide> const FileReader = require('../FileReader');
<ide>
<del>describe('FileReader', function() {
<add>describe('FileReader', function () {
<ide> it('should read blob as text', async () => {
<ide> const e = await new Promise((resolve, reject) => {
<ide> const reader = new FileReader();
<ide><path>Libraries/Blob/__tests__/URL-test.js
<ide>
<ide> const URL = require('../URL').URL;
<ide>
<del>describe('URL', function() {
<add>describe('URL', function () {
<ide> it('should pass Mozilla Dev Network examples', () => {
<ide> const a = new URL('/', 'https://developer.mozilla.org');
<ide> expect(a.href).toBe('https://developer.mozilla.org/');
<ide><path>Libraries/Components/AccessibilityInfo/AccessibilityInfo.android.js
<ide> const AccessibilityInfo = {
<ide> /**
<ide> * iOS only
<ide> */
<del> isBoldTextEnabled: function(): Promise<boolean> {
<add> isBoldTextEnabled: function (): Promise<boolean> {
<ide> return Promise.resolve(false);
<ide> },
<ide>
<ide> /**
<ide> * iOS only
<ide> */
<del> isGrayscaleEnabled: function(): Promise<boolean> {
<add> isGrayscaleEnabled: function (): Promise<boolean> {
<ide> return Promise.resolve(false);
<ide> },
<ide>
<ide> /**
<ide> * iOS only
<ide> */
<del> isInvertColorsEnabled: function(): Promise<boolean> {
<add> isInvertColorsEnabled: function (): Promise<boolean> {
<ide> return Promise.resolve(false);
<ide> },
<ide>
<del> isReduceMotionEnabled: function(): Promise<boolean> {
<add> isReduceMotionEnabled: function (): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<ide> if (NativeAccessibilityInfo) {
<ide> NativeAccessibilityInfo.isReduceMotionEnabled(resolve);
<ide> const AccessibilityInfo = {
<ide> /**
<ide> * iOS only
<ide> */
<del> isReduceTransparencyEnabled: function(): Promise<boolean> {
<add> isReduceTransparencyEnabled: function (): Promise<boolean> {
<ide> return Promise.resolve(false);
<ide> },
<ide>
<del> isScreenReaderEnabled: function(): Promise<boolean> {
<add> isScreenReaderEnabled: function (): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<ide> if (NativeAccessibilityInfo) {
<ide> NativeAccessibilityInfo.isTouchExplorationEnabled(resolve);
<ide> const AccessibilityInfo = {
<ide> return this.isScreenReaderEnabled;
<ide> },
<ide>
<del> addEventListener: function(
<add> addEventListener: function (
<ide> eventName: ChangeEventName,
<ide> handler: Function,
<ide> ): void {
<ide> const AccessibilityInfo = {
<ide> if (eventName === 'change' || eventName === 'screenReaderChanged') {
<ide> listener = RCTDeviceEventEmitter.addListener(
<ide> TOUCH_EXPLORATION_EVENT,
<del> enabled => {
<add> (enabled) => {
<ide> handler(enabled);
<ide> },
<ide> );
<ide> } else if (eventName === 'reduceMotionChanged') {
<ide> listener = RCTDeviceEventEmitter.addListener(
<ide> REDUCE_MOTION_EVENT,
<del> enabled => {
<add> (enabled) => {
<ide> handler(enabled);
<ide> },
<ide> );
<ide> const AccessibilityInfo = {
<ide> _subscriptions.set(handler, listener);
<ide> },
<ide>
<del> removeEventListener: function(
<add> removeEventListener: function (
<ide> eventName: ChangeEventName,
<ide> handler: Function,
<ide> ): void {
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#setaccessibilityfocus
<ide> */
<del> setAccessibilityFocus: function(reactTag: number): void {
<add> setAccessibilityFocus: function (reactTag: number): void {
<ide> UIManager.sendAccessibilityEvent(
<ide> reactTag,
<ide> UIManager.getConstants().AccessibilityEventTypes.typeViewFocused,
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#announceforaccessibility
<ide> */
<del> announceForAccessibility: function(announcement: string): void {
<add> announceForAccessibility: function (announcement: string): void {
<ide> if (NativeAccessibilityInfo) {
<ide> NativeAccessibilityInfo.announceForAccessibility(announcement);
<ide> }
<ide><path>Libraries/Components/AccessibilityInfo/AccessibilityInfo.ios.js
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#isBoldTextEnabled
<ide> */
<del> isBoldTextEnabled: function(): Promise<boolean> {
<add> isBoldTextEnabled: function (): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<ide> if (NativeAccessibilityManager) {
<ide> NativeAccessibilityManager.getCurrentBoldTextState(resolve, reject);
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#isGrayscaleEnabled
<ide> */
<del> isGrayscaleEnabled: function(): Promise<boolean> {
<add> isGrayscaleEnabled: function (): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<ide> if (NativeAccessibilityManager) {
<ide> NativeAccessibilityManager.getCurrentGrayscaleState(resolve, reject);
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#isInvertColorsEnabled
<ide> */
<del> isInvertColorsEnabled: function(): Promise<boolean> {
<add> isInvertColorsEnabled: function (): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<ide> if (NativeAccessibilityManager) {
<ide> NativeAccessibilityManager.getCurrentInvertColorsState(resolve, reject);
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#isReduceMotionEnabled
<ide> */
<del> isReduceMotionEnabled: function(): Promise<boolean> {
<add> isReduceMotionEnabled: function (): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<ide> if (NativeAccessibilityManager) {
<ide> NativeAccessibilityManager.getCurrentReduceMotionState(resolve, reject);
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#isReduceTransparencyEnabled
<ide> */
<del> isReduceTransparencyEnabled: function(): Promise<boolean> {
<add> isReduceTransparencyEnabled: function (): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<ide> if (NativeAccessibilityManager) {
<ide> NativeAccessibilityManager.getCurrentReduceTransparencyState(
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#isScreenReaderEnabled
<ide> */
<del> isScreenReaderEnabled: function(): Promise<boolean> {
<add> isScreenReaderEnabled: function (): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<ide> if (NativeAccessibilityManager) {
<ide> NativeAccessibilityManager.getCurrentVoiceOverState(resolve, reject);
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#addeventlistener
<ide> */
<del> addEventListener: function(
<add> addEventListener: function (
<ide> eventName: ChangeEventName,
<ide> handler: Function,
<ide> ): Object {
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#setaccessibilityfocus
<ide> */
<del> setAccessibilityFocus: function(reactTag: number): void {
<add> setAccessibilityFocus: function (reactTag: number): void {
<ide> if (NativeAccessibilityManager) {
<ide> NativeAccessibilityManager.setAccessibilityFocus(reactTag);
<ide> }
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#announceforaccessibility
<ide> */
<del> announceForAccessibility: function(announcement: string): void {
<add> announceForAccessibility: function (announcement: string): void {
<ide> if (NativeAccessibilityManager) {
<ide> NativeAccessibilityManager.announceForAccessibility(announcement);
<ide> }
<ide> const AccessibilityInfo = {
<ide> *
<ide> * See https://reactnative.dev/docs/accessibilityinfo.html#removeeventlistener
<ide> */
<del> removeEventListener: function(
<add> removeEventListener: function (
<ide> eventName: ChangeEventName,
<ide> handler: Function,
<ide> ): void {
<ide><path>Libraries/Components/ActivityIndicator/ActivityIndicator.js
<ide> const ActivityIndicator = (props: Props, forwardedRef?: any) => {
<ide> return (
<ide> <View
<ide> onLayout={onLayout}
<del> style={StyleSheet.compose(
<del> styles.container,
<del> style,
<del> )}>
<add> style={StyleSheet.compose(styles.container, style)}>
<ide> {Platform.OS === 'android' ? (
<ide> // $FlowFixMe Flow doesn't know when this is the android component
<ide> <PlatformActivityIndicator {...nativeProps} {...androidProps} />
<ide><path>Libraries/Components/AppleTV/TVEventHandler.js
<ide> class TVEventHandler {
<ide> );
<ide> this.__nativeTVNavigationEventListener = this.__nativeTVNavigationEventEmitter.addListener(
<ide> 'onHWKeyEvent',
<del> data => {
<add> (data) => {
<ide> if (callback) {
<ide> callback(component, data);
<ide> }
<ide><path>Libraries/Components/CheckBox/CheckBox.android.js
<ide> class CheckBox extends React.Component<Props> {
<ide> _nativeRef: ?React.ElementRef<typeof AndroidCheckBoxNativeComponent> = null;
<ide> _setNativeRef = setAndForwardRef({
<ide> getForwardedRef: () => this.props.forwardedRef,
<del> setLocalRef: ref => {
<add> setLocalRef: (ref) => {
<ide> this._nativeRef = ref;
<ide> },
<ide> });
<ide><path>Libraries/Components/DatePicker/DatePickerIOS.ios.js
<ide> class DatePickerIOS extends React.Component<Props> {
<ide> <View style={props.style}>
<ide> <RCTDatePickerNativeComponent
<ide> testID={props.testID}
<del> ref={picker => {
<add> ref={(picker) => {
<ide> this._picker = picker;
<ide> }}
<ide> style={styles.datePickerIOS}
<ide><path>Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.android.js
<ide> class DrawerLayoutAndroid extends React.Component<Props, State> {
<ide> );
<ide> }
<ide>
<del> _onDrawerSlide = event => {
<add> _onDrawerSlide = (event) => {
<ide> if (this.props.onDrawerSlide) {
<ide> this.props.onDrawerSlide(event);
<ide> }
<ide> class DrawerLayoutAndroid extends React.Component<Props, State> {
<ide> }
<ide> };
<ide>
<del> _onDrawerStateChanged = event => {
<add> _onDrawerStateChanged = (event) => {
<ide> if (this.props.onDrawerStateChanged) {
<ide> this.props.onDrawerStateChanged(
<ide> DRAWER_STATES[event.nativeEvent.drawerState],
<ide><path>Libraries/Components/Keyboard/Keyboard.js
<ide> const Keyboard = {
<ide>
<ide> // Throw away the dummy object and reassign it to original module
<ide> KeyboardEventEmitter.dismiss = dismissKeyboard;
<del>KeyboardEventEmitter.scheduleLayoutAnimation = function(event: KeyboardEvent) {
<add>KeyboardEventEmitter.scheduleLayoutAnimation = function (event: KeyboardEvent) {
<ide> const {duration, easing} = event;
<ide> if (duration != null && duration !== 0) {
<ide> LayoutAnimation.configureNext({
<ide><path>Libraries/Components/Keyboard/KeyboardAvoidingView.js
<ide> class KeyboardAvoidingView extends React.Component<Props, State> {
<ide> }
<ide>
<ide> componentWillUnmount(): void {
<del> this._subscriptions.forEach(subscription => {
<add> this._subscriptions.forEach((subscription) => {
<ide> subscription.remove();
<ide> });
<ide> }
<ide> class KeyboardAvoidingView extends React.Component<Props, State> {
<ide> return (
<ide> <View
<ide> ref={this.viewRef}
<del> style={StyleSheet.compose(
<del> style,
<del> heightStyle,
<del> )}
<add> style={StyleSheet.compose(style, heightStyle)}
<ide> onLayout={this._onLayout}
<ide> {...props}>
<ide> {children}
<ide> class KeyboardAvoidingView extends React.Component<Props, State> {
<ide> onLayout={this._onLayout}
<ide> {...props}>
<ide> <View
<del> style={StyleSheet.compose(
<del> contentContainerStyle,
<del> {
<del> bottom: bottomHeight,
<del> },
<del> )}>
<add> style={StyleSheet.compose(contentContainerStyle, {
<add> bottom: bottomHeight,
<add> })}>
<ide> {children}
<ide> </View>
<ide> </View>
<ide> class KeyboardAvoidingView extends React.Component<Props, State> {
<ide> return (
<ide> <View
<ide> ref={this.viewRef}
<del> style={StyleSheet.compose(
<del> style,
<del> {paddingBottom: bottomHeight},
<del> )}
<add> style={StyleSheet.compose(style, {paddingBottom: bottomHeight})}
<ide> onLayout={this._onLayout}
<ide> {...props}>
<ide> {children}
<ide><path>Libraries/Components/Keyboard/__tests__/Keyboard-test.js
<ide> describe('Keyboard', () => {
<ide> });
<ide>
<ide> describe('animation update type', () => {
<del> const assertAnimationUpdateType = type =>
<add> const assertAnimationUpdateType = (type) =>
<ide> expect(LayoutAnimation.configureNext).toHaveBeenCalledWith(
<ide> expect.objectContaining({
<ide> duration: expect.anything(),
<ide><path>Libraries/Components/Picker/PickerAndroid.android.js
<ide> function PickerAndroid(props: Props): React.Node {
<ide> if (onValueChange != null) {
<ide> if (position >= 0) {
<ide> const children = React.Children.toArray(props.children).filter(
<del> item => item != null,
<add> (item) => item != null,
<ide> );
<ide> const value = children[position].props.value;
<ide> if (props.selectedValue !== value) {
<ide> function PickerAndroid(props: Props): React.Node {
<ide> prompt: props.prompt,
<ide> ref: pickerRef,
<ide> selected,
<del> style: StyleSheet.compose(
<del> styles.pickerAndroid,
<del> props.style,
<del> ),
<add> style: StyleSheet.compose(styles.pickerAndroid, props.style),
<ide> backgroundColor: props.backgroundColor,
<ide> testID: props.testID,
<ide> };
<ide><path>Libraries/Components/Picker/PickerIOS.ios.js
<ide> class PickerIOS extends React.Component<Props, State> {
<ide> let selectedIndex = 0;
<ide> const items = [];
<ide> React.Children.toArray(props.children)
<del> .filter(child => child !== null)
<del> .forEach(function(child, index) {
<add> .filter((child) => child !== null)
<add> .forEach(function (child, index) {
<ide> if (child.props.value === props.selectedValue) {
<ide> selectedIndex = index;
<ide> }
<ide> class PickerIOS extends React.Component<Props, State> {
<ide> return (
<ide> <View style={this.props.style}>
<ide> <RCTPickerNativeComponent
<del> ref={picker => {
<add> ref={(picker) => {
<ide> this._picker = picker;
<ide> }}
<ide> testID={this.props.testID}
<ide> class PickerIOS extends React.Component<Props, State> {
<ide> }
<ide> }
<ide>
<del> _onChange = event => {
<add> _onChange = (event) => {
<ide> if (this.props.onChange) {
<ide> this.props.onChange(event);
<ide> }
<ide><path>Libraries/Components/ScrollResponder.js
<ide> const ScrollResponderMixin = {
<ide> _subscriptionKeyboardWillHide: (null: ?EmitterSubscription),
<ide> _subscriptionKeyboardDidShow: (null: ?EmitterSubscription),
<ide> _subscriptionKeyboardDidHide: (null: ?EmitterSubscription),
<del> scrollResponderMixinGetInitialState: function(): State {
<add> scrollResponderMixinGetInitialState: function (): State {
<ide> return {
<ide> isTouching: false,
<ide> lastMomentumScrollBeginTime: 0,
<ide> const ScrollResponderMixin = {
<ide> /**
<ide> * Invoke this from an `onScroll` event.
<ide> */
<del> scrollResponderHandleScrollShouldSetResponder: function(): boolean {
<add> scrollResponderHandleScrollShouldSetResponder: function (): boolean {
<ide> // Allow any event touch pass through if the default pan responder is disabled
<ide> if (this.props.disableScrollViewPanResponder === true) {
<ide> return false;
<ide> const ScrollResponderMixin = {
<ide> * true.
<ide> *
<ide> */
<del> scrollResponderHandleStartShouldSetResponder: function(
<add> scrollResponderHandleStartShouldSetResponder: function (
<ide> e: PressEvent,
<ide> ): boolean {
<ide> // Allow any event touch pass through if the default pan responder is disabled
<ide> const ScrollResponderMixin = {
<ide> *
<ide> * Invoke this from an `onStartShouldSetResponderCapture` event.
<ide> */
<del> scrollResponderHandleStartShouldSetResponderCapture: function(
<add> scrollResponderHandleStartShouldSetResponderCapture: function (
<ide> e: PressEvent,
<ide> ): boolean {
<ide> // The scroll view should receive taps instead of its descendants if:
<ide> const ScrollResponderMixin = {
<ide> * altogether. To improve this, find a way to disable the `UIScrollView` after
<ide> * a touch has already started.
<ide> */
<del> scrollResponderHandleResponderReject: function() {},
<add> scrollResponderHandleResponderReject: function () {},
<ide>
<ide> /**
<ide> * We will allow the scroll view to give up its lock iff it acquired the lock
<ide> const ScrollResponderMixin = {
<ide> * navigation of a swipe gesture higher in the view hierarchy, should be
<ide> * rejected.
<ide> */
<del> scrollResponderHandleTerminationRequest: function(): boolean {
<add> scrollResponderHandleTerminationRequest: function (): boolean {
<ide> return !this.state.observedScrollSinceBecomingResponder;
<ide> },
<ide>
<ide> const ScrollResponderMixin = {
<ide> *
<ide> * @param {PressEvent} e Event.
<ide> */
<del> scrollResponderHandleTouchEnd: function(e: PressEvent) {
<add> scrollResponderHandleTouchEnd: function (e: PressEvent) {
<ide> const nativeEvent = e.nativeEvent;
<ide> this.state.isTouching = nativeEvent.touches.length !== 0;
<ide> this.props.onTouchEnd && this.props.onTouchEnd(e);
<ide> const ScrollResponderMixin = {
<ide> *
<ide> * @param {PressEvent} e Event.
<ide> */
<del> scrollResponderHandleTouchCancel: function(e: PressEvent) {
<add> scrollResponderHandleTouchCancel: function (e: PressEvent) {
<ide> this.state.isTouching = false;
<ide> this.props.onTouchCancel && this.props.onTouchCancel(e);
<ide> },
<ide>
<ide> /**
<ide> * Invoke this from an `onResponderRelease` event.
<ide> */
<del> scrollResponderHandleResponderRelease: function(e: PressEvent) {
<add> scrollResponderHandleResponderRelease: function (e: PressEvent) {
<ide> this.props.onResponderRelease && this.props.onResponderRelease(e);
<ide>
<ide> if (typeof e.target === 'number') {
<ide> const ScrollResponderMixin = {
<ide> }
<ide> },
<ide>
<del> scrollResponderHandleScroll: function(e: ScrollEvent) {
<add> scrollResponderHandleScroll: function (e: ScrollEvent) {
<ide> (this: any).state.observedScrollSinceBecomingResponder = true;
<ide> (this: any).props.onScroll && (this: any).props.onScroll(e);
<ide> },
<ide>
<ide> /**
<ide> * Invoke this from an `onResponderGrant` event.
<ide> */
<del> scrollResponderHandleResponderGrant: function(e: ScrollEvent) {
<add> scrollResponderHandleResponderGrant: function (e: ScrollEvent) {
<ide> this.state.observedScrollSinceBecomingResponder = false;
<ide> this.props.onResponderGrant && this.props.onResponderGrant(e);
<ide> this.state.becameResponderWhileAnimating = this.scrollResponderIsAnimating();
<ide> const ScrollResponderMixin = {
<ide> *
<ide> * Invoke this from an `onScrollBeginDrag` event.
<ide> */
<del> scrollResponderHandleScrollBeginDrag: function(e: ScrollEvent) {
<add> scrollResponderHandleScrollBeginDrag: function (e: ScrollEvent) {
<ide> FrameRateLogger.beginScroll(); // TODO: track all scrolls after implementing onScrollEndAnimation
<ide> this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e);
<ide> },
<ide>
<ide> /**
<ide> * Invoke this from an `onScrollEndDrag` event.
<ide> */
<del> scrollResponderHandleScrollEndDrag: function(e: ScrollEvent) {
<add> scrollResponderHandleScrollEndDrag: function (e: ScrollEvent) {
<ide> const {velocity} = e.nativeEvent;
<ide> // - If we are animating, then this is a "drag" that is stopping the scrollview and momentum end
<ide> // will fire.
<ide> const ScrollResponderMixin = {
<ide> /**
<ide> * Invoke this from an `onMomentumScrollBegin` event.
<ide> */
<del> scrollResponderHandleMomentumScrollBegin: function(e: ScrollEvent) {
<add> scrollResponderHandleMomentumScrollBegin: function (e: ScrollEvent) {
<ide> this.state.lastMomentumScrollBeginTime = performanceNow();
<ide> this.props.onMomentumScrollBegin && this.props.onMomentumScrollBegin(e);
<ide> },
<ide>
<ide> /**
<ide> * Invoke this from an `onMomentumScrollEnd` event.
<ide> */
<del> scrollResponderHandleMomentumScrollEnd: function(e: ScrollEvent) {
<add> scrollResponderHandleMomentumScrollEnd: function (e: ScrollEvent) {
<ide> FrameRateLogger.endScroll();
<ide> this.state.lastMomentumScrollEndTime = performanceNow();
<ide> this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e);
<ide> const ScrollResponderMixin = {
<ide> *
<ide> * @param {PressEvent} e Touch Start event.
<ide> */
<del> scrollResponderHandleTouchStart: function(e: PressEvent) {
<add> scrollResponderHandleTouchStart: function (e: PressEvent) {
<ide> this.state.isTouching = true;
<ide> this.props.onTouchStart && this.props.onTouchStart(e);
<ide> },
<ide> const ScrollResponderMixin = {
<ide> *
<ide> * @param {PressEvent} e Touch Start event.
<ide> */
<del> scrollResponderHandleTouchMove: function(e: PressEvent) {
<add> scrollResponderHandleTouchMove: function (e: PressEvent) {
<ide> this.props.onTouchMove && this.props.onTouchMove(e);
<ide> },
<ide>
<ide> const ScrollResponderMixin = {
<ide> * view is currently animating. This is particularly useful to know when
<ide> * a touch has just started or ended.
<ide> */
<del> scrollResponderIsAnimating: function(): boolean {
<add> scrollResponderIsAnimating: function (): boolean {
<ide> const now = performanceNow();
<ide> const timeSinceLastMomentumScrollEnd =
<ide> now - this.state.lastMomentumScrollEndTime;
<ide> const ScrollResponderMixin = {
<ide> * Components can pass what node to use by defining a `getScrollableNode`
<ide> * function otherwise `this` is used.
<ide> */
<del> scrollResponderGetScrollableNode: function(): ?number {
<add> scrollResponderGetScrollableNode: function (): ?number {
<ide> return this.getScrollableNode
<ide> ? this.getScrollableNode()
<ide> : ReactNative.findNodeHandle(this);
<ide> const ScrollResponderMixin = {
<ide> * the function also accepts separate arguments as as alternative to the options object.
<ide> * This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.
<ide> */
<del> scrollResponderScrollTo: function(
<add> scrollResponderScrollTo: function (
<ide> x?:
<ide> | number
<ide> | {
<ide> const ScrollResponderMixin = {
<ide> *
<ide> * `scrollResponderScrollToEnd({animated: true})`
<ide> */
<del> scrollResponderScrollToEnd: function(options?: {animated?: boolean, ...}) {
<add> scrollResponderScrollToEnd: function (options?: {animated?: boolean, ...}) {
<ide> // Default to true
<ide> const animated = (options && options.animated) !== false;
<ide>
<ide> const ScrollResponderMixin = {
<ide> *
<ide> * @platform ios
<ide> */
<del> scrollResponderZoomTo: function(
<add> scrollResponderZoomTo: function (
<ide> rect: {|
<ide> x: number,
<ide> y: number,
<ide> const ScrollResponderMixin = {
<ide> /**
<ide> * Displays the scroll indicators momentarily.
<ide> */
<del> scrollResponderFlashScrollIndicators: function() {
<add> scrollResponderFlashScrollIndicators: function () {
<ide> const that: React.ElementRef<ScrollView> = (this: any);
<ide> invariant(
<ide> that.getNativeScrollRef != null,
<ide> const ScrollResponderMixin = {
<ide> * @param {bool} preventNegativeScrolling Whether to allow pulling the content
<ide> * down to make it meet the keyboard's top. Default is false.
<ide> */
<del> scrollResponderScrollNativeHandleToKeyboard: function<T>(
<add> scrollResponderScrollNativeHandleToKeyboard: function <T>(
<ide> nodeHandle: number | React.ElementRef<HostComponent<T>>,
<ide> additionalOffset?: number,
<ide> preventNegativeScrollOffset?: boolean,
<ide> const ScrollResponderMixin = {
<ide> * @param {number} width Width of the text input.
<ide> * @param {number} height Height of the text input.
<ide> */
<del> scrollResponderInputMeasureAndScrollToKeyboard: function(
<add> scrollResponderInputMeasureAndScrollToKeyboard: function (
<ide> left: number,
<ide> top: number,
<ide> width: number,
<ide> const ScrollResponderMixin = {
<ide> this.preventNegativeScrollOffset = false;
<ide> },
<ide>
<del> scrollResponderTextInputFocusError: function(msg: string) {
<add> scrollResponderTextInputFocusError: function (msg: string) {
<ide> console.error('Error measuring text field: ', msg);
<ide> },
<ide>
<ide> const ScrollResponderMixin = {
<ide> *
<ide> * The `keyboardWillShow` is called before input focus.
<ide> */
<del> UNSAFE_componentWillMount: function() {
<add> UNSAFE_componentWillMount: function () {
<ide> const {keyboardShouldPersistTaps} = ((this: any).props: ScrollViewProps);
<ide> if (typeof keyboardShouldPersistTaps === 'boolean') {
<ide> console.warn(
<ide> const ScrollResponderMixin = {
<ide> );
<ide> },
<ide>
<del> componentWillUnmount: function() {
<add> componentWillUnmount: function () {
<ide> if (this._subscriptionKeyboardWillShow != null) {
<ide> this._subscriptionKeyboardWillShow.remove();
<ide> }
<ide> const ScrollResponderMixin = {
<ide> * relevant to you. (For example, only if you receive these callbacks after
<ide> * you had explicitly focused a node etc).
<ide> */
<del> scrollResponderKeyboardWillShow: function(e: KeyboardEvent) {
<add> scrollResponderKeyboardWillShow: function (e: KeyboardEvent) {
<ide> this.keyboardWillOpenTo = e;
<ide> this.props.onKeyboardWillShow && this.props.onKeyboardWillShow(e);
<ide> },
<ide>
<del> scrollResponderKeyboardWillHide: function(e: KeyboardEvent) {
<add> scrollResponderKeyboardWillHide: function (e: KeyboardEvent) {
<ide> this.keyboardWillOpenTo = null;
<ide> this.props.onKeyboardWillHide && this.props.onKeyboardWillHide(e);
<ide> },
<ide>
<del> scrollResponderKeyboardDidShow: function(e: KeyboardEvent) {
<add> scrollResponderKeyboardDidShow: function (e: KeyboardEvent) {
<ide> // TODO(7693961): The event for DidShow is not available on iOS yet.
<ide> // Use the one from WillShow and do not assign.
<ide> if (e) {
<ide> const ScrollResponderMixin = {
<ide> this.props.onKeyboardDidShow && this.props.onKeyboardDidShow(e);
<ide> },
<ide>
<del> scrollResponderKeyboardDidHide: function(e: KeyboardEvent) {
<add> scrollResponderKeyboardDidHide: function (e: KeyboardEvent) {
<ide> this.keyboardWillOpenTo = null;
<ide> this.props.onKeyboardDidHide && this.props.onKeyboardDidHide(e);
<ide> },
<ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> type VRProps = $ReadOnly<{|
<ide>
<ide> type StickyHeaderComponentType = React.AbstractComponent<
<ide> ScrollViewStickyHeaderProps,
<del> $ReadOnly<{setNextHeaderY: number => void, ...}>,
<add> $ReadOnly<{setNextHeaderY: (number) => void, ...}>,
<ide> >;
<ide>
<ide> export type Props = $ReadOnly<{|
<ide> class ScrollView extends React.Component<Props, State> {
<ide> * instance.
<ide> */
<ide> Object.keys(ScrollResponder.Mixin)
<del> .filter(key => typeof ScrollResponder.Mixin[key] !== 'function')
<del> .forEach(key => {
<add> .filter((key) => typeof ScrollResponder.Mixin[key] !== 'function')
<add> .forEach((key) => {
<ide> // $FlowFixMe - dynamically adding properties to a class
<ide> (this: any)[key] = ScrollResponder.Mixin[key];
<ide> });
<ide> class ScrollView extends React.Component<Props, State> {
<ide> _innerViewRef: ?React.ElementRef<typeof View> = null;
<ide> _setInnerViewRef = setAndForwardRef({
<ide> getForwardedRef: () => this.props.innerViewRef,
<del> setLocalRef: ref => {
<add> setLocalRef: (ref) => {
<ide> this._innerViewRef = ref;
<ide> },
<ide> });
<ide> class ScrollView extends React.Component<Props, State> {
<ide> if (__DEV__ && this.props.style !== undefined) {
<ide> const style = flattenStyle(this.props.style);
<ide> const childLayoutProps = ['alignItems', 'justifyContent'].filter(
<del> prop => style && style[prop] !== undefined,
<add> (prop) => style && style[prop] !== undefined,
<ide> );
<ide> invariant(
<ide> childLayoutProps.length === 0,
<ide> class ScrollView extends React.Component<Props, State> {
<ide> return (
<ide> <StickyHeaderComponent
<ide> key={key}
<del> ref={ref => this._setStickyHeaderRef(key, ref)}
<add> ref={(ref) => this._setStickyHeaderRef(key, ref)}
<ide> nextHeaderLayoutY={this._headerLayoutYs.get(
<ide> this._getKeyForIndex(nextIndex, childArray),
<ide> )}
<del> onLayout={event => this._onStickyHeaderLayout(index, event, key)}
<add> onLayout={(event) =>
<add> this._onStickyHeaderLayout(index, event, key)
<add> }
<ide> scrollAnimatedValue={this._scrollAnimatedValue}
<ide> inverted={this.props.invertStickyHeaders}
<ide> scrollViewHeight={this.state.layoutHeight}>
<ide><path>Libraries/Components/ScrollView/ScrollViewStickyHeader.js
<ide> class ScrollViewStickyHeader extends React.Component<Props, State> {
<ide> this.setState({nextHeaderLayoutY: y});
<ide> }
<ide>
<del> _onLayout = event => {
<add> _onLayout = (event) => {
<ide> this.setState({
<ide> measured: true,
<ide> layoutY: event.nativeEvent.layout.y,
<ide><path>Libraries/Components/Slider/Slider.js
<ide> const Slider = (
<ide> props: Props,
<ide> forwardedRef?: ?React.Ref<typeof SliderNativeComponent>,
<ide> ) => {
<del> const style = StyleSheet.compose(
<del> styles.slider,
<del> props.style,
<del> );
<add> const style = StyleSheet.compose(styles.slider, props.style);
<ide>
<ide> const {
<ide> disabled = false,
<ide><path>Libraries/Components/Sound/SoundManager.js
<ide> import NativeSoundManager from './NativeSoundManager';
<ide>
<ide> const SoundManager = {
<del> playTouchSound: function(): void {
<add> playTouchSound: function (): void {
<ide> if (NativeSoundManager) {
<ide> NativeSoundManager.playTouchSound();
<ide> }
<ide><path>Libraries/Components/StatusBar/StatusBar.js
<ide> class StatusBar extends React.Component<Props> {
<ide> const processedColor = processColor(mergedProps.backgroundColor.value);
<ide> if (processedColor == null) {
<ide> console.warn(
<del> `\`StatusBar._updatePropsStack\`: Color ${
<del> mergedProps.backgroundColor.value
<del> } parsed to null or undefined`,
<add> `\`StatusBar._updatePropsStack\`: Color ${mergedProps.backgroundColor.value} parsed to null or undefined`,
<ide> );
<ide> } else {
<ide> invariant(
<ide><path>Libraries/Components/TextInput/TextInput.js
<ide> function InternalTextInput(props: Props): React.Node {
<ide>
<ide> const _setNativeRef = setAndForwardRef({
<ide> getForwardedRef: () => props.forwardedRef,
<del> setLocalRef: ref => {
<add> setLocalRef: (ref) => {
<ide> inputRef.current = ref;
<ide>
<ide> /*
<ide><path>Libraries/Components/TextInput/__tests__/TextInput-test.js
<ide> describe('TextInput tests', () => {
<ide> <TextInput
<ide> ref={inputRef}
<ide> value={state.text}
<del> onChangeText={text => {
<add> onChangeText={(text) => {
<ide> onChangeTextListener(text);
<ide> setState({text});
<ide> }}
<del> onChange={event => {
<add> onChange={(event) => {
<ide> onChangeListener(event);
<ide> }}
<ide> />
<ide> describe('TextInput tests', () => {
<ide> ReactTestRenderer.create(<TextInput ref={textInputRef} value="value1" />);
<ide>
<ide> expect(textInputRef.current.isFocused()).toBe(false);
<del> ReactNative.findNodeHandle = jest.fn().mockImplementation(ref => {
<add> ReactNative.findNodeHandle = jest.fn().mockImplementation((ref) => {
<ide> if (ref == null) {
<ide> return null;
<ide> }
<ide> describe('TextInput tests', () => {
<ide> <TextInput ref={textInputRe2} value="value2" />
<ide> </>,
<ide> );
<del> ReactNative.findNodeHandle = jest.fn().mockImplementation(ref => {
<add> ReactNative.findNodeHandle = jest.fn().mockImplementation((ref) => {
<ide> if (
<ide> ref === textInputRe1.current ||
<ide> ref === textInputRe1.current.getNativeRef()
<ide><path>Libraries/Components/ToastAndroid/ToastAndroid.android.js
<ide> const ToastAndroid = {
<ide> BOTTOM: (NativeToastAndroid.getConstants().BOTTOM: number),
<ide> CENTER: (NativeToastAndroid.getConstants().CENTER: number),
<ide>
<del> show: function(message: string, duration: number): void {
<add> show: function (message: string, duration: number): void {
<ide> NativeToastAndroid.show(message, duration);
<ide> },
<ide>
<del> showWithGravity: function(
<add> showWithGravity: function (
<ide> message: string,
<ide> duration: number,
<ide> gravity: number,
<ide> ): void {
<ide> NativeToastAndroid.showWithGravity(message, duration, gravity);
<ide> },
<ide>
<del> showWithGravityAndOffset: function(
<add> showWithGravityAndOffset: function (
<ide> message: string,
<ide> duration: number,
<ide> gravity: number,
<ide><path>Libraries/Components/ToastAndroid/ToastAndroid.ios.js
<ide> const warning = require('fbjs/lib/warning');
<ide>
<ide> const ToastAndroid = {
<del> show: function(message: string, duration: number): void {
<add> show: function (message: string, duration: number): void {
<ide> warning(false, 'ToastAndroid is not supported on this platform.');
<ide> },
<ide>
<del> showWithGravity: function(
<add> showWithGravity: function (
<ide> message: string,
<ide> duration: number,
<ide> gravity: number,
<ide> ): void {
<ide> warning(false, 'ToastAndroid is not supported on this platform.');
<ide> },
<ide>
<del> showWithGravityAndOffset: function(
<add> showWithGravityAndOffset: function (
<ide> message: string,
<ide> duration: number,
<ide> gravity: number,
<ide><path>Libraries/Components/Touchable/BoundingDimensions.js
<ide> function BoundingDimensions(width, height) {
<ide> this.height = height;
<ide> }
<ide>
<del>BoundingDimensions.prototype.destructor = function() {
<add>BoundingDimensions.prototype.destructor = function () {
<ide> this.width = null;
<ide> this.height = null;
<ide> };
<ide> BoundingDimensions.prototype.destructor = function() {
<ide> * @param {HTMLElement} element Element to return `BoundingDimensions` for.
<ide> * @return {BoundingDimensions} Bounding dimensions of `element`.
<ide> */
<del>BoundingDimensions.getPooledFromElement = function(element) {
<add>BoundingDimensions.getPooledFromElement = function (element) {
<ide> return BoundingDimensions.getPooled(
<ide> element.offsetWidth,
<ide> element.offsetHeight,
<ide><path>Libraries/Components/Touchable/PooledClass.js
<ide> const invariant = require('invariant');
<ide> * the Class itself, not an instance. If any others are needed, simply add them
<ide> * here, or in their own files.
<ide> */
<del>const oneArgumentPooler = function(copyFieldsFrom) {
<add>const oneArgumentPooler = function (copyFieldsFrom) {
<ide> const Klass = this;
<ide> if (Klass.instancePool.length) {
<ide> const instance = Klass.instancePool.pop();
<ide> const oneArgumentPooler = function(copyFieldsFrom) {
<ide> }
<ide> };
<ide>
<del>const twoArgumentPooler = function(a1, a2) {
<add>const twoArgumentPooler = function (a1, a2) {
<ide> const Klass = this;
<ide> if (Klass.instancePool.length) {
<ide> const instance = Klass.instancePool.pop();
<ide> const twoArgumentPooler = function(a1, a2) {
<ide> }
<ide> };
<ide>
<del>const threeArgumentPooler = function(a1, a2, a3) {
<add>const threeArgumentPooler = function (a1, a2, a3) {
<ide> const Klass = this;
<ide> if (Klass.instancePool.length) {
<ide> const instance = Klass.instancePool.pop();
<ide> const threeArgumentPooler = function(a1, a2, a3) {
<ide> }
<ide> };
<ide>
<del>const fourArgumentPooler = function(a1, a2, a3, a4) {
<add>const fourArgumentPooler = function (a1, a2, a3, a4) {
<ide> const Klass = this;
<ide> if (Klass.instancePool.length) {
<ide> const instance = Klass.instancePool.pop();
<ide> const fourArgumentPooler = function(a1, a2, a3, a4) {
<ide> }
<ide> };
<ide>
<del>const standardReleaser = function(instance) {
<add>const standardReleaser = function (instance) {
<ide> const Klass = this;
<ide> invariant(
<ide> instance instanceof Klass,
<ide> type Pooler = any;
<ide> * @param {Function} CopyConstructor Constructor that can be used to reset.
<ide> * @param {Function} pooler Customizable pooler.
<ide> */
<del>const addPoolingTo = function<T>(
<add>const addPoolingTo = function <T>(
<ide> CopyConstructor: Class<T>,
<ide> pooler: Pooler,
<ide> ): Class<T> & {
<ide><path>Libraries/Components/Touchable/Position.js
<ide> function Position(left, top) {
<ide> this.top = top;
<ide> }
<ide>
<del>Position.prototype.destructor = function() {
<add>Position.prototype.destructor = function () {
<ide> this.left = null;
<ide> this.top = null;
<ide> };
<ide><path>Libraries/Components/Touchable/Touchable.js
<ide> const normalizeColor = require('../../StyleSheet/normalizeColor');
<ide> import type {EdgeInsetsProp} from '../../StyleSheet/EdgeInsetsPropType';
<ide> import type {PressEvent} from '../../Types/CoreEventTypes';
<ide>
<del>const extractSingleTouch = nativeEvent => {
<add>const extractSingleTouch = (nativeEvent) => {
<ide> const touches = nativeEvent.touches;
<ide> const changedTouches = nativeEvent.changedTouches;
<ide> const hasTouches = touches && touches.length > 0;
<ide> const LONG_PRESS_ALLOWED_MOVEMENT = 10;
<ide> * @lends Touchable.prototype
<ide> */
<ide> const TouchableMixin = {
<del> componentDidMount: function() {
<add> componentDidMount: function () {
<ide> if (!Platform.isTV) {
<ide> return;
<ide> }
<ide>
<ide> this._tvEventHandler = new TVEventHandler();
<del> this._tvEventHandler.enable(this, function(cmp, evt) {
<add> this._tvEventHandler.enable(this, function (cmp, evt) {
<ide> const myTag = ReactNative.findNodeHandle(cmp);
<ide> evt.dispatchConfig = {};
<ide> if (myTag === evt.tag) {
<ide> const TouchableMixin = {
<ide> /**
<ide> * Clear all timeouts on unmount
<ide> */
<del> componentWillUnmount: function() {
<add> componentWillUnmount: function () {
<ide> if (this._tvEventHandler) {
<ide> this._tvEventHandler.disable();
<ide> delete this._tvEventHandler;
<ide> const TouchableMixin = {
<ide> * @return {object} State object to be placed inside of
<ide> * `this.state.touchable`.
<ide> */
<del> touchableGetInitialState: function(): $TEMPORARY$object<{|
<add> touchableGetInitialState: function (): $TEMPORARY$object<{|
<ide> touchable: $TEMPORARY$object<{|responderID: null, touchState: void|}>,
<ide> |}> {
<ide> return {
<ide> const TouchableMixin = {
<ide> /**
<ide> * Must return true if embedded in a native platform scroll view.
<ide> */
<del> touchableHandleResponderTerminationRequest: function(): any {
<add> touchableHandleResponderTerminationRequest: function (): any {
<ide> return !this.props.rejectResponderTermination;
<ide> },
<ide>
<ide> /**
<ide> * Must return true to start the process of `Touchable`.
<ide> */
<del> touchableHandleStartShouldSetResponder: function(): any {
<add> touchableHandleStartShouldSetResponder: function (): any {
<ide> return !this.props.disabled;
<ide> },
<ide>
<ide> /**
<ide> * Return true to cancel press on long press.
<ide> */
<del> touchableLongPressCancelsPress: function(): boolean {
<add> touchableLongPressCancelsPress: function (): boolean {
<ide> return true;
<ide> },
<ide>
<ide> const TouchableMixin = {
<ide> * @param {SyntheticEvent} e Synthetic event from event system.
<ide> *
<ide> */
<del> touchableHandleResponderGrant: function(e: PressEvent) {
<add> touchableHandleResponderGrant: function (e: PressEvent) {
<ide> const dispatchID = e.currentTarget;
<ide> // Since e is used in a callback invoked on another event loop
<ide> // (as in setTimeout etc), we need to call e.persist() on the
<ide> const TouchableMixin = {
<ide> /**
<ide> * Place as callback for a DOM element's `onResponderRelease` event.
<ide> */
<del> touchableHandleResponderRelease: function(e: PressEvent) {
<add> touchableHandleResponderRelease: function (e: PressEvent) {
<ide> this.pressInLocation = null;
<ide> this._receiveSignal(Signals.RESPONDER_RELEASE, e);
<ide> },
<ide>
<ide> /**
<ide> * Place as callback for a DOM element's `onResponderTerminate` event.
<ide> */
<del> touchableHandleResponderTerminate: function(e: PressEvent) {
<add> touchableHandleResponderTerminate: function (e: PressEvent) {
<ide> this.pressInLocation = null;
<ide> this._receiveSignal(Signals.RESPONDER_TERMINATED, e);
<ide> },
<ide>
<ide> /**
<ide> * Place as callback for a DOM element's `onResponderMove` event.
<ide> */
<del> touchableHandleResponderMove: function(e: PressEvent) {
<add> touchableHandleResponderMove: function (e: PressEvent) {
<ide> // Measurement may not have returned yet.
<ide> if (!this.state.touchable.positionOnActivate) {
<ide> return;
<ide> const TouchableMixin = {
<ide> * element that was blurred just prior to this. This can be overridden when
<ide> * using `Touchable.Mixin.withoutDefaultFocusAndBlur`.
<ide> */
<del> touchableHandleFocus: function(e: Event) {
<add> touchableHandleFocus: function (e: Event) {
<ide> this.props.onFocus && this.props.onFocus(e);
<ide> },
<ide>
<ide> const TouchableMixin = {
<ide> * This can be overridden when using
<ide> * `Touchable.Mixin.withoutDefaultFocusAndBlur`.
<ide> */
<del> touchableHandleBlur: function(e: Event) {
<add> touchableHandleBlur: function (e: Event) {
<ide> this.props.onBlur && this.props.onBlur(e);
<ide> },
<ide>
<ide> const TouchableMixin = {
<ide> * @sideeffects
<ide> * @private
<ide> */
<del> _remeasureMetricsOnActivation: function() {
<add> _remeasureMetricsOnActivation: function () {
<ide> const responderID = this.state.touchable.responderID;
<ide> if (responderID == null) {
<ide> return;
<ide> const TouchableMixin = {
<ide> }
<ide> },
<ide>
<del> _handleQueryLayout: function(
<add> _handleQueryLayout: function (
<ide> l: number,
<ide> t: number,
<ide> w: number,
<ide> const TouchableMixin = {
<ide> );
<ide> },
<ide>
<del> _handleDelay: function(e: PressEvent) {
<add> _handleDelay: function (e: PressEvent) {
<ide> this.touchableDelayTimeout = null;
<ide> this._receiveSignal(Signals.DELAY, e);
<ide> },
<ide>
<del> _handleLongDelay: function(e: PressEvent) {
<add> _handleLongDelay: function (e: PressEvent) {
<ide> this.longPressDelayTimeout = null;
<ide> const curState = this.state.touchable.touchState;
<ide> if (
<ide> const TouchableMixin = {
<ide> * @throws Error if invalid state transition or unrecognized signal.
<ide> * @sideeffects
<ide> */
<del> _receiveSignal: function(signal: Signal, e: PressEvent) {
<add> _receiveSignal: function (signal: Signal, e: PressEvent) {
<ide> const responderID = this.state.touchable.responderID;
<ide> const curState = this.state.touchable.touchState;
<ide> const nextState = Transitions[curState] && Transitions[curState][signal];
<ide> const TouchableMixin = {
<ide> }
<ide> },
<ide>
<del> _cancelLongPressDelayTimeout: function() {
<add> _cancelLongPressDelayTimeout: function () {
<ide> this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
<ide> this.longPressDelayTimeout = null;
<ide> },
<ide>
<del> _isHighlight: function(state: State): boolean {
<add> _isHighlight: function (state: State): boolean {
<ide> return (
<ide> state === States.RESPONDER_ACTIVE_PRESS_IN ||
<ide> state === States.RESPONDER_ACTIVE_LONG_PRESS_IN
<ide> );
<ide> },
<ide>
<del> _savePressInLocation: function(e: PressEvent) {
<add> _savePressInLocation: function (e: PressEvent) {
<ide> const touch = extractSingleTouch(e.nativeEvent);
<ide> const pageX = touch && touch.pageX;
<ide> const pageY = touch && touch.pageY;
<ide> const TouchableMixin = {
<ide> this.pressInLocation = {pageX, pageY, locationX, locationY};
<ide> },
<ide>
<del> _getDistanceBetweenPoints: function(
<add> _getDistanceBetweenPoints: function (
<ide> aX: number,
<ide> aY: number,
<ide> bX: number,
<ide> const TouchableMixin = {
<ide> * @param {Event} e Native event.
<ide> * @sideeffects
<ide> */
<del> _performSideEffectsForTransition: function(
<add> _performSideEffectsForTransition: function (
<ide> curState: State,
<ide> nextState: State,
<ide> signal: Signal,
<ide> const TouchableMixin = {
<ide> this.touchableDelayTimeout = null;
<ide> },
<ide>
<del> _startHighlight: function(e: PressEvent) {
<add> _startHighlight: function (e: PressEvent) {
<ide> this._savePressInLocation(e);
<ide> this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e);
<ide> },
<ide>
<del> _endHighlight: function(e: PressEvent) {
<add> _endHighlight: function (e: PressEvent) {
<ide> if (this.touchableHandleActivePressOut) {
<ide> if (
<ide> this.touchableGetPressOutDelayMS &&
<ide><path>Libraries/Components/Touchable/TouchableBounce.js
<ide> class TouchableBounce extends React.Component<Props, State> {
<ide> delayPressOut: this.props.delayPressOut,
<ide> pressRectOffset: this.props.pressRetentionOffset,
<ide> android_disableSound: this.props.touchSoundDisabled,
<del> onBlur: event => {
<add> onBlur: (event) => {
<ide> if (Platform.isTV) {
<ide> this._bounceTo(1, 0.4, 0);
<ide> }
<ide> if (this.props.onBlur != null) {
<ide> this.props.onBlur(event);
<ide> }
<ide> },
<del> onFocus: event => {
<add> onFocus: (event) => {
<ide> if (Platform.isTV) {
<ide> this._bounceTo(0.93, 0.1, 0);
<ide> }
<ide> if (this.props.onFocus != null) {
<ide> this.props.onFocus(event);
<ide> }
<ide> },
<del> onLongPress: event => {
<add> onLongPress: (event) => {
<ide> if (this.props.onLongPress != null) {
<ide> this.props.onLongPress(event);
<ide> }
<ide> },
<del> onPress: event => {
<add> onPress: (event) => {
<ide> const {onPressAnimationComplete, onPressWithCompletion} = this.props;
<ide> const releaseBounciness = this.props.releaseBounciness ?? 10;
<ide> const releaseVelocity = this.props.releaseVelocity ?? 10;
<ide> class TouchableBounce extends React.Component<Props, State> {
<ide> this.props.onPress(event);
<ide> }
<ide> },
<del> onPressIn: event => {
<add> onPressIn: (event) => {
<ide> this._bounceTo(0.93, 0.1, 0);
<ide> if (this.props.onPressIn != null) {
<ide> this.props.onPressIn(event);
<ide> }
<ide> },
<del> onPressOut: event => {
<add> onPressOut: (event) => {
<ide> this._bounceTo(1, 0.4, 0);
<ide> if (this.props.onPressOut != null) {
<ide> this.props.onPressOut(event);
<ide> class TouchableBounce extends React.Component<Props, State> {
<ide> if (Platform.isTV) {
<ide> this._tvTouchable = new TVTouchable(this, {
<ide> getDisabled: () => this.props.disabled === true,
<del> onBlur: event => {
<add> onBlur: (event) => {
<ide> if (this.props.onBlur != null) {
<ide> this.props.onBlur(event);
<ide> }
<ide> },
<del> onFocus: event => {
<add> onFocus: (event) => {
<ide> if (this.props.onFocus != null) {
<ide> this.props.onFocus(event);
<ide> }
<ide> },
<del> onPress: event => {
<add> onPress: (event) => {
<ide> if (this.props.onPress != null) {
<ide> this.props.onPress(event);
<ide> }
<ide><path>Libraries/Components/Touchable/TouchableHighlight.js
<ide> class TouchableHighlight extends React.Component<Props, State> {
<ide> delayPressOut: this.props.delayPressOut,
<ide> pressRectOffset: this.props.pressRetentionOffset,
<ide> android_disableSound: this.props.touchSoundDisabled,
<del> onBlur: event => {
<add> onBlur: (event) => {
<ide> if (Platform.isTV) {
<ide> this._hideUnderlay();
<ide> }
<ide> if (this.props.onBlur != null) {
<ide> this.props.onBlur(event);
<ide> }
<ide> },
<del> onFocus: event => {
<add> onFocus: (event) => {
<ide> if (Platform.isTV) {
<ide> this._showUnderlay();
<ide> }
<ide> if (this.props.onFocus != null) {
<ide> this.props.onFocus(event);
<ide> }
<ide> },
<del> onLongPress: event => {
<add> onLongPress: (event) => {
<ide> if (this.props.onLongPress != null) {
<ide> this.props.onLongPress(event);
<ide> }
<ide> },
<del> onPress: event => {
<add> onPress: (event) => {
<ide> if (this._hideTimeout != null) {
<ide> clearTimeout(this._hideTimeout);
<ide> }
<ide> class TouchableHighlight extends React.Component<Props, State> {
<ide> this.props.onPress(event);
<ide> }
<ide> },
<del> onPressIn: event => {
<add> onPressIn: (event) => {
<ide> if (this._hideTimeout != null) {
<ide> clearTimeout(this._hideTimeout);
<ide> this._hideTimeout = null;
<ide> class TouchableHighlight extends React.Component<Props, State> {
<ide> this.props.onPressIn(event);
<ide> }
<ide> },
<del> onPressOut: event => {
<add> onPressOut: (event) => {
<ide> if (this._hideTimeout == null) {
<ide> this._hideUnderlay();
<ide> }
<ide> class TouchableHighlight extends React.Component<Props, State> {
<ide> if (Platform.isTV) {
<ide> this._tvTouchable = new TVTouchable(this, {
<ide> getDisabled: () => this.props.disabled === true,
<del> onBlur: event => {
<add> onBlur: (event) => {
<ide> if (this.props.onBlur != null) {
<ide> this.props.onBlur(event);
<ide> }
<ide> },
<del> onFocus: event => {
<add> onFocus: (event) => {
<ide> if (this.props.onFocus != null) {
<ide> this.props.onFocus(event);
<ide> }
<ide> },
<del> onPress: event => {
<add> onPress: (event) => {
<ide> if (this.props.onPress != null) {
<ide> this.props.onPress(event);
<ide> }
<ide><path>Libraries/Components/Touchable/TouchableNativeFeedback.js
<ide> class TouchableNativeFeedback extends React.Component<Props, State> {
<ide> android_disableSound: this.props.touchSoundDisabled,
<ide> onLongPress: this.props.onLongPress,
<ide> onPress: this.props.onPress,
<del> onPressIn: event => {
<add> onPressIn: (event) => {
<ide> if (Platform.OS === 'android') {
<ide> this._dispatchPressedStateChange(true);
<ide> this._dispatchHotspotUpdate(event);
<ide> class TouchableNativeFeedback extends React.Component<Props, State> {
<ide> this.props.onPressIn(event);
<ide> }
<ide> },
<del> onPressMove: event => {
<add> onPressMove: (event) => {
<ide> if (Platform.OS === 'android') {
<ide> this._dispatchHotspotUpdate(event);
<ide> }
<ide> },
<del> onPressOut: event => {
<add> onPressOut: (event) => {
<ide> if (Platform.OS === 'android') {
<ide> this._dispatchPressedStateChange(false);
<ide> }
<ide> class TouchableNativeFeedback extends React.Component<Props, State> {
<ide> if (Platform.isTV) {
<ide> this._tvTouchable = new TVTouchable(this, {
<ide> getDisabled: () => this.props.disabled === true,
<del> onBlur: event => {
<add> onBlur: (event) => {
<ide> if (this.props.onBlur != null) {
<ide> this.props.onBlur(event);
<ide> }
<ide> },
<del> onFocus: event => {
<add> onFocus: (event) => {
<ide> if (this.props.onFocus != null) {
<ide> this.props.onFocus(event);
<ide> }
<ide> },
<del> onPress: event => {
<add> onPress: (event) => {
<ide> if (this.props.onPress != null) {
<ide> this.props.onPress(event);
<ide> }
<ide><path>Libraries/Components/Touchable/TouchableOpacity.js
<ide> class TouchableOpacity extends React.Component<Props, State> {
<ide> delayPressIn: this.props.delayPressIn,
<ide> delayPressOut: this.props.delayPressOut,
<ide> pressRectOffset: this.props.pressRetentionOffset,
<del> onBlur: event => {
<add> onBlur: (event) => {
<ide> if (Platform.isTV) {
<ide> this._opacityInactive(250);
<ide> }
<ide> if (this.props.onBlur != null) {
<ide> this.props.onBlur(event);
<ide> }
<ide> },
<del> onFocus: event => {
<add> onFocus: (event) => {
<ide> if (Platform.isTV) {
<ide> this._opacityActive(150);
<ide> }
<ide> class TouchableOpacity extends React.Component<Props, State> {
<ide> },
<ide> onLongPress: this.props.onLongPress,
<ide> onPress: this.props.onPress,
<del> onPressIn: event => {
<add> onPressIn: (event) => {
<ide> this._opacityActive(
<ide> event.dispatchConfig.registrationName === 'onResponderGrant'
<ide> ? 0
<ide> class TouchableOpacity extends React.Component<Props, State> {
<ide> this.props.onPressIn(event);
<ide> }
<ide> },
<del> onPressOut: event => {
<add> onPressOut: (event) => {
<ide> this._opacityInactive(250);
<ide> if (this.props.onPressOut != null) {
<ide> this.props.onPressOut(event);
<ide> class TouchableOpacity extends React.Component<Props, State> {
<ide> if (Platform.isTV) {
<ide> this._tvTouchable = new TVTouchable(this, {
<ide> getDisabled: () => this.props.disabled === true,
<del> onBlur: event => {
<add> onBlur: (event) => {
<ide> if (this.props.onBlur != null) {
<ide> this.props.onBlur(event);
<ide> }
<ide> },
<del> onFocus: event => {
<add> onFocus: (event) => {
<ide> if (this.props.onFocus != null) {
<ide> this.props.onFocus(event);
<ide> }
<ide> },
<del> onPress: event => {
<add> onPress: (event) => {
<ide> if (this.props.onPress != null) {
<ide> this.props.onPress(event);
<ide> }
<ide><path>Libraries/Components/Touchable/TouchableWithoutFeedback.js
<ide> class TouchableWithoutFeedback extends React.Component<Props, State> {
<ide> if (Platform.isTV) {
<ide> this._tvTouchable = new TVTouchable(this, {
<ide> getDisabled: () => this.props.disabled === true,
<del> onBlur: event => {
<add> onBlur: (event) => {
<ide> if (this.props.onBlur != null) {
<ide> this.props.onBlur(event);
<ide> }
<ide> },
<del> onFocus: event => {
<add> onFocus: (event) => {
<ide> if (this.props.onFocus != null) {
<ide> this.props.onFocus(event);
<ide> }
<ide> },
<del> onPress: event => {
<add> onPress: (event) => {
<ide> if (this.props.onPress != null) {
<ide> this.props.onPress(event);
<ide> }
<ide><path>Libraries/Components/Touchable/ensurePositiveDelayProps.js
<ide>
<ide> const invariant = require('invariant');
<ide>
<del>const ensurePositiveDelayProps = function(props: any) {
<add>const ensurePositiveDelayProps = function (props: any) {
<ide> invariant(
<ide> !(
<ide> props.delayPressIn < 0 ||
<ide><path>Libraries/Core/Devtools/__tests__/parseErrorStack-test.js
<ide> function getFakeError() {
<ide> return new Error('Happy Cat');
<ide> }
<ide>
<del>describe('parseErrorStack', function() {
<del> it('parses error stack', function() {
<add>describe('parseErrorStack', function () {
<add> it('parses error stack', function () {
<ide> const stack = parseErrorStack(getFakeError());
<ide> expect(stack.length).toBeGreaterThan(0);
<ide>
<ide> describe('parseErrorStack', function() {
<ide> expect(firstFrame.file).toMatch(/parseErrorStack-test\.js$/);
<ide> });
<ide>
<del> it('does not support framesToPop', function() {
<add> it('does not support framesToPop', function () {
<ide> function getWrappedError() {
<ide> const error = getFakeError();
<ide> error.framesToPop = 1;
<ide> describe('parseErrorStack', function() {
<ide> expect(stack[0].methodName).toEqual('getFakeError');
<ide> });
<ide>
<del> it('ignores bad inputs', function() {
<add> it('ignores bad inputs', function () {
<ide> expect(parseErrorStack({})).toEqual([]);
<ide> expect(parseErrorStack(null)).toEqual([]);
<ide> });
<ide><path>Libraries/Core/Devtools/parseErrorStack.js
<ide> function parseErrorStack(e: ExtendedError): Array<StackFrame> {
<ide> ? e.stack
<ide> : global.HermesInternal
<ide> ? convertHermesStack(parseHermesStack(e.stack))
<del> : stacktraceParser.parse(e.stack).map(frame => ({
<add> : stacktraceParser.parse(e.stack).map((frame) => ({
<ide> ...frame,
<ide> column: frame.column != null ? frame.column - 1 : null,
<ide> }));
<ide><path>Libraries/Core/ExceptionsManager.js
<ide> class SyntheticError extends Error {
<ide> name: string = '';
<ide> }
<ide>
<del>type ExceptionDecorator = ExceptionData => ExceptionData;
<add>type ExceptionDecorator = (ExceptionData) => ExceptionData;
<ide>
<ide> let userExceptionDecorator: ?ExceptionDecorator;
<ide> let inUserExceptionDecorator = false;
<ide> function reportException(
<ide> throw new Error('The stack is null');
<ide> }
<ide> })
<del> .catch(error => {
<add> .catch((error) => {
<ide> console.log('Unable to symbolicate stack trace: ' + error.message);
<ide> });
<ide> }
<ide> function reactConsoleErrorHandler() {
<ide> } else {
<ide> const stringifySafe = require('../Utilities/stringifySafe').default;
<ide> const str = Array.prototype.map
<del> .call(arguments, value =>
<add> .call(arguments, (value) =>
<ide> typeof value === 'string' ? value : stringifySafe(value),
<ide> )
<ide> .join(' ');
<ide><path>Libraries/Core/Timers/JSTimers.js
<ide> function _callTimer(timerID: number, frameTime: number, didTimeout: ?boolean) {
<ide> callback(performanceNow());
<ide> } else if (type === 'requestIdleCallback') {
<ide> callback({
<del> timeRemaining: function() {
<add> timeRemaining: function () {
<ide> // TODO: Optimisation: allow running for longer than one frame if
<ide> // there are no pending JS calls on the bridge from native. This
<ide> // would require a way to check the bridge queue synchronously.
<ide> const JSTimers = {
<ide> * @param {function} func Callback to be invoked after `duration` ms.
<ide> * @param {number} duration Number of milliseconds.
<ide> */
<del> setTimeout: function(func: Function, duration: number, ...args: any): number {
<add> setTimeout: function (
<add> func: Function,
<add> duration: number,
<add> ...args: any
<add> ): number {
<ide> if (__DEV__ && IS_ANDROID && duration > MAX_TIMER_DURATION_MS) {
<ide> console.warn(
<ide> ANDROID_LONG_TIMER_MESSAGE +
<ide> const JSTimers = {
<ide> * @param {function} func Callback to be invoked every `duration` ms.
<ide> * @param {number} duration Number of milliseconds.
<ide> */
<del> setInterval: function(
<add> setInterval: function (
<ide> func: Function,
<ide> duration: number,
<ide> ...args: any
<ide> const JSTimers = {
<ide> * @param {function} func Callback to be invoked before the end of the
<ide> * current JavaScript execution loop.
<ide> */
<del> setImmediate: function(func: Function, ...args: any) {
<add> setImmediate: function (func: Function, ...args: any) {
<ide> const id = _allocateCallback(
<ide> () => func.apply(undefined, args),
<ide> 'setImmediate',
<ide> const JSTimers = {
<ide> /**
<ide> * @param {function} func Callback to be invoked every frame.
<ide> */
<del> requestAnimationFrame: function(func: Function) {
<add> requestAnimationFrame: function (func: Function) {
<ide> const id = _allocateCallback(func, 'requestAnimationFrame');
<ide> createTimer(id, 1, Date.now(), /* recurring */ false);
<ide> return id;
<ide> const JSTimers = {
<ide> * with time remaining in frame.
<ide> * @param {?object} options
<ide> */
<del> requestIdleCallback: function(func: Function, options: ?Object) {
<add> requestIdleCallback: function (func: Function, options: ?Object) {
<ide> if (requestIdleCallbacks.length === 0) {
<ide> setSendIdleEvents(true);
<ide> }
<ide>
<ide> const timeout = options && options.timeout;
<ide> const id = _allocateCallback(
<ide> timeout != null
<del> ? deadline => {
<add> ? (deadline) => {
<ide> const timeoutId = requestIdleCallbackTimeouts[id];
<ide> if (timeoutId) {
<ide> JSTimers.clearTimeout(timeoutId);
<ide> const JSTimers = {
<ide> return id;
<ide> },
<ide>
<del> cancelIdleCallback: function(timerID: number) {
<add> cancelIdleCallback: function (timerID: number) {
<ide> _freeCallback(timerID);
<ide> const index = requestIdleCallbacks.indexOf(timerID);
<ide> if (index !== -1) {
<ide> const JSTimers = {
<ide> }
<ide> },
<ide>
<del> clearTimeout: function(timerID: number) {
<add> clearTimeout: function (timerID: number) {
<ide> _freeCallback(timerID);
<ide> },
<ide>
<del> clearInterval: function(timerID: number) {
<add> clearInterval: function (timerID: number) {
<ide> _freeCallback(timerID);
<ide> },
<ide>
<del> clearImmediate: function(timerID: number) {
<add> clearImmediate: function (timerID: number) {
<ide> _freeCallback(timerID);
<ide> const index = immediates.indexOf(timerID);
<ide> if (index !== -1) {
<ide> immediates.splice(index, 1);
<ide> }
<ide> },
<ide>
<del> cancelAnimationFrame: function(timerID: number) {
<add> cancelAnimationFrame: function (timerID: number) {
<ide> _freeCallback(timerID);
<ide> },
<ide>
<ide> /**
<ide> * This is called from the native side. We are passed an array of timerIDs,
<ide> * and
<ide> */
<del> callTimers: function(timersToCall: Array<number>) {
<add> callTimers: function (timersToCall: Array<number>) {
<ide> invariant(
<ide> timersToCall.length !== 0,
<ide> 'Cannot call `callTimers` with an empty list of IDs.',
<ide> const JSTimers = {
<ide> // error one at a time
<ide> for (let ii = 1; ii < errorCount; ii++) {
<ide> JSTimers.setTimeout(
<del> (error => {
<add> ((error) => {
<ide> throw error;
<ide> }).bind(null, errors[ii]),
<ide> 0,
<ide> const JSTimers = {
<ide> }
<ide> },
<ide>
<del> callIdleCallbacks: function(frameTime: number) {
<add> callIdleCallbacks: function (frameTime: number) {
<ide> if (
<ide> FRAME_DURATION - (performanceNow() - frameTime) <
<ide> IDLE_CALLBACK_FRAME_DEADLINE
<ide> const JSTimers = {
<ide> }
<ide>
<ide> if (errors) {
<del> errors.forEach(error =>
<add> errors.forEach((error) =>
<ide> JSTimers.setTimeout(() => {
<ide> throw error;
<ide> }, 0),
<ide> const JSTimers = {
<ide> errors = (null: ?Array<Error>);
<ide> while (_callImmediatesPass()) {}
<ide> if (errors) {
<del> errors.forEach(error =>
<add> errors.forEach((error) =>
<ide> JSTimers.setTimeout(() => {
<ide> throw error;
<ide> }, 0),
<ide><path>Libraries/Core/Timers/__tests__/JSTimers-test.js
<ide> jest
<ide>
<ide> const JSTimers = require('../JSTimers');
<ide>
<del>describe('JSTimers', function() {
<del> const firstArgumentOfTheLastCallTo = function(func) {
<add>describe('JSTimers', function () {
<add> const firstArgumentOfTheLastCallTo = function (func) {
<ide> return func.mock.calls[func.mock.calls.length - 1][0];
<ide> };
<ide>
<del> beforeEach(function() {
<add> beforeEach(function () {
<ide> global.setTimeout = JSTimers.setTimeout;
<ide> });
<ide>
<del> it('should call function with setTimeout', function() {
<add> it('should call function with setTimeout', function () {
<ide> let didCall = false;
<del> const id = JSTimers.setTimeout(function() {
<add> const id = JSTimers.setTimeout(function () {
<ide> didCall = true;
<ide> });
<ide> JSTimers.callTimers([id]);
<ide> expect(didCall).toBe(true);
<ide> });
<ide>
<del> it('should call nested setTimeout when cleared', function() {
<add> it('should call nested setTimeout when cleared', function () {
<ide> let id1, id2, id3;
<ide> let callCount = 0;
<ide>
<del> id1 = JSTimers.setTimeout(function() {
<add> id1 = JSTimers.setTimeout(function () {
<ide> JSTimers.clearTimeout(id1);
<del> id2 = JSTimers.setTimeout(function() {
<add> id2 = JSTimers.setTimeout(function () {
<ide> JSTimers.clearTimeout(id2);
<del> id3 = JSTimers.setTimeout(function() {
<add> id3 = JSTimers.setTimeout(function () {
<ide> callCount += 1;
<ide> });
<ide> });
<ide> describe('JSTimers', function() {
<ide> expect(callCount).toBe(1);
<ide> });
<ide>
<del> it('should call nested setImmediate when cleared', function() {
<add> it('should call nested setImmediate when cleared', function () {
<ide> let id1, id2, id3;
<ide> let callCount = 0;
<ide>
<del> id1 = JSTimers.setImmediate(function() {
<add> id1 = JSTimers.setImmediate(function () {
<ide> JSTimers.clearImmediate(id1);
<del> id2 = JSTimers.setImmediate(function() {
<add> id2 = JSTimers.setImmediate(function () {
<ide> JSTimers.clearImmediate(id2);
<del> id3 = JSTimers.setImmediate(function() {
<add> id3 = JSTimers.setImmediate(function () {
<ide> callCount += 1;
<ide> });
<ide> });
<ide> describe('JSTimers', function() {
<ide> expect(callCount).toBe(1);
<ide> });
<ide>
<del> it('should call nested requestAnimationFrame when cleared', function() {
<add> it('should call nested requestAnimationFrame when cleared', function () {
<ide> let id1, id2, id3;
<ide> let callCount = 0;
<ide>
<del> id1 = JSTimers.requestAnimationFrame(function() {
<add> id1 = JSTimers.requestAnimationFrame(function () {
<ide> JSTimers.cancelAnimationFrame(id1);
<del> id2 = JSTimers.requestAnimationFrame(function() {
<add> id2 = JSTimers.requestAnimationFrame(function () {
<ide> JSTimers.cancelAnimationFrame(id2);
<del> id3 = JSTimers.requestAnimationFrame(function() {
<add> id3 = JSTimers.requestAnimationFrame(function () {
<ide> callCount += 1;
<ide> });
<ide> });
<ide> describe('JSTimers', function() {
<ide> expect(callCount).toBe(1);
<ide> });
<ide>
<del> it('should call nested setInterval when cleared', function() {
<add> it('should call nested setInterval when cleared', function () {
<ide> let id1, id2, id3;
<ide> let callCount = 0;
<ide>
<del> id1 = JSTimers.setInterval(function() {
<add> id1 = JSTimers.setInterval(function () {
<ide> JSTimers.clearInterval(id1);
<del> id2 = JSTimers.setInterval(function() {
<add> id2 = JSTimers.setInterval(function () {
<ide> JSTimers.clearInterval(id2);
<del> id3 = JSTimers.setInterval(function() {
<add> id3 = JSTimers.setInterval(function () {
<ide> callCount += 1;
<ide> });
<ide> });
<ide> describe('JSTimers', function() {
<ide> expect(callCount).toBe(1);
<ide> });
<ide>
<del> it('should call function with setInterval', function() {
<add> it('should call function with setInterval', function () {
<ide> const callback = jest.fn();
<ide> const id = JSTimers.setInterval(callback);
<ide> JSTimers.callTimers([id]);
<ide> expect(callback).toBeCalledTimes(1);
<ide> });
<ide>
<del> it('should call function with setImmediate', function() {
<add> it('should call function with setImmediate', function () {
<ide> const callback = jest.fn();
<ide> JSTimers.setImmediate(callback);
<ide> JSTimers.callImmediates();
<ide> expect(callback).toBeCalledTimes(1);
<ide> });
<ide>
<del> it('should not call function with clearImmediate', function() {
<add> it('should not call function with clearImmediate', function () {
<ide> const callback = jest.fn();
<ide> const id = JSTimers.setImmediate(callback);
<ide> JSTimers.clearImmediate(id);
<ide> JSTimers.callImmediates();
<ide> expect(callback).not.toBeCalled();
<ide> });
<ide>
<del> it('should call functions in the right order with setImmediate', function() {
<add> it('should call functions in the right order with setImmediate', function () {
<ide> let count = 0;
<ide> let firstCalled = null;
<ide> let secondCalled = null;
<del> JSTimers.setImmediate(function() {
<add> JSTimers.setImmediate(function () {
<ide> firstCalled = count++;
<ide> });
<del> JSTimers.setImmediate(function() {
<add> JSTimers.setImmediate(function () {
<ide> secondCalled = count++;
<ide> });
<ide> JSTimers.callImmediates();
<ide> expect(firstCalled).toBe(0);
<ide> expect(secondCalled).toBe(1);
<ide> });
<ide>
<del> it('should call functions in the right order with nested setImmediate', function() {
<add> it('should call functions in the right order with nested setImmediate', function () {
<ide> let count = 0;
<ide> let firstCalled = null;
<ide> let secondCalled = null;
<ide> let thirdCalled = null;
<del> JSTimers.setImmediate(function() {
<add> JSTimers.setImmediate(function () {
<ide> firstCalled = count++;
<del> JSTimers.setImmediate(function() {
<add> JSTimers.setImmediate(function () {
<ide> thirdCalled = count++;
<ide> });
<ide> secondCalled = count++;
<ide> describe('JSTimers', function() {
<ide> expect(thirdCalled).toBe(2);
<ide> });
<ide>
<del> it('should call nested setImmediate', function() {
<add> it('should call nested setImmediate', function () {
<ide> let firstCalled = false;
<ide> let secondCalled = false;
<del> JSTimers.setImmediate(function() {
<add> JSTimers.setImmediate(function () {
<ide> firstCalled = true;
<del> JSTimers.setImmediate(function() {
<add> JSTimers.setImmediate(function () {
<ide> secondCalled = true;
<ide> });
<ide> });
<ide> describe('JSTimers', function() {
<ide> expect(secondCalled).toBe(true);
<ide> });
<ide>
<del> it('should call function with requestAnimationFrame', function() {
<add> it('should call function with requestAnimationFrame', function () {
<ide> const callback = jest.fn();
<ide> const id = JSTimers.requestAnimationFrame(callback);
<ide> JSTimers.callTimers([id]);
<ide> expect(callback).toBeCalledTimes(1);
<ide> });
<ide>
<del> it("should not call function if we don't callTimers", function() {
<add> it("should not call function if we don't callTimers", function () {
<ide> const callback = jest.fn();
<ide> JSTimers.setTimeout(callback, 10);
<ide> expect(callback).not.toBeCalled();
<ide> describe('JSTimers', function() {
<ide> expect(callback).not.toBeCalled();
<ide> });
<ide>
<del> it('should call setInterval as many times as callTimers is called', function() {
<add> it('should call setInterval as many times as callTimers is called', function () {
<ide> const callback = jest.fn();
<ide> const id = JSTimers.setInterval(callback, 10);
<ide> JSTimers.callTimers([id]);
<ide> describe('JSTimers', function() {
<ide> expect(callback).toBeCalledTimes(4);
<ide> });
<ide>
<del> it("should only call the function who's id we pass in", function() {
<add> it("should only call the function who's id we pass in", function () {
<ide> let firstCalled = false;
<ide> let secondCalled = false;
<del> JSTimers.setTimeout(function() {
<add> JSTimers.setTimeout(function () {
<ide> firstCalled = true;
<ide> });
<del> const secondID = JSTimers.setTimeout(function() {
<add> const secondID = JSTimers.setTimeout(function () {
<ide> secondCalled = true;
<ide> });
<ide> JSTimers.callTimers([secondID]);
<ide> expect(firstCalled).toBe(false);
<ide> expect(secondCalled).toBe(true);
<ide> });
<ide>
<del> it('should work with calling multiple timers', function() {
<add> it('should work with calling multiple timers', function () {
<ide> let firstCalled = false;
<ide> let secondCalled = false;
<del> const firstID = JSTimers.setTimeout(function() {
<add> const firstID = JSTimers.setTimeout(function () {
<ide> firstCalled = true;
<ide> });
<del> const secondID = JSTimers.setTimeout(function() {
<add> const secondID = JSTimers.setTimeout(function () {
<ide> secondCalled = true;
<ide> });
<ide> JSTimers.callTimers([firstID, secondID]);
<ide> expect(firstCalled).toBe(true);
<ide> expect(secondCalled).toBe(true);
<ide> });
<ide>
<del> it('should still execute all callbacks even if one throws', function() {
<del> const firstID = JSTimers.setTimeout(function() {
<add> it('should still execute all callbacks even if one throws', function () {
<add> const firstID = JSTimers.setTimeout(function () {
<ide> throw new Error('error');
<ide> }, 10);
<ide> let secondCalled = false;
<del> const secondID = JSTimers.setTimeout(function() {
<add> const secondID = JSTimers.setTimeout(function () {
<ide> secondCalled = true;
<ide> }, 10);
<ide> expect(JSTimers.callTimers.bind(null, [firstID, secondID])).toThrow();
<ide> expect(secondCalled).toBe(true);
<ide> });
<ide>
<del> it('should clear timers even if callback throws', function() {
<del> const timerID = JSTimers.setTimeout(function() {
<add> it('should clear timers even if callback throws', function () {
<add> const timerID = JSTimers.setTimeout(function () {
<ide> throw new Error('error');
<ide> }, 10);
<ide> expect(JSTimers.callTimers.bind(null, [timerID])).toThrow('error');
<ide> JSTimers.callTimers.bind(null, [timerID]);
<ide> });
<ide>
<del> it('should not warn if callback is called on cancelled timer', function() {
<add> it('should not warn if callback is called on cancelled timer', function () {
<ide> const callback = jest.fn();
<ide> const timerID = JSTimers.setTimeout(callback, 10);
<ide> JSTimers.clearTimeout(timerID);
<ide> describe('JSTimers', function() {
<ide> expect(firstArgumentOfTheLastCallTo(warning)).toBe(true);
<ide> });
<ide>
<del> it('should warn when callTimers is called with garbage timer id', function() {
<add> it('should warn when callTimers is called with garbage timer id', function () {
<ide> JSTimers.callTimers([1337]);
<ide> expect(firstArgumentOfTheLastCallTo(warning)).toBe(false);
<ide> });
<ide>
<del> it('should only call callback once for setTimeout', function() {
<add> it('should only call callback once for setTimeout', function () {
<ide> const callback = jest.fn();
<ide> const timerID = JSTimers.setTimeout(callback, 10);
<ide> // First time the timer fires, should call callback
<ide> describe('JSTimers', function() {
<ide> expect(firstArgumentOfTheLastCallTo(warning)).toBe(true);
<ide> });
<ide>
<del> it('should only call callback once for requestAnimationFrame', function() {
<add> it('should only call callback once for requestAnimationFrame', function () {
<ide> const callback = jest.fn();
<ide> const timerID = JSTimers.requestAnimationFrame(callback, 10);
<ide> // First time the timer fires, should call callback
<ide> describe('JSTimers', function() {
<ide> expect(firstArgumentOfTheLastCallTo(warning)).toBe(true);
<ide> });
<ide>
<del> it('should re-throw first exception', function() {
<del> const timerID1 = JSTimers.setTimeout(function() {
<add> it('should re-throw first exception', function () {
<add> const timerID1 = JSTimers.setTimeout(function () {
<ide> throw new Error('first error');
<ide> });
<del> const timerID2 = JSTimers.setTimeout(function() {
<add> const timerID2 = JSTimers.setTimeout(function () {
<ide> throw new Error('second error');
<ide> });
<ide> expect(JSTimers.callTimers.bind(null, [timerID1, timerID2])).toThrowError(
<ide> 'first error',
<ide> );
<ide> });
<ide>
<del> it('should pass along errors thrown from setImmediate', function() {
<del> JSTimers.setImmediate(function() {
<add> it('should pass along errors thrown from setImmediate', function () {
<add> JSTimers.setImmediate(function () {
<ide> throw new Error('error within setImmediate');
<ide> });
<ide>
<ide> describe('JSTimers', function() {
<ide> );
<ide> });
<ide>
<del> it('should throw all errors from setImmediate', function() {
<del> JSTimers.setImmediate(function() {
<add> it('should throw all errors from setImmediate', function () {
<add> JSTimers.setImmediate(function () {
<ide> throw new Error('first error');
<ide> });
<ide>
<del> JSTimers.setImmediate(function() {
<add> JSTimers.setImmediate(function () {
<ide> throw new Error('second error');
<ide> });
<ide>
<ide> describe('JSTimers', function() {
<ide> );
<ide> });
<ide>
<del> it('should pass along errors thrown from setTimeout', function() {
<del> const timerID = JSTimers.setTimeout(function() {
<add> it('should pass along errors thrown from setTimeout', function () {
<add> const timerID = JSTimers.setTimeout(function () {
<ide> throw new Error('error within setTimeout');
<ide> });
<ide>
<ide> describe('JSTimers', function() {
<ide> );
<ide> });
<ide>
<del> it('should throw all errors from setTimeout', function() {
<del> const firstTimerID = JSTimers.setTimeout(function() {
<add> it('should throw all errors from setTimeout', function () {
<add> const firstTimerID = JSTimers.setTimeout(function () {
<ide> throw new Error('first error');
<ide> });
<del> const secondTimerID = JSTimers.setTimeout(function() {
<add> const secondTimerID = JSTimers.setTimeout(function () {
<ide> throw new Error('second error');
<ide> });
<ide>
<ide> describe('JSTimers', function() {
<ide> );
<ide> });
<ide>
<del> it('should pass along errors thrown from setInterval', function() {
<del> const timerID = JSTimers.setInterval(function() {
<add> it('should pass along errors thrown from setInterval', function () {
<add> const timerID = JSTimers.setInterval(function () {
<ide> throw new Error('error within setInterval');
<ide> });
<ide> expect(JSTimers.callTimers.bind(null, [timerID])).toThrowError(
<ide> 'error within setInterval',
<ide> );
<ide> });
<ide>
<del> it('should not call to native when clearing a null timer', function() {
<add> it('should not call to native when clearing a null timer', function () {
<ide> const timerID = JSTimers.setTimeout(() => {});
<ide> JSTimers.clearTimeout(timerID);
<ide> NativeTiming.deleteTimer = jest.fn();
<ide><path>Libraries/Core/__mocks__/ErrorUtils.js
<ide> function reportError(error) {
<ide> const ErrorUtils = {
<ide> apply: jest.fn(execute),
<ide> applyWithGuard: jest.fn(execute),
<del> guard: jest.fn(callback => callback),
<add> guard: jest.fn((callback) => callback),
<ide> inGuard: jest.fn().mockReturnValue(true),
<ide> reportError: jest.fn(reportError),
<ide> setGlobalHandler: jest.fn(),
<ide><path>Libraries/Core/__tests__/ExceptionsManager-test.js
<ide> describe('ExceptionsManager', () => {
<ide>
<ide> test('modifying the exception data', () => {
<ide> const error = new Error('Some error happened');
<del> const decorator = jest.fn().mockImplementation(data => ({
<add> const decorator = jest.fn().mockImplementation((data) => ({
<ide> ...data,
<ide> message: 'decorated: ' + data.message,
<ide> }));
<ide> describe('ExceptionsManager', () => {
<ide>
<ide> test('clearing a decorator', () => {
<ide> const error = new Error('Some error happened');
<del> const decorator = jest.fn().mockImplementation(data => ({
<add> const decorator = jest.fn().mockImplementation((data) => ({
<ide> ...data,
<ide> message: 'decorated: ' + data.message,
<ide> }));
<ide> describe('ExceptionsManager', () => {
<ide>
<ide> test('prevents decorator recursion from error handler', () => {
<ide> const error = new Error('Some error happened');
<del> const decorator = jest.fn().mockImplementation(data => {
<add> const decorator = jest.fn().mockImplementation((data) => {
<ide> console.error('Logging an error within the decorator');
<ide> return {
<ide> ...data,
<ide> describe('ExceptionsManager', () => {
<ide>
<ide> test('prevents decorator recursion from console.error', () => {
<ide> const error = new Error('Some error happened');
<del> const decorator = jest.fn().mockImplementation(data => {
<add> const decorator = jest.fn().mockImplementation((data) => {
<ide> console.error('Logging an error within the decorator');
<ide> return {
<ide> ...data,
<ide> describe('ExceptionsManager', () => {
<ide>
<ide> test('can handle throwing decorators recursion when exception is thrown', () => {
<ide> const error = new Error('Some error happened');
<del> const decorator = jest.fn().mockImplementation(data => {
<add> const decorator = jest.fn().mockImplementation((data) => {
<ide> throw new Error('Throwing an error within the decorator');
<ide> });
<ide>
<ide> describe('ExceptionsManager', () => {
<ide>
<ide> test('can handle throwing decorators recursion when exception is logged', () => {
<ide> const error = new Error('Some error happened');
<del> const decorator = jest.fn().mockImplementation(data => {
<add> const decorator = jest.fn().mockImplementation((data) => {
<ide> throw new Error('Throwing an error within the decorator');
<ide> });
<ide>
<ide><path>Libraries/Core/__tests__/ReactNativeVersionCheck-test.js
<ide> function _defineCheckVersionTests() {
<ide> beforeEach(() => {
<ide> consoleOutput = '';
<ide> console.error = jest.fn();
<del> global.console = {error: jest.fn(error => (consoleOutput += error))};
<add> global.console = {error: jest.fn((error) => (consoleOutput += error))};
<ide> spyOnConsoleError = jest.spyOn(global.console, 'error');
<ide> });
<ide>
<ide><path>Libraries/Core/setUpAlert.js
<ide> * You can use this module directly, or just require InitializeCore.
<ide> */
<ide> if (!global.alert) {
<del> global.alert = function(text) {
<add> global.alert = function (text) {
<ide> // Require Alert on demand. Requiring it too early can lead to issues
<ide> // with things like Platform not being fully initialized.
<ide> require('../Alert/Alert').alert('Alert', '' + text);
<ide><path>Libraries/Core/setUpDeveloperTools.js
<ide> if (__DEV__) {
<ide> 'groupCollapsed',
<ide> 'groupEnd',
<ide> 'debug',
<del> ].forEach(level => {
<add> ].forEach((level) => {
<ide> const originalFunction = console[level];
<del> console[level] = function(...args) {
<add> console[level] = function (...args) {
<ide> HMRClient.log(level, args);
<ide> originalFunction.apply(console, args);
<ide> };
<ide><path>Libraries/Core/setUpTimers.js
<ide> if (!global.RN$Bridgeless) {
<ide> * Set up timers.
<ide> * You can use this module directly, or just require InitializeCore.
<ide> */
<del> const defineLazyTimer = name => {
<add> const defineLazyTimer = (name) => {
<ide> polyfillGlobal(name, () => require('./Timers/JSTimers')[name]);
<ide> };
<ide> defineLazyTimer('setTimeout');
<ide><path>Libraries/DeprecatedPropTypes/DeprecatedColorPropType.js
<ide>
<ide> const normalizeColor = require('../StyleSheet/normalizeColor');
<ide>
<del>const colorPropType = function(
<add>const colorPropType = function (
<ide> isRequired,
<ide> props,
<ide> propName,
<ide><path>Libraries/DeprecatedPropTypes/DeprecatedStyleSheetPropType.js
<ide> function DeprecatedStyleSheetPropType(shape: {
<ide> ...,
<ide> }): ReactPropsCheckType {
<ide> const shapePropType = deprecatedCreateStrictShapeTypeChecker(shape);
<del> return function(props, propName, componentName, location?, ...rest) {
<add> return function (props, propName, componentName, location?, ...rest) {
<ide> let newProps = props;
<ide> if (props[propName]) {
<ide> // Just make a dummy prop object with only the flattened style
<ide><path>Libraries/DeprecatedPropTypes/DeprecatedTransformPropTypes.js
<ide> const ReactPropTypes = require('prop-types');
<ide>
<ide> const deprecatedPropType = require('../Utilities/deprecatedPropType');
<ide>
<del>const TransformMatrixPropType = function(
<add>const TransformMatrixPropType = function (
<ide> props: Object,
<ide> propName: string,
<ide> componentName: string,
<ide> const TransformMatrixPropType = function(
<ide> }
<ide> };
<ide>
<del>const DecomposedMatrixPropType = function(
<add>const DecomposedMatrixPropType = function (
<ide> props: Object,
<ide> propName: string,
<ide> componentName: string,
<ide><path>Libraries/HeapCapture/HeapCapture.js
<ide> import NativeJSCHeapCapture from './NativeJSCHeapCapture';
<ide>
<ide> const HeapCapture = {
<del> captureHeap: function(path: string) {
<add> captureHeap: function (path: string) {
<ide> let error = null;
<ide> try {
<ide> global.nativeCaptureHeap(path);
<ide><path>Libraries/Image/Image.android.js
<ide> function getSize(
<ide> failure?: (error: any) => void,
<ide> ): any {
<ide> return NativeImageLoaderAndroid.getSize(url)
<del> .then(function(sizes) {
<add> .then(function (sizes) {
<ide> success(sizes.width, sizes.height);
<ide> })
<ide> .catch(
<ide> failure ||
<del> function() {
<add> function () {
<ide> console.warn('Failed to get size for image: ' + url);
<ide> },
<ide> );
<ide> function getSizeWithHeaders(
<ide> failure?: (error: any) => void,
<ide> ): any {
<ide> return NativeImageLoaderAndroid.getSizeWithHeaders(url, headers)
<del> .then(function(sizes) {
<add> .then(function (sizes) {
<ide> success(sizes.width, sizes.height);
<ide> })
<ide> .catch(
<ide> failure ||
<del> function() {
<add> function () {
<ide> console.warn('Failed to get size for image: ' + url);
<ide> },
<ide> );
<ide> let Image = (props: ImagePropsType, forwardedRef) => {
<ide>
<ide> return (
<ide> <TextAncestor.Consumer>
<del> {hasTextAncestor =>
<add> {(hasTextAncestor) =>
<ide> hasTextAncestor ? (
<ide> <TextInlineImageNativeComponent {...nativeProps} />
<ide> ) : (
<ide><path>Libraries/Image/Image.ios.js
<ide> function getSize(
<ide> .then(([width, height]) => success(width, height))
<ide> .catch(
<ide> failure ||
<del> function() {
<add> function () {
<ide> console.warn('Failed to get size for image ' + uri);
<ide> },
<ide> );
<ide> function getSizeWithHeaders(
<ide> failure?: (error: any) => void,
<ide> ): any {
<ide> return NativeImageLoaderIOS.getSizeWithHeaders(uri, headers)
<del> .then(function(sizes) {
<add> .then(function (sizes) {
<ide> success(sizes.width, sizes.height);
<ide> })
<ide> .catch(
<ide> failure ||
<del> function() {
<add> function () {
<ide> console.warn('Failed to get size for image: ' + uri);
<ide> },
<ide> );
<ide><path>Libraries/Image/ImageBackground.js
<ide> class ImageBackground extends React.Component<$FlowFixMeProps> {
<ide>
<ide> _viewRef: ?React.ElementRef<typeof View> = null;
<ide>
<del> _captureRef = ref => {
<add> _captureRef = (ref) => {
<ide> this._viewRef = ref;
<ide> };
<ide>
<ide><path>Libraries/Image/ImagePickerIOS.js
<ide> import NativeImagePickerIOS from './NativeImagePickerIOS';
<ide> import invariant from 'invariant';
<ide>
<ide> const ImagePickerIOS = {
<del> canRecordVideos: function(callback: (result: boolean) => void): void {
<add> canRecordVideos: function (callback: (result: boolean) => void): void {
<ide> invariant(NativeImagePickerIOS, 'ImagePickerIOS is not available');
<ide> return NativeImagePickerIOS.canRecordVideos(callback);
<ide> },
<del> canUseCamera: function(callback: (result: boolean) => void): void {
<add> canUseCamera: function (callback: (result: boolean) => void): void {
<ide> invariant(NativeImagePickerIOS, 'ImagePickerIOS is not available');
<ide> return NativeImagePickerIOS.canUseCamera(callback);
<ide> },
<del> openCameraDialog: function(
<add> openCameraDialog: function (
<ide> config: $ReadOnly<{|
<ide> unmirrorFrontFacingCamera?: boolean,
<ide> videoMode?: boolean,
<ide> const ImagePickerIOS = {
<ide> cancelCallback,
<ide> );
<ide> },
<del> openSelectDialog: function(
<add> openSelectDialog: function (
<ide> config: $ReadOnly<{|
<ide> showImages?: boolean,
<ide> showVideos?: boolean,
<ide> const ImagePickerIOS = {
<ide> * It is safe to call this method for urlsthat aren't video URLs;
<ide> * it will be a no-op.
<ide> */
<del> removePendingVideo: function(url: string): void {
<add> removePendingVideo: function (url: string): void {
<ide> invariant(NativeImagePickerIOS, 'ImagePickerIOS is not available');
<ide> NativeImagePickerIOS.removePendingVideo(url);
<ide> },
<ide> /**
<ide> * WARNING: In most cases, removePendingVideo should be used instead because
<ide> * clearAllPendingVideos could clear out pending videos made by other callers.
<ide> */
<del> clearAllPendingVideos: function(): void {
<add> clearAllPendingVideos: function (): void {
<ide> invariant(NativeImagePickerIOS, 'ImagePickerIOS is not available');
<ide> NativeImagePickerIOS.clearAllPendingVideos();
<ide> },
<ide><path>Libraries/Image/__tests__/resolveAssetSource-test.js
<ide> describe('resolveAssetSource', () => {
<ide> });
<ide>
<ide> it('uses bundled source, event when js is sideloaded', () => {
<del> resolveAssetSource.setCustomSourceTransformer(resolver =>
<add> resolveAssetSource.setCustomSourceTransformer((resolver) =>
<ide> resolver.resourceIdentifierWithoutScale(),
<ide> );
<ide> expectResolvesAsset(
<ide> describe('resolveAssetSource', () => {
<ide> });
<ide>
<ide> it('allows any customization', () => {
<del> resolveAssetSource.setCustomSourceTransformer(resolver =>
<add> resolveAssetSource.setCustomSourceTransformer((resolver) =>
<ide> resolver.fromSource('TEST'),
<ide> );
<ide> expectResolvesAsset(
<ide><path>Libraries/Inspector/ElementProperties.js
<ide> type Props = $ReadOnly<{|
<ide> },
<ide> frame?: ?Object,
<ide> selection?: ?number,
<del> setSelection?: number => mixed,
<add> setSelection?: (number) => mixed,
<ide> |}>;
<ide>
<ide> class ElementProperties extends React.Component<Props> {
<ide> class ElementProperties extends React.Component<Props> {
<ide> <Text style={styles.breadItemText}>{hierarchyItem.name}</Text>
<ide> </TouchableHighlight>
<ide> ),
<del> i => (
<add> (i) => (
<ide> <Text key={'sep-' + i} style={styles.breadSep}>
<ide> ▸
<ide> </Text>
<ide><path>Libraries/Inspector/Inspector.js
<ide> class Inspector extends React.Component<
<ide>
<ide> componentWillUnmount() {
<ide> if (this._subs) {
<del> this._subs.map(fn => fn());
<add> this._subs.map((fn) => fn());
<ide> }
<ide> hook.off('react-devtools', this._attachToDevtools);
<ide> }
<ide> class Inspector extends React.Component<
<ide> }, 100);
<ide> };
<ide>
<del> _onAgentShowNativeHighlight = node => {
<add> _onAgentShowNativeHighlight = (node) => {
<ide> clearTimeout(this._hideTimeoutID);
<ide>
<ide> node.measure((x, y, width, height, left, top) => {
<ide> class Inspector extends React.Component<
<ide>
<ide> setTouchTargeting(val: boolean) {
<ide> Touchable.TOUCH_TARGET_DEBUG = val;
<del> this.props.onRequestRerenderApp(inspectedView => {
<add> this.props.onRequestRerenderApp((inspectedView) => {
<ide> this.setState({inspectedView});
<ide> });
<ide> }
<ide><path>Libraries/Inspector/InspectorPanel.js
<ide> type Props = $ReadOnly<{|
<ide> setNetworking: (val: boolean) => void,
<ide> hierarchy?: ?Array<{|name: string|}>,
<ide> selection?: ?number,
<del> setSelection: number => mixed,
<add> setSelection: (number) => mixed,
<ide> inspected?: ?$ReadOnly<{|
<ide> style?: ?ViewStyleProp,
<ide> frame?: ?$ReadOnly<{|
<ide><path>Libraries/Inspector/NetworkOverlay.js
<ide> class NetworkOverlay extends React.Component<Props, State> {
<ide>
<ide> _renderItemDetail(id) {
<ide> const requestItem = this.state.requests[id];
<del> const details = Object.keys(requestItem).map(key => {
<add> const details = Object.keys(requestItem).map((key) => {
<ide> if (key === 'id') {
<ide> return;
<ide> }
<ide> class NetworkOverlay extends React.Component<Props, State> {
<ide> </TouchableHighlight>
<ide> <ScrollView
<ide> style={styles.detailScrollView}
<del> ref={scrollRef => (this._detailScrollView = scrollRef)}>
<add> ref={(scrollRef) => (this._detailScrollView = scrollRef)}>
<ide> {details}
<ide> </ScrollView>
<ide> </View>
<ide><path>Libraries/Inspector/StyleInspector.js
<ide> class StyleInspector extends React.Component<$FlowFixMeProps> {
<ide> return (
<ide> <View style={styles.container}>
<ide> <View>
<del> {names.map(name => (
<add> {names.map((name) => (
<ide> <Text key={name} style={styles.attr}>
<ide> {name}:
<ide> </Text>
<ide> ))}
<ide> </View>
<ide>
<ide> <View>
<del> {names.map(name => {
<add> {names.map((name) => {
<ide> const value = this.props.style[name];
<ide> return (
<ide> <Text key={name} style={styles.value}>
<ide><path>Libraries/Interaction/BridgeSpyStallHandler.js
<ide> const MessageQueue = require('../BatchedBridge/MessageQueue');
<ide> const infoLog = require('../Utilities/infoLog');
<ide>
<ide> const BridgeSpyStallHandler = {
<del> register: function() {
<add> register: function () {
<ide> let spyBuffer = [];
<del> MessageQueue.spy(data => {
<add> MessageQueue.spy((data) => {
<ide> spyBuffer.push(data);
<ide> });
<ide> const TO_JS = 0;
<ide> JSEventLoopWatchdog.addHandler({
<ide> onStall: () => {
<ide> infoLog(
<ide> spyBuffer.length + ' bridge messages during stall: ',
<del> spyBuffer.map(info => {
<add> spyBuffer.map((info) => {
<ide> let args = '<args>';
<ide> try {
<ide> args = JSON.stringify(info.args);
<ide> } catch (e1) {
<ide> if (Array.isArray(info.args)) {
<del> args = info.args.map(arg => {
<add> args = info.args.map((arg) => {
<ide> try {
<ide> return JSON.stringify(arg);
<ide> } catch (e2) {
<ide><path>Libraries/Interaction/FrameRateLogger.js
<ide> const FrameRateLogger = {
<ide> * Enable `debug` to see local logs of what's going on. `reportStackTraces` will grab stack traces
<ide> * during UI thread stalls and upload them if the native module supports it.
<ide> */
<del> setGlobalOptions: function(options: {
<add> setGlobalOptions: function (options: {
<ide> debug?: boolean,
<ide> reportStackTraces?: boolean,
<ide> ...
<ide> const FrameRateLogger = {
<ide> * Must call `setContext` before any events can be properly tracked, which is done automatically
<ide> * in `AppRegistry`, but navigation is also a common place to hook in.
<ide> */
<del> setContext: function(context: string) {
<add> setContext: function (context: string) {
<ide> NativeFrameRateLogger && NativeFrameRateLogger.setContext(context);
<ide> },
<ide>
<ide><path>Libraries/Interaction/InteractionManager.js
<ide> const InteractionManager = {
<ide> ...
<ide> } {
<ide> const tasks = [];
<del> const promise = new Promise(resolve => {
<add> const promise = new Promise((resolve) => {
<ide> _scheduleUpdate();
<ide> if (task) {
<ide> tasks.push(task);
<ide> const InteractionManager = {
<ide> );
<ide> }
<ide> },
<del> cancel: function() {
<add> cancel: function () {
<ide> _taskQueue.cancelTasks(tasks);
<ide> },
<ide> };
<ide> function _processUpdate() {
<ide> _nextUpdateHandle = 0;
<ide>
<ide> const interactionCount = _interactionSet.size;
<del> _addInteractionSet.forEach(handle => _interactionSet.add(handle));
<del> _deleteInteractionSet.forEach(handle => _interactionSet.delete(handle));
<add> _addInteractionSet.forEach((handle) => _interactionSet.add(handle));
<add> _deleteInteractionSet.forEach((handle) => _interactionSet.delete(handle));
<ide> const nextInteractionCount = _interactionSet.size;
<ide>
<ide> if (interactionCount !== 0 && nextInteractionCount === 0) {
<ide><path>Libraries/Interaction/InteractionMixin.js
<ide> import {type Handle} from './InteractionManager';
<ide> * once per start, even if the component is unmounted.
<ide> */
<ide> const InteractionMixin = {
<del> componentWillUnmount: function() {
<add> componentWillUnmount: function () {
<ide> while (this._interactionMixinHandles.length) {
<ide> InteractionManager.clearInteractionHandle(
<ide> this._interactionMixinHandles.pop(),
<ide> const InteractionMixin = {
<ide>
<ide> _interactionMixinHandles: ([]: Array<number>),
<ide>
<del> createInteractionHandle: function(): Handle {
<add> createInteractionHandle: function (): Handle {
<ide> const handle = InteractionManager.createInteractionHandle();
<ide> this._interactionMixinHandles.push(handle);
<ide> return handle;
<ide> },
<ide>
<del> clearInteractionHandle: function(clearHandle: number): void {
<add> clearInteractionHandle: function (clearHandle: number): void {
<ide> InteractionManager.clearInteractionHandle(clearHandle);
<ide> this._interactionMixinHandles = this._interactionMixinHandles.filter(
<del> handle => handle !== clearHandle,
<add> (handle) => handle !== clearHandle,
<ide> );
<ide> },
<ide>
<ide> const InteractionMixin = {
<ide> *
<ide> * @param {function} callback
<ide> */
<del> runAfterInteractions: function(callback: Function): void {
<add> runAfterInteractions: function (callback: Function): void {
<ide> InteractionManager.runAfterInteractions(callback);
<ide> },
<ide> };
<ide><path>Libraries/Interaction/JSEventLoopWatchdog.js
<ide> type Handler = {
<ide> * queried with `getStats`.
<ide> */
<ide> const JSEventLoopWatchdog = {
<del> getStats: function(): Object {
<add> getStats: function (): Object {
<ide> return {stallCount, totalStallTime, longestStall, acceptableBusyTime};
<ide> },
<del> reset: function() {
<add> reset: function () {
<ide> infoLog('JSEventLoopWatchdog: reset');
<ide> totalStallTime = 0;
<ide> stallCount = 0;
<ide> longestStall = 0;
<ide> lastInterval = performanceNow();
<ide> },
<del> addHandler: function(handler: Handler) {
<add> addHandler: function (handler: Handler) {
<ide> handlers.push(handler);
<ide> },
<del> install: function({thresholdMS}: {thresholdMS: number, ...}) {
<add> install: function ({thresholdMS}: {thresholdMS: number, ...}) {
<ide> acceptableBusyTime = thresholdMS;
<ide> if (installed) {
<ide> return;
<ide> const JSEventLoopWatchdog = {
<ide> let msg =
<ide> `JSEventLoopWatchdog: JS thread busy for ${busyTime}ms. ` +
<ide> `${totalStallTime}ms in ${stallCount} stalls so far. `;
<del> handlers.forEach(handler => {
<add> handlers.forEach((handler) => {
<ide> msg += handler.onStall({lastInterval, busyTime}) || '';
<ide> });
<ide> infoLog(msg);
<ide> }
<del> handlers.forEach(handler => {
<add> handlers.forEach((handler) => {
<ide> handler.onIterate && handler.onIterate();
<ide> });
<ide> lastInterval = now;
<ide><path>Libraries/Interaction/TaskQueue.js
<ide> class TaskQueue {
<ide> }
<ide>
<ide> enqueueTasks(tasks: Array<Task>): void {
<del> tasks.forEach(task => this.enqueue(task));
<add> tasks.forEach((task) => this.enqueue(task));
<ide> }
<ide>
<ide> cancelTasks(tasksToCancel: Array<Task>): void {
<ide> // search through all tasks and remove them.
<ide> this._queueStack = this._queueStack
<del> .map(queue => ({
<add> .map((queue) => ({
<ide> ...queue,
<del> tasks: queue.tasks.filter(task => tasksToCancel.indexOf(task) === -1),
<add> tasks: queue.tasks.filter((task) => tasksToCancel.indexOf(task) === -1),
<ide> }))
<ide> .filter((queue, idx) => queue.tasks.length > 0 || idx === 0);
<ide> }
<ide> class TaskQueue {
<ide> this._queueStack[stackIdx].popable = true;
<ide> this.hasTasksToProcess() && this._onMoreTasks();
<ide> })
<del> .catch(ex => {
<del> ex.message = `TaskQueue: Error resolving Promise in task ${
<del> task.name
<del> }: ${ex.message}`;
<add> .catch((ex) => {
<add> ex.message = `TaskQueue: Error resolving Promise in task ${task.name}: ${ex.message}`;
<ide> throw ex;
<ide> })
<ide> .done();
<ide><path>Libraries/Interaction/TouchHistoryMath.js
<ide> const TouchHistoryMath = {
<ide> * touches vs. previous centroid of now actively moving touches.
<ide> * @return {number} value of centroid in specified dimension.
<ide> */
<del> centroidDimension: function(
<add> centroidDimension: function (
<ide> touchHistory,
<ide> touchesChangedAfter,
<ide> isXAxis,
<ide> const TouchHistoryMath = {
<ide> return count > 0 ? total / count : TouchHistoryMath.noCentroid;
<ide> },
<ide>
<del> currentCentroidXOfTouchesChangedAfter: function(
<add> currentCentroidXOfTouchesChangedAfter: function (
<ide> touchHistory,
<ide> touchesChangedAfter,
<ide> ) {
<ide> const TouchHistoryMath = {
<ide> );
<ide> },
<ide>
<del> currentCentroidYOfTouchesChangedAfter: function(
<add> currentCentroidYOfTouchesChangedAfter: function (
<ide> touchHistory,
<ide> touchesChangedAfter,
<ide> ) {
<ide> const TouchHistoryMath = {
<ide> );
<ide> },
<ide>
<del> previousCentroidXOfTouchesChangedAfter: function(
<add> previousCentroidXOfTouchesChangedAfter: function (
<ide> touchHistory,
<ide> touchesChangedAfter,
<ide> ) {
<ide> const TouchHistoryMath = {
<ide> );
<ide> },
<ide>
<del> previousCentroidYOfTouchesChangedAfter: function(
<add> previousCentroidYOfTouchesChangedAfter: function (
<ide> touchHistory,
<ide> touchesChangedAfter,
<ide> ) {
<ide> const TouchHistoryMath = {
<ide> );
<ide> },
<ide>
<del> currentCentroidX: function(touchHistory) {
<add> currentCentroidX: function (touchHistory) {
<ide> return TouchHistoryMath.centroidDimension(
<ide> touchHistory,
<ide> 0, // touchesChangedAfter
<ide> const TouchHistoryMath = {
<ide> );
<ide> },
<ide>
<del> currentCentroidY: function(touchHistory) {
<add> currentCentroidY: function (touchHistory) {
<ide> return TouchHistoryMath.centroidDimension(
<ide> touchHistory,
<ide> 0, // touchesChangedAfter
<ide><path>Libraries/Interaction/__tests__/InteractionManager-test.js
<ide> describe('promise tasks', () => {
<ide> it('should run a basic promise task', () => {
<ide> const task1 = jest.fn(() => {
<ide> expect(++sequenceId).toBe(1);
<del> return new Promise(resolve => resolve());
<add> return new Promise((resolve) => resolve());
<ide> });
<ide> InteractionManager.runAfterInteractions({gen: task1, name: 'gen1'});
<ide> jest.runAllTimers();
<ide> describe('promise tasks', () => {
<ide> it('should handle nested promises', () => {
<ide> const task1 = jest.fn(() => {
<ide> expect(++sequenceId).toBe(1);
<del> return new Promise(resolve => {
<add> return new Promise((resolve) => {
<ide> InteractionManager.runAfterInteractions({
<ide> gen: task2,
<ide> name: 'gen2',
<ide> describe('promise tasks', () => {
<ide> });
<ide> const task2 = jest.fn(() => {
<ide> expect(++sequenceId).toBe(2);
<del> return new Promise(resolve => resolve());
<add> return new Promise((resolve) => resolve());
<ide> });
<ide> InteractionManager.runAfterInteractions({gen: task1, name: 'gen1'});
<ide> jest.runAllTimers();
<ide> describe('promise tasks', () => {
<ide> const task1 = createSequenceTask(1);
<ide> const task2 = jest.fn(() => {
<ide> expect(++sequenceId).toBe(2);
<del> return new Promise(resolve => {
<add> return new Promise((resolve) => {
<ide> setTimeout(() => {
<ide> InteractionManager.runAfterInteractions(task3).then(resolve);
<ide> }, 1);
<ide> describe('promise tasks', () => {
<ide> expectToBeCalledOnce(task2);
<ide> });
<ide>
<del> const bigAsyncTest = resolveTest => {
<add> const bigAsyncTest = (resolveTest) => {
<ide> jest.useRealTimers();
<ide>
<ide> const task1 = createSequenceTask(1);
<ide> const task2 = jest.fn(() => {
<ide> expect(++sequenceId).toBe(2);
<del> return new Promise(resolve => {
<add> return new Promise((resolve) => {
<ide> InteractionManager.runAfterInteractions(task3);
<ide> setTimeout(() => {
<ide> InteractionManager.runAfterInteractions({
<ide> describe('promise tasks', () => {
<ide> const task3 = createSequenceTask(3);
<ide> const task4 = jest.fn(() => {
<ide> expect(++sequenceId).toBe(4);
<del> return new Promise(resolve => {
<add> return new Promise((resolve) => {
<ide> InteractionManager.runAfterInteractions(task5).then(resolve);
<ide> });
<ide> });
<ide><path>Libraries/Interaction/__tests__/TaskQueue-test.js
<ide> describe('TaskQueue', () => {
<ide>
<ide> it('should handle blocking promise task', () => {
<ide> const task1 = jest.fn(() => {
<del> return new Promise(resolve => {
<add> return new Promise((resolve) => {
<ide> setTimeout(() => {
<ide> expect(++sequenceId).toBe(1);
<ide> resolve();
<ide> describe('TaskQueue', () => {
<ide>
<ide> it('should handle nested promises', () => {
<ide> const task1 = jest.fn(() => {
<del> return new Promise(resolve => {
<add> return new Promise((resolve) => {
<ide> setTimeout(() => {
<ide> expect(++sequenceId).toBe(1);
<ide> taskQueue.enqueue({gen: task2, name: 'gen2'});
<ide> describe('TaskQueue', () => {
<ide> });
<ide> });
<ide> const task2 = jest.fn(() => {
<del> return new Promise(resolve => {
<add> return new Promise((resolve) => {
<ide> setTimeout(() => {
<ide> expect(++sequenceId).toBe(2);
<ide> taskQueue.enqueue({run: task3, name: 'run3'});
<ide><path>Libraries/LayoutAnimation/LayoutAnimation.js
<ide> function configureNext(
<ide> if (!Platform.isTesting) {
<ide> UIManager.configureNextLayoutAnimation(
<ide> config,
<del> onAnimationDidEnd ?? function() {},
<del> function() {} /* unused onError */,
<add> onAnimationDidEnd ?? function () {},
<add> function () {} /* unused onError */,
<ide> );
<ide> }
<ide> }
<ide><path>Libraries/Lists/FillRateHelper.js
<ide> class FillRateHelper {
<ide> _samplesStartTime = (null: ?number);
<ide>
<ide> static addListener(
<del> callback: FillRateInfo => void,
<add> callback: (FillRateInfo) => void,
<ide> ): {remove: () => void, ...} {
<ide> warning(
<ide> _sampleRate !== null,
<ide> class FillRateHelper {
<ide> _listeners.push(callback);
<ide> return {
<ide> remove: () => {
<del> _listeners = _listeners.filter(listener => callback !== listener);
<add> _listeners = _listeners.filter((listener) => callback !== listener);
<ide> },
<ide> };
<ide> }
<ide> class FillRateHelper {
<ide> }
<ide> console.debug('FillRateHelper deactivateAndFlush: ', {derived, info});
<ide> }
<del> _listeners.forEach(listener => listener(info));
<add> _listeners.forEach((listener) => listener(info));
<ide> this._resetData();
<ide> }
<ide>
<ide><path>Libraries/Lists/FlatList.js
<ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> {
<ide> this._checkProps(this.props);
<ide> if (this.props.viewabilityConfigCallbackPairs) {
<ide> this._virtualizedListPairs = this.props.viewabilityConfigCallbackPairs.map(
<del> pair => ({
<add> (pair) => ({
<ide> viewabilityConfig: pair.viewabilityConfig,
<ide> onViewableItemsChanged: this._createOnViewableItemsChanged(
<ide> pair.onViewableItemsChanged,
<ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> {
<ide> _listRef: ?React.ElementRef<typeof VirtualizedList>;
<ide> _virtualizedListPairs: Array<ViewabilityConfigCallbackPair> = [];
<ide>
<del> _captureRef = ref => {
<add> _captureRef = (ref) => {
<ide> this._listRef = ref;
<ide> };
<ide>
<ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> {
<ide> if (numColumns > 1) {
<ide> const changed = [];
<ide> const viewableItems = [];
<del> info.viewableItems.forEach(v =>
<add> info.viewableItems.forEach((v) =>
<ide> this._pushMultiColumnViewable(viewableItems, v),
<ide> );
<del> info.changed.forEach(v => this._pushMultiColumnViewable(changed, v));
<add> info.changed.forEach((v) =>
<add> this._pushMultiColumnViewable(changed, v),
<add> );
<ide> onViewableItemsChanged({viewableItems, changed});
<ide> } else {
<ide> onViewableItemsChanged(info);
<ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> {
<ide> 'Expected array of items with numColumns > 1',
<ide> );
<ide> return (
<del> <View
<del> style={StyleSheet.compose(
<del> styles.row,
<del> columnWrapperStyle,
<del> )}>
<add> <View style={StyleSheet.compose(styles.row, columnWrapperStyle)}>
<ide> {item.map((it, kk) => {
<ide> const element = renderer({
<ide> item: it,
<ide><path>Libraries/Lists/SectionList.js
<ide> class SectionList<SectionT: SectionBase<any>> extends React.PureComponent<
<ide> <VirtualizedSectionList
<ide> {...this.props}
<ide> ref={this._captureRef}
<del> getItemCount={items => items.length}
<add> getItemCount={(items) => items.length}
<ide> getItem={(items, index) => items[index]}
<ide> />
<ide> );
<ide> }
<ide>
<ide> _wrapperListRef: ?React.ElementRef<typeof VirtualizedSectionList>;
<del> _captureRef = ref => {
<add> _captureRef = (ref) => {
<ide> /* $FlowFixMe(>=0.99.0 site=react_native_fb) This comment suppresses an
<ide> * error found when Flow v0.99 was deployed. To see the error, delete this
<ide> * comment and run Flow. */
<ide><path>Libraries/Lists/ViewabilityHelper.js
<ide> class ViewabilityHelper {
<ide> createViewToken,
<ide> ) {
<ide> // Filter out indices that have gone out of view since this call was scheduled.
<del> viewableIndicesToCheck = viewableIndicesToCheck.filter(ii =>
<add> viewableIndicesToCheck = viewableIndicesToCheck.filter((ii) =>
<ide> this._viewableIndices.includes(ii),
<ide> );
<ide> const prevItems = this._viewableItems;
<ide> const nextItems = new Map(
<del> viewableIndicesToCheck.map(ii => {
<add> viewableIndicesToCheck.map((ii) => {
<ide> const viewable = createViewToken(ii, true);
<ide> return [viewable.key, viewable];
<ide> }),
<ide><path>Libraries/Lists/VirtualizedList.js
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> const {animated, index, viewOffset, viewPosition} = params;
<ide> invariant(
<ide> index >= 0 && index < getItemCount(data),
<del> `scrollToIndex out of range: requested index ${index} but maximum is ${getItemCount(
<del> data,
<del> ) - 1}`,
<add> `scrollToIndex out of range: requested index ${index} but maximum is ${
<add> getItemCount(data) - 1
<add> }`,
<ide> );
<ide> if (!getItemLayout && index > this._highestMeasuredFrameIndex) {
<ide> invariant(
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> }
<ide>
<ide> recordInteraction() {
<del> this._nestedChildLists.forEach(childList => {
<add> this._nestedChildLists.forEach((childList) => {
<ide> childList.ref && childList.ref.recordInteraction();
<ide> });
<del> this._viewabilityTuples.forEach(t => {
<add> this._viewabilityTuples.forEach((t) => {
<ide> t.viewabilityHelper.recordInteraction();
<ide> });
<ide> this._updateViewableItems(this.props.data);
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> },
<ide> horizontal: ?boolean,
<ide> getOutermostParentListRef: Function,
<del> getNestedChildState: string => ?ChildListState,
<add> getNestedChildState: (string) => ?ChildListState,
<ide> registerAsNestedChild: ({
<ide> cellKey: string,
<ide> key: string,
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide>
<ide> if (this.props.viewabilityConfigCallbackPairs) {
<ide> this._viewabilityTuples = this.props.viewabilityConfigCallbackPairs.map(
<del> pair => ({
<add> (pair) => ({
<ide> viewabilityHelper: new ViewabilityHelper(pair.viewabilityConfig),
<ide> onViewableItemsChanged: pair.onViewableItemsChanged,
<ide> }),
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> }
<ide> this._updateViewableItems(null);
<ide> this._updateCellsToRenderBatcher.dispose({abort: true});
<del> this._viewabilityTuples.forEach(tuple => {
<add> this._viewabilityTuples.forEach((tuple) => {
<ide> tuple.viewabilityHelper.dispose();
<ide> });
<ide> this._fillRateHelper.deactivateAndFlush();
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> key={key}
<ide> prevCellKey={prevCellKey}
<ide> onUpdateSeparators={this._onUpdateSeparators}
<del> onLayout={e => this._onCellLayout(e, key, ii)}
<add> onLayout={(e) => this._onCellLayout(e, key, ii)}
<ide> onUnmount={this._onCellUnmount}
<ide> parentProps={this.props}
<del> ref={ref => {
<add> ref={(ref) => {
<ide> this._cellRefs[key] = ref;
<ide> }}
<ide> />,
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> }
<ide>
<ide> _onUpdateSeparators = (keys: Array<?string>, newProps: Object) => {
<del> keys.forEach(key => {
<add> keys.forEach((key) => {
<ide> const ref = key != null && this._cellRefs[key];
<ide> ref && ref.updateSeparatorProps(newProps);
<ide> });
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> cells.push(
<ide> React.cloneElement(element, {
<ide> key: '$empty',
<del> onLayout: event => {
<add> onLayout: (event) => {
<ide> this._onLayoutEmpty(event);
<ide> if (element.props.onLayout) {
<ide> element.props.onLayout(event);
<ide> }
<ide> },
<del> style: StyleSheet.compose(
<del> inversionStyle,
<del> element.props.style,
<del> ),
<add> style: StyleSheet.compose(inversionStyle, element.props.style),
<ide> }),
<ide> );
<ide> }
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> if (__DEV__) {
<ide> ret = (
<ide> <ScrollView.Context.Consumer>
<del> {scrollContext => {
<add> {(scrollContext) => {
<ide> if (
<ide> scrollContext != null &&
<ide> !scrollContext.horizontal === !this.props.horizontal &&
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide>
<ide> // clear the viewableIndices cache to also trigger
<ide> // the onViewableItemsChanged callback with the new data
<del> this._viewabilityTuples.forEach(tuple => {
<add> this._viewabilityTuples.forEach((tuple) => {
<ide> tuple.viewabilityHelper.resetViewableIndices();
<ide> });
<ide> }
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> _updateCellsToRenderBatcher: Batchinator;
<ide> _viewabilityTuples: Array<ViewabilityHelperCallbackTuple> = [];
<ide>
<del> _captureScrollRef = ref => {
<add> _captureScrollRef = (ref) => {
<ide> this._scrollRef = ref;
<ide> };
<ide>
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> );
<ide> }
<ide>
<del> _defaultRenderScrollComponent = props => {
<add> _defaultRenderScrollComponent = (props) => {
<ide> const onRefresh = props.onRefresh;
<ide> if (this._isNestedWithSameOrientation()) {
<ide> // $FlowFixMe - Typing ReactNativeComponent revealed errors
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> this._scrollMetrics.visibleLength = scrollMetrics.visibleLength;
<ide> this._scrollMetrics.offset = scrollMetrics.offset;
<ide> },
<del> error => {
<add> (error) => {
<ide> console.warn(
<ide> "VirtualizedList: Encountered an error while measuring a list's" +
<ide> ' offset from its containing VirtualizedList.',
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> this._maybeCallOnEndReached();
<ide> };
<ide>
<del> _onLayoutEmpty = e => {
<add> _onLayoutEmpty = (e) => {
<ide> this.props.onLayout && this.props.onLayout(e);
<ide> };
<ide>
<ide> _getFooterCellKey(): string {
<ide> return this._getCellKey() + '-footer';
<ide> }
<ide>
<del> _onLayoutFooter = e => {
<add> _onLayoutFooter = (e) => {
<ide> this._triggerRemeasureForChildListsInCell(this._getFooterCellKey());
<ide> this._footerLength = this._selectLength(e.nativeEvent.layout);
<ide> };
<ide>
<del> _onLayoutHeader = e => {
<add> _onLayoutHeader = (e) => {
<ide> this._headerLength = this._selectLength(e.nativeEvent.layout);
<ide> };
<ide>
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> };
<ide>
<ide> _onScroll = (e: Object) => {
<del> this._nestedChildLists.forEach(childList => {
<add> this._nestedChildLists.forEach((childList) => {
<ide> childList.ref && childList.ref._onScroll(e);
<ide> });
<ide> if (this.props.onScroll) {
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> }
<ide>
<ide> _onScrollBeginDrag = (e): void => {
<del> this._nestedChildLists.forEach(childList => {
<add> this._nestedChildLists.forEach((childList) => {
<ide> childList.ref && childList.ref._onScrollBeginDrag(e);
<ide> });
<del> this._viewabilityTuples.forEach(tuple => {
<add> this._viewabilityTuples.forEach((tuple) => {
<ide> tuple.viewabilityHelper.recordInteraction();
<ide> });
<ide> this._hasInteracted = true;
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> if (!data) {
<ide> return;
<ide> }
<del> this.setState(state => {
<add> this.setState((state) => {
<ide> let newState;
<ide> const {contentLength, offset, visibleLength} = this._scrollMetrics;
<ide> if (!isVirtualizationDisabled) {
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> _updateViewableItems(data: any) {
<ide> const {getItemCount} = this.props;
<ide>
<del> this._viewabilityTuples.forEach(tuple => {
<add> this._viewabilityTuples.forEach((tuple) => {
<ide> tuple.viewabilityHelper.onUpdate(
<ide> getItemCount(data),
<ide> this._scrollMetrics.offset,
<ide> class CellRenderer extends React.Component<
<ide> };
<ide>
<ide> updateSeparatorProps(newProps: Object) {
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> separatorProps: {...state.separatorProps, ...newProps},
<ide> }));
<ide> }
<ide><path>Libraries/Lists/VirtualizedSectionList.js
<ide> class VirtualizedSectionList<
<ide> leadingSection={info.leadingSection}
<ide> onUpdateSeparator={this._onUpdateSeparator}
<ide> prevCellKey={(this._subExtractor(index - 1) || {}).key}
<del> ref={ref => {
<add> ref={(ref) => {
<ide> this._cellRefs[info.key] = ref;
<ide> }}
<ide> renderItem={renderItem}
<ide> class VirtualizedSectionList<
<ide>
<ide> _cellRefs = {};
<ide> _listRef: VirtualizedList;
<del> _captureRef = ref => {
<add> _captureRef = (ref) => {
<ide> /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment
<ide> * suppresses an error when upgrading Flow's support for React. To see the
<ide> * error delete this comment and run Flow. */
<ide> class ItemWithSeparator extends React.Component<
<ide>
<ide> _separators = {
<ide> highlight: () => {
<del> ['leading', 'trailing'].forEach(s =>
<add> ['leading', 'trailing'].forEach((s) =>
<ide> this._separators.updateProps(s, {highlighted: true}),
<ide> );
<ide> },
<ide> unhighlight: () => {
<del> ['leading', 'trailing'].forEach(s =>
<add> ['leading', 'trailing'].forEach((s) =>
<ide> this._separators.updateProps(s, {highlighted: false}),
<ide> );
<ide> },
<ide> updateProps: (select: 'leading' | 'trailing', newProps: Object) => {
<ide> const {LeadingSeparatorComponent, cellKey, prevCellKey} = this.props;
<ide> if (select === 'leading' && LeadingSeparatorComponent != null) {
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> leadingSeparatorProps: {...state.leadingSeparatorProps, ...newProps},
<ide> }));
<ide> } else {
<ide> class ItemWithSeparator extends React.Component<
<ide> }
<ide>
<ide> updateSeparatorProps(newProps: Object) {
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> separatorProps: {...state.separatorProps, ...newProps},
<ide> }));
<ide> }
<ide><path>Libraries/Lists/__flowtests__/FlatList-flowtest.js
<ide> module.exports = {
<ide> ];
<ide> return (
<ide> <FlatList
<del> renderItem={info => (
<add> renderItem={(info) => (
<ide> <span>
<ide> {
<ide> // $FlowExpectedError - bad widgetCount type 6, should be Object
<ide><path>Libraries/Lists/__tests__/FillRateHelper-test.js
<ide> function computeResult({helper, props, state, scroll}): number {
<ide> return helper.computeBlankness(
<ide> {
<ide> data: dataGlobal,
<del> getItemCount: data2 => data2.length,
<add> getItemCount: (data2) => data2.length,
<ide> initialNumToRender: 10,
<ide> ...(props || {}),
<ide> },
<ide> function computeResult({helper, props, state, scroll}): number {
<ide> );
<ide> }
<ide>
<del>describe('computeBlankness', function() {
<add>describe('computeBlankness', function () {
<ide> beforeEach(() => {
<ide> FillRateHelper.setSampleRate(1);
<ide> FillRateHelper.setMinSampleCount(0);
<ide> });
<ide>
<del> it('computes correct blankness of viewport', function() {
<add> it('computes correct blankness of viewport', function () {
<ide> const helper = new FillRateHelper(getFrameMetrics);
<ide> rowFramesGlobal = {
<ide> header: {y: 0, height: 0, inLayout: true},
<ide> describe('computeBlankness', function() {
<ide> expect(blankness).toBe(1);
<ide> });
<ide>
<del> it('skips frames that are not in layout', function() {
<add> it('skips frames that are not in layout', function () {
<ide> const helper = new FillRateHelper(getFrameMetrics);
<ide> rowFramesGlobal = {
<ide> header: {y: 0, height: 0, inLayout: false},
<ide> describe('computeBlankness', function() {
<ide> expect(blankness).toBe(0.3);
<ide> });
<ide>
<del> it('sampling rate can disable', function() {
<add> it('sampling rate can disable', function () {
<ide> let helper = new FillRateHelper(getFrameMetrics);
<ide> rowFramesGlobal = {
<ide> header: {y: 0, height: 0, inLayout: true},
<ide> describe('computeBlankness', function() {
<ide> expect(blankness).toBe(0);
<ide> });
<ide>
<del> it('can handle multiple listeners and unsubscribe', function() {
<add> it('can handle multiple listeners and unsubscribe', function () {
<ide> const listeners = [jest.fn(), jest.fn(), jest.fn()];
<del> const subscriptions = listeners.map(listener =>
<add> const subscriptions = listeners.map((listener) =>
<ide> FillRateHelper.addListener(listener),
<ide> );
<ide> subscriptions[1].remove();
<ide><path>Libraries/Lists/__tests__/FlatList-test.js
<ide> describe('FlatList', () => {
<ide> ReactTestRenderer.create(
<ide> <FlatList
<ide> data={[{key: 'outer0'}, {key: 'outer1'}]}
<del> renderItem={outerInfo => (
<add> renderItem={(outerInfo) => (
<ide> <FlatList
<ide> data={[
<ide> {key: outerInfo.item.key + ':inner0'},
<ide> {key: outerInfo.item.key + ':inner1'},
<ide> ]}
<del> renderItem={innerInfo => {
<add> renderItem={(innerInfo) => {
<ide> return <item title={innerInfo.item.key} />;
<ide> }}
<ide> ref={listRef}
<ide><path>Libraries/Lists/__tests__/SectionList-test.js
<ide> describe('SectionList', () => {
<ide> const component = ReactTestRenderer.create(
<ide> <SectionList
<ide> initialNumToRender={Infinity}
<del> ItemSeparatorComponent={props => (
<add> ItemSeparatorComponent={(props) => (
<ide> <defaultItemSeparator v={propStr(props)} />
<ide> )}
<del> ListEmptyComponent={props => <empty v={propStr(props)} />}
<del> ListFooterComponent={props => <footer v={propStr(props)} />}
<del> ListHeaderComponent={props => <header v={propStr(props)} />}
<del> SectionSeparatorComponent={props => (
<add> ListEmptyComponent={(props) => <empty v={propStr(props)} />}
<add> ListFooterComponent={(props) => <footer v={propStr(props)} />}
<add> ListHeaderComponent={(props) => <header v={propStr(props)} />}
<add> SectionSeparatorComponent={(props) => (
<ide> <sectionSeparator v={propStr(props)} />
<ide> )}
<ide> sections={[
<ide> {
<del> renderItem: props => <itemForSection1 v={propStr(props)} />,
<add> renderItem: (props) => <itemForSection1 v={propStr(props)} />,
<ide> key: 's1',
<ide> keyExtractor: (item, index) => item.id,
<del> ItemSeparatorComponent: props => (
<add> ItemSeparatorComponent: (props) => (
<ide> <itemSeparatorForSection1 v={propStr(props)} />
<ide> ),
<ide> data: [{id: 'i1s1'}, {id: 'i2s1'}],
<ide> describe('SectionList', () => {
<ide> ]}
<ide> refreshing={false}
<ide> onRefresh={jest.fn()}
<del> renderItem={props => <defaultItem v={propStr(props)} />}
<del> renderSectionHeader={props => <sectionHeader v={propStr(props)} />}
<del> renderSectionFooter={props => <sectionFooter v={propStr(props)} />}
<add> renderItem={(props) => <defaultItem v={propStr(props)} />}
<add> renderSectionHeader={(props) => <sectionHeader v={propStr(props)} />}
<add> renderSectionFooter={(props) => <sectionFooter v={propStr(props)} />}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('SectionList', () => {
<ide> <SectionList
<ide> sections={[{key: 's1', data: []}]}
<ide> renderItem={({item}) => <item v={item.key} />}
<del> renderSectionHeader={props => <sectionHeader v={propStr(props)} />}
<del> renderSectionFooter={props => <sectionFooter v={propStr(props)} />}
<add> renderSectionHeader={(props) => <sectionHeader v={propStr(props)} />}
<add> renderSectionFooter={(props) => <sectionFooter v={propStr(props)} />}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('SectionList', () => {
<ide> <SectionList
<ide> sections={[{key: 's1', data: []}]}
<ide> renderItem={({item}) => <item v={item.key} />}
<del> renderSectionFooter={props => <sectionFooter v={propStr(props)} />}
<add> renderSectionFooter={(props) => <sectionFooter v={propStr(props)} />}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('SectionList', () => {
<ide>
<ide> function propStr(props) {
<ide> return Object.keys(props)
<del> .map(k => {
<add> .map((k) => {
<ide> const propObj = props[k] || {};
<ide> return `${k}:${propObj.key || propObj.id || props[k]}`;
<ide> })
<ide><path>Libraries/Lists/__tests__/ViewabilityHelper-test.js
<ide> function createViewToken(index: number, isViewable: boolean) {
<ide> return {key: data[index].key, isViewable};
<ide> }
<ide>
<del>describe('computeViewableItems', function() {
<del> it('returns all 4 entirely visible rows as viewable', function() {
<add>describe('computeViewableItems', function () {
<add> it('returns all 4 entirely visible rows as viewable', function () {
<ide> const helper = new ViewabilityHelper({
<ide> viewAreaCoveragePercentThreshold: 50,
<ide> });
<ide> describe('computeViewableItems', function() {
<ide> ).toEqual([0, 1, 2, 3]);
<ide> });
<ide>
<del> it('returns top 2 rows as viewable (1. entirely visible and 2. majority)', function() {
<add> it('returns top 2 rows as viewable (1. entirely visible and 2. majority)', function () {
<ide> const helper = new ViewabilityHelper({
<ide> viewAreaCoveragePercentThreshold: 50,
<ide> });
<ide> describe('computeViewableItems', function() {
<ide> ).toEqual([0, 1]);
<ide> });
<ide>
<del> it('returns only 2nd row as viewable (majority)', function() {
<add> it('returns only 2nd row as viewable (majority)', function () {
<ide> const helper = new ViewabilityHelper({
<ide> viewAreaCoveragePercentThreshold: 50,
<ide> });
<ide> describe('computeViewableItems', function() {
<ide> ).toEqual([1]);
<ide> });
<ide>
<del> it('handles empty input', function() {
<add> it('handles empty input', function () {
<ide> const helper = new ViewabilityHelper({
<ide> viewAreaCoveragePercentThreshold: 50,
<ide> });
<ide> describe('computeViewableItems', function() {
<ide> ).toEqual([]);
<ide> });
<ide>
<del> it('handles different view area coverage percent thresholds', function() {
<add> it('handles different view area coverage percent thresholds', function () {
<ide> rowFrames = {
<ide> a: {y: 0, height: 50},
<ide> b: {y: 50, height: 150},
<ide> describe('computeViewableItems', function() {
<ide> ).toEqual([1, 2]);
<ide> });
<ide>
<del> it('handles different item visible percent thresholds', function() {
<add> it('handles different item visible percent thresholds', function () {
<ide> rowFrames = {
<ide> a: {y: 0, height: 50},
<ide> b: {y: 50, height: 150},
<ide> describe('computeViewableItems', function() {
<ide> });
<ide> });
<ide>
<del>describe('onUpdate', function() {
<del> it('returns 1 visible row as viewable then scrolls away', function() {
<add>describe('onUpdate', function () {
<add> it('returns 1 visible row as viewable then scrolls away', function () {
<ide> const helper = new ViewabilityHelper();
<ide> rowFrames = {
<ide> a: {y: 0, height: 50},
<ide> describe('onUpdate', function() {
<ide> });
<ide> });
<ide>
<del> it('returns 1st visible row then 1st and 2nd then just 2nd', function() {
<add> it('returns 1st visible row then 1st and 2nd then just 2nd', function () {
<ide> const helper = new ViewabilityHelper();
<ide> rowFrames = {
<ide> a: {y: 0, height: 200},
<ide> describe('onUpdate', function() {
<ide> });
<ide> });
<ide>
<del> it('minimumViewTime delays callback', function() {
<add> it('minimumViewTime delays callback', function () {
<ide> const helper = new ViewabilityHelper({
<ide> minimumViewTime: 350,
<ide> viewAreaCoveragePercentThreshold: 0,
<ide> describe('onUpdate', function() {
<ide> });
<ide> });
<ide>
<del> it('minimumViewTime skips briefly visible items', function() {
<add> it('minimumViewTime skips briefly visible items', function () {
<ide> const helper = new ViewabilityHelper({
<ide> minimumViewTime: 350,
<ide> viewAreaCoveragePercentThreshold: 0,
<ide> describe('onUpdate', function() {
<ide> });
<ide> });
<ide>
<del> it('waitForInteraction blocks callback until interaction', function() {
<add> it('waitForInteraction blocks callback until interaction', function () {
<ide> const helper = new ViewabilityHelper({
<ide> waitForInteraction: true,
<ide> viewAreaCoveragePercentThreshold: 0,
<ide> describe('onUpdate', function() {
<ide> });
<ide> });
<ide>
<del> it('returns the right visible row after the underlying data changed', function() {
<add> it('returns the right visible row after the underlying data changed', function () {
<ide> const helper = new ViewabilityHelper();
<ide> rowFrames = {
<ide> a: {y: 0, height: 200},
<ide> describe('onUpdate', function() {
<ide>
<ide> expect(onViewableItemsChanged.mock.calls.length).toBe(2);
<ide> expect(onViewableItemsChanged.mock.calls[1][0]).toEqual({
<del> changed: [{isViewable: true, key: 'c'}, {isViewable: false, key: 'a'}],
<add> changed: [
<add> {isViewable: true, key: 'c'},
<add> {isViewable: false, key: 'a'},
<add> ],
<ide> viewabilityConfig: {viewAreaCoveragePercentThreshold: 0},
<ide> viewableItems: [{isViewable: true, key: 'c'}],
<ide> });
<ide><path>Libraries/Lists/__tests__/VirtualizeUtils-test.js
<ide> const {
<ide> newRangeCount,
<ide> } = require('../VirtualizeUtils');
<ide>
<del>describe('newRangeCount', function() {
<del> it('handles subset', function() {
<add>describe('newRangeCount', function () {
<add> it('handles subset', function () {
<ide> expect(newRangeCount({first: 1, last: 4}, {first: 2, last: 3})).toBe(0);
<ide> });
<del> it('handles forward disjoint set', function() {
<add> it('handles forward disjoint set', function () {
<ide> expect(newRangeCount({first: 1, last: 4}, {first: 6, last: 9})).toBe(4);
<ide> });
<del> it('handles reverse disjoint set', function() {
<add> it('handles reverse disjoint set', function () {
<ide> expect(newRangeCount({first: 6, last: 8}, {first: 1, last: 4})).toBe(4);
<ide> });
<del> it('handles superset', function() {
<add> it('handles superset', function () {
<ide> expect(newRangeCount({first: 1, last: 4}, {first: 0, last: 5})).toBe(2);
<ide> });
<del> it('handles end extension', function() {
<add> it('handles end extension', function () {
<ide> expect(newRangeCount({first: 1, last: 4}, {first: 1, last: 8})).toBe(4);
<ide> });
<del> it('handles front extension', function() {
<add> it('handles front extension', function () {
<ide> expect(newRangeCount({first: 1, last: 4}, {first: 0, last: 4})).toBe(1);
<ide> });
<del> it('handles forward intersect', function() {
<add> it('handles forward intersect', function () {
<ide> expect(newRangeCount({first: 1, last: 4}, {first: 3, last: 6})).toBe(2);
<ide> });
<del> it('handles reverse intersect', function() {
<add> it('handles reverse intersect', function () {
<ide> expect(newRangeCount({first: 3, last: 6}, {first: 1, last: 4})).toBe(2);
<ide> });
<ide> });
<ide>
<del>describe('elementsThatOverlapOffsets', function() {
<del> it('handles fixed length', function() {
<add>describe('elementsThatOverlapOffsets', function () {
<add> it('handles fixed length', function () {
<ide> const offsets = [0, 250, 350, 450];
<ide> function getFrameMetrics(index: number) {
<ide> return {
<ide> describe('elementsThatOverlapOffsets', function() {
<ide> 4,
<ide> ]);
<ide> });
<del> it('handles variable length', function() {
<add> it('handles variable length', function () {
<ide> const offsets = [150, 250, 900];
<ide> const frames = [
<ide> {offset: 0, length: 50},
<ide> describe('elementsThatOverlapOffsets', function() {
<ide> {offset: 950, length: 150},
<ide> ];
<ide> expect(
<del> elementsThatOverlapOffsets(offsets, frames.length, ii => frames[ii]),
<add> elementsThatOverlapOffsets(offsets, frames.length, (ii) => frames[ii]),
<ide> ).toEqual([1, 1, 3]);
<ide> });
<del> it('handles out of bounds', function() {
<add> it('handles out of bounds', function () {
<ide> const offsets = [150, 900];
<ide> const frames = [
<ide> {offset: 0, length: 50},
<ide> {offset: 50, length: 150},
<ide> {offset: 250, length: 100},
<ide> ];
<ide> expect(
<del> elementsThatOverlapOffsets(offsets, frames.length, ii => frames[ii]),
<add> elementsThatOverlapOffsets(offsets, frames.length, (ii) => frames[ii]),
<ide> ).toEqual([1]);
<ide> });
<del> it('errors on non-increasing offsets', function() {
<add> it('errors on non-increasing offsets', function () {
<ide> const offsets = [150, 50];
<ide> const frames = [
<ide> {offset: 0, length: 50},
<ide> {offset: 50, length: 150},
<ide> {offset: 250, length: 100},
<ide> ];
<ide> expect(() => {
<del> elementsThatOverlapOffsets(offsets, frames.length, ii => frames[ii]);
<add> elementsThatOverlapOffsets(offsets, frames.length, (ii) => frames[ii]);
<ide> }).toThrowErrorMatchingSnapshot();
<ide> });
<ide> });
<ide><path>Libraries/Lists/__tests__/VirtualizedList-test.js
<ide> describe('VirtualizedList', () => {
<ide> data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('VirtualizedList', () => {
<ide> data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]}
<ide> ListItemComponent={ListItemComponent}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('VirtualizedList', () => {
<ide> <item value={item.key} testID={`${item.key}-renderItem`} />
<ide> )}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide>
<ide> describe('VirtualizedList', () => {
<ide> it('throws if no renderItem or ListItemComponent', () => {
<ide> // Silence the React error boundary warning; we expect an uncaught error.
<ide> const consoleError = console.error;
<del> jest.spyOn(console, 'error').mockImplementation(message => {
<add> jest.spyOn(console, 'error').mockImplementation((message) => {
<ide> if (message.startsWith('The above error occured in the ')) {
<ide> return;
<ide> }
<ide> describe('VirtualizedList', () => {
<ide> <VirtualizedList
<ide> data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide> expect(componentFactory).toThrow(
<ide> describe('VirtualizedList', () => {
<ide> data={[]}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('VirtualizedList', () => {
<ide> data={undefined}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => 0}
<add> getItemCount={(data) => 0}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('VirtualizedList', () => {
<ide> ListFooterComponent={() => <footer />}
<ide> ListHeaderComponent={() => <header />}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> />,
<ide> );
<ide> describe('VirtualizedList', () => {
<ide> data={[{key: 'hello'}]}
<ide> ListEmptyComponent={() => <empty />}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> />,
<ide> );
<ide> describe('VirtualizedList', () => {
<ide> ListHeaderComponent={() => <header />}
<ide> data={new Array(5).fill().map((_, ii) => ({id: String(ii)}))}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> getItemLayout={({index}) => ({length: 50, offset: index * 50})}
<ide> inverted={true}
<ide> keyExtractor={(item, index) => item.id}
<ide> describe('VirtualizedList', () => {
<ide> const infos = [];
<ide> const component = ReactTestRenderer.create(
<ide> <VirtualizedList
<del> ItemSeparatorComponent={props => <separator {...props} />}
<add> ItemSeparatorComponent={(props) => <separator {...props} />}
<ide> data={[{key: 'i0'}, {key: 'i1'}, {key: 'i2'}]}
<del> renderItem={info => {
<add> renderItem={(info) => {
<ide> infos.push(info);
<ide> return <item title={info.item.key} />;
<ide> }}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('VirtualizedList', () => {
<ide> const component = ReactTestRenderer.create(
<ide> <VirtualizedList
<ide> data={[{key: 'outer0'}, {key: 'outer1'}]}
<del> renderItem={outerInfo => (
<add> renderItem={(outerInfo) => (
<ide> <VirtualizedList
<ide> data={[
<ide> {key: outerInfo.item.key + ':inner0'},
<ide> {key: outerInfo.item.key + ':inner1'},
<ide> ]}
<ide> horizontal={outerInfo.item.key === 'outer1'}
<del> renderItem={innerInfo => {
<add> renderItem={(innerInfo) => {
<ide> return <item title={innerInfo.item.key} />;
<ide> }}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />
<ide> )}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('VirtualizedList', () => {
<ide> data,
<ide> renderItem: ({item}) => <item value={item.key} />,
<ide> getItem: (items, index) => items[index],
<del> getItemCount: items => items.length,
<add> getItemCount: (items) => items.length,
<ide> getItemLayout: (items, index) => ({
<ide> length: ITEM_HEIGHT,
<ide> offset: ITEM_HEIGHT * index,
<ide> describe('VirtualizedList', () => {
<ide> data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> ref={listRef}
<ide> />,
<ide> );
<ide> describe('VirtualizedList', () => {
<ide> ReactTestRenderer.create(
<ide> <VirtualizedList
<ide> data={[{key: 'outer0'}, {key: 'outer1'}]}
<del> renderItem={outerInfo => (
<add> renderItem={(outerInfo) => (
<ide> <VirtualizedList
<ide> data={[
<ide> {key: outerInfo.item.key + ':inner0'},
<ide> {key: outerInfo.item.key + ':inner1'},
<ide> ]}
<del> renderItem={innerInfo => {
<add> renderItem={(innerInfo) => {
<ide> return <item title={innerInfo.item.key} />;
<ide> }}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> ref={listRef}
<ide> />
<ide> )}
<ide> getItem={(data, index) => data[index]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide> const scrollRef = listRef.current.getScrollRef();
<ide> describe('VirtualizedList', () => {
<ide> windowSize: 21,
<ide> renderItem: ({item}) => <item value={item.key} />,
<ide> getItem: (items, index) => items[index],
<del> getItemCount: items => items.length,
<add> getItemCount: (items) => items.length,
<ide> getItemLayout: (items, index) => ({
<ide> length: ITEM_HEIGHT,
<ide> offset: ITEM_HEIGHT * index,
<ide> describe('VirtualizedList', () => {
<ide> const commonProps = {
<ide> data: [{key: 'cell0'}],
<ide> getItem: (data, index) => data[index],
<del> getItemCount: data => data.length,
<add> getItemCount: (data) => data.length,
<ide> renderItem: ({item}) => <item value={item.key} />,
<ide> };
<ide> try {
<ide><path>Libraries/Lists/__tests__/VirtualizedSectionList-test.js
<ide> describe('VirtualizedSectionList', () => {
<ide> ]}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> getItem={(data, key) => data[key]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('VirtualizedSectionList', () => {
<ide> sections={[]}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> getItem={(data, key) => data[key]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('VirtualizedSectionList', () => {
<ide> sections={undefined}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> getItem={(data, key) => data[key]}
<del> getItemCount={data => 0}
<add> getItemCount={(data) => 0}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('VirtualizedSectionList', () => {
<ide> ListFooterComponent={() => <footer />}
<ide> ListHeaderComponent={() => <header />}
<ide> getItem={(data, key) => data[key]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> />,
<ide> );
<ide> describe('VirtualizedSectionList', () => {
<ide> sections={[{title: 's1', data: [{key: 'hello'}]}]}
<ide> ListEmptyComponent={() => <empty />}
<ide> getItem={(data, key) => data[key]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> />,
<ide> );
<ide> describe('VirtualizedSectionList', () => {
<ide> },
<ide> ]}
<ide> getItem={(data, key) => data[key]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> getItemLayout={({index}) => ({length: 50, offset: index * 50})}
<ide> inverted={true}
<ide> keyExtractor={(item, index) => item.id}
<ide> describe('VirtualizedSectionList', () => {
<ide> const infos = [];
<ide> const component = ReactTestRenderer.create(
<ide> <VirtualizedSectionList
<del> ItemSeparatorComponent={props => <separator {...props} />}
<add> ItemSeparatorComponent={(props) => <separator {...props} />}
<ide> sections={[
<ide> {title: 's0', data: [{key: 'i0'}, {key: 'i1'}, {key: 'i2'}]},
<ide> ]}
<del> renderItem={info => {
<add> renderItem={(info) => {
<ide> infos.push(info);
<ide> return <item title={info.item.key} />;
<ide> }}
<ide> getItem={(data, key) => data[key]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('VirtualizedSectionList', () => {
<ide> const component = ReactTestRenderer.create(
<ide> <VirtualizedSectionList
<ide> sections={[{title: 'outer', data: [{key: 'outer0'}, {key: 'outer1'}]}]}
<del> renderItem={outerInfo => (
<add> renderItem={(outerInfo) => (
<ide> <VirtualizedSectionList
<ide> sections={[
<ide> {
<ide> describe('VirtualizedSectionList', () => {
<ide> },
<ide> ]}
<ide> horizontal={outerInfo.item.key === 'outer1'}
<del> renderItem={innerInfo => {
<add> renderItem={(innerInfo) => {
<ide> return <item title={innerInfo.item.key} />;
<ide> }}
<ide> getItem={(data, key) => data[key]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />
<ide> )}
<ide> getItem={(data, key) => data[key]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> />,
<ide> );
<ide> expect(component).toMatchSnapshot();
<ide> describe('VirtualizedSectionList', () => {
<ide> describe('scrollToLocation', () => {
<ide> const ITEM_HEIGHT = 100;
<ide>
<del> const createVirtualizedSectionList = props => {
<add> const createVirtualizedSectionList = (props) => {
<ide> const component = ReactTestRenderer.create(
<ide> <VirtualizedSectionList
<ide> sections={[
<ide> describe('VirtualizedSectionList', () => {
<ide> ]}
<ide> renderItem={({item}) => <item value={item.key} />}
<ide> getItem={(data, key) => data[key]}
<del> getItemCount={data => data.length}
<add> getItemCount={(data) => data.length}
<ide> getItemLayout={(data, index) => ({
<ide> length: ITEM_HEIGHT,
<ide> offset: ITEM_HEIGHT * index,
<ide><path>Libraries/LogBox/Data/LogBoxData.js
<ide> let updateTimeout = null;
<ide> let _isDisabled = false;
<ide> let _selectedIndex = -1;
<ide>
<del>let warningFilter: WarningFilter = function(format) {
<add>let warningFilter: WarningFilter = function (format) {
<ide> return {
<ide> finalFormat: format,
<ide> forceDialogImmediately: false,
<ide> function appendNewLog(newLog) {
<ide> }
<ide> }, OPTIMISTIC_WAIT_TIME);
<ide>
<del> newLog.symbolicate(status => {
<add> newLog.symbolicate((status) => {
<ide> if (addPendingLog && status !== 'PENDING') {
<ide> addPendingLog();
<ide> clearTimeout(optimisticTimeout);
<ide> export function setSelectedLog(proposedNewIndex: number): void {
<ide> }
<ide>
<ide> export function clearWarnings(): void {
<del> const newLogs = Array.from(logs).filter(log => log.level !== 'warn');
<add> const newLogs = Array.from(logs).filter((log) => log.level !== 'warn');
<ide> if (newLogs.length !== logs.size) {
<ide> logs = new Set(newLogs);
<ide> setSelectedLog(-1);
<ide> export function clearWarnings(): void {
<ide>
<ide> export function clearErrors(): void {
<ide> const newLogs = Array.from(logs).filter(
<del> log => log.level !== 'error' && log.level !== 'fatal',
<add> (log) => log.level !== 'error' && log.level !== 'fatal',
<ide> );
<ide> if (newLogs.length !== logs.size) {
<ide> logs = new Set(newLogs);
<ide> export function addIgnorePatterns(
<ide> // Without this, if you ignore a pattern after the a log is created,
<ide> // then we would keep showing the log.
<ide> logs = new Set(
<del> Array.from(logs).filter(log => !isMessageIgnored(log.message.content)),
<add> Array.from(logs).filter((log) => !isMessageIgnored(log.message.content)),
<ide> );
<ide> }
<ide> handleUpdate();
<ide> export function withSubscription(
<ide> }
<ide>
<ide> componentDidMount(): void {
<del> this._subscription = observe(data => {
<add> this._subscription = observe((data) => {
<ide> this.setState(data);
<ide> });
<ide> }
<ide><path>Libraries/LogBox/Data/LogBoxLog.js
<ide> class LogBoxLog {
<ide> if (this.symbolicated.status !== 'PENDING') {
<ide> this.updateStatus(null, null, null, callback);
<ide> LogBoxSymbolication.symbolicate(this.stack).then(
<del> data => {
<add> (data) => {
<ide> this.updateStatus(null, data?.stack, data?.codeFrame, callback);
<ide> },
<del> error => {
<add> (error) => {
<ide> this.updateStatus(error, null, null, callback);
<ide> },
<ide> );
<ide><path>Libraries/LogBox/Data/__tests__/LogBoxData-test.js
<ide> const observe = () => {
<ide> };
<ide> };
<ide>
<del>const addLogs = logs => {
<del> logs.forEach(message => {
<add>const addLogs = (logs) => {
<add> logs.forEach((message) => {
<ide> LogBoxData.addLog({
<ide> level: 'warn',
<ide> message: {
<ide> const addLogs = logs => {
<ide> });
<ide> };
<ide>
<del>const addSoftErrors = errors => {
<del> errors.forEach(error => {
<add>const addSoftErrors = (errors) => {
<add> errors.forEach((error) => {
<ide> LogBoxData.addException(
<ide> Object.assign(
<ide> {},
<ide> const addSoftErrors = errors => {
<ide> });
<ide> };
<ide>
<del>const addFatalErrors = errors => {
<del> errors.forEach(error => {
<add>const addFatalErrors = (errors) => {
<add> errors.forEach((error) => {
<ide> LogBoxData.addException(
<ide> Object.assign(
<ide> {},
<ide><path>Libraries/LogBox/Data/__tests__/LogBoxLog-test.js
<ide> jest.mock('../LogBoxSymbolication', () => {
<ide> });
<ide>
<ide> function getLogBoxLog() {
<del> return new (require('../LogBoxLog')).default({
<add> return new (require('../LogBoxLog').default)({
<ide> level: 'warn',
<ide> isComponentError: false,
<ide> message: {content: '...', substitutions: []},
<ide> function getLogBoxSymbolication(): {|
<ide> return (require('../LogBoxSymbolication'): any);
<ide> }
<ide>
<del>const createStack = methodNames =>
<del> methodNames.map(methodName => ({
<add>const createStack = (methodNames) =>
<add> methodNames.map((methodName) => ({
<ide> column: null,
<ide> file: 'file://path/to/file.js',
<ide> lineNumber: 1,
<ide> describe('LogBoxLog', () => {
<ide> beforeEach(() => {
<ide> jest.resetModules();
<ide>
<del> getLogBoxSymbolication().symbolicate.mockImplementation(async stack => ({
<del> stack: createStack(stack.map(frame => `S(${frame.methodName})`)),
<add> getLogBoxSymbolication().symbolicate.mockImplementation(async (stack) => ({
<add> stack: createStack(stack.map((frame) => `S(${frame.methodName})`)),
<ide> codeFrame: null,
<ide> }));
<ide> });
<ide> describe('LogBoxLog', () => {
<ide>
<ide> it('updates when symbolication fails', () => {
<ide> const error = new Error('...');
<del> getLogBoxSymbolication().symbolicate.mockImplementation(async stack => {
<add> getLogBoxSymbolication().symbolicate.mockImplementation(async (stack) => {
<ide> throw error;
<ide> });
<ide>
<ide> describe('LogBoxLog', () => {
<ide>
<ide> it('retry updates when symbolication fails', () => {
<ide> const error = new Error('...');
<del> getLogBoxSymbolication().symbolicate.mockImplementation(async stack => {
<add> getLogBoxSymbolication().symbolicate.mockImplementation(async (stack) => {
<ide> throw error;
<ide> });
<ide>
<ide> describe('LogBoxLog', () => {
<ide> // Retry to symbolicate again.
<ide> callback.mockClear();
<ide> getLogBoxSymbolication().symbolicate.mockClear();
<del> getLogBoxSymbolication().symbolicate.mockImplementation(async stack => ({
<del> stack: createStack(stack.map(frame => `S(${frame.methodName})`)),
<add> getLogBoxSymbolication().symbolicate.mockImplementation(async (stack) => ({
<add> stack: createStack(stack.map((frame) => `S(${frame.methodName})`)),
<ide> codeFrame: null,
<ide> }));
<ide>
<ide><path>Libraries/LogBox/Data/__tests__/LogBoxSymbolication-test.js
<ide> const symbolicateStackTrace: JestMockFn<
<ide> Promise<Array<StackFrame>>,
<ide> > = (require('../../../Core/Devtools/symbolicateStackTrace'): any);
<ide>
<del>const createStack = methodNames =>
<del> methodNames.map(methodName => ({
<add>const createStack = (methodNames) =>
<add> methodNames.map((methodName) => ({
<ide> column: null,
<ide> file: 'file://path/to/file.js',
<ide> lineNumber: 1,
<ide> const createStack = methodNames =>
<ide> describe('LogBoxSymbolication', () => {
<ide> beforeEach(() => {
<ide> jest.resetModules();
<del> symbolicateStackTrace.mockImplementation(async stack => stack);
<add> symbolicateStackTrace.mockImplementation(async (stack) => stack);
<ide> });
<ide>
<ide> it('symbolicates different stacks', () => {
<ide><path>Libraries/LogBox/Data/parseLogBoxLog.js
<ide> export function parseInterpolation(
<ide> contentParts.push(contentString);
<ide> }
<ide>
<del> const remainingArgs = remaining.map(arg => {
<add> const remainingArgs = remaining.map((arg) => {
<ide> // Don't stringify a string type.
<ide> // It adds quotation mark wrappers around the string,
<ide> // which causes the LogBox to look odd.
<ide> export function parseInterpolation(
<ide> export function parseComponentStack(message: string): ComponentStack {
<ide> return message
<ide> .split(/\n {4}in /g)
<del> .map(s => {
<add> .map((s) => {
<ide> if (!s) {
<ide> return null;
<ide> }
<ide><path>Libraries/LogBox/LogBox.js
<ide> if (__DEV__) {
<ide> let errorImpl = error.bind(console);
<ide> let warnImpl = warn.bind(console);
<ide>
<del> (console: any).error = function(...args) {
<add> (console: any).error = function (...args) {
<ide> errorImpl(...args);
<ide> };
<del> (console: any).warn = function(...args) {
<add> (console: any).warn = function (...args) {
<ide> warnImpl(...args);
<ide> };
<ide>
<ide> if (__DEV__) {
<ide> // Trigger lazy initialization of module.
<ide> require('../NativeModules/specs/NativeLogBox');
<ide>
<del> errorImpl = function(...args) {
<add> errorImpl = function (...args) {
<ide> registerError(...args);
<ide> };
<ide>
<del> warnImpl = function(...args) {
<add> warnImpl = function (...args) {
<ide> registerWarning(...args);
<ide> };
<ide>
<ide> if (__DEV__) {
<ide> (Object.defineProperty: any)(console, 'disableYellowBox', {
<ide> configurable: true,
<ide> get: () => LogBoxData.isDisabled(),
<del> set: value => {
<add> set: (value) => {
<ide> LogBoxData.setDisabled(value);
<ide> console.warn(
<ide> 'console.disableYellowBox has been deprecated and will be removed in a future release. Please use LogBox.ignoreAllLogs(value) instead.',
<ide><path>Libraries/LogBox/LogBoxNotificationContainer.js
<ide> export function _LogBoxNotificationContainer(props: Props): React.Node {
<ide> return null;
<ide> }
<ide>
<del> const warnings = logs.filter(log => log.level === 'warn');
<add> const warnings = logs.filter((log) => log.level === 'warn');
<ide> const errors = logs.filter(
<del> log => log.level === 'error' || log.level === 'fatal',
<add> (log) => log.level === 'error' || log.level === 'fatal',
<ide> );
<ide> return (
<ide> <View style={styles.list}>
<ide><path>Libraries/LogBox/UI/AnsiHighlight.js
<ide> export default function Ansi({
<ide> ...
<ide> }): React.Node {
<ide> let commonWhitespaceLength = Infinity;
<del> const parsedLines = text.split(/\n/).map(line =>
<add> const parsedLines = text.split(/\n/).map((line) =>
<ide> ansiToJson(line, {
<ide> json: true,
<ide> remove_empty: true,
<ide> use_classes: true,
<ide> }),
<ide> );
<ide>
<del> parsedLines.map(lines => {
<add> parsedLines.map((lines) => {
<ide> // The third item on each line includes the whitespace of the source code.
<ide> // We are looking for the least amount of common whitespace to trim all lines.
<ide> // Example: Array [" ", " 96 |", " text", ...]
<ide><path>Libraries/LogBox/UI/LogBoxMessage.js
<ide> type Props = {
<ide> ...
<ide> };
<ide>
<del>const cleanContent = content =>
<add>const cleanContent = (content) =>
<ide> content.replace(/^(TransformError |Warning: (Warning: )?|Error: )/g, '');
<ide>
<ide> function LogBoxMessage(props: Props): React.Node {
<ide><path>Libraries/LogBox/UI/__tests__/LogBoxInspectorStackFrames-test.js
<ide> const {} = require('../LogBoxInspectorStackFrames');
<ide> const LogBoxLog = require('../../Data/LogBoxLog').default;
<ide> const render = require('../../../../jest/renderer');
<ide>
<del>const createLogWithFrames = collapsedOptions => {
<add>const createLogWithFrames = (collapsedOptions) => {
<ide> return new LogBoxLog({
<ide> level: 'warn',
<ide> isComponentError: false,
<ide> const createLogWithFrames = collapsedOptions => {
<ide> });
<ide> };
<ide>
<del>const createCollapsedFrames = collapsedOptions => {
<del> return collapsedOptions.map(option => ({
<add>const createCollapsedFrames = (collapsedOptions) => {
<add> return collapsedOptions.map((option) => ({
<ide> column: 1,
<ide> file: 'dependency.js',
<ide> lineNumber: 1,
<ide> describe('LogBoxInspectorStackFrame', () => {
<ide> expect(
<ide> getCollapseMessage(
<ide> createCollapsedFrames(
<del> [stackOne, stackTwo, stackThree].filter(i => i != null),
<add> [stackOne, stackTwo, stackThree].filter((i) => i != null),
<ide> ),
<ide> collapsed,
<ide> ),
<ide><path>Libraries/Modal/Modal.js
<ide> class Modal extends React.Component<Props> {
<ide> props.transparent
<ide> ) {
<ide> console.warn(
<del> `Modal with '${
<del> props.presentationStyle
<del> }' presentation style and 'transparent' value is not supported.`,
<add> `Modal with '${props.presentationStyle}' presentation style and 'transparent' value is not supported.`,
<ide> );
<ide> }
<ide> }
<ide><path>Libraries/Network/RCTNetworking.android.js
<ide> class RCTNetworking extends NativeEventEmitter {
<ide> ) {
<ide> const body = convertRequestBody(data);
<ide> if (body && body.formData) {
<del> body.formData = body.formData.map(part => ({
<add> body.formData = body.formData.map((part) => ({
<ide> ...part,
<ide> headers: convertHeadersMapToArray(part.headers),
<ide> }));
<ide><path>Libraries/Network/XHRInterceptor.js
<ide> const XHRInterceptor = {
<ide> }
<ide> // Override `open` method for all XHR requests to intercept the request
<ide> // method and url, then pass them through the `openCallback`.
<del> XMLHttpRequest.prototype.open = function(method, url) {
<add> XMLHttpRequest.prototype.open = function (method, url) {
<ide> if (openCallback) {
<ide> openCallback(method, url, this);
<ide> }
<ide> const XHRInterceptor = {
<ide>
<ide> // Override `setRequestHeader` method for all XHR requests to intercept
<ide> // the request headers, then pass them through the `requestHeaderCallback`.
<del> XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
<add> XMLHttpRequest.prototype.setRequestHeader = function (header, value) {
<ide> if (requestHeaderCallback) {
<ide> requestHeaderCallback(header, value, this);
<ide> }
<ide> const XHRInterceptor = {
<ide>
<ide> // Override `send` method of all XHR requests to intercept the data sent,
<ide> // register listeners to intercept the response, and invoke the callbacks.
<del> XMLHttpRequest.prototype.send = function(data) {
<add> XMLHttpRequest.prototype.send = function (data) {
<ide> if (sendCallback) {
<ide> sendCallback(data, this);
<ide> }
<ide><path>Libraries/Network/XMLHttpRequest.js
<ide> class XMLHttpRequest extends (EventTarget(...XHR_EVENTS): any) {
<ide> }
<ide>
<ide> _clearSubscriptions(): void {
<del> (this._subscriptions || []).forEach(sub => {
<add> (this._subscriptions || []).forEach((sub) => {
<ide> if (sub) {
<ide> sub.remove();
<ide> }
<ide> class XMLHttpRequest extends (EventTarget(...XHR_EVENTS): any) {
<ide> }
<ide> const headers = this.responseHeaders || {};
<ide> return Object.keys(headers)
<del> .map(headerName => {
<add> .map((headerName) => {
<ide> return headerName + ': ' + headers[headerName];
<ide> })
<ide> .join('\r\n');
<ide> class XMLHttpRequest extends (EventTarget(...XHR_EVENTS): any) {
<ide> this._incrementalEvents || !!this.onreadystatechange || !!this.onprogress;
<ide>
<ide> this._subscriptions.push(
<del> RCTNetworking.addListener('didSendNetworkData', args =>
<add> RCTNetworking.addListener('didSendNetworkData', (args) =>
<ide> this.__didUploadProgress(...args),
<ide> ),
<ide> );
<ide> this._subscriptions.push(
<del> RCTNetworking.addListener('didReceiveNetworkResponse', args =>
<add> RCTNetworking.addListener('didReceiveNetworkResponse', (args) =>
<ide> this.__didReceiveResponse(...args),
<ide> ),
<ide> );
<ide> this._subscriptions.push(
<del> RCTNetworking.addListener('didReceiveNetworkData', args =>
<add> RCTNetworking.addListener('didReceiveNetworkData', (args) =>
<ide> this.__didReceiveData(...args),
<ide> ),
<ide> );
<ide> this._subscriptions.push(
<del> RCTNetworking.addListener('didReceiveNetworkIncrementalData', args =>
<add> RCTNetworking.addListener('didReceiveNetworkIncrementalData', (args) =>
<ide> this.__didReceiveIncrementalData(...args),
<ide> ),
<ide> );
<ide> this._subscriptions.push(
<del> RCTNetworking.addListener('didReceiveNetworkDataProgress', args =>
<add> RCTNetworking.addListener('didReceiveNetworkDataProgress', (args) =>
<ide> this.__didReceiveDataProgress(...args),
<ide> ),
<ide> );
<ide> this._subscriptions.push(
<del> RCTNetworking.addListener('didCompleteNetworkResponse', args =>
<add> RCTNetworking.addListener('didCompleteNetworkResponse', (args) =>
<ide> this.__didCompleteResponse(...args),
<ide> ),
<ide> );
<ide><path>Libraries/Network/__tests__/FormData-test.js
<ide>
<ide> const FormData = require('../FormData');
<ide>
<del>describe('FormData', function() {
<add>describe('FormData', function () {
<ide> var formData;
<ide>
<ide> beforeEach(() => {
<ide> describe('FormData', function() {
<ide> formData = null;
<ide> });
<ide>
<del> it('should return non blob null', function() {
<add> it('should return non blob null', function () {
<ide> formData.append('null', null);
<ide>
<ide> const expectedPart = {
<ide> describe('FormData', function() {
<ide> expect(formData.getParts()[0]).toMatchObject(expectedPart);
<ide> });
<ide>
<del> it('should return blob', function() {
<add> it('should return blob', function () {
<ide> formData.append('photo', {
<ide> uri: 'arbitrary/path',
<ide> type: 'image/jpeg',
<ide><path>Libraries/Network/__tests__/XMLHttpRequest-test.js
<ide> jest
<ide> .dontMock('event-target-shim')
<ide> .setMock('../../BatchedBridge/NativeModules', {
<ide> Networking: {
<del> addListener: function() {},
<del> removeListeners: function() {},
<add> addListener: function () {},
<add> removeListeners: function () {},
<ide> sendRequest(options, callback) {
<ide> if (typeof callback === 'function') {
<ide> // android does not pass a callback
<ide> callback(requestId);
<ide> }
<ide> },
<del> abortRequest: function() {},
<add> abortRequest: function () {},
<ide> },
<ide> PlatformConstants: {
<ide> getConstants() {
<ide> jest
<ide>
<ide> const XMLHttpRequest = require('../XMLHttpRequest');
<ide>
<del>describe('XMLHttpRequest', function() {
<add>describe('XMLHttpRequest', function () {
<ide> let xhr;
<ide> let handleTimeout;
<ide> let handleError;
<ide> describe('XMLHttpRequest', function() {
<ide> handleReadyStateChange = null;
<ide> });
<ide>
<del> it('should transition readyState correctly', function() {
<add> it('should transition readyState correctly', function () {
<ide> expect(xhr.readyState).toBe(xhr.UNSENT);
<ide>
<ide> xhr.open('GET', 'blabla');
<ide> describe('XMLHttpRequest', function() {
<ide> expect(xhr.readyState).toBe(xhr.OPENED);
<ide> });
<ide>
<del> it('should expose responseType correctly', function() {
<add> it('should expose responseType correctly', function () {
<ide> expect(xhr.responseType).toBe('');
<ide>
<ide> jest.spyOn(console, 'error').mockImplementationOnce(() => {});
<ide> describe('XMLHttpRequest', function() {
<ide> }).toThrow();
<ide> });
<ide>
<del> it('should expose responseText correctly', function() {
<add> it('should expose responseText correctly', function () {
<ide> xhr.responseType = '';
<ide> expect(xhr.responseText).toBe('');
<ide> expect(xhr.response).toBe('');
<ide> describe('XMLHttpRequest', function() {
<ide> expect(xhr.responseText).toBe('Some data');
<ide> });
<ide>
<del> it('should call ontimeout function when the request times out', function() {
<add> it('should call ontimeout function when the request times out', function () {
<ide> xhr.open('GET', 'blabla');
<ide> xhr.send();
<ide> setRequestId(3);
<ide> describe('XMLHttpRequest', function() {
<ide> expect(handleLoad).not.toBeCalled();
<ide> });
<ide>
<del> it('should call onerror function when the request times out', function() {
<add> it('should call onerror function when the request times out', function () {
<ide> xhr.open('GET', 'blabla');
<ide> xhr.send();
<ide> setRequestId(4);
<ide> describe('XMLHttpRequest', function() {
<ide> expect(handleLoad).not.toBeCalled();
<ide> });
<ide>
<del> it('should call onload function when there is no error', function() {
<add> it('should call onload function when there is no error', function () {
<ide> xhr.open('GET', 'blabla');
<ide> xhr.send();
<ide> setRequestId(5);
<ide> describe('XMLHttpRequest', function() {
<ide> expect(handleTimeout).not.toBeCalled();
<ide> });
<ide>
<del> it('should call upload onprogress', function() {
<add> it('should call upload onprogress', function () {
<ide> xhr.open('GET', 'blabla');
<ide> xhr.send();
<ide>
<ide> describe('XMLHttpRequest', function() {
<ide> expect(handleProgress.mock.calls[0][0].total).toBe(100);
<ide> });
<ide>
<del> it('should combine response headers with CRLF', function() {
<add> it('should combine response headers with CRLF', function () {
<ide> xhr.open('GET', 'blabla');
<ide> xhr.send();
<ide> setRequestId(7);
<ide><path>Libraries/Performance/PureComponentDebug.js
<ide> class PureComponentDebug<
<ide> console.warn(
<ide> 'PureComponentDebug: different prop keys',
<ide> tag,
<del> prevPropsKeys.filter(key => !nextPropsKeys.includes(key)),
<del> nextPropsKeys.filter(key => !prevPropsKeys.includes(key)),
<add> prevPropsKeys.filter((key) => !nextPropsKeys.includes(key)),
<add> nextPropsKeys.filter((key) => !prevPropsKeys.includes(key)),
<ide> );
<ide> }
<ide> const prevStateKeys = Object.keys(this.state || {});
<ide> class PureComponentDebug<
<ide> console.warn(
<ide> 'PureComponentDebug: different state keys',
<ide> tag,
<del> prevStateKeys.filter(key => !nextStateKeys.includes(key)),
<del> nextStateKeys.filter(key => !prevStateKeys.includes(key)),
<add> prevStateKeys.filter((key) => !nextStateKeys.includes(key)),
<add> nextStateKeys.filter((key) => !prevStateKeys.includes(key)),
<ide> );
<ide> }
<ide> for (const key in this.props) {
<ide><path>Libraries/Performance/SamplingProfiler.js
<ide> 'use strict';
<ide>
<ide> const SamplingProfiler = {
<del> poke: function(token: number): void {
<add> poke: function (token: number): void {
<ide> let error = null;
<ide> let result = null;
<ide> try {
<ide><path>Libraries/Pressability/Pressability.js
<ide> const Transitions = Object.freeze({
<ide> },
<ide> });
<ide>
<del>const isActiveSignal = signal =>
<add>const isActiveSignal = (signal) =>
<ide> signal === 'RESPONDER_ACTIVE_PRESS_IN' ||
<ide> signal === 'RESPONDER_ACTIVE_LONG_PRESS_IN';
<ide>
<del>const isActivationSignal = signal =>
<add>const isActivationSignal = (signal) =>
<ide> signal === 'RESPONDER_ACTIVE_PRESS_OUT' ||
<ide> signal === 'RESPONDER_ACTIVE_PRESS_IN';
<ide>
<del>const isPressInSignal = signal =>
<add>const isPressInSignal = (signal) =>
<ide> signal === 'RESPONDER_INACTIVE_PRESS_IN' ||
<ide> signal === 'RESPONDER_ACTIVE_PRESS_IN' ||
<ide> signal === 'RESPONDER_ACTIVE_LONG_PRESS_IN';
<ide>
<del>const isTerminalSignal = signal =>
<add>const isTerminalSignal = (signal) =>
<ide> signal === 'RESPONDER_TERMINATED' || signal === 'RESPONDER_RELEASE';
<ide>
<ide> const DEFAULT_LONG_PRESS_DELAY_MS = 370; // 500 - 130
<ide><path>Libraries/Pressability/__tests__/Pressability-test.js
<ide> function getMock<TArguments: $ReadOnlyArray<mixed>, TReturn>(
<ide> return (fn: $FlowFixMe);
<ide> }
<ide>
<del>const createMockPressability = overrides => {
<add>const createMockPressability = (overrides) => {
<ide> const config = {
<ide> cancelable: null,
<ide> disabled: null,
<ide> const mockUIManagerMeasure = (options?: {|delay: number|}) => {
<ide> });
<ide> };
<ide>
<del>const createMockTargetEvent = registrationName => {
<add>const createMockTargetEvent = (registrationName) => {
<ide> const nativeEvent = {
<ide> target: 42,
<ide> };
<ide> const createMockTargetEvent = registrationName => {
<ide> };
<ide> };
<ide>
<del>const createMockMouseEvent = registrationName => {
<add>const createMockMouseEvent = (registrationName) => {
<ide> const nativeEvent = {
<ide> clientX: 0,
<ide> clientY: 0,
<ide><path>Libraries/Promise.js
<ide> if (__DEV__) {
<ide> (stack == null ? '' : stack);
<ide> console.warn(warning);
<ide> },
<del> onHandled: id => {
<add> onHandled: (id) => {
<ide> const warning =
<ide> `Promise Rejection Handled (id: ${id})\n` +
<ide> 'This means you can ignore any previous messages of the form ' +
<ide><path>Libraries/PushNotificationIOS/PushNotificationIOS.js
<ide> class PushNotificationIOS {
<ide> if (type === 'notification') {
<ide> listener = PushNotificationEmitter.addListener(
<ide> DEVICE_NOTIF_EVENT,
<del> notifData => {
<add> (notifData) => {
<ide> handler(new PushNotificationIOS(notifData));
<ide> },
<ide> );
<ide> } else if (type === 'localNotification') {
<ide> listener = PushNotificationEmitter.addListener(
<ide> DEVICE_LOCAL_NOTIF_EVENT,
<del> notifData => {
<add> (notifData) => {
<ide> handler(new PushNotificationIOS(notifData));
<ide> },
<ide> );
<ide> } else if (type === 'register') {
<ide> listener = PushNotificationEmitter.addListener(
<ide> NOTIF_REGISTER_EVENT,
<del> registrationInfo => {
<add> (registrationInfo) => {
<ide> handler(registrationInfo.deviceToken);
<ide> },
<ide> );
<ide> } else if (type === 'registrationError') {
<ide> listener = PushNotificationEmitter.addListener(
<ide> NOTIF_REGISTRATION_ERROR_EVENT,
<del> errorInfo => {
<add> (errorInfo) => {
<ide> handler(errorInfo);
<ide> },
<ide> );
<ide> class PushNotificationIOS {
<ide> 'PushNotificationManager is not available.',
<ide> );
<ide> return NativePushNotificationManagerIOS.getInitialNotification().then(
<del> notification => {
<add> (notification) => {
<ide> return notification && new PushNotificationIOS(notification);
<ide> },
<ide> );
<ide> class PushNotificationIOS {
<ide> if (nativeNotif.remote) {
<ide> // Extract data from Apple's `aps` dict as defined:
<ide> // https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html
<del> Object.keys(nativeNotif).forEach(notifKey => {
<add> Object.keys(nativeNotif).forEach((notifKey) => {
<ide> const notifVal = nativeNotif[notifKey];
<ide> if (notifKey === 'aps') {
<ide> this._alert = notifVal.alert;
<ide><path>Libraries/ReactNative/AppContainer.js
<ide> class AppContainer extends React.Component<Props, State> {
<ide> <Inspector
<ide> isFabric={this.props.fabric === true}
<ide> inspectedView={this._mainRef}
<del> onRequestRerenderApp={updateInspectedView => {
<add> onRequestRerenderApp={(updateInspectedView) => {
<ide> this.setState(
<del> s => ({mainKey: s.mainKey + 1}),
<add> (s) => ({mainKey: s.mainKey + 1}),
<ide> () => updateInspectedView(this._mainRef),
<ide> );
<ide> }}
<ide> class AppContainer extends React.Component<Props, State> {
<ide> key={this.state.mainKey}
<ide> pointerEvents="box-none"
<ide> style={styles.appContainer}
<del> ref={ref => {
<add> ref={(ref) => {
<ide> this._mainRef = ref;
<ide> }}>
<ide> {this.props.children}
<ide><path>Libraries/ReactNative/AppRegistry.js
<ide> export type Registry = {
<ide> runnables: Runnables,
<ide> ...
<ide> };
<del>export type WrapperComponentProvider = any => React$ComponentType<*>;
<add>export type WrapperComponentProvider = (any) => React$ComponentType<*>;
<ide>
<ide> const runnables: Runnables = {};
<ide> let runCount = 1;
<ide> const AppRegistry = {
<ide> },
<ide>
<ide> registerConfig(config: Array<AppConfig>): void {
<del> config.forEach(appConfig => {
<add> config.forEach((appConfig) => {
<ide> if (appConfig.run) {
<ide> AppRegistry.registerRunnable(appConfig.appKey, appConfig.run);
<ide> } else {
<ide> const AppRegistry = {
<ide> let scopedPerformanceLogger = createPerformanceLogger();
<ide> runnables[appKey] = {
<ide> componentProvider,
<del> run: appParameters => {
<add> run: (appParameters) => {
<ide> renderApplication(
<ide> componentProviderInstrumentationHook(
<ide> componentProvider,
<ide> const AppRegistry = {
<ide> NativeHeadlessJsTaskSupport.notifyTaskFinished(taskId);
<ide> }
<ide> })
<del> .catch(reason => {
<add> .catch((reason) => {
<ide> console.error(reason);
<ide>
<ide> if (
<ide> NativeHeadlessJsTaskSupport &&
<ide> reason instanceof HeadlessJsTaskError
<ide> ) {
<ide> NativeHeadlessJsTaskSupport.notifyTaskRetry(taskId).then(
<del> retryPosted => {
<add> (retryPosted) => {
<ide> if (!retryPosted) {
<ide> NativeHeadlessJsTaskSupport.notifyTaskFinished(taskId);
<ide> }
<ide><path>Libraries/ReactNative/PaperUIManager.js
<ide> const UIManagerJS = {
<ide> getConstants(): Object {
<ide> return getConstants();
<ide> },
<del> getViewManagerConfig: function(viewManagerName: string): any {
<add> getViewManagerConfig: function (viewManagerName: string): any {
<ide> if (
<ide> viewManagerConfigs[viewManagerName] === undefined &&
<ide> NativeUIManager.getConstantsForViewManager
<ide> function lazifyViewManagerConfig(viewName) {
<ide> const viewManager = NativeModules[viewConfig.Manager];
<ide> const constants = {};
<ide> viewManager &&
<del> Object.keys(viewManager).forEach(key => {
<add> Object.keys(viewManager).forEach((key) => {
<ide> const value = viewManager[key];
<ide> if (typeof value !== 'function') {
<ide> constants[key] = value;
<ide> function lazifyViewManagerConfig(viewName) {
<ide> const commands = {};
<ide> let index = 0;
<ide> viewManager &&
<del> Object.keys(viewManager).forEach(key => {
<add> Object.keys(viewManager).forEach((key) => {
<ide> const value = viewManager[key];
<ide> if (typeof value === 'function') {
<ide> commands[key] = index++;
<ide> function lazifyViewManagerConfig(viewName) {
<ide> * namespace instead of UIManager, unlike Android.
<ide> */
<ide> if (Platform.OS === 'ios') {
<del> Object.keys(getConstants()).forEach(viewName => {
<add> Object.keys(getConstants()).forEach((viewName) => {
<ide> lazifyViewManagerConfig(viewName);
<ide> });
<ide> } else if (getConstants().ViewManagerNames) {
<del> NativeUIManager.getConstants().ViewManagerNames.forEach(viewManagerName => {
<add> NativeUIManager.getConstants().ViewManagerNames.forEach((viewManagerName) => {
<ide> defineLazyObjectProperty(NativeUIManager, viewManagerName, {
<ide> get: () => NativeUIManager.getConstantsForViewManager(viewManagerName),
<ide> });
<ide> });
<ide> }
<ide>
<ide> if (!global.nativeCallSyncHook) {
<del> Object.keys(getConstants()).forEach(viewManagerName => {
<add> Object.keys(getConstants()).forEach((viewManagerName) => {
<ide> if (!UIManagerProperties.includes(viewManagerName)) {
<ide> if (!viewManagerConfigs[viewManagerName]) {
<ide> viewManagerConfigs[viewManagerName] = getConstants()[viewManagerName];
<ide><path>Libraries/ReactNative/queryLayoutByID.js
<ide> type OnErrorCallback = (error: any) => void;
<ide> * @param {function} onError `func(error)`
<ide> * @param {function} onSuccess `func(left, top, width, height, pageX, pageY)`
<ide> */
<del>const queryLayoutByID = function(
<add>const queryLayoutByID = function (
<ide> tag: ?number,
<ide> onError: OnErrorCallback,
<ide> onSuccess: OnSuccessCallback,
<ide><path>Libraries/Renderer/shims/ReactNativeViewConfigRegistry.js
<ide> function processEventTypes(
<ide> * A callback is provided to load the view config from UIManager.
<ide> * The callback is deferred until the view is actually rendered.
<ide> */
<del>exports.register = function(name: string, callback: ViewConfigGetter): string {
<add>exports.register = function (name: string, callback: ViewConfigGetter): string {
<ide> invariant(
<ide> !viewConfigCallbacks.has(name),
<ide> 'Tried to register two views with the same name %s',
<ide> exports.register = function(name: string, callback: ViewConfigGetter): string {
<ide> * If this is the first time the view has been used,
<ide> * This configuration will be lazy-loaded from UIManager.
<ide> */
<del>exports.get = function(name: string): ReactNativeBaseComponentViewConfig<> {
<add>exports.get = function (name: string): ReactNativeBaseComponentViewConfig<> {
<ide> let viewConfig;
<ide> if (!viewConfigs.has(name)) {
<ide> const callback = viewConfigCallbacks.get(name);
<ide><path>Libraries/Renderer/shims/createReactNativeComponentClass.js
<ide> const {register} = ReactNativeViewConfigRegistry;
<ide> * @param {string} config iOS View configuration.
<ide> * @private
<ide> */
<del>const createReactNativeComponentClass = function(
<add>const createReactNativeComponentClass = function (
<ide> name: string,
<ide> callback: ViewConfigGetter,
<ide> ): string {
<ide><path>Libraries/Settings/Settings.ios.js
<ide> const Settings = {
<ide> },
<ide>
<ide> _sendObservations(body: Object) {
<del> Object.keys(body).forEach(key => {
<add> Object.keys(body).forEach((key) => {
<ide> const newValue = body[key];
<ide> const didChange = this._settings[key] !== newValue;
<ide> this._settings[key] = newValue;
<ide>
<ide> if (didChange) {
<del> subscriptions.forEach(sub => {
<add> subscriptions.forEach((sub) => {
<ide> if (sub.keys.indexOf(key) !== -1 && sub.callback) {
<ide> sub.callback();
<ide> }
<ide><path>Libraries/Share/Share.js
<ide> class Share {
<ide> tintColor: typeof tintColor === 'number' ? tintColor : undefined,
<ide> excludedActivityTypes: options.excludedActivityTypes,
<ide> },
<del> error => reject(error),
<add> (error) => reject(error),
<ide> (success, activityType) => {
<ide> if (success) {
<ide> resolve({
<ide><path>Libraries/Storage/AsyncStorage.js
<ide> const AsyncStorage = {
<ide> *
<ide> * See https://reactnative.dev/docs/asyncstorage.html#getitem
<ide> */
<del> getItem: function(
<add> getItem: function (
<ide> key: string,
<ide> callback?: ?(error: ?Error, result: ?string) => void,
<ide> ): Promise {
<ide> invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
<ide> return new Promise((resolve, reject) => {
<del> RCTAsyncStorage.multiGet([key], function(errors, result) {
<add> RCTAsyncStorage.multiGet([key], function (errors, result) {
<ide> // Unpack result to get value from [[key,value]]
<ide> const value = result && result[0] && result[0][1] ? result[0][1] : null;
<ide> const errs = convertErrors(errors);
<ide> const AsyncStorage = {
<ide> *
<ide> * See https://reactnative.dev/docs/asyncstorage.html#setitem
<ide> */
<del> setItem: function(
<add> setItem: function (
<ide> key: string,
<ide> value: string,
<ide> callback?: ?(error: ?Error) => void,
<ide> ): Promise {
<ide> invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
<ide> return new Promise((resolve, reject) => {
<del> RCTAsyncStorage.multiSet([[key, value]], function(errors) {
<add> RCTAsyncStorage.multiSet([[key, value]], function (errors) {
<ide> const errs = convertErrors(errors);
<ide> callback && callback(errs && errs[0]);
<ide> if (errs) {
<ide> const AsyncStorage = {
<ide> *
<ide> * See https://reactnative.dev/docs/asyncstorage.html#removeitem
<ide> */
<del> removeItem: function(
<add> removeItem: function (
<ide> key: string,
<ide> callback?: ?(error: ?Error) => void,
<ide> ): Promise {
<ide> invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
<ide> return new Promise((resolve, reject) => {
<del> RCTAsyncStorage.multiRemove([key], function(errors) {
<add> RCTAsyncStorage.multiRemove([key], function (errors) {
<ide> const errs = convertErrors(errors);
<ide> callback && callback(errs && errs[0]);
<ide> if (errs) {
<ide> const AsyncStorage = {
<ide> *
<ide> * See https://reactnative.dev/docs/asyncstorage.html#mergeitem
<ide> */
<del> mergeItem: function(
<add> mergeItem: function (
<ide> key: string,
<ide> value: string,
<ide> callback?: ?(error: ?Error) => void,
<ide> ): Promise {
<ide> invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
<ide> return new Promise((resolve, reject) => {
<del> RCTAsyncStorage.multiMerge([[key, value]], function(errors) {
<add> RCTAsyncStorage.multiMerge([[key, value]], function (errors) {
<ide> const errs = convertErrors(errors);
<ide> callback && callback(errs && errs[0]);
<ide> if (errs) {
<ide> const AsyncStorage = {
<ide> *
<ide> * See https://reactnative.dev/docs/asyncstorage.html#clear
<ide> */
<del> clear: function(callback?: ?(error: ?Error) => void): Promise {
<add> clear: function (callback?: ?(error: ?Error) => void): Promise {
<ide> invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
<ide> return new Promise((resolve, reject) => {
<del> RCTAsyncStorage.clear(function(error) {
<add> RCTAsyncStorage.clear(function (error) {
<ide> callback && callback(convertError(error));
<ide> if (error && convertError(error)) {
<ide> reject(convertError(error));
<ide> const AsyncStorage = {
<ide> *
<ide> * See https://reactnative.dev/docs/asyncstorage.html#getallkeys
<ide> */
<del> getAllKeys: function(
<add> getAllKeys: function (
<ide> callback?: ?(error: ?Error, keys: ?Array<string>) => void,
<ide> ): Promise {
<ide> invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
<ide> return new Promise((resolve, reject) => {
<del> RCTAsyncStorage.getAllKeys(function(error, keys) {
<add> RCTAsyncStorage.getAllKeys(function (error, keys) {
<ide> callback && callback(convertError(error), keys);
<ide> if (error) {
<ide> reject(convertError(error));
<ide> const AsyncStorage = {
<ide> *
<ide> * See https://reactnative.dev/docs/asyncstorage.html#flushgetrequests
<ide> * */
<del> flushGetRequests: function(): void {
<add> flushGetRequests: function (): void {
<ide> const getRequests = this._getRequests;
<ide> const getKeys = this._getKeys;
<ide>
<ide> this._getRequests = [];
<ide> this._getKeys = [];
<ide>
<ide> invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
<del> RCTAsyncStorage.multiGet(getKeys, function(errors, result) {
<add> RCTAsyncStorage.multiGet(getKeys, function (errors, result) {
<ide> // Even though the runtime complexity of this is theoretically worse vs if we used a map,
<ide> // it's much, much faster in practice for the data sets we deal with (we avoid
<ide> // allocating result pair arrays). This was heavily benchmarked.
<ide> const AsyncStorage = {
<ide> for (let i = 0; i < reqLength; i++) {
<ide> const request = getRequests[i];
<ide> const requestKeys = request.keys;
<del> const requestResult = requestKeys.map(key => [key, map[key]]);
<add> const requestResult = requestKeys.map((key) => [key, map[key]]);
<ide> request.callback && request.callback(null, requestResult);
<ide> request.resolve && request.resolve(requestResult);
<ide> }
<ide> const AsyncStorage = {
<ide> *
<ide> * See https://reactnative.dev/docs/asyncstorage.html#multiget
<ide> */
<del> multiGet: function(
<add> multiGet: function (
<ide> keys: Array<string>,
<ide> callback?: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void,
<ide> ): Promise {
<ide> const AsyncStorage = {
<ide>
<ide> this._getRequests.push(getRequest);
<ide> // avoid fetching duplicates
<del> keys.forEach(key => {
<add> keys.forEach((key) => {
<ide> if (this._getKeys.indexOf(key) === -1) {
<ide> this._getKeys.push(key);
<ide> }
<ide> const AsyncStorage = {
<ide> *
<ide> * See https://reactnative.dev/docs/asyncstorage.html#multiset
<ide> */
<del> multiSet: function(
<add> multiSet: function (
<ide> keyValuePairs: Array<Array<string>>,
<ide> callback?: ?(errors: ?Array<Error>) => void,
<ide> ): Promise {
<ide> invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
<ide> return new Promise((resolve, reject) => {
<del> RCTAsyncStorage.multiSet(keyValuePairs, function(errors) {
<add> RCTAsyncStorage.multiSet(keyValuePairs, function (errors) {
<ide> const error = convertErrors(errors);
<ide> callback && callback(error);
<ide> if (error) {
<ide> const AsyncStorage = {
<ide> *
<ide> * See https://reactnative.dev/docs/asyncstorage.html#multiremove
<ide> */
<del> multiRemove: function(
<add> multiRemove: function (
<ide> keys: Array<string>,
<ide> callback?: ?(errors: ?Array<Error>) => void,
<ide> ): Promise {
<ide> invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
<ide> return new Promise((resolve, reject) => {
<del> RCTAsyncStorage.multiRemove(keys, function(errors) {
<add> RCTAsyncStorage.multiRemove(keys, function (errors) {
<ide> const error = convertErrors(errors);
<ide> callback && callback(error);
<ide> if (error) {
<ide> const AsyncStorage = {
<ide> *
<ide> * See https://reactnative.dev/docs/asyncstorage.html#multimerge
<ide> */
<del> multiMerge: function(
<add> multiMerge: function (
<ide> keyValuePairs: Array<Array<string>>,
<ide> callback?: ?(errors: ?Array<Error>) => void,
<ide> ): Promise {
<ide> invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
<ide> return new Promise((resolve, reject) => {
<del> RCTAsyncStorage.multiMerge(keyValuePairs, function(errors) {
<add> RCTAsyncStorage.multiMerge(keyValuePairs, function (errors) {
<ide> const error = convertErrors(errors);
<ide> callback && callback(error);
<ide> if (error) {
<ide> function convertErrors(errs) {
<ide> if (!errs) {
<ide> return null;
<ide> }
<del> return (Array.isArray(errs) ? errs : [errs]).map(e => convertError(e));
<add> return (Array.isArray(errs) ? errs : [errs]).map((e) => convertError(e));
<ide> }
<ide>
<ide> function convertError(error) {
<ide><path>Libraries/StyleSheet/StyleSheetValidation.js
<ide> class StyleSheetValidation {
<ide> }
<ide> }
<ide>
<del>const styleError = function(message1, style, caller?, message2?) {
<add>const styleError = function (message1, style, caller?, message2?) {
<ide> invariant(
<ide> false,
<ide> message1 +
<ide><path>Libraries/StyleSheet/__flowtests__/StyleSheet-flowtest.js
<ide> const textStyle = {color: 'rgb(0, 0, 0)'};
<ide>
<ide> module.exports = {
<ide> testGoodCompose() {
<del> (StyleSheet.compose(
<del> imageStyle,
<del> imageStyle,
<del> ): ImageStyleProp);
<add> (StyleSheet.compose(imageStyle, imageStyle): ImageStyleProp);
<ide>
<del> (StyleSheet.compose(
<del> textStyle,
<del> textStyle,
<del> ): TextStyleProp);
<add> (StyleSheet.compose(textStyle, textStyle): TextStyleProp);
<ide>
<del> (StyleSheet.compose(
<del> null,
<del> null,
<del> ): TextStyleProp);
<add> (StyleSheet.compose(null, null): TextStyleProp);
<ide>
<del> (StyleSheet.compose(
<del> textStyle,
<del> null,
<del> ): TextStyleProp);
<add> (StyleSheet.compose(textStyle, null): TextStyleProp);
<ide>
<ide> (StyleSheet.compose(
<ide> textStyle,
<ide> Math.random() < 0.5 ? textStyle : null,
<ide> ): TextStyleProp);
<ide>
<del> (StyleSheet.compose(
<del> [textStyle],
<del> null,
<del> ): TextStyleProp);
<add> (StyleSheet.compose([textStyle], null): TextStyleProp);
<ide>
<del> (StyleSheet.compose(
<del> [textStyle],
<del> null,
<del> ): TextStyleProp);
<add> (StyleSheet.compose([textStyle], null): TextStyleProp);
<ide>
<del> (StyleSheet.compose(
<del> [textStyle],
<del> [textStyle],
<del> ): TextStyleProp);
<add> (StyleSheet.compose([textStyle], [textStyle]): TextStyleProp);
<ide> },
<ide>
<ide> testBadCompose() {
<ide> // $FlowExpectedError - Incompatible type.
<del> (StyleSheet.compose(
<del> textStyle,
<del> textStyle,
<del> ): ImageStyleProp);
<add> (StyleSheet.compose(textStyle, textStyle): ImageStyleProp);
<ide>
<ide> // $FlowExpectedError - Incompatible type.
<ide> (StyleSheet.compose(
<ide><path>Libraries/StyleSheet/__tests__/normalizeColor-test.js
<ide> const DynamicColorIOS = require('../PlatformColorValueTypesIOS.ios')
<ide> const PlatformColorAndroid = require('../PlatformColorValueTypes.android')
<ide> .PlatformColor;
<ide>
<del>describe('normalizeColor', function() {
<del> it('should accept only spec compliant colors', function() {
<add>describe('normalizeColor', function () {
<add> it('should accept only spec compliant colors', function () {
<ide> expect(normalizeColor('#abc')).not.toBe(null);
<ide> expect(normalizeColor('#abcd')).not.toBe(null);
<ide> expect(normalizeColor('#abcdef')).not.toBe(null);
<ide> describe('normalizeColor', function() {
<ide> expect(normalizeColor(0xffffffff + 1)).toBe(null);
<ide> });
<ide>
<del> it('should temporarily accept floating point values for rgb', function() {
<add> it('should temporarily accept floating point values for rgb', function () {
<ide> expect(normalizeColor('rgb(1.1, 2.1, 3.1)')).toBe(0x010203ff);
<ide> expect(normalizeColor('rgba(1.1, 2.1, 3.1, 1.0)')).toBe(0x010203ff);
<ide> });
<ide>
<del> it('should refuse non spec compliant colors', function() {
<add> it('should refuse non spec compliant colors', function () {
<ide> expect(normalizeColor('#00gg00')).toBe(null);
<ide> expect(normalizeColor('rgb(1, 2, 3,)')).toBe(null);
<ide> expect(normalizeColor('rgb(1, 2, 3')).toBe(null);
<ide> describe('normalizeColor', function() {
<ide> expect(normalizeColor('rgb(1%, 2%, 3%)')).toBe(null);
<ide> });
<ide>
<del> it('should handle hex6 properly', function() {
<add> it('should handle hex6 properly', function () {
<ide> expect(normalizeColor('#000000')).toBe(0x000000ff);
<ide> expect(normalizeColor('#ffffff')).toBe(0xffffffff);
<ide> expect(normalizeColor('#ff00ff')).toBe(0xff00ffff);
<ide> expect(normalizeColor('#abcdef')).toBe(0xabcdefff);
<ide> expect(normalizeColor('#012345')).toBe(0x012345ff);
<ide> });
<ide>
<del> it('should handle hex3 properly', function() {
<add> it('should handle hex3 properly', function () {
<ide> expect(normalizeColor('#000')).toBe(0x000000ff);
<ide> expect(normalizeColor('#fff')).toBe(0xffffffff);
<ide> expect(normalizeColor('#f0f')).toBe(0xff00ffff);
<ide> });
<ide>
<del> it('should handle hex8 properly', function() {
<add> it('should handle hex8 properly', function () {
<ide> expect(normalizeColor('#00000000')).toBe(0x00000000);
<ide> expect(normalizeColor('#ffffffff')).toBe(0xffffffff);
<ide> expect(normalizeColor('#ffff00ff')).toBe(0xffff00ff);
<ide> expect(normalizeColor('#abcdef01')).toBe(0xabcdef01);
<ide> expect(normalizeColor('#01234567')).toBe(0x01234567);
<ide> });
<ide>
<del> it('should handle rgb properly', function() {
<add> it('should handle rgb properly', function () {
<ide> expect(normalizeColor('rgb(0, 0, 0)')).toBe(0x000000ff);
<ide> expect(normalizeColor('rgb(-1, -2, -3)')).toBe(0x000000ff);
<ide> expect(normalizeColor('rgb(0, 0, 255)')).toBe(0x0000ffff);
<ide> describe('normalizeColor', function() {
<ide> expect(normalizeColor('rgb(256, 256, 256)')).toBe(0xffffffff);
<ide> });
<ide>
<del> it('should handle rgba properly', function() {
<add> it('should handle rgba properly', function () {
<ide> expect(normalizeColor('rgba(0, 0, 0, 0.0)')).toBe(0x00000000);
<ide> expect(normalizeColor('rgba(0, 0, 0, 0)')).toBe(0x00000000);
<ide> expect(normalizeColor('rgba(0, 0, 0, -0.5)')).toBe(0x00000000);
<ide> describe('normalizeColor', function() {
<ide> expect(normalizeColor('rgba(100, 15, 69, 0.5)')).toBe(0x640f4580);
<ide> });
<ide>
<del> it('should handle hsl properly', function() {
<add> it('should handle hsl properly', function () {
<ide> expect(normalizeColor('hsl(0, 0%, 0%)')).toBe(0x000000ff);
<ide> expect(normalizeColor('hsl(360, 100%, 100%)')).toBe(0xffffffff);
<ide> expect(normalizeColor('hsl(180, 50%, 50%)')).toBe(0x40bfbfff);
<ide> describe('normalizeColor', function() {
<ide> expect(normalizeColor('hsl(70, -10%, 75%)')).toBe(0xbfbfbfff);
<ide> });
<ide>
<del> it('should handle hsla properly', function() {
<add> it('should handle hsla properly', function () {
<ide> expect(normalizeColor('hsla(0, 0%, 0%, 0)')).toBe(0x00000000);
<ide> expect(normalizeColor('hsla(360, 100%, 100%, 1)')).toBe(0xffffffff);
<ide> expect(normalizeColor('hsla(360, 100%, 100%, 0)')).toBe(0xffffff00);
<ide> expect(normalizeColor('hsla(180, 50%, 50%, 0.2)')).toBe(0x40bfbf33);
<ide> });
<ide>
<del> it('should handle named colors properly', function() {
<add> it('should handle named colors properly', function () {
<ide> expect(normalizeColor('red')).toBe(0xff0000ff);
<ide> expect(normalizeColor('transparent')).toBe(0x00000000);
<ide> expect(normalizeColor('peachpuff')).toBe(0xffdab9ff);
<ide> });
<ide>
<del> it('should handle number colors properly', function() {
<add> it('should handle number colors properly', function () {
<ide> expect(normalizeColor(0x00000000)).toBe(0x00000000);
<ide> expect(normalizeColor(0xff0000ff)).toBe(0xff0000ff);
<ide> expect(normalizeColor(0xffffffff)).toBe(0xffffffff);
<ide> expect(normalizeColor(0x01234567)).toBe(0x01234567);
<ide> });
<ide>
<del> it("should return the same color when it's already normalized", function() {
<add> it("should return the same color when it's already normalized", function () {
<ide> const normalizedColor = normalizeColor('red') || 0;
<ide> expect(normalizeColor(normalizedColor)).toBe(normalizedColor);
<ide> });
<ide><path>Libraries/StyleSheet/__tests__/processColor-test.js
<ide> const PlatformColorAndroid = require('../PlatformColorValueTypes.android')
<ide>
<ide> const platformSpecific =
<ide> OS === 'android'
<del> ? unsigned => unsigned | 0 //eslint-disable-line no-bitwise
<del> : x => x;
<add> ? (unsigned) => unsigned | 0 //eslint-disable-line no-bitwise
<add> : (x) => x;
<ide>
<ide> describe('processColor', () => {
<ide> describe('predefined color names', () => {
<ide><path>Libraries/StyleSheet/__tests__/processColorArray-test.js
<ide> const PlatformColorAndroid = require('../PlatformColorValueTypes.android')
<ide>
<ide> const platformSpecific =
<ide> OS === 'android'
<del> ? unsigned => unsigned | 0 //eslint-disable-line no-bitwise
<del> : x => x;
<add> ? (unsigned) => unsigned | 0 //eslint-disable-line no-bitwise
<add> : (x) => x;
<ide>
<ide> describe('processColorArray', () => {
<ide> describe('predefined color name array', () => {
<ide><path>Libraries/StyleSheet/__tests__/setNormalizedColorAlpha-test.js
<ide> const setNormalizedColorAlpha = require('../setNormalizedColorAlpha');
<ide> const normalizeColor = require('../normalizeColor');
<ide>
<del>describe('setNormalizedColorAlpha', function() {
<del> it('should adjust the alpha of the color passed in', function() {
<add>describe('setNormalizedColorAlpha', function () {
<add> it('should adjust the alpha of the color passed in', function () {
<ide> expect(setNormalizedColorAlpha(0xffffffff, 0.4)).toBe(0xffffff66);
<ide> expect(setNormalizedColorAlpha(0x204080ff, 0.6)).toBe(0x20408099);
<ide> });
<ide>
<del> it('should clamp invalid input', function() {
<add> it('should clamp invalid input', function () {
<ide> expect(setNormalizedColorAlpha(0xffffffff, 1.5)).toBe(0xffffffff);
<ide> expect(setNormalizedColorAlpha(0xffffffff, -1)).toBe(0xffffff00);
<ide> });
<ide>
<del> it("should ignore the color's original alpha", function() {
<add> it("should ignore the color's original alpha", function () {
<ide> expect(setNormalizedColorAlpha(0x204080aa, 0.8)).toBe(0x204080cc);
<ide> });
<ide>
<del> it('should return the original color when alpha is unchanged', function() {
<add> it('should return the original color when alpha is unchanged', function () {
<ide> const originalColor = normalizeColor('blue');
<ide> expect(setNormalizedColorAlpha(originalColor, 1)).toBe(originalColor);
<ide> });
<ide><path>Libraries/StyleSheet/processTransform.js
<ide> function processTransform(
<ide>
<ide> const result = MatrixMath.createIdentityMatrix();
<ide>
<del> transform.forEach(transformation => {
<add> transform.forEach((transformation) => {
<ide> const key = Object.keys(transformation)[0];
<ide> const value = transformation[key];
<ide>
<ide> function _convertToRadians(value: string): number {
<ide> }
<ide>
<ide> function _validateTransforms(transform: Array<Object>): void {
<del> transform.forEach(transformation => {
<add> transform.forEach((transformation) => {
<ide> const keys = Object.keys(transformation);
<ide> invariant(
<ide> keys.length === 1,
<ide><path>Libraries/StyleSheet/splitLayoutProps.js
<ide> function splitLayoutProps(
<ide> const inner = {};
<ide> const outer = {};
<ide> if (props) {
<del> Object.keys(props).forEach(k => {
<add> Object.keys(props).forEach((k) => {
<ide> const value: $ElementType<DangerouslyImpreciseStyle, typeof k> = props[k];
<ide> if (OUTER_PROPS[k]) {
<ide> outer[k] = value;
<ide><path>Libraries/Text/Text.js
<ide> class TouchableText extends React.Component<Props, State> {
<ide> }
<ide> return (
<ide> <TextAncestor.Consumer>
<del> {hasTextAncestor =>
<add> {(hasTextAncestor) =>
<ide> hasTextAncestor ? (
<ide> <RCTVirtualText {...props} ref={props.forwardedRef} />
<ide> ) : (
<ide><path>Libraries/Utilities/BackHandler.android.js
<ide> type BackPressEventName = 'backPress' | 'hardwareBackPress';
<ide>
<ide> const _backPressSubscriptions = [];
<ide>
<del>RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
<add>RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function () {
<ide> for (let i = _backPressSubscriptions.length - 1; i >= 0; i--) {
<ide> if (_backPressSubscriptions[i]()) {
<ide> return;
<ide> type TBackHandler = {|
<ide> ) => void,
<ide> |};
<ide> const BackHandler: TBackHandler = {
<del> exitApp: function(): void {
<add> exitApp: function (): void {
<ide> if (!NativeDeviceEventManager) {
<ide> return;
<ide> }
<ide> const BackHandler: TBackHandler = {
<ide> * - `hardwareBackPress`: Fires when the Android hardware back button is pressed or when the
<ide> * tvOS menu button is pressed.
<ide> */
<del> addEventListener: function(
<add> addEventListener: function (
<ide> eventName: BackPressEventName,
<ide> handler: Function,
<ide> ): {remove: () => void, ...} {
<ide> const BackHandler: TBackHandler = {
<ide> /**
<ide> * Removes the event handler.
<ide> */
<del> removeEventListener: function(
<add> removeEventListener: function (
<ide> eventName: BackPressEventName,
<ide> handler: Function,
<ide> ): void {
<ide><path>Libraries/Utilities/BackHandler.ios.js
<ide> if (Platform.isTV) {
<ide> const _tvEventHandler = new TVEventHandler();
<ide> const _backPressSubscriptions = new Set();
<ide>
<del> _tvEventHandler.enable(this, function(cmp, evt) {
<add> _tvEventHandler.enable(this, function (cmp, evt) {
<ide> if (evt && evt.eventType === 'menu') {
<ide> let invokeDefault = true;
<ide> const subscriptions = Array.from(
<ide> if (Platform.isTV) {
<ide> BackHandler = {
<ide> exitApp: emptyFunction,
<ide>
<del> addEventListener: function(
<add> addEventListener: function (
<ide> eventName: BackPressEventName,
<ide> handler: Function,
<ide> ): {remove: () => void, ...} {
<ide> if (Platform.isTV) {
<ide> };
<ide> },
<ide>
<del> removeEventListener: function(
<add> removeEventListener: function (
<ide> eventName: BackPressEventName,
<ide> handler: Function,
<ide> ): void {
<ide><path>Libraries/Utilities/DevSettings.js
<ide> class DevSettings extends NativeEventEmitter {
<ide> }
<ide>
<ide> this._menuItems.set(title, handler);
<del> this.addListener('didPressMenuItem', event => {
<add> this.addListener('didPressMenuItem', (event) => {
<ide> if (event.title === title) {
<ide> handler();
<ide> }
<ide><path>Libraries/Utilities/HMRClient.js
<ide> const HMRClient: HMRClientNativeInterface = {
<ide> JSON.stringify({
<ide> type: 'log',
<ide> level,
<del> data: data.map(item =>
<add> data: data.map((item) =>
<ide> typeof item === 'string'
<ide> ? item
<ide> : prettyFormat(item, {
<ide> const HMRClient: HMRClientNativeInterface = {
<ide> `ws://${wsHost}/hot?bundleEntry=${bundleEntry}&platform=${platform}`,
<ide> );
<ide>
<del> client.on('connection-error', e => {
<add> client.on('connection-error', (e) => {
<ide> let error = `Cannot connect to the Metro server.
<ide>
<ide> Try the following to fix the issue:
<ide> Error: ${e.message}`;
<ide> LoadingView.hide();
<ide> });
<ide>
<del> client.on('error', data => {
<add> client.on('error', (data) => {
<ide> LoadingView.hide();
<ide>
<ide> if (data.type === 'GraphNotFoundError') {
<ide> Error: ${e.message}`;
<ide> }
<ide> });
<ide>
<del> client.on('close', data => {
<add> client.on('close', (data) => {
<ide> LoadingView.hide();
<ide> setHMRUnavailableReason('Disconnected from the Metro server.');
<ide> });
<ide><path>Libraries/Utilities/JSDevSupportModule.js
<ide> import NativeJSDevSupport from './NativeJSDevSupport';
<ide> const ReactNative = require('../Renderer/shims/ReactNative');
<ide>
<ide> const JSDevSupportModule = {
<del> getJSHierarchy: function(tag: number) {
<add> getJSHierarchy: function (tag: number) {
<ide> if (NativeJSDevSupport) {
<ide> const constants = NativeJSDevSupport.getConstants();
<ide> try {
<ide><path>Libraries/Utilities/MatrixMath.js
<ide> const invariant = require('invariant');
<ide> * matrices, which are reusable.
<ide> */
<ide> const MatrixMath = {
<del> createIdentityMatrix: function() {
<add> createIdentityMatrix: function () {
<ide> return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
<ide> },
<ide>
<del> createCopy: function(m) {
<add> createCopy: function (m) {
<ide> return [
<ide> m[0],
<ide> m[1],
<ide> const MatrixMath = {
<ide> ];
<ide> },
<ide>
<del> createOrthographic: function(left, right, bottom, top, near, far) {
<add> createOrthographic: function (left, right, bottom, top, near, far) {
<ide> const a = 2 / (right - left);
<ide> const b = 2 / (top - bottom);
<ide> const c = -2 / (far - near);
<ide> const MatrixMath = {
<ide> return [a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, tx, ty, tz, 1];
<ide> },
<ide>
<del> createFrustum: function(left, right, bottom, top, near, far) {
<add> createFrustum: function (left, right, bottom, top, near, far) {
<ide> const r_width = 1 / (right - left);
<ide> const r_height = 1 / (top - bottom);
<ide> const r_depth = 1 / (near - far);
<ide> const MatrixMath = {
<ide> *
<ide> * @param fovInRadians - field of view in randians
<ide> */
<del> createPerspective: function(fovInRadians, aspect, near, far) {
<add> createPerspective: function (fovInRadians, aspect, near, far) {
<ide> const h = 1 / Math.tan(fovInRadians / 2);
<ide> const r_depth = 1 / (near - far);
<ide> const C = (far + near) * r_depth;
<ide> const D = 2 * (far * near * r_depth);
<ide> return [h / aspect, 0, 0, 0, 0, h, 0, 0, 0, 0, C, -1, 0, 0, D, 0];
<ide> },
<ide>
<del> createTranslate2d: function(x, y) {
<add> createTranslate2d: function (x, y) {
<ide> const mat = MatrixMath.createIdentityMatrix();
<ide> MatrixMath.reuseTranslate2dCommand(mat, x, y);
<ide> return mat;
<ide> },
<ide>
<del> reuseTranslate2dCommand: function(matrixCommand, x, y) {
<add> reuseTranslate2dCommand: function (matrixCommand, x, y) {
<ide> matrixCommand[12] = x;
<ide> matrixCommand[13] = y;
<ide> },
<ide>
<del> reuseTranslate3dCommand: function(matrixCommand, x, y, z) {
<add> reuseTranslate3dCommand: function (matrixCommand, x, y, z) {
<ide> matrixCommand[12] = x;
<ide> matrixCommand[13] = y;
<ide> matrixCommand[14] = z;
<ide> },
<ide>
<del> createScale: function(factor) {
<add> createScale: function (factor) {
<ide> const mat = MatrixMath.createIdentityMatrix();
<ide> MatrixMath.reuseScaleCommand(mat, factor);
<ide> return mat;
<ide> },
<ide>
<del> reuseScaleCommand: function(matrixCommand, factor) {
<add> reuseScaleCommand: function (matrixCommand, factor) {
<ide> matrixCommand[0] = factor;
<ide> matrixCommand[5] = factor;
<ide> },
<ide>
<del> reuseScale3dCommand: function(matrixCommand, x, y, z) {
<add> reuseScale3dCommand: function (matrixCommand, x, y, z) {
<ide> matrixCommand[0] = x;
<ide> matrixCommand[5] = y;
<ide> matrixCommand[10] = z;
<ide> },
<ide>
<del> reusePerspectiveCommand: function(matrixCommand, p) {
<add> reusePerspectiveCommand: function (matrixCommand, p) {
<ide> matrixCommand[11] = -1 / p;
<ide> },
<ide>
<ide> const MatrixMath = {
<ide> matrixCommand[10] = factor;
<ide> },
<ide>
<del> reuseRotateXCommand: function(matrixCommand, radians) {
<add> reuseRotateXCommand: function (matrixCommand, radians) {
<ide> matrixCommand[5] = Math.cos(radians);
<ide> matrixCommand[6] = Math.sin(radians);
<ide> matrixCommand[9] = -Math.sin(radians);
<ide> matrixCommand[10] = Math.cos(radians);
<ide> },
<ide>
<del> reuseRotateYCommand: function(matrixCommand, amount) {
<add> reuseRotateYCommand: function (matrixCommand, amount) {
<ide> matrixCommand[0] = Math.cos(amount);
<ide> matrixCommand[2] = -Math.sin(amount);
<ide> matrixCommand[8] = Math.sin(amount);
<ide> matrixCommand[10] = Math.cos(amount);
<ide> },
<ide>
<ide> // http://www.w3.org/TR/css3-transforms/#recomposing-to-a-2d-matrix
<del> reuseRotateZCommand: function(matrixCommand, radians) {
<add> reuseRotateZCommand: function (matrixCommand, radians) {
<ide> matrixCommand[0] = Math.cos(radians);
<ide> matrixCommand[1] = Math.sin(radians);
<ide> matrixCommand[4] = -Math.sin(radians);
<ide> matrixCommand[5] = Math.cos(radians);
<ide> },
<ide>
<del> createRotateZ: function(radians) {
<add> createRotateZ: function (radians) {
<ide> const mat = MatrixMath.createIdentityMatrix();
<ide> MatrixMath.reuseRotateZCommand(mat, radians);
<ide> return mat;
<ide> },
<ide>
<del> reuseSkewXCommand: function(matrixCommand, radians) {
<add> reuseSkewXCommand: function (matrixCommand, radians) {
<ide> matrixCommand[4] = Math.tan(radians);
<ide> },
<ide>
<del> reuseSkewYCommand: function(matrixCommand, radians) {
<add> reuseSkewYCommand: function (matrixCommand, radians) {
<ide> matrixCommand[1] = Math.tan(radians);
<ide> },
<ide>
<del> multiplyInto: function(out, a, b) {
<add> multiplyInto: function (out, a, b) {
<ide> const a00 = a[0],
<ide> a01 = a[1],
<ide> a02 = a[2],
<ide><path>Libraries/Utilities/ReactNativeTestTools.js
<ide> const {
<ide>
<ide> function byClickable(): Predicate {
<ide> return withMessage(
<del> node =>
<add> (node) =>
<ide> // note: <Text /> lazy-mounts press handlers after the first press,
<ide> // so this is a workaround for targeting text nodes.
<ide> (node.type === Text &&
<ide> function byClickable(): Predicate {
<ide>
<ide> function byTestID(testID: string): Predicate {
<ide> return withMessage(
<del> node => node.props && node.props.testID === testID,
<add> (node) => node.props && node.props.testID === testID,
<ide> `testID prop equals ${testID}`,
<ide> );
<ide> }
<ide> function byTextMatching(regex: RegExp): Predicate {
<ide> /* $FlowFixMe(>=0.120.0) This comment suppresses an error found when Flow
<ide> * v0.120 was deployed. To see the error, delete this comment and run Flow.
<ide> */
<del> node => node.props && regex.exec(node.props.children),
<add> (node) => node.props && regex.exec(node.props.children),
<ide> `text content matches ${regex.toString()}`,
<ide> );
<ide> }
<ide> function maximumDepthOfJSON(node: ?ReactTestRendererJSON): number {
<ide> return 1;
<ide> } else {
<ide> let maxDepth = 0;
<del> node.children.forEach(child => {
<add> node.children.forEach((child) => {
<ide> maxDepth = Math.max(maximumDepthOfJSON(child) + 1, maxDepth);
<ide> });
<ide> return maxDepth;
<ide> function renderAndEnforceStrictMode(element: React.Node): any {
<ide> }
<ide>
<ide> function renderWithStrictMode(element: React.Node): ReactTestRendererType {
<del> const WorkAroundBugWithStrictModeInTestRenderer = prps => prps.children;
<add> const WorkAroundBugWithStrictModeInTestRenderer = (prps) => prps.children;
<ide> const StrictMode = (React: $FlowFixMe).StrictMode;
<ide> return ReactTestRenderer.create(
<ide> <WorkAroundBugWithStrictModeInTestRenderer>
<ide><path>Libraries/Utilities/SceneTracker.js
<ide> let _activeScene = {name: 'default'};
<ide> const SceneTracker = {
<ide> setActiveScene(scene: Scene) {
<ide> _activeScene = scene;
<del> _listeners.forEach(listener => listener(_activeScene));
<add> _listeners.forEach((listener) => listener(_activeScene));
<ide> },
<ide>
<ide> getActiveScene(): Scene {
<ide> const SceneTracker = {
<ide> _listeners.push(callback);
<ide> return {
<ide> remove: () => {
<del> _listeners = _listeners.filter(listener => callback !== listener);
<add> _listeners = _listeners.filter((listener) => callback !== listener);
<ide> },
<ide> };
<ide> },
<ide><path>Libraries/Utilities/__mocks__/BackHandler.js
<ide> const _backPressSubscriptions = new Set();
<ide> const BackHandler = {
<ide> exitApp: jest.fn(),
<ide>
<del> addEventListener: function(
<add> addEventListener: function (
<ide> eventName: BackPressEventName,
<ide> handler: Function,
<ide> ): {remove: () => void} {
<ide> const BackHandler = {
<ide> };
<ide> },
<ide>
<del> removeEventListener: function(
<add> removeEventListener: function (
<ide> eventName: BackPressEventName,
<ide> handler: Function,
<ide> ): void {
<ide> _backPressSubscriptions.delete(handler);
<ide> },
<ide>
<del> mockPressBack: function() {
<add> mockPressBack: function () {
<ide> let invokeDefault = true;
<ide> const subscriptions = [..._backPressSubscriptions].reverse();
<ide> for (let i = 0; i < subscriptions.length; ++i) {
<ide><path>Libraries/Utilities/__mocks__/PixelRatio.js
<ide> const PixelRatio = {
<ide> get: jest.fn().mockReturnValue(2),
<ide> getFontScale: jest.fn(() => PixelRatio.get()),
<del> getPixelSizeForLayoutSize: jest.fn(layoutSize =>
<add> getPixelSizeForLayoutSize: jest.fn((layoutSize) =>
<ide> Math.round(layoutSize * PixelRatio.get()),
<ide> ),
<del> roundToNearestPixel: jest.fn(layoutSize => {
<add> roundToNearestPixel: jest.fn((layoutSize) => {
<ide> const ratio = PixelRatio.get();
<ide> return Math.round(layoutSize * ratio) / ratio;
<ide> }),
<ide><path>Libraries/Utilities/__tests__/MatrixMath-test.js
<ide> function degreesToRadians(degrees) {
<ide> }
<ide>
<ide> function convertZeroes(degrees) {
<del> return degrees.map(value => (value === -0 ? 0 : value));
<add> return degrees.map((value) => (value === -0 ? 0 : value));
<ide> }
<ide>
<ide> describe('MatrixMath', () => {
<ide> describe('MatrixMath', () => {
<ide> ]).rotationDegrees,
<ide> ).toEqual([0, 0, 0]);
<ide>
<del> [30, 45, 60, 75, 90, 100, 115, 120, 133, 167].forEach(angle => {
<add> [30, 45, 60, 75, 90, 100, 115, 120, 133, 167].forEach((angle) => {
<ide> let mat = MatrixMath.createRotateZ(degreesToRadians(angle));
<ide> expect(
<ide> convertZeroes(MatrixMath.decomposeMatrix(mat).rotationDegrees),
<ide> describe('MatrixMath', () => {
<ide>
<ide> it('decomposes a 4x4 matrix to produce accurate Y-axis angles', () => {
<ide> let mat;
<del> [30, 45, 60, 75, 90, 100, 110, 120, 133, 167].forEach(angle => {
<add> [30, 45, 60, 75, 90, 100, 110, 120, 133, 167].forEach((angle) => {
<ide> mat = MatrixMath.createIdentityMatrix();
<ide> MatrixMath.reuseRotateYCommand(mat, degreesToRadians(angle));
<ide> expect(
<ide> describe('MatrixMath', () => {
<ide>
<ide> it('decomposes a 4x4 matrix to produce accurate X-axis angles', () => {
<ide> let mat;
<del> [30, 45, 60, 75, 90, 100, 110, 120, 133, 167].forEach(angle => {
<add> [30, 45, 60, 75, 90, 100, 110, 120, 133, 167].forEach((angle) => {
<ide> mat = MatrixMath.createIdentityMatrix();
<ide> MatrixMath.reuseRotateXCommand(mat, degreesToRadians(angle));
<ide> expect(
<ide><path>Libraries/Utilities/__tests__/SceneTracker-test.js
<ide>
<ide> const SceneTracker = require('../SceneTracker');
<ide>
<del>describe('setActiveScene', function() {
<del> it('can handle multiple listeners and unsubscribe', function() {
<add>describe('setActiveScene', function () {
<add> it('can handle multiple listeners and unsubscribe', function () {
<ide> const listeners = [jest.fn(), jest.fn(), jest.fn()];
<del> const subscriptions = listeners.map(listener =>
<add> const subscriptions = listeners.map((listener) =>
<ide> SceneTracker.addActiveSceneChangedListener(listener),
<ide> );
<ide> subscriptions[1].remove();
<ide><path>Libraries/Utilities/__tests__/buildStyleInterpolator-test.js
<ide>
<ide> const buildStyleInterpolator = require('../buildStyleInterpolator');
<ide>
<del>const validateEmpty = function(interpolator, value, validator) {
<add>const validateEmpty = function (interpolator, value, validator) {
<ide> const emptyObject = {};
<ide> let changed = interpolator(emptyObject, value);
<ide> validator(emptyObject);
<ide> expect(changed).toBe(true);
<ide> changed = interpolator(emptyObject, value);
<ide> expect(changed).toBe(false);
<ide> };
<del>describe('buildStyleInterpolator', function() {
<del> it('should linearly interpolate without extrapolating', function() {
<add>describe('buildStyleInterpolator', function () {
<add> it('should linearly interpolate without extrapolating', function () {
<ide> const testAnim = {
<ide> opacity: {
<ide> from: 100,
<ide> describe('buildStyleInterpolator', function() {
<ide> },
<ide> };
<ide> const interpolator = buildStyleInterpolator(testAnim);
<del> validateEmpty(interpolator, 0, function(res) {
<add> validateEmpty(interpolator, 0, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 100,
<ide> left: 200,
<ide> top: 23.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, 1, function(res) {
<add> validateEmpty(interpolator, 1, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 200,
<ide> left: 300,
<ide> top: 23.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, -0.1, function(res) {
<add> validateEmpty(interpolator, -0.1, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 100,
<ide> left: 200,
<ide> top: 23.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, 1.1, function(res) {
<add> validateEmpty(interpolator, 1.1, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 200,
<ide> left: 300,
<ide> top: 23.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, 0.5, function(res) {
<add> validateEmpty(interpolator, 0.5, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 150,
<ide> left: 250,
<ide> top: 23.5,
<ide> });
<ide> });
<ide> });
<del> it('should linearly interpolate with extrapolating', function() {
<add> it('should linearly interpolate with extrapolating', function () {
<ide> const testAnim = {
<ide> opacity: {
<ide> from: 100,
<ide> describe('buildStyleInterpolator', function() {
<ide> },
<ide> };
<ide> const interpolator = buildStyleInterpolator(testAnim);
<del> validateEmpty(interpolator, 0, function(res) {
<add> validateEmpty(interpolator, 0, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 100,
<ide> left: 200,
<ide> top: 23.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, 1, function(res) {
<add> validateEmpty(interpolator, 1, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 200,
<ide> left: 300,
<ide> top: 23.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, -0.1, function(res) {
<add> validateEmpty(interpolator, -0.1, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 90,
<ide> left: 190,
<ide> top: 23.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, 1.1, function(res) {
<add> validateEmpty(interpolator, 1.1, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 210,
<ide> left: 310,
<ide> top: 23.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, 0.5, function(res) {
<add> validateEmpty(interpolator, 0.5, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 150,
<ide> left: 250,
<ide> top: 23.5,
<ide> });
<ide> });
<ide> });
<del> it('should round accordingly', function() {
<add> it('should round accordingly', function () {
<ide> const testAnim = {
<ide> opacity: {
<ide> from: 0,
<ide> describe('buildStyleInterpolator', function() {
<ide> },
<ide> };
<ide> const interpolator = buildStyleInterpolator(testAnim);
<del> validateEmpty(interpolator, 0, function(res) {
<add> validateEmpty(interpolator, 0, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 0,
<ide> });
<ide> });
<del> validateEmpty(interpolator, 0.5, function(res) {
<add> validateEmpty(interpolator, 0.5, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 0.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, 0.4, function(res) {
<add> validateEmpty(interpolator, 0.4, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 0.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, 0.26, function(res) {
<add> validateEmpty(interpolator, 0.26, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 0.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, 0.74, function(res) {
<add> validateEmpty(interpolator, 0.74, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 0.5,
<ide> });
<ide> });
<del> validateEmpty(interpolator, 0.76, function(res) {
<add> validateEmpty(interpolator, 0.76, function (res) {
<ide> expect(res).toEqual({
<ide> opacity: 1.0,
<ide> });
<ide> });
<ide> });
<del> it('should detect changes correctly', function() {
<add> it('should detect changes correctly', function () {
<ide> const testAnim = {
<ide> opacity: {
<ide> from: 0,
<ide> describe('buildStyleInterpolator', function() {
<ide> });
<ide> expect(res).toBe(false);
<ide> });
<del> it('should handle identity', function() {
<add> it('should handle identity', function () {
<ide> const testAnim = {
<ide> opacity: {
<ide> type: 'identity',
<ide> describe('buildStyleInterpolator', function() {
<ide> });
<ide> expect(res).toBe(false);
<ide> });
<del> it('should translate', function() {
<add> it('should translate', function () {
<ide> const testAnim = {
<ide> transformTranslate: {
<ide> from: {x: 1, y: 10, z: 100},
<ide> describe('buildStyleInterpolator', function() {
<ide> });
<ide> expect(res).toBe(true);
<ide> });
<del> it('should scale', function() {
<add> it('should scale', function () {
<ide> const testAnim = {
<ide> transformScale: {
<ide> from: {x: 1, y: 10, z: 100},
<ide> describe('buildStyleInterpolator', function() {
<ide> });
<ide> expect(res).toBe(true);
<ide> });
<del> it('should combine scale and translate', function() {
<add> it('should combine scale and translate', function () {
<ide> const testAnim = {
<ide> transformScale: {
<ide> from: {x: 1, y: 10, z: 100},
<ide> describe('buildStyleInterpolator', function() {
<ide> });
<ide> expect(res).toBe(true);
<ide> });
<del> it('should step', function() {
<add> it('should step', function () {
<ide> const testAnim = {
<ide> opacity: {
<ide> threshold: 13,
<ide><path>Libraries/Utilities/__tests__/codegenNativeComponent-test.js
<ide> const {UIManager} = require('react-native');
<ide> jest.unmock('../../ReactNative/requireNativeComponent');
<ide> jest.mock(
<ide> '../../Renderer/shims/createReactNativeComponentClass',
<del> () => componentName => componentName,
<add> () => (componentName) => componentName,
<ide> );
<ide> jest
<ide> .spyOn(UIManager, 'getViewManagerConfig')
<del> .mockImplementation(componentName =>
<add> .mockImplementation((componentName) =>
<ide> componentName.includes('ComponentNameDoesNotExist') ? false : true,
<ide> );
<ide>
<ide><path>Libraries/Utilities/__tests__/deepFreezeAndThrowOnMutationInDev-test.js
<ide>
<ide> const deepFreezeAndThrowOnMutationInDev = require('../deepFreezeAndThrowOnMutationInDev');
<ide>
<del>describe('deepFreezeAndThrowOnMutationInDev', function() {
<add>describe('deepFreezeAndThrowOnMutationInDev', function () {
<ide> it('should be a noop on non object values', () => {
<ide> __DEV__ = true;
<ide> expect(() => deepFreezeAndThrowOnMutationInDev('')).not.toThrow();
<ide><path>Libraries/Utilities/__tests__/mapWithSeparator-test.js
<ide> describe('mapWithSeparator', () => {
<ide> const array = [1, 2, 3];
<ide> const result = mapWithSeparator(
<ide> array,
<del> function(value) {
<add> function (value) {
<ide> return value * 2;
<ide> },
<del> function() {
<add> function () {
<ide> return 0;
<ide> },
<ide> );
<ide> describe('mapWithSeparator', () => {
<ide> const array = [1, 2, 3];
<ide> const result = mapWithSeparator(
<ide> array,
<del> function(value, index) {
<add> function (value, index) {
<ide> return index;
<ide> },
<del> function(index) {
<add> function (index) {
<ide> return index;
<ide> },
<ide> );
<ide> describe('mapWithSeparator', () => {
<ide> const array = [3, 2, 1];
<ide> const result = mapWithSeparator(
<ide> array,
<del> function(value, index, arr) {
<add> function (value, index, arr) {
<ide> return arr[index];
<ide> },
<del> function(index) {
<add> function (index) {
<ide> return index;
<ide> },
<ide> );
<ide> describe('mapWithSeparator', () => {
<ide> const array = [];
<ide> const result = mapWithSeparator(
<ide> array,
<del> function(value) {
<add> function (value) {
<ide> return value * 2;
<ide> },
<del> function() {
<add> function () {
<ide> return 0;
<ide> },
<ide> );
<ide><path>Libraries/Utilities/__tests__/setAndForwardRef-test.js
<ide> describe('setAndForwardRef', () => {
<ide> _nativeRef: ?React.ElementRef<typeof ForwardedComponent> = null;
<ide> _setNativeRef = setAndForwardRef({
<ide> getForwardedRef: () => this.props.forwardedRef,
<del> setLocalRef: ref => {
<add> setLocalRef: (ref) => {
<ide> this._nativeRef = ref;
<ide> },
<ide> });
<ide> describe('setAndForwardRef', () => {
<ide>
<ide> ReactTestRenderer.create(
<ide> <TestComponentWithRef
<del> ref={ref => {
<add> ref={(ref) => {
<ide> testRef = ref;
<ide> }}
<ide> />,
<ide><path>Libraries/Utilities/__tests__/stringifySafe-test.js
<ide> describe('stringifySafe', () => {
<ide> });
<ide>
<ide> it('stringifySafe stringifies function values', () => {
<del> expect(stringifySafe(function() {})).toEqual('function () {}');
<add> expect(stringifySafe(function () {})).toEqual('function () {}');
<ide> });
<ide>
<ide> it('stringifySafe stringifies non-circular objects', () => {
<ide><path>Libraries/Utilities/buildStyleInterpolator.js
<ide> const InitialOperationField = {
<ide> };
<ide>
<ide> const InterpolateMatrix = {
<del> transformScale: function(mat, x, y, z) {
<add> transformScale: function (mat, x, y, z) {
<ide> mat[0] = mat[0] * x;
<ide> mat[1] = mat[1] * x;
<ide> mat[2] = mat[2] * x;
<ide> const InterpolateMatrix = {
<ide> mat[10] = mat[10] * z;
<ide> mat[11] = mat[11] * z;
<ide> },
<del> transformTranslate: function(mat, x, y, z) {
<add> transformTranslate: function (mat, x, y, z) {
<ide> mat[12] = mat[0] * x + mat[4] * y + mat[8] * z + mat[12];
<ide> mat[13] = mat[1] * x + mat[5] * y + mat[9] * z + mat[13];
<ide> mat[14] = mat[2] * x + mat[6] * y + mat[10] * z + mat[14];
<ide> mat[15] = mat[3] * x + mat[7] * y + mat[11] * z + mat[15];
<ide> },
<ide> };
<ide>
<del>const computeNextValLinear = function(anim, from, to, value) {
<add>const computeNextValLinear = function (anim, from, to, value) {
<ide> const hasRoundRatio = 'round' in anim;
<ide> const roundRatio = anim.round;
<ide> let ratio = (value - anim.min) / (anim.max - anim.min);
<ide> const computeNextValLinear = function(anim, from, to, value) {
<ide> return nextVal;
<ide> };
<ide>
<del>const computeNextValLinearScalar = function(anim, value) {
<add>const computeNextValLinearScalar = function (anim, value) {
<ide> return computeNextValLinear(anim, anim.from, anim.to, value);
<ide> };
<ide>
<del>const setNextValAndDetectChange = function(result, name, nextVal, didChange) {
<add>const setNextValAndDetectChange = function (result, name, nextVal, didChange) {
<ide> if (!didChange) {
<ide> const prevVal = result[name];
<ide> result[name] = nextVal;
<ide> const setNextValAndDetectChange = function(result, name, nextVal, didChange) {
<ide> return didChange;
<ide> };
<ide>
<del>const initIdentity = function(mat) {
<add>const initIdentity = function (mat) {
<ide> mat[0] = 1;
<ide> mat[1] = 0;
<ide> mat[2] = 0;
<ide> const initIdentity = function(mat) {
<ide> mat[15] = 1;
<ide> };
<ide>
<del>const computeNextMatrixOperationField = function(
<add>const computeNextMatrixOperationField = function (
<ide> anim,
<ide> name,
<ide> dim,
<ide> const computeNextMatrixOperationField = function(
<ide> }
<ide> };
<ide>
<del>const computeTransform = function(
<add>const computeTransform = function (
<ide> anim,
<ide> name,
<ide> value,
<ide> const computeTransform = function(
<ide> * @return {function} Function accepting style object, that mutates that style
<ide> * object and returns a boolean describing if any update was actually applied.
<ide> */
<del>const buildStyleInterpolator = function(anims) {
<add>const buildStyleInterpolator = function (anims) {
<ide> function styleInterpolator(result, value) {
<ide> let didChange = false;
<ide> let didMatrix = false;
<ide><path>Libraries/Utilities/codegenNativeCommands.js
<ide> type Options<T = string> = $ReadOnly<{|
<ide> function codegenNativeCommands<T: {...}>(options: Options<$Keys<T>>): T {
<ide> const commandObj = {};
<ide>
<del> options.supportedCommands.forEach(command => {
<add> options.supportedCommands.forEach((command) => {
<ide> commandObj[command] = (ref, ...args) => {
<ide> dispatchCommand(ref, command, args);
<ide> };
<ide><path>Libraries/Utilities/codegenNativeComponent.js
<ide> function codegenNativeComponent<Props>(
<ide> componentNameInUse = options.paperComponentNameDeprecated;
<ide> } else {
<ide> throw new Error(
<del> `Failed to find native component for either ${componentName} or ${options.paperComponentNameDeprecated ||
<del> '(unknown)'}`,
<add> `Failed to find native component for either ${componentName} or ${
<add> options.paperComponentNameDeprecated || '(unknown)'
<add> }`,
<ide> );
<ide> }
<ide> }
<ide><path>Libraries/Utilities/createPerformanceLogger.js
<ide> function createPerformanceLogger(): IPerformanceLogger {
<ide> },
<ide>
<ide> clearExceptTimespans(keys: Array<string>) {
<del> this._timespans = Object.keys(this._timespans).reduce(function(
<add> this._timespans = Object.keys(this._timespans).reduce(function (
<ide> previous,
<ide> key,
<ide> ) {
<ide><path>Libraries/Utilities/differ/__tests__/deepDiffer-test.js
<ide>
<ide> const deepDiffer = require('../deepDiffer');
<ide>
<del>describe('deepDiffer', function() {
<add>describe('deepDiffer', function () {
<ide> it('should diff primitives of the same type', () => {
<ide> expect(deepDiffer(1, 2)).toBe(true);
<ide> expect(deepDiffer(42, 42)).toBe(false);
<ide> describe('deepDiffer', function() {
<ide> ).toBe(false);
<ide> });
<ide> it('should consider all functions equal', () => {
<del> expect(deepDiffer(() => {}, x => x)).toBe(false);
<add> expect(
<add> deepDiffer(
<add> () => {},
<add> (x) => x,
<add> ),
<add> ).toBe(false);
<ide> const f = () => {};
<ide> expect(deepDiffer(f, f)).toBe(false);
<ide> });
<ide> it('should compare functions if unsafelyIgnoreFunctions is false', () => {
<ide> expect(
<del> deepDiffer(() => {}, x => x, undefined, {unsafelyIgnoreFunctions: false}),
<add> deepDiffer(
<add> () => {},
<add> (x) => x,
<add> undefined,
<add> {unsafelyIgnoreFunctions: false},
<add> ),
<ide> ).toBe(true);
<ide> const f = () => {};
<ide> expect(deepDiffer(f, f, undefined, {unsafelyIgnoreFunctions: false})).toBe(
<ide> false,
<ide> );
<ide>
<ide> // shorthand, omitting maxDepth
<del> expect(deepDiffer(() => {}, x => x, {unsafelyIgnoreFunctions: false})).toBe(
<del> true,
<del> );
<add> expect(
<add> deepDiffer(
<add> () => {},
<add> (x) => x,
<add> {unsafelyIgnoreFunctions: false},
<add> ),
<add> ).toBe(true);
<ide> expect(deepDiffer(f, f, {unsafelyIgnoreFunctions: false})).toBe(false);
<ide> });
<ide> it('should log when implicitly considering two different functions equal', () => {
<ide><path>Libraries/Utilities/differ/__tests__/matricesDiffer-test.js
<ide>
<ide> const matricesDiffer = require('../matricesDiffer');
<ide>
<del>describe('matricesDiffer', function() {
<add>describe('matricesDiffer', function () {
<ide> it('diffs matrices with single element', () => {
<ide> var x = [1];
<ide> var y = [2];
<ide><path>Libraries/Utilities/differ/deepDiffer.js
<ide> function unstable_setLogListeners(listeners: ?LogListeners) {
<ide> /*
<ide> * @returns {bool} true if different, false if equal
<ide> */
<del>const deepDiffer = function(
<add>const deepDiffer = function (
<ide> one: any,
<ide> two: any,
<ide> maxDepthOrOptions: Options | number = -1,
<ide><path>Libraries/Utilities/differ/insetsDiffer.js
<ide> const dummyInsets = {
<ide> bottom: undefined,
<ide> };
<ide>
<del>const insetsDiffer = function(one: Inset, two: Inset): boolean {
<add>const insetsDiffer = function (one: Inset, two: Inset): boolean {
<ide> one = one || dummyInsets;
<ide> two = two || dummyInsets;
<ide> return (
<ide><path>Libraries/Utilities/differ/matricesDiffer.js
<ide> * @param {MatrixMath.Matrix} two Second matrix.
<ide> * @return {boolean} Whether or not the two matrices differ.
<ide> */
<del>const matricesDiffer = function(one, two) {
<add>const matricesDiffer = function (one, two) {
<ide> if (one === two) {
<ide> return false;
<ide> }
<ide><path>Libraries/Utilities/differ/pointsDiffer.js
<ide> type Point = {
<ide>
<ide> const dummyPoint = {x: undefined, y: undefined};
<ide>
<del>const pointsDiffer = function(one: ?Point, two: ?Point): boolean {
<add>const pointsDiffer = function (one: ?Point, two: ?Point): boolean {
<ide> one = one || dummyPoint;
<ide> two = two || dummyPoint;
<ide> return one !== two && (one.x !== two.x || one.y !== two.y);
<ide><path>Libraries/Utilities/differ/sizesDiffer.js
<ide>
<ide> const dummySize = {width: undefined, height: undefined};
<ide>
<del>const sizesDiffer = function(one, two) {
<add>const sizesDiffer = function (one, two) {
<ide> one = one || dummySize;
<ide> two = two || dummySize;
<ide> return one !== two && (one.width !== two.width || one.height !== two.height);
<ide><path>Libraries/Utilities/logError.js
<ide> * `console.error` as a failure callback - it's not properly bound. If passes an
<ide> * `Error` object, it will print the message and stack.
<ide> */
<del>const logError = function(...args: $ReadOnlyArray<mixed>) {
<add>const logError = function (...args: $ReadOnlyArray<mixed>) {
<ide> if (args.length === 1 && args[0] instanceof Error) {
<ide> const err = args[0];
<ide> console.error('Error: "' + err.message + '". Stack:\n' + err.stack);
<ide><path>Libraries/Utilities/mergeIntoFast.js
<ide> * @param {object} one Object to assign to.
<ide> * @param {object} two Object to assign from.
<ide> */
<del>const mergeIntoFast = function(one: Object, two: Object): void {
<add>const mergeIntoFast = function (one: Object, two: Object): void {
<ide> for (const keyTwo in two) {
<ide> one[keyTwo] = two[keyTwo];
<ide> }
<ide><path>Libraries/Utilities/stringifySafe.js
<ide> export function createStringifySafeWithLimits(limits: {|
<ide> maxStringLimit?: number,
<ide> maxArrayLimit?: number,
<ide> maxObjectKeysLimit?: number,
<del>|}): mixed => string {
<add>|}): (mixed) => string {
<ide> const {
<ide> maxDepth = Number.POSITIVE_INFINITY,
<ide> maxStringLimit = Number.POSITIVE_INFINITY,
<ide> export function createStringifySafeWithLimits(limits: {|
<ide> };
<ide> }
<ide>
<del>const stringifySafe: mixed => string = createStringifySafeWithLimits({
<add>const stringifySafe: (mixed) => string = createStringifySafeWithLimits({
<ide> maxDepth: 10,
<ide> maxStringLimit: 100,
<ide> maxArrayLimit: 50,
<ide><path>Libraries/Utilities/truncate.js
<ide> const defaultOptions = {
<ide> };
<ide>
<ide> // maxChars (including ellipsis)
<del>const truncate = function(
<add>const truncate = function (
<ide> str: ?string,
<ide> maxChars: number,
<ide> options?: truncateOptions,
<ide><path>Libraries/Utilities/useColorScheme.js
<ide> export default function useColorScheme(): ?ColorSchemeName {
<ide> const subscription = useMemo(
<ide> () => ({
<ide> getCurrentValue: () => Appearance.getColorScheme(),
<del> subscribe: callback => {
<add> subscribe: (callback) => {
<ide> Appearance.addChangeListener(callback);
<ide> return () => Appearance.removeChangeListener(callback);
<ide> },
<ide><path>Libraries/Utilities/verifyComponentAttributeEquivalence.js
<ide> function verifyComponentAttributeEquivalence(
<ide> const nativeAttributes = getNativeComponentAttributes(componentName);
<ide>
<ide> ['validAttributes', 'bubblingEventTypes', 'directEventTypes'].forEach(
<del> prop => {
<add> (prop) => {
<ide> const diffKeys = Object.keys(
<ide> lefthandObjectDiff(nativeAttributes[prop], config[prop]),
<ide> );
<ide> export function getConfigWithoutViewProps(
<ide> }
<ide>
<ide> return Object.keys(viewConfig[propName])
<del> .filter(prop => !ReactNativeViewViewConfig[propName][prop])
<add> .filter((prop) => !ReactNativeViewViewConfig[propName][prop])
<ide> .reduce((obj, prop) => {
<ide> obj[prop] = viewConfig[propName][prop];
<ide> return obj;
<ide><path>Libraries/Vibration/Vibration.js
<ide> const Vibration = {
<ide> *
<ide> * See https://reactnative.dev/docs/vibration.html#vibrate
<ide> */
<del> vibrate: function(
<add> vibrate: function (
<ide> pattern: number | Array<number> = 400,
<ide> repeat: boolean = false,
<ide> ) {
<ide> const Vibration = {
<ide> *
<ide> * See https://reactnative.dev/docs/vibration.html#cancel
<ide> */
<del> cancel: function() {
<add> cancel: function () {
<ide> if (Platform.OS === 'ios') {
<ide> _vibrating = false;
<ide> } else {
<ide><path>Libraries/WebSocket/WebSocket.js
<ide> class WebSocket extends (EventTarget(...WEBSOCKET_EVENTS): any) {
<ide> }
<ide>
<ide> _unregisterEvents(): void {
<del> this._subscriptions.forEach(e => e.remove());
<add> this._subscriptions.forEach((e) => e.remove());
<ide> this._subscriptions = [];
<ide> }
<ide>
<ide> _registerEvents(): void {
<ide> this._subscriptions = [
<del> this._eventEmitter.addListener('websocketMessage', ev => {
<add> this._eventEmitter.addListener('websocketMessage', (ev) => {
<ide> if (ev.id !== this._socketId) {
<ide> return;
<ide> }
<ide> class WebSocket extends (EventTarget(...WEBSOCKET_EVENTS): any) {
<ide> }
<ide> this.dispatchEvent(new WebSocketEvent('message', {data}));
<ide> }),
<del> this._eventEmitter.addListener('websocketOpen', ev => {
<add> this._eventEmitter.addListener('websocketOpen', (ev) => {
<ide> if (ev.id !== this._socketId) {
<ide> return;
<ide> }
<ide> this.readyState = this.OPEN;
<ide> this.protocol = ev.protocol;
<ide> this.dispatchEvent(new WebSocketEvent('open'));
<ide> }),
<del> this._eventEmitter.addListener('websocketClosed', ev => {
<add> this._eventEmitter.addListener('websocketClosed', (ev) => {
<ide> if (ev.id !== this._socketId) {
<ide> return;
<ide> }
<ide> class WebSocket extends (EventTarget(...WEBSOCKET_EVENTS): any) {
<ide> this._unregisterEvents();
<ide> this.close();
<ide> }),
<del> this._eventEmitter.addListener('websocketFailed', ev => {
<add> this._eventEmitter.addListener('websocketFailed', (ev) => {
<ide> if (ev.id !== this._socketId) {
<ide> return;
<ide> }
<ide><path>Libraries/WebSocket/WebSocketInterceptor.js
<ide> const WebSocketInterceptor = {
<ide> },
<ide>
<ide> _unregisterEvents() {
<del> subscriptions.forEach(e => e.remove());
<add> subscriptions.forEach((e) => e.remove());
<ide> subscriptions = [];
<ide> },
<ide>
<ide> const WebSocketInterceptor = {
<ide> */
<ide> _registerEvents() {
<ide> subscriptions = [
<del> eventEmitter.addListener('websocketMessage', ev => {
<add> eventEmitter.addListener('websocketMessage', (ev) => {
<ide> if (onMessageCallback) {
<ide> onMessageCallback(
<ide> ev.id,
<ide> const WebSocketInterceptor = {
<ide> );
<ide> }
<ide> }),
<del> eventEmitter.addListener('websocketOpen', ev => {
<add> eventEmitter.addListener('websocketOpen', (ev) => {
<ide> if (onOpenCallback) {
<ide> onOpenCallback(ev.id);
<ide> }
<ide> }),
<del> eventEmitter.addListener('websocketClosed', ev => {
<add> eventEmitter.addListener('websocketClosed', (ev) => {
<ide> if (onCloseCallback) {
<ide> onCloseCallback(ev.id, {code: ev.code, reason: ev.reason});
<ide> }
<ide> }),
<del> eventEmitter.addListener('websocketFailed', ev => {
<add> eventEmitter.addListener('websocketFailed', (ev) => {
<ide> if (onErrorCallback) {
<ide> onErrorCallback(ev.id, {message: ev.message});
<ide> }
<ide> const WebSocketInterceptor = {
<ide> // Override `connect` method for all RCTWebSocketModule requests
<ide> // to intercept the request url, protocols, options and socketId,
<ide> // then pass them through the `connectCallback`.
<del> NativeWebSocketModule.connect = function(
<add> NativeWebSocketModule.connect = function (
<ide> url,
<ide> protocols,
<ide> options,
<ide> const WebSocketInterceptor = {
<ide>
<ide> // Override `send` method for all RCTWebSocketModule requests to intercept
<ide> // the data sent, then pass them through the `sendCallback`.
<del> NativeWebSocketModule.send = function(data, socketId) {
<add> NativeWebSocketModule.send = function (data, socketId) {
<ide> if (sendCallback) {
<ide> sendCallback(data, socketId);
<ide> }
<ide> const WebSocketInterceptor = {
<ide>
<ide> // Override `sendBinary` method for all RCTWebSocketModule requests to
<ide> // intercept the data sent, then pass them through the `sendCallback`.
<del> NativeWebSocketModule.sendBinary = function(data, socketId) {
<add> NativeWebSocketModule.sendBinary = function (data, socketId) {
<ide> if (sendCallback) {
<ide> sendCallback(WebSocketInterceptor._arrayBufferToString(data), socketId);
<ide> }
<ide> const WebSocketInterceptor = {
<ide>
<ide> // Override `close` method for all RCTWebSocketModule requests to intercept
<ide> // the close information, then pass them through the `closeCallback`.
<del> NativeWebSocketModule.close = function() {
<add> NativeWebSocketModule.close = function () {
<ide> if (closeCallback) {
<ide> if (arguments.length === 3) {
<ide> closeCallback(arguments[0], arguments[1], arguments[2]);
<ide><path>Libraries/WebSocket/__tests__/WebSocket-test.js
<ide> jest.setMock('../../BatchedBridge/NativeModules', {
<ide>
<ide> const WebSocket = require('../WebSocket');
<ide>
<del>describe('WebSocket', function() {
<add>describe('WebSocket', function () {
<ide> it('should have connection lifecycle constants defined on the class', () => {
<ide> expect(WebSocket.CONNECTING).toEqual(0);
<ide> });
<ide><path>Libraries/__flowtests__/ReactNativeTypes-flowtest.js
<ide> function takesHostComponentInstance(
<ide> const MyHostComponent = (('Host': any): HostComponent<mixed>);
<ide>
<ide> <MyHostComponent
<del> ref={hostComponentRef => {
<add> ref={(hostComponentRef) => {
<ide> takesHostComponentInstance(hostComponentRef);
<ide>
<ide> if (hostComponentRef == null) {
<ide><path>Libraries/polyfills/Object.es7.js
<ide> * @nolint
<ide> */
<ide>
<del>(function() {
<add>(function () {
<ide> 'use strict';
<ide>
<ide> const hasOwnProperty = Object.prototype.hasOwnProperty;
<ide> * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
<ide> */
<ide> if (typeof Object.entries !== 'function') {
<del> Object.entries = function(object) {
<add> Object.entries = function (object) {
<ide> // `null` and `undefined` values are not allowed.
<ide> if (object == null) {
<ide> throw new TypeError('Object.entries called on non-object');
<ide> * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
<ide> */
<ide> if (typeof Object.values !== 'function') {
<del> Object.values = function(object) {
<add> Object.values = function (object) {
<ide> // `null` and `undefined` values are not allowed.
<ide> if (object == null) {
<ide> throw new TypeError('Object.values called on non-object');
<ide><path>Libraries/polyfills/__tests__/Object.es7-test.js
<ide> describe('Object (ES7)', () => {
<ide> expect(Object.entries(foo)).toEqual([['x', 10]]);
<ide>
<ide> const bar = {x: 10, y: 20};
<del> expect(Object.entries(bar)).toEqual([['x', 10], ['y', 20]]);
<add> expect(Object.entries(bar)).toEqual([
<add> ['x', 10],
<add> ['y', 20],
<add> ]);
<ide> });
<ide>
<ide> it('should work with proto-less objects', () => {
<ide> describe('Object (ES7)', () => {
<ide> });
<ide>
<ide> it('should convert to object primitive string', () => {
<del> expect(Object.entries('ab')).toEqual([['0', 'a'], ['1', 'b']]);
<add> expect(Object.entries('ab')).toEqual([
<add> ['0', 'a'],
<add> ['1', 'b'],
<add> ]);
<ide> });
<ide> });
<ide>
<ide><path>Libraries/polyfills/console.js
<ide> * This pipes all of our console logging functions to native logging so that
<ide> * JavaScript errors in required modules show up in Xcode via NSLog.
<ide> */
<del>const inspect = (function() {
<add>const inspect = (function () {
<ide> // Copyright Joyent, Inc. and other Node contributors.
<ide> //
<ide> // Permission is hereby granted, free of charge, to any person obtaining a
<ide> const inspect = (function() {
<ide> function arrayToHash(array) {
<ide> var hash = {};
<ide>
<del> array.forEach(function(val, idx) {
<add> array.forEach(function (val, idx) {
<ide> hash[val] = true;
<ide> });
<ide>
<ide> const inspect = (function() {
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> ctx.formatValueCalls++;
<ide> if (ctx.formatValueCalls > 200) {
<del> return `[TOO BIG formatValueCalls ${
<del> ctx.formatValueCalls
<del> } exceeded limit of 200]`;
<add> return `[TOO BIG formatValueCalls ${ctx.formatValueCalls} exceeded limit of 200]`;
<ide> }
<ide>
<ide> // Primitive types cannot have properties
<ide> const inspect = (function() {
<ide> if (array) {
<ide> output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
<ide> } else {
<del> output = keys.map(function(key) {
<add> output = keys.map(function (key) {
<ide> return formatProperty(
<ide> ctx,
<ide> value,
<ide> const inspect = (function() {
<ide> output.push('');
<ide> }
<ide> }
<del> keys.forEach(function(key) {
<add> keys.forEach(function (key) {
<ide> if (!key.match(/^\d+$/)) {
<ide> output.push(
<ide> formatProperty(ctx, value, recurseTimes, visibleKeys, key, true),
<ide> const inspect = (function() {
<ide> if (array) {
<ide> str = str
<ide> .split('\n')
<del> .map(function(line) {
<add> .map(function (line) {
<ide> return ' ' + line;
<ide> })
<ide> .join('\n')
<ide> const inspect = (function() {
<ide> '\n' +
<ide> str
<ide> .split('\n')
<del> .map(function(line) {
<add> .map(function (line) {
<ide> return ' ' + line;
<ide> })
<ide> .join('\n');
<ide> const inspect = (function() {
<ide>
<ide> function reduceToSingleString(output, base, braces) {
<ide> var numLinesEst = 0;
<del> var length = output.reduce(function(prev, cur) {
<add> var length = output.reduce(function (prev, cur) {
<ide> numLinesEst++;
<ide> if (cur.indexOf('\n') >= 0) numLinesEst++;
<ide> return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
<ide> INSPECTOR_LEVELS[LOG_LEVELS.error] = 'error';
<ide> const INSPECTOR_FRAMES_TO_SKIP = __DEV__ ? 2 : 1;
<ide>
<ide> function getNativeLogFunction(level) {
<del> return function() {
<add> return function () {
<ide> let str;
<ide> if (arguments.length === 1 && typeof arguments[0] === 'string') {
<ide> str = arguments[0];
<ide> } else {
<ide> str = Array.prototype.map
<del> .call(arguments, function(arg) {
<add> .call(arguments, function (arg) {
<ide> return inspect(arg, {depth: 10});
<ide> })
<ide> .join(', ');
<ide> function getNativeLogFunction(level) {
<ide> }
<ide>
<ide> function repeat(element, n) {
<del> return Array.apply(null, Array(n)).map(function() {
<add> return Array.apply(null, Array(n)).map(function () {
<ide> return element;
<ide> });
<ide> }
<ide> function consoleTablePolyfill(rows) {
<ide>
<ide> // Convert each cell to a string. Also
<ide> // figure out max cell width for each column
<del> columns.forEach(function(k, i) {
<add> columns.forEach(function (k, i) {
<ide> columnWidths[i] = k.length;
<ide> for (var j = 0; j < rows.length; j++) {
<ide> var cellStr = (rows[j][k] || '?').toString();
<ide> function consoleTablePolyfill(rows) {
<ide> // Join all elements in the row into a single string with | separators
<ide> // (appends extra spaces to each cell to make separators | aligned)
<ide> function joinRow(row, space) {
<del> var cells = row.map(function(cell, i) {
<add> var cells = row.map(function (cell, i) {
<ide> var extraSpaces = repeat(' ', columnWidths[i] - cell.length).join('');
<ide> return cell + extraSpaces;
<ide> });
<ide> space = space || ' ';
<ide> return cells.join(space + '|' + space);
<ide> }
<ide>
<del> var separators = columnWidths.map(function(columnWidth) {
<add> var separators = columnWidths.map(function (columnWidth) {
<ide> return repeat('-', columnWidth).join('');
<ide> });
<ide> var separatorRow = joinRow(separators, '-');
<ide> if (global.nativeLoggingHook) {
<ide> // sometimes useful. Ex: on OS X, this will let you see rich output in
<ide> // the Safari Web Inspector console.
<ide> if (__DEV__ && originalConsole) {
<del> Object.keys(console).forEach(methodName => {
<add> Object.keys(console).forEach((methodName) => {
<ide> const reactNativeMethod = console[methodName];
<ide> if (originalConsole[methodName]) {
<del> console[methodName] = function() {
<add> console[methodName] = function () {
<ide> // TODO(T43930203): remove this special case once originalConsole.assert properly checks
<ide> // the condition
<ide> if (methodName === 'assert') {
<ide> if (global.nativeLoggingHook) {
<ide> // The following methods are not supported by this polyfill but
<ide> // we still should pass them to original console if they are
<ide> // supported by it.
<del> ['clear', 'dir', 'dirxml', 'profile', 'profileEnd'].forEach(methodName => {
<del> if (typeof originalConsole[methodName] === 'function') {
<del> console[methodName] = function() {
<del> originalConsole[methodName](...arguments);
<del> };
<del> }
<del> });
<add> ['clear', 'dir', 'dirxml', 'profile', 'profileEnd'].forEach(
<add> (methodName) => {
<add> if (typeof originalConsole[methodName] === 'function') {
<add> console[methodName] = function () {
<add> originalConsole[methodName](...arguments);
<add> };
<add> }
<add> },
<add> );
<ide> }
<ide> } else if (!global.console) {
<ide> function stub() {}
<ide><path>Libraries/vendor/emitter/EventEmitter.js
<ide> class EventEmitter {
<ide> // exist; it is not called for missing elements of the array."
<ide> // https://www.ecma-international.org/ecma-262/9.0/index.html#sec-array.prototype.filter
<ide> .filter(sparseFilterPredicate)
<del> .map(subscription => subscription.listener)
<add> .map((subscription) => subscription.listener)
<ide> : [];
<ide> }
<ide>
<ide><path>RNTester/RNTesterUnitTests/RNTesterUnitTestsBundle.js
<ide>
<ide> // eslint-disable-next-line no-unused-vars
<ide> const __fbBatchedBridge = {
<del> flushedQueue: function() {
<add> flushedQueue: function () {
<ide> return null;
<ide> },
<ide> };
<ide><path>RNTester/e2e/e2e-helpers.js
<ide> exports.openComponentWithLabel = async (component, label) => {
<ide>
<ide> // Will open an individual example for a component
<ide> // by filtering on the example title
<del>exports.openExampleWithTitle = async title => {
<add>exports.openExampleWithTitle = async (title) => {
<ide> await element(by.id('example_search')).replaceText(title);
<ide> };
<ide><path>RNTester/e2e/test-init.js
<ide> beforeAll(async () => {
<ide> });
<ide> });
<ide>
<del>beforeEach(async function() {
<add>beforeEach(async function () {
<ide> await adapter.beforeEach();
<ide> });
<ide>
<ide><path>RNTester/js/RNTesterApp.android.js
<ide> const Header = ({
<ide> ...
<ide> }) => (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <View style={[styles.toolbar, {backgroundColor: theme.ToolbarColor}]}>
<ide> <View style={styles.toolbarCenter}>
<ide> class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
<ide> }
<ide>
<ide> componentDidMount() {
<del> Linking.getInitialURL().then(url => {
<add> Linking.getInitialURL().then((url) => {
<ide> AsyncStorage.getItem(APP_STATE_KEY, (err, storedString) => {
<ide> const exampleAction = URIActionMap(
<ide> this.props.exampleFromAppetizeParams,
<ide> class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
<ide> * found when making Flow check .android.js files. */
<ide> this._overrideBackPressForDrawerLayout = false;
<ide> }}
<del> ref={drawer => {
<add> ref={(drawer) => {
<ide> /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
<ide> * found when making Flow check .android.js files. */
<ide> this.drawer = drawer;
<ide> class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
<ide> onExampleExit={() => {
<ide> this._handleAction(RNTesterActions.Back());
<ide> }}
<del> ref={example => {
<add> ref={(example) => {
<ide> /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue
<ide> * was found when making Flow check .android.js files. */
<ide> this._exampleRef = example;
<ide> class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
<ide> onPressDrawer={() => this.drawer.openDrawer()}
<ide> title={ExampleModule.title}
<ide> module={ExampleModule}
<del> exampleRef={example => {
<add> exampleRef={(example) => {
<ide> /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue
<ide> * was found when making Flow check .android.js files. */
<ide> this._exampleRef = example;
<ide><path>RNTester/js/RNTesterApp.ios.js
<ide> const Header = ({
<ide> ...
<ide> }) => (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <SafeAreaView
<ide> style={[
<ide> class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
<ide>
<ide> componentDidMount() {
<ide> this._mounted = true;
<del> Linking.getInitialURL().then(url => {
<add> Linking.getInitialURL().then((url) => {
<ide> AsyncStorage.getItem(APP_STATE_KEY, (err, storedString) => {
<ide> if (!this._mounted) {
<ide> return;
<ide> class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
<ide> });
<ide> });
<ide>
<del> Linking.addEventListener('url', url => {
<add> Linking.addEventListener('url', (url) => {
<ide> this._handleAction(URIActionMap(url));
<ide> });
<ide> }
<ide><path>RNTester/js/components/ListExampleShared.js
<ide> function getItemLayout(
<ide> function pressItem(context: Object, key: string) {
<ide> const index = Number(key);
<ide> const pressed = !context.state.data[index].pressed;
<del> context.setState(state => {
<add> context.setState((state) => {
<ide> const newData = [...state.data];
<ide> newData[index] = {
<ide> ...state.data[index],
<ide> function renderSmallSwitchOption(
<ide> <Switch
<ide> style={styles.smallSwitch}
<ide> value={context.state[key]}
<del> onValueChange={value => context.setState({[key]: value})}
<add> onValueChange={(value) => context.setState({[key]: value})}
<ide> />
<ide> </View>
<ide> );
<ide><path>RNTester/js/components/RNTesterBlock.js
<ide> class RNTesterBlock extends React.Component<Props, State> {
<ide> render(): React.Node {
<ide> const description = this.props.description ? (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <Text style={[styles.descriptionText, {color: theme.LabelColor}]}>
<ide> {this.props.description}
<ide> class RNTesterBlock extends React.Component<Props, State> {
<ide>
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <View
<ide> style={[
<ide><path>RNTester/js/components/RNTesterExampleFilter.js
<ide> class RNTesterExampleFilter extends React.Component<Props, State> {
<ide> );
<ide> }
<ide>
<del> const filter = example =>
<add> const filter = (example) =>
<ide> this.props.disableSearch || this.props.filter({example, filterRegex});
<ide>
<del> const filteredSections = this.props.sections.map(section => ({
<add> const filteredSections = this.props.sections.map((section) => ({
<ide> ...section,
<ide> data: section.data.filter(filter),
<ide> }));
<ide> class RNTesterExampleFilter extends React.Component<Props, State> {
<ide> }
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <View
<ide> style={[
<ide> class RNTesterExampleFilter extends React.Component<Props, State> {
<ide> autoCapitalize="none"
<ide> autoCorrect={false}
<ide> clearButtonMode="always"
<del> onChangeText={text => {
<add> onChangeText={(text) => {
<ide> this.setState(() => ({filter: text}));
<ide> }}
<ide> placeholder="Search..."
<ide><path>RNTester/js/components/RNTesterExampleList.js
<ide> class RowComponent extends React.PureComponent<{
<ide> const {item} = this.props;
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <TouchableHighlight
<ide> onShowUnderlay={this.props.onShowUnderlay}
<ide> class RowComponent extends React.PureComponent<{
<ide>
<ide> const renderSectionHeader = ({section}) => (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <Text
<ide> style={[
<ide> class RNTesterExampleList extends React.Component<Props, $FlowFixMeState> {
<ide>
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <View
<ide> style={[
<ide> class RNTesterExampleList extends React.Component<Props, $FlowFixMeState> {
<ide>
<ide> const ItemSeparator = ({highlighted}) => (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <View
<ide> style={
<ide><path>RNTester/js/components/RNTesterPage.js
<ide> class RNTesterPage extends React.Component<Props> {
<ide> const spacer = this.props.noSpacer ? null : <View style={styles.spacer} />;
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <View
<ide> style={[
<ide><path>RNTester/js/components/RNTesterSettingSwitchRow.js
<ide> class RNTesterSettingSwitchRow extends React.Component<
<ide> <Text>{label}</Text>
<ide> <Switch
<ide> value={persister.state}
<del> onValueChange={value => {
<add> onValueChange={(value) => {
<ide> persister.setState(() => value);
<ide> }}
<ide> />
<ide><path>RNTester/js/components/RNTesterTitle.js
<ide> class RNTesterTitle extends React.Component<$FlowFixMeProps> {
<ide> render(): React.Node {
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <View
<ide> style={[
<ide><path>RNTester/js/components/TextLegend.js
<ide> class TextLegend extends React.Component<*, *> {
<ide> <View>
<ide> <Text
<ide> onPress={() =>
<del> this.setState(prevState => ({fontSize: prevState.fontSize + 3}))
<add> this.setState((prevState) => ({fontSize: prevState.fontSize + 3}))
<ide> }>
<ide> Increase size
<ide> </Text>
<ide> <Text
<ide> onPress={() =>
<del> this.setState(prevState => ({fontSize: prevState.fontSize - 3}))
<add> this.setState((prevState) => ({fontSize: prevState.fontSize - 3}))
<ide> }>
<ide> Decrease size
<ide> </Text>
<ide> <Picker
<ide> selectedValue={this.state.language}
<del> onValueChange={itemValue => this.setState({language: itemValue})}>
<del> {Object.keys(PANGRAMS).map(x => (
<add> onValueChange={(itemValue) => this.setState({language: itemValue})}>
<add> {Object.keys(PANGRAMS).map((x) => (
<ide> <Picker.Item
<ide> label={x[0].toUpperCase() + x.substring(1)}
<ide> key={x}
<ide> class TextLegend extends React.Component<*, *> {
<ide> },
<ide> )}
<ide> <Text
<del> onTextLayout={event => {
<add> onTextLayout={(event) => {
<ide> this.setState({textMetrics: event.nativeEvent.lines});
<ide> }}
<ide> style={{
<ide> class TextLegend extends React.Component<*, *> {
<ide> </View>
<ide> <Picker
<ide> selectedValue={this.state.alignment}
<del> onValueChange={itemValue => this.setState({alignment: itemValue})}>
<add> onValueChange={(itemValue) => this.setState({alignment: itemValue})}>
<ide> <Picker.Item label="Left align" value="left" />
<ide> <Picker.Item label="Center align" value="center" />
<ide> <Picker.Item label="Right align" value="right" />
<ide><path>RNTester/js/components/createExamplePage.js
<ide> const React = require('react');
<ide> const RNTesterExampleContainer = require('./RNTesterExampleContainer');
<ide> import type {RNTesterExample} from '../types/RNTesterTypes';
<ide>
<del>const createExamplePage = function(
<add>const createExamplePage = function (
<ide> title: ?string,
<ide> exampleModule: RNTesterExample,
<ide> ): React.ComponentType<any> {
<ide><path>RNTester/js/examples/Accessibility/AccessibilityExample.js
<ide> class AccessibilityActionsExample extends React.Component {
<ide> <View
<ide> accessible={true}
<ide> accessibilityActions={[{name: 'activate'}]}
<del> onAccessibilityAction={event => {
<add> onAccessibilityAction={(event) => {
<ide> switch (event.nativeEvent.actionName) {
<ide> case 'activate':
<ide> Alert.alert('Alert', 'View is clicked');
<ide> class AccessibilityActionsExample extends React.Component {
<ide> {name: 'copy', label: 'copy label'},
<ide> {name: 'paste', label: 'paste label'},
<ide> ]}
<del> onAccessibilityAction={event => {
<add> onAccessibilityAction={(event) => {
<ide> switch (event.nativeEvent.actionName) {
<ide> case 'cut':
<ide> Alert.alert('Alert', 'cut action success');
<ide> class AccessibilityActionsExample extends React.Component {
<ide> accessible={true}
<ide> accessibilityRole="adjustable"
<ide> accessibilityActions={[{name: 'increment'}, {name: 'decrement'}]}
<del> onAccessibilityAction={event => {
<add> onAccessibilityAction={(event) => {
<ide> switch (event.nativeEvent.actionName) {
<ide> case 'increment':
<ide> Alert.alert('Alert', 'increment action success');
<ide> class AccessibilityActionsExample extends React.Component {
<ide> {name: 'copy', label: 'copy label'},
<ide> {name: 'paste', label: 'paste label'},
<ide> ]}
<del> onAccessibilityAction={event => {
<add> onAccessibilityAction={(event) => {
<ide> switch (event.nativeEvent.actionName) {
<ide> case 'cut':
<ide> Alert.alert('Alert', 'cut action success');
<ide> class FakeSliderExample extends React.Component {
<ide> accessibilityLabel="Fake Slider"
<ide> accessibilityRole="adjustable"
<ide> accessibilityActions={[{name: 'increment'}, {name: 'decrement'}]}
<del> onAccessibilityAction={event => {
<add> onAccessibilityAction={(event) => {
<ide> switch (event.nativeEvent.actionName) {
<ide> case 'increment':
<ide> this.increment();
<ide> class FakeSliderExample extends React.Component {
<ide> accessibilityLabel="Equalizer"
<ide> accessibilityRole="adjustable"
<ide> accessibilityActions={[{name: 'increment'}, {name: 'decrement'}]}
<del> onAccessibilityAction={event => {
<add> onAccessibilityAction={(event) => {
<ide> switch (event.nativeEvent.actionName) {
<ide> case 'increment':
<ide> if (this.state.textualValue === 'center') {
<ide> class ScreenReaderStatusExample extends React.Component<{}> {
<ide> 'change',
<ide> this._handleScreenReaderToggled,
<ide> );
<del> AccessibilityInfo.fetch().done(isEnabled => {
<add> AccessibilityInfo.fetch().done((isEnabled) => {
<ide> this.setState({
<ide> screenReaderEnabled: isEnabled,
<ide> });
<ide> class ScreenReaderStatusExample extends React.Component<{}> {
<ide> );
<ide> }
<ide>
<del> _handleScreenReaderToggled = isEnabled => {
<add> _handleScreenReaderToggled = (isEnabled) => {
<ide> this.setState({
<ide> screenReaderEnabled: isEnabled,
<ide> });
<ide><path>RNTester/js/examples/Accessibility/AccessibilityIOSExample.js
<ide> class AccessibilityIOSExample extends React.Component<Props> {
<ide> return (
<ide> <RNTesterBlock title="Accessibility iOS APIs">
<ide> <View
<del> onAccessibilityAction={event => {
<add> onAccessibilityAction={(event) => {
<ide> if (event.nativeEvent.actionName === 'activate') {
<ide> Alert.alert('Alert', 'onAccessibilityTap success');
<ide> }
<ide> class AccessibilityIOSExample extends React.Component<Props> {
<ide> <Text>Accessibility normal tap example</Text>
<ide> </View>
<ide> <View
<del> onAccessibilityAction={event => {
<add> onAccessibilityAction={(event) => {
<ide> if (event.nativeEvent.actionName === 'magicTap') {
<ide> Alert.alert('Alert', 'onMagicTap success');
<ide> }
<ide> class AccessibilityIOSExample extends React.Component<Props> {
<ide> <Text>Accessibility magic tap example</Text>
<ide> </View>
<ide> <View
<del> onAccessibilityAction={event => {
<add> onAccessibilityAction={(event) => {
<ide> if (event.nativeEvent.actionName === 'escape') {
<ide> Alert.alert('onAccessibilityEscape success');
<ide> }
<ide><path>RNTester/js/examples/ActionSheetIOS/ActionSheetIOSExample.js
<ide> class ActionSheetExample extends React.Component<Props, State> {
<ide> cancelButtonIndex: CANCEL_INDEX,
<ide> destructiveButtonIndex: DESTRUCTIVE_INDEX,
<ide> },
<del> buttonIndex => {
<add> (buttonIndex) => {
<ide> this.setState({clicked: BUTTONS[buttonIndex]});
<ide> },
<ide> );
<ide> class ActionSheetTintExample extends React.Component<
<ide> destructiveButtonIndex: DESTRUCTIVE_INDEX,
<ide> tintColor: 'green',
<ide> },
<del> buttonIndex => {
<add> (buttonIndex) => {
<ide> this.setState({clicked: BUTTONS[buttonIndex]});
<ide> },
<ide> );
<ide> class ActionSheetAnchorExample extends React.Component<
<ide> ? findNodeHandle(this.anchorRef.current)
<ide> : undefined,
<ide> },
<del> buttonIndex => {
<add> (buttonIndex) => {
<ide> this.setState({clicked: BUTTONS[buttonIndex]});
<ide> },
<ide> );
<ide> class ShareActionSheetExample extends React.Component<
<ide> subject: 'a subject to go in the email heading',
<ide> excludedActivityTypes: ['com.apple.UIKit.activity.PostToTwitter'],
<ide> },
<del> error => Alert.alert('Error', error),
<add> (error) => Alert.alert('Error', error),
<ide> (completed, method) => {
<ide> let text;
<ide> if (completed) {
<ide> class ShareScreenshotExample extends React.Component<
<ide> showShareActionSheet = () => {
<ide> // Take the snapshot (returns a temp file uri)
<ide> ScreenshotManager.takeScreenshot('window')
<del> .then(uri => {
<add> .then((uri) => {
<ide> // Share image data
<ide> ActionSheetIOS.showShareActionSheetWithOptions(
<ide> {
<ide> url: uri,
<ide> excludedActivityTypes: ['com.apple.UIKit.activity.PostToTwitter'],
<ide> },
<del> error => Alert.alert('Error', error),
<add> (error) => Alert.alert('Error', error),
<ide> (completed, method) => {
<ide> let text;
<ide> if (completed) {
<ide> class ShareScreenshotExample extends React.Component<
<ide> },
<ide> );
<ide> })
<del> .catch(error => Alert.alert('Error', error));
<add> .catch((error) => Alert.alert('Error', error));
<ide> };
<ide> }
<ide>
<ide> class ShareScreenshotAnchorExample extends React.Component<
<ide> showShareActionSheet = () => {
<ide> // Take the snapshot (returns a temp file uri)
<ide> ScreenshotManager.takeScreenshot('window')
<del> .then(uri => {
<add> .then((uri) => {
<ide> // Share image data
<ide> ActionSheetIOS.showShareActionSheetWithOptions(
<ide> {
<ide> class ShareScreenshotAnchorExample extends React.Component<
<ide> ? findNodeHandle(this.anchorRef.current)
<ide> : undefined,
<ide> },
<del> error => Alert.alert('Error', error),
<add> (error) => Alert.alert('Error', error),
<ide> (completed, method) => {
<ide> let text;
<ide> if (completed) {
<ide> class ShareScreenshotAnchorExample extends React.Component<
<ide> },
<ide> );
<ide> })
<del> .catch(error => Alert.alert('Error', error));
<add> .catch((error) => Alert.alert('Error', error));
<ide> };
<ide> }
<ide>
<ide><path>RNTester/js/examples/Animated/AnimatedExample.js
<ide> exports.examples = [
<ide> description: ('Uses a simple timing animation to ' +
<ide> 'bring opacity from 0 to 1 when the component ' +
<ide> 'mounts.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> class FadeInView extends React.Component<$FlowFixMeProps, any> {
<ide> constructor(props) {
<ide> super(props);
<ide> exports.examples = [
<ide> <View>
<ide> <RNTesterButton
<ide> onPress={() => {
<del> this.setState(state => ({show: !state.show}));
<add> this.setState((state) => ({show: !state.show}));
<ide> }}>
<ide> Press to {this.state.show ? 'Hide' : 'Show'}
<ide> </RNTesterButton>
<ide> exports.examples = [
<ide> 'ordered set of transforms. Each transform has ' +
<ide> 'an interpolation to convert the value into the ' +
<ide> 'right range and units.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> this.anim = this.anim || new Animated.Value(0);
<ide> return (
<ide> <View>
<ide> exports.examples = [
<ide> title: 'Composite Animations with Easing',
<ide> description: ('Sequence, parallel, delay, and ' +
<ide> 'stagger with different easing functions.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> this.anims = this.anims || [1, 2, 3].map(() => new Animated.Value(0));
<ide> return (
<ide> <View>
<ide> exports.examples = [
<ide> Animated.stagger(
<ide> 200,
<ide> this.anims
<del> .map(anim =>
<add> .map((anim) =>
<ide> timing(anim, {
<ide> toValue: 200,
<ide> useNativeDriver: false,
<ide> }),
<ide> )
<ide> .concat(
<del> this.anims.map(anim =>
<add> this.anims.map((anim) =>
<ide> timing(anim, {
<ide> toValue: 0,
<ide> useNativeDriver: false,
<ide> exports.examples = [
<ide> Animated.delay(400),
<ide> Animated.stagger(
<ide> 200,
<del> this.anims.map(anim =>
<add> this.anims.map((anim) =>
<ide> timing(anim, {
<ide> toValue: 0,
<ide>
<ide> exports.examples = [
<ide> {
<ide> title: 'Rotating Images',
<ide> description: 'Simple Animated.Image rotation.',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> this.anim = this.anim || new Animated.Value(0);
<ide> return (
<ide> <View>
<ide><path>RNTester/js/examples/Animated/AnimatedGratuitousApp/AnExApp.js
<ide> class Circle extends React.Component<any, any> {
<ide>
<ide> _onLongPress(): void {
<ide> const config = {tension: 40, friction: 3};
<del> this.state.pan.addListener(value => {
<add> this.state.pan.addListener((value) => {
<ide> // Async listener for state changes (step1: uncomment)
<ide> this.props.onMove && this.props.onMove(value);
<ide> });
<ide> class AnExApp extends React.Component<any, any> {
<ide> } else {
<ide> let onLayout = null;
<ide> if (!this.state.restLayouts[idx]) {
<del> onLayout = function(index, e) {
<add> onLayout = function (index, e) {
<ide> const layout = e.nativeEvent.layout;
<del> this.setState(state => {
<add> this.setState((state) => {
<ide> state.restLayouts[index] = layout;
<ide> return state;
<ide> });
<ide> class AnExApp extends React.Component<any, any> {
<ide> <View style={styles.container}>
<ide> <View
<ide> style={styles.grid}
<del> onLayout={e => this.setState({layout: e.nativeEvent.layout})}>
<add> onLayout={(e) => this.setState({layout: e.nativeEvent.layout})}>
<ide> {circles}
<ide> </View>
<ide> </View>
<ide><path>RNTester/js/examples/Animated/AnimatedGratuitousApp/AnExChained.js
<ide> class AnExChained extends React.Component<Object, any> {
<ide> this.state.chainResponder = PanResponder.create({
<ide> onStartShouldSetPanResponder: () => true,
<ide> onPanResponderGrant: () => {
<del> this.state.stickers[0].stopAnimation(value => {
<add> this.state.stickers[0].stopAnimation((value) => {
<ide> this.state.stickers[0].setOffset(value); // start where sticker animated to
<ide> this.state.stickers[0].setValue({x: 0, y: 0}); // avoid flicker before next event
<ide> });
<ide><path>RNTester/js/examples/AppState/AppStateExample.js
<ide> class AppStateSubscription extends React.Component<
<ide> this.setState({memoryWarnings: this.state.memoryWarnings + 1});
<ide> };
<ide>
<del> _handleAppStateChange = appState => {
<add> _handleAppStateChange = (appState) => {
<ide> const previousAppStates = this.state.previousAppStates.slice();
<ide> previousAppStates.push(this.state.appState);
<ide> this.setState({
<ide><path>RNTester/js/examples/Appearance/AppearanceExample.js
<ide> class ColorSchemeSubscription extends React.Component<
<ide> render() {
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <ThemedContainer>
<ide> <ThemedText>{this.state.colorScheme}</ThemedText>
<ide> class ColorSchemeSubscription extends React.Component<
<ide> }
<ide> }
<ide>
<del>const ThemedContainer = props => (
<add>const ThemedContainer = (props) => (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <View
<ide> style={{
<ide> const ThemedContainer = props => (
<ide> </RNTesterThemeContext.Consumer>
<ide> );
<ide>
<del>const ThemedText = props => (
<add>const ThemedText = (props) => (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return <Text style={{color: theme.LabelColor}}>{props.children}</Text>;
<ide> }}
<ide> </RNTesterThemeContext.Consumer>
<ide> exports.examples = [
<ide> render(): React.Element<any> {
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <ThemedContainer>
<ide> <ThemedText>
<ide> exports.examples = [
<ide> title: 'RNTester App Colors',
<ide> description: 'A light and a dark theme based on standard iOS 13 colors.',
<ide> render(): React.Element<any> {
<del> const ColorShowcase = props => (
<add> const ColorShowcase = (props) => (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <View
<ide> style={{
<ide> exports.examples = [
<ide> <Text style={{fontWeight: '700', color: theme.LabelColor}}>
<ide> {props.themeName}
<ide> </Text>
<del> {Object.keys(theme).map(key => (
<add> {Object.keys(theme).map((key) => (
<ide> <View style={{flexDirection: 'row'}} key={key}>
<ide> <View
<ide> style={{
<ide><path>RNTester/js/examples/AsyncStorage/AsyncStorageExample.js
<ide> class BasicStorageExample extends React.Component<{...}, $FlowFixMeState> {
<ide> return (
<ide> <View>
<ide> <PickerIOS selectedValue={color} onValueChange={this._onValueChange}>
<del> {COLORS.map(value => (
<add> {COLORS.map((value) => (
<ide> <PickerItemIOS key={value} value={value} label={value} />
<ide> ))}
<ide> </PickerIOS>
<ide> class BasicStorageExample extends React.Component<{...}, $FlowFixMeState> {
<ide> </Text>
<ide> <Text />
<ide> <Text>Messages:</Text>
<del> {this.state.messages.map(m => (
<add> {this.state.messages.map((m) => (
<ide> <Text key={m}>{m}</Text>
<ide> ))}
<ide> </View>
<ide> );
<ide> }
<ide>
<del> _onValueChange = async selectedValue => {
<add> _onValueChange = async (selectedValue) => {
<ide> this.setState({selectedValue});
<ide> try {
<ide> await AsyncStorage.setItem(STORAGE_KEY, selectedValue);
<ide> class BasicStorageExample extends React.Component<{...}, $FlowFixMeState> {
<ide> }
<ide> };
<ide>
<del> _appendMessage = message => {
<add> _appendMessage = (message) => {
<ide> this.setState({messages: this.state.messages.concat(message)});
<ide> };
<ide> }
<ide><path>RNTester/js/examples/Button/ButtonExample.js
<ide> exports.examples = [
<ide> description: ('The title and onPress handler are required. It is ' +
<ide> 'recommended to set accessibilityLabel to help make your app usable by ' +
<ide> 'everyone.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <Button
<ide> onPress={() => onButtonPress('Simple')}
<ide> exports.examples = [
<ide> description: ('Adjusts the color in a way that looks standard on each ' +
<ide> 'platform. On iOS, the color prop controls the color of the text. On ' +
<ide> 'Android, the color adjusts the background color of the button.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <Button
<ide> onPress={() => onButtonPress('Purple')}
<ide> exports.examples = [
<ide> title: 'Fit to text layout',
<ide> description: ('This layout strategy lets the title define the width of ' +
<ide> 'the button': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<del> {theme => {
<add> {(theme) => {
<ide> return (
<ide> <View style={styles.container}>
<ide> <Button
<ide> exports.examples = [
<ide> {
<ide> title: 'Disabled Button',
<ide> description: 'All interactions for the component are disabled.',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Button
<ide> disabled
<ide><path>RNTester/js/examples/CheckBox/CheckBoxExample.js
<ide> class BasicCheckBoxExample extends React.Component<BasicProps, BasicState> {
<ide> return (
<ide> <View>
<ide> <CheckBox
<del> onValueChange={value => this.setState({falseCheckBoxIsOn: value})}
<add> onValueChange={(value) => this.setState({falseCheckBoxIsOn: value})}
<ide> style={styles.checkbox}
<ide> value={this.state.falseCheckBoxIsOn}
<ide> tintColors={{false: 'red'}}
<ide> />
<ide> <CheckBox
<del> onValueChange={value => this.setState({trueCheckBoxIsOn: value})}
<add> onValueChange={(value) => this.setState({trueCheckBoxIsOn: value})}
<ide> value={this.state.trueCheckBoxIsOn}
<ide> tintColors={{true: 'green'}}
<ide> />
<ide> class EventCheckBoxExample extends React.Component<EventProps, EventState> {
<ide> <View style={styles.container}>
<ide> <View>
<ide> <CheckBox
<del> onValueChange={value => this.setState({eventCheckBoxIsOn: value})}
<add> onValueChange={(value) => this.setState({eventCheckBoxIsOn: value})}
<ide> style={styles.checkbox}
<ide> value={this.state.eventCheckBoxIsOn}
<ide> />
<ide> <CheckBox
<del> onValueChange={value => this.setState({eventCheckBoxIsOn: value})}
<add> onValueChange={(value) => this.setState({eventCheckBoxIsOn: value})}
<ide> style={styles.checkbox}
<ide> value={this.state.eventCheckBoxIsOn}
<ide> />
<ide> <Text>{this.state.eventCheckBoxIsOn ? 'On' : 'Off'}</Text>
<ide> </View>
<ide> <View>
<ide> <CheckBox
<del> onValueChange={value =>
<add> onValueChange={(value) =>
<ide> this.setState({eventCheckBoxRegressionIsOn: value})
<ide> }
<ide> style={styles.checkbox}
<ide> value={this.state.eventCheckBoxRegressionIsOn}
<ide> />
<ide> <CheckBox
<del> onValueChange={value =>
<add> onValueChange={(value) =>
<ide> this.setState({eventCheckBoxRegressionIsOn: value})
<ide> }
<ide> style={styles.checkbox}
<ide><path>RNTester/js/examples/DatePicker/DatePickerAndroidExample.js
<ide> exports.description = 'Standard Android date picker dialog';
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple date picker',
<del> render: function(): React.Element<typeof DatePickerAndroidExample> {
<add> render: function (): React.Element<typeof DatePickerAndroidExample> {
<ide> return <DatePickerAndroidExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/DatePicker/DatePickerIOSExample.js
<ide> class WithDatePickerData extends React.Component<Props, State> {
<ide> date: new Date(),
<ide> };
<ide>
<del> onDateChange = date => {
<add> onDateChange = (date) => {
<ide> this.setState({date: date});
<ide> };
<ide>
<ide> exports.description = 'Select dates and times using the native UIDatePicker.';
<ide> exports.examples = [
<ide> {
<ide> title: 'Date and time picker',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return (
<ide> <WithDatePickerData>
<ide> {(state, onDateChange) => (
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Date only picker',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return (
<ide> <WithDatePickerData>
<ide> {(state, onDateChange) => (
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Time only picker, 20-minute interval',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return (
<ide> <WithDatePickerData>
<ide> {(state, onDateChange) => (
<ide><path>RNTester/js/examples/Dimensions/DimensionsExample.js
<ide> class DimensionsSubscription extends React.Component<
<ide> Dimensions.removeEventListener('change', this._handleDimensionsChange);
<ide> }
<ide>
<del> _handleDimensionsChange = dimensions => {
<add> _handleDimensionsChange = (dimensions) => {
<ide> this.setState({
<ide> dims: dimensions[this.props.dim],
<ide> });
<ide><path>RNTester/js/examples/FlatList/FlatListExample.js
<ide> class FlatListExample extends React.PureComponent<Props, State> {
<ide> fadingEdgeLength: 0,
<ide> };
<ide>
<del> _onChangeFilterText = filterText => {
<add> _onChangeFilterText = (filterText) => {
<ide> this.setState({filterText});
<ide> };
<ide>
<del> _onChangeScrollToIndex = text => {
<add> _onChangeScrollToIndex = (text) => {
<ide> this._listRef
<ide> .getNode()
<ide> .scrollToIndex({viewPosition: 0.5, index: Number(text)});
<ide> class FlatListExample extends React.PureComponent<Props, State> {
<ide>
<ide> render(): React.Node {
<ide> const filterRegex = new RegExp(String(this.state.filterText), 'i');
<del> const filter = item =>
<add> const filter = (item) =>
<ide> filterRegex.test(item.text) || filterRegex.test(item.title);
<ide> const filteredData = this.state.data.filter(filter);
<ide> const flatListItemRendererProps = this._renderItemComponent();
<ide> class FlatListExample extends React.PureComponent<Props, State> {
<ide> placeholder="Fading edge length"
<ide> underlineColorAndroid="black"
<ide> keyboardType={'numeric'}
<del> onChange={event =>
<add> onChange={(event) =>
<ide> this.setState({
<ide> fadingEdgeLength: Number(event.nativeEvent.text),
<ide> })
<ide> class FlatListExample extends React.PureComponent<Props, State> {
<ide> </RNTesterPage>
<ide> );
<ide> }
<del> _captureRef = ref => {
<add> _captureRef = (ref) => {
<ide> this._listRef = ref;
<ide> };
<ide> _getItemLayout = (data: any, index: number) => {
<ide> class FlatListExample extends React.PureComponent<Props, State> {
<ide> if (this.state.data.length >= 1000) {
<ide> return;
<ide> }
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> data: state.data.concat(genItemData(100, state.data.length)),
<ide> }));
<ide> };
<ide> class FlatListExample extends React.PureComponent<Props, State> {
<ide> if (this.state.logViewable) {
<ide> infoLog(
<ide> 'onViewableItemsChanged: ',
<del> info.changed.map(v => ({...v, item: '...'})),
<add> info.changed.map((v) => ({...v, item: '...'})),
<ide> );
<ide> }
<ide> };
<ide> exports.simpleExampleContainer = true;
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple list of items',
<del> render: function(): React.Element<typeof FlatListExample> {
<add> render: function (): React.Element<typeof FlatListExample> {
<ide> return <FlatListExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/Image/ImageExample.js
<ide> class NetworkImageCallbackExample extends React.Component<
<ide> }
<ide>
<ide> _loadEventFired = (event: string) => {
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> events: [...state.events, event],
<ide> }));
<ide> };
<ide> class NetworkImageCallbackExample extends React.Component<
<ide> onLoadStart={() =>
<ide> this._loadEventFired(`✔ onLoadStart (+${new Date() - mountTime}ms)`)
<ide> }
<del> onLoad={event => {
<add> onLoad={(event) => {
<ide> if (event.nativeEvent.source) {
<ide> const url = event.nativeEvent.source.url;
<ide> this._loadEventFired(
<ide> class NetworkImageCallbackExample extends React.Component<
<ide> this._loadEventFired(
<ide> `✔ Prefetch OK (+${new Date() - mountTime}ms)`,
<ide> );
<del> Image.queryCache([IMAGE_PREFETCH_URL]).then(map => {
<add> Image.queryCache([IMAGE_PREFETCH_URL]).then((map) => {
<ide> const result = map[IMAGE_PREFETCH_URL];
<ide> if (result) {
<ide> this._loadEventFired(
<del> `✔ queryCache "${result}" (+${new Date() -
<del> mountTime}ms)`,
<add> `✔ queryCache "${result}" (+${
<add> new Date() - mountTime
<add> }ms)`,
<ide> );
<ide> } else {
<ide> this._loadEventFired(
<ide> class NetworkImageCallbackExample extends React.Component<
<ide> }
<ide> });
<ide> },
<del> error => {
<add> (error) => {
<ide> this._loadEventFired(
<ide> `✘ Prefetch failed (+${new Date() - mountTime}ms)`,
<ide> );
<ide> class NetworkImageCallbackExample extends React.Component<
<ide> `✔ (prefetched) onLoadStart (+${new Date() - mountTime}ms)`,
<ide> )
<ide> }
<del> onLoad={event => {
<add> onLoad={(event) => {
<ide> // Currently this image source feature is only available on iOS.
<ide> if (event.nativeEvent.source) {
<ide> const url = event.nativeEvent.source.url;
<ide> this._loadEventFired(
<del> `✔ (prefetched) onLoad (+${new Date() -
<del> mountTime}ms) for URL ${url}`,
<add> `✔ (prefetched) onLoad (+${
<add> new Date() - mountTime
<add> }ms) for URL ${url}`,
<ide> );
<ide> } else {
<ide> this._loadEventFired(
<ide> class NetworkImageExample extends React.Component<
<ide> <ImageBackground
<ide> source={this.props.source}
<ide> style={[styles.base, {overflow: 'visible'}]}
<del> onLoadStart={e => this.setState({loading: true})}
<del> onError={e =>
<add> onLoadStart={(e) => this.setState({loading: true})}
<add> onError={(e) =>
<ide> this.setState({error: e.nativeEvent.error, loading: false})
<ide> }
<del> onProgress={e =>
<add> onProgress={(e) =>
<ide> this.setState({
<ide> progress: Math.round(
<ide> (100 * e.nativeEvent.loaded) / e.nativeEvent.total,
<ide> exports.examples = [
<ide> title: 'Plain Network Image',
<ide> description: ('If the `source` prop `uri` property is prefixed with ' +
<ide> '"http", then it will be downloaded from the network.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <Image source={fullImage} style={styles.base} />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Plain Static Image',
<ide> description: ('Static assets should be placed in the source code tree, and ' +
<ide> 'required in the same way as JavaScript modules.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View style={styles.horizontal}>
<ide> <Image
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Image Loading Events',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <NetworkImageCallbackExample
<ide> source={{
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Error Handler',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <NetworkImageExample
<ide> source={{
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Image Download Progress',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <NetworkImageExample
<ide> source={{
<ide> exports.examples = [
<ide> {
<ide> title: 'defaultSource',
<ide> description: 'Show a placeholder image when a network image is loading',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Image
<ide> defaultSource={require('../../assets/bunny.png')}
<ide> exports.examples = [
<ide> description: ('First image has never been loaded before and is instructed not to load unless in cache.' +
<ide> 'Placeholder image from above will stay. Second image is the same but forced to load regardless of' +
<ide> ' local cache state.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View style={styles.horizontal}>
<ide> <Image
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Border Color',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View style={styles.horizontal}>
<ide> <Image
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Border Width',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View style={styles.horizontal}>
<ide> <Image
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Border Radius',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View style={styles.horizontal}>
<ide> <Image style={[styles.base, {borderRadius: 5}]} source={fullImage} />
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Background Color',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View style={styles.horizontal}>
<ide> <Image source={smallImage} style={styles.base} />
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Opacity',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View style={styles.horizontal}>
<ide> <Image style={[styles.base, {opacity: 1}]} source={fullImage} />
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Nesting content inside <Image> component',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View style={{width: 60, height: 60}}>
<ide> <Image
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Nesting content inside <ImageBackground> component',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <ImageBackground
<ide> style={{width: 60, height: 60, backgroundColor: 'transparent'}}
<ide> exports.examples = [
<ide> title: 'Tint Color',
<ide> description: ('The `tintColor` style prop changes all the non-alpha ' +
<ide> 'pixels to the tint color.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <View style={styles.horizontal}>
<ide> exports.examples = [
<ide> title: 'Resize Mode',
<ide> description: ('The `resizeMode` style prop controls how the image is ' +
<ide> 'rendered within the frame.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> {[smallImage, fullImage].map((image, index) => {
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Animated GIF',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Image
<ide> style={styles.gif}
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Base64 image',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Image style={styles.base64} source={{uri: base64Icon, scale: 3}} />
<ide> );
<ide> exports.examples = [
<ide> 'by capInsets will stay a fixed size, but the center content and ' +
<ide> 'borders of the image will be stretched. This is useful for creating ' +
<ide> 'resizable rounded buttons, shadows, and other resizable assets.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <ImageCapInsetsExample />;
<ide> },
<ide> platform: 'ios',
<ide> },
<ide> {
<ide> title: 'Image Size',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> /* $FlowFixMe(>=0.115.0 site=react_native_fb) This comment suppresses an
<ide> * error found when Flow v0.115 was deployed. To see the error, delete
<ide> * this comment and run Flow. */
<ide> exports.examples = [
<ide> title: 'MultipleSourcesExample',
<ide> description: ('The `source` prop allows passing in an array of uris, so that native to choose which image ' +
<ide> 'to diplay based on the size of the of the target image': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <MultipleSourcesExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Legacy local image',
<ide> description: ('Images shipped with the native bundle, but not managed ' +
<ide> 'by the JS packager': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <Image source={{uri: 'legacy_image', width: 120, height: 120}} />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Bundled images',
<ide> description: 'Images shipped in a separate native bundle',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View style={{flexDirection: 'row'}}>
<ide> <Image
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Blur Radius',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View style={styles.horizontal}>
<ide> <Image style={[styles.base]} source={fullImage} blurRadius={0} />
<ide><path>RNTester/js/examples/InputAccessoryView/InputAccessoryViewExample.js
<ide> class TextInputBar extends React.PureComponent<TextInputProps, TextInputState> {
<ide> <View style={styles.textInputContainer}>
<ide> <TextInput
<ide> style={styles.textInput}
<del> onChangeText={text => {
<add> onChangeText={(text) => {
<ide> this.setState({text});
<ide> }}
<ide> value={this.state.text}
<ide> exports.description =
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple view with sticky input',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <InputAccessoryViewExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/JSResponderHandlerExample/JSResponderHandlerExample.js
<ide> exports.examples = [
<ide> ' right side of the gray area), the touch event is managed by native ' +
<ide> 'which blocks the scroll event.': string),
<ide>
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> const views = [];
<ide> for (let i = 0; i < 100; i++) {
<ide> views[i] = (
<ide><path>RNTester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js
<ide> exports.description =
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple keyboard view',
<del> render: function(): React.Element<typeof KeyboardAvoidingViewExample> {
<add> render: function (): React.Element<typeof KeyboardAvoidingViewExample> {
<ide> return <KeyboardAvoidingViewExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/Layout/LayoutAnimationExample.js
<ide> class AddRemoveExample extends React.Component<{...}, $FlowFixMeState> {
<ide> };
<ide>
<ide> UNSAFE_componentWillUpdate() {
<del> LayoutAnimation.easeInEaseOut(args =>
<add> LayoutAnimation.easeInEaseOut((args) =>
<ide> console.log('AddRemoveExample completed', args),
<ide> );
<ide> }
<ide>
<ide> _onPressAddView = () => {
<del> this.setState(state => ({views: [...state.views, {}]}));
<add> this.setState((state) => ({views: [...state.views, {}]}));
<ide> };
<ide>
<ide> _onPressRemoveView = () => {
<del> this.setState(state => ({views: state.views.slice(0, -1)}));
<add> this.setState((state) => ({views: state.views.slice(0, -1)}));
<ide> };
<ide>
<ide> render() {
<ide> class CrossFadeExample extends React.Component<{...}, $FlowFixMeState> {
<ide> };
<ide>
<ide> _onPressToggle = () => {
<del> LayoutAnimation.easeInEaseOut(args =>
<add> LayoutAnimation.easeInEaseOut((args) =>
<ide> console.log('CrossFadeExample completed', args),
<ide> );
<del> this.setState(state => ({toggled: !state.toggled}));
<add> this.setState((state) => ({toggled: !state.toggled}));
<ide> };
<ide>
<ide> render() {
<ide> class LayoutUpdateExample extends React.Component<{...}, $FlowFixMeState> {
<ide> type: LayoutAnimation.Types.linear,
<ide> },
<ide> },
<del> args => console.log('LayoutUpdateExample completed', args),
<add> (args) => console.log('LayoutUpdateExample completed', args),
<ide> );
<ide>
<ide> this.timeout = setTimeout(() => this.setState({width: 100}), 500);
<ide><path>RNTester/js/examples/Layout/LayoutEventsExample.js
<ide> exports.description = ('Examples that show how Layout events can be used to ' +
<ide> exports.examples = [
<ide> {
<ide> title: 'LayoutEventExample',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <LayoutEventExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/Layout/LayoutExample.js
<ide> exports.displayName = 'LayoutExample';
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple layout using flexbox',
<del> render: function(): React.Element<typeof LayoutExample> {
<add> render: function (): React.Element<typeof LayoutExample> {
<ide> return <LayoutExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/Linking/LinkingExample.js
<ide> type Props = $ReadOnly<{|
<ide>
<ide> class OpenURLButton extends React.Component<Props> {
<ide> handleClick = () => {
<del> Linking.canOpenURL(this.props.url).then(supported => {
<add> Linking.canOpenURL(this.props.url).then((supported) => {
<ide> if (supported) {
<ide> Linking.openURL(this.props.url);
<ide> } else {
<ide> exports.description = 'Shows how to use Linking to open URLs.';
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple list of items',
<del> render: function(): React.Element<typeof IntentAndroidExample> {
<add> render: function (): React.Element<typeof IntentAndroidExample> {
<ide> return <IntentAndroidExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/MaskedView/MaskedViewExample.js
<ide> class ChangingChildrenMaskExample extends React.Component<
<ide>
<ide> componentDidMount() {
<ide> setInterval(() => {
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> alternateChildren: !state.alternateChildren,
<ide> }));
<ide> }, 1000);
<ide> exports.description =
<ide> exports.examples = [
<ide> {
<ide> title: 'Basic Mask',
<del> render: function(): React.Element<typeof View> {
<add> render: function (): React.Element<typeof View> {
<ide> return (
<ide> <View style={styles.exampleWrapperStyle}>
<ide> <MaskedViewIOS
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Image Mask',
<del> render: function(): React.Element<typeof View> {
<add> render: function (): React.Element<typeof View> {
<ide> return (
<ide> <View style={[styles.exampleWrapperStyle, styles.grayStyle]}>
<ide> <MaskedViewIOS
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Animated Mask',
<del> render: function(): React.Element<typeof AnimatedMaskExample> {
<add> render: function (): React.Element<typeof AnimatedMaskExample> {
<ide> return <AnimatedMaskExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Mask w/ Changing Children',
<del> render: function(): React.Element<typeof ChangingChildrenMaskExample> {
<add> render: function (): React.Element<typeof ChangingChildrenMaskExample> {
<ide> return <ChangingChildrenMaskExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/Modal/ModalExample.js
<ide> class ModalExample extends React.Component<{...}, $FlowFixMeState> {
<ide> currentOrientation: 'unknown',
<ide> };
<ide>
<del> _setModalVisible = visible => {
<add> _setModalVisible = (visible) => {
<ide> this.setState({modalVisible: visible});
<ide> };
<ide>
<del> _setAnimationType = type => {
<add> _setAnimationType = (type) => {
<ide> this.setState({animationType: type});
<ide> };
<ide>
<ide> class ModalExample extends React.Component<{...}, $FlowFixMeState> {
<ide> this.state.selectedSupportedOrientation
<ide> ]
<ide> }
<del> onOrientationChange={evt =>
<add> onOrientationChange={(evt) =>
<ide> this.setState({currentOrientation: evt.nativeEvent.orientation})
<ide> }>
<ide> <View style={[styles.container, modalBackgroundStyle]}>
<ide> class ModalExample extends React.Component<{...}, $FlowFixMeState> {
<ide> <Text style={styles.rowTitle}>Presentation style</Text>
<ide> <Picker
<ide> selectedValue={this.state.presentationStyle}
<del> onValueChange={presentationStyle =>
<add> onValueChange={(presentationStyle) =>
<ide> this.setState({presentationStyle})
<ide> }
<ide> itemStyle={styles.pickerItem}>
<ide><path>RNTester/js/examples/MultiColumn/MultiColumnExample.js
<ide> class MultiColumnExample extends React.PureComponent<
<ide> numColumns: 2,
<ide> virtualized: true,
<ide> };
<del> _onChangeFilterText = filterText => {
<add> _onChangeFilterText = (filterText) => {
<ide> this.setState(() => ({filterText}));
<ide> };
<del> _onChangeNumColumns = numColumns => {
<add> _onChangeNumColumns = (numColumns) => {
<ide> this.setState(() => ({numColumns: Number(numColumns)}));
<ide> };
<ide> render(): React.Node {
<ide> const filterRegex = new RegExp(String(this.state.filterText), 'i');
<del> const filter = item =>
<add> const filter = (item) =>
<ide> filterRegex.test(item.text) || filterRegex.test(item.title);
<ide> const filteredData = this.state.data.filter(filter);
<ide> return (
<ide> class MultiColumnExample extends React.PureComponent<
<ide> if (this.state.logViewable) {
<ide> infoLog(
<ide> 'onViewableItemsChanged: ',
<del> info.changed.map(v => ({...v, item: '...'})),
<add> info.changed.map((v) => ({...v, item: '...'})),
<ide> );
<ide> }
<ide> };
<ide> exports.description = 'Performant, scrollable grid of data.';
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple flat list multi column',
<del> render: function(): React.Element<typeof MultiColumnExample> {
<add> render: function (): React.Element<typeof MultiColumnExample> {
<ide> return <MultiColumnExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/NativeAnimation/NativeAnimationsExample.js
<ide> class ValueListenerExample extends React.Component<{...}, $FlowFixMeState> {
<ide> _current = 0;
<ide>
<ide> componentDidMount() {
<del> this.state.anim.addListener(e => this.setState({progress: e.value}));
<add> this.state.anim.addListener((e) => this.setState({progress: e.value}));
<ide> }
<ide>
<ide> componentWillUnmount() {
<ide> class InternalSettings extends React.Component<
<ide> require('../../../../Libraries/Interaction/JSEventLoopWatchdog').addHandler(
<ide> {
<ide> onStall: ({busyTime}) =>
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> busyTime,
<ide> filteredStall:
<ide> (state.filteredStall || 0) * 0.97 + busyTime * 0.03,
<ide> exports.description = 'Test out Native Animations';
<ide> exports.examples = [
<ide> {
<ide> title: 'Multistage With Multiply and rotation',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Tester type="timing" config={{duration: 1000}}>
<del> {anim => (
<add> {(anim) => (
<ide> <Animated.View
<ide> style={[
<ide> styles.block,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Multistage With Multiply',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Tester type="timing" config={{duration: 1000}}>
<del> {anim => (
<add> {(anim) => (
<ide> <Animated.View
<ide> style={[
<ide> styles.block,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Multistage With Subtract',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Tester type="timing" config={{duration: 1000}}>
<del> {anim => (
<add> {(anim) => (
<ide> <Animated.View
<ide> style={[
<ide> styles.block,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Scale interpolation with clamping',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Tester type="timing" config={{duration: 1000}}>
<del> {anim => (
<add> {(anim) => (
<ide> <Animated.View
<ide> style={[
<ide> styles.block,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Opacity with delay',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Tester type="timing" config={{duration: 1000, delay: 1000}}>
<del> {anim => (
<add> {(anim) => (
<ide> <Animated.View
<ide> style={[
<ide> styles.block,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Rotate interpolation',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Tester type="timing" config={{duration: 1000}}>
<del> {anim => (
<add> {(anim) => (
<ide> <Animated.View
<ide> style={[
<ide> styles.block,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'translateX => Animated.spring (bounciness/speed)',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Tester type="spring" config={{bounciness: 0}}>
<del> {anim => (
<add> {(anim) => (
<ide> <Animated.View
<ide> style={[
<ide> styles.block,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'translateX => Animated.spring (stiffness/damping/mass)',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Tester type="spring" config={{stiffness: 1000, damping: 500, mass: 3}}>
<del> {anim => (
<add> {(anim) => (
<ide> <Animated.View
<ide> style={[
<ide> styles.block,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'translateX => Animated.decay',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Tester
<ide> type="decay"
<ide> config={{velocity: 0.5}}
<ide> reverseConfig={{velocity: -0.5}}>
<del> {anim => (
<add> {(anim) => (
<ide> <Animated.View
<ide> style={[
<ide> styles.block,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Drive custom property (tap to animate)',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Tester type="timing" config={{duration: 1000}}>
<del> {anim => <AnimatedSlider style={{}} value={anim} />}
<add> {(anim) => <AnimatedSlider style={{}} value={anim} />}
<ide> </Tester>
<ide> );
<ide> },
<ide> },
<ide> {
<ide> title: 'Animated value listener',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <ValueListenerExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Animated loop',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <LoopExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Animated events',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <EventExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Animated Tracking - tap me many times',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <TrackingExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Internal Settings',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <InternalSettings />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/NewAppScreen/NewAppScreenExample.js
<ide> exports.examples = [
<ide> render(): React.Element<any> {
<ide> return (
<ide> <View style={{flexDirection: 'row'}}>
<del> {Object.keys(Colors).map(key => (
<add> {Object.keys(Colors).map((key) => (
<ide> <View
<ide> key={`color-${key}`}
<ide> style={{width: 50, height: 50, backgroundColor: Colors[key]}}
<ide><path>RNTester/js/examples/PanResponder/PanResponderExample.js
<ide> class PanResponderExample extends React.Component<Props, State> {
<ide> title="Basic gesture handling">
<ide> <View style={styles.container}>
<ide> <View
<del> ref={circle => {
<add> ref={(circle) => {
<ide> this.circle = circle;
<ide> }}
<ide> style={[
<ide> exports.simpleExampleContainer = true;
<ide> exports.examples = [
<ide> {
<ide> title: 'Basic gesture handling',
<del> render: function(): React.Element<typeof PanResponderExample> {
<add> render: function (): React.Element<typeof PanResponderExample> {
<ide> return <PanResponderExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/Picker/PickerExample.js
<ide> class BasicPickerExample extends React.Component<{...}, State> {
<ide> testID="basic-picker"
<ide> style={styles.picker}
<ide> selectedValue={this.state.value}
<del> onValueChange={v => this.setState({value: v})}>
<add> onValueChange={(v) => this.setState({value: v})}>
<ide> <Item label="hello" value="key0" />
<ide> <Item label="world" value="key1" />
<ide> </Picker>
<ide> class DropdownPickerExample extends React.Component<{...}, State> {
<ide> <Picker
<ide> style={styles.picker}
<ide> selectedValue={this.state.value}
<del> onValueChange={v => this.setState({value: v})}
<add> onValueChange={(v) => this.setState({value: v})}
<ide> mode="dropdown">
<ide> <Item label="hello" value="key0" />
<ide> <Item label="world" value="key1" />
<ide> class PromptPickerExample extends React.Component<{...}, State> {
<ide> <Picker
<ide> style={styles.picker}
<ide> selectedValue={this.state.value}
<del> onValueChange={v => this.setState({value: v})}
<add> onValueChange={(v) => this.setState({value: v})}
<ide> prompt="Pick one, just one">
<ide> <Item label="hello" value="key0" />
<ide> <Item label="world" value="key1" />
<ide> class ColorPickerExample extends React.Component<{...}, ColorState> {
<ide> <Picker
<ide> style={[styles.picker, {color: 'white', backgroundColor: '#333'}]}
<ide> selectedValue={this.state.color}
<del> onValueChange={v => this.setState({color: v})}
<add> onValueChange={(v) => this.setState({color: v})}
<ide> mode="dropdown">
<ide> <Item label="red" color="red" value="red" />
<ide> <Item label="green" color="green" value="green" />
<ide> class ColorPickerExample extends React.Component<{...}, ColorState> {
<ide> <Picker
<ide> style={styles.picker}
<ide> selectedValue={this.state.color}
<del> onValueChange={v => this.setState({color: v})}
<add> onValueChange={(v) => this.setState({color: v})}
<ide> mode="dialog">
<ide> <Item label="red" color="red" value="red" />
<ide> <Item label="green" color="green" value="green" />
<ide> class AccessibilityLabelPickerExample extends React.Component<{||}, State> {
<ide> accessibilityLabel={this.state.value + 'Hours'}
<ide> style={styles.picker}
<ide> selectedValue={this.state.value}
<del> onValueChange={v => this.setState({value: v})}>
<add> onValueChange={(v) => this.setState({value: v})}>
<ide> <Item label="1" value="1" />
<ide> <Item label="2" value="2" />
<ide> <Item label="3" value="3" />
<ide> exports.description =
<ide> exports.examples = [
<ide> {
<ide> title: 'Basic Picker',
<del> render: function(): React.Element<typeof BasicPickerExample> {
<add> render: function (): React.Element<typeof BasicPickerExample> {
<ide> return <BasicPickerExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Disabled Picker',
<del> render: function(): React.Element<typeof DisabledPickerExample> {
<add> render: function (): React.Element<typeof DisabledPickerExample> {
<ide> return <DisabledPickerExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Dropdown Picker',
<del> render: function(): React.Element<typeof DropdownPickerExample> {
<add> render: function (): React.Element<typeof DropdownPickerExample> {
<ide> return <DropdownPickerExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Picker with prompt message',
<del> render: function(): React.Element<typeof PromptPickerExample> {
<add> render: function (): React.Element<typeof PromptPickerExample> {
<ide> return <PromptPickerExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Accessibility Label pickers',
<del> render: function(): React.Element<typeof AccessibilityLabelPickerExample> {
<add> render: function (): React.Element<typeof AccessibilityLabelPickerExample> {
<ide> return <AccessibilityLabelPickerExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Picker with no listener',
<del> render: function(): React.Element<typeof PromptPickerExample> {
<add> render: function (): React.Element<typeof PromptPickerExample> {
<ide> return (
<ide> /* $FlowFixMe(>=0.99.0 site=react_native_fb) This comment suppresses an
<ide> * error found when Flow v0.99 was deployed. To see the error, delete
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Colorful pickers',
<del> render: function(): React.Element<typeof ColorPickerExample> {
<add> render: function (): React.Element<typeof ColorPickerExample> {
<ide> return <ColorPickerExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'AccessibilityLabel pickers',
<del> render: function(): React.Element<typeof AccessibilityLabelPickerExample> {
<add> render: function (): React.Element<typeof AccessibilityLabelPickerExample> {
<ide> return <AccessibilityLabelPickerExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/Picker/PickerIOSExample.js
<ide> class PickerExample extends React.Component<{...}, $FlowFixMeState> {
<ide> <Text>Please choose a make for your car:</Text>
<ide> <PickerIOS
<ide> selectedValue={this.state.carMake}
<del> onValueChange={carMake => this.setState({carMake, modelIndex: 0})}>
<del> {Object.keys(CAR_MAKES_AND_MODELS).map(carMake => (
<add> onValueChange={(carMake) => this.setState({carMake, modelIndex: 0})}>
<add> {Object.keys(CAR_MAKES_AND_MODELS).map((carMake) => (
<ide> <PickerItemIOS
<ide> key={carMake}
<ide> value={carMake}
<ide> class PickerExample extends React.Component<{...}, $FlowFixMeState> {
<ide> <PickerIOS
<ide> selectedValue={this.state.modelIndex}
<ide> key={this.state.carMake}
<del> onValueChange={modelIndex => this.setState({modelIndex})}>
<add> onValueChange={(modelIndex) => this.setState({modelIndex})}>
<ide> {CAR_MAKES_AND_MODELS[this.state.carMake].models.map(
<ide> (modelName, modelIndex) => (
<ide> <PickerItemIOS
<ide> class PickerStyleExample extends React.Component<{...}, $FlowFixMeState> {
<ide> fontWeight: 'bold',
<ide> }}
<ide> selectedValue={this.state.carMake}
<del> onValueChange={carMake => this.setState({carMake, modelIndex: 0})}>
<del> {Object.keys(CAR_MAKES_AND_MODELS).map(carMake => (
<add> onValueChange={(carMake) => this.setState({carMake, modelIndex: 0})}>
<add> {Object.keys(CAR_MAKES_AND_MODELS).map((carMake) => (
<ide> <PickerItemIOS
<ide> key={carMake}
<ide> value={carMake}
<ide> exports.description = 'Render lists of selectable options with UIPickerView.';
<ide> exports.examples = [
<ide> {
<ide> title: '<PickerIOS>',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <PickerExample />;
<ide> },
<ide> },
<ide> {
<ide> title: '<PickerIOS> with custom styling',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <PickerStyleExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/PointerEvents/PointerEventsExample.js
<ide> class ExampleBox extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
<ide> log: [],
<ide> };
<ide>
<del> handleLog = msg => {
<add> handleLog = (msg) => {
<ide> this.state.log = this.state.log.concat([msg]);
<ide> };
<ide>
<ide> const exampleClasses: Array<ExampleClass> = [
<ide> },
<ide> ];
<ide>
<del>const infoToExample = info => {
<add>const infoToExample = (info) => {
<ide> return {
<ide> title: info.title,
<ide> description: info.description,
<del> render: function() {
<add> render: function () {
<ide> return <ExampleBox key={info.title} Component={info.Component} />;
<ide> },
<ide> };
<ide><path>RNTester/js/examples/Pressable/PressableExample.js
<ide> function ContentPress() {
<ide> <View style={styles.row}>
<ide> <Pressable
<ide> onPress={() => {
<del> setTimesPressed(current => current + 1);
<add> setTimesPressed((current) => current + 1);
<ide> }}>
<ide> {({pressed}) => (
<ide> <Text style={styles.text}>{pressed ? 'Pressed!' : 'Press Me'}</Text>
<ide> function TextOnPressBox() {
<ide> style={styles.textBlock}
<ide> testID="tappable_text"
<ide> onPress={() => {
<del> setTimesPressed(prev => prev + 1);
<add> setTimesPressed((prev) => prev + 1);
<ide> }}>
<ide> Text has built-in onPress handling
<ide> </Text>
<ide> function PressableFeedbackEvents() {
<ide>
<ide> function appendEvent(eventName) {
<ide> const limit = 6;
<del> setEventLog(current => {
<add> setEventLog((current) => {
<ide> return [eventName].concat(current.slice(0, limit - 1));
<ide> });
<ide> }
<ide> function ForceTouchExample() {
<ide> style={styles.wrapper}
<ide> testID="pressable_3dtouch_button"
<ide> onStartShouldSetResponder={() => true}
<del> onResponderMove={event => setForce(event.nativeEvent.force)}
<del> onResponderRelease={event => setForce(0)}>
<add> onResponderMove={(event) => setForce(event.nativeEvent.force)}
<add> onResponderRelease={(event) => setForce(0)}>
<ide> <Text style={styles.button}>Press Me</Text>
<ide> </View>
<ide> </View>
<ide> function PressableHitSlop() {
<ide> <View testID="pressable_hit_slop">
<ide> <View style={[styles.row, styles.centered]}>
<ide> <Pressable
<del> onPress={() => setTimesPressed(num => num + 1)}
<add> onPress={() => setTimesPressed((num) => num + 1)}
<ide> style={styles.hitSlopWrapper}
<ide> hitSlop={{top: 30, bottom: 30, left: 60, right: 60}}
<ide> testID="pressable_hit_slop_button">
<ide> exports.examples = [
<ide> title: 'Pressable feedback events',
<ide> description: ('<Pressable> components accept onPress, onPressIn, ' +
<ide> 'onPressOut, and onLongPress as props.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <PressableFeedbackEvents />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Pressable with Ripple and Animated child',
<ide> description: ('Pressable can have an AnimatedComponent as a direct child.': string),
<ide> platform: 'android',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> const mScale = new Animated.Value(1);
<ide> Animated.timing(mScale, {
<ide> toValue: 0.3,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: '<Text onPress={fn}> with highlight',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <TextOnPressBox />;
<ide> },
<ide> },
<ide> exports.examples = [
<ide> description: ('<Pressable> also accept delayPressIn, ' +
<ide> 'delayPressOut, and delayLongPress as props. These props impact the ' +
<ide> 'timing of feedback events.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <PressableDelayEvents />;
<ide> },
<ide> },
<ide> {
<ide> title: '3D Touch / Force Touch',
<ide> description:
<ide> 'iPhone 8 and 8 plus support 3D touch, which adds a force property to touches',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <ForceTouchExample />;
<ide> },
<ide> platform: 'ios',
<ide> exports.examples = [
<ide> title: 'Pressable Hit Slop',
<ide> description: ('<Pressable> components accept hitSlop prop which extends the touch area ' +
<ide> 'without changing the view bounds.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <PressableHitSlop />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Pressable Native Methods',
<ide> description: ('<Pressable> components expose native methods like `measure`.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <PressableNativeMethods />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Disabled Pressable',
<ide> description: ('<Pressable> components accept disabled prop which prevents ' +
<ide> 'any interaction with component': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <PressableDisabled />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/ProgressBarAndroid/ProgressBarAndroidExample.android.js
<ide> exports.description = 'Horizontal bar to show the progress of some operation.';
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple progress bar',
<del> render: function(): React.Element<typeof ProgressBarAndroidExample> {
<add> render: function (): React.Element<typeof ProgressBarAndroidExample> {
<ide> return <ProgressBarAndroidExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/ProgressViewIOS/ProgressViewIOSExample.js
<ide> class ProgressViewExample extends React.Component<Props, State> {
<ide> this._rafId = requestAnimationFrame(() => this.updateProgress());
<ide> };
<ide>
<del> getProgress = offset => {
<add> getProgress = (offset) => {
<ide> const progress = this.state.progress + offset;
<ide> return Math.sin(progress % Math.PI) % 1;
<ide> };
<ide><path>RNTester/js/examples/PushNotificationIOS/PushNotificationIOSExample.js
<ide> class NotificationPermissionExample extends React.Component<
<ide>
<ide> _requestPermissions = () => {
<ide> PushNotificationIOS.requestPermissions().then(
<del> onFulfill => {
<add> (onFulfill) => {
<ide> this._showAlert(
<ide> 'Successfully requested permissions -- ' +
<ide> 'Alert: ' +
<ide> class NotificationPermissionExample extends React.Component<
<ide> };
<ide>
<ide> _checkPermissions = () => {
<del> PushNotificationIOS.checkPermissions(permissions => {
<add> PushNotificationIOS.checkPermissions((permissions) => {
<ide> this.setState({permissions});
<ide> });
<ide> };
<ide><path>RNTester/js/examples/RTL/RTLExample.js
<ide> function withRTLState(Component) {
<ide> }
<ide>
<ide> render() {
<del> const setRTL = isRTL => this.setState({isRTL: isRTL});
<add> const setRTL = (isRTL) => this.setState({isRTL: isRTL});
<ide> return (
<ide> <Component isRTL={this.state.isRTL} setRTL={setRTL} {...this.props} />
<ide> );
<ide> const BorderExample = withRTLState(({isRTL, setRTL}) => {
<ide> );
<ide> });
<ide>
<del>const directionStyle = isRTL =>
<add>const directionStyle = (isRTL) =>
<ide> Platform.OS === 'ios' ? {direction: isRTL ? 'rtl' : 'ltr'} : null;
<ide>
<ide> const styles = StyleSheet.create({
<ide> exports.description = 'Examples to show how to apply components to RTL layout.';
<ide> exports.examples = [
<ide> {
<ide> title: 'Current Layout Direction',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <RTLToggleExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'A Simple List Item Layout',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <SimpleListItemExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Default Text Alignment',
<ide> description: ('In iOS, it depends on active language. ' +
<ide> 'In Android, it depends on the text content.': string),
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <TextAlignmentExample style={styles.fontSizeSmall} />;
<ide> },
<ide> },
<ide> {
<ide> title: "Using textAlign: 'left'",
<ide> description: ('In iOS/Android, text alignment flips regardless of ' +
<ide> 'languages or text content.': string),
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return (
<ide> <TextAlignmentExample
<ide> style={[styles.fontSizeSmall, styles.textAlignLeft]}
<ide> exports.examples = [
<ide> title: "Using textAlign: 'right'",
<ide> description: ('In iOS/Android, text alignment flips regardless of ' +
<ide> 'languages or text content.': string),
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return (
<ide> <TextAlignmentExample
<ide> style={[styles.fontSizeSmall, styles.textAlignRight]}
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Working With Icons',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <IconsExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Controlling Animation',
<ide> description: 'Animation direction according to layout',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <AnimationContainer />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Padding Start/End',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <PaddingExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Margin Start/End',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <MarginExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Position Start/End',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <PositionExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Border Width Start/End',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <BorderWidthExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Border Color Start/End',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <BorderColorExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Border Radii Start/End',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <BorderRadiiExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Border',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <BorderExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/RefreshControl/RefreshControlExample.js
<ide> class RefreshControlExample extends React.Component {
<ide> })),
<ide> };
<ide>
<del> _onClick = row => {
<add> _onClick = (row) => {
<ide> row.clicks++;
<ide> this.setState({
<ide> rowData: this.state.rowData,
<ide> exports.simpleExampleContainer = true;
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple refresh',
<del> render: function(): React.Element<typeof RefreshControlExample> {
<add> render: function (): React.Element<typeof RefreshControlExample> {
<ide> return <RefreshControlExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/SafeAreaView/SafeAreaViewExample.js
<ide> class SafeAreaViewExample extends React.Component<
<ide> emulateUnlessSupported: true,
<ide> };
<ide>
<del> _setModalVisible = visible => {
<add> _setModalVisible = (visible) => {
<ide> this.setState({modalVisible: visible});
<ide> };
<ide>
<ide> class SafeAreaViewExample extends React.Component<
<ide> />
<ide> <Text>emulateUnlessSupported:</Text>
<ide> <Switch
<del> onValueChange={value =>
<add> onValueChange={(value) =>
<ide> this.setState({emulateUnlessSupported: value})
<ide> }
<ide> value={this.state.emulateUnlessSupported}
<ide> class SafeAreaViewExample extends React.Component<
<ide> />
<ide> <Text>emulateUnlessSupported:</Text>
<ide> <Switch
<del> onValueChange={value =>
<add> onValueChange={(value) =>
<ide> this.setState({emulateUnlessSupported: value})
<ide> }
<ide> value={this.state.emulateUnlessSupported}
<ide><path>RNTester/js/examples/ScrollView/ScrollViewAnimatedExample.js
<ide> exports.description = 'Component that is animated when ScrollView is offset.';
<ide> exports.examples = [
<ide> {
<ide> title: 'Animated by scroll view',
<del> render: function(): React.Element<typeof ScrollViewAnimatedExample> {
<add> render: function (): React.Element<typeof ScrollViewAnimatedExample> {
<ide> return <ScrollViewAnimatedExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/ScrollView/ScrollViewExample.js
<ide> exports.examples = [
<ide> title: '<ScrollView>\n',
<ide> description:
<ide> 'To make content scrollable, wrap it within a <ScrollView> component',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> let _scrollView: ?React.ElementRef<typeof ScrollView>;
<ide> return (
<ide> <View>
<ide> <ScrollView
<del> ref={scrollView => {
<add> ref={(scrollView) => {
<ide> _scrollView = scrollView;
<ide> }}
<ide> automaticallyAdjustContentInsets={false}
<ide> exports.examples = [
<ide> title: '<ScrollView> (horizontal = true)\n',
<ide> description:
<ide> "You can display <ScrollView>'s child components horizontally rather than vertically",
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> function renderScrollView(
<ide> title: string,
<ide> additionalStyles: ViewStyleProp,
<ide> exports.examples = [
<ide> <View style={additionalStyles}>
<ide> <Text style={styles.text}>{title}</Text>
<ide> <ScrollView
<del> ref={scrollView => {
<add> ref={(scrollView) => {
<ide> _scrollView = scrollView;
<ide> }}
<ide> automaticallyAdjustContentInsets={false}
<ide> exports.examples = [
<ide> {
<ide> title: '<ScrollView> enable & disable\n',
<ide> description: 'ScrollView scrolling behaviour can be disabled and enabled',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> class EnableDisableList extends React.Component<{...}, *> {
<ide> state = {
<ide> scrollEnabled: true,
<ide> if (Platform.OS === 'ios') {
<ide> description:
<ide> 'The `maintainVisibleContentPosition` prop allows insertions to either end of the content ' +
<ide> 'without causing the visible content to jump. Re-ordering is not supported.',
<del> render: function() {
<add> render: function () {
<ide> let itemCount = 6;
<ide> class AppendingList extends React.Component<{...}, *> {
<ide> state = {
<ide> if (Platform.OS === 'ios') {
<ide> autoscrollToTopThreshold: 10,
<ide> }}
<ide> style={styles.scrollView}>
<del> {this.state.items.map(item =>
<add> {this.state.items.map((item) =>
<ide> React.cloneElement(item, {key: item.props.msg}),
<ide> )}
<ide> </ScrollView>
<ide> if (Platform.OS === 'ios') {
<ide> autoscrollToTopThreshold: 10,
<ide> }}
<ide> style={[styles.scrollView, styles.horizontalScrollView]}>
<del> {this.state.items.map(item =>
<add> {this.state.items.map((item) =>
<ide> React.cloneElement(item, {key: item.props.msg, style: null}),
<ide> )}
<ide> </ScrollView>
<ide> <View style={styles.row}>
<ide> <Button
<ide> label="Add to top"
<ide> onPress={() => {
<del> this.setState(state => {
<add> this.setState((state) => {
<ide> const idx = itemCount++;
<ide> return {
<ide> items: [
<ide> if (Platform.OS === 'ios') {
<ide> <Button
<ide> label="Remove top"
<ide> onPress={() => {
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> items: state.items.slice(1),
<ide> }));
<ide> }}
<ide> />
<ide> <Button
<ide> label="Change height top"
<ide> onPress={() => {
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> items: [
<ide> React.cloneElement(state.items[0], {
<ide> style: {paddingBottom: Math.random() * 40},
<ide> if (Platform.OS === 'ios') {
<ide> <Button
<ide> label="Add to end"
<ide> onPress={() => {
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> items: state.items.concat(
<ide> <Item msg={`Item ${itemCount++}`} />,
<ide> ),
<ide> if (Platform.OS === 'ios') {
<ide> <Button
<ide> label="Remove end"
<ide> onPress={() => {
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> items: state.items.slice(0, -1),
<ide> }));
<ide> }}
<ide> />
<ide> <Button
<ide> label="Change height end"
<ide> onPress={() => {
<del> this.setState(state => ({
<add> this.setState((state) => ({
<ide> items: state.items.slice(0, -1).concat(
<ide> React.cloneElement(
<ide> state.items[state.items.length - 1],
<ide><path>RNTester/js/examples/ScrollView/ScrollViewSimpleExample.js
<ide> exports.description =
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple scroll view',
<del> render: function(): React.Element<typeof ScrollViewSimpleExample> {
<add> render: function (): React.Element<typeof ScrollViewSimpleExample> {
<ide> return <ScrollViewSimpleExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/SectionList/SectionListExample.js
<ide> class SectionListExample extends React.PureComponent<{...}, $FlowFixMeState> {
<ide> );
<ide>
<ide> _sectionListRef: React.ElementRef<typeof Animated.SectionList>;
<del> _captureRef = ref => {
<add> _captureRef = (ref) => {
<ide> this._sectionListRef = ref;
<ide> };
<ide>
<ide> class SectionListExample extends React.PureComponent<{...}, $FlowFixMeState> {
<ide>
<ide> render(): React.Node {
<ide> const filterRegex = new RegExp(String(this.state.filterText), 'i');
<del> const filter = item =>
<add> const filter = (item) =>
<ide> filterRegex.test(item.text) || filterRegex.test(item.title);
<ide> const filteredData = this.state.data.filter(filter);
<ide> const filteredSectionData = [];
<ide> class SectionListExample extends React.PureComponent<{...}, $FlowFixMeState> {
<ide> <RNTesterPage noSpacer={true} noScroll={true}>
<ide> <View style={styles.searchRow}>
<ide> <PlainInput
<del> onChangeText={filterText => {
<add> onChangeText={(filterText) => {
<ide> this.setState(() => ({filterText}));
<ide> }}
<ide> placeholder="Search..."
<ide> class SectionListExample extends React.PureComponent<{...}, $FlowFixMeState> {
<ide> ref={this._captureRef}
<ide> ListHeaderComponent={HeaderComponent}
<ide> ListFooterComponent={FooterComponent}
<del> SectionSeparatorComponent={info => (
<add> SectionSeparatorComponent={(info) => (
<ide> <CustomSeparatorComponent {...info} text="SECTION SEPARATOR" />
<ide> )}
<del> ItemSeparatorComponent={info => (
<add> ItemSeparatorComponent={(info) => (
<ide> <CustomSeparatorComponent {...info} text="ITEM SEPARATOR" />
<ide> )}
<ide> debug={this.state.debug}
<ide> exports.description = 'Performant, scrollable list of data.';
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple scrollable list',
<del> render: function(): React.Element<typeof SectionListExample> {
<add> render: function (): React.Element<typeof SectionListExample> {
<ide> return <SectionListExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/SegmentedControlIOS/SegmentedControlIOSExample.js
<ide> class EventSegmentedControlExample extends React.Component<
<ide> );
<ide> }
<ide>
<del> _onChange = event => {
<add> _onChange = (event) => {
<ide> this.setState({
<ide> selectedIndex: event.nativeEvent.selectedSegmentIndex,
<ide> });
<ide> };
<ide>
<del> _onValueChange = value => {
<add> _onValueChange = (value) => {
<ide> this.setState({
<ide> value: value,
<ide> });
<ide><path>RNTester/js/examples/Share/ShareExample.js
<ide> class ShareMessageExample extends React.Component<Props, State> {
<ide> 'React Native | A framework for building native apps using React',
<ide> })
<ide> .then(this._showResult)
<del> .catch(error => this.setState({result: 'error: ' + error.message}));
<add> .catch((error) => this.setState({result: 'error: ' + error.message}));
<ide> }
<ide>
<ide> _shareText() {
<ide> class ShareMessageExample extends React.Component<Props, State> {
<ide> },
<ide> )
<ide> .then(this._showResult)
<del> .catch(error => this.setState({result: 'error: ' + error.message}));
<add> .catch((error) => this.setState({result: 'error: ' + error.message}));
<ide> }
<ide>
<ide> _showResult(result) {
<ide><path>RNTester/js/examples/Slider/SliderExample.js
<ide> function SliderExample(props: React.ElementConfig<typeof Slider>) {
<ide> return (
<ide> <View>
<ide> <Text style={styles.text}>{value.toFixed(3)}</Text>
<del> <Slider {...props} onValueChange={newValue => setValue(newValue)} />
<add> <Slider {...props} onValueChange={(newValue) => setValue(newValue)} />
<ide> </View>
<ide> );
<ide> }
<ide> function SlidingCompleteExample(props: React.ElementConfig<typeof Slider>) {
<ide> <View>
<ide> <SliderExample
<ide> {...props}
<del> onSlidingComplete={value => {
<add> onSlidingComplete={(value) => {
<ide> setSlideCompletionValue(value);
<del> setSlideCompletionCount(count => count + 1);
<add> setSlideCompletionCount((count) => count + 1);
<ide> }}
<ide> />
<ide> <Text>
<ide><path>RNTester/js/examples/Snapshot/SnapshotExample.js
<ide> class ScreenshotExample extends React.Component<{...}, $FlowFixMeState> {
<ide>
<ide> takeScreenshot = () => {
<ide> ScreenshotManager.takeScreenshot('window', {format: 'jpeg', quality: 0.8}) // See UIManager.js for options
<del> .then(uri => this.setState({uri}))
<del> .catch(error => Alert.alert(error));
<add> .then((uri) => this.setState({uri}))
<add> .catch((error) => Alert.alert(error));
<ide> };
<ide> }
<ide>
<ide><path>RNTester/js/examples/Switch/SwitchExample.js
<ide> class BasicSwitchExample extends React.Component<
<ide> <ExampleRow>
<ide> <Switch
<ide> testID="on-off-initial-off"
<del> onValueChange={value => this.setState({falseSwitchIsOn: value})}
<add> onValueChange={(value) => this.setState({falseSwitchIsOn: value})}
<ide> trackColor={{
<ide> true: 'yellow',
<ide> false: 'purple',
<ide> class BasicSwitchExample extends React.Component<
<ide> <ExampleRow>
<ide> <Switch
<ide> testID="on-off-initial-on"
<del> onValueChange={value => this.setState({trueSwitchIsOn: value})}
<add> onValueChange={(value) => this.setState({trueSwitchIsOn: value})}
<ide> value={this.state.trueSwitchIsOn}
<ide> />
<ide> <OnOffIndicator
<ide> class DisabledSwitchExample extends React.Component<
<ide> <Switch
<ide> testID="disabled-initial-off"
<ide> disabled={true}
<del> onValueChange={value => this.setState({falseSwitchIsOn: value})}
<add> onValueChange={(value) => this.setState({falseSwitchIsOn: value})}
<ide> value={this.state.falseSwitchIsOn}
<ide> />
<ide>
<ide> class DisabledSwitchExample extends React.Component<
<ide> <Switch
<ide> testID="disabled-initial-on"
<ide> disabled={true}
<del> onValueChange={value => this.setState({trueSwitchIsOn: value})}
<add> onValueChange={(value) => this.setState({trueSwitchIsOn: value})}
<ide> value={this.state.trueSwitchIsOn}
<ide> />
<ide>
<ide> class ColorSwitchExample extends React.Component<{...}, $FlowFixMeState> {
<ide> return (
<ide> <View>
<ide> <Switch
<del> onValueChange={value => this.setState({colorFalseSwitchIsOn: value})}
<add> onValueChange={(value) =>
<add> this.setState({colorFalseSwitchIsOn: value})
<add> }
<ide> style={{marginBottom: 10}}
<ide> thumbColor="#0000ff"
<ide> trackColor={{
<ide> class ColorSwitchExample extends React.Component<{...}, $FlowFixMeState> {
<ide> value={this.state.colorFalseSwitchIsOn}
<ide> />
<ide> <Switch
<del> onValueChange={value => this.setState({colorTrueSwitchIsOn: value})}
<add> onValueChange={(value) => this.setState({colorTrueSwitchIsOn: value})}
<ide> thumbColor="#0000ff"
<ide> trackColor={{
<ide> false: '#ff0000',
<ide> class EventSwitchExample extends React.Component<{...}, $FlowFixMeState> {
<ide> <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
<ide> <View>
<ide> <Switch
<del> onValueChange={value => this.setState({eventSwitchIsOn: value})}
<add> onValueChange={(value) => this.setState({eventSwitchIsOn: value})}
<ide> style={{marginBottom: 10}}
<ide> value={this.state.eventSwitchIsOn}
<ide> />
<ide> <Switch
<del> onValueChange={value => this.setState({eventSwitchIsOn: value})}
<add> onValueChange={(value) => this.setState({eventSwitchIsOn: value})}
<ide> style={{marginBottom: 10}}
<ide> value={this.state.eventSwitchIsOn}
<ide> />
<ide> <Text>{this.state.eventSwitchIsOn ? 'On' : 'Off'}</Text>
<ide> </View>
<ide> <View>
<ide> <Switch
<del> onValueChange={value =>
<add> onValueChange={(value) =>
<ide> this.setState({eventSwitchRegressionIsOn: value})
<ide> }
<ide> style={{marginBottom: 10}}
<ide> value={this.state.eventSwitchRegressionIsOn}
<ide> />
<ide> <Switch
<del> onValueChange={value =>
<add> onValueChange={(value) =>
<ide> this.setState({eventSwitchRegressionIsOn: value})
<ide> }
<ide> style={{marginBottom: 10}}
<ide><path>RNTester/js/examples/TVEventHandler/TVEventHandlerExample.js
<ide> class TVEventHandlerView extends React.Component<Props, State> {
<ide>
<ide> _enableTVEventHandler() {
<ide> this._tvEventHandler = new TVEventHandler();
<del> this._tvEventHandler.enable(this, function(cmp, evt) {
<add> this._tvEventHandler.enable(this, function (cmp, evt) {
<ide> cmp.setState({
<ide> lastEventType: evt.eventType,
<ide> });
<ide><path>RNTester/js/examples/Text/TextExample.android.js
<ide> exports.description = 'Base component for rendering styled text.';
<ide> exports.examples = [
<ide> {
<ide> title: 'Basic text',
<del> render: function(): React.Element<typeof TextExample> {
<add> render: function (): React.Element<typeof TextExample> {
<ide> return <TextExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/Text/TextExample.ios.js
<ide> class TextRenderInfoExample extends React.Component<*, *> {
<ide> />
<ide> <Text
<ide> style={{fontSize: this.state.fontSize}}
<del> onTextLayout={event => {
<add> onTextLayout={(event) => {
<ide> const {lines} = event.nativeEvent;
<ide> if (lines.length > 0) {
<ide> this.setState({textMetrics: lines[lines.length - 1]});
<ide> class TextWithCapBaseBox extends React.Component<*, *> {
<ide> render() {
<ide> return (
<ide> <Text
<del> onTextLayout={event => {
<add> onTextLayout={(event) => {
<ide> const {lines} = event.nativeEvent;
<ide> if (lines.length > 0) {
<ide> this.setState({textMetrics: lines[0]});
<ide> exports.displayName = 'TextExample';
<ide> exports.examples = [
<ide> {
<ide> title: 'Wrap',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Text>
<ide> The text should wrap if it goes on multiple lines. See, this is going
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: "Substring Emoji (should only see 'test')",
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <Text>{'test🙃'.substring(0, 5)}</Text>;
<ide> },
<ide> },
<ide> {
<ide> title: 'Transparent Background Color',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Text style={{backgroundColor: '#00000020', padding: 10}}>
<ide> Text in a gray box!
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Text metrics',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <TextRenderInfoExample />;
<ide> },
<ide> },
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Padding',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Text style={{padding: 10}}>
<ide> This text is indented by 10px padding on all sides.
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Font Family',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text style={{fontFamily: Platform.isTV ? 'Times' : 'Cochin'}}>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Font Size',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text style={{fontSize: 23}}>Size 23</Text>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Color',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text style={{color: 'red'}}>Red color</Text>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Font Weight',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text style={{fontSize: 20, fontWeight: '100'}}>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Font Style',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text style={{fontStyle: 'normal'}}>Normal text</Text>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Selectable',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text selectable={true}>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Text Decoration',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text
<ide> exports.examples = [
<ide> description: ('Nested text components will inherit the styles of their ' +
<ide> 'parents (only backgroundColor is inherited from non-Text parents). ' +
<ide> '<Text> only supports other <Text> and raw text (strings) as children.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Text Align',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text>auto (default) - english LTR</Text>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Letter Spacing',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text style={{letterSpacing: 0}}>letterSpacing = 0</Text>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Spaces',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Text>
<ide> A {'generated'} {'string'} and some spaces
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Line Height',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Text>
<ide> <Text style={{lineHeight: 35}}>
<ide> exports.examples = [
<ide> {
<ide> title: 'Empty Text',
<ide> description: "It's ok to have Text with zero or null children.",
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <Text />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Toggling Attributes',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <AttributeToggler />;
<ide> },
<ide> },
<ide> {
<ide> title: 'backgroundColor attribute',
<ide> description: 'backgroundColor is inherited from all types of views.',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <Text style={{backgroundColor: 'yellow'}}>
<ide> Yellow container background,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'numberOfLines attribute',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text numberOfLines={1}>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Text highlighting (tap the link to see highlight)',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'allowFontScaling attribute',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Text shadow',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Ellipsize mode',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text numberOfLines={1}>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Font variants',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text style={{fontVariant: ['small-caps']}}>Small Caps{'\n'}</Text>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Nested content',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> // iOS-only because it relies on inline views being able to size to content.
<ide> // Android's implementation requires that a width and height be specified
<ide> // on the inline view.
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Dynamic Font Size Adjustment',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <AdjustingFontSize />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Text Align with RTL',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <TextAlignRTLExample />;
<ide> },
<ide> },
<ide> {
<ide> title: "Text `alignItems: 'baseline'` style",
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <TextBaseLineLayoutExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Transform',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text style={{textTransform: 'uppercase'}}>
<ide><path>RNTester/js/examples/TextInput/TextInputExample.android.js
<ide> class AutogrowingTextInputExample extends React.Component<{...}> {
<ide> step={10}
<ide> /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
<ide> * found when making Flow check .android.js files. */
<del> onValueChange={value => this.setState({width: value})}
<add> onValueChange={(value) => this.setState({width: value})}
<ide> />
<ide> <Text>Multiline:</Text>
<ide> <Switch
<ide> class AutogrowingTextInputExample extends React.Component<{...}> {
<ide> value={this.state.multiline}
<ide> /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
<ide> * found when making Flow check .android.js files. */
<del> onValueChange={value => this.setState({multiline: value})}
<add> onValueChange={(value) => this.setState({multiline: value})}
<ide> />
<ide> <Text>TextInput:</Text>
<ide> <TextInput
<ide> class AutogrowingTextInputExample extends React.Component<{...}> {
<ide> style={[style, {width: this.state.width + '%'}]}
<ide> /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
<ide> * found when making Flow check .android.js files. */
<del> onChangeText={value => this.setState({text: value})}
<del> onContentSizeChange={event =>
<add> onChangeText={(value) => this.setState({text: value})}
<add> onContentSizeChange={(event) =>
<ide> /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
<ide> * found when making Flow check .android.js files. */
<ide> this.setState({contentSize: event.nativeEvent.contentSize})
<ide> exports.examples = ([
<ide> ...TextInputSharedExamples,
<ide> {
<ide> title: 'Colors and text inputs',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Text input, themes and heights',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <TextInput
<ide> placeholder="If you set height, beware of padding set from themes"
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'letterSpacing',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Passwords',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Editable',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <TextInput
<ide> defaultValue="Can't touch this! (>'-')> ^(' - ')^ <('-'<) (>'-')> ^(' - ')^"
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Multiline',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> exports.examples = ([
<ide> {
<ide> title: 'Fixed number of lines',
<ide> platform: 'android',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Auto-expanding',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <AutogrowingTextInputExample
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Return key',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> const returnKeyTypes = [
<ide> 'none',
<ide> 'go',
<ide> exports.examples = ([
<ide> 'next',
<ide> ];
<ide> const returnKeyLabels = ['Compile', 'React Native'];
<del> const examples = returnKeyTypes.map(type => {
<add> const examples = returnKeyTypes.map((type) => {
<ide> return (
<ide> <TextInput
<ide> key={type}
<ide> exports.examples = ([
<ide> />
<ide> );
<ide> });
<del> const types = returnKeyLabels.map(type => {
<add> const types = returnKeyLabels.map((type) => {
<ide> return (
<ide> <TextInput
<ide> key={type}
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Inline Images',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Toggle Default Padding',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <ToggleDefaultPaddingExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/TextInput/TextInputExample.ios.js
<ide> class TextInputAccessoryViewExample extends React.Component<{...}, *> {
<ide> <TextInput
<ide> style={styles.default}
<ide> inputAccessoryViewID={inputAccessoryViewID}
<del> onChangeText={text => this.setState({text})}
<add> onChangeText={(text) => this.setState({text})}
<ide> value={this.state.text}
<ide> />
<ide> <InputAccessoryView nativeID={inputAccessoryViewID}>
<ide> class RewriteExampleKana extends React.Component<$FlowFixMeProps, any> {
<ide> <View style={styles.rewriteContainer}>
<ide> <TextInput
<ide> multiline={false}
<del> onChangeText={text => {
<add> onChangeText={(text) => {
<ide> this.setState({text: text.replace(/ひ/g, '日')});
<ide> }}
<ide> style={styles.default}
<ide> class SecureEntryExample extends React.Component<$FlowFixMeProps, any> {
<ide> secureTextEntry={true}
<ide> style={styles.default}
<ide> defaultValue="abc"
<del> onChangeText={text => this.setState({text})}
<add> onChangeText={(text) => this.setState({text})}
<ide> value={this.state.text}
<ide> />
<ide> <Text>Current text is: {this.state.text}</Text>
<ide> class SecureEntryExample extends React.Component<$FlowFixMeProps, any> {
<ide> <TextInput
<ide> style={styles.default}
<ide> defaultValue="cde"
<del> onChangeText={text => this.setState({password: text})}
<add> onChangeText={(text) => this.setState({password: text})}
<ide> secureTextEntry={this.state.isSecureTextEntry}
<ide> value={this.state.password}
<ide> />
<ide> <Switch
<del> onValueChange={value => {
<add> onValueChange={(value) => {
<ide> this.setState({isSecureTextEntry: value});
<ide> }}
<ide> style={{marginLeft: 4}}
<ide> class AutogrowingTextInputExample extends React.Component<
<ide> minimumValue={0}
<ide> maximumValue={100}
<ide> step={10}
<del> onValueChange={value => this.setState({width: value})}
<add> onValueChange={(value) => this.setState({width: value})}
<ide> />
<ide> <Text>Multiline:</Text>
<ide> <Switch
<ide> value={this.state.multiline}
<del> onValueChange={value => this.setState({multiline: value})}
<add> onValueChange={(value) => this.setState({multiline: value})}
<ide> />
<ide> <Text>TextInput:</Text>
<ide> <TextInput
<ide> value="prop"
<ide> multiline={this.state.multiline}
<ide> style={[style, {width: this.state.width + '%'}]}
<del> onChangeText={value => this.setState({text: value})}
<del> onContentSizeChange={event =>
<add> onChangeText={(value) => this.setState({text: value})}
<add> onContentSizeChange={(event) =>
<ide> this.setState({contentSize: event.nativeEvent.contentSize})
<ide> }
<ide> {...props}
<ide> exports.examples = ([
<ide> ...TextInputSharedExamples,
<ide> {
<ide> title: 'Live Re-Write (ひ -> 日)',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <RewriteExampleKana />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Keyboard Accessory View',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <TextInputAccessoryViewExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Nested content and `value` property',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <WithLabel label="singleline">
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Keyboard appearance',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> const keyboardAppearance = ['default', 'light', 'dark'];
<del> const examples = keyboardAppearance.map(type => {
<add> const examples = keyboardAppearance.map((type) => {
<ide> return (
<ide> <WithLabel key={type} label={type}>
<ide> <TextInput keyboardAppearance={type} style={styles.default} />
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Return key types',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> const returnKeyTypes = [
<ide> 'default',
<ide> 'go',
<ide> exports.examples = ([
<ide> 'done',
<ide> 'emergency-call',
<ide> ];
<del> const examples = returnKeyTypes.map(type => {
<add> const examples = returnKeyTypes.map((type) => {
<ide> return (
<ide> <WithLabel key={type} label={type}>
<ide> <TextInput returnKeyType={type} style={styles.default} />
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Enable return key automatically',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <WithLabel label="true">
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Secure text entry',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <SecureEntryExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Colored input text',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Colored highlight/cursor for text input',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Clear button mode',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> const clearButtonModes = [
<ide> 'never',
<ide> 'while-editing',
<ide> 'unless-editing',
<ide> 'always',
<ide> ];
<del> const examples = clearButtonModes.map(mode => {
<add> const examples = clearButtonModes.map((mode) => {
<ide> return (
<ide> <WithLabel key={mode} label={mode}>
<ide> <TextInput
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Clear and select',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <WithLabel label="clearTextOnFocus">
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Multiline blur on submit',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> exports.examples = ([
<ide> returnKeyType="next"
<ide> blurOnSubmit={true}
<ide> multiline={true}
<del> onSubmitEditing={event =>
<add> onSubmitEditing={(event) =>
<ide> Alert.alert('Alert', event.nativeEvent.text)
<ide> }
<ide> />
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Multiline',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'TextInput Intrinsic Size',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <Text>Singleline TextInput</Text>
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Auto-expanding',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Auto-expanding',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <AutogrowingTextInputExample
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'TextInput maxLength',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <WithLabel label="maxLength: 5">
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'Text Content Type',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <WithLabel label="emailAddress">
<ide> exports.examples = ([
<ide> },
<ide> {
<ide> title: 'TextInput Placeholder Styles',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <WithLabel label="letterSpacing: 10 lineHeight: 20 textAlign: 'center'">
<ide><path>RNTester/js/examples/TextInput/TextInputSharedExamples.js
<ide> class RewriteExample extends React.Component<$FlowFixMeProps, any> {
<ide> autoCorrect={false}
<ide> multiline={false}
<ide> maxLength={limit}
<del> onChangeText={text => {
<add> onChangeText={(text) => {
<ide> text = text.replace(/ /g, '_');
<ide> this.setState({text});
<ide> }}
<ide> class RewriteExampleInvalidCharacters extends React.Component<
<ide> testID="rewrite_no_sp_input"
<ide> autoCorrect={false}
<ide> multiline={false}
<del> onChangeText={text => {
<add> onChangeText={(text) => {
<ide> this.setState({text: text.replace(/\s/g, '')});
<ide> }}
<ide> style={styles.default}
<ide> class RewriteInvalidCharactersAndClearExample extends React.Component<
<ide> <TextInput
<ide> testID="rewrite_clear_input"
<ide> autoCorrect={false}
<del> ref={ref => {
<add> ref={(ref) => {
<ide> this.inputRef = ref;
<ide> }}
<ide> multiline={false}
<del> onChangeText={text => {
<add> onChangeText={(text) => {
<ide> this.setState({text: text.replace(/\s/g, '')});
<ide> }}
<ide> style={styles.default}
<ide> class RewriteInvalidCharactersAndClearExample extends React.Component<
<ide> }
<ide>
<ide> class BlurOnSubmitExample extends React.Component<{...}> {
<del> focusNextField = nextField => {
<add> focusNextField = (nextField) => {
<ide> this.refs[nextField].focus();
<ide> };
<ide>
<ide> class TextEventsExample extends React.Component<{...}, $FlowFixMeState> {
<ide> prev3Text: '<No Event>',
<ide> };
<ide>
<del> updateText = text => {
<del> this.setState(state => {
<add> updateText = (text) => {
<add> this.setState((state) => {
<ide> return {
<ide> curText: text,
<ide> prevText: state.curText,
<ide> class TextEventsExample extends React.Component<{...}, $FlowFixMeState> {
<ide> multiline
<ide> onFocus={() => this.updateText('onFocus')}
<ide> onBlur={() => this.updateText('onBlur')}
<del> onChange={event =>
<add> onChange={(event) =>
<ide> this.updateText('onChange text: ' + event.nativeEvent.text)
<ide> }
<del> onContentSizeChange={event =>
<add> onContentSizeChange={(event) =>
<ide> this.updateText(
<ide> 'onContentSizeChange size: ' +
<ide> JSON.stringify(event.nativeEvent.contentSize),
<ide> )
<ide> }
<del> onEndEditing={event =>
<add> onEndEditing={(event) =>
<ide> this.updateText('onEndEditing text: ' + event.nativeEvent.text)
<ide> }
<del> onSubmitEditing={event =>
<add> onSubmitEditing={(event) =>
<ide> this.updateText('onSubmitEditing text: ' + event.nativeEvent.text)
<ide> }
<del> onKeyPress={event =>
<add> onKeyPress={(event) =>
<ide> this.updateText('onKeyPress key: ' + event.nativeEvent.key)
<ide> }
<ide> style={styles.singleLine}
<ide> class TokenizedTextExample extends React.Component<
<ide> parts.push(_text);
<ide>
<ide> //highlight hashtags
<del> parts = parts.map(text => {
<add> parts = parts.map((text) => {
<ide> if (/^#/.test(text)) {
<ide> return (
<ide> <Text key={text} style={styles.hashtag}>
<ide> class TokenizedTextExample extends React.Component<
<ide> <TextInput
<ide> multiline={true}
<ide> style={styles.multiline}
<del> onChangeText={text => {
<add> onChangeText={(text) => {
<ide> this.setState({text});
<ide> }}>
<ide> <Text>{parts}</Text>
<ide> class SelectionExample extends React.Component<
<ide> <View>
<ide> <TextInput
<ide> multiline={this.props.multiline}
<del> onChangeText={value => this.setState({value})}
<add> onChangeText={(value) => this.setState({value})}
<ide> onSelectionChange={this.onSelectionChange.bind(this)}
<del> ref={textInput => (this._textInput = textInput)}
<add> ref={(textInput) => (this._textInput = textInput)}
<ide> selection={this.state.selection}
<ide> style={this.props.style}
<ide> value={this.state.value}
<ide> class SelectionExample extends React.Component<
<ide> module.exports = ([
<ide> {
<ide> title: 'Auto-focus',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <TextInput
<ide> autoFocus={true}
<ide> module.exports = ([
<ide> },
<ide> {
<ide> title: "Live Re-Write (<sp> -> '_') + maxLength",
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <RewriteExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Live Re-Write (no spaces allowed)',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <RewriteExampleInvalidCharacters />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Live Re-Write (no spaces allowed) and clear',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <RewriteInvalidCharactersAndClearExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Auto-capitalize',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <WithLabel label="none">
<ide> module.exports = ([
<ide> },
<ide> {
<ide> title: 'Auto-correct',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <WithLabel label="true">
<ide> module.exports = ([
<ide> },
<ide> {
<ide> title: 'Keyboard types',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> const keyboardTypes = [
<ide> 'default',
<ide> 'ascii-capable',
<ide> module.exports = ([
<ide> 'ascii-capable-number-pad',
<ide> 'numeric',
<ide> ];
<del> const examples = keyboardTypes.map(type => {
<add> const examples = keyboardTypes.map((type) => {
<ide> return (
<ide> <WithLabel key={type} label={type}>
<ide> <TextInput keyboardType={type} style={styles.default} />
<ide> module.exports = ([
<ide> },
<ide> {
<ide> title: 'Blur on submit',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <BlurOnSubmitExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Event handling',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <TextEventsExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'fontFamily, fontWeight and fontStyle',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> const fontFamilyA = Platform.OS === 'ios' ? 'Cochin' : 'sans-serif';
<ide> const fontFamilyB = Platform.OS === 'ios' ? 'Courier' : 'serif';
<ide>
<ide> module.exports = ([
<ide> },
<ide> {
<ide> title: 'Attributed text',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <TokenizedTextExample />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Text selection & cursor placement',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <SelectionExample
<ide><path>RNTester/js/examples/Timer/TimerExample.js
<ide> class RequestIdleCallbackTester extends React.Component<
<ide> this._idleTimer = null;
<ide> }
<ide>
<del> this._idleTimer = requestIdleCallback(deadline => {
<add> this._idleTimer = requestIdleCallback((deadline) => {
<ide> let message = '';
<ide>
<ide> if (shouldBurnCPU) {
<ide> class RequestIdleCallbackTester extends React.Component<
<ide> }
<ide>
<ide> this._idleTimer = requestIdleCallback(
<del> deadline => {
<add> (deadline) => {
<ide> this.setState({
<ide> message: `${deadline.timeRemaining()}ms remaining in frame, it did timeout: ${
<ide> deadline.didTimeout ? 'yes' : 'no'
<ide> class RequestIdleCallbackTester extends React.Component<
<ide> this._idleTimer = null;
<ide> }
<ide>
<del> const handler = deadline => {
<add> const handler = (deadline) => {
<ide> while (deadline.timeRemaining() > 5) {
<ide> burnCPU(5);
<ide> this.setState({
<ide> exports.examples = [
<ide> description: ('Execute function fn t milliseconds in the future. If ' +
<ide> 't === 0, it will be enqueued immediately in the next event loop. ' +
<ide> 'Larger values will fire on the closest frame.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TimerTester type="setTimeout" dt={0} />
<ide> exports.examples = [
<ide> {
<ide> title: 'this.requestAnimationFrame(fn)',
<ide> description: 'Execute function fn on the next frame.',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TimerTester type="requestAnimationFrame" />
<ide> exports.examples = [
<ide> {
<ide> title: 'this.requestIdleCallback(fn)',
<ide> description: 'Execute function fn on the next JS frame that has idle time',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <RequestIdleCallbackTester />
<ide> exports.examples = [
<ide> {
<ide> title: 'this.setImmediate(fn)',
<ide> description: 'Execute function fn at the end of the current JS event loop.',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <View>
<ide> <TimerTester type="setImmediate" />
<ide> exports.examples = [
<ide> title: 'this.setInterval(fn, t)',
<ide> description: ('Execute function fn every t milliseconds until cancelled ' +
<ide> 'or component is unmounted.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> type IntervalExampleProps = $ReadOnly<{||}>;
<ide> type IntervalExampleState = {|
<ide> showTimer: boolean,
<ide> exports.examples = [
<ide> return (
<ide> <View>
<ide> <TimerTester
<del> ref={ref => (this._timerTester = ref)}
<add> ref={(ref) => (this._timerTester = ref)}
<ide> dt={25}
<ide> type="setInterval"
<ide> />
<ide><path>RNTester/js/examples/ToastAndroid/ToastAndroidExample.android.js
<ide> exports.description =
<ide> exports.examples = [
<ide> {
<ide> title: 'Basic toast',
<del> render: function(): React.Element<typeof ToastExample> {
<add> render: function (): React.Element<typeof ToastExample> {
<ide> return <ToastExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/Touchable/TouchableExample.js
<ide> class TouchableFeedbackEvents extends React.Component<{...}, $FlowFixMeState> {
<ide> );
<ide> }
<ide>
<del> _appendEvent = eventName => {
<add> _appendEvent = (eventName) => {
<ide> const limit = 6;
<ide> const eventLog = this.state.eventLog.slice(0, limit - 1);
<ide> eventLog.unshift(eventName);
<ide> class TouchableDelayEvents extends React.Component<{...}, $FlowFixMeState> {
<ide> );
<ide> }
<ide>
<del> _appendEvent = eventName => {
<add> _appendEvent = (eventName) => {
<ide> const limit = 6;
<ide> const eventLog = this.state.eventLog.slice(0, limit - 1);
<ide> eventLog.unshift(eventName);
<ide> class ForceTouchExample extends React.Component<{...}, $FlowFixMeState> {
<ide> style={styles.wrapper}
<ide> testID="touchable_3dtouch_button"
<ide> onStartShouldSetResponder={() => true}
<del> onResponderMove={event =>
<add> onResponderMove={(event) =>
<ide> this.setState({force: event.nativeEvent.force})
<ide> }
<del> onResponderRelease={event => this.setState({force: 0})}>
<add> onResponderRelease={(event) => this.setState({force: 0})}>
<ide> <Text style={styles.button}>Press Me</Text>
<ide> </View>
<ide> </View>
<ide> exports.examples = [
<ide> 'child view is fully opaque, although it can be made to work as a simple ' +
<ide> 'background color change as well with the activeOpacity and ' +
<ide> 'underlayColor props.': string),
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <TouchableHighlightBox />;
<ide> },
<ide> },
<ide> {
<ide> title: '<TouchableWithoutFeedback>',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return <TouchableWithoutFeedbackBox />;
<ide> },
<ide> },
<ide> exports.examples = [
<ide> description: ('TouchableNativeFeedback can have an AnimatedComponent as a' +
<ide> 'direct child.': string),
<ide> platform: 'android',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> const mScale = new Animated.Value(1);
<ide> Animated.timing(mScale, {
<ide> toValue: 0.3,
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: '<Text onPress={fn}> with highlight',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <TextOnPressBox />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Touchable feedback events',
<ide> description: ('<Touchable*> components accept onPress, onPressIn, ' +
<ide> 'onPressOut, and onLongPress as props.': string),
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <TouchableFeedbackEvents />;
<ide> },
<ide> },
<ide> exports.examples = [
<ide> description: ('<Touchable*> components also accept delayPressIn, ' +
<ide> 'delayPressOut, and delayLongPress as props. These props impact the ' +
<ide> 'timing of feedback events.': string),
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <TouchableDelayEvents />;
<ide> },
<ide> },
<ide> {
<ide> title: '3D Touch / Force Touch',
<ide> description:
<ide> 'iPhone 8 and 8 plus support 3D touch, which adds a force property to touches',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <ForceTouchExample />;
<ide> },
<ide> platform: 'ios',
<ide> exports.examples = [
<ide> title: 'Touchable Hit Slop',
<ide> description: ('<Touchable*> components accept hitSlop prop which extends the touch area ' +
<ide> 'without changing the view bounds.': string),
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <TouchableHitSlop />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Touchable Native Methods',
<ide> description: ('Some <Touchable*> components expose native methods like `measure`.': string),
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <TouchableNativeMethods />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Disabled Touchable*',
<ide> description: ('<Touchable*> components accept disabled prop which prevents ' +
<ide> 'any interaction with component': string),
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <TouchableDisabled />;
<ide> },
<ide> },
<ide> {
<ide> title: 'Custom Ripple Radius (Android-only)',
<ide> description: ('Ripple radius on TouchableNativeFeedback can be controlled': string),
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <CustomRippleRadius />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/TurboModule/SampleTurboModuleExample.js
<ide> class SampleTurboModuleExample extends React.Component<{||}, State> {
<ide> // Add calls to methods in TurboModule here
<ide> _tests = {
<ide> callback: () =>
<del> NativeSampleTurboModule.getValueWithCallback(callbackValue =>
<add> NativeSampleTurboModule.getValueWithCallback((callbackValue) =>
<ide> this._setResult('callback', callbackValue),
<ide> ),
<ide> promise: () =>
<del> NativeSampleTurboModule.getValueWithPromise(false).then(valuePromise =>
<add> NativeSampleTurboModule.getValueWithPromise(false).then((valuePromise) =>
<ide> this._setResult('promise', valuePromise),
<ide> ),
<ide> rejectPromise: () =>
<ide> NativeSampleTurboModule.getValueWithPromise(true)
<ide> .then(() => {})
<del> .catch(e => this._setResult('rejectPromise', e.message)),
<add> .catch((e) => this._setResult('rejectPromise', e.message)),
<ide> getConstants: () => NativeSampleTurboModule.getConstants(),
<ide> voidFunc: () => NativeSampleTurboModule.voidFunc(),
<ide> getBool: () => NativeSampleTurboModule.getBool(true),
<ide> class SampleTurboModuleExample extends React.Component<{||}, State> {
<ide> }
<ide> if (Platform.OS === 'ios') {
<ide> // iOS is fully implemented, so show all results immediately.
<del> Object.keys(this._tests).forEach(item =>
<add> Object.keys(this._tests).forEach((item) =>
<ide> this._setResult(item, this._tests[item]()),
<ide> );
<ide> }
<ide> class SampleTurboModuleExample extends React.Component<{||}, State> {
<ide> <TouchableOpacity
<ide> style={[styles.column, styles.button]}
<ide> onPress={() =>
<del> Object.keys(this._tests).forEach(item =>
<add> Object.keys(this._tests).forEach((item) =>
<ide> this._setResult(item, this._tests[item]()),
<ide> )
<ide> }>
<ide> class SampleTurboModuleExample extends React.Component<{||}, State> {
<ide> </View>
<ide> <FlatList
<ide> data={Object.keys(this._tests)}
<del> keyExtractor={item => item}
<add> keyExtractor={(item) => item}
<ide> renderItem={({item}) => (
<ide> <View style={styles.item}>
<ide> <TouchableOpacity
<ide> style={[styles.column, styles.button]}
<del> onPress={e => this._setResult(item, this._tests[item]())}>
<add> onPress={(e) => this._setResult(item, this._tests[item]())}>
<ide> <Text style={styles.buttonText}>{item}</Text>
<ide> </TouchableOpacity>
<ide> <View style={[styles.column]}>{this._renderResult(item)}</View>
<ide><path>RNTester/js/examples/TurboModule/TurboModuleExample.js
<ide> exports.description = 'Usage of TurboModule';
<ide> exports.examples = [
<ide> {
<ide> title: 'SampleTurboModule',
<del> render: function(): React.Element<any> {
<add> render: function (): React.Element<any> {
<ide> return <SampleTurboModuleExample />;
<ide> },
<ide> },
<ide><path>RNTester/js/examples/View/ViewExample.js
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'BackfaceVisibility',
<del> render: function(): React.Node {
<add> render: function (): React.Node {
<ide> return (
<ide> <>
<ide> <Text style={{paddingBottom: 10}}>
<ide><path>RNTester/js/examples/WebSocket/WebSocketExample.js
<ide> class WebSocketImage extends React.Component {
<ide> componentDidMount() {
<ide> let ws = (this.ws = new WebSocket(this.props.url));
<ide> ws.binaryType = 'blob';
<del> ws.onmessage = event => {
<add> ws.onmessage = (event) => {
<ide> if (event.data instanceof Blob) {
<ide> const blob = event.data;
<ide> if (this.state.blob) {
<ide> class WebSocketImage extends React.Component {
<ide> this.setState({blob});
<ide> }
<ide> };
<del> ws.onopen = event => {
<add> ws.onopen = (event) => {
<ide> ws.send('getImage');
<ide> };
<ide> }
<ide> class WebSocketExample extends React.Component<any, any, State> {
<ide>
<ide> _connect = () => {
<ide> const socket = new WebSocket(this.state.url);
<del> WS_EVENTS.forEach(ev => socket.addEventListener(ev, this._onSocketEvent));
<add> WS_EVENTS.forEach((ev) => socket.addEventListener(ev, this._onSocketEvent));
<ide> this.setState({
<ide> socket,
<ide> socketState: socket.readyState,
<ide> class WebSocketExample extends React.Component<any, any, State> {
<ide> this.setState({
<ide> fetchStatus: 'fetching',
<ide> });
<del> fetch(this.state.httpUrl).then(response => {
<add> fetch(this.state.httpUrl).then((response) => {
<ide> if (response.status >= 200 && response.status < 400) {
<ide> this.setState({
<ide> fetchStatus: 'OK',
<ide> class WebSocketExample extends React.Component<any, any, State> {
<ide> style={styles.textInput}
<ide> autoCorrect={false}
<ide> placeholder="Server URL..."
<del> onChangeText={url => this.setState({url})}
<add> onChangeText={(url) => this.setState({url})}
<ide> value={this.state.url}
<ide> />
<ide> <View style={styles.buttonRow}>
<ide> class WebSocketExample extends React.Component<any, any, State> {
<ide> style={styles.textInput}
<ide> autoCorrect={false}
<ide> placeholder="Type message here..."
<del> onChangeText={outgoingMessage => this.setState({outgoingMessage})}
<add> onChangeText={(outgoingMessage) => this.setState({outgoingMessage})}
<ide> value={this.state.outgoingMessage}
<ide> />
<ide> <View style={styles.buttonRow}>
<ide> class WebSocketExample extends React.Component<any, any, State> {
<ide> style={styles.textInput}
<ide> autoCorrect={false}
<ide> placeholder="HTTP URL..."
<del> onChangeText={httpUrl => this.setState({httpUrl})}
<add> onChangeText={(httpUrl) => this.setState({httpUrl})}
<ide> value={this.state.httpUrl}
<ide> />
<ide> <View style={styles.buttonRow}>
<ide><path>RNTester/js/examples/XHR/XHRExampleAbortController.js
<ide> class XHRExampleAbortController extends React.Component<{...}, {...}> {
<ide> fetch('https://reactnative.dev/', {
<ide> signal: abortController.signal,
<ide> })
<del> .then(res => res.text())
<del> .then(res => Alert.alert(res))
<del> .catch(err => Alert.alert(err.message));
<add> .then((res) => res.text())
<add> .then((res) => Alert.alert(res))
<add> .catch((err) => Alert.alert(err.message));
<ide> this._timeout = setTimeout(() => {
<ide> abortController.abort();
<ide> }, abortDelay);
<ide><path>RNTester/js/examples/XHR/XHRExampleBinaryUpload.js
<ide> class XHRExampleBinaryUpload extends React.Component<{...}, $FlowFixMeState> {
<ide> <Text>Upload 255 bytes as...</Text>
<ide> <Picker
<ide> selectedValue={this.state.type}
<del> onValueChange={type => this.setState({type})}>
<del> {Object.keys(BINARY_TYPES).map(type => (
<add> onValueChange={(type) => this.setState({type})}>
<add> {Object.keys(BINARY_TYPES).map((type) => (
<ide> <Picker.Item key={type} label={type} value={type} />
<ide> ))}
<ide> </Picker>
<ide><path>RNTester/js/examples/XHR/XHRExampleDownload.js
<ide> class XHRExampleDownload extends React.Component<{...}, Object> {
<ide> });
<ide> }
<ide> };
<del> const onprogress = event => {
<add> const onprogress = (event) => {
<ide> this.setState({
<ide> progressTotal: event.total,
<ide> progressLoaded: event.loaded,
<ide> class XHRExampleDownload extends React.Component<{...}, Object> {
<ide> return;
<ide> }
<ide> if (xhr.status === 200) {
<del> let responseType = `Response is a string, ${
<del> xhr.response.length
<del> } characters long.`;
<add> let responseType = `Response is a string, ${xhr.response.length} characters long.`;
<ide> if (xhr.response instanceof ArrayBuffer) {
<del> responseType = `Response is an ArrayBuffer, ${
<del> xhr.response.byteLength
<del> } bytes long.`;
<add> responseType = `Response is an ArrayBuffer, ${xhr.response.byteLength} bytes long.`;
<ide> }
<ide> Alert.alert('Download complete!', responseType);
<ide> } else if (xhr.status !== 0) {
<ide> class XHRExampleDownload extends React.Component<{...}, Object> {
<ide> <Text>onreadystatechange handler</Text>
<ide> <Switch
<ide> value={this.state.readystateHandler}
<del> onValueChange={readystateHandler =>
<add> onValueChange={(readystateHandler) =>
<ide> this.setState({readystateHandler})
<ide> }
<ide> />
<ide> class XHRExampleDownload extends React.Component<{...}, Object> {
<ide> <Text>onprogress handler</Text>
<ide> <Switch
<ide> value={this.state.progressHandler}
<del> onValueChange={progressHandler => this.setState({progressHandler})}
<add> onValueChange={(progressHandler) =>
<add> this.setState({progressHandler})
<add> }
<ide> />
<ide> </View>
<ide> <View style={styles.configRow}>
<ide> <Text>download as arraybuffer</Text>
<ide> <Switch
<ide> value={this.state.arraybuffer}
<del> onValueChange={arraybuffer => this.setState({arraybuffer})}
<add> onValueChange={(arraybuffer) => this.setState({arraybuffer})}
<ide> />
<ide> </View>
<ide> {button}
<ide><path>RNTester/js/examples/XHR/XHRExampleFetch.js
<ide> class XHRExampleFetch extends React.Component<any, any> {
<ide>
<ide> submit(uri: string) {
<ide> fetch(uri)
<del> .then(response => {
<add> .then((response) => {
<ide> this.responseURL = response.url;
<ide> this.responseHeaders = response.headers;
<ide> return response.text();
<ide> })
<del> .then(body => {
<add> .then((body) => {
<ide> this.setState({responseText: body});
<ide> });
<ide> }
<ide> class XHRExampleFetch extends React.Component<any, any> {
<ide> <TextInput
<ide> returnKeyType="go"
<ide> defaultValue="http://www.posttestserver.com/post.php"
<del> onSubmitEditing={event => {
<add> onSubmitEditing={(event) => {
<ide> this.submit(event.nativeEvent.text);
<ide> }}
<ide> style={styles.textInput}
<ide><path>RNTester/js/utils/RNTesterList.android.js
<ide> const APIExamples: Array<RNTesterExample> = [
<ide>
<ide> const Modules: any = {};
<ide>
<del>APIExamples.concat(ComponentExamples).forEach(Example => {
<add>APIExamples.concat(ComponentExamples).forEach((Example) => {
<ide> Modules[Example.key] = Example.module;
<ide> });
<ide>
<ide><path>RNTester/js/utils/RNTesterList.ios.js
<ide> const APIExamples: Array<RNTesterExample> = [
<ide>
<ide> const Modules: {...} = {};
<ide>
<del>APIExamples.concat(ComponentExamples).forEach(Example => {
<add>APIExamples.concat(ComponentExamples).forEach((Example) => {
<ide> Modules[Example.key] = Example.module;
<ide> });
<ide>
<ide><path>RNTester/js/utils/RNTesterStatePersister.js
<ide> function createContainer<Props: Object, State>(
<ide> /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment
<ide> * suppresses an error when upgrading Flow's support for React. To see the
<ide> * error delete this comment and run Flow. */
<del> static displayName = `RNTesterStatePersister(${Component.displayName ||
<del> Component.name})`;
<add> static displayName = `RNTesterStatePersister(${
<add> Component.displayName || Component.name
<add> })`;
<ide> state = {value: spec.getInitialState(this.props)};
<ide> _cacheKey = `RNTester:${spec.version || 'v1'}:${spec.cacheKeySuffix(
<ide> this.props,
<ide> function createContainer<Props: Object, State>(
<ide> });
<ide> }
<ide> _passSetState = (stateLamda: (state: State) => State): void => {
<del> this.setState(state => {
<add> this.setState((state) => {
<ide> const value = stateLamda(state.value);
<ide> AsyncStorage.setItem(this._cacheKey, JSON.stringify(value));
<ide> return {value};
<ide><path>ReactAndroid/src/androidTest/js/Asserts.js
<ide> const {NativeModules} = require('react-native');
<ide> const {Assert} = NativeModules;
<ide>
<ide> const Asserts = {
<del> assertEquals: function(expected, actual, msg) {
<add> assertEquals: function (expected, actual, msg) {
<ide> if (expected !== actual) {
<ide> Assert.fail(
<ide> msg ||
<ide> const Asserts = {
<ide> Assert.success();
<ide> }
<ide> },
<del> assertTrue: function(expr, msg) {
<add> assertTrue: function (expr, msg) {
<ide> Asserts.assertEquals(true, expr, msg);
<ide> },
<ide> };
<ide><path>ReactAndroid/src/androidTest/js/CatalystRootViewTestModule.js
<ide> class CatalystRootViewTestApp extends React.Component {
<ide> }
<ide>
<ide> const ReactRootViewTestModule = {
<del> setHeight: function(height) {
<add> setHeight: function (height) {
<ide> that.setState({height: height});
<ide> },
<ide> };
<ide><path>ReactAndroid/src/androidTest/js/DatePickerDialogTestModule.js
<ide> class DatePickerDialogTestApp extends React.Component {
<ide>
<ide> const DatePickerDialogTestModule = {
<ide> DatePickerDialogTestApp: DatePickerDialogTestApp,
<del> showDatePickerDialog: function(options) {
<add> showDatePickerDialog: function (options) {
<ide> DatePickerAndroid.open(options).then(
<ide> ({action, year, month, day}) => {
<ide> if (action === DatePickerAndroid.dateSetAction) {
<ide><path>ReactAndroid/src/androidTest/js/ImageErrorTestApp.js
<ide> const {Image, NativeModules, StyleSheet, View} = require('react-native');
<ide> const {Recording: RecordingModule} = NativeModules;
<ide>
<ide> class ImageErrorTestApp extends React.Component {
<del> onError = e => {
<add> onError = (e) => {
<ide> RecordingModule.record('Got error: ' + e.nativeEvent.error);
<ide> };
<ide>
<ide><path>ReactAndroid/src/androidTest/js/LayoutEventsTestApp.js
<ide> class LayoutEventsTestApp extends React.Component {
<ide> this.numParentLayouts = 0;
<ide> }
<ide>
<del> handleOnLayout = e => {
<add> handleOnLayout = (e) => {
<ide> const layout = e.nativeEvent.layout;
<ide> RecordingModule.record(
<ide> layout.x + ',' + layout.y + '-' + layout.width + 'x' + layout.height,
<ide> class LayoutEventsTestApp extends React.Component {
<ide> }
<ide> };
<ide>
<del> handleParentOnLayout = e => {
<add> handleParentOnLayout = (e) => {
<ide> if (this.numParentLayouts > 0) {
<ide> // This will cause the test to fail - the parent's layout doesn't change
<ide> // so we should only get the event once.
<ide><path>ReactAndroid/src/androidTest/js/MeasureLayoutTestModule.js
<ide> function shouldNotCallThisCallback() {
<ide>
<ide> const MeasureLayoutTestModule = {
<ide> MeasureLayoutTestApp: MeasureLayoutTestApp,
<del> verifyMeasureOnViewA: function() {
<del> UIManager.measure(A, function(a, b, width, height, x, y) {
<add> verifyMeasureOnViewA: function () {
<add> UIManager.measure(A, function (a, b, width, height, x, y) {
<ide> assertEquals(500, width);
<ide> assertEquals(500, height);
<ide> assertEquals(0, x);
<ide> assertEquals(0, y);
<ide> });
<ide> },
<del> verifyMeasureOnViewC: function() {
<del> UIManager.measure(C, function(a, b, width, height, x, y) {
<add> verifyMeasureOnViewC: function () {
<add> UIManager.measure(C, function (a, b, width, height, x, y) {
<ide> assertEquals(50, width);
<ide> assertEquals(150, height);
<ide> assertEquals(150, x);
<ide> assertEquals(150, y);
<ide> });
<ide> },
<del> verifyMeasureLayoutCRelativeToA: function() {
<del> UIManager.measureLayout(C, A, shouldNotCallThisCallback, function(
<add> verifyMeasureLayoutCRelativeToA: function () {
<add> UIManager.measureLayout(C, A, shouldNotCallThisCallback, function (
<ide> x,
<ide> y,
<ide> width,
<ide> const MeasureLayoutTestModule = {
<ide> assertEquals(150, y);
<ide> });
<ide> },
<del> verifyMeasureLayoutCRelativeToB: function() {
<del> UIManager.measureLayout(C, B, shouldNotCallThisCallback, function(
<add> verifyMeasureLayoutCRelativeToB: function () {
<add> UIManager.measureLayout(C, B, shouldNotCallThisCallback, function (
<ide> x,
<ide> y,
<ide> width,
<ide> const MeasureLayoutTestModule = {
<ide> assertEquals(70, y);
<ide> });
<ide> },
<del> verifyMeasureLayoutCRelativeToSelf: function() {
<del> UIManager.measureLayout(C, C, shouldNotCallThisCallback, function(
<add> verifyMeasureLayoutCRelativeToSelf: function () {
<add> UIManager.measureLayout(C, C, shouldNotCallThisCallback, function (
<ide> x,
<ide> y,
<ide> width,
<ide> const MeasureLayoutTestModule = {
<ide> assertEquals(0, y);
<ide> });
<ide> },
<del> verifyMeasureLayoutRelativeToParentOnViewA: function() {
<add> verifyMeasureLayoutRelativeToParentOnViewA: function () {
<ide> UIManager.measureLayoutRelativeToParent(
<ide> A,
<ide> shouldNotCallThisCallback,
<del> function(x, y, width, height) {
<add> function (x, y, width, height) {
<ide> assertEquals(500, width);
<ide> assertEquals(500, height);
<ide> assertEquals(0, x);
<ide> assertEquals(0, y);
<ide> },
<ide> );
<ide> },
<del> verifyMeasureLayoutRelativeToParentOnViewB: function() {
<add> verifyMeasureLayoutRelativeToParentOnViewB: function () {
<ide> UIManager.measureLayoutRelativeToParent(
<ide> B,
<ide> shouldNotCallThisCallback,
<del> function(x, y, width, height) {
<add> function (x, y, width, height) {
<ide> assertEquals(200, width);
<ide> assertEquals(300, height);
<ide> assertEquals(50, x);
<ide> assertEquals(80, y);
<ide> },
<ide> );
<ide> },
<del> verifyMeasureLayoutRelativeToParentOnViewC: function() {
<add> verifyMeasureLayoutRelativeToParentOnViewC: function () {
<ide> UIManager.measureLayoutRelativeToParent(
<ide> C,
<ide> shouldNotCallThisCallback,
<del> function(x, y, width, height) {
<add> function (x, y, width, height) {
<ide> assertEquals(50, width);
<ide> assertEquals(150, height);
<ide> assertEquals(100, x);
<ide> assertEquals(70, y);
<ide> },
<ide> );
<ide> },
<del> verifyMeasureLayoutDRelativeToB: function() {
<add> verifyMeasureLayoutDRelativeToB: function () {
<ide> UIManager.measureLayout(
<ide> D,
<ide> B,
<del> function() {
<add> function () {
<ide> assertEquals(true, true);
<ide> },
<ide> shouldNotCallThisCallback,
<ide> );
<ide> },
<del> verifyMeasureLayoutNonExistentTag: function() {
<add> verifyMeasureLayoutNonExistentTag: function () {
<ide> UIManager.measureLayout(
<ide> 192,
<ide> A,
<del> function() {
<add> function () {
<ide> assertEquals(true, true);
<ide> },
<ide> shouldNotCallThisCallback,
<ide> );
<ide> },
<del> verifyMeasureLayoutNonExistentAncestor: function() {
<add> verifyMeasureLayoutNonExistentAncestor: function () {
<ide> UIManager.measureLayout(
<ide> B,
<ide> 192,
<del> function() {
<add> function () {
<ide> assertEquals(true, true);
<ide> },
<ide> shouldNotCallThisCallback,
<ide> );
<ide> },
<del> verifyMeasureLayoutRelativeToParentNonExistentTag: function() {
<add> verifyMeasureLayoutRelativeToParentNonExistentTag: function () {
<ide> UIManager.measureLayoutRelativeToParent(
<ide> 192,
<del> function() {
<add> function () {
<ide> assertEquals(true, true);
<ide> },
<ide> shouldNotCallThisCallback,
<ide><path>ReactAndroid/src/androidTest/js/MultitouchHandlingTestAppModule.js
<ide> const {NativeModules, StyleSheet, View} = require('react-native');
<ide>
<ide> const {Recording} = NativeModules;
<ide>
<del>const extractSingleTouch = nativeEvent => {
<add>const extractSingleTouch = (nativeEvent) => {
<ide> const touches = nativeEvent.touches;
<ide> const changedTouches = nativeEvent.changedTouches;
<ide> const hasTouches = touches && touches.length > 0;
<ide> const extractSingleTouch = nativeEvent => {
<ide> };
<ide>
<ide> class TouchTestApp extends React.Component {
<del> handleStartShouldSetResponder = e => {
<add> handleStartShouldSetResponder = (e) => {
<ide> return true;
<ide> };
<ide>
<del> handleOnResponderMove = e => {
<add> handleOnResponderMove = (e) => {
<ide> e = extractSingleTouch(e.nativeEvent);
<ide> Recording.record('move;' + e.touches.length);
<ide> };
<ide>
<del> handleResponderStart = e => {
<add> handleResponderStart = (e) => {
<ide> e = extractSingleTouch(e.nativeEvent);
<ide> if (e.touches) {
<ide> Recording.record('start;' + e.touches.length);
<ide> class TouchTestApp extends React.Component {
<ide> }
<ide> };
<ide>
<del> handleResponderEnd = e => {
<add> handleResponderEnd = (e) => {
<ide> e = extractSingleTouch(e.nativeEvent);
<ide> if (e.touches) {
<ide> Recording.record('end;' + e.touches.length);
<ide><path>ReactAndroid/src/androidTest/js/PickerAndroidTestModule.js
<ide> class PickerAndroidTestApp extends React.Component {
<ide> );
<ide> }
<ide>
<del> onValueChange = value => {
<add> onValueChange = (value) => {
<ide> this.setState({selected: value});
<ide> RecordingModule.recordSelection(value);
<ide> };
<ide> }
<ide>
<ide> const PickerAndroidTestModule = {
<ide> PickerAndroidTestApp: PickerAndroidTestApp,
<del> selectItem: function(value) {
<add> selectItem: function (value) {
<ide> appInstance.setState({selected: value});
<ide> },
<del> setMode: function(mode) {
<add> setMode: function (mode) {
<ide> appInstance.setState({mode: mode});
<ide> },
<del> setPrimaryColor: function(color) {
<add> setPrimaryColor: function (color) {
<ide> appInstance.setState({style: {color}});
<ide> },
<ide> };
| 300
|
PHP
|
PHP
|
apply fixes from styleci
|
e04a7ffba8b80b934506783a7d0a161dd52eb2ef
|
<ide><path>src/Illuminate/Support/Str.php
<ide> protected static function charsArray()
<ide> '7' => ['⁷', '₇', '۷', '7'],
<ide> '8' => ['⁸', '₈', '۸', '8'],
<ide> '9' => ['⁹', '₉', '۹', '9'],
<del> 'a' => ['à', 'á', 'ả', 'ã', 'ạ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ', 'ặ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'ā', 'ą', 'å', 'α', 'ά', 'ἀ', 'ἁ', 'ἂ', 'ἃ', 'ἄ', 'ἅ', 'ἆ', 'ἇ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ὰ', 'ά', 'ᾰ', 'ᾱ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'а', 'أ', 'အ', 'ာ', 'ါ', 'ǻ', 'ǎ', 'ª', 'ა', 'अ', 'ا', 'a', 'ä','א'],
<del> 'b' => ['б', 'β', 'ب', 'ဗ', 'ბ', 'b','ב'],
<add> 'a' => ['à', 'á', 'ả', 'ã', 'ạ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ', 'ặ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'ā', 'ą', 'å', 'α', 'ά', 'ἀ', 'ἁ', 'ἂ', 'ἃ', 'ἄ', 'ἅ', 'ἆ', 'ἇ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ὰ', 'ά', 'ᾰ', 'ᾱ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'а', 'أ', 'အ', 'ာ', 'ါ', 'ǻ', 'ǎ', 'ª', 'ა', 'अ', 'ا', 'a', 'ä', 'א'],
<add> 'b' => ['б', 'β', 'ب', 'ဗ', 'ბ', 'b', 'ב'],
<ide> 'c' => ['ç', 'ć', 'č', 'ĉ', 'ċ', 'c'],
<ide> 'd' => ['ď', 'ð', 'đ', 'ƌ', 'ȡ', 'ɖ', 'ɗ', 'ᵭ', 'ᶁ', 'ᶑ', 'д', 'δ', 'د', 'ض', 'ဍ', 'ဒ', 'დ', 'd', 'ד'],
<ide> 'e' => ['é', 'è', 'ẻ', 'ẽ', 'ẹ', 'ê', 'ế', 'ề', 'ể', 'ễ', 'ệ', 'ë', 'ē', 'ę', 'ě', 'ĕ', 'ė', 'ε', 'έ', 'ἐ', 'ἑ', 'ἒ', 'ἓ', 'ἔ', 'ἕ', 'ὲ', 'έ', 'е', 'ё', 'э', 'є', 'ə', 'ဧ', 'ေ', 'ဲ', 'ე', 'ए', 'إ', 'ئ', 'e'],
<ide> 'f' => ['ф', 'φ', 'ف', 'ƒ', 'ფ', 'f', 'פ', 'ף'],
<del> 'g' => ['ĝ', 'ğ', 'ġ', 'ģ', 'г', 'ґ', 'γ', 'ဂ', 'გ', 'گ', 'g','ג'],
<add> 'g' => ['ĝ', 'ğ', 'ġ', 'ģ', 'г', 'ґ', 'γ', 'ဂ', 'გ', 'گ', 'g', 'ג'],
<ide> 'h' => ['ĥ', 'ħ', 'η', 'ή', 'ح', 'ه', 'ဟ', 'ှ', 'ჰ', 'h', 'ה'],
<del> 'i' => ['í', 'ì', 'ỉ', 'ĩ', 'ị', 'î', 'ï', 'ī', 'ĭ', 'į', 'ı', 'ι', 'ί', 'ϊ', 'ΐ', 'ἰ', 'ἱ', 'ἲ', 'ἳ', 'ἴ', 'ἵ', 'ἶ', 'ἷ', 'ὶ', 'ί', 'ῐ', 'ῑ', 'ῒ', 'ΐ', 'ῖ', 'ῗ', 'і', 'ї', 'и', 'ဣ', 'ိ', 'ီ', 'ည်', 'ǐ', 'ი', 'इ', 'ی', 'i','י'],
<add> 'i' => ['í', 'ì', 'ỉ', 'ĩ', 'ị', 'î', 'ï', 'ī', 'ĭ', 'į', 'ı', 'ι', 'ί', 'ϊ', 'ΐ', 'ἰ', 'ἱ', 'ἲ', 'ἳ', 'ἴ', 'ἵ', 'ἶ', 'ἷ', 'ὶ', 'ί', 'ῐ', 'ῑ', 'ῒ', 'ΐ', 'ῖ', 'ῗ', 'і', 'ї', 'и', 'ဣ', 'ိ', 'ီ', 'ည်', 'ǐ', 'ი', 'इ', 'ی', 'i', 'י'],
<ide> 'j' => ['ĵ', 'ј', 'Ј', 'ჯ', 'ج', 'j'],
<ide> 'k' => ['ķ', 'ĸ', 'к', 'κ', 'Ķ', 'ق', 'ك', 'က', 'კ', 'ქ', 'ک', 'k', 'ק'],
<ide> 'l' => ['ł', 'ľ', 'ĺ', 'ļ', 'ŀ', 'л', 'λ', 'ل', 'လ', 'ლ', 'l', 'ל'],
<del> 'm' => ['м', 'μ', 'م', 'မ', 'მ', 'm', 'מ' , 'ם'],
<add> 'm' => ['м', 'μ', 'م', 'မ', 'მ', 'm', 'מ', 'ם'],
<ide> 'n' => ['ñ', 'ń', 'ň', 'ņ', 'ʼn', 'ŋ', 'ν', 'н', 'ن', 'န', 'ნ', 'n', 'נ'],
<ide> 'o' => ['ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ', 'ộ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ', 'ø', 'ō', 'ő', 'ŏ', 'ο', 'ὀ', 'ὁ', 'ὂ', 'ὃ', 'ὄ', 'ὅ', 'ὸ', 'ό', 'о', 'و', 'ို', 'ǒ', 'ǿ', 'º', 'ო', 'ओ', 'o', 'ö'],
<ide> 'p' => ['п', 'π', 'ပ', 'პ', 'پ', 'p', 'פ', 'ף'],
<ide> protected static function languageSpecificCharsArray($language)
<ide> ['ae', 'oe', 'ue', 'AE', 'OE', 'UE'],
<ide> ],
<ide> 'he' => [
<del> ['א','ב','ג','ד','ה','ו'],
<del> ['ז','ח','ט','י','כ','ל'],
<del> ['מ','נ','ס','ע','פ','צ'],
<del> ['ק','ר','ש','ת','ן','ץ','ך','ם', 'ף'],
<add> ['א', 'ב', 'ג', 'ד', 'ה', 'ו'],
<add> ['ז', 'ח', 'ט', 'י', 'כ', 'ל'],
<add> ['מ', 'נ', 'ס', 'ע', 'פ', 'צ'],
<add> ['ק', 'ר', 'ש', 'ת', 'ן', 'ץ', 'ך', 'ם', 'ף'],
<ide> ],
<ide> 'ro' => [
<ide> ['ă', 'â', 'î', 'ș', 'ț', 'Ă', 'Â', 'Î', 'Ș', 'Ț'],
| 1
|
Javascript
|
Javascript
|
add draw range for instanced geometry
|
3bc8d4f997cb82076a4febf8ac83ebca390d3832
|
<ide><path>src/renderers/webgl/WebGLBufferRenderer.js
<ide> function WebGLBufferRenderer( gl, extensions, infoRender ) {
<ide>
<ide> }
<ide>
<del> function renderInstances( geometry ) {
<add> function renderInstances( geometry, start, count ) {
<ide>
<ide> var extension = extensions.get( 'ANGLE_instanced_arrays' );
<ide>
<ide> function WebGLBufferRenderer( gl, extensions, infoRender ) {
<ide>
<ide> var position = geometry.attributes.position;
<ide>
<del> var count = 0;
<del>
<ide> if ( position.isInterleavedBufferAttribute ) {
<ide>
<ide> count = position.data.count;
<ide> function WebGLBufferRenderer( gl, extensions, infoRender ) {
<ide>
<ide> } else {
<ide>
<del> count = position.count;
<del>
<del> extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
<add> extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
<ide>
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
remove foreach from test case
|
4f3fce4ad2252e9dfa00c7300eb73bb36965db5b
|
<ide><path>test/lang/ko.js
<ide> exports["lang:kr"] = {
<ide> }
<ide> test.done();
<ide> },
<del>
<add>
<ide> "parse meridiem" : function (test) {
<ide> var elements = [{
<ide> expression : "1981년 9월 8일 오후 2시 30분",
<ide> exports["lang:kr"] = {
<ide> outputFormat : "H",
<ide> expected : "16"
<ide> }];
<del>
<add>
<ide> test.expect(elements.length);
<del>
<del> elements.forEach(function (it) {
<del> var actual = moment(it.expression, it.inputFormat).format(it.outputFormat);
<del>
<add>
<add> var i, l, it, actual;
<add> for (i = 0, l = elements.length; i < l; ++i) {
<add> it = elements[i];
<add> actual = moment(it.expression, it.inputFormat).format(it.outputFormat);
<add>
<ide> test.equal(
<ide> actual,
<del> it.expected,
<add> it.expected,
<ide> "'" + it.outputFormat + "' of '" + it.expression + "' must be '" + it.expected + "' but was '" + actual + "'."
<ide> );
<del> });
<del>
<add> }
<add>
<ide> test.done();
<ide> },
<del>
<add>
<ide> "format" : function (test) {
<ide> test.expect(22);
<ide>
<ide> exports["lang:kr"] = {
<ide>
<ide> test.done();
<ide> },
<del>
<add>
<ide> "returns the name of the language" : function (test) {
<ide> if (typeof module !== 'undefined' && module.exports) {
<ide> test.equal(require('../../lang/ko'), 'ko', "module should export ko");
<ide> }
<del>
<add>
<ide> test.done();
<ide> }
<ide> };
| 1
|
Ruby
|
Ruby
|
use args.flatten! in query methods when applicable
|
755d1636107f814c6e0f76e7b3f327b9b4bdcc07
|
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def references(*args)
<ide> end
<ide>
<ide> def references!(*args)
<del> self.references_values = (references_values + args.flatten.map(&:to_s)).uniq
<add> args.flatten!
<add>
<add> self.references_values = (references_values + args.map!(&:to_s)).uniq
<ide> self
<ide> end
<ide>
<ide> def group(*args)
<ide> end
<ide>
<ide> def group!(*args)
<del> self.group_values += args.flatten
<add> args.flatten!
<add>
<add> self.group_values += args
<ide> self
<ide> end
<ide>
<ide> def order(*args)
<ide> end
<ide>
<ide> def order!(*args)
<del> args = args.flatten
<add> args.flatten!
<ide>
<ide> references = args.reject { |arg| Arel::Node === arg }
<del> .map { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }
<del> .compact
<add> references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact!
<ide> references!(references) if references.any?
<ide>
<ide> self.order_values += args
<ide> def reorder(*args)
<ide> end
<ide>
<ide> def reorder!(*args)
<add> args.flatten!
<add>
<ide> self.reordering_value = true
<del> self.order_values = args.flatten
<add> self.order_values = args
<ide> self
<ide> end
<ide>
<ide> def limit!(value)
<ide> #
<ide> # Should be used with order.
<ide> #
<del> # User.offset(10).order("name ASC")
<add> # User.offset(10).order("name ASC")
<ide> def offset(value)
<ide> spawn.offset!(value)
<ide> end
| 1
|
Javascript
|
Javascript
|
remove obsolete todo
|
eabed2f518804c6e6ae170beef37438743139b9d
|
<ide><path>lib/repl.js
<ide> function addStandardGlobals(completionGroups, filter) {
<ide> }
<ide>
<ide> function defineDefaultCommands(repl) {
<del> // TODO remove me after 0.3.x
<ide> repl.defineCommand('break', {
<ide> help: 'Sometimes you get stuck, this gets you out',
<ide> action: function() {
| 1
|
PHP
|
PHP
|
remove tests for methods that don't exist anymore
|
7b096f03d4bcb557b050f786b8c0af7658058f3b
|
<ide><path>tests/TestCase/Console/Command/Task/ModelTaskTest.php
<ide> public function testGetValidation() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<del>/**
<del> * test that individual field validation works, with interactive = false
<del> * tests the guessing features of validation
<del> *
<del> * @return void
<del> */
<del> public function testFieldValidationGuessing() {
<del> $this->markTestIncomplete('Not done here yet');
<del> $this->Task->interactive = false;
<del> $this->Task->initValidations();
<del>
<del> $result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
<del> $expected = array('notEmpty' => 'notEmpty');
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->Task->fieldValidation('text', array('type' => 'date', 'length' => 10, 'null' => false));
<del> $expected = array('date' => 'date');
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->Task->fieldValidation('text', array('type' => 'time', 'length' => 10, 'null' => false));
<del> $expected = array('time' => 'time');
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->Task->fieldValidation('email', array('type' => 'string', 'length' => 10, 'null' => false));
<del> $expected = array('email' => 'email');
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->Task->fieldValidation('test', array('type' => 'integer', 'length' => 10, 'null' => false));
<del> $expected = array('numeric' => 'numeric');
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->Task->fieldValidation('test', array('type' => 'boolean', 'length' => 10, 'null' => false));
<del> $expected = array('boolean' => 'boolean');
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<del>/**
<del> * test that interactive field validation works and returns multiple validators.
<del> *
<del> * @return void
<del> */
<del> public function testInteractiveFieldValidation() {
<del> $this->markTestIncomplete('Not done here yet');
<del> $this->Task->initValidations();
<del> $this->Task->interactive = true;
<del> $this->Task->expects($this->any())->method('in')
<del> ->will($this->onConsecutiveCalls('24', 'y', '18', 'n'));
<del>
<del> $result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
<del> $expected = array('notEmpty' => 'notEmpty', 'maxLength' => 'maxLength');
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<del>/**
<del> * test that a bogus response doesn't cause errors to bubble up.
<del> *
<del> * @return void
<del> */
<del> public function testInteractiveFieldValidationWithBogusResponse() {
<del> $this->markTestIncomplete('Not done here yet');
<del> $this->_useMockedOut();
<del> $this->Task->initValidations();
<del> $this->Task->interactive = true;
<del>
<del> $this->Task->expects($this->any())->method('in')
<del> ->will($this->onConsecutiveCalls('999999', '24', 'n'));
<del>
<del> $this->Task->expects($this->at(10))->method('out')
<del> ->with($this->stringContains('make a valid'));
<del>
<del> $result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
<del> $expected = array('notEmpty' => 'notEmpty');
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<del>/**
<del> * test that a regular expression can be used for validation.
<del> *
<del> * @return void
<del> */
<del> public function testInteractiveFieldValidationWithRegexp() {
<del> $this->markTestIncomplete('Not done here yet');
<del> $this->Task->initValidations();
<del> $this->Task->interactive = true;
<del> $this->Task->expects($this->any())->method('in')
<del> ->will($this->onConsecutiveCalls('/^[a-z]{0,9}$/', 'n'));
<del>
<del> $result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
<del> $expected = array('a_z_0_9' => '/^[a-z]{0,9}$/');
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<del>/**
<del> * Test that skipping fields during rule choice works when doing interactive field validation.
<del> *
<del> * @return void
<del> */
<del> public function testSkippingChoiceInteractiveFieldValidation() {
<del> $this->markTestIncomplete('Not done here yet');
<del> $this->Task->initValidations();
<del> $this->Task->interactive = true;
<del> $this->Task->expects($this->any())->method('in')
<del> ->will($this->onConsecutiveCalls('24', 'y', 's'));
<del>
<del> $result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
<del> $expected = array('notEmpty' => 'notEmpty', '_skipFields' => true);
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<del>/**
<del> * Test that skipping fields after rule choice works when doing interactive field validation.
<del> *
<del> * @return void
<del> */
<del> public function testSkippingAnotherInteractiveFieldValidation() {
<del> $this->markTestIncomplete('Not done here yet');
<del> $this->Task->initValidations();
<del> $this->Task->interactive = true;
<del> $this->Task->expects($this->any())->method('in')
<del> ->will($this->onConsecutiveCalls('24', 's'));
<del>
<del> $result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
<del> $expected = array('notEmpty' => 'notEmpty', '_skipFields' => true);
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<del>/**
<del> * Test the validation generation routine with skipping the rest of the fields
<del> * when doing interactive field validation.
<del> *
<del> * @return void
<del> */
<del> public function testInteractiveDoValidationWithSkipping() {
<del> $this->markTestIncomplete('Not done here yet');
<del> $this->Task->expects($this->any())
<del> ->method('in')
<del> ->will($this->onConsecutiveCalls('35', '24', 'n', '11', 's'));
<del> $this->Task->interactive = true;
<del> $Model = $this->getMock('Model');
<del> $Model->primaryKey = 'id';
<del> $Model->expects($this->any())
<del> ->method('schema')
<del> ->will($this->returnValue(array(
<del> 'id' => array(
<del> 'type' => 'integer',
<del> 'length' => 11,
<del> 'null' => false,
<del> 'key' => 'primary',
<del> ),
<del> 'name' => array(
<del> 'type' => 'string',
<del> 'length' => 20,
<del> 'null' => false,
<del> ),
<del> 'email' => array(
<del> 'type' => 'string',
<del> 'length' => 255,
<del> 'null' => false,
<del> ),
<del> 'some_date' => array(
<del> 'type' => 'date',
<del> 'length' => '',
<del> 'null' => false,
<del> ),
<del> 'some_time' => array(
<del> 'type' => 'time',
<del> 'length' => '',
<del> 'null' => false,
<del> ),
<del> 'created' => array(
<del> 'type' => 'datetime',
<del> 'length' => '',
<del> 'null' => false,
<del> )
<del> )
<del> ));
<del>
<del> $result = $this->Task->doValidation($Model);
<del> $expected = array(
<del> 'name' => array(
<del> 'notEmpty' => 'notEmpty'
<del> ),
<del> 'email' => array(
<del> 'email' => 'email',
<del> ),
<del> );
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<del>/**
<del> * test the validation Generation routine
<del> *
<del> * @return void
<del> */
<del> public function testNonInteractiveDoValidation() {
<del> $this->markTestIncomplete('Not done here yet');
<del> $Model = $this->getMock('Model');
<del> $Model->primaryKey = 'id';
<del> $Model->expects($this->any())
<del> ->method('schema')
<del> ->will($this->returnValue(array(
<del> 'id' => array(
<del> 'type' => 'integer',
<del> 'length' => 11,
<del> 'null' => false,
<del> 'key' => 'primary',
<del> ),
<del> 'name' => array(
<del> 'type' => 'string',
<del> 'length' => 20,
<del> 'null' => false,
<del> ),
<del> 'email' => array(
<del> 'type' => 'string',
<del> 'length' => 255,
<del> 'null' => false,
<del> ),
<del> 'some_date' => array(
<del> 'type' => 'date',
<del> 'length' => '',
<del> 'null' => false,
<del> ),
<del> 'some_time' => array(
<del> 'type' => 'time',
<del> 'length' => '',
<del> 'null' => false,
<del> ),
<del> 'created' => array(
<del> 'type' => 'datetime',
<del> 'length' => '',
<del> 'null' => false,
<del> )
<del> )
<del> ));
<del> $this->Task->interactive = false;
<del>
<del> $result = $this->Task->doValidation($Model);
<del> $expected = array(
<del> 'name' => array(
<del> 'notEmpty' => 'notEmpty'
<del> ),
<del> 'email' => array(
<del> 'email' => 'email',
<del> ),
<del> 'some_date' => array(
<del> 'date' => 'date'
<del> ),
<del> 'some_time' => array(
<del> 'time' => 'time'
<del> ),
<del> );
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<del>/**
<del> * test non interactive doAssociations
<del> *
<del> * @return void
<del> */
<del> public function testDoAssociationsNonInteractive() {
<del> $this->markTestIncomplete('Not done here yet');
<del> $this->Task->connection = 'test';
<del> $this->Task->interactive = false;
<del> $model = new Model(array('ds' => 'test', 'name' => 'BakeArticle'));
<del> $result = $this->Task->doAssociations($model);
<del> $expected = array(
<del> 'belongsTo' => array(
<del> array(
<del> 'alias' => 'BakeUser',
<del> 'className' => 'BakeUser',
<del> 'foreignKey' => 'bake_user_id',
<del> ),
<del> ),
<del> 'hasMany' => array(
<del> array(
<del> 'alias' => 'BakeComment',
<del> 'className' => 'BakeComment',
<del> 'foreignKey' => 'bake_article_id',
<del> ),
<del> ),
<del> 'hasAndBelongsToMany' => array(
<del> array(
<del> 'alias' => 'BakeTag',
<del> 'className' => 'BakeTag',
<del> 'foreignKey' => 'bake_article_id',
<del> 'joinTable' => 'bake_articles_bake_tags',
<del> 'associationForeignKey' => 'bake_tag_id',
<del> ),
<del> ),
<del> );
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<ide> /**
<ide> * test non interactive doActsAs
<ide> *
| 1
|
Ruby
|
Ruby
|
implement `requirements` in terms of routes
|
c3284e2a36e92af1a2ad3bdbc1c74523811f3ad2
|
<ide><path>actionpack/test/dispatch/mapper_test.rb
<ide> def conditions
<ide> end
<ide>
<ide> def requirements
<del> @my_routes.map { |x| x[2] }
<add> routes.map(&:path).map(&:requirements)
<ide> end
<ide>
<ide> def asts
| 1
|
PHP
|
PHP
|
add test cases for mcrypt/openssl
|
3578d92ee74aaf897dc7c4a55a47de62b7efc326
|
<ide><path>src/Utility/Crypto/Mcrypt.php
<ide> public static function decrypt($cipher, $key) {
<ide> $cipher = substr($cipher, $ivSize);
<ide> $plain = mcrypt_decrypt($algorithm, $key, $cipher, $mode, $iv);
<ide>
<del> // Remove PKCS#7 padding
<add> // Remove PKCS#7 padding or Null bytes
<add> // Newer values will be PKCS#7 padded, while old
<add> // mcrypt values will be null byte padded.
<ide> $padChar = substr($plain, -1);
<add> if ($padChar === "\0") {
<add> return trim($plain, "\0");
<add> }
<ide> $padLen = ord($padChar);
<ide> return substr($plain, 0, -$padLen);
<ide> }
<ide><path>tests/TestCase/Utility/Crypto/McryptTest.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 0.10.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Test\TestCase\Utility\Crypto;
<add>
<add>use Cake\TestSuite\TestCase;
<add>use Cake\Utility\Crypto\Mcrypt;
<add>
<add>/**
<add> * Mcrypt engine tests.
<add> */
<add>class McryptTest extends TestCase {
<add>
<add>/**
<add> * Setup function.
<add> *
<add> * @return void
<add> */
<add> public function setUp() {
<add> parent::setUp();
<add> $this->skipIf(!function_exists('mcrypt_encrypt'), 'No mcrypt skipping tests');
<add> $this->crypt = new Mcrypt();
<add> }
<add>
<add>/**
<add> * testRijndael method
<add> *
<add> * @return void
<add> */
<add> public function testRijndael() {
<add> $txt = 'The quick brown fox jumped over the lazy dog.';
<add> $key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi';
<add>
<add> $result = $this->crypt->rijndael($txt, $key, 'encrypt');
<add> $this->assertEquals($txt, $this->crypt->rijndael($result, $key, 'decrypt'));
<add>
<add> $result = $this->crypt->rijndael($key, $txt, 'encrypt');
<add> $this->assertEquals($key, $this->crypt->rijndael($result, $txt, 'decrypt'));
<add>
<add> $result = $this->crypt->rijndael('', $key, 'encrypt');
<add> $this->assertEquals('', $this->crypt->rijndael($result, $key, 'decrypt'));
<add>
<add> $key = 'this is my key of over 32 chars, yes it is';
<add> $result = $this->crypt->rijndael($txt, $key, 'encrypt');
<add> $this->assertEquals($txt, $this->crypt->rijndael($result, $key, 'decrypt'));
<add> }
<add>
<add>/**
<add> * Test encrypt/decrypt.
<add> *
<add> * @return void
<add> */
<add> public function testEncryptDecrypt() {
<add> $txt = 'The quick brown fox';
<add> $key = 'This key is enough bytes';
<add> $result = $this->crypt->encrypt($txt, $key);
<add> $this->assertNotEquals($txt, $result, 'Should be encrypted.');
<add> $this->assertNotEquals($result, $this->crypt->encrypt($txt, $key), 'Each result is unique.');
<add> $this->assertEquals($txt, $this->crypt->decrypt($result, $key));
<add> }
<add>
<add>/**
<add> * Test that changing the key causes decryption to fail.
<add> *
<add> * @return void
<add> */
<add> public function testDecryptKeyFailure() {
<add> $txt = 'The quick brown fox';
<add> $key = 'This key is enough bytes';
<add> $result = $this->crypt->encrypt($txt, $key);
<add>
<add> $key = 'Not the same key.';
<add> $this->assertFalse($this->crypt->decrypt($txt, $key), 'Modified key will fail.');
<add> }
<add>
<add>/**
<add> * Test that decrypt fails when there is an hmac error.
<add> *
<add> * @return void
<add> */
<add> public function testDecryptHmacFailure() {
<add> $txt = 'The quick brown fox';
<add> $key = 'This key is long enough';
<add> $salt = 'this is a delicious salt!';
<add> $result = $this->crypt->encrypt($txt, $key, $salt);
<add>
<add> // Change one of the bytes in the hmac.
<add> $result[10] = 'x';
<add> $this->assertFalse($this->crypt->decrypt($result, $key, $salt), 'Modified hmac causes failure.');
<add> }
<add>
<add>/**
<add> * Ensure that data encrypted with 2.x encrypt() function can be decrypted with mcrypt engine.
<add> *
<add> * The $cipher variable is base64 encoded data from 2.x encrypt()
<add> *
<add> * @return
<add> */
<add> public function testDecryptOldData() {
<add> $key = 'My password is nice and long really it is';
<add> $cipher = 'ZmFkMjdmY2U2NjgzOTkwMGZmMWJiMzY0ZDA5ZDUwZmNjYTdjNWVkZThkMzhmNzdiY' .
<add> 'Tg3ZDFjMzNjNmViMDljMnk9k0LmYpwSZH5eq7GmDozMwHxzh37YaXFQ2TK5gXb5OfTKXv83K+NjAS9lIo/Zvw==';
<add> $salt = '';
<add>
<add> $result = $this->crypt->encrypt($txt, $key, $salt);
<add> $this->assertEquals('This is a secret message', $result);
<add> }
<add>
<add>}
<ide><path>tests/TestCase/Utility/Crypto/OpenSslTest.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 0.10.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Test\TestCase\Utility\Crypto;
<add>
<add>use Cake\TestSuite\TestCase;
<add>use Cake\Utility\Crypto\OpenSsl;
<add>
<add>/**
<add> * Openssl engine tests.
<add> */
<add>class OpenSslTest extends TestCase {
<add>
<add>/**
<add> * Setup function.
<add> *
<add> * @return void
<add> */
<add> public function setUp() {
<add> parent::setUp();
<add> $this->skipIf(!function_exists('openssl_encrypt'), 'No openssl skipping tests');
<add> $this->crypt = new OpenSsl();
<add> }
<add>
<add>/**
<add> * testRijndael method
<add> *
<add> * @expectedException \LogicException
<add> * @return void
<add> */
<add> public function testRijndael() {
<add> $txt = 'The quick brown fox jumped over the lazy dog.';
<add> $key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi';
<add>
<add> $this->crypt->rijndael($txt, $key, 'encrypt');
<add> }
<add>
<add>/**
<add> * Test encrypt/decrypt.
<add> *
<add> * @return void
<add> */
<add> public function testEncryptDecrypt() {
<add> $txt = 'The quick brown fox';
<add> $key = 'This key is enough bytes';
<add> $result = $this->crypt->encrypt($txt, $key);
<add> $this->assertNotEquals($txt, $result, 'Should be encrypted.');
<add> $this->assertNotEquals($result, $this->crypt->encrypt($txt, $key), 'Each result is unique.');
<add> $this->assertEquals($txt, $this->crypt->decrypt($result, $key));
<add> }
<add>
<add>/**
<add> * Test that changing the key causes decryption to fail.
<add> *
<add> * @return void
<add> */
<add> public function testDecryptKeyFailure() {
<add> $txt = 'The quick brown fox';
<add> $key = 'This key is enough bytes';
<add> $result = $this->crypt->encrypt($txt, $key);
<add>
<add> $key = 'Not the same key.';
<add> $this->assertFalse($this->crypt->decrypt($txt, $key), 'Modified key will fail.');
<add> }
<add>
<add>/**
<add> * Test that decrypt fails when there is an hmac error.
<add> *
<add> * @return void
<add> */
<add> public function testDecryptHmacFailure() {
<add> $txt = 'The quick brown fox';
<add> $key = 'This key is long enough';
<add> $salt = 'this is a delicious salt!';
<add> $result = $this->crypt->encrypt($txt, $key, $salt);
<add>
<add> // Change one of the bytes in the hmac.
<add> $result[10] = 'x';
<add> $this->assertFalse($this->crypt->decrypt($result, $key, $salt), 'Modified hmac causes failure.');
<add> }
<add>
<add>}
| 3
|
Javascript
|
Javascript
|
use strict equalities in test/driver.js
|
e525902241fbbe1f436235b3973943adcb65eeba
|
<ide><path>test/driver.js
<ide> window.load = function load() {
<ide> var r = new XMLHttpRequest();
<ide> r.open('GET', manifestFile, false);
<ide> r.onreadystatechange = function loadOnreadystatechange(e) {
<del> if (r.readyState == 4) {
<add> if (r.readyState === 4) {
<ide> log('done\n');
<ide> manifest = JSON.parse(r.responseText);
<ide> currentTaskIdx = 0;
<ide> function nextTask() {
<ide> }
<ide>
<ide> function continueNextTask() {
<del> if (currentTaskIdx == manifest.length) {
<add> if (currentTaskIdx === manifest.length) {
<ide> done();
<ide> return;
<ide> }
<ide> function nextPage(task, loadError) {
<ide> var initPromise = new Promise(function (resolve) {
<ide> resolveInitPromise = resolve;
<ide> });
<del> if (task.type == 'text') {
<add> if (task.type === 'text') {
<ide> // using dummy canvas for pdf context drawing operations
<ide> if (!dummyCanvas) {
<ide> dummyCanvas = document.createElement('canvas');
<ide> function sendQuitRequest(cb) {
<ide> var r = new XMLHttpRequest();
<ide> r.open('POST', '/tellMeToQuit?path=' + escape(appPath), false);
<ide> r.onreadystatechange = function sendQuitRequestOnreadystatechange(e) {
<del> if (r.readyState == 4) {
<add> if (r.readyState === 4) {
<ide> if (cb) {
<ide> cb();
<ide> }
<ide> function send(url, message, callback) {
<ide> r.open('POST', url, true);
<ide> r.setRequestHeader('Content-Type', 'application/json');
<ide> r.onreadystatechange = function sendTaskResultOnreadystatechange(e) {
<del> if (r.readyState == 4) {
<add> if (r.readyState === 4) {
<ide> inFlightRequests--;
<ide> // Retry until successful
<ide> if (r.status !== 200) {
| 1
|
Python
|
Python
|
fix sql_to_gcs hook gzip of schema_file
|
76962867b5877cf5ffd1b6004453f783c0732ab1
|
<ide><path>airflow/providers/google/cloud/operators/sql_to_gcs.py
<ide> def _upload_to_gcs(self, files_to_upload):
<ide> hook.upload(self.bucket, tmp_file.get('file_name'),
<ide> tmp_file.get('file_handle').name,
<ide> mime_type=tmp_file.get('file_mime_type'),
<del> gzip=self.gzip if tmp_file.get('file_name') == self.schema_filename else False)
<add> gzip=self.gzip if tmp_file.get('file_name') != self.schema_filename else False)
| 1
|
Javascript
|
Javascript
|
improve code coverage in webcrypto api
|
30d7f05fef08a15f33fa77849966b604a4019e54
|
<ide><path>test/parallel/test-webcrypto-sign-verify-hmac.js
<ide> async function testSign({ hash,
<ide> assert(await subtle.verify({ name, hash }, key, sig, plaintext));
<ide> }
<ide>
<add> await assert.rejects(
<add> subtle.generateKey({ name }, false, []), {
<add> name: 'TypeError',
<add> code: 'ERR_MISSING_OPTION',
<add> message: 'algorithm.hash is required'
<add> });
<add>
<ide> // Test failure when no sign usage
<ide> await assert.rejects(
<ide> subtle.sign({ name, hash }, noSignKey, plaintext), {
| 1
|
Ruby
|
Ruby
|
add failing tests, according to #480
|
b6a2113b8d8301bc1b3cc8b9a1db2e270a24f7b3
|
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_create_from_association_should_respect_default_scope
<ide> assert_equal 'exotic', bulb.name
<ide> end
<ide>
<add> def test_create_from_association_with_nil_values_should_work
<add> car = Car.create(:name => 'honda')
<add>
<add> bulb = car.bulbs.new(nil)
<add> assert_equal 'defaulty', bulb.name
<add>
<add> bulb = car.bulbs.build(nil)
<add> assert_equal 'defaulty', bulb.name
<add>
<add> bulb = car.bulbs.create(nil)
<add> assert_equal 'defaulty', bulb.name
<add> end
<add>
<add>
<ide> # When creating objects on the association, we must not do it within a scope (even though it
<ide> # would be convenient), because this would cause that scope to be applied to any callbacks etc.
<ide> def test_build_and_create_should_not_happen_within_scope
| 1
|
Javascript
|
Javascript
|
remove deregisternotifier feature for $watch
|
0554c1aae49a81691154a77e70b602b0f24dca81
|
<ide><path>src/ng/interpolate.js
<ide> function $InterpolateProvider() {
<ide> exp: text, //just for compatibility with regular watchers created via $watch
<ide> separators: separators,
<ide> expressions: expressions,
<del> $$watchDelegate: function (scope, listener, objectEquality, deregisterNotifier) {
<add> $$watchDelegate: function (scope, listener, objectEquality) {
<ide> var lastValue;
<ide> return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
<ide> var currValue = compute(values);
<ide> if (isFunction(listener)) {
<ide> listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
<ide> }
<ide> lastValue = currValue;
<del> }, objectEquality, deregisterNotifier);
<add> }, objectEquality);
<ide> }
<ide> });
<ide> }
<ide><path>src/ng/parse.js
<ide> function $ParseProvider() {
<ide> }
<ide> };
<ide>
<del> function oneTimeWatch(scope, listener, objectEquality, deregisterNotifier, parsedExpression) {
<add> function oneTimeWatch(scope, listener, objectEquality, parsedExpression) {
<ide> var unwatch, lastValue;
<ide> return unwatch = scope.$watch(function oneTimeWatch(scope) {
<ide> return parsedExpression(scope);
<ide> function $ParseProvider() {
<ide> }
<ide> });
<ide> }
<del> }, objectEquality, deregisterNotifier);
<add> }, objectEquality);
<ide> }
<ide>
<del> function oneTimeLiteralWatch(scope, listener, objectEquality, deregisterNotifier, parsedExpression) {
<add> function oneTimeLiteralWatch(scope, listener, objectEquality, parsedExpression) {
<ide> var unwatch;
<ide> return unwatch = scope.$watch(function oneTimeWatch(scope) {
<ide> return parsedExpression(scope);
<ide> function $ParseProvider() {
<ide> }
<ide> }
<ide>
<del> function constantWatch(scope, listener, objectEquality, deregisterNotifier, parsedExpression) {
<add> function constantWatch(scope, listener, objectEquality, parsedExpression) {
<ide> var unwatch;
<ide> return unwatch = scope.$watch(function constantWatch(scope) {
<ide> return parsedExpression(scope);
<ide> function $ParseProvider() {
<ide> listener.apply(this, arguments);
<ide> }
<ide> unwatch();
<del> }, objectEquality, deregisterNotifier);
<add> }, objectEquality);
<ide> }
<ide>
<ide> function addInterceptor(parsedExpression, interceptorFn) {
<ide><path>src/ng/rootScope.js
<ide> function $RootScopeProvider(){
<ide> * - `scope` refers to the current scope
<ide> * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
<ide> * comparing for reference equality.
<del> * @param {function()=} deregisterNotifier Function to call when the deregistration function
<del> * get called.
<ide> * @returns {function()} Returns a deregistration function for this listener.
<ide> */
<del> $watch: function(watchExp, listener, objectEquality, deregisterNotifier) {
<add> $watch: function(watchExp, listener, objectEquality) {
<ide> var get = compileToFn(watchExp, 'watch');
<ide>
<ide> if (get.$$watchDelegate) {
<del> return get.$$watchDelegate(this, listener, objectEquality, deregisterNotifier, get);
<add> return get.$$watchDelegate(this, listener, objectEquality, get);
<ide> }
<ide> var scope = this,
<ide> array = scope.$$watchers,
<ide> function $RootScopeProvider(){
<ide> return function deregisterWatch() {
<ide> arrayRemove(array, watcher);
<ide> lastDirtyWatch = null;
<del> if (isFunction(deregisterNotifier)) {
<del> deregisterNotifier();
<del> }
<ide> };
<ide> },
<ide>
<ide><path>test/ng/rootScopeSpec.js
<ide> describe('Scope', function() {
<ide> expect(log).toEqual(['watch1', 'watchAction1', 'watch2', 'watchAction2', 'watch3', 'watchAction3',
<ide> 'watch2', 'watch3']);
<ide> }));
<del>
<del> describe('deregisterNotifier', function () {
<del> it('should call the deregisterNotifier when the watch is deregistered', inject(
<del> function($rootScope) {
<del> var notifier = jasmine.createSpy('deregisterNotifier');
<del> var listenerRemove = $rootScope.$watch('noop', noop, false, notifier);
<del>
<del> expect(notifier).not.toHaveBeenCalled();
<del>
<del> listenerRemove();
<del> expect(notifier).toHaveBeenCalledOnce();
<del> }));
<del>
<del>
<del> it('should call the deregisterNotifier when a one-time expression is stable', inject(
<del> function($rootScope) {
<del> var notifier = jasmine.createSpy('deregisterNotifier');
<del> $rootScope.$watch('::foo', noop, false, notifier);
<del>
<del> expect(notifier).not.toHaveBeenCalledOnce();
<del> $rootScope.$digest();
<del> expect(notifier).not.toHaveBeenCalledOnce();
<del>
<del> $rootScope.foo = 'foo';
<del> $rootScope.$digest();
<del> expect(notifier).toHaveBeenCalledOnce();
<del> }));
<del> });
<ide> });
<ide>
<ide>
| 4
|
Python
|
Python
|
remove leading zeros for python3 compatibility
|
9e43e56b260fa54a2c467d1bd8e17be3a9a987ab
|
<ide><path>tests/models.py
<ide> class DagRunTest(unittest.TestCase):
<ide> def test_id_for_date(self):
<ide> run_id = models.DagRun.id_for_date(
<del> datetime.datetime(2015, 01, 02, 03, 04, 05, 06, None))
<add> datetime.datetime(2015, 1, 2, 3, 4, 5, 6, None))
<ide> assert run_id == 'scheduled__2015-01-02T03:04:05', (
<ide> 'Generated run_id did not match expectations: {0}'.format(run_id))
<ide>
| 1
|
Ruby
|
Ruby
|
show full name when a installing a tap dependency
|
e8727a4eeea08b21b10e561685c898100e3697b6
|
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def install_dependency(dep, inherited_options)
<ide> fi.ignore_deps = true
<ide> fi.only_deps = false
<ide> fi.show_header = false
<del> oh1 "Installing #{f} dependency: #{Tty.green}#{df}#{Tty.reset}"
<add> oh1 "Installing #{f} dependency: #{Tty.green}#{dep.name}#{Tty.reset}"
<ide> outdated_keg.unlink if outdated_keg
<ide> fi.install
<ide> fi.caveats
| 1
|
Javascript
|
Javascript
|
fix wrong order of base, head arguments
|
903384ab0ccd57efd56225dbc82ba6ad56021380
|
<ide><path>dangerfile.js
<ide> function getBundleSizes(pathToSizesDir) {
<ide> async function printResultsForChannel(baseResults, headResults) {
<ide> // Take the JSON of the build response and
<ide> // make an array comparing the results for printing
<del> const results = generateResultsArray(baseResults, headResults);
<add> const results = generateResultsArray(headResults, baseResults);
<ide>
<ide> const packagesToShow = results
<ide> .filter(
| 1
|
Text
|
Text
|
add docs for vectors.most_similar [ci skip]
|
ce1d441de557d9ec282c7b0ab9b42718751fab9b
|
<ide><path>website/docs/api/vectors.md
<ide> vectors, they will be counted individually.
<ide> | ----------- | ---- | ------------------------------------ |
<ide> | **RETURNS** | int | The number of all keys in the table. |
<ide>
<add>## Vectors.most_similar {#most_similar tag="method"}
<add>
<add>For each of the given vectors, find the `n` most similar entries to it, by
<add>cosine. Queries are by vector. Results are returned as a
<add>`(keys, best_rows, scores)` tuple. If `queries` is large, the calculations are
<add>performed in chunks, to avoid consuming too much memory. You can set the
<add>`batch_size` to control the size/space trade-off during the calculations.
<add>
<add>> #### Example
<add>>
<add>> ```python
<add>> queries = numpy.asarray([numpy.random.uniform(-1, 1, (300,))])
<add>> most_similar = nlp.vectors.most_similar(queries, n=10)
<add>> ```
<add>
<add>| Name | Type | Description |
<add>| ------------ | --------- | ------------------------------------------------------------------ |
<add>| `queries` | `ndarray` | An array with one or more vectors. |
<add>| `batch_size` | int | The batch size to use. Default to `1024`. |
<add>| `n` | int | The number of entries to return for each query. Defaults to `1`. |
<add>| `sort` | bool | Whether to sort the entries returned by score. Defaults to `True`. |
<add>| **RETURNS** | tuple | The most similar entries as a `(keys, best_rows, scores)` tuple. |
<add>
<ide> ## Vectors.from_glove {#from_glove tag="method"}
<ide>
<ide> Load [GloVe](https://nlp.stanford.edu/projects/glove/) vectors from a directory.
| 1
|
Javascript
|
Javascript
|
use error codes in debugger repl
|
fa009e1428f3f59cfed9cf96c59291594b6ac089
|
<ide><path>lib/internal/inspector/inspect_repl.js
<ide> // TODO(trott): enable ESLint
<del>/* eslint-disable getter-return, no-restricted-syntax */
<add>/* eslint-disable getter-return */
<ide>
<ide> 'use strict';
<ide>
<ide> const {
<ide> ArrayPrototypeSome,
<ide> ArrayPrototypeSplice,
<ide> Date,
<del> Error,
<ide> FunctionPrototypeCall,
<ide> JSONStringify,
<ide> MathMax,
<ide> const {
<ide> StringPrototypeStartsWith,
<ide> StringPrototypeToUpperCase,
<ide> StringPrototypeTrim,
<del> TypeError,
<ide> } = primordials;
<ide>
<add>const { ERR_DEBUGGER_ERROR } = require('internal/errors').codes;
<add>
<add>const { validateString } = require('internal/validators');
<add>
<ide> const FS = require('fs');
<ide> const Path = require('path');
<ide> const Repl = require('repl');
<ide> function extractErrorMessage(stack) {
<ide>
<ide> function convertResultToError(result) {
<ide> const { className, description } = result;
<del> const err = new Error(extractErrorMessage(description));
<add> const err = new ERR_DEBUGGER_ERROR(extractErrorMessage(description));
<ide> err.stack = description;
<ide> ObjectDefineProperty(err, 'name', { value: className });
<ide> return err;
<ide> function createRepl(inspector) {
<ide>
<ide> function getCurrentLocation() {
<ide> if (!selectedFrame) {
<del> throw new Error('Requires execution to be paused');
<add> throw new ERR_DEBUGGER_ERROR('Requires execution to be paused');
<ide> }
<ide> return selectedFrame.location;
<ide> }
<ide> function createRepl(inspector) {
<ide> // Repl asked for scope variables
<ide> if (code === '.scope') {
<ide> if (!selectedFrame) {
<del> throw new Error('Requires execution to be paused');
<add> throw new ERR_DEBUGGER_ERROR('Requires execution to be paused');
<ide> }
<ide> const scopes = await selectedFrame.loadScopes();
<ide> return ArrayPrototypeMap(scopes, (scope) => scope.completionGroup);
<ide> function createRepl(inspector) {
<ide> registerBreakpoint);
<ide> }
<ide>
<del> if (typeof script !== 'string') {
<del> throw new TypeError(`setBreakpoint() expects a string, got ${script}`);
<del> }
<add> validateString(script, 'script');
<ide>
<ide> // setBreakpoint('fn()'): Break when a function is called
<ide> if (StringPrototypeEndsWith(script, '()')) {
| 1
|
Text
|
Text
|
add bodastage and bts-ce to current user list
|
044b2c70fb6c112f11cacc4511955828c4a217f2
|
<ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [BlueApron](https://www.blueapron.com) [[@jasonjho](https://github.com/jasonjho) & [@matthewdavidhauser](https://github.com/matthewdavidhauser)]
<ide> 1. [Bluecore](https://www.bluecore.com) [[@JLDLaughlin](https://github.com/JLDLaughlin)]
<ide> 1. [Blue Yonder](http://www.blue-yonder.com) [[@blue-yonder](https://github.com/blue-yonder)]
<add>1. [Boda Telecom Suite - CE](https://github.com/bodastage/bts-ce) [[@erssebaggala](https://github.com/erssebaggala), [@bodastage](https://github.com/bodastage)]
<add>1. [Bodastage Solutions](http://bodastage.com) [[@erssebaggala](https://github.com/erssebaggala), [@bodastage](https://github.com/bodastage)]
<ide> 1. [California Data Collaborative](https://github.com/California-Data-Collaborative) powered by [ARGO Labs](http://www.argolabs.org)
<ide> 1. [Carbonite](https://www.carbonite.com) [[@ajbosco](https://github.com/ajbosco)]
<ide> 1. [Celect](http://www.celect.com) [[@superdosh](https://github.com/superdosh) & [@chadcelect](https://github.com/chadcelect)]
| 1
|
Go
|
Go
|
add lock in libcontainerd client addprocess
|
278273bc1699873304240a6eca342b54051e2f23
|
<ide><path>libcontainerd/client_linux.go
<ide> func (clnt *client) AddProcess(ctx context.Context, containerID, processFriendly
<ide> clnt.unlock(containerID)
<ide>
<ide> if err := clnt.backend.AttachStreams(processFriendlyName, *iopipe); err != nil {
<add> clnt.lock(containerID)
<ide> return err
<ide> }
<ide> clnt.lock(containerID)
<ide><path>libcontainerd/types_linux.go
<ide> type Process struct {
<ide> Capabilities []string `json:"capabilities,omitempty"`
<ide> // Rlimits specifies rlimit options to apply to the process.
<ide> Rlimits []specs.Rlimit `json:"rlimits,omitempty"`
<del> // ApparmorProfile specified the apparmor profile for the container.
<add> // ApparmorProfile specifies the apparmor profile for the container.
<ide> ApparmorProfile *string `json:"apparmorProfile,omitempty"`
<del> // SelinuxProcessLabel specifies the selinux context that the container process is run as.
<add> // SelinuxLabel specifies the selinux context that the container process is run as.
<ide> SelinuxLabel *string `json:"selinuxLabel,omitempty"`
<ide> }
<ide>
| 2
|
PHP
|
PHP
|
capitalize d in uuid
|
d828133f576bca9001645681edea2e20ab955728
|
<ide><path>src/Routing/Router.php
<ide> class Router {
<ide> const ID = '[0-9]+';
<ide>
<ide> /**
<del> * Regular expression for UUIds
<add> * Regular expression for UUIDs
<ide> *
<ide> * @var string
<ide> */
| 1
|
Javascript
|
Javascript
|
use fixture files
|
61040db1f6d0591e4da35d160d885a0b418c4ead
|
<ide><path>node-tests/blueprints/initializer-test-test.js
<ide> const modifyPackages = blueprintHelpers.modifyPackages;
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<ide>
<add>const fixture = require('../helpers/fixture');
<add>
<ide> describe('Blueprint: initializer-test', function() {
<ide> setupTestHooks(this);
<ide>
<ide> describe('Blueprint: initializer-test', function() {
<ide> it('initializer-test foo', function() {
<ide> return emberGenerateDestroy(['initializer-test', 'foo'], _file => {
<ide> expect(_file('tests/unit/initializers/foo-test.js'))
<del> .to.contain("import { initialize } from 'my-app/initializers/foo';")
<del> .to.contain("module('Unit | Initializer | foo'")
<del> .to.contain("application = Application.create();")
<del> .to.contain("initialize(this.application);");
<add> .to.equal(fixture('initializer-test/default.js'));
<ide> });
<ide> });
<ide>
<ide> describe('Blueprint: initializer-test', function() {
<ide> it('initializer-test foo', function() {
<ide> return emberGenerateDestroy(['initializer-test', 'foo'], _file => {
<ide> expect(_file('tests/unit/initializers/foo-test.js'))
<del> .to.contain("import { initialize } from 'my-app/initializers/foo';")
<del> .to.contain("describe('Unit | Initializer | foo', function() {")
<del> .to.contain("application = Application.create();")
<del> .to.contain("initialize(application);");
<add> .to.equal(fixture('initializer-test/mocha.js'));
<ide> });
<ide> });
<ide> });
<ide> describe('Blueprint: initializer-test', function() {
<ide> it('initializer-test foo', function() {
<ide> return emberGenerateDestroy(['initializer-test', 'foo'], _file => {
<ide> expect(_file('tests/unit/initializers/foo-test.js'))
<del> .to.contain("import { initialize } from 'dummy/initializers/foo';")
<del> .to.contain("module('Unit | Initializer | foo'")
<del> .to.contain("application = Application.create();")
<del> .to.contain("initialize(this.application);");
<add> .to.equal(fixture('initializer-test/dummy.js'));
<ide> });
<ide> });
<ide> });
<ide><path>node-tests/fixtures/initializer-test/default.js
<add>import Application from '@ember/application';
<add>import { run } from '@ember/runloop';
<add>
<add>import { initialize } from 'my-app/initializers/foo';
<add>import { module, test } from 'qunit';
<add>import destroyApp from '../../helpers/destroy-app';
<add>
<add>module('Unit | Initializer | foo', {
<add> beforeEach() {
<add> run(() => {
<add> this.application = Application.create();
<add> this.application.deferReadiness();
<add> });
<add> },
<add> afterEach() {
<add> destroyApp(this.application);
<add> }
<add>});
<add>
<add>// Replace this with your real tests.
<add>test('it works', function(assert) {
<add> initialize(this.application);
<add>
<add> // you would normally confirm the results of the initializer here
<add> assert.ok(true);
<add>});
<ide><path>node-tests/fixtures/initializer-test/dummy.js
<add>import Application from '@ember/application';
<add>import { run } from '@ember/runloop';
<add>
<add>import { initialize } from 'dummy/initializers/foo';
<add>import { module, test } from 'qunit';
<add>import destroyApp from '../../helpers/destroy-app';
<add>
<add>module('Unit | Initializer | foo', {
<add> beforeEach() {
<add> run(() => {
<add> this.application = Application.create();
<add> this.application.deferReadiness();
<add> });
<add> },
<add> afterEach() {
<add> destroyApp(this.application);
<add> }
<add>});
<add>
<add>// Replace this with your real tests.
<add>test('it works', function(assert) {
<add> initialize(this.application);
<add>
<add> // you would normally confirm the results of the initializer here
<add> assert.ok(true);
<add>});
<ide><path>node-tests/fixtures/initializer-test/mocha.js
<add>import { expect } from 'chai';
<add>import { describe, it, beforeEach, afterEach } from 'mocha';
<add>import { run } from '@ember/runloop';
<add>import Application from '@ember/application';
<add>import { initialize } from 'my-app/initializers/foo';
<add>import destroyApp from '../../helpers/destroy-app';
<add>
<add>describe('Unit | Initializer | foo', function() {
<add> let application;
<add>
<add> beforeEach(function() {
<add> run(function() {
<add> application = Application.create();
<add> application.deferReadiness();
<add> });
<add> });
<add>
<add> afterEach(function() {
<add> destroyApp(application);
<add> });
<add>
<add> // Replace this with your real tests.
<add> it('works', function() {
<add> initialize(application);
<add>
<add> // you would normally confirm the results of the initializer here
<add> expect(true).to.be.ok;
<add> });
<add>});
| 4
|
Python
|
Python
|
use str.format and print_function
|
b194fc3935772f5eba8b7c5b5e34e12d13281a4c
|
<ide><path>celery/app/base.py
<ide> def _rgetattr(self, path):
<ide> return reduce(getattr, [self] + path.split('.'))
<ide>
<ide> def __repr__(self):
<del> return '<%s %s:0x%x>' % (self.__class__.__name__,
<del> self.main or '__main__', id(self), )
<add> return '<{0} {1}:0x{2:x}>'.format(
<add> type(self).__name__, self.main or '__main__', id(self))
<ide>
<ide> def __reduce__(self):
<ide> # Reduce only pickles the configuration changes,
<ide><path>celery/app/control.py
<ide> def active_queues(self):
<ide> def conf(self):
<ide> return self._request('dump_conf')
<ide>
<add>
<ide> class Control(object):
<ide> Mailbox = Mailbox
<ide>
<ide><path>celery/app/defaults.py
<ide> def to_python(self, value):
<ide> return self.typemap[self.type](value)
<ide>
<ide> def __repr__(self):
<del> return '<Option: type->%s default->%r>' % (self.type, self.default)
<add> return '<Option: type->{0} default->{1!r}>'.format(self.type,
<add> self.default)
<ide>
<ide>
<ide> NAMESPACES = {
<ide> def find_deprecated_settings(source):
<ide> from celery.utils import warn_deprecated
<ide> for name, opt in flatten(NAMESPACES):
<ide> if (opt.deprecate_by or opt.remove_by) and getattr(source, name, None):
<del> warn_deprecated(description='The %r setting' % (name, ),
<add> warn_deprecated(description='The {0!r} setting'.format(name),
<ide> deprecation=opt.deprecate_by,
<ide> removal=opt.remove_by,
<ide> alternative=opt.alt)
<ide><path>celery/app/log.py
<ide> import os
<ide> import sys
<ide>
<add>from logging.handlers import WatchedFileHandler
<add>
<ide> from kombu.log import NullHandler
<ide>
<ide> from celery import signals
<ide> from celery._state import get_current_task
<ide> from celery.utils import isatty
<del>from celery.utils.compat import WatchedFileHandler
<ide> from celery.utils.log import (
<ide> get_logger, mlevel,
<ide> ColorFormatter, ensure_process_aware_logger,
<ide><path>celery/app/task.py
<ide> def get(self, key, default=None):
<ide> return default
<ide>
<ide> def __repr__(self):
<del> return '<Context: %r>' % (vars(self, ))
<add> return '<Context: {0!r}>'.format(vars(self))
<ide>
<ide> @property
<ide> def children(self):
<ide> def __new__(cls, name, bases, attrs):
<ide> return instance.__class__
<ide>
<ide> def __repr__(cls):
<del> if cls._app:
<del> return '<class %s of %s>' % (cls.__name__, cls._app, )
<del> return '<unbound %s>' % (cls.__name__, )
<add> return ('<class {0.__name__} of {0._app}>' if cls._app
<add> else '<unbound {0.__name__}>').format(cls)
<ide>
<ide>
<ide> class Task(object):
<ide> def retry(self, args=None, kwargs=None, exc=None, throw=True,
<ide> if exc:
<ide> maybe_reraise()
<ide> raise self.MaxRetriesExceededError(
<del> """Can't retry %s[%s] args:%s kwargs:%s""" % (
<add> "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
<ide> self.name, options['task_id'], args, kwargs))
<ide>
<ide> # If task was executed eagerly using apply(),
<ide> def pop_request(self):
<ide>
<ide> def __repr__(self):
<ide> """`repr(task)`"""
<del> return '<@task: %s>' % (self.name, )
<add> return '<@task: {0.name}>'.format(self)
<ide>
<ide> @property
<ide> def request(self):
<ide><path>celery/apps/worker.py
<ide> platform tweaks, and so on.
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import logging
<ide> import os
<ide> def active_thread_count():
<ide>
<ide>
<ide> def safe_say(msg):
<del> sys.__stderr__.write('\n%s\n' % msg)
<add> print('\n{0}'.format(msg), file=sys.__stderr__)
<ide>
<ide> ARTLINES = [
<ide> ' --------------',
<ide> def safe_say(msg):
<ide> ]
<ide>
<ide> BANNER = """\
<del>celery@%(hostname)s v%(version)s
<add>celery@{hostname} v{version}
<ide>
<ide> [Configuration]
<del>. broker: %(conninfo)s
<del>. app: %(app)s
<del>. concurrency: %(concurrency)s
<del>. events: %(events)s
<add>. broker: {conninfo}
<add>. app: {app}
<add>. concurrency: {concurrency}
<add>. events: {events}
<ide>
<ide> [Queues]
<del>%(queues)s
<add>{queues}
<ide> """
<ide>
<ide> EXTRA_INFO_FMT = """
<ide> [Tasks]
<del>%(tasks)s
<add>{tasks}
<ide> """
<ide>
<ide> UNKNOWN_QUEUE = """\
<del>Trying to select queue subset of %r, but queue %s is not
<add>Trying to select queue subset of {0!r}, but queue {1} is not
<ide> defined in the CELERY_QUEUES setting.
<ide>
<ide> If you want to automatically declare unknown queues you can
<ide> def run(self):
<ide>
<ide> def on_consumer_ready(self, consumer):
<ide> signals.worker_ready.send(sender=consumer)
<del> print('celery@%s has started.' % self.hostname)
<add> print('celery@{0.hostname} has started.'.format(self))
<ide>
<ide> def init_queues(self):
<ide> try:
<ide> self.app.select_queues(self.use_queues)
<ide> except KeyError as exc:
<del> raise ImproperlyConfigured(UNKNOWN_QUEUE % (self.use_queues, exc))
<add> raise ImproperlyConfigured(
<add> UNKNOWN_QUEUE.format(self.use_queues, exc))
<ide> if self.app.conf.CELERY_WORKER_DIRECT:
<ide> self.app.amqp.queues.select_add(worker_direct(self.hostname))
<ide>
<ide> def redirect_stdouts_to_logger(self):
<ide>
<ide> def purge_messages(self):
<ide> count = self.app.control.purge()
<del> print('purge: Erased %d %s from the queue.\n' % (
<add> print('purge: Erased {0} {1} from the queue.\n'.format(
<ide> count, pluralize(count, 'message')))
<ide>
<ide> def tasklist(self, include_builtins=True):
<ide> tasks = self.app.tasks.keys()
<ide> if not include_builtins:
<ide> tasks = filter(lambda s: not s.startswith('celery.'), tasks)
<del> return '\n'.join(' . %s' % task for task in sorted(tasks))
<add> return '\n'.join(' . {0}'.format(task) for task in sorted(tasks))
<ide>
<ide> def extra_info(self):
<ide> if self.loglevel <= logging.INFO:
<ide> include_builtins = self.loglevel <= logging.DEBUG
<ide> tasklist = self.tasklist(include_builtins=include_builtins)
<del> return EXTRA_INFO_FMT % {'tasks': tasklist}
<add> return EXTRA_INFO_FMT.format(tasks=tasklist)
<ide>
<ide> def startup_info(self):
<ide> app = self.app
<ide> concurrency = unicode(self.concurrency)
<del> appr = '%s:0x%x' % (app.main or '__main__', id(app))
<add> appr = '{0}:0x{1:x}'.format(app.main or '__main__', id(app))
<ide> if not isinstance(app.loader, AppLoader):
<ide> loader = qualname(app.loader)
<ide> if loader.startswith('celery.loaders'):
<ide> loader = loader[14:]
<del> appr += ' (%s)' % loader
<add> appr += ' ({0})'.format(loader)
<ide> if self.autoscale:
<ide> max, min = self.autoscale
<del> concurrency = '{min=%s, max=%s}' % (min, max)
<add> concurrency = '{{min={0}, max={1}}}'.format(min, max)
<ide> pool = self.pool_cls
<ide> if not isinstance(pool, basestring):
<ide> pool = pool.__module__
<del> concurrency += ' (%s)' % pool.split('.')[-1]
<add> concurrency += ' ({0})'.format(pool.split('.')[-1])
<ide> events = 'ON'
<ide> if not self.send_events:
<ide> events = 'OFF (enable -E to monitor this worker)'
<ide>
<del> banner = (BANNER % {
<del> 'app': appr,
<del> 'hostname': self.hostname,
<del> 'version': VERSION_BANNER,
<del> 'conninfo': self.app.connection().as_uri(),
<del> 'concurrency': concurrency,
<del> 'events': events,
<del> 'queues': app.amqp.queues.format(indent=0, indent_first=False),
<del> }).splitlines()
<add> banner = BANNER.format(
<add> app=appr,
<add> hostname=self.hostname,
<add> version=VERSION_BANNER,
<add> conninfo=self.app.connection().as_uri(),
<add> concurrency=concurrency,
<add> events=events,
<add> queues=app.amqp.queues.format(indent=0, indent_first=False),
<add> ).splitlines()
<ide>
<ide> # integrate the ASCII art.
<ide> for i, x in enumerate(banner):
<ide> def osx_proxy_detection_workaround(self):
<ide>
<ide> def set_process_status(self, info):
<ide> return platforms.set_mp_process_title('celeryd',
<del> info='%s (%s)' % (info, platforms.strargv(sys.argv)),
<add> info='{0} ({1})'.format(info, platforms.strargv(sys.argv)),
<ide> hostname=self.hostname)
<ide>
<ide>
<ide> def _handle_request(signum, frame):
<ide> if current_process()._name == 'MainProcess':
<ide> if callback:
<ide> callback(worker)
<del> safe_say('celeryd: %s shutdown (MainProcess)' % how)
<add> safe_say('celeryd: {0} shutdown (MainProcess)'.format(how))
<ide> if active_thread_count() > 1:
<ide> setattr(state, {'Warm': 'should_stop',
<ide> 'Cold': 'should_terminate'}[how], True)
<ide> def install_worker_restart_handler(worker, sig='SIGHUP'):
<ide> def restart_worker_sig_handler(signum, frame):
<ide> """Signal handler restarting the current python program."""
<ide> set_in_sighandler(True)
<del> safe_say('Restarting celeryd (%s)' % (' '.join(sys.argv), ))
<add> safe_say('Restarting celeryd ({0})'.format(' '.join(sys.argv)))
<ide> pid = os.fork()
<ide> if pid == 0:
<ide> os.execv(sys.executable, [sys.executable] + sys.argv)
<ide> def install_HUP_not_supported_handler(worker, sig='SIGHUP'):
<ide> def warn_on_HUP_handler(signum, frame):
<ide> set_in_sighandler(True)
<ide> try:
<del> safe_say('%(sig)s not supported: Restarting with %(sig)s is '
<del> 'unstable on this platform!' % {'sig': sig})
<add> safe_say('{sig} not supported: Restarting with {sig} is '
<add> 'unstable on this platform!'.format(sig=sig))
<ide> finally:
<ide> set_in_sighandler(False)
<ide> platforms.signals[sig] = warn_on_HUP_handler
<ide><path>celery/backends/__init__.py
<ide> from celery.utils.functional import memoize
<ide>
<ide> UNKNOWN_BACKEND = """\
<del>Unknown result backend: %r. Did you spell that correctly? (%r)\
<add>Unknown result backend: {0!r}. Did you spell that correctly? ({1!r})\
<ide> """
<ide>
<ide> BACKEND_ALIASES = {
<ide> def get_backend_cls(backend=None, loader=None):
<ide> try:
<ide> return symbol_by_name(backend, aliases)
<ide> except ValueError as exc:
<del> raise ValueError, ValueError(UNKNOWN_BACKEND % (
<add> raise ValueError, ValueError(UNKNOWN_BACKEND.format(
<ide> backend, exc)), sys.exc_info()[2]
<ide>
<ide>
<ide><path>celery/beat.py
<ide> def should_sync(self):
<ide> (time.time() - self._last_sync) > self.sync_every)
<ide>
<ide> def reserve(self, entry):
<del> new_entry = self.schedule[entry.name] = entry.next()
<add> new_entry = self.schedule[entry.name] = next(entry)
<ide> return new_entry
<ide>
<ide> def apply_async(self, entry, publisher=None, **kwargs):
<ide><path>celery/bin/base.py
<ide> Optional directory to change to after detaching.
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import os
<ide> import re
<ide> warnings.simplefilter('once', warning, 0)
<ide>
<ide> ARGV_DISABLED = """
<del>Unrecognized command line arguments: %s
<add>Unrecognized command line arguments: {0}
<ide>
<ide> Try --help?
<ide> """
<ide> class HelpFormatter(IndentedHelpFormatter):
<ide>
<ide> def format_epilog(self, epilog):
<ide> if epilog:
<del> return '\n%s\n\n' % epilog
<add> return '\n{0}\n\n'.format(epilog)
<ide> return ''
<ide>
<ide> def format_description(self, description):
<ide> def on_concurrency_setup(self):
<ide>
<ide> def usage(self, command):
<ide> """Returns the command-line usage string for this app."""
<del> return '%%prog [options] %s' % (self.args, )
<add> return '%%prog [options] {0.args}'.format(self)
<ide>
<ide> def get_options(self):
<ide> """Get supported command line options."""
<ide> def prepare_args(self, options, args):
<ide>
<ide> def check_args(self, args):
<ide> if not self.supports_args and args:
<del> self.die(ARGV_DISABLED % (', '.join(args, )), EX_USAGE)
<add> self.die(ARGV_DISABLED.format(', '.join(args)), EX_USAGE)
<ide>
<ide> def die(self, msg, status=EX_FAILURE):
<del> sys.stderr.write(msg + '\n')
<add> print(msg, file=sys.stderr)
<ide> sys.exit(status)
<ide>
<ide> def early_version(self, argv):
<ide> if '--version' in argv:
<del> sys.stdout.write('%s\n' % self.version)
<add> print(self.version)
<ide> sys.exit(0)
<ide>
<ide> def parse_options(self, prog_name, arguments):
<ide> def prepare_parser(self, parser):
<ide> for long_opt, help in doc.iteritems():
<ide> option = parser.get_option(long_opt)
<ide> if option is not None:
<del> option.help = ' '.join(help) % {'default': option.default}
<add> option.help = ' '.join(help).format(default=option.default)
<ide> return parser
<ide>
<ide> def prepare_preload_options(self, options):
<ide> def find_app(self, app):
<ide> sym = self.symbol_by_name(app)
<ide> if isinstance(sym, ModuleType):
<ide> if getattr(sym, '__path__', None):
<del> return self.find_app('%s.celery:' % (app.replace(':', ''), ))
<add> return self.find_app('{0}.celery:'.format(
<add> app.replace(':', '')))
<ide> return sym.celery
<ide> return sym
<ide>
<ide><path>celery/bin/camqadm.py
<ide> .. program:: celery amqp
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import cmd
<ide> import sys
<ide> import shlex
<ide> import pprint
<ide>
<add>from functools import partial
<ide> from itertools import count
<ide>
<ide> from amqplib import client_0_8 as amqp
<ide> -> queue.delete myqueue yes no
<ide> """
<ide>
<del>
<del>def say(m, fh=sys.stderr):
<del> fh.write('%s\n' % (m, ))
<add>say = partial(print, file=sys.stderr)
<ide>
<ide>
<ide> class Spec(object):
<ide> def __init__(self, *args, **kwargs):
<ide> def note(self, m):
<ide> """Say something to the user. Disabled if :attr:`silent`."""
<ide> if not self.silent:
<del> say(m, fh=self.out)
<add> say(m, file=self.out)
<ide>
<ide> def say(self, m):
<del> say(m, fh=self.out)
<add> say(m, file=self.out)
<ide>
<ide> def get_amqp_api_command(self, cmd, arglist):
<ide> """With a command name and a list of arguments, convert the arguments
<ide> def run(self):
<ide>
<ide> def note(self, m):
<ide> if not self.silent:
<del> say(m, fh=self.out)
<add> say(m, file=self.out)
<ide>
<ide>
<ide> class AMQPAdminCommand(Command):
<ide><path>celery/bin/celery.py
<ide> .. program:: celery
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import anyjson
<ide> import sys
<ide> def error(self, s):
<ide> self.out(s, fh=self.stderr)
<ide>
<ide> def out(self, s, fh=None):
<del> s = str(s)
<del> if not s.endswith('\n'):
<del> s += '\n'
<del> (fh or self.stdout).write(s)
<add> print(s, file=fh or self.stdout)
<ide>
<ide> def run_from_argv(self, prog_name, argv):
<ide> self.prog_name = prog_name
<ide> def run(self, *args, **kwargs):
<ide> no_color=kwargs.get('no_color', False),
<ide> stdout=self.stdout, stderr=self.stderr,
<ide> show_reply=False) \
<del> .run('ping', quiet=True, show_body=False, **kwargs)
<add> .run('ping', **dict(kwargs, quiet=True, show_body=False))
<ide> if not replies:
<ide> raise Error('No nodes replied within time constraint',
<ide> status=EX_UNAVAILABLE)
<ide><path>celery/bin/celerybeat.py
<ide>
<ide> Path to the schedule database. Defaults to `celerybeat-schedule`.
<ide> The extension '.db' may be appended to the filename.
<del> Default is %(default)s.
<add> Default is {default}.
<ide>
<ide> .. cmdoption:: -S, --scheduler
<ide>
<ide><path>celery/bin/celeryd.py
<ide> .. cmdoption:: -S, --statedb
<ide>
<ide> Path to the state database. The extension '.db' may
<del> be appended to the filename. Default: %(default)s
<add> be appended to the filename. Default: {default}
<ide>
<ide> .. cmdoption:: -E, --events
<ide>
<ide><path>celery/bin/celeryd_multi.py
<ide> celeryd -n xuzzy.myhost -c 3
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import errno
<ide> import os
<ide> def execute_from_commandline(self, argv, cmd='celeryd'):
<ide> return self.retcode
<ide>
<ide> def say(self, m, newline=True):
<del> self.fh.write('%s%s' % (m, '\n' if newline else ''))
<add> print(m, file=self.fh, end='\n' if newline else '')
<ide>
<ide> def names(self, argv, cmd):
<ide> p = NamespacedOptionParser(argv)
<ide><path>celery/canvas.py
<ide> from celery import current_app
<ide> from celery.local import Proxy
<ide> from celery.utils import cached_property, uuid
<del>from celery.utils.compat import chain_from_iterable
<ide> from celery.utils.functional import (
<ide> maybe_list, is_list, regen,
<ide> chunks as _chunks,
<ide> def link_error(self, errback):
<ide> return self.append_to_list_option('link_error', errback)
<ide>
<ide> def flatten_links(self):
<del> return list(chain_from_iterable(_chain([[self]],
<add> return list(_chain.from_iterable(_chain([[self]],
<ide> (link.flatten_links()
<ide> for link in maybe_list(self.options.get('link')) or []))))
<ide>
<ide><path>celery/contrib/rdb.py
<ide> def add(x, y):
<ide> base port. The selected port will be logged by the worker.
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import errno
<ide> import os
<ide> def get_avail_port(self, host, port, search_limit=100, skew=+0):
<ide> 'environment variable CELERY_RDB_PORT' % (self.me, ))
<ide>
<ide> def say(self, m):
<del> self.out.write(m + '\n')
<add> print(m, file=self.out)
<ide>
<ide> def _close_session(self):
<ide> self.stdin, self.stdout = sys.stdin, sys.stdout = self._prev_handles
<ide><path>celery/datastructures.py
<ide> Custom types and data structures.
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import sys
<ide> import time
<ide>
<ide> from collections import defaultdict
<add>from functools import partial
<ide> from itertools import chain
<ide>
<ide> from billiard.einfo import ExceptionInfo # noqa
<ide> def to_dot(self, fh, ws=' ' * 4):
<ide> :param fh: A file, or a file-like object to write the graph to.
<ide>
<ide> """
<del> fh.write('digraph dependencies {\n')
<add> P = partial(print, file=fh)
<add> P('digraph dependencies {')
<ide> for obj, adjacent in self.iteritems():
<ide> if not adjacent:
<del> fh.write(ws + '"%s"\n' % (obj, ))
<add> P(ws + '"{0}"'.format(obj))
<ide> for req in adjacent:
<del> fh.write(ws + '"%s" -> "%s"\n' % (obj, req))
<del> fh.write('}\n')
<add> P(ws + '"{0}" -> "{1}"'.format(obj, req))
<add> P('}')
<ide>
<ide> def __iter__(self):
<ide> return self.adjacent.iterkeys()
<ide><path>celery/events/cursesmon.py
<ide> Graphical monitor of Celery events using curses.
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import curses
<ide> import sys
<ide> def run(self):
<ide> def capture_events(app, state, display): # pragma: no cover
<ide>
<ide> def on_connection_error(exc, interval):
<del> sys.stderr.write('Connection Error: %r. Retry in %ss.' % (
<del> exc, interval))
<add> print('Connection Error: {0!r}. Retry in {1}s.'.format(
<add> exc, interval), file=sys.stderr)
<ide>
<ide> while 1:
<del> sys.stderr.write('-> evtop: starting capture...\n')
<add> print('-> evtop: starting capture...', file=sys.stderr)
<ide> with app.connection() as conn:
<ide> try:
<ide> conn.ensure_connection(on_connection_error,
<ide> def on_connection_error(exc, interval):
<ide> with recv.consumer():
<ide> recv.drain_events(timeout=1, ignore_timeouts=True)
<ide> except conn.connection_errors + conn.channel_errors as exc:
<del> sys.stderr.write('Connection lost: %r' % (exc, ))
<add> print('Connection lost: {0!r}'.format(exc), file=sys.stderr)
<ide>
<ide>
<ide> def evtop(app=None): # pragma: no cover
<ide><path>celery/events/dumper.py
<ide> as they happen. Think of it like a `tcpdump` for Celery events.
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import sys
<ide>
<ide> def humanize_type(type):
<ide> return type.lower().replace('-', ' ')
<ide>
<ide>
<del>def say(msg, out=sys.stdout):
<del> out.write(msg + '\n')
<del>
<del>
<ide> class Dumper(object):
<ide>
<ide> def __init__(self, out=sys.stdout):
<ide> self.out = out
<ide>
<ide> def say(self, msg):
<del> say(msg, out=self.out)
<add> print(msg, file=self.out)
<ide>
<ide> def on_event(self, event):
<ide> timestamp = datetime.utcfromtimestamp(event.pop('timestamp'))
<ide> def on_event(self, event):
<ide> if type.startswith('task-'):
<ide> uuid = event.pop('uuid')
<ide> if type in ('task-received', 'task-sent'):
<del> task = TASK_NAMES[uuid] = '%s(%s) args=%s kwargs=%s' % (
<add> task = TASK_NAMES[uuid] = '{0}({1}) args={2} kwargs={3}' \
<add> .format(
<ide> event.pop('name'), uuid,
<ide> event.pop('args'),
<ide> event.pop('kwargs'))
<ide> else:
<ide> task = TASK_NAMES.get(uuid, '')
<ide> return self.format_task_event(hostname, timestamp,
<ide> type, task, event)
<del> fields = ', '.join('%s=%s' % (key, event[key])
<add> fields = ', '.join('{0}={1}'.format(key, event[key])
<ide> for key in sorted(event.keys()))
<ide> sep = fields and ':' or ''
<del> self.say('%s [%s] %s%s %s' % (hostname, timestamp,
<del> humanize_type(type), sep, fields))
<add> self.say('{0} [{1}] {2}{3} {4}'.format(hostname, timestamp,
<add> humanize_type(type), sep, fields))
<ide>
<ide> def format_task_event(self, hostname, timestamp, type, task, event):
<del> fields = ', '.join('%s=%s' % (key, event[key])
<add> fields = ', '.join('{0}={1}'.format(key, event[key])
<ide> for key in sorted(event.keys()))
<ide> sep = fields and ':' or ''
<del> self.say('%s [%s] %s%s %s %s' % (hostname, timestamp,
<add> self.say('{0} [{1}] {2}{3} {4} {5}'.format(hostname, timestamp,
<ide> humanize_type(type), sep, task, fields))
<ide>
<ide>
<ide><path>celery/events/snapshot.py
<ide> def evcam(camera, freq=1.0, maxrate=None, loglevel=0,
<ide>
<ide> app.log.setup_logging_subsystem(loglevel, logfile)
<ide>
<del> logger.info(
<del> '-> evcam: Taking snapshots with %s (every %s secs.)\n' % (
<del> camera, freq))
<add> print('-> evcam: Taking snapshots with {0} (every {1} secs.)'.format(
<add> camera, freq))
<ide> state = app.events.State()
<ide> cam = instantiate(camera, state, app=app, freq=freq,
<ide> maxrate=maxrate, timer=timer)
<ide><path>celery/events/state.py
<ide> def _heartpush(self, timestamp):
<ide> self.heartbeats = self.heartbeats[self.heartbeat_max:]
<ide>
<ide> def __repr__(self):
<del> return '<Worker: %s (%s)' % (self.hostname,
<del> self.alive and 'ONLINE' or 'OFFLINE')
<add> return '<Worker: {0.hostname} (0.status_string)'.format(self)
<add>
<add> @property
<add> def status_string(self):
<add> return 'ONLINE' if self.alive else 'OFFLINE'
<ide>
<ide> @property
<ide> def heartbeat_expires(self):
<ide> def _keys():
<ide> return dict(_keys())
<ide>
<ide> def __repr__(self):
<del> return '<Task: %s(%s) %s>' % (self.name, self.uuid, self.state)
<add> return '<Task: {0.name}({0.uuid}) {0.state}>'.format(self)
<ide>
<ide> @property
<ide> def ready(self):
<ide> def worker_event(self, type, fields):
<ide> hostname = fields.pop('hostname', None)
<ide> if hostname:
<ide> worker = self.get_or_create_worker(hostname)
<del> handler = getattr(worker, 'on_%s' % type, None)
<add> handler = getattr(worker, 'on_' + type, None)
<ide> if handler:
<ide> handler(**fields)
<ide>
<ide> def task_event(self, type, fields):
<ide> hostname = fields.pop('hostname')
<ide> worker = self.get_or_create_worker(hostname)
<ide> task = self.get_or_create_task(uuid)
<del> handler = getattr(task, 'on_%s' % type, None)
<add> handler = getattr(task, 'on_' + type, None)
<ide> if type == 'received':
<ide> self.task_count += 1
<ide> if handler:
<ide> def alive_workers(self):
<ide> return [w for w in self.workers.values() if w.alive]
<ide>
<ide> def __repr__(self):
<del> return '<ClusterState: events=%s tasks=%s>' % (self.event_count,
<del> self.task_count)
<add> return '<State: events={0.event_count} tasks={0.task_count}>' \
<add> .format(self)
<ide>
<ide>
<ide> state = State()
<ide><path>celery/loaders/base.py
<ide> BUILTIN_MODULES = frozenset()
<ide>
<ide> ERROR_ENVVAR_NOT_SET = (
<del>"""The environment variable %r is not set,
<add>"""The environment variable {0!r} is not set,
<ide> and as such the configuration could not be loaded.
<ide> Please set this variable and make it point to
<ide> a configuration module.""")
<ide> def config_from_envvar(self, variable_name, silent=False):
<ide> if not module_name:
<ide> if silent:
<ide> return False
<del> raise ImproperlyConfigured(self.error_envvar_not_set % module_name)
<add> raise ImproperlyConfigured(
<add> self.error_envvar_not_set.format(module_name))
<ide> return self.config_from_object(module_name, silent=silent)
<ide>
<ide> def config_from_object(self, obj, silent=False):
<ide> def getarg(arg):
<ide> value = NAMESPACES[ns][key].to_python(value)
<ide> except ValueError as exc:
<ide> # display key name in error message.
<del> raise ValueError('%r: %s' % (ns_key, exc))
<add> raise ValueError('{0!r}: {1}'.format(ns_key, exc))
<ide> return ns_key, value
<ide>
<ide> return dict(map(getarg, args))
<ide><path>celery/loaders/default.py
<ide> C_WNOCONF = strtobool(os.environ.get('C_WNOCONF', False))
<ide>
<ide> CONFIG_INVALID_NAME = """
<del>Error: Module '%(module)s' doesn't exist, or it's not a valid \
<add>Error: Module '{module}' doesn't exist, or it's not a valid \
<ide> Python module name.
<ide> """
<ide>
<ide> CONFIG_WITH_SUFFIX = CONFIG_INVALID_NAME + """
<del>Did you mean '%(suggest)s'?
<add>Did you mean '{suggest}'?
<ide> """
<ide>
<ide>
<ide> def read_configuration(self):
<ide> except NotAPackage:
<ide> if configname.endswith('.py'):
<ide> raise NotAPackage, NotAPackage(
<del> CONFIG_WITH_SUFFIX % {
<del> 'module': configname,
<del> 'suggest': configname[:-3]}), sys.exc_info()[2]
<add> CONFIG_WITH_SUFFIX.format(
<add> module=configname,
<add> suggest=configname[:-3])), sys.exc_info()[2]
<ide> raise NotAPackage, NotAPackage(
<del> CONFIG_INVALID_NAME % {
<del> 'module': configname}), sys.exc_info()[2]
<add> CONFIG_INVALID_NAME.format(
<add> module=configname)), sys.exc_info()[2]
<ide> except ImportError:
<ide> # billiard sets this if forked using execv
<ide> if C_WNOCONF and not os.environ.get('FORKED_BY_MULTIPROCESSING'):
<ide> warnings.warn(NotConfigured(
<del> 'No %r module found! Please make sure it exists and '
<del> 'is available to Python.' % (configname, )))
<add> 'No {module} module found! Please make sure it exists and '
<add> 'is available to Python.'.format(module=configname)))
<ide> return self.setup_settings({})
<ide> else:
<ide> celeryconfig = self.import_from_cwd(configname)
<ide><path>celery/platforms.py
<ide> users, groups, and so on.
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import atexit
<ide> import errno
<ide>
<ide> _setps_bucket = TokenBucket(0.5) # 30/m, every 2 seconds
<ide>
<del>PIDLOCKED = """ERROR: Pidfile (%s) already exists.
<del>Seems we're already running? (PID: %s)"""
<add>PIDLOCKED = """ERROR: Pidfile ({0}) already exists.
<add>Seems we're already running? (PID: {1})"""
<ide>
<ide>
<ide> def pyimplementation():
<ide> def read_pid(self):
<ide> line = fh.readline()
<ide> if line.strip() == line: # must contain '\n'
<ide> raise ValueError(
<del> 'Partially written or invalid pidfile %r' % (self.path))
<add> 'Partial or invalid pidfile {0.path}'.format(self))
<ide> finally:
<ide> fh.close()
<ide>
<ide> try:
<ide> return int(line.strip())
<ide> except ValueError:
<del> raise ValueError('PID file %r contents invalid.' % self.path)
<add> raise ValueError('PID file {0.path} invalid.'.format(self))
<ide>
<ide> def remove(self):
<ide> """Removes the lock."""
<ide> def remove_if_stale(self):
<ide> try:
<ide> pid = self.read_pid()
<ide> except ValueError as exc:
<del> sys.stderr.write('Broken pidfile found. Removing it.\n')
<add> print('Broken pidfile found. Removing it.', file=sys.stderr)
<ide> self.remove()
<ide> return True
<ide> if not pid:
<ide> def remove_if_stale(self):
<ide> os.kill(pid, 0)
<ide> except os.error as exc:
<ide> if exc.errno == errno.ESRCH:
<del> sys.stderr.write('Stale pidfile exists. Removing it.\n')
<add> print('Stale pidfile exists. Removing it.', file=sys.stderr)
<ide> self.remove()
<ide> return True
<ide> return False
<ide>
<ide> def write_pid(self):
<ide> pid = os.getpid()
<del> content = '%d\n' % (pid, )
<add> content = '{0}\n'.format(pid)
<ide>
<ide> pidfile_fd = os.open(self.path, PIDFILE_FLAGS, PIDFILE_MODE)
<ide> pidfile = os.fdopen(pidfile_fd, 'w')
<ide> def create_pidlock(pidfile):
<ide> """
<ide> pidlock = PIDFile(pidfile)
<ide> if pidlock.is_locked() and not pidlock.remove_if_stale():
<del> raise SystemExit(PIDLOCKED % (pidfile, pidlock.read_pid()))
<add> raise SystemExit(PIDLOCKED.format(pidfile, pidlock.read_pid()))
<ide> pidlock.acquire()
<ide> atexit.register(pidlock.release)
<ide> return pidlock
<ide> def parse_uid(uid):
<ide> try:
<ide> return pwd.getpwnam(uid).pw_uid
<ide> except (AttributeError, KeyError):
<del> raise KeyError('User does not exist: %r' % (uid, ))
<add> raise KeyError('User does not exist: {0}'.format(uid))
<ide>
<ide>
<ide> def parse_gid(gid):
<ide> def parse_gid(gid):
<ide> try:
<ide> return grp.getgrnam(gid).gr_gid
<ide> except (AttributeError, KeyError):
<del> raise KeyError('Group does not exist: %r' % (gid, ))
<add> raise KeyError('Group does not exist: {0}'.format(gid))
<ide>
<ide>
<ide> def _setgroups_hack(groups):
<ide> def set_process_title(progname, info=None):
<ide> Only works if :mod:`setproctitle` is installed.
<ide>
<ide> """
<del> proctitle = '[%s]' % progname
<del> proctitle = '%s %s' % (proctitle, info) if info else proctitle
<add> proctitle = '[{0}]'.format(progname)
<add> proctitle = '{0} {1}'.format(proctitle, info) if info else proctitle
<ide> if _setproctitle:
<ide> _setproctitle.setproctitle(proctitle)
<ide> return proctitle
<ide> def set_mp_process_title(progname, info=None, hostname=None, # noqa
<ide> """
<ide> if not rate_limit or _setps_bucket.can_consume(1):
<ide> if hostname:
<del> progname = '%s@%s' % (progname, hostname.split('.')[0])
<add> progname = '{0}@{1}'.format(progname, hostname.split('.')[0])
<ide> return set_process_title(
<del> '%s:%s' % (progname, current_process().name), info=info)
<add> '{0}:{1}'.format(progname, current_process().name), info=info)
<ide>
<ide>
<ide> def shellsplit(s):
<ide><path>celery/schedules.py
<ide> timezone)
<ide> from .datastructures import AttributeDict
<ide>
<add>CRON_PATTERN_INVALID = """\
<add>Invalid crontab pattern. Valid range is {min}-{max}. \
<add>'{value}' was found.\
<add>"""
<add>
<add>CRON_INVALID_TYPE = """\
<add>Argument cronspec needs to be of any of the following types: \
<add>int, basestring, or an iterable type. {type!r} was given.\
<add>"""
<add>
<ide>
<ide> class ParseException(Exception):
<ide> """Raised by crontab_parser when the input can't be parsed."""
<ide> def is_due(self, last_run_at):
<ide> return False, rem
<ide>
<ide> def __repr__(self):
<del> return '<freq: %s>' % self.human_seconds
<add> return '<freq: {0.human_seconds}>'.format(self)
<ide>
<ide> def __eq__(self, other):
<ide> if isinstance(other, schedule):
<ide> def _expand_number(self, s):
<ide> try:
<ide> i = weekday(s)
<ide> except KeyError:
<del> raise ValueError("Invalid weekday literal '%s'." % s)
<add> raise ValueError("Invalid weekday literal {0!r}.".format(s))
<ide>
<ide> if i < self.min_:
<del> raise ValueError('Invalid beginning range: %s < %s.' %
<del> (i, self.min_))
<add> raise ValueError(
<add> 'Invalid beginning range: {0} < {1}.'.format(i, self.min_))
<ide> return i
<ide>
<ide>
<ide> def _expand_cronspec(cronspec, max_, min_=0):
<ide> elif is_iterable(cronspec):
<ide> result = set(cronspec)
<ide> else:
<del> raise TypeError(
<del> 'Argument cronspec needs to be of any of the '
<del> 'following types: int, basestring, or an iterable type. '
<del> "'%s' was given." % type(cronspec))
<add> raise TypeError(CRON_INVALID_TYPE.format(type=type(cronspec)))
<ide>
<ide> # assure the result does not preceed the min or exceed the max
<ide> for number in result:
<ide> if number >= max_ + min_ or number < min_:
<del> raise ValueError(
<del> 'Invalid crontab pattern. Valid '
<del> "range is %d-%d. '%d' was found." %
<del> (min_, max_ - 1 + min_, number))
<del>
<add> raise ValueError(CRON_PATTERN_INVALID.format(
<add> min=min_, max=max_ - 1 + min_, value=number))
<ide> return result
<ide>
<ide> def _delta_to_next(self, last_run_at, next_hour, next_minute):
<ide><path>celery/task/http.py
<ide> def __str__(self):
<ide> scheme, netloc, path, params, query, fragment = self.parts
<ide> query = urlencode(utf8dict(self.query.items()))
<ide> components = [scheme + '://', netloc, path or '/',
<del> ';%s' % params if params else '',
<del> '?%s' % query if query else '',
<del> '#%s' % fragment if fragment else '']
<add> ';{0}'.format(params) if params else '',
<add> '?{0}'.format(query) if query else '',
<add> '#{0}'.format(fragment) if fragment else '']
<ide> return ''.join(filter(None, components))
<ide>
<ide> def __repr__(self):
<del> return '<%s: %s>' % (self.__class__.__name__, str(self))
<add> return '<{0}: {1}>'.format(type(self).__name__, self)
<ide>
<ide>
<ide> class HttpDispatch(object):
<ide> class HttpDispatch(object):
<ide> :param logger: Logger used for user/system feedback.
<ide>
<ide> """
<del> user_agent = 'celery/%s' % celery_version
<add> user_agent = 'celery/{version}'.format(version=celery_version)
<ide> timeout = 5
<ide>
<ide> def __init__(self, url, method, task_kwargs, **kwargs):
<ide><path>celery/task/sets.py
<ide> def apply(self, taskset_id=None):
<ide> def _sync_results(self, taskset_id):
<ide> return [task.apply(taskset_id=taskset_id) for task in self]
<ide>
<del> def _get_tasks(self):
<add> @property
<add> def tasks(self):
<ide> return self
<ide>
<del> def _set_tasks(self, tasks):
<add> @tasks.setter # noqa
<add> def tasks(self, tasks):
<ide> self[:] = tasks
<del> tasks = property(_get_tasks, _set_tasks)
<ide><path>celery/task/trace.py
<ide> def report_internal_error(task, exc):
<ide> _value = task.backend.prepare_exception(exc)
<ide> exc_info = ExceptionInfo((_type, _value, _tb), internal=True)
<ide> warn(RuntimeWarning(
<del> 'Exception raised outside body: %r:\n%s' % (
<add> 'Exception raised outside body: {0!r}:\n{1}'.format(
<ide> exc, exc_info.traceback)))
<ide> return exc_info
<ide> finally:
<ide><path>celery/tests/app/test_beat.py
<ide> def test_next(self):
<ide> self.assertEqual(entry.total_run_count, 0)
<ide>
<ide> next_run_at = entry.last_run_at + timedelta(seconds=10)
<del> next = entry.next(next_run_at)
<del> self.assertGreaterEqual(next.last_run_at, next_run_at)
<del> self.assertEqual(next.total_run_count, 1)
<add> next_entry = entry.next(next_run_at)
<add> self.assertGreaterEqual(next_entry.last_run_at, next_run_at)
<add> self.assertEqual(next_entry.total_run_count, 1)
<ide>
<ide> def test_is_due(self):
<ide> entry = self.create_entry(schedule=timedelta(seconds=10))
<ide> def test_is_due(self):
<ide> self.assertGreater(next_time_to_run1, 9)
<ide>
<ide> next_run_at = entry.last_run_at - timedelta(seconds=10)
<del> next = entry.next(next_run_at)
<del> due2, next_time_to_run2 = next.is_due()
<add> next_entry = entry.next(next_run_at)
<add> due2, next_time_to_run2 = next_entry.is_due()
<ide> self.assertTrue(due2)
<ide> self.assertGreater(next_time_to_run2, 9)
<ide>
<ide><path>celery/tests/app/test_loaders.py
<ide>
<ide> import os
<ide> import sys
<add>import warnings
<ide>
<ide> from mock import Mock, patch
<ide>
<ide> from celery.utils.mail import SendmailWarning
<ide>
<ide> from celery.tests.utils import AppCase, Case
<del>from celery.tests.compat import catch_warnings
<ide>
<ide>
<ide> class ObjectConfig(object):
<ide> class _Loader(default.Loader):
<ide> def find_module(self, name):
<ide> raise ImportError(name)
<ide>
<del> with catch_warnings(record=True):
<add> with warnings.catch_warnings(record=True):
<ide> l = _Loader()
<ide> self.assertDictEqual(l.conf, {})
<ide> context_executed[0] = True
<ide><path>celery/tests/backends/test_amqp.py
<ide> def Consumer(*args, **kwargs):
<ide>
<ide> b = Backend()
<ide> with self.assertRaises(KeyError):
<del> b.get_many(['id1']).next()
<add> next(b.get_many(['id1']))
<ide>
<ide> def test_test_get_many_raises_inner_block(self):
<ide>
<ide> def drain_events(self, *args, **kwargs):
<ide>
<ide> b = Backend()
<ide> with self.assertRaises(KeyError):
<del> b.get_many(['id1']).next()
<add> next(b.get_many(['id1']))
<ide>
<ide> def test_no_expires(self):
<ide> b = self.create_backend(expires=None)
<ide><path>celery/tests/backends/test_database.py
<ide> from __future__ import absolute_import
<ide>
<del>import sys
<del>
<ide> from datetime import datetime
<ide>
<ide> from nose import SkipTest
<ide><path>celery/tests/bin/test_base.py
<ide> def test_early_version(self, stdout):
<ide> cmd = Command()
<ide> with self.assertRaises(SystemExit):
<ide> cmd.early_version(['--version'])
<del> stdout.write.assert_called_with(cmd.version + '\n')
<ide>
<ide> def test_execute_from_commandline(self):
<ide> cmd = MockCommand()
<ide><path>celery/tests/bin/test_celery.py
<ide> def test_error(self):
<ide> def test_out(self):
<ide> f = Mock()
<ide> self.cmd.out('foo', f)
<del> f.write.assert_called_with('foo\n')
<del> self.cmd.out('foo\n', f)
<ide>
<ide> def test_call(self):
<ide> self.cmd.run = Mock()
<ide><path>celery/tests/compat.py
<del>from __future__ import absolute_import
<del>
<del>import sys
<del>
<del>
<del>class WarningMessage(object):
<del>
<del> """Holds the result of a single showwarning() call."""
<del>
<del> _WARNING_DETAILS = ('message', 'category', 'filename', 'lineno', 'file',
<del> 'line')
<del>
<del> def __init__(self, message, category, filename, lineno, file=None,
<del> line=None):
<del> local_values = locals()
<del> for attr in self._WARNING_DETAILS:
<del> setattr(self, attr, local_values[attr])
<del>
<del> self._category_name = category and category.__name__ or None
<del>
<del> def __str__(self):
<del> return ('{message : %r, category : %r, filename : %r, lineno : %s, '
<del> 'line : %r}' % (self.message, self._category_name,
<del> self.filename, self.lineno, self.line))
<del>
<del>
<del>class catch_warnings(object):
<del>
<del> """A context manager that copies and restores the warnings filter upon
<del> exiting the context.
<del>
<del> The 'record' argument specifies whether warnings should be captured by a
<del> custom implementation of warnings.showwarning() and be appended to a list
<del> returned by the context manager. Otherwise None is returned by the context
<del> manager. The objects appended to the list are arguments whose attributes
<del> mirror the arguments to showwarning().
<del>
<del> The 'module' argument is to specify an alternative module to the module
<del> named 'warnings' and imported under that name. This argument is only
<del> useful when testing the warnings module itself.
<del>
<del> """
<del>
<del> def __init__(self, record=False, module=None):
<del> """Specify whether to record warnings and if an alternative module
<del> should be used other than sys.modules['warnings'].
<del>
<del> For compatibility with Python 3.0, please consider all arguments to be
<del> keyword-only.
<del>
<del> """
<del> self._record = record
<del> self._module = module is None and sys.modules['warnings'] or module
<del> self._entered = False
<del>
<del> def __repr__(self):
<del> args = []
<del> if self._record:
<del> args.append('record=True')
<del> if self._module is not sys.modules['warnings']:
<del> args.append('module=%r' % self._module)
<del> name = type(self).__name__
<del> return '%s(%s)' % (name, ', '.join(args))
<del>
<del> def __enter__(self):
<del> if self._entered:
<del> raise RuntimeError('Cannot enter %r twice' % self)
<del> self._entered = True
<del> self._filters = self._module.filters
<del> self._module.filters = self._filters[:]
<del> self._showwarning = self._module.showwarning
<del> if self._record:
<del> log = []
<del>
<del> def showwarning(*args, **kwargs):
<del> log.append(WarningMessage(*args, **kwargs))
<del>
<del> self._module.showwarning = showwarning
<del> return log
<del>
<del> def __exit__(self, *exc_info):
<del> if not self._entered:
<del> raise RuntimeError('Cannot exit %r without entering first' % self)
<del> self._module.filters = self._filters
<del> self._module.showwarning = self._showwarning
<ide><path>celery/tests/compat_modules/test_decorators.py
<ide> from __future__ import absolute_import
<ide>
<add>import warnings
<add>
<ide> from celery.task import base
<ide>
<del>from celery.tests.compat import catch_warnings
<ide> from celery.tests.utils import Case
<ide>
<ide>
<ide> def add(x, y):
<ide> class test_decorators(Case):
<ide>
<ide> def setUp(self):
<del> with catch_warnings(record=True):
<add> with warnings.catch_warnings(record=True):
<ide> from celery import decorators
<ide> self.decorators = decorators
<ide>
<ide><path>celery/tests/events/test_events.py
<ide> def test_itercapture(self):
<ide> try:
<ide> r = self.app.events.Receiver(connection, node_id='celery.tests')
<ide> it = r.itercapture(timeout=0.0001, wakeup=False)
<del> consumer = it.next()
<add> consumer = next(it)
<ide> self.assertTrue(consumer.queues)
<ide> self.assertEqual(consumer.callbacks[0], r._receive)
<ide>
<ide> with self.assertRaises(socket.timeout):
<del> it.next()
<add> next(it)
<ide>
<ide> with self.assertRaises(socket.timeout):
<ide> r.capture(timeout=0.00001)
<ide> def handler(event):
<ide> for ev in evs:
<ide> producer.send(ev)
<ide> it = r.itercapture(limit=4, wakeup=True)
<del> it.next() # skip consumer (see itercapture)
<add> next(it) # skip consumer (see itercapture)
<ide> list(it)
<ide> self.assertEqual(events_received[0], 4)
<ide> finally:
<ide><path>celery/tests/events/test_state.py
<ide> def test_repr(self):
<ide>
<ide> def test_worker_online_offline(self):
<ide> r = ev_worker_online_offline(State())
<del> r.next()
<add> next(r)
<ide> self.assertTrue(r.state.alive_workers())
<ide> self.assertTrue(r.state.workers['utest1'].alive)
<ide> r.play()
<ide> def test_itertasks(self):
<ide>
<ide> def test_worker_heartbeat_expire(self):
<ide> r = ev_worker_heartbeats(State())
<del> r.next()
<add> next(r)
<ide> self.assertFalse(r.state.alive_workers())
<ide> self.assertFalse(r.state.workers['utest1'].alive)
<ide> r.play()
<ide> def test_task_states(self):
<ide> r = ev_task_states(State())
<ide>
<ide> # RECEIVED
<del> r.next()
<add> next(r)
<ide> self.assertTrue(r.tid in r.state.tasks)
<ide> task = r.state.tasks[r.tid]
<ide> self.assertEqual(task.state, states.RECEIVED)
<ide> def test_task_states(self):
<ide> self.assertEqual(task.worker.hostname, 'utest1')
<ide>
<ide> # STARTED
<del> r.next()
<add> next(r)
<ide> self.assertTrue(r.state.workers['utest1'].alive,
<ide> 'any task event adds worker heartbeat')
<ide> self.assertEqual(task.state, states.STARTED)
<ide> def test_task_states(self):
<ide> self.assertEqual(task.worker.hostname, 'utest1')
<ide>
<ide> # REVOKED
<del> r.next()
<add> next(r)
<ide> self.assertEqual(task.state, states.REVOKED)
<ide> self.assertTrue(task.revoked)
<ide> self.assertEqual(task.timestamp, task.revoked)
<ide> self.assertEqual(task.worker.hostname, 'utest1')
<ide>
<ide> # RETRY
<del> r.next()
<add> next(r)
<ide> self.assertEqual(task.state, states.RETRY)
<ide> self.assertTrue(task.retried)
<ide> self.assertEqual(task.timestamp, task.retried)
<ide> def test_task_states(self):
<ide> self.assertEqual(task.traceback, 'line 2 at main')
<ide>
<ide> # FAILURE
<del> r.next()
<add> next(r)
<ide> self.assertEqual(task.state, states.FAILURE)
<ide> self.assertTrue(task.failed)
<ide> self.assertEqual(task.timestamp, task.failed)
<ide> def test_task_states(self):
<ide> self.assertEqual(task.traceback, 'line 1 at main')
<ide>
<ide> # SUCCESS
<del> r.next()
<add> next(r)
<ide> self.assertEqual(task.state, states.SUCCESS)
<ide> self.assertTrue(task.succeeded)
<ide> self.assertEqual(task.timestamp, task.succeeded)
<ide><path>celery/tests/security/test_certificate.py
<ide> def test_invalid_certificate(self):
<ide> self.assertRaises(SecurityError, Certificate, KEY1)
<ide>
<ide> def test_has_expired(self):
<del> self.assertTrue(Certificate(CERT1).has_expired())
<add> self.assertFalse(Certificate(CERT1).has_expired())
<ide>
<ide>
<ide> class test_CertStore(SecurityCase):
<ide><path>celery/tests/tasks/test_result.py
<ide> def test_iterate_raises(self):
<ide> ts = GroupResult(uuid(), [ar])
<ide> it = iter(ts)
<ide> with self.assertRaises(KeyError):
<del> it.next()
<add> next(it)
<ide>
<ide> def test_forget(self):
<ide> subs = [MockAsyncResultSuccess(uuid()),
<ide> def test_iterate_yields(self):
<ide> ar2 = MockAsyncResultSuccess(uuid())
<ide> ts = GroupResult(uuid(), [ar, ar2])
<ide> it = iter(ts)
<del> self.assertEqual(it.next(), 42)
<del> self.assertEqual(it.next(), 42)
<add> self.assertEqual(next(it), 42)
<add> self.assertEqual(next(it), 42)
<ide>
<ide> def test_iterate_eager(self):
<ide> ar1 = EagerResult(uuid(), 42, states.SUCCESS)
<ide> ar2 = EagerResult(uuid(), 42, states.SUCCESS)
<ide> ts = GroupResult(uuid(), [ar1, ar2])
<ide> it = iter(ts)
<del> self.assertEqual(it.next(), 42)
<del> self.assertEqual(it.next(), 42)
<add> self.assertEqual(next(it), 42)
<add> self.assertEqual(next(it), 42)
<ide>
<ide> def test_join_timeout(self):
<ide> ar = MockAsyncResultSuccess(uuid())
<ide><path>celery/tests/utilities/test_local.py
<ide> from __future__ import absolute_import
<ide>
<del>import sys
<del>
<del>from nose import SkipTest
<del>
<ide> from celery.local import Proxy, PromiseProxy, maybe_evaluate, try_import
<del>
<ide> from celery.tests.utils import Case
<ide>
<ide>
<ide><path>celery/tests/utilities/test_mail.py
<ide> def test_str(self):
<ide>
<ide> class test_Mailer(Case):
<ide>
<del> def test_send_supports_timeout(self):
<add> def test_send_wrapper(self):
<ide> mailer = Mailer()
<del> mailer.supports_timeout = True
<ide> mailer._send = Mock()
<ide> mailer.send(msg)
<del> mailer._send.assert_called_with(msg, timeout=2)
<del>
<del> @patch('socket.setdefaulttimeout')
<del> @patch('socket.getdefaulttimeout')
<del> def test_send_no_timeout(self, get, set):
<del> mailer = Mailer()
<del> mailer.supports_timeout = False
<del> mailer._send = Mock()
<del> get.return_value = 10
<del> mailer.send(msg)
<del> get.assert_called_with()
<del> sets = set.call_args_list
<del> self.assertEqual(sets[0][0], (2, ))
<del> self.assertEqual(sets[1][0], (10, ))
<ide> mailer._send.assert_called_with(msg)
<ide>
<ide> @patch('smtplib.SMTP_SSL', create=True)
<ide><path>celery/tests/utils.py
<ide> from ..utils.compat import WhateverIO
<ide> from ..utils.functional import noop
<ide>
<del>from .compat import catch_warnings
<del>
<ide>
<ide> class Mock(mock.Mock):
<ide>
<ide> def __enter__(self):
<ide> for v in sys.modules.values():
<ide> if getattr(v, '__warningregistry__', None):
<ide> v.__warningregistry__ = {}
<del> self.warnings_manager = catch_warnings(record=True)
<add> self.warnings_manager = warnings.catch_warnings(record=True)
<ide> self.warnings = self.warnings_manager.__enter__()
<ide> warnings.simplefilter('always', self.expected)
<ide> return self
<ide><path>celery/tests/worker/test_hub.py
<ide> def test_fire_timers(self):
<ide> max_delay=32.321), 32.321)
<ide>
<ide> hub.timer._queue = [1]
<del> hub.scheduler = Mock()
<del> hub.scheduler.next.return_value = 3.743, None
<add> hub.scheduler = iter([(3.743, None)])
<ide> self.assertEqual(hub.fire_timers(), 3.743)
<ide>
<ide> e1, e2, e3 = Mock(), Mock(), Mock()
<ide> entries = [e1, e2, e3]
<ide>
<ide> def se():
<del> if entries:
<del> return None, entries.pop()
<del> return 3.982, None
<del> hub.scheduler.next = Mock()
<del> hub.scheduler.next.side_effect = se
<add> while 1:
<add> while entries:
<add> yield None, entries.pop()
<add> yield 3.982, None
<add> hub.scheduler = se()
<ide>
<ide> self.assertEqual(hub.fire_timers(max_timers=10), 3.982)
<ide> hub.timer.apply_entry.assert_has_calls(map(call, [e3, e2, e1]))
<ide><path>celery/utils/__init__.py
<ide> Utility functions.
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import operator
<ide> import os
<ide> from .functional import noop
<ide>
<ide> PENDING_DEPRECATION_FMT = """
<del> %(description)s is scheduled for deprecation in \
<del> version %(deprecation)s and removal in version v%(removal)s. \
<del> %(alternative)s
<add> {description} is scheduled for deprecation in \
<add> version {deprecation} and removal in version v{removal}. \
<add> {alternative}
<ide> """
<ide>
<ide> DEPRECATION_FMT = """
<del> %(description)s is deprecated and scheduled for removal in
<del> version %(removal)s. %(alternative)s
<add> {description} is deprecated and scheduled for removal in
<add> version {removal}. {alternative}
<ide> """
<ide>
<ide> #: Billiard sets this when execv is enabled.
<ide> WORKER_DIRECT_EXCHANGE = Exchange('C.dq')
<ide>
<ide> #: Format for worker direct queue names.
<del>WORKER_DIRECT_QUEUE_FORMAT = '%s.dq'
<add>WORKER_DIRECT_QUEUE_FORMAT = '{hostname}.dq'
<ide>
<ide>
<ide> def worker_direct(hostname):
<ide> if isinstance(hostname, Queue):
<ide> return hostname
<del> return Queue(WORKER_DIRECT_QUEUE_FORMAT % hostname,
<add> return Queue(WORKER_DIRECT_QUEUE_FORMAT.format(hostname=hostname),
<ide> WORKER_DIRECT_EXCHANGE,
<ide> hostname,
<ide> auto_delete=True)
<ide> def warn_deprecated(description=None, deprecation=None, removal=None,
<ide> 'deprecation': deprecation, 'removal': removal,
<ide> 'alternative': alternative}
<ide> if deprecation is not None:
<del> w = CPendingDeprecationWarning(PENDING_DEPRECATION_FMT % ctx)
<add> w = CPendingDeprecationWarning(PENDING_DEPRECATION_FMT.format(**ctx))
<ide> else:
<del> w = CDeprecationWarning(DEPRECATION_FMT % ctx)
<add> w = CDeprecationWarning(DEPRECATION_FMT.format(**ctx))
<ide> warnings.warn(w)
<ide>
<ide>
<ide> def cry(): # pragma: no cover
<ide> main_thread = t
<ide>
<ide> out = StringIO()
<del> sep = '=' * 49 + '\n'
<add> P = partial(print, file=out)
<add> sep = '=' * 49
<ide> for tid, frame in sys._current_frames().iteritems():
<ide> thread = tmap.get(tid, main_thread)
<ide> if not thread:
<ide> # skip old junk (left-overs from a fork)
<ide> continue
<del> out.write('%s\n' % (thread.getName(), ))
<del> out.write(sep)
<add> P('{0.name}'.format(thread))
<add> P(sep)
<ide> traceback.print_stack(frame, file=out)
<del> out.write(sep)
<del> out.write('LOCAL VARIABLES\n')
<del> out.write(sep)
<add> P(sep)
<add> P('LOCAL VARIABLES')
<add> P(sep)
<ide> pprint(frame.f_locals, stream=out)
<del> out.write('\n\n')
<add> P('\n')
<ide> return out.getvalue()
<ide>
<ide>
<ide> def strtobool(term, table={'false': False, 'no': False, '0': False,
<ide> try:
<ide> return table[term.lower()]
<ide> except KeyError:
<del> raise TypeError('Cannot coerce %r to type bool' % (term, ))
<add> raise TypeError('Cannot coerce {0!r} to type bool'.format(term))
<ide> return term
<ide>
<ide>
<ide> def jsonify(obj):
<ide> elif isinstance(obj, (tuple, list)):
<ide> return map(jsonify, obj)
<ide> elif isinstance(obj, dict):
<del> return dict([(k,jsonify(v)) for k,v in obj.iteritems()])
<add> return dict([(k, jsonify(v)) for k, v in obj.iteritems()])
<ide> # See "Date Time String Format" in the ECMA-262 specification.
<ide> elif isinstance(obj, datetime.datetime):
<ide> r = obj.isoformat()
<ide> def jsonify(obj):
<ide> elif isinstance(obj, datetime.timedelta):
<ide> return str(obj)
<ide> else:
<del> raise ValueError("Unsupported type: %s" % type(obj))
<add> raise ValueError("Unsupported type: {0}".format(type(obj)))
<ide>
<ide>
<ide> def gen_task_name(app, name, module_name):
<ide><path>celery/utils/compat.py
<ide> def write(self, data):
<ide> except ImportError: # pragma: no cover
<ide> from ordereddict import OrderedDict # noqa
<ide>
<del>############## itertools.zip_longest #######################################
<del>
<del>try:
<del> from itertools import izip_longest as zip_longest
<del>except ImportError: # pragma: no cover
<del> import itertools
<del>
<del> def zip_longest(*args, **kwds): # noqa
<del> fillvalue = kwds.get('fillvalue')
<del>
<del> def sentinel(counter=([fillvalue] * (len(args) - 1)).pop):
<del> yield counter() # yields the fillvalue, or raises IndexError
<del>
<del> fillers = itertools.repeat(fillvalue)
<del> iters = [itertools.chain(it, sentinel(), fillers)
<del> for it in args]
<del> try:
<del> for tup in itertools.izip(*iters):
<del> yield tup
<del> except IndexError:
<del> pass
<del>
<del>
<del>############## itertools.chain.from_iterable ################################
<del>from itertools import chain
<del>
<del>
<del>def _compat_chain_from_iterable(iterables): # pragma: no cover
<del> for it in iterables:
<del> for element in it:
<del> yield element
<del>
<del>try:
<del> chain_from_iterable = getattr(chain, 'from_iterable')
<del>except AttributeError: # pragma: no cover
<del> chain_from_iterable = _compat_chain_from_iterable
<del>
<del>
<del>############## logging.handlers.WatchedFileHandler ##########################
<del>import logging
<del>import os
<del>from stat import ST_DEV, ST_INO
<del>import platform as _platform
<del>
<del>if _platform.system() == 'Windows': # pragma: no cover
<del> #since windows doesn't go with WatchedFileHandler use FileHandler instead
<del> WatchedFileHandler = logging.FileHandler
<del>else:
<del> try:
<del> from logging.handlers import WatchedFileHandler
<del> except ImportError: # pragma: no cover
<del> class WatchedFileHandler(logging.FileHandler): # noqa
<del> """
<del> A handler for logging to a file, which watches the file
<del> to see if it has changed while in use. This can happen because of
<del> usage of programs such as newsyslog and logrotate which perform
<del> log file rotation. This handler, intended for use under Unix,
<del> watches the file to see if it has changed since the last emit.
<del> (A file has changed if its device or inode have changed.)
<del> If it has changed, the old file stream is closed, and the file
<del> opened to get a new stream.
<del>
<del> This handler is not appropriate for use under Windows, because
<del> under Windows open files cannot be moved or renamed - logging
<del> opens the files with exclusive locks - and so there is no need
<del> for such a handler. Furthermore, ST_INO is not supported under
<del> Windows; stat always returns zero for this value.
<del>
<del> This handler is based on a suggestion and patch by Chad J.
<del> Schroeder.
<del> """
<del> def __init__(self, *args, **kwargs):
<del> logging.FileHandler.__init__(self, *args, **kwargs)
<del>
<del> if not os.path.exists(self.baseFilename):
<del> self.dev, self.ino = -1, -1
<del> else:
<del> stat = os.stat(self.baseFilename)
<del> self.dev, self.ino = stat[ST_DEV], stat[ST_INO]
<del>
<del> def emit(self, record):
<del> """
<del> Emit a record.
<del>
<del> First check if the underlying file has changed, and if it
<del> has, close the old stream and reopen the file to get the
<del> current stream.
<del> """
<del> if not os.path.exists(self.baseFilename):
<del> stat = None
<del> changed = 1
<del> else:
<del> stat = os.stat(self.baseFilename)
<del> changed = ((stat[ST_DEV] != self.dev) or
<del> (stat[ST_INO] != self.ino))
<del> if changed and self.stream is not None:
<del> self.stream.flush()
<del> self.stream.close()
<del> self.stream = self._open()
<del> if stat is None:
<del> stat = os.stat(self.baseFilename)
<del> self.dev, self.ino = stat[ST_DEV], stat[ST_INO]
<del> logging.FileHandler.emit(self, record)
<del>
<del>
<ide> ############## format(int, ',d') ##########################
<ide>
<ide> if sys.version_info >= (2, 7): # pragma: no cover
<ide><path>celery/utils/functional.py
<ide> def __setitem__(self, key, value):
<ide> # remove least recently used key.
<ide> with self.mutex:
<ide> if self.limit and len(self.data) >= self.limit:
<del> self.data.pop(iter(self.data).next())
<add> self.data.pop(next(iter(self.data)))
<ide> self.data[key] = value
<ide>
<ide> def __iter__(self):
<ide><path>celery/utils/log.py
<ide> Logging utilities.
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import logging
<ide> import os
<ide> def format(self, record):
<ide> try:
<ide> record.msg = safe_str(str_t(color(record.msg)))
<ide> except Exception as exc:
<del> record.msg = '<Unrepresentable %r: %r>' % (
<add> record.msg = '<Unrepresentable {0!r}: {1!r}>'.format(
<ide> type(record.msg), exc)
<ide> record.exc_info = True
<ide>
<ide> def handleError(self, record):
<ide> def write(self, data):
<ide> """Write message to logging object."""
<ide> if in_sighandler:
<del> return sys.__stderr__.write(safe_str(data))
<add> print(safe_str(data), file=sys.__stderr__)
<ide> if getattr(self._thread, 'recurse_protection', False):
<ide> # Logger is logging back to this file, so stop recursing.
<ide> return
<ide> class SigSafeLogger(OldLoggerClass):
<ide>
<ide> def log(self, *args, **kwargs):
<ide> if in_sighandler:
<del> sys.__stderr__.write('CANNOT LOG IN SIGHANDLER')
<add> print('CANNOT LOG IN SIGHANDLER', # noqa
<add> file=sys.__stderr__)
<ide> return
<ide> return OldLoggerClass.log(self, *args, **kwargs)
<ide> logging.setLoggerClass(SigSafeLogger)
<ide><path>celery/utils/mail.py
<ide> """
<ide> from __future__ import absolute_import
<ide>
<del>import sys
<ide> import smtplib
<ide> import traceback
<ide> import warnings
<ide> from .functional import maybe_list
<ide> from .imports import symbol_by_name
<ide>
<del>supports_timeout = sys.version_info >= (2, 6)
<del>
<ide>
<ide> class SendmailWarning(UserWarning):
<ide> """Problem happened while sending the email message."""
<ide> def __init__(self, to=None, sender=None, subject=None, body=None,
<ide> self.charset = charset
<ide>
<ide> def __repr__(self):
<del> return '<Email: To:%r Subject:%r>' % (self.to, self.subject)
<add> return '<Email: To:{0.to!r} Subject:{0.subject!r}>'.format(self)
<ide>
<ide> def __str__(self):
<ide> msg = MIMEText(self.body, 'plain', self.charset)
<ide> def __str__(self):
<ide>
<ide>
<ide> class Mailer(object):
<del> supports_timeout = supports_timeout
<ide>
<ide> def __init__(self, host='localhost', port=0, user=None, password=None,
<ide> timeout=2, use_ssl=False, use_tls=False):
<ide> def __init__(self, host='localhost', port=0, user=None, password=None,
<ide> self.use_ssl = use_ssl
<ide> self.use_tls = use_tls
<ide>
<del> def send(self, message, fail_silently=False):
<add> def send(self, message, fail_silently=False, **kwargs):
<ide> try:
<del> if self.supports_timeout:
<del> self._send(message, timeout=self.timeout)
<del> else:
<del> import socket
<del> old_timeout = socket.getdefaulttimeout()
<del> socket.setdefaulttimeout(self.timeout)
<del> try:
<del> self._send(message)
<del> finally:
<del> socket.setdefaulttimeout(old_timeout)
<add> self._send(message, **kwargs)
<ide> except Exception as exc:
<ide> if not fail_silently:
<ide> raise
<ide> warnings.warn(SendmailWarning(
<del> 'Mail could not be sent: %r %r\n%r' % (
<add> 'Mail could not be sent: {0!r} {1!r}\n{2!r}'.format(
<ide> exc, {'To': ', '.join(message.to),
<ide> 'Subject': message.subject},
<ide> traceback.format_stack())))
<ide>
<ide> def _send(self, message, **kwargs):
<ide> Client = smtplib.SMTP_SSL if self.use_ssl else smtplib.SMTP
<del> client = Client(self.host, self.port, **kwargs)
<add> client = Client(self.host, self.port, timeout=self.timeout, **kwargs)
<ide>
<ide> if self.use_tls:
<ide> client.ehlo()
<ide> class ErrorMail(object):
<ide>
<ide> #: Format string used to generate error email subjects.
<ide> subject = """\
<del> [celery@%(hostname)s] Error: Task %(name)s (%(id)s): %(exc)s
<add> [celery@{hostname}] Error: Task {name} ({id}): {exc!r}
<ide> """
<ide>
<ide> #: Format string used to generate error email content.
<ide> body = """
<del>Task %%(name)s with id %%(id)s raised exception:\n%%(exc)r
<add>Task {{name}} with id {{id}} raised exception:\n{{exc!r}}
<ide>
<ide>
<del>Task was called with args: %%(args)s kwargs: %%(kwargs)s.
<add>Task was called with args: {{args}} kwargs: {{kwargs}}.
<ide>
<ide> The contents of the full traceback was:
<ide>
<del>%%(traceback)s
<add>{{traceback}}
<ide>
<del>%(EMAIL_SIGNATURE_SEP)s
<add>{EMAIL_SIGNATURE_SEP}
<ide> Just to let you know,
<del>py-celery at %%(hostname)s.
<del>""" % {'EMAIL_SIGNATURE_SEP': EMAIL_SIGNATURE_SEP}
<add>py-celery at {{hostname}}.
<add>""".format(EMAIL_SIGNATURE_SEP=EMAIL_SIGNATURE_SEP)
<ide>
<ide> error_whitelist = None
<ide>
<ide> def should_send(self, context, exc):
<ide> return not self.error_whitelist or isinstance(exc, allow_classes)
<ide>
<ide> def format_subject(self, context):
<del> return self.subject.strip() % context
<add> return self.subject.strip().format(**context)
<ide>
<ide> def format_body(self, context):
<del> return self.body.strip() % context
<add> return self.body.strip().format(**context)
<ide>
<ide> def send(self, context, exc, fail_silently=True):
<ide> if self.should_send(context, exc):
<ide><path>celery/utils/serialization.py
<ide> from __future__ import absolute_import
<ide>
<ide> import inspect
<del>import sys
<del>import types
<ide>
<ide> try:
<ide> import cPickle as pickle
<ide> except ImportError:
<del> import pickle
<add> import pickle # noqa
<ide>
<ide> from .encoding import safe_repr
<ide>
<ide><path>celery/utils/threads.py
<ide> Threading utilities.
<ide>
<ide> """
<del>from __future__ import absolute_import
<add>from __future__ import absolute_import, print_function
<ide>
<ide> import os
<ide> import sys
<ide> def body(self):
<ide> raise NotImplementedError('subclass responsibility')
<ide>
<ide> def on_crash(self, msg, *fmt, **kwargs):
<del> sys.stderr.write((msg + '\n') % fmt)
<add> print(msg % fmt, file=sys.stderr)
<ide> exc_info = sys.exc_info()
<ide> try:
<ide> traceback.print_exception(exc_info[0], exc_info[1], exc_info[2],
<ide><path>celery/utils/timer2.py
<ide> def cancel(self):
<ide> self.tref.cancelled = True
<ide>
<ide> def __repr__(self):
<del> return '<TimerEntry: %s(*%r, **%r)' % (
<add> return '<TimerEntry: {0}(*{1!r}, **{2!r})'.format(
<ide> self.fun.__name__, self.args, self.kwargs)
<ide>
<ide> if sys.version_info[0] == 3: # pragma: no cover
<ide> def __init__(self, schedule=None, on_error=None, on_tick=None,
<ide> self._is_stopped = Event()
<ide> self.mutex = Lock()
<ide> self.not_empty = Condition(self.mutex)
<del> self.setDaemon(True)
<del> self.setName('Timer-%s' % (self._timer_count(), ))
<add> self.daemon = True
<add> self.name = 'Timer-{0}'.format(self._timer_count())
<ide>
<ide> def _next_entry(self):
<ide> with self.not_empty:
<del> delay, entry = self.scheduler.next()
<add> delay, entry = next(self.scheduler)
<ide> if entry is None:
<ide> if delay is None:
<ide> self.not_empty.wait(1.0)
<ide><path>celery/utils/timeutils.py
<ide>
<ide> HAVE_TIMEDELTA_TOTAL_SECONDS = hasattr(timedelta, 'total_seconds')
<ide>
<del>TIME_UNITS = (('day', 60 * 60 * 24.0, lambda n: '%.2f' % n),
<del> ('hour', 60 * 60.0, lambda n: '%.2f' % n),
<del> ('minute', 60.0, lambda n: '%.2f' % n),
<del> ('second', 1.0, lambda n: '%.2f' % n))
<add>TIME_UNITS = (('day', 60 * 60 * 24.0, lambda n: format(n, '.2f')),
<add> ('hour', 60 * 60.0, lambda n: format(n, '.2f')),
<add> ('minute', 60.0, lambda n: format(n, '.2f')),
<add> ('second', 1.0, lambda n: format(n, '.2f')))
<ide>
<ide>
<ide> class _Zone(object):
<ide> def humanize_seconds(secs, prefix=''):
<ide> for unit, divider, formatter in TIME_UNITS:
<ide> if secs >= divider:
<ide> w = secs / divider
<del> return '%s%s %s' % (prefix, formatter(w),
<del> pluralize(w, unit))
<add> return '{0}{1} {2}'.format(prefix, formatter(w),
<add> pluralize(w, unit))
<ide> return 'now'
<ide>
<ide>
<ide><path>celery/worker/buckets.py
<ide> import threading
<ide>
<ide> from collections import deque
<add>from itertools import chain, izip_longest
<ide> from time import time, sleep
<ide> from Queue import Queue, Empty
<ide>
<ide> from kombu.utils.limits import TokenBucket
<ide>
<ide> from celery.utils import timeutils
<del>from celery.utils.compat import zip_longest, chain_from_iterable
<ide>
<ide>
<ide> class RateLimitExceeded(Exception):
<ide> def items(self):
<ide> """Flattens the data in all of the buckets into a single list."""
<ide> # for queues with contents [(1, 2), (3, 4), (5, 6), (7, 8)]
<ide> # zips and flattens to [1, 3, 5, 7, 2, 4, 6, 8]
<del> return filter(None, chain_from_iterable(zip_longest(*[bucket.items
<add> return filter(None, chain.from_iterable(izip_longest(*[bucket.items
<ide> for bucket in self.buckets.values()])))
<ide>
<ide>
<ide><path>celery/worker/consumer.py
<ide> """
<ide>
<ide> MESSAGE_REPORT_FMT = """\
<del>body: %s {content_type:%s content_encoding:%s delivery_info:%s}\
<add>body: {0} {{content_type:{1} content_encoding:{2} delivery_info:{3}}}\
<ide> """
<ide>
<ide>
<ide> def apply_eta_task(self, task):
<ide> self.qos.decrement_eventually()
<ide>
<ide> def _message_report(self, body, message):
<del> return MESSAGE_REPORT_FMT % (dump_body(message, body),
<del> safe_repr(message.content_type),
<del> safe_repr(message.content_encoding),
<del> safe_repr(message.delivery_info))
<add> return MESSAGE_REPORT_FMT.format(dump_body(message, body),
<add> safe_repr(message.content_type),
<add> safe_repr(message.content_encoding),
<add> safe_repr(message.delivery_info))
<ide>
<ide> def handle_unknown_message(self, body, message):
<ide> warn(UNKNOWN_FORMAT, self._message_report(body, message))
<ide><path>celery/worker/control.py
<ide> def revoke(panel, task_id, terminate=False, signal=None, **kwargs):
<ide> signum = _signals.signum(signal or 'TERM')
<ide> for request in state.active_requests:
<ide> if request.id == task_id:
<del> action = 'terminated (%s)' % (signum, )
<add> action = 'terminated ({0})'.format(signum)
<ide> request.terminate(panel.consumer.pool, signal=signum)
<ide> break
<ide>
<ide> logger.info('Task %s %s.', task_id, action)
<del> return {'ok': 'task %s %s' % (task_id, action)}
<add> return {'ok': 'task {0} {1}'.format(task_id, action)}
<ide>
<ide>
<ide> @Panel.register
<ide> def rate_limit(panel, task_name, rate_limit, **kwargs):
<ide> try:
<ide> timeutils.rate(rate_limit)
<ide> except ValueError as exc:
<del> return {'error': 'Invalid rate limit string: %s' % exc}
<add> return {'error': 'Invalid rate limit string: {!r}'.format(exc)}
<ide>
<ide> try:
<ide> panel.app.tasks[task_name].rate_limit = rate_limit
<ide> def dump_schedule(panel, safe=False, **kwargs):
<ide> logger.debug('--Empty schedule--')
<ide> return []
<ide>
<del> formatitem = lambda (i, item): '%s. %s pri%s %r' % (i,
<add> formatitem = lambda (i, item): '{0}. {1} pri{2} {3!r}'.format(i,
<ide> datetime.utcfromtimestamp(item['eta']),
<del> item['priority'],
<del> item['item'])
<add> item['priority'], item['item'])
<ide> info = map(formatitem, enumerate(schedule.info()))
<ide> logger.debug('* Dump of current schedule:\n%s', '\n'.join(info))
<ide> scheduled_tasks = []
<ide> def _extract_info(task):
<ide> info = map('='.join, fields.items())
<ide> if not info:
<ide> return task.name
<del> return '%s [%s]' % (task.name, ' '.join(info))
<add> return '{0} [{1}]'.format(task.name, ' '.join(info))
<ide>
<ide> info = map(_extract_info, (tasks[task]
<ide> for task in sorted(tasks.keys())))
<ide> def autoscale(panel, max=None, min=None):
<ide> autoscaler = panel.consumer.controller.autoscaler
<ide> if autoscaler:
<ide> max_, min_ = autoscaler.update(max, min)
<del> return {'ok': 'autoscale now min=%r max=%r' % (max_, min_)}
<add> return {'ok': 'autoscale now min={0} max={1}'.format(max_, min_)}
<ide> raise ValueError('Autoscale not enabled')
<ide>
<ide>
<ide> def add_consumer(panel, queue, exchange=None, exchange_type=None,
<ide> routing_key=None, **options):
<ide> panel.consumer.add_task_queue(queue, exchange, exchange_type,
<ide> routing_key, **options)
<del> return {'ok': 'add consumer %r' % (queue, )}
<add> return {'ok': 'add consumer {0}'.format(queue)}
<ide>
<ide>
<ide> @Panel.register
<ide> def cancel_consumer(panel, queue=None, **_):
<ide> panel.consumer.cancel_task_queue(queue)
<del> return {'ok': 'no longer consuming from %s' % (queue, )}
<add> return {'ok': 'no longer consuming from {0}'.format(queue)}
<ide>
<ide>
<ide> @Panel.register
<ide><path>celery/worker/hub.py
<ide> def fire_timers(self, min_delay=1, max_delay=10, max_timers=10):
<ide> delay = None
<ide> if self.timer._queue:
<ide> for i in xrange(max_timers):
<del> delay, entry = self.scheduler.next()
<add> delay, entry = next(self.scheduler)
<ide> if entry is None:
<ide> break
<ide> self.timer.apply_entry(entry)
<ide><path>celery/worker/job.py
<ide> def info(self, safe=False):
<ide> 'worker_pid': self.worker_pid}
<ide>
<ide> def __str__(self):
<del> return '%s[%s]%s%s' % (
<del> self.name, self.id,
<del> ' eta:[%s]' % (self.eta, ) if self.eta else '',
<del> ' expires:[%s]' % (self.expires, ) if self.expires else '')
<add> return '{0.name}[{0.id}]{1}{2}'.format(self,
<add> ' eta:[{0}]'.format(self.eta) if self.eta else '',
<add> ' expires:[{0}]'.format(self.expires) if self.expires else '')
<ide> shortinfo = __str__
<ide>
<ide> def __repr__(self):
<del> return '<%s %s: %s>' % (type(self).__name__, self.id,
<del> reprcall(self.name, self.args, self.kwargs))
<add> return '<{0} {1}: {2}>'.format(type(self).__name__, self.id,
<add> reprcall(self.name, self.args, self.kwargs))
<ide>
<ide> @property
<ide> def tzlocal(self):
<ide> def store_errors(self):
<ide> return (not self.task.ignore_result
<ide> or self.task.store_errors_even_if_ignored)
<ide>
<del> def _compat_get_task_id(self):
<add> @property
<add> def task_id(self):
<add> # XXX compat
<ide> return self.id
<ide>
<del> def _compat_set_task_id(self, value):
<add> @task_id.setter # noqa
<add> def task_id(self, value):
<ide> self.id = value
<del> task_id = property(_compat_get_task_id, _compat_set_task_id)
<ide>
<del> def _compat_get_task_name(self):
<add> @property
<add> def task_name(self):
<add> # XXX compat
<ide> return self.name
<ide>
<del> def _compat_set_task_name(self, value):
<add> @task_name.setter # noqa
<add> def task_name(self, value):
<ide> self.name = value
<del> task_name = property(_compat_get_task_name, _compat_set_task_name)
<ide>
<ide>
<ide> class TaskRequest(Request):
<ide><path>celery/worker/state.py
<ide> def task_ready(request):
<ide> @atexit.register
<ide> def on_shutdown():
<ide> if bench_first is not None and bench_last is not None:
<del> print('- Time spent in benchmark: %r' % (
<del> bench_last - bench_first))
<del> print('- Avg: %s' % (sum(bench_sample) / len(bench_sample)))
<add> print('- Time spent in benchmark: {0!r}'.format(
<add> bench_last - bench_first))
<add> print('- Avg: {0}'.format(
<add> sum(bench_sample) / len(bench_sample)))
<ide> memdump()
<ide>
<ide> def task_reserved(request): # noqa
<ide> def task_ready(request): # noqa
<ide> now = time()
<ide> diff = now - bench_start
<ide> print('- Time spent processing %s tasks (since first '
<del> 'task received): ~%.4fs\n' % (bench_every, diff))
<add> 'task received): ~{0:.4f}s\n'.format(bench_every, diff))
<ide> sys.stdout.flush()
<ide> bench_start = bench_last = now
<ide> bench_sample.append(diff)
| 59
|
Text
|
Text
|
add missing `cookies_serializer` config default
|
c2d0b1a030d0ddb08c8b60389f113a7fbef35793
|
<ide><path>guides/source/configuring.md
<ide> Accepts a string for the HTML tag used to wrap attachments. Defaults to `"action
<ide> - `config.active_support.use_rfc4122_namespaced_uuids`: `true`
<ide> - `config.active_support.disable_to_s_conversion`: `true`
<ide> - `config.action_dispatch.return_only_request_media_type_on_content_type`: `false`
<add>- `config.action_dispatch.cookies_serializer`: `:json`
<ide> - `config.action_mailer.smtp_timeout`: `5`
<ide> - `config.active_storage.video_preview_arguments`: `"-vf 'select=eq(n\\,0)+eq(key\\,1)+gt(scene\\,0.015),loop=loop=-1:size=2,trim=start_frame=1' -frames:v 1 -f image2"`
<ide> - `config.active_storage.multiple_file_field_include_hidden`: `true`
| 1
|
Python
|
Python
|
add missing newline at the end of test file
|
6e4bdb55969171c87296aba9711dbc77f8a1e366
|
<ide><path>rest_framework/tests/test_files.py
<ide> def test_validation_with_no_data(self):
<ide> uploaded_file = UploadedFile(file=file, created=now)
<ide>
<ide> serializer = UploadedFileSerializer(files={'file': file})
<del> self.assertFalse(serializer.is_valid())
<ide>\ No newline at end of file
<add> self.assertFalse(serializer.is_valid())
| 1
|
PHP
|
PHP
|
create a test for testcomponent class
|
ff9d29e455829bd404680b4f31be33b7dcbbaf23
|
<ide><path>tests/Foundation/Testing/Concerns/InteractsWithViewsTest.php
<ide> namespace Illuminate\Tests\Foundation\Testing\Concerns;
<ide>
<ide> use Illuminate\Foundation\Testing\Concerns\InteractsWithViews;
<add>use Illuminate\View\Component;
<ide> use Orchestra\Testbench\TestCase;
<ide>
<ide> class InteractsWithViewsTest extends TestCase
<ide> public function testBladeCorrectlyRendersString()
<ide>
<ide> $this->assertEquals('test ', $string);
<ide> }
<add>
<add> public function testComponentCanAccessPublicProperties()
<add> {
<add> $exampleComponent = new class extends Component
<add> {
<add> public $foo = 'bar';
<add> public function render()
<add> {
<add> return '';
<add> }
<add> };
<add> $component = $this->component(get_class($exampleComponent));
<add>
<add> $this->assertEquals('bar', $component->foo);
<add> }
<ide> }
| 1
|
Javascript
|
Javascript
|
remove obsolete comment from dgram test
|
89f8ef2bf44ef958b9cd6811bd0110e8c9940cb8
|
<ide><path>test/parallel/test-dgram-oob-buffer.js
<ide> socket.send(buf, 3, 1, common.PORT, '127.0.0.1', ok);
<ide> // Since length of zero means nothing, don't error despite OOB.
<ide> socket.send(buf, 4, 0, common.PORT, '127.0.0.1', ok);
<ide>
<del>socket.close(); // FIXME should not be necessary
<add>socket.close();
| 1
|
PHP
|
PHP
|
fix edge case in assertjsonfragment
|
932cccb5c511d9e36a5e27217232d2626949737a
|
<ide><path>src/Illuminate/Foundation/Testing/TestResponse.php
<ide> protected function jsonSearchStrings($key, $value)
<ide> $needle = substr(json_encode([$key => $value]), 1, -1);
<ide>
<ide> return [
<add> $needle.':',
<ide> $needle.']',
<ide> $needle.'}',
<ide> $needle.',',
<ide><path>tests/Foundation/FoundationTestResponseTest.php
<ide> public function testAssertJsonFragment()
<ide>
<ide> $response = TestResponse::fromBaseResponse(new Response(new JsonSerializableMixedResourcesStub));
<ide>
<add> $response->assertJsonFragment(['foobar']);
<add>
<ide> $response->assertJsonFragment(['foo' => 'bar']);
<ide>
<ide> $response->assertJsonFragment(['foobar_foo' => 'foo']);
| 2
|
Javascript
|
Javascript
|
fix prop overrides of touchablewithoutfeedback
|
68825f9ca5a6c8c70390e8499d9663c5be475639
|
<ide><path>Libraries/Components/Touchable/TouchableWithoutFeedback.js
<ide> type FocusEvent = TargetEvent;
<ide>
<ide> const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
<ide>
<add>const OVERRIDE_PROPS = [
<add> 'accessibilityComponentType',
<add> 'accessibilityLabel',
<add> 'accessibilityHint',
<add> 'accessibilityIgnoresInvertColors',
<add> 'accessibilityRole',
<add> 'accessibilityStates',
<add> 'accessibilityTraits',
<add> 'hitSlop',
<add> 'nativeID',
<add> 'onBlur',
<add> 'onFocus',
<add> 'onLayout',
<add> 'testID',
<add>];
<add>
<ide> export type Props = $ReadOnly<{|
<ide> accessible?: ?boolean,
<ide> accessibilityComponentType?: ?AccessibilityComponentType,
<ide> const TouchableWithoutFeedback = ((createReactClass({
<ide> accessibilityComponentType: PropTypes.oneOf(
<ide> DeprecatedAccessibilityComponentTypes,
<ide> ),
<add> accessibilityIgnoresInvertColors: PropTypes.bool,
<ide> accessibilityRole: PropTypes.oneOf(DeprecatedAccessibilityRoles),
<ide> accessibilityStates: PropTypes.arrayOf(
<ide> PropTypes.oneOf(DeprecatedAccessibilityStates),
<ide> const TouchableWithoutFeedback = ((createReactClass({
<ide> Touchable.renderDebugView({color: 'red', hitSlop: this.props.hitSlop}),
<ide> );
<ide> }
<add>
<add> const overrides = {};
<add> for (const prop of OVERRIDE_PROPS) {
<add> if (this.props[prop] !== undefined) {
<add> overrides[prop] = this.props[prop];
<add> }
<add> }
<add>
<ide> return (React: any).cloneElement(child, {
<add> ...overrides,
<ide> accessible: this.props.accessible !== false,
<del> accessibilityLabel: this.props.accessibilityLabel,
<del> accessibilityHint: this.props.accessibilityHint,
<del> accessibilityComponentType: this.props.accessibilityComponentType,
<del> accessibilityRole: this.props.accessibilityRole,
<del> accessibilityStates: this.props.accessibilityStates,
<del> accessibilityTraits: this.props.accessibilityTraits,
<del> nativeID: this.props.nativeID,
<del> testID: this.props.testID,
<del> onLayout: this.props.onLayout,
<del> hitSlop: this.props.hitSlop,
<ide> onStartShouldSetResponder: this.touchableHandleStartShouldSetResponder,
<ide> onResponderTerminationRequest: this
<ide> .touchableHandleResponderTerminationRequest,
| 1
|
PHP
|
PHP
|
implement mail fake queue method
|
1b4762d2f034cb0cad0776cb31535815260639b5
|
<ide><path>src/Illuminate/Support/Testing/Fakes/MailFake.php
<ide>
<ide> namespace Illuminate\Support\Testing\Fakes;
<ide>
<del>use Illuminate\Contracts\Mail\Mailer;
<add>use InvalidArgumentException;
<ide> use Illuminate\Contracts\Mail\Mailable;
<add>use Illuminate\Contracts\Mail\Mailer;
<add>use Illuminate\Mail\MailableContract;
<ide> use PHPUnit\Framework\Assert as PHPUnit;
<ide>
<ide> class MailFake implements Mailer
<ide> class MailFake implements Mailer
<ide> */
<ide> protected $mailables = [];
<ide>
<add> /**
<add> * All of the mailables that have been queued;
<add> * @var array
<add> */
<add> protected $queuedMailables = [];
<add>
<ide> /**
<ide> * Assert if a mailable was sent based on a truth-test callback.
<ide> *
<ide> public function assertNothingSent()
<ide> PHPUnit::assertEmpty($this->mailables, 'Mailables were sent unexpectedly.');
<ide> }
<ide>
<add> /**
<add> * Assert if a mailable was queued based on a truth-test callback.
<add> *
<add> * @param string $mailable
<add> * @param callable|null $callback
<add> * @return void
<add> */
<add> public function assertQueued($mailable, $callback = null)
<add> {
<add> PHPUnit::assertTrue(
<add> $this->queued($mailable, $callback)->count() > 0,
<add> "The expected [{$mailable}] mailable was not queued."
<add> );
<add> }
<add>
<add> /**
<add> * Determine if a mailable was not queued based on a truth-test callback.
<add> *
<add> * @param string $mailable
<add> * @param callable|null $callback
<add> * @return void
<add> */
<add> public function assertNotSent($mailable, $callback = null)
<add> {
<add> PHPUnit::assertTrue(
<add> $this->queued($mailable, $callback)->count() === 0,
<add> "The unexpected [{$mailable}] mailable was queued."
<add> );
<add> }
<add>
<add> /**
<add> * Assert that no mailables were queued.
<add> *
<add> * @return void
<add> */
<add> public function assertNothingQueued()
<add> {
<add> PHPUnit::assertEmpty($this->mailables, 'Mailables were queued unexpectedly.');
<add> }
<add>
<ide> /**
<ide> * Get all of the mailables matching a truth-test callback.
<ide> *
<ide> public function hasSent($mailable)
<ide> return $this->mailablesOf($mailable)->count() > 0;
<ide> }
<ide>
<add> /**
<add> * Get all of the queued mailables matching a truth-test callback.
<add> *
<add> * @param string $mailable
<add> * @param callable|null $callback
<add> * @return \Illuminate\Support\Collection
<add> */
<add> public function queued($mailable, $callback = null)
<add> {
<add> if (! $this->hasQueued($mailable)) {
<add> return collect();
<add> }
<add>
<add> $callback = $callback ?: function () {
<add> return true;
<add> };
<add>
<add> return $this->mailablesOf($mailable, true)->filter(function ($mailable) use ($callback) {
<add> return $callback($mailable);
<add> });
<add> }
<add>
<add> /**
<add> * Determine if the given mailable has been queued.
<add> *
<add> * @param string $mailable
<add> * @return bool
<add> */
<add> public function hasQueued($mailable)
<add> {
<add> return $this->mailablesOf($mailable, true)->count() > 0;
<add> }
<add>
<ide> /**
<ide> * Get all of the mailed mailables for a given type.
<ide> *
<ide> * @param string $type
<ide> * @return \Illuminate\Support\Collection
<ide> */
<del> protected function mailablesOf($type)
<add> protected function mailablesOf($type, $queued = false)
<ide> {
<del> return collect($this->mailables)->filter(function ($mailable) use ($type) {
<add> $mailables = $queued ? $this->queuedMailables : $this->mailables;
<add>
<add> return collect($mailables)->filter(function ($mailable) use ($type) {
<ide> return $mailable instanceof $type;
<ide> });
<ide> }
<ide> public function send($view, array $data = [], $callback = null)
<ide> */
<ide> public function queue($view, array $data = [], $callback = null, $queue = null)
<ide> {
<del> $this->send($view);
<add> if (! $view instanceof MailableContract) {
<add> throw new InvalidArgumentException('Only mailables may be queued.');
<add> }
<add>
<add> $this->queuedMailables[] = $view;
<ide> }
<ide>
<ide> /**
| 1
|
Python
|
Python
|
improve rackspace driver documentation
|
33818e1c2c4bfccfb26ec083442572beda20c644
|
<ide><path>libcloud/drivers/rackspace.py
<ide> def request(self, action, params={}, data='', headers={}, method='GET'):
<ide>
<ide>
<ide> class RackspaceNodeDriver(NodeDriver):
<del> """Rackspace node driver.
<add> """
<add> Rackspace node driver.
<ide>
<del> Extra node attributes:
<del> password: root password, available after create.
<del> hostId: represents the host your cloud server runs on
<del> imageId: id of image
<del> flavorId: id of flavor
<add> Extra node attributes:
<add> - password: root password, available after create.
<add> - hostId: represents the host your cloud server runs on
<add> - imageId: id of image
<add> - flavorId: id of flavor
<ide> """
<ide> connectionCls = RackspaceConnection
<ide> type = Provider.RACKSPACE
<ide> def list_images(self):
<ide> return self.to_images(self.connection.request('/images/detail').object)
<ide>
<ide> def create_node(self, **kwargs):
<add> """Create a new rackspace node
<add>
<add> See L{NodeDriver.create_node} for more keyword args.
<add> @keyword metadata: Key/Value metadata to associate with a node
<add> @type metadata: C{dict}
<add>
<add> @keyword file: File Path => File contents to create on the node
<add> @type file: C{dict}
<add> """
<ide> name = kwargs['name']
<ide> image = kwargs['image']
<ide> size = kwargs['size']
| 1
|
Javascript
|
Javascript
|
update ios rntester header to utilize safeareaview
|
ad4b124aa117483b4a0ec9dfa145b8e9a17f06c6
|
<ide><path>RNTester/js/RNTesterApp.ios.js
<ide> const {
<ide> StyleSheet,
<ide> Text,
<ide> View,
<add> SafeAreaView
<ide> } = ReactNative;
<ide>
<ide> import type { RNTesterExample } from './RNTesterList.ios';
<ide> type Props = {
<ide> const APP_STATE_KEY = 'RNTesterAppState.v2';
<ide>
<ide> const Header = ({ onBack, title }: { onBack?: () => mixed, title: string }) => (
<del> <View style={styles.header}>
<del> <View style={styles.headerCenter}>
<del> <Text style={styles.title}>{title}</Text>
<add> <SafeAreaView style={styles.headerContainer}>
<add> <View style={styles.header}>
<add> <View style={styles.headerCenter}>
<add> <Text style={styles.title}>{title}</Text>
<add> </View>
<add> {onBack && <View style={styles.headerLeft}>
<add> <Button title="Back" onPress={onBack} />
<add> </View>}
<ide> </View>
<del> {onBack && <View style={styles.headerLeft}>
<del> <Button title="Back" onPress={onBack} />
<del> </View>}
<del> </View>
<add> </SafeAreaView>
<ide> );
<ide>
<ide> class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
<ide> class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
<ide> }
<ide>
<ide> const styles = StyleSheet.create({
<del> header: {
<del> height: 60,
<add> headerContainer: {
<ide> borderBottomWidth: StyleSheet.hairlineWidth,
<ide> borderBottomColor: '#96969A',
<ide> backgroundColor: '#F5F5F6',
<del> flexDirection: 'row',
<del> paddingTop: 20,
<add> },
<add> header: {
<add> height: 40,
<add> flexDirection: 'row'
<ide> },
<ide> headerLeft: {
<ide> },
<ide> headerCenter: {
<ide> flex: 1,
<ide> position: 'absolute',
<del> top: 27,
<add> top: 7,
<ide> left: 0,
<ide> right: 0,
<ide> },
| 1
|
Ruby
|
Ruby
|
move legacy functions to compat
|
c70bb474e3d8ae447042e2d24ed1d67e6071dc48
|
<ide><path>Library/Homebrew/compat.rb
<ide> require "compat/language/python"
<ide> require "compat/requirements/macos_requirement"
<ide> require "compat/formula"
<add>require "compat/os/mac" if OS.mac?
<ide><path>Library/Homebrew/compat/os/mac.rb
<add># frozen_string_literal: true
<add>
<add>module OS
<add> module Mac
<add> class << self
<add> module Compat
<add> def preferred_arch
<add> # odeprecated "MacOS.preferred_arch", "Hardware::CPU.arch (or ideally let the compiler handle it)"
<add> if Hardware::CPU.is_64_bit?
<add> Hardware::CPU.arch_64_bit
<add> else
<add> Hardware::CPU.arch_32_bit
<add> end
<add> end
<add>
<add> def tcc_db
<add> # odeprecated "MacOS.tcc_db"
<add> @tcc_db ||= Pathname.new("/Library/Application Support/com.apple.TCC/TCC.db")
<add> end
<add>
<add> def pre_mavericks_accessibility_dotfile
<add> # odeprecated "MacOS.pre_mavericks_accessibility_dotfile"
<add> @pre_mavericks_accessibility_dotfile ||= Pathname.new("/private/var/db/.AccessibilityAPIEnabled")
<add> end
<add> end
<add>
<add> prepend Compat
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/os/mac.rb
<ide> def macports_or_fink
<ide> paths.uniq
<ide> end
<ide>
<del> def preferred_arch
<del> if Hardware::CPU.is_64_bit?
<del> Hardware::CPU.arch_64_bit
<del> else
<del> Hardware::CPU.arch_32_bit
<del> end
<del> end
<del>
<ide> def app_with_bundle_id(*ids)
<ide> path = mdfind(*ids)
<ide> .reject { |p| p.include?("/Backups.backupdb/") }
<ide> def pkgutil_info(id)
<ide> def mdfind_query(*ids)
<ide> ids.map! { |id| "kMDItemCFBundleIdentifier == #{id}" }.join(" || ")
<ide> end
<del>
<del> def tcc_db
<del> @tcc_db ||= Pathname.new("/Library/Application Support/com.apple.TCC/TCC.db")
<del> end
<del>
<del> def pre_mavericks_accessibility_dotfile
<del> @pre_mavericks_accessibility_dotfile ||= Pathname.new("/private/var/db/.AccessibilityAPIEnabled")
<del> end
<ide> end
<ide> end
| 3
|
Text
|
Text
|
fix incorrect net listen signature
|
647954d0a045c72fc6b22afcfd89daa72d81bab3
|
<ide><path>doc/api/net.md
<ide> Possible signatures:
<ide> * [`server.listen(options[, callback])`][`server.listen(options)`]
<ide> * [`server.listen(path[, backlog][, callback])`][`server.listen(path)`]
<ide> for [IPC][] servers
<del>* [`server.listen([[[port[, hostname[, backlog]]][, callback])`][`server.listen(port, host)`]
<add>* [`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port, host)`]
<ide> for TCP servers
<ide>
<ide> This function is asynchronous. When the server starts listening, the
<ide> added: v0.11.14
<ide> * Returns: {net.Server}
<ide>
<ide> If `port` is specified, it behaves the same as
<del>[`server.listen([[[port[, hostname[, backlog]]][, callback])`][`server.listen(port, host)`].
<add>[`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port, host)`].
<ide> Otherwise, if `path` is specified, it behaves the same as
<ide> [`server.listen(path[, backlog][, callback])`][`server.listen(path)`].
<ide> If none of them is specified, an error will be thrown.
<ide> added: v0.1.90
<ide>
<ide> Start a [IPC][] server listening for connections on the given `path`.
<ide>
<del>#### server.listen([port][, host][, backlog][, callback])
<add>#### server.listen([port[, host[, backlog]]][, callback])
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
| 1
|
Python
|
Python
|
fix bad merge
|
0487fb02618a81c9a1b1e7fd5a294eb337e6ba5b
|
<ide><path>numpy/random/tests/test_direct.py
<ide> assert_raises)
<ide> import pytest
<ide>
<del><<<<<<< HEAD
<ide> from numpy.random import (Generator, MT19937, PCG64, Philox, RandomState)
<del>=======
<del>from numpy.random import (Generator, MT19937, PCG64,
<del> Philox, Xoshiro256, Xoshiro512, RandomState,
<del> SeedSequence)
<del>>>>>>>> ENH: use SeedSequence to generate entropy for seeding
<ide> from numpy.random.common import interface
<ide>
<ide> try:
| 1
|
Python
|
Python
|
set data augmentation by default
|
4c1b6a4c812402ea8087da75f127f723ef070349
|
<ide><path>spacy/cli/train.py
<ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0,
<ide> batch_sizes = util.compounding(util.env_opt('batch_from', 1),
<ide> util.env_opt('batch_to', 64),
<ide> util.env_opt('batch_compound', 1.001))
<add> gold_preproc = util.env_opt('gold_preproc', False)
<add> noise_level = util.env_opt('noise_level', 0.25)
<ide>
<ide> if resume:
<ide> prints(output_path / 'model19.pickle', title="Resuming training")
<ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0,
<ide> i += 20
<ide> with tqdm.tqdm(total=n_train_words, leave=False) as pbar:
<ide> train_docs = corpus.train_docs(nlp, projectivize=True,
<del> gold_preproc=False, max_length=0)
<add> gold_preproc=gold_preproc,
<add> noise_level=noise_level,
<add> max_length=0)
<ide> losses = {}
<ide> for batch in minibatch(train_docs, size=batch_sizes):
<ide> docs, golds = zip(*batch)
<ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0,
<ide> scorer = nlp_loaded.evaluate(
<ide> corpus.dev_docs(
<ide> nlp_loaded,
<del> gold_preproc=False))
<add> gold_preproc=gold_preproc))
<ide> acc_loc =(output_path / ('model%d' % i) / 'accuracy.json')
<ide> with acc_loc.open('w') as file_:
<ide> file_.write(json_dumps(scorer.scores))
| 1
|
Python
|
Python
|
add missing parens
|
665f2786010a7a0743263544a496f28fcff26652
|
<ide><path>celery/pool.py
<ide> def add_worker(self):
<ide> self._pool.append(w)
<ide> self.logger.debug(
<ide> "DynamicPool: Started pool worker %s (PID: %s, Poolsize: %d)" %(
<del> w.name, w.pid, len(self._pool))
<add> w.name, w.pid, len(self._pool)))
<ide>
<ide> def grow(self, size=1):
<ide> """Add workers to the pool.
| 1
|
PHP
|
PHP
|
remove unnecessary loadfixtures()
|
52c2fad9ebb3c55009c1997923d768b86ba076cc
|
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> public function testBufferedStatementCollectionWrappingStatement()
<ide> !($this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlite),
<ide> 'Only required for SQLite driver which does not support buffered results natively'
<ide> );
<del> $this->loadFixtures('Things');
<add>
<ide> $statement = $this->connection->query('SELECT * FROM things LIMIT 3');
<ide>
<ide> $collection = new Collection($statement);
| 1
|
PHP
|
PHP
|
add beforefind event to orm\table
|
f72d2b2afc1bfbcfedf492216c6b68744a0398a6
|
<ide><path>lib/Cake/ORM/Table.php
<ide> */
<ide> namespace Cake\ORM;
<ide>
<add>use Cake\Event\Event;
<add>use Cake\Event\EventManager;
<ide> use Cake\Database\Schema\Table as Schema;
<ide> use Cake\ORM\Association\BelongsTo;
<ide> use Cake\ORM\Association\BelongsToMany;
<ide> * instances of this class can be created for the same database table with
<ide> * different aliases, this allows you to address your database structure in a
<ide> * richer and more expressive way.
<add> *
<add> * ### Callbacks/events
<add> *
<add> * Table objects provide a few callbacks/events you can hook into to augment/replace
<add> * find operations. Each event uses the standard Event subsystem in CakePHP
<add> *
<add> * - beforeFind($event, $query, $options) - Fired before each find operation. By stopping
<add> * the event and supplying a return value you can bypass the find operation entirely. Any
<add> * changes done to the $query instance will be retained for the rest of the find.
<add> *
<ide> */
<ide> class Table {
<ide>
<ide> class Table {
<ide> */
<ide> protected $_associations = [];
<ide>
<add>/**
<add> * EventManager for this model.
<add> *
<add> * All model/behavior callbacks will be dispatched on this manager.
<add> *
<add> * @var Cake\Event\EventManager
<add> */
<add> protected $_eventManager;
<add>
<ide> /**
<ide> * Initializes a new instance
<ide> *
<ide> class Table {
<ide> * @param array config Lsit of options for this table
<ide> * @return void
<ide> */
<del> public function __construct($config = array()) {
<add> public function __construct($config = []) {
<ide> if (!empty($config['table'])) {
<ide> $this->table($config['table']);
<ide> }
<ide> public function __construct($config = array()) {
<ide> if (!empty($config['schema'])) {
<ide> $this->schema($config['schema']);
<ide> }
<add> $eventManager = null;
<add> if (!empty($config['eventManager'])) {
<add> $eventManager = $config['eventManager'];
<add> }
<add> $this->_eventManager = $eventManager ?: new EventManager();
<ide> }
<ide>
<ide> /**
<ide> public function connection($conn = null) {
<ide> return $this->_connection = $conn;
<ide> }
<ide>
<add>/**
<add> * Get the event manager for this Table.
<add> *
<add> * @return Cake\Event\EventManager
<add> */
<add> public function getEventManager() {
<add> return $this->_eventManager;
<add> }
<add>
<ide> /**
<ide> * Returns the schema table object describing this table's properties.
<ide> *
<ide> public function belongsToMany($associated, array $options = []) {
<ide> public function find($type, $options = []) {
<ide> $query = $this->_buildQuery();
<ide> $query->select();
<add>
<add> $event = new Event('Model.beforeFind', $this, [$query, $options]);
<add> $this->_eventManager->dispatch($event);
<add> if ($event->isStopped()) {
<add> return $event->result;
<add> }
<ide> return $this->{'find' . ucfirst($type)}($query, $options);
<ide> }
<ide>
<ide><path>lib/Cake/Test/TestCase/ORM/TableTest.php
<ide> public function testFindAllConditionAutoTypes() {
<ide> $this->assertSame($expected, $query->toArray());
<ide> }
<ide>
<add>/**
<add> * Test that beforeFind events can mutate the query.
<add> *
<add> * @return void
<add> */
<add> public function testFindBeforeFindEventMutateQuery() {
<add> $table = new Table(['table' => 'users', 'connection' => $this->connection]);
<add> $table->getEventManager()->attach(function ($event, $query, $options) {
<add> $query->limit(1);
<add> }, 'Model.beforeFind');
<add>
<add> $result = $table->find('all')->execute();
<add> $this->assertCount(1, $result, 'Should only have 1 record, limit 1 applied.');
<add> }
<add>
<add>/**
<add> * Test that beforeFind events are fired and can stop the find and
<add> * return custom results.
<add> *
<add> * @return void
<add> */
<add> public function testFindBeforeFindEventOverrideReturn() {
<add> $table = new Table(['table' => 'users', 'connection' => $this->connection]);
<add> $table->getEventManager()->attach(function ($event, $query, $options) {
<add> $event->stopPropagation();
<add> return 'Something else';
<add> }, 'Model.beforeFind');
<add>
<add> $result = $table->find('all');
<add> $this->assertEquals('Something else', $result);
<add> }
<add>
<ide> /**
<ide> * Tests that belongsTo() creates and configures correctly the association
<ide> *
| 2
|
Java
|
Java
|
fix assertion message in defaultdatabuffer
|
346b75580267dc5d8d257be198d5841ce4e1add5
|
<ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public String toString() {
<ide>
<ide> private void checkIndex(int index, int length) {
<ide> assertIndex(index >= 0, "index %d must be >= 0", index);
<del> assertIndex(length >= 0, "length %d must be >= 0", index);
<add> assertIndex(length >= 0, "length %d must be >= 0", length);
<ide> assertIndex(index <= this.capacity, "index %d must be <= %d", index, this.capacity);
<del> assertIndex(length <= this.capacity, "length %d must be <= %d", index, this.capacity);
<add> assertIndex(length <= this.capacity, "length %d must be <= %d", length, this.capacity);
<ide> }
<ide>
<ide> private void assertIndex(boolean expression, String format, Object... args) {
| 1
|
PHP
|
PHP
|
apply fixes from styleci
|
1627d05c1624f81b8edf3fc116cd8443e7899f05
|
<ide><path>tests/Support/SupportReflectorTest.php
<ide> public function testUnionTypeName()
<ide>
<ide> public function testIsCallable()
<ide> {
<del> $this->assertTrue(Reflector::isCallable(function () {}));
<add> $this->assertTrue(Reflector::isCallable(function () {
<add> }));
<ide> $this->assertTrue(Reflector::isCallable([B::class, 'f']));
<ide> $this->assertFalse(Reflector::isCallable([TestClassWithCall::class, 'f']));
<ide> $this->assertTrue(Reflector::isCallable([new TestClassWithCall, 'f']));
<ide> class TestClassWithCall
<ide> {
<ide> public function __call($method, $parameters)
<ide> {
<del>
<ide> }
<ide> }
<ide>
<ide> class TestClassWithCallStatic
<ide> {
<ide> public static function __callStatic($method, $parameters)
<ide> {
<del>
<ide> }
<ide> }
| 1
|
Javascript
|
Javascript
|
pass jest usestderr flag when debugging
|
8426bb6956fb12279c458e69fbfc62fbb04a621c
|
<ide><path>scripts/jest/jest-cli.js
<ide> function getCommandArgs() {
<ide> if (argv.debug) {
<ide> args.unshift('--inspect-brk');
<ide> args.push('--runInBand');
<add>
<add> // Prevent console logs from being hidden until test completes.
<add> args.push('--useStderr');
<ide> }
<ide>
<ide> // CI Environments have limited workers.
| 1
|
Javascript
|
Javascript
|
throw exception for invalid multipart streams
|
d9a81374b2e6995a5118f76cf15cba67a67be66d
|
<ide><path>lib/multipart.js
<ide> proto.init = function(options) {
<ide>
<ide> if ('headers' in options) {
<ide> var req = options, contentType = req.headers['content-type'];
<del> if (contentType) {
<del> contentType = contentType.split(/; ?boundary=/)
<del> this.boundary = '--'+contentType[1];
<add> if (!contentType) {
<add> throw new Error('Content-Type header not set');
<ide> }
<ide>
<add> var boundary = contentType.match(/^multipart\/form-data; ?boundary=(.+)$/i)
<add> if (!boundary) {
<add> throw new Error('Content-Type is not multipart: "'+contentType+'"');
<add> }
<add>
<add> this.boundary = '--'+boundary[1];
<ide> this.bytesTotal = req.headers['content-length'];
<ide>
<ide> var self = this;
<ide> proto.init = function(options) {
<ide> self.emit('complete');
<ide> });
<ide> } else {
<add> if (!options.boundary) {
<add> throw new Error('No boundary option given');
<add> }
<add>
<ide> this.boundary = options.boundary;
<ide> this.write(options.data || '');
<ide> }
<ide><path>test/mjsunit/test-multipart.js
<ide> var fixture = require('./fixtures/multipart');
<ide> var port = 8222;
<ide> var parts_reveived = 0;
<ide> var parts_complete = 0;
<add>var requests = 0;
<add>var badRequests = 0;
<ide> var parts = {};
<add>var respond = function(res, text) {
<add> requests++;
<add> if (requests == 2) {
<add> server.close();
<add> }
<add>
<add> res.sendHeader(200, {"Content-Type": "text/plain"});
<add> res.sendBody(text);
<add> res.finish();
<add>};
<ide>
<ide> var server = http.createServer(function(req, res) {
<del> var stream = new multipart.Stream(req);
<add> try {
<add> var stream = new multipart.Stream(req);
<add> } catch (e) {
<add> badRequests++;
<add> respond(res, 'no thanks');
<add> return;
<add> }
<ide>
<ide> stream.addListener('part', function(part) {
<ide> parts_reveived++;
<ide> var server = http.createServer(function(req, res) {
<ide> });
<ide>
<ide> stream.addListener('complete', function() {
<del> res.sendHeader(200, {"Content-Type": "text/plain"});
<del> res.sendBody('thanks');
<del> res.finish();
<del> server.close();
<add> respond(res, 'thanks');
<ide> });
<ide> });
<ide> server.listen(port);
<ide> var request = client.request('POST', '/', {'Content-Type': 'multipart/form-data;
<ide> request.sendBody(fixture.reply, 'binary');
<ide> request.finish();
<ide>
<add>var badRequest = client.request('POST', '/', {'Content-Type': 'something', 'Content-Length': fixture.reply.length});
<add>badRequest.sendBody(fixture.reply, 'binary');
<add>badRequest.finish();
<add>
<ide> process.addListener('exit', function() {
<ide> puts("done");
<ide> assert.equal(2, parts_complete);
<ide> assert.equal(2, parts_reveived);
<del>});
<add> assert.equal(1, badRequests);
<add>});
<ide>\ No newline at end of file
| 2
|
PHP
|
PHP
|
use @isset directive
|
7c283c201d04f3ee949dc89600a5aa0e4bbb80f1
|
<ide><path>src/Illuminate/Mail/resources/views/html/message.blade.php
<ide> {{ $slot }}
<ide>
<ide> {{-- Subcopy --}}
<del> @if (isset($subcopy))
<add> @isset($subcopy)
<ide> @slot('subcopy')
<ide> @component('mail::subcopy')
<ide> {{ $subcopy }}
<ide> @endcomponent
<ide> @endslot
<del> @endif
<add> @endisset
<ide>
<ide> {{-- Footer --}}
<ide> @slot('footer')
<ide><path>src/Illuminate/Mail/resources/views/markdown/layout.blade.php
<ide> {!! strip_tags($header) !!}
<ide>
<ide> {!! strip_tags($slot) !!}
<del>@if (isset($subcopy))
<add>@isset($subcopy)
<ide>
<ide> {!! strip_tags($subcopy) !!}
<del>@endif
<add>@endisset
<ide>
<ide> {!! strip_tags($footer) !!}
<ide><path>src/Illuminate/Mail/resources/views/markdown/message.blade.php
<ide> {{ $slot }}
<ide>
<ide> {{-- Subcopy --}}
<del> @if (isset($subcopy))
<add> @isset($subcopy)
<ide> @slot('subcopy')
<ide> @component('mail::subcopy')
<ide> {{ $subcopy }}
<ide> @endcomponent
<ide> @endslot
<del> @endif
<add> @endisset
<ide>
<ide> {{-- Footer --}}
<ide> @slot('footer')
<ide><path>src/Illuminate/Notifications/resources/views/email.blade.php
<ide> @endforeach
<ide>
<ide> {{-- Action Button --}}
<del>@if (isset($actionText))
<add>@isset($actionText)
<ide> <?php
<ide> switch ($level) {
<ide> case 'success':
<ide> @component('mail::button', ['url' => $actionUrl, 'color' => $color])
<ide> {{ $actionText }}
<ide> @endcomponent
<del>@endif
<add>@endisset
<ide>
<ide> {{-- Outro Lines --}}
<ide> @foreach ($outroLines as $line)
<ide> @endif
<ide>
<ide> <!-- Subcopy -->
<del>@if (isset($actionText))
<add>@isset($actionText)
<ide> @component('mail::subcopy')
<ide> If you’re having trouble clicking the "{{ $actionText }}" button, copy and paste the URL below
<ide> into your web browser: [{{ $actionUrl }}]({{ $actionUrl }})
<ide> @endcomponent
<del>@endif
<add>@endisset
<ide> @endcomponent
| 4
|
Javascript
|
Javascript
|
remove maxduration from tests
|
4c75881ee38ba2596c5c603d268f0dff178b8581
|
<ide><path>packages/react-dom/src/__tests__/ReactDOMFiberAsync-test.internal.js
<ide> describe('ReactDOMFiberAsync', () => {
<ide>
<ide> let root = ReactDOM.unstable_createRoot(container);
<ide> root.render(
<del> <React.Suspense maxDuration={1000} fallback={'Loading'}>
<del> Initial
<del> </React.Suspense>,
<add> <React.Suspense fallback={'Loading'}>Initial</React.Suspense>,
<ide> );
<ide>
<ide> Scheduler.flushAll();
<ide> expect(container.textContent).toBe('Initial');
<ide>
<ide> root.render(
<del> <React.Suspense maxDuration={1000} fallback={'Loading'}>
<add> <React.Suspense fallback={'Loading'}>
<ide> <Suspend />
<ide> </React.Suspense>,
<ide> );
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerPartialHydration-test.internal.js
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> <div>
<ide> <Suspense fallback="Loading...">
<ide> <span ref={ref} className={className}>
<del> <Suspense maxDuration={200}>
<add> <Suspense>
<ide> <Child text={text} />
<ide> </Suspense>
<ide> </span>
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> expect(ref.current).toBe(span);
<ide> });
<ide>
<del> it('replaces the fallback within the maxDuration if there is a nested suspense', async () => {
<add> it('replaces the fallback within the suspended time if there is a nested suspense', async () => {
<ide> let suspend = false;
<ide> let promise = new Promise(resolvePromise => {});
<ide> let ref = React.createRef();
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> function App() {
<ide> return (
<ide> <div>
<del> <Suspense fallback="Loading..." maxDuration={100}>
<add> <Suspense fallback="Loading...">
<ide> <span ref={ref}>
<ide> <Child />
<ide> </span>
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App />);
<ide> Scheduler.flushAll();
<del> // This will have exceeded the maxDuration so we should timeout.
<add> // This will have exceeded the suspended time so we should timeout.
<ide> jest.advanceTimersByTime(500);
<ide> // The boundary should longer be suspended for the middle content
<ide> // even though the inner boundary is still suspended.
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> expect(ref.current).toBe(span);
<ide> });
<ide>
<del> it('replaces the fallback within the maxDuration if there is a nested suspense in a nested suspense', async () => {
<add> it('replaces the fallback within the suspended time if there is a nested suspense in a nested suspense', async () => {
<ide> let suspend = false;
<ide> let promise = new Promise(resolvePromise => {});
<ide> let ref = React.createRef();
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> return (
<ide> <div>
<ide> <Suspense fallback="Another layer">
<del> <Suspense fallback="Loading..." maxDuration={100}>
<add> <Suspense fallback="Loading...">
<ide> <span ref={ref}>
<ide> <Child />
<ide> </span>
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App />);
<ide> Scheduler.flushAll();
<del> // This will have exceeded the maxDuration so we should timeout.
<add> // This will have exceeded the suspended time so we should timeout.
<ide> jest.advanceTimersByTime(500);
<ide> // The boundary should longer be suspended for the middle content
<ide> // even though the inner boundary is still suspended.
<ide><path>packages/react-dom/src/__tests__/ReactDOMSuspensePlaceholder-test.js
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide> ];
<ide> function App() {
<ide> return (
<del> <Suspense maxDuration={500} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <div ref={divs[0]}>
<ide> <Text text="A" />
<ide> </div>
<ide> <div ref={divs[1]}>
<del> <AsyncText ms={1000} text="B" />
<add> <AsyncText ms={500} text="B" />
<ide> </div>
<ide> <div style={{display: 'block'}} ref={divs[2]}>
<ide> <Text text="C" />
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide> expect(divs[1].current.style.display).toEqual('none');
<ide> expect(divs[2].current.style.display).toEqual('none');
<ide>
<del> await advanceTimers(1000);
<add> await advanceTimers(500);
<ide>
<ide> expect(divs[0].current.style.display).toEqual('');
<ide> expect(divs[1].current.style.display).toEqual('');
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide> it('hides and unhides timed out text nodes', async () => {
<ide> function App() {
<ide> return (
<del> <Suspense maxDuration={500} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <Text text="A" />
<del> <AsyncText ms={1000} text="B" />
<add> <AsyncText ms={500} text="B" />
<ide> <Text text="C" />
<ide> </Suspense>
<ide> );
<ide> }
<ide> ReactDOM.render(<App />, container);
<ide> expect(container.textContent).toEqual('Loading...');
<ide>
<del> await advanceTimers(1000);
<add> await advanceTimers(500);
<ide>
<ide> expect(container.textContent).toEqual('ABC');
<ide> });
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide>
<ide> function App() {
<ide> return (
<del> <Suspense maxDuration={500} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <Sibling>Sibling</Sibling>
<ide> <span>
<del> <AsyncText ms={1000} text="Async" />
<add> <AsyncText ms={500} text="Async" />
<ide> </span>
<ide> </Suspense>
<ide> );
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide> '<span style="display: none;">Sibling</span><span style="display: none;"></span>Loading...',
<ide> );
<ide>
<del> await advanceTimers(1000);
<add> await advanceTimers(500);
<ide>
<ide> expect(container.innerHTML).toEqual(
<ide> '<span style="display: inline;">Sibling</span><span style="">Async</span>',
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js
<ide> let didWarnAboutContextTypeOnFunctionComponent;
<ide> let didWarnAboutGetDerivedStateOnFunctionComponent;
<ide> let didWarnAboutFunctionRefs;
<ide> export let didWarnAboutReassigningProps;
<add>let didWarnAboutMaxDuration;
<ide>
<ide> if (__DEV__) {
<ide> didWarnAboutBadClass = {};
<ide> if (__DEV__) {
<ide> didWarnAboutGetDerivedStateOnFunctionComponent = {};
<ide> didWarnAboutFunctionRefs = {};
<ide> didWarnAboutReassigningProps = false;
<add> didWarnAboutMaxDuration = false;
<ide> }
<ide>
<ide> export function reconcileChildren(
<ide> function updateSuspenseComponent(
<ide> workInProgress.effectTag &= ~DidCapture;
<ide> }
<ide>
<add> if (__DEV__) {
<add> if ('maxDuration' in nextProps) {
<add> if (!didWarnAboutMaxDuration) {
<add> didWarnAboutMaxDuration = true;
<add> warning(
<add> false,
<add> 'maxDuration has been removed from React. ' +
<add> 'Remove the maxDuration prop.',
<add> );
<add> }
<add> }
<add> }
<add>
<ide> // This next part is a bit confusing. If the children timeout, we switch to
<ide> // showing the fallback children in place of the "primary" children.
<ide> // However, we don't want to delete the primary children because then their
<ide><path>packages/react-reconciler/src/ReactFiberUnwindWork.js
<ide> function throwException(
<ide> break;
<ide> }
<ide> }
<del> let timeoutPropMs = workInProgress.pendingProps.maxDuration;
<del> if (typeof timeoutPropMs === 'number') {
<del> if (timeoutPropMs <= 0) {
<del> earliestTimeoutMs = 0;
<del> } else if (
<del> earliestTimeoutMs === -1 ||
<del> timeoutPropMs < earliestTimeoutMs
<del> ) {
<del> earliestTimeoutMs = timeoutPropMs;
<del> }
<add> const defaultSuspenseTimeout = 150;
<add> if (
<add> earliestTimeoutMs === -1 ||
<add> defaultSuspenseTimeout < earliestTimeoutMs
<add> ) {
<add> earliestTimeoutMs = defaultSuspenseTimeout;
<ide> }
<ide> }
<ide> // If there is a DehydratedSuspenseComponent we don't have to do anything because
<ide><path>packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js
<ide> describe('ReactLazy', () => {
<ide> return <Text text="Bar" />;
<ide> }
<ide>
<del> const promiseForFoo = delay(1000).then(() => fakeImport(Foo));
<del> const promiseForBar = delay(2000).then(() => fakeImport(Bar));
<add> const promiseForFoo = delay(100).then(() => fakeImport(Foo));
<add> const promiseForBar = delay(500).then(() => fakeImport(Bar));
<ide>
<ide> const LazyFoo = lazy(() => promiseForFoo);
<ide> const LazyBar = lazy(() => promiseForBar);
<ide> describe('ReactLazy', () => {
<ide> expect(Scheduler).toFlushAndYield(['Loading...']);
<ide> expect(root).toMatchRenderedOutput(null);
<ide>
<del> jest.advanceTimersByTime(1000);
<add> jest.advanceTimersByTime(100);
<ide> await promiseForFoo;
<ide>
<ide> expect(Scheduler).toFlushAndYield(['Foo', 'Loading...']);
<ide> expect(root).toMatchRenderedOutput(null);
<ide>
<del> jest.advanceTimersByTime(1000);
<add> jest.advanceTimersByTime(500);
<ide> await promiseForBar;
<ide>
<ide> expect(Scheduler).toFlushAndYield(['Foo', 'Bar']);
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspense-test.internal.js
<ide> describe('ReactSuspense', () => {
<ide> // Render two sibling Suspense components
<ide> const root = ReactTestRenderer.create(
<ide> <React.Fragment>
<del> <Suspense maxDuration={1000} fallback={<Text text="Loading A..." />}>
<add> <Suspense fallback={<Text text="Loading A..." />}>
<ide> <AsyncText text="A" ms={5000} />
<ide> </Suspense>
<del> <Suspense maxDuration={3000} fallback={<Text text="Loading B..." />}>
<add> <Suspense fallback={<Text text="Loading B..." />}>
<ide> <AsyncText text="B" ms={6000} />
<ide> </Suspense>
<ide> </React.Fragment>,
<ide> describe('ReactSuspense', () => {
<ide> }
<ide>
<ide> const root = ReactTestRenderer.create(
<del> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <Async />
<ide> <Text text="Sibling" />
<ide> </Suspense>,
<ide> describe('ReactSuspense', () => {
<ide> it('only captures if `fallback` is defined', () => {
<ide> const root = ReactTestRenderer.create(
<ide> <Suspense fallback={<Text text="Loading..." />}>
<del> <Suspense maxDuration={100}>
<add> <Suspense>
<ide> <AsyncText text="Hi" ms={5000} />
<ide> </Suspense>
<ide> </Suspense>,
<ide> describe('ReactSuspense', () => {
<ide>
<ide> function App() {
<ide> return (
<del> <Suspense
<del> maxDuration={1000}
<del> fallback={<TextWithLifecycle text="Loading..." />}>
<add> <Suspense fallback={<TextWithLifecycle text="Loading..." />}>
<ide> <TextWithLifecycle text="A" />
<ide> <AsyncTextWithLifecycle ms={100} text="B" ref={instance} />
<ide> <TextWithLifecycle text="C" />
<ide> describe('ReactSuspense', () => {
<ide>
<ide> function App(props) {
<ide> return (
<del> <Suspense maxDuration={10} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <Stateful />
<ide> </Suspense>
<ide> );
<ide> describe('ReactSuspense', () => {
<ide>
<ide> function App(props) {
<ide> return (
<del> <Suspense maxDuration={10} fallback={<ShouldMountOnce />}>
<add> <Suspense fallback={<ShouldMountOnce />}>
<ide> <AsyncText ms={1000} text="Child 1" />
<ide> <AsyncText ms={2000} text="Child 2" />
<ide> <AsyncText ms={3000} text="Child 3" />
<ide> describe('ReactSuspense', () => {
<ide> it('does not get stuck with fallback in concurrent mode for a large delay', () => {
<ide> function App(props) {
<ide> return (
<del> <Suspense maxDuration={10} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <AsyncText ms={1000} text="Child 1" />
<ide> <AsyncText ms={7000} text="Child 2" />
<ide> </Suspense>
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseFuzz-test.internal.js
<ide> describe('ReactSuspenseFuzz', () => {
<ide> remainingElements--;
<ide> const children = createRandomChildren(3);
<ide>
<del> const maxDuration = pickRandomWeighted(rand, [
<del> {value: undefined, weight: 1},
<del> {value: rand.intBetween(0, 5000), weight: 1},
<del> ]);
<del>
<ide> const fallbackType = pickRandomWeighted(rand, [
<ide> {value: 'none', weight: 1},
<ide> {value: 'normal', weight: 1},
<ide> describe('ReactSuspenseFuzz', () => {
<ide> );
<ide> }
<ide>
<del> return React.createElement(
<del> Suspense,
<del> {maxDuration, fallback},
<del> ...children,
<del> );
<add> return React.createElement(Suspense, {fallback}, ...children);
<ide> }
<ide> case 'return':
<ide> default:
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspensePlaceholder-test.internal.js
<ide> describe('ReactSuspensePlaceholder', () => {
<ide>
<ide> function App(props) {
<ide> return (
<del> <Suspense maxDuration={500} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <HiddenText text="A" />
<ide> <span>
<ide> <AsyncText ms={1000} text={props.middleText} />
<ide> describe('ReactSuspensePlaceholder', () => {
<ide> it('times out text nodes', async () => {
<ide> function App(props) {
<ide> return (
<del> <Suspense maxDuration={500} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <Text text="A" />
<ide> <AsyncText ms={1000} text={props.middleText} />
<ide> <Text text="C" />
<ide> describe('ReactSuspensePlaceholder', () => {
<ide> // uppercase is a special type that causes React Noop to render child
<ide> // text nodes as uppercase.
<ide> <uppercase>
<del> <Suspense maxDuration={500} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <Text text="a" />
<ide> <AsyncText ms={1000} text={props.middleText} />
<ide> <Text text="c" />
<ide> describe('ReactSuspensePlaceholder', () => {
<ide> Scheduler.yieldValue('App');
<ide> return (
<ide> <Profiler id="root" onRender={onRender}>
<del> <Suspense maxDuration={500} fallback={<Fallback />}>
<add> <Suspense fallback={<Fallback />}>
<ide> {shouldSuspend && <Suspending />}
<ide> <Text fakeRenderDuration={textRenderDuration} text={text} />
<ide> </Suspense>
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.internal.js
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> }
<ide> }
<ide>
<add> it('warns if the deprecated maxDuration option is used', () => {
<add> function Foo() {
<add> return (
<add> <Suspense maxDuration={100} fallback="Loading...">
<add> <div />;
<add> </Suspense>
<add> );
<add> }
<add>
<add> ReactNoop.render(<Foo />);
<add>
<add> expect(() => Scheduler.flushAll()).toWarnDev([
<add> 'Warning: maxDuration has been removed from React. ' +
<add> 'Remove the maxDuration prop.' +
<add> '\n in Suspense (at **)' +
<add> '\n in Foo (at **)',
<add> ]);
<add> });
<add>
<ide> it('suspends rendering and continues later', async () => {
<ide> function Bar(props) {
<ide> Scheduler.yieldValue('Bar');
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> // Render two sibling Suspense components
<ide> ReactNoop.render(
<ide> <Fragment>
<del> <Suspense maxDuration={1000} fallback={<Text text="Loading A..." />}>
<add> <Suspense fallback={<Text text="Loading A..." />}>
<ide> <AsyncText text="A" ms={5000} />
<ide> </Suspense>
<del> <Suspense maxDuration={3000} fallback={<Text text="Loading B..." />}>
<add> <Suspense fallback={<Text text="Loading B..." />}>
<ide> <AsyncText text="B" ms={6000} />
<ide> </Suspense>
<ide> </Fragment>,
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> const errorBoundary = React.createRef();
<ide> function App() {
<ide> return (
<del> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <ErrorBoundary ref={errorBoundary}>
<ide> <AsyncText text="Result" ms={3000} />
<ide> </ErrorBoundary>
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> });
<ide>
<ide> it('keeps working on lower priority work after being pinged', async () => {
<add> // Advance the virtual time so that we're close to the edge of a bucket.
<add> ReactNoop.expire(149);
<add>
<ide> function App(props) {
<ide> return (
<ide> <Suspense fallback={<Text text="Loading..." />}>
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(Scheduler).toFlushAndYield(['Suspend! [A]', 'Loading...']);
<ide> expect(ReactNoop.getChildren()).toEqual([]);
<ide>
<del> // Advance React's virtual time by enough to fall into a new async bucket.
<del> ReactNoop.expire(1200);
<add> // Advance React's virtual time by enough to fall into a new async bucket,
<add> // but not enough to expire the suspense timeout.
<add> ReactNoop.expire(120);
<ide> ReactNoop.render(<App showB={true} />);
<ide> expect(Scheduler).toFlushAndYield(['Suspend! [A]', 'B', 'Loading...']);
<ide> expect(ReactNoop.getChildren()).toEqual([]);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> });
<ide>
<ide> it('switches to an inner fallback even if it expires later', async () => {
<add> // Advance the virtual time so that we're closer to the edge of a bucket.
<add> ReactNoop.expire(200);
<add>
<ide> ReactNoop.render(
<ide> <Fragment>
<ide> <Text text="Sync" />
<del> <Suspense
<del> maxDuration={1000}
<del> fallback={<Text text="Loading outer..." />}>
<del> <AsyncText text="Outer content" ms={2000} />
<del> <Suspense
<del> maxDuration={2500}
<del> fallback={<Text text="Loading inner..." />}>
<del> <AsyncText text="Inner content" ms={5000} />
<add> <Suspense fallback={<Text text="Loading outer..." />}>
<add> <AsyncText text="Outer content" ms={300} />
<add> <Suspense fallback={<Text text="Loading inner..." />}>
<add> <AsyncText text="Inner content" ms={1000} />
<ide> </Suspense>
<ide> </Suspense>
<ide> </Fragment>,
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> // Expire the outer timeout, but don't expire the inner one.
<ide> // We should see the outer loading placeholder.
<del> ReactNoop.expire(1500);
<del> await advanceTimers(1500);
<add> ReactNoop.expire(250);
<add> await advanceTimers(250);
<ide> expect(Scheduler).toFlushWithoutYielding();
<ide> expect(ReactNoop.getChildren()).toEqual([
<ide> span('Sync'),
<ide> span('Loading outer...'),
<ide> ]);
<ide>
<ide> // Resolve the outer promise.
<del> ReactNoop.expire(2000);
<del> await advanceTimers(2000);
<del> // At this point, 3.5 seconds have elapsed total. The outer placeholder
<del> // timed out at 1.5 seconds. So, 2 seconds have elapsed since the
<del> // placeholder timed out. That means we still haven't reached the 2.5 second
<add> ReactNoop.expire(50);
<add> await advanceTimers(50);
<add> // At this point, 250ms have elapsed total. The outer placeholder
<add> // timed out at around 150-200ms. So, 50-100ms have elapsed since the
<add> // placeholder timed out. That means we still haven't reached the 150ms
<ide> // threshold of the inner placeholder.
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [Outer content]']);
<ide> expect(Scheduler).toFlushAndYield([
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> // Expire the inner timeout.
<ide> ReactNoop.expire(500);
<ide> await advanceTimers(500);
<del> // Now that 2.5 seconds have elapsed since the outer placeholder timed out,
<add> // Now that 750ms have elapsed since the outer placeholder timed out,
<ide> // we can timeout the inner placeholder.
<ide> expect(ReactNoop.getChildren()).toEqual([
<ide> span('Sync'),
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([span('Loading (outer)...')]);
<ide> });
<ide>
<del> it('expires early with a `maxDuration` option', async () => {
<add> it('expires early by default', async () => {
<ide> ReactNoop.render(
<ide> <Fragment>
<del> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <AsyncText text="Async" ms={3000} />
<ide> </Suspense>
<ide> <Text text="Sync" />
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('resolves successfully even if fallback render is pending', async () => {
<ide> ReactNoop.render(
<del> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <AsyncText text="Async" ms={3000} />
<ide> </Suspense>,
<ide> );
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('a Suspense component correctly handles more than one suspended child', async () => {
<ide> ReactNoop.render(
<del> <Suspense maxDuration={0} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <AsyncText text="A" ms={100} />
<ide> <AsyncText text="B" ms={100} />
<ide> </Suspense>,
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('can resume rendering earlier than a timeout', async () => {
<ide> ReactNoop.render(
<del> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <AsyncText text="Async" ms={100} />
<ide> </Suspense>,
<ide> );
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([span('Async')]);
<ide> });
<ide>
<del> it('starts working on an update even if its priority falls between two suspended levels', async () => {
<add> // TODO: This cannot be tested until we have a way to long-suspend navigations.
<add> it.skip('starts working on an update even if its priority falls between two suspended levels', async () => {
<ide> function App(props) {
<ide> return (
<del> <Suspense fallback={<Text text="Loading..." />} maxDuration={10000}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> {props.text === 'C' ? (
<ide> <Text text="C" />
<ide> ) : (
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([span('goodbye')]);
<ide> });
<ide>
<del> describe('a Delay component', () => {
<del> function Never() {
<del> // Throws a promise that resolves after some arbitrarily large
<del> // number of seconds. The idea is that this component will never
<del> // resolve. It's always wrapped by a Suspense.
<del> throw new Promise(resolve => setTimeout(() => resolve(), 10000));
<del> }
<del>
<del> function Delay({ms}) {
<del> // Once ms has elapsed, render null. This allows the rest of the
<del> // tree to resume rendering.
<del> return (
<del> <Suspense fallback={null} maxDuration={ms}>
<del> <Never />
<del> </Suspense>
<del> );
<del> }
<del>
<del> function DebouncedText({text, ms}) {
<del> return (
<del> <Fragment>
<del> <Delay ms={ms} />
<del> <Text text={text} />
<del> </Fragment>
<del> );
<del> }
<del>
<del> it('works', async () => {
<del> ReactNoop.render(<DebouncedText text="A" ms={1000} />);
<del> expect(Scheduler).toFlushAndYield(['A']);
<del> expect(ReactNoop.getChildren()).toEqual([]);
<del>
<del> await advanceTimers(800);
<del> ReactNoop.expire(800);
<del> expect(Scheduler).toFlushWithoutYielding();
<del> expect(ReactNoop.getChildren()).toEqual([]);
<del>
<del> await advanceTimers(1000);
<del> ReactNoop.expire(1000);
<del> expect(Scheduler).toFlushWithoutYielding();
<del> expect(ReactNoop.getChildren()).toEqual([span('A')]);
<del> });
<del> });
<del>
<ide> describe('sync mode', () => {
<ide> it('times out immediately', async () => {
<ide> function App() {
<ide> return (
<del> <Suspense maxDuration={1000} fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <AsyncText ms={100} text="Result" />
<ide> </Suspense>
<ide> );
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> const text = React.createRef(null);
<ide> function App() {
<ide> return (
<del> <Suspense maxDuration={1000} fallback={<Spinner />}>
<add> <Suspense fallback={<Spinner />}>
<ide> <ConcurrentMode>
<ide> <UpdatingText ref={text} />
<ide> <Text text="Sibling" />
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> function App() {
<ide> return (
<ide> <Fragment>
<del> <Suspense
<del> maxDuration={1000}
<del> fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <ConcurrentMode>
<ide> <UpdatingText ref={text1} initialText="Async: 1">
<ide> {text => (
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> function App() {
<ide> return (
<ide> <StrictMode>
<del> <Suspense
<del> maxDuration={1000}
<del> fallback={<Text text="Loading..." />}>
<add> <Suspense fallback={<Text text="Loading..." />}>
<ide> <ConcurrentMode>
<ide> <UpdatingText ref={text1} initialText="Async: 1">
<ide> {text => (
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> function App() {
<ide> return (
<del> <Suspense
<del> maxDuration={1000}
<del> fallback={<TextWithLifecycle text="Loading..." />}>
<add> <Suspense fallback={<TextWithLifecycle text="Loading..." />}>
<ide> <TextWithLifecycle text="A" />
<ide> <AsyncTextWithLifecycle ms={100} text="B" />
<ide> <TextWithLifecycle text="C" />
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> function App() {
<ide> return (
<del> <Suspense
<del> maxDuration={1000}
<del> fallback={<TextWithLifecycle text="Loading..." />}>
<add> <Suspense fallback={<TextWithLifecycle text="Loading..." />}>
<ide> <TextWithLifecycle text="A" />
<ide> <AsyncTextWithLifecycle ms={100} text="B" />
<ide> <TextWithLifecycle text="C" />
<ide><path>packages/react/src/__tests__/ReactProfiler-test.internal.js
<ide> describe('Profiler', () => {
<ide> () => {
<ide> ReactTestRenderer.create(
<ide> <React.Profiler id="app" onRender={onRender}>
<del> <React.Suspense
<del> maxDuration={1000}
<del> fallback={<Text text="loading" />}>
<del> <AsyncText text="loaded" ms={2000} />
<add> <React.Suspense fallback={<Text text="loading" />}>
<add> <AsyncText text="loaded" ms={500} />
<ide> </React.Suspense>
<ide> </React.Profiler>,
<ide> );
<ide> describe('Profiler', () => {
<ide> () => {
<ide> ReactTestRenderer.create(
<ide> <React.Profiler id="app" onRender={onRender}>
<del> <React.Suspense
<del> maxDuration={1000}
<del> fallback={<Text text="loading" />}>
<del> <AsyncComponentWithCascadingWork text="loaded" ms={2000} />
<add> <React.Suspense fallback={<Text text="loading" />}>
<add> <AsyncComponentWithCascadingWork text="loaded" ms={500} />
<ide> </React.Suspense>
<ide> </React.Profiler>,
<ide> );
<ide> describe('Profiler', () => {
<ide> () => {
<ide> ReactTestRenderer.create(
<ide> <React.Profiler id="app" onRender={onRender}>
<del> <React.Suspense
<del> maxDuration={1000}
<del> fallback={<Text text="loading" />}>
<del> <AsyncText text="loaded" ms={2000} />
<add> <React.Suspense fallback={<Text text="loading" />}>
<add> <AsyncText text="loaded" ms={500} />
<ide> </React.Suspense>
<ide> </React.Profiler>,
<ide> {
<ide> describe('Profiler', () => {
<ide> },
<ide> );
<ide>
<del> Scheduler.advanceTime(1500);
<del> await awaitableAdvanceTimers(1500);
<add> Scheduler.advanceTime(400);
<add> await awaitableAdvanceTimers(400);
<ide>
<ide> expect(Scheduler).toFlushAndYield([
<ide> 'Suspend [loaded]',
<ide> 'Text [loading]',
<ide> ]);
<ide> expect(onInteractionScheduledWorkCompleted).not.toHaveBeenCalled();
<ide>
<del> Scheduler.advanceTime(2500);
<del> await awaitableAdvanceTimers(2500);
<add> Scheduler.advanceTime(500);
<add> await awaitableAdvanceTimers(500);
<ide>
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [loaded]']);
<ide> expect(Scheduler).toFlushAndYield(['AsyncText [loaded]']);
<ide> describe('Profiler', () => {
<ide> () => {
<ide> ReactTestRenderer.create(
<ide> <React.Profiler id="app" onRender={onRender}>
<del> <React.Suspense
<del> maxDuration={2000}
<del> fallback={<Text text="loading" />}>
<del> <AsyncText text="loaded" ms={1000} />
<add> <React.Suspense fallback={<Text text="loading" />}>
<add> <AsyncText text="loaded" ms={100} />
<ide> </React.Suspense>
<ide> </React.Profiler>,
<ide> {unstable_isConcurrent: true},
<ide> describe('Profiler', () => {
<ide>
<ide> expect(onInteractionScheduledWorkCompleted).not.toHaveBeenCalled();
<ide>
<del> jest.advanceTimersByTime(1000);
<add> jest.advanceTimersByTime(100);
<ide> await resourcePromise;
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [loaded]']);
<ide> expect(Scheduler).toFlushAndYield(['AsyncText [loaded]']);
<ide> describe('Profiler', () => {
<ide> () => {
<ide> renderer = ReactTestRenderer.create(
<ide> <React.Profiler id="app" onRender={onRender}>
<del> <React.Suspense
<del> maxDuration={2000}
<del> fallback={<Text text="loading" />}>
<del> <AsyncText text="loaded" ms={1000} />
<add> <React.Suspense fallback={<Text text="loading" />}>
<add> <AsyncText text="loaded" ms={100} />
<ide> </React.Suspense>
<ide> <Text text="initial" />
<ide> </React.Profiler>,
<ide> describe('Profiler', () => {
<ide> () => {
<ide> renderer.update(
<ide> <React.Profiler id="app" onRender={onRender}>
<del> <React.Suspense
<del> maxDuration={2000}
<del> fallback={<Text text="loading" />}>
<del> <AsyncText text="loaded" ms={1000} />
<add> <React.Suspense fallback={<Text text="loading" />}>
<add> <AsyncText text="loaded" ms={100} />
<ide> </React.Suspense>
<ide> <Text text="updated" />
<ide> </React.Profiler>,
<ide> describe('Profiler', () => {
<ide>
<ide> expect(onInteractionScheduledWorkCompleted).not.toHaveBeenCalled();
<ide>
<del> Scheduler.advanceTime(1000);
<del> jest.advanceTimersByTime(1000);
<add> Scheduler.advanceTime(100);
<add> jest.advanceTimersByTime(100);
<ide> await originalPromise;
<ide> expect(renderer.toJSON()).toEqual(['loaded', 'updated']);
<ide>
<ide> describe('Profiler', () => {
<ide> () => {
<ide> renderer = ReactTestRenderer.create(
<ide> <React.Profiler id="app" onRender={onRender}>
<del> <React.Suspense
<del> maxDuration={2000}
<del> fallback={<Text text="loading" />}>
<del> <AsyncText text="loaded" ms={1000} />
<add> <React.Suspense fallback={<Text text="loading" />}>
<add> <AsyncText text="loaded" ms={100} />
<ide> </React.Suspense>
<ide> <Text text="initial" />
<ide> </React.Profiler>,
<ide> describe('Profiler', () => {
<ide> expect(onInteractionScheduledWorkCompleted).not.toHaveBeenCalled();
<ide> expect(onRender).not.toHaveBeenCalled();
<ide>
<del> Scheduler.advanceTime(500);
<del> jest.advanceTimersByTime(500);
<add> Scheduler.advanceTime(50);
<add> jest.advanceTimersByTime(50);
<ide>
<ide> const highPriUpdateInteraction = {
<ide> id: 1,
<ide> describe('Profiler', () => {
<ide> () => {
<ide> renderer.update(
<ide> <React.Profiler id="app" onRender={onRender}>
<del> <React.Suspense
<del> maxDuration={2000}
<del> fallback={<Text text="loading" />}>
<del> <AsyncText text="loaded" ms={1000} />
<add> <React.Suspense fallback={<Text text="loading" />}>
<add> <AsyncText text="loaded" ms={100} />
<ide> </React.Suspense>
<ide> <Text text="updated" />
<ide> </React.Profiler>,
<ide> describe('Profiler', () => {
<ide>
<ide> expect(onInteractionScheduledWorkCompleted).toHaveBeenCalledTimes(0);
<ide>
<del> Scheduler.advanceTime(500);
<del> jest.advanceTimersByTime(500);
<add> Scheduler.advanceTime(50);
<add> jest.advanceTimersByTime(50);
<ide> await originalPromise;
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [loaded]']);
<ide> expect(Scheduler).toFlushAndYield(['AsyncText [loaded]']);
<ide><path>packages/react/src/__tests__/ReactProfilerDOM-test.internal.js
<ide> describe('ProfilerDOM', () => {
<ide> const root = ReactDOM.unstable_createRoot(element);
<ide> batch = root.createBatch();
<ide> batch.render(
<del> <React.Suspense maxDuration={100} fallback={<Text text="Loading..." />}>
<add> <React.Suspense fallback={<Text text="Loading..." />}>
<ide> <AsyncText text="Text" ms={2000} />
<ide> </React.Suspense>,
<ide> );
| 12
|
Ruby
|
Ruby
|
fix incorrect cellar value in json
|
0f90267bd0ffdd6ebff241a9703173bdb1ced74e
|
<ide><path>Library/Homebrew/dev-cmd/bottle.rb
<ide> def bottle_formula(f, args:)
<ide> "bottle" => {
<ide> "root_url" => bottle.root_url,
<ide> "prefix" => bottle.prefix,
<del> "cellar" => bottle.cellar.to_s,
<add> "cellar" => bottle_cellar.to_s,
<ide> "rebuild" => bottle.rebuild,
<ide> "date" => Pathname(local_filename).mtime.strftime("%F"),
<ide> "tags" => {
| 1
|
Javascript
|
Javascript
|
remove url parameters from forum href
|
0b362380d444dcf087356b6c6279603f350f336e
|
<ide><path>client/src/templates/Challenges/redux/create-question-epic.js
<ide> function createQuestionEpic(action$, state$, { window }) {
<ide> challengeMetaSelector(state);
<ide> const {
<ide> navigator: { userAgent },
<del> location: { href }
<add> location: { pathname, origin }
<ide> } = window;
<add> // Removes query params
<add> const challengeUrl = new URL(pathname, origin).href;
<ide> const projectFormValues = Object.entries(
<ide> projectFormValuesSelector(state)
<ide> );
<ide> function createQuestionEpic(action$, state$, { window }) {
<ide> 'forum-help.challenge'
<ide> )} ${challengeTitle}\n\n${i18next.t(
<ide> 'forum-help.challenge-link'
<del> )}\n${href}`
<add> )}\n${challengeUrl}`
<ide> );
<ide>
<ide> let textMessage = dedent(`${i18next.t(
| 1
|
Ruby
|
Ruby
|
send checksum to s3 to verify file integrity
|
f8539164c046e162531728b15f764fa8248704f1
|
<ide><path>lib/active_storage/service/s3_service.rb
<ide> def initialize(access_key_id:, secret_access_key:, region:, bucket:)
<ide> end
<ide>
<ide> def upload(key, io, checksum: nil)
<del> # FIXME: Ensure integrity by sending the checksum for service side verification
<del> object_for(key).put(body: io)
<add> object_for(key).put(body: io, content_md5: checksum)
<ide> end
<ide>
<ide> def download(key)
| 1
|
Javascript
|
Javascript
|
add missing semicolon
|
d3fce9e82c1e248231d46bf3ff6ed61b20914088
|
<ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide> var jqObject = jqLite("<p><span>s1</span><span>s2</span></p>").find("span"),
<ide> log = [];
<ide>
<del> forEach(jqObject, function(value, key) { log.push(key + ':' + value.innerHTML)});
<add> forEach(jqObject, function(value, key) { log.push(key + ':' + value.innerHTML); });
<ide> expect(log).toEqual(['0:s1', '1:s2']);
<ide> });
<ide>
| 1
|
Text
|
Text
|
add missing parameter types
|
68229a9f08ea900979e38df0d6c2612e2197cfe1
|
<ide><path>doc/api/timers.md
<ide> Cancels an `Immediate` object created by [`setImmediate()`][].
<ide> added: v0.0.1
<ide> -->
<ide>
<del>* `timeout` {Timeout} A `Timeout` object as returned by [`setInterval()`][].
<add>* `timeout` {Timeout|string|number} A `Timeout` object as returned by [`setInterval()`][]
<add> or the [primitive][] of the `Timeout` object as a string or a number.
<ide>
<ide> Cancels a `Timeout` object created by [`setInterval()`][].
<ide>
<ide> Cancels a `Timeout` object created by [`setInterval()`][].
<ide> added: v0.0.1
<ide> -->
<ide>
<del>* `timeout` {Timeout} A `Timeout` object as returned by [`setTimeout()`][].
<add>* `timeout` {Timeout|string|number} A `Timeout` object as returned by [`setTimeout()`][]
<add> or the [primitive][] of the `Timeout` object as a string or a number.
<ide>
<ide> Cancels a `Timeout` object created by [`setTimeout()`][].
<ide>
<ide> const interval = 100;
<ide> [`setTimeout()`]: timers.md#timers_settimeout_callback_delay_args
<ide> [`util.promisify()`]: util.md#util_util_promisify_original
<ide> [`worker_threads`]: worker_threads.md
<add>[primitive]: timers.md#timers_timeout_symbol_toprimitive
| 1
|
Mixed
|
Python
|
update new models and internal changes
|
146a37c6663e4a249e02d3dff0087b576e3dc3a1
|
<ide><path>research/deeplab/README.md
<ide> under tensorflow/models. Please refer to the LICENSE for details.
<ide>
<ide> ## Change Logs
<ide>
<add>### March 27, 2019
<add>
<add>* Supported using different loss weights on different classes during training.
<add>**Contributor**: Yuwei Yang.
<add>
<add>
<add>### March 26, 2019
<add>
<add>* Supported ResNet-v1-18. **Contributor**: Michalis Raptis.
<add>
<add>
<ide> ### March 6, 2019
<ide>
<ide> * Released the evaluation code (under the `evaluation` folder) for image
<ide><path>research/deeplab/common.py
<ide> flags.DEFINE_integer('resize_factor', None,
<ide> 'Resized dimensions are multiple of factor plus one.')
<ide>
<add>flags.DEFINE_boolean('keep_aspect_ratio', True,
<add> 'Keep aspect ratio after resizing or not.')
<add>
<ide> # Model dependent flags.
<ide>
<ide> flags.DEFINE_integer('logits_kernel_size', 1,
<ide> flags.DEFINE_boolean(
<ide> 'prediction_with_upsampled_logits', True,
<ide> 'When performing prediction, there are two options: (1) bilinear '
<del> 'upsampling the logits followed by argmax, or (2) armax followed by '
<del> 'nearest upsampling the predicted labels. The second option may introduce '
<del> 'some "blocking effect", but it is more computationally efficient. '
<del> 'Currently, prediction_with_upsampled_logits=False is only supported for '
<del> 'single-scale inference.')
<add> 'upsampling the logits followed by softmax, or (2) softmax followed by '
<add> 'bilinear upsampling.')
<ide>
<ide> flags.DEFINE_string(
<ide> 'dense_prediction_cell_json',
<ide> 'nas_stem_output_num_conv_filters', 20,
<ide> 'Number of filters of the stem output tensor in NAS models.')
<ide>
<add>flags.DEFINE_bool('nas_use_classification_head', False,
<add> 'Use image classification head for NAS model variants.')
<add>
<add>flags.DEFINE_bool('nas_remove_os32_stride', False,
<add> 'Remove the stride in the output stride 32 branch.')
<add>
<ide> flags.DEFINE_bool('use_bounded_activation', False,
<ide> 'Whether or not to use bounded activations. Bounded '
<ide> 'activations better lend themselves to quantized inference.')
<ide>
<add>flags.DEFINE_boolean('aspp_with_concat_projection', True,
<add> 'ASPP with concat projection.')
<add>
<add>flags.DEFINE_boolean('aspp_with_squeeze_and_excitation', False,
<add> 'ASPP with squeeze and excitation.')
<add>
<add>flags.DEFINE_integer('aspp_convs_filters', 256, 'ASPP convolution filters.')
<add>
<add>flags.DEFINE_boolean('decoder_use_sum_merge', False,
<add> 'Decoder uses simply sum merge.')
<add>
<add>flags.DEFINE_integer('decoder_filters', 256, 'Decoder filters.')
<add>
<add>flags.DEFINE_boolean('decoder_output_is_logits', False,
<add> 'Use decoder output as logits or not.')
<add>
<add>flags.DEFINE_boolean('image_se_uses_qsigmoid', False, 'Use q-sigmoid.')
<add>
<add>flags.DEFINE_multi_float(
<add> 'label_weights', None,
<add> 'A list of label weights, each element represents the weight for the label '
<add> 'of its index, for example, label_weights = [0.1, 0.5] means the weight '
<add> 'for label 0 is 0.1 and the weight for label 1 is 0.5. If set as None, all '
<add> 'the labels have the same weight 1.0.')
<add>
<add>flags.DEFINE_float('batch_norm_decay', 0.9997, 'Batchnorm decay.')
<add>
<ide> FLAGS = flags.FLAGS
<ide>
<ide> # Constants
<ide> class ModelOptions(
<ide> 'divisible_by',
<ide> 'prediction_with_upsampled_logits',
<ide> 'dense_prediction_cell_config',
<del> 'nas_stem_output_num_conv_filters',
<del> 'use_bounded_activation'
<add> 'nas_architecture_options',
<add> 'use_bounded_activation',
<add> 'aspp_with_concat_projection',
<add> 'aspp_with_squeeze_and_excitation',
<add> 'aspp_convs_filters',
<add> 'decoder_use_sum_merge',
<add> 'decoder_filters',
<add> 'decoder_output_is_logits',
<add> 'image_se_uses_qsigmoid',
<add> 'label_weights',
<add> 'sync_batch_norm_method',
<add> 'batch_norm_decay',
<ide> ])):
<ide> """Immutable class to hold model options."""
<ide>
<ide> def __new__(cls,
<ide> image_pooling_stride = [1, 1]
<ide> if FLAGS.image_pooling_stride:
<ide> image_pooling_stride = [int(x) for x in FLAGS.image_pooling_stride]
<add> label_weights = FLAGS.label_weights
<add> if label_weights is None:
<add> label_weights = 1.0
<add> nas_architecture_options = {
<add> 'nas_stem_output_num_conv_filters': (
<add> FLAGS.nas_stem_output_num_conv_filters),
<add> 'nas_use_classification_head': FLAGS.nas_use_classification_head,
<add> 'nas_remove_os32_stride': FLAGS.nas_remove_os32_stride,
<add> }
<ide> return super(ModelOptions, cls).__new__(
<ide> cls, outputs_to_num_classes, crop_size, atrous_rates, output_stride,
<del> preprocessed_images_dtype, FLAGS.merge_method,
<add> preprocessed_images_dtype,
<add> FLAGS.merge_method,
<ide> FLAGS.add_image_level_feature,
<ide> image_pooling_crop_size,
<ide> image_pooling_stride,
<ide> FLAGS.aspp_with_batch_norm,
<del> FLAGS.aspp_with_separable_conv, FLAGS.multi_grid, decoder_output_stride,
<del> FLAGS.decoder_use_separable_conv, FLAGS.logits_kernel_size,
<del> FLAGS.model_variant, FLAGS.depth_multiplier, FLAGS.divisible_by,
<del> FLAGS.prediction_with_upsampled_logits, dense_prediction_cell_config,
<del> FLAGS.nas_stem_output_num_conv_filters, FLAGS.use_bounded_activation)
<add> FLAGS.aspp_with_separable_conv,
<add> FLAGS.multi_grid,
<add> decoder_output_stride,
<add> FLAGS.decoder_use_separable_conv,
<add> FLAGS.logits_kernel_size,
<add> FLAGS.model_variant,
<add> FLAGS.depth_multiplier,
<add> FLAGS.divisible_by,
<add> FLAGS.prediction_with_upsampled_logits,
<add> dense_prediction_cell_config,
<add> nas_architecture_options,
<add> FLAGS.use_bounded_activation,
<add> FLAGS.aspp_with_concat_projection,
<add> FLAGS.aspp_with_squeeze_and_excitation,
<add> FLAGS.aspp_convs_filters,
<add> FLAGS.decoder_use_sum_merge,
<add> FLAGS.decoder_filters,
<add> FLAGS.decoder_output_is_logits,
<add> FLAGS.image_se_uses_qsigmoid,
<add> label_weights,
<add> 'None',
<add> FLAGS.batch_norm_decay)
<ide>
<ide> def __deepcopy__(self, memo):
<ide> return ModelOptions(copy.deepcopy(self.outputs_to_num_classes),
<ide><path>research/deeplab/core/conv2d_ws.py
<add># Lint as: python2, python3
<add># Copyright 2019 The TensorFlow Authors All Rights Reserved.
<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>"""Augment slim.conv2d with optional Weight Standardization (WS).
<add>
<add>WS is a normalization method to accelerate micro-batch training. When used with
<add>Group Normalization and trained with 1 image/GPU, WS is able to match or
<add>outperform the performances of BN trained with large batch sizes.
<add>[1] Siyuan Qiao, Huiyu Wang, Chenxi Liu, Wei Shen, Alan Yuille
<add> Weight Standardization. arXiv:1903.10520
<add>[2] Lei Huang, Xianglong Liu, Yang Liu, Bo Lang, Dacheng Tao
<add> Centered Weight Normalization in Accelerating Training of Deep Neural
<add> Networks. ICCV 2017
<add>"""
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import tensorflow as tf
<add>from tensorflow.contrib import framework as contrib_framework
<add>from tensorflow.contrib import layers as contrib_layers
<add>
<add>from tensorflow.contrib.layers.python.layers import layers
<add>from tensorflow.contrib.layers.python.layers import utils
<add>
<add>
<add>class Conv2D(tf.keras.layers.Conv2D, tf.layers.Layer):
<add> """2D convolution layer (e.g. spatial convolution over images).
<add>
<add> This layer creates a convolution kernel that is convolved
<add> (actually cross-correlated) with the layer input to produce a tensor of
<add> outputs. If `use_bias` is True (and a `bias_initializer` is provided),
<add> a bias vector is created and added to the outputs. Finally, if
<add> `activation` is not `None`, it is applied to the outputs as well.
<add> """
<add>
<add> def __init__(self,
<add> filters,
<add> kernel_size,
<add> strides=(1, 1),
<add> padding='valid',
<add> data_format='channels_last',
<add> dilation_rate=(1, 1),
<add> activation=None,
<add> use_bias=True,
<add> kernel_initializer=None,
<add> bias_initializer=tf.zeros_initializer(),
<add> kernel_regularizer=None,
<add> bias_regularizer=None,
<add> use_weight_standardization=False,
<add> activity_regularizer=None,
<add> kernel_constraint=None,
<add> bias_constraint=None,
<add> trainable=True,
<add> name=None,
<add> **kwargs):
<add> """Constructs the 2D convolution layer.
<add>
<add> Args:
<add> filters: Integer, the dimensionality of the output space (i.e. the number
<add> of filters in the convolution).
<add> kernel_size: An integer or tuple/list of 2 integers, specifying the height
<add> and width of the 2D convolution window. Can be a single integer to
<add> specify the same value for all spatial dimensions.
<add> strides: An integer or tuple/list of 2 integers, specifying the strides of
<add> the convolution along the height and width. Can be a single integer to
<add> specify the same value for all spatial dimensions. Specifying any stride
<add> value != 1 is incompatible with specifying any `dilation_rate` value !=
<add> 1.
<add> padding: One of `"valid"` or `"same"` (case-insensitive).
<add> data_format: A string, one of `channels_last` (default) or
<add> `channels_first`. The ordering of the dimensions in the inputs.
<add> `channels_last` corresponds to inputs with shape `(batch, height, width,
<add> channels)` while `channels_first` corresponds to inputs with shape
<add> `(batch, channels, height, width)`.
<add> dilation_rate: An integer or tuple/list of 2 integers, specifying the
<add> dilation rate to use for dilated convolution. Can be a single integer to
<add> specify the same value for all spatial dimensions. Currently, specifying
<add> any `dilation_rate` value != 1 is incompatible with specifying any
<add> stride value != 1.
<add> activation: Activation function. Set it to None to maintain a linear
<add> activation.
<add> use_bias: Boolean, whether the layer uses a bias.
<add> kernel_initializer: An initializer for the convolution kernel.
<add> bias_initializer: An initializer for the bias vector. If None, the default
<add> initializer will be used.
<add> kernel_regularizer: Optional regularizer for the convolution kernel.
<add> bias_regularizer: Optional regularizer for the bias vector.
<add> use_weight_standardization: Boolean, whether the layer uses weight
<add> standardization.
<add> activity_regularizer: Optional regularizer function for the output.
<add> kernel_constraint: Optional projection function to be applied to the
<add> kernel after being updated by an `Optimizer` (e.g. used to implement
<add> norm constraints or value constraints for layer weights). The function
<add> must take as input the unprojected variable and must return the
<add> projected variable (which must have the same shape). Constraints are not
<add> safe to use when doing asynchronous distributed training.
<add> bias_constraint: Optional projection function to be applied to the bias
<add> after being updated by an `Optimizer`.
<add> trainable: Boolean, if `True` also add variables to the graph collection
<add> `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).
<add> name: A string, the name of the layer.
<add> **kwargs: Arbitrary keyword arguments passed to tf.keras.layers.Conv2D
<add> """
<add>
<add> super(Conv2D, self).__init__(
<add> filters=filters,
<add> kernel_size=kernel_size,
<add> strides=strides,
<add> padding=padding,
<add> data_format=data_format,
<add> dilation_rate=dilation_rate,
<add> activation=activation,
<add> use_bias=use_bias,
<add> kernel_initializer=kernel_initializer,
<add> bias_initializer=bias_initializer,
<add> kernel_regularizer=kernel_regularizer,
<add> bias_regularizer=bias_regularizer,
<add> activity_regularizer=activity_regularizer,
<add> kernel_constraint=kernel_constraint,
<add> bias_constraint=bias_constraint,
<add> trainable=trainable,
<add> name=name,
<add> **kwargs)
<add> self.use_weight_standardization = use_weight_standardization
<add>
<add> def call(self, inputs):
<add> if self.use_weight_standardization:
<add> mean, var = tf.nn.moments(self.kernel, [0, 1, 2], keep_dims=True)
<add> kernel = (self.kernel - mean) / tf.sqrt(var + 1e-5)
<add> outputs = self._convolution_op(inputs, kernel)
<add> else:
<add> outputs = self._convolution_op(inputs, self.kernel)
<add>
<add> if self.use_bias:
<add> if self.data_format == 'channels_first':
<add> if self.rank == 1:
<add> # tf.nn.bias_add does not accept a 1D input tensor.
<add> bias = tf.reshape(self.bias, (1, self.filters, 1))
<add> outputs += bias
<add> else:
<add> outputs = tf.nn.bias_add(outputs, self.bias, data_format='NCHW')
<add> else:
<add> outputs = tf.nn.bias_add(outputs, self.bias, data_format='NHWC')
<add>
<add> if self.activation is not None:
<add> return self.activation(outputs)
<add> return outputs
<add>
<add>
<add>@contrib_framework.add_arg_scope
<add>def conv2d(inputs,
<add> num_outputs,
<add> kernel_size,
<add> stride=1,
<add> padding='SAME',
<add> data_format=None,
<add> rate=1,
<add> activation_fn=tf.nn.relu,
<add> normalizer_fn=None,
<add> normalizer_params=None,
<add> weights_initializer=contrib_layers.xavier_initializer(),
<add> weights_regularizer=None,
<add> biases_initializer=tf.zeros_initializer(),
<add> biases_regularizer=None,
<add> use_weight_standardization=False,
<add> reuse=None,
<add> variables_collections=None,
<add> outputs_collections=None,
<add> trainable=True,
<add> scope=None):
<add> """Adds a 2D convolution followed by an optional batch_norm layer.
<add>
<add> `convolution` creates a variable called `weights`, representing the
<add> convolutional kernel, that is convolved (actually cross-correlated) with the
<add> `inputs` to produce a `Tensor` of activations. If a `normalizer_fn` is
<add> provided (such as `batch_norm`), it is then applied. Otherwise, if
<add> `normalizer_fn` is None and a `biases_initializer` is provided then a `biases`
<add> variable would be created and added the activations. Finally, if
<add> `activation_fn` is not `None`, it is applied to the activations as well.
<add>
<add> Performs atrous convolution with input stride/dilation rate equal to `rate`
<add> if a value > 1 for any dimension of `rate` is specified. In this case
<add> `stride` values != 1 are not supported.
<add>
<add> Args:
<add> inputs: A Tensor of rank N+2 of shape `[batch_size] + input_spatial_shape +
<add> [in_channels]` if data_format does not start with "NC" (default), or
<add> `[batch_size, in_channels] + input_spatial_shape` if data_format starts
<add> with "NC".
<add> num_outputs: Integer, the number of output filters.
<add> kernel_size: A sequence of N positive integers specifying the spatial
<add> dimensions of the filters. Can be a single integer to specify the same
<add> value for all spatial dimensions.
<add> stride: A sequence of N positive integers specifying the stride at which to
<add> compute output. Can be a single integer to specify the same value for all
<add> spatial dimensions. Specifying any `stride` value != 1 is incompatible
<add> with specifying any `rate` value != 1.
<add> padding: One of `"VALID"` or `"SAME"`.
<add> data_format: A string or None. Specifies whether the channel dimension of
<add> the `input` and output is the last dimension (default, or if `data_format`
<add> does not start with "NC"), or the second dimension (if `data_format`
<add> starts with "NC"). For N=1, the valid values are "NWC" (default) and
<add> "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". For
<add> N=3, the valid values are "NDHWC" (default) and "NCDHW".
<add> rate: A sequence of N positive integers specifying the dilation rate to use
<add> for atrous convolution. Can be a single integer to specify the same value
<add> for all spatial dimensions. Specifying any `rate` value != 1 is
<add> incompatible with specifying any `stride` value != 1.
<add> activation_fn: Activation function. The default value is a ReLU function.
<add> Explicitly set it to None to skip it and maintain a linear activation.
<add> normalizer_fn: Normalization function to use instead of `biases`. If
<add> `normalizer_fn` is provided then `biases_initializer` and
<add> `biases_regularizer` are ignored and `biases` are not created nor added.
<add> default set to None for no normalizer function
<add> normalizer_params: Normalization function parameters.
<add> weights_initializer: An initializer for the weights.
<add> weights_regularizer: Optional regularizer for the weights.
<add> biases_initializer: An initializer for the biases. If None skip biases.
<add> biases_regularizer: Optional regularizer for the biases.
<add> use_weight_standardization: Boolean, whether the layer uses weight
<add> standardization.
<add> reuse: Whether or not the layer and its variables should be reused. To be
<add> able to reuse the layer scope must be given.
<add> variables_collections: Optional list of collections for all the variables or
<add> a dictionary containing a different list of collection per variable.
<add> outputs_collections: Collection to add the outputs.
<add> trainable: If `True` also add variables to the graph collection
<add> `GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
<add> scope: Optional scope for `variable_scope`.
<add>
<add> Returns:
<add> A tensor representing the output of the operation.
<add>
<add> Raises:
<add> ValueError: If `data_format` is invalid.
<add> ValueError: Both 'rate' and `stride` are not uniformly 1.
<add> """
<add> if data_format not in [None, 'NWC', 'NCW', 'NHWC', 'NCHW', 'NDHWC', 'NCDHW']:
<add> raise ValueError('Invalid data_format: %r' % (data_format,))
<add>
<add> # pylint: disable=protected-access
<add> layer_variable_getter = layers._build_variable_getter({
<add> 'bias': 'biases',
<add> 'kernel': 'weights'
<add> })
<add> # pylint: enable=protected-access
<add> with tf.variable_scope(
<add> scope, 'Conv', [inputs], reuse=reuse,
<add> custom_getter=layer_variable_getter) as sc:
<add> inputs = tf.convert_to_tensor(inputs)
<add> input_rank = inputs.get_shape().ndims
<add>
<add> if input_rank != 4:
<add> raise ValueError('Convolution expects input with rank %d, got %d' %
<add> (4, input_rank))
<add>
<add> data_format = ('channels_first' if data_format and
<add> data_format.startswith('NC') else 'channels_last')
<add> layer = Conv2D(
<add> filters=num_outputs,
<add> kernel_size=kernel_size,
<add> strides=stride,
<add> padding=padding,
<add> data_format=data_format,
<add> dilation_rate=rate,
<add> activation=None,
<add> use_bias=not normalizer_fn and biases_initializer,
<add> kernel_initializer=weights_initializer,
<add> bias_initializer=biases_initializer,
<add> kernel_regularizer=weights_regularizer,
<add> bias_regularizer=biases_regularizer,
<add> use_weight_standardization=use_weight_standardization,
<add> activity_regularizer=None,
<add> trainable=trainable,
<add> name=sc.name,
<add> dtype=inputs.dtype.base_dtype,
<add> _scope=sc,
<add> _reuse=reuse)
<add> outputs = layer.apply(inputs)
<add>
<add> # Add variables to collections.
<add> # pylint: disable=protected-access
<add> layers._add_variable_to_collections(layer.kernel, variables_collections,
<add> 'weights')
<add> if layer.use_bias:
<add> layers._add_variable_to_collections(layer.bias, variables_collections,
<add> 'biases')
<add> # pylint: enable=protected-access
<add> if normalizer_fn is not None:
<add> normalizer_params = normalizer_params or {}
<add> outputs = normalizer_fn(outputs, **normalizer_params)
<add>
<add> if activation_fn is not None:
<add> outputs = activation_fn(outputs)
<add> return utils.collect_named_outputs(outputs_collections, sc.name, outputs)
<add>
<add>
<add>def conv2d_same(inputs, num_outputs, kernel_size, stride, rate=1, scope=None):
<add> """Strided 2-D convolution with 'SAME' padding.
<add>
<add> When stride > 1, then we do explicit zero-padding, followed by conv2d with
<add> 'VALID' padding.
<add>
<add> Note that
<add>
<add> net = conv2d_same(inputs, num_outputs, 3, stride=stride)
<add>
<add> is equivalent to
<add>
<add> net = conv2d(inputs, num_outputs, 3, stride=1, padding='SAME')
<add> net = subsample(net, factor=stride)
<add>
<add> whereas
<add>
<add> net = conv2d(inputs, num_outputs, 3, stride=stride, padding='SAME')
<add>
<add> is different when the input's height or width is even, which is why we add the
<add> current function. For more details, see ResnetUtilsTest.testConv2DSameEven().
<add>
<add> Args:
<add> inputs: A 4-D tensor of size [batch, height_in, width_in, channels].
<add> num_outputs: An integer, the number of output filters.
<add> kernel_size: An int with the kernel_size of the filters.
<add> stride: An integer, the output stride.
<add> rate: An integer, rate for atrous convolution.
<add> scope: Scope.
<add>
<add> Returns:
<add> output: A 4-D tensor of size [batch, height_out, width_out, channels] with
<add> the convolution output.
<add> """
<add> if stride == 1:
<add> return conv2d(
<add> inputs,
<add> num_outputs,
<add> kernel_size,
<add> stride=1,
<add> rate=rate,
<add> padding='SAME',
<add> scope=scope)
<add> else:
<add> kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)
<add> pad_total = kernel_size_effective - 1
<add> pad_beg = pad_total // 2
<add> pad_end = pad_total - pad_beg
<add> inputs = tf.pad(inputs,
<add> [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]])
<add> return conv2d(
<add> inputs,
<add> num_outputs,
<add> kernel_size,
<add> stride=stride,
<add> rate=rate,
<add> padding='VALID',
<add> scope=scope)
<ide><path>research/deeplab/core/conv2d_ws_test.py
<add># Lint as: python2, python3
<add># Copyright 2019 The TensorFlow Authors All Rights Reserved.
<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>"""Tests for conv2d_ws."""
<add>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import numpy as np
<add>import tensorflow as tf
<add>from tensorflow.contrib import framework as contrib_framework
<add>from tensorflow.contrib import layers as contrib_layers
<add>from deeplab.core import conv2d_ws
<add>
<add>
<add>class ConvolutionTest(tf.test.TestCase):
<add>
<add> def testInvalidShape(self):
<add> with self.cached_session():
<add> images_3d = tf.random_uniform((5, 6, 7, 9, 3), seed=1)
<add> with self.assertRaisesRegexp(
<add> ValueError, 'Convolution expects input with rank 4, got 5'):
<add> conv2d_ws.conv2d(images_3d, 32, 3)
<add>
<add> def testInvalidDataFormat(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> with self.assertRaisesRegexp(ValueError, 'data_format'):
<add> conv2d_ws.conv2d(images, 32, 3, data_format='CHWN')
<add>
<add> def testCreateConv(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = np.random.uniform(size=(5, height, width, 4)).astype(np.float32)
<add> output = conv2d_ws.conv2d(images, 32, [3, 3])
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(), [5, height, width, 32])
<add> weights = contrib_framework.get_variables_by_name('weights')[0]
<add> self.assertListEqual(weights.get_shape().as_list(), [3, 3, 4, 32])
<add> biases = contrib_framework.get_variables_by_name('biases')[0]
<add> self.assertListEqual(biases.get_shape().as_list(), [32])
<add>
<add> def testCreateConvWithWS(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = np.random.uniform(size=(5, height, width, 4)).astype(np.float32)
<add> output = conv2d_ws.conv2d(
<add> images, 32, [3, 3], use_weight_standardization=True)
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(), [5, height, width, 32])
<add> weights = contrib_framework.get_variables_by_name('weights')[0]
<add> self.assertListEqual(weights.get_shape().as_list(), [3, 3, 4, 32])
<add> biases = contrib_framework.get_variables_by_name('biases')[0]
<add> self.assertListEqual(biases.get_shape().as_list(), [32])
<add>
<add> def testCreateConvNCHW(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = np.random.uniform(size=(5, 4, height, width)).astype(np.float32)
<add> output = conv2d_ws.conv2d(images, 32, [3, 3], data_format='NCHW')
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(), [5, 32, height, width])
<add> weights = contrib_framework.get_variables_by_name('weights')[0]
<add> self.assertListEqual(weights.get_shape().as_list(), [3, 3, 4, 32])
<add> biases = contrib_framework.get_variables_by_name('biases')[0]
<add> self.assertListEqual(biases.get_shape().as_list(), [32])
<add>
<add> def testCreateSquareConv(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> output = conv2d_ws.conv2d(images, 32, 3)
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(), [5, height, width, 32])
<add>
<add> def testCreateConvWithTensorShape(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> output = conv2d_ws.conv2d(images, 32, images.get_shape()[1:3])
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(), [5, height, width, 32])
<add>
<add> def testCreateFullyConv(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 32), seed=1)
<add> output = conv2d_ws.conv2d(
<add> images, 64, images.get_shape()[1:3], padding='VALID')
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(), [5, 1, 1, 64])
<add> biases = contrib_framework.get_variables_by_name('biases')[0]
<add> self.assertListEqual(biases.get_shape().as_list(), [64])
<add>
<add> def testFullyConvWithCustomGetter(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> called = [0]
<add>
<add> def custom_getter(getter, *args, **kwargs):
<add> called[0] += 1
<add> return getter(*args, **kwargs)
<add>
<add> with tf.variable_scope('test', custom_getter=custom_getter):
<add> images = tf.random_uniform((5, height, width, 32), seed=1)
<add> conv2d_ws.conv2d(images, 64, images.get_shape()[1:3])
<add> self.assertEqual(called[0], 2) # Custom getter called twice.
<add>
<add> def testCreateVerticalConv(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 4), seed=1)
<add> output = conv2d_ws.conv2d(images, 32, [3, 1])
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(), [5, height, width, 32])
<add> weights = contrib_framework.get_variables_by_name('weights')[0]
<add> self.assertListEqual(weights.get_shape().as_list(), [3, 1, 4, 32])
<add> biases = contrib_framework.get_variables_by_name('biases')[0]
<add> self.assertListEqual(biases.get_shape().as_list(), [32])
<add>
<add> def testCreateHorizontalConv(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 4), seed=1)
<add> output = conv2d_ws.conv2d(images, 32, [1, 3])
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(), [5, height, width, 32])
<add> weights = contrib_framework.get_variables_by_name('weights')[0]
<add> self.assertListEqual(weights.get_shape().as_list(), [1, 3, 4, 32])
<add>
<add> def testCreateConvWithStride(self):
<add> height, width = 6, 8
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> output = conv2d_ws.conv2d(images, 32, [3, 3], stride=2)
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(),
<add> [5, height / 2, width / 2, 32])
<add>
<add> def testCreateConvCreatesWeightsAndBiasesVars(self):
<add> height, width = 7, 9
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> with self.cached_session():
<add> self.assertFalse(contrib_framework.get_variables('conv1/weights'))
<add> self.assertFalse(contrib_framework.get_variables('conv1/biases'))
<add> conv2d_ws.conv2d(images, 32, [3, 3], scope='conv1')
<add> self.assertTrue(contrib_framework.get_variables('conv1/weights'))
<add> self.assertTrue(contrib_framework.get_variables('conv1/biases'))
<add>
<add> def testCreateConvWithScope(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> output = conv2d_ws.conv2d(images, 32, [3, 3], scope='conv1')
<add> self.assertEqual(output.op.name, 'conv1/Relu')
<add>
<add> def testCreateConvWithCollection(self):
<add> height, width = 7, 9
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> with tf.name_scope('fe'):
<add> conv = conv2d_ws.conv2d(
<add> images, 32, [3, 3], outputs_collections='outputs', scope='Conv')
<add> output_collected = tf.get_collection('outputs')[0]
<add> self.assertEqual(output_collected.aliases, ['Conv'])
<add> self.assertEqual(output_collected, conv)
<add>
<add> def testCreateConvWithoutActivation(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> output = conv2d_ws.conv2d(images, 32, [3, 3], activation_fn=None)
<add> self.assertEqual(output.op.name, 'Conv/BiasAdd')
<add>
<add> def testCreateConvValid(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> output = conv2d_ws.conv2d(images, 32, [3, 3], padding='VALID')
<add> self.assertListEqual(output.get_shape().as_list(), [5, 5, 7, 32])
<add>
<add> def testCreateConvWithWD(self):
<add> height, width = 7, 9
<add> weight_decay = 0.01
<add> with self.cached_session() as sess:
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> regularizer = contrib_layers.l2_regularizer(weight_decay)
<add> conv2d_ws.conv2d(images, 32, [3, 3], weights_regularizer=regularizer)
<add> l2_loss = tf.nn.l2_loss(
<add> contrib_framework.get_variables_by_name('weights')[0])
<add> wd = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)[0]
<add> self.assertEqual(wd.op.name, 'Conv/kernel/Regularizer/l2_regularizer')
<add> sess.run(tf.global_variables_initializer())
<add> self.assertAlmostEqual(sess.run(wd), weight_decay * l2_loss.eval())
<add>
<add> def testCreateConvNoRegularizers(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> conv2d_ws.conv2d(images, 32, [3, 3])
<add> self.assertEqual(
<add> tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES), [])
<add>
<add> def testReuseVars(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> conv2d_ws.conv2d(images, 32, [3, 3], scope='conv1')
<add> self.assertEqual(len(contrib_framework.get_variables()), 2)
<add> conv2d_ws.conv2d(images, 32, [3, 3], scope='conv1', reuse=True)
<add> self.assertEqual(len(contrib_framework.get_variables()), 2)
<add>
<add> def testNonReuseVars(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> conv2d_ws.conv2d(images, 32, [3, 3])
<add> self.assertEqual(len(contrib_framework.get_variables()), 2)
<add> conv2d_ws.conv2d(images, 32, [3, 3])
<add> self.assertEqual(len(contrib_framework.get_variables()), 4)
<add>
<add> def testReuseConvWithWD(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> weight_decay = contrib_layers.l2_regularizer(0.01)
<add> with contrib_framework.arg_scope([conv2d_ws.conv2d],
<add> weights_regularizer=weight_decay):
<add> conv2d_ws.conv2d(images, 32, [3, 3], scope='conv1')
<add> self.assertEqual(len(contrib_framework.get_variables()), 2)
<add> self.assertEqual(
<add> len(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)), 1)
<add> conv2d_ws.conv2d(images, 32, [3, 3], scope='conv1', reuse=True)
<add> self.assertEqual(len(contrib_framework.get_variables()), 2)
<add> self.assertEqual(
<add> len(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)), 1)
<add>
<add> def testConvWithBatchNorm(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 32), seed=1)
<add> with contrib_framework.arg_scope([conv2d_ws.conv2d],
<add> normalizer_fn=contrib_layers.batch_norm,
<add> normalizer_params={'decay': 0.9}):
<add> net = conv2d_ws.conv2d(images, 32, [3, 3])
<add> net = conv2d_ws.conv2d(net, 32, [3, 3])
<add> self.assertEqual(len(contrib_framework.get_variables()), 8)
<add> self.assertEqual(
<add> len(contrib_framework.get_variables('Conv/BatchNorm')), 3)
<add> self.assertEqual(
<add> len(contrib_framework.get_variables('Conv_1/BatchNorm')), 3)
<add>
<add> def testReuseConvWithBatchNorm(self):
<add> height, width = 7, 9
<add> with self.cached_session():
<add> images = tf.random_uniform((5, height, width, 32), seed=1)
<add> with contrib_framework.arg_scope([conv2d_ws.conv2d],
<add> normalizer_fn=contrib_layers.batch_norm,
<add> normalizer_params={'decay': 0.9}):
<add> net = conv2d_ws.conv2d(images, 32, [3, 3], scope='Conv')
<add> net = conv2d_ws.conv2d(net, 32, [3, 3], scope='Conv', reuse=True)
<add> self.assertEqual(len(contrib_framework.get_variables()), 4)
<add> self.assertEqual(
<add> len(contrib_framework.get_variables('Conv/BatchNorm')), 3)
<add> self.assertEqual(
<add> len(contrib_framework.get_variables('Conv_1/BatchNorm')), 0)
<add>
<add> def testCreateConvCreatesWeightsAndBiasesVarsWithRateTwo(self):
<add> height, width = 7, 9
<add> images = tf.random_uniform((5, height, width, 3), seed=1)
<add> with self.cached_session():
<add> self.assertFalse(contrib_framework.get_variables('conv1/weights'))
<add> self.assertFalse(contrib_framework.get_variables('conv1/biases'))
<add> conv2d_ws.conv2d(images, 32, [3, 3], rate=2, scope='conv1')
<add> self.assertTrue(contrib_framework.get_variables('conv1/weights'))
<add> self.assertTrue(contrib_framework.get_variables('conv1/biases'))
<add>
<add> def testOutputSizeWithRateTwoSamePadding(self):
<add> num_filters = 32
<add> input_size = [5, 10, 12, 3]
<add> expected_size = [5, 10, 12, num_filters]
<add>
<add> images = tf.random_uniform(input_size, seed=1)
<add> output = conv2d_ws.conv2d(
<add> images, num_filters, [3, 3], rate=2, padding='SAME')
<add> self.assertListEqual(list(output.get_shape().as_list()), expected_size)
<add> with self.cached_session() as sess:
<add> sess.run(tf.global_variables_initializer())
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(list(output.eval().shape), expected_size)
<add>
<add> def testOutputSizeWithRateTwoValidPadding(self):
<add> num_filters = 32
<add> input_size = [5, 10, 12, 3]
<add> expected_size = [5, 6, 8, num_filters]
<add>
<add> images = tf.random_uniform(input_size, seed=1)
<add> output = conv2d_ws.conv2d(
<add> images, num_filters, [3, 3], rate=2, padding='VALID')
<add> self.assertListEqual(list(output.get_shape().as_list()), expected_size)
<add> with self.cached_session() as sess:
<add> sess.run(tf.global_variables_initializer())
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(list(output.eval().shape), expected_size)
<add>
<add> def testOutputSizeWithRateTwoThreeValidPadding(self):
<add> num_filters = 32
<add> input_size = [5, 10, 12, 3]
<add> expected_size = [5, 6, 6, num_filters]
<add>
<add> images = tf.random_uniform(input_size, seed=1)
<add> output = conv2d_ws.conv2d(
<add> images, num_filters, [3, 3], rate=[2, 3], padding='VALID')
<add> self.assertListEqual(list(output.get_shape().as_list()), expected_size)
<add> with self.cached_session() as sess:
<add> sess.run(tf.global_variables_initializer())
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(list(output.eval().shape), expected_size)
<add>
<add> def testDynamicOutputSizeWithRateOneValidPadding(self):
<add> num_filters = 32
<add> input_size = [5, 9, 11, 3]
<add> expected_size = [None, None, None, num_filters]
<add> expected_size_dynamic = [5, 7, 9, num_filters]
<add>
<add> with self.cached_session():
<add> images = tf.placeholder(np.float32, [None, None, None, input_size[3]])
<add> output = conv2d_ws.conv2d(
<add> images, num_filters, [3, 3], rate=1, padding='VALID')
<add> tf.global_variables_initializer().run()
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(), expected_size)
<add> eval_output = output.eval({images: np.zeros(input_size, np.float32)})
<add> self.assertListEqual(list(eval_output.shape), expected_size_dynamic)
<add>
<add> def testDynamicOutputSizeWithRateOneValidPaddingNCHW(self):
<add> if tf.test.is_gpu_available(cuda_only=True):
<add> num_filters = 32
<add> input_size = [5, 3, 9, 11]
<add> expected_size = [None, num_filters, None, None]
<add> expected_size_dynamic = [5, num_filters, 7, 9]
<add>
<add> with self.session(use_gpu=True):
<add> images = tf.placeholder(np.float32, [None, input_size[1], None, None])
<add> output = conv2d_ws.conv2d(
<add> images,
<add> num_filters, [3, 3],
<add> rate=1,
<add> padding='VALID',
<add> data_format='NCHW')
<add> tf.global_variables_initializer().run()
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(), expected_size)
<add> eval_output = output.eval({images: np.zeros(input_size, np.float32)})
<add> self.assertListEqual(list(eval_output.shape), expected_size_dynamic)
<add>
<add> def testDynamicOutputSizeWithRateTwoValidPadding(self):
<add> num_filters = 32
<add> input_size = [5, 9, 11, 3]
<add> expected_size = [None, None, None, num_filters]
<add> expected_size_dynamic = [5, 5, 7, num_filters]
<add>
<add> with self.cached_session():
<add> images = tf.placeholder(np.float32, [None, None, None, input_size[3]])
<add> output = conv2d_ws.conv2d(
<add> images, num_filters, [3, 3], rate=2, padding='VALID')
<add> tf.global_variables_initializer().run()
<add> self.assertEqual(output.op.name, 'Conv/Relu')
<add> self.assertListEqual(output.get_shape().as_list(), expected_size)
<add> eval_output = output.eval({images: np.zeros(input_size, np.float32)})
<add> self.assertListEqual(list(eval_output.shape), expected_size_dynamic)
<add>
<add> def testWithScope(self):
<add> num_filters = 32
<add> input_size = [5, 9, 11, 3]
<add> expected_size = [5, 5, 7, num_filters]
<add>
<add> images = tf.random_uniform(input_size, seed=1)
<add> output = conv2d_ws.conv2d(
<add> images, num_filters, [3, 3], rate=2, padding='VALID', scope='conv7')
<add> with self.cached_session() as sess:
<add> sess.run(tf.global_variables_initializer())
<add> self.assertEqual(output.op.name, 'conv7/Relu')
<add> self.assertListEqual(list(output.eval().shape), expected_size)
<add>
<add> def testWithScopeWithoutActivation(self):
<add> num_filters = 32
<add> input_size = [5, 9, 11, 3]
<add> expected_size = [5, 5, 7, num_filters]
<add>
<add> images = tf.random_uniform(input_size, seed=1)
<add> output = conv2d_ws.conv2d(
<add> images,
<add> num_filters, [3, 3],
<add> rate=2,
<add> padding='VALID',
<add> activation_fn=None,
<add> scope='conv7')
<add> with self.cached_session() as sess:
<add> sess.run(tf.global_variables_initializer())
<add> self.assertEqual(output.op.name, 'conv7/BiasAdd')
<add> self.assertListEqual(list(output.eval().shape), expected_size)
<add>
<add>
<add>if __name__ == '__main__':
<add> tf.test.main()
<ide><path>research/deeplab/core/feature_extractor.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> # ==============================================================================
<ide>
<ide> """Extracts features for different models."""
<add>import copy
<ide> import functools
<add>
<ide> import tensorflow as tf
<add>from tensorflow.contrib import slim as contrib_slim
<ide>
<ide> from deeplab.core import nas_network
<ide> from deeplab.core import resnet_v1_beta
<ide> from deeplab.core import xception
<del>from tensorflow.contrib.slim.nets import resnet_utils
<add>from nets.mobilenet import conv_blocks
<add>from nets.mobilenet import mobilenet
<ide> from nets.mobilenet import mobilenet_v2
<add>from nets.mobilenet import mobilenet_v3
<ide>
<del>
<del>slim = tf.contrib.slim
<add>slim = contrib_slim
<ide>
<ide> # Default end point for MobileNetv2.
<ide> _MOBILENET_V2_FINAL_ENDPOINT = 'layer_18'
<add>_MOBILENET_V3_LARGE_FINAL_ENDPOINT = 'layer_17'
<add>_MOBILENET_V3_SMALL_FINAL_ENDPOINT = 'layer_13'
<ide>
<ide>
<ide> def _mobilenet_v2(net,
<ide> depth_multiplier,
<ide> output_stride,
<add> conv_defs=None,
<ide> divisible_by=None,
<ide> reuse=None,
<ide> scope=None,
<ide> def _mobilenet_v2(net,
<ide> if necessary to prevent the network from reducing the spatial resolution
<ide> of the activation maps. Allowed values are 8 (accurate fully convolutional
<ide> mode), 16 (fast fully convolutional mode), 32 (classification mode).
<add> conv_defs: MobileNet con def.
<ide> divisible_by: None (use default setting) or an integer that ensures all
<ide> layers # channels will be divisible by this number. Used in MobileNet.
<ide> reuse: Reuse model variables.
<ide> def _mobilenet_v2(net,
<ide> """
<ide> if divisible_by is None:
<ide> divisible_by = 8 if depth_multiplier == 1.0 else 1
<add> if conv_defs is None:
<add> conv_defs = mobilenet_v2.V2_DEF
<ide> with tf.variable_scope(
<ide> scope, 'MobilenetV2', [net], reuse=reuse) as scope:
<ide> return mobilenet_v2.mobilenet_base(
<ide> net,
<del> conv_defs=mobilenet_v2.V2_DEF,
<add> conv_defs=conv_defs,
<ide> depth_multiplier=depth_multiplier,
<ide> min_depth=8 if depth_multiplier == 1.0 else 1,
<ide> divisible_by=divisible_by,
<ide> def _mobilenet_v2(net,
<ide> scope=scope)
<ide>
<ide>
<add>def _mobilenet_v3(net,
<add> depth_multiplier,
<add> output_stride,
<add> conv_defs=None,
<add> divisible_by=None,
<add> reuse=None,
<add> scope=None,
<add> final_endpoint=None):
<add> """Auxiliary function to build mobilenet v3.
<add>
<add> Args:
<add> net: Input tensor of shape [batch_size, height, width, channels].
<add> depth_multiplier: Float multiplier for the depth (number of channels)
<add> for all convolution ops. The value must be greater than zero. Typical
<add> usage will be to set this value in (0, 1) to reduce the number of
<add> parameters or computation cost of the model.
<add> output_stride: An integer that specifies the requested ratio of input to
<add> output spatial resolution. If not None, then we invoke atrous convolution
<add> if necessary to prevent the network from reducing the spatial resolution
<add> of the activation maps. Allowed values are 8 (accurate fully convolutional
<add> mode), 16 (fast fully convolutional mode), 32 (classification mode).
<add> conv_defs: A list of ConvDef namedtuples specifying the net architecture.
<add> divisible_by: None (use default setting) or an integer that ensures all
<add> layers # channels will be divisible by this number. Used in MobileNet.
<add> reuse: Reuse model variables.
<add> scope: Optional variable scope.
<add> final_endpoint: The endpoint to construct the network up to.
<add>
<add> Returns:
<add> net: The output tensor.
<add> end_points: A set of activations for external use.
<add>
<add> Raises:
<add> ValueError: If conv_defs or final_endpoint is not specified.
<add> """
<add> del divisible_by
<add> with tf.variable_scope(
<add> scope, 'MobilenetV3', [net], reuse=reuse) as scope:
<add> if conv_defs is None:
<add> raise ValueError('conv_defs must be specified for mobilenet v3.')
<add> if final_endpoint is None:
<add> raise ValueError('Final endpoint must be specified for mobilenet v3.')
<add> net, end_points = mobilenet_v3.mobilenet_base(
<add> net,
<add> depth_multiplier=depth_multiplier,
<add> conv_defs=conv_defs,
<add> output_stride=output_stride,
<add> final_endpoint=final_endpoint,
<add> scope=scope)
<add>
<add> return net, end_points
<add>
<add>
<add>def mobilenet_v3_large_seg(net,
<add> depth_multiplier,
<add> output_stride,
<add> divisible_by=None,
<add> reuse=None,
<add> scope=None,
<add> final_endpoint=None):
<add> """Final mobilenet v3 large model for segmentation task."""
<add> del divisible_by
<add> del final_endpoint
<add> conv_defs = copy.deepcopy(mobilenet_v3.V3_LARGE)
<add>
<add> # Reduce the filters by a factor of 2 in the last block.
<add> for layer, expansion in [(13, 336), (14, 480), (15, 480), (16, None)]:
<add> conv_defs['spec'][layer].params['num_outputs'] /= 2
<add> # Update expansion size
<add> if expansion is not None:
<add> factor = expansion / conv_defs['spec'][layer - 1].params['num_outputs']
<add> conv_defs['spec'][layer].params[
<add> 'expansion_size'] = mobilenet_v3.expand_input(factor)
<add>
<add> return _mobilenet_v3(
<add> net,
<add> depth_multiplier=depth_multiplier,
<add> output_stride=output_stride,
<add> divisible_by=8,
<add> conv_defs=conv_defs,
<add> reuse=reuse,
<add> scope=scope,
<add> final_endpoint=_MOBILENET_V3_LARGE_FINAL_ENDPOINT)
<add>
<add>
<add>def mobilenet_v3_small_seg(net,
<add> depth_multiplier,
<add> output_stride,
<add> divisible_by=None,
<add> reuse=None,
<add> scope=None,
<add> final_endpoint=None):
<add> """Final mobilenet v3 small model for segmentation task."""
<add> del divisible_by
<add> del final_endpoint
<add> conv_defs = copy.deepcopy(mobilenet_v3.V3_SMALL)
<add>
<add> # Reduce the filters by a factor of 2 in the last block.
<add> for layer, expansion in [(9, 144), (10, 288), (11, 288), (12, None)]:
<add> conv_defs['spec'][layer].params['num_outputs'] /= 2
<add> # Update expansion size
<add> if expansion is not None:
<add> factor = expansion / conv_defs['spec'][layer - 1].params['num_outputs']
<add> conv_defs['spec'][layer].params[
<add> 'expansion_size'] = mobilenet_v3.expand_input(factor)
<add>
<add> return _mobilenet_v3(
<add> net,
<add> depth_multiplier=depth_multiplier,
<add> output_stride=output_stride,
<add> divisible_by=8,
<add> conv_defs=conv_defs,
<add> reuse=reuse,
<add> scope=scope,
<add> final_endpoint=_MOBILENET_V3_SMALL_FINAL_ENDPOINT)
<add>
<add>
<ide> # A map from network name to network function.
<ide> networks_map = {
<ide> 'mobilenet_v2': _mobilenet_v2,
<add> 'mobilenet_v3_large_seg': mobilenet_v3_large_seg,
<add> 'mobilenet_v3_small_seg': mobilenet_v3_small_seg,
<add> 'resnet_v1_18': resnet_v1_beta.resnet_v1_18,
<add> 'resnet_v1_18_beta': resnet_v1_beta.resnet_v1_18_beta,
<ide> 'resnet_v1_50': resnet_v1_beta.resnet_v1_50,
<ide> 'resnet_v1_50_beta': resnet_v1_beta.resnet_v1_50_beta,
<ide> 'resnet_v1_101': resnet_v1_beta.resnet_v1_101,
<ide> def _mobilenet_v2(net,
<ide> 'nas_hnasnet': nas_network.hnasnet,
<ide> }
<ide>
<add>
<add>def mobilenet_v2_arg_scope(is_training=True,
<add> weight_decay=0.00004,
<add> stddev=0.09,
<add> activation=tf.nn.relu6,
<add> bn_decay=0.997,
<add> bn_epsilon=None,
<add> bn_renorm=None):
<add> """Defines the default MobilenetV2 arg scope.
<add>
<add> Args:
<add> is_training: Whether or not we're training the model. If this is set to None
<add> is_training parameter in batch_norm is not set. Please note that this also
<add> sets the is_training parameter in dropout to None.
<add> weight_decay: The weight decay to use for regularizing the model.
<add> stddev: Standard deviation for initialization, if negative uses xavier.
<add> activation: If True, a modified activation is used (initialized ~ReLU6).
<add> bn_decay: decay for the batch norm moving averages.
<add> bn_epsilon: batch normalization epsilon.
<add> bn_renorm: whether to use batchnorm renormalization
<add>
<add> Returns:
<add> An `arg_scope` to use for the mobilenet v1 model.
<add> """
<add> batch_norm_params = {
<add> 'center': True,
<add> 'scale': True,
<add> 'decay': bn_decay,
<add> }
<add> if bn_epsilon is not None:
<add> batch_norm_params['epsilon'] = bn_epsilon
<add> if is_training is not None:
<add> batch_norm_params['is_training'] = is_training
<add> if bn_renorm is not None:
<add> batch_norm_params['renorm'] = bn_renorm
<add> dropout_params = {}
<add> if is_training is not None:
<add> dropout_params['is_training'] = is_training
<add>
<add> instance_norm_params = {
<add> 'center': True,
<add> 'scale': True,
<add> 'epsilon': 0.001,
<add> }
<add>
<add> if stddev < 0:
<add> weight_intitializer = slim.initializers.xavier_initializer()
<add> else:
<add> weight_intitializer = tf.truncated_normal_initializer(stddev=stddev)
<add>
<add> # Set weight_decay for weights in Conv and FC layers.
<add> with slim.arg_scope(
<add> [slim.conv2d, slim.fully_connected, slim.separable_conv2d],
<add> weights_initializer=weight_intitializer,
<add> activation_fn=activation,
<add> normalizer_fn=slim.batch_norm), \
<add> slim.arg_scope(
<add> [conv_blocks.expanded_conv], normalizer_fn=slim.batch_norm), \
<add> slim.arg_scope([mobilenet.apply_activation], activation_fn=activation),\
<add> slim.arg_scope([slim.batch_norm], **batch_norm_params), \
<add> slim.arg_scope([mobilenet.mobilenet_base, mobilenet.mobilenet],
<add> is_training=is_training),\
<add> slim.arg_scope([slim.dropout], **dropout_params), \
<add> slim.arg_scope([slim.instance_norm], **instance_norm_params), \
<add> slim.arg_scope([slim.conv2d], \
<add> weights_regularizer=slim.l2_regularizer(weight_decay)), \
<add> slim.arg_scope([slim.separable_conv2d], weights_regularizer=None), \
<add> slim.arg_scope([slim.conv2d, slim.separable_conv2d], padding='SAME') as s:
<add> return s
<add>
<add>
<ide> # A map from network name to network arg scope.
<ide> arg_scopes_map = {
<ide> 'mobilenet_v2': mobilenet_v2.training_scope,
<del> 'resnet_v1_50': resnet_utils.resnet_arg_scope,
<del> 'resnet_v1_50_beta': resnet_utils.resnet_arg_scope,
<del> 'resnet_v1_101': resnet_utils.resnet_arg_scope,
<del> 'resnet_v1_101_beta': resnet_utils.resnet_arg_scope,
<add> 'mobilenet_v3_large_seg': mobilenet_v2_arg_scope,
<add> 'mobilenet_v3_small_seg': mobilenet_v2_arg_scope,
<add> 'resnet_v1_18': resnet_v1_beta.resnet_arg_scope,
<add> 'resnet_v1_18_beta': resnet_v1_beta.resnet_arg_scope,
<add> 'resnet_v1_50': resnet_v1_beta.resnet_arg_scope,
<add> 'resnet_v1_50_beta': resnet_v1_beta.resnet_arg_scope,
<add> 'resnet_v1_101': resnet_v1_beta.resnet_arg_scope,
<add> 'resnet_v1_101_beta': resnet_v1_beta.resnet_arg_scope,
<ide> 'xception_41': xception.xception_arg_scope,
<ide> 'xception_65': xception.xception_arg_scope,
<ide> 'xception_71': xception.xception_arg_scope,
<ide> def _mobilenet_v2(net,
<ide> 'mobilenet_v2': {
<ide> DECODER_END_POINTS: {
<ide> 4: ['layer_4/depthwise_output'],
<add> 8: ['layer_7/depthwise_output'],
<add> 16: ['layer_14/depthwise_output'],
<add> },
<add> },
<add> 'mobilenet_v3_large_seg': {
<add> DECODER_END_POINTS: {
<add> 4: ['layer_4/depthwise_output'],
<add> 8: ['layer_7/depthwise_output'],
<add> 16: ['layer_13/depthwise_output'],
<add> },
<add> },
<add> 'mobilenet_v3_small_seg': {
<add> DECODER_END_POINTS: {
<add> 4: ['layer_2/depthwise_output'],
<add> 8: ['layer_4/depthwise_output'],
<add> 16: ['layer_9/depthwise_output'],
<add> },
<add> },
<add> 'resnet_v1_18': {
<add> DECODER_END_POINTS: {
<add> 4: ['block1/unit_1/lite_bottleneck_v1/conv2'],
<add> 8: ['block2/unit_1/lite_bottleneck_v1/conv2'],
<add> 16: ['block3/unit_1/lite_bottleneck_v1/conv2'],
<add> },
<add> },
<add> 'resnet_v1_18_beta': {
<add> DECODER_END_POINTS: {
<add> 4: ['block1/unit_1/lite_bottleneck_v1/conv2'],
<add> 8: ['block2/unit_1/lite_bottleneck_v1/conv2'],
<add> 16: ['block3/unit_1/lite_bottleneck_v1/conv2'],
<ide> },
<ide> },
<ide> 'resnet_v1_50': {
<ide> DECODER_END_POINTS: {
<ide> 4: ['block1/unit_2/bottleneck_v1/conv3'],
<add> 8: ['block2/unit_3/bottleneck_v1/conv3'],
<add> 16: ['block3/unit_5/bottleneck_v1/conv3'],
<ide> },
<ide> },
<ide> 'resnet_v1_50_beta': {
<ide> DECODER_END_POINTS: {
<ide> 4: ['block1/unit_2/bottleneck_v1/conv3'],
<add> 8: ['block2/unit_3/bottleneck_v1/conv3'],
<add> 16: ['block3/unit_5/bottleneck_v1/conv3'],
<ide> },
<ide> },
<ide> 'resnet_v1_101': {
<ide> DECODER_END_POINTS: {
<ide> 4: ['block1/unit_2/bottleneck_v1/conv3'],
<add> 8: ['block2/unit_3/bottleneck_v1/conv3'],
<add> 16: ['block3/unit_22/bottleneck_v1/conv3'],
<ide> },
<ide> },
<ide> 'resnet_v1_101_beta': {
<ide> DECODER_END_POINTS: {
<ide> 4: ['block1/unit_2/bottleneck_v1/conv3'],
<add> 8: ['block2/unit_3/bottleneck_v1/conv3'],
<add> 16: ['block3/unit_22/bottleneck_v1/conv3'],
<ide> },
<ide> },
<ide> 'xception_41': {
<ide> DECODER_END_POINTS: {
<ide> 4: ['entry_flow/block2/unit_1/xception_module/'
<ide> 'separable_conv2_pointwise'],
<add> 8: ['entry_flow/block3/unit_1/xception_module/'
<add> 'separable_conv2_pointwise'],
<add> 16: ['exit_flow/block1/unit_1/xception_module/'
<add> 'separable_conv2_pointwise'],
<ide> },
<ide> },
<ide> 'xception_65': {
<ide> DECODER_END_POINTS: {
<ide> 4: ['entry_flow/block2/unit_1/xception_module/'
<ide> 'separable_conv2_pointwise'],
<add> 8: ['entry_flow/block3/unit_1/xception_module/'
<add> 'separable_conv2_pointwise'],
<add> 16: ['exit_flow/block1/unit_1/xception_module/'
<add> 'separable_conv2_pointwise'],
<ide> },
<ide> },
<ide> 'xception_71': {
<ide> DECODER_END_POINTS: {
<ide> 4: ['entry_flow/block3/unit_1/xception_module/'
<ide> 'separable_conv2_pointwise'],
<add> 8: ['entry_flow/block5/unit_1/xception_module/'
<add> 'separable_conv2_pointwise'],
<add> 16: ['exit_flow/block1/unit_1/xception_module/'
<add> 'separable_conv2_pointwise'],
<ide> },
<ide> },
<ide> 'nas_pnasnet': {
<ide> DECODER_END_POINTS: {
<ide> 4: ['Stem'],
<add> 8: ['Cell_3'],
<add> 16: ['Cell_7'],
<ide> },
<ide> },
<ide> 'nas_hnasnet': {
<ide> DECODER_END_POINTS: {
<ide> 4: ['Cell_2'],
<add> 8: ['Cell_5'],
<add> 16: ['Cell_7'],
<ide> },
<ide> },
<ide> }
<ide> def _mobilenet_v2(net,
<ide> # ImageNet pretrained versions of these models.
<ide> name_scope = {
<ide> 'mobilenet_v2': 'MobilenetV2',
<add> 'mobilenet_v3_large_seg': 'MobilenetV3',
<add> 'mobilenet_v3_small_seg': 'MobilenetV3',
<add> 'resnet_v1_18': 'resnet_v1_18',
<add> 'resnet_v1_18_beta': 'resnet_v1_18',
<ide> 'resnet_v1_50': 'resnet_v1_50',
<ide> 'resnet_v1_50_beta': 'resnet_v1_50',
<ide> 'resnet_v1_101': 'resnet_v1_101',
<ide> def _preprocess_zero_mean_unit_range(inputs, dtype=tf.float32):
<ide>
<ide> _PREPROCESS_FN = {
<ide> 'mobilenet_v2': _preprocess_zero_mean_unit_range,
<add> 'mobilenet_v3_large_seg': _preprocess_zero_mean_unit_range,
<add> 'mobilenet_v3_small_seg': _preprocess_zero_mean_unit_range,
<add> 'resnet_v1_18': _preprocess_subtract_imagenet_mean,
<add> 'resnet_v1_18_beta': _preprocess_zero_mean_unit_range,
<ide> 'resnet_v1_50': _preprocess_subtract_imagenet_mean,
<ide> 'resnet_v1_50_beta': _preprocess_zero_mean_unit_range,
<ide> 'resnet_v1_101': _preprocess_subtract_imagenet_mean,
<ide> def extract_features(images,
<ide> preprocessed_images_dtype=tf.float32,
<ide> num_classes=None,
<ide> global_pool=False,
<del> nas_stem_output_num_conv_filters=20,
<add> nas_architecture_options=None,
<ide> nas_training_hyper_parameters=None,
<ide> use_bounded_activation=False):
<ide> """Extracts features by the particular model_variant.
<ide> def extract_features(images,
<ide> to None for dense prediction tasks.
<ide> global_pool: Global pooling for image classification task. Defaults to
<ide> False, since dense prediction tasks do not use this.
<del> nas_stem_output_num_conv_filters: Number of filters of the NAS stem output
<del> tensor.
<add> nas_architecture_options: A dictionary storing NAS architecture options.
<add> It is either None or its kerys are:
<add> - `nas_stem_output_num_conv_filters`: Number of filters of the NAS stem
<add> output tensor.
<add> - `nas_use_classification_head`: Boolean, use image classification head.
<ide> nas_training_hyper_parameters: A dictionary storing hyper-parameters for
<ide> training nas models. It is either None or its keys are:
<ide> - `drop_path_keep_prob`: Probability to keep each path in the cell when
<ide> def extract_features(images,
<ide> multi_grid=multi_grid,
<ide> reuse=reuse,
<ide> scope=name_scope[model_variant])
<del> elif 'mobilenet' in model_variant:
<add> elif 'mobilenet' in model_variant or model_variant.startswith('mnas'):
<ide> arg_scope = arg_scopes_map[model_variant](
<ide> is_training=(is_training and fine_tune_batch_norm),
<ide> weight_decay=weight_decay)
<ide> def extract_features(images,
<ide> is_training=(is_training and fine_tune_batch_norm),
<ide> global_pool=global_pool,
<ide> output_stride=output_stride,
<del> nas_stem_output_num_conv_filters=nas_stem_output_num_conv_filters,
<add> nas_architecture_options=nas_architecture_options,
<ide> nas_training_hyper_parameters=nas_training_hyper_parameters,
<ide> reuse=reuse,
<ide> scope=name_scope[model_variant])
<ide><path>research/deeplab/core/nas_cell.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<add>import functools
<add>from six.moves import range
<add>from six.moves import zip
<ide> import tensorflow as tf
<add>from tensorflow.contrib import framework as contrib_framework
<add>from tensorflow.contrib import slim as contrib_slim
<add>from deeplab.core import xception as xception_utils
<ide> from deeplab.core.utils import resize_bilinear
<ide> from deeplab.core.utils import scale_dimension
<add>from tensorflow.contrib.slim.nets import resnet_utils
<ide>
<del>arg_scope = tf.contrib.framework.arg_scope
<del>slim = tf.contrib.slim
<add>arg_scope = contrib_framework.arg_scope
<add>slim = contrib_slim
<add>
<add>separable_conv2d_same = functools.partial(xception_utils.separable_conv2d_same,
<add> regularize_depthwise=True)
<ide>
<ide>
<ide> class NASBaseCell(object):
<del> """NASNet Cell class that is used as a 'layer' in image architectures.
<del> See https://arxiv.org/abs/1707.07012 and https://arxiv.org/abs/1712.00559.
<del>
<del> Args:
<del> num_conv_filters: The number of filters for each convolution operation.
<del> operations: List of operations that are performed in the NASNet Cell in
<del> order.
<del> used_hiddenstates: Binary array that signals if the hiddenstate was used
<del> within the cell. This is used to determine what outputs of the cell
<del> should be concatenated together.
<del> hiddenstate_indices: Determines what hiddenstates should be combined
<del> together with the specified operations to create the NASNet cell.
<del> """
<add> """NASNet Cell class that is used as a 'layer' in image architectures."""
<ide>
<ide> def __init__(self, num_conv_filters, operations, used_hiddenstates,
<ide> hiddenstate_indices, drop_path_keep_prob, total_num_cells,
<del> total_training_steps):
<add> total_training_steps, batch_norm_fn=slim.batch_norm):
<add> """Init function.
<add>
<add> For more details about NAS cell, see
<add> https://arxiv.org/abs/1707.07012 and https://arxiv.org/abs/1712.00559.
<add>
<add> Args:
<add> num_conv_filters: The number of filters for each convolution operation.
<add> operations: List of operations that are performed in the NASNet Cell in
<add> order.
<add> used_hiddenstates: Binary array that signals if the hiddenstate was used
<add> within the cell. This is used to determine what outputs of the cell
<add> should be concatenated together.
<add> hiddenstate_indices: Determines what hiddenstates should be combined
<add> together with the specified operations to create the NASNet cell.
<add> drop_path_keep_prob: Float, drop path keep probability.
<add> total_num_cells: Integer, total number of cells.
<add> total_training_steps: Integer, total training steps.
<add> batch_norm_fn: Function, batch norm function. Defaults to
<add> slim.batch_norm.
<add> """
<ide> if len(hiddenstate_indices) != len(operations):
<ide> raise ValueError(
<ide> 'Number of hiddenstate_indices and operations should be the same.')
<ide> def __init__(self, num_conv_filters, operations, used_hiddenstates,
<ide> self._drop_path_keep_prob = drop_path_keep_prob
<ide> self._total_num_cells = total_num_cells
<ide> self._total_training_steps = total_training_steps
<add> self._batch_norm_fn = batch_norm_fn
<ide>
<ide> def __call__(self, net, scope, filter_scaling, stride, prev_layer, cell_num):
<ide> """Runs the conv cell."""
<ide> def _cell_base(self, net, prev_layer):
<ide> if filter_size != prev_layer.shape[3]:
<ide> prev_layer = tf.nn.relu(prev_layer)
<ide> prev_layer = slim.conv2d(prev_layer, filter_size, 1, scope='prev_1x1')
<del> prev_layer = slim.batch_norm(prev_layer, scope='prev_bn')
<add> prev_layer = self._batch_norm_fn(prev_layer, scope='prev_bn')
<ide>
<ide> net = tf.nn.relu(net)
<ide> net = slim.conv2d(net, filter_size, 1, scope='1x1')
<del> net = slim.batch_norm(net, scope='beginning_bn')
<add> net = self._batch_norm_fn(net, scope='beginning_bn')
<ide> net = tf.split(axis=3, num_or_size_splits=1, value=net)
<ide> net.append(prev_layer)
<ide> return net
<ide> def _apply_conv_operation(self, net, operation, stride,
<ide> kernel_size = int(operation.split('x')[0][-1])
<ide> for layer_num in range(num_layers):
<ide> net = tf.nn.relu(net)
<del> net = slim.separable_conv2d(
<add> net = separable_conv2d_same(
<ide> net,
<ide> filter_size,
<ide> kernel_size,
<ide> depth_multiplier=1,
<ide> scope='separable_{0}x{0}_{1}'.format(kernel_size, layer_num + 1),
<ide> stride=stride)
<del> net = slim.batch_norm(
<add> net = self._batch_norm_fn(
<ide> net, scope='bn_sep_{0}x{0}_{1}'.format(kernel_size, layer_num + 1))
<ide> stride = 1
<ide> elif 'atrous' in operation:
<ide> def _apply_conv_operation(self, net, operation, stride,
<ide> scaled_height = scale_dimension(tf.shape(net)[1], 0.5)
<ide> scaled_width = scale_dimension(tf.shape(net)[2], 0.5)
<ide> net = resize_bilinear(net, [scaled_height, scaled_width], net.dtype)
<del> net = slim.conv2d(net, filter_size, kernel_size, rate=1,
<del> scope='atrous_{0}x{0}'.format(kernel_size))
<add> net = resnet_utils.conv2d_same(
<add> net, filter_size, kernel_size, rate=1, stride=1,
<add> scope='atrous_{0}x{0}'.format(kernel_size))
<ide> else:
<del> net = slim.conv2d(net, filter_size, kernel_size, rate=2,
<del> scope='atrous_{0}x{0}'.format(kernel_size))
<del> net = slim.batch_norm(net, scope='bn_atr_{0}x{0}'.format(kernel_size))
<add> net = resnet_utils.conv2d_same(
<add> net, filter_size, kernel_size, rate=2, stride=1,
<add> scope='atrous_{0}x{0}'.format(kernel_size))
<add> net = self._batch_norm_fn(net, scope='bn_atr_{0}x{0}'.format(kernel_size))
<ide> elif operation in ['none']:
<ide> if stride > 1 or (input_filters != filter_size):
<ide> net = tf.nn.relu(net)
<ide> net = slim.conv2d(net, filter_size, 1, stride=stride, scope='1x1')
<del> net = slim.batch_norm(net, scope='bn_1')
<add> net = self._batch_norm_fn(net, scope='bn_1')
<ide> elif 'pool' in operation:
<ide> pooling_type = operation.split('_')[0]
<ide> pooling_shape = int(operation.split('_')[-1].split('x')[0])
<ide> def _apply_conv_operation(self, net, operation, stride,
<ide> raise ValueError('Unimplemented pooling type: ', pooling_type)
<ide> if input_filters != filter_size:
<ide> net = slim.conv2d(net, filter_size, 1, stride=1, scope='1x1')
<del> net = slim.batch_norm(net, scope='bn_1')
<add> net = self._batch_norm_fn(net, scope='bn_1')
<ide> else:
<ide> raise ValueError('Unimplemented operation', operation)
<ide>
<ide> def _combine_unused_states(self, net):
<ide> net = tf.concat(values=states_to_combine, axis=3)
<ide> return net
<ide>
<del> @tf.contrib.framework.add_arg_scope
<add> @contrib_framework.add_arg_scope
<ide> def _apply_drop_path(self, net):
<ide> """Apply drop_path regularization."""
<ide> drop_path_keep_prob = self._drop_path_keep_prob
<ide><path>research/deeplab/core/nas_genotypes.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> from __future__ import absolute_import
<ide> from __future__ import division
<ide> from __future__ import print_function
<del>
<add>from tensorflow.contrib import slim as contrib_slim
<ide> from deeplab.core import nas_cell
<ide>
<add>slim = contrib_slim
<add>
<ide>
<ide> class PNASCell(nas_cell.NASBaseCell):
<ide> """Configuration and construction of the PNASNet-5 Cell."""
<ide>
<ide> def __init__(self, num_conv_filters, drop_path_keep_prob, total_num_cells,
<del> total_training_steps):
<add> total_training_steps, batch_norm_fn=slim.batch_norm):
<ide> # Name of operations: op_kernel-size_num-layers.
<ide> operations = [
<ide> 'separable_5x5_2', 'max_pool_3x3', 'separable_7x7_2', 'max_pool_3x3',
<ide> def __init__(self, num_conv_filters, drop_path_keep_prob, total_num_cells,
<ide>
<ide> super(PNASCell, self).__init__(
<ide> num_conv_filters, operations, used_hiddenstates, hiddenstate_indices,
<del> drop_path_keep_prob, total_num_cells, total_training_steps)
<add> drop_path_keep_prob, total_num_cells, total_training_steps,
<add> batch_norm_fn)
<ide><path>research/deeplab/core/nas_network.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<add>from six.moves import range
<ide> import tensorflow as tf
<add>from tensorflow.contrib import framework as contrib_framework
<add>from tensorflow.contrib import layers as contrib_layers
<add>from tensorflow.contrib import slim as contrib_slim
<add>from tensorflow.contrib import training as contrib_training
<ide>
<ide> from deeplab.core import nas_genotypes
<add>from deeplab.core import utils
<ide> from deeplab.core.nas_cell import NASBaseCell
<del>from deeplab.core.utils import resize_bilinear
<del>from deeplab.core.utils import scale_dimension
<add>from tensorflow.contrib.slim.nets import resnet_utils
<ide>
<del>arg_scope = tf.contrib.framework.arg_scope
<del>slim = tf.contrib.slim
<add>arg_scope = contrib_framework.arg_scope
<add>slim = contrib_slim
<add>resize_bilinear = utils.resize_bilinear
<add>scale_dimension = utils.scale_dimension
<ide>
<ide>
<ide> def config(num_conv_filters=20,
<ide> total_training_steps=500000,
<ide> drop_path_keep_prob=1.0):
<del> return tf.contrib.training.HParams(
<add> return contrib_training.HParams(
<ide> # Multiplier when spatial size is reduced by 2.
<ide> filter_scaling_rate=2.0,
<ide> # Number of filters of the stem output tensor.
<ide> def config(num_conv_filters=20,
<ide> )
<ide>
<ide>
<del>def nas_arg_scope(weight_decay=4e-5, batch_norm_decay=0.9997,
<del> batch_norm_epsilon=0.001):
<add>def nas_arg_scope(weight_decay=4e-5,
<add> batch_norm_decay=0.9997,
<add> batch_norm_epsilon=0.001,
<add> sync_batch_norm_method='None'):
<ide> """Default arg scope for the NAS models."""
<ide> batch_norm_params = {
<ide> # Decay for the moving averages.
<ide> 'decay': batch_norm_decay,
<ide> # epsilon to prevent 0s in variance.
<ide> 'epsilon': batch_norm_epsilon,
<ide> 'scale': True,
<del> 'fused': True,
<ide> }
<del> weights_regularizer = tf.contrib.layers.l2_regularizer(weight_decay)
<del> weights_initializer = tf.contrib.layers.variance_scaling_initializer(
<del> factor=1/3.0, mode='FAN_IN', uniform=True)
<add> batch_norm = utils.get_batch_norm_fn(sync_batch_norm_method)
<add> weights_regularizer = contrib_layers.l2_regularizer(weight_decay)
<add> weights_initializer = contrib_layers.variance_scaling_initializer(
<add> factor=1 / 3.0, mode='FAN_IN', uniform=True)
<ide> with arg_scope([slim.fully_connected, slim.conv2d, slim.separable_conv2d],
<ide> weights_regularizer=weights_regularizer,
<ide> weights_initializer=weights_initializer):
<ide> with arg_scope([slim.fully_connected],
<ide> activation_fn=None, scope='FC'):
<ide> with arg_scope([slim.conv2d, slim.separable_conv2d],
<ide> activation_fn=None, biases_initializer=None):
<del> with arg_scope([slim.batch_norm], **batch_norm_params) as sc:
<add> with arg_scope([batch_norm], **batch_norm_params) as sc:
<ide> return sc
<ide>
<ide>
<del>def _nas_stem(inputs):
<add>def _nas_stem(inputs,
<add> batch_norm_fn=slim.batch_norm):
<ide> """Stem used for NAS models."""
<del> net = slim.conv2d(inputs, 64, [3, 3], stride=2,
<del> scope='conv0', padding='SAME')
<del> net = slim.batch_norm(net, scope='conv0_bn')
<add> net = resnet_utils.conv2d_same(inputs, 64, 3, stride=2, scope='conv0')
<add> net = batch_norm_fn(net, scope='conv0_bn')
<ide> net = tf.nn.relu(net)
<del> net = slim.conv2d(net, 64, [3, 3], stride=1,
<del> scope='conv1', padding='SAME')
<del> net = slim.batch_norm(net, scope='conv1_bn')
<add> net = resnet_utils.conv2d_same(net, 64, 3, stride=1, scope='conv1')
<add> net = batch_norm_fn(net, scope='conv1_bn')
<ide> cell_outputs = [net]
<ide> net = tf.nn.relu(net)
<del> net = slim.conv2d(net, 128, [3, 3], stride=2,
<del> scope='conv2', padding='SAME')
<del> net = slim.batch_norm(net, scope='conv2_bn')
<add> net = resnet_utils.conv2d_same(net, 128, 3, stride=2, scope='conv2')
<add> net = batch_norm_fn(net, scope='conv2_bn')
<ide> cell_outputs.append(net)
<ide> return net, cell_outputs
<ide>
<ide> def _build_nas_base(images,
<ide> num_classes,
<ide> hparams,
<ide> global_pool=False,
<add> output_stride=16,
<add> nas_use_classification_head=False,
<ide> reuse=None,
<ide> scope=None,
<del> final_endpoint=None):
<add> final_endpoint=None,
<add> batch_norm_fn=slim.batch_norm,
<add> nas_remove_os32_stride=False):
<ide> """Constructs a NAS model.
<ide>
<ide> Args:
<ide> def _build_nas_base(images,
<ide> hparams: Hyperparameters needed to construct the network.
<ide> global_pool: If True, we perform global average pooling before computing the
<ide> logits. Set to True for image classification, False for dense prediction.
<add> output_stride: Interger, the stride of output feature maps.
<add> nas_use_classification_head: Boolean, use image classification head.
<ide> reuse: Whether or not the network and its variables should be reused. To be
<ide> able to reuse 'scope' must be given.
<ide> scope: Optional variable_scope.
<ide> final_endpoint: The endpoint to construct the network up to.
<add> batch_norm_fn: Batch norm function.
<add> nas_remove_os32_stride: Boolean, remove stride in output_stride 32 branch.
<ide>
<ide> Returns:
<ide> net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
<ide> end_points: A dictionary from components of the network to the corresponding
<ide> activation.
<add>
<add> Raises:
<add> ValueError: If output_stride is not a multiple of backbone output stride.
<ide> """
<ide> with tf.variable_scope(scope, 'nas', [images], reuse=reuse):
<ide> end_points = {}
<ide> def add_and_check_endpoint(endpoint_name, net):
<ide> end_points[endpoint_name] = net
<ide> return final_endpoint and (endpoint_name == final_endpoint)
<ide>
<del> net, cell_outputs = _nas_stem(images)
<add> net, cell_outputs = _nas_stem(images,
<add> batch_norm_fn=batch_norm_fn)
<ide> if add_and_check_endpoint('Stem', net):
<ide> return net, end_points
<ide>
<ide> def add_and_check_endpoint(endpoint_name, net):
<ide> else:
<ide> if backbone[cell_num] == backbone[cell_num - 1] + 1:
<ide> stride = 2
<add> if backbone[cell_num] == 3 and nas_remove_os32_stride:
<add> stride = 1
<ide> filter_scaling *= hparams.filter_scaling_rate
<ide> elif backbone[cell_num] == backbone[cell_num - 1] - 1:
<del> scaled_height = scale_dimension(net.shape[1].value, 2)
<del> scaled_width = scale_dimension(net.shape[2].value, 2)
<del> net = resize_bilinear(net, [scaled_height, scaled_width], net.dtype)
<add> if backbone[cell_num - 1] == 3 and nas_remove_os32_stride:
<add> # No need to rescale features.
<add> pass
<add> else:
<add> # Scale features by a factor of 2.
<add> scaled_height = scale_dimension(net.shape[1].value, 2)
<add> scaled_width = scale_dimension(net.shape[2].value, 2)
<add> net = resize_bilinear(net, [scaled_height, scaled_width], net.dtype)
<ide> filter_scaling /= hparams.filter_scaling_rate
<ide> net = cell(
<ide> net,
<ide> def add_and_check_endpoint(endpoint_name, net):
<ide> cell_outputs.append(net)
<ide> net = tf.nn.relu(net)
<ide>
<add> if nas_use_classification_head:
<add> # Add image classification head.
<add> # We will expand the filters for different output_strides.
<add> output_stride_to_expanded_filters = {8: 256, 16: 512, 32: 1024}
<add> current_output_scale = 2 + backbone[-1]
<add> current_output_stride = 2 ** current_output_scale
<add> if output_stride % current_output_stride != 0:
<add> raise ValueError(
<add> 'output_stride must be a multiple of backbone output stride.')
<add> output_stride //= current_output_stride
<add> rate = 1
<add> if current_output_stride != 32:
<add> num_downsampling = 5 - current_output_scale
<add> for i in range(num_downsampling):
<add> # Gradually donwsample feature maps to output stride = 32.
<add> target_output_stride = 2 ** (current_output_scale + 1 + i)
<add> target_filters = output_stride_to_expanded_filters[
<add> target_output_stride]
<add> scope = 'downsample_os{}'.format(target_output_stride)
<add> if output_stride != 1:
<add> stride = 2
<add> output_stride //= 2
<add> else:
<add> stride = 1
<add> rate *= 2
<add> net = resnet_utils.conv2d_same(
<add> net, target_filters, 3, stride=stride, rate=rate,
<add> scope=scope + '_conv')
<add> net = batch_norm_fn(net, scope=scope + '_bn')
<add> add_and_check_endpoint(scope, net)
<add> net = tf.nn.relu(net)
<add> # Apply 1x1 convolution to expand dimension to 2048.
<add> scope = 'classification_head'
<add> net = slim.conv2d(net, 2048, 1, scope=scope + '_conv')
<add> net = batch_norm_fn(net, scope=scope + '_bn')
<add> add_and_check_endpoint(scope, net)
<add> net = tf.nn.relu(net)
<ide> if global_pool:
<ide> # Global average pooling.
<ide> net = tf.reduce_mean(net, [1, 2], name='global_pool', keepdims=True)
<ide> if num_classes is not None:
<del> net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None,
<add> net = slim.conv2d(net, num_classes, 1, activation_fn=None,
<ide> normalizer_fn=None, scope='logits')
<ide> end_points['predictions'] = slim.softmax(net, scope='predictions')
<ide> return net, end_points
<ide> def pnasnet(images,
<ide> is_training=True,
<ide> global_pool=False,
<ide> output_stride=16,
<del> nas_stem_output_num_conv_filters=20,
<add> nas_architecture_options=None,
<ide> nas_training_hyper_parameters=None,
<ide> reuse=None,
<ide> scope='pnasnet',
<del> final_endpoint=None):
<add> final_endpoint=None,
<add> sync_batch_norm_method='None'):
<ide> """Builds PNASNet model."""
<del> hparams = config(num_conv_filters=nas_stem_output_num_conv_filters)
<add> if nas_architecture_options is None:
<add> raise ValueError(
<add> 'Using NAS model variants. nas_architecture_options cannot be None.')
<add> hparams = config(num_conv_filters=nas_architecture_options[
<add> 'nas_stem_output_num_conv_filters'])
<ide> if nas_training_hyper_parameters:
<ide> hparams.set_hparam('drop_path_keep_prob',
<ide> nas_training_hyper_parameters['drop_path_keep_prob'])
<ide> def pnasnet(images,
<ide> backbone = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
<ide> else:
<ide> raise ValueError('Unsupported output_stride ', output_stride)
<add> batch_norm = utils.get_batch_norm_fn(sync_batch_norm_method)
<ide> cell = nas_genotypes.PNASCell(hparams.num_conv_filters,
<ide> hparams.drop_path_keep_prob,
<ide> len(backbone),
<del> hparams.total_training_steps)
<del> with arg_scope([slim.dropout, slim.batch_norm], is_training=is_training):
<add> hparams.total_training_steps,
<add> batch_norm_fn=batch_norm)
<add> with arg_scope([slim.dropout, batch_norm], is_training=is_training):
<ide> return _build_nas_base(
<ide> images,
<ide> cell=cell,
<ide> backbone=backbone,
<ide> num_classes=num_classes,
<ide> hparams=hparams,
<ide> global_pool=global_pool,
<add> output_stride=output_stride,
<add> nas_use_classification_head=nas_architecture_options[
<add> 'nas_use_classification_head'],
<ide> reuse=reuse,
<ide> scope=scope,
<del> final_endpoint=final_endpoint)
<add> final_endpoint=final_endpoint,
<add> batch_norm_fn=batch_norm,
<add> nas_remove_os32_stride=nas_architecture_options[
<add> 'nas_remove_os32_stride'])
<ide>
<ide>
<ide> # pylint: disable=unused-argument
<ide> def hnasnet(images,
<ide> num_classes,
<ide> is_training=True,
<ide> global_pool=False,
<del> output_stride=16,
<del> nas_stem_output_num_conv_filters=20,
<add> output_stride=8,
<add> nas_architecture_options=None,
<ide> nas_training_hyper_parameters=None,
<ide> reuse=None,
<ide> scope='hnasnet',
<del> final_endpoint=None):
<add> final_endpoint=None,
<add> sync_batch_norm_method='None'):
<ide> """Builds hierarchical model."""
<del> hparams = config(num_conv_filters=nas_stem_output_num_conv_filters)
<add> if nas_architecture_options is None:
<add> raise ValueError(
<add> 'Using NAS model variants. nas_architecture_options cannot be None.')
<add> hparams = config(num_conv_filters=nas_architecture_options[
<add> 'nas_stem_output_num_conv_filters'])
<ide> if nas_training_hyper_parameters:
<ide> hparams.set_hparam('drop_path_keep_prob',
<ide> nas_training_hyper_parameters['drop_path_keep_prob'])
<ide> def hnasnet(images,
<ide> used_hiddenstates = [1, 1, 0, 0, 0, 0, 0]
<ide> hiddenstate_indices = [1, 0, 1, 0, 3, 1, 4, 2, 3, 5]
<ide> backbone = [0, 0, 0, 1, 2, 1, 2, 2, 3, 3, 2, 1]
<add> batch_norm = utils.get_batch_norm_fn(sync_batch_norm_method)
<ide> cell = NASBaseCell(hparams.num_conv_filters,
<ide> operations,
<ide> used_hiddenstates,
<ide> hiddenstate_indices,
<ide> hparams.drop_path_keep_prob,
<ide> len(backbone),
<del> hparams.total_training_steps)
<del> with arg_scope([slim.dropout, slim.batch_norm], is_training=is_training):
<add> hparams.total_training_steps,
<add> batch_norm_fn=batch_norm)
<add> with arg_scope([slim.dropout, batch_norm], is_training=is_training):
<ide> return _build_nas_base(
<ide> images,
<ide> cell=cell,
<ide> backbone=backbone,
<ide> num_classes=num_classes,
<ide> hparams=hparams,
<ide> global_pool=global_pool,
<add> output_stride=output_stride,
<add> nas_use_classification_head=nas_architecture_options[
<add> 'nas_use_classification_head'],
<ide> reuse=reuse,
<ide> scope=scope,
<del> final_endpoint=final_endpoint)
<add> final_endpoint=final_endpoint,
<add> batch_norm_fn=batch_norm,
<add> nas_remove_os32_stride=nas_architecture_options[
<add> 'nas_remove_os32_stride'])
<ide><path>research/deeplab/core/nas_network_test.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide>
<ide> import numpy as np
<ide> import tensorflow as tf
<add>from tensorflow.contrib import framework as contrib_framework
<add>from tensorflow.contrib import slim as contrib_slim
<add>from tensorflow.contrib import training as contrib_training
<ide>
<ide> from deeplab.core import nas_genotypes
<ide> from deeplab.core import nas_network
<ide>
<del>arg_scope = tf.contrib.framework.arg_scope
<del>slim = tf.contrib.slim
<add>arg_scope = contrib_framework.arg_scope
<add>slim = contrib_slim
<ide>
<ide>
<ide> def create_test_input(batch, height, width, channels):
<ide> def _pnasnet(self,
<ide> output_stride=16,
<ide> final_endpoint=None):
<ide> """Build PNASNet model backbone."""
<del> hparams = tf.contrib.training.HParams(
<add> hparams = contrib_training.HParams(
<ide> filter_scaling_rate=2.0,
<ide> num_conv_filters=10,
<ide> drop_path_keep_prob=1.0,
<ide><path>research/deeplab/core/resnet_v1_beta.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> from __future__ import print_function
<ide>
<ide> import functools
<add>from six.moves import range
<ide> import tensorflow as tf
<del>
<add>from tensorflow.contrib import slim as contrib_slim
<add>from deeplab.core import conv2d_ws
<add>from deeplab.core import utils
<ide> from tensorflow.contrib.slim.nets import resnet_utils
<ide>
<del>slim = tf.contrib.slim
<add>slim = contrib_slim
<ide>
<ide> _DEFAULT_MULTI_GRID = [1, 1, 1]
<add>_DEFAULT_MULTI_GRID_RESNET_18 = [1, 1]
<ide>
<ide>
<ide> @slim.add_arg_scope
<ide> def bottleneck(inputs,
<ide> if depth == depth_in:
<ide> shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')
<ide> else:
<del> shortcut = slim.conv2d(
<add> shortcut = conv2d_ws.conv2d(
<ide> inputs,
<ide> depth,
<ide> [1, 1],
<ide> stride=stride,
<ide> activation_fn=None,
<ide> scope='shortcut')
<ide>
<del> residual = slim.conv2d(inputs, depth_bottleneck, [1, 1], stride=1,
<del> scope='conv1')
<del> residual = resnet_utils.conv2d_same(residual, depth_bottleneck, 3, stride,
<del> rate=rate*unit_rate, scope='conv2')
<del> residual = slim.conv2d(residual, depth, [1, 1], stride=1,
<del> activation_fn=None, scope='conv3')
<add> residual = conv2d_ws.conv2d(inputs, depth_bottleneck, [1, 1], stride=1,
<add> scope='conv1')
<add> residual = conv2d_ws.conv2d_same(residual, depth_bottleneck, 3, stride,
<add> rate=rate*unit_rate, scope='conv2')
<add> residual = conv2d_ws.conv2d(residual, depth, [1, 1], stride=1,
<add> activation_fn=None, scope='conv3')
<add> output = tf.nn.relu(shortcut + residual)
<add>
<add> return slim.utils.collect_named_outputs(outputs_collections, sc.name,
<add> output)
<add>
<add>
<add>@slim.add_arg_scope
<add>def lite_bottleneck(inputs,
<add> depth,
<add> stride,
<add> unit_rate=1,
<add> rate=1,
<add> outputs_collections=None,
<add> scope=None):
<add> """Bottleneck residual unit variant with BN after convolutions.
<add>
<add> This is the original residual unit proposed in [1]. See Fig. 1(a) of [2] for
<add> its definition. Note that we use here the bottleneck variant which has an
<add> extra bottleneck layer.
<add>
<add> When putting together two consecutive ResNet blocks that use this unit, one
<add> should use stride = 2 in the last unit of the first block.
<add>
<add> Args:
<add> inputs: A tensor of size [batch, height, width, channels].
<add> depth: The depth of the ResNet unit output.
<add> stride: The ResNet unit's stride. Determines the amount of downsampling of
<add> the units output compared to its input.
<add> unit_rate: An integer, unit rate for atrous convolution.
<add> rate: An integer, rate for atrous convolution.
<add> outputs_collections: Collection to add the ResNet unit output.
<add> scope: Optional variable_scope.
<add>
<add> Returns:
<add> The ResNet unit's output.
<add> """
<add> with tf.variable_scope(scope, 'lite_bottleneck_v1', [inputs]) as sc:
<add> depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4)
<add> if depth == depth_in:
<add> shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')
<add> else:
<add> shortcut = conv2d_ws.conv2d(
<add> inputs,
<add> depth, [1, 1],
<add> stride=stride,
<add> activation_fn=None,
<add> scope='shortcut')
<add>
<add> residual = conv2d_ws.conv2d_same(
<add> inputs, depth, 3, 1, rate=rate * unit_rate, scope='conv1')
<add> with slim.arg_scope([conv2d_ws.conv2d], activation_fn=None):
<add> residual = conv2d_ws.conv2d_same(
<add> residual, depth, 3, stride, rate=rate * unit_rate, scope='conv2')
<ide> output = tf.nn.relu(shortcut + residual)
<ide>
<del> return slim.utils.collect_named_outputs(outputs_collections,
<del> sc.name,
<add> return slim.utils.collect_named_outputs(outputs_collections, sc.name,
<ide> output)
<ide>
<ide>
<del>def root_block_fn_for_beta_variant(net):
<add>def root_block_fn_for_beta_variant(net, depth_multiplier=1.0):
<ide> """Gets root_block_fn for beta variant.
<ide>
<ide> ResNet-v1 beta variant modifies the first original 7x7 convolution to three
<ide> 3x3 convolutions.
<ide>
<ide> Args:
<ide> net: A tensor of size [batch, height, width, channels], input to the model.
<add> depth_multiplier: Controls the number of convolution output channels for
<add> each input channel. The total number of depthwise convolution output
<add> channels will be equal to `num_filters_out * depth_multiplier`.
<ide>
<ide> Returns:
<ide> A tensor after three 3x3 convolutions.
<ide> """
<del> net = resnet_utils.conv2d_same(net, 64, 3, stride=2, scope='conv1_1')
<del> net = resnet_utils.conv2d_same(net, 64, 3, stride=1, scope='conv1_2')
<del> net = resnet_utils.conv2d_same(net, 128, 3, stride=1, scope='conv1_3')
<add> net = conv2d_ws.conv2d_same(
<add> net, int(64 * depth_multiplier), 3, stride=2, scope='conv1_1')
<add> net = conv2d_ws.conv2d_same(
<add> net, int(64 * depth_multiplier), 3, stride=1, scope='conv1_2')
<add> net = conv2d_ws.conv2d_same(
<add> net, int(128 * depth_multiplier), 3, stride=1, scope='conv1_3')
<ide>
<ide> return net
<ide>
<ide> def resnet_v1_beta(inputs,
<ide> output_stride=None,
<ide> root_block_fn=None,
<ide> reuse=None,
<del> scope=None):
<add> scope=None,
<add> sync_batch_norm_method='None'):
<ide> """Generator for v1 ResNet models (beta variant).
<ide>
<ide> This function generates a family of modified ResNet v1 models. In particular,
<ide> def resnet_v1_beta(inputs,
<ide> reuse: whether or not the network and its variables should be reused. To be
<ide> able to reuse 'scope' must be given.
<ide> scope: Optional variable_scope.
<add> sync_batch_norm_method: String, sync batchnorm method.
<ide>
<ide> Returns:
<ide> net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
<ide> def resnet_v1_beta(inputs,
<ide> ValueError: If the target output_stride is not valid.
<ide> """
<ide> if root_block_fn is None:
<del> root_block_fn = functools.partial(resnet_utils.conv2d_same,
<add> root_block_fn = functools.partial(conv2d_ws.conv2d_same,
<ide> num_outputs=64,
<ide> kernel_size=7,
<ide> stride=2,
<ide> scope='conv1')
<add> batch_norm = utils.get_batch_norm_fn(sync_batch_norm_method)
<ide> with tf.variable_scope(scope, 'resnet_v1', [inputs], reuse=reuse) as sc:
<ide> end_points_collection = sc.original_name_scope + '_end_points'
<del> with slim.arg_scope([slim.conv2d, bottleneck,
<del> resnet_utils.stack_blocks_dense],
<add> with slim.arg_scope([
<add> conv2d_ws.conv2d, bottleneck, lite_bottleneck,
<add> resnet_utils.stack_blocks_dense
<add> ],
<ide> outputs_collections=end_points_collection):
<ide> if is_training is not None:
<del> arg_scope = slim.arg_scope([slim.batch_norm], is_training=is_training)
<add> arg_scope = slim.arg_scope([batch_norm], is_training=is_training)
<ide> else:
<ide> arg_scope = slim.arg_scope([])
<ide> with arg_scope:
<ide> net = inputs
<ide> if output_stride is not None:
<ide> if output_stride % 4 != 0:
<ide> raise ValueError('The output_stride needs to be a multiple of 4.')
<del> output_stride /= 4
<add> output_stride //= 4
<ide> net = root_block_fn(net)
<ide> net = slim.max_pool2d(net, 3, stride=2, padding='SAME', scope='pool1')
<ide> net = resnet_utils.stack_blocks_dense(net, blocks, output_stride)
<ide> def resnet_v1_beta(inputs,
<ide> # Global average pooling.
<ide> net = tf.reduce_mean(net, [1, 2], name='pool5', keepdims=True)
<ide> if num_classes is not None:
<del> net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None,
<del> normalizer_fn=None, scope='logits')
<add> net = conv2d_ws.conv2d(net, num_classes, [1, 1], activation_fn=None,
<add> normalizer_fn=None, scope='logits',
<add> use_weight_standardization=False)
<ide> # Convert end_points_collection into a dictionary of end_points.
<ide> end_points = slim.utils.convert_collection_to_dict(
<ide> end_points_collection)
<ide> def resnet_v1_beta_block(scope, base_depth, num_units, stride):
<ide> }])
<ide>
<ide>
<add>def resnet_v1_small_beta_block(scope, base_depth, num_units, stride):
<add> """Helper function for creating a resnet_18 beta variant bottleneck block.
<add>
<add> Args:
<add> scope: The scope of the block.
<add> base_depth: The depth of the bottleneck layer for each unit.
<add> num_units: The number of units in the block.
<add> stride: The stride of the block, implemented as a stride in the last unit.
<add> All other units have stride=1.
<add>
<add> Returns:
<add> A resnet_18 bottleneck block.
<add> """
<add> block_args = []
<add> for _ in range(num_units - 1):
<add> block_args.append({'depth': base_depth, 'stride': 1, 'unit_rate': 1})
<add> block_args.append({'depth': base_depth, 'stride': stride, 'unit_rate': 1})
<add> return resnet_utils.Block(scope, lite_bottleneck, block_args)
<add>
<add>
<add>def resnet_v1_18(inputs,
<add> num_classes=None,
<add> is_training=None,
<add> global_pool=False,
<add> output_stride=None,
<add> multi_grid=None,
<add> reuse=None,
<add> scope='resnet_v1_18',
<add> sync_batch_norm_method='None'):
<add> """Resnet v1 18.
<add>
<add> Args:
<add> inputs: A tensor of size [batch, height_in, width_in, channels].
<add> num_classes: Number of predicted classes for classification tasks. If None
<add> we return the features before the logit layer.
<add> is_training: Enable/disable is_training for batch normalization.
<add> global_pool: If True, we perform global average pooling before computing the
<add> logits. Set to True for image classification, False for dense prediction.
<add> output_stride: If None, then the output will be computed at the nominal
<add> network stride. If output_stride is not None, it specifies the requested
<add> ratio of input to output spatial resolution.
<add> multi_grid: Employ a hierarchy of different atrous rates within network.
<add> reuse: whether or not the network and its variables should be reused. To be
<add> able to reuse 'scope' must be given.
<add> scope: Optional variable_scope.
<add> sync_batch_norm_method: String, sync batchnorm method.
<add>
<add> Returns:
<add> net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
<add> If global_pool is False, then height_out and width_out are reduced by a
<add> factor of output_stride compared to the respective height_in and width_in,
<add> else both height_out and width_out equal one. If num_classes is None, then
<add> net is the output of the last ResNet block, potentially after global
<add> average pooling. If num_classes is not None, net contains the pre-softmax
<add> activations.
<add> end_points: A dictionary from components of the network to the corresponding
<add> activation.
<add>
<add> Raises:
<add> ValueError: if multi_grid is not None and does not have length = 3.
<add> """
<add> if multi_grid is None:
<add> multi_grid = _DEFAULT_MULTI_GRID_RESNET_18
<add> else:
<add> if len(multi_grid) != 2:
<add> raise ValueError('Expect multi_grid to have length 2.')
<add>
<add> block4_args = []
<add> for rate in multi_grid:
<add> block4_args.append({'depth': 512, 'stride': 1, 'unit_rate': rate})
<add>
<add> blocks = [
<add> resnet_v1_small_beta_block(
<add> 'block1', base_depth=64, num_units=2, stride=2),
<add> resnet_v1_small_beta_block(
<add> 'block2', base_depth=128, num_units=2, stride=2),
<add> resnet_v1_small_beta_block(
<add> 'block3', base_depth=256, num_units=2, stride=2),
<add> resnet_utils.Block('block4', lite_bottleneck, block4_args),
<add> ]
<add> return resnet_v1_beta(
<add> inputs,
<add> blocks=blocks,
<add> num_classes=num_classes,
<add> is_training=is_training,
<add> global_pool=global_pool,
<add> output_stride=output_stride,
<add> reuse=reuse,
<add> scope=scope,
<add> sync_batch_norm_method=sync_batch_norm_method)
<add>
<add>
<add>def resnet_v1_18_beta(inputs,
<add> num_classes=None,
<add> is_training=None,
<add> global_pool=False,
<add> output_stride=None,
<add> multi_grid=None,
<add> root_depth_multiplier=0.25,
<add> reuse=None,
<add> scope='resnet_v1_18',
<add> sync_batch_norm_method='None'):
<add> """Resnet v1 18 beta variant.
<add>
<add> This variant modifies the first convolution layer of ResNet-v1-18. In
<add> particular, it changes the original one 7x7 convolution to three 3x3
<add> convolutions.
<add>
<add> Args:
<add> inputs: A tensor of size [batch, height_in, width_in, channels].
<add> num_classes: Number of predicted classes for classification tasks. If None
<add> we return the features before the logit layer.
<add> is_training: Enable/disable is_training for batch normalization.
<add> global_pool: If True, we perform global average pooling before computing the
<add> logits. Set to True for image classification, False for dense prediction.
<add> output_stride: If None, then the output will be computed at the nominal
<add> network stride. If output_stride is not None, it specifies the requested
<add> ratio of input to output spatial resolution.
<add> multi_grid: Employ a hierarchy of different atrous rates within network.
<add> root_depth_multiplier: Float, depth multiplier used for the first three
<add> convolution layers that replace the 7x7 convolution.
<add> reuse: whether or not the network and its variables should be reused. To be
<add> able to reuse 'scope' must be given.
<add> scope: Optional variable_scope.
<add> sync_batch_norm_method: String, sync batchnorm method.
<add>
<add> Returns:
<add> net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
<add> If global_pool is False, then height_out and width_out are reduced by a
<add> factor of output_stride compared to the respective height_in and width_in,
<add> else both height_out and width_out equal one. If num_classes is None, then
<add> net is the output of the last ResNet block, potentially after global
<add> average pooling. If num_classes is not None, net contains the pre-softmax
<add> activations.
<add> end_points: A dictionary from components of the network to the corresponding
<add> activation.
<add>
<add> Raises:
<add> ValueError: if multi_grid is not None and does not have length = 3.
<add> """
<add> if multi_grid is None:
<add> multi_grid = _DEFAULT_MULTI_GRID_RESNET_18
<add> else:
<add> if len(multi_grid) != 2:
<add> raise ValueError('Expect multi_grid to have length 2.')
<add>
<add> block4_args = []
<add> for rate in multi_grid:
<add> block4_args.append({'depth': 512, 'stride': 1, 'unit_rate': rate})
<add>
<add> blocks = [
<add> resnet_v1_small_beta_block(
<add> 'block1', base_depth=64, num_units=2, stride=2),
<add> resnet_v1_small_beta_block(
<add> 'block2', base_depth=128, num_units=2, stride=2),
<add> resnet_v1_small_beta_block(
<add> 'block3', base_depth=256, num_units=2, stride=2),
<add> resnet_utils.Block('block4', lite_bottleneck, block4_args),
<add> ]
<add> return resnet_v1_beta(
<add> inputs,
<add> blocks=blocks,
<add> num_classes=num_classes,
<add> is_training=is_training,
<add> global_pool=global_pool,
<add> output_stride=output_stride,
<add> root_block_fn=functools.partial(root_block_fn_for_beta_variant,
<add> depth_multiplier=root_depth_multiplier),
<add> reuse=reuse,
<add> scope=scope,
<add> sync_batch_norm_method=sync_batch_norm_method)
<add>
<add>
<ide> def resnet_v1_50(inputs,
<ide> num_classes=None,
<ide> is_training=None,
<ide> global_pool=False,
<ide> output_stride=None,
<ide> multi_grid=None,
<ide> reuse=None,
<del> scope='resnet_v1_50'):
<add> scope='resnet_v1_50',
<add> sync_batch_norm_method='None'):
<ide> """Resnet v1 50.
<ide>
<ide> Args:
<ide> def resnet_v1_50(inputs,
<ide> reuse: whether or not the network and its variables should be reused. To be
<ide> able to reuse 'scope' must be given.
<ide> scope: Optional variable_scope.
<add> sync_batch_norm_method: String, sync batchnorm method.
<ide>
<ide> Returns:
<ide> net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
<ide> def resnet_v1_50(inputs,
<ide> resnet_v1_beta_block(
<ide> 'block3', base_depth=256, num_units=6, stride=2),
<ide> resnet_utils.Block('block4', bottleneck, [
<del> {'depth': 2048,
<del> 'depth_bottleneck': 512,
<del> 'stride': 1,
<add> {'depth': 2048, 'depth_bottleneck': 512, 'stride': 1,
<ide> 'unit_rate': rate} for rate in multi_grid]),
<ide> ]
<ide> return resnet_v1_beta(
<ide> def resnet_v1_50(inputs,
<ide> global_pool=global_pool,
<ide> output_stride=output_stride,
<ide> reuse=reuse,
<del> scope=scope)
<add> scope=scope,
<add> sync_batch_norm_method=sync_batch_norm_method)
<ide>
<ide>
<ide> def resnet_v1_50_beta(inputs,
<ide> def resnet_v1_50_beta(inputs,
<ide> output_stride=None,
<ide> multi_grid=None,
<ide> reuse=None,
<del> scope='resnet_v1_50'):
<add> scope='resnet_v1_50',
<add> sync_batch_norm_method='None'):
<ide> """Resnet v1 50 beta variant.
<ide>
<ide> This variant modifies the first convolution layer of ResNet-v1-50. In
<ide> def resnet_v1_50_beta(inputs,
<ide> reuse: whether or not the network and its variables should be reused. To be
<ide> able to reuse 'scope' must be given.
<ide> scope: Optional variable_scope.
<add> sync_batch_norm_method: String, sync batchnorm method.
<ide>
<ide> Returns:
<ide> net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
<ide> def resnet_v1_50_beta(inputs,
<ide> resnet_v1_beta_block(
<ide> 'block3', base_depth=256, num_units=6, stride=2),
<ide> resnet_utils.Block('block4', bottleneck, [
<del> {'depth': 2048,
<del> 'depth_bottleneck': 512,
<del> 'stride': 1,
<add> {'depth': 2048, 'depth_bottleneck': 512, 'stride': 1,
<ide> 'unit_rate': rate} for rate in multi_grid]),
<ide> ]
<ide> return resnet_v1_beta(
<ide> def resnet_v1_50_beta(inputs,
<ide> output_stride=output_stride,
<ide> root_block_fn=functools.partial(root_block_fn_for_beta_variant),
<ide> reuse=reuse,
<del> scope=scope)
<add> scope=scope,
<add> sync_batch_norm_method=sync_batch_norm_method)
<ide>
<ide>
<ide> def resnet_v1_101(inputs,
<ide> def resnet_v1_101(inputs,
<ide> output_stride=None,
<ide> multi_grid=None,
<ide> reuse=None,
<del> scope='resnet_v1_101'):
<add> scope='resnet_v1_101',
<add> sync_batch_norm_method='None'):
<ide> """Resnet v1 101.
<ide>
<ide> Args:
<ide> def resnet_v1_101(inputs,
<ide> reuse: whether or not the network and its variables should be reused. To be
<ide> able to reuse 'scope' must be given.
<ide> scope: Optional variable_scope.
<add> sync_batch_norm_method: String, sync batchnorm method.
<ide>
<ide> Returns:
<ide> net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
<ide> def resnet_v1_101(inputs,
<ide> resnet_v1_beta_block(
<ide> 'block3', base_depth=256, num_units=23, stride=2),
<ide> resnet_utils.Block('block4', bottleneck, [
<del> {'depth': 2048,
<del> 'depth_bottleneck': 512,
<del> 'stride': 1,
<add> {'depth': 2048, 'depth_bottleneck': 512, 'stride': 1,
<ide> 'unit_rate': rate} for rate in multi_grid]),
<ide> ]
<ide> return resnet_v1_beta(
<ide> def resnet_v1_101(inputs,
<ide> global_pool=global_pool,
<ide> output_stride=output_stride,
<ide> reuse=reuse,
<del> scope=scope)
<add> scope=scope,
<add> sync_batch_norm_method=sync_batch_norm_method)
<ide>
<ide>
<ide> def resnet_v1_101_beta(inputs,
<ide> def resnet_v1_101_beta(inputs,
<ide> output_stride=None,
<ide> multi_grid=None,
<ide> reuse=None,
<del> scope='resnet_v1_101'):
<add> scope='resnet_v1_101',
<add> sync_batch_norm_method='None'):
<ide> """Resnet v1 101 beta variant.
<ide>
<ide> This variant modifies the first convolution layer of ResNet-v1-101. In
<ide> def resnet_v1_101_beta(inputs,
<ide> reuse: whether or not the network and its variables should be reused. To be
<ide> able to reuse 'scope' must be given.
<ide> scope: Optional variable_scope.
<add> sync_batch_norm_method: String, sync batchnorm method.
<ide>
<ide> Returns:
<ide> net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
<ide> def resnet_v1_101_beta(inputs,
<ide> resnet_v1_beta_block(
<ide> 'block3', base_depth=256, num_units=23, stride=2),
<ide> resnet_utils.Block('block4', bottleneck, [
<del> {'depth': 2048,
<del> 'depth_bottleneck': 512,
<del> 'stride': 1,
<add> {'depth': 2048, 'depth_bottleneck': 512, 'stride': 1,
<ide> 'unit_rate': rate} for rate in multi_grid]),
<ide> ]
<ide> return resnet_v1_beta(
<ide> def resnet_v1_101_beta(inputs,
<ide> output_stride=output_stride,
<ide> root_block_fn=functools.partial(root_block_fn_for_beta_variant),
<ide> reuse=reuse,
<del> scope=scope)
<add> scope=scope,
<add> sync_batch_norm_method=sync_batch_norm_method)
<add>
<add>
<add>def resnet_arg_scope(weight_decay=0.0001,
<add> batch_norm_decay=0.997,
<add> batch_norm_epsilon=1e-5,
<add> batch_norm_scale=True,
<add> activation_fn=tf.nn.relu,
<add> use_batch_norm=True,
<add> sync_batch_norm_method='None',
<add> normalization_method='unspecified',
<add> use_weight_standardization=False):
<add> """Defines the default ResNet arg scope.
<add>
<add> Args:
<add> weight_decay: The weight decay to use for regularizing the model.
<add> batch_norm_decay: The moving average decay when estimating layer activation
<add> statistics in batch normalization.
<add> batch_norm_epsilon: Small constant to prevent division by zero when
<add> normalizing activations by their variance in batch normalization.
<add> batch_norm_scale: If True, uses an explicit `gamma` multiplier to scale the
<add> activations in the batch normalization layer.
<add> activation_fn: The activation function which is used in ResNet.
<add> use_batch_norm: Deprecated in favor of normalization_method.
<add> sync_batch_norm_method: String, sync batchnorm method.
<add> normalization_method: String, one of `batch`, `none`, or `group`, to use
<add> batch normalization, no normalization, or group normalization.
<add> use_weight_standardization: Boolean, whether to use weight standardization.
<add>
<add> Returns:
<add> An `arg_scope` to use for the resnet models.
<add> """
<add> batch_norm_params = {
<add> 'decay': batch_norm_decay,
<add> 'epsilon': batch_norm_epsilon,
<add> 'scale': batch_norm_scale,
<add> }
<add> batch_norm = utils.get_batch_norm_fn(sync_batch_norm_method)
<add> if normalization_method == 'batch':
<add> normalizer_fn = batch_norm
<add> elif normalization_method == 'none':
<add> normalizer_fn = None
<add> elif normalization_method == 'group':
<add> normalizer_fn = slim.group_norm
<add> elif normalization_method == 'unspecified':
<add> normalizer_fn = batch_norm if use_batch_norm else None
<add> else:
<add> raise ValueError('Unrecognized normalization_method %s' %
<add> normalization_method)
<add>
<add> with slim.arg_scope([conv2d_ws.conv2d],
<add> weights_regularizer=slim.l2_regularizer(weight_decay),
<add> weights_initializer=slim.variance_scaling_initializer(),
<add> activation_fn=activation_fn,
<add> normalizer_fn=normalizer_fn,
<add> use_weight_standardization=use_weight_standardization):
<add> with slim.arg_scope([batch_norm], **batch_norm_params):
<add> # The following implies padding='SAME' for pool1, which makes feature
<add> # alignment easier for dense prediction tasks. This is also used in
<add> # https://github.com/facebook/fb.resnet.torch. However the accompanying
<add> # code of 'Deep Residual Learning for Image Recognition' uses
<add> # padding='VALID' for pool1. You can switch to that choice by setting
<add> # slim.arg_scope([slim.max_pool2d], padding='VALID').
<add> with slim.arg_scope([slim.max_pool2d], padding='SAME') as arg_sc:
<add> return arg_sc
<ide><path>research/deeplab/core/resnet_v1_beta_test.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> import functools
<ide>
<ide> import numpy as np
<add>import six
<ide> import tensorflow as tf
<add>from tensorflow.contrib import slim as contrib_slim
<ide>
<ide> from deeplab.core import resnet_v1_beta
<ide> from tensorflow.contrib.slim.nets import resnet_utils
<ide>
<del>slim = tf.contrib.slim
<add>slim = contrib_slim
<ide>
<ide>
<ide> def create_test_input(batch, height, width, channels):
<ide> def create_test_input(batch, height, width, channels):
<ide> class ResnetCompleteNetworkTest(tf.test.TestCase):
<ide> """Tests with complete small ResNet v1 networks."""
<ide>
<add> def _resnet_small_lite_bottleneck(self,
<add> inputs,
<add> num_classes=None,
<add> is_training=True,
<add> global_pool=True,
<add> output_stride=None,
<add> multi_grid=None,
<add> reuse=None,
<add> scope='resnet_v1_small'):
<add> """A shallow and thin ResNet v1 with lite_bottleneck."""
<add> if multi_grid is None:
<add> multi_grid = [1, 1]
<add> else:
<add> if len(multi_grid) != 2:
<add> raise ValueError('Expect multi_grid to have length 2.')
<add> block = resnet_v1_beta.resnet_v1_small_beta_block
<add> blocks = [
<add> block('block1', base_depth=1, num_units=1, stride=2),
<add> block('block2', base_depth=2, num_units=1, stride=2),
<add> block('block3', base_depth=4, num_units=1, stride=2),
<add> resnet_utils.Block('block4', resnet_v1_beta.lite_bottleneck, [
<add> {'depth': 8,
<add> 'stride': 1,
<add> 'unit_rate': rate} for rate in multi_grid])]
<add> return resnet_v1_beta.resnet_v1_beta(
<add> inputs,
<add> blocks,
<add> num_classes=num_classes,
<add> is_training=is_training,
<add> global_pool=global_pool,
<add> output_stride=output_stride,
<add> root_block_fn=functools.partial(
<add> resnet_v1_beta.root_block_fn_for_beta_variant,
<add> depth_multiplier=0.25),
<add> reuse=reuse,
<add> scope=scope)
<add>
<ide> def _resnet_small(self,
<ide> inputs,
<ide> num_classes=None,
<ide> def _resnet_small(self,
<ide>
<ide> block = resnet_v1_beta.resnet_v1_beta_block
<ide> blocks = [
<del> block('block1', base_depth=1, num_units=3, stride=2),
<del> block('block2', base_depth=2, num_units=3, stride=2),
<del> block('block3', base_depth=4, num_units=3, stride=2),
<add> block('block1', base_depth=1, num_units=1, stride=2),
<add> block('block2', base_depth=2, num_units=1, stride=2),
<add> block('block3', base_depth=4, num_units=1, stride=2),
<ide> resnet_utils.Block('block4', resnet_v1_beta.bottleneck, [
<del> {'depth': 32,
<del> 'depth_bottleneck': 8,
<del> 'stride': 1,
<add> {'depth': 32, 'depth_bottleneck': 8, 'stride': 1,
<ide> 'unit_rate': rate} for rate in multi_grid])]
<ide>
<ide> return resnet_v1_beta.resnet_v1_beta(
<ide> def _resnet_small(self,
<ide> reuse=reuse,
<ide> scope=scope)
<ide>
<add> def testClassificationEndPointsWithLiteBottleneck(self):
<add> global_pool = True
<add> num_classes = 10
<add> inputs = create_test_input(2, 224, 224, 3)
<add> with slim.arg_scope(resnet_utils.resnet_arg_scope()):
<add> logits, end_points = self._resnet_small_lite_bottleneck(
<add> inputs,
<add> num_classes,
<add> global_pool=global_pool,
<add> scope='resnet')
<add>
<add> self.assertTrue(logits.op.name.startswith('resnet/logits'))
<add> self.assertListEqual(logits.get_shape().as_list(), [2, 1, 1, num_classes])
<add> self.assertIn('predictions', end_points)
<add> self.assertListEqual(end_points['predictions'].get_shape().as_list(),
<add> [2, 1, 1, num_classes])
<add>
<add> def testClassificationEndPointsWithMultigridAndLiteBottleneck(self):
<add> global_pool = True
<add> num_classes = 10
<add> inputs = create_test_input(2, 224, 224, 3)
<add> multi_grid = [1, 2]
<add> with slim.arg_scope(resnet_utils.resnet_arg_scope()):
<add> logits, end_points = self._resnet_small_lite_bottleneck(
<add> inputs,
<add> num_classes,
<add> global_pool=global_pool,
<add> multi_grid=multi_grid,
<add> scope='resnet')
<add>
<add> self.assertTrue(logits.op.name.startswith('resnet/logits'))
<add> self.assertListEqual(logits.get_shape().as_list(), [2, 1, 1, num_classes])
<add> self.assertIn('predictions', end_points)
<add> self.assertListEqual(end_points['predictions'].get_shape().as_list(),
<add> [2, 1, 1, num_classes])
<add>
<add> def testClassificationShapesWithLiteBottleneck(self):
<add> global_pool = True
<add> num_classes = 10
<add> inputs = create_test_input(2, 224, 224, 3)
<add> with slim.arg_scope(resnet_utils.resnet_arg_scope()):
<add> _, end_points = self._resnet_small_lite_bottleneck(
<add> inputs,
<add> num_classes,
<add> global_pool=global_pool,
<add> scope='resnet')
<add> endpoint_to_shape = {
<add> 'resnet/conv1_1': [2, 112, 112, 16],
<add> 'resnet/conv1_2': [2, 112, 112, 16],
<add> 'resnet/conv1_3': [2, 112, 112, 32],
<add> 'resnet/block1': [2, 28, 28, 1],
<add> 'resnet/block2': [2, 14, 14, 2],
<add> 'resnet/block3': [2, 7, 7, 4],
<add> 'resnet/block4': [2, 7, 7, 8]}
<add> for endpoint, shape in six.iteritems(endpoint_to_shape):
<add> self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
<add>
<add> def testFullyConvolutionalEndpointShapesWithLiteBottleneck(self):
<add> global_pool = False
<add> num_classes = 10
<add> inputs = create_test_input(2, 321, 321, 3)
<add> with slim.arg_scope(resnet_utils.resnet_arg_scope()):
<add> _, end_points = self._resnet_small_lite_bottleneck(
<add> inputs,
<add> num_classes,
<add> global_pool=global_pool,
<add> scope='resnet')
<add> endpoint_to_shape = {
<add> 'resnet/conv1_1': [2, 161, 161, 16],
<add> 'resnet/conv1_2': [2, 161, 161, 16],
<add> 'resnet/conv1_3': [2, 161, 161, 32],
<add> 'resnet/block1': [2, 41, 41, 1],
<add> 'resnet/block2': [2, 21, 21, 2],
<add> 'resnet/block3': [2, 11, 11, 4],
<add> 'resnet/block4': [2, 11, 11, 8]}
<add> for endpoint, shape in six.iteritems(endpoint_to_shape):
<add> self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
<add>
<add> def testAtrousFullyConvolutionalEndpointShapesWithLiteBottleneck(self):
<add> global_pool = False
<add> num_classes = 10
<add> output_stride = 8
<add> inputs = create_test_input(2, 321, 321, 3)
<add> with slim.arg_scope(resnet_utils.resnet_arg_scope()):
<add> _, end_points = self._resnet_small_lite_bottleneck(
<add> inputs,
<add> num_classes,
<add> global_pool=global_pool,
<add> output_stride=output_stride,
<add> scope='resnet')
<add> endpoint_to_shape = {
<add> 'resnet/conv1_1': [2, 161, 161, 16],
<add> 'resnet/conv1_2': [2, 161, 161, 16],
<add> 'resnet/conv1_3': [2, 161, 161, 32],
<add> 'resnet/block1': [2, 41, 41, 1],
<add> 'resnet/block2': [2, 41, 41, 2],
<add> 'resnet/block3': [2, 41, 41, 4],
<add> 'resnet/block4': [2, 41, 41, 8]}
<add> for endpoint, shape in six.iteritems(endpoint_to_shape):
<add> self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
<add>
<add> def testAtrousFullyConvolutionalValuesWithLiteBottleneck(self):
<add> """Verify dense feature extraction with atrous convolution."""
<add> nominal_stride = 32
<add> for output_stride in [4, 8, 16, 32, None]:
<add> with slim.arg_scope(resnet_utils.resnet_arg_scope()):
<add> with tf.Graph().as_default():
<add> with self.test_session() as sess:
<add> tf.set_random_seed(0)
<add> inputs = create_test_input(2, 81, 81, 3)
<add> # Dense feature extraction followed by subsampling.
<add> output, _ = self._resnet_small_lite_bottleneck(
<add> inputs,
<add> None,
<add> is_training=False,
<add> global_pool=False,
<add> output_stride=output_stride)
<add> if output_stride is None:
<add> factor = 1
<add> else:
<add> factor = nominal_stride // output_stride
<add> output = resnet_utils.subsample(output, factor)
<add> # Make the two networks use the same weights.
<add> tf.get_variable_scope().reuse_variables()
<add> # Feature extraction at the nominal network rate.
<add> expected, _ = self._resnet_small_lite_bottleneck(
<add> inputs,
<add> None,
<add> is_training=False,
<add> global_pool=False)
<add> sess.run(tf.global_variables_initializer())
<add> self.assertAllClose(output.eval(), expected.eval(),
<add> atol=1e-4, rtol=1e-4)
<add>
<add> def testUnknownBatchSizeWithLiteBottleneck(self):
<add> batch = 2
<add> height, width = 65, 65
<add> global_pool = True
<add> num_classes = 10
<add> inputs = create_test_input(None, height, width, 3)
<add> with slim.arg_scope(resnet_utils.resnet_arg_scope()):
<add> logits, _ = self._resnet_small_lite_bottleneck(
<add> inputs,
<add> num_classes,
<add> global_pool=global_pool,
<add> scope='resnet')
<add> self.assertTrue(logits.op.name.startswith('resnet/logits'))
<add> self.assertListEqual(logits.get_shape().as_list(),
<add> [None, 1, 1, num_classes])
<add> images = create_test_input(batch, height, width, 3)
<add> with self.test_session() as sess:
<add> sess.run(tf.global_variables_initializer())
<add> output = sess.run(logits, {inputs: images.eval()})
<add> self.assertEqual(output.shape, (batch, 1, 1, num_classes))
<add>
<add> def testFullyConvolutionalUnknownHeightWidthWithLiteBottleneck(self):
<add> batch = 2
<add> height, width = 65, 65
<add> global_pool = False
<add> inputs = create_test_input(batch, None, None, 3)
<add> with slim.arg_scope(resnet_utils.resnet_arg_scope()):
<add> output, _ = self._resnet_small_lite_bottleneck(
<add> inputs,
<add> None,
<add> global_pool=global_pool)
<add> self.assertListEqual(output.get_shape().as_list(),
<add> [batch, None, None, 8])
<add> images = create_test_input(batch, height, width, 3)
<add> with self.test_session() as sess:
<add> sess.run(tf.global_variables_initializer())
<add> output = sess.run(output, {inputs: images.eval()})
<add> self.assertEqual(output.shape, (batch, 3, 3, 8))
<add>
<add> def testAtrousFullyConvolutionalUnknownHeightWidthWithLiteBottleneck(self):
<add> batch = 2
<add> height, width = 65, 65
<add> global_pool = False
<add> output_stride = 8
<add> inputs = create_test_input(batch, None, None, 3)
<add> with slim.arg_scope(resnet_utils.resnet_arg_scope()):
<add> output, _ = self._resnet_small_lite_bottleneck(
<add> inputs,
<add> None,
<add> global_pool=global_pool,
<add> output_stride=output_stride)
<add> self.assertListEqual(output.get_shape().as_list(),
<add> [batch, None, None, 8])
<add> images = create_test_input(batch, height, width, 3)
<add> with self.test_session() as sess:
<add> sess.run(tf.global_variables_initializer())
<add> output = sess.run(output, {inputs: images.eval()})
<add> self.assertEqual(output.shape, (batch, 9, 9, 8))
<add>
<ide> def testClassificationEndPoints(self):
<ide> global_pool = True
<ide> num_classes = 10
<ide> def testClassificationEndPoints(self):
<ide>
<ide> self.assertTrue(logits.op.name.startswith('resnet/logits'))
<ide> self.assertListEqual(logits.get_shape().as_list(), [2, 1, 1, num_classes])
<del> self.assertTrue('predictions' in end_points)
<add> self.assertIn('predictions', end_points)
<add> self.assertListEqual(end_points['predictions'].get_shape().as_list(),
<add> [2, 1, 1, num_classes])
<add>
<add> def testClassificationEndPointsWithWS(self):
<add> global_pool = True
<add> num_classes = 10
<add> inputs = create_test_input(2, 224, 224, 3)
<add> with slim.arg_scope(
<add> resnet_v1_beta.resnet_arg_scope(use_weight_standardization=True)):
<add> logits, end_points = self._resnet_small(
<add> inputs, num_classes, global_pool=global_pool, scope='resnet')
<add>
<add> self.assertTrue(logits.op.name.startswith('resnet/logits'))
<add> self.assertListEqual(logits.get_shape().as_list(), [2, 1, 1, num_classes])
<add> self.assertIn('predictions', end_points)
<add> self.assertListEqual(end_points['predictions'].get_shape().as_list(),
<add> [2, 1, 1, num_classes])
<add>
<add> def testClassificationEndPointsWithGN(self):
<add> global_pool = True
<add> num_classes = 10
<add> inputs = create_test_input(2, 224, 224, 3)
<add> with slim.arg_scope(
<add> resnet_v1_beta.resnet_arg_scope(normalization_method='group')):
<add> with slim.arg_scope([slim.group_norm], groups=1):
<add> logits, end_points = self._resnet_small(
<add> inputs, num_classes, global_pool=global_pool, scope='resnet')
<add>
<add> self.assertTrue(logits.op.name.startswith('resnet/logits'))
<add> self.assertListEqual(logits.get_shape().as_list(), [2, 1, 1, num_classes])
<add> self.assertIn('predictions', end_points)
<add> self.assertListEqual(end_points['predictions'].get_shape().as_list(),
<add> [2, 1, 1, num_classes])
<add>
<add> def testInvalidGroupsWithGN(self):
<add> global_pool = True
<add> num_classes = 10
<add> inputs = create_test_input(2, 224, 224, 3)
<add> with self.assertRaisesRegexp(ValueError, 'Invalid groups'):
<add> with slim.arg_scope(
<add> resnet_v1_beta.resnet_arg_scope(normalization_method='group')):
<add> with slim.arg_scope([slim.group_norm], groups=32):
<add> _, _ = self._resnet_small(
<add> inputs, num_classes, global_pool=global_pool, scope='resnet')
<add>
<add> def testClassificationEndPointsWithGNWS(self):
<add> global_pool = True
<add> num_classes = 10
<add> inputs = create_test_input(2, 224, 224, 3)
<add> with slim.arg_scope(
<add> resnet_v1_beta.resnet_arg_scope(
<add> normalization_method='group', use_weight_standardization=True)):
<add> with slim.arg_scope([slim.group_norm], groups=1):
<add> logits, end_points = self._resnet_small(
<add> inputs, num_classes, global_pool=global_pool, scope='resnet')
<add>
<add> self.assertTrue(logits.op.name.startswith('resnet/logits'))
<add> self.assertListEqual(logits.get_shape().as_list(), [2, 1, 1, num_classes])
<add> self.assertIn('predictions', end_points)
<ide> self.assertListEqual(end_points['predictions'].get_shape().as_list(),
<ide> [2, 1, 1, num_classes])
<ide>
<ide> def testClassificationEndPointsWithMultigrid(self):
<ide>
<ide> self.assertTrue(logits.op.name.startswith('resnet/logits'))
<ide> self.assertListEqual(logits.get_shape().as_list(), [2, 1, 1, num_classes])
<del> self.assertTrue('predictions' in end_points)
<add> self.assertIn('predictions', end_points)
<ide> self.assertListEqual(end_points['predictions'].get_shape().as_list(),
<ide> [2, 1, 1, num_classes])
<ide>
<ide> def testClassificationShapes(self):
<ide> 'resnet/block2': [2, 14, 14, 8],
<ide> 'resnet/block3': [2, 7, 7, 16],
<ide> 'resnet/block4': [2, 7, 7, 32]}
<del> for endpoint, shape in endpoint_to_shape.iteritems():
<add> for endpoint, shape in six.iteritems(endpoint_to_shape):
<ide> self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
<ide>
<ide> def testFullyConvolutionalEndpointShapes(self):
<ide> def testFullyConvolutionalEndpointShapes(self):
<ide> 'resnet/block2': [2, 21, 21, 8],
<ide> 'resnet/block3': [2, 11, 11, 16],
<ide> 'resnet/block4': [2, 11, 11, 32]}
<del> for endpoint, shape in endpoint_to_shape.iteritems():
<add> for endpoint, shape in six.iteritems(endpoint_to_shape):
<ide> self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
<ide>
<ide> def testAtrousFullyConvolutionalEndpointShapes(self):
<ide> def testAtrousFullyConvolutionalEndpointShapes(self):
<ide> 'resnet/block2': [2, 41, 41, 8],
<ide> 'resnet/block3': [2, 41, 41, 16],
<ide> 'resnet/block4': [2, 41, 41, 32]}
<del> for endpoint, shape in endpoint_to_shape.iteritems():
<add> for endpoint, shape in six.iteritems(endpoint_to_shape):
<ide> self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
<ide>
<ide> def testAtrousFullyConvolutionalValues(self):
<ide> def testUnknownBatchSize(self):
<ide> with self.test_session() as sess:
<ide> sess.run(tf.global_variables_initializer())
<ide> output = sess.run(logits, {inputs: images.eval()})
<del> self.assertEquals(output.shape, (batch, 1, 1, num_classes))
<add> self.assertEqual(output.shape, (batch, 1, 1, num_classes))
<ide>
<ide> def testFullyConvolutionalUnknownHeightWidth(self):
<ide> batch = 2
<ide> def testFullyConvolutionalUnknownHeightWidth(self):
<ide> with self.test_session() as sess:
<ide> sess.run(tf.global_variables_initializer())
<ide> output = sess.run(output, {inputs: images.eval()})
<del> self.assertEquals(output.shape, (batch, 3, 3, 32))
<add> self.assertEqual(output.shape, (batch, 3, 3, 32))
<ide>
<ide> def testAtrousFullyConvolutionalUnknownHeightWidth(self):
<ide> batch = 2
<ide> def testAtrousFullyConvolutionalUnknownHeightWidth(self):
<ide> with self.test_session() as sess:
<ide> sess.run(tf.global_variables_initializer())
<ide> output = sess.run(output, {inputs: images.eval()})
<del> self.assertEquals(output.shape, (batch, 9, 9, 32))
<add> self.assertEqual(output.shape, (batch, 9, 9, 32))
<ide>
<ide>
<ide> if __name__ == '__main__':
<ide><path>research/deeplab/core/utils.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide>
<ide> """This script contains utility functions."""
<ide> import tensorflow as tf
<add>from tensorflow.contrib import framework as contrib_framework
<add>from tensorflow.contrib import slim as contrib_slim
<ide>
<del>slim = tf.contrib.slim
<add>slim = contrib_slim
<add>
<add>
<add># Quantized version of sigmoid function.
<add>q_sigmoid = lambda x: tf.nn.relu6(x + 3) * 0.16667
<ide>
<ide>
<ide> def resize_bilinear(images, size, output_dtype=tf.float32):
<ide> def split_separable_conv2d(inputs,
<ide> stddev=pointwise_weights_initializer_stddev),
<ide> weights_regularizer=slim.l2_regularizer(weight_decay),
<ide> scope=scope + '_pointwise')
<add>
<add>
<add>def get_label_weight_mask(labels, ignore_label, num_classes, label_weights=1.0):
<add> """Gets the label weight mask.
<add>
<add> Args:
<add> labels: A Tensor of labels with the shape of [-1].
<add> ignore_label: Integer, label to ignore.
<add> num_classes: Integer, the number of semantic classes.
<add> label_weights: A float or a list of weights. If it is a float, it means all
<add> the labels have the same weight. If it is a list of weights, then each
<add> element in the list represents the weight for the label of its index, for
<add> example, label_weights = [0.1, 0.5] means the weight for label 0 is 0.1
<add> and the weight for label 1 is 0.5.
<add>
<add> Returns:
<add> A Tensor of label weights with the same shape of labels, each element is the
<add> weight for the label with the same index in labels and the element is 0.0
<add> if the label is to ignore.
<add>
<add> Raises:
<add> ValueError: If label_weights is neither a float nor a list, or if
<add> label_weights is a list and its length is not equal to num_classes.
<add> """
<add> if not isinstance(label_weights, (float, list)):
<add> raise ValueError(
<add> 'The type of label_weights is invalid, it must be a float or a list.')
<add>
<add> if isinstance(label_weights, list) and len(label_weights) != num_classes:
<add> raise ValueError(
<add> 'Length of label_weights must be equal to num_classes if it is a list, '
<add> 'label_weights: %s, num_classes: %d.' % (label_weights, num_classes))
<add>
<add> not_ignore_mask = tf.not_equal(labels, ignore_label)
<add> not_ignore_mask = tf.cast(not_ignore_mask, tf.float32)
<add> if isinstance(label_weights, float):
<add> return not_ignore_mask * label_weights
<add>
<add> label_weights = tf.constant(label_weights, tf.float32)
<add> weight_mask = tf.einsum('...y,y->...',
<add> tf.one_hot(labels, num_classes, dtype=tf.float32),
<add> label_weights)
<add> return tf.multiply(not_ignore_mask, weight_mask)
<add>
<add>
<add>def get_batch_norm_fn(sync_batch_norm_method):
<add> """Gets batch norm function.
<add>
<add> Currently we only support the following methods:
<add> - `None` (no sync batch norm). We use slim.batch_norm in this case.
<add>
<add> Args:
<add> sync_batch_norm_method: String, method used to sync batch norm.
<add>
<add> Returns:
<add> Batchnorm function.
<add>
<add> Raises:
<add> ValueError: If sync_batch_norm_method is not supported.
<add> """
<add> if sync_batch_norm_method == 'None':
<add> return slim.batch_norm
<add> else:
<add> raise ValueError('Unsupported sync_batch_norm_method.')
<add>
<add>
<add>def get_batch_norm_params(decay=0.9997,
<add> epsilon=1e-5,
<add> center=True,
<add> scale=True,
<add> is_training=True,
<add> sync_batch_norm_method='None',
<add> initialize_gamma_as_zeros=False):
<add> """Gets batch norm parameters.
<add>
<add> Args:
<add> decay: Float, decay for the moving average.
<add> epsilon: Float, value added to variance to avoid dividing by zero.
<add> center: Boolean. If True, add offset of `beta` to normalized tensor. If
<add> False,`beta` is ignored.
<add> scale: Boolean. If True, multiply by `gamma`. If False, `gamma` is not used.
<add> is_training: Boolean, whether or not the layer is in training mode.
<add> sync_batch_norm_method: String, method used to sync batch norm.
<add> initialize_gamma_as_zeros: Boolean, initializing `gamma` as zeros or not.
<add>
<add> Returns:
<add> A dictionary for batchnorm parameters.
<add>
<add> Raises:
<add> ValueError: If sync_batch_norm_method is not supported.
<add> """
<add> batch_norm_params = {
<add> 'is_training': is_training,
<add> 'decay': decay,
<add> 'epsilon': epsilon,
<add> 'scale': scale,
<add> 'center': center,
<add> }
<add> if initialize_gamma_as_zeros:
<add> if sync_batch_norm_method == 'None':
<add> # Slim-type gamma_initialier.
<add> batch_norm_params['param_initializers'] = {
<add> 'gamma': tf.zeros_initializer(),
<add> }
<add> else:
<add> raise ValueError('Unsupported sync_batch_norm_method.')
<add> return batch_norm_params
<ide><path>research/deeplab/core/utils_test.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> # ==============================================================================
<ide> """Tests for utils.py."""
<ide>
<add>import numpy as np
<ide> import tensorflow as tf
<ide>
<ide> from deeplab.core import utils
<ide> def testScaleDimensionOutput(self):
<ide> self.assertEqual(193, utils.scale_dimension(321, 0.6))
<ide> self.assertEqual(241, utils.scale_dimension(321, 0.75))
<ide>
<add> def testGetLabelWeightMask_withFloatLabelWeights(self):
<add> labels = tf.constant([0, 4, 1, 3, 2])
<add> ignore_label = 4
<add> num_classes = 5
<add> label_weights = 0.5
<add> expected_label_weight_mask = np.array([0.5, 0.0, 0.5, 0.5, 0.5],
<add> dtype=np.float32)
<add>
<add> with self.test_session() as sess:
<add> label_weight_mask = utils.get_label_weight_mask(
<add> labels, ignore_label, num_classes, label_weights=label_weights)
<add> label_weight_mask = sess.run(label_weight_mask)
<add> self.assertAllEqual(label_weight_mask, expected_label_weight_mask)
<add>
<add> def testGetLabelWeightMask_withListLabelWeights(self):
<add> labels = tf.constant([0, 4, 1, 3, 2])
<add> ignore_label = 4
<add> num_classes = 5
<add> label_weights = [0.0, 0.1, 0.2, 0.3, 0.4]
<add> expected_label_weight_mask = np.array([0.0, 0.0, 0.1, 0.3, 0.2],
<add> dtype=np.float32)
<add>
<add> with self.test_session() as sess:
<add> label_weight_mask = utils.get_label_weight_mask(
<add> labels, ignore_label, num_classes, label_weights=label_weights)
<add> label_weight_mask = sess.run(label_weight_mask)
<add> self.assertAllEqual(label_weight_mask, expected_label_weight_mask)
<add>
<add> def testGetLabelWeightMask_withInvalidLabelWeightsType(self):
<add> labels = tf.constant([0, 4, 1, 3, 2])
<add> ignore_label = 4
<add> num_classes = 5
<add>
<add> self.assertRaisesWithRegexpMatch(
<add> ValueError,
<add> '^The type of label_weights is invalid, it must be a float or a list',
<add> utils.get_label_weight_mask,
<add> labels=labels,
<add> ignore_label=ignore_label,
<add> num_classes=num_classes,
<add> label_weights=None)
<add>
<add> def testGetLabelWeightMask_withInvalidLabelWeightsLength(self):
<add> labels = tf.constant([0, 4, 1, 3, 2])
<add> ignore_label = 4
<add> num_classes = 5
<add> label_weights = [0.0, 0.1, 0.2]
<add>
<add> self.assertRaisesWithRegexpMatch(
<add> ValueError,
<add> '^Length of label_weights must be equal to num_classes if it is a list',
<add> utils.get_label_weight_mask,
<add> labels=labels,
<add> ignore_label=ignore_label,
<add> num_classes=num_classes,
<add> label_weights=label_weights)
<add>
<ide>
<ide> if __name__ == '__main__':
<ide> tf.test.main()
<ide><path>research/deeplab/core/xception.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> Tobias Weyand, Marco Andreetto, Hartwig Adam
<ide> https://arxiv.org/abs/1704.04861
<ide> """
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import collections
<add>from six.moves import range
<ide> import tensorflow as tf
<add>from tensorflow.contrib import slim as contrib_slim
<ide>
<add>from deeplab.core import utils
<ide> from tensorflow.contrib.slim.nets import resnet_utils
<add>from nets.mobilenet import conv_blocks as mobilenet_v3_ops
<ide>
<del>slim = tf.contrib.slim
<add>slim = contrib_slim
<ide>
<ide>
<ide> _DEFAULT_MULTI_GRID = [1, 1, 1]
<ide> def xception_module(inputs,
<ide> depth_list,
<ide> skip_connection_type,
<ide> stride,
<add> kernel_size=3,
<ide> unit_rate_list=None,
<ide> rate=1,
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=False,
<ide> outputs_collections=None,
<ide> scope=None,
<ide> use_bounded_activation=False,
<del> use_explicit_padding=True):
<add> use_explicit_padding=True,
<add> use_squeeze_excite=False,
<add> se_pool_size=None):
<ide> """An Xception module.
<ide>
<ide> The output of one Xception module is equal to the sum of `residual` and
<ide> def xception_module(inputs,
<ide> supports 'conv', 'sum', or 'none'.
<ide> stride: The block unit's stride. Determines the amount of downsampling of
<ide> the units output compared to its input.
<add> kernel_size: Integer, convolution kernel size.
<ide> unit_rate_list: A list of three integers, determining the unit rate for
<ide> each separable convolution in the xception module.
<ide> rate: An integer, rate for atrous convolution.
<ide> def xception_module(inputs,
<ide> use_explicit_padding: If True, use explicit padding to make the model fully
<ide> compatible with the open source version, otherwise use the native
<ide> Tensorflow 'SAME' padding.
<add> use_squeeze_excite: Boolean, use squeeze-and-excitation or not.
<add> se_pool_size: None or integer specifying the pooling size used in SE module.
<ide>
<ide> Returns:
<ide> The Xception module's output.
<ide> def _separable_conv(features, depth, kernel_size, depth_multiplier,
<ide> for i in range(3):
<ide> residual = _separable_conv(residual,
<ide> depth_list[i],
<del> kernel_size=3,
<add> kernel_size=kernel_size,
<ide> depth_multiplier=1,
<ide> regularize_depthwise=regularize_depthwise,
<ide> rate=rate*unit_rate_list[i],
<ide> stride=stride if i == 2 else 1,
<ide> scope='separable_conv' + str(i+1))
<add> if use_squeeze_excite:
<add> residual = mobilenet_v3_ops.squeeze_excite(
<add> input_tensor=residual,
<add> squeeze_factor=16,
<add> inner_activation_fn=tf.nn.relu,
<add> gating_fn=lambda x: tf.nn.relu6(x+3)*0.16667,
<add> pool=se_pool_size)
<add>
<ide> if skip_connection_type == 'conv':
<ide> shortcut = slim.conv2d(inputs,
<ide> depth_list[-1],
<ide> def xception(inputs,
<ide> keep_prob=0.5,
<ide> output_stride=None,
<ide> reuse=None,
<del> scope=None):
<add> scope=None,
<add> sync_batch_norm_method='None'):
<ide> """Generator for Xception models.
<ide>
<ide> This function generates a family of Xception models. See the xception_*()
<ide> def xception(inputs,
<ide> reuse: whether or not the network and its variables should be reused. To be
<ide> able to reuse 'scope' must be given.
<ide> scope: Optional variable_scope.
<add> sync_batch_norm_method: String, sync batchnorm method. Currently only
<add> support `None`.
<ide>
<ide> Returns:
<ide> net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
<ide> def xception(inputs,
<ide> with tf.variable_scope(
<ide> scope, 'xception', [inputs], reuse=reuse) as sc:
<ide> end_points_collection = sc.original_name_scope + 'end_points'
<add> batch_norm = utils.get_batch_norm_fn(sync_batch_norm_method)
<ide> with slim.arg_scope([slim.conv2d,
<ide> slim.separable_conv2d,
<ide> xception_module,
<ide> stack_blocks_dense],
<ide> outputs_collections=end_points_collection):
<del> with slim.arg_scope([slim.batch_norm], is_training=is_training):
<add> with slim.arg_scope([batch_norm], is_training=is_training):
<ide> net = inputs
<ide> if output_stride is not None:
<ide> if output_stride % 2 != 0:
<ide> raise ValueError('The output_stride needs to be a multiple of 2.')
<del> output_stride /= 2
<add> output_stride //= 2
<ide> # Root block function operated on inputs.
<ide> net = resnet_utils.conv2d_same(net, 32, 3, stride=2,
<ide> scope='entry_flow/conv1_1')
<ide> def xception_block(scope,
<ide> regularize_depthwise,
<ide> num_units,
<ide> stride,
<del> unit_rate_list=None):
<add> kernel_size=3,
<add> unit_rate_list=None,
<add> use_squeeze_excite=False,
<add> se_pool_size=None):
<ide> """Helper function for creating a Xception block.
<ide>
<ide> Args:
<ide> def xception_block(scope,
<ide> num_units: The number of units in the block.
<ide> stride: The stride of the block, implemented as a stride in the last unit.
<ide> All other units have stride=1.
<add> kernel_size: Integer, convolution kernel size.
<ide> unit_rate_list: A list of three integers, determining the unit rate in the
<ide> corresponding xception block.
<add> use_squeeze_excite: Boolean, use squeeze-and-excitation or not.
<add> se_pool_size: None or integer specifying the pooling size used in SE module.
<ide>
<ide> Returns:
<ide> An Xception block.
<ide> def xception_block(scope,
<ide> 'activation_fn_in_separable_conv': activation_fn_in_separable_conv,
<ide> 'regularize_depthwise': regularize_depthwise,
<ide> 'stride': stride,
<add> 'kernel_size': kernel_size,
<ide> 'unit_rate_list': unit_rate_list,
<add> 'use_squeeze_excite': use_squeeze_excite,
<add> 'se_pool_size': se_pool_size,
<ide> }] * num_units)
<ide>
<ide>
<ide> def xception_41(inputs,
<ide> regularize_depthwise=False,
<ide> multi_grid=None,
<ide> reuse=None,
<del> scope='xception_41'):
<add> scope='xception_41',
<add> sync_batch_norm_method='None'):
<ide> """Xception-41 model."""
<ide> blocks = [
<ide> xception_block('entry_flow/block1',
<ide> def xception_41(inputs,
<ide> keep_prob=keep_prob,
<ide> output_stride=output_stride,
<ide> reuse=reuse,
<del> scope=scope)
<del>
<del>
<del>def xception_65(inputs,
<del> num_classes=None,
<del> is_training=True,
<del> global_pool=True,
<del> keep_prob=0.5,
<del> output_stride=None,
<del> regularize_depthwise=False,
<del> multi_grid=None,
<del> reuse=None,
<del> scope='xception_65'):
<del> """Xception-65 model."""
<add> scope=scope,
<add> sync_batch_norm_method=sync_batch_norm_method)
<add>
<add>
<add>def xception_65_factory(inputs,
<add> num_classes=None,
<add> is_training=True,
<add> global_pool=True,
<add> keep_prob=0.5,
<add> output_stride=None,
<add> regularize_depthwise=False,
<add> kernel_size=3,
<add> multi_grid=None,
<add> reuse=None,
<add> use_squeeze_excite=False,
<add> se_pool_size=None,
<add> scope='xception_65',
<add> sync_batch_norm_method='None'):
<add> """Xception-65 model factory."""
<ide> blocks = [
<ide> xception_block('entry_flow/block1',
<ide> depth_list=[128, 128, 128],
<ide> skip_connection_type='conv',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<del> stride=2),
<add> stride=2,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=False,
<add> se_pool_size=se_pool_size),
<ide> xception_block('entry_flow/block2',
<ide> depth_list=[256, 256, 256],
<ide> skip_connection_type='conv',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<del> stride=2),
<add> stride=2,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=False,
<add> se_pool_size=se_pool_size),
<ide> xception_block('entry_flow/block3',
<ide> depth_list=[728, 728, 728],
<ide> skip_connection_type='conv',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<del> stride=2),
<add> stride=2,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=use_squeeze_excite,
<add> se_pool_size=se_pool_size),
<ide> xception_block('middle_flow/block1',
<ide> depth_list=[728, 728, 728],
<ide> skip_connection_type='sum',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=16,
<del> stride=1),
<add> stride=1,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=use_squeeze_excite,
<add> se_pool_size=se_pool_size),
<ide> xception_block('exit_flow/block1',
<ide> depth_list=[728, 1024, 1024],
<ide> skip_connection_type='conv',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<del> stride=2),
<add> stride=2,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=use_squeeze_excite,
<add> se_pool_size=se_pool_size),
<ide> xception_block('exit_flow/block2',
<ide> depth_list=[1536, 1536, 2048],
<ide> skip_connection_type='none',
<ide> activation_fn_in_separable_conv=True,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<ide> stride=1,
<del> unit_rate_list=multi_grid),
<add> kernel_size=kernel_size,
<add> unit_rate_list=multi_grid,
<add> use_squeeze_excite=False,
<add> se_pool_size=se_pool_size),
<ide> ]
<ide> return xception(inputs,
<ide> blocks=blocks,
<ide> def xception_65(inputs,
<ide> keep_prob=keep_prob,
<ide> output_stride=output_stride,
<ide> reuse=reuse,
<del> scope=scope)
<add> scope=scope,
<add> sync_batch_norm_method=sync_batch_norm_method)
<ide>
<ide>
<del>def xception_71(inputs,
<add>def xception_65(inputs,
<ide> num_classes=None,
<ide> is_training=True,
<ide> global_pool=True,
<ide> def xception_71(inputs,
<ide> regularize_depthwise=False,
<ide> multi_grid=None,
<ide> reuse=None,
<del> scope='xception_71'):
<del> """Xception-71 model."""
<add> scope='xception_65',
<add> sync_batch_norm_method='None'):
<add> """Xception-65 model."""
<add> return xception_65_factory(
<add> inputs=inputs,
<add> num_classes=num_classes,
<add> is_training=is_training,
<add> global_pool=global_pool,
<add> keep_prob=keep_prob,
<add> output_stride=output_stride,
<add> regularize_depthwise=regularize_depthwise,
<add> multi_grid=multi_grid,
<add> reuse=reuse,
<add> scope=scope,
<add> use_squeeze_excite=False,
<add> se_pool_size=None,
<add> sync_batch_norm_method=sync_batch_norm_method)
<add>
<add>
<add>def xception_71_factory(inputs,
<add> num_classes=None,
<add> is_training=True,
<add> global_pool=True,
<add> keep_prob=0.5,
<add> output_stride=None,
<add> regularize_depthwise=False,
<add> kernel_size=3,
<add> multi_grid=None,
<add> reuse=None,
<add> scope='xception_71',
<add> use_squeeze_excite=False,
<add> se_pool_size=None,
<add> sync_batch_norm_method='None'):
<add> """Xception-71 model factory."""
<ide> blocks = [
<ide> xception_block('entry_flow/block1',
<ide> depth_list=[128, 128, 128],
<ide> skip_connection_type='conv',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<del> stride=2),
<add> stride=2,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=False,
<add> se_pool_size=se_pool_size),
<ide> xception_block('entry_flow/block2',
<ide> depth_list=[256, 256, 256],
<ide> skip_connection_type='conv',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<del> stride=1),
<add> stride=1,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=False,
<add> se_pool_size=se_pool_size),
<ide> xception_block('entry_flow/block3',
<ide> depth_list=[256, 256, 256],
<ide> skip_connection_type='conv',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<del> stride=2),
<add> stride=2,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=False,
<add> se_pool_size=se_pool_size),
<ide> xception_block('entry_flow/block4',
<ide> depth_list=[728, 728, 728],
<ide> skip_connection_type='conv',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<del> stride=1),
<add> stride=1,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=use_squeeze_excite,
<add> se_pool_size=se_pool_size),
<ide> xception_block('entry_flow/block5',
<ide> depth_list=[728, 728, 728],
<ide> skip_connection_type='conv',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<del> stride=2),
<add> stride=2,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=use_squeeze_excite,
<add> se_pool_size=se_pool_size),
<ide> xception_block('middle_flow/block1',
<ide> depth_list=[728, 728, 728],
<ide> skip_connection_type='sum',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=16,
<del> stride=1),
<add> stride=1,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=use_squeeze_excite,
<add> se_pool_size=se_pool_size),
<ide> xception_block('exit_flow/block1',
<ide> depth_list=[728, 1024, 1024],
<ide> skip_connection_type='conv',
<ide> activation_fn_in_separable_conv=False,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<del> stride=2),
<add> stride=2,
<add> kernel_size=kernel_size,
<add> use_squeeze_excite=use_squeeze_excite,
<add> se_pool_size=se_pool_size),
<ide> xception_block('exit_flow/block2',
<ide> depth_list=[1536, 1536, 2048],
<ide> skip_connection_type='none',
<ide> activation_fn_in_separable_conv=True,
<ide> regularize_depthwise=regularize_depthwise,
<ide> num_units=1,
<ide> stride=1,
<del> unit_rate_list=multi_grid),
<add> kernel_size=kernel_size,
<add> unit_rate_list=multi_grid,
<add> use_squeeze_excite=False,
<add> se_pool_size=se_pool_size),
<ide> ]
<ide> return xception(inputs,
<ide> blocks=blocks,
<ide> def xception_71(inputs,
<ide> keep_prob=keep_prob,
<ide> output_stride=output_stride,
<ide> reuse=reuse,
<del> scope=scope)
<add> scope=scope,
<add> sync_batch_norm_method=sync_batch_norm_method)
<add>
<add>
<add>def xception_71(inputs,
<add> num_classes=None,
<add> is_training=True,
<add> global_pool=True,
<add> keep_prob=0.5,
<add> output_stride=None,
<add> regularize_depthwise=False,
<add> multi_grid=None,
<add> reuse=None,
<add> scope='xception_71',
<add> sync_batch_norm_method='None'):
<add> """Xception-71 model."""
<add> return xception_71_factory(
<add> inputs=inputs,
<add> num_classes=num_classes,
<add> is_training=is_training,
<add> global_pool=global_pool,
<add> keep_prob=keep_prob,
<add> output_stride=output_stride,
<add> regularize_depthwise=regularize_depthwise,
<add> multi_grid=multi_grid,
<add> reuse=reuse,
<add> scope=scope,
<add> use_squeeze_excite=False,
<add> se_pool_size=None,
<add> sync_batch_norm_method=sync_batch_norm_method)
<ide>
<ide>
<ide> def xception_arg_scope(weight_decay=0.00004,
<ide> def xception_arg_scope(weight_decay=0.00004,
<ide> weights_initializer_stddev=0.09,
<ide> regularize_depthwise=False,
<ide> use_batch_norm=True,
<del> use_bounded_activation=False):
<add> use_bounded_activation=False,
<add> sync_batch_norm_method='None'):
<ide> """Defines the default Xception arg scope.
<ide>
<ide> Args:
<ide> def xception_arg_scope(weight_decay=0.00004,
<ide> use_batch_norm: Whether or not to use batch normalization.
<ide> use_bounded_activation: Whether or not to use bounded activations. Bounded
<ide> activations better lend themselves to quantized inference.
<add> sync_batch_norm_method: String, sync batchnorm method. Currently only
<add> support `None`. Also, it is only effective for Xception.
<ide>
<ide> Returns:
<ide> An `arg_scope` to use for the Xception models.
<ide> def xception_arg_scope(weight_decay=0.00004,
<ide> else:
<ide> depthwise_regularizer = None
<ide> activation_fn = tf.nn.relu6 if use_bounded_activation else tf.nn.relu
<add> batch_norm = utils.get_batch_norm_fn(sync_batch_norm_method)
<ide> with slim.arg_scope(
<ide> [slim.conv2d, slim.separable_conv2d],
<ide> weights_initializer=tf.truncated_normal_initializer(
<ide> stddev=weights_initializer_stddev),
<ide> activation_fn=activation_fn,
<del> normalizer_fn=slim.batch_norm if use_batch_norm else None):
<del> with slim.arg_scope([slim.batch_norm], **batch_norm_params):
<add> normalizer_fn=batch_norm if use_batch_norm else None):
<add> with slim.arg_scope([batch_norm], **batch_norm_params):
<ide> with slim.arg_scope(
<ide> [slim.conv2d],
<ide> weights_regularizer=slim.l2_regularizer(weight_decay)):
<ide><path>research/deeplab/core/xception_test.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> import numpy as np
<ide> import six
<ide> import tensorflow as tf
<add>from tensorflow.contrib import slim as contrib_slim
<ide>
<ide> from deeplab.core import xception
<ide> from tensorflow.contrib.slim.nets import resnet_utils
<ide>
<del>slim = tf.contrib.slim
<add>slim = contrib_slim
<ide>
<ide>
<ide> def create_test_input(batch, height, width, channels):
<ide> """Create test input tensor."""
<ide> if None in [batch, height, width, channels]:
<ide> return tf.placeholder(tf.float32, (batch, height, width, channels))
<ide> else:
<del> return tf.to_float(
<add> return tf.cast(
<ide> np.tile(
<ide> np.reshape(
<ide> np.reshape(np.arange(height), [height, 1]) +
<ide> np.reshape(np.arange(width), [1, width]),
<ide> [1, height, width, 1]),
<del> [batch, 1, 1, channels]))
<add> [batch, 1, 1, channels]),
<add> tf.float32)
<ide>
<ide>
<ide> class UtilityFunctionTest(tf.test.TestCase):
<ide> def testSeparableConv2DSameWithInputEvenSize(self):
<ide>
<ide> y1 = slim.separable_conv2d(x, 1, [3, 3], depth_multiplier=1,
<ide> stride=1, scope='Conv')
<del> y1_expected = tf.to_float([[14, 28, 43, 26],
<del> [28, 48, 66, 37],
<del> [43, 66, 84, 46],
<del> [26, 37, 46, 22]])
<add> y1_expected = tf.cast([[14, 28, 43, 26],
<add> [28, 48, 66, 37],
<add> [43, 66, 84, 46],
<add> [26, 37, 46, 22]], tf.float32)
<ide> y1_expected = tf.reshape(y1_expected, [1, n, n, 1])
<ide>
<ide> y2 = resnet_utils.subsample(y1, 2)
<del> y2_expected = tf.to_float([[14, 43],
<del> [43, 84]])
<add> y2_expected = tf.cast([[14, 43],
<add> [43, 84]], tf.float32)
<ide> y2_expected = tf.reshape(y2_expected, [1, n2, n2, 1])
<ide>
<ide> y3 = xception.separable_conv2d_same(x, 1, 3, depth_multiplier=1,
<ide> def testSeparableConv2DSameWithInputEvenSize(self):
<ide>
<ide> y4 = slim.separable_conv2d(x, 1, [3, 3], depth_multiplier=1,
<ide> stride=2, scope='Conv')
<del> y4_expected = tf.to_float([[48, 37],
<del> [37, 22]])
<add> y4_expected = tf.cast([[48, 37],
<add> [37, 22]], tf.float32)
<ide> y4_expected = tf.reshape(y4_expected, [1, n2, n2, 1])
<ide>
<ide> with self.test_session() as sess:
<ide> def testSeparableConv2DSameWithInputOddSize(self):
<ide>
<ide> y1 = slim.separable_conv2d(x, 1, [3, 3], depth_multiplier=1,
<ide> stride=1, scope='Conv')
<del> y1_expected = tf.to_float([[14, 28, 43, 58, 34],
<del> [28, 48, 66, 84, 46],
<del> [43, 66, 84, 102, 55],
<del> [58, 84, 102, 120, 64],
<del> [34, 46, 55, 64, 30]])
<add> y1_expected = tf.cast([[14, 28, 43, 58, 34],
<add> [28, 48, 66, 84, 46],
<add> [43, 66, 84, 102, 55],
<add> [58, 84, 102, 120, 64],
<add> [34, 46, 55, 64, 30]], tf.float32)
<ide> y1_expected = tf.reshape(y1_expected, [1, n, n, 1])
<ide>
<ide> y2 = resnet_utils.subsample(y1, 2)
<del> y2_expected = tf.to_float([[14, 43, 34],
<del> [43, 84, 55],
<del> [34, 55, 30]])
<add> y2_expected = tf.cast([[14, 43, 34],
<add> [43, 84, 55],
<add> [34, 55, 30]], tf.float32)
<ide> y2_expected = tf.reshape(y2_expected, [1, n2, n2, 1])
<ide>
<ide> y3 = xception.separable_conv2d_same(x, 1, 3, depth_multiplier=1,
<ide> def _xception_small(self,
<ide>
<ide> def testClassificationEndPoints(self):
<ide> global_pool = True
<del> num_classes = 10
<del> inputs = create_test_input(2, 224, 224, 3)
<add> num_classes = 3
<add> inputs = create_test_input(2, 32, 32, 3)
<ide> with slim.arg_scope(xception.xception_arg_scope()):
<ide> logits, end_points = self._xception_small(
<ide> inputs,
<ide> def testClassificationEndPoints(self):
<ide>
<ide> def testEndpointNames(self):
<ide> global_pool = True
<del> num_classes = 10
<del> inputs = create_test_input(2, 224, 224, 3)
<add> num_classes = 3
<add> inputs = create_test_input(2, 32, 32, 3)
<ide> with slim.arg_scope(xception.xception_arg_scope()):
<ide> _, end_points = self._xception_small(
<ide> inputs,
<ide> def testEndpointNames(self):
<ide> 'xception/logits',
<ide> 'predictions',
<ide> ]
<del> self.assertItemsEqual(end_points.keys(), expected)
<add> self.assertItemsEqual(list(end_points.keys()), expected)
<ide>
<ide> def testClassificationShapes(self):
<ide> global_pool = True
<del> num_classes = 10
<del> inputs = create_test_input(2, 224, 224, 3)
<add> num_classes = 3
<add> inputs = create_test_input(2, 64, 64, 3)
<ide> with slim.arg_scope(xception.xception_arg_scope()):
<ide> _, end_points = self._xception_small(
<ide> inputs,
<ide> num_classes,
<ide> global_pool=global_pool,
<ide> scope='xception')
<ide> endpoint_to_shape = {
<del> 'xception/entry_flow/conv1_1': [2, 112, 112, 32],
<del> 'xception/entry_flow/block1': [2, 56, 56, 1],
<del> 'xception/entry_flow/block2': [2, 28, 28, 2],
<del> 'xception/entry_flow/block4': [2, 14, 14, 4],
<del> 'xception/middle_flow/block1': [2, 14, 14, 4],
<del> 'xception/exit_flow/block1': [2, 7, 7, 8],
<del> 'xception/exit_flow/block2': [2, 7, 7, 16]}
<add> 'xception/entry_flow/conv1_1': [2, 32, 32, 32],
<add> 'xception/entry_flow/block1': [2, 16, 16, 1],
<add> 'xception/entry_flow/block2': [2, 8, 8, 2],
<add> 'xception/entry_flow/block4': [2, 4, 4, 4],
<add> 'xception/middle_flow/block1': [2, 4, 4, 4],
<add> 'xception/exit_flow/block1': [2, 2, 2, 8],
<add> 'xception/exit_flow/block2': [2, 2, 2, 16]}
<ide> for endpoint, shape in six.iteritems(endpoint_to_shape):
<ide> self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
<ide>
<ide> def testFullyConvolutionalEndpointShapes(self):
<ide> global_pool = False
<del> num_classes = 10
<del> inputs = create_test_input(2, 321, 321, 3)
<add> num_classes = 3
<add> inputs = create_test_input(2, 65, 65, 3)
<ide> with slim.arg_scope(xception.xception_arg_scope()):
<ide> _, end_points = self._xception_small(
<ide> inputs,
<ide> num_classes,
<ide> global_pool=global_pool,
<ide> scope='xception')
<ide> endpoint_to_shape = {
<del> 'xception/entry_flow/conv1_1': [2, 161, 161, 32],
<del> 'xception/entry_flow/block1': [2, 81, 81, 1],
<del> 'xception/entry_flow/block2': [2, 41, 41, 2],
<del> 'xception/entry_flow/block4': [2, 21, 21, 4],
<del> 'xception/middle_flow/block1': [2, 21, 21, 4],
<del> 'xception/exit_flow/block1': [2, 11, 11, 8],
<del> 'xception/exit_flow/block2': [2, 11, 11, 16]}
<add> 'xception/entry_flow/conv1_1': [2, 33, 33, 32],
<add> 'xception/entry_flow/block1': [2, 17, 17, 1],
<add> 'xception/entry_flow/block2': [2, 9, 9, 2],
<add> 'xception/entry_flow/block4': [2, 5, 5, 4],
<add> 'xception/middle_flow/block1': [2, 5, 5, 4],
<add> 'xception/exit_flow/block1': [2, 3, 3, 8],
<add> 'xception/exit_flow/block2': [2, 3, 3, 16]}
<ide> for endpoint, shape in six.iteritems(endpoint_to_shape):
<ide> self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
<ide>
<ide> def testAtrousFullyConvolutionalEndpointShapes(self):
<ide> global_pool = False
<del> num_classes = 10
<add> num_classes = 3
<ide> output_stride = 8
<del> inputs = create_test_input(2, 321, 321, 3)
<add> inputs = create_test_input(2, 65, 65, 3)
<ide> with slim.arg_scope(xception.xception_arg_scope()):
<ide> _, end_points = self._xception_small(
<ide> inputs,
<ide> def testAtrousFullyConvolutionalEndpointShapes(self):
<ide> output_stride=output_stride,
<ide> scope='xception')
<ide> endpoint_to_shape = {
<del> 'xception/entry_flow/block1': [2, 81, 81, 1],
<del> 'xception/entry_flow/block2': [2, 41, 41, 2],
<del> 'xception/entry_flow/block4': [2, 41, 41, 4],
<del> 'xception/middle_flow/block1': [2, 41, 41, 4],
<del> 'xception/exit_flow/block1': [2, 41, 41, 8],
<del> 'xception/exit_flow/block2': [2, 41, 41, 16]}
<add> 'xception/entry_flow/block1': [2, 17, 17, 1],
<add> 'xception/entry_flow/block2': [2, 9, 9, 2],
<add> 'xception/entry_flow/block4': [2, 9, 9, 4],
<add> 'xception/middle_flow/block1': [2, 9, 9, 4],
<add> 'xception/exit_flow/block1': [2, 9, 9, 8],
<add> 'xception/exit_flow/block2': [2, 9, 9, 16]}
<ide> for endpoint, shape in six.iteritems(endpoint_to_shape):
<ide> self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
<ide>
<ide> def testEndpointsReuse(self):
<ide> inputs,
<ide> num_classes=10,
<ide> reuse=True)
<del> self.assertItemsEqual(end_points0.keys(), end_points1.keys())
<add> self.assertItemsEqual(list(end_points0.keys()), list(end_points1.keys()))
<ide>
<ide> def testUseBoundedAcitvation(self):
<ide> global_pool = False
<del> num_classes = 10
<del> output_stride = 8
<add> num_classes = 3
<add> output_stride = 16
<ide> for use_bounded_activation in (True, False):
<ide> tf.reset_default_graph()
<del> inputs = create_test_input(2, 321, 321, 3)
<add> inputs = create_test_input(2, 65, 65, 3)
<ide> with slim.arg_scope(xception.xception_arg_scope(
<ide> use_bounded_activation=use_bounded_activation)):
<ide> _, _ = self._xception_small(
<ide><path>research/deeplab/model.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> (https://arxiv.org/abs/1412.7062)
<ide> """
<ide> import tensorflow as tf
<add>from tensorflow.contrib import slim as contrib_slim
<ide> from deeplab.core import dense_prediction_cell
<ide> from deeplab.core import feature_extractor
<ide> from deeplab.core import utils
<ide>
<del>slim = tf.contrib.slim
<add>slim = contrib_slim
<ide>
<ide> LOGITS_SCOPE_NAME = 'logits'
<ide> MERGED_LOGITS_SCOPE = 'merged_logits'
<ide> DECODER_SCOPE = 'decoder'
<ide> META_ARCHITECTURE_SCOPE = 'meta_architecture'
<ide>
<add>PROB_SUFFIX = '_prob'
<add>
<ide> _resize_bilinear = utils.resize_bilinear
<ide> scale_dimension = utils.scale_dimension
<ide> split_separable_conv2d = utils.split_separable_conv2d
<ide> def predict_labels_multi_scale(images,
<ide> # Compute average prediction across different scales and flipped images.
<ide> predictions = tf.reduce_mean(tf.concat(predictions, 4), axis=4)
<ide> outputs_to_predictions[output] = tf.argmax(predictions, 3)
<add> predictions[output + PROB_SUFFIX] = tf.nn.softmax(predictions)
<ide>
<ide> return outputs_to_predictions
<ide>
<ide> def predict_labels(images, model_options, image_pyramid=None):
<ide> tf.shape(images)[1:3],
<ide> scales_to_logits[MERGED_LOGITS_SCOPE].dtype)
<ide> predictions[output] = tf.argmax(logits, 3)
<add> predictions[output + PROB_SUFFIX] = tf.nn.softmax(logits)
<ide> else:
<ide> argmax_results = tf.argmax(logits, 3)
<ide> argmax_results = tf.image.resize_nearest_neighbor(
<ide> def predict_labels(images, model_options, image_pyramid=None):
<ide> align_corners=True,
<ide> name='resize_prediction')
<ide> predictions[output] = tf.squeeze(argmax_results, 3)
<del>
<add> predictions[output + PROB_SUFFIX] = tf.image.resize_bilinear(
<add> tf.nn.softmax(logits),
<add> tf.shape(images)[1:3],
<add> align_corners=True,
<add> name='resize_prob')
<ide> return predictions
<ide>
<ide>
<ide> def extract_features(images,
<ide> is_training=is_training,
<ide> preprocessed_images_dtype=model_options.preprocessed_images_dtype,
<ide> fine_tune_batch_norm=fine_tune_batch_norm,
<del> nas_stem_output_num_conv_filters=(
<del> model_options.nas_stem_output_num_conv_filters),
<add> nas_architecture_options=model_options.nas_architecture_options,
<ide> nas_training_hyper_parameters=nas_training_hyper_parameters,
<ide> use_bounded_activation=model_options.use_bounded_activation)
<ide>
<ide> def extract_features(images,
<ide> # could express the ASPP module as one particular dense prediction
<ide> # cell architecture. We do not do so but leave the following codes
<ide> # for backward compatibility.
<del> batch_norm_params = {
<del> 'is_training': is_training and fine_tune_batch_norm,
<del> 'decay': 0.9997,
<del> 'epsilon': 1e-5,
<del> 'scale': True,
<del> }
<del>
<add> batch_norm_params = utils.get_batch_norm_params(
<add> decay=0.9997,
<add> epsilon=1e-5,
<add> scale=True,
<add> is_training=(is_training and fine_tune_batch_norm),
<add> sync_batch_norm_method=model_options.sync_batch_norm_method)
<add> batch_norm = utils.get_batch_norm_fn(
<add> model_options.sync_batch_norm_method)
<ide> activation_fn = (
<ide> tf.nn.relu6 if model_options.use_bounded_activation else tf.nn.relu)
<del>
<ide> with slim.arg_scope(
<ide> [slim.conv2d, slim.separable_conv2d],
<ide> weights_regularizer=slim.l2_regularizer(weight_decay),
<ide> activation_fn=activation_fn,
<del> normalizer_fn=slim.batch_norm,
<add> normalizer_fn=batch_norm,
<ide> padding='SAME',
<ide> stride=1,
<ide> reuse=reuse):
<del> with slim.arg_scope([slim.batch_norm], **batch_norm_params):
<del> depth = 256
<add> with slim.arg_scope([batch_norm], **batch_norm_params):
<add> depth = model_options.aspp_convs_filters
<ide> branch_logits = []
<ide>
<ide> if model_options.add_image_level_feature:
<ide> def extract_features(images,
<ide> features, axis=[1, 2], keepdims=True)
<ide> resize_height = pool_height
<ide> resize_width = pool_width
<add> image_feature_activation_fn = tf.nn.relu
<add> image_feature_normalizer_fn = batch_norm
<add> if model_options.aspp_with_squeeze_and_excitation:
<add> image_feature_activation_fn = tf.nn.sigmoid
<add> if model_options.image_se_uses_qsigmoid:
<add> image_feature_activation_fn = utils.q_sigmoid
<add> image_feature_normalizer_fn = None
<ide> image_feature = slim.conv2d(
<del> image_feature, depth, 1, scope=IMAGE_POOLING_SCOPE)
<add> image_feature, depth, 1,
<add> activation_fn=image_feature_activation_fn,
<add> normalizer_fn=image_feature_normalizer_fn,
<add> scope=IMAGE_POOLING_SCOPE)
<ide> image_feature = _resize_bilinear(
<ide> image_feature,
<ide> [resize_height, resize_width],
<ide> def extract_features(images,
<ide> if isinstance(resize_width, tf.Tensor):
<ide> resize_width = None
<ide> image_feature.set_shape([None, resize_height, resize_width, depth])
<del> branch_logits.append(image_feature)
<add> if not model_options.aspp_with_squeeze_and_excitation:
<add> branch_logits.append(image_feature)
<ide>
<ide> # Employ a 1x1 convolution.
<ide> branch_logits.append(slim.conv2d(features, depth, 1,
<ide> def extract_features(images,
<ide>
<ide> # Merge branch logits.
<ide> concat_logits = tf.concat(branch_logits, 3)
<del> concat_logits = slim.conv2d(
<del> concat_logits, depth, 1, scope=CONCAT_PROJECTION_SCOPE)
<del> concat_logits = slim.dropout(
<del> concat_logits,
<del> keep_prob=0.9,
<del> is_training=is_training,
<del> scope=CONCAT_PROJECTION_SCOPE + '_dropout')
<add> if model_options.aspp_with_concat_projection:
<add> concat_logits = slim.conv2d(
<add> concat_logits, depth, 1, scope=CONCAT_PROJECTION_SCOPE)
<add> concat_logits = slim.dropout(
<add> concat_logits,
<add> keep_prob=0.9,
<add> is_training=is_training,
<add> scope=CONCAT_PROJECTION_SCOPE + '_dropout')
<add> if (model_options.add_image_level_feature and
<add> model_options.aspp_with_squeeze_and_excitation):
<add> concat_logits *= image_feature
<ide>
<ide> return concat_logits, end_points
<ide>
<ide> def _get_logits(images,
<ide> fine_tune_batch_norm=fine_tune_batch_norm,
<ide> nas_training_hyper_parameters=nas_training_hyper_parameters)
<ide>
<del> if model_options.decoder_output_stride is not None:
<add> if model_options.decoder_output_stride:
<add> crop_size = model_options.crop_size
<add> if crop_size is None:
<add> crop_size = [tf.shape(images)[1], tf.shape(images)[2]]
<ide> features = refine_by_decoder(
<ide> features,
<ide> end_points,
<del> crop_size=model_options.crop_size,
<add> crop_size=crop_size,
<ide> decoder_output_stride=model_options.decoder_output_stride,
<ide> decoder_use_separable_conv=model_options.decoder_use_separable_conv,
<add> decoder_use_sum_merge=model_options.decoder_use_sum_merge,
<add> decoder_filters=model_options.decoder_filters,
<add> decoder_output_is_logits=model_options.decoder_output_is_logits,
<ide> model_variant=model_options.model_variant,
<ide> weight_decay=weight_decay,
<ide> reuse=reuse,
<ide> def _get_logits(images,
<ide>
<ide> outputs_to_logits = {}
<ide> for output in sorted(model_options.outputs_to_num_classes):
<del> outputs_to_logits[output] = get_branch_logits(
<del> features,
<del> model_options.outputs_to_num_classes[output],
<del> model_options.atrous_rates,
<del> aspp_with_batch_norm=model_options.aspp_with_batch_norm,
<del> kernel_size=model_options.logits_kernel_size,
<del> weight_decay=weight_decay,
<del> reuse=reuse,
<del> scope_suffix=output)
<add> if model_options.decoder_output_is_logits:
<add> outputs_to_logits[output] = tf.identity(features,
<add> name=output)
<add> else:
<add> outputs_to_logits[output] = get_branch_logits(
<add> features,
<add> model_options.outputs_to_num_classes[output],
<add> model_options.atrous_rates,
<add> aspp_with_batch_norm=model_options.aspp_with_batch_norm,
<add> kernel_size=model_options.logits_kernel_size,
<add> weight_decay=weight_decay,
<add> reuse=reuse,
<add> scope_suffix=output)
<ide>
<ide> return outputs_to_logits
<ide>
<ide> def refine_by_decoder(features,
<ide> crop_size=None,
<ide> decoder_output_stride=None,
<ide> decoder_use_separable_conv=False,
<add> decoder_use_sum_merge=False,
<add> decoder_filters=256,
<add> decoder_output_is_logits=False,
<ide> model_variant=None,
<ide> weight_decay=0.0001,
<ide> reuse=None,
<ide> is_training=False,
<ide> fine_tune_batch_norm=False,
<del> use_bounded_activation=False):
<add> use_bounded_activation=False,
<add> sync_batch_norm_method='None'):
<ide> """Adds the decoder to obtain sharper segmentation results.
<ide>
<ide> Args:
<ide> def refine_by_decoder(features,
<ide> decoder_output_stride: A list of integers specifying the output stride of
<ide> low-level features used in the decoder module.
<ide> decoder_use_separable_conv: Employ separable convolution for decoder or not.
<add> decoder_use_sum_merge: Boolean, decoder uses simple sum merge or not.
<add> decoder_filters: Integer, decoder filter size.
<add> decoder_output_is_logits: Boolean, using decoder output as logits or not.
<ide> model_variant: Model variant for feature extraction.
<ide> weight_decay: The weight decay for model variables.
<ide> reuse: Reuse the model variables or not.
<ide> is_training: Is training or not.
<ide> fine_tune_batch_norm: Fine-tune the batch norm parameters or not.
<ide> use_bounded_activation: Whether or not to use bounded activations. Bounded
<ide> activations better lend themselves to quantized inference.
<add> sync_batch_norm_method: String, method used to sync batch norm. Currently
<add> only support `None` (no sync batch norm) and `tpu` (use tpu code to
<add> sync batch norm).
<ide>
<ide> Returns:
<ide> Decoder output with size [batch, decoder_height, decoder_width,
<ide> def refine_by_decoder(features,
<ide> """
<ide> if crop_size is None:
<ide> raise ValueError('crop_size must be provided when using decoder.')
<del> batch_norm_params = {
<del> 'is_training': is_training and fine_tune_batch_norm,
<del> 'decay': 0.9997,
<del> 'epsilon': 1e-5,
<del> 'scale': True,
<del> }
<del>
<add> batch_norm_params = utils.get_batch_norm_params(
<add> decay=0.9997,
<add> epsilon=1e-5,
<add> scale=True,
<add> is_training=(is_training and fine_tune_batch_norm),
<add> sync_batch_norm_method=sync_batch_norm_method)
<add> batch_norm = utils.get_batch_norm_fn(sync_batch_norm_method)
<add> decoder_depth = decoder_filters
<add> projected_filters = 48
<add> if decoder_use_sum_merge:
<add> # When using sum merge, the projected filters must be equal to decoder
<add> # filters.
<add> projected_filters = decoder_filters
<add> if decoder_output_is_logits:
<add> # Overwrite the setting when decoder output is logits.
<add> activation_fn = None
<add> normalizer_fn = None
<add> conv2d_kernel = 1
<add> # Use original conv instead of separable conv.
<add> decoder_use_separable_conv = False
<add> else:
<add> # Default setting when decoder output is not logits.
<add> activation_fn = tf.nn.relu6 if use_bounded_activation else tf.nn.relu
<add> normalizer_fn = batch_norm
<add> conv2d_kernel = 3
<ide> with slim.arg_scope(
<ide> [slim.conv2d, slim.separable_conv2d],
<ide> weights_regularizer=slim.l2_regularizer(weight_decay),
<del> activation_fn=tf.nn.relu6 if use_bounded_activation else tf.nn.relu,
<del> normalizer_fn=slim.batch_norm,
<add> activation_fn=activation_fn,
<add> normalizer_fn=normalizer_fn,
<ide> padding='SAME',
<ide> stride=1,
<ide> reuse=reuse):
<del> with slim.arg_scope([slim.batch_norm], **batch_norm_params):
<add> with slim.arg_scope([batch_norm], **batch_norm_params):
<ide> with tf.variable_scope(DECODER_SCOPE, DECODER_SCOPE, [features]):
<ide> decoder_features = features
<ide> decoder_stage = 0
<ide> def refine_by_decoder(features,
<ide> for i, name in enumerate(feature_list):
<ide> decoder_features_list = [decoder_features]
<ide> # MobileNet and NAS variants use different naming convention.
<del> if 'mobilenet' in model_variant or model_variant.startswith('nas'):
<add> if ('mobilenet' in model_variant or
<add> model_variant.startswith('mnas') or
<add> model_variant.startswith('nas')):
<ide> feature_name = name
<ide> else:
<ide> feature_name = '{}/{}'.format(
<ide> feature_extractor.name_scope[model_variant], name)
<ide> decoder_features_list.append(
<ide> slim.conv2d(
<ide> end_points[feature_name],
<del> 48,
<add> projected_filters,
<ide> 1,
<ide> scope='feature_projection' + str(i) + scope_suffix))
<ide> # Determine the output size.
<ide> def refine_by_decoder(features,
<ide> w = (None if isinstance(decoder_width, tf.Tensor)
<ide> else decoder_width)
<ide> decoder_features_list[j].set_shape([None, h, w, None])
<del> decoder_depth = 256
<del> if decoder_use_separable_conv:
<del> decoder_features = split_separable_conv2d(
<del> tf.concat(decoder_features_list, 3),
<del> filters=decoder_depth,
<del> rate=1,
<del> weight_decay=weight_decay,
<del> scope='decoder_conv0' + scope_suffix)
<del> decoder_features = split_separable_conv2d(
<del> decoder_features,
<del> filters=decoder_depth,
<del> rate=1,
<add> if decoder_use_sum_merge:
<add> decoder_features = _decoder_with_sum_merge(
<add> decoder_features_list,
<add> decoder_depth,
<add> conv2d_kernel=conv2d_kernel,
<add> decoder_use_separable_conv=decoder_use_separable_conv,
<ide> weight_decay=weight_decay,
<del> scope='decoder_conv1' + scope_suffix)
<add> scope_suffix=scope_suffix)
<ide> else:
<del> num_convs = 2
<del> decoder_features = slim.repeat(
<del> tf.concat(decoder_features_list, 3),
<del> num_convs,
<del> slim.conv2d,
<add> if not decoder_use_separable_conv:
<add> scope_suffix = str(i) + scope_suffix
<add> decoder_features = _decoder_with_concat_merge(
<add> decoder_features_list,
<ide> decoder_depth,
<del> 3,
<del> scope='decoder_conv' + str(i) + scope_suffix)
<add> decoder_use_separable_conv=decoder_use_separable_conv,
<add> weight_decay=weight_decay,
<add> scope_suffix=scope_suffix)
<ide> decoder_stage += 1
<ide> return decoder_features
<ide>
<ide>
<add>def _decoder_with_sum_merge(decoder_features_list,
<add> decoder_depth,
<add> conv2d_kernel=3,
<add> decoder_use_separable_conv=True,
<add> weight_decay=0.0001,
<add> scope_suffix=''):
<add> """Decoder with sum to merge features.
<add>
<add> Args:
<add> decoder_features_list: A list of decoder features.
<add> decoder_depth: Integer, the filters used in the convolution.
<add> conv2d_kernel: Integer, the convolution kernel size.
<add> decoder_use_separable_conv: Boolean, use separable conv or not.
<add> weight_decay: Weight decay for the model variables.
<add> scope_suffix: String, used in the scope suffix.
<add>
<add> Returns:
<add> decoder features merged with sum.
<add>
<add> Raises:
<add> RuntimeError: If decoder_features_list have length not equal to 2.
<add> """
<add> if len(decoder_features_list) != 2:
<add> raise RuntimeError('Expect decoder_features has length 2.')
<add> # Only apply one convolution when decoder use sum merge.
<add> if decoder_use_separable_conv:
<add> decoder_features = split_separable_conv2d(
<add> decoder_features_list[0],
<add> filters=decoder_depth,
<add> rate=1,
<add> weight_decay=weight_decay,
<add> scope='decoder_split_sep_conv0'+scope_suffix) + decoder_features_list[1]
<add> else:
<add> decoder_features = slim.conv2d(
<add> decoder_features_list[0],
<add> decoder_depth,
<add> conv2d_kernel,
<add> scope='decoder_conv0'+scope_suffix) + decoder_features_list[1]
<add> return decoder_features
<add>
<add>
<add>def _decoder_with_concat_merge(decoder_features_list,
<add> decoder_depth,
<add> decoder_use_separable_conv=True,
<add> weight_decay=0.0001,
<add> scope_suffix=''):
<add> """Decoder with concatenation to merge features.
<add>
<add> This decoder method applies two convolutions to smooth the features obtained
<add> by concatenating the input decoder_features_list.
<add>
<add> This decoder module is proposed in the DeepLabv3+ paper.
<add>
<add> Args:
<add> decoder_features_list: A list of decoder features.
<add> decoder_depth: Integer, the filters used in the convolution.
<add> decoder_use_separable_conv: Boolean, use separable conv or not.
<add> weight_decay: Weight decay for the model variables.
<add> scope_suffix: String, used in the scope suffix.
<add>
<add> Returns:
<add> decoder features merged with concatenation.
<add> """
<add> if decoder_use_separable_conv:
<add> decoder_features = split_separable_conv2d(
<add> tf.concat(decoder_features_list, 3),
<add> filters=decoder_depth,
<add> rate=1,
<add> weight_decay=weight_decay,
<add> scope='decoder_conv0'+scope_suffix)
<add> decoder_features = split_separable_conv2d(
<add> decoder_features,
<add> filters=decoder_depth,
<add> rate=1,
<add> weight_decay=weight_decay,
<add> scope='decoder_conv1'+scope_suffix)
<add> else:
<add> num_convs = 2
<add> decoder_features = slim.repeat(
<add> tf.concat(decoder_features_list, 3),
<add> num_convs,
<add> slim.conv2d,
<add> decoder_depth,
<add> 3,
<add> scope='decoder_conv'+scope_suffix)
<add> return decoder_features
<add>
<add>
<ide> def get_branch_logits(features,
<ide> num_classes,
<ide> atrous_rates=None,
<ide><path>research/deeplab/train.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> See model.py for more details and usage.
<ide> """
<ide>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<ide> import six
<ide> import tensorflow as tf
<del>from tensorflow.python.ops import math_ops
<add>from tensorflow.contrib import quantize as contrib_quantize
<add>from tensorflow.contrib import tfprof as contrib_tfprof
<ide> from deeplab import common
<ide> from deeplab import model
<ide> from deeplab.datasets import data_generator
<ide> from deeplab.utils import train_utils
<add>from deployment import model_deploy
<ide>
<add>slim = tf.contrib.slim
<ide> flags = tf.app.flags
<ide> FLAGS = flags.FLAGS
<ide>
<ide>
<ide> # Settings for training strategy.
<ide>
<add>flags.DEFINE_enum('optimizer', 'momentum', ['momentum', 'adam'],
<add> 'Which optimizer to use.')
<add>
<add>
<add># Momentum optimizer flags
<add>
<ide> flags.DEFINE_enum('learning_policy', 'poly', ['poly', 'step'],
<ide> 'Learning rate policy for training.')
<ide>
<ide> flags.DEFINE_float('base_learning_rate', .0001,
<ide> 'The base learning rate for model training.')
<ide>
<add>flags.DEFINE_float('decay_steps', 0.0,
<add> 'Decay steps for polynomial learning rate schedule.')
<add>
<add>flags.DEFINE_float('end_learning_rate', 0.0,
<add> 'End learning rate for polynomial learning rate schedule.')
<add>
<ide> flags.DEFINE_float('learning_rate_decay_factor', 0.1,
<ide> 'The rate to decay the base learning rate.')
<ide>
<ide>
<ide> flags.DEFINE_float('momentum', 0.9, 'The momentum value to use')
<ide>
<add># Adam optimizer flags
<add>flags.DEFINE_float('adam_learning_rate', 0.001,
<add> 'Learning rate for the adam optimizer.')
<add>flags.DEFINE_float('adam_epsilon', 1e-08, 'Adam optimizer epsilon.')
<add>
<ide> # When fine_tune_batch_norm=True, use at least batch size larger than 12
<ide> # (batch size more than 16 is better). Otherwise, one could use smaller batch
<ide> # size and set fine_tune_batch_norm=False.
<ide> 'top_k_percent_pixels=0.25, then mining percent will gradually reduce from '
<ide> '100% to 25% until 100K steps after which we only mine top 25% pixels.')
<ide>
<del>
<ide> flags.DEFINE_float(
<ide> 'top_k_percent_pixels', 1.0,
<ide> 'The top k percent pixels (in terms of the loss values) used to compute '
<ide> def _build_deeplab(iterator, outputs_to_num_classes, ignore_label):
<ide> samples[common.LABEL],
<ide> num_classes,
<ide> ignore_label,
<del> loss_weight=1.0,
<add> loss_weight=model_options.label_weights,
<ide> upsample_logits=FLAGS.upsample_logits,
<ide> hard_example_mining_step=FLAGS.hard_example_mining_step,
<ide> top_k_percent_pixels=FLAGS.top_k_percent_pixels,
<ide> scope=output)
<ide>
<del> # Log the summary
<del> _log_summaries(samples[common.IMAGE], samples[common.LABEL], num_classes,
<del> output_type_dict[model.MERGED_LOGITS_SCOPE])
<del>
<del>
<del>def _tower_loss(iterator, num_of_classes, ignore_label, scope, reuse_variable):
<del> """Calculates the total loss on a single tower running the deeplab model.
<del>
<del> Args:
<del> iterator: An iterator of type tf.data.Iterator for images and labels.
<del> num_of_classes: Number of classes for the dataset.
<del> ignore_label: Ignore label for the dataset.
<del> scope: Unique prefix string identifying the deeplab tower.
<del> reuse_variable: If the variable should be reused.
<del>
<del> Returns:
<del> The total loss for a batch of data.
<del> """
<del> with tf.variable_scope(
<del> tf.get_variable_scope(), reuse=True if reuse_variable else None):
<del> _build_deeplab(iterator, {common.OUTPUT_TYPE: num_of_classes}, ignore_label)
<del>
<del> losses = tf.losses.get_losses(scope=scope)
<del> for loss in losses:
<del> tf.summary.scalar('Losses/%s' % loss.op.name, loss)
<del>
<del> regularization_loss = tf.losses.get_regularization_loss(scope=scope)
<del> tf.summary.scalar('Losses/%s' % regularization_loss.op.name,
<del> regularization_loss)
<del>
<del> total_loss = tf.add_n([tf.add_n(losses), regularization_loss])
<del> return total_loss
<del>
<del>
<del>def _average_gradients(tower_grads):
<del> """Calculates average of gradient for each shared variable across all towers.
<del>
<del> Note that this function provides a synchronization point across all towers.
<del>
<del> Args:
<del> tower_grads: List of lists of (gradient, variable) tuples. The outer list is
<del> over individual gradients. The inner list is over the gradient calculation
<del> for each tower.
<del>
<del> Returns:
<del> List of pairs of (gradient, variable) where the gradient has been summed
<del> across all towers.
<del> """
<del> average_grads = []
<del> for grad_and_vars in zip(*tower_grads):
<del> # Note that each grad_and_vars looks like the following:
<del> # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))
<del> grads, variables = zip(*grad_and_vars)
<del> grad = tf.reduce_mean(tf.stack(grads, axis=0), axis=0)
<del>
<del> # All vars are of the same value, using the first tower here.
<del> average_grads.append((grad, variables[0]))
<del>
<del> return average_grads
<del>
<del>
<del>def _log_summaries(input_image, label, num_of_classes, output):
<del> """Logs the summaries for the model.
<del>
<del> Args:
<del> input_image: Input image of the model. Its shape is [batch_size, height,
<del> width, channel].
<del> label: Label of the image. Its shape is [batch_size, height, width].
<del> num_of_classes: The number of classes of the dataset.
<del> output: Output of the model. Its shape is [batch_size, height, width].
<del> """
<del> # Add summaries for model variables.
<del> for model_var in tf.model_variables():
<del> tf.summary.histogram(model_var.op.name, model_var)
<del>
<del> # Add summaries for images, labels, semantic predictions.
<del> if FLAGS.save_summaries_images:
<del> tf.summary.image('samples/%s' % common.IMAGE, input_image)
<del>
<del> # Scale up summary image pixel values for better visualization.
<del> pixel_scaling = max(1, 255 // num_of_classes)
<del> summary_label = tf.cast(label * pixel_scaling, tf.uint8)
<del> tf.summary.image('samples/%s' % common.LABEL, summary_label)
<del>
<del> predictions = tf.expand_dims(tf.argmax(output, 3), -1)
<del> summary_predictions = tf.cast(predictions * pixel_scaling, tf.uint8)
<del> tf.summary.image('samples/%s' % common.OUTPUT_TYPE, summary_predictions)
<del>
<del>
<del>def _train_deeplab_model(iterator, num_of_classes, ignore_label):
<del> """Trains the deeplab model.
<del>
<del> Args:
<del> iterator: An iterator of type tf.data.Iterator for images and labels.
<del> num_of_classes: Number of classes for the dataset.
<del> ignore_label: Ignore label for the dataset.
<del>
<del> Returns:
<del> train_tensor: A tensor to update the model variables.
<del> summary_op: An operation to log the summaries.
<del> """
<del> global_step = tf.train.get_or_create_global_step()
<del>
<del> learning_rate = train_utils.get_model_learning_rate(
<del> FLAGS.learning_policy, FLAGS.base_learning_rate,
<del> FLAGS.learning_rate_decay_step, FLAGS.learning_rate_decay_factor,
<del> FLAGS.training_number_of_steps, FLAGS.learning_power,
<del> FLAGS.slow_start_step, FLAGS.slow_start_learning_rate)
<del> tf.summary.scalar('learning_rate', learning_rate)
<del>
<del> optimizer = tf.train.MomentumOptimizer(learning_rate, FLAGS.momentum)
<del>
<del> tower_losses = []
<del> tower_grads = []
<del> for i in range(FLAGS.num_clones):
<del> with tf.device('/gpu:%d' % i):
<del> # First tower has default name scope.
<del> name_scope = ('clone_%d' % i) if i else ''
<del> with tf.name_scope(name_scope) as scope:
<del> loss = _tower_loss(
<del> iterator=iterator,
<del> num_of_classes=num_of_classes,
<del> ignore_label=ignore_label,
<del> scope=scope,
<del> reuse_variable=(i != 0))
<del> tower_losses.append(loss)
<del>
<del> if FLAGS.quantize_delay_step >= 0:
<del> if FLAGS.num_clones > 1:
<del> raise ValueError('Quantization doesn\'t support multi-clone yet.')
<del> tf.contrib.quantize.create_training_graph(
<del> quant_delay=FLAGS.quantize_delay_step)
<del>
<del> for i in range(FLAGS.num_clones):
<del> with tf.device('/gpu:%d' % i):
<del> name_scope = ('clone_%d' % i) if i else ''
<del> with tf.name_scope(name_scope) as scope:
<del> grads = optimizer.compute_gradients(tower_losses[i])
<del> tower_grads.append(grads)
<del>
<del> with tf.device('/cpu:0'):
<del> grads_and_vars = _average_gradients(tower_grads)
<del>
<del> # Modify the gradients for biases and last layer variables.
<del> last_layers = model.get_extra_layer_scopes(
<del> FLAGS.last_layers_contain_logits_only)
<del> grad_mult = train_utils.get_model_gradient_multipliers(
<del> last_layers, FLAGS.last_layer_gradient_multiplier)
<del> if grad_mult:
<del> grads_and_vars = tf.contrib.training.multiply_gradients(
<del> grads_and_vars, grad_mult)
<del>
<del> # Create gradient update op.
<del> grad_updates = optimizer.apply_gradients(
<del> grads_and_vars, global_step=global_step)
<del>
<del> # Gather update_ops. These contain, for example,
<del> # the updates for the batch_norm variables created by model_fn.
<del> update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
<del> update_ops.append(grad_updates)
<del> update_op = tf.group(*update_ops)
<del>
<del> total_loss = tf.losses.get_total_loss(add_regularization_losses=True)
<del>
<del> # Print total loss to the terminal.
<del> # This implementation is mirrored from tf.slim.summaries.
<del> should_log = math_ops.equal(math_ops.mod(global_step, FLAGS.log_steps), 0)
<del> total_loss = tf.cond(
<del> should_log,
<del> lambda: tf.Print(total_loss, [total_loss], 'Total loss is :'),
<del> lambda: total_loss)
<del>
<del> tf.summary.scalar('total_loss', total_loss)
<del> with tf.control_dependencies([update_op]):
<del> train_tensor = tf.identity(total_loss, name='train_op')
<del>
<del> # Excludes summaries from towers other than the first one.
<del> summary_op = tf.summary.merge_all(scope='(?!clone_)')
<del>
<del> return train_tensor, summary_op
<del>
<ide>
<ide> def main(unused_argv):
<ide> tf.logging.set_verbosity(tf.logging.INFO)
<add> # Set up deployment (i.e., multi-GPUs and/or multi-replicas).
<add> config = model_deploy.DeploymentConfig(
<add> num_clones=FLAGS.num_clones,
<add> clone_on_cpu=FLAGS.clone_on_cpu,
<add> replica_id=FLAGS.task,
<add> num_replicas=FLAGS.num_replicas,
<add> num_ps_tasks=FLAGS.num_ps_tasks)
<add>
<add> # Split the batch across GPUs.
<add> assert FLAGS.train_batch_size % config.num_clones == 0, (
<add> 'Training batch size not divisble by number of clones (GPUs).')
<add>
<add> clone_batch_size = FLAGS.train_batch_size // config.num_clones
<ide>
<ide> tf.gfile.MakeDirs(FLAGS.train_logdir)
<ide> tf.logging.info('Training on %s set', FLAGS.train_split)
<ide>
<del> graph = tf.Graph()
<del> with graph.as_default():
<del> with tf.device(tf.train.replica_device_setter(ps_tasks=FLAGS.num_ps_tasks)):
<del> assert FLAGS.train_batch_size % FLAGS.num_clones == 0, (
<del> 'Training batch size not divisble by number of clones (GPUs).')
<del> clone_batch_size = FLAGS.train_batch_size // FLAGS.num_clones
<del>
<add> with tf.Graph().as_default() as graph:
<add> with tf.device(config.inputs_device()):
<ide> dataset = data_generator.Dataset(
<ide> dataset_name=FLAGS.dataset,
<ide> split_name=FLAGS.train_split,
<ide> def main(unused_argv):
<ide> max_scale_factor=FLAGS.max_scale_factor,
<ide> scale_factor_step_size=FLAGS.scale_factor_step_size,
<ide> model_variant=FLAGS.model_variant,
<del> num_readers=2,
<add> num_readers=4,
<ide> is_training=True,
<ide> should_shuffle=True,
<ide> should_repeat=True)
<ide>
<del> train_tensor, summary_op = _train_deeplab_model(
<del> dataset.get_one_shot_iterator(), dataset.num_of_classes,
<del> dataset.ignore_label)
<del>
<del> # Soft placement allows placing on CPU ops without GPU implementation.
<del> session_config = tf.ConfigProto(
<del> allow_soft_placement=True, log_device_placement=False)
<del>
<add> # Create the global step on the device storing the variables.
<add> with tf.device(config.variables_device()):
<add> global_step = tf.train.get_or_create_global_step()
<add>
<add> # Define the model and create clones.
<add> model_fn = _build_deeplab
<add> model_args = (dataset.get_one_shot_iterator(), {
<add> common.OUTPUT_TYPE: dataset.num_of_classes
<add> }, dataset.ignore_label)
<add> clones = model_deploy.create_clones(config, model_fn, args=model_args)
<add>
<add> # Gather update_ops from the first clone. These contain, for example,
<add> # the updates for the batch_norm variables created by model_fn.
<add> first_clone_scope = config.clone_scope(0)
<add> update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, first_clone_scope)
<add>
<add> # Gather initial summaries.
<add> summaries = set(tf.get_collection(tf.GraphKeys.SUMMARIES))
<add>
<add> # Add summaries for model variables.
<add> for model_var in tf.model_variables():
<add> summaries.add(tf.summary.histogram(model_var.op.name, model_var))
<add>
<add> # Add summaries for images, labels, semantic predictions
<add> if FLAGS.save_summaries_images:
<add> summary_image = graph.get_tensor_by_name(
<add> ('%s/%s:0' % (first_clone_scope, common.IMAGE)).strip('/'))
<add> summaries.add(
<add> tf.summary.image('samples/%s' % common.IMAGE, summary_image))
<add>
<add> first_clone_label = graph.get_tensor_by_name(
<add> ('%s/%s:0' % (first_clone_scope, common.LABEL)).strip('/'))
<add> # Scale up summary image pixel values for better visualization.
<add> pixel_scaling = max(1, 255 // dataset.num_classes)
<add> summary_label = tf.cast(first_clone_label * pixel_scaling, tf.uint8)
<add> summaries.add(
<add> tf.summary.image('samples/%s' % common.LABEL, summary_label))
<add>
<add> first_clone_output = graph.get_tensor_by_name(
<add> ('%s/%s:0' % (first_clone_scope, common.OUTPUT_TYPE)).strip('/'))
<add> predictions = tf.expand_dims(tf.argmax(first_clone_output, 3), -1)
<add>
<add> summary_predictions = tf.cast(predictions * pixel_scaling, tf.uint8)
<add> summaries.add(
<add> tf.summary.image(
<add> 'samples/%s' % common.OUTPUT_TYPE, summary_predictions))
<add>
<add> # Add summaries for losses.
<add> for loss in tf.get_collection(tf.GraphKeys.LOSSES, first_clone_scope):
<add> summaries.add(tf.summary.scalar('losses/%s' % loss.op.name, loss))
<add>
<add> # Build the optimizer based on the device specification.
<add> with tf.device(config.optimizer_device()):
<add> learning_rate = train_utils.get_model_learning_rate(
<add> FLAGS.learning_policy,
<add> FLAGS.base_learning_rate,
<add> FLAGS.learning_rate_decay_step,
<add> FLAGS.learning_rate_decay_factor,
<add> FLAGS.training_number_of_steps,
<add> FLAGS.learning_power,
<add> FLAGS.slow_start_step,
<add> FLAGS.slow_start_learning_rate,
<add> decay_steps=FLAGS.decay_steps,
<add> end_learning_rate=FLAGS.end_learning_rate)
<add>
<add> summaries.add(tf.summary.scalar('learning_rate', learning_rate))
<add>
<add> if FLAGS.optimizer == 'momentum':
<add> optimizer = tf.train.MomentumOptimizer(learning_rate, FLAGS.momentum)
<add> elif FLAGS.optimizer == 'adam':
<add> optimizer = tf.train.AdamOptimizer(
<add> learning_rate=FLAGS.adam_learning_rate, epsilon=FLAGS.adam_epsilon)
<add> else:
<add> raise ValueError('Unknown optimizer')
<add>
<add> if FLAGS.quantize_delay_step >= 0:
<add> if FLAGS.num_clones > 1:
<add> raise ValueError('Quantization doesn\'t support multi-clone yet.')
<add> contrib_quantize.create_training_graph(
<add> quant_delay=FLAGS.quantize_delay_step)
<add>
<add> startup_delay_steps = FLAGS.task * FLAGS.startup_delay_steps
<add>
<add> with tf.device(config.variables_device()):
<add> total_loss, grads_and_vars = model_deploy.optimize_clones(
<add> clones, optimizer)
<add> total_loss = tf.check_numerics(total_loss, 'Loss is inf or nan.')
<add> summaries.add(tf.summary.scalar('total_loss', total_loss))
<add>
<add> # Modify the gradients for biases and last layer variables.
<ide> last_layers = model.get_extra_layer_scopes(
<ide> FLAGS.last_layers_contain_logits_only)
<add> grad_mult = train_utils.get_model_gradient_multipliers(
<add> last_layers, FLAGS.last_layer_gradient_multiplier)
<add> if grad_mult:
<add> grads_and_vars = slim.learning.multiply_gradients(
<add> grads_and_vars, grad_mult)
<add>
<add> # Create gradient update op.
<add> grad_updates = optimizer.apply_gradients(
<add> grads_and_vars, global_step=global_step)
<add> update_ops.append(grad_updates)
<add> update_op = tf.group(*update_ops)
<add> with tf.control_dependencies([update_op]):
<add> train_tensor = tf.identity(total_loss, name='train_op')
<add>
<add> # Add the summaries from the first clone. These contain the summaries
<add> # created by model_fn and either optimize_clones() or _gather_clone_loss().
<add> summaries |= set(
<add> tf.get_collection(tf.GraphKeys.SUMMARIES, first_clone_scope))
<add>
<add> # Merge all summaries together.
<add> summary_op = tf.summary.merge(list(summaries))
<add>
<add> # Soft placement allows placing on CPU ops without GPU implementation.
<add> session_config = tf.ConfigProto(
<add> allow_soft_placement=True, log_device_placement=False)
<add>
<add> # Start the training.
<add> profile_dir = FLAGS.profile_logdir
<add> if profile_dir is not None:
<add> tf.gfile.MakeDirs(profile_dir)
<add>
<add> with contrib_tfprof.ProfileContext(
<add> enabled=profile_dir is not None, profile_dir=profile_dir):
<ide> init_fn = None
<ide> if FLAGS.tf_initial_checkpoint:
<ide> init_fn = train_utils.get_model_init_fn(
<ide> def main(unused_argv):
<ide> last_layers,
<ide> ignore_missing_vars=True)
<ide>
<del> scaffold = tf.train.Scaffold(
<add> slim.learning.train(
<add> train_tensor,
<add> logdir=FLAGS.train_logdir,
<add> log_every_n_steps=FLAGS.log_steps,
<add> master=FLAGS.master,
<add> number_of_steps=FLAGS.training_number_of_steps,
<add> is_chief=(FLAGS.task == 0),
<add> session_config=session_config,
<add> startup_delay_steps=startup_delay_steps,
<ide> init_fn=init_fn,
<ide> summary_op=summary_op,
<del> )
<del>
<del> stop_hook = tf.train.StopAtStepHook(
<del> last_step=FLAGS.training_number_of_steps)
<del>
<del> profile_dir = FLAGS.profile_logdir
<del> if profile_dir is not None:
<del> tf.gfile.MakeDirs(profile_dir)
<del>
<del> with tf.contrib.tfprof.ProfileContext(
<del> enabled=profile_dir is not None, profile_dir=profile_dir):
<del> with tf.train.MonitoredTrainingSession(
<del> master=FLAGS.master,
<del> is_chief=(FLAGS.task == 0),
<del> config=session_config,
<del> scaffold=scaffold,
<del> checkpoint_dir=FLAGS.train_logdir,
<del> summary_dir=FLAGS.train_logdir,
<del> log_step_count_steps=FLAGS.log_steps,
<del> save_summaries_steps=FLAGS.save_summaries_secs,
<del> save_checkpoint_secs=FLAGS.save_interval_secs,
<del> hooks=[stop_hook]) as sess:
<del> while not sess.should_stop():
<del> sess.run([train_tensor])
<add> save_summaries_secs=FLAGS.save_summaries_secs,
<add> save_interval_secs=FLAGS.save_interval_secs)
<ide>
<ide>
<ide> if __name__ == '__main__':
<ide><path>research/deeplab/utils/train_utils.py
<add># Lint as: python2, python3
<ide> # Copyright 2018 The TensorFlow Authors All Rights Reserved.
<ide> #
<ide> # Licensed under the Apache License, Version 2.0 (the "License");
<ide> """Utility functions for training."""
<ide>
<ide> import six
<del>
<ide> import tensorflow as tf
<add>from tensorflow.contrib import framework as contrib_framework
<add>
<ide> from deeplab.core import preprocess_utils
<add>from deeplab.core import utils
<ide>
<ide>
<ide> def _div_maybe_zero(total_loss, num_present):
<ide> """Normalizes the total loss with the number of present pixels."""
<del> return tf.to_float(num_present > 0) * tf.div(total_loss,
<del> tf.maximum(1e-5, num_present))
<add> return tf.to_float(num_present > 0) * tf.math.divide(
<add> total_loss,
<add> tf.maximum(1e-5, num_present))
<ide>
<ide>
<ide> def add_softmax_cross_entropy_loss_for_each_scale(scales_to_logits,
<ide> def add_softmax_cross_entropy_loss_for_each_scale(scales_to_logits,
<ide> upsample_logits=True,
<ide> hard_example_mining_step=0,
<ide> top_k_percent_pixels=1.0,
<add> gt_is_matting_map=False,
<ide> scope=None):
<ide> """Adds softmax cross entropy loss for logits of each scale.
<ide>
<ide> def add_softmax_cross_entropy_loss_for_each_scale(scales_to_logits,
<ide> labels: Groundtruth labels with shape [batch, image_height, image_width, 1].
<ide> num_classes: Integer, number of target classes.
<ide> ignore_label: Integer, label to ignore.
<del> loss_weight: Float, loss weight.
<add> loss_weight: A float or a list of loss weights. If it is a float, it means
<add> all the labels have the same weight. If it is a list of weights, then each
<add> element in the list represents the weight for the label of its index, for
<add> example, loss_weight = [0.1, 0.5] means the weight for label 0 is 0.1 and
<add> the weight for label 1 is 0.5.
<ide> upsample_logits: Boolean, upsample logits or not.
<ide> hard_example_mining_step: An integer, the training step in which the hard
<ide> exampling mining kicks off. Note that we gradually reduce the mining
<ide> def add_softmax_cross_entropy_loss_for_each_scale(scales_to_logits,
<ide> top_k_percent_pixels: A float, the value lies in [0.0, 1.0]. When its value
<ide> < 1.0, only compute the loss for the top k percent pixels (e.g., the top
<ide> 20% pixels). This is useful for hard pixel mining.
<add> gt_is_matting_map: If true, the groundtruth is a matting map of confidence
<add> score. If false, the groundtruth is an integer valued class mask.
<ide> scope: String, the scope for the loss.
<ide>
<ide> Raises:
<del> ValueError: Label or logits is None.
<add> ValueError: Label or logits is None, or groundtruth is matting map while
<add> label is not floating value.
<ide> """
<ide> if labels is None:
<ide> raise ValueError('No label for softmax cross entropy loss.')
<ide>
<add> # If input groundtruth is a matting map of confidence, check if the input
<add> # labels are floating point values.
<add> if gt_is_matting_map and not labels.dtype.is_floating:
<add> raise ValueError('Labels must be floats if groundtruth is a matting map.')
<add>
<ide> for scale, logits in six.iteritems(scales_to_logits):
<ide> loss_scope = None
<ide> if scope:
<ide> def add_softmax_cross_entropy_loss_for_each_scale(scales_to_logits,
<ide> scaled_labels = labels
<ide> else:
<ide> # Label is downsampled to the same size as logits.
<add> # When gt_is_matting_map = true, label downsampling with nearest neighbor
<add> # method may introduce artifacts. However, to avoid ignore_label from
<add> # being interpolated with other labels, we still perform nearest neighbor
<add> # interpolation.
<add> # TODO(huizhongc): Change to bilinear interpolation by processing padded
<add> # and non-padded label separately.
<add> if gt_is_matting_map:
<add> tf.logging.warning(
<add> 'Label downsampling with nearest neighbor may introduce artifacts.')
<add>
<ide> scaled_labels = tf.image.resize_nearest_neighbor(
<ide> labels,
<ide> preprocess_utils.resolve_shape(logits, 4)[1:3],
<ide> align_corners=True)
<ide>
<ide> scaled_labels = tf.reshape(scaled_labels, shape=[-1])
<del> not_ignore_mask = tf.to_float(tf.not_equal(scaled_labels,
<del> ignore_label)) * loss_weight
<del> one_hot_labels = tf.one_hot(
<del> scaled_labels, num_classes, on_value=1.0, off_value=0.0)
<del>
<del> if top_k_percent_pixels == 1.0:
<del> # Compute the loss for all pixels.
<del> tf.losses.softmax_cross_entropy(
<del> one_hot_labels,
<del> tf.reshape(logits, shape=[-1, num_classes]),
<del> weights=not_ignore_mask,
<del> scope=loss_scope)
<add> weights = utils.get_label_weight_mask(
<add> scaled_labels, ignore_label, num_classes, label_weights=loss_weight)
<add> # Dimension of keep_mask is equal to the total number of pixels.
<add> keep_mask = tf.cast(
<add> tf.not_equal(scaled_labels, ignore_label), dtype=tf.float32)
<add>
<add> train_labels = None
<add> logits = tf.reshape(logits, shape=[-1, num_classes])
<add>
<add> if gt_is_matting_map:
<add> # When the groundtruth is integer label mask, we can assign class
<add> # dependent label weights to the loss. When the groundtruth is image
<add> # matting confidence, we do not apply class-dependent label weight (i.e.,
<add> # label_weight = 1.0).
<add> if loss_weight != 1.0:
<add> raise ValueError(
<add> 'loss_weight must equal to 1 if groundtruth is matting map.')
<add>
<add> # Assign label value 0 to ignore pixels. The exact label value of ignore
<add> # pixel does not matter, because those ignore_value pixel losses will be
<add> # multiplied to 0 weight.
<add> train_labels = scaled_labels * keep_mask
<add>
<add> train_labels = tf.expand_dims(train_labels, 1)
<add> train_labels = tf.concat([1 - train_labels, train_labels], axis=1)
<ide> else:
<del> logits = tf.reshape(logits, shape=[-1, num_classes])
<del> weights = not_ignore_mask
<del> with tf.name_scope(loss_scope, 'softmax_hard_example_mining',
<del> [logits, one_hot_labels, weights]):
<del> one_hot_labels = tf.stop_gradient(
<del> one_hot_labels, name='labels_stop_gradient')
<del> pixel_losses = tf.nn.softmax_cross_entropy_with_logits_v2(
<del> labels=one_hot_labels,
<del> logits=logits,
<del> name='pixel_losses')
<del> weighted_pixel_losses = tf.multiply(pixel_losses, weights)
<add> train_labels = tf.one_hot(
<add> scaled_labels, num_classes, on_value=1.0, off_value=0.0)
<add>
<add> default_loss_scope = ('softmax_all_pixel_loss'
<add> if top_k_percent_pixels == 1.0 else
<add> 'softmax_hard_example_mining')
<add> with tf.name_scope(loss_scope, default_loss_scope,
<add> [logits, train_labels, weights]):
<add> # Compute the loss for all pixels.
<add> pixel_losses = tf.nn.softmax_cross_entropy_with_logits_v2(
<add> labels=tf.stop_gradient(
<add> train_labels, name='train_labels_stop_gradient'),
<add> logits=logits,
<add> name='pixel_losses')
<add> weighted_pixel_losses = tf.multiply(pixel_losses, weights)
<add>
<add> if top_k_percent_pixels == 1.0:
<add> total_loss = tf.reduce_sum(weighted_pixel_losses)
<add> num_present = tf.reduce_sum(keep_mask)
<add> loss = _div_maybe_zero(total_loss, num_present)
<add> tf.losses.add_loss(loss)
<add> else:
<ide> num_pixels = tf.to_float(tf.shape(logits)[0])
<ide> # Compute the top_k_percent pixels based on current training step.
<ide> if hard_example_mining_step == 0:
<ide> def get_model_init_fn(train_logdir,
<ide> if not initialize_last_layer:
<ide> exclude_list.extend(last_layers)
<ide>
<del> variables_to_restore = tf.contrib.framework.get_variables_to_restore(
<add> variables_to_restore = contrib_framework.get_variables_to_restore(
<ide> exclude=exclude_list)
<ide>
<ide> if variables_to_restore:
<del> init_op, init_feed_dict = tf.contrib.framework.assign_from_checkpoint(
<add> init_op, init_feed_dict = contrib_framework.assign_from_checkpoint(
<ide> tf_initial_checkpoint,
<ide> variables_to_restore,
<ide> ignore_missing_vars=ignore_missing_vars)
<ide> def get_model_learning_rate(learning_policy,
<ide> learning_power,
<ide> slow_start_step,
<ide> slow_start_learning_rate,
<del> slow_start_burnin_type='none'):
<add> slow_start_burnin_type='none',
<add> decay_steps=0.0,
<add> end_learning_rate=0.0,
<add> boundaries=None,
<add> boundary_learning_rates=None):
<ide> """Gets model's learning rate.
<ide>
<ide> Computes the model's learning rate for different learning policy.
<ide> def get_model_learning_rate(learning_policy,
<ide> `none` which means no burnin or `linear` which means the learning rate
<ide> increases linearly from slow_start_learning_rate and reaches
<ide> base_learning_rate after slow_start_steps.
<add> decay_steps: Float, `decay_steps` for polynomial learning rate.
<add> end_learning_rate: Float, `end_learning_rate` for polynomial learning rate.
<add> boundaries: A list of `Tensor`s or `int`s or `float`s with strictly
<add> increasing entries.
<add> boundary_learning_rates: A list of `Tensor`s or `float`s or `int`s that
<add> specifies the values for the intervals defined by `boundaries`. It should
<add> have one more element than `boundaries`, and all elements should have the
<add> same type.
<ide>
<ide> Returns:
<ide> Learning rate for the specified learning policy.
<ide>
<ide> Raises:
<ide> ValueError: If learning policy or slow start burnin type is not recognized.
<add> ValueError: If `boundaries` and `boundary_learning_rates` are not set for
<add> multi_steps learning rate decay.
<ide> """
<ide> global_step = tf.train.get_or_create_global_step()
<del> adjusted_global_step = global_step
<del>
<del> if slow_start_burnin_type != 'none':
<del> adjusted_global_step -= slow_start_step
<del>
<add> adjusted_global_step = tf.maximum(global_step - slow_start_step, 0)
<add> if decay_steps == 0.0:
<add> tf.logging.info('Setting decay_steps to total training steps.')
<add> decay_steps = training_number_of_steps - slow_start_step
<ide> if learning_policy == 'step':
<ide> learning_rate = tf.train.exponential_decay(
<ide> base_learning_rate,
<ide> def get_model_learning_rate(learning_policy,
<ide> learning_rate = tf.train.polynomial_decay(
<ide> base_learning_rate,
<ide> adjusted_global_step,
<del> training_number_of_steps,
<del> end_learning_rate=0,
<add> decay_steps=decay_steps,
<add> end_learning_rate=end_learning_rate,
<ide> power=learning_power)
<add> elif learning_policy == 'cosine':
<add> learning_rate = tf.train.cosine_decay(
<add> base_learning_rate,
<add> adjusted_global_step,
<add> training_number_of_steps - slow_start_step)
<add> elif learning_policy == 'multi_steps':
<add> if boundaries is None or boundary_learning_rates is None:
<add> raise ValueError('Must set `boundaries` and `boundary_learning_rates` '
<add> 'for multi_steps learning rate decay.')
<add> learning_rate = tf.train.piecewise_constant_decay(
<add> adjusted_global_step,
<add> boundaries,
<add> boundary_learning_rates)
<ide> else:
<ide> raise ValueError('Unknown learning policy.')
<ide>
| 18
|
Python
|
Python
|
add missing type hints in `matrix` directory
|
46842e8c5b5fc78ced0f38206560deb2b8160a54
|
<ide><path>matrix/count_islands_in_matrix.py
<ide>
<ide>
<ide> class matrix: # Public class to implement a graph
<del> def __init__(self, row: int, col: int, graph: list):
<add> def __init__(self, row: int, col: int, graph: list[list[bool]]) -> None:
<ide> self.ROW = row
<ide> self.COL = col
<ide> self.graph = graph
<ide>
<del> def is_safe(self, i, j, visited) -> bool:
<add> def is_safe(self, i: int, j: int, visited: list[list[bool]]) -> bool:
<ide> return (
<ide> 0 <= i < self.ROW
<ide> and 0 <= j < self.COL
<ide> and not visited[i][j]
<ide> and self.graph[i][j]
<ide> )
<ide>
<del> def diffs(self, i, j, visited): # Checking all 8 elements surrounding nth element
<add> def diffs(self, i: int, j: int, visited: list[list[bool]]) -> None:
<add> # Checking all 8 elements surrounding nth element
<ide> rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order
<ide> colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]
<ide> visited[i][j] = True # Make those cells visited
<ide><path>matrix/matrix_class.py
<ide> # An OOP approach to representing and manipulating matrices
<ide>
<add>from __future__ import annotations
<add>
<ide>
<ide> class Matrix:
<ide> """
<ide> class Matrix:
<ide> [6. -12. 6.]
<ide> [-3. 6. -3.]]
<ide> >>> print(matrix.inverse())
<del> None
<add> Traceback (most recent call last):
<add> ...
<add> TypeError: Only matrices with a non-zero determinant have an inverse
<ide>
<ide> Determinant is an int, float, or Nonetype
<ide> >>> matrix.determinant()
<ide> class Matrix:
<ide> [198. 243. 288. 304.]
<ide> [306. 378. 450. 472.]
<ide> [414. 513. 612. 640.]]
<del>
<ide> """
<ide>
<del> def __init__(self, rows):
<add> def __init__(self, rows: list[list[int]]):
<ide> error = TypeError(
<ide> "Matrices must be formed from a list of zero or more lists containing at "
<ide> "least one and the same number of values, each of which must be of type "
<ide> def __init__(self, rows):
<ide> self.rows = []
<ide>
<ide> # MATRIX INFORMATION
<del> def columns(self):
<add> def columns(self) -> list[list[int]]:
<ide> return [[row[i] for row in self.rows] for i in range(len(self.rows[0]))]
<ide>
<ide> @property
<del> def num_rows(self):
<add> def num_rows(self) -> int:
<ide> return len(self.rows)
<ide>
<ide> @property
<del> def num_columns(self):
<add> def num_columns(self) -> int:
<ide> return len(self.rows[0])
<ide>
<ide> @property
<del> def order(self):
<add> def order(self) -> tuple[int, int]:
<ide> return (self.num_rows, self.num_columns)
<ide>
<ide> @property
<del> def is_square(self):
<add> def is_square(self) -> bool:
<ide> return self.order[0] == self.order[1]
<ide>
<del> def identity(self):
<add> def identity(self) -> Matrix:
<ide> values = [
<ide> [0 if column_num != row_num else 1 for column_num in range(self.num_rows)]
<ide> for row_num in range(self.num_rows)
<ide> ]
<ide> return Matrix(values)
<ide>
<del> def determinant(self):
<add> def determinant(self) -> int:
<ide> if not self.is_square:
<del> return None
<add> return 0
<ide> if self.order == (0, 0):
<ide> return 1
<ide> if self.order == (1, 1):
<del> return self.rows[0][0]
<add> return int(self.rows[0][0])
<ide> if self.order == (2, 2):
<del> return (self.rows[0][0] * self.rows[1][1]) - (
<del> self.rows[0][1] * self.rows[1][0]
<add> return int(
<add> (self.rows[0][0] * self.rows[1][1])
<add> - (self.rows[0][1] * self.rows[1][0])
<ide> )
<ide> else:
<ide> return sum(
<ide> self.rows[0][column] * self.cofactors().rows[0][column]
<ide> for column in range(self.num_columns)
<ide> )
<ide>
<del> def is_invertable(self):
<add> def is_invertable(self) -> bool:
<ide> return bool(self.determinant())
<ide>
<del> def get_minor(self, row, column):
<add> def get_minor(self, row: int, column: int) -> int:
<ide> values = [
<ide> [
<ide> self.rows[other_row][other_column]
<ide> def get_minor(self, row, column):
<ide> ]
<ide> return Matrix(values).determinant()
<ide>
<del> def get_cofactor(self, row, column):
<add> def get_cofactor(self, row: int, column: int) -> int:
<ide> if (row + column) % 2 == 0:
<ide> return self.get_minor(row, column)
<ide> return -1 * self.get_minor(row, column)
<ide>
<del> def minors(self):
<add> def minors(self) -> Matrix:
<ide> return Matrix(
<ide> [
<ide> [self.get_minor(row, column) for column in range(self.num_columns)]
<ide> for row in range(self.num_rows)
<ide> ]
<ide> )
<ide>
<del> def cofactors(self):
<add> def cofactors(self) -> Matrix:
<ide> return Matrix(
<ide> [
<ide> [
<ide> def cofactors(self):
<ide> ]
<ide> )
<ide>
<del> def adjugate(self):
<add> def adjugate(self) -> Matrix:
<ide> values = [
<ide> [self.cofactors().rows[column][row] for column in range(self.num_columns)]
<ide> for row in range(self.num_rows)
<ide> ]
<ide> return Matrix(values)
<ide>
<del> def inverse(self):
<add> def inverse(self) -> Matrix:
<ide> determinant = self.determinant()
<del> return None if not determinant else self.adjugate() * (1 / determinant)
<add> if not determinant:
<add> raise TypeError("Only matrices with a non-zero determinant have an inverse")
<add> return self.adjugate() * (1 / determinant)
<ide>
<del> def __repr__(self):
<add> def __repr__(self) -> str:
<ide> return str(self.rows)
<ide>
<del> def __str__(self):
<add> def __str__(self) -> str:
<ide> if self.num_rows == 0:
<ide> return "[]"
<ide> if self.num_rows == 1:
<del> return "[[" + ". ".join(self.rows[0]) + "]]"
<add> return "[[" + ". ".join(str(self.rows[0])) + "]]"
<ide> return (
<ide> "["
<ide> + "\n ".join(
<ide> def __str__(self):
<ide> )
<ide>
<ide> # MATRIX MANIPULATION
<del> def add_row(self, row, position=None):
<add> def add_row(self, row: list[int], position: int | None = None) -> None:
<ide> type_error = TypeError("Row must be a list containing all ints and/or floats")
<ide> if not isinstance(row, list):
<ide> raise type_error
<ide> def add_row(self, row, position=None):
<ide> else:
<ide> self.rows = self.rows[0:position] + [row] + self.rows[position:]
<ide>
<del> def add_column(self, column, position=None):
<add> def add_column(self, column: list[int], position: int | None = None) -> None:
<ide> type_error = TypeError(
<ide> "Column must be a list containing all ints and/or floats"
<ide> )
<ide> def add_column(self, column, position=None):
<ide> ]
<ide>
<ide> # MATRIX OPERATIONS
<del> def __eq__(self, other):
<add> def __eq__(self, other: object) -> bool:
<ide> if not isinstance(other, Matrix):
<ide> raise TypeError("A Matrix can only be compared with another Matrix")
<ide> return self.rows == other.rows
<ide>
<del> def __ne__(self, other):
<add> def __ne__(self, other: object) -> bool:
<ide> return not self == other
<ide>
<del> def __neg__(self):
<add> def __neg__(self) -> Matrix:
<ide> return self * -1
<ide>
<del> def __add__(self, other):
<add> def __add__(self, other: Matrix) -> Matrix:
<ide> if self.order != other.order:
<ide> raise ValueError("Addition requires matrices of the same order")
<ide> return Matrix(
<ide> def __add__(self, other):
<ide> ]
<ide> )
<ide>
<del> def __sub__(self, other):
<add> def __sub__(self, other: Matrix) -> Matrix:
<ide> if self.order != other.order:
<ide> raise ValueError("Subtraction requires matrices of the same order")
<ide> return Matrix(
<ide> def __sub__(self, other):
<ide> ]
<ide> )
<ide>
<del> def __mul__(self, other):
<add> def __mul__(self, other: Matrix | int | float) -> Matrix:
<ide> if isinstance(other, (int, float)):
<del> return Matrix([[element * other for element in row] for row in self.rows])
<add> return Matrix(
<add> [[int(element * other) for element in row] for row in self.rows]
<add> )
<ide> elif isinstance(other, Matrix):
<ide> if self.num_columns != other.num_rows:
<ide> raise ValueError(
<ide> def __mul__(self, other):
<ide> "A Matrix can only be multiplied by an int, float, or another matrix"
<ide> )
<ide>
<del> def __pow__(self, other):
<add> def __pow__(self, other: int) -> Matrix:
<ide> if not isinstance(other, int):
<ide> raise TypeError("A Matrix can only be raised to the power of an int")
<ide> if not self.is_square:
<ide> def __pow__(self, other):
<ide> return result
<ide>
<ide> @classmethod
<del> def dot_product(cls, row, column):
<add> def dot_product(cls, row: list[int], column: list[int]) -> int:
<ide> return sum(row[i] * column[i] for i in range(len(row)))
<ide>
<ide>
<ide><path>matrix/matrix_operation.py
<ide>
<ide> from __future__ import annotations
<ide>
<add>from typing import Any
<ide>
<del>def add(*matrix_s: list[list]) -> list[list]:
<add>
<add>def add(*matrix_s: list[list[int]]) -> list[list[int]]:
<ide> """
<ide> >>> add([[1,2],[3,4]],[[2,3],[4,5]])
<ide> [[3, 5], [7, 9]]
<ide> def add(*matrix_s: list[list]) -> list[list]:
<ide> raise TypeError("Expected a matrix, got int/list instead")
<ide>
<ide>
<del>def subtract(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
<add>def subtract(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]:
<ide> """
<ide> >>> subtract([[1,2],[3,4]],[[2,3],[4,5]])
<ide> [[-1, -1], [-1, -1]]
<ide> def subtract(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
<ide> raise TypeError("Expected a matrix, got int/list instead")
<ide>
<ide>
<del>def scalar_multiply(matrix: list[list], n: int | float) -> list[list]:
<add>def scalar_multiply(matrix: list[list[int]], n: int | float) -> list[list[float]]:
<ide> """
<ide> >>> scalar_multiply([[1,2],[3,4]],5)
<ide> [[5, 10], [15, 20]]
<ide> def scalar_multiply(matrix: list[list], n: int | float) -> list[list]:
<ide> return [[x * n for x in row] for row in matrix]
<ide>
<ide>
<del>def multiply(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
<add>def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]:
<ide> """
<ide> >>> multiply([[1,2],[3,4]],[[5,5],[7,5]])
<ide> [[19, 15], [43, 35]]
<ide> def multiply(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
<ide> ]
<ide>
<ide>
<del>def identity(n: int) -> list[list]:
<add>def identity(n: int) -> list[list[int]]:
<ide> """
<ide> :param n: dimension for nxn matrix
<ide> :type n: int
<ide> def identity(n: int) -> list[list]:
<ide> return [[int(row == column) for column in range(n)] for row in range(n)]
<ide>
<ide>
<del>def transpose(matrix: list[list], return_map: bool = True) -> list[list] | map[list]:
<add>def transpose(
<add> matrix: list[list[int]], return_map: bool = True
<add>) -> list[list[int]] | map[list[int]]:
<ide> """
<ide> >>> transpose([[1,2],[3,4]]) # doctest: +ELLIPSIS
<ide> <map object at ...
<ide> def transpose(matrix: list[list], return_map: bool = True) -> list[list] | map[l
<ide> raise TypeError("Expected a matrix, got int/list instead")
<ide>
<ide>
<del>def minor(matrix: list[list], row: int, column: int) -> list[list]:
<add>def minor(matrix: list[list[int]], row: int, column: int) -> list[list[int]]:
<ide> """
<ide> >>> minor([[1, 2], [3, 4]], 1, 1)
<ide> [[1]]
<ide> def minor(matrix: list[list], row: int, column: int) -> list[list]:
<ide> return [row[:column] + row[column + 1 :] for row in minor]
<ide>
<ide>
<del>def determinant(matrix: list[list]) -> int:
<add>def determinant(matrix: list[list[int]]) -> Any:
<ide> """
<ide> >>> determinant([[1, 2], [3, 4]])
<ide> -2
<ide> def determinant(matrix: list[list]) -> int:
<ide> )
<ide>
<ide>
<del>def inverse(matrix: list[list]) -> list[list] | None:
<add>def inverse(matrix: list[list[int]]) -> list[list[float]] | None:
<ide> """
<ide> >>> inverse([[1, 2], [3, 4]])
<ide> [[-2.0, 1.0], [1.5, -0.5]]
<ide> def inverse(matrix: list[list]) -> list[list] | None:
<ide> return scalar_multiply(adjugate, 1 / det)
<ide>
<ide>
<del>def _check_not_integer(matrix: list[list]) -> bool:
<add>def _check_not_integer(matrix: list[list[int]]) -> bool:
<ide> return not isinstance(matrix, int) and not isinstance(matrix[0], int)
<ide>
<ide>
<del>def _shape(matrix: list[list]) -> tuple[int, int]:
<add>def _shape(matrix: list[list[int]]) -> tuple[int, int]:
<ide> return len(matrix), len(matrix[0])
<ide>
<ide>
<ide> def _verify_matrix_sizes(
<del> matrix_a: list[list], matrix_b: list[list]
<del>) -> tuple[tuple, tuple]:
<add> matrix_a: list[list[int]], matrix_b: list[list[int]]
<add>) -> tuple[tuple[int, int], tuple[int, int]]:
<ide> shape = _shape(matrix_a) + _shape(matrix_b)
<ide> if shape[0] != shape[3] or shape[1] != shape[2]:
<ide> raise ValueError(
<del> "operands could not be broadcast together with shape "
<add> f"operands could not be broadcast together with shape "
<ide> f"({shape[0], shape[1]}), ({shape[2], shape[3]})"
<ide> )
<ide> return (shape[0], shape[2]), (shape[1], shape[3])
<ide>
<ide>
<del>def main():
<add>def main() -> None:
<ide> matrix_a = [[12, 10], [3, 9]]
<ide> matrix_b = [[3, 4], [7, 4]]
<ide> matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
<ide><path>matrix/nth_fibonacci_using_matrix_exponentiation.py
<ide> """
<ide>
<ide>
<del>def multiply(matrix_a, matrix_b):
<add>def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]:
<ide> matrix_c = []
<ide> n = len(matrix_a)
<ide> for i in range(n):
<ide> def multiply(matrix_a, matrix_b):
<ide> return matrix_c
<ide>
<ide>
<del>def identity(n):
<add>def identity(n: int) -> list[list[int]]:
<ide> return [[int(row == column) for column in range(n)] for row in range(n)]
<ide>
<ide>
<del>def nth_fibonacci_matrix(n):
<add>def nth_fibonacci_matrix(n: int) -> int:
<ide> """
<ide> >>> nth_fibonacci_matrix(100)
<ide> 354224848179261915075
<ide> def nth_fibonacci_matrix(n):
<ide> return res_matrix[0][0]
<ide>
<ide>
<del>def nth_fibonacci_bruteforce(n):
<add>def nth_fibonacci_bruteforce(n: int) -> int:
<ide> """
<ide> >>> nth_fibonacci_bruteforce(100)
<ide> 354224848179261915075
<ide> def nth_fibonacci_bruteforce(n):
<ide> return fib1
<ide>
<ide>
<del>def main():
<add>def main() -> None:
<ide> for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split():
<ide> n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000
<ide> print(
<ide><path>matrix/rotate_matrix.py
<ide> from __future__ import annotations
<ide>
<ide>
<del>def make_matrix(row_size: int = 4) -> list[list]:
<add>def make_matrix(row_size: int = 4) -> list[list[int]]:
<ide> """
<ide> >>> make_matrix()
<ide> [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
<ide> def make_matrix(row_size: int = 4) -> list[list]:
<ide> return [[1 + x + y * row_size for x in range(row_size)] for y in range(row_size)]
<ide>
<ide>
<del>def rotate_90(matrix: list[list]) -> list[list]:
<add>def rotate_90(matrix: list[list[int]]) -> list[list[int]]:
<ide> """
<ide> >>> rotate_90(make_matrix())
<ide> [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]]
<ide> def rotate_90(matrix: list[list]) -> list[list]:
<ide> # OR.. transpose(reverse_column(matrix))
<ide>
<ide>
<del>def rotate_180(matrix: list[list]) -> list[list]:
<add>def rotate_180(matrix: list[list[int]]) -> list[list[int]]:
<ide> """
<ide> >>> rotate_180(make_matrix())
<ide> [[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]]
<ide> def rotate_180(matrix: list[list]) -> list[list]:
<ide> # OR.. reverse_column(reverse_row(matrix))
<ide>
<ide>
<del>def rotate_270(matrix: list[list]) -> list[list]:
<add>def rotate_270(matrix: list[list[int]]) -> list[list[int]]:
<ide> """
<ide> >>> rotate_270(make_matrix())
<ide> [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]
<ide> def rotate_270(matrix: list[list]) -> list[list]:
<ide> # OR.. transpose(reverse_row(matrix))
<ide>
<ide>
<del>def transpose(matrix: list[list]) -> list[list]:
<add>def transpose(matrix: list[list[int]]) -> list[list[int]]:
<ide> matrix[:] = [list(x) for x in zip(*matrix)]
<ide> return matrix
<ide>
<ide>
<del>def reverse_row(matrix: list[list]) -> list[list]:
<add>def reverse_row(matrix: list[list[int]]) -> list[list[int]]:
<ide> matrix[:] = matrix[::-1]
<ide> return matrix
<ide>
<ide>
<del>def reverse_column(matrix: list[list]) -> list[list]:
<add>def reverse_column(matrix: list[list[int]]) -> list[list[int]]:
<ide> matrix[:] = [x[::-1] for x in matrix]
<ide> return matrix
<ide>
<ide>
<del>def print_matrix(matrix: list[list]) -> None:
<add>def print_matrix(matrix: list[list[int]]) -> None:
<ide> for i in matrix:
<ide> print(*i)
<ide>
<ide><path>matrix/searching_in_sorted_matrix.py
<ide>
<ide>
<ide> def search_in_a_sorted_matrix(
<del> mat: list[list], m: int, n: int, key: int | float
<add> mat: list[list[int]], m: int, n: int, key: int | float
<ide> ) -> None:
<ide> """
<ide> >>> search_in_a_sorted_matrix(
<ide> def search_in_a_sorted_matrix(
<ide> print(f"Key {key} not found")
<ide>
<ide>
<del>def main():
<add>def main() -> None:
<ide> mat = [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]]
<ide> x = int(input("Enter the element to be searched:"))
<ide> print(mat)
<ide><path>matrix/sherman_morrison.py
<add>from __future__ import annotations
<add>
<add>from typing import Any
<add>
<add>
<ide> class Matrix:
<ide> """
<ide> <class Matrix>
<ide> Matrix structure.
<ide> """
<ide>
<del> def __init__(self, row: int, column: int, default_value: float = 0):
<add> def __init__(self, row: int, column: int, default_value: float = 0) -> None:
<ide> """
<ide> <method Matrix.__init__>
<ide> Initialize matrix with given size and default value.
<del>
<ide> Example:
<ide> >>> a = Matrix(2, 3, 1)
<ide> >>> a
<ide> def __init__(self, row: int, column: int, default_value: float = 0):
<ide> self.row, self.column = row, column
<ide> self.array = [[default_value for c in range(column)] for r in range(row)]
<ide>
<del> def __str__(self):
<add> def __str__(self) -> str:
<ide> """
<ide> <method Matrix.__str__>
<ide> Return string representation of this matrix.
<ide> def __str__(self):
<ide> string_format_identifier = "%%%ds" % (max_element_length,)
<ide>
<ide> # Make string and return
<del> def single_line(row_vector):
<add> def single_line(row_vector: list[float]) -> str:
<ide> nonlocal string_format_identifier
<ide> line = "["
<ide> line += ", ".join(string_format_identifier % (obj,) for obj in row_vector)
<ide> def single_line(row_vector):
<ide> s += "\n".join(single_line(row_vector) for row_vector in self.array)
<ide> return s
<ide>
<del> def __repr__(self):
<add> def __repr__(self) -> str:
<ide> return str(self)
<ide>
<del> def validateIndices(self, loc: tuple):
<add> def validateIndices(self, loc: tuple[int, int]) -> bool:
<ide> """
<ide> <method Matrix.validateIndices>
<ide> Check if given indices are valid to pick element from matrix.
<del>
<ide> Example:
<ide> >>> a = Matrix(2, 6, 0)
<ide> >>> a.validateIndices((2, 7))
<ide> def validateIndices(self, loc: tuple):
<ide> else:
<ide> return True
<ide>
<del> def __getitem__(self, loc: tuple):
<add> def __getitem__(self, loc: tuple[int, int]) -> Any:
<ide> """
<ide> <method Matrix.__getitem__>
<ide> Return array[row][column] where loc = (row, column).
<del>
<ide> Example:
<ide> >>> a = Matrix(3, 2, 7)
<ide> >>> a[1, 0]
<ide> def __getitem__(self, loc: tuple):
<ide> assert self.validateIndices(loc)
<ide> return self.array[loc[0]][loc[1]]
<ide>
<del> def __setitem__(self, loc: tuple, value: float):
<add> def __setitem__(self, loc: tuple[int, int], value: float) -> None:
<ide> """
<ide> <method Matrix.__setitem__>
<ide> Set array[row][column] = value where loc = (row, column).
<del>
<ide> Example:
<ide> >>> a = Matrix(2, 3, 1)
<ide> >>> a[1, 2] = 51
<ide> def __setitem__(self, loc: tuple, value: float):
<ide> assert self.validateIndices(loc)
<ide> self.array[loc[0]][loc[1]] = value
<ide>
<del> def __add__(self, another):
<add> def __add__(self, another: Matrix) -> Matrix:
<ide> """
<ide> <method Matrix.__add__>
<ide> Return self + another.
<del>
<ide> Example:
<ide> >>> a = Matrix(2, 1, -4)
<ide> >>> b = Matrix(2, 1, 3)
<ide> def __add__(self, another):
<ide> result[r, c] = self[r, c] + another[r, c]
<ide> return result
<ide>
<del> def __neg__(self):
<add> def __neg__(self) -> Matrix:
<ide> """
<ide> <method Matrix.__neg__>
<ide> Return -self.
<del>
<ide> Example:
<ide> >>> a = Matrix(2, 2, 3)
<ide> >>> a[0, 1] = a[1, 0] = -2
<ide> def __neg__(self):
<ide> result[r, c] = -self[r, c]
<ide> return result
<ide>
<del> def __sub__(self, another):
<add> def __sub__(self, another: Matrix) -> Matrix:
<ide> return self + (-another)
<ide>
<del> def __mul__(self, another):
<add> def __mul__(self, another: int | float | Matrix) -> Matrix:
<ide> """
<ide> <method Matrix.__mul__>
<ide> Return self * another.
<del>
<ide> Example:
<ide> >>> a = Matrix(2, 3, 1)
<ide> >>> a[0,2] = a[1,2] = 3
<ide> def __mul__(self, another):
<ide> else:
<ide> raise TypeError(f"Unsupported type given for another ({type(another)})")
<ide>
<del> def transpose(self):
<add> def transpose(self) -> Matrix:
<ide> """
<ide> <method Matrix.transpose>
<ide> Return self^T.
<del>
<ide> Example:
<ide> >>> a = Matrix(2, 3)
<ide> >>> for r in range(2):
<ide> def transpose(self):
<ide> result[c, r] = self[r, c]
<ide> return result
<ide>
<del> def ShermanMorrison(self, u, v):
<add> def ShermanMorrison(self, u: Matrix, v: Matrix) -> Any:
<ide> """
<ide> <method Matrix.ShermanMorrison>
<ide> Apply Sherman-Morrison formula in O(n^2).
<ide> def ShermanMorrison(self, u, v):
<ide> impossible to calculate.
<ide> Warning: This method doesn't check if self is invertible.
<ide> Make sure self is invertible before execute this method.
<del>
<ide> Example:
<ide> >>> ainv = Matrix(3, 3, 0)
<ide> >>> for i in range(3): ainv[i,i] = 1
<ide> def ShermanMorrison(self, u, v):
<ide> # Testing
<ide> if __name__ == "__main__":
<ide>
<del> def test1():
<add> def test1() -> None:
<ide> # a^(-1)
<ide> ainv = Matrix(3, 3, 0)
<ide> for i in range(3):
<ide> def test1():
<ide> v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5
<ide> print(f"u is {u}")
<ide> print(f"v is {v}")
<del> print(f"uv^T is {u * v.transpose()}")
<add> print("uv^T is %s" % (u * v.transpose()))
<ide> # Sherman Morrison
<ide> print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}")
<ide>
<del> def test2():
<add> def test2() -> None:
<ide> import doctest
<ide>
<ide> doctest.testmod()
<ide><path>matrix/spiral_print.py
<ide> """
<ide> This program print the matrix in spiral form.
<ide> This problem has been solved through recursive way.
<del>
<ide> Matrix must satisfy below conditions
<ide> i) matrix should be only one or two dimensional
<ide> ii) number of column of all rows should be equal
<ide> """
<ide>
<del>from collections.abc import Iterable
<del>
<ide>
<del>def check_matrix(matrix):
<add>def check_matrix(matrix: list[list[int]]) -> bool:
<ide> # must be
<del> if matrix and isinstance(matrix, Iterable):
<del> if isinstance(matrix[0], Iterable):
<add> matrix = list(list(row) for row in matrix)
<add> if matrix and isinstance(matrix, list):
<add> if isinstance(matrix[0], list):
<ide> prev_len = 0
<ide> for row in matrix:
<ide> if prev_len == 0:
<ide> def check_matrix(matrix):
<ide> return result
<ide>
<ide>
<del>def spiralPrint(a):
<add>def spiral_print_clockwise(a: list[list[int]]) -> None:
<add> """
<add> >>> spiral_print_clockwise([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
<add> 1
<add> 2
<add> 3
<add> 4
<add> 8
<add> 12
<add> 11
<add> 10
<add> 9
<add> 5
<add> 6
<add> 7
<add> """
<ide> if check_matrix(a) and len(a) > 0:
<del> matRow = len(a)
<del> if isinstance(a[0], Iterable):
<del> matCol = len(a[0])
<add> a = list(list(row) for row in a)
<add> mat_row = len(a)
<add> if isinstance(a[0], list):
<add> mat_col = len(a[0])
<ide> else:
<ide> for dat in a:
<del> print(dat),
<add> print(dat)
<ide> return
<ide>
<ide> # horizotal printing increasing
<del> for i in range(0, matCol):
<del> print(a[0][i]),
<add> for i in range(0, mat_col):
<add> print(a[0][i])
<ide> # vertical printing down
<del> for i in range(1, matRow):
<del> print(a[i][matCol - 1]),
<add> for i in range(1, mat_row):
<add> print(a[i][mat_col - 1])
<ide> # horizotal printing decreasing
<del> if matRow > 1:
<del> for i in range(matCol - 2, -1, -1):
<del> print(a[matRow - 1][i]),
<add> if mat_row > 1:
<add> for i in range(mat_col - 2, -1, -1):
<add> print(a[mat_row - 1][i])
<ide> # vertical printing up
<del> for i in range(matRow - 2, 0, -1):
<del> print(a[i][0]),
<del> remainMat = [row[1 : matCol - 1] for row in a[1 : matRow - 1]]
<del> if len(remainMat) > 0:
<del> spiralPrint(remainMat)
<add> for i in range(mat_row - 2, 0, -1):
<add> print(a[i][0])
<add> remain_mat = [row[1 : mat_col - 1] for row in a[1 : mat_row - 1]]
<add> if len(remain_mat) > 0:
<add> spiral_print_clockwise(remain_mat)
<ide> else:
<ide> return
<ide> else:
<ide> def spiralPrint(a):
<ide>
<ide> # driver code
<ide> if __name__ == "__main__":
<del> a = ([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12])
<del> spiralPrint(a)
<add> a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
<add> spiral_print_clockwise(a)
| 8
|
Ruby
|
Ruby
|
convert params keys to strings
|
7eef11eb657e6efb54dfe782ca2531df93654f83
|
<ide><path>actionpack/lib/action_dispatch/test/mock.rb
<ide> def env_for(path, opts)
<ide> opts[:input] = params
<ide> end
<ide> else
<add> params.stringify_keys!
<ide> params.update(::Rack::Utils.parse_query(uri.query))
<ide> uri.query = requestify(params)
<ide> end
| 1
|
Javascript
|
Javascript
|
add custom inspect to bufferlist
|
9d3958102ec28f2bb468b2c532b7b34cabd61f1b
|
<ide><path>lib/internal/streams/BufferList.js
<ide> 'use strict';
<ide>
<ide> const { Buffer } = require('buffer');
<add>const { inspect } = require('util');
<ide>
<ide> function copyBuffer(src, target, offset) {
<ide> Buffer.prototype.copy.call(src, target, offset);
<ide> module.exports = class BufferList {
<ide> }
<ide> return ret;
<ide> }
<add>
<add> [inspect.custom]() {
<add> const obj = inspect({ length: this.length });
<add> return `${this.constructor.name} ${obj}`;
<add> }
<ide> };
| 1
|
PHP
|
PHP
|
fix translator bug
|
5046370454bed497801fe47e29efa00fab0535cd
|
<ide><path>src/Illuminate/Translation/Translator.php
<ide> protected function getLine($namespace, $group, $locale, $item, array $replace)
<ide> {
<ide> return $this->makeReplacements($line, $replace);
<ide> }
<del> elseif (is_array($line))
<add> elseif (is_array($line) and ! is_null($item))
<ide> {
<ide> return $line;
<ide> }
| 1
|
Java
|
Java
|
pass sockjs session attributes to handshakehandler
|
b4fa1c24cc782a90935bde9275bfb203d4c97b14
|
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/WebSocketSession.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 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> public interface WebSocketSession extends Closeable {
<ide>
<ide> /**
<ide> * Return the map with attributes associated with the WebSocket session.
<del> * <p>When the WebSocketSession is created, on the server side, the map can be
<del> * through a {@link org.springframework.web.socket.server.HandshakeInterceptor}.
<del> * On the client side, the map can be populated by passing attributes to the
<del> * {@link org.springframework.web.socket.client.WebSocketClient} handshake methods.
<add> * <p>On the server side the map can be populated initially through a
<add> * {@link org.springframework.web.socket.server.HandshakeInterceptor
<add> * HandshakeInterceptor}. On the client side the map can be populated via
<add> * {@link org.springframework.web.socket.client.WebSocketClient
<add> * WebSocketClient} handshake methods.
<add> * @return a Map with the session attributes, never {@code null}.
<ide> */
<ide> Map<String, Object> getAttributes();
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/WebSocketTransportHandler.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 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> package org.springframework.web.socket.sockjs.transport.handler;
<ide>
<del>import java.util.Collections;
<ide> import java.util.Map;
<ide>
<ide> import org.springframework.http.server.ServerHttpRequest;
<ide> public HandshakeHandler getHandshakeHandler() {
<ide> }
<ide>
<ide> @Override
<del> public AbstractSockJsSession createSession(
<del> String sessionId, WebSocketHandler handler, Map<String, Object> attributes) {
<del>
<del> return new WebSocketServerSockJsSession(sessionId, getServiceConfig(), handler, attributes);
<add> public AbstractSockJsSession createSession(String id, WebSocketHandler handler, Map<String, Object> attrs) {
<add> return new WebSocketServerSockJsSession(id, getServiceConfig(), handler, attrs);
<ide> }
<ide>
<ide> @Override
<ide> public void handleRequest(ServerHttpRequest request, ServerHttpResponse response
<ide> WebSocketServerSockJsSession sockJsSession = (WebSocketServerSockJsSession) wsSession;
<ide> try {
<ide> wsHandler = new SockJsWebSocketHandler(getServiceConfig(), wsHandler, sockJsSession);
<del> this.handshakeHandler.doHandshake(request, response, wsHandler, Collections.<String, Object>emptyMap());
<add> this.handshakeHandler.doHandshake(request, response, wsHandler, sockJsSession.getAttributes());
<ide> }
<ide> catch (Throwable ex) {
<ide> sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
| 2
|
Text
|
Text
|
pass path in url constructor
|
b5e818197f127b36f18fb0d0481928227b88b053
|
<ide><path>doc/api/esm.md
<ide> The resolve hook returns the resolved file URL and module format for a
<ide> given module specifier and parent file URL:
<ide>
<ide> ```js
<del>const baseURL = new URL('file://');
<del>baseURL.pathname = `${process.cwd()}/`;
<add>const baseURL = new URL(`${process.cwd()}/`, 'file://');
<ide>
<ide> export async function resolve(specifier,
<ide> parentModuleURL = baseURL,
<ide> import Module from 'module';
<ide> const builtins = Module.builtinModules;
<ide> const JS_EXTENSIONS = new Set(['.js', '.mjs']);
<ide>
<del>const baseURL = new URL('file://');
<del>baseURL.pathname = `${process.cwd()}/`;
<add>const baseURL = new URL(`${process.cwd()}/`, 'file://');
<ide>
<ide> export function resolve(specifier, parentModuleURL = baseURL, defaultResolve) {
<ide> if (builtins.includes(specifier)) {
| 1
|
Java
|
Java
|
disallow empty expression in @disabledif
|
54d6f250e2c496a4c6ce82392418a962eca40991
|
<ide><path>spring-test/src/main/java/org/springframework/test/context/junit/jupiter/DisabledIfCondition.java
<ide> private ConditionEvaluationResult evaluateDisabledIf(ExtensionContext extensionC
<ide> Optional<DisabledIf> disabledIf = findMergedAnnotation(element, DisabledIf.class);
<ide> Assert.state(disabledIf.isPresent(), () -> "@DisabledIf must be present on " + element);
<ide>
<del> String expression = disabledIf.get().expression().trim();
<add> String expression = disabledIf.map(DisabledIf::expression).filter(StringUtils::hasText).orElseThrow(
<add> () -> new IllegalStateException(
<add> String.format("The expression in @DisabledIf on [%s] must not be blank", element)));
<ide>
<ide> if (isDisabled(expression, extensionContext)) {
<ide> String reason = disabledIf.map(DisabledIf::reason).filter(StringUtils::hasText).orElseGet(
| 1
|
PHP
|
PHP
|
use referer header if it exists
|
b8778d24106ac6fc71d32284424ac0e5c2cb5bd3
|
<ide><path>src/Illuminate/Routing/Redirector.php
<ide> public function home($status = 302)
<ide> */
<ide> public function back($status = 302, $headers = array())
<ide> {
<del> if ($this->session->hasPreviousUrl())
<add> if ($this->generator->getRequest()->headers->has('referer'))
<ide> {
<del> $back = $this->session->getPreviousUrl();
<add> $back = $this->generator->getRequest()->headers->get('referer');
<ide> }
<del> else
<add> elseif ($this->session->hasPreviousUrl())
<ide> {
<del> $back = $this->generator->getRequest()->headers->get('referer');
<add> $back = $this->session->getPreviousUrl();
<ide> }
<ide>
<ide> return $this->createRedirect($back, $status, $headers);
| 1
|
Javascript
|
Javascript
|
write test for _optionsforqueryparam
|
786ad9b6f5387a6e818244110b8c8e2377040cb9
|
<ide><path>packages/@ember/-internals/routing/tests/system/route_test.js
<ide> moduleFor(
<ide> runDestroy(owner);
<ide> }
<ide>
<add> ["@test _optionsForQueryParam should work with nested properties"](assert) {
<add> let route = EmberRoute.extend({
<add> queryParams: {
<add> 'nested.foo': {
<add> // By default, controller query param properties don't
<add> // cause a full transition when they are changed, but
<add> // rather only cause the URL to update. Setting
<add> // `refreshModel` to true will cause an "in-place"
<add> // transition to occur, whereby the model hooks for
<add> // this route (and any child routes) will re-fire, allowing
<add> // you to reload models (e.g., from the server) using the
<add> // updated query param values.
<add> refreshModel: true,
<add>
<add> // By default, the query param URL key is the same name as
<add> // the controller property name. Use `as` to specify a
<add> // different URL key.
<add> as: 'foobar'
<add> }
<add> }
<add> }).create();
<add>
<add> assert.strictEqual(route._optionsForQueryParam({
<add> prop: 'nested.foo',
<add> urlKey: 'foobar'
<add> }), route.queryParams['nested.foo']);
<add> }
<add>
<ide> ["@test modelFor doesn't require the routerMicrolib"](assert) {
<ide> let route = EmberRoute.create({
<ide> _router: { _routerMicrolib: null },
| 1
|
Text
|
Text
|
update the file of dockerizing a node.js app
|
883b0567f2c96cb5cbcc31e5b02938bcc6d5877f
|
<ide><path>docs/examples/nodejs_web_app.md
<ide> Install your app dependencies using the `npm` binary:
<ide>
<ide> # Install app dependencies
<ide> COPY package.json /src/package.json
<del> RUN cd /src; npm install
<add> RUN cd /src; npm install --production
<ide>
<ide> To bundle your app's source code inside the Docker image, use the `COPY`
<ide> instruction:
<ide> Your `Dockerfile` should now look like this:
<ide>
<ide> # Install app dependencies
<ide> COPY package.json /src/package.json
<del> RUN cd /src; npm install
<add> RUN cd /src; npm install --production
<ide>
<ide> # Bundle app source
<ide> COPY . /src
| 1
|
Javascript
|
Javascript
|
install updated `fbjs` downstream
|
8457a46e43cfb6086338fd92e1426541932a69b5
|
<ide><path>packager/blacklist.js
<ide> var sharedBlacklist = [
<ide> 'downstream/core/invariant.js',
<ide> 'downstream/core/nativeRequestAnimationFrame.js',
<ide> 'downstream/core/toArray.js',
<del> 'downstream/functional/mapObject.js',
<del> 'downstream/key-mirror/keyMirror.js',
<del> 'downstream/key-mirror/keyOf.js',
<ide> ];
<ide>
<ide> // Raw unescaped patterns in case you need to use wildcards
| 1
|
Ruby
|
Ruby
|
remove some nodes
|
e55763a29d922bf4b5c483b9d3dadb1dba3bc683
|
<ide><path>lib/arel/nodes/as.rb
<del>module Arel
<del> module Nodes
<del> class As < Arel::Nodes::Binary
<del> end
<del> end
<del>end
<ide><path>lib/arel/nodes/assignment.rb
<del>module Arel
<del> module Nodes
<del> class Assignment < Arel::Nodes::Binary
<del> end
<del> end
<del>end
<ide><path>lib/arel/nodes/between.rb
<del>module Arel
<del> module Nodes
<del> class Between < Arel::Nodes::Binary
<del> end
<del> end
<del>end
<ide><path>lib/arel/nodes/not_equal.rb
<del>module Arel
<del> module Nodes
<del> class NotEqual < Arel::Nodes::Binary
<del> end
<del> end
<del>end
<ide><path>lib/arel/nodes/or.rb
<del>module Arel
<del> module Nodes
<del> class Or < Arel::Nodes::Binary
<del> end
<del> end
<del>end
| 5
|
Text
|
Text
|
fix typo in http2 docs
|
575b4e368d01b0be0a5f821d4c46b5aa8ff4b528
|
<ide><path>doc/api/http2.md
<ide> changes:
<ide> * `http2.constants.PADDING_STRATEGY_NONE`: No padding is applied.
<ide> * `http2.constants.PADDING_STRATEGY_MAX`: The maximum amount of padding,
<ide> determined by the internal implementation, is applied.
<del> * `http2.constants.PADDING_STRATEGY_ALIGNED`: Attemps to apply enough
<add> * `http2.constants.PADDING_STRATEGY_ALIGNED`: Attempts to apply enough
<ide> padding to ensure that the total frame length, including the
<ide> 9-byte header, is a multiple of 8. For each frame, there is a maximum
<ide> allowed number of padding bytes that is determined by current flow control
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.