content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
improve extraceblockmodulesmap performance
ccc6f6c6917c788558380ed35bbf142929c32e91
<ide><path>lib/buildChunkGraph.js <ide> const bySetSize = (a, b) => { <ide> }; <ide> <ide> /** <del> * Extracts simplified info from the modules and their dependencies <add> * Extracts block to modules mapping from all modules <ide> * @param {Compilation} compilation the compilation <del> * @returns {Map<DependenciesBlock, { modules: Iterable<Module>, blocks: AsyncDependenciesBlock[]}>} the mapping block to modules and inner blocks <add> * @returns {Map<DependenciesBlock, Iterable<Module>>} the mapping block to modules <ide> */ <del>const extraceBlockInfoMap = compilation => { <del> /** @type {Map<DependenciesBlock, { modules: Iterable<Module>, blocks: AsyncDependenciesBlock[]}>} */ <del> const blockInfoMap = new Map(); <add>const extraceBlockModulesMap = compilation => { <add> const { moduleGraph } = compilation; <ide> <del> /** <del> * @param {Dependency} d dependency to iterate over <del> * @returns {void} <del> */ <del> const iteratorDependency = d => { <del> // We skip Dependencies without Module pointer <del> const connection = compilation.moduleGraph.getConnection(d); <del> if ( <del> !connection || <del> !connection.module || <del> !connection.active || <del> connection.weak <del> ) { <del> return; <del> } <add> /** @type {Map<DependenciesBlock, Iterable<Module>>} */ <add> const blockModulesMap = new Map(); <ide> <del> blockInfoModules.add(connection.module); <del> }; <del> <del> /** <del> * @param {AsyncDependenciesBlock} b blocks to prepare <del> * @returns {void} <del> */ <del> const iteratorBlockPrepare = b => { <del> blockInfoBlocks.push(b); <del> blockQueue.push(b); <del> }; <del> <del> /** @type {DependenciesBlock} */ <del> let block; <del> /** @type {DependenciesBlock[]} */ <del> let blockQueue; <del> /** @type {Set<Module>} */ <del> let blockInfoModules; <del> /** @type {AsyncDependenciesBlock[]} */ <del> let blockInfoBlocks; <add> const blockQueue = new Set(); <ide> <ide> for (const module of compilation.modules) { <del> blockQueue = [module]; <del> while (blockQueue.length > 0) { <del> block = blockQueue.pop(); <del> blockInfoModules = new Set(); <del> blockInfoBlocks = []; <del> <del> if (block.dependencies) { <del> for (const dep of block.dependencies) iteratorDependency(dep); <add> /** @type {WeakMap<Dependency, Module>} */ <add> let moduleMap; <add> <add> for (const connection of moduleGraph.getOutgoingConnections(module)) { <add> const d = connection.dependency; <add> // We skip connections without dependency <add> if (!d) continue; <add> const m = connection.module; <add> // We skip connections without Module pointer <add> if (!m) continue; <add> // We skip weak connections <add> if (connection.weak) continue; <add> // We skip inactive connections <add> if (!connection.active) continue; <add> // Store Dependency to Module mapping in local map <add> // to allow to access it faster compared to <add> // moduleGraph.getConnection() <add> if (moduleMap === undefined) { <add> moduleMap = new WeakMap(); <ide> } <add> moduleMap.set(connection.dependency, m); <add> } <ide> <del> if (block.blocks) { <del> for (const b of block.blocks) iteratorBlockPrepare(b); <add> blockQueue.clear(); <add> blockQueue.add(module); <add> for (const block of blockQueue) { <add> let modules; <add> <add> if (moduleMap !== undefined && block.dependencies) { <add> for (const dep of block.dependencies) { <add> const module = moduleMap.get(dep); <add> if (module !== undefined) { <add> if (modules === undefined) { <add> modules = new Set(); <add> blockModulesMap.set(block, modules); <add> } <add> modules.add(module); <add> } <add> } <ide> } <ide> <del> const blockInfo = { <del> modules: blockInfoModules, <del> blocks: blockInfoBlocks <del> }; <del> blockInfoMap.set(block, blockInfo); <add> if (block.blocks) { <add> for (const b of block.blocks) { <add> blockQueue.add(b); <add> } <add> } <ide> } <ide> } <ide> <del> return blockInfoMap; <add> return blockModulesMap; <ide> }; <ide> <ide> /** <ide> const visitModules = ( <ide> const { moduleGraph, chunkGraph, namedChunkGroups } = compilation; <ide> <ide> logger.time("visitModules: prepare"); <del> const blockInfoMap = extraceBlockInfoMap(compilation); <add> const blockModulesMap = extraceBlockModulesMap(compilation); <ide> <ide> let nextChunkGroupIndex = 0; <ide> <ide> const visitModules = ( <ide> // fallthrough <ide> case PROCESS_BLOCK: { <ide> // get prepared block info <del> const blockInfo = blockInfoMap.get(block); <del> <del> // Buffer items because order need to be reverse to get indicies correct <del> const skipBuffer = []; <del> const queueBuffer = []; <del> // Traverse all referenced modules <del> for (const refModule of blockInfo.modules) { <del> if (chunkGraph.isModuleInChunk(refModule, chunk)) { <del> // skip early if already connected <del> continue; <del> } <del> if (minAvailableModules.has(refModule)) { <del> // already in parent chunks, skip it for now <del> skipBuffer.push({ <add> const blockModules = blockModulesMap.get(block); <add> <add> if (blockModules !== undefined) { <add> // Buffer items because order need to be reverse to get indicies correct <add> const skipBuffer = []; <add> const queueBuffer = []; <add> // Traverse all referenced modules <add> for (const refModule of blockModules) { <add> if (chunkGraph.isModuleInChunk(refModule, chunk)) { <add> // skip early if already connected <add> continue; <add> } <add> if (minAvailableModules.has(refModule)) { <add> // already in parent chunks, skip it for now <add> skipBuffer.push({ <add> action: ADD_AND_ENTER_MODULE, <add> block: refModule, <add> module: refModule, <add> chunk, <add> chunkGroup <add> }); <add> continue; <add> } <add> // enqueue the add and enter to enter in the correct order <add> // this is relevant with circular dependencies <add> queueBuffer.push({ <ide> action: ADD_AND_ENTER_MODULE, <ide> block: refModule, <ide> module: refModule, <ide> chunk, <ide> chunkGroup <ide> }); <del> continue; <ide> } <del> // enqueue the add and enter to enter in the correct order <del> // this is relevant with circular dependencies <del> queueBuffer.push({ <del> action: ADD_AND_ENTER_MODULE, <del> block: refModule, <del> module: refModule, <del> chunk, <del> chunkGroup <del> }); <del> } <del> // Add buffered items in reversed order <del> for (let i = skipBuffer.length - 1; i >= 0; i--) { <del> skippedItems.push(skipBuffer[i]); <del> } <del> for (let i = queueBuffer.length - 1; i >= 0; i--) { <del> queue.push(queueBuffer[i]); <add> // Add buffered items in reversed order <add> for (let i = skipBuffer.length - 1; i >= 0; i--) { <add> skippedItems.push(skipBuffer[i]); <add> } <add> for (let i = queueBuffer.length - 1; i >= 0; i--) { <add> queue.push(queueBuffer[i]); <add> } <ide> } <ide> <ide> // Traverse all Blocks <del> for (const block of blockInfo.blocks) iteratorBlock(block); <add> for (const b of block.blocks) iteratorBlock(b); <ide> <del> if (blockInfo.blocks.length > 0 && module !== block) { <add> if (block.blocks.length > 0 && module !== block) { <ide> blocksWithNestedBlocks.add(block); <ide> } <ide> break;
1
Java
Java
fix checkstyle violation
1c270d8d067bec08bbf419adeb354f96a3731780
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ErrorHandlerIntegrationTests.java <ide> <ide> import java.net.URI; <ide> <del>import org.junit.Assume; <ide> import org.junit.jupiter.api.Assumptions; <ide> import reactor.core.publisher.Mono; <ide>
1
Python
Python
expand airflow.cfg and defaults
7f1a791d271bc8d368be446197e4ba29bccee8fb
<ide><path>airflow/configuration.py <ide> def get(self, section, key): <ide> <ide> # ...then the config file <ide> elif self.has_option(section, key): <del> return ConfigParser.get(self, section, key) <add> return expand_env_var(ConfigParser.get(self, section, key)) <ide> <ide> # ...then the defaults <ide> elif section in d and key in d[section]: <del> return d[section][key] <add> return expand_env_var(d[section][key]) <ide> <ide> else: <ide> raise AirflowConfigException(
1
Text
Text
fix npm to v6
85218238310c6a5876c8c47c114189dcf1dcc2ef
<ide><path>docs/devops.md <ide> Provisioning VMs with the Code <ide> 2. Update `npm` and install PM2 and setup `logrotate` and startup on boot <ide> <ide> ```console <del> npm i -g npm <add> npm i -g npm@6 <ide> npm i -g pm2 <ide> pm2 install pm2-logrotate <ide> pm2 startup <ide> Provisioning VMs with the Code <ide> 2. Update `npm` and install PM2 and setup `logrotate` and startup on boot <ide> <ide> ```console <del> npm i -g npm <add> npm i -g npm@6 <ide> npm i -g pm2 <ide> npm install -g serve <ide> pm2 install pm2-logrotate
1
Text
Text
fix broken url link
77a42ffbc76f9cbf2fca8c9a463b1e755fea0247
<ide><path>syntaxnet/g3doc/syntaxnet-tutorial.md <ide> Note that `stack` here means "words we have already tagged." Thus, this feature <ide> spec uses three types of features: words, suffixes, and prefixes. The features <ide> are grouped into blocks that share an embedding matrix, concatenated together, <ide> and fed into a chain of hidden layers. This structure is based upon the model <del>proposed by [Chen and Manning (2014)] <del>(http://cs.stanford.edu/people/danqi/papers/emnlp2014.pdf). <add>proposed by [Chen and Manning (2014)](http://cs.stanford.edu/people/danqi/papers/emnlp2014.pdf). <ide> <ide> We show this layout in the schematic below: the state of the system (a stack and <ide> a buffer, visualized below for both the POS and the dependency parsing task) is
1
Ruby
Ruby
adjust alignment of select and sort
c8084244996e6b7a6f0e018f18703ff5c4190ed2
<ide><path>Library/Homebrew/cmd/outdated.rb <ide> def print_outdated(formulae) <ide> verbose = ($stdout.tty? || ARGV.verbose?) && !ARGV.flag?("--quiet") <ide> fetch_head = ARGV.fetch_head? <ide> <del> outdated_formulae = formulae <del> .select { |f| f.outdated?(fetch_head: fetch_head) } <del> .sort <add> outdated_formulae = formulae.select { |f| f.outdated?(fetch_head: fetch_head) } <add> .sort <ide> <ide> outdated_formulae.each do |f| <ide> if verbose
1
Text
Text
add doc for converting a textmate theme
147db97d4d27b78bdaa4c29c464ed85c02ee7f61
<ide><path>docs/converting-a-text-mate-theme.md <add>## Converting a TextMate Theme <add> <add>This guide will show you how to convert a [TextMate][TextMate] theme to an Atom <add>theme. <add> <add>### Differences <add> <add>TextMate themes use [plist][plist] files while Atom themes use [CSS][CSS] or <add>[LESS][LESS] to style the UI and syntax in the editor. <add> <add>The utility that converts the theme first parses the theme's plist file and <add>then creates comparable CSS rules and properties that will style Atom similarly. <add> <add>### Install apm <add> <add>The `apm` command line utility that ships with Atom supports converting <add>a TextMate theme to an Atom theme. <add> <add>Check that you have `apm` installed by running the following command in your <add>terminal: <add> <add>``` <add>apm -h <add>``` <add> <add>You should see a message print out with all the possible `apm` commands. <add> <add>If you do not, launch Atom and run the _Atom > Install Shell Commmands_ menu <add>to install the `apm` and `atom` commands. <add> <add>### Convert the Theme <add> <add>Download the theme you wish to convert, you can browse existing TextMate themes <add>[here][TextMateThemes]. <add> <add>Now, let's say you've downloaded the theme to `~/Downloads/MyTheme.tmTheme`, <add>you can convert the theme with the following command: <add> <add>```sh <add>apm init --theme ~/.atom/packages/my-theme --convert ~/Downloads/MyTheme.tmTheme <add>``` <add> <add>You can browse to `~/.atom/packages/my-theme` to see the generated theme. <add> <add>### Activate the Theme <add> <add>Now that your theme is installed to `~/.atom/packages` you can enable it <add>by launching Atom and selecting the _Atom > Preferences..._ menu. <add> <add>Select the _Themes_ link on the left side and choose _My Theme_ from the <add>__Syntax Theme__ dropdown menu to enable your new theme. <add> <add>:tada: Your theme is now enabled, open an editor to see it in action! <add> <add>[CSS]: http://en.wikipedia.org/wiki/Cascading_Style_Sheets <add>[LESS]: http://lesscss.org <add>[plist]: http://en.wikipedia.org/wiki/Property_list <add>[TextMate]: http://macromates.com <add>[TextMateThemes]: http://wiki.macromates.com/Themes/UserSubmittedThemes
1
Javascript
Javascript
use rangeerror/typeerror consistently
b514bd231ed8926a0037b78e85d267a602c2e7cd
<ide><path>lib/zlib.js <ide> for (var ck = 0; ck < ckeys.length; ck++) { <ide> codes[codes[ckey]] = ckey; <ide> } <ide> <del>function isValidFlushFlag(flag) { <del> return flag >= constants.Z_NO_FLUSH && <del> flag <= constants.Z_BLOCK; <add>function isInvalidFlushFlag(flag) { <add> return typeof flag !== 'number' || <add> flag < constants.Z_NO_FLUSH || <add> flag > constants.Z_BLOCK; <ide> <ide> // Covers: constants.Z_NO_FLUSH (0), <ide> // constants.Z_PARTIAL_FLUSH (1), <ide> class Zlib extends Transform { <ide> this._opts = opts; <ide> this._chunkSize = opts.chunkSize || constants.Z_DEFAULT_CHUNK; <ide> <del> if (opts.flush && !isValidFlushFlag(opts.flush)) { <del> throw new Error('Invalid flush flag: ' + opts.flush); <add> if (opts.flush && isInvalidFlushFlag(opts.flush)) { <add> throw new RangeError('Invalid flush flag: ' + opts.flush); <ide> } <del> if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) { <del> throw new Error('Invalid flush flag: ' + opts.finishFlush); <add> if (opts.finishFlush && isInvalidFlushFlag(opts.finishFlush)) { <add> throw new RangeError('Invalid flush flag: ' + opts.finishFlush); <ide> } <ide> <ide> this._flushFlag = opts.flush || constants.Z_NO_FLUSH; <ide> class Zlib extends Transform { <ide> <ide> if (opts.chunkSize) { <ide> if (opts.chunkSize < constants.Z_MIN_CHUNK) { <del> throw new Error('Invalid chunk size: ' + opts.chunkSize); <add> throw new RangeError('Invalid chunk size: ' + opts.chunkSize); <ide> } <ide> } <ide> <ide> if (opts.windowBits) { <ide> if (opts.windowBits < constants.Z_MIN_WINDOWBITS || <ide> opts.windowBits > constants.Z_MAX_WINDOWBITS) { <del> throw new Error('Invalid windowBits: ' + opts.windowBits); <add> throw new RangeError('Invalid windowBits: ' + opts.windowBits); <ide> } <ide> } <ide> <ide> if (opts.level) { <ide> if (opts.level < constants.Z_MIN_LEVEL || <ide> opts.level > constants.Z_MAX_LEVEL) { <del> throw new Error('Invalid compression level: ' + opts.level); <add> throw new RangeError('Invalid compression level: ' + opts.level); <ide> } <ide> } <ide> <ide> if (opts.memLevel) { <ide> if (opts.memLevel < constants.Z_MIN_MEMLEVEL || <ide> opts.memLevel > constants.Z_MAX_MEMLEVEL) { <del> throw new Error('Invalid memLevel: ' + opts.memLevel); <add> throw new RangeError('Invalid memLevel: ' + opts.memLevel); <ide> } <ide> } <ide> <ide> if (opts.strategy && isInvalidStrategy(opts.strategy)) <del> throw new Error('Invalid strategy: ' + opts.strategy); <add> throw new TypeError('Invalid strategy: ' + opts.strategy); <ide> <ide> if (opts.dictionary) { <ide> if (!(opts.dictionary instanceof Buffer)) { <del> throw new Error('Invalid dictionary: it should be a Buffer instance'); <add> throw new TypeError( <add> 'Invalid dictionary: it should be a Buffer instance'); <ide> } <ide> } <ide> <ide> class Zlib extends Transform { <ide> var last = ending && (!chunk || ws.length === chunk.length); <ide> <ide> if (chunk !== null && !(chunk instanceof Buffer)) <del> return cb(new Error('invalid input')); <add> return cb(new TypeError('invalid input')); <ide> <ide> if (!this._handle) <ide> return cb(new Error('zlib binding closed')); <ide><path>test/parallel/test-zlib-deflate-constructors.js <ide> assert.ok(new zlib.DeflateRaw() instanceof zlib.DeflateRaw); <ide> // Throws if `opts.chunkSize` is invalid <ide> assert.throws( <ide> () => { new zlib.Deflate({chunkSize: -Infinity}); }, <del> /^Error: Invalid chunk size: -Infinity$/ <add> /^RangeError: Invalid chunk size: -Infinity$/ <ide> ); <ide> <ide> // Confirm that maximum chunk size cannot be exceeded because it is `Infinity`. <ide> assert.strictEqual(zlib.constants.Z_MAX_CHUNK, Infinity); <ide> // Throws if `opts.windowBits` is invalid <ide> assert.throws( <ide> () => { new zlib.Deflate({windowBits: -Infinity}); }, <del> /^Error: Invalid windowBits: -Infinity$/ <add> /^RangeError: Invalid windowBits: -Infinity$/ <ide> ); <ide> <ide> assert.throws( <ide> () => { new zlib.Deflate({windowBits: Infinity}); }, <del> /^Error: Invalid windowBits: Infinity$/ <add> /^RangeError: Invalid windowBits: Infinity$/ <ide> ); <ide> <ide> // Throws if `opts.level` is invalid <ide> assert.throws( <ide> () => { new zlib.Deflate({level: -Infinity}); }, <del> /^Error: Invalid compression level: -Infinity$/ <add> /^RangeError: Invalid compression level: -Infinity$/ <ide> ); <ide> <ide> assert.throws( <ide> () => { new zlib.Deflate({level: Infinity}); }, <del> /^Error: Invalid compression level: Infinity$/ <add> /^RangeError: Invalid compression level: Infinity$/ <ide> ); <ide> <ide> // Throws a RangeError if `level` invalid in `Deflate.prototype.params()` <ide> assert.throws( <ide> // Throws if `opts.memLevel` is invalid <ide> assert.throws( <ide> () => { new zlib.Deflate({memLevel: -Infinity}); }, <del> /^Error: Invalid memLevel: -Infinity$/ <add> /^RangeError: Invalid memLevel: -Infinity$/ <ide> ); <ide> <ide> assert.throws( <ide> () => { new zlib.Deflate({memLevel: Infinity}); }, <del> /^Error: Invalid memLevel: Infinity$/ <add> /^RangeError: Invalid memLevel: Infinity$/ <ide> ); <ide> <ide> // Does not throw if opts.strategy is valid <ide> assert.doesNotThrow( <ide> // Throws if opt.strategy is the wrong type. <ide> assert.throws( <ide> () => { new zlib.Deflate({strategy: '' + zlib.constants.Z_RLE }); }, <del> /^Error: Invalid strategy: 3$/ <add> /^TypeError: Invalid strategy: 3$/ <ide> ); <ide> <ide> // Throws if opts.strategy is invalid <ide> assert.throws( <ide> () => { new zlib.Deflate({strategy: 'this is a bogus strategy'}); }, <del> /^Error: Invalid strategy: this is a bogus strategy$/ <add> /^TypeError: Invalid strategy: this is a bogus strategy$/ <ide> ); <ide> <ide> // Throws TypeError if `strategy` is invalid in `Deflate.prototype.params()` <ide> assert.throws( <ide> // Throws if opts.dictionary is not a Buffer <ide> assert.throws( <ide> () => { new zlib.Deflate({dictionary: 'not a buffer'}); }, <del> /^Error: Invalid dictionary: it should be a Buffer instance$/ <add> /^TypeError: Invalid dictionary: it should be a Buffer instance$/ <ide> ); <ide><path>test/parallel/test-zlib-flush-flags.js <ide> assert.doesNotThrow(() => { <ide> <ide> assert.throws(() => { <ide> zlib.createGzip({ flush: 'foobar' }); <del>}, /Invalid flush flag: foobar/); <add>}, /^RangeError: Invalid flush flag: foobar$/); <ide> <ide> assert.throws(() => { <ide> zlib.createGzip({ flush: 10000 }); <del>}, /Invalid flush flag: 10000/); <add>}, /^RangeError: Invalid flush flag: 10000$/); <ide> <ide> assert.doesNotThrow(() => { <ide> zlib.createGzip({ finishFlush: zlib.constants.Z_SYNC_FLUSH }); <ide> }); <ide> <ide> assert.throws(() => { <ide> zlib.createGzip({ finishFlush: 'foobar' }); <del>}, /Invalid flush flag: foobar/); <add>}, /^RangeError: Invalid flush flag: foobar$/); <ide> <ide> assert.throws(() => { <ide> zlib.createGzip({ finishFlush: 10000 }); <del>}, /Invalid flush flag: 10000/); <add>}, /^RangeError: Invalid flush flag: 10000$/);
3
Go
Go
make extracted fds closeonexec
b0228d94beeeb331f6ac58b289eba4982a42c5d4
<ide><path>pkg/beam/unix.go <ide> func sendUnix(conn *net.UnixConn, data []byte, fds ...int) error { <ide> } <ide> <ide> func extractFds(oob []byte) (fds []int) { <add> // Grab forklock to make sure no forks accidentally inherit the new <add> // fds before they are made CLOEXEC <add> // There is a slight race condition between ReadMsgUnix returns and <add> // when we grap the lock, so this is not perfect. Unfortunately <add> // There is no way to pass MSG_CMSG_CLOEXEC to recvmsg() nor any <add> // way to implement non-blocking i/o in go, so this is hard to fix. <add> syscall.ForkLock.Lock() <add> defer syscall.ForkLock.Unlock() <ide> scms, err := syscall.ParseSocketControlMessage(oob) <ide> if err != nil { <ide> return <ide> func extractFds(oob []byte) (fds []int) { <ide> continue <ide> } <ide> fds = append(fds, gotFds...) <add> <add> for _, fd := range fds { <add> syscall.CloseOnExec(fd) <add> } <ide> } <ide> return <ide> }
1
Javascript
Javascript
fix error message
7b119f8b38671ca7ee26d369ccc7f629fb9bc3bf
<ide><path>lib/net.js <ide> Stream.prototype.write = function (data, encoding, fd) { <ide> if (this._writeQueue && this._writeQueue.length) { <ide> // Slow. There is already a write queue, so let's append to it. <ide> if (this._writeQueueLast() === END_OF_FILE) { <del> throw new Error('Stream.close() called already; cannot write.'); <add> throw new Error('Stream.end() called already; cannot write.'); <ide> } <ide> <ide> if (typeof data == 'string' &&
1
Ruby
Ruby
add specific examples to install cmd
daa87fa10f1c6fda9c4b48509f72fac19b44f878
<ide><path>Library/Homebrew/cmd/install.rb <ide> def install <ide> end <ide> <ide> opoo e <add> <add> reason = MissingFormula.reason(name, silent: true) <add> if !args.cask? && reason <add> $stderr.puts reason <add> return <add> end <add> <add> return if name.include?("/") <add> <ide> ohai "Searching for similarly named formulae and casks..." <ide> <ide> # Don't treat formula/cask name as a regex <ide> query = string_or_regex = name <del> if search_names(query, string_or_regex, args) <del> puts <<~EOL <add> all_formulae, all_casks = search_names(query, string_or_regex) <add> <add> print_formulae = args.formula? <add> print_casks = args.cask? <add> print_formulae = print_casks = true if !print_formulae && !print_casks <add> print_formulae &&= all_formulae.any? <add> print_casks &&= all_casks.any? <ide> <del> To install one of them, run: <del> brew install 'package_name' <del> EOL <add> if print_formulae <add> ohai "Formulae", Formatter.columns(all_formulae) <add> first_formula = all_formulae.first.to_s <add> puts <<~EOS <add> <add> To install #{first_formula}, run: <add> brew install #{first_formula} <add> EOS <ide> end <add> puts if print_formulae && print_casks <add> if print_casks <add> ohai "Casks", Formatter.columns(all_casks) <add> first_cask = all_casks.first.to_s <add> puts <<~EOS <add> <add> To install #{first_cask}, run: <add> brew install --cask #{first_cask} <add> EOS <add> end <add> <add> odie "No formulae or casks found for #{name}." if !print_formulae && !print_casks <ide> end <ide> end <ide><path>Library/Homebrew/cmd/search.rb <ide> def search <ide> elsif args.pull_request? <ide> search_pull_requests(query, args) <ide> else <del> search_names(query, string_or_regex, args) <add> formulae, casks = search_names(query, string_or_regex) <add> print_results(formulae, casks, query, args) <ide> end <ide> <ide> puts "Use `brew desc` to list packages with a short description." if args.verbose? <ide> def search_pull_requests(query, args) <ide> <ide> GitHub.print_pull_requests_matching(query, only) <ide> end <add> <add> def print_results(all_formulae, all_casks, query, args) <add> print_formulae = args.formula? <add> print_casks = args.cask? <add> print_formulae = print_casks = true if !print_formulae && !print_casks <add> print_formulae &&= all_formulae.any? <add> print_casks &&= all_casks.any? <add> <add> count = 0 <add> if all_formulae <add> if $stdout.tty? <add> ohai "Formulae", Formatter.columns(all_formulae) <add> else <add> puts all_formulae <add> end <add> count += all_formulae.count <add> end <add> puts if print_formulae && print_casks <add> if print_casks <add> if $stdout.tty? <add> ohai "Casks", Formatter.columns(all_casks) <add> else <add> puts all_casks <add> end <add> count += all_casks.count <add> end <add> <add> print_missing_formula_help(query, count.positive?) if all_casks.exclude?(query) <add> <add> odie "No formulae or casks found for #{query.inspect}." if count.zero? <add> end <add> <add> def print_missing_formula_help(query, found_matches) <add> return unless $stdout.tty? <add> <add> reason = MissingFormula.reason(query, silent: true) <add> return if reason.nil? <add> <add> if found_matches <add> puts <add> puts "If you meant #{query.inspect} specifically:" <add> end <add> puts reason <add> end <ide> end <ide><path>Library/Homebrew/search.rb <ide> def search_casks(_string_or_regex) <ide> [] <ide> end <ide> <del> def search_names(query, string_or_regex, args) <add> def search_names(query, string_or_regex) <ide> remote_results = search_taps(query, silent: true) <ide> <ide> local_formulae = search_formulae(string_or_regex) <ide> def search_names(query, string_or_regex, args) <ide> remote_casks = remote_results[:casks] <ide> all_casks = local_casks + remote_casks <ide> <del> print_formulae = args.formula? <del> print_casks = args.cask? <del> print_formulae = print_casks = true if !print_formulae && !print_casks <del> print_formulae &&= all_formulae.any? <del> print_casks &&= all_casks.any? <del> <del> count = 0 <del> if print_formulae <del> if $stdout.tty? <del> ohai "Formulae", Formatter.columns(all_formulae) <del> else <del> puts all_formulae <del> end <del> count += all_formulae.count <del> end <del> puts if print_formulae && print_casks <del> if print_casks <del> if $stdout.tty? <del> ohai "Casks", Formatter.columns(all_casks) <del> else <del> puts all_casks <del> end <del> count += all_casks.count <del> end <del> <del> print_missing_formula_help(query, count.positive?) if local_casks.exclude?(query) <del> <del> odie "No formulae or casks found for #{query.inspect}." if count.zero? <del> !count.zero? <del> end <del> <del> def print_missing_formula_help(query, found_matches) <del> return unless $stdout.tty? <del> <del> reason = MissingFormula.reason(query, silent: true) <del> return if reason.nil? <del> <del> if found_matches <del> puts <del> puts "If you meant #{query.inspect} specifically:" <del> end <del> puts reason <add> [all_formulae, all_casks] <ide> end <ide> end <ide> end
3
Ruby
Ruby
use render on inlinetemplate
7d5c8505f528f195433693d5074a00f7635955b2
<ide><path>actionpack/lib/action_view/base.rb <ide> def render_file(template_path, use_full_path = nil, local_assigns = {}) #:nodoc: <ide> end <ide> <ide> def render_inline(text, local_assigns = {}, type = nil) <del> InlineTemplate.new(self, text, local_assigns, type).render_template <add> InlineTemplate.new(self, text, local_assigns, type).render <ide> end <ide> <ide> def wrap_content_for_layout(content)
1
Text
Text
add v3.11.0-beta.3 to changelog
d7a2737078dbb389b5ec2356512be9680076a9fd
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.11.0-beta.3 (June 10, 2019) <add> <add>- [#18080](https://github.com/emberjs/ember.js/pull/18080) [BUGFIX] Fix `ember-template-compiler` compatibility with Fastboot. <add>- [#18071](https://github.com/emberjs/ember.js/pull/18071) [BUGFIX] Ensure modifiers do not run in FastBoot modes. <add> <ide> ### v3.11.0-beta.2 (June 3, 2019) <ide> <ide> - [#18064](https://github.com/emberjs/ember.js/pull/18064) [BUGFIX] Fix 'hasAttribute is not a function' when jQuery is disabled
1
Javascript
Javascript
improve performance of hash fn
8e3d6a085ba036b401edbfc4a58409cec88968f6
<ide><path>dist/Immutable.dev.js <ide> function hashValue(o) { <ide> if (o === true) { <ide> return 1; <ide> } <del> if (typeof o.hashCode === 'function') { <del> return o.hashCode(); <del> } <ide> var type = typeof o; <ide> if (type === 'number') { <del> return Math.floor(o) % 2147483647; <add> if ((o | 0) === o) { <add> return o % HASH_MAX_VAL; <add> } <add> o = '' + o; <add> type = 'string'; <ide> } <ide> if (type === 'string') { <del> return hashString(o); <add> return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o); <add> } <add> if (o.hashCode && typeof o.hashCode === 'function') { <add> return o.hashCode(); <ide> } <ide> throw new Error('Unable to hash: ' + o); <ide> } <del>function hashString(string) { <add>function cachedHashString(string) { <ide> var hash = STRING_HASH_CACHE[string]; <ide> if (hash == null) { <del> hash = 0; <del> for (var ii = 0; ii < string.length; ii++) { <del> hash = (31 * hash + string.charCodeAt(ii)) % STRING_HASH_MAX_VAL; <del> } <add> hash = hashString(string); <ide> if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { <ide> STRING_HASH_CACHE_SIZE = 0; <ide> STRING_HASH_CACHE = {}; <ide> function hashString(string) { <ide> } <ide> return hash; <ide> } <del>var STRING_HASH_MAX_VAL = 0x100000000; <add>function hashString(string) { <add> var hash = 0; <add> for (var ii = 0; ii < string.length; ii++) { <add> hash = (31 * hash + string.charCodeAt(ii)); <add> } <add> return hash % HASH_MAX_VAL; <add>} <add>var HASH_MAX_VAL = 0x100000000; <add>var STRING_HASH_CACHE_MIN_STRLEN = 16; <ide> var STRING_HASH_CACHE_MAX_SIZE = 255; <ide> var STRING_HASH_CACHE_SIZE = 0; <ide> var STRING_HASH_CACHE = {}; <ide><path>dist/Immutable.js <ide> * LICENSE file in the root directory of this source tree. An additional grant <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> */ <del>function t(){function t(t,e,n,r){var i;if(r){var s=r.prototype;i=G.create(s)}else i=t.prototype;return G.keys(e).forEach(function(t){i[t]=e[t]}),G.keys(n).forEach(function(e){t[e]=n[e]}),i.constructor=t,t.prototype=i,t}function e(t,e,n,r){return G.getPrototypeOf(e)[n].apply(t,r)}function n(t,n,r){e(t,n,"constructor",r)}function r(){return Object.create(X)}function i(t){var e=Object.create($);return e.__reversedIndices=t?t.__reversedIndices:!1,e}function s(t,e,n,r){var i=t.get?t.get(e[r],he):he;return i===he?n:++r===e.length?i:s(i,e,n,r)}function u(t,e,n){return(0===t||null!=n&&-n>=t)&&(null==e||null!=n&&e>=n)}function h(t,e){return 0>t?Math.max(0,e+t):e?Math.min(e,t):t}function a(t,e){return null==t?e:0>t?Math.max(0,e+t):e?Math.min(e,t):t}function o(t){return t}function c(t,e){return[e,t]}function f(){return!0}function l(){return this}function _(t){return(t||0)+1}function v(t,e,n,r,i){var s=t.__makeSequence();return s.__iterateUncached=function(s,u,h){var a=0,o=t.__iterate(function(t,i,u){if(e.call(n,t,i,u)){if(s(t,r?i:a,u)===!1)return!1;a++}},u,h);return i?o:a},s}function g(t){return function(){return!t.apply(this,arguments)}}function p(t){return"string"==typeof t?JSON.stringify(t):t}function m(t,e){for(var n="";e;)1&e&&(n+=t),(e>>=1)&&(t+=t);return n}function d(t,e){return t>e?1:e>t?-1:0}function y(t){I(1/0!==t,"Cannot perform this action with an infinite sequence.")}function w(t,e){return t===e?0!==t||0!==e||1/t===1/e:t!==t?e!==e:t instanceof Q?t.equals(e):!1}function I(t,e){if(!t)throw Error(e)}function O(t,e,n){var r=t._rootData.updateIn(t._keyPath,e),i=t._keyPath||[];return t._onChange&&t._onChange.call(void 0,r,t._rootData,n?i.concat(n):i),new ne(r,t._keyPath,t._onChange)}function D(){}function b(t){return we.value=t,we}function M(t,e,n){var r=Object.create(ce);return r.length=t,r._root=e,r.__ownerID=n,r}function k(t,e,n,r,i){if(n.hash===r)return new ge(t,r,[n.entry,i]);var s,u=n.hash>>>e&ue,h=r>>>e&ue,a=u===h?[k(t,e+ie,n,r,i)]:(s=new me(t,r,i),h>u?[n,s]:[s,n]);return new fe(t,1<<u|1<<h,a)}function S(t,e,n){for(var r=[],i=0;n.length>i;i++){var s=n[i]; <del>s&&r.push(Array.isArray(s)?Q(s).fromEntries():Q(s))}return E(t,e,r)}function x(t){return function(e,n){return e&&e.mergeDeepWith?e.mergeDeepWith(t,n):t?t(e,n):n}}function E(t,e,n){return 0===n.length?t:t.withMutations(function(t){for(var r=e?function(n,r){var i=t.get(r,he);t.set(r,i===he?n:e(i,n))}:function(e,n){t.set(n,e)},i=0;n.length>i;i++)n[i].forEach(r)})}function C(t,e,n,r){var i=e[r],s=t.get?t.get(i,he):he;return s===he&&(s=ae.empty()),I(t.set,"updateIn with invalid keyPath"),t.set(i,++r===e.length?n(s):C(s,e,n,r))}function A(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function q(t){if(!t)return 0;if(t===!0)return 1;if("function"==typeof t.hashCode)return t.hashCode();var e=typeof t;if("number"===e)return Math.floor(t)%2147483647;if("string"===e)return j(t);throw Error("Unable to hash: "+t)}function j(t){var e=be[t];if(null==e){e=0;for(var n=0;t.length>n;n++)e=(31*e+t.charCodeAt(n))%Ie;De===Oe&&(De=0,be={}),De++,be[t]=e}return e}function P(t,e,n,r,i,s){var u=Object.create(Ee);return u.length=e-t,u._origin=t,u._size=e,u._level=n,u._root=r,u._tail=i,u.__ownerID=s,u}function U(t,e){if(e>=J(t._size))return t._tail;if(1<<t._level+ie>e){for(var n=t._root,r=t._level;n&&r>0;)n=n.array[e>>>r&ue],r-=ie;return n}}function z(t,e,n){var r=t.__ownerID||new D,i=t._origin,s=t._size,u=i+e,h=null==n?s:0>n?s+n:i+n;if(u===i&&h===s)return t;if(u>=h)return t.clear();for(var a=t._level,o=t._root,c=0;0>u+c;)o=new Ce(o.array.length?[,o]:[],r),a+=ie,c+=1<<a;c&&(u+=c,i+=c,h+=c,s+=c);for(var f=J(s),l=J(h);l>=1<<a+ie;)o=new Ce(o.array.length?[o]:[],r),a+=ie;var _=t._tail,v=f>l?U(t,h-1):l>f?new Ce([],r):_;if(l>f&&s>u&&_.array.length){o=o.ensureOwner(r);for(var g=o,p=a;p>ie;p-=ie){var m=f>>>p&ue;g=g.array[m]=g.array[m]?g.array[m].ensureOwner(r):new Ce([],r)}g.array[f>>>ie&ue]=_}if(s>h&&(v=v.removeAfter(r,0,h)),u>=l)u-=l,h-=l,a=ie,o=Pe,v=v.removeBefore(r,0,u);else if(u>i||f>l){var d,y;c=0;do d=u>>>a&ue,y=l-1>>>a&ue,d===y&&(d&&(c+=(1<<a)*d),a-=ie,o=o&&o.array[d]);while(o&&d===y); <del>o&&u>i&&(o=o.removeBefore(r,a,u-c)),o&&f>l&&(o=o.removeAfter(r,a,l-c)),c&&(u-=c,h-=c),o=o||Pe}return t.__ownerID?(t.length=h-u,t._origin=u,t._size=h,t._level=a,t._root=o,t._tail=v,t):P(u,h,a,o,v)}function R(t,e,n){for(var r=[],i=0;n.length>i;i++){var s=n[i];s&&r.push(s.forEach?s:Q(s))}var u=Math.max.apply(null,r.map(function(t){return t.length||0}));return u>t.length&&(t=t.setLength(u)),E(t,e,r)}function W(t,e){return I(t>=0,"Index out of bounds"),t+e}function J(t){return se>t?0:t-1>>>ie<<ie}function B(t,e){var n=Object.create(Re);return n.length=t?t.length:0,n._map=t,n.__ownerID=e,n}function L(t,e,n){var r=Object.create(Je.prototype);return r.length=t?t.length:0,r._map=t,r._vector=e,r.__ownerID=n,r}function V(t,e,n){var r=Object.create(Object.getPrototypeOf(t));return r._map=e,r.__ownerID=n,r}function K(t,e){return e?N(e,t,"",{"":t}):F(t)}function N(t,e,n,r){return e&&(Array.isArray(e)||e.constructor===Object)?t.call(r,n,Q(e).map(function(n,r){return N(t,n,r,e)})):e}function F(t){if(t){if(Array.isArray(t))return Q(t).map(F).toVector();if(t.constructor===Object)return Q(t).map(F).toMap()}return t}var G=Object,H={};H.createClass=t,H.superCall=e,H.defaultSuperCall=n;var Q=function(t){return T.from(1===arguments.length?t:Array.prototype.slice.call(arguments))},T=Q;H.createClass(Q,{toString:function(){return this.__toString("Seq {","}")},__toString:function(t,e){return 0===this.length?t+e:t+" "+this.map(this.__toStringMapper).join(", ")+" "+e},__toStringMapper:function(t,e){return e+": "+p(t)},toJS:function(){return this.map(function(t){return t instanceof T?t.toJS():t}).__toJS()},toArray:function(){y(this.length);var t=Array(this.length||0);return this.values().forEach(function(e,n){t[n]=e}),t},toObject:function(){y(this.length);var t={};return this.forEach(function(e,n){t[n]=e}),t},toVector:function(){return y(this.length),Se.from(this)},toMap:function(){return y(this.length),ae.from(this)},toOrderedMap:function(){return y(this.length),Je.from(this)},toSet:function(){return y(this.length),Ue.from(this)},equals:function(t){if(this===t)return!0; <del>if(!(t instanceof T))return!1;if(null!=this.length&&null!=t.length){if(this.length!==t.length)return!1;if(0===this.length&&0===t.length)return!0}return this.__deepEquals(t)},__deepEquals:function(t){var e=this.cacheResult().entries().toArray(),n=0;return t.every(function(t,r){var i=e[n++];return w(r,i[0])&&w(t,i[1])})},join:function(t){t=t||",";var e="",n=!0;return this.forEach(function(r){n?(n=!1,e+=r):e+=t+r}),e},count:function(t,e){return t?this.filter(t,e).count():(null==this.length&&(this.length=this.forEach(f)),this.length)},countBy:function(t){var e=this;return Je.empty().withMutations(function(n){e.forEach(function(e,r,i){n.update(t(e,r,i),_)})})},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];var n=[this].concat(t.map(function(t){return T(t)})),r=this.__makeSequence();return r.length=n.reduce(function(t,e){return null!=t&&null!=e.length?t+e.length:void 0},0),r.__iterateUncached=function(t,e){for(var r,i=0,s=n.length-1,u=0;s>=u&&!r;u++){var h=n[e?s-u:u];i+=h.__iterate(function(e,n,i){return t(e,n,i)===!1?(r=!0,!1):void 0},e)}return i},r},reverse:function(){var t=this,e=t.__makeSequence();return e.length=t.length,e.__iterateUncached=function(e,n){return t.__iterate(e,!n)},e.reverse=function(){return t},e},keys:function(){return this.flip().values()},values:function(){var t=this,e=i(t);return e.length=t.length,e.values=l,e.__iterateUncached=function(e,n,r){if(r&&null==this.length)return this.cacheResult().__iterate(e,n,r);var i,s=0;return r?(s=this.length-1,i=function(t,n,r){return e(t,s--,r)!==!1}):i=function(t,n,r){return e(t,s++,r)!==!1},t.__iterate(i,n),r?this.length:s},e},entries:function(){var t=this;if(t._cache)return T(t._cache);var e=t.map(c).values();return e.fromEntries=function(){return t},e},forEach:function(t,e){return this.__iterate(e?t.bind(e):t)},reduce:function(t,e,n){var r=e;return this.forEach(function(e,i,s){r=t.call(n,r,e,i,s)}),r},reduceRight:function(t,e,n){return this.reverse(!0).reduce(t,e,n)},every:function(t,e){var n=!0;return this.forEach(function(r,i,s){return t.call(e,r,i,s)?void 0:(n=!1,!1) <del>}),n},some:function(t,e){return!this.every(g(t),e)},first:function(){return this.find(f)},last:function(){return this.findLast(f)},rest:function(){return this.slice(1)},butLast:function(){return this.slice(0,-1)},has:function(t){return this.get(t,he)!==he},get:function(t,e){return this.find(function(e,n){return w(n,t)},null,e)},getIn:function(t,e){return t&&0!==t.length?s(this,t,e,0):this},contains:function(t){return this.find(function(e){return w(e,t)},null,he)!==he},find:function(t,e,n){var r=n;return this.forEach(function(n,i,s){return t.call(e,n,i,s)?(r=n,!1):void 0}),r},findKey:function(t,e){var n;return this.forEach(function(r,i,s){return t.call(e,r,i,s)?(n=i,!1):void 0}),n},findLast:function(t,e,n){return this.reverse(!0).find(t,e,n)},findLastKey:function(t,e){return this.reverse(!0).findKey(t,e)},flip:function(){var t=this,e=r();return e.length=t.length,e.flip=function(){return t},e.__iterateUncached=function(e,n){return t.__iterate(function(t,n,r){return e(n,t,r)!==!1},n)},e},map:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){return n.__iterate(function(n,i,s){return r(t.call(e,n,i,s),i,s)!==!1},i)},r},mapKeys:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){return n.__iterate(function(n,i,s){return r(n,t.call(e,i,n,s),s)!==!1},i)},r},filter:function(t,e){return v(this,t,e,!0,!1)},slice:function(t,e){if(u(t,e,this.length))return this;var n=h(t,this.length),r=a(e,this.length);if(n!==n||r!==r)return this.entries().slice(t,e).fromEntries();var i=0===n?this:this.skip(n);return null==r||r===this.length?i:i.take(r-n)},take:function(t){var e=0,n=this.takeWhile(function(){return e++<t});return n.length=this.length&&Math.min(this.length,t),n},takeLast:function(t,e){return this.reverse(e).take(t).reverse(e)},takeWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,s){if(i)return this.cacheResult().__iterate(r,i,s);var u=0;return n.__iterate(function(n,i,s){return t.call(e,n,i,s)&&r(n,i,s)!==!1?void u++:!1 <del>},i,s),u},r},takeUntil:function(t,e,n){return this.takeWhile(g(t),e,n)},skip:function(t,e){if(0===t)return this;var n=0,r=this.skipWhile(function(){return n++<t},null,e);return r.length=this.length&&Math.max(0,this.length-t),r},skipLast:function(t,e){return this.reverse(e).skip(t).reverse(e)},skipWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,s){if(i)return this.cacheResult().__iterate(r,i,s);var u=!0,h=0;return n.__iterate(function(n,i,s){if(!u||!(u=t.call(e,n,i,s))){if(r(n,i,s)===!1)return!1;h++}},i,s),h},r},skipUntil:function(t,e,n){return this.skipWhile(g(t),e,n)},groupBy:function(t){var e=this,n=Je.empty().withMutations(function(n){e.forEach(function(e,r,i){var s=t(e,r,i),u=n.get(s,he);u===he&&(u=[],n.set(s,u)),u.push([r,e])})});return n.map(function(t){return T(t).fromEntries()})},sort:function(t,e){return this.sortBy(o,t,e)},sortBy:function(t,e){e=e||d;var n=this;return T(this.entries().entries().toArray().sort(function(r,i){return e(t(r[1][1],r[1][0],n),t(i[1][1],i[1][0],n))||r[0]-i[0]})).fromEntries().values().fromEntries()},cacheResult:function(){return!this._cache&&this.__iterateUncached&&(y(this.length),this._cache=this.entries().toArray(),null==this.length&&(this.length=this._cache.length)),this},__iterate:function(t,e,n){if(!this._cache)return this.__iterateUncached(t,e,n);var r=this.length-1,i=this._cache,s=this;if(e)for(var u=i.length-1;u>=0;u--){var h=i[u];if(t(h[1],n?h[0]:r-h[0],s)===!1)break}else i.every(n?function(e){return t(e[1],r-e[0],s)!==!1}:function(e){return t(e[1],e[0],s)!==!1});return this.length},__makeSequence:function(){return r()}},{from:function(t){if(t instanceof T)return t;if(!Array.isArray(t)){if(t&&t.constructor===Object)return new te(t);t=[t]}return new ee(t)}});var X=Q.prototype;X.toJSON=X.toJS,X.__toJS=X.toObject,X.inspect=X.toSource=function(){return""+this};var Y=function(){H.defaultSuperCall(this,Z.prototype,arguments)},Z=Y;H.createClass(Y,{toString:function(){return this.__toString("Seq [","]")},toArray:function(){y(this.length); <del>var t=Array(this.length||0);return t.length=this.forEach(function(e,n){t[n]=e}),t},fromEntries:function(){var t=this,e=r();return e.length=t.length,e.entries=function(){return t},e.__iterateUncached=function(e,n,r){return t.__iterate(function(t,n,r){return e(t[1],t[0],r)},n,r)},e},join:function(t){t=t||",";var e="",n=0;return this.forEach(function(r,i){var s=i-n;n=i,e+=(1===s?t:m(t,s))+r}),this.length&&this.length-1>n&&(e+=m(t,this.length-1-n)),e},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];var n=[this].concat(t).map(function(t){return Q(t)}),r=this.__makeSequence();return r.length=n.reduce(function(t,e){return null!=t&&null!=e.length?t+e.length:void 0},0),r.__iterateUncached=function(t,e,r){if(r&&!this.length)return this.cacheResult().__iterate(t,e,r);for(var i,s=0,u=r&&this.length-1,h=n.length-1,a=0;h>=a&&!i;a++){var o=n[e?h-a:a];o instanceof Z||(o=o.values()),s+=o.__iterate(function(e,n,h){return n+=s,t(e,r?u-n:n,h)===!1?(i=!0,!1):void 0},e)}return s},r},reverse:function(t){var e=this,n=e.__makeSequence();return n.length=e.length,n.__reversedIndices=!!(t^e.__reversedIndices),n.__iterateUncached=function(n,r,i){return e.__iterate(n,!r,i^t)},n.reverse=function(n){return t===n?e:$.reverse.call(this,n)},n},values:function(){var t=H.superCall(this,Z.prototype,"values",[]);return t.length=void 0,t},filter:function(t,e,n){var r=v(this,t,e,n,n);return n&&(r.length=this.length),r},indexOf:function(t){return this.findIndex(function(e){return w(e,t)})},lastIndexOf:function(t){return this.reverse(!0).indexOf(t)},findIndex:function(t,e){var n=this.findKey(t,e);return null==n?-1:n},findLastIndex:function(t,e){return this.reverse(!0).findIndex(t,e)},slice:function(t,e,n){var r=this;if(u(t,e,r.length))return r;var i=r.__makeSequence(),s=h(t,r.length),o=a(e,r.length);return i.length=r.length&&(n?r.length:o-s),i.__reversedIndices=r.__reversedIndices,i.__iterateUncached=function(i,u,c){if(u)return this.cacheResult().__iterate(i,u,c);var f=this.__reversedIndices^c;if(s!==s||o!==o||f&&null==r.length){var l=r.count(); <del>s=h(t,l),o=a(e,l)}var _=f?r.length-o:s,v=f?r.length-s:o,g=r.__iterate(function(t,e,r){return f?null!=v&&e>=v||e>=_&&i(t,n?e:e-_,r)!==!1:_>e||(null==v||v>e)&&i(t,n?e:e-_,r)!==!1},u,c);return null!=this.length?this.length:n?g:Math.max(0,g-_)},i},splice:function(t,e){for(var n=[],r=2;arguments.length>r;r++)n[r-2]=arguments[r];return 0===e&&0===n.length?this:this.slice(0,t).concat(n,this.slice(t+e))},takeWhile:function(t,e,n){var r=this,i=r.__makeSequence();return i.__iterateUncached=function(s,u,h){if(u)return this.cacheResult().__iterate(s,u,h);var a=0,o=!0,c=r.__iterate(function(n,r,i){return t.call(e,n,r,i)&&s(n,r,i)!==!1?void(a=r):(o=!1,!1)},u,h);return n?i.length:o?c:a+1},n&&(i.length=this.length),i},skipWhile:function(t,e,n){var r=this,i=r.__makeSequence();return n&&(i.length=this.length),i.__iterateUncached=function(i,s,u){if(s)return this.cacheResult().__iterate(i,s,u);var h=r.__reversedIndices^u,a=!0,o=0,c=r.__iterate(function(r,s,h){return a&&(a=t.call(e,r,s,h),a||(o=s)),a||i(r,u||n?s:s-o,h)!==!1},s,u);return n?c:h?o+1:c-o},i},groupBy:function(t,e,n){var r=this,i=Je.empty().withMutations(function(e){r.forEach(function(i,s,u){var h=t(i,s,u),a=e.get(h,he);a===he&&(a=Array(n?r.length:0),e.set(h,a)),n?a[s]=i:a.push(i)})});return i.map(function(t){return Q(t)})},sortBy:function(t,e,n){var r=H.superCall(this,Z.prototype,"sortBy",[t,e]);return n||(r=r.values()),r.length=this.length,r},__makeSequence:function(){return i(this)}},{},Q);var $=Y.prototype;$.__toJS=$.toArray,$.__toStringMapper=p;var te=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.length=e.length};H.createClass(te,{toObject:function(){return this._object},get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var n=this._object,r=this._keys,i=r.length-1,s=0;i>=s;s++){var u=e?i-s:s;if(t(n[r[u]],r[u],n)===!1)break}return s}},{},Q);var ee=function(t){this._array=t,this.length=t.length};H.createClass(ee,{toArray:function(){return this._array},__iterate:function(t,e,n){var r=this._array,i=r.length-1,s=-1; <del>if(e){for(var u=i;u>=0;u--){if(r.hasOwnProperty(u)&&t(r[u],n?u:i-u,r)===!1)return s+1;s=u}return r.length}var h=r.every(function(e,u){return t(e,n?i-u:u,r)===!1?!1:(s=u,!0)});return h?r.length:s+1}},{},Y),ee.prototype.get=te.prototype.get,ee.prototype.has=te.prototype.has;var ne=function(t,e,n){this._rootData=t,this._keyPath=e,this._onChange=n},re=ne;H.createClass(ne,{get:function(t,e){var n=this._rootData.getIn(this._keyPath,ae.empty());return t?n.get(t,e):n},set:function(t,e){return O(this,function(n){return n.set(t,e)},t)},"delete":function(t){return O(this,function(e){return e.delete(t)},t)},update:function(t,e){var n;return"function"==typeof t?(n=t,t=void 0):n=function(n){return n.update(t,e)},O(this,n,t)},cursor:function(t){return t&&!Array.isArray(t)&&(t=[t]),t&&0!==t.length?new re(this._rootData,this._keyPath?this._keyPath.concat(t):t,this._onChange):this}},{});var ie=5,se=1<<ie,ue=se-1,he={},ae=function(t){return t&&t.constructor===oe?t:t&&0!==t.length?oe.empty().merge(t):oe.empty()},oe=ae;H.createClass(ae,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return null==t||null==this._root?e:this._root.get(0,q(t),t,e)},set:function(t,e){if(null==t)return this;var n,r=this.length;if(this._root){var i=b();n=this._root.update(this.__ownerID,0,q(t),t,e,i),i.value&&r++}else r++,n=new me(this.__ownerID,q(t),[t,e]);return this.__ownerID?(this.length=r,this._root=n,this):n===this._root?this:M(r,n)},"delete":function(t){if(null==t||null==this._root)return this;var e=this.__ownerID&&b(),n=this._root.update(this.__ownerID,0,q(t),t,he,e);return this.__ownerID?(this._root=n,e.value&&this.length--,this):n?n===this._root?this:M(this.length-1,n):oe.empty()},update:function(t,e){return this.set(t,e(this.get(t)))},clear:function(){return this.__ownerID?(this.length=0,this._root=null,this):oe.empty()},merge:function(){return S(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return S(this,t,e)},mergeDeep:function(){return S(this,x(null),arguments) <del>},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return S(this,x(t),e)},updateIn:function(t,e){return t&&0!==t.length?C(this,t,e,0):e(this)},cursor:function(t,e){return e||"function"!=typeof t||(e=t,t=null),t&&!Array.isArray(t)&&(t=[t]),new ne(this,t,e)},withMutations:function(t){var e=this.asMutable();return t(e),e.__ensureOwner(this.__ownerID)},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new D)},asImmutable:function(){return this.__ensureOwner()},__iterate:function(t,e){return this._root?this._root.iterate(this,t,e):0},__deepEqual:function(t){var e=this;return t.every(function(t,n){return w(e.get(n,he),t)})},__ensureOwner:function(t){return t===this.__ownerID?this:t?M(this.length,this._root,t):(this.__ownerID=t,this)}},{empty:function(){return ye||(ye=M(0))}},Q);var ce=ae.prototype;ae.from=ae;var fe=function(t,e,n){this.ownerID=t,this.bitmap=e,this.nodes=n},le=fe;H.createClass(fe,{get:function(t,e,n,r){var i=1<<(e>>>t&ue),s=this.bitmap;return 0===(s&i)?r:this.nodes[A(s&i-1)].get(t+ie,e,n,r)},update:function(t,e,n,r,i,s){var u=n>>>e&ue,h=1<<u,a=this.bitmap,o=0!==(a&h),c=i===he;if(c&&!o)return this;var f,l,_=A(a&h-1),v=this.nodes;if(!o){if(s&&(s.value=!0),l=new me(t,n,[r,i]),v.length>=Me){for(var g=0,p=[],m=0;0!==a;m++,a>>>=1)1&a&&(p[m]=v[g++]);return p[u]=l,new _e(t,g+1,p)}return f=this.ensureOwner(t),f.nodes.splice(_,0,l),f.bitmap|=h,f}var d=v[_];return l=d.update(t,e+ie,n,r,i,s),l===d?this:l||this.bitmap!==h?(f=this.ensureOwner(t),l?f.nodes[_]=l:(f.nodes.splice(_,1),f.bitmap^=h),f):null},ensureOwner:function(t){return t&&t===this.ownerID?this:new le(t,this.bitmap,this.nodes.slice())},iterate:function(t,e,n){for(var r=this.nodes,i=r.length-1,s=0;i>=s;s++){var u=n?i-s:s,h=r[u];if(!h.iterate(t,e,n))return!1}return!0}},{});var _e=function(t,e,n){this.ownerID=t,this.count=e,this.nodes=n},ve=_e;H.createClass(_e,{get:function(t,e,n,r){var i=e>>>t&ue,s=this.nodes[i];return s?s.get(t+ie,e,n,r):r},update:function(t,e,n,r,i,s){var u=n>>>e&ue,h=i===he,a=this.nodes,o=a[u]; <del>if(h&&!o)return this;var c,f=this.count;if(o){if(c=o.update(t,e+ie,n,r,i,s),c===o)return this;if(!c&&(f--,s&&(s.value=!0),ke>=f)){for(var l=[],_=0,v=0,g=1,p=a.length;p>v;v++,g<<=1){var m=a[v];v!==u&&m&&(l.push(m),_|=g)}return new fe(t,_,l)}}else c=new me(t,n,[r,i]),f++,s&&(s.value=!0);if(t&&t===this.ownerID)return this.count=f,this.nodes[u]=c,this;var d=a.slice();return d[u]=c,new ve(t,f,d)},iterate:function(t,e,n){for(var r=this.nodes,i=0,s=r.length-1;s>=i;i++){var u=r[n?s-i:i];if(u&&!u.iterate(t,e,n))return!1}return!0}},{});var ge=function(t,e,n){this.ownerID=t,this.hash=e,this.entries=n},pe=ge;H.createClass(ge,{get:function(t,e,n,r){for(var i=this.entries,s=0,u=i.length;u>s;s++)if(n===i[s][0])return i[s][1];return r},update:function(t,e,n,r,i,s){var u,h=i===he;if(n!==this.hash)return h?this:(s&&(s.value=!0),k(t,e,this,n,[r,i]));for(var a=this.entries,o=0,c=a.length;c>o;o++)if(r===a[o][0])return h?(s&&(s.value=!0),2===c?new me(t,this.hash,a[o]):(u=this.ensureOwner(t),o===c-1?u.entries.pop():u.entries[o]=u.entries.pop(),u)):(u=this.ensureOwner(t),u.entries[o]=[r,i],u);return h?this:(s&&(s.value=!0),u=this.ensureOwner(t),u.push([r,i]),u)},ensureOwner:function(t){return t&&t===this.ownerID?this:new pe(t,this.hash,this.entries.slice())},iterate:function(t,e,n){for(var r=this.entries,i=r.length-1,s=0;i>=s;s++){var u=n?i-s:s;if(e(r[u][1],r[u][0],t)===!1)return!1}return!0}},{});var me=function(t,e,n){this.ownerID=t,this.hash=e,this.entry=n},de=me;H.createClass(me,{get:function(t,e,n,r){return n===this.entry[0]?this.entry[1]:r},update:function(t,e,n,r,i,s){var u=r===this.entry[0];return i===he?(u&&s&&(s.value=!0),u?null:this):u?i===this.entry[1]?this:t&&t===this.ownerID?(this.entry[1]=i,this):new de(t,n,[r,i]):(s&&(s.value=!0),k(t,e,this,n,[r,i]))},iterate:function(t,e){return e(this.entry[1],this.entry[0],t)!==!1}},{});var ye,we={value:!1},Ie=4294967296,Oe=255,De=0,be={},Me=se/2,ke=se/4,Se=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return xe.from(t)},xe=Se;H.createClass(Se,{toString:function(){return this.__toString("Vector [","]") <del>},get:function(t,e){if(t=W(t,this._origin),t>=this._size)return e;var n=U(this,t),r=t&ue;return n&&(void 0===e||n.array.hasOwnProperty(r))?n.array[r]:e},first:function(){return this.get(0)},last:function(){return this.get(this.length?this.length-1:0)},set:function(t,e){var n=J(this._size);if(t>=this.length)return this.withMutations(function(n){return z(n,0,t+1).set(t,e)});if(this.get(t,he)===e)return this;if(t=W(t,this._origin),t>=n){var r=this._tail.ensureOwner(this.__ownerID);r.array[t&ue]=e;var i=t>=this._size?t+1:this._size;return this.__ownerID?(this.length=i-this._origin,this._size=i,this._tail=r,this):P(this._origin,i,this._level,this._root,r)}for(var s=this._root.ensureOwner(this.__ownerID),u=s,h=this._level;h>0;h-=ie){var a=t>>>h&ue;u=u.array[a]=u.array[a]?u.array[a].ensureOwner(this.__ownerID):new Ce([],this.__ownerID)}return u.array[t&ue]=e,this.__ownerID?(this._root=s,this):P(this._origin,this._size,this._level,s,this._tail)},"delete":function(t){if(!this.has(t))return this;var e=J(this._size);if(t=W(t,this._origin),t>=e){var n=this._tail.ensureOwner(this.__ownerID);return delete n.array[t&ue],this.__ownerID?(this._tail=n,this):P(this._origin,this._size,this._level,this._root,n)}for(var r=this._root.ensureOwner(this.__ownerID),i=r,s=this._level;s>0;s-=ie){var u=t>>>s&ue;i=i.array[u]=i.array[u].ensureOwner(this.__ownerID)}return delete i.array[t&ue],this.__ownerID?(this._root=r,this):P(this._origin,this._size,this._level,r,this._tail)},clear:function(){return this.__ownerID?(this.length=this._origin=this._size=0,this._level=ie,this._root=this._tail=Pe,this):xe.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(n){z(n,0,e+t.length);for(var r=0;t.length>r;r++)n.set(e+r,t[r])})},pop:function(){return z(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){z(e,-t.length);for(var n=0;t.length>n;n++)e.set(n,t[n])})},shift:function(){return z(this,1)},merge:function(){return R(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n]; <del>return R(this,t,e)},mergeDeep:function(){return R(this,x(null),arguments)},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return R(this,x(t),e)},setLength:function(t){return z(this,0,t)},slice:function(t,e,n){var r=H.superCall(this,xe.prototype,"slice",[t,e,n]);if(!n&&r!==this){var i=this,s=i.length;r.toVector=function(){return z(i,0>t?Math.max(0,s+t):s?Math.min(s,t):t,null==e?s:0>e?Math.max(0,s+e):s?Math.min(s,e):e)}}return r},iterator:function(){return new qe(this,this._origin,this._size,this._level,this._root,this._tail)},__iterate:function(t,e,n){var r=this,i=0,s=r.length-1;n^=e;var u,h=function(e,u){return t(e,n?s-u:u,r)===!1?!1:(i=u,!0)},a=J(this._size);return u=e?this._tail.iterate(0,a-this._origin,this._size-this._origin,h,e)&&this._root.iterate(this._level,-this._origin,a-this._origin,h,e):this._root.iterate(this._level,-this._origin,a-this._origin,h,e)&&this._tail.iterate(0,a-this._origin,this._size-this._origin,h,e),(u?s:e?s-i:i)+1},__deepEquals:function(t){var e=this.iterator();return t.every(function(t,n){var r=e.next().value;return r&&n===r[0]&&w(t,r[1])})},__ensureOwner:function(t){return t===this.__ownerID?this:t?P(this._origin,this._size,this._level,this._root,this._tail,t):(this.__ownerID=t,this)}},{empty:function(){return je||(je=P(0,0,ie,Pe,Pe))},from:function(t){if(t&&t.constructor===xe)return t;if(!t||0===t.length)return xe.empty();var e=Array.isArray(t);return t.length>0&&se>t.length?P(0,t.length,ie,Pe,new Ce(e?t.slice():Q(t).toArray())):(e||(t=Q(t),t instanceof Y||(t=t.values())),xe.empty().merge(t))}},Y);var Ee=Se.prototype;Ee["@@iterator"]=Ee.__iterator__,Ee.update=ce.update,Ee.updateIn=ce.updateIn,Ee.cursor=ce.cursor,Ee.withMutations=ce.withMutations,Ee.asMutable=ce.asMutable,Ee.asImmutable=ce.asImmutable;var Ce=function(t,e){this.array=t,this.ownerID=e},Ae=Ce;H.createClass(Ce,{ensureOwner:function(t){return t&&t===this.ownerID?this:new Ae(this.array.slice(),t)},removeBefore:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this;var r=n>>>e&ue; <del>if(r>=this.array.length)return new Ae([],t);var i,s=0===r;if(e>0){var u=this.array[r];if(i=u&&u.removeBefore(t,e-ie,n),i===u&&s)return this}if(s&&!i)return this;var h=this.ensureOwner();if(!s)for(var a=0;r>a;a++)delete h.array[a];return i&&(h.array[r]=i),h},removeAfter:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this;var r=n-1>>>e&ue;if(r>=this.array.length)return this;var i,s=r===this.array.length-1;if(e>0){var u=this.array[r];if(i=u&&u.removeAfter(t,e-ie,n),i===u&&s)return this}if(s&&!i)return this;var h=this.ensureOwner();return s||(h.array.length=r+1),i&&(h.array[r]=i),h},iterate:function(t,e,n,r,i){if(0===t){if(i){for(var s=this.array.length-1;s>=0;s--)if(this.array.hasOwnProperty(s)){var u=s+e;if(u>=0&&n>u&&r(this.array[s],u)===!1)return!1}return!0}return this.array.every(function(t,i){var s=i+e;return 0>s||s>=n||r(t,s)!==!1})}var h=1<<t,a=t-ie;if(i){for(var o=this.array.length-1;o>=0;o--){var c=e+o*h;if(n>c&&c+h>0&&this.array.hasOwnProperty(o)&&!this.array[o].iterate(a,c,n,r,i))return!1}return!0}return this.array.every(function(t,s){var u=e+s*h;return u>=n||0>=u+h||t.iterate(a,u,n,r,i)})}},{});var qe=function(t,e,n,r,i,s){var u=J(n);this._stack={node:i.array,level:r,offset:-e,max:u-e,__prev:{node:s.array,level:0,offset:u-e,max:n-e}}};H.createClass(qe,{next:function(){var t=this._stack;t:for(;t;){if(0===t.level)for(t.rawIndex||(t.rawIndex=0);t.node.length>t.rawIndex;){var e=t.rawIndex+t.offset;if(e>=0&&t.max>e&&t.node.hasOwnProperty(t.rawIndex)){var n=t.node[t.rawIndex];return t.rawIndex++,{value:[e,n],done:!0}}t.rawIndex++}else{var r=1<<t.level;for(t.levelIndex||(t.levelIndex=0);t.node.length>t.levelIndex;){var i=t.offset+t.levelIndex*r;if(i+r>0&&t.max>i&&t.node.hasOwnProperty(t.levelIndex)){var s=t.node[t.levelIndex].array;t.levelIndex++,t=this._stack={node:s,level:t.level-ie,offset:i,max:t.max,__prev:t};continue t}t.levelIndex++}}t=this._stack=this._stack.__prev}return{done:!0}}},{});var je,Pe=new Ce([]),Ue=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return ze.from(t) <del>},ze=Ue;H.createClass(Ue,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map?this._map.has(t):!1},get:function(t,e){return this.has(t)?t:e},add:function(t){if(null==t)return this;var e=this._map;return e||(e=ae.empty().__ensureOwner(this.__ownerID)),e=e.set(t,null),this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:B(e)},"delete":function(t){if(null==t||null==this._map)return this;var e=this._map.delete(t);return 0===e.length?this.clear():this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:B(e)},clear:function(){return this.__ownerID?(this.length=0,this._map=null,this):ze.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var n=0;t.length>n;n++){var r=t[n];r=r.forEach?r:Q(r),r.forEach(function(t){return e.add(t)})}})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return Q(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.every(function(t){return t.contains(n)})||e.delete(n)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return Q(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.some(function(t){return t.contains(n)})&&e.delete(n)})})},isSubset:function(t){return t=Q(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=Q(t),t.every(function(t){return e.contains(t)})},__iterate:function(t,e){var n=this;return this._map?this._map.__iterate(function(e,r){return t(r,r,n)},e):0},__deepEquals:function(t){return!(this._map||t._map)||this._map.equals(t._map)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?B(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return We||(We=B())},from:function(t){return t&&t.constructor===ze?t:t&&0!==t.length?ze.empty().union(t):ze.empty() <del>},fromKeys:function(t){return ze.from(Q(t).flip())}},Q);var Re=Ue.prototype;Re.contains=Re.has,Re.withMutations=ae.prototype.withMutations,Re.asMutable=ae.prototype.asMutable,Re.asImmutable=ae.prototype.asImmutable,Re.__toJS=Y.prototype.__toJS,Re.__toStringMapper=Y.prototype.__toStringMapper;var We,Je=function(t){return t&&t.constructor===Be?t:t&&0!==t.length?Be.empty().merge(t):Be.empty()},Be=Je;H.createClass(Je,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){if(null!=t&&this._map){var n=this._map.get(t);if(null!=n)return this._vector.get(n)[1]}return e},clear:function(){return this.__ownerID?(this.length=0,this._map=this._vector=null,this):Be.empty()},set:function(t,e){if(null==t)return this;var n=this._map,r=this._vector;if(n){var i=n.get(t);null==i?(n=n.set(t,r.length),r=r.push([t,e])):r.get(i)[1]!==e&&(r=r.set(i,[t,e]))}else r=Se.empty().__ensureOwner(this.__ownerID).set(0,[t,e]),n=ae.empty().__ensureOwner(this.__ownerID).set(t,0);return this.__ownerID?(this.length=n.length,this._map=n,this._vector=r,this):r===this._vector?this:L(n,r)},"delete":function(t){if(null==t||null==this._map)return this;var e=this._map.get(t);if(null==e)return this;var n=this._map.delete(t),r=this._vector.delete(e);return 0===n.length?this.clear():this.__ownerID?(this.length=n.length,this._map=n,this._vector=r,this):n===this._map?this:L(n,r)},__iterate:function(t,e){return this._vector?this._vector.fromEntries().__iterate(t,e):0},__deepEqual:function(t){var e=this._vector.__iterator__();return t.every(function(t,n){var r=e.next();return r&&(r=r[1]),r&&w(n,r[0])&&w(t,r[1])})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t),n=this._vector&&this._vector.__ensureOwner(t);return t?L(e,n,t):(this.__ownerID=t,this._map=e,this._vector=n,this)}},{empty:function(){return Le||(Le=L())}},ae),Je.from=Je;var Le,Ve=function(t,e){var n=function(t){this._map=ae(t)};t=Q(t);var r=n.prototype=Object.create(Ne);r.constructor=n,r._name=e,r._defaultValues=t;var i=Object.keys(t); <del>return n.prototype.length=i.length,Object.defineProperty&&t.forEach(function(t,e){Object.defineProperty(n.prototype,e,{get:function(){return this.get(e)},set:function(t){I(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}),n},Ke=Ve;H.createClass(Ve,{toString:function(){return this.__toString((this._name||"Record")+" {","}")},has:function(t){return this._defaultValues.has(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues.get(t)):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;Object.getPrototypeOf(this).constructor;return Ke._empty||(Ke._empty=V(this,ae.empty()))},set:function(t,e){if(null==t||!this.has(t))return this;var n=this._map.set(t,e);return this.__ownerID||n===this._map?this:V(this,n)},"delete":function(t){if(null==t||!this.has(t))return this;var e=this._map.delete(t);return this.__ownerID||e===this._map?this:V(this,e)},__iterate:function(t,e){var n=this;return this._defaultValues.map(function(t,e){return n.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?V(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},Q);var Ne=Ve.prototype;Ne.__deepEqual=ce.__deepEqual,Ne.merge=ce.merge,Ne.mergeWith=ce.mergeWith,Ne.mergeDeep=ce.mergeDeep,Ne.mergeDeepWith=ce.mergeDeepWith,Ne.update=ce.update,Ne.updateIn=ce.updateIn,Ne.cursor=ce.cursor,Ne.withMutations=ce.withMutations,Ne.asMutable=ce.asMutable,Ne.asImmutable=ce.asImmutable;var Fe=function(t,e,n){return this instanceof Ge?(I(0!==n,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&Qe?Qe:(n=null==n?1:Math.abs(n),t>e&&(n=-n),this._start=t,this._end=e,this._step=n,void(this.length=Math.max(0,Math.ceil((e-t)/n-1)+1)))):new Ge(t,e,n)},Ge=Fe;H.createClass(Fe,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},has:function(t){return I(t>=0,"Index out of bounds"),this.length>t},get:function(t,e){return I(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._start+t*this._step:e <del>},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e,n){return u(t,e,this.length)?this:n?H.superCall(this,Ge.prototype,"slice",[t,e,n]):(t=h(t,this.length),e=a(e,this.length),t>=e?Qe:new Ge(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var n=e/this._step;if(n>=0&&this.length>n)return n}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,t)},skip:function(t,e){return e?H.superCall(this,Ge.prototype,"skip",[t]):this.slice(t)},__iterate:function(t,e,n){for(var r=e^n,i=this.length-1,s=this._step,u=e?this._start+i*s:this._start,h=0;i>=h&&t(u,r?i-h:h,this)!==!1;h++)u+=e?-s:s;return r?this.length:h},__deepEquals:function(t){return this._start===t._start&&this._end===t._end&&this._step===t._step}},{},Y);var He=Fe.prototype;He.__toJS=He.toArray,He.first=Ee.first,He.last=Ee.last;var Qe=Fe(0,0),Te=function(t,e){return 0===e&&Ze?Ze:this instanceof Xe?(this._value=t,void(this.length=null==e?1/0:Math.max(0,e))):new Xe(t,e)},Xe=Te;H.createClass(Te,{toString:function(){return 0===this.length?"Repeat []":"Repeat [ "+this._value+" "+this.length+" times ]"},get:function(t,e){return I(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._value:e},first:function(){return this._value},contains:function(t){return w(this._value,t)},slice:function(t,e,n){if(n)return H.superCall(this,Xe.prototype,"slice",[t,e,n]);var r=this.length;return t=0>t?Math.max(0,r+t):Math.min(r,t),e=null==e?r:e>0?Math.min(r,e):Math.max(0,r+e),e>t?new Xe(this._value,e-t):Ze},reverse:function(t){return t?H.superCall(this,Xe.prototype,"reverse",[t]):this},indexOf:function(t){return w(this._value,t)?0:-1},lastIndexOf:function(t){return w(this._value,t)?this.length:-1},__iterate:function(t,e,n){var r=e^n;I(!r||1/0>this.length,"Cannot access end of infinite range.");for(var i=this.length-1,s=0;i>=s&&t(this._value,r?i-s:s,this)!==!1;s++);return r?this.length:s},__deepEquals:function(t){return w(this._value,t._value) <del>}},{},Y);var Ye=Te.prototype;Ye.last=Ye.first,Ye.has=He.has,Ye.take=He.take,Ye.skip=He.skip,Ye.__toJS=He.__toJS;var Ze=new Te(void 0,0),$e={Sequence:Q,Map:ae,Vector:Se,Set:Ue,OrderedMap:Je,Record:Ve,Range:Fe,Repeat:Te,is:w,fromJS:K};return $e}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t(); <ide>\ No newline at end of file <add>function t(){function t(t,e,n,r){var i;if(r){var s=r.prototype;i=H.create(s)}else i=t.prototype;return H.keys(e).forEach(function(t){i[t]=e[t]}),H.keys(n).forEach(function(e){t[e]=n[e]}),i.constructor=t,t.prototype=i,t}function e(t,e,n,r){return H.getPrototypeOf(e)[n].apply(t,r)}function n(t,n,r){e(t,n,"constructor",r)}function r(){return Object.create(Y)}function i(t){var e=Object.create(te);return e.__reversedIndices=t?t.__reversedIndices:!1,e}function s(t,e,n,r){var i=t.get?t.get(e[r],ae):ae;return i===ae?n:++r===e.length?i:s(i,e,n,r)}function u(t,e,n){return(0===t||null!=n&&-n>=t)&&(null==e||null!=n&&e>=n)}function h(t,e){return 0>t?Math.max(0,e+t):e?Math.min(e,t):t}function a(t,e){return null==t?e:0>t?Math.max(0,e+t):e?Math.min(e,t):t}function o(t){return t}function c(t,e){return[e,t]}function f(){return!0}function l(){return this}function _(t){return(t||0)+1}function v(t,e,n,r,i){var s=t.__makeSequence();return s.__iterateUncached=function(s,u,h){var a=0,o=t.__iterate(function(t,i,u){if(e.call(n,t,i,u)){if(s(t,r?i:a,u)===!1)return!1;a++}},u,h);return i?o:a},s}function g(t){return function(){return!t.apply(this,arguments)}}function p(t){return"string"==typeof t?JSON.stringify(t):t}function m(t,e){for(var n="";e;)1&e&&(n+=t),(e>>=1)&&(t+=t);return n}function d(t,e){return t>e?1:e>t?-1:0}function y(t){I(1/0!==t,"Cannot perform this action with an infinite sequence.")}function w(t,e){return t===e?0!==t||0!==e||1/t===1/e:t!==t?e!==e:t instanceof T?t.equals(e):!1}function I(t,e){if(!t)throw Error(e)}function O(t,e,n){var r=t._rootData.updateIn(t._keyPath,e),i=t._keyPath||[];return t._onChange&&t._onChange.call(void 0,r,t._rootData,n?i.concat(n):i),new re(r,t._keyPath,t._onChange)}function D(){}function b(t){return Ie.value=t,Ie}function M(t,e,n){var r=Object.create(fe);return r.length=t,r._root=e,r.__ownerID=n,r}function k(t,e,n,r,i){if(n.hash===r)return new pe(t,r,[n.entry,i]);var s,u=n.hash>>>e&he,h=r>>>e&he,a=u===h?[k(t,e+se,n,r,i)]:(s=new de(t,r,i),h>u?[n,s]:[s,n]);return new le(t,1<<u|1<<h,a)}function S(t,e,n){for(var r=[],i=0;n.length>i;i++){var s=n[i]; <add>s&&r.push(Array.isArray(s)?T(s).fromEntries():T(s))}return E(t,e,r)}function x(t){return function(e,n){return e&&e.mergeDeepWith?e.mergeDeepWith(t,n):t?t(e,n):n}}function E(t,e,n){return 0===n.length?t:t.withMutations(function(t){for(var r=e?function(n,r){var i=t.get(r,ae);t.set(r,i===ae?n:e(i,n))}:function(e,n){t.set(n,e)},i=0;n.length>i;i++)n[i].forEach(r)})}function C(t,e,n,r){var i=e[r],s=t.get?t.get(i,ae):ae;return s===ae&&(s=oe.empty()),I(t.set,"updateIn with invalid keyPath"),t.set(i,++r===e.length?n(s):C(s,e,n,r))}function A(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function q(t){if(!t)return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){if((0|t)===t)return t%Oe;t=""+t,e="string"}if("string"===e)return t.length>De?j(t):P(t);if(t.hashCode&&"function"==typeof t.hashCode)return t.hashCode();throw Error("Unable to hash: "+t)}function j(t){var e=ke[t];return null==e&&(e=P(t),Me===be&&(Me=0,ke={}),Me++,ke[t]=e),e}function P(t){for(var e=0,n=0;t.length>n;n++)e=31*e+t.charCodeAt(n);return e%Oe}function U(t,e,n,r,i,s){var u=Object.create(Ae);return u.length=e-t,u._origin=t,u._size=e,u._level=n,u._root=r,u._tail=i,u.__ownerID=s,u}function z(t,e){if(e>=B(t._size))return t._tail;if(1<<t._level+se>e){for(var n=t._root,r=t._level;n&&r>0;)n=n.array[e>>>r&he],r-=se;return n}}function R(t,e,n){var r=t.__ownerID||new D,i=t._origin,s=t._size,u=i+e,h=null==n?s:0>n?s+n:i+n;if(u===i&&h===s)return t;if(u>=h)return t.clear();for(var a=t._level,o=t._root,c=0;0>u+c;)o=new qe(o.array.length?[,o]:[],r),a+=se,c+=1<<a;c&&(u+=c,i+=c,h+=c,s+=c);for(var f=B(s),l=B(h);l>=1<<a+se;)o=new qe(o.array.length?[o]:[],r),a+=se;var _=t._tail,v=f>l?z(t,h-1):l>f?new qe([],r):_;if(l>f&&s>u&&_.array.length){o=o.ensureOwner(r);for(var g=o,p=a;p>se;p-=se){var m=f>>>p&he;g=g.array[m]=g.array[m]?g.array[m].ensureOwner(r):new qe([],r)}g.array[f>>>se&he]=_}if(s>h&&(v=v.removeAfter(r,0,h)),u>=l)u-=l,h-=l,a=se,o=ze,v=v.removeBefore(r,0,u);else if(u>i||f>l){var d,y;c=0;do d=u>>>a&he,y=l-1>>>a&he,d===y&&(d&&(c+=(1<<a)*d),a-=se,o=o&&o.array[d]); <add>while(o&&d===y);o&&u>i&&(o=o.removeBefore(r,a,u-c)),o&&f>l&&(o=o.removeAfter(r,a,l-c)),c&&(u-=c,h-=c),o=o||ze}return t.__ownerID?(t.length=h-u,t._origin=u,t._size=h,t._level=a,t._root=o,t._tail=v,t):U(u,h,a,o,v)}function W(t,e,n){for(var r=[],i=0;n.length>i;i++){var s=n[i];s&&r.push(s.forEach?s:T(s))}var u=Math.max.apply(null,r.map(function(t){return t.length||0}));return u>t.length&&(t=t.setLength(u)),E(t,e,r)}function J(t,e){return I(t>=0,"Index out of bounds"),t+e}function B(t){return ue>t?0:t-1>>>se<<se}function L(t,e){var n=Object.create(Je);return n.length=t?t.length:0,n._map=t,n.__ownerID=e,n}function V(t,e,n){var r=Object.create(Le.prototype);return r.length=t?t.length:0,r._map=t,r._vector=e,r.__ownerID=n,r}function K(t,e,n){var r=Object.create(Object.getPrototypeOf(t));return r._map=e,r.__ownerID=n,r}function N(t,e){return e?F(e,t,"",{"":t}):G(t)}function F(t,e,n,r){return e&&(Array.isArray(e)||e.constructor===Object)?t.call(r,n,T(e).map(function(n,r){return F(t,n,r,e)})):e}function G(t){if(t){if(Array.isArray(t))return T(t).map(G).toVector();if(t.constructor===Object)return T(t).map(G).toMap()}return t}var H=Object,Q={};Q.createClass=t,Q.superCall=e,Q.defaultSuperCall=n;var T=function(t){return X.from(1===arguments.length?t:Array.prototype.slice.call(arguments))},X=T;Q.createClass(T,{toString:function(){return this.__toString("Seq {","}")},__toString:function(t,e){return 0===this.length?t+e:t+" "+this.map(this.__toStringMapper).join(", ")+" "+e},__toStringMapper:function(t,e){return e+": "+p(t)},toJS:function(){return this.map(function(t){return t instanceof X?t.toJS():t}).__toJS()},toArray:function(){y(this.length);var t=Array(this.length||0);return this.values().forEach(function(e,n){t[n]=e}),t},toObject:function(){y(this.length);var t={};return this.forEach(function(e,n){t[n]=e}),t},toVector:function(){return y(this.length),Ee.from(this)},toMap:function(){return y(this.length),oe.from(this)},toOrderedMap:function(){return y(this.length),Le.from(this)},toSet:function(){return y(this.length),Re.from(this) <add>},equals:function(t){if(this===t)return!0;if(!(t instanceof X))return!1;if(null!=this.length&&null!=t.length){if(this.length!==t.length)return!1;if(0===this.length&&0===t.length)return!0}return this.__deepEquals(t)},__deepEquals:function(t){var e=this.cacheResult().entries().toArray(),n=0;return t.every(function(t,r){var i=e[n++];return w(r,i[0])&&w(t,i[1])})},join:function(t){t=t||",";var e="",n=!0;return this.forEach(function(r){n?(n=!1,e+=r):e+=t+r}),e},count:function(t,e){return t?this.filter(t,e).count():(null==this.length&&(this.length=this.forEach(f)),this.length)},countBy:function(t){var e=this;return Le.empty().withMutations(function(n){e.forEach(function(e,r,i){n.update(t(e,r,i),_)})})},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];var n=[this].concat(t.map(function(t){return X(t)})),r=this.__makeSequence();return r.length=n.reduce(function(t,e){return null!=t&&null!=e.length?t+e.length:void 0},0),r.__iterateUncached=function(t,e){for(var r,i=0,s=n.length-1,u=0;s>=u&&!r;u++){var h=n[e?s-u:u];i+=h.__iterate(function(e,n,i){return t(e,n,i)===!1?(r=!0,!1):void 0},e)}return i},r},reverse:function(){var t=this,e=t.__makeSequence();return e.length=t.length,e.__iterateUncached=function(e,n){return t.__iterate(e,!n)},e.reverse=function(){return t},e},keys:function(){return this.flip().values()},values:function(){var t=this,e=i(t);return e.length=t.length,e.values=l,e.__iterateUncached=function(e,n,r){if(r&&null==this.length)return this.cacheResult().__iterate(e,n,r);var i,s=0;return r?(s=this.length-1,i=function(t,n,r){return e(t,s--,r)!==!1}):i=function(t,n,r){return e(t,s++,r)!==!1},t.__iterate(i,n),r?this.length:s},e},entries:function(){var t=this;if(t._cache)return X(t._cache);var e=t.map(c).values();return e.fromEntries=function(){return t},e},forEach:function(t,e){return this.__iterate(e?t.bind(e):t)},reduce:function(t,e,n){var r=e;return this.forEach(function(e,i,s){r=t.call(n,r,e,i,s)}),r},reduceRight:function(t,e,n){return this.reverse(!0).reduce(t,e,n)},every:function(t,e){var n=!0; <add>return this.forEach(function(r,i,s){return t.call(e,r,i,s)?void 0:(n=!1,!1)}),n},some:function(t,e){return!this.every(g(t),e)},first:function(){return this.find(f)},last:function(){return this.findLast(f)},rest:function(){return this.slice(1)},butLast:function(){return this.slice(0,-1)},has:function(t){return this.get(t,ae)!==ae},get:function(t,e){return this.find(function(e,n){return w(n,t)},null,e)},getIn:function(t,e){return t&&0!==t.length?s(this,t,e,0):this},contains:function(t){return this.find(function(e){return w(e,t)},null,ae)!==ae},find:function(t,e,n){var r=n;return this.forEach(function(n,i,s){return t.call(e,n,i,s)?(r=n,!1):void 0}),r},findKey:function(t,e){var n;return this.forEach(function(r,i,s){return t.call(e,r,i,s)?(n=i,!1):void 0}),n},findLast:function(t,e,n){return this.reverse(!0).find(t,e,n)},findLastKey:function(t,e){return this.reverse(!0).findKey(t,e)},flip:function(){var t=this,e=r();return e.length=t.length,e.flip=function(){return t},e.__iterateUncached=function(e,n){return t.__iterate(function(t,n,r){return e(n,t,r)!==!1},n)},e},map:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){return n.__iterate(function(n,i,s){return r(t.call(e,n,i,s),i,s)!==!1},i)},r},mapKeys:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){return n.__iterate(function(n,i,s){return r(n,t.call(e,i,n,s),s)!==!1},i)},r},filter:function(t,e){return v(this,t,e,!0,!1)},slice:function(t,e){if(u(t,e,this.length))return this;var n=h(t,this.length),r=a(e,this.length);if(n!==n||r!==r)return this.entries().slice(t,e).fromEntries();var i=0===n?this:this.skip(n);return null==r||r===this.length?i:i.take(r-n)},take:function(t){var e=0,n=this.takeWhile(function(){return e++<t});return n.length=this.length&&Math.min(this.length,t),n},takeLast:function(t,e){return this.reverse(e).take(t).reverse(e)},takeWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,s){if(i)return this.cacheResult().__iterate(r,i,s); <add>var u=0;return n.__iterate(function(n,i,s){return t.call(e,n,i,s)&&r(n,i,s)!==!1?void u++:!1},i,s),u},r},takeUntil:function(t,e,n){return this.takeWhile(g(t),e,n)},skip:function(t,e){if(0===t)return this;var n=0,r=this.skipWhile(function(){return n++<t},null,e);return r.length=this.length&&Math.max(0,this.length-t),r},skipLast:function(t,e){return this.reverse(e).skip(t).reverse(e)},skipWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,s){if(i)return this.cacheResult().__iterate(r,i,s);var u=!0,h=0;return n.__iterate(function(n,i,s){if(!u||!(u=t.call(e,n,i,s))){if(r(n,i,s)===!1)return!1;h++}},i,s),h},r},skipUntil:function(t,e,n){return this.skipWhile(g(t),e,n)},groupBy:function(t){var e=this,n=Le.empty().withMutations(function(n){e.forEach(function(e,r,i){var s=t(e,r,i),u=n.get(s,ae);u===ae&&(u=[],n.set(s,u)),u.push([r,e])})});return n.map(function(t){return X(t).fromEntries()})},sort:function(t,e){return this.sortBy(o,t,e)},sortBy:function(t,e){e=e||d;var n=this;return X(this.entries().entries().toArray().sort(function(r,i){return e(t(r[1][1],r[1][0],n),t(i[1][1],i[1][0],n))||r[0]-i[0]})).fromEntries().values().fromEntries()},cacheResult:function(){return!this._cache&&this.__iterateUncached&&(y(this.length),this._cache=this.entries().toArray(),null==this.length&&(this.length=this._cache.length)),this},__iterate:function(t,e,n){if(!this._cache)return this.__iterateUncached(t,e,n);var r=this.length-1,i=this._cache,s=this;if(e)for(var u=i.length-1;u>=0;u--){var h=i[u];if(t(h[1],n?h[0]:r-h[0],s)===!1)break}else i.every(n?function(e){return t(e[1],r-e[0],s)!==!1}:function(e){return t(e[1],e[0],s)!==!1});return this.length},__makeSequence:function(){return r()}},{from:function(t){if(t instanceof X)return t;if(!Array.isArray(t)){if(t&&t.constructor===Object)return new ee(t);t=[t]}return new ne(t)}});var Y=T.prototype;Y.toJSON=Y.toJS,Y.__toJS=Y.toObject,Y.inspect=Y.toSource=function(){return""+this};var Z=function(){Q.defaultSuperCall(this,$.prototype,arguments)},$=Z;Q.createClass(Z,{toString:function(){return this.__toString("Seq [","]") <add>},toArray:function(){y(this.length);var t=Array(this.length||0);return t.length=this.forEach(function(e,n){t[n]=e}),t},fromEntries:function(){var t=this,e=r();return e.length=t.length,e.entries=function(){return t},e.__iterateUncached=function(e,n,r){return t.__iterate(function(t,n,r){return e(t[1],t[0],r)},n,r)},e},join:function(t){t=t||",";var e="",n=0;return this.forEach(function(r,i){var s=i-n;n=i,e+=(1===s?t:m(t,s))+r}),this.length&&this.length-1>n&&(e+=m(t,this.length-1-n)),e},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];var n=[this].concat(t).map(function(t){return T(t)}),r=this.__makeSequence();return r.length=n.reduce(function(t,e){return null!=t&&null!=e.length?t+e.length:void 0},0),r.__iterateUncached=function(t,e,r){if(r&&!this.length)return this.cacheResult().__iterate(t,e,r);for(var i,s=0,u=r&&this.length-1,h=n.length-1,a=0;h>=a&&!i;a++){var o=n[e?h-a:a];o instanceof $||(o=o.values()),s+=o.__iterate(function(e,n,h){return n+=s,t(e,r?u-n:n,h)===!1?(i=!0,!1):void 0},e)}return s},r},reverse:function(t){var e=this,n=e.__makeSequence();return n.length=e.length,n.__reversedIndices=!!(t^e.__reversedIndices),n.__iterateUncached=function(n,r,i){return e.__iterate(n,!r,i^t)},n.reverse=function(n){return t===n?e:te.reverse.call(this,n)},n},values:function(){var t=Q.superCall(this,$.prototype,"values",[]);return t.length=void 0,t},filter:function(t,e,n){var r=v(this,t,e,n,n);return n&&(r.length=this.length),r},indexOf:function(t){return this.findIndex(function(e){return w(e,t)})},lastIndexOf:function(t){return this.reverse(!0).indexOf(t)},findIndex:function(t,e){var n=this.findKey(t,e);return null==n?-1:n},findLastIndex:function(t,e){return this.reverse(!0).findIndex(t,e)},slice:function(t,e,n){var r=this;if(u(t,e,r.length))return r;var i=r.__makeSequence(),s=h(t,r.length),o=a(e,r.length);return i.length=r.length&&(n?r.length:o-s),i.__reversedIndices=r.__reversedIndices,i.__iterateUncached=function(i,u,c){if(u)return this.cacheResult().__iterate(i,u,c);var f=this.__reversedIndices^c; <add>if(s!==s||o!==o||f&&null==r.length){var l=r.count();s=h(t,l),o=a(e,l)}var _=f?r.length-o:s,v=f?r.length-s:o,g=r.__iterate(function(t,e,r){return f?null!=v&&e>=v||e>=_&&i(t,n?e:e-_,r)!==!1:_>e||(null==v||v>e)&&i(t,n?e:e-_,r)!==!1},u,c);return null!=this.length?this.length:n?g:Math.max(0,g-_)},i},splice:function(t,e){for(var n=[],r=2;arguments.length>r;r++)n[r-2]=arguments[r];return 0===e&&0===n.length?this:this.slice(0,t).concat(n,this.slice(t+e))},takeWhile:function(t,e,n){var r=this,i=r.__makeSequence();return i.__iterateUncached=function(s,u,h){if(u)return this.cacheResult().__iterate(s,u,h);var a=0,o=!0,c=r.__iterate(function(n,r,i){return t.call(e,n,r,i)&&s(n,r,i)!==!1?void(a=r):(o=!1,!1)},u,h);return n?i.length:o?c:a+1},n&&(i.length=this.length),i},skipWhile:function(t,e,n){var r=this,i=r.__makeSequence();return n&&(i.length=this.length),i.__iterateUncached=function(i,s,u){if(s)return this.cacheResult().__iterate(i,s,u);var h=r.__reversedIndices^u,a=!0,o=0,c=r.__iterate(function(r,s,h){return a&&(a=t.call(e,r,s,h),a||(o=s)),a||i(r,u||n?s:s-o,h)!==!1},s,u);return n?c:h?o+1:c-o},i},groupBy:function(t,e,n){var r=this,i=Le.empty().withMutations(function(e){r.forEach(function(i,s,u){var h=t(i,s,u),a=e.get(h,ae);a===ae&&(a=Array(n?r.length:0),e.set(h,a)),n?a[s]=i:a.push(i)})});return i.map(function(t){return T(t)})},sortBy:function(t,e,n){var r=Q.superCall(this,$.prototype,"sortBy",[t,e]);return n||(r=r.values()),r.length=this.length,r},__makeSequence:function(){return i(this)}},{},T);var te=Z.prototype;te.__toJS=te.toArray,te.__toStringMapper=p;var ee=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.length=e.length};Q.createClass(ee,{toObject:function(){return this._object},get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var n=this._object,r=this._keys,i=r.length-1,s=0;i>=s;s++){var u=e?i-s:s;if(t(n[r[u]],r[u],n)===!1)break}return s}},{},T);var ne=function(t){this._array=t,this.length=t.length};Q.createClass(ne,{toArray:function(){return this._array <add>},__iterate:function(t,e,n){var r=this._array,i=r.length-1,s=-1;if(e){for(var u=i;u>=0;u--){if(r.hasOwnProperty(u)&&t(r[u],n?u:i-u,r)===!1)return s+1;s=u}return r.length}var h=r.every(function(e,u){return t(e,n?i-u:u,r)===!1?!1:(s=u,!0)});return h?r.length:s+1}},{},Z),ne.prototype.get=ee.prototype.get,ne.prototype.has=ee.prototype.has;var re=function(t,e,n){this._rootData=t,this._keyPath=e,this._onChange=n},ie=re;Q.createClass(re,{get:function(t,e){var n=this._rootData.getIn(this._keyPath,oe.empty());return t?n.get(t,e):n},set:function(t,e){return O(this,function(n){return n.set(t,e)},t)},"delete":function(t){return O(this,function(e){return e.delete(t)},t)},update:function(t,e){var n;return"function"==typeof t?(n=t,t=void 0):n=function(n){return n.update(t,e)},O(this,n,t)},cursor:function(t){return t&&!Array.isArray(t)&&(t=[t]),t&&0!==t.length?new ie(this._rootData,this._keyPath?this._keyPath.concat(t):t,this._onChange):this}},{});var se=5,ue=1<<se,he=ue-1,ae={},oe=function(t){return t&&t.constructor===ce?t:t&&0!==t.length?ce.empty().merge(t):ce.empty()},ce=oe;Q.createClass(oe,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return null==t||null==this._root?e:this._root.get(0,q(t),t,e)},set:function(t,e){if(null==t)return this;var n,r=this.length;if(this._root){var i=b();n=this._root.update(this.__ownerID,0,q(t),t,e,i),i.value&&r++}else r++,n=new de(this.__ownerID,q(t),[t,e]);return this.__ownerID?(this.length=r,this._root=n,this):n===this._root?this:M(r,n)},"delete":function(t){if(null==t||null==this._root)return this;var e=this.__ownerID&&b(),n=this._root.update(this.__ownerID,0,q(t),t,ae,e);return this.__ownerID?(this._root=n,e.value&&this.length--,this):n?n===this._root?this:M(this.length-1,n):ce.empty()},update:function(t,e){return this.set(t,e(this.get(t)))},clear:function(){return this.__ownerID?(this.length=0,this._root=null,this):ce.empty()},merge:function(){return S(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return S(this,t,e) <add>},mergeDeep:function(){return S(this,x(null),arguments)},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return S(this,x(t),e)},updateIn:function(t,e){return t&&0!==t.length?C(this,t,e,0):e(this)},cursor:function(t,e){return e||"function"!=typeof t||(e=t,t=null),t&&!Array.isArray(t)&&(t=[t]),new re(this,t,e)},withMutations:function(t){var e=this.asMutable();return t(e),e.__ensureOwner(this.__ownerID)},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new D)},asImmutable:function(){return this.__ensureOwner()},__iterate:function(t,e){return this._root?this._root.iterate(this,t,e):0},__deepEqual:function(t){var e=this;return t.every(function(t,n){return w(e.get(n,ae),t)})},__ensureOwner:function(t){return t===this.__ownerID?this:t?M(this.length,this._root,t):(this.__ownerID=t,this)}},{empty:function(){return we||(we=M(0))}},T);var fe=oe.prototype;oe.from=oe;var le=function(t,e,n){this.ownerID=t,this.bitmap=e,this.nodes=n},_e=le;Q.createClass(le,{get:function(t,e,n,r){var i=1<<(e>>>t&he),s=this.bitmap;return 0===(s&i)?r:this.nodes[A(s&i-1)].get(t+se,e,n,r)},update:function(t,e,n,r,i,s){var u=n>>>e&he,h=1<<u,a=this.bitmap,o=0!==(a&h),c=i===ae;if(c&&!o)return this;var f,l,_=A(a&h-1),v=this.nodes;if(!o){if(s&&(s.value=!0),l=new de(t,n,[r,i]),v.length>=Se){for(var g=0,p=[],m=0;0!==a;m++,a>>>=1)1&a&&(p[m]=v[g++]);return p[u]=l,new ve(t,g+1,p)}return f=this.ensureOwner(t),f.nodes.splice(_,0,l),f.bitmap|=h,f}var d=v[_];return l=d.update(t,e+se,n,r,i,s),l===d?this:l||this.bitmap!==h?(f=this.ensureOwner(t),l?f.nodes[_]=l:(f.nodes.splice(_,1),f.bitmap^=h),f):null},ensureOwner:function(t){return t&&t===this.ownerID?this:new _e(t,this.bitmap,this.nodes.slice())},iterate:function(t,e,n){for(var r=this.nodes,i=r.length-1,s=0;i>=s;s++){var u=n?i-s:s,h=r[u];if(!h.iterate(t,e,n))return!1}return!0}},{});var ve=function(t,e,n){this.ownerID=t,this.count=e,this.nodes=n},ge=ve;Q.createClass(ve,{get:function(t,e,n,r){var i=e>>>t&he,s=this.nodes[i];return s?s.get(t+se,e,n,r):r},update:function(t,e,n,r,i,s){var u=n>>>e&he,h=i===ae,a=this.nodes,o=a[u]; <add>if(h&&!o)return this;var c,f=this.count;if(o){if(c=o.update(t,e+se,n,r,i,s),c===o)return this;if(!c&&(f--,s&&(s.value=!0),xe>=f)){for(var l=[],_=0,v=0,g=1,p=a.length;p>v;v++,g<<=1){var m=a[v];v!==u&&m&&(l.push(m),_|=g)}return new le(t,_,l)}}else c=new de(t,n,[r,i]),f++,s&&(s.value=!0);if(t&&t===this.ownerID)return this.count=f,this.nodes[u]=c,this;var d=a.slice();return d[u]=c,new ge(t,f,d)},iterate:function(t,e,n){for(var r=this.nodes,i=0,s=r.length-1;s>=i;i++){var u=r[n?s-i:i];if(u&&!u.iterate(t,e,n))return!1}return!0}},{});var pe=function(t,e,n){this.ownerID=t,this.hash=e,this.entries=n},me=pe;Q.createClass(pe,{get:function(t,e,n,r){for(var i=this.entries,s=0,u=i.length;u>s;s++)if(n===i[s][0])return i[s][1];return r},update:function(t,e,n,r,i,s){var u,h=i===ae;if(n!==this.hash)return h?this:(s&&(s.value=!0),k(t,e,this,n,[r,i]));for(var a=this.entries,o=0,c=a.length;c>o;o++)if(r===a[o][0])return h?(s&&(s.value=!0),2===c?new de(t,this.hash,a[o]):(u=this.ensureOwner(t),o===c-1?u.entries.pop():u.entries[o]=u.entries.pop(),u)):(u=this.ensureOwner(t),u.entries[o]=[r,i],u);return h?this:(s&&(s.value=!0),u=this.ensureOwner(t),u.push([r,i]),u)},ensureOwner:function(t){return t&&t===this.ownerID?this:new me(t,this.hash,this.entries.slice())},iterate:function(t,e,n){for(var r=this.entries,i=r.length-1,s=0;i>=s;s++){var u=n?i-s:s;if(e(r[u][1],r[u][0],t)===!1)return!1}return!0}},{});var de=function(t,e,n){this.ownerID=t,this.hash=e,this.entry=n},ye=de;Q.createClass(de,{get:function(t,e,n,r){return n===this.entry[0]?this.entry[1]:r},update:function(t,e,n,r,i,s){var u=r===this.entry[0];return i===ae?(u&&s&&(s.value=!0),u?null:this):u?i===this.entry[1]?this:t&&t===this.ownerID?(this.entry[1]=i,this):new ye(t,n,[r,i]):(s&&(s.value=!0),k(t,e,this,n,[r,i]))},iterate:function(t,e){return e(this.entry[1],this.entry[0],t)!==!1}},{});var we,Ie={value:!1},Oe=4294967296,De=16,be=255,Me=0,ke={},Se=ue/2,xe=ue/4,Ee=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Ce.from(t)},Ce=Ee;Q.createClass(Ee,{toString:function(){return this.__toString("Vector [","]") <add>},get:function(t,e){if(t=J(t,this._origin),t>=this._size)return e;var n=z(this,t),r=t&he;return n&&(void 0===e||n.array.hasOwnProperty(r))?n.array[r]:e},first:function(){return this.get(0)},last:function(){return this.get(this.length?this.length-1:0)},set:function(t,e){var n=B(this._size);if(t>=this.length)return this.withMutations(function(n){return R(n,0,t+1).set(t,e)});if(this.get(t,ae)===e)return this;if(t=J(t,this._origin),t>=n){var r=this._tail.ensureOwner(this.__ownerID);r.array[t&he]=e;var i=t>=this._size?t+1:this._size;return this.__ownerID?(this.length=i-this._origin,this._size=i,this._tail=r,this):U(this._origin,i,this._level,this._root,r)}for(var s=this._root.ensureOwner(this.__ownerID),u=s,h=this._level;h>0;h-=se){var a=t>>>h&he;u=u.array[a]=u.array[a]?u.array[a].ensureOwner(this.__ownerID):new qe([],this.__ownerID)}return u.array[t&he]=e,this.__ownerID?(this._root=s,this):U(this._origin,this._size,this._level,s,this._tail)},"delete":function(t){if(!this.has(t))return this;var e=B(this._size);if(t=J(t,this._origin),t>=e){var n=this._tail.ensureOwner(this.__ownerID);return delete n.array[t&he],this.__ownerID?(this._tail=n,this):U(this._origin,this._size,this._level,this._root,n)}for(var r=this._root.ensureOwner(this.__ownerID),i=r,s=this._level;s>0;s-=se){var u=t>>>s&he;i=i.array[u]=i.array[u].ensureOwner(this.__ownerID)}return delete i.array[t&he],this.__ownerID?(this._root=r,this):U(this._origin,this._size,this._level,r,this._tail)},clear:function(){return this.__ownerID?(this.length=this._origin=this._size=0,this._level=se,this._root=this._tail=ze,this):Ce.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(n){R(n,0,e+t.length);for(var r=0;t.length>r;r++)n.set(e+r,t[r])})},pop:function(){return R(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){R(e,-t.length);for(var n=0;t.length>n;n++)e.set(n,t[n])})},shift:function(){return R(this,1)},merge:function(){return W(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n]; <add>return W(this,t,e)},mergeDeep:function(){return W(this,x(null),arguments)},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return W(this,x(t),e)},setLength:function(t){return R(this,0,t)},slice:function(t,e,n){var r=Q.superCall(this,Ce.prototype,"slice",[t,e,n]);if(!n&&r!==this){var i=this,s=i.length;r.toVector=function(){return R(i,0>t?Math.max(0,s+t):s?Math.min(s,t):t,null==e?s:0>e?Math.max(0,s+e):s?Math.min(s,e):e)}}return r},iterator:function(){return new Pe(this,this._origin,this._size,this._level,this._root,this._tail)},__iterate:function(t,e,n){var r=this,i=0,s=r.length-1;n^=e;var u,h=function(e,u){return t(e,n?s-u:u,r)===!1?!1:(i=u,!0)},a=B(this._size);return u=e?this._tail.iterate(0,a-this._origin,this._size-this._origin,h,e)&&this._root.iterate(this._level,-this._origin,a-this._origin,h,e):this._root.iterate(this._level,-this._origin,a-this._origin,h,e)&&this._tail.iterate(0,a-this._origin,this._size-this._origin,h,e),(u?s:e?s-i:i)+1},__deepEquals:function(t){var e=this.iterator();return t.every(function(t,n){var r=e.next().value;return r&&n===r[0]&&w(t,r[1])})},__ensureOwner:function(t){return t===this.__ownerID?this:t?U(this._origin,this._size,this._level,this._root,this._tail,t):(this.__ownerID=t,this)}},{empty:function(){return Ue||(Ue=U(0,0,se,ze,ze))},from:function(t){if(t&&t.constructor===Ce)return t;if(!t||0===t.length)return Ce.empty();var e=Array.isArray(t);return t.length>0&&ue>t.length?U(0,t.length,se,ze,new qe(e?t.slice():T(t).toArray())):(e||(t=T(t),t instanceof Z||(t=t.values())),Ce.empty().merge(t))}},Z);var Ae=Ee.prototype;Ae["@@iterator"]=Ae.__iterator__,Ae.update=fe.update,Ae.updateIn=fe.updateIn,Ae.cursor=fe.cursor,Ae.withMutations=fe.withMutations,Ae.asMutable=fe.asMutable,Ae.asImmutable=fe.asImmutable;var qe=function(t,e){this.array=t,this.ownerID=e},je=qe;Q.createClass(qe,{ensureOwner:function(t){return t&&t===this.ownerID?this:new je(this.array.slice(),t)},removeBefore:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this;var r=n>>>e&he; <add>if(r>=this.array.length)return new je([],t);var i,s=0===r;if(e>0){var u=this.array[r];if(i=u&&u.removeBefore(t,e-se,n),i===u&&s)return this}if(s&&!i)return this;var h=this.ensureOwner();if(!s)for(var a=0;r>a;a++)delete h.array[a];return i&&(h.array[r]=i),h},removeAfter:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this;var r=n-1>>>e&he;if(r>=this.array.length)return this;var i,s=r===this.array.length-1;if(e>0){var u=this.array[r];if(i=u&&u.removeAfter(t,e-se,n),i===u&&s)return this}if(s&&!i)return this;var h=this.ensureOwner();return s||(h.array.length=r+1),i&&(h.array[r]=i),h},iterate:function(t,e,n,r,i){if(0===t){if(i){for(var s=this.array.length-1;s>=0;s--)if(this.array.hasOwnProperty(s)){var u=s+e;if(u>=0&&n>u&&r(this.array[s],u)===!1)return!1}return!0}return this.array.every(function(t,i){var s=i+e;return 0>s||s>=n||r(t,s)!==!1})}var h=1<<t,a=t-se;if(i){for(var o=this.array.length-1;o>=0;o--){var c=e+o*h;if(n>c&&c+h>0&&this.array.hasOwnProperty(o)&&!this.array[o].iterate(a,c,n,r,i))return!1}return!0}return this.array.every(function(t,s){var u=e+s*h;return u>=n||0>=u+h||t.iterate(a,u,n,r,i)})}},{});var Pe=function(t,e,n,r,i,s){var u=B(n);this._stack={node:i.array,level:r,offset:-e,max:u-e,__prev:{node:s.array,level:0,offset:u-e,max:n-e}}};Q.createClass(Pe,{next:function(){var t=this._stack;t:for(;t;){if(0===t.level)for(t.rawIndex||(t.rawIndex=0);t.node.length>t.rawIndex;){var e=t.rawIndex+t.offset;if(e>=0&&t.max>e&&t.node.hasOwnProperty(t.rawIndex)){var n=t.node[t.rawIndex];return t.rawIndex++,{value:[e,n],done:!0}}t.rawIndex++}else{var r=1<<t.level;for(t.levelIndex||(t.levelIndex=0);t.node.length>t.levelIndex;){var i=t.offset+t.levelIndex*r;if(i+r>0&&t.max>i&&t.node.hasOwnProperty(t.levelIndex)){var s=t.node[t.levelIndex].array;t.levelIndex++,t=this._stack={node:s,level:t.level-se,offset:i,max:t.max,__prev:t};continue t}t.levelIndex++}}t=this._stack=this._stack.__prev}return{done:!0}}},{});var Ue,ze=new qe([]),Re=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return We.from(t) <add>},We=Re;Q.createClass(Re,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map?this._map.has(t):!1},get:function(t,e){return this.has(t)?t:e},add:function(t){if(null==t)return this;var e=this._map;return e||(e=oe.empty().__ensureOwner(this.__ownerID)),e=e.set(t,null),this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:L(e)},"delete":function(t){if(null==t||null==this._map)return this;var e=this._map.delete(t);return 0===e.length?this.clear():this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:L(e)},clear:function(){return this.__ownerID?(this.length=0,this._map=null,this):We.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var n=0;t.length>n;n++){var r=t[n];r=r.forEach?r:T(r),r.forEach(function(t){return e.add(t)})}})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return T(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.every(function(t){return t.contains(n)})||e.delete(n)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return T(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.some(function(t){return t.contains(n)})&&e.delete(n)})})},isSubset:function(t){return t=T(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=T(t),t.every(function(t){return e.contains(t)})},__iterate:function(t,e){var n=this;return this._map?this._map.__iterate(function(e,r){return t(r,r,n)},e):0},__deepEquals:function(t){return!(this._map||t._map)||this._map.equals(t._map)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?L(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return Be||(Be=L())},from:function(t){return t&&t.constructor===We?t:t&&0!==t.length?We.empty().union(t):We.empty() <add>},fromKeys:function(t){return We.from(T(t).flip())}},T);var Je=Re.prototype;Je.contains=Je.has,Je.withMutations=oe.prototype.withMutations,Je.asMutable=oe.prototype.asMutable,Je.asImmutable=oe.prototype.asImmutable,Je.__toJS=Z.prototype.__toJS,Je.__toStringMapper=Z.prototype.__toStringMapper;var Be,Le=function(t){return t&&t.constructor===Ve?t:t&&0!==t.length?Ve.empty().merge(t):Ve.empty()},Ve=Le;Q.createClass(Le,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){if(null!=t&&this._map){var n=this._map.get(t);if(null!=n)return this._vector.get(n)[1]}return e},clear:function(){return this.__ownerID?(this.length=0,this._map=this._vector=null,this):Ve.empty()},set:function(t,e){if(null==t)return this;var n=this._map,r=this._vector;if(n){var i=n.get(t);null==i?(n=n.set(t,r.length),r=r.push([t,e])):r.get(i)[1]!==e&&(r=r.set(i,[t,e]))}else r=Ee.empty().__ensureOwner(this.__ownerID).set(0,[t,e]),n=oe.empty().__ensureOwner(this.__ownerID).set(t,0);return this.__ownerID?(this.length=n.length,this._map=n,this._vector=r,this):r===this._vector?this:V(n,r)},"delete":function(t){if(null==t||null==this._map)return this;var e=this._map.get(t);if(null==e)return this;var n=this._map.delete(t),r=this._vector.delete(e);return 0===n.length?this.clear():this.__ownerID?(this.length=n.length,this._map=n,this._vector=r,this):n===this._map?this:V(n,r)},__iterate:function(t,e){return this._vector?this._vector.fromEntries().__iterate(t,e):0},__deepEqual:function(t){var e=this._vector.__iterator__();return t.every(function(t,n){var r=e.next();return r&&(r=r[1]),r&&w(n,r[0])&&w(t,r[1])})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t),n=this._vector&&this._vector.__ensureOwner(t);return t?V(e,n,t):(this.__ownerID=t,this._map=e,this._vector=n,this)}},{empty:function(){return Ke||(Ke=V())}},oe),Le.from=Le;var Ke,Ne=function(t,e){var n=function(t){this._map=oe(t)};t=T(t);var r=n.prototype=Object.create(Ge);r.constructor=n,r._name=e,r._defaultValues=t;var i=Object.keys(t); <add>return n.prototype.length=i.length,Object.defineProperty&&t.forEach(function(t,e){Object.defineProperty(n.prototype,e,{get:function(){return this.get(e)},set:function(t){I(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}),n},Fe=Ne;Q.createClass(Ne,{toString:function(){return this.__toString((this._name||"Record")+" {","}")},has:function(t){return this._defaultValues.has(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues.get(t)):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;Object.getPrototypeOf(this).constructor;return Fe._empty||(Fe._empty=K(this,oe.empty()))},set:function(t,e){if(null==t||!this.has(t))return this;var n=this._map.set(t,e);return this.__ownerID||n===this._map?this:K(this,n)},"delete":function(t){if(null==t||!this.has(t))return this;var e=this._map.delete(t);return this.__ownerID||e===this._map?this:K(this,e)},__iterate:function(t,e){var n=this;return this._defaultValues.map(function(t,e){return n.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?K(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},T);var Ge=Ne.prototype;Ge.__deepEqual=fe.__deepEqual,Ge.merge=fe.merge,Ge.mergeWith=fe.mergeWith,Ge.mergeDeep=fe.mergeDeep,Ge.mergeDeepWith=fe.mergeDeepWith,Ge.update=fe.update,Ge.updateIn=fe.updateIn,Ge.cursor=fe.cursor,Ge.withMutations=fe.withMutations,Ge.asMutable=fe.asMutable,Ge.asImmutable=fe.asImmutable;var He=function(t,e,n){return this instanceof Qe?(I(0!==n,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&Xe?Xe:(n=null==n?1:Math.abs(n),t>e&&(n=-n),this._start=t,this._end=e,this._step=n,void(this.length=Math.max(0,Math.ceil((e-t)/n-1)+1)))):new Qe(t,e,n)},Qe=He;Q.createClass(He,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},has:function(t){return I(t>=0,"Index out of bounds"),this.length>t},get:function(t,e){return I(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._start+t*this._step:e <add>},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e,n){return u(t,e,this.length)?this:n?Q.superCall(this,Qe.prototype,"slice",[t,e,n]):(t=h(t,this.length),e=a(e,this.length),t>=e?Xe:new Qe(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var n=e/this._step;if(n>=0&&this.length>n)return n}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,t)},skip:function(t,e){return e?Q.superCall(this,Qe.prototype,"skip",[t]):this.slice(t)},__iterate:function(t,e,n){for(var r=e^n,i=this.length-1,s=this._step,u=e?this._start+i*s:this._start,h=0;i>=h&&t(u,r?i-h:h,this)!==!1;h++)u+=e?-s:s;return r?this.length:h},__deepEquals:function(t){return this._start===t._start&&this._end===t._end&&this._step===t._step}},{},Z);var Te=He.prototype;Te.__toJS=Te.toArray,Te.first=Ae.first,Te.last=Ae.last;var Xe=He(0,0),Ye=function(t,e){return 0===e&&tn?tn:this instanceof Ze?(this._value=t,void(this.length=null==e?1/0:Math.max(0,e))):new Ze(t,e)},Ze=Ye;Q.createClass(Ye,{toString:function(){return 0===this.length?"Repeat []":"Repeat [ "+this._value+" "+this.length+" times ]"},get:function(t,e){return I(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._value:e},first:function(){return this._value},contains:function(t){return w(this._value,t)},slice:function(t,e,n){if(n)return Q.superCall(this,Ze.prototype,"slice",[t,e,n]);var r=this.length;return t=0>t?Math.max(0,r+t):Math.min(r,t),e=null==e?r:e>0?Math.min(r,e):Math.max(0,r+e),e>t?new Ze(this._value,e-t):tn},reverse:function(t){return t?Q.superCall(this,Ze.prototype,"reverse",[t]):this},indexOf:function(t){return w(this._value,t)?0:-1},lastIndexOf:function(t){return w(this._value,t)?this.length:-1},__iterate:function(t,e,n){var r=e^n;I(!r||1/0>this.length,"Cannot access end of infinite range.");for(var i=this.length-1,s=0;i>=s&&t(this._value,r?i-s:s,this)!==!1;s++);return r?this.length:s},__deepEquals:function(t){return w(this._value,t._value) <add>}},{},Z);var $e=Ye.prototype;$e.last=$e.first,$e.has=Te.has,$e.take=Te.take,$e.skip=Te.skip,$e.__toJS=Te.__toJS;var tn=new Ye(void 0,0),en={Sequence:T,Map:oe,Vector:Ee,Set:Re,OrderedMap:Le,Record:Ne,Range:He,Repeat:Ye,is:w,fromJS:N};return en}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t(); <ide>\ No newline at end of file <ide><path>src/Map.js <ide> function hashValue(o) { <ide> if (o === true) { <ide> return 1; <ide> } <del> if (typeof o.hashCode === 'function') { <del> return o.hashCode(); <del> } <ide> var type = typeof o; <ide> if (type === 'number') { <del> return Math.floor(o) % 2147483647; // 2^31-1 <add> if ((o | 0) === o) { <add> return o % HASH_MAX_VAL; <add> } <add> o = '' + o; <add> type = 'string'; <ide> } <ide> if (type === 'string') { <del> return hashString(o); <add> return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o); <add> } <add> if (o.hashCode && typeof o.hashCode === 'function') { <add> return o.hashCode(); <ide> } <ide> throw new Error('Unable to hash: ' + o); <ide> } <ide> <del>// http://jsperf.com/string-hash-to-int <del>function hashString(string) { <add>function cachedHashString(string) { <ide> var hash = STRING_HASH_CACHE[string]; <ide> if (hash == null) { <del> // This is the hash from JVM <del> // The hash code for a string is computed as <del> // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], <del> // where s[i] is the ith character of the string and n is the length of <del> // the string. We mod the result to make it between 0 (inclusive) and 2^32 <del> // (exclusive). <del> hash = 0; <del> for (var ii = 0; ii < string.length; ii++) { <del> hash = (31 * hash + string.charCodeAt(ii)) % STRING_HASH_MAX_VAL; <del> } <add> hash = hashString(string); <ide> if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { <ide> STRING_HASH_CACHE_SIZE = 0; <ide> STRING_HASH_CACHE = {}; <ide> function hashString(string) { <ide> return hash; <ide> } <ide> <add>// http://jsperf.com/hashing-strings <add>function hashString(string) { <add> // This is the hash from JVM <add> // The hash code for a string is computed as <add> // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], <add> // where s[i] is the ith character of the string and n is the length of <add> // the string. We mod the result to make it between 0 (inclusive) and 2^32 <add> // (exclusive). <add> var hash = 0; <add> for (var ii = 0; ii < string.length; ii++) { <add> hash = (31 * hash + string.charCodeAt(ii)); <add> } <add> return hash % HASH_MAX_VAL; <add>} <ide> <del>var STRING_HASH_MAX_VAL = 0x100000000; // 2^32 <add>var HASH_MAX_VAL = 0x100000000; // 2^32 <add>var STRING_HASH_CACHE_MIN_STRLEN = 16; <ide> var STRING_HASH_CACHE_MAX_SIZE = 255; <ide> var STRING_HASH_CACHE_SIZE = 0; <ide> var STRING_HASH_CACHE = {};
3
PHP
PHP
check extension before passing to addtestfile()
a96e4397beb0dd5e28ac463b630ef1da9f0240e0
<ide><path>lib/Cake/Test/Case/Console/AllConsoleLibsTest.php <ide> public static function suite() { <ide> if (!$file->isFile() || strpos($file, 'All') === 0) { <ide> continue; <ide> } <del> $suite->addTestFile($file->getRealPath()); <add> $fileName = $file->getRealPath(); <add> if (substr($fileName, -4) === '.php') { <add> $suite->addTestFile($file->getRealPath()); <add> } <ide> } <ide> return $suite; <ide> }
1
Mixed
Javascript
handle enumerable symbol keys
db2e093e055c9e359745fdf0f2eaf35858455185
<ide><path>doc/api/assert.md <ide> Primitive values are compared with the [Abstract Equality Comparison][] <ide> <ide> Only [enumerable "own" properties][] are considered. The <ide> [`assert.deepEqual()`][] implementation does not test the <del>[`[[Prototype]]`][prototype-spec] of objects, attached symbols, or <del>non-enumerable properties — for such checks, consider using <del>[`assert.deepStrictEqual()`][] instead. This can lead to some <del>potentially surprising results. For example, the following example does not <del>throw an `AssertionError` because the properties on the [`RegExp`][] object are <del>not enumerable: <add>[`[[Prototype]]`][prototype-spec] of objects or enumerable own [`Symbol`][] <add>properties. For such checks, consider using [assert.deepStrictEqual()][] <add>instead. [`assert.deepEqual()`][] can have potentially surprising results. The <add>following example does not throw an `AssertionError` because the properties on <add>the [RegExp][] object are not enumerable: <ide> <ide> ```js <ide> // WARNING: This does not throw an AssertionError! <ide> parameter is an instance of an `Error` then it will be thrown instead of the <ide> <!-- YAML <ide> added: v1.2.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/15169 <add> description: Enumerable symbol properties are now compared. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/15036 <ide> description: NaN is now compared using the [SameValueZero][] comparison. <ide> changes: <ide> * `expected` {any} <ide> * `message` {any} <ide> <del>Generally identical to `assert.deepEqual()` with a few exceptions: <add>Similar to `assert.deepEqual()` with the following exceptions: <ide> <ide> 1. Primitive values besides `NaN` are compared using the [Strict Equality <ide> Comparison][] ( `===` ). Set and Map values, Map keys and `NaN` are compared <ide> Generally identical to `assert.deepEqual()` with a few exceptions: <ide> 3. [Type tags][Object.prototype.toString()] of objects should be the same. <ide> 4. [Object wrappers][] are compared both as objects and unwrapped values. <ide> 5. `0` and `-0` are not considered equal. <add>6. Enumerable own [`Symbol`][] properties are compared as well. <ide> <ide> ```js <ide> const assert = require('assert'); <ide> assert.deepStrictEqual(-0, -0); <ide> // OK <ide> assert.deepStrictEqual(0, -0); <ide> // AssertionError: 0 deepStrictEqual -0 <add> <add>const symbol1 = Symbol(); <add>const symbol2 = Symbol(); <add>assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 }); <add>// OK, because it is the same symbol on both objects. <add>assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 }); <add>// Fails because symbol1 !== symbol2! <ide> ``` <ide> <ide> If the values are not equal, an `AssertionError` is thrown with a `message` <ide> For more information, see <ide> [`Object.is()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is <ide> [`RegExp`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions <ide> [`Set`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set <add>[`Symbol`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol <ide> [`TypeError`]: errors.html#errors_class_typeerror <ide> [`assert.deepEqual()`]: #assert_assert_deepequal_actual_expected_message <ide> [`assert.deepStrictEqual()`]: #assert_assert_deepstrictequal_actual_expected_message <ide><path>lib/assert.js <ide> const { compare } = process.binding('buffer'); <ide> const { isSet, isMap, isDate, isRegExp } = process.binding('util'); <ide> const { objectToString } = require('internal/util'); <ide> const errors = require('internal/errors'); <add>const { propertyIsEnumerable } = Object.prototype; <ide> <ide> // The assert module provides functions that throw <ide> // AssertionError's when particular conditions are not met. The <ide> function isObjectOrArrayTag(tag) { <ide> // For strict comparison, objects should have <ide> // a) The same built-in type tags <ide> // b) The same prototypes. <del>function strictDeepEqual(actual, expected) { <add>function strictDeepEqual(actual, expected, memos) { <ide> if (typeof actual !== 'object') { <ide> return typeof actual === 'number' && Number.isNaN(actual) && <ide> Number.isNaN(expected); <ide> function strictDeepEqual(actual, expected) { <ide> // Check for sparse arrays and general fast path <ide> if (actual.length !== expected.length) <ide> return false; <del> // Skip testing the part below and continue in the callee function. <del> return; <add> // Skip testing the part below and continue with the keyCheck. <add> return keyCheck(actual, expected, true, memos); <ide> } <ide> if (actualTag === '[object Object]') { <del> // Skip testing the part below and continue in the callee function. <del> return; <add> // Skip testing the part below and continue with the keyCheck. <add> return keyCheck(actual, expected, true, memos); <ide> } <ide> if (isDate(actual)) { <ide> if (actual.getTime() !== expected.getTime()) { <ide> function strictDeepEqual(actual, expected) { <ide> } <ide> // Buffer.compare returns true, so actual.length === expected.length <ide> // if they both only contain numeric keys, we don't need to exam further <del> if (Object.keys(actual).length === actual.length && <del> Object.keys(expected).length === expected.length) { <del> return true; <del> } <add> return keyCheck(actual, expected, true, memos, actual.length, <add> expected.length); <ide> } else if (typeof actual.valueOf === 'function') { <ide> const actualValue = actual.valueOf(); <ide> // Note: Boxed string keys are going to be compared again by Object.keys <ide> function strictDeepEqual(actual, expected) { <ide> lengthActual = actual.length; <ide> lengthExpected = expected.length; <ide> } <del> if (Object.keys(actual).length === lengthActual && <del> Object.keys(expected).length === lengthExpected) { <del> return true; <del> } <add> return keyCheck(actual, expected, true, memos, lengthActual, <add> lengthExpected); <ide> } <ide> } <add> return keyCheck(actual, expected, true, memos); <ide> } <ide> <del>function looseDeepEqual(actual, expected) { <add>function looseDeepEqual(actual, expected, memos) { <ide> if (actual === null || typeof actual !== 'object') { <ide> if (expected === null || typeof expected !== 'object') { <ide> // eslint-disable-next-line eqeqeq <ide> function looseDeepEqual(actual, expected) { <ide> } else if (isArguments(actualTag) || isArguments(expectedTag)) { <ide> return false; <ide> } <add> return keyCheck(actual, expected, false, memos); <ide> } <ide> <del>function innerDeepEqual(actual, expected, strict, memos) { <del> // All identical values are equivalent, as determined by ===. <del> if (actual === expected) { <del> if (actual !== 0) <del> return true; <del> return strict ? Object.is(actual, expected) : true; <del> } <del> <del> // Returns a boolean if (not) equal and undefined in case we have to check <del> // further. <del> const partialCheck = strict ? <del> strictDeepEqual(actual, expected) : <del> looseDeepEqual(actual, expected); <del> <del> if (partialCheck !== undefined) { <del> return partialCheck; <del> } <del> <add>function keyCheck(actual, expected, strict, memos, lengthA, lengthB) { <ide> // For all remaining Object pairs, including Array, objects and Maps, <ide> // equivalence is determined by having: <ide> // a) The same number of owned enumerable properties <ide> // b) The same set of keys/indexes (although not necessarily the same order) <ide> // c) Equivalent values for every corresponding key/index <ide> // d) For Sets and Maps, equal contents <ide> // Note: this accounts for both named and indexed properties on Arrays. <add> var aKeys = Object.keys(actual); <add> var bKeys = Object.keys(expected); <add> var i; <add> <add> // The pair must have the same number of owned properties. <add> if (aKeys.length !== bKeys.length) <add> return false; <add> <add> if (strict) { <add> var symbolKeysA = Object.getOwnPropertySymbols(actual); <add> var symbolKeysB = Object.getOwnPropertySymbols(expected); <add> if (symbolKeysA.length !== 0) { <add> symbolKeysA = symbolKeysA.filter((k) => <add> propertyIsEnumerable.call(actual, k)); <add> symbolKeysB = symbolKeysB.filter((k) => <add> propertyIsEnumerable.call(expected, k)); <add> if (symbolKeysA.length !== symbolKeysB.length) <add> return false; <add> } else if (symbolKeysB.length !== 0 && symbolKeysB.filter((k) => <add> propertyIsEnumerable.call(expected, k)).length !== 0) { <add> return false; <add> } <add> if (lengthA !== undefined) { <add> if (aKeys.length !== lengthA || bKeys.length !== lengthB) <add> return false; <add> if (symbolKeysA.length === 0) <add> return true; <add> aKeys = []; <add> bKeys = []; <add> } <add> if (symbolKeysA.length !== 0) { <add> aKeys.push(...symbolKeysA); <add> bKeys.push(...symbolKeysB); <add> } <add> } <add> <add> // Cheap key test: <add> const keys = {}; <add> for (i = 0; i < aKeys.length; i++) { <add> keys[aKeys[i]] = true; <add> } <add> for (i = 0; i < aKeys.length; i++) { <add> if (keys[bKeys[i]] === undefined) <add> return false; <add> } <ide> <ide> // Use memos to handle cycles. <ide> if (memos === undefined) { <ide> function innerDeepEqual(actual, expected, strict, memos) { <ide> memos.position++; <ide> } <ide> <del> const aKeys = Object.keys(actual); <del> const bKeys = Object.keys(expected); <del> var i; <del> <del> // The pair must have the same number of owned properties <del> // (keys incorporates hasOwnProperty). <del> if (aKeys.length !== bKeys.length) <del> return false; <del> <del> // Cheap key test: <del> const keys = {}; <del> for (i = 0; i < aKeys.length; i++) { <del> keys[aKeys[i]] = true; <del> } <del> for (i = 0; i < aKeys.length; i++) { <del> if (keys[bKeys[i]] === undefined) <del> return false; <del> } <del> <ide> memos.actual.set(actual, memos.position); <ide> memos.expected.set(expected, memos.position); <ide> <ide> function innerDeepEqual(actual, expected, strict, memos) { <ide> return areEq; <ide> } <ide> <add>function innerDeepEqual(actual, expected, strict, memos) { <add> // All identical values are equivalent, as determined by ===. <add> if (actual === expected) { <add> if (actual !== 0) <add> return true; <add> return strict ? Object.is(actual, expected) : true; <add> } <add> <add> // Check more closely if actual and expected are equal. <add> if (strict === true) <add> return strictDeepEqual(actual, expected, memos); <add> <add> return looseDeepEqual(actual, expected, memos); <add>} <add> <ide> function setHasEqualElement(set, val1, strict, memo) { <ide> // Go looking. <ide> for (const val2 of set) { <ide><path>test/parallel/test-assert-deep.js <ide> assert.doesNotThrow( <ide> boxedSymbol.slow = true; <ide> assertNotDeepOrStrict(boxedSymbol, {}); <ide> } <add> <ide> // Minus zero <ide> assertOnlyDeepEqual(0, -0); <ide> assertDeepAndStrictEqual(-0, -0); <ide> <add>// Handle symbols (enumerable only) <add>{ <add> const symbol1 = Symbol(); <add> const obj1 = { [symbol1]: 1 }; <add> const obj2 = { [symbol1]: 1 }; <add> const obj3 = { [Symbol()]: 1 }; <add> // Add a non enumerable symbol as well. It is going to be ignored! <add> Object.defineProperty(obj2, Symbol(), { value: 1 }); <add> assertOnlyDeepEqual(obj1, obj3); <add> assertDeepAndStrictEqual(obj1, obj2); <add> // TypedArrays have a fast path. Test for this as well. <add> const a = new Uint8Array(4); <add> const b = new Uint8Array(4); <add> a[symbol1] = true; <add> b[symbol1] = false; <add> assertOnlyDeepEqual(a, b); <add> b[symbol1] = true; <add> assertDeepAndStrictEqual(a, b); <add> // The same as TypedArrays is valid for boxed primitives <add> const boxedStringA = new String('test'); <add> const boxedStringB = new String('test'); <add> boxedStringA[symbol1] = true; <add> assertOnlyDeepEqual(boxedStringA, boxedStringB); <add> boxedStringA[symbol1] = true; <add> assertDeepAndStrictEqual(a, b); <add>} <add> <ide> /* eslint-enable */ <ide><path>test/parallel/test-net-normalize-args.js <ide> function validateNormalizedArgs(input, output) { <ide> } <ide> <ide> // Test creation of normalized arguments. <del>validateNormalizedArgs([], [{}, null]); <del>validateNormalizedArgs([{ port: 1234 }], [{ port: 1234 }, null]); <del>validateNormalizedArgs([{ port: 1234 }, assert.fail], <del> [{ port: 1234 }, assert.fail]); <add>const res = [{}, null]; <add>res[normalizedArgsSymbol] = true; <add>validateNormalizedArgs([], res); <add>res[0].port = 1234; <add>validateNormalizedArgs([{ port: 1234 }], res); <add>res[1] = assert.fail; <add>validateNormalizedArgs([{ port: 1234 }, assert.fail], res); <ide> <ide> // Connecting to the server should fail with a standard array. <ide> {
4
Ruby
Ruby
comment the recorder methods
5d8df14d6dd3f657af28e72e30f9a97ca9607f82
<ide><path>activerecord/lib/active_record/migration/command_recorder.rb <ide> def respond_to?(*args) # :nodoc: <ide> <ide> [:create_table, :rename_table, :add_column, :remove_column, :rename_index, :rename_column, :add_index, :remove_index, :add_timestamps, :remove_timestamps, :change_column, :change_column_default].each do |method| <ide> class_eval <<-EOV, __FILE__, __LINE__ + 1 <del> def #{method}(*args) <del> record(:"#{method}", args) <del> end <add> def #{method}(*args) # def create_table(*args) <add> record(:"#{method}", args) # record(:create_table, args) <add> end # end <ide> EOV <ide> end <ide>
1
Text
Text
fix typo in autoload documentation [ci skip]
fab42177c1e8b6ea265a30ea7566547523422676
<ide><path>guides/source/autoloading_and_reloading_constants.md <ide> INFO. Autoload paths are called _root directories_ in Zeitwerk documentation, bu <ide> <ide> Within an autoload path, file names must match the constants they define as documented [here](https://github.com/fxn/zeitwerk#file-structure). <ide> <del>By default, the autoload paths of an application consist of all the subdirectories of `app` that exist when the application boots ---except for `aasets`, `javascripts`, `views`,--- plus the autoload paths of engines it might depend on. <add>By default, the autoload paths of an application consist of all the subdirectories of `app` that exist when the application boots ---except for `assets`, `javascripts`, `views`,--- plus the autoload paths of engines it might depend on. <ide> <ide> For example, if `UsersHelper` is implemented in `app/helpers/users_helper.rb`, the module is autoloadable, you do not need (and should not write) a `require` call for it: <ide>
1
Python
Python
add regression test for changeset
1e3d6e6af36dad10ff4e59d425babc8f6568c9d7
<ide><path>numpy/core/tests/test_regression.py <ide> def check_nonnative_endian_fill(self, level=rlevel): <ide> x.fill(1) <ide> assert_equal(x, np.array([1], dtype=dtype)) <ide> <add> def check_asfarray_none(self, level=rlevel): <add> """Test for changeset r5065""" <add> assert_array_equal(np.array([np.nan]), np.asfarray([None])) <ide> <ide> <ide> if __name__ == "__main__":
1
Javascript
Javascript
create glimmercomponent subclass
a6856fdaf25afa4fbdf971a54084874eeece896b
<ide><path>packages/ember-htmlbars/lib/glimmer-component.js <del>import EmberObject from "ember-runtime/system/object"; <add>import CoreView from 'ember-views/views/core_view'; <add>import ViewChildViewsSupport from 'ember-views/mixins/view_child_views_support'; <add>import ViewStateSupport from 'ember-views/mixins/view_state_support'; <add>import TemplateRenderingSupport from 'ember-views/mixins/template_rendering_support'; <add>import ClassNamesSupport from 'ember-views/mixins/class_names_support'; <add>import InstrumentationSupport from 'ember-views/mixins/instrumentation_support'; <add>import AriaRoleSupport from 'ember-views/mixins/aria_role_support'; <add>import ViewMixin from 'ember-views/mixins/view_support'; <add>import EmberView from 'ember-views/views/view'; <ide> <del>export default EmberObject.extend({ <add>export default CoreView.extend( <add> ViewChildViewsSupport, <add> ViewStateSupport, <add> TemplateRenderingSupport, <add> ClassNamesSupport, <add> InstrumentationSupport, <add> AriaRoleSupport, <add> ViewMixin, { <add> isGlimmerComponent: true, <ide> <del>}); <add> init() { <add> this._super(...arguments); <add> this._viewRegistry = this._viewRegistry || EmberView.views; <add> } <add> }); <ide><path>packages/ember-htmlbars/lib/hooks/bind-self.js <ide> export default function bindSelf(env, scope, _self) { <ide> if (self && self.isView) { <ide> newStream(scope.locals, 'view', self, null); <ide> newStream(scope.locals, 'controller', scope.locals.view.getKey('controller')); <del> newStream(scope, 'self', scope.locals.view.getKey('context'), null, true); <add> <add> if (self.isGlimmerComponent) { <add> newStream(scope, 'self', self, null, true); <add> } else { <add> newStream(scope, 'self', scope.locals.view.getKey('context'), null, true); <add> } <add> <ide> return; <ide> } <ide> <ide><path>packages/ember-htmlbars/lib/main.js <ide> import legacyEachWithKeywordHelper from 'ember-htmlbars/helpers/-legacy-each-wit <ide> import htmlSafeHelper from 'ember-htmlbars/helpers/-html-safe'; <ide> import DOMHelper from 'ember-htmlbars/system/dom-helper'; <ide> import Helper, { helper as makeHelper } from 'ember-htmlbars/helper'; <add>import GlimmerComponent from 'ember-htmlbars/glimmer-component'; <ide> <ide> // importing adds template bootstrapping <ide> // initializer to enable embedded templates <ide> Ember.HTMLBars = { <ide> DOMHelper <ide> }; <ide> <add>Ember.GlimmerComponent = GlimmerComponent; <add> <ide> if (isEnabled('ember-htmlbars-helper')) { <ide> Helper.helper = makeHelper; <ide> Ember.Helper = Helper; <ide><path>packages/ember-htmlbars/tests/glimmer-component/render-test.js <del>import Registry from "container/registry"; <del>import View from "ember-views/views/view"; <del>import GlimmerComponent from "ember-htmlbars/glimmer-component"; <add>import Registry from 'container/registry'; <add>import View from 'ember-views/views/view'; <add>import GlimmerComponent from 'ember-htmlbars/glimmer-component'; <ide> import compile from 'ember-template-compiler/system/compile'; <ide> import { runAppend, runDestroy } from 'ember-runtime/tests/utils'; <add>import ComponentLookup from 'ember-views/component_lookup'; <ide> <ide> let view; <ide> <del>QUnit.module("A basic glimmer component", { <add>QUnit.module('A basic glimmer component', { <ide> teardown() { <ide> runDestroy(view); <ide> } <ide> }); <ide> <ide> function renderComponent(tag, component) { <del> let { params, hash, implementation } = component; <add> let { params, hash, yielded, implementation } = component; <ide> params = params || []; <ide> hash = hash || {}; <del> let stringParams = params.join(" "); <add> let stringParams = params.join(' '); <ide> let stringHash = Object.keys(hash) <ide> .map(key => `${key}=${hash[key]}`) <ide> .join(' '); <ide> <ide> let registry = new Registry(); <add> registry.register('component-lookup:main', ComponentLookup); <ide> registry.register(`component:${tag}`, implementation); <ide> <ide> view = View.extend({ <ide> container: registry.container(), <del> template: compile(`{{debugger}}<${tag} ${stringParams} ${stringHash}></${tag}>`) <add> template: compile(`<${tag} ${stringParams} ${stringHash}>${yielded}</${tag}>`) <ide> }).create(); <ide> <ide> runAppend(view); <ide> function hasSelector(assert, selector) { <ide> assert.ok(document.querySelector(`#qunit-fixture ${selector}`), `${selector} exists`); <ide> } <ide> <del>QUnit.test("it renders", function(assert) { <add>QUnit.test('it renders', function(assert) { <ide> let component; <ide> <ide> let MyComponent = GlimmerComponent.extend({ <ide> init() { <ide> component = this; <ide> this._super(...arguments); <del> } <add> }, <add> layout: compile(`<my-component>{{yield}}</my-component>`) <ide> }); <ide> <ide> renderComponent('my-component', { <del> implementation: MyComponent <add> implementation: MyComponent, <add> yielded: 'Hello world' <ide> }); <ide> <ide> ok(component instanceof GlimmerComponent, 'the component was instantiated correctly'); <ide> equal(view.childViews[0], component, 'the component was rendered and inserted into child views'); <del> hasSelector(assert, 'my-component'); <add> hasSelector(assert, `my-component.ember-view[id=${component.elementId}]`); <ide> }); <ide> <ide> <ide> //testForComponent({ <del> //name: "my-component", <add> //name: 'my-component', <ide> //params: [], <ide> //hash: {}, <ide> //template: ` <ide><path>packages/ember-htmlbars/tests/glimmer-component/test-helpers.js <ide> export function moduleForGlimmerComponent(name, options) { <del> let beforeEach = () => { <del> <del> }; <add> function beforeEach() { <add> } <ide> <del> let afterEach = () => { <del> <del> }; <add> function afterEach() { <add> } <ide> <ide> QUnit.module(`Glimmer Component - ${name}`, { beforeEach, afterEach }); <ide> } <ide><path>packages/ember-htmlbars/tests/integration/component_invocation_test.js <ide> import jQuery from 'ember-views/system/jquery'; <ide> import compile from 'ember-template-compiler/system/compile'; <ide> import ComponentLookup from 'ember-views/component_lookup'; <ide> import Component from 'ember-views/components/component'; <add>import GlimmerComponent from 'ember-htmlbars/glimmer-component'; <ide> import { runAppend, runDestroy } from 'ember-runtime/tests/utils'; <ide> import { get } from 'ember-metal/property_get'; <ide> import { set } from 'ember-metal/property_set'; <ide> if (isEnabled('ember-htmlbars-component-generation')) { <ide> //equal(jQuery('#qunit-fixture').text(), 'In layout - someProp: something here'); <ide> }); <ide> <del> QUnit.skip('attributes are not installed on the top level', function() { <add> QUnit.test('attributes are not installed on the top level', function() { <ide> let component; <ide> <del> registry.register('template:components/non-block', compile('<non-block>In layout - {{attrs.text}} -- {{text}}</non-block>')); <del> registry.register('component:non-block', Component.extend({ <add> registry.register('template:components/non-block', compile('<non-block>In layout - {{attrs.text}}</non-block>')); <add> registry.register('component:non-block', GlimmerComponent.extend({ <ide> text: null, <ide> dynamic: null, <ide> <ide> if (isEnabled('ember-htmlbars-component-generation')) { <ide> strictEqual(get(component, 'dynamic'), null); <ide> }); <ide> <del> QUnit.test('non-block with properties on attrs and component class', function() { <del> registry.register('component:non-block', Component.extend()); <add> QUnit.test('non-block with properties on attrs and component class', function() { <add> registry.register('component:non-block', GlimmerComponent.extend()); <ide> registry.register('template:components/non-block', compile('<non-block>In layout - someProp: {{attrs.someProp}}</non-block>')); <ide> <ide> view = appendViewFor('<non-block someProp="something here" />'); <ide> if (isEnabled('ember-htmlbars-component-generation')) { <ide> var willUpdate = 0; <ide> var didReceiveAttrs = 0; <ide> <del> registry.register('component:non-block', Component.extend({ <add> registry.register('component:non-block', GlimmerComponent.extend({ <ide> didReceiveAttrs() { <ide> didReceiveAttrs++; <ide> }, <ide><path>packages/ember-htmlbars/tests/integration/component_lifecycle_test.js <ide> import jQuery from 'ember-views/system/jquery'; <ide> import compile from 'ember-template-compiler/system/compile'; <ide> import ComponentLookup from 'ember-views/component_lookup'; <ide> import Component from 'ember-views/components/component'; <add>import GlimmerComponent from 'ember-htmlbars/glimmer-component'; <ide> import { runAppend, runDestroy } from 'ember-runtime/tests/utils'; <ide> import run from 'ember-metal/run_loop'; <ide> import EmberView from 'ember-views/views/view'; <ide> <ide> var registry, container, view; <ide> var hooks; <ide> <del>QUnit.module('component - lifecycle hooks', { <del> setup() { <del> registry = new Registry(); <del> container = registry.container(); <del> registry.optionsForType('component', { singleton: false }); <del> registry.optionsForType('view', { singleton: false }); <del> registry.optionsForType('template', { instantiate: false }); <del> registry.register('component-lookup:main', ComponentLookup); <del> <del> hooks = []; <del> }, <del> <del> teardown() { <del> runDestroy(container); <del> runDestroy(view); <del> registry = container = view = null; <add>let styles = [{ <add> name: 'curly', <add> class: Component <add>}, { <add> name: 'angle', <add> class: GlimmerComponent <add>}]; <add> <add>styles.forEach(style => { <add> function invoke(name, hash) { <add> if (style.name === 'curly') { <add> let attrs = Object.keys(hash).map(k => `${k}=${val(hash[k])}`).join(' '); <add> return `{{${name} ${attrs}}}`; <add> } else if (style.name === 'angle') { <add> let attrs = Object.keys(hash).map(k => `${k}=${val(hash[k])}`).join(' '); <add> return `<${name} ${attrs} />`; <add> } <ide> } <del>}); <del> <del>function pushHook(view, type, arg) { <del> hooks.push(hook(view, type, arg)); <del>} <del> <del>function hook(view, type, arg) { <del> return { type: type, view: view, arg: arg }; <del>} <del> <del>QUnit.test('lifecycle hooks are invoked in a predictable order', function() { <del> var components = {}; <ide> <del> function component(label) { <del> return Component.extend({ <del> init() { <del> this.label = label; <del> components[label] = this; <del> this._super.apply(this, arguments); <del> }, <del> <del> didInitAttrs(options) { <del> pushHook(label, 'didInitAttrs', options); <del> }, <add> function val(value) { <add> if (value.isString) { <add> return JSON.stringify(value.value); <add> } <ide> <del> didUpdateAttrs(options) { <del> pushHook(label, 'didUpdateAttrs', options); <del> }, <add> if (style.name === 'curly') { <add> return `(readonly ${value})`; <add> } else { <add> return `{{${value}}}`; <add> } <add> } <ide> <del> willUpdate(options) { <del> pushHook(label, 'willUpdate', options); <del> }, <add> function string(val) { <add> return { isString: true, value: val }; <add> } <ide> <del> didReceiveAttrs(options) { <del> pushHook(label, 'didReceiveAttrs', options); <del> }, <add> QUnit.module(`component - lifecycle hooks (${style.name})`, { <add> setup() { <add> registry = new Registry(); <add> container = registry.container(); <add> registry.optionsForType('component', { singleton: false }); <add> registry.optionsForType('view', { singleton: false }); <add> registry.optionsForType('template', { instantiate: false }); <add> registry.register('component-lookup:main', ComponentLookup); <add> <add> hooks = []; <add> }, <add> <add> teardown() { <add> runDestroy(container); <add> runDestroy(view); <add> registry = container = view = null; <add> } <add> }); <ide> <del> willRender() { <del> pushHook(label, 'willRender'); <del> }, <add> function pushHook(view, type, arg) { <add> hooks.push(hook(view, type, arg)); <add> } <ide> <del> didRender() { <del> pushHook(label, 'didRender'); <del> }, <add> function hook(view, type, arg) { <add> return { type: type, view: view, arg: arg }; <add> } <ide> <del> didInsertElement() { <del> pushHook(label, 'didInsertElement'); <del> }, <add> QUnit.test('lifecycle hooks are invoked in a predictable order', function() { <add> var components = {}; <add> <add> function component(label) { <add> return style.class.extend({ <add> init() { <add> this.label = label; <add> components[label] = this; <add> this._super.apply(this, arguments); <add> }, <add> <add> didInitAttrs(options) { <add> pushHook(label, 'didInitAttrs', options); <add> }, <add> <add> didUpdateAttrs(options) { <add> pushHook(label, 'didUpdateAttrs', options); <add> }, <add> <add> willUpdate(options) { <add> pushHook(label, 'willUpdate', options); <add> }, <add> <add> didReceiveAttrs(options) { <add> pushHook(label, 'didReceiveAttrs', options); <add> }, <add> <add> willRender() { <add> pushHook(label, 'willRender'); <add> }, <add> <add> didRender() { <add> pushHook(label, 'didRender'); <add> }, <add> <add> didInsertElement() { <add> pushHook(label, 'didInsertElement'); <add> }, <add> <add> didUpdate(options) { <add> pushHook(label, 'didUpdate', options); <add> } <add> }); <add> } <ide> <del> didUpdate(options) { <del> pushHook(label, 'didUpdate', options); <del> } <del> }); <del> } <add> registry.register('component:the-top', component('top')); <add> registry.register('component:the-middle', component('middle')); <add> registry.register('component:the-bottom', component('bottom')); <ide> <del> registry.register('component:the-top', component('top')); <del> registry.register('component:the-middle', component('middle')); <del> registry.register('component:the-bottom', component('bottom')); <add> registry.register('template:components/the-top', compile(`Twitter: {{attrs.twitter}} ${invoke('the-middle', { name: string('Tom Dale') })}`)); <add> registry.register('template:components/the-middle', compile(`Name: {{attrs.name}} ${invoke('the-bottom', { website: string('tomdale.net') })}`)); <add> registry.register('template:components/the-bottom', compile('Website: {{attrs.website}}')); <ide> <del> registry.register('template:components/the-top', compile('Twitter: {{attrs.twitter}} {{the-middle name="Tom Dale"}}')); <del> registry.register('template:components/the-middle', compile('Name: {{attrs.name}} {{the-bottom website="tomdale.net"}}')); <del> registry.register('template:components/the-bottom', compile('Website: {{attrs.website}}')); <add> view = EmberView.extend({ <add> template: compile(invoke('the-top', { twitter: 'view.twitter' })), <add> twitter: '@tomdale', <add> container: container <add> }).create(); <ide> <del> view = EmberView.extend({ <del> template: compile('{{the-top twitter=(readonly view.twitter)}}'), <del> twitter: '@tomdale', <del> container: container <del> }).create(); <add> runAppend(view); <ide> <del> runAppend(view); <add> ok(component, 'The component was inserted'); <add> equal(jQuery('#qunit-fixture').text(), 'Twitter: @tomdale Name: Tom Dale Website: tomdale.net'); <ide> <del> ok(component, 'The component was inserted'); <del> equal(jQuery('#qunit-fixture').text(), 'Twitter: @tomdale Name: Tom Dale Website: tomdale.net'); <add> let topAttrs = { twitter: '@tomdale' }; <add> let middleAttrs = { name: 'Tom Dale' }; <add> let bottomAttrs = { website: 'tomdale.net' }; <ide> <del> let topAttrs = { twitter: '@tomdale' }; <del> let middleAttrs = { name: 'Tom Dale' }; <del> let bottomAttrs = { website: 'tomdale.net' }; <add> deepEqual(hooks, [ <add> hook('top', 'didInitAttrs', { attrs: topAttrs }), hook('top', 'didReceiveAttrs', { newAttrs: topAttrs }), hook('top', 'willRender'), <add> hook('middle', 'didInitAttrs', { attrs: middleAttrs }), hook('middle', 'didReceiveAttrs', { newAttrs: middleAttrs }), hook('middle', 'willRender'), <add> hook('bottom', 'didInitAttrs', { attrs: bottomAttrs }), hook('bottom', 'didReceiveAttrs', { newAttrs: bottomAttrs }), hook('bottom', 'willRender'), <add> hook('bottom', 'didInsertElement'), hook('bottom', 'didRender'), <add> hook('middle', 'didInsertElement'), hook('middle', 'didRender'), <add> hook('top', 'didInsertElement'), hook('top', 'didRender') <add> ]); <ide> <del> deepEqual(hooks, [ <del> hook('top', 'didInitAttrs', { attrs: topAttrs }), hook('top', 'didReceiveAttrs', { newAttrs: topAttrs }), hook('top', 'willRender'), <del> hook('middle', 'didInitAttrs', { attrs: middleAttrs }), hook('middle', 'didReceiveAttrs', { newAttrs: middleAttrs }), hook('middle', 'willRender'), <del> hook('bottom', 'didInitAttrs', { attrs: bottomAttrs }), hook('bottom', 'didReceiveAttrs', { newAttrs: bottomAttrs }), hook('bottom', 'willRender'), <del> hook('bottom', 'didInsertElement'), hook('bottom', 'didRender'), <del> hook('middle', 'didInsertElement'), hook('middle', 'didRender'), <del> hook('top', 'didInsertElement'), hook('top', 'didRender') <del> ]); <add> hooks = []; <ide> <del> hooks = []; <add> run(function() { <add> components.bottom.rerender(); <add> }); <ide> <del> run(function() { <del> components.bottom.rerender(); <del> }); <add> deepEqual(hooks, [ <add> hook('bottom', 'willUpdate'), hook('bottom', 'willRender'), <add> hook('bottom', 'didUpdate'), hook('bottom', 'didRender') <add> ]); <ide> <del> deepEqual(hooks, [ <del> hook('bottom', 'willUpdate'), hook('bottom', 'willRender'), <del> hook('bottom', 'didUpdate'), hook('bottom', 'didRender') <del> ]); <add> hooks = []; <ide> <del> hooks = []; <add> run(function() { <add> components.middle.rerender(); <add> }); <ide> <del> run(function() { <del> components.middle.rerender(); <del> }); <add> bottomAttrs = { oldAttrs: { website: 'tomdale.net' }, newAttrs: { website: 'tomdale.net' } }; <ide> <del> bottomAttrs = { oldAttrs: { website: 'tomdale.net' }, newAttrs: { website: 'tomdale.net' } }; <add> deepEqual(hooks, [ <add> hook('middle', 'willUpdate'), hook('middle', 'willRender'), <ide> <del> deepEqual(hooks, [ <del> hook('middle', 'willUpdate'), hook('middle', 'willRender'), <add> hook('bottom', 'didUpdateAttrs', bottomAttrs), <add> hook('bottom', 'didReceiveAttrs', bottomAttrs), <ide> <del> hook('bottom', 'didUpdateAttrs', bottomAttrs), <del> hook('bottom', 'didReceiveAttrs', bottomAttrs), <add> hook('bottom', 'willUpdate'), hook('bottom', 'willRender'), <ide> <del> hook('bottom', 'willUpdate'), hook('bottom', 'willRender'), <add> hook('bottom', 'didUpdate'), hook('bottom', 'didRender'), <add> hook('middle', 'didUpdate'), hook('middle', 'didRender') <add> ]); <ide> <del> hook('bottom', 'didUpdate'), hook('bottom', 'didRender'), <del> hook('middle', 'didUpdate'), hook('middle', 'didRender') <del> ]); <add> hooks = []; <ide> <del> hooks = []; <add> run(function() { <add> components.top.rerender(); <add> }); <ide> <del> run(function() { <del> components.top.rerender(); <del> }); <add> middleAttrs = { oldAttrs: { name: 'Tom Dale' }, newAttrs: { name: 'Tom Dale' } }; <ide> <del> middleAttrs = { oldAttrs: { name: 'Tom Dale' }, newAttrs: { name: 'Tom Dale' } }; <add> deepEqual(hooks, [ <add> hook('top', 'willUpdate'), hook('top', 'willRender'), <ide> <del> deepEqual(hooks, [ <del> hook('top', 'willUpdate'), hook('top', 'willRender'), <add> hook('middle', 'didUpdateAttrs', middleAttrs), hook('middle', 'didReceiveAttrs', middleAttrs), <add> hook('middle', 'willUpdate'), hook('middle', 'willRender'), <ide> <del> hook('middle', 'didUpdateAttrs', middleAttrs), hook('middle', 'didReceiveAttrs', middleAttrs), <del> hook('middle', 'willUpdate'), hook('middle', 'willRender'), <add> hook('bottom', 'didUpdateAttrs', bottomAttrs), hook('bottom', 'didReceiveAttrs', bottomAttrs), <add> hook('bottom', 'willUpdate'), hook('bottom', 'willRender'), <add> hook('bottom', 'didUpdate'), hook('bottom', 'didRender'), <ide> <del> hook('bottom', 'didUpdateAttrs', bottomAttrs), hook('bottom', 'didReceiveAttrs', bottomAttrs), <del> hook('bottom', 'willUpdate'), hook('bottom', 'willRender'), <del> hook('bottom', 'didUpdate'), hook('bottom', 'didRender'), <add> hook('middle', 'didUpdate'), hook('middle', 'didRender'), <add> hook('top', 'didUpdate'), hook('top', 'didRender') <add> ]); <ide> <del> hook('middle', 'didUpdate'), hook('middle', 'didRender'), <del> hook('top', 'didUpdate'), hook('top', 'didRender') <del> ]); <add> hooks = []; <ide> <del> hooks = []; <add> run(function() { <add> view.set('twitter', '@hipstertomdale'); <add> }); <ide> <del> run(function() { <del> view.set('twitter', '@hipstertomdale'); <add> // Because the `twitter` attr is only used by the topmost component, <add> // and not passed down, we do not expect to see lifecycle hooks <add> // called for child components. If the `didReceiveAttrs` hook used <add> // the new attribute to rerender itself imperatively, that would result <add> // in lifecycle hooks being invoked for the child. <add> <add> deepEqual(hooks, [ <add> hook('top', 'didUpdateAttrs', { oldAttrs: { twitter: '@tomdale' }, newAttrs: { twitter: '@hipstertomdale' } }), <add> hook('top', 'didReceiveAttrs', { oldAttrs: { twitter: '@tomdale' }, newAttrs: { twitter: '@hipstertomdale' } }), <add> hook('top', 'willUpdate'), <add> hook('top', 'willRender'), <add> hook('top', 'didUpdate'), hook('top', 'didRender') <add> ]); <ide> }); <ide> <del> // Because the `twitter` attr is only used by the topmost component, <del> // and not passed down, we do not expect to see lifecycle hooks <del> // called for child components. If the `didReceiveAttrs` hook used <del> // the new attribute to rerender itself imperatively, that would result <del> // in lifecycle hooks being invoked for the child. <del> <del> deepEqual(hooks, [ <del> hook('top', 'didUpdateAttrs', { oldAttrs: { twitter: '@tomdale' }, newAttrs: { twitter: '@hipstertomdale' } }), <del> hook('top', 'didReceiveAttrs', { oldAttrs: { twitter: '@tomdale' }, newAttrs: { twitter: '@hipstertomdale' } }), <del> hook('top', 'willUpdate'), <del> hook('top', 'willRender'), <del> hook('top', 'didUpdate'), hook('top', 'didRender') <del> ]); <del>}); <del> <del>QUnit.test('passing values through attrs causes lifecycle hooks to fire if the attribute values have changed', function() { <del> var components = {}; <add> QUnit.test('passing values through attrs causes lifecycle hooks to fire if the attribute values have changed', function() { <add> var components = {}; <add> <add> function component(label) { <add> return style.class.extend({ <add> init() { <add> this.label = label; <add> components[label] = this; <add> this._super.apply(this, arguments); <add> }, <add> <add> didInitAttrs(options) { <add> pushHook(label, 'didInitAttrs', options); <add> }, <add> <add> didUpdateAttrs(options) { <add> pushHook(label, 'didUpdateAttrs', options); <add> }, <add> <add> willUpdate(options) { <add> pushHook(label, 'willUpdate', options); <add> }, <add> <add> didReceiveAttrs(options) { <add> pushHook(label, 'didReceiveAttrs', options); <add> }, <add> <add> willRender() { <add> pushHook(label, 'willRender'); <add> }, <add> <add> didRender() { <add> pushHook(label, 'didRender'); <add> }, <add> <add> didInsertElement() { <add> pushHook(label, 'didInsertElement'); <add> }, <add> <add> didUpdate(options) { <add> pushHook(label, 'didUpdate', options); <add> } <add> }); <add> } <ide> <del> function component(label) { <del> return Component.extend({ <del> init() { <del> this.label = label; <del> components[label] = this; <del> this._super.apply(this, arguments); <del> }, <add> registry.register('component:the-top', component('top')); <add> registry.register('component:the-middle', component('middle')); <add> registry.register('component:the-bottom', component('bottom')); <ide> <del> didInitAttrs(options) { <del> pushHook(label, 'didInitAttrs', options); <del> }, <add> registry.register('template:components/the-top', compile(`Top: ${invoke('the-middle', { twitterTop: 'attrs.twitter' })}`)); <add> registry.register('template:components/the-middle', compile(`Middle: ${invoke('the-bottom', { twitterMiddle: 'attrs.twitterTop' })}`)); <add> registry.register('template:components/the-bottom', compile('Bottom: {{attrs.twitterMiddle}}')); <ide> <del> didUpdateAttrs(options) { <del> pushHook(label, 'didUpdateAttrs', options); <del> }, <add> view = EmberView.extend({ <add> template: compile(invoke('the-top', { twitter: 'view.twitter' })), <add> twitter: '@tomdale', <add> container: container <add> }).create(); <ide> <del> willUpdate(options) { <del> pushHook(label, 'willUpdate', options); <del> }, <add> runAppend(view); <ide> <del> didReceiveAttrs(options) { <del> pushHook(label, 'didReceiveAttrs', options); <del> }, <add> ok(component, 'The component was inserted'); <add> equal(jQuery('#qunit-fixture').text(), 'Top: Middle: Bottom: @tomdale'); <ide> <del> willRender() { <del> pushHook(label, 'willRender'); <del> }, <add> let topAttrs = { twitter: '@tomdale' }; <add> let middleAttrs = { twitterTop: '@tomdale' }; <add> let bottomAttrs = { twitterMiddle: '@tomdale' }; <ide> <del> didRender() { <del> pushHook(label, 'didRender'); <del> }, <add> deepEqual(hooks, [ <add> hook('top', 'didInitAttrs', { attrs: topAttrs }), hook('top', 'didReceiveAttrs', { newAttrs: topAttrs }), hook('top', 'willRender'), <add> hook('middle', 'didInitAttrs', { attrs: middleAttrs }), hook('middle', 'didReceiveAttrs', { newAttrs: middleAttrs }), hook('middle', 'willRender'), <add> hook('bottom', 'didInitAttrs', { attrs: bottomAttrs }), hook('bottom', 'didReceiveAttrs', { newAttrs: bottomAttrs }), hook('bottom', 'willRender'), <add> hook('bottom', 'didInsertElement'), hook('bottom', 'didRender'), <add> hook('middle', 'didInsertElement'), hook('middle', 'didRender'), <add> hook('top', 'didInsertElement'), hook('top', 'didRender') <add> ]); <ide> <del> didInsertElement() { <del> pushHook(label, 'didInsertElement'); <del> }, <add> hooks = []; <ide> <del> didUpdate(options) { <del> pushHook(label, 'didUpdate', options); <del> } <add> run(function() { <add> view.set('twitter', '@hipstertomdale'); <ide> }); <del> } <del> <del> registry.register('component:the-top', component('top')); <del> registry.register('component:the-middle', component('middle')); <del> registry.register('component:the-bottom', component('bottom')); <del> <del> registry.register('template:components/the-top', compile('Top: {{the-middle twitterTop=(readonly attrs.twitter)}}')); <del> registry.register('template:components/the-middle', compile('Middle: {{the-bottom twitterMiddle=(readonly attrs.twitterTop)}}')); <del> registry.register('template:components/the-bottom', compile('Bottom: {{attrs.twitterMiddle}}')); <del> <del> view = EmberView.extend({ <del> template: compile('{{the-top twitter=(readonly view.twitter)}}'), <del> twitter: '@tomdale', <del> container: container <del> }).create(); <ide> <del> runAppend(view); <add> // Because the `twitter` attr is used by the all of the components, <add> // the lifecycle hooks are invoked for all components. <ide> <del> ok(component, 'The component was inserted'); <del> equal(jQuery('#qunit-fixture').text(), 'Top: Middle: Bottom: @tomdale'); <ide> <del> let topAttrs = { twitter: '@tomdale' }; <del> let middleAttrs = { twitterTop: '@tomdale' }; <del> let bottomAttrs = { twitterMiddle: '@tomdale' }; <add> topAttrs = { oldAttrs: { twitter: '@tomdale' }, newAttrs: { twitter: '@hipstertomdale' } }; <add> middleAttrs = { oldAttrs: { twitterTop: '@tomdale' }, newAttrs: { twitterTop: '@hipstertomdale' } }; <add> bottomAttrs = { oldAttrs: { twitterMiddle: '@tomdale' }, newAttrs: { twitterMiddle: '@hipstertomdale' } }; <ide> <del> deepEqual(hooks, [ <del> hook('top', 'didInitAttrs', { attrs: topAttrs }), hook('top', 'didReceiveAttrs', { newAttrs: topAttrs }), hook('top', 'willRender'), <del> hook('middle', 'didInitAttrs', { attrs: middleAttrs }), hook('middle', 'didReceiveAttrs', { newAttrs: middleAttrs }), hook('middle', 'willRender'), <del> hook('bottom', 'didInitAttrs', { attrs: bottomAttrs }), hook('bottom', 'didReceiveAttrs', { newAttrs: bottomAttrs }), hook('bottom', 'willRender'), <del> hook('bottom', 'didInsertElement'), hook('bottom', 'didRender'), <del> hook('middle', 'didInsertElement'), hook('middle', 'didRender'), <del> hook('top', 'didInsertElement'), hook('top', 'didRender') <del> ]); <add> deepEqual(hooks, [ <add> hook('top', 'didUpdateAttrs', topAttrs), hook('top', 'didReceiveAttrs', topAttrs), <add> hook('top', 'willUpdate'), hook('top', 'willRender'), <ide> <del> hooks = []; <add> hook('middle', 'didUpdateAttrs', middleAttrs), hook('middle', 'didReceiveAttrs', middleAttrs), <add> hook('middle', 'willUpdate'), hook('middle', 'willRender'), <ide> <del> run(function() { <del> view.set('twitter', '@hipstertomdale'); <del> }); <del> <del> // Because the `twitter` attr is used by the all of the components, <del> // the lifecycle hooks are invoked for all components. <add> hook('bottom', 'didUpdateAttrs', bottomAttrs), hook('bottom', 'didReceiveAttrs', bottomAttrs), <add> hook('bottom', 'willUpdate'), hook('bottom', 'willRender'), <add> hook('bottom', 'didUpdate'), hook('bottom', 'didRender'), <ide> <add> hook('middle', 'didUpdate'), hook('middle', 'didRender'), <add> hook('top', 'didUpdate'), hook('top', 'didRender') <add> ]); <ide> <del> topAttrs = { oldAttrs: { twitter: '@tomdale' }, newAttrs: { twitter: '@hipstertomdale' } }; <del> middleAttrs = { oldAttrs: { twitterTop: '@tomdale' }, newAttrs: { twitterTop: '@hipstertomdale' } }; <del> bottomAttrs = { oldAttrs: { twitterMiddle: '@tomdale' }, newAttrs: { twitterMiddle: '@hipstertomdale' } }; <add> hooks = []; <ide> <del> deepEqual(hooks, [ <del> hook('top', 'didUpdateAttrs', topAttrs), hook('top', 'didReceiveAttrs', topAttrs), <del> hook('top', 'willUpdate'), hook('top', 'willRender'), <add> // In this case, because the attrs are passed down, all child components are invoked. <ide> <del> hook('middle', 'didUpdateAttrs', middleAttrs), hook('middle', 'didReceiveAttrs', middleAttrs), <del> hook('middle', 'willUpdate'), hook('middle', 'willRender'), <add> run(function() { <add> view.rerender(); <add> }); <ide> <del> hook('bottom', 'didUpdateAttrs', bottomAttrs), hook('bottom', 'didReceiveAttrs', bottomAttrs), <del> hook('bottom', 'willUpdate'), hook('bottom', 'willRender'), <del> hook('bottom', 'didUpdate'), hook('bottom', 'didRender'), <add> topAttrs = { oldAttrs: { twitter: '@hipstertomdale' }, newAttrs: { twitter: '@hipstertomdale' } }; <add> middleAttrs = { oldAttrs: { twitterTop: '@hipstertomdale' }, newAttrs: { twitterTop: '@hipstertomdale' } }; <add> bottomAttrs = { oldAttrs: { twitterMiddle: '@hipstertomdale' }, newAttrs: { twitterMiddle: '@hipstertomdale' } }; <ide> <del> hook('middle', 'didUpdate'), hook('middle', 'didRender'), <del> hook('top', 'didUpdate'), hook('top', 'didRender') <del> ]); <add> deepEqual(hooks, [ <add> hook('top', 'didUpdateAttrs', topAttrs), hook('top', 'didReceiveAttrs', topAttrs), <add> hook('top', 'willUpdate'), hook('top', 'willRender'), <ide> <del> hooks = []; <add> hook('middle', 'didUpdateAttrs', middleAttrs), hook('middle', 'didReceiveAttrs', middleAttrs), <add> hook('middle', 'willUpdate'), hook('middle', 'willRender'), <ide> <del> // In this case, because the attrs are passed down, all child components are invoked. <add> hook('bottom', 'didUpdateAttrs', bottomAttrs), hook('bottom', 'didReceiveAttrs', bottomAttrs), <add> hook('bottom', 'willUpdate'), hook('bottom', 'willRender'), <add> hook('bottom', 'didUpdate'), hook('bottom', 'didRender'), <ide> <del> run(function() { <del> view.rerender(); <add> hook('middle', 'didUpdate'), hook('middle', 'didRender'), <add> hook('top', 'didUpdate'), hook('top', 'didRender') <add> ]); <ide> }); <ide> <del> topAttrs = { oldAttrs: { twitter: '@hipstertomdale' }, newAttrs: { twitter: '@hipstertomdale' } }; <del> middleAttrs = { oldAttrs: { twitterTop: '@hipstertomdale' }, newAttrs: { twitterTop: '@hipstertomdale' } }; <del> bottomAttrs = { oldAttrs: { twitterMiddle: '@hipstertomdale' }, newAttrs: { twitterMiddle: '@hipstertomdale' } }; <del> <del> deepEqual(hooks, [ <del> hook('top', 'didUpdateAttrs', topAttrs), hook('top', 'didReceiveAttrs', topAttrs), <del> hook('top', 'willUpdate'), hook('top', 'willRender'), <del> <del> hook('middle', 'didUpdateAttrs', middleAttrs), hook('middle', 'didReceiveAttrs', middleAttrs), <del> hook('middle', 'willUpdate'), hook('middle', 'willRender'), <del> <del> hook('bottom', 'didUpdateAttrs', bottomAttrs), hook('bottom', 'didReceiveAttrs', bottomAttrs), <del> hook('bottom', 'willUpdate'), hook('bottom', 'willRender'), <del> hook('bottom', 'didUpdate'), hook('bottom', 'didRender'), <add> QUnit.test('changing a component\'s displayed properties inside didInsertElement() is deprecated', function(assert) { <add> let component = style.class.extend({ <add> layout: compile('<div>{{debugger}}{{handle}}</div>'), <add> handle: '@wycats', <add> container: container, <ide> <del> hook('middle', 'didUpdate'), hook('middle', 'didRender'), <del> hook('top', 'didUpdate'), hook('top', 'didRender') <del> ]); <del>}); <del> <del>QUnit.test('changing a component\'s displayed properties inside didInsertElement() is deprecated', function(assert) { <del> let component = Component.extend({ <del> layout: compile('{{handle}}'), <del> handle: '@wycats', <del> container: container, <del> <del> didInsertElement() { <del> this.set('handle', '@tomdale'); <del> } <del> }).create(); <add> didInsertElement() { <add> this.set('handle', '@tomdale'); <add> } <add> }).create(); <ide> <del> expectDeprecation(() => { <del> runAppend(component); <del> }, /modified inside the didInsertElement hook/); <add> expectDeprecation(() => { <add> runAppend(component); <add> }, /modified inside the didInsertElement hook/); <ide> <del> assert.strictEqual(component.$().text(), '@tomdale'); <add> assert.strictEqual(component.$().text(), '@tomdale'); <ide> <del> run(() => { <del> component.destroy(); <add> run(() => { <add> component.destroy(); <add> }); <ide> }); <ide> }); <ide> <ide><path>packages/ember-views/lib/main.js <ide> if (Ember.ENV._ENABLE_LEGACY_VIEW_SUPPORT) { <ide> Ember.View.cloneStates = cloneStates; <ide> Ember.View._Renderer = Renderer; <ide> Ember.ContainerView = DeprecatedContainerView; <del> Ember.CollectionView = DeprecatedCollectionView; <add> Ember.CollectionView = CollectionView; <ide> } <ide> <ide> Ember._Renderer = Renderer; <ide><path>packages/ember-views/lib/mixins/legacy_child_views_support.js <add>import { Mixin } from 'ember-metal/mixin'; <add>import { get } from 'ember-metal/property_get'; <add>import { set } from 'ember-metal/property_set'; <add> <add>export default Mixin.create({ <add> linkChild(instance) { <add> instance.container = this.container; <add> if (get(instance, 'parentView') !== this) { <add> // linkChild should be idempotent <add> set(instance, 'parentView', this); <add> instance.trigger('parentViewDidChange'); <add> } <add> instance.ownerView = this.ownerView; <add> }, <add> <add> unlinkChild(instance) { <add> set(instance, 'parentView', null); <add> instance.trigger('parentViewDidChange'); <add> } <add>}); <ide><path>packages/ember-views/lib/mixins/legacy_view_support.js <ide> @submodule ember-views <ide> */ <ide> import Ember from 'ember-metal/core'; <del>import { Mixin } from 'ember-metal/mixin'; <add>import { Mixin, observer } from 'ember-metal/mixin'; <ide> import { get } from 'ember-metal/property_get'; <ide> <ide> /** <ide> var LegacyViewSupport = Mixin.create({ <ide> if (view instanceof klass) { return view; } <ide> view = get(view, 'parentView'); <ide> } <del> } <add> }, <add> <add> /** <add> If a value that affects template rendering changes, the view should be <add> re-rendered to reflect the new value. <add> <add> @method _contextDidChange <add> @private <add> @private <add> */ <add> _contextDidChange: observer('context', function() { <add> this.rerender(); <add> }) <ide> }); <ide> <ide> export default LegacyViewSupport; <ide><path>packages/ember-views/lib/mixins/view_child_views_support.js <ide> export default Mixin.create({ <ide> <ide> linkChild(instance) { <ide> instance.container = this.container; <del> if (get(instance, 'parentView') !== this) { <del> // linkChild should be idempotentj <del> set(instance, 'parentView', this); <del> instance.trigger('parentViewDidChange'); <del> } <add> instance.parentView = this; <ide> instance.ownerView = this.ownerView; <ide> }, <ide> <ide> unlinkChild(instance) { <del> set(instance, 'parentView', null); <del> instance.trigger('parentViewDidChange'); <add> instance.parentView = null; <ide> } <ide> }); <ide><path>packages/ember-views/lib/mixins/view_support.js <add>import Ember from 'ember-metal/core'; <add>import EmberError from 'ember-metal/error'; <add>import { get } from 'ember-metal/property_get'; <add>import run from 'ember-metal/run_loop'; <add>import { addObserver, removeObserver } from 'ember-metal/observer'; <add>import { guidFor } from 'ember-metal/utils'; <add>import { computed } from 'ember-metal/computed'; <add>import { Mixin } from 'ember-metal/mixin'; <add> <add>import jQuery from 'ember-views/system/jquery'; <add> <add>function K() { return this; } <add> <add>export default Mixin.create({ <add> concatenatedProperties: ['attributeBindings'], <add> <add> /** <add> @property isView <add> @type Boolean <add> @default true <add> @static <add> @private <add> */ <add> isView: true, <add> <add> // .......................................................... <add> // TEMPLATE SUPPORT <add> // <add> <add> /** <add> The name of the template to lookup if no template is provided. <add> <add> By default `Ember.View` will lookup a template with this name in <add> `Ember.TEMPLATES` (a shared global object). <add> <add> @property templateName <add> @type String <add> @default null <add> @private <add> */ <add> templateName: null, <add> <add> /** <add> The name of the layout to lookup if no layout is provided. <add> <add> By default `Ember.View` will lookup a template with this name in <add> `Ember.TEMPLATES` (a shared global object). <add> <add> @property layoutName <add> @type String <add> @default null <add> @private <add> */ <add> layoutName: null, <add> <add> /** <add> The template used to render the view. This should be a function that <add> accepts an optional context parameter and returns a string of HTML that <add> will be inserted into the DOM relative to its parent view. <add> <add> In general, you should set the `templateName` property instead of setting <add> the template yourself. <add> <add> @property template <add> @type Function <add> @private <add> */ <add> template: computed('templateName', { <add> get() { <add> var templateName = get(this, 'templateName'); <add> var template = this.templateForName(templateName, 'template'); <add> Ember.assert('You specified the templateName ' + templateName + ' for ' + this + ', but it did not exist.', !templateName || !!template); <add> return template || get(this, 'defaultTemplate'); <add> }, <add> set(key, value) { <add> if (value !== undefined) { return value; } <add> return get(this, key); <add> } <add> }), <add> <add> /** <add> A view may contain a layout. A layout is a regular template but <add> supersedes the `template` property during rendering. It is the <add> responsibility of the layout template to retrieve the `template` <add> property from the view (or alternatively, call `Handlebars.helpers.yield`, <add> `{{yield}}`) to render it in the correct location. <add> <add> This is useful for a view that has a shared wrapper, but which delegates <add> the rendering of the contents of the wrapper to the `template` property <add> on a subclass. <add> <add> @property layout <add> @type Function <add> @private <add> */ <add> layout: computed('layoutName', { <add> get(key) { <add> var layoutName = get(this, 'layoutName'); <add> var layout = this.templateForName(layoutName, 'layout'); <add> <add> Ember.assert('You specified the layoutName ' + layoutName + ' for ' + this + ', but it did not exist.', !layoutName || !!layout); <add> <add> return layout || get(this, 'defaultLayout'); <add> }, <add> <add> set(key, value) { <add> return value; <add> } <add> }), <add> <add> templateForName(name, type) { <add> if (!name) { return; } <add> Ember.assert('templateNames are not allowed to contain periods: ' + name, name.indexOf('.') === -1); <add> <add> if (!this.container) { <add> throw new EmberError('Container was not found when looking up a views template. ' + <add> 'This is most likely due to manually instantiating an Ember.View. ' + <add> 'See: http://git.io/EKPpnA'); <add> } <add> <add> return this.container.lookup('template:' + name); <add> }, <add> <add> /** <add> Return the nearest ancestor that is an instance of the provided <add> class or mixin. <add> <add> @method nearestOfType <add> @param {Class,Mixin} klass Subclass of Ember.View (or Ember.View itself), <add> or an instance of Ember.Mixin. <add> @return Ember.View <add> @private <add> */ <add> nearestOfType(klass) { <add> var view = get(this, 'parentView'); <add> var isOfType = klass instanceof Mixin ? <add> function(view) { return klass.detect(view); } : <add> function(view) { return klass.detect(view.constructor); }; <add> <add> while (view) { <add> if (isOfType(view)) { return view; } <add> view = get(view, 'parentView'); <add> } <add> }, <add> <add> /** <add> Return the nearest ancestor that has a given property. <add> <add> @method nearestWithProperty <add> @param {String} property A property name <add> @return Ember.View <add> @private <add> */ <add> nearestWithProperty(property) { <add> var view = get(this, 'parentView'); <add> <add> while (view) { <add> if (property in view) { return view; } <add> view = get(view, 'parentView'); <add> } <add> }, <add> <add> /** <add> Renders the view again. This will work regardless of whether the <add> view is already in the DOM or not. If the view is in the DOM, the <add> rendering process will be deferred to give bindings a chance <add> to synchronize. <add> <add> If children were added during the rendering process using `appendChild`, <add> `rerender` will remove them, because they will be added again <add> if needed by the next `render`. <add> <add> In general, if the display of your view changes, you should modify <add> the DOM element directly instead of manually calling `rerender`, which can <add> be slow. <add> <add> @method rerender <add> @public <add> */ <add> rerender() { <add> return this.currentState.rerender(this); <add> }, <add> <add> // .......................................................... <add> // ELEMENT SUPPORT <add> // <add> <add> /** <add> Returns the current DOM element for the view. <add> <add> @property element <add> @type DOMElement <add> @public <add> */ <add> element: null, <add> <add> /** <add> Returns a jQuery object for this view's element. If you pass in a selector <add> string, this method will return a jQuery object, using the current element <add> as its buffer. <add> <add> For example, calling `view.$('li')` will return a jQuery object containing <add> all of the `li` elements inside the DOM element of this view. <add> <add> @method $ <add> @param {String} [selector] a jQuery-compatible selector string <add> @return {jQuery} the jQuery object for the DOM node <add> @public <add> */ <add> $(sel) { <add> Ember.assert('You cannot access this.$() on a component with `tagName: \'\'` specified.', this.tagName !== ''); <add> return this.currentState.$(this, sel); <add> }, <add> <add> forEachChildView(callback) { <add> var childViews = this.childViews; <add> <add> if (!childViews) { return this; } <add> <add> var len = childViews.length; <add> var view, idx; <add> <add> for (idx = 0; idx < len; idx++) { <add> view = childViews[idx]; <add> callback(view); <add> } <add> <add> return this; <add> }, <add> <add> /** <add> Appends the view's element to the specified parent element. <add> <add> If the view does not have an HTML representation yet, `createElement()` <add> will be called automatically. <add> <add> Note that this method just schedules the view to be appended; the DOM <add> element will not be appended to the given element until all bindings have <add> finished synchronizing. <add> <add> This is not typically a function that you will need to call directly when <add> building your application. You might consider using `Ember.ContainerView` <add> instead. If you do need to use `appendTo`, be sure that the target element <add> you are providing is associated with an `Ember.Application` and does not <add> have an ancestor element that is associated with an Ember view. <add> <add> @method appendTo <add> @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object <add> @return {Ember.View} receiver <add> @private <add> */ <add> appendTo(selector) { <add> var target = jQuery(selector); <add> <add> Ember.assert('You tried to append to (' + selector + ') but that isn\'t in the DOM', target.length > 0); <add> Ember.assert('You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead.', !target.is('.ember-view') && !target.parents().is('.ember-view')); <add> <add> this.renderer.appendTo(this, target[0]); <add> <add> return this; <add> }, <add> <add> /** <add> @private <add> <add> Creates a new DOM element, renders the view into it, then returns the <add> element. <add> <add> By default, the element created and rendered into will be a `BODY` element, <add> since this is the default context that views are rendered into when being <add> inserted directly into the DOM. <add> <add> ```js <add> var element = view.renderToElement(); <add> element.tagName; // => "BODY" <add> ``` <add> <add> You can override the kind of element rendered into and returned by <add> specifying an optional tag name as the first argument. <add> <add> ```js <add> var element = view.renderToElement('table'); <add> element.tagName; // => "TABLE" <add> ``` <add> <add> This method is useful if you want to render the view into an element that <add> is not in the document's body. Instead, a new `body` element, detached from <add> the DOM is returned. FastBoot uses this to serialize the rendered view into <add> a string for transmission over the network. <add> <add> ```js <add> app.visit('/').then(function(instance) { <add> var element; <add> Ember.run(function() { <add> element = renderToElement(instance); <add> }); <add> <add> res.send(serialize(element)); <add> }); <add> ``` <add> <add> @method renderToElement <add> @param {String} tagName The tag of the element to create and render into. Defaults to "body". <add> @return {HTMLBodyElement} element <add> @private <add> */ <add> renderToElement(tagName) { <add> tagName = tagName || 'body'; <add> <add> var element = this.renderer._dom.createElement(tagName); <add> <add> this.renderer.appendTo(this, element); <add> return element; <add> }, <add> <add> /** <add> Replaces the content of the specified parent element with this view's <add> element. If the view does not have an HTML representation yet, <add> the element will be generated automatically. <add> <add> Note that this method just schedules the view to be appended; the DOM <add> element will not be appended to the given element until all bindings have <add> finished synchronizing <add> <add> @method replaceIn <add> @param {String|DOMElement|jQuery} target A selector, element, HTML string, or jQuery object <add> @return {Ember.View} received <add> @private <add> */ <add> replaceIn(selector) { <add> var target = jQuery(selector); <add> <add> Ember.assert('You tried to replace in (' + selector + ') but that isn\'t in the DOM', target.length > 0); <add> Ember.assert('You cannot replace an existing Ember.View. Consider using Ember.ContainerView instead.', !target.is('.ember-view') && !target.parents().is('.ember-view')); <add> <add> this.renderer.replaceIn(this, target[0]); <add> <add> return this; <add> }, <add> <add> /** <add> Appends the view's element to the document body. If the view does <add> not have an HTML representation yet <add> the element will be generated automatically. <add> <add> If your application uses the `rootElement` property, you must append <add> the view within that element. Rendering views outside of the `rootElement` <add> is not supported. <add> <add> Note that this method just schedules the view to be appended; the DOM <add> element will not be appended to the document body until all bindings have <add> finished synchronizing. <add> <add> @method append <add> @return {Ember.View} receiver <add> @private <add> */ <add> append() { <add> return this.appendTo(document.body); <add> }, <add> <add> /** <add> Removes the view's element from the element to which it is attached. <add> <add> @method remove <add> @return {Ember.View} receiver <add> @private <add> */ <add> remove() { <add> // What we should really do here is wait until the end of the run loop <add> // to determine if the element has been re-appended to a different <add> // element. <add> // In the interim, we will just re-render if that happens. It is more <add> // important than elements get garbage collected. <add> if (!this.removedFromDOM) { this.destroyElement(); } <add> <add> // Set flag to avoid future renders <add> this._willInsert = false; <add> }, <add> <add> /** <add> The HTML `id` of the view's element in the DOM. You can provide this <add> value yourself but it must be unique (just as in HTML): <add> <add> ```handlebars <add> {{my-component elementId="a-really-cool-id"}} <add> ``` <add> <add> If not manually set a default value will be provided by the framework. <add> <add> Once rendered an element's `elementId` is considered immutable and you <add> should never change it. If you need to compute a dynamic value for the <add> `elementId`, you should do this when the component or element is being <add> instantiated: <add> <add> ```javascript <add> export default Ember.Component.extend({ <add> setElementId: Ember.on('init', function() { <add> var index = this.get('index'); <add> this.set('elementId', 'component-id' + index); <add> }) <add> }); <add> ``` <add> <add> @property elementId <add> @type String <add> @public <add> */ <add> elementId: null, <add> <add> /** <add> Attempts to discover the element in the parent element. The default <add> implementation looks for an element with an ID of `elementId` (or the <add> view's guid if `elementId` is null). You can override this method to <add> provide your own form of lookup. For example, if you want to discover your <add> element using a CSS class name instead of an ID. <add> <add> @method findElementInParentElement <add> @param {DOMElement} parentElement The parent's DOM element <add> @return {DOMElement} The discovered element <add> @private <add> */ <add> findElementInParentElement(parentElem) { <add> var id = '#' + this.elementId; <add> return jQuery(id)[0] || jQuery(id, parentElem)[0]; <add> }, <add> <add> /** <add> Creates a DOM representation of the view and all of its child views by <add> recursively calling the `render()` method. Once the element is created, <add> it sets the `element` property of the view to the rendered element. <add> <add> After the element has been inserted into the DOM, `didInsertElement` will <add> be called on this view and all of its child views. <add> <add> @method createElement <add> @return {Ember.View} receiver <add> @private <add> */ <add> createElement() { <add> if (this.element) { return this; } <add> <add> this.renderer.createElement(this); <add> <add> return this; <add> }, <add> <add> /** <add> Called when a view is going to insert an element into the DOM. <add> <add> @event willInsertElement <add> @public <add> */ <add> willInsertElement: K, <add> <add> /** <add> Called when the element of the view has been inserted into the DOM <add> or after the view was re-rendered. Override this function to do any <add> set up that requires an element in the document body. <add> <add> When a view has children, didInsertElement will be called on the <add> child view(s) first, bubbling upwards through the hierarchy. <add> <add> @event didInsertElement <add> @public <add> */ <add> didInsertElement: K, <add> <add> /** <add> Called when the view is about to rerender, but before anything has <add> been torn down. This is a good opportunity to tear down any manual <add> observers you have installed based on the DOM state <add> <add> @event willClearRender <add> @public <add> */ <add> willClearRender: K, <add> <add> /** <add> Destroys any existing element along with the element for any child views <add> as well. If the view does not currently have a element, then this method <add> will do nothing. <add> <add> If you implement `willDestroyElement()` on your view, then this method will <add> be invoked on your view before your element is destroyed to give you a <add> chance to clean up any event handlers, etc. <add> <add> If you write a `willDestroyElement()` handler, you can assume that your <add> `didInsertElement()` handler was called earlier for the same element. <add> <add> You should not call or override this method yourself, but you may <add> want to implement the above callbacks. <add> <add> @method destroyElement <add> @return {Ember.View} receiver <add> @private <add> */ <add> destroyElement() { <add> return this.currentState.destroyElement(this); <add> }, <add> <add> /** <add> Called when the element of the view is going to be destroyed. Override <add> this function to do any teardown that requires an element, like removing <add> event listeners. <add> <add> Please note: any property changes made during this event will have no <add> effect on object observers. <add> <add> @event willDestroyElement <add> @public <add> */ <add> willDestroyElement: K, <add> <add> /** <add> Called when the parentView property has changed. <add> <add> @event parentViewDidChange <add> @private <add> */ <add> parentViewDidChange: K, <add> <add> // .......................................................... <add> // STANDARD RENDER PROPERTIES <add> // <add> <add> /** <add> Tag name for the view's outer element. The tag name is only used when an <add> element is first created. If you change the `tagName` for an element, you <add> must destroy and recreate the view element. <add> <add> By default, the render buffer will use a `<div>` tag for views. <add> <add> @property tagName <add> @type String <add> @default null <add> @public <add> */ <add> <add> // We leave this null by default so we can tell the difference between <add> // the default case and a user-specified tag. <add> tagName: null, <add> <add> /* <add> Used to specify a default tagName that can be overridden when extending <add> or invoking from a template. <add> <add> @property _defaultTagName <add> @private <add> */ <add> <add> /** <add> Normally, Ember's component model is "write-only". The component takes a <add> bunch of attributes that it got passed in, and uses them to render its <add> template. <add> <add> One nice thing about this model is that if you try to set a value to the <add> same thing as last time, Ember (through HTMLBars) will avoid doing any <add> work on the DOM. <add> <add> This is not just a performance optimization. If an attribute has not <add> changed, it is important not to clobber the element's "hidden state". <add> For example, if you set an input's `value` to the same value as before, <add> it will clobber selection state and cursor position. In other words, <add> setting an attribute is not **always** idempotent. <add> <add> This method provides a way to read an element's attribute and also <add> update the last value Ember knows about at the same time. This makes <add> setting an attribute idempotent. <add> <add> In particular, what this means is that if you get an `<input>` element's <add> `value` attribute and then re-render the template with the same value, <add> it will avoid clobbering the cursor and selection position. <add> <add> Since most attribute sets are idempotent in the browser, you typically <add> can get away with reading attributes using jQuery, but the most reliable <add> way to do so is through this method. <add> <add> @method readDOMAttr <add> @param {String} name the name of the attribute <add> @return String <add> @public <add> */ <add> readDOMAttr(name) { <add> let attr = this._renderNode.childNodes.filter(node => node.attrName === name)[0]; <add> if (!attr) { return null; } <add> return attr.getContent(); <add> }, <add> <add> // ....................................................... <add> // CORE DISPLAY METHODS <add> // <add> <add> /** <add> Setup a view, but do not finish waking it up. <add> <add> * configure `childViews` <add> * register the view with the global views hash, which is used for event <add> dispatch <add> <add> @method init <add> @private <add> */ <add> init() { <add> if (!this.elementId) { <add> this.elementId = guidFor(this); <add> } <add> <add> this.scheduledRevalidation = false; <add> <add> this._super(...arguments); <add> this.renderer.componentInitAttrs(this, this.attrs || {}); <add> }, <add> <add> __defineNonEnumerable(property) { <add> this[property.name] = property.descriptor.value; <add> }, <add> <add> revalidate() { <add> this.renderer.revalidateTopLevelView(this); <add> this.scheduledRevalidation = false; <add> }, <add> <add> scheduleRevalidate(node, label, manualRerender) { <add> if (node && !this._dispatching && node.guid in this.env.renderedNodes) { <add> if (manualRerender) { <add> Ember.deprecate(`You manually rerendered ${label} (a parent component) from a child component during the rendering process. This rarely worked in Ember 1.x and will be removed in Ember 2.0`, <add> false, <add> { id: 'ember-views.manual-parent-rerender', until: '3.0.0' }); <add> } else { <add> Ember.deprecate(`You modified ${label} twice in a single render. This was unreliable in Ember 1.x and will be removed in Ember 2.0`, <add> false, <add> { id: 'ember-views.render-double-modify', until: '3.0.0' }); <add> } <add> run.scheduleOnce('render', this, this.revalidate); <add> return; <add> } <add> <add> Ember.deprecate(`A property of ${this} was modified inside the ${this._dispatching} hook. You should never change properties on components, services or models during ${this._dispatching} because it causes significant performance degradation.`, <add> !this._dispatching, <add> { id: 'ember-views.dispatching-modify-property', until: '3.0.0' }); <add> <add> if (!this.scheduledRevalidation || this._dispatching) { <add> this.scheduledRevalidation = true; <add> run.scheduleOnce('render', this, this.revalidate); <add> } <add> }, <add> <add> templateRenderer: null, <add> <add> /** <add> Removes the view from its `parentView`, if one is found. Otherwise <add> does nothing. <add> <add> @method removeFromParent <add> @return {Ember.View} receiver <add> @private <add> */ <add> removeFromParent() { <add> var parent = this.parentView; <add> <add> // Remove DOM element from parent <add> this.remove(); <add> <add> if (parent) { parent.removeChild(this); } <add> return this; <add> }, <add> <add> /** <add> You must call `destroy` on a view to destroy the view (and all of its <add> child views). This will remove the view from any parent node, then make <add> sure that the DOM element managed by the view can be released by the <add> memory manager. <add> <add> @method destroy <add> @private <add> */ <add> destroy() { <add> // get parentView before calling super because it'll be destroyed <add> var parentView = this.parentView; <add> var viewName = this.viewName; <add> <add> if (!this._super(...arguments)) { return; } <add> <add> // remove from non-virtual parent view if viewName was specified <add> if (viewName && parentView) { <add> parentView.set(viewName, null); <add> } <add> <add> // Destroy HTMLbars template <add> if (this.lastResult) { <add> this.lastResult.destroy(); <add> } <add> <add> return this; <add> }, <add> <add> // ....................................................... <add> // EVENT HANDLING <add> // <add> <add> /** <add> Handle events from `Ember.EventDispatcher` <add> <add> @method handleEvent <add> @param eventName {String} <add> @param evt {Event} <add> @private <add> */ <add> handleEvent(eventName, evt) { <add> return this.currentState.handleEvent(this, eventName, evt); <add> }, <add> <add> /** <add> Registers the view in the view registry, keyed on the view's `elementId`. <add> This is used by the EventDispatcher to locate the view in response to <add> events. <add> <add> This method should only be called once the view has been inserted into the <add> DOM. <add> <add> @method _register <add> @private <add> */ <add> _register() { <add> Ember.assert('Attempted to register a view with an id already in use: ' + this.elementId, !this._viewRegistry[this.elementId]); <add> this._viewRegistry[this.elementId] = this; <add> }, <add> <add> /** <add> Removes the view from the view registry. This should be called when the <add> view is removed from DOM. <add> <add> @method _unregister <add> @private <add> */ <add> _unregister() { <add> delete this._viewRegistry[this.elementId]; <add> }, <add> <add> registerObserver(root, path, target, observer) { <add> if (!observer && 'function' === typeof target) { <add> observer = target; <add> target = null; <add> } <add> <add> if (!root || typeof root !== 'object') { <add> return; <add> } <add> <add> var scheduledObserver = this._wrapAsScheduled(observer); <add> <add> addObserver(root, path, target, scheduledObserver); <add> <add> this.one('willClearRender', function() { <add> removeObserver(root, path, target, scheduledObserver); <add> }); <add> }, <add> <add> _wrapAsScheduled(fn) { <add> var view = this; <add> var stateCheckedFn = function() { <add> view.currentState.invokeObserver(this, fn); <add> }; <add> var scheduledFn = function() { <add> run.scheduleOnce('render', this, stateCheckedFn); <add> }; <add> return scheduledFn; <add> } <add>}); <ide><path>packages/ember-views/lib/views/view.js <ide> // Ember.ENV <ide> import Ember from 'ember-metal/core'; <ide> <del>import EmberError from 'ember-metal/error'; <del>import { get } from 'ember-metal/property_get'; <del>import run from 'ember-metal/run_loop'; <del>import { addObserver, removeObserver } from 'ember-metal/observer'; <del>import { guidFor } from 'ember-metal/utils'; <del>import { computed } from 'ember-metal/computed'; <del>import { <del> Mixin, <del> observer <del>} from 'ember-metal/mixin'; <del> <del>import jQuery from 'ember-views/system/jquery'; <ide> import 'ember-views/system/ext'; // for the side effect of extending Ember.run.queues <ide> <ide> import CoreView from 'ember-views/views/core_view'; <ide> import ViewContextSupport from 'ember-views/mixins/view_context_support'; <ide> import ViewChildViewsSupport from 'ember-views/mixins/view_child_views_support'; <add>import ViewLegacyChildViewsSupport from 'ember-views/mixins/legacy_child_views_support'; <ide> import { <ide> childViewsProperty <ide> } from 'ember-views/mixins/view_child_views_support'; <ide> import InstrumentationSupport from 'ember-views/mixins/instrumentation_support'; <ide> import AriaRoleSupport from 'ember-views/mixins/aria_role_support'; <ide> import VisibilitySupport from 'ember-views/mixins/visibility_support'; <ide> import CompatAttrsProxy from 'ember-views/compat/attrs-proxy'; <del> <del>function K() { return this; } <add>import ViewMixin from 'ember-views/mixins/view_support'; <ide> <ide> /** <ide> @module ember <ide> Ember.TEMPLATES = {}; <ide> var View = CoreView.extend( <ide> ViewContextSupport, <ide> ViewChildViewsSupport, <add> ViewLegacyChildViewsSupport, <ide> ViewStateSupport, <ide> TemplateRenderingSupport, <ide> ClassNamesSupport, <ide> LegacyViewSupport, <ide> InstrumentationSupport, <ide> VisibilitySupport, <ide> CompatAttrsProxy, <del> AriaRoleSupport, { <del> concatenatedProperties: ['attributeBindings'], <del> <del> /** <del> @property isView <del> @type Boolean <del> @default true <del> @static <del> @private <del> */ <del> isView: true, <del> <del> // .......................................................... <del> // TEMPLATE SUPPORT <del> // <del> <del> /** <del> The name of the template to lookup if no template is provided. <del> <del> By default `Ember.View` will lookup a template with this name in <del> `Ember.TEMPLATES` (a shared global object). <del> <del> @property templateName <del> @type String <del> @default null <del> @private <del> */ <del> templateName: null, <del> <del> /** <del> The name of the layout to lookup if no layout is provided. <del> <del> By default `Ember.View` will lookup a template with this name in <del> `Ember.TEMPLATES` (a shared global object). <del> <del> @property layoutName <del> @type String <del> @default null <del> @public <del> */ <del> layoutName: null, <del> <del> /** <del> The template used to render the view. This should be a function that <del> accepts an optional context parameter and returns a string of HTML that <del> will be inserted into the DOM relative to its parent view. <del> <del> In general, you should set the `templateName` property instead of setting <del> the template yourself. <del> <del> @property template <del> @type Function <del> @private <del> */ <del> template: computed('templateName', { <del> get() { <del> var templateName = get(this, 'templateName'); <del> var template = this.templateForName(templateName, 'template'); <del> Ember.assert('You specified the templateName ' + templateName + ' for ' + this + ', but it did not exist.', !templateName || !!template); <del> return template || get(this, 'defaultTemplate'); <del> }, <del> set(key, value) { <del> if (value !== undefined) { return value; } <del> return get(this, key); <del> } <del> }), <del> <del> /** <del> A view may contain a layout. A layout is a regular template but <del> supersedes the `template` property during rendering. It is the <del> responsibility of the layout template to retrieve the `template` <del> property from the view (or alternatively, call `Handlebars.helpers.yield`, <del> `{{yield}}`) to render it in the correct location. <del> <del> This is useful for a view that has a shared wrapper, but which delegates <del> the rendering of the contents of the wrapper to the `template` property <del> on a subclass. <del> <del> @property layout <del> @type Function <del> @public <del> */ <del> layout: computed('layoutName', { <del> get(key) { <del> var layoutName = get(this, 'layoutName'); <del> var layout = this.templateForName(layoutName, 'layout'); <del> <del> Ember.assert('You specified the layoutName ' + layoutName + ' for ' + this + ', but it did not exist.', !layoutName || !!layout); <del> <del> return layout || get(this, 'defaultLayout'); <del> }, <del> <del> set(key, value) { <del> return value; <del> } <del> }), <del> <del> templateForName(name, type) { <del> if (!name) { return; } <del> Ember.assert('templateNames are not allowed to contain periods: ' + name, name.indexOf('.') === -1); <del> <del> if (!this.container) { <del> throw new EmberError('Container was not found when looking up a views template. ' + <del> 'This is most likely due to manually instantiating an Ember.View. ' + <del> 'See: http://git.io/EKPpnA'); <del> } <del> <del> return this.container.lookup('template:' + name); <del> }, <del> <del> /** <del> If a value that affects template rendering changes, the view should be <del> re-rendered to reflect the new value. <del> <del> @method _contextDidChange <del> @private <del> @private <del> */ <del> _contextDidChange: observer('context', function() { <del> this.rerender(); <del> }), <del> <del> /** <del> Return the nearest ancestor that is an instance of the provided <del> class or mixin. <del> <del> @method nearestOfType <del> @param {Class,Mixin} klass Subclass of Ember.View (or Ember.View itself), <del> or an instance of Ember.Mixin. <del> @return Ember.View <del> @private <del> */ <del> nearestOfType(klass) { <del> var view = get(this, 'parentView'); <del> var isOfType = klass instanceof Mixin ? <del> function(view) { return klass.detect(view); } : <del> function(view) { return klass.detect(view.constructor); }; <del> <del> while (view) { <del> if (isOfType(view)) { return view; } <del> view = get(view, 'parentView'); <del> } <del> }, <del> <del> /** <del> Return the nearest ancestor that has a given property. <del> <del> @method nearestWithProperty <del> @param {String} property A property name <del> @return Ember.View <del> @private <del> */ <del> nearestWithProperty(property) { <del> var view = get(this, 'parentView'); <del> <del> while (view) { <del> if (property in view) { return view; } <del> view = get(view, 'parentView'); <del> } <del> }, <del> <del> /** <del> Renders the view again. This will work regardless of whether the <del> view is already in the DOM or not. If the view is in the DOM, the <del> rendering process will be deferred to give bindings a chance <del> to synchronize. <del> <del> If children were added during the rendering process using `appendChild`, <del> `rerender` will remove them, because they will be added again <del> if needed by the next `render`. <del> <del> In general, if the display of your view changes, you should modify <del> the DOM element directly instead of manually calling `rerender`, which can <del> be slow. <del> <del> @method rerender <del> @public <del> */ <del> rerender() { <del> return this.currentState.rerender(this); <del> }, <del> <del> /** <del> Given a property name, returns a dasherized version of that <del> property name if the property evaluates to a non-falsy value. <del> <del> For example, if the view has property `isUrgent` that evaluates to true, <del> passing `isUrgent` to this method will return `"is-urgent"`. <del> <del> @method _classStringForProperty <del> @param property <del> @private <del> */ <del> _classStringForProperty(parsedPath) { <del> return View._classStringForValue(parsedPath.path, parsedPath.stream.value(), parsedPath.className, parsedPath.falsyClassName); <del> }, <del> <del> // .......................................................... <del> // ELEMENT SUPPORT <del> // <del> <del> /** <del> Returns the current DOM element for the view. <del> <del> @property element <del> @type DOMElement <del> @public <del> */ <del> element: null, <del> <del> /** <del> Returns a jQuery object for this view's element. If you pass in a selector <del> string, this method will return a jQuery object, using the current element <del> as its buffer. <del> <del> For example, calling `view.$('li')` will return a jQuery object containing <del> all of the `li` elements inside the DOM element of this view. <del> <del> @method $ <del> @param {String} [selector] a jQuery-compatible selector string <del> @return {jQuery} the jQuery object for the DOM node <del> @public <del> */ <del> $(sel) { <del> Ember.assert('You cannot access this.$() on a component with `tagName: \'\'` specified.', this.tagName !== ''); <del> return this.currentState.$(this, sel); <del> }, <del> <del> forEachChildView(callback) { <del> var childViews = this.childViews; <del> <del> if (!childViews) { return this; } <del> <del> var len = childViews.length; <del> var view, idx; <del> <del> for (idx = 0; idx < len; idx++) { <del> view = childViews[idx]; <del> callback(view); <del> } <del> <del> return this; <del> }, <del> <del> /** <del> Appends the view's element to the specified parent element. <del> <del> If the view does not have an HTML representation yet, `createElement()` <del> will be called automatically. <del> <del> Note that this method just schedules the view to be appended; the DOM <del> element will not be appended to the given element until all bindings have <del> finished synchronizing. <del> <del> This is not typically a function that you will need to call directly when <del> building your application. You might consider using `Ember.ContainerView` <del> instead. If you do need to use `appendTo`, be sure that the target element <del> you are providing is associated with an `Ember.Application` and does not <del> have an ancestor element that is associated with an Ember view. <del> <del> @method appendTo <del> @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object <del> @return {Ember.View} receiver <del> @private <del> */ <del> appendTo(selector) { <del> var target = jQuery(selector); <del> <del> Ember.assert('You tried to append to (' + selector + ') but that isn\'t in the DOM', target.length > 0); <del> Ember.assert('You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead.', !target.is('.ember-view') && !target.parents().is('.ember-view')); <del> <del> this.renderer.appendTo(this, target[0]); <del> <del> return this; <del> }, <del> <del> /** <del> @private <del> <del> Creates a new DOM element, renders the view into it, then returns the <del> element. <del> <del> By default, the element created and rendered into will be a `BODY` element, <del> since this is the default context that views are rendered into when being <del> inserted directly into the DOM. <del> <del> ```js <del> var element = view.renderToElement(); <del> element.tagName; // => "BODY" <del> ``` <del> <del> You can override the kind of element rendered into and returned by <del> specifying an optional tag name as the first argument. <del> <del> ```js <del> var element = view.renderToElement('table'); <del> element.tagName; // => "TABLE" <del> ``` <del> <del> This method is useful if you want to render the view into an element that <del> is not in the document's body. Instead, a new `body` element, detached from <del> the DOM is returned. FastBoot uses this to serialize the rendered view into <del> a string for transmission over the network. <del> <del> ```js <del> app.visit('/').then(function(instance) { <del> var element; <del> Ember.run(function() { <del> element = renderToElement(instance); <del> }); <del> <del> res.send(serialize(element)); <del> }); <del> ``` <del> <del> @method renderToElement <del> @param {String} tagName The tag of the element to create and render into. Defaults to "body". <del> @return {HTMLBodyElement} element <del> @private <del> */ <del> renderToElement(tagName) { <del> tagName = tagName || 'body'; <del> <del> var element = this.renderer._dom.createElement(tagName); <del> <del> this.renderer.appendTo(this, element); <del> return element; <del> }, <del> <del> /** <del> Replaces the content of the specified parent element with this view's <del> element. If the view does not have an HTML representation yet, <del> the element will be generated automatically. <del> <del> Note that this method just schedules the view to be appended; the DOM <del> element will not be appended to the given element until all bindings have <del> finished synchronizing <del> <del> @method replaceIn <del> @param {String|DOMElement|jQuery} target A selector, element, HTML string, or jQuery object <del> @return {Ember.View} received <del> @private <del> */ <del> replaceIn(selector) { <del> var target = jQuery(selector); <del> <del> Ember.assert('You tried to replace in (' + selector + ') but that isn\'t in the DOM', target.length > 0); <del> Ember.assert('You cannot replace an existing Ember.View. Consider using Ember.ContainerView instead.', !target.is('.ember-view') && !target.parents().is('.ember-view')); <del> <del> this.renderer.replaceIn(this, target[0]); <del> <del> return this; <del> }, <del> <del> /** <del> Appends the view's element to the document body. If the view does <del> not have an HTML representation yet <del> the element will be generated automatically. <del> <del> If your application uses the `rootElement` property, you must append <del> the view within that element. Rendering views outside of the `rootElement` <del> is not supported. <del> <del> Note that this method just schedules the view to be appended; the DOM <del> element will not be appended to the document body until all bindings have <del> finished synchronizing. <del> <del> @method append <del> @return {Ember.View} receiver <del> @private <del> */ <del> append() { <del> return this.appendTo(document.body); <del> }, <del> <del> /** <del> Removes the view's element from the element to which it is attached. <del> <del> @method remove <del> @return {Ember.View} receiver <del> @private <del> */ <del> remove() { <del> // What we should really do here is wait until the end of the run loop <del> // to determine if the element has been re-appended to a different <del> // element. <del> // In the interim, we will just re-render if that happens. It is more <del> // important than elements get garbage collected. <del> if (!this.removedFromDOM) { this.destroyElement(); } <del> <del> // Set flag to avoid future renders <del> this._willInsert = false; <del> }, <del> <del> /** <del> The HTML `id` of the view's element in the DOM. You can provide this <del> value yourself but it must be unique (just as in HTML): <del> <del> ```handlebars <del> {{my-component elementId="a-really-cool-id"}} <del> ``` <del> <del> If not manually set a default value will be provided by the framework. <del> <del> Once rendered an element's `elementId` is considered immutable and you <del> should never change it. If you need to compute a dynamic value for the <del> `elementId`, you should do this when the component or element is being <del> instantiated: <del> <del> ```javascript <del> export default Ember.Component.extend({ <del> setElementId: Ember.on('init', function() { <del> var index = this.get('index'); <del> this.set('elementId', 'component-id' + index); <del> }) <del> }); <del> ``` <del> <del> @property elementId <del> @type String <del> @public <del> */ <del> elementId: null, <del> <del> /** <del> Attempts to discover the element in the parent element. The default <del> implementation looks for an element with an ID of `elementId` (or the <del> view's guid if `elementId` is null). You can override this method to <del> provide your own form of lookup. For example, if you want to discover your <del> element using a CSS class name instead of an ID. <del> <del> @method findElementInParentElement <del> @param {DOMElement} parentElement The parent's DOM element <del> @return {DOMElement} The discovered element <del> @private <del> */ <del> findElementInParentElement(parentElem) { <del> var id = '#' + this.elementId; <del> return jQuery(id)[0] || jQuery(id, parentElem)[0]; <del> }, <del> <del> /** <del> Creates a DOM representation of the view and all of its child views by <del> recursively calling the `render()` method. Once the element is created, <del> it sets the `element` property of the view to the rendered element. <del> <del> After the element has been inserted into the DOM, `didInsertElement` will <del> be called on this view and all of its child views. <del> <del> @method createElement <del> @return {Ember.View} receiver <del> @private <del> */ <del> createElement() { <del> if (this.element) { return this; } <del> <del> this.renderer.createElement(this); <del> <del> return this; <del> }, <del> <del> /** <del> Called when a view is going to insert an element into the DOM. <del> <del> @event willInsertElement <del> @public <del> */ <del> willInsertElement: K, <del> <del> /** <del> Called when the element of the view has been inserted into the DOM <del> or after the view was re-rendered. Override this function to do any <del> set up that requires an element in the document body. <del> <del> When a view has children, didInsertElement will be called on the <del> child view(s) first, bubbling upwards through the hierarchy. <del> <del> @event didInsertElement <del> @public <del> */ <del> didInsertElement: K, <del> <del> /** <del> Called when the view is about to rerender, but before anything has <del> been torn down. This is a good opportunity to tear down any manual <del> observers you have installed based on the DOM state <del> <del> @event willClearRender <del> @public <del> */ <del> willClearRender: K, <del> <del> /** <del> Destroys any existing element along with the element for any child views <del> as well. If the view does not currently have a element, then this method <del> will do nothing. <del> <del> If you implement `willDestroyElement()` on your view, then this method will <del> be invoked on your view before your element is destroyed to give you a <del> chance to clean up any event handlers, etc. <del> <del> If you write a `willDestroyElement()` handler, you can assume that your <del> `didInsertElement()` handler was called earlier for the same element. <del> <del> You should not call or override this method yourself, but you may <del> want to implement the above callbacks. <del> <del> @method destroyElement <del> @return {Ember.View} receiver <del> @private <del> */ <del> destroyElement() { <del> return this.currentState.destroyElement(this); <del> }, <del> <del> /** <del> Called when the element of the view is going to be destroyed. Override <del> this function to do any teardown that requires an element, like removing <del> event listeners. <del> <del> Please note: any property changes made during this event will have no <del> effect on object observers. <del> <del> @event willDestroyElement <del> @public <del> */ <del> willDestroyElement: K, <del> <del> /** <del> Called when the parentView property has changed. <del> <del> @event parentViewDidChange <del> @private <del> */ <del> parentViewDidChange: K, <del> <del> // .......................................................... <del> // STANDARD RENDER PROPERTIES <del> // <del> <del> /** <del> Tag name for the view's outer element. The tag name is only used when an <del> element is first created. If you change the `tagName` for an element, you <del> must destroy and recreate the view element. <del> <del> By default, the render buffer will use a `<div>` tag for views. <del> <del> @property tagName <del> @type String <del> @default null <del> @public <del> */ <del> <del> // We leave this null by default so we can tell the difference between <del> // the default case and a user-specified tag. <del> tagName: null, <del> <del> /* <del> Used to specify a default tagName that can be overridden when extending <del> or invoking from a template. <del> <del> @property _defaultTagName <del> @private <del> */ <del> <del> /** <del> Normally, Ember's component model is "write-only". The component takes a <del> bunch of attributes that it got passed in, and uses them to render its <del> template. <del> <del> One nice thing about this model is that if you try to set a value to the <del> same thing as last time, Ember (through HTMLBars) will avoid doing any <del> work on the DOM. <del> <del> This is not just a performance optimization. If an attribute has not <del> changed, it is important not to clobber the element's "hidden state". <del> For example, if you set an input's `value` to the same value as before, <del> it will clobber selection state and cursor position. In other words, <del> setting an attribute is not **always** idempotent. <del> <del> This method provides a way to read an element's attribute and also <del> update the last value Ember knows about at the same time. This makes <del> setting an attribute idempotent. <del> <del> In particular, what this means is that if you get an `<input>` element's <del> `value` attribute and then re-render the template with the same value, <del> it will avoid clobbering the cursor and selection position. <del> <del> Since most attribute sets are idempotent in the browser, you typically <del> can get away with reading attributes using jQuery, but the most reliable <del> way to do so is through this method. <del> <del> @method readDOMAttr <del> @param {String} name the name of the attribute <del> @return String <del> @public <del> */ <del> readDOMAttr(name) { <del> let attr = this._renderNode.childNodes.filter(node => node.attrName === name)[0]; <del> if (!attr) { return null; } <del> return attr.getContent(); <del> }, <del> <del> // ....................................................... <del> // CORE DISPLAY METHODS <del> // <del> <del> /** <del> Setup a view, but do not finish waking it up. <del> <del> * configure `childViews` <del> * register the view with the global views hash, which is used for event <del> dispatch <del> <del> @method init <del> @private <del> */ <del> init() { <del> if (!this.elementId) { <del> this.elementId = guidFor(this); <del> } <del> <del> this.scheduledRevalidation = false; <add> AriaRoleSupport, <add> ViewMixin, { <add> init() { <add> this._super(...arguments); <ide> <del> this._super(...arguments); <del> <del> if (!this._viewRegistry) { <del> this._viewRegistry = View.views; <del> } <del> <del> this.renderer.componentInitAttrs(this, this.attrs || {}); <del> }, <del> <del> __defineNonEnumerable(property) { <del> this[property.name] = property.descriptor.value; <del> }, <del> <del> revalidate() { <del> this.renderer.revalidateTopLevelView(this); <del> this.scheduledRevalidation = false; <del> }, <del> <del> scheduleRevalidate(node, label, manualRerender) { <del> if (node && !this._dispatching && node.guid in this.env.renderedNodes) { <del> if (manualRerender) { <del> Ember.deprecate(`You manually rerendered ${label} (a parent component) from a child component during the rendering process. This rarely worked in Ember 1.x and will be removed in Ember 2.0`, <del> false, <del> { id: 'ember-views.manual-parent-rerender', until: '3.0.0' }); <del> } else { <del> Ember.deprecate(`You modified ${label} twice in a single render. This was unreliable in Ember 1.x and will be removed in Ember 2.0`, <del> false, <del> { id: 'ember-views.render-double-modify', until: '3.0.0' }); <add> if (!this._viewRegistry) { <add> this._viewRegistry = View.views; <ide> } <del> run.scheduleOnce('render', this, this.revalidate); <del> return; <del> } <del> <del> Ember.deprecate(`A property of ${this} was modified inside the ${this._dispatching} hook. You should never change properties on components, services or models during ${this._dispatching} because it causes significant performance degradation.`, <del> !this._dispatching, <del> { id: 'ember-views.dispatching-modify-property', until: '3.0.0' }); <del> <del> if (!this.scheduledRevalidation || this._dispatching) { <del> this.scheduledRevalidation = true; <del> run.scheduleOnce('render', this, this.revalidate); <del> } <del> }, <del> <del> templateRenderer: null, <del> <del> /** <del> Removes the view from its `parentView`, if one is found. Otherwise <del> does nothing. <del> <del> @method removeFromParent <del> @return {Ember.View} receiver <del> @private <del> */ <del> removeFromParent() { <del> var parent = this.parentView; <del> <del> // Remove DOM element from parent <del> this.remove(); <del> <del> if (parent) { parent.removeChild(this); } <del> return this; <del> }, <del> <del> /** <del> You must call `destroy` on a view to destroy the view (and all of its <del> child views). This will remove the view from any parent node, then make <del> sure that the DOM element managed by the view can be released by the <del> memory manager. <del> <del> @method destroy <del> @private <del> */ <del> destroy() { <del> // get parentView before calling super because it'll be destroyed <del> var parentView = this.parentView; <del> var viewName = this.viewName; <del> <del> if (!this._super(...arguments)) { return; } <del> <del> // remove from non-virtual parent view if viewName was specified <del> if (viewName && parentView) { <del> parentView.set(viewName, null); <del> } <del> <del> // Destroy HTMLbars template <del> if (this.lastResult) { <del> this.lastResult.destroy(); <del> } <del> <del> return this; <del> }, <del> <del> // ....................................................... <del> // EVENT HANDLING <del> // <del> <del> /** <del> Handle events from `Ember.EventDispatcher` <del> <del> @method handleEvent <del> @param eventName {String} <del> @param evt {Event} <del> @private <del> */ <del> handleEvent(eventName, evt) { <del> return this.currentState.handleEvent(this, eventName, evt); <del> }, <del> <del> /** <del> Registers the view in the view registry, keyed on the view's `elementId`. <del> This is used by the EventDispatcher to locate the view in response to <del> events. <del> <del> This method should only be called once the view has been inserted into the <del> DOM. <del> <del> @method _register <del> @private <del> */ <del> _register() { <del> Ember.assert('Attempted to register a view with an id already in use: ' + this.elementId, !this._viewRegistry[this.elementId]); <del> this._viewRegistry[this.elementId] = this; <del> }, <add> }, <ide> <del> /** <del> Removes the view from the view registry. This should be called when the <del> view is removed from DOM. <add> /** <add> Given a property name, returns a dasherized version of that <add> property name if the property evaluates to a non-falsy value. <ide> <del> @method _unregister <del> @private <del> */ <del> _unregister() { <del> delete this._viewRegistry[this.elementId]; <del> }, <del> <del> registerObserver(root, path, target, observer) { <del> if (!observer && 'function' === typeof target) { <del> observer = target; <del> target = null; <del> } <add> For example, if the view has property `isUrgent` that evaluates to true, <add> passing `isUrgent` to this method will return `"is-urgent"`. <ide> <del> if (!root || typeof root !== 'object') { <del> return; <add> @method _classStringForProperty <add> @param property <add> @private <add> */ <add> _classStringForProperty(parsedPath) { <add> return View._classStringForValue(parsedPath.path, parsedPath.stream.value(), parsedPath.className, parsedPath.falsyClassName); <ide> } <del> <del> var scheduledObserver = this._wrapAsScheduled(observer); <del> <del> addObserver(root, path, target, scheduledObserver); <del> <del> this.one('willClearRender', function() { <del> removeObserver(root, path, target, scheduledObserver); <del> }); <del> }, <del> <del> _wrapAsScheduled(fn) { <del> var view = this; <del> var stateCheckedFn = function() { <del> view.currentState.invokeObserver(this, fn); <del> }; <del> var scheduledFn = function() { <del> run.scheduleOnce('render', this, stateCheckedFn); <del> }; <del> return scheduledFn; <del> } <del>}); <add> }); <ide> // jscs:enable validateIndentation <ide> <ide> /*
13
Javascript
Javascript
add some utility functions to buffergeometryutils
908fa7354d9f5b9aa0fdd83a391360e058b51552
<ide><path>examples/js/BufferGeometryUtils.js <ide> THREE.BufferGeometryUtils = { <ide> <ide> return new THREE.BufferAttribute( array, itemSize, normalized ); <ide> <add> }, <add> <add> /** <add> * @param {Array<THREE.BufferAttribute>} attributes <add> * @return {Array<THREE.InterleavedBufferAttribute>} <add> */ <add> interleaveAttributes: function ( attributes ) { <add> <add> // Interleaves the provided attributes into an InterleavedBuffer and returns <add> // a set of InterleavedBufferAttributes for each attribute <add> var TypedArray; <add> var arrayLength = 0; <add> var stride = 0; <add> <add> // calculate the the length and type of the interleavedBuffer <add> for ( var i = 0, l = attributes.length; i < l; ++ i ) { <add> <add> var attribute = attributes[ i ]; <add> <add> if ( TypedArray === undefined ) TypedArray = attribute.array.constructor; <add> if ( TypedArray !== attribute.array.constructor ) { <add> <add> console.warn( 'AttributeBuffers of different types cannot be interleaved' ); <add> return null; <add> <add> } <add> <add> arrayLength += attribute.array.length; <add> stride += attribute.itemSize; <add> <add> } <add> <add> // Create the set of buffer attributes <add> var interleavedBuffer = new THREE.InterleavedBuffer( new TypedArray( arrayLength ), stride ); <add> var offset = 0; <add> var res = []; <add> var getters = [ 'getX', 'getY', 'getZ', 'getW' ]; <add> var setters = [ 'setX', 'setY', 'setZ', 'setW' ]; <add> <add> for ( var j = 0, l = attributes.length; j < l; j ++ ) { <add> <add> var attribute = attributes[ j ]; <add> var itemSize = attribute.itemSize; <add> var count = attribute.count; <add> var iba = new THREE.InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized ); <add> res.push( iba ); <add> <add> offset += itemSize; <add> <add> // Move the data for each attribute into the new interleavedBuffer <add> // at the appropriate offset <add> for ( var c = 0; c < count; c ++ ) { <add> <add> for ( var k = 0; k < itemSize; k ++ ) { <add> <add> iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) ); <add> <add> } <add> <add> } <add> <add> } <add> <add> return res; <add> <add> }, <add> <add> /** <add> * @param {Array<THREE.BufferGeometry>} geometry <add> * @return {number} <add> */ <add> getMemoryUse: function ( geometry ) { <add> <add> // Return the estimated memory used by this geometry <add> var mem = 0; <add> for ( var name in geometry.attributes ) { <add> <add> mem += geometry.getAttribute( name ).array.byteLength; <add> <add> } <add> <add> mem += geometry.getIndex() ? geometry.getIndex().array.byteLength : 0; <add> return mem; <add> <ide> } <ide> <ide> };
1
Javascript
Javascript
replace common.fixturesdir with readkey
86d803b3855ef8cf3b14510f484fdbdb17872533
<ide><path>test/parallel/test-http2-https-fallback.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <add>const fixtures = require('../common/fixtures'); <ide> <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> <ide> const { strictEqual } = require('assert'); <del>const { join } = require('path'); <del>const { readFileSync } = require('fs'); <ide> const { createSecureContext } = require('tls'); <ide> const { createSecureServer, connect } = require('http2'); <ide> const { get } = require('https'); <ide> const { connect: tls } = require('tls'); <ide> <ide> const countdown = (count, done) => () => --count === 0 && done(); <ide> <del>function loadKey(keyname) { <del> return readFileSync(join(common.fixturesDir, 'keys', keyname)); <del>} <del> <del>const key = loadKey('agent8-key.pem'); <del>const cert = loadKey('agent8-cert.pem'); <del>const ca = loadKey('fake-startcom-root-cert.pem'); <add>const key = fixtures.readKey('agent8-key.pem'); <add>const cert = fixtures.readKey('agent8-cert.pem'); <add>const ca = fixtures.readKey('fake-startcom-root-cert.pem'); <ide> <ide> const clientOptions = { secureContext: createSecureContext({ ca }) }; <ide>
1
Ruby
Ruby
generate mailer layouts even if no action is given
7a47690a13f403278036f38b69465167466f6b5f
<ide><path>railties/lib/rails/generators/erb/mailer/mailer_generator.rb <ide> def copy_view_files <ide> view_base_path = File.join("app/views", class_path, file_name) <ide> empty_directory view_base_path <ide> <del> layout_base_path = "app/views/layouts" <add> formats.each do |format| <add> layout_path = File.join("app/views/layouts", filename_with_extensions("mailer", format)) <add> template filename_with_extensions(:layout, format), layout_path <add> end <ide> <ide> actions.each do |action| <ide> @action = action <ide> <ide> formats.each do |format| <ide> @path = File.join(view_base_path, filename_with_extensions(action, format)) <ide> template filename_with_extensions(:view, format), @path <del> <del> layout_path = File.join(layout_base_path, filename_with_extensions("mailer", format)) <del> template filename_with_extensions(:layout, format), layout_path <ide> end <ide> end <ide> end <ide><path>railties/test/generators/mailer_generator_test.rb <ide> def test_invokes_default_html_template_engine <ide> def test_invokes_default_template_engine_even_with_no_action <ide> run_generator ["notifier"] <ide> assert_file "app/views/notifier" <add> assert_file "app/views/layouts/mailer.text.erb" <add> assert_file "app/views/layouts/mailer.html.erb" <ide> end <ide> <ide> def test_logs_if_the_template_engine_cannot_be_found
2
Python
Python
make fix copy
e7bff0aabe0ef02296da1c9e1fcbb3f3040196ce
<ide><path>src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py <ide> def forward( <ide> src_len = key_states.size(1) <ide> attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) <ide> <del> assert attn_weights.size() == ( <del> bsz * self.num_heads, <del> tgt_len, <del> src_len, <del> ), f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}" <add> if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len): <add> raise ValueError( <add> f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}" <add> ) <ide> <ide> if attention_mask is not None: <del> assert attention_mask.size() == ( <del> bsz, <del> 1, <del> tgt_len, <del> src_len, <del> ), f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" <add> if attention_mask.size() != (bsz, 1, tgt_len, src_len): <add> raise ValueError( <add> f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" <add> ) <ide> attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask <ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) <ide> <ide> attn_weights = F.softmax(attn_weights, dim=-1) <ide> <ide> if layer_head_mask is not None: <del> assert layer_head_mask.size() == ( <del> self.num_heads, <del> ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}" <add> if layer_head_mask.size() != (self.num_heads,): <add> raise ValueError( <add> f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}" <add> ) <ide> attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) <ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) <ide> <ide> def forward( <ide> <ide> attn_output = torch.bmm(attn_probs, value_states) <ide> <del> assert attn_output.size() == ( <del> bsz * self.num_heads, <del> tgt_len, <del> self.head_dim, <del> ), f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}" <add> if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim): <add> raise ValueError( <add> f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}" <add> ) <ide> <del> attn_output = ( <del> attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) <del> .transpose(1, 2) <del> .reshape(bsz, tgt_len, embed_dim) <del> ) <add> attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) <add> attn_output = attn_output.transpose(1, 2) <add> attn_output = attn_output.reshape(bsz, tgt_len, embed_dim) <ide> <ide> attn_output = self.out_proj(attn_output) <ide>
1
Java
Java
revise use of resolvabletype in methodparameter
b67dbe66ef43e6faca7886a36ebc6f9e9a1fd8f4
<ide><path>spring-core/src/main/java/org/springframework/core/MethodParameter.java <ide> public MethodParameter(Constructor<?> constructor, int parameterIndex, int nesti <ide> * @param containingClass the containing class <ide> * @since 5.2 <ide> */ <del> MethodParameter(Executable executable, int parameterIndex, <del> @Nullable Class<?> containingClass) { <del> <add> MethodParameter(Executable executable, int parameterIndex, @Nullable Class<?> containingClass) { <ide> Assert.notNull(executable, "Executable must not be null"); <ide> this.executable = executable; <ide> this.parameterIndex = validateIndex(executable, parameterIndex); <ide> public Class<?> getParameterType() { <ide> if (paramType != null) { <ide> return paramType; <ide> } <del> if (this.containingClass != null) { <del> paramType = ResolvableType.forMethodParameter(this, null, 1, null).resolve(); <del> } <add> paramType = ResolvableType.forMethodParameter(this, null, 1).resolve(); <ide> if (paramType == null) { <ide> paramType = computeParameterType(); <ide> } <ide> public boolean equals(@Nullable Object other) { <ide> return false; <ide> } <ide> MethodParameter otherParam = (MethodParameter) other; <del> return (this.containingClass == otherParam.containingClass && <add> return (getContainingClass() == otherParam.getContainingClass() && <ide> ObjectUtils.nullSafeEquals(this.typeIndexesPerLevel, otherParam.typeIndexesPerLevel) && <ide> this.nestingLevel == otherParam.nestingLevel && <ide> this.parameterIndex == otherParam.parameterIndex && <ide> static private Class<?> getReturnType(Method method) { <ide> KFunction<?> function = ReflectJvmMapping.getKotlinFunction(method); <ide> if (function != null && function.isSuspend()) { <ide> Type paramType = ReflectJvmMapping.getJavaType(function.getReturnType()); <del> Class<?> paramClass = ResolvableType.forType(paramType).resolve(); <del> Assert.notNull(paramClass, "Type " + paramType + "can't be resolved to a class"); <del> return paramClass; <add> return ResolvableType.forType(paramType).resolve(method.getReturnType()); <ide> } <ide> return method.getReturnType(); <ide> } <ide> } <add> <ide> } <ide><path>spring-core/src/main/java/org/springframework/core/ResolvableType.java <ide> public static ResolvableType forMethodParameter(MethodParameter methodParameter, <ide> */ <ide> public static ResolvableType forMethodParameter(MethodParameter methodParameter, @Nullable Type targetType) { <ide> Assert.notNull(methodParameter, "MethodParameter must not be null"); <del> int nestingLevel = methodParameter.getNestingLevel(); <del> Map<Integer, Integer> typeIndexesPerLevel = methodParameter.typeIndexesPerLevel; <del> return forMethodParameter(methodParameter, targetType, nestingLevel, <del> typeIndexesPerLevel); <add> return forMethodParameter(methodParameter, targetType, methodParameter.getNestingLevel()); <ide> } <ide> <ide> /** <ide> public static ResolvableType forMethodParameter(MethodParameter methodParameter, <ide> * @param methodParameter the source method parameter (must not be {@code null}) <ide> * @param targetType the type to resolve (a part of the method parameter's type) <ide> * @param nestingLevel the nesting level to use <del> * @param typeIndexesPerLevel the type indexes per nesting level <ide> * @return a {@link ResolvableType} for the specified method parameter <ide> * @since 5.2 <ide> * @see #forMethodParameter(Method, int) <ide> */ <del> static ResolvableType forMethodParameter(MethodParameter methodParameter, @Nullable Type targetType, <del> int nestingLevel, @Nullable Map<Integer, Integer> typeIndexesPerLevel) { <add> static ResolvableType forMethodParameter( <add> MethodParameter methodParameter, @Nullable Type targetType, int nestingLevel) { <add> <ide> ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass()); <ide> return forType(targetType, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()). <del> getNested(nestingLevel, typeIndexesPerLevel); <add> getNested(nestingLevel, methodParameter.typeIndexesPerLevel); <ide> } <ide> <ide> /**
2
Text
Text
update v5.4 changelog
f0d417bfa7a2e78d70c7382bfc51fe02321f0a3e
<ide><path>CHANGELOG-5.4.md <ide> # Release Notes for 5.4.x <ide> <add>## [Unreleased] <add> <add>### Changed <add>- Moved `tap()` method from `Builder` to `BuildsQueries` ([#20384](https://github.com/laravel/framework/pull/20384)) <add>- Made Blade `or` operator case-insensitive ([#20425](https://github.com/laravel/framework/pull/20425)) <add>- Support `$amount = 0` in `Arr::random()` ([#20439](https://github.com/laravel/framework/pull/20439)) <add> <add>### Fixed <add>- Fixed bug when using empty values in `SQLiteGrammar::compileInsert()` ([#20424](https://github.com/laravel/framework/pull/20424)) <add> <add> <ide> ## v5.4.32 (2017-08-03) <ide> <ide> ### Added
1
Ruby
Ruby
fix minor typo
cff0c63d034b79c0d9766356f0532110a12a816c
<ide><path>Library/Homebrew/test/test_integration_cmds.rb <ide> def test_bottle <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <ide> formula_file.write <<-EOS.undent <ide> class Testball < Formula <del> url "https://example.com/testabll-0.1.tar.gz" <add> url "https://example.com/testball-0.1.tar.gz" <ide> end <ide> EOS <ide> HOMEBREW_CACHE.cd do
1
Go
Go
lock all calls to hcsshim to prevent close races
740e26f384fe4fe70b5dd2ec5ef80cfdbafac177
<ide><path>daemon/kill.go <ide> func (daemon *Daemon) Kill(container *container.Container) error { <ide> return nil <ide> } <ide> <del> if container.IsRunning() { <del> container.WaitStop(2 * time.Second) <del> if container.IsRunning() { <del> return err <del> } <add> if _, err2 := container.WaitStop(2 * time.Second); err2 != nil { <add> return err <ide> } <ide> } <ide> <ide><path>daemon/monitor.go <ide> func (daemon *Daemon) AttachStreams(id string, iop libcontainerd.IOPipe) error { <ide> if iop.Stdin != nil { <ide> go func() { <ide> io.Copy(iop.Stdin, stdin) <del> iop.Stdin.Close() <add> if err := iop.Stdin.Close(); err != nil { <add> logrus.Error(err) <add> } <ide> }() <ide> } <ide> } else { <ide> func (daemon *Daemon) AttachStreams(id string, iop libcontainerd.IOPipe) error { <ide> if (c != nil && !c.Config.Tty) || (ec != nil && !ec.Tty && runtime.GOOS == "windows") { <ide> // tty is enabled, so dont close containerd's iopipe stdin. <ide> if iop.Stdin != nil { <del> iop.Stdin.Close() <add> if err := iop.Stdin.Close(); err != nil { <add> logrus.Error(err) <add> } <ide> } <ide> } <ide> } <ide><path>daemon/stop.go <ide> func (daemon *Daemon) containerStop(container *container.Container, seconds int) <ide> stopSignal := container.StopSignal() <ide> // 1. Send a stop signal <ide> if err := daemon.killPossiblyDeadProcess(container, stopSignal); err != nil { <del> logrus.Infof("Failed to send signal %d to the process, force killing", stopSignal) <del> if err := daemon.killPossiblyDeadProcess(container, 9); err != nil { <del> return err <add> // While normally we might "return err" here we're not going to <add> // because if we can't stop the container by this point then <add> // its probably because its already stopped. Meaning, between <add> // the time of the IsRunning() call above and now it stopped. <add> // Also, since the err return will be environment specific we can't <add> // look for any particular (common) error that would indicate <add> // that the process is already dead vs something else going wrong. <add> // So, instead we'll give it up to 2 more seconds to complete and if <add> // by that time the container is still running, then the error <add> // we got is probably valid and so we force kill it. <add> if _, err := container.WaitStop(2 * time.Second); err != nil { <add> logrus.Infof("Container failed to stop after sending signal %d to the process, force killing", stopSignal) <add> if err := daemon.killPossiblyDeadProcess(container, 9); err != nil { <add> return err <add> } <ide> } <ide> } <ide> <ide><path>libcontainerd/client.go <ide> func (clnt *client) appendContainer(cont *container) { <ide> clnt.containers[cont.containerID] = cont <ide> clnt.mapMutex.Unlock() <ide> } <del>func (clnt *client) deleteContainer(friendlyName string) { <add>func (clnt *client) deleteContainer(containerID string) { <ide> clnt.mapMutex.Lock() <del> delete(clnt.containers, friendlyName) <add> delete(clnt.containers, containerID) <ide> clnt.mapMutex.Unlock() <ide> } <ide> <ide><path>libcontainerd/client_windows.go <ide> const defaultOwner = "docker" <ide> // Create is the entrypoint to create a container from a spec, and if successfully <ide> // created, start it too. <ide> func (clnt *client) Create(containerID string, checkpoint string, checkpointDir string, spec Spec, options ...CreateOption) error { <add> clnt.lock(containerID) <add> defer clnt.unlock(containerID) <ide> logrus.Debugln("libcontainerd: client.Create() with spec", spec) <ide> <ide> configuration := &hcsshim.ContainerConfig{ <ide> func (clnt *client) AddProcess(ctx context.Context, containerID, processFriendly <ide> return err <ide> } <ide> <add> pid := newProcess.Pid() <add> openedProcess, err := container.hcsContainer.OpenProcess(pid) <add> if err != nil { <add> logrus.Errorf("AddProcess %s OpenProcess() failed %s", containerID, err) <add> return err <add> } <add> <ide> stdin, stdout, stderr, err = newProcess.Stdio() <ide> if err != nil { <ide> logrus.Errorf("libcontainerd: %s getting std pipes failed %s", containerID, err) <ide> func (clnt *client) AddProcess(ctx context.Context, containerID, processFriendly <ide> iopipe.Stderr = openReaderFromPipe(stderr) <ide> } <ide> <del> pid := newProcess.Pid() <del> <ide> proc := &process{ <ide> processCommon: processCommon{ <ide> containerID: containerID, <ide> func (clnt *client) AddProcess(ctx context.Context, containerID, processFriendly <ide> systemPid: uint32(pid), <ide> }, <ide> commandLine: createProcessParms.CommandLine, <del> hcsProcess: newProcess, <add> hcsProcess: openedProcess, <ide> } <ide> <ide> // Add the process to the container's list of processes <ide> func (clnt *client) Signal(containerID string, sig int) error { <ide> err error <ide> ) <ide> <del> // Get the container as we need it to find the pid of the process. <add> // Get the container as we need it to get the container handle. <ide> clnt.lock(containerID) <ide> defer clnt.unlock(containerID) <ide> if cont, err = clnt.getContainer(containerID); err != nil { <ide><path>libcontainerd/container_windows.go <ide> func (ctr *container) newProcess(friendlyName string) *process { <ide> } <ide> } <ide> <add>// start starts a created container. <add>// Caller needs to lock container ID before calling this method. <ide> func (ctr *container) start() error { <ide> var err error <ide> isServicing := false <ide> func (ctr *container) start() error { <ide> createProcessParms.CommandLine = strings.Join(ctr.ociSpec.Process.Args, " ") <ide> <ide> // Start the command running in the container. <del> hcsProcess, err := ctr.hcsContainer.CreateProcess(createProcessParms) <add> newProcess, err := ctr.hcsContainer.CreateProcess(createProcessParms) <ide> if err != nil { <ide> logrus.Errorf("libcontainerd: CreateProcess() failed %s", err) <ide> if err := ctr.terminate(); err != nil { <ide> func (ctr *container) start() error { <ide> } <ide> ctr.startedAt = time.Now() <ide> <add> pid := newProcess.Pid() <add> openedProcess, err := ctr.hcsContainer.OpenProcess(pid) <add> if err != nil { <add> logrus.Errorf("OpenProcess() failed %s", err) <add> if err := ctr.terminate(); err != nil { <add> logrus.Errorf("Failed to cleanup after a failed OpenProcess. %s", err) <add> } else { <add> logrus.Debugln("Cleaned up after failed OpenProcess by calling Terminate") <add> } <add> return err <add> } <add> <ide> // Save the hcs Process and PID <ide> ctr.process.friendlyName = InitFriendlyName <del> pid := hcsProcess.Pid() <del> ctr.process.hcsProcess = hcsProcess <add> ctr.process.hcsProcess = openedProcess <ide> <ide> // If this is a servicing container, wait on the process synchronously here and <ide> // if it succeeds, wait for it cleanly shutdown and merge into the parent container. <ide> func (ctr *container) start() error { <ide> <ide> var stdout, stderr io.ReadCloser <ide> var stdin io.WriteCloser <del> stdin, stdout, stderr, err = hcsProcess.Stdio() <add> stdin, stdout, stderr, err = newProcess.Stdio() <ide> if err != nil { <ide> logrus.Errorf("libcontainerd: failed to get stdio pipes: %s", err) <ide> if err := ctr.terminate(); err != nil { <ide> func (ctr *container) start() error { <ide> <ide> iopipe := &IOPipe{Terminal: ctr.ociSpec.Process.Terminal} <ide> <del> iopipe.Stdin = createStdInCloser(stdin, hcsProcess) <add> iopipe.Stdin = createStdInCloser(stdin, newProcess) <ide> <ide> // Convert io.ReadClosers to io.Readers <ide> if stdout != nil { <ide> func (ctr *container) start() error { <ide> State: StateStart, <ide> Pid: ctr.systemPid, // Not sure this is needed? Double-check monitor.go in daemon BUGBUG @jhowardmsft <ide> }} <add> logrus.Debugf("libcontainerd: start() completed OK, %+v", si) <ide> return ctr.client.backend.StateChanged(ctr.containerID, si) <ide> <ide> } <ide> func (ctr *container) waitProcessExitCode(process *process) int { <ide> // has exited to avoid a container being dropped on the floor. <ide> } <ide> <del> if err := process.hcsProcess.Close(); err != nil { <del> logrus.Errorf("libcontainerd: hcsProcess.Close(): %v", err) <del> } <del> <ide> return exitCode <ide> } <ide> <ide> func (ctr *container) waitExit(process *process, isFirstProcessToStart bool) err <ide> logrus.Debugln("libcontainerd: waitExit() on pid", process.systemPid) <ide> <ide> exitCode := ctr.waitProcessExitCode(process) <add> // Lock the container while shutting down <add> ctr.client.lock(ctr.containerID) <ide> <ide> // Assume the container has exited <ide> si := StateInfo{ <ide> func (ctr *container) waitExit(process *process, isFirstProcessToStart bool) err <ide> // But it could have been an exec'd process which exited <ide> if !isFirstProcessToStart { <ide> si.State = StateExitProcess <add> ctr.cleanProcess(process.friendlyName) <ide> } else { <ide> updatePending, err := ctr.hcsContainer.HasPendingUpdates() <ide> if err != nil { <ide> func (ctr *container) waitExit(process *process, isFirstProcessToStart bool) err <ide> } else if restart { <ide> si.State = StateRestart <ide> ctr.restarting = true <add> ctr.client.deleteContainer(ctr.containerID) <ide> waitRestart = wait <ide> } <ide> } <ide> <ide> // Remove process from list if we have exited <ide> // We need to do so here in case the Message Handler decides to restart it. <ide> if si.State == StateExit { <del> ctr.client.deleteContainer(ctr.friendlyName) <add> ctr.client.deleteContainer(ctr.containerID) <ide> } <ide> } <ide> <add> if err := process.hcsProcess.Close(); err != nil { <add> logrus.Errorf("libcontainerd: hcsProcess.Close(): %v", err) <add> } <add> <add> // Unlock here before we call back into the daemon to update state <add> ctr.client.unlock(ctr.containerID) <add> <ide> // Call into the backend to notify it of the state change. <ide> logrus.Debugf("libcontainerd: waitExit() calling backend.StateChanged %+v", si) <ide> if err := ctr.client.backend.StateChanged(ctr.containerID, si); err != nil { <ide> func (ctr *container) waitExit(process *process, isFirstProcessToStart bool) err <ide> go func() { <ide> err := <-waitRestart <ide> ctr.restarting = false <del> ctr.client.deleteContainer(ctr.friendlyName) <ide> if err == nil { <ide> if err = ctr.client.Create(ctr.containerID, "", "", ctr.ociSpec, ctr.options...); err != nil { <ide> logrus.Errorf("libcontainerd: error restarting %v", err) <ide> func (ctr *container) waitExit(process *process, isFirstProcessToStart bool) err <ide> return nil <ide> } <ide> <add>// cleanProcess removes process from the map. <add>// Caller needs to lock container ID before calling this method. <add>func (ctr *container) cleanProcess(id string) { <add> delete(ctr.processes, id) <add>} <add> <add>// shutdown shuts down the container in HCS <add>// Caller needs to lock container ID before calling this method. <ide> func (ctr *container) shutdown() error { <ide> const shutdownTimeout = time.Minute * 5 <ide> err := ctr.hcsContainer.Shutdown() <ide> func (ctr *container) shutdown() error { <ide> return nil <ide> } <ide> <add>// terminate terminates the container in HCS <add>// Caller needs to lock container ID before calling this method. <ide> func (ctr *container) terminate() error { <ide> const terminateTimeout = time.Minute * 5 <ide> err := ctr.hcsContainer.Terminate() <ide><path>libcontainerd/process_windows.go <ide> import ( <ide> "io" <ide> <ide> "github.com/Microsoft/hcsshim" <add> "github.com/docker/docker/pkg/ioutils" <ide> ) <ide> <ide> // process keeps the state for both main container process and exec process. <ide> func openReaderFromPipe(p io.ReadCloser) io.Reader { <ide> return r <ide> } <ide> <del>type stdInCloser struct { <del> io.WriteCloser <del> hcsshim.Process <del>} <del> <del>func createStdInCloser(pipe io.WriteCloser, process hcsshim.Process) *stdInCloser { <del> return &stdInCloser{ <del> WriteCloser: pipe, <del> Process: process, <del> } <del>} <del> <del>func (stdin *stdInCloser) Close() error { <del> if err := stdin.WriteCloser.Close(); err != nil { <del> return err <del> } <add>func createStdInCloser(pipe io.WriteCloser, process hcsshim.Process) io.WriteCloser { <add> return ioutils.NewWriteCloserWrapper(pipe, func() error { <add> if err := pipe.Close(); err != nil { <add> return err <add> } <ide> <del> return stdin.Process.CloseStdin() <del>} <add> // We do not need to lock container ID here, even though <add> // we are calling into hcsshim. This is safe, because the <add> // only place that closes this process handle is this method. <add> err := process.CloseStdin() <add> if err != nil && !hcsshim.IsNotExist(err) { <add> // This error will occur if the compute system is currently shutting down <add> if perr, ok := err.(*hcsshim.ProcessError); ok && perr.Err != hcsshim.ErrVmcomputeOperationInvalidState { <add> return err <add> } <add> } <ide> <del>func (stdin *stdInCloser) Write(p []byte) (n int, err error) { <del> return stdin.WriteCloser.Write(p) <add> return process.Close() <add> }) <ide> }
7
Text
Text
fix typo in stream docs
3ef2e7aca41af2f7b44f6d19e344efe1e9ad6c2b
<ide><path>doc/api/stream.md <ide> user programs. <ide> #### `writable._writev(chunks, callback)` <ide> <ide> * `chunks` {Object[]} The data to be written. The value is an array of {Object} <del> that each represent a discreet chunk of data to write. The properties of <add> that each represent a discrete chunk of data to write. The properties of <ide> these objects are: <ide> * `chunk` {Buffer|string} A buffer instance or string containing the data to <ide> be written. The `chunk` will be a string if the `Writable` was created with
1
Ruby
Ruby
allow blank queue names
4a1dbba108ece1a957b26d1e6280c1a8cd986fe8
<ide><path>activejob/lib/active_job/queue_name.rb <ide> def queue_as(part_name=nil, &block) <ide> end <ide> <ide> def queue_name_from_part(part_name) #:nodoc: <del> queue_name = part_name.to_s.presence || default_queue_name <add> queue_name = part_name || default_queue_name <ide> name_parts = [queue_name_prefix.presence, queue_name] <ide> name_parts.compact.join('_') <ide> end <ide><path>activejob/test/cases/queue_naming_test.rb <ide> class QueueNamingTest < ActiveSupport::TestCase <ide> end <ide> end <ide> <add> test 'allows a blank queue name' do <add> begin <add> original_queue_name = HelloJob.queue_name <add> HelloJob.queue_as "" <add> assert_equal "", HelloJob.new.queue_name <add> ensure <add> HelloJob.queue_name = original_queue_name <add> end <add> end <add> <add> test 'does not use a nil queue name' do <add> begin <add> original_queue_name = HelloJob.queue_name <add> HelloJob.queue_as nil <add> assert_equal "default", HelloJob.new.queue_name <add> ensure <add> HelloJob.queue_name = original_queue_name <add> end <add> end <add> <ide> test 'evals block given to queue_as to determine queue' do <ide> begin <ide> original_queue_name = HelloJob.queue_name
2
Javascript
Javascript
use isnone to check tag name
6c446205090966f6838cdd1576e677aadf64411f
<ide><path>packages/ember-views/lib/views/view.js <ide> Ember.CoreView = Ember.Object.extend(Ember.Evented, { <ide> // insert a new buffer after the "parent buffer"). <ide> var tagName = this.tagName; <ide> <del> if (tagName === null || tagName === undefined) { <add> if (Ember.isNone(tagName)) { <ide> tagName = 'div'; <ide> } <ide>
1
Mixed
Ruby
improve performance of #one? and #many?
b3caf0c99aea48f6738777f722863159058ec3be
<ide><path>activerecord/CHANGELOG.md <add>* Improve performance of `one?` and `many?` by limiting the generated count query to 2 results. <add> <add> *Gonzalo Riestra* <add> <ide> * Don't check type when using `if_not_exists` on `add_column`. <ide> <ide> Previously, if a migration called `add_column` with the `if_not_exists` option set to true <ide><path>activerecord/lib/active_record/relation.rb <ide> def initialize(klass, table: klass.arel_table, predicate_builder: klass.predicat <ide> @delegate_to_klass = false <ide> @future_result = nil <ide> @records = nil <add> @limited_count = nil <ide> end <ide> <ide> def initialize_copy(other) <ide> def any? <ide> # Returns true if there is exactly one record. <ide> def one? <ide> return super if block_given? <del> limit_value ? records.one? : size == 1 <add> return records.one? if limit_value || loaded? <add> limited_count == 1 <ide> end <ide> <ide> # Returns true if there is more than one record. <ide> def many? <ide> return super if block_given? <del> limit_value ? records.many? : size > 1 <add> return records.many? if limit_value || loaded? <add> limited_count > 1 <ide> end <ide> <ide> # Returns a stable cache key that can be used to identify this query. <ide> def reset <ide> @offsets = @take = nil <ide> @cache_keys = nil <ide> @records = nil <add> @limited_count = nil <ide> self <ide> end <ide> <ide> def tables_in_string(string) <ide> # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries <ide> string.scan(/[a-zA-Z_][.\w]+(?=.?\.)/).map!(&:downcase) - ["raw_sql_"] <ide> end <add> <add> def limited_count <add> @limited_count ||= limit(2).count <add> end <ide> end <ide> end <ide><path>activerecord/test/cases/associations/has_many_associations_test.rb <ide> def test_calling_many_on_loaded_association_should_not_use_query <ide> assert_no_queries { assert firm.clients.many? } <ide> end <ide> <add> def test_subsequent_calls_to_many_should_not_use_query <add> firm = companies(:first_firm) <add> assert_queries(1) do <add> firm.clients.many? <add> firm.clients.many? <add> end <add> end <add> <ide> def test_calling_many_should_defer_to_collection_if_using_a_block <ide> firm = companies(:first_firm) <ide> assert_queries(1) do <ide> def test_calling_one_on_loaded_association_should_not_use_query <ide> assert_no_queries { assert_not firm.clients.one? } <ide> end <ide> <add> def test_subsequent_calls_to_one_should_not_use_query <add> firm = companies(:first_firm) <add> assert_queries(1) do <add> firm.clients.one? <add> firm.clients.one? <add> end <add> end <add> <ide> def test_calling_one_should_defer_to_collection_if_using_a_block <ide> firm = companies(:first_firm) <ide> assert_queries(1) do
3
Ruby
Ruby
build native addons from source
02113e2714aae818ee2c43e203137b3cd0b61ced
<ide><path>Library/Homebrew/language/node.rb <ide> def self.std_npm_install_args(libexec) <ide> %W[ <ide> -ddd <ide> --global <add> --build-from-source <ide> --prefix=#{libexec} <ide> #{Dir.pwd}/#{pack} <ide> ] <ide> def self.std_npm_install_args(libexec) <ide> def self.local_npm_install_args <ide> setup_npm_environment <ide> # npm install args for local style module format <del> ["-ddd"] <add> %w[ <add> -ddd <add> --build-from-source <add> ] <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/test/language/node_spec.rb <ide> <ide> specify "#local_npm_install_args" do <ide> resp = subject.local_npm_install_args <del> expect(resp).to include("-ddd") <add> expect(resp).to include("-ddd", "--build-from-source") <ide> end <ide> end
2
PHP
PHP
improve behavior of mysql flag, add config
318a04646baea45d8d3d2e52fbdf08339d56061e
<ide><path>src/Illuminate/Database/Connectors/MySqlConnector.php <ide> <ide> namespace Illuminate\Database\Connectors; <ide> <add>use PDO; <add> <ide> class MySqlConnector extends Connector implements ConnectorInterface <ide> { <ide> /** <ide> public function connect(array $config) <ide> )->execute(); <ide> } <ide> <del> // If the "strict" option has been configured for the connection we will setup <del> // strict mode for this session. Strict mode enforces some extra rules when <del> // using the MySQL database system and is a quicker way to enforce them. <del> if (isset($config['strict'])) { <del> if ($config['strict']) { <del> $connection->prepare("set session sql_mode='STRICT_ALL_TABLES'")->execute(); <del> } else { <del> $connection->prepare("set session sql_mode=''")->execute(); <del> } <del> } <add> $this->setModes($connection, $config); <ide> <ide> return $connection; <ide> } <ide> protected function getHostDsn(array $config) <ide> ? "mysql:host={$host};port={$port};dbname={$database}" <ide> : "mysql:host={$host};dbname={$database}"; <ide> } <add> <add> /** <add> * Set the modes for the connection. <add> * <add> * @param \PDO $connection <add> * @param array $config <add> * @return void <add> */ <add> protected function setModes(PDO $connection, array $config) <add> { <add> if (isset($config['modes'])) { <add> $modes = implode(',', $config['modes']); <add> $connection->prepare("set session sql_mode='".$modes."'")->execute(); <add> } elseif (isset($config['strict'])) { <add> if ($config['strict']) { <add> $connection->prepare("set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'")->execute(); <add> } else { <add> $connection->prepare("set session sql_mode='NO_ENGINE_SUBSTITUTION'")->execute(); <add> } <add> } <add> } <ide> } <ide><path>tests/Database/DatabaseConnectorTest.php <ide> public function testOptionResolution() <ide> public function testMySqlConnectCallsCreateConnectionWithProperArguments($dsn, $config) <ide> { <ide> $connector = $this->getMock('Illuminate\Database\Connectors\MySqlConnector', ['createConnection', 'getOptions']); <del> $connection = m::mock('stdClass'); <add> $connection = m::mock('PDO'); <ide> $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(['options'])); <ide> $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->will($this->returnValue($connection)); <ide> $connection->shouldReceive('prepare')->once()->with('set names \'utf8\' collate \'utf8_unicode_ci\'')->andReturn($connection);
2
Javascript
Javascript
improve serbian latin translation
e686babb12fdc0a5845eb69775485625b85694e9
<ide><path>lang/rs.js <del>// moment.js language configuration <del>// language : serbian (rs) <del>// author : Limon Monte : https://github.com/limonte <del>// based on (bs) translation by Nedim Cholich <del> <del>(function (factory) { <del> if (typeof define === 'function' && define.amd) { <del> define(['moment'], factory); // AMD <del> } else if (typeof exports === 'object') { <del> module.exports = factory(require('../moment')); // Node <del> } else { <del> factory(window.moment); // Browser global <del> } <del>}(function (moment) { <del> <del> function translate(number, withoutSuffix, key) { <del> var result = number + " "; <del> switch (key) { <del> case 'm': <del> return withoutSuffix ? 'jedna minuta' : 'jedne minute'; <del> case 'mm': <del> if (number === 1) { <del> result += 'minuta'; <del> } else if (number === 2 || number === 3 || number === 4) { <del> result += 'minute'; <del> } else { <del> result += 'minuta'; <del> } <del> return result; <del> case 'h': <del> return withoutSuffix ? 'jedan sat' : 'jednog sata'; <del> case 'hh': <del> if (number === 1) { <del> result += 'sat'; <del> } else if (number === 2 || number === 3 || number === 4) { <del> result += 'sata'; <del> } else { <del> result += 'sati'; <del> } <del> return result; <del> case 'dd': <del> if (number === 1) { <del> result += 'dan'; <del> } else { <del> result += 'dana'; <del> } <del> return result; <del> case 'MM': <del> if (number === 1) { <del> result += 'mesec'; <del> } else if (number === 2 || number === 3 || number === 4) { <del> result += 'meseca'; <del> } else { <del> result += 'meseci'; <del> } <del> return result; <del> case 'yy': <del> if (number === 1) { <del> result += 'godina'; <del> } else if (number === 2 || number === 3 || number === 4) { <del> result += 'godine'; <del> } else { <del> result += 'godina'; <del> } <del> return result; <del> } <del> } <del> <del> return moment.lang('rs', { <del> months : "januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar".split("_"), <del> monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), <del> weekdays : "nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota".split("_"), <del> weekdaysShort : "ned._pon._uto._sre._čet._pet._sub.".split("_"), <del> weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), <del> longDateFormat : { <del> LT : "H:mm", <del> L : "DD. MM. YYYY", <del> LL : "D. MMMM YYYY", <del> LLL : "D. MMMM YYYY LT", <del> LLLL : "dddd, D. MMMM YYYY LT" <del> }, <del> calendar : { <del> sameDay : '[danas u] LT', <del> nextDay : '[sutra u] LT', <del> <del> nextWeek : function () { <del> switch (this.day()) { <del> case 0: <del> return '[u] [nedelju] [u] LT'; <del> case 3: <del> return '[u] [sredu] [u] LT'; <del> case 6: <del> return '[u] [subotu] [u] LT'; <del> case 1: <del> case 2: <del> case 4: <del> case 5: <del> return '[u] dddd [u] LT'; <del> } <del> }, <del> lastDay : '[juče u] LT', <del> lastWeek : function () { <del> switch (this.day()) { <del> case 0: <del> case 3: <del> return '[prošlu] dddd [u] LT'; <del> case 6: <del> return '[prošle] [subote] [u] LT'; <del> case 1: <del> case 2: <del> case 4: <del> case 5: <del> return '[prošli] dddd [u] LT'; <del> } <del> }, <del> sameElse : 'L' <del> }, <del> relativeTime : { <del> future : "za %s", <del> past : "pre %s", <del> s : "par sekundi", <del> m : translate, <del> mm : translate, <del> h : translate, <del> hh : translate, <del> d : "dan", <del> dd : translate, <del> M : "mesec", <del> MM : translate, <del> y : "godinu", <del> yy : translate <del> }, <del> ordinal : '%d.', <del> week : { <del> dow : 1, // Monday is the first day of the week. <del> doy : 7 // The week that contains Jan 1st is the first week of the year. <del> } <del> }); <del>})); <ide><path>lang/sr.js <add>// moment.js language configuration <add>// language : Serbian-latin (sr) <add>// author : Milan Janačković<[email protected]> : https://github.com/milan-j <add> <add>(function (factory) { <add> if (typeof define === 'function' && define.amd) { <add> define(['moment'], factory); // AMD <add> } else if (typeof exports === 'object') { <add> module.exports = factory(require('../moment')); // Node <add> } else { <add> factory(window.moment); // Browser global <add> } <add>}(function (moment) { <add> <add> var translator = { <add> words: { //Different grammatical cases <add> m: ['jedan minut', 'jedne minute'], <add> mm: ['minut', 'minute', 'minuta'], <add> h: ['jedan sat', 'jednog sata'], <add> hh: ['sat', 'sata', 'sati'], <add> dd: ['dan', 'dana', 'dana'], <add> MM: ['mesec', 'meseca', 'meseci'], <add> yy: ['godina', 'godine', 'godina'] <add> }, <add> correctGrammaticalCase: function (number, wordKey) { <add> return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); <add> }, <add> translate: function (number, withoutSuffix, key) { <add> var wordKey = translator.words[key]; <add> if (key.length === 1) { <add> return withoutSuffix ? wordKey[0] : wordKey[1]; <add> } else { <add> return number + ' ' + translator.correctGrammaticalCase(number, wordKey); <add> } <add> } <add> }; <add> <add> return moment.lang('sr', { <add> months: ['januar', 'februar', 'mart', 'april', 'maj', 'jun', 'jul', 'avgust', 'septembar', 'oktobar', 'novembar', 'decembar'], <add> monthsShort: ['jan.', 'feb.', 'mar.', 'apr.', 'maj', 'jun', 'jul', 'avg.', 'sep.', 'okt.', 'nov.', 'dec.'], <add> weekdays: ['nedelja', 'ponedeljak', 'utorak', 'sreda', 'četvrtak', 'petak', 'subota'], <add> weekdaysShort: ['ned.', 'pon.', 'uto.', 'sre.', 'čet.', 'pet.', 'sub.'], <add> weekdaysMin: ['ne', 'po', 'ut', 'sr', 'če', 'pe', 'su'], <add> longDateFormat: { <add> LT: "H:mm", <add> L: "DD. MM. YYYY", <add> LL: "D. MMMM YYYY", <add> LLL: "D. MMMM YYYY LT", <add> LLLL: "dddd, D. MMMM YYYY LT" <add> }, <add> calendar: { <add> sameDay: '[danas u] LT', <add> nextDay: '[sutra u] LT', <add> <add> nextWeek: function () { <add> switch (this.day()) { <add> case 0: <add> return '[u] [nedelju] [u] LT'; <add> case 3: <add> return '[u] [sredu] [u] LT'; <add> case 6: <add> return '[u] [subotu] [u] LT'; <add> case 1: <add> case 2: <add> case 4: <add> case 5: <add> return '[u] dddd [u] LT'; <add> } <add> }, <add> lastDay : '[juče u] LT', <add> lastWeek : function () { <add> var lastWeekDays = [ <add> '[prošle] [nedelje] [u] LT', <add> '[prošlog] [ponedeljka] [u] LT', <add> '[prošlog] [utorka] [u] LT', <add> '[prošle] [srede] [u] LT', <add> '[prošlog] [četvrtka] [u] LT', <add> '[prošlog] [petka] [u] LT', <add> '[prošle] [subote] [u] LT' <add> ]; <add> return lastWeekDays[this.day()]; <add> }, <add> sameElse : 'L' <add> }, <add> relativeTime : { <add> future : "za %s", <add> past : "pre %s", <add> s : "nekoliko sekundi", <add> m : translator.translate, <add> mm : translator.translate, <add> h : translator.translate, <add> hh : translator.translate, <add> d : "dan", <add> dd : translator.translate, <add> M : "mesec", <add> MM : translator.translate, <add> y : "godinu", <add> yy : translator.translate <add> }, <add> ordinal : '%d.', <add> week : { <add> dow : 1, // Monday is the first day of the week. <add> doy : 7 // The week that contains Jan 1st is the first week of the year. <add> } <add> }); <add>})); <add><path>test/lang/sr.js <del><path>test/lang/rs.js <ide> var moment = require("../../moment"); <ide> <ide> <ide> /************************************************** <del> Serbian <add> Serbian-latin (sr) <ide> *************************************************/ <ide> <del>exports["lang:rs"] = { <add>exports["lang:sr"] = { <ide> setUp : function (cb) { <del> moment.lang('rs'); <add> moment.lang('sr-lat'); <ide> cb(); <ide> }, <ide> <ide> exports["lang:rs"] = { <ide> "parse" : function (test) { <ide> test.expect(96); <ide> <del> var tests = 'januar jan._februar feb._mart mar._april apr._maj maj._jun jun._jul jul._avgust avg._septembar sep._oktobar okt._novembar nov._decembar dec.'.split("_"), i; <add> var tests = 'januar jan._februar feb._mart mar._april apr._maj maj_jun jun_jul jul_avgust avg._septembar sep._oktobar okt._novembar nov._decembar dec.'.split("_"), <add> i; <ide> function equalTest(input, mmm, i) { <ide> test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); <ide> } <ide> exports["lang:rs"] = { <ide> <ide> "format month" : function (test) { <ide> test.expect(12); <del> var expected = 'januar jan._februar feb._mart mar._april apr._maj maj._jun jun._jul jul._avgust avg._septembar sep._oktobar okt._novembar nov._decembar dec.'.split("_"), i; <add> var expected = 'januar jan._februar feb._mart mar._april apr._maj maj_jun jun_jul jul_avgust avg._septembar sep._oktobar okt._novembar nov._decembar dec.'.split("_"), <add> i; <ide> for (i = 0; i < expected.length; i++) { <ide> test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); <ide> } <ide> exports["lang:rs"] = { <ide> <ide> "format week" : function (test) { <ide> test.expect(7); <del> var expected = 'nedelja ned. ne_ponedeljak pon. po_utorak uto. ut_sreda sre. sr_četvrtak čet. če_petak pet. pe_subota sub. su'.split("_"), i; <add> var expected = 'nedelja ned. ne_ponedeljak pon. po_utorak uto. ut_sreda sre. sr_četvrtak čet. če_petak pet. pe_subota sub. su'.split("_"), <add> i; <ide> for (i = 0; i < expected.length; i++) { <ide> test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); <ide> } <ide> exports["lang:rs"] = { <ide> "from" : function (test) { <ide> test.expect(30); <ide> var start = moment([2007, 1, 28]); <del> test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "par sekundi", "44 seconds = a few seconds"); <del> test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), "jedna minuta", "45 seconds = a minute"); <del> test.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), "jedna minuta", "89 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "nekoliko sekundi", "44 seconds = a few seconds"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), "jedan minut", "45 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), "jedan minut", "89 seconds = a minute"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), "2 minute", "90 seconds = 2 minutes"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), "44 minuta", "44 minutes = 44 minutes"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), "jedan sat", "45 minutes = an hour"); <ide> exports["lang:rs"] = { <ide> <ide> "suffix" : function (test) { <ide> test.expect(2); <del> test.equal(moment(30000).from(0), "za par sekundi", "prefix"); <del> test.equal(moment(0).from(30000), "pre par sekundi", "prefix"); <add> test.equal(moment(30000).from(0), "za nekoliko sekundi", "prefix"); <add> test.equal(moment(0).from(30000), "pre nekoliko sekundi", "prefix"); <ide> test.done(); <ide> }, <ide> <ide> "now from now" : function (test) { <ide> test.expect(1); <del> test.equal(moment().fromNow(), "pre par sekundi", "now from now should display as in the past"); <add> test.equal(moment().fromNow(), "pre nekoliko sekundi", "now from now should display as in the past"); <ide> test.done(); <ide> }, <ide> <ide> "fromNow" : function (test) { <ide> test.expect(2); <del> test.equal(moment().add({s: 30}).fromNow(), "za par sekundi", "in a few seconds"); <add> test.equal(moment().add({s: 30}).fromNow(), "za nekoliko sekundi", "in a few seconds"); <ide> test.equal(moment().add({d: 5}).fromNow(), "za 5 dana", "in 5 days"); <ide> test.done(); <ide> }, <ide> exports["lang:rs"] = { <ide> var i, m; <ide> <ide> function makeFormat(d) { <del> switch (d.day()) { <del> case 0: <del> case 3: <del> return '[prošlu] dddd [u] LT'; <del> case 6: <del> return '[prošle] [subote] [u] LT'; <del> case 1: <del> case 2: <del> case 4: <del> case 5: <del> return '[prošli] dddd [u] LT'; <del> } <add> var lastWeekDay = [ <add> '[prošle] [nedelje] [u] LT', <add> '[prošlog] [ponedeljka] [u] LT', <add> '[prošlog] [utorka] [u] LT', <add> '[prošle] [srede] [u] LT', <add> '[prošlog] [četvrtka] [u] LT', <add> '[prošlog] [petka] [u] LT', <add> '[prošle] [subote] [u] LT' <add> ]; <add> <add> return lastWeekDay[d.day()]; <ide> } <ide> <ide> for (i = 2; i < 7; i++) { <ide> exports["lang:rs"] = { <ide> <ide> "returns the name of the language" : function (test) { <ide> if (typeof module !== 'undefined' && module.exports) { <del> test.equal(require('../../lang/rs'), 'rs', "module should export rs"); <add> test.equal(require('../../lang/sr'), 'sr', "module should export sr"); <ide> } <ide> <ide> test.done();
3
Javascript
Javascript
fix more name collisions
0ad05043f5f268c6241d34997ca8773b1e88357b
<ide><path>packager/blacklist.js <ide> var sharedBlacklist = [ <ide> 'downstream/core/createArrayFromMixed.js', <ide> 'downstream/core/toArray.js', <ide> 'downstream/core/dom/getActiveElement.js', <add> 'downstream/core/dom/focusNode.js', <add> 'downstream/core/dom/getUnboundedScrollPosition.js', <add> 'downstream/core/createNodesFromMarkup.js', <add> 'downstream/core/CSSCore.js', <add> 'downstream/core/getMarkupWrap.js', <add> 'downstream/core/hyphenateStyleName.js', <ide> ]; <ide> <ide> // Raw unescaped patterns in case you need to use wildcards
1
Python
Python
fix typo in fsmt tokenizer
61d3928bfb3029bceb5be3e68ca3d4bf8456758f
<ide><path>src/transformers/models/fsmt/tokenization_fsmt.py <ide> def moses_tokenize(self, text, lang): <ide> ) <ide> <ide> def moses_detokenize(self, tokens, lang): <del> if lang not in self.cache_moses_tokenizer: <del> moses_detokenizer = self.sm.MosesDetokenizer(lang=self.tgt_lang) <add> if lang not in self.cache_moses_detokenizer: <add> moses_detokenizer = self.sm.MosesDetokenizer(lang=lang) <ide> self.cache_moses_detokenizer[lang] = moses_detokenizer <ide> return self.cache_moses_detokenizer[lang].detokenize(tokens) <ide>
1
Ruby
Ruby
remove the reference to mocha in activemodel
ec7771e7f6a5e33b73c9cc713ed3772a7ef0fb12
<ide><path>activemodel/test/cases/validations/i18n_validation_test.rb <ide> def test_errors_full_messages_uses_format <ide> [ "given option that is not reserved", { format: "jpg" }, { format: "jpg" }] <ide> ] <ide> <del> # validates_confirmation_of w/ mocha <add> # validates_confirmation_of w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_confirmation_of on generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_acceptance_of w/ mocha <add> # validates_acceptance_of w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_acceptance_of on generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_presence_of w/ mocha <add> # validates_presence_of w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_presence_of on generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_length_of :within too short w/ mocha <add> # validates_length_of :within too short w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_length_of for :within on generated message when too short #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_length_of :within too long w/ mocha <add> # validates_length_of :within too long w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_length_of for :too_long generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_length_of :is w/ mocha <add> # validates_length_of :is w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_length_of for :is on generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_format_of w/ mocha <add> # validates_format_of w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_format_of on generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_inclusion_of w/ mocha <add> # validates_inclusion_of w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_inclusion_of on generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_inclusion_of using :within w/ mocha <add> # validates_inclusion_of using :within w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_inclusion_of using :within on generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_exclusion_of w/ mocha <add> # validates_exclusion_of w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_exclusion_of generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_exclusion_of using :within w/ mocha <add> # validates_exclusion_of using :within w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_exclusion_of using :within generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_numericality_of without :only_integer w/ mocha <add> # validates_numericality_of without :only_integer w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_numericality_of generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_numericality_of with :only_integer w/ mocha <add> # validates_numericality_of with :only_integer w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_numericality_of for :only_integer on generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_numericality_of :odd w/ mocha <add> # validates_numericality_of :odd w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_numericality_of for :odd on generated message #{name}" do <ide> def test_errors_full_messages_uses_format <ide> end <ide> end <ide> <del> # validates_numericality_of :less_than w/ mocha <add> # validates_numericality_of :less_than w/ mocks <ide> <ide> COMMON_CASES.each do |name, validation_options, generate_message_options| <ide> test "validates_numericality_of for :less_than on generated message #{name}" do <ide> def self.set_expectations_for_validation(validation, error_type, &block_that_set <ide> end <ide> end <ide> <del> # validates_confirmation_of w/o mocha <add> # validates_confirmation_of w/o mocks <ide> <ide> set_expectations_for_validation "validates_confirmation_of", :confirmation do |person, options_to_merge| <ide> Person.validates_confirmation_of :title, options_to_merge <ide> person.title_confirmation = 'foo' <ide> end <ide> <del> # validates_acceptance_of w/o mocha <add> # validates_acceptance_of w/o mocks <ide> <ide> set_expectations_for_validation "validates_acceptance_of", :accepted do |person, options_to_merge| <ide> Person.validates_acceptance_of :title, options_to_merge.merge(allow_nil: false) <ide> end <ide> <del> # validates_presence_of w/o mocha <add> # validates_presence_of w/o mocks <ide> <ide> set_expectations_for_validation "validates_presence_of", :blank do |person, options_to_merge| <ide> Person.validates_presence_of :title, options_to_merge <ide> end <ide> <del> # validates_length_of :within w/o mocha <add> # validates_length_of :within w/o mocks <ide> <ide> set_expectations_for_validation "validates_length_of", :too_short do |person, options_to_merge| <ide> Person.validates_length_of :title, options_to_merge.merge(within: 3..5) <ide> def self.set_expectations_for_validation(validation, error_type, &block_that_set <ide> person.title = "too long" <ide> end <ide> <del> # validates_length_of :is w/o mocha <add> # validates_length_of :is w/o mocks <ide> <ide> set_expectations_for_validation "validates_length_of", :wrong_length do |person, options_to_merge| <ide> Person.validates_length_of :title, options_to_merge.merge(is: 5) <ide> end <ide> <del> # validates_format_of w/o mocha <add> # validates_format_of w/o mocks <ide> <ide> set_expectations_for_validation "validates_format_of", :invalid do |person, options_to_merge| <ide> Person.validates_format_of :title, options_to_merge.merge(with: /\A[1-9][0-9]*\z/) <ide> end <ide> <del> # validates_inclusion_of w/o mocha <add> # validates_inclusion_of w/o mocks <ide> <ide> set_expectations_for_validation "validates_inclusion_of", :inclusion do |person, options_to_merge| <ide> Person.validates_inclusion_of :title, options_to_merge.merge(in: %w(a b c)) <ide> end <ide> <del> # validates_exclusion_of w/o mocha <add> # validates_exclusion_of w/o mocks <ide> <ide> set_expectations_for_validation "validates_exclusion_of", :exclusion do |person, options_to_merge| <ide> Person.validates_exclusion_of :title, options_to_merge.merge(in: %w(a b c)) <ide> person.title = 'a' <ide> end <ide> <del> # validates_numericality_of without :only_integer w/o mocha <add> # validates_numericality_of without :only_integer w/o mocks <ide> <ide> set_expectations_for_validation "validates_numericality_of", :not_a_number do |person, options_to_merge| <ide> Person.validates_numericality_of :title, options_to_merge <ide> person.title = 'a' <ide> end <ide> <del> # validates_numericality_of with :only_integer w/o mocha <add> # validates_numericality_of with :only_integer w/o mocks <ide> <ide> set_expectations_for_validation "validates_numericality_of", :not_an_integer do |person, options_to_merge| <ide> Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true) <ide> person.title = '1.0' <ide> end <ide> <del> # validates_numericality_of :odd w/o mocha <add> # validates_numericality_of :odd w/o mocks <ide> <ide> set_expectations_for_validation "validates_numericality_of", :odd do |person, options_to_merge| <ide> Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true, odd: true) <ide> person.title = 0 <ide> end <ide> <del> # validates_numericality_of :less_than w/o mocha <add> # validates_numericality_of :less_than w/o mocks <ide> <ide> set_expectations_for_validation "validates_numericality_of", :less_than do |person, options_to_merge| <ide> Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true, less_than: 0)
1
Javascript
Javascript
send data if a delete ajax request is done. fixes
23492fdf9fa6f2c3b8ee85d062fed74297f3c438
<ide><path>src/ajax.js <ide> jQuery.extend({ <ide> <ide> // Send the data <ide> try { <del> xhr.send( type === "POST" || type === "PUT" ? s.data : null ); <add> xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null ); <ide> } catch(e) { <ide> jQuery.handleError(s, xhr, null, e); <ide> // Fire the complete handlers
1
Text
Text
add full solution code to jquery challenges
058db4f44994140837780d4e3ecf0b4e6e72441f
<ide><path>guide/english/certifications/front-end-libraries/jquery/change-text-inside-an-element-using-jquery/index.md <ide> title: Change Text Inside an Element Using jQuery <ide> }); <ide> </script> <ide> <del><!-- Only change code above this line. --> <del> <ide> <div class="container-fluid"> <ide> <h3 class="text-primary text-center">jQuery Playground</h3> <ide> <div class="row"> <ide><path>guide/english/certifications/front-end-libraries/jquery/index.md <ide> title: jQuery <ide> --- <ide> ## jQuery <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <del> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <del> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <add>jQuery is a JavaScript library which is popularly used for JavaScript DOM manipulation, CSS handling and Ajax. <ide> <ide> #### More Information: <del><!-- Please add any articles you think might be helpful to read before writing the article --> <add> <add>- [jQuery Website](https://jquery.com/) <add>- [jQuery | Wikipedia](https://en.wikipedia.org/wiki/JQuery) <ide>\ No newline at end of file <ide><path>guide/english/certifications/front-end-libraries/jquery/remove-classes-from-an-element-with-jquery/index.md <ide> title: Remove Classes from an Element with jQuery <ide> }); <ide> </script> <ide> <del><!-- Only change code above this line. --> <del> <ide> <div class="container-fluid"> <ide> <h3 class="text-primary text-center">jQuery Playground</h3> <ide> <div class="row"> <ide><path>guide/english/certifications/front-end-libraries/jquery/target-elements-by-class-using-jquery/index.md <ide> title: Target Elements by Class Using jQuery <ide> $(".well").addClass("shake"); <ide> }); <ide> </script> <add> <add><div class="container-fluid"> <add> <h3 class="text-primary text-center">jQuery Playground</h3> <add> <div class="row"> <add> <div class="col-xs-6"> <add> <h4>#left-well</h4> <add> <div class="well" id="left-well"> <add> <button class="btn btn-default target" id="target1">#target1</button> <add> <button class="btn btn-default target" id="target2">#target2</button> <add> <button class="btn btn-default target" id="target3">#target3</button> <add> </div> <add> </div> <add> <div class="col-xs-6"> <add> <h4>#right-well</h4> <add> <div class="well" id="right-well"> <add> <button class="btn btn-default target" id="target4">#target4</button> <add> <button class="btn btn-default target" id="target5">#target5</button> <add> <button class="btn btn-default target" id="target6">#target6</button> <add> </div> <add> </div> <add> </div> <add></div> <ide> ``` <ide><path>guide/english/certifications/front-end-libraries/jquery/target-elements-by-id-using-jquery/index.md <ide> title: Target Elements by id Using jQuery <ide> $(document).ready(function() { <ide> $("button").addClass("animated bounce"); <ide> $(".well").addClass("animated shake"); <del> $("#target3").addClass("fadeOut"); // Target elements with the id "target3" and add the class "fadeOut" to them. <add> $("#target3").addClass("fadeOut"); <ide> }); <ide> </script> <add> <add><div class="container-fluid"> <add> <h3 class="text-primary text-center">jQuery Playground</h3> <add> <div class="row"> <add> <div class="col-xs-6"> <add> <h4>#left-well</h4> <add> <div class="well" id="left-well"> <add> <button class="btn btn-default target" id="target1">#target1</button> <add> <button class="btn btn-default target" id="target2">#target2</button> <add> <button class="btn btn-default target" id="target3">#target3</button> <add> </div> <add> </div> <add> <div class="col-xs-6"> <add> <h4>#right-well</h4> <add> <div class="well" id="right-well"> <add> <button class="btn btn-default target" id="target4">#target4</button> <add> <button class="btn btn-default target" id="target5">#target5</button> <add> <button class="btn btn-default target" id="target6">#target6</button> <add> </div> <add> </div> <add> </div> <add></div> <add> <ide> ``` <ide><path>guide/english/certifications/front-end-libraries/jquery/target-html-elements-with-selectors-using-jquery/index.md <ide> title: Target HTML Elements with Selectors Using jQuery <ide> ## Example <ide> ```js <ide> //You can select all <p> elements on a page like this = $("p") <del> $(document).ready(function(){ <del> $("button").click(function(){ <del> $("p").hide(); <del> }); <add>$(document).ready(function(){ <add> $("button").click(function(){ <add> $("p").hide(); <add> }); <ide> }); <ide> ``` <ide> <ide> <ide> ## Solution <ide> ```html <ide> <script> <del> $(document).ready(function() { <del> $("button").addClass("animated bounce"); // We are selecting the button elements and adding "animated bounce" class to them. <add> $(document).ready(function(){ <add> $("button").addClass("animated bounce"); <ide> }); <ide> </script> <del>``` <add> <add><div class="container-fluid"> <add> <h3 class="text-primary text-center">jQuery Playground</h3> <add> <div class="row"> <add> <div class="col-xs-6"> <add> <h4>#left-well</h4> <add> <div class="well" id="left-well"> <add> <button class="btn btn-default target" id="target1">#target1</button> <add> <button class="btn btn-default target" id="target2">#target2</button> <add> <button class="btn btn-default target" id="target3">#target3</button> <add> </div> <add> </div> <add> <div class="col-xs-6"> <add> <h4>#right-well</h4> <add> <div class="well" id="right-well"> <add> <button class="btn btn-default target" id="target4">#target4</button> <add> <button class="btn btn-default target" id="target5">#target5</button> <add> <button class="btn btn-default target" id="target6">#target6</button> <add> </div> <add> </div> <add> </div> <add></div> <add>``` <ide>\ No newline at end of file <ide><path>guide/english/certifications/front-end-libraries/jquery/target-the-parent-of-an-element-using-jquery/index.md <ide> title: Target the Parent of an Element Using jQuery <ide> ```html <ide> <script> <ide> $(document).ready(function() { <del> $("#target1").parent().css("background-color", "red"); // Selects the parent of #target1 and changes its background-color to red <add> $("#target1").css("color", "red"); <add> $("#target1").prop("disabled", true); <add> $("#target4").remove(); <add> $("#target2").appendTo("#right-well"); <add> $("#target5").clone().appendTo("#left-well"); <add> $("#target1").parent().css("background-color", "red"); <ide> }); <ide> </script> <del>``` <add> <add><body> <add> <div class="container-fluid"> <add> <h3 class="text-primary text-center">jQuery Playground</h3> <add> <div class="row"> <add> <div class="col-xs-6"> <add> <h4>#left-well</h4> <add> <div class="well" id="left-well"> <add> <button class="btn btn-default target" id="target1">#target1</button> <add> <button class="btn btn-default target" id="target2">#target2</button> <add> <button class="btn btn-default target" id="target3">#target3</button> <add> </div> <add> </div> <add> <div class="col-xs-6"> <add> <h4>#right-well</h4> <add> <div class="well" id="right-well"> <add> <button class="btn btn-default target" id="target4">#target4</button> <add> <button class="btn btn-default target" id="target5">#target5</button> <add> <button class="btn btn-default target" id="target6">#target6</button> <add> </div> <add> </div> <add> </div> <add> </div> <add></body> <add>``` <ide>\ No newline at end of file <ide><path>guide/english/certifications/front-end-libraries/jquery/target-the-same-element-with-multiple-jquery-selectors/index.md <ide> title: Target the Same Element with Multiple jQuery Selectors <ide> ```html <ide> <script> <ide> $(document).ready(function() { <del> $("button").addClass("animated"); // Target elements with type "button" and add the class "animated" to them. <del> $(".btn").addClass("shake"); // Target elements with class ".btn" and add the class "shake" to them. <del> $("#target1").addClass("btn-primary"); // Target elements with id "#target1" and add the class "btn-primary" to them. <add> $("button").addClass("animated"); <add> $(".btn").addClass("shake"); <add> $("#target1").addClass("btn-primary"); <ide> }); <ide> </script> <add> <add><div class="container-fluid"> <add> <h3 class="text-primary text-center">jQuery Playground</h3> <add> <div class="row"> <add> <div class="col-xs-6"> <add> <h4>#left-well</h4> <add> <div class="well" id="left-well"> <add> <button class="btn btn-default target" id="target1">#target1</button> <add> <button class="btn btn-default target" id="target2">#target2</button> <add> <button class="btn btn-default target" id="target3">#target3</button> <add> </div> <add> </div> <add> <div class="col-xs-6"> <add> <h4>#right-well</h4> <add> <div class="well" id="right-well"> <add> <button class="btn btn-default target" id="target4">#target4</button> <add> <button class="btn btn-default target" id="target5">#target5</button> <add> <button class="btn btn-default target" id="target6">#target6</button> <add> </div> <add> </div> <add> </div> <add></div> <ide> ```
8
Text
Text
remove erroneous comma in cluster explainer
ae59bcb7b125d8fa99878152e6932f95a501442a
<ide><path>doc/api/cluster.md <ide> handles back and forth. <ide> The cluster module supports two methods of distributing incoming <ide> connections. <ide> <del>The first one (and the default one on all platforms except Windows), <add>The first one (and the default one on all platforms except Windows) <ide> is the round-robin approach, where the primary process listens on a <ide> port, accepts new connections and distributes them across the workers <ide> in a round-robin fashion, with some built-in smarts to avoid
1
Javascript
Javascript
fix vertical offset in calendar example
85de0bed709005129c39f04508f2e6222d31b7c8
<ide><path>examples/calendar/dji.js <ide> d3.csv("dji.csv", function(csv) { <ide> pw = 14, <ide> z = ~~((w - pw * 2) / 53), <ide> ph = z >> 1, <del> h = z * 7 + ph * 2; <add> h = z * 7; <ide> <ide> var vis = d3.select("#chart") <ide> .selectAll("svg") <ide> .data(d3.range(1990, 2011)) <ide> .enter().append("svg:svg") <ide> .attr("width", w) <del> .attr("height", h) <add> .attr("height", h + ph * 2) <ide> .attr("class", "RdGy") <ide> .append("svg:g") <ide> .attr("transform", "translate(" + pw + "," + ph + ")"); <ide><path>examples/calendar/vix.js <ide> d3.csv("vix.csv", function(csv) { <ide> pw = 14, <ide> z = ~~((w - pw * 2) / 53), <ide> ph = z >> 1, <del> h = z * 7 + ph * 2; <add> h = z * 7; <ide> <ide> var vis = d3.select("#chart") <ide> .selectAll("svg") <ide> .data(d3.range(1993, 2011)) <ide> .enter().append("svg:svg") <ide> .attr("width", w) <del> .attr("height", h) <add> .attr("height", h + ph * 2) <ide> .attr("class", "RdYlGn") <ide> .append("svg:g") <ide> .attr("transform", "translate(" + pw + "," + ph + ")");
2
Go
Go
fix segfault if dns resolv error
3e6c69e5a1dbb428c4a62656f96cfe77c19986f9
<ide><path>registry/session.go <ide> func (r *Session) GetRemoteImageJSON(imgID, registry string, token []string) ([] <ide> <ide> func (r *Session) GetRemoteImageLayer(imgID, registry string, token []string, imgSize int64) (io.ReadCloser, error) { <ide> var ( <del> retries = 5 <del> client *http.Client <del> res *http.Response <del> imageURL = fmt.Sprintf("%simages/%s/layer", registry, imgID) <add> retries = 5 <add> statusCode = 0 <add> client *http.Client <add> res *http.Response <add> imageURL = fmt.Sprintf("%simages/%s/layer", registry, imgID) <ide> ) <ide> <ide> req, err := r.reqFactory.NewRequest("GET", imageURL, nil) <ide> func (r *Session) GetRemoteImageLayer(imgID, registry string, token []string, im <ide> } <ide> setTokenAuth(req, token) <ide> for i := 1; i <= retries; i++ { <add> statusCode = 0 <ide> res, client, err = r.doRequest(req) <ide> if err != nil { <del> if res.Body != nil { <del> res.Body.Close() <add> log.Debugf("Error contacting registry: %s", err) <add> if res != nil { <add> if res.Body != nil { <add> res.Body.Close() <add> } <add> statusCode = res.StatusCode <ide> } <ide> if i == retries { <ide> return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", <del> res.StatusCode, imgID) <add> statusCode, imgID) <ide> } <ide> time.Sleep(time.Duration(i) * 5 * time.Second) <ide> continue
1
Go
Go
fix unmounts out of container export funcs
02fdc194fc726ef2ce1fa4303e121abd277f8d32
<ide><path>container.go <ide> func (container *Container) ExportRw() (archive.Archive, error) { <ide> if container.runtime == nil { <ide> return nil, fmt.Errorf("Can't load storage driver for unregistered container %s", container.ID) <ide> } <del> defer container.Unmount() <del> <del> return container.runtime.Diff(container) <add> archive, err := container.runtime.Diff(container) <add> if err != nil { <add> container.Unmount() <add> return nil, err <add> } <add> return EofReader(archive, func() { container.Unmount() }), nil <ide> } <ide> <ide> func (container *Container) Export() (archive.Archive, error) { <ide> func (container *Container) Export() (archive.Archive, error) { <ide> <ide> archive, err := archive.Tar(container.basefs, archive.Uncompressed) <ide> if err != nil { <add> container.Unmount() <ide> return nil, err <ide> } <ide> return EofReader(archive, func() { container.Unmount() }), nil
1
PHP
PHP
allow warnings for xml entities
22d4cb3794e78381556636f90849608d4f1864e9
<ide><path>lib/Cake/Test/Case/Utility/XmlTest.php <ide> public function testNoEntityLoading() { <ide> <xxe>&payload;</xxe> <ide> </request> <ide> XML; <del> $result = Xml::build($xml); <del> $this->assertEquals('', (string)$result->xxe); <add> try { <add> $result = Xml::build($xml); <add> $this->assertEquals('', (string)$result->xxe); <add> } catch (PHPUnit_Framework_Error_Warning $e) { <add> $this->assertTrue(true, 'A warning was raised meaning external entities were not loaded'); <add> } <ide> } <ide> <ide> }
1
Ruby
Ruby
add tests for inferring option names
3a6f34d27bc654d41c274c4ef469f89c2d93be70
<ide><path>Library/Homebrew/test/cli/parser_spec.rb <ide> end <ide> end <ide> <add> describe "test inferrability of args" do <add> subject(:parser) { <add> described_class.new do <add> switch "--switch-a" <add> switch "--switch-b" <add> switch "--foo-switch" <add> flag "--flag-foo=" <add> comma_array "--comma-array-foo" <add> end <add> } <add> <add> it "parses a valid switch that uses `_` instead of `-`" do <add> args = parser.parse(["--switch_a"]) <add> expect(args).to be_switch_a <add> end <add> <add> it "parses a valid flag that uses `_` instead of `-`" do <add> args = parser.parse(["--flag_foo=foo.txt"]) <add> expect(args.flag_foo).to eq "foo.txt" <add> end <add> <add> it "parses a valid comma_array that uses `_` instead of `-`" do <add> args = parser.parse(["--comma_array_foo=foo.txt,bar.txt"]) <add> expect(args.comma_array_foo).to eq %w[foo.txt bar.txt] <add> end <add> <add> it "raises an error when option is ambiguous" do <add> expect { parser.parse(["--switch"]) }.to raise_error(RuntimeError, /ambiguous option: --switch/) <add> end <add> <add> it "inferrs the option from an abbreviated name" do <add> args = parser.parse(["--foo"]) <add> expect(args).to be_foo_switch <add> end <add> end <add> <ide> describe "test argv extensions" do <ide> subject(:parser) { <ide> described_class.new do
1
Python
Python
support regional gke cluster
a4622e19fa0edc983cb0b29ca6a92969d0cb46fd
<ide><path>airflow/providers/google/cloud/hooks/kubernetes_engine.py <ide> def get_operation(self, operation_name: str, project_id: Optional[str] = None) - <ide> :return: The new, updated operation from Google Cloud <ide> """ <ide> return self.get_conn().get_operation( <del> project_id=project_id or self.project_id, zone=self.location, operation_id=operation_name <add> name=f'projects/{project_id or self.project_id}' <add> + f'/locations/{self.location}/operations/{operation_name}' <ide> ) <ide> <ide> @staticmethod <ide> def delete_cluster( <ide> :type timeout: float <ide> :return: The full url to the delete operation if successful, else None <ide> """ <del> self.log.info("Deleting (project_id=%s, zone=%s, cluster_id=%s)", project_id, self.location, name) <add> self.log.info("Deleting (project_id=%s, location=%s, cluster_id=%s)", project_id, self.location, name) <ide> <ide> try: <ide> resource = self.get_conn().delete_cluster( <del> project_id=project_id, zone=self.location, cluster_id=name, retry=retry, timeout=timeout <add> name=f'projects/{project_id}/locations/{self.location}/clusters/{name}', <add> retry=retry, <add> timeout=timeout, <ide> ) <ide> resource = self.wait_for_operation(resource) <ide> # Returns server-defined url for the resource <ide> def create_cluster( <ide> self._append_label(cluster, 'airflow-version', 'v' + version.version) <ide> <ide> self.log.info( <del> "Creating (project_id=%s, zone=%s, cluster_name=%s)", project_id, self.location, cluster.name <add> "Creating (project_id=%s, location=%s, cluster_name=%s)", project_id, self.location, cluster.name <ide> ) <ide> try: <ide> resource = self.get_conn().create_cluster( <del> project_id=project_id, zone=self.location, cluster=cluster, retry=retry, timeout=timeout <add> parent=f'projects/{project_id}/locations/{self.location}', <add> cluster=cluster, <add> retry=retry, <add> timeout=timeout, <ide> ) <ide> resource = self.wait_for_operation(resource) <ide> <ide> def get_cluster( <ide> :return: google.cloud.container_v1.types.Cluster <ide> """ <ide> self.log.info( <del> "Fetching cluster (project_id=%s, zone=%s, cluster_name=%s)", <add> "Fetching cluster (project_id=%s, location=%s, cluster_name=%s)", <ide> project_id or self.project_id, <ide> self.location, <ide> name, <ide> def get_cluster( <ide> return ( <ide> self.get_conn() <ide> .get_cluster( <del> project_id=project_id, zone=self.location, cluster_id=name, retry=retry, timeout=timeout <add> name=f'projects/{project_id}/locations/{self.location}/clusters/{name}', <add> retry=retry, <add> timeout=timeout, <ide> ) <ide> .self_link <ide> ) <ide><path>airflow/providers/google/cloud/operators/kubernetes_engine.py <ide> class GKEDeleteClusterOperator(BaseOperator): <ide> :type project_id: str <ide> :param name: The name of the resource to delete, in this case cluster name <ide> :type name: str <del> :param location: The name of the Google Compute Engine zone in which the cluster <add> :param location: The name of the Google Compute Engine zone or region in which the cluster <ide> resides. <ide> :type location: str <ide> :param gcp_conn_id: The connection ID to use connecting to Google Cloud. <ide> class GKECreateClusterOperator(BaseOperator): <ide> <ide> :param project_id: The Google Developers Console [project ID or project number] <ide> :type project_id: str <del> :param location: The name of the Google Compute Engine zone in which the cluster <add> :param location: The name of the Google Compute Engine or region in which the cluster <ide> resides. <ide> :type location: str <ide> :param body: The Cluster definition to create, can be protobuf or python dict, if <ide> class GKEStartPodOperator(KubernetesPodOperator): <ide> For more information on how to use this operator, take a look at the guide: <ide> :ref:`howto/operator:GKEStartPodOperator` <ide> <del> :param location: The name of the Google Kubernetes Engine zone in which the <add> :param location: The name of the Google Kubernetes Engine zone or region in which the <ide> cluster resides, e.g. 'us-central1-a' <ide> :type location: str <ide> :param cluster_name: The name of the Google Kubernetes Engine cluster the pod <ide> should be spawned in <ide> :type cluster_name: str <ide> :param use_internal_ip: Use the internal IP address as the endpoint. <add> :type use_internal_ip: bool <ide> :param project_id: The Google Developers Console project id <ide> :type project_id: str <ide> :param gcp_conn_id: The google cloud connection id to use. This allows for <ide> class GKEStartPodOperator(KubernetesPodOperator): <ide> Service Account Token Creator IAM role to the directly preceding identity, with first <ide> account from the list granting this role to the originating account (templated). <ide> :type impersonation_chain: Union[str, Sequence[str]] <add> :param regional: The location param is region name. <add> :type regional: bool <ide> """ <ide> <ide> template_fields = {'project_id', 'location', 'cluster_name'} | set(KubernetesPodOperator.template_fields) <ide> def __init__( <ide> project_id: Optional[str] = None, <ide> gcp_conn_id: str = 'google_cloud_default', <ide> impersonation_chain: Optional[Union[str, Sequence[str]]] = None, <add> regional: bool = False, <ide> **kwargs, <ide> ) -> None: <ide> super().__init__(**kwargs) <ide> def __init__( <ide> self.gcp_conn_id = gcp_conn_id <ide> self.use_internal_ip = use_internal_ip <ide> self.impersonation_chain = impersonation_chain <add> self.regional = regional <ide> <ide> if self.gcp_conn_id is None: <ide> raise AirflowException( <ide> def execute(self, context) -> Optional[str]: <ide> "clusters", <ide> "get-credentials", <ide> self.cluster_name, <del> "--zone", <del> self.location, <ide> "--project", <ide> self.project_id, <ide> ] <ide> def execute(self, context) -> Optional[str]: <ide> impersonation_account, <ide> ] <ide> ) <add> if self.regional: <add> cmd.append('--region') <add> else: <add> cmd.append('--zone') <add> cmd.append(self.location) <ide> if self.use_internal_ip: <ide> cmd.append('--internal-ip') <ide> execute_in_subprocess(cmd) <ide><path>tests/providers/google/cloud/hooks/test_kubernetes_engine.py <ide> def test_delete_cluster(self, wait_mock, convert_mock, mock_project_id): <ide> ) <ide> <ide> client_delete.assert_called_once_with( <del> project_id=TEST_GCP_PROJECT_ID, <del> zone=GKE_ZONE, <del> cluster_id=CLUSTER_NAME, <add> name=f'projects/{TEST_GCP_PROJECT_ID}/locations/{GKE_ZONE}/clusters/{CLUSTER_NAME}', <ide> retry=retry_mock, <ide> timeout=timeout_mock, <ide> ) <ide> def test_create_cluster_proto(self, wait_mock, convert_mock, mock_project_id): <ide> ) <ide> <ide> client_create.assert_called_once_with( <del> project_id=TEST_GCP_PROJECT_ID, <del> zone=GKE_ZONE, <add> parent=f'projects/{TEST_GCP_PROJECT_ID}/locations/{GKE_ZONE}', <ide> cluster=mock_cluster_proto, <ide> retry=retry_mock, <ide> timeout=timeout_mock, <ide> def test_create_cluster_dict(self, wait_mock, convert_mock, mock_project_id): <ide> ) <ide> <ide> client_create.assert_called_once_with( <del> project_id=TEST_GCP_PROJECT_ID, <del> zone=GKE_ZONE, <add> parent=f'projects/{TEST_GCP_PROJECT_ID}/locations/{GKE_ZONE}', <ide> cluster=proto_mock, <ide> retry=retry_mock, <ide> timeout=timeout_mock, <ide> def test_get_cluster(self): <ide> ) <ide> <ide> client_get.assert_called_once_with( <del> project_id=TEST_GCP_PROJECT_ID, <del> zone=GKE_ZONE, <del> cluster_id=CLUSTER_NAME, <add> name=f'projects/{TEST_GCP_PROJECT_ID}/locations/{GKE_ZONE}/clusters/{CLUSTER_NAME}', <ide> retry=retry_mock, <ide> timeout=timeout_mock, <ide> ) <ide> def test_get_operation(self): <ide> self.gke_hook._client.get_operation = mock.Mock() <ide> self.gke_hook.get_operation('TEST_OP', project_id=TEST_GCP_PROJECT_ID) <ide> self.gke_hook._client.get_operation.assert_called_once_with( <del> project_id=TEST_GCP_PROJECT_ID, zone=GKE_ZONE, operation_id='TEST_OP' <add> name=f'projects/{TEST_GCP_PROJECT_ID}/locations/{GKE_ZONE}/operations/TEST_OP' <ide> ) <ide> <ide> def test_append_label(self): <ide><path>tests/providers/google/cloud/operators/test_kubernetes_engine.py <ide> def test_execute(self, file_mock, mock_execute_in_subprocess, mock_gcp_hook, exe <ide> 'clusters', <ide> 'get-credentials', <ide> CLUSTER_NAME, <add> '--project', <add> TEST_GCP_PROJECT_ID, <ide> '--zone', <ide> PROJECT_LOCATION, <add> ] <add> ) <add> <add> assert self.gke_op.config_file == FILE_NAME <add> <add> @mock.patch.dict(os.environ, {}) <add> @mock.patch( <add> "airflow.hooks.base.BaseHook.get_connections", <add> return_value=[ <add> Connection( <add> extra=json.dumps( <add> {"extra__google_cloud_platform__keyfile_dict": '{"private_key": "r4nd0m_k3y"}'} <add> ) <add> ) <add> ], <add> ) <add> @mock.patch('airflow.providers.cncf.kubernetes.operators.kubernetes_pod.KubernetesPodOperator.execute') <add> @mock.patch('airflow.providers.google.cloud.operators.kubernetes_engine.GoogleBaseHook') <add> @mock.patch('airflow.providers.google.cloud.operators.kubernetes_engine.execute_in_subprocess') <add> @mock.patch('tempfile.NamedTemporaryFile') <add> def test_execute_regional( <add> self, file_mock, mock_execute_in_subprocess, mock_gcp_hook, exec_mock, get_con_mock <add> ): <add> self.gke_op.regional = True <add> type(file_mock.return_value.__enter__.return_value).name = PropertyMock( <add> side_effect=[FILE_NAME, '/path/to/new-file'] <add> ) <add> <add> self.gke_op.execute(None) <add> <add> mock_gcp_hook.return_value.provide_authorized_gcloud.assert_called_once() <add> <add> mock_execute_in_subprocess.assert_called_once_with( <add> [ <add> 'gcloud', <add> 'container', <add> 'clusters', <add> 'get-credentials', <add> CLUSTER_NAME, <ide> '--project', <ide> TEST_GCP_PROJECT_ID, <add> '--region', <add> PROJECT_LOCATION, <ide> ] <ide> ) <ide> <ide> def test_execute_with_internal_ip( <ide> 'clusters', <ide> 'get-credentials', <ide> CLUSTER_NAME, <del> '--zone', <del> PROJECT_LOCATION, <ide> '--project', <ide> TEST_GCP_PROJECT_ID, <add> '--zone', <add> PROJECT_LOCATION, <ide> '--internal-ip', <ide> ] <ide> ) <ide> def test_execute_with_impersonation_service_account( <ide> 'clusters', <ide> 'get-credentials', <ide> CLUSTER_NAME, <del> '--zone', <del> PROJECT_LOCATION, <ide> '--project', <ide> TEST_GCP_PROJECT_ID, <ide> '--impersonate-service-account', <ide> '[email protected]', <add> '--zone', <add> PROJECT_LOCATION, <ide> ] <ide> ) <ide> <ide> def test_execute_with_impersonation_service_chain_one_element( <ide> 'clusters', <ide> 'get-credentials', <ide> CLUSTER_NAME, <del> '--zone', <del> PROJECT_LOCATION, <ide> '--project', <ide> TEST_GCP_PROJECT_ID, <ide> '--impersonate-service-account', <ide> '[email protected]', <add> '--zone', <add> PROJECT_LOCATION, <ide> ] <ide> ) <ide>
4
Javascript
Javascript
fix typo in orderby.js documentation
62e6b4eeb6c4434a25f4c7a4cc2883232d502820
<ide><path>src/ng/filter/orderBy.js <ide> <table class="friend"> <ide> <tr> <ide> <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> <del> (<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th> <add> (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th> <ide> <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <ide> <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> <ide> </tr>
1
Javascript
Javascript
apply default export interop to `next/error`
3f30e26a3a3a919c7f2ca5746488533b961f211d
<ide><path>packages/next/taskfile.js <ide> export async function pages_app(task, opts) { <ide> export async function pages_error(task, opts) { <ide> await task <ide> .source('pages/_error.tsx') <del> .swc('client', { dev: opts.dev, keepImportAssertions: true }) <add> .swc('client', { <add> dev: opts.dev, <add> keepImportAssertions: true, <add> interopClientDefaultExport: true, <add> }) <ide> .target('dist/pages') <ide> } <ide>
1
Javascript
Javascript
apply default export interop to pages/_app
bcb0e282018045cba63090cc90451f4e5d08d3d7
<ide><path>packages/next/taskfile.js <ide> export async function nextbuildstatic(task, opts) { <ide> export async function pages_app(task, opts) { <ide> await task <ide> .source('pages/_app.tsx') <del> .swc('client', { dev: opts.dev, keepImportAssertions: true }) <add> .swc('client', { <add> dev: opts.dev, <add> keepImportAssertions: true, <add> interopClientDefaultExport: true, <add> }) <ide> .target('dist/pages') <ide> } <ide>
1
Ruby
Ruby
fix postgresql adapter setup for actioncable tests
be806d8696675b82e4407eeaf8b63f59afd3f00e
<ide><path>actioncable/test/subscription_adapter/postgresql_test.rb <ide> def setup <ide> if Dir.exist?(ar_tests) <ide> require File.join(ar_tests, "config") <ide> require File.join(ar_tests, "support/config") <del> local_config = ARTest.config["arunit"] <add> local_config = ARTest.config["connections"]["postgresql"]["arunit"] <ide> database_config.update local_config if local_config <ide> end <ide>
1
Javascript
Javascript
improve error message
b1f81a5e3eea5b4fa6f1f95d44c20a300aab4ae4
<ide><path>lib/webpack.js <ide> const defineMissingPluginError = (pluginName, errorMessage) => { <ide> configurable: false, <ide> enumerable: true, <ide> get() { <del> throw new Error(errorMessage); <add> throw new Error(`RemovedPluginError: ${errorMessage}`); <ide> } <ide> }); <ide> };
1
Python
Python
add ascii encoding on network interface name
c98b364d3c7b0552f14f63f56275574d9b2edd49
<ide><path>glances/glances.py <ide> def displayNetwork(self, network): <ide> # network interface name <ide> self.term_window.addnstr( <ide> self.network_y + 1 + i, self.network_x, <del> network[i]['interface_name'] + ':', 8) <add> unicode(network[i]['interface_name'], 'ascii', 'ignore') + ':', 8) <ide> <ide> # Byte/s or bit/s <ide> if self.net_byteps_tag:
1
PHP
PHP
add keys to transform
1232e5e7baf7d6faeed139ff6014bb5b5bc66e10
<ide><path>src/Illuminate/Support/Collection.php <ide> public function take($limit = null) <ide> */ <ide> public function transform(callable $callback) <ide> { <del> $this->items = array_map($callback, $this->items); <add> $this->items = array_map($callback, $this->items, array_keys($this->items)); <ide> <ide> return $this; <ide> } <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testGetListValueWithAccessors() <ide> public function testTransform() <ide> { <ide> $data = new Collection(array('taylor', 'colin', 'shawn')); <del> $data->transform(function($item) { return strrev($item); }); <del> $this->assertEquals(array('rolyat', 'niloc', 'nwahs'), array_values($data->all())); <add> $data->transform(function($item, $key) { return strrev($item).$key; }); <add> $this->assertEquals(array('rolyat0', 'niloc1', 'nwahs2'), array_values($data->all())); <ide> } <ide> <ide>
2
Javascript
Javascript
fix bug which only showed up in ie7
3b41979891f5dc6a68e05cd5ed9c355c34774193
<ide><path>src/directives.js <ide> angularWidget("@ng:repeat", function(expression, element){ <ide> var index = 0, childCount = children.length, childScope, lastElement = reference, <ide> collection = this.$tryEval(rhs, reference), is_array = isArray(collection); <ide> for ( var key in collection) { <del> if (is_array && !collection.hasOwnProperty(key)) break; <del> if (index < childCount) { <del> // reuse existing child <del> childScope = children[index]; <del> childScope[valueIdent] = collection[key]; <del> if (keyIdent) childScope[keyIdent] = key; <del> } else { <del> // grow children <del> childScope = template(element.clone(), createScope(currentScope)); <del> childScope[valueIdent] = collection[key]; <del> if (keyIdent) childScope[keyIdent] = key; <del> lastElement.after(childScope.$element); <del> childScope.$index = index; <del> childScope.$element.attr('ng:repeat-index', index); <del> childScope.$init(); <del> children.push(childScope); <add> if (!is_array || collection.hasOwnProperty(key)) { <add> if (index < childCount) { <add> // reuse existing child <add> childScope = children[index]; <add> childScope[valueIdent] = collection[key]; <add> if (keyIdent) childScope[keyIdent] = key; <add> } else { <add> // grow children <add> childScope = template(element.clone(), createScope(currentScope)); <add> childScope[valueIdent] = collection[key]; <add> if (keyIdent) childScope[keyIdent] = key; <add> lastElement.after(childScope.$element); <add> childScope.$index = index; <add> childScope.$element.attr('ng:repeat-index', index); <add> childScope.$init(); <add> children.push(childScope); <add> } <add> childScope.$eval(); <add> lastElement = childScope.$element; <add> index ++; <ide> } <del> childScope.$eval(); <del> lastElement = childScope.$element; <del> index ++; <ide> }; <ide> // shrink children <ide> while(children.length > index) {
1
Ruby
Ruby
return a list rather than hash
a901433ee3bd318fd6c87b939ddabe0925830bc9
<ide><path>activerecord/lib/active_record/associations/preloader/through_association.rb <ide> def source_reflection <ide> def associated_records_by_owner <ide> through_records = through_records_by_owner <ide> <del> preloader = Preloader.new(through_records.values.flatten, <add> middle_records = through_records.map { |rec| rec[1] }.flatten <add> <add> preloader = Preloader.new(middle_records, <ide> source_reflection.name, <ide> reflection_scope) <ide> preloader.run <ide> <del> through_records.each do |owner, records| <del> records.map! { |r| r.send(source_reflection.name) }.flatten! <del> records.compact! <del> end <add> through_records.each_with_object({}) { |(lhs,middles,assoc),h| <add> h[lhs] = middles.flat_map { |r| <add> r.send(source_reflection.name) <add> }.compact <add> } <ide> end <ide> <ide> private <ide> def through_records_by_owner <ide> should_reset = (through_scope != through_reflection.klass.unscoped) || <ide> (reflection.options[:source_type] && through_reflection.collection?) <ide> <del> owners.each_with_object({}) do |owner, h| <add> owners.map do |owner, h| <ide> association = owner.association through_reflection.name <del> h[owner] = Array(association.reader) <add> <add> x = [owner, Array(association.reader), association] <ide> <ide> # Dont cache the association - we would only be caching a subset <ide> association.reset if should_reset <add> <add> x <ide> end <ide> end <ide>
1
Javascript
Javascript
move login logic into user model
296387d67e3c4c22d300326cce29b117026520a4
<ide><path>common/models/user.js <ide> import { <ide> getPort <ide> } from '../../server/utils/url-utils.js'; <ide> <del>const debug = debugFactory('fcc:user:remote'); <add>const debug = debugFactory('fcc:models:user'); <ide> const BROWNIEPOINTS_TIMEOUT = [1, 'hour']; <ide> <ide> const createEmailError = redirectTo => wrapHandledError( <ide> module.exports = function(User) { <ide> }); <ide> }; <ide> <del> User.afterRemote('login', function(ctx, accessToken, next) { <del> var res = ctx.res; <del> var req = ctx.req; <del> // var args = ctx.args; <del> <del> var config = { <del> signed: !!req.signedCookies, <del> maxAge: accessToken.ttl <del> }; <del> <del> if (accessToken && accessToken.id) { <del> debug('setting cookies'); <del> res.cookie('access_token', accessToken.id, config); <del> res.cookie('userId', accessToken.userId, config); <del> } <del> <del> return req.logIn({ id: accessToken.userId.toString() }, function(err) { <del> if (err) { return next(err); } <del> <del> debug('user logged in'); <del> <del> if (req.session && req.session.returnTo) { <del> var redirectTo = req.session.returnTo; <del> if (redirectTo === '/map-aside') { <del> redirectTo = '/map'; <add> User.prototype.loginByRequest = function login(req, res) { <add> const createToken = this.createAccessToken$() <add> .do(accessToken => { <add> const config = { <add> signed: !!req.signedCookies, <add> maxAge: accessToken.ttl <add> }; <add> if (accessToken && accessToken.id) { <add> res.cookie('access_token', accessToken.id, config); <add> res.cookie('userId', accessToken.userId, config); <ide> } <del> return res.redirect(redirectTo); <del> } <del> <del> req.flash('success', { msg: 'Success! You are now logged in.' }); <del> return res.redirect('/'); <del> }); <del> }); <del> <del> User.afterRemoteError('login', function(ctx) { <del> var res = ctx.res; <del> var req = ctx.req; <del> <del> req.flash('errors', { <del> msg: 'Invalid username or password.' <add> }); <add> const updateUser = this.update$({ <add> emailVerified: true, <add> emailAuthLinkTTL: null, <add> emailVerifyTTL: null <ide> }); <del> return res.redirect('/email-signin'); <del> }); <add> return Observable.combineLatest( <add> createToken, <add> updateUser, <add> req.logIn(this), <add> (accessToken) => accessToken, <add> ); <add> }; <ide> <ide> User.afterRemote('logout', function(ctx, result, next) { <ide> var res = ctx.res; <ide><path>server/boot/authentication.js <ide> module.exports = function enableAuthentication(app) { <ide> }) <ide> // at this point token has been validated and destroyed <ide> // update user and log them in <del> .map(user => { <del> const emailVerified = true; <del> const emailAuthLinkTTL = null; <del> const emailVerifyTTL = null; <del> <del> const updateUser = user.update$({ <del> emailVerified, <del> emailAuthLinkTTL, <del> emailVerifyTTL <del> }) <del> .do((user) => { <del> // update$ does not update in place <del> // update user instance to reflect db <del> user.emailVerified = emailVerified; <del> user.emailAuthLinkTTL = emailAuthLinkTTL; <del> user.emailVerifyTTL = emailVerifyTTL; <del> }); <del> <del> const createToken = user.createAccessToken$() <del> .do(accessToken => { <del> const config = { <del> signed: !!req.signedCookies, <del> maxAge: accessToken.ttl <del> }; <del> if (accessToken && accessToken.id) { <del> res.cookie('access_token', accessToken.id, config); <del> res.cookie('userId', accessToken.userId, config); <del> } <del> }); <del> <del> return Observable.combineLatest( <del> updateUser, <del> createToken, <del> req.logIn(user), <del> ); <del> }) <add> .map(user => user.loginByRequest(req, res)) <ide> .do(() => { <ide> let redirectTo = '/'; <ide>
2
Ruby
Ruby
fix safe buffer by adding a dirty status
594603b45f1248380068c4a32ac62283fe061e82
<ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb <ide> def html_safe? <ide> module ActiveSupport #:nodoc: <ide> class SafeBuffer < String <ide> UNSAFE_STRING_METHODS = ["capitalize", "chomp", "chop", "delete", "downcase", "gsub", "lstrip", "next", "reverse", "rstrip", "slice", "squeeze", "strip", "sub", "succ", "swapcase", "tr", "tr_s", "upcase"].freeze <add> <add> # TODO: Should safe_concat check if the current buffer is dirty or not? <add> # We should probably raise as it would mean we are adding concatenating <add> # to something that is safe but it actually isn't. <ide> alias safe_concat concat <ide> <add> def initialize(*) <add> @dirty = false <add> super <add> end <add> <add> def initialize_copy(other) <add> super <add> @dirty = other.dirty? <add> end <add> <ide> def concat(value) <del> if value.html_safe? <add> if dirty? || value.html_safe? <ide> super(value) <ide> else <ide> super(ERB::Util.h(value)) <ide> def +(other) <ide> end <ide> <ide> def html_safe? <del> true <del> end <del> <del> def html_safe <del> self <add> !dirty? <ide> end <ide> <ide> def to_s <ide> def encode_with(coder) <ide> <ide> def to_yaml(*args) <ide> return super() if defined?(YAML::ENGINE) && !YAML::ENGINE.syck? <del> <ide> to_str.to_yaml(*args) <ide> end <ide> <ide> def #{unsafe_method}(*args) <ide> end <ide> <ide> def #{unsafe_method}!(*args) <del> raise TypeError, "Cannot modify SafeBuffer in place" <add> @dirty = true <add> super <ide> end <ide> EOT <ide> end <add> <add> protected <add> <add> def dirty? <add> @dirty <add> end <ide> end <ide> end <ide> <ide> class String <del> def html_safe! <del> raise "You can't call html_safe! on a String" <del> end <del> <ide> def html_safe <ide> ActiveSupport::SafeBuffer.new(self) <ide> end <ide><path>activesupport/test/safe_buffer_test.rb <ide> rescue LoadError <ide> end <ide> <add>require 'active_support/core_ext/string/inflections' <ide> require 'yaml' <ide> <ide> class SafeBufferTest < ActiveSupport::TestCase <ide> def setup <ide> assert_equal ActiveSupport::SafeBuffer, new_buffer.class <ide> end <ide> <del> def test_to_yaml <add> test "Should be converted to_yaml" do <ide> str = 'hello!' <ide> buf = ActiveSupport::SafeBuffer.new str <ide> yaml = buf.to_yaml <ide> def test_to_yaml <ide> assert_equal 'hello!', YAML.load(yaml) <ide> end <ide> <del> def test_nested <add> test "Should work in nested to_yaml conversion" do <ide> str = 'hello!' <ide> data = { 'str' => ActiveSupport::SafeBuffer.new(str) } <ide> yaml = YAML.dump data <ide> assert_equal({'str' => str}, YAML.load(yaml)) <ide> end <ide> <add> test "Should work with underscore" do <add> str = "MyTest".html_safe.underscore <add> assert_equal "my_test", str <add> end <add> <ide> test "Should not return safe buffer from gsub" do <ide> altered_buffer = @buffer.gsub('', 'asdf') <ide> assert_equal 'asdf', altered_buffer <ide> assert !altered_buffer.html_safe? <ide> end <ide> <del> test "Should not allow gsub! on safe buffers" do <del> assert_raise TypeError do <del> @buffer.gsub!('', 'asdf') <del> end <add> test "Should not return safe buffer from gsub!" do <add> @buffer.gsub!('', 'asdf') <add> assert_equal 'asdf', @buffer <add> assert [email protected]_safe? <add> end <add> <add> test "Should escape dirty buffers on add" do <add> dirty = @buffer <add> clean = "hello".html_safe <add> @buffer.gsub!('', '<>') <add> assert_equal "hello&lt;&gt;", clean + @buffer <add> end <add> <add> test "Should concat as a normal string when dirty" do <add> dirty = @buffer <add> clean = "hello".html_safe <add> @buffer.gsub!('', '<>') <add> assert_equal "<>hello", @buffer + clean <add> end <add> <add> test "Should preserve dirty? status on copy" do <add> @buffer.gsub!('', '<>') <add> assert [email protected]_safe? <ide> end <ide> end
2
Java
Java
implement background in flatshadownode
f19acaed4b339e68b4b70c138b76acf9bde45a79
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/DrawBackgroundColor.java <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <add>package com.facebook.react.flat; <add> <add>import android.graphics.Canvas; <add>import android.graphics.Paint; <add> <add>/** <add> * Draws background for a FlatShadowNode as a solid rectangle. <add> */ <add>/* package */ final class DrawBackgroundColor extends AbstractDrawCommand { <add> <add> private static final Paint PAINT = new Paint(); <add> <add> private final int mBackgroundColor; <add> <add> /* package */ DrawBackgroundColor(int backgroundColor) { <add> mBackgroundColor = backgroundColor; <add> } <add> <add> @Override <add> public void draw(Canvas canvas) { <add> PAINT.setColor(mBackgroundColor); <add> canvas.drawRect(getLeft(), getTop(), getRight(), getBottom(), PAINT); <add> } <add>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatShadowNode.java <ide> <ide> package com.facebook.react.flat; <ide> <add>import javax.annotation.Nullable; <add> <ide> import com.facebook.react.uimanager.LayoutShadowNode; <add>import com.facebook.react.uimanager.ReactProp; <add>import com.facebook.react.uimanager.ViewProps; <ide> <ide> /** <ide> * FlatShadowNode is a base class for all shadow node used in FlatUIImplementation. It extends <ide> * {@link LayoutShadowNode} by adding an ability to prepare DrawCommands off the UI thread. <ide> */ <ide> /* package */ class FlatShadowNode extends LayoutShadowNode { <ide> <add> private @Nullable DrawBackgroundColor mDrawBackground; <add> <ide> /** <ide> * Collects DrawCommands produced by this FlatShadoNode. <ide> */ <ide> protected void collectState( <ide> float top, <ide> float right, <ide> float bottom) { <del> // do nothing yet. <add> if (mDrawBackground != null) { <add> mDrawBackground = (DrawBackgroundColor) mDrawBackground.updateBoundsAndFreeze( <add> left, <add> top, <add> right, <add> bottom); <add> stateBuilder.addDrawCommand(mDrawBackground); <add> } <add> } <add> <add> @ReactProp(name = ViewProps.BACKGROUND_COLOR) <add> public void setBackgroundColor(int backgroundColor) { <add> mDrawBackground = (backgroundColor == 0) ? null : new DrawBackgroundColor(backgroundColor); <add> invalidate(); <ide> } <ide> <ide> /** <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTView.java <ide> protected void collectState( <ide> } <ide> } <ide> <add> @Override <ide> public void setBackgroundColor(int backgroundColor) { <ide> getMutableBorder().setBackgroundColor(backgroundColor); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTVirtualText.java <ide> public void setColor(double textColor) { <ide> } <ide> } <ide> <del> @ReactProp(name = ViewProps.BACKGROUND_COLOR) <add> @Override <ide> public void setBackgroundColor(int backgroundColor) { <del> if (mFontStylingSpan.getBackgroundColor() != backgroundColor) { <del> getSpan().setBackgroundColor(backgroundColor); <del> notifyChanged(false); <add> if (isVirtual()) { <add> // for nested Text elements, we want to apply background color to the text only <add> // e.g. Hello <style backgroundColor=red>World</style>, "World" will have red background color <add> if (mFontStylingSpan.getBackgroundColor() != backgroundColor) { <add> getSpan().setBackgroundColor(backgroundColor); <add> notifyChanged(false); <add> } <add> } else { <add> // for top-level Text element, background needs to be applied for the entire shadow node <add> // <add> // For example: <Text style={flex:1}>Hello World</Text> <add> // "Hello World" may only occupy e.g. 200 pixels, but the node may be measured at e.g. 500px. <add> // In this case, we want background to be 500px wide as well, and this is exactly what <add> // FlatShadowNode does. <add> super.setBackgroundColor(backgroundColor); <ide> } <ide> } <ide>
4
Text
Text
update the docs
4d4271e6c4088913f3fcbe1e2c8c43d967b3379e
<ide><path>docs/02-Line-Chart.md <ide> var data = { <ide> // Number or array - border width of point when hovered <ide> pointHoverBorderWidth: 2, <ide> <del> // Tension - bezier curve tension of the line. Set to 0 to draw straight Wlines connecting points <del> tension: 0.1, <add> // Tension - bezier curve tension of the line. Set to 0 to draw straight lines connecting points <add> // Used to be called "tension" but was renamed for consistency. The old option name continues to work for compatibility. <add> lineTension: 0.1, <ide> <ide> // Number - the pixel size of the point shape. Can be set to 0 to not render a circle over the point <ide> radius: 1,
1
Text
Text
translate the toc in french
b8bd0459204be4920198f893f48f88ea3c54cc47
<ide><path>threejs/lessons/fr/threejs-cameras.md <ide> Title: Caméras dans Three.js <ide> Description: Comment utiliser les Cameras dans Three.js <del>TOC: Cameras <add>TOC: Caméras <ide> <ide> Cet article fait partie d'une série consacrée à Three.js. <ide> Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
1
Javascript
Javascript
remove redundant return in test
6dea193acaa3c548fa2dedf57a4e32c8401a02c2
<ide><path>test/parallel/test-tls-disable-renegotiation.js <ide> const fs = require('fs'); <ide> <ide> // Tests that calling disableRenegotiation on a TLSSocket stops renegotiation. <ide> <del>if (!common.hasCrypto) { <add>if (!common.hasCrypto) <ide> common.skip('missing crypto'); <del> return; <del>} <add> <ide> const tls = require('tls'); <ide> <ide> const options = {
1
Python
Python
handle pytz.ambiguoustimeerror. closes
ea4581f4dedcbbaf697d980da31286514ef56640
<ide><path>celery/utils/timeutils.py <ide> <ide> from kombu.utils import cached_property, reprcall <ide> <del>from pytz import timezone as _timezone <add>from pytz import timezone as _timezone, AmbiguousTimeError <ide> <ide> from celery.five import string_t <ide> <ide> def is_naive(dt): <ide> def make_aware(dt, tz): <ide> """Sets the timezone for a datetime object.""" <ide> try: <del> localize = tz.localize <add> _localize = tz.localize <ide> except AttributeError: <ide> return dt.replace(tzinfo=tz) <ide> else: <ide> # works on pytz timezones <del> return localize(dt, is_dst=None) <add> try: <add> return _localize(dt, is_dst=None) <add> except AmbiguousTimeError: <add> return min(_localize(dt, is_dst=True), <add> _localize(dt, is_dst=False)) <ide> <ide> <ide> def localize(dt, tz): <ide> """Convert aware datetime to another timezone.""" <ide> dt = dt.astimezone(tz) <ide> try: <del> normalize = tz.normalize <del> except AttributeError: <add> _normalize = tz.normalize <add> except AttributeError: # non-pytz tz <ide> return dt <ide> else: <del> return normalize(dt) # pytz <add> try: <add> return _normalize(dt, is_dst=None) <add> except AmbiguousTimeError: <add> return min(_normalize(dt, is_dst=True), <add> _normalize(dt, is_dst=False)) <ide> <ide> <ide> def to_utc(dt):
1
Python
Python
add phone_validator method
72aa4cc315ca0a70e09026884556cb724145d12e
<ide><path>strings/indian_phone_validator.py <add>import re <add> <add> <add>def indian_phone_validator(phone: str) -> bool: <add> """ <add> Determine whether the string is a valid phone number or not <add> :param phone: <add> :return: Boolean <add> >>> indian_phone_validator("+91123456789") <add> False <add> >>> indian_phone_validator("+919876543210") <add> True <add> >>> indian_phone_validator("01234567896") <add> False <add> >>> indian_phone_validator("919876543218") <add> True <add> >>> indian_phone_validator("+91-1234567899") <add> False <add> """ <add> pat = re.compile(r"^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$") <add> match = re.search(pat, phone) <add> if match: <add> return match.string == phone <add> return False <add> <add> <add>if __name__ == "__main__": <add> print(indian_phone_validator("+918827897895"))
1
Java
Java
allow update of state to receive null objects
c65267ca6ffdf68e9846c0cf912d23162e671758
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java <ide> private MountItem updateLocalDataMountItem(int reactTag, ReadableMap newLocalDat <ide> <ide> @DoNotStrip <ide> @SuppressWarnings("unused") <del> private MountItem updateStateMountItem(int reactTag, Object stateWrapper) { <add> private MountItem updateStateMountItem(int reactTag, @Nullable Object stateWrapper) { <ide> return new UpdateStateMountItem(reactTag, (StateWrapper) stateWrapper); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java <ide> public void updateLocalData(int reactTag, ReadableMap newLocalData) { <ide> } <ide> <ide> @UiThread <del> public void updateState(final int reactTag, StateWrapper stateWrapper) { <add> public void updateState(final int reactTag, @Nullable StateWrapper stateWrapper) { <ide> UiThreadUtil.assertOnUiThread(); <ide> ViewState viewState = getViewState(reactTag); <del> ReadableNativeMap newState = stateWrapper.getState(); <del> if (viewState.mCurrentState != null && viewState.mCurrentState.equals(newState)) { <add> @Nullable ReadableNativeMap newState = stateWrapper == null ? null : stateWrapper.getState(); <add> if ((viewState.mCurrentState != null && viewState.mCurrentState.equals(newState)) <add> || (viewState.mCurrentState == null && stateWrapper == null)) { <ide> return; <ide> } <ide> viewState.mCurrentState = newState; <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/UpdateStateMountItem.java <ide> */ <ide> package com.facebook.react.fabric.mounting.mountitems; <ide> <add>import androidx.annotation.Nullable; <ide> import com.facebook.react.fabric.mounting.MountingManager; <ide> import com.facebook.react.uimanager.StateWrapper; <ide> <ide> public class UpdateStateMountItem implements MountItem { <ide> <ide> private final int mReactTag; <del> private final StateWrapper mStateWrapper; <add> @Nullable private final StateWrapper mStateWrapper; <ide> <del> public UpdateStateMountItem(int reactTag, StateWrapper stateWrapper) { <add> public UpdateStateMountItem(int reactTag, @Nullable StateWrapper stateWrapper) { <ide> mReactTag = reactTag; <ide> mStateWrapper = stateWrapper; <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManager.java <ide> public Map<String, String> getNativeProps() { <ide> * this component type. <ide> */ <ide> public @Nullable Object updateState( <del> @NonNull T view, ReactStylesDiffMap props, StateWrapper stateWrapper) { <add> @NonNull T view, ReactStylesDiffMap props, @Nullable StateWrapper stateWrapper) { <ide> return null; <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostManager.java <ide> public void setStatusBarTranslucent(ReactModalHostView view, boolean statusBarTr <ide> view.setStatusBarTranslucent(statusBarTranslucent); <ide> } <ide> <del> <ide> @Override <ide> @ReactProp(name = "hardwareAccelerated") <ide> public void setHardwareAccelerated(ReactModalHostView view, boolean hardwareAccelerated) { <ide> protected void onAfterUpdateTransaction(ReactModalHostView view) { <ide> <ide> @Override <ide> public Object updateState( <del> ReactModalHostView view, ReactStylesDiffMap props, StateWrapper stateWrapper) { <add> ReactModalHostView view, ReactStylesDiffMap props, @Nullable StateWrapper stateWrapper) { <add> // TODO T55794595: Add support for updating state with null stateWrapper <ide> Point modalSize = ModalHostHelper.getModalHostSize(view.getContext()); <ide> view.updateState(stateWrapper, modalSize.x, modalSize.y); <ide> return null; <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextViewManager.java <ide> public boolean needsCustomLayoutForChildren() { <ide> <ide> @Override <ide> public Object updateState( <del> ReactTextView view, ReactStylesDiffMap props, StateWrapper stateWrapper) { <add> ReactTextView view, ReactStylesDiffMap props, @Nullable StateWrapper stateWrapper) { <add> // TODO T55794595: Add support for updating state with null stateWrapper <ide> ReadableMap attributedString = stateWrapper.getState().getMap("attributedString"); <ide> <ide> Spannable spanned =
6
Python
Python
fix trailing whitespace
aa7192575646c54a89caa020e3a4390bf8f6dead
<ide><path>libcloud/compute/drivers/dimensiondata.py <ide> def ex_create_firewall_rule(self, network_domain, rule, position): <ide> source_ip.set('address', 'ANY') <ide> else: <ide> source_ip.set('address', rule.source.ip_address) <del> if rule.source.ip_prefix_size is not None: <add> if rule.source.ip_prefix_size is not None: <ide> source_ip.set('prefixSize', str(rule.source.ip_prefix_size)) <ide> if rule.source.port_begin is not None: <ide> source_port = ET.SubElement(source, 'port')
1
Go
Go
implement docker rmi with standalone client lib
37d6fee8cfddd8e1afabbdaa232fa64a36494579
<ide><path>api/client/lib/image_remove.go <add>package lib <add> <add>import ( <add> "encoding/json" <add> "net/url" <add> <add> "github.com/docker/docker/api/types" <add>) <add> <add>// ImageRemoveOptions holds parameters to remove images. <add>type ImageRemoveOptions struct { <add> ImageID string <add> Force bool <add> PruneChildren bool <add>} <add> <add>// ImageRemove removes an image from the docker host. <add>func (cli *Client) ImageRemove(options ImageRemoveOptions) ([]types.ImageDelete, error) { <add> var query url.Values <add> <add> if options.Force { <add> query.Set("force", "1") <add> } <add> if !options.PruneChildren { <add> query.Set("noprune", "1") <add> } <add> <add> resp, err := cli.DELETE("/images/"+options.ImageID, query, nil) <add> if err != nil { <add> return nil, err <add> } <add> defer ensureReaderClosed(resp) <add> <add> var dels []types.ImageDelete <add> err = json.NewDecoder(resp.body).Decode(&dels) <add> return dels, err <add>} <ide><path>api/client/rmi.go <ide> package client <ide> <ide> import ( <del> "encoding/json" <ide> "fmt" <ide> "net/url" <ide> <del> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/client/lib" <ide> Cli "github.com/docker/docker/cli" <ide> flag "github.com/docker/docker/pkg/mflag" <ide> ) <ide> func (cli *DockerCli) CmdRmi(args ...string) error { <ide> <ide> var errNames []string <ide> for _, name := range cmd.Args() { <del> serverResp, err := cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, nil) <add> options := lib.ImageRemoveOptions{ <add> ImageID: name, <add> Force: *force, <add> PruneChildren: !*noprune, <add> } <add> <add> dels, err := cli.client.ImageRemove(options) <ide> if err != nil { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> errNames = append(errNames, name) <ide> } else { <del> defer serverResp.body.Close() <del> <del> dels := []types.ImageDelete{} <del> if err := json.NewDecoder(serverResp.body).Decode(&dels); err != nil { <del> fmt.Fprintf(cli.err, "%s\n", err) <del> errNames = append(errNames, name) <del> continue <del> } <del> <ide> for _, del := range dels { <ide> if del.Deleted != "" { <ide> fmt.Fprintf(cli.out, "Deleted: %s\n", del.Deleted)
2
Javascript
Javascript
remove an unused parameter of $location.url
99d95f1639b64c39231448d77209676b54e6f0be
<ide><path>src/ng/location.js <ide> LocationHashbangInHtml5Url.prototype = <ide> * Change path, search and hash, when called with parameter and return `$location`. <ide> * <ide> * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) <del> * @param {string=} replace The path that will be changed <ide> * @return {string} url <ide> */ <del> url: function(url, replace) { <add> url: function(url) { <ide> if (isUndefined(url)) <ide> return this.$$url; <ide> <ide> var match = PATH_MATCH.exec(url); <ide> if (match[1]) this.path(decodeURIComponent(match[1])); <ide> if (match[2] || match[1]) this.search(match[3] || ''); <del> this.hash(match[5] || '', replace); <add> this.hash(match[5] || ''); <ide> <ide> return this; <ide> },
1
Javascript
Javascript
remove redundant code, add tests in timers.js
070aac4a87a04380463da4f3730568c3bf5bf729
<ide><path>lib/timers.js <ide> const TIMEOUT_MAX = 2147483647; // 2^31-1 <ide> // value = list <ide> var lists = {}; <ide> <add> <add>// call this whenever the item is active (not idle) <add>// it will reset its timeout. <ide> // the main function - creates lists on demand and the watchers associated <ide> // with them. <del>function insert(item, msecs) { <del> item._idleStart = Timer.now(); <del> item._idleTimeout = msecs; <del> <add>exports.active = function(item) { <add> const msecs = item._idleTimeout; <ide> if (msecs < 0) return; <ide> <add> item._idleStart = Timer.now(); <add> <ide> var list; <ide> <ide> if (lists[msecs]) { <ide> function insert(item, msecs) { <ide> <ide> L.append(list, item); <ide> assert(!L.isEmpty(list)); // list is not empty <del>} <add>}; <ide> <ide> function listOnTimeout() { <ide> var msecs = this.msecs; <ide> exports.enroll = function(item, msecs) { <ide> }; <ide> <ide> <del>// call this whenever the item is active (not idle) <del>// it will reset its timeout. <del>exports.active = function(item) { <del> var msecs = item._idleTimeout; <del> if (msecs >= 0) <del> insert(item, msecs); <del>}; <del> <del> <ide> /* <ide> * DOM-style timers <ide> */ <ide><path>test/parallel/test-timers-active.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const active = require('timers').active; <add> <add>// active() should create timers for these <add>var legitTimers = [ <add> { _idleTimeout: 0 }, <add> { _idleTimeout: 1 } <add>]; <add> <add>legitTimers.forEach(function(legit) { <add> const savedTimeout = legit._idleTimeout; <add> active(legit); <add> // active() should mutate these objects <add> assert(legit._idleTimeout === savedTimeout); <add> assert(Number.isInteger(legit._idleStart)); <add> assert(legit._idleNext); <add> assert(legit._idlePrev); <add>}); <add> <add> <add>// active() should not create a timer for these <add>var bogusTimers = [ <add> { _idleTimeout: -1 } <add>]; <add> <add>bogusTimers.forEach(function(bogus) { <add> const savedTimeout = bogus._idleTimeout; <add> active(bogus); <add> // active() should not mutate these objects <add> assert.deepStrictEqual(bogus, {_idleTimeout: savedTimeout}); <add>});
2
Ruby
Ruby
move digest cache on to the detailskey object
3239ed48d28f3c0baf4445e6c279107e892b7cab
<ide><path>actionview/lib/action_view/digestor.rb <ide> <ide> module ActionView <ide> class Digestor <del> cattr_reader(:cache) <del> @@cache = Concurrent::Map.new <ide> @@digest_monitor = Monitor.new <ide> <ide> class PerRequestDigestCacheExpiry < Struct.new(:app) # :nodoc: <ide> def call(env) <del> ActionView::Digestor.cache.clear <add> ActionView::LookupContext::DetailsKey.clear <ide> app.call(env) <ide> end <ide> end <ide> class << self <ide> def digest(name:, finder:, **options) <ide> options.assert_valid_keys(:dependencies, :partial) <ide> <del> cache_key = ([ name, finder.details_key.hash ].compact + Array.wrap(options[:dependencies])).join('.') <add> cache_key = ([ name ].compact + Array.wrap(options[:dependencies])).join('.') <ide> <ide> # this is a correctly done double-checked locking idiom <ide> # (Concurrent::Map's lookups have volatile semantics) <del> digest_monitor.synchronize do <del> @@cache.fetch(cache_key) do # re-check under lock <add> finder.digest_cache[cache_key] || @@digest_monitor.synchronize do <add> finder.digest_cache.fetch(cache_key) do # re-check under lock <ide> compute_and_store_digest(cache_key, name, finder, options) <ide> end <ide> end <ide> def compute_and_store_digest(cache_key, name, finder, options) # called under @@ <ide> # Prevent re-entry or else recursive templates will blow the stack. <ide> # There is no need to worry about other threads seeing the +false+ value, <ide> # as they will then have to wait for this thread to let go of the @@digest_monitor lock. <del> pre_stored = @@cache.put_if_absent(cache_key, false).nil? # put_if_absent returns nil on insertion <add> pre_stored = finder.digest_cache.put_if_absent(cache_key, false).nil? # put_if_absent returns nil on insertion <ide> PartialDigestor <ide> else <ide> Digestor <ide> end <ide> <del> @@cache[cache_key] = stored_digest = klass.new(name, finder, options).digest <add> finder.digest_cache[cache_key] = stored_digest = klass.new(name, finder, options).digest <ide> ensure <ide> # something went wrong or ActionView::Resolver.caching? is false, make sure not to corrupt the @@cache <del> @@cache.delete_pair(cache_key, false) if pre_stored && !stored_digest <add> finder.digest_cache.delete_pair(cache_key, false) if pre_stored && !stored_digest <ide> end <ide> end <ide> <ide><path>actionview/lib/action_view/lookup_context.rb <ide> def self.get(details) <ide> def self.clear <ide> @details_keys.clear <ide> end <add> <add> def self.empty?; @details_keys.empty?; end <add> <add> def self.digest_caches <add> @details_keys.values.map(&:digest_cache) <add> end <add> <add> attr_reader :digest_cache <add> <add> def initialize <add> @digest_cache = Concurrent::Map.new <add> end <ide> end <ide> <ide> # Add caching behavior on top of Details. <ide> def initialize(view_paths, details = {}, prefixes = []) <ide> self.view_paths = view_paths <ide> end <ide> <add> def digest_cache <add> details_key.digest_cache <add> end <add> <ide> def initialize_details(target, details) <ide> registered_details.each do |k| <ide> target[k] = details[k] || Accessors::DEFAULT_PROCS[k].call <ide><path>actionview/test/template/digestor_test.rb <ide> def setup <ide> def teardown <ide> Dir.chdir @cwd <ide> FileUtils.rm_r @tmp_dir <del> ActionView::Digestor.cache.clear <ide> end <ide> <ide> def test_top_level_change_reflected <ide> def assert_logged(message) <ide> <ide> def assert_digest_difference(template_name, options = {}) <ide> previous_digest = digest(template_name, options) <del> ActionView::Digestor.cache.clear <add> finder.digest_cache.clear <ide> <ide> yield <ide> <ide> assert_not_equal previous_digest, digest(template_name, options), "digest didn't change" <del> ActionView::Digestor.cache.clear <add> finder.digest_cache.clear <ide> end <ide> <ide> def digest(template_name, options = {}) <ide><path>railties/test/application/per_request_digest_cache_test.rb <ide> def index <ide> get '/customers' <ide> assert_equal 200, last_response.status <ide> <del> assert_equal [ '8ba099b7749542fe765ff34a6824d548' ], ActionView::Digestor.cache.values <add> values = ActionView::LookupContext::DetailsKey.digest_caches.first.values <add> assert_equal [ '8ba099b7749542fe765ff34a6824d548' ], values <ide> assert_equal %w(david dingus), last_response.body.split.map(&:strip) <ide> end <ide> <ide> test "template digests are cleared before a request" do <del> assert_called(ActionView::Digestor.cache, :clear) do <add> assert_called(ActionView::LookupContext::DetailsKey, :clear) do <ide> get '/customers' <ide> assert_equal 200, last_response.status <ide> end
4
Mixed
Javascript
destroy sockets after keepalivetimeout
0aa7ef595084bca35f76cb38e28a0efc7a3128a3
<ide><path>doc/api/http.md <ide> Returns `server`. <ide> added: v0.9.12 <ide> --> <ide> <del>* {number} Defaults to 120000 (2 minutes). <add>* {number} Timeout in milliseconds. Defaults to 120000 (2 minutes). <ide> <ide> The number of milliseconds of inactivity before a socket is presumed <ide> to have timed out. <ide> <del>Note that the socket timeout logic is set up on connection, so <del>changing this value only affects *new* connections to the server, not <del>any existing connections. <add>A value of 0 will disable the timeout behavior on incoming connections. <ide> <del>Set to 0 to disable any kind of automatic timeout behavior on incoming <del>connections. <add>*Note*: The socket timeout logic is set up on connection, so changing this <add>value only affects new connections to the server, not any existing connections. <add> <add>### server.keepAliveTimeout <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* {number} Timeout in milliseconds. Defaults to 5000 (5 seconds). <add> <add>The number of milliseconds of inactivity a server needs to wait for additional <add>incoming data, after it has finished writing the last response, before a socket <add>will be destroyed. If the server receives new data before the keep-alive <add>timeout has fired, it will reset the regular inactivity timeout, i.e., <add>[`server.timeout`][]. <add> <add>A value of 0 will disable the keep-alive timeout behavior on incoming connections. <add> <add>*Note*: The socket timeout logic is set up on connection, so changing this <add>value only affects new connections to the server, not any existing connections. <ide> <ide> ## Class: http.ServerResponse <ide> <!-- YAML <ide> There are a few special headers that should be noted. <ide> [`response.write(data, encoding)`]: #http_response_write_chunk_encoding_callback <ide> [`response.writeContinue()`]: #http_response_writecontinue <ide> [`response.writeHead()`]: #http_response_writehead_statuscode_statusmessage_headers <add>[`server.timeout`]: #http_server_timeout <ide> [`socket.setKeepAlive()`]: net.html#net_socket_setkeepalive_enable_initialdelay <ide> [`socket.setNoDelay()`]: net.html#net_socket_setnodelay_nodelay <ide> [`socket.setTimeout()`]: net.html#net_socket_settimeout_timeout_callback <ide><path>doc/api/https.md <ide> added: v0.11.2 <ide> <ide> See [`http.Server#timeout`][]. <ide> <add>### server.keepAliveTimeout <add><!-- YAML <add>added: REPLACEME <add>--> <add>- {number} Defaults to 5000 (5 seconds). <add> <add>See [`http.Server#keepAliveTimeout`][]. <add> <ide> ## https.createServer(options[, requestListener]) <ide> <!-- YAML <ide> added: v0.3.4 <ide> const req = https.request(options, (res) => { <ide> <ide> [`Agent`]: #https_class_https_agent <ide> [`http.Agent`]: http.html#http_class_http_agent <add>[`http.Server#keepAliveTimeout`]: http.html#http_server_keepalivetimeout <ide> [`http.Server#setTimeout()`]: http.html#http_server_settimeout_msecs_callback <ide> [`http.Server#timeout`]: http.html#http_server_timeout <ide> [`http.Server`]: http.html#http_class_http_server <ide><path>lib/_http_server.js <ide> function Server(requestListener) { <ide> this.on('connection', connectionListener); <ide> <ide> this.timeout = 2 * 60 * 1000; <del> <add> this.keepAliveTimeout = 5000; <ide> this._pendingResponseData = 0; <ide> this.maxHeadersCount = null; <ide> } <ide> function connectionListener(socket) { <ide> // inactive responses. If more data than the high watermark is queued - we <ide> // need to pause TCP socket/HTTP parser, and wait until the data will be <ide> // sent to the client. <del> outgoingData: 0 <add> outgoingData: 0, <add> keepAliveTimeoutSet: false <ide> }; <ide> state.onData = socketOnData.bind(undefined, this, socket, parser, state); <ide> state.onEnd = socketOnEnd.bind(undefined, this, socket, parser, state); <ide> function socketOnEnd(server, socket, parser, state) { <ide> function socketOnData(server, socket, parser, state, d) { <ide> assert(!socket._paused); <ide> debug('SERVER socketOnData %d', d.length); <del> var ret = parser.execute(d); <ide> <add> if (state.keepAliveTimeoutSet) { <add> socket.setTimeout(0); <add> if (server.timeout) { <add> socket.setTimeout(server.timeout); <add> } <add> state.keepAliveTimeoutSet = false; <add> } <add> <add> var ret = parser.execute(d); <ide> onParserExecuteCommon(server, socket, parser, state, ret, d); <ide> } <ide> <ide> function onParserExecuteCommon(server, socket, parser, state, ret, d) { <ide> } <ide> } <ide> <del>function resOnFinish(req, res, socket, state) { <add>function resOnFinish(req, res, socket, state, server) { <ide> // Usually the first incoming element should be our request. it may <ide> // be that in the case abortIncoming() was called that the incoming <ide> // array will be empty. <ide> function resOnFinish(req, res, socket, state) { <ide> <ide> if (res._last) { <ide> socket.destroySoon(); <add> } else if (state.outgoing.length === 0) { <add> if (server.keepAliveTimeout) { <add> socket.setTimeout(0); <add> socket.setTimeout(server.keepAliveTimeout); <add> state.keepAliveTimeoutSet = true; <add> } <ide> } else { <ide> // start sending the next message <ide> var m = state.outgoing.shift(); <ide> function parserOnIncoming(server, socket, state, req, keepAlive) { <ide> <ide> // When we're finished writing the response, check if this is the last <ide> // response, if so destroy the socket. <del> res.on('finish', resOnFinish.bind(undefined, req, res, socket, state)); <add> res.on('finish', <add> resOnFinish.bind(undefined, req, res, socket, state, server)); <ide> <ide> if (req.headers.expect !== undefined && <ide> (req.httpVersionMajor === 1 && req.httpVersionMinor === 1)) { <ide><path>lib/https.js <ide> function Server(opts, requestListener) { <ide> }); <ide> <ide> this.timeout = 2 * 60 * 1000; <add> this.keepAliveTimeout = 5000; <ide> } <ide> inherits(Server, tls.Server); <ide> exports.Server = Server; <ide><path>test/parallel/test-http-server-keep-alive-timeout.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const http = require('http'); <add>const net = require('net'); <add> <add>const tests = []; <add> <add>function test(fn) { <add> if (!tests.length) { <add> process.nextTick(run); <add> } <add> tests.push(fn); <add>} <add> <add>function run() { <add> const fn = tests.shift(); <add> if (fn) fn(run); <add>} <add> <add>test(function serverEndKeepAliveTimeoutWithPipeline(cb) { <add> let socket; <add> let destroyedSockets = 0; <add> let timeoutCount = 0; <add> let requestCount = 0; <add> process.on('exit', () => { <add> assert.strictEqual(timeoutCount, 1); <add> assert.strictEqual(requestCount, 3); <add> assert.strictEqual(destroyedSockets, 1); <add> }); <add> const server = http.createServer((req, res) => { <add> socket = req.socket; <add> requestCount++; <add> res.end(); <add> }); <add> server.setTimeout(200, (socket) => { <add> timeoutCount++; <add> socket.destroy(); <add> }); <add> server.keepAliveTimeout = 50; <add> server.listen(0, common.mustCall(() => { <add> const options = { <add> port: server.address().port, <add> allowHalfOpen: true <add> }; <add> const c = net.connect(options, () => { <add> c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> }); <add> setTimeout(() => { <add> server.close(); <add> if (socket.destroyed) destroyedSockets++; <add> cb(); <add> }, 1000); <add> })); <add>}); <add> <add>test(function serverNoEndKeepAliveTimeoutWithPipeline(cb) { <add> let socket; <add> let destroyedSockets = 0; <add> let timeoutCount = 0; <add> let requestCount = 0; <add> process.on('exit', () => { <add> assert.strictEqual(timeoutCount, 1); <add> assert.strictEqual(requestCount, 3); <add> assert.strictEqual(destroyedSockets, 1); <add> }); <add> const server = http.createServer((req, res) => { <add> socket = req.socket; <add> requestCount++; <add> }); <add> server.setTimeout(200, (socket) => { <add> timeoutCount++; <add> socket.destroy(); <add> }); <add> server.keepAliveTimeout = 50; <add> server.listen(0, common.mustCall(() => { <add> const options = { <add> port: server.address().port, <add> allowHalfOpen: true <add> }; <add> const c = net.connect(options, () => { <add> c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> }); <add> setTimeout(() => { <add> server.close(); <add> if (socket.destroyed) destroyedSockets++; <add> cb(); <add> }, 1000); <add> })); <add>}); <ide><path>test/parallel/test-https-server-keep-alive-timeout.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const https = require('https'); <add>const tls = require('tls'); <add>const fs = require('fs'); <add> <add>const tests = []; <add> <add>const serverOptions = { <add> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <add> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <add>}; <add> <add>function test(fn) { <add> if (!tests.length) { <add> process.nextTick(run); <add> } <add> tests.push(fn); <add>} <add> <add>function run() { <add> const fn = tests.shift(); <add> if (fn) fn(run); <add>} <add> <add>test(function serverKeepAliveTimeoutWithPipeline(cb) { <add> let socket; <add> let destroyedSockets = 0; <add> let timeoutCount = 0; <add> let requestCount = 0; <add> process.on('exit', function() { <add> assert.strictEqual(timeoutCount, 1); <add> assert.strictEqual(requestCount, 3); <add> assert.strictEqual(destroyedSockets, 1); <add> }); <add> const server = https.createServer(serverOptions, (req, res) => { <add> socket = req.socket; <add> requestCount++; <add> res.end(); <add> }); <add> server.setTimeout(200, (socket) => { <add> timeoutCount++; <add> socket.destroy(); <add> }); <add> server.keepAliveTimeout = 50; <add> server.listen(0, common.mustCall(() => { <add> const options = { <add> port: server.address().port, <add> allowHalfOpen: true, <add> rejectUnauthorized: false <add> }; <add> const c = tls.connect(options, () => { <add> c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> }); <add> setTimeout(() => { <add> server.close(); <add> if (socket.destroyed) destroyedSockets++; <add> cb(); <add> }, 1000); <add> })); <add>}); <add> <add>test(function serverNoEndKeepAliveTimeoutWithPipeline(cb) { <add> let socket; <add> let destroyedSockets = 0; <add> let timeoutCount = 0; <add> let requestCount = 0; <add> process.on('exit', () => { <add> assert.strictEqual(timeoutCount, 1); <add> assert.strictEqual(requestCount, 3); <add> assert.strictEqual(destroyedSockets, 1); <add> }); <add> const server = https.createServer(serverOptions, (req, res) => { <add> socket = req.socket; <add> requestCount++; <add> }); <add> server.setTimeout(200, (socket) => { <add> timeoutCount++; <add> socket.destroy(); <add> }); <add> server.keepAliveTimeout = 50; <add> server.listen(0, common.mustCall(() => { <add> const options = { <add> port: server.address().port, <add> allowHalfOpen: true, <add> rejectUnauthorized: false <add> }; <add> const c = tls.connect(options, () => { <add> c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> }); <add> setTimeout(() => { <add> server.close(); <add> if (socket && socket.destroyed) destroyedSockets++; <add> cb(); <add> }, 1000); <add> })); <add>});
6
Mixed
Ruby
expect xcode 7.1
f6cf1a4025b80a01427570d9b451b9f3fd684a7e
<ide><path>Library/Homebrew/os/mac.rb <ide> def preferred_arch <ide> "6.4" => { :clang => "6.1", :clang_build => 602 }, <ide> "7.0" => { :clang => "7.0", :clang_build => 700 }, <ide> "7.0.1" => { :clang => "7.0", :clang_build => 700 }, <add> "7.1" => { :clang => "7.0", :clang_build => 700 }, <ide> } <ide> <ide> def compilers_standard? <ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def latest_version <ide> when "10.7" then "4.6.3" <ide> when "10.8" then "5.1.1" <ide> when "10.9" then "6.2" <del> when "10.10" then "7.0.1" <del> when "10.11" then "7.0.1" <add> when "10.10" then "7.1" <add> when "10.11" then "7.1" <ide> else <ide> # Default to newest known version of Xcode for unreleased OSX versions. <ide> if OS::Mac.prerelease? <del> "7.0.1" <add> "7.1" <ide> else <ide> raise "OS X '#{MacOS.version}' is invalid" <ide> end <ide> def installed? <ide> <ide> def latest_version <ide> case MacOS.version <del> when "10.11" then "700.0.72" <del> when "10.10" then "700.0.72" <add> when "10.11" then "700.1.76" <add> when "10.10" then "700.1.76" <ide> when "10.9" then "600.0.57" <ide> when "10.8" then "503.0.40" <ide> else <ide><path>share/doc/homebrew/Xcode.md <ide> Tools available for your platform: <ide> 10.7 | 4.6.3 | April 2013 <ide> 10.8 | 5.1.1 | April 2014 <ide> 10.9 | 6.2 | 6.2 <del> 10.10 | 7.0.1 | 7.0.1 <del> 10.11 | 7.0.1 | 7.0.1 <add> 10.10 | 7.1 | 7.1 <add> 10.11 | 7.1 | 7.1 <ide> <ide> <ide> ## Compiler Version Database <ide> Tools available for your platform: <ide> 6.4 | — | — | — | — | 6.1 (602.0.53) | 3.6 <ide> 7.0 | — | — | — | — | 7.0 (700.0.72) | - <ide> 7.0.1 | — | — | — | — | 7.0 (700.0.72) | - <add> 7.1 | — | — | — | — | 7.0 (700.1.76) | - <ide> <ide> ## References to Xcode and compiler versions in code <ide> When a new Xcode release is made, the following things need to be
3
Javascript
Javascript
restore csstransitiongroup tests
b918f7fc079a4d0ebc5d028d102e969dfe97f0b6
<ide><path>src/addons/transitions/__tests__/ReactCSSTransitionGroup-test.js <ide> describe('ReactCSSTransitionGroup', function() { <ide> expect(a.getDOMNode().childNodes[0].id).toBe('three'); <ide> expect(a.getDOMNode().childNodes[1].id).toBe('two'); <ide> }); <del> return; <add> <ide> it('should work with no children', function () { <ide> React.renderComponent( <ide> <ReactCSSTransitionGroup transitionName="yolo">
1
Javascript
Javascript
update reactdebughooks to handle composite hooks
e1c7e651feb7d8f0339db5720cfb61b036ee7290
<ide><path>packages/react-debug-tools/src/ReactDebugHooks.js <ide> function useResponder( <ide> function useTransition( <ide> config: SuspenseConfig | null | void, <ide> ): [(() => void) => void, boolean] { <del> nextHook(); <add> // useTransition() composes multiple hooks internally. <add> // Advance the current hook index the same number of times <add> // so that subsequent hooks have the right memoized state. <add> nextHook(); // State <add> nextHook(); // Callback <ide> hookLog.push({ <ide> primitive: 'Transition', <ide> stackError: new Error(), <ide> function useTransition( <ide> } <ide> <ide> function useDeferredValue<T>(value: T, config: TimeoutConfig | null | void): T { <del> nextHook(); <add> // useDeferredValue() composes multiple hooks internally. <add> // Advance the current hook index the same number of times <add> // so that subsequent hooks have the right memoized state. <add> nextHook(); // State <add> nextHook(); // Effect <ide> hookLog.push({ <ide> primitive: 'DeferredValue', <ide> stackError: new Error(), <ide><path>packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js <ide> describe('ReactHooksInspectionIntegration', () => { <ide> ]); <ide> }); <ide> <add> if (__EXPERIMENTAL__) { <add> it('should support composite useTransition hook', () => { <add> function Foo(props) { <add> React.useTransition(); <add> const memoizedValue = React.useMemo(() => 'hello', []); <add> return <div>{memoizedValue}</div>; <add> } <add> let renderer = ReactTestRenderer.create(<Foo />); <add> let childFiber = renderer.root.findByType(Foo)._currentFiber(); <add> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber); <add> expect(tree).toEqual([ <add> { <add> id: 0, <add> isStateEditable: false, <add> name: 'Transition', <add> value: undefined, <add> subHooks: [], <add> }, <add> { <add> id: 1, <add> isStateEditable: false, <add> name: 'Memo', <add> value: 'hello', <add> subHooks: [], <add> }, <add> ]); <add> }); <add> <add> it('should support composite useDeferredValue hook', () => { <add> function Foo(props) { <add> React.useDeferredValue('abc', { <add> timeoutMs: 500, <add> }); <add> const [state] = React.useState(() => 'hello', []); <add> return <div>{state}</div>; <add> } <add> let renderer = ReactTestRenderer.create(<Foo />); <add> let childFiber = renderer.root.findByType(Foo)._currentFiber(); <add> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber); <add> expect(tree).toEqual([ <add> { <add> id: 0, <add> isStateEditable: false, <add> name: 'DeferredValue', <add> value: 'abc', <add> subHooks: [], <add> }, <add> { <add> id: 1, <add> isStateEditable: true, <add> name: 'State', <add> value: 'hello', <add> subHooks: [], <add> }, <add> ]); <add> }); <add> } <add> <ide> describe('useDebugValue', () => { <ide> it('should support inspectable values for multiple custom hooks', () => { <ide> function useLabeledValue(label) {
2
Text
Text
fix russian translate
1b214fdec10125b80744fc2d99dbce2533488719
<ide><path>guide/russian/php/arrays/sorting-arrays/index.md <ide> localeTitle: Сортировка массивов <ide> <ide> PHP предлагает несколько функций для сортировки массивов. На этой странице описаны различные функции и примеры. <ide> <del>### Сортировать() <add>### sort() <ide> <ide> Функция `sort()` сортирует значения массива в порядке возрастания в алфавитном / цифровом порядке (например, A, B, C, D, E ... 5, 4, 3, 2, 1 ...) <ide> <ide> PHP предлагает несколько функций для сортиро <ide> print_r($freecodecamp); <ide> ``` <ide> <del>**Выход:** <add>**Вывод:** <ide> <ide> ```text <ide> Array <ide> Array <ide> print_r($freecodecamp); <ide> ``` <ide> <del>**Выход:** <add>**Вывод:** <ide> <ide> ```text <ide> Array <ide> Array <ide> print_r($freecodecamp); <ide> ``` <ide> <del>**Выход:** <add>**Вывод:** <ide> <ide> ```text <ide> Array <ide> Array <ide> print_r($freecodecamp); <ide> ``` <ide> <del>**Выход:** <add>**Вывод:** <ide> <ide> ```text <ide> Array <ide> Array <ide> print_r($freecodecamp); <ide> ``` <ide> <del>**Выход:** <add>**Вывод:** <ide> <ide> ```text <ide> Array <ide> Array <ide> print_r($freecodecamp); <ide> ``` <ide> <del>**Выход:** <add>**Вывод:** <ide> <ide> ```text <ide> Array <ide> Array <ide> * [Руководство пользователя php.net ksort ()](https://secure.php.net/manual/en/function.ksort.php) <ide> * [Руководство пользователя php.net arsort ()](https://secure.php.net/manual/en/function.arsort.php) <ide> * [Руководство пользователя php.net krsort ()](https://secure.php.net/manual/en/function.krsort.php) <del>* [Руководство пользователя php.net print\_r ()](https://secure.php.net/manual/en/function.print-r.php) <ide>\ No newline at end of file <add>* [Руководство пользователя php.net print\_r ()](https://secure.php.net/manual/en/function.print-r.php)
1
Javascript
Javascript
use weakmap for hashing objects if available
e345f6677f907ed564ac2629e461aa599cbdde88
<ide><path>dist/Immutable.js <ide> function hashString(string) { <ide> return hash; <ide> } <ide> function hashJSObj(obj) { <del> var hash = obj[UID_HASH_KEY]; <add> var hash = weakMap && weakMap.get(obj); <add> if (hash) <add> return hash; <add> hash = obj[UID_HASH_KEY]; <ide> if (hash) <ide> return hash; <ide> if (!canDefineProperty) { <ide> function hashJSObj(obj) { <ide> if (hash) <ide> return hash; <ide> } <del> if (!canDefineProperty || Object.isExtensible(obj)) { <del> hash = ++objHashUID & HASH_MAX_VAL; <del> if (canDefineProperty) { <del> Object.defineProperty(obj, UID_HASH_KEY, { <del> 'enumerable': false, <del> 'configurable': false, <del> 'writable': false, <del> 'value': hash <del> }); <del> } else if (propertyIsEnumerable && obj.propertyIsEnumerable === propertyIsEnumerable) { <del> obj.propertyIsEnumerable = function() { <del> return propertyIsEnumerable.apply(this, arguments); <del> }; <del> obj.propertyIsEnumerable[UID_HASH_KEY] = hash; <del> } else if (obj.nodeType) { <del> obj[UID_HASH_KEY] = hash; <del> } else { <del> throw new Error('Unable to set a non-enumerable property on object.'); <del> } <del> return hash; <del> } else { <add> if (canDefineProperty && !Object.isExtensible(obj)) { <ide> throw new Error('Non-extensible objects are not allowed as keys.'); <ide> } <add> hash = ++objHashUID & HASH_MAX_VAL; <add> if (weakMap) { <add> weakMap.set(obj, hash); <add> } else if (canDefineProperty) { <add> Object.defineProperty(obj, UID_HASH_KEY, { <add> 'enumerable': false, <add> 'configurable': false, <add> 'writable': false, <add> 'value': hash <add> }); <add> } else if (propertyIsEnumerable && obj.propertyIsEnumerable === propertyIsEnumerable) { <add> obj.propertyIsEnumerable = function() { <add> return propertyIsEnumerable.apply(this, arguments); <add> }; <add> obj.propertyIsEnumerable[UID_HASH_KEY] = hash; <add> } else if (obj.nodeType) { <add> obj[UID_HASH_KEY] = hash; <add> } else { <add> throw new Error('Unable to set a non-enumerable property on object.'); <add> } <add> return hash; <ide> } <ide> var propertyIsEnumerable = Object.prototype.propertyIsEnumerable; <ide> var canDefineProperty = (function() { <ide> function getIENodeHash(node) { <ide> } <ide> } <ide> } <add>var weakMap = typeof WeakMap === 'function' && new WeakMap(); <ide> var HASH_MAX_VAL = 0x7FFFFFFF; <ide> var objHashUID = 0; <ide> var UID_HASH_KEY = '__immutablehash__'; <del>if (typeof Symbol !== 'undefined') { <add>if (typeof Symbol === 'function') { <ide> UID_HASH_KEY = Symbol(UID_HASH_KEY); <ide> } <ide> var STRING_HASH_CACHE_MIN_STRLEN = 16; <ide><path>dist/Immutable.min.js <ide> * LICENSE file in the root directory of this source tree. An additional grant <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> */ <del>function t(){function t(t,e,r,n){var i;if(n){var u=n.prototype;i=Ee.create(u)}else i=t.prototype;return Ee.keys(e).forEach(function(t){i[t]=e[t]}),Ee.keys(r).forEach(function(e){t[e]=r[e]}),i.constructor=t,t.prototype=i,t}function e(t,e,r,n){return Ee.getPrototypeOf(e)[r].apply(t,n)}function r(t,r,n){e(t,r,"constructor",n)}function n(t,e){return t===e?0!==t||0!==e||1/t===1/e:t!==t?e!==e:t&&"function"==typeof t.equals?t.equals(e):!1}function i(t){return t.value=!1,t}function u(t){t&&(t.value=!0)}function a(){}function s(t,e){e=e||0;for(var r=Math.max(0,t.length-e),n=Array(r),i=0;r>i;i++)n[i]=t[i+e];return n}function o(t,e){if(!t)throw Error(e)}function h(t){if(!t)return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){if((0|t)===t)return t&Le;t=""+t,e="string"}return"string"===e?t.length>Fe?c(t):f(t):t.hashCode?h("function"==typeof t.hashCode?t.hashCode():t.hashCode):_(t)}function c(t){var e=Qe[t];return null==e&&(e=f(t),He===Ge&&(He=0,Qe={}),He++,Qe[t]=e),e}function f(t){for(var e=0,r=0;t.length>r;r++)e=31*e+t.charCodeAt(r)&Le;return e}function _(t){var e=t[Te];if(e)return e;if(!Ve){if(e=t.propertyIsEnumerable&&t.propertyIsEnumerable[Te])return e;if(e=l(t))return e}if(!Ve||Object.isExtensible(t)){if(e=++Ne&Le,Ve)Object.defineProperty(t,Te,{enumerable:!1,configurable:!1,writable:!1,value:e});else if(Be&&t.propertyIsEnumerable===Be)t.propertyIsEnumerable=function(){return Be.apply(this,arguments)},t.propertyIsEnumerable[Te]=e;else{if(!t.nodeType)throw Error("Unable to set a non-enumerable property on object.");t[Te]=e}return e}throw Error("Non-extensible objects are not allowed as keys.")}function l(t){if(t&&t.nodeType>0)switch(t.nodeType){case 1:return t.uniqueID;case 9:return t.documentElement&&t.documentElement.uniqueID}}function v(t,e,r,n){var i=0===t?e:1===t?r:[e,r];return n?n.value=i:n={value:i,done:!1},n}function g(){return{value:void 0,done:!0}}function p(t){return!!y(t)}function m(t){return t&&"function"==typeof t.next}function d(t){var e=y(t);return e&&e.call(t)}function y(t){var e=t&&(tr&&t[tr]||t[$e]); <del>return"function"==typeof e?e:void 0}function w(t){return null==t.length&&t.cacheResult(),o(1/0>t.length,"Cannot reverse infinite range."),t.length}function S(t,e,r){return(0===t||null!=r&&-r>=t)&&(null==e||null!=r&&e>=r)}function I(t,e){return b(t,e,0)}function q(t,e){return b(t,e,e)}function b(t,e,r){return null==t?r:0>t?Math.max(0,e+t):e?Math.min(e,t):t}function x(t){return t}function k(t,e){return[e,t]}function M(){return!0}function D(t){return function(){return!t.apply(this,arguments)}}function O(t){return"string"==typeof t?JSON.stringify(t):t}function C(t,e){return t>e?1:e>t?-1:0}function A(t,e){return 0>e?(null==t.length&&t.cacheResult(),t.length+e):e}function E(t){o(1/0!==t,"Cannot perform this action with an infinite sequence.")}function j(t,e,r,n){var i=t._cache;if(i){for(var u=i.length-1,a=0;u>=a;a++){var s=i[r?u-a:a];if(e(s[1],n?s[0]:a,t)===!1)return a+1}return a}return t.__iterateUncached(e,r)}function R(t,e,r,n){var i=t._cache;if(i){var u=i.length-1,a=0;return new rr(function(){var t=i[r?u-a:a];return a++>u?g():v(e,n?t[0]:a-1,t[1])})}return t.__iteratorUncached(e,r)}function U(t){var e=t.__makeSequence();return e.length=t.length,e.flip=function(){return t},e.reverse=function(){var e=t.reverse.apply(this);return e.flip=function(){return t.reverse()},e},e.has=function(e){return t.contains(e)},e.contains=function(e){return t.has(e)},e.__iterateUncached=function(e,r){var n=this;return t.__iterate(function(t,r){return e(r,t,n)!==!1},r)},e.__iteratorUncached=function(e,r){if(e===Ze){var n=t.__iterator(e,r);return new rr(function(){var t=n.next();if(!t.done){var e=t.value[0];t.value[0]=t.value[1],t.value[1]=e}return t})}return t.__iterator(e===Ye?Xe:Ye,r)},e}function P(t,e,r){var n=t.__makeSequence();return n.length=t.length,n.has=function(e){return t.has(e)},n.get=function(n,i){var u=t.get(n,Ke);return u===Ke?i:e.call(r,u,n,t)},n.__iterateUncached=function(n,i){var u=this;return t.__iterate(function(t,i,a){return n(e.call(r,t,i,a),i,u)!==!1},i)},n.__iteratorUncached=function(n,i){var u=t.__iterator(Ze,i);return new rr(function(){var i=u.next(); <del>if(i.done)return i;var a=i.value,s=a[0];return v(n,s,e.call(r,a[1],s,t),i)})},n}function W(t,e){var r=t.__makeSequence();return r.length=t.length,r.reverse=function(){return t},r.flip=function(){var e=t.flip.apply(this);return e.reverse=function(){return t.flip()},e},r.get=function(r,n){return t.get(e?r:-1-r,n)},r.has=function(r){return t.has(e?r:-1-r)},r.contains=function(e){return t.contains(e)},r.cacheResult=function(){return t.cacheResult(),this.length=t.length,this},r.__iterate=function(e,r){var n=this;return t.__iterate(function(t,r){return e(t,r,n)},!r)},r.__iterator=function(e,r){return t.__iterator(e,!r)},r}function K(t,e,r,n){var i=t.__makeSequence();return n&&(i.has=function(n){var i=t.get(n,Ke);return i!==Ke&&!!e.call(r,i,n,t)},i.get=function(n,i){var u=t.get(n,Ke);return u!==Ke&&e.call(r,u,n,t)?u:i}),i.__iterateUncached=function(i,u){var a=this,s=0;return t.__iterate(function(t,u,o){return e.call(r,t,u,o)?(s++,i(t,n?u:s-1,a)):void 0},u),s},i.__iteratorUncached=function(i,u){var a=t.__iterator(Ze,u),s=0;return new rr(function(){for(;;){var u=a.next();if(u.done)return u;var o=u.value,h=o[0],c=o[1];if(e.call(r,c,h,t))return v(i,n?h:s++,c,u)}})},i}function z(t,e,r,n){var i={},u=[];return t.__iterate(function(a,s){var o=e.call(r,a,s,t),c=h(o),f=n?[s,a]:a;i.hasOwnProperty(c)?u[i[c]][1].push(f):(i[c]=u.length,u.push([o,[f]]))}),ir(u).fromEntrySeq().map(n?function(t){return ir(t).fromEntrySeq()}:function(t){return ir(t)})}function J(t,e){if(e>t.length)return t;0>e&&(e=0);var r=t.__makeSequence();return r.length=t.length&&Math.min(t.length,e),r.__iterateUncached=function(r,n){var i=this;if(0===e)return 0;if(n)return this.cacheResult().__iterate(r,n);var u=0;return t.__iterate(function(t,n){return++u&&r(t,n,i)!==!1&&e>u}),u},r.__iteratorUncached=function(r,n){if(n)return this.cacheResult().__iterator(r,n);var i=e&&t.__iterator(r,n),u=0;return new rr(function(){return u++>e?g():i.next()})},r}function B(t,e,r){var n=t.__makeSequence();return n.__iterateUncached=function(n,i){var u=this;if(i)return this.cacheResult().__iterate(n,i); <del>var a=0;return t.__iterate(function(t,i,s){return e.call(r,t,i,s)&&++a&&n(t,i,u)}),a},n.__iteratorUncached=function(n,i){var u=this;if(i)return this.cacheResult().__iterator(n,i);var a=t.__iterator(Ze,i),s=!0;return new rr(function(){if(!s)return g();var t=a.next();if(t.done)return t;var i=t.value,o=i[0],h=i[1];return e.call(r,h,o,u)?n===Ze?t:v(n,o,h,t):(s=!1,g())})},n}function V(t,e,r){if(0>=e)return t;var n=t.__makeSequence();return n.length=t.length&&Math.max(0,t.length-e),n.__iterateUncached=function(n,i){var u=this;if(i)return this.cacheResult().__iterate(n,i);var a=0,s=!0,o=0;return t.__iterate(function(t,i){return s&&(s=a++<e)?void 0:(o++,n(t,r?i:o-1,u))}),o},n.__iteratorUncached=function(n,i){if(i)return this.cacheResult().__iterator(n,i);var u=e&&t.__iterator(n,i),a=0,s=0;return new rr(function(){for(;e>a;)a++,u.next();var t=u.next();return r||n===Ye?t:n===Xe?v(n,s++,null,t):v(n,s++,t.value[1],t)})},n}function L(t,e,r,n){var i=t.__makeSequence();return i.__iterateUncached=function(i,u){var a=this;if(u)return this.cacheResult().__iterate(i,u);var s=!0,o=0;return t.__iterate(function(t,u,h){return s&&(s=e.call(r,t,u,h))?void 0:(o++,i(t,n?u:o-1,a))}),o},i.__iteratorUncached=function(i,u){var a=this;if(u)return this.cacheResult().__iterator(i,u);var s=t.__iterator(Ze,u),o=!0,h=0;return new rr(function(){var t,u,c;do{if(t=s.next(),t.done)return n||i===Ye?t:i===Xe?v(i,h++,null,t):v(i,h++,t.value[1],t);var f=t.value;u=f[0],c=f[1],o&&(o=e.call(r,c,u,a))}while(o);return i===Ze?t:v(i,u,c,t)})},i}function N(t,e,r){var n=[t].concat(e),i=ir(n);return r&&(i=i.toKeyedSeq()),i=i.flatMap(x),i.length=n.reduce(function(t,e){if(void 0!==t){var r=ir(e).length;if(null!=r)return t+r}},0),i}function T(t,e,r){var n=t.__makeSequence();return n.__iterateUncached=function(n,i){function u(t,o){var h=this;t.__iterate(function(t,i){return(!e||e>o)&&t instanceof ir?u(t,o+1):n(t,r?i:a++,h)===!1&&(s=!0),!s},i)}var a=0,s=!1;return u(t,0),a},n.__iteratorUncached=function(n,i){var u=t.__iterator(n,i),a=[],s=0;return new rr(function(){for(;u;){var t=u.next(); <del>if(t.done===!1){var o=t.value;if(n===Ze&&(o=o[1]),!((!e||e>a.length)&&o instanceof ir))return r?t:v(n,s++,o,t);a.push(u),u=o.__iterator(n,i)}else u=a.pop()}return g()})},n}function F(t,e){var r=t.__makeSequence();return r.length=t.length&&2*t.length-1,r.__iterateUncached=function(r,n){var i=this,u=0;return t.__iterate(function(t){return(!u||r(e,u++,i)!==!1)&&r(t,u++,i)!==!1},n),u},r.__iteratorUncached=function(r,n){var i,u=t.__iterator(Ye,n),a=0;return new rr(function(){return(!i||a%2)&&(i=u.next(),i.done)?i:a%2?v(r,a++,e):v(r,a++,i.value,i)})},r}function G(t,e){return v(t,e[0],e[1])}function H(t,e){return{node:t,index:0,__prev:e}}function Q(t,e,r,n){var i=Object.create(yr);return i.length=t,i._root=e,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function X(t,e,r){var n=i(ze),u=i(Je),a=Y(t._root,t.__ownerID,0,h(e),e,r,n,u);if(!u.value)return t;var s=t.length+(n.value?r===Ke?-1:1:0);return t.__ownerID?(t.length=s,t._root=a,t.__hash=void 0,t.__altered=!0,t):a?Q(s,a):mr.empty()}function Y(t,e,r,n,i,a,s,o){return t?t.update(e,r,n,i,a,s,o):a===Ke?t:(u(o),u(s),new kr(e,n,[i,a]))}function Z(t){return t.constructor===kr||t.constructor===br}function $(t,e,r,n,i){if(t.hash===n)return new br(e,n,[t.entry,i]);var u,a=(0===r?t.hash:t.hash>>>r)&We,s=(0===r?n:n>>>r)&We,o=a===s?[$(t,e,r+Ue,n,i)]:(u=new kr(e,n,i),s>a?[t,u]:[u,t]);return new wr(e,1<<a|1<<s,o)}function te(t,e,r,n){for(var i=0,u=0,a=Array(r),s=0,o=1,h=e.length;h>s;s++,o<<=1){var c=e[s];null!=c&&s!==n&&(i|=o,a[u++]=c)}return new wr(t,i,a)}function ee(t,e,r,n,i){for(var u=0,a=Array(Pe),s=0;0!==r;s++,r>>>=1)a[s]=1&r?e[u++]:null;return a[n]=i,new Ir(t,u+1,a)}function re(t,e,r){for(var n=[],i=0;r.length>i;i++){var u=r[i];u instanceof ir||(u=ir(u),u instanceof sr&&(u=u.fromEntrySeq())),u&&n.push(u)}return ie(t,e,n)}function ne(t){return function(e,r){return e&&e.mergeDeepWith?e.mergeDeepWith(t,r):t?t(e,r):r}}function ie(t,e,r){return 0===r.length?t:t.withMutations(function(t){for(var n=e?function(r,n){var i=t.get(n,Ke);t.set(n,i===Ke?r:e(i,r))}:function(e,r){t.set(r,e)},i=0;r.length>i;i++)r[i].forEach(n) <del>})}function ue(t,e,r,n,i){var u=e.length;if(i===u)return n(t);o(t.set,"updateIn with invalid keyPath");var a=i===u-1?r:mr.empty(),s=e[i],h=t.get(s,a),c=ue(h,e,r,n,i+1);return c===h?t:t.set(s,c)}function ae(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function se(t,e,r,n){var i=n?t:s(t);return i[e]=r,i}function oe(t,e,r,n){var i=t.length+1;if(n&&e+1===i)return t[e]=r,t;for(var u=Array(i),a=0,s=0;i>s;s++)s===e?(u[s]=r,a=-1):u[s]=t[s+a];return u}function he(t,e,r){var n=t.length-1;if(r&&e===n)return t.pop(),t;for(var i=Array(n),u=0,a=0;n>a;a++)a===e&&(u=1),i[a]=t[a+u];return i}function ce(t,e,r,n,i,u){var a,s=t&&t.array;if(0===e){var o=0>r?-r:0,h=n-r;for(h>Pe&&(h=Pe),a=o;h>a;a++)if(i(s&&s[u?o+h-1-a:a])===!1)return!1}else{var c=1<<e,f=e-Ue;for(a=0;We>=a;a++){var _=u?We-a:a,l=r+(_<<e);if(n>l&&l+c>0){var v=s&&s[_];if(!ce(v,f,l,n,i,u))return!1}}}return!0}function fe(t,e,r,n,i){return{array:t,level:e,offset:r,max:n,rawMax:n-r>>e,index:0,__prev:i}}function _e(t,e,r,n,i,u,a){var s=Object.create(Rr);return s.length=e-t,s._origin=t,s._size=e,s._level=r,s._root=n,s._tail=i,s.__ownerID=u,s.__hash=a,s.__altered=!1,s}function le(t,e,r){if(e=A(t,e),e>=t.length||0>e)return r===Ke?t:t.withMutations(function(t){0>e?me(t,e).set(0,r):me(t,0,e+1).set(e,r)});e+=t._origin;var n=t._tail,u=t._root,a=i(Je);return e>=ye(t._size)?n=ve(n,t.__ownerID,0,e,r,a):u=ve(u,t.__ownerID,t._level,e,r,a),a.value?t.__ownerID?(t._root=u,t._tail=n,t.__hash=void 0,t.__altered=!0,t):_e(t._origin,t._size,t._level,u,n):t}function ve(t,e,r,n,i,a){var s,o=i===Ke,h=n>>>r&We,c=t&&t.array.length>h;if(o&&!c)return t;if(r>0){var f=t&&t.array[h],_=ve(f,e,r-Ue,n,i,a);return _===f?t:(s=ge(t,e),s.array[h]=_,s)}return!o&&c&&t.array[h]===i?t:(u(a),s=ge(t,e),o&&h===s.array.length-1?s.array.pop():s.array[h]=o?void 0:i,s)}function ge(t,e){return e&&t&&e===t.ownerID?t:new Ur(t?t.array.slice():[],e)}function pe(t,e){if(e>=ye(t._size))return t._tail;if(1<<t._level+Ue>e){for(var r=t._root,n=t._level;r&&n>0;)r=r.array[e>>>n&We],n-=Ue; <del>return r}}function me(t,e,r){var n=t.__ownerID||new a,i=t._origin,u=t._size,s=i+e,o=null==r?u:0>r?u+r:i+r;if(s===i&&o===u)return t;if(s>=o)return t.clear();for(var h=t._level,c=t._root,f=0;0>s+f;)c=new Ur(c&&c.array.length?[null,c]:[],n),h+=Ue,f+=1<<h;f&&(s+=f,i+=f,o+=f,u+=f);for(var _=ye(u),l=ye(o);l>=1<<h+Ue;)c=new Ur(c&&c.array.length?[c]:[],n),h+=Ue;var v=t._tail,g=_>l?pe(t,o-1):l>_?new Ur([],n):v;if(v&&l>_&&u>s&&v.array.length){c=ge(c,n);for(var p=c,m=h;m>Ue;m-=Ue){var d=_>>>m&We;p=p.array[d]=ge(p.array[d],n)}p.array[_>>>Ue&We]=v}if(u>o&&(g=g&&g.removeAfter(n,0,o)),s>=l)s-=l,o-=l,h=Ue,c=null,g=g&&g.removeBefore(n,0,s);else if(s>i||_>l){var y,w;f=0;do y=s>>>h&We,w=l-1>>>h&We,y===w&&(y&&(f+=(1<<h)*y),h-=Ue,c=c&&c.array[y]);while(c&&y===w);c&&s>i&&(c=c&&c.removeBefore(n,h,s-f)),c&&_>l&&(c=c&&c.removeAfter(n,h,l-f)),f&&(s-=f,o-=f)}return t.__ownerID?(t.length=o-s,t._origin=s,t._size=o,t._level=h,t._root=c,t._tail=g,t.__hash=void 0,t.__altered=!0,t):_e(s,o,h,c,g)}function de(t,e,r){for(var n=[],i=0;r.length>i;i++){var u=r[i];u&&n.push(ir(u))}var a=Math.max.apply(null,n.map(function(t){return t.length||0}));return a>t.length&&(t=t.setLength(a)),ie(t,e,n)}function ye(t){return Pe>t?0:t-1>>>Ue<<Ue}function we(t,e,r,n){var i=Object.create(Br);return i.length=t,i._head=e,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function Se(t,e){var r=Object.create(Tr);return r.length=t?t.length:0,r._map=t,r.__ownerID=e,r}function Ie(t,e,r,n){var i=Object.create(Gr.prototype);return i.length=t?t.length:0,i._map=t,i._vector=e,i.__ownerID=r,i.__hash=n,i}function qe(t,e,r){var n=t._map,i=t._vector,u=n.get(e),a=void 0!==u,s=r===Ke;if(!a&&s||a&&r===i.get(u)[1])return t;a||(u=i.length);var o=s?n.remove(e):a?n:n.set(e,u),h=s?i.remove(u):i.set(u,[e,r]);return t.__ownerID?(t.length=o.length,t._map=o,t._vector=h,t.__hash=void 0,t):Ie(o,h)}function be(t,e,r){var n=Object.create(Object.getPrototypeOf(t));return n._map=e,n.__ownerID=r,n}function xe(t,e){return e?ke(e,t,"",{"":t}):Me(t)}function ke(t,e,r,n){return e&&(Array.isArray(e)||e.constructor===Object)?t.call(n,r,ir(e).map(function(r,n){return ke(t,r,n,e) <del>})):e}function Me(t){if(t){if(Array.isArray(t))return ir(t).map(Me).toVector();if(t.constructor===Object)return ir(t).map(Me).toMap()}return t}function De(t,e,r,n){4>arguments.length&&(n=t.getIn(e));var i=n instanceof ir?n.length:null,u=n instanceof sr?hn:sn;return new u(t,e,r,i)}function Oe(t,e,r){return r instanceof ir?Ce(t,e,r):r}function Ce(t,e,r){return De(t._rootData,t._keyPath.concat(e),t._onChange,r)}function Ae(t,e,r){var n=t._rootData.updateIn(t._keyPath,r?mr.empty():void 0,e),i=t._keyPath||[];return t._onChange&&t._onChange.call(void 0,n,t._rootData,r?i.concat(r):i),De(n,t._keyPath,t._onChange)}var Ee=Object,je={};je.createClass=t,je.superCall=e,je.defaultSuperCall=r;var Re="delete",Ue=5,Pe=1<<Ue,We=Pe-1,Ke={},ze={value:!1},Je={value:!1},Be=Object.prototype.propertyIsEnumerable,Ve=function(){try{return Object.defineProperty({},"x",{}),!0}catch(t){return!1}}(),Le=2147483647,Ne=0,Te="__immutablehash__";"undefined"!=typeof Symbol&&(Te=Symbol(Te));var Fe=16,Ge=255,He=0,Qe={},Xe=0,Ye=1,Ze=2,$e="@@iterator",tr="function"==typeof Symbol&&Symbol.iterator,er=tr||$e,rr=function(t){this.next=t};je.createClass(rr,{toString:function(){return"[Iterator]"}},{});var nr=rr.prototype;nr.inspect=nr.toSource=function(){return""+this},nr[er]=function(){return this};var ir=function(t){return ur.from(1===arguments.length?t:Array.prototype.slice.call(arguments))},ur=ir;je.createClass(ir,{toArray:function(){E(this.length);var t=Array(this.length||0);return this.valueSeq().__iterate(function(e,r){t[r]=e}),t},toJS:function(){return this.map(function(t){return t instanceof ur?t.toJS():t}).__toJS()},toMap:function(){return E(this.length),mr.from(this)},toObject:function(){E(this.length);var t={};return this.__iterate(function(e,r){t[r]=e}),t},toOrderedMap:function(){return E(this.length),Gr.from(this)},toSet:function(){return E(this.length),Lr.from(this)},toStack:function(){return E(this.length),zr.from(this)},toVector:function(){return E(this.length),Er.from(this)},toString:function(){return this.__toString("Seq {","}")},__toString:function(t,e){return 0===this.length?t+e:t+" "+this.map(this.__toStringMapper).join(", ")+" "+e <del>},__toStringMapper:function(t,e){return e+": "+O(t)},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return N(this,t,!0)},contains:function(t){return this.find(function(e){return n(e,t)},null,Ke)!==Ke},entries:function(){return this.__iterator(Ze)},every:function(t,e){var r=!0;return this.__iterate(function(n,i,u){return t.call(e,n,i,u)?void 0:(r=!1,!1)}),r},filter:function(t,e){return K(this,t,e,!0)},find:function(t,e,r){var n=r;return this.__iterate(function(r,i,u){return t.call(e,r,i,u)?(n=r,!1):void 0}),n},forEach:function(t,e){return this.__iterate(e?t.bind(e):t)},join:function(t){t=void 0!==t?""+t:",";var e="",r=!0;return this.__iterate(function(n){r?r=!1:e+=t,e+=null!=n?n:""}),e},keys:function(){return this.__iterator(Xe)},map:function(t,e){return P(this,t,e)},reduce:function(t,e,r){var n,i;return 2>arguments.length?i=!0:n=e,this.__iterate(function(e,u,a){i?(i=!1,n=e):n=t.call(r,n,e,u,a)}),n},reduceRight:function(){var t=this.toKeyedSeq().reverse();return t.reduce.apply(t,arguments)},reverse:function(){return W(this,!0)},slice:function(t,e){if(S(t,e,this.length))return this;var r=I(t,this.length),n=q(e,this.length);if(r!==r||n!==n)return this.cacheResult().slice(t,e);var i=0===r?this:this.skip(r);return null==n||n===this.length?i:i.take(n-r)},some:function(t,e){return!this.every(D(t),e)},sort:function(t){return this.sortBy(x,t)},values:function(){return this.__iterator(Ye)},butLast:function(){return this.slice(0,-1)},count:function(t,e){return t?this.filter(t,e).count():(null==this.length&&(this.length=this.__iterate(M)),this.length)},countBy:function(t,e){var r=this,n={},i=[];return this.__iterate(function(u,a){var s=t.call(e,u,a,r),o=h(s);n.hasOwnProperty(o)?i[n[o]][1]++:(n[o]=i.length,i.push([s,1]))}),ur(i).fromEntrySeq()},equals:function(t){if(this===t)return!0;if(!(t instanceof ur))return!1;if(null!=this.length&&null!=t.length){if(this.length!==t.length)return!1;if(0===this.length&&0===t.length)return!0}return null!=this.__hash&&null!=t.__hash&&this.__hash!==t.__hash?!1:this.__deepEquals(t) <del>},__deepEquals:function(t){var e=this.entries();return t.every(function(t,r){var i=e.next().value;return i&&n(i[0],r)&&n(i[1],t)})&&e.next().done},entrySeq:function(){var t=this;if(t._cache)return ur(t._cache);var e=t.toKeyedSeq().map(k).valueSeq();return e.fromEntries=function(){return t},e},findKey:function(t,e){var r;return this.__iterate(function(n,i,u){return t.call(e,n,i,u)?(r=i,!1):void 0}),r},findLast:function(t,e,r){return this.toKeyedSeq().reverse().find(t,e,r)},findLastKey:function(t,e){return this.toKeyedSeq().reverse().findKey(t,e)},first:function(){return this.find(M)},flatMap:function(t,e){return this.map(function(r,n,i){return ur(t.call(e,r,n,i))}).flatten(!0)},flatten:function(t){return T(this,t,!0)},flip:function(){return U(this)},get:function(t,e){return this.find(function(e,r){return n(r,t)},null,e)},getIn:function(t,e){var r=this;if(t)for(var n=0;t.length>n;n++)if(r=r&&r.get?r.get(t[n],Ke):Ke,r===Ke)return e;return r},groupBy:function(t,e){return z(this,t,e,!0)},has:function(t){return this.get(t,Ke)!==Ke},keySeq:function(){return this.flip().valueSeq()},last:function(){return this.reverse().first()},mapEntries:function(t,e){var r=this;return this.entrySeq().map(function(n,i){return t.call(e,n,i,r)}).fromEntrySeq()},mapKeys:function(t,e){var r=this;return this.flip().map(function(n,i){return t.call(e,n,i,r)}).flip()},rest:function(){return this.slice(1)},skip:function(t){return V(this,t,!0)},skipLast:function(t){return this.reverse().skip(t).reverse()},skipWhile:function(t,e){return L(this,t,e,!0)},skipUntil:function(t,e){return this.skipWhile(D(t),e)},sortBy:function(t,e){e=e||C;var r=this;return ur(this.entrySeq().entrySeq().toArray().sort(function(n,i){return e(t(n[1][1],n[1][0],r),t(i[1][1],i[1][0],r))||n[0]-i[0]})).fromEntrySeq().valueSeq().fromEntrySeq()},take:function(t){return J(this,t)},takeLast:function(t){return this.reverse().take(t).reverse()},takeWhile:function(t,e){return B(this,t,e)},takeUntil:function(t,e){return this.takeWhile(D(t),e)},toKeyedSeq:function(){return this},valueSeq:function(){return new vr(this) <del>},cacheResult:function(){return!this._cache&&this.__iterateUncached&&(E(this.length),this._cache=this.entrySeq().toArray(),null==this.length&&(this.length=this._cache.length)),this},hashCode:function(){return this.__hash||(this.__hash=1/0===this.length?0:this.reduce(function(t,e,r){return t+(h(e)^(e===r?0:h(r)))&Le},0))},__makeSequence:function(){return Object.create(ar)},__iterate:function(t,e){return j(this,t,e,!0)},__iterator:function(t,e){return R(this,t,e,!0)}},{from:function(t){if(t instanceof ur)return t;if(!Array.isArray(t)){if(m(t))return new cr(t);if(p(t))return new fr(t);if(t&&t.constructor===Object)return new _r(t);t=[t]}return new lr(t)}});var ar=ir.prototype;ar[er]=ar.entries,ar.toJSON=ar.toJS,ar.__toJS=ar.toObject,ar.inspect=ar.toSource=function(){return""+this},ar.chain=ar.flatMap;var sr=function(){je.defaultSuperCall(this,or.prototype,arguments)},or=sr;je.createClass(sr,{toString:function(){return this.__toString("Seq [","]")},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return N(this,t,!1)},filter:function(t,e){return K(this,t,e,!1)},findIndex:function(t,e){var r=this.findKey(t,e);return null==r?-1:r},indexOf:function(t){return this.findIndex(function(e){return n(e,t)})},lastIndexOf:function(t){return this.toKeyedSeq().reverse().indexOf(t)},reverse:function(){return W(this,!1)},splice:function(t,e){var r=arguments.length;if(e=Math.max(0|e,0),0===r||2===r&&!e)return this;t=I(t,this.length);var n=this.slice(0,t);return 1===r?n:n.concat(s(arguments,2),this.slice(t+e))},findLastIndex:function(t,e){return this.toKeyedSeq().reverse().findIndex(t,e)},first:function(){return this.get(0)},flatten:function(t){return T(this,t,!1)},flip:function(){return U(this.toKeyedSeq())},fromEntrySeq:function(){return new pr(this)},get:function(t,e){return t=A(this,t),0>t||1/0===this.length||null!=this.length&&t>this.length?e:this.find(function(e,r){return r===t},null,e)},groupBy:function(t,e){return z(this,t,e,!1)},has:function(t){return t=A(this,t),t>=0&&(null!=this.length?1/0===this.length||this.length>t:-1!==this.indexOf(t)) <del>},interpose:function(t){return F(this,t)},last:function(){return this.get(-1)},skip:function(t){var e=this,r=V(e,t,!1);return r!==e&&(r.get=function(r,n){return r=A(this,r),r>=0?e.get(r+t,n):n}),r},skipWhile:function(t,e){return L(this,t,e,!1)},sortBy:function(t,e){e=e||C;var r=this;return ir(this.entrySeq().toArray().sort(function(n,i){return e(t(n[1],n[0],r),t(i[1],i[0],r))||n[0]-i[0]})).fromEntrySeq().valueSeq()},take:function(t){var e=this,r=J(e,t);return r!==e&&(r.get=function(r,n){return r=A(this,r),r>=0&&t>r?e.get(r,n):n}),r},toKeyedSeq:function(){return new gr(this)},valueSeq:function(){return this},__makeSequence:function(){return Object.create(hr)},__iterate:function(t,e){return j(this,t,e,!1)},__iterator:function(t,e){return R(this,t,e,!1)}},{},ir);var hr=sr.prototype;hr[er]=hr.values,hr.__toJS=hr.toArray,hr.__toStringMapper=O;var cr=function(t){this._iterator=t,this._iteratorCache=[]};je.createClass(cr,{__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);for(var r=this._iterator,n=this._iteratorCache,i=0;n.length>i;)if(t(n[i],i++,this)===!1)return i;for(var u;!(u=r.next()).done;){var a=u.value;if(n[i]=a,t(a,i++,this)===!1)break}return i},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterator,n=this._iteratorCache,i=0;return new rr(function(){if(i>=n.length){var e=r.next();if(e.done)return e;n[i]=e.value}return v(t,i,n[i++])})}},{},sr);var fr=function(t){this._iterable=t,this.length=t.length||t.size};je.createClass(fr,{__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);var r=this._iterable,n=d(r),i=0;if(m(n))for(var u;!(u=n.next()).done&&t(u.value,i++,this)!==!1;);return i},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterable,n=d(r);if(!m(n))return new rr(function(){return g()});var i=0;return new rr(function(){var e=n.next();return e.done?e:v(t,i++,e.value)})}},{},sr);var _r=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.length=e.length};je.createClass(_r,{toObject:function(){return this._object <del>},get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var r=this._object,n=this._keys,i=n.length-1,u=0;i>=u;u++){var a=n[e?i-u:u];if(t(r[a],a,this)===!1)return u+1}return u},__iterator:function(t,e){var r=this._object,n=this._keys,i=n.length-1,u=0;return new rr(function(){var a=n[e?i-u:u];return u++>i?g():v(t,a,r[a])})}},{},ir);var lr=function(t){this._array=t,this.length=t.length};je.createClass(lr,{toArray:function(){return this._array},get:function(t,e){return this.has(t)?this._array[A(this,t)]:e},__iterate:function(t,e){for(var r=this._array,n=r.length-1,i=0;n>=i;i++)if(t(r[e?n-i:i],i,this)===!1)return i+1;return i},__iterator:function(t,e){var r=this._array,n=r.length-1,i=0;return new rr(function(){return i>n?g():v(t,i,r[e?n-i++:i++])})}},{},sr);var vr=function(t){this._seq=t,this.length=t.length};je.createClass(vr,{contains:function(t){return this._seq.contains(t)},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this},__iterate:function(t,e){var r=this,n=0;return this._seq.__iterate(function(e){return t(e,n++,r)},e)},__iterator:function(t,e){var r=this._seq.__iterator(Ye,e),n=0;return new rr(function(){var e=r.next();return e.done?e:v(t,n++,e.value,e)})}},{},sr);var gr=function(t){this._seq=t,this.length=t.length};je.createClass(gr,{get:function(t,e){return this._seq.get(t,e)},has:function(t){return this._seq.has(t)},valueSeq:function(){return this._seq},reverse:function(){var t=this,e=W(this,!0);return e.valueSeq=function(){return t._seq.reverse()},e},map:function(t,e){var r=this,n=P(this,t,e);return n.valueSeq=function(){return r._seq.map(t,e)},n},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this},__iterate:function(t,e){var r=this,n=e?w(this):0;return this._seq.__iterate(function(i){return t(i,e?--n:n++,r)},e)},__iterator:function(t,e){var r=this._seq.__iterator(Ye,e),n=e?w(this):0;return new rr(function(){var i=r.next();return i.done?i:v(t,e?--n:n++,i.value,i) <del>})}},{},ir);var pr=function(t){this._seq=t,this.length=t.length};je.createClass(pr,{entrySeq:function(){return this._seq},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this},__iterate:function(t,e){var r=this;return this._seq.__iterate(function(e){return e&&t(e[1],e[0],r)},e)},__iterator:function(t,e){var r=this._seq.__iterator(Ye,e);return new rr(function(){for(;;){var e=r.next();if(e.done)return e;var n=e.value;if(n)return t===Ze?e:v(t,n[0],n[1],e)}})}},{},ir);var mr=function(t){var e=dr.empty();return t?t.constructor===dr?t:e.merge(t):e},dr=mr;je.createClass(mr,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return this._root?this._root.get(0,h(t),t,e):e},set:function(t,e){return X(this,t,e)},remove:function(t){return X(this,t,Ke)},update:function(t,e,r){return 1===arguments.length?this.updateIn([],void 0,t):this.updateIn([t],e,r)},updateIn:function(t,e,r){return r||(r=e,e=void 0),ue(this,t,e,r,0)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):dr.empty()},merge:function(){return re(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return re(this,t,e)},mergeDeep:function(){return re(this,ne(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return re(this,ne(t),e)},cursor:function(t,e){var r=0===arguments.length||"function"==typeof t&&(e=t)?[]:Array.isArray(t)?t:[t];return De(this,r,e)},withMutations:function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new a)},asImmutable:function(){return this.__ensureOwner()},wasAltered:function(){return this.__altered},__iterator:function(t,e){return new Dr(this,t,e)},__iterate:function(t,e){var r=this,n=0;return this._root&&this._root.iterate(function(e){return n++,t(e[1],e[0],r)},e),n},__ensureOwner:function(t){return t===this.__ownerID?this:t?Q(this.length,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this) <del>}},{empty:function(){return Or||(Or=Q(0))}},ir);var yr=mr.prototype;yr[Re]=yr.remove,mr.from=mr;var wr=function(t,e,r){this.ownerID=t,this.bitmap=e,this.nodes=r},Sr=wr;je.createClass(wr,{get:function(t,e,r,n){var i=1<<((0===t?e:e>>>t)&We),u=this.bitmap;return 0===(u&i)?n:this.nodes[ae(u&i-1)].get(t+Ue,e,r,n)},update:function(t,e,r,n,i,u,a){var s=(0===e?r:r>>>e)&We,o=1<<s,h=this.bitmap,c=0!==(h&o);if(!c&&i===Ke)return this;var f=ae(h&o-1),_=this.nodes,l=c?_[f]:null,v=Y(l,t,e+Ue,r,n,i,u,a);if(v===l)return this;if(!c&&v&&_.length>=Cr)return ee(t,_,h,s,v);if(c&&!v&&2===_.length&&Z(_[1^f]))return _[1^f];if(c&&v&&1===_.length&&Z(v))return v;var g=t&&t===this.ownerID,p=c?v?h:h^o:h|o,m=c?v?se(_,f,v,g):he(_,f,g):oe(_,f,v,g);return g?(this.bitmap=p,this.nodes=m,this):new Sr(t,p,m)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++)if(r[e?i-n:n].iterate(t,e)===!1)return!1}},{});var Ir=function(t,e,r){this.ownerID=t,this.count=e,this.nodes=r},qr=Ir;je.createClass(Ir,{get:function(t,e,r,n){var i=(0===t?e:e>>>t)&We,u=this.nodes[i];return u?u.get(t+Ue,e,r,n):n},update:function(t,e,r,n,i,u,a){var s=(0===e?r:r>>>e)&We,o=i===Ke,h=this.nodes,c=h[s];if(o&&!c)return this;var f=Y(c,t,e+Ue,r,n,i,u,a);if(f===c)return this;var _=this.count;if(c){if(!f&&(_--,Ar>_))return te(t,h,_,s)}else _++;var l=t&&t===this.ownerID,v=se(h,s,f,l);return l?(this.count=_,this.nodes=v,this):new qr(t,_,v)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++){var u=r[e?i-n:n];if(u&&u.iterate(t,e)===!1)return!1}}},{});var br=function(t,e,r){this.ownerID=t,this.hash=e,this.entries=r},xr=br;je.createClass(br,{get:function(t,e,r,i){for(var u=this.entries,a=0,s=u.length;s>a;a++)if(n(r,u[a][0]))return u[a][1];return i},update:function(t,e,r,i,a,o,h){var c=a===Ke;if(r!==this.hash)return c?this:(u(h),u(o),$(this,t,e,r,[i,a]));for(var f=this.entries,_=0,l=f.length;l>_&&!n(i,f[_][0]);_++);var v=l>_;if(c&&!v)return this;if(u(h),(c||!v)&&u(o),c&&2===l)return new kr(t,this.hash,f[1^_]);var g=t&&t===this.ownerID,p=g?f:s(f);return v?c?_===l-1?p.pop():p[_]=p.pop():p[_]=[i,a]:p.push([i,a]),g?(this.entries=p,this):new xr(t,this.hash,p) <del>},iterate:function(t,e){for(var r=this.entries,n=0,i=r.length-1;i>=n;n++)if(t(r[e?i-n:n])===!1)return!1}},{});var kr=function(t,e,r){this.ownerID=t,this.hash=e,this.entry=r},Mr=kr;je.createClass(kr,{get:function(t,e,r,i){return n(r,this.entry[0])?this.entry[1]:i},update:function(t,e,r,i,a,s,o){var h=a===Ke,c=n(i,this.entry[0]);return(c?a===this.entry[1]:h)?this:(u(o),h?(u(s),null):c?t&&t===this.ownerID?(this.entry[1]=a,this):new Mr(t,r,[i,a]):(u(s),$(this,t,e,r,[i,a])))},iterate:function(t){return t(this.entry)}},{});var Dr=function(t,e,r){this._type=e,this._reverse=r,this._stack=t._root&&H(t._root)};je.createClass(Dr,{next:function(){for(var t=this._type,e=this._stack;e;){var r,n=e.node,i=e.index++;if(n.entry){if(0===i)return G(t,n.entry)}else if(n.entries){if(r=n.entries.length-1,r>=i)return G(t,n.entries[this._reverse?r-i:i])}else if(r=n.nodes.length-1,r>=i){var u=n.nodes[this._reverse?r-i:i];if(u){if(u.entry)return G(t,u.entry);e=this._stack=H(u,e)}continue}e=this._stack=this._stack.__prev}return g()}},{},rr);var Or,Cr=Pe/2,Ar=Pe/4,Er=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return jr.from(t)},jr=Er;je.createClass(Er,{toString:function(){return this.__toString("Vector [","]")},get:function(t,e){if(t=A(this,t),0>t||t>=this.length)return e;t+=this._origin;var r=pe(this,t);return r&&r.array[t&We]},set:function(t,e){return le(this,t,e)},remove:function(t){return le(this,t,Ke)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=this._origin=this._size=0,this._level=Ue,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):jr.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(r){me(r,0,e+t.length);for(var n=0;t.length>n;n++)r.set(e+n,t[n])})},pop:function(){return me(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){me(e,-t.length);for(var r=0;t.length>r;r++)e.set(r,t[r])})},shift:function(){return me(this,1)},merge:function(){return de(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r]; <del>return de(this,t,e)},mergeDeep:function(){return de(this,ne(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return de(this,ne(t),e)},setLength:function(t){return me(this,0,t)},slice:function(t,e){var r=je.superCall(this,jr.prototype,"slice",[t,e]);if(r!==this){var n=this,i=n.length;r.toVector=function(){return me(n,0>t?Math.max(0,i+t):i?Math.min(i,t):t,null==e?i:0>e?Math.max(0,i+e):i?Math.min(i,e):e)}}return r},__iterator:function(t,e){return new Wr(this,t,e)},__iterate:function(t,e){var r=this,n=0,i=function(e){return t(e,n++,r)},u=ye(this._size);return e?ce(this._tail,0,u-this._origin,this._size-this._origin,i,e)&&ce(this._root,this._level,-this._origin,u-this._origin,i,e):ce(this._root,this._level,-this._origin,u-this._origin,i,e)&&ce(this._tail,0,u-this._origin,this._size-this._origin,i,e),n},__ensureOwner:function(t){return t===this.__ownerID?this:t?_e(this._origin,this._size,this._level,this._root,this._tail,t,this.__hash):(this.__ownerID=t,this)}},{empty:function(){return Kr||(Kr=_e(0,0,Ue))},from:function(t){if(!t||0===t.length)return jr.empty();if(t.constructor===jr)return t;var e=Array.isArray(t);return t.length>0&&Pe>t.length?_e(0,t.length,Ue,null,new Ur(e?s(t):ir(t).toArray())):(e||(t=ir(t).valueSeq()),jr.empty().merge(t))}},sr);var Rr=Er.prototype;Rr[Re]=Rr.remove,Rr.update=yr.update,Rr.updateIn=yr.updateIn,Rr.cursor=yr.cursor,Rr.withMutations=yr.withMutations,Rr.asMutable=yr.asMutable,Rr.asImmutable=yr.asImmutable,Rr.wasAltered=yr.wasAltered;var Ur=function(t,e){this.array=t,this.ownerID=e},Pr=Ur;je.createClass(Ur,{removeBefore:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r>>>e&We;if(n>=this.array.length)return new Pr([],t);var i,u=0===n;if(e>0){var a=this.array[n];if(i=a&&a.removeBefore(t,e-Ue,r),i===a&&u)return this}if(u&&!i)return this;var s=ge(this,t);if(!u)for(var o=0;n>o;o++)s.array[o]=void 0;return i&&(s.array[n]=i),s},removeAfter:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r-1>>>e&We; <del>if(n>=this.array.length)return this;var i,u=n===this.array.length-1;if(e>0){var a=this.array[n];if(i=a&&a.removeAfter(t,e-Ue,r),i===a&&u)return this}if(u&&!i)return this;var s=ge(this,t);return u||s.array.pop(),i&&(s.array[n]=i),s}},{});var Wr=function(t,e,r){this._type=e,this._reverse=!!r,this._maxIndex=t.length-1;var n=ye(t._size),i=fe(t._root&&t._root.array,t._level,-t._origin,n-t._origin-1),u=fe(t._tail&&t._tail.array,0,n-t._origin,t._size-t._origin-1);this._stack=r?u:i,this._stack.__prev=r?i:u};je.createClass(Wr,{next:function(){for(var t=this._stack;t;){var e=t.array,r=t.index++;if(this._reverse&&(r=We-r,r>t.rawMax&&(r=t.rawMax,t.index=Pe-r)),r>=0&&Pe>r&&t.rawMax>=r){var n=e&&e[r];if(0===t.level){var i,u=this._type;return 1!==u&&(i=t.offset+(r<<t.level),this._reverse&&(i=this._maxIndex-i)),v(u,i,n)}this._stack=t=fe(n&&n.array,t.level-Ue,t.offset+(r<<t.level),t.max,t)}else t=this._stack=this._stack.__prev}return g()}},{},rr);var Kr,zr=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Jr.from(t)},Jr=zr;je.createClass(zr,{toString:function(){return this.__toString("Stack [","]")},get:function(t,e){for(var r=this._head;r&&t--;)r=r.next;return r?r.value:e},peek:function(){return this._head&&this._head.value},push:function(){if(0===arguments.length)return this;for(var t=this.length+arguments.length,e=this._head,r=arguments.length-1;r>=0;r--)e={value:arguments[r],next:e};return this.__ownerID?(this.length=t,this._head=e,this.__hash=void 0,this.__altered=!0,this):we(t,e)},pushAll:function(t){if(t=ir(t),0===t.length)return this;var e=this.length,r=this._head;return t.reverse().forEach(function(t){e++,r={value:t,next:r}}),this.__ownerID?(this.length=e,this._head=r,this.__hash=void 0,this.__altered=!0,this):we(e,r)},pop:function(){return this.slice(1)},unshift:function(){return this.push.apply(this,arguments)},unshiftAll:function(t){return this.pushAll(t)},shift:function(){return this.pop.apply(this,arguments)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Jr.empty() <del>},slice:function(t,e){if(S(t,e,this.length))return this;var r=I(t,this.length),n=q(e,this.length);if(n!==this.length)return je.superCall(this,Jr.prototype,"slice",[t,e]);for(var i=this.length-r,u=this._head;r--;)u=u.next;return this.__ownerID?(this.length=i,this._head=u,this.__hash=void 0,this.__altered=!0,this):we(i,u)},__ensureOwner:function(t){return t===this.__ownerID?this:t?we(this.length,this._head,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);for(var r=0,n=this._head;n&&t(n.value,r++,this)!==!1;)n=n.next;return r},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=0,n=this._head;return new rr(function(){if(n){var e=n.value;return n=n.next,v(t,r++,e)}return g()})}},{empty:function(){return Vr||(Vr=we(0))},from:function(t){var e=Jr.empty();return t?t.constructor===Jr?t:e.unshiftAll(t):e}},sr);var Br=zr.prototype;Br.withMutations=yr.withMutations,Br.asMutable=yr.asMutable,Br.asImmutable=yr.asImmutable,Br.wasAltered=yr.wasAltered;var Vr,Lr=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Nr.from(t)},Nr=Lr;je.createClass(Lr,{toString:function(){return this.__toString("Set {","}")},get:function(t,e){return this._map.has(t)?t:e},contains:function(t){return this._map.has(t)},add:function(t){var e=this._map.set(t,null);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:Se(e)},remove:function(t){var e=this._map.remove(t);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:0===e.length?Nr.empty():Se(e)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this):Nr.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var r=0;t.length>r;r++)ir(t[r]).forEach(function(t){return e.add(t)})})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ir(t) <del>});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.every(function(t){return t.contains(r)})||e.remove(r)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ir(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.some(function(t){return t.contains(r)})&&e.remove(r)})})},isSubset:function(t){return t=ir(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=ir(t),t.every(function(t){return e.contains(t)})},merge:function(){return this.union.apply(this,arguments)},mergeWith:function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return this.union.apply(this,t)},wasAltered:function(){return this._map.wasAltered()},__iterate:function(t,e){var r=this;return this._map.__iterate(function(e,n){return t(n,n,r)},e)},__iterator:function(t,e){return this._map.map(function(t,e){return e}).__iterator(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t);return t?Se(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return Fr||(Fr=Se(mr.empty()))},from:function(t){var e=Nr.empty();return t?t.constructor===Nr?t:e.union(t):e},fromKeys:function(t){return Nr.from(ir(t).flip())}},ir);var Tr=Lr.prototype;Tr[Re]=Tr.remove,Tr[er]=Tr.values,Tr.mergeDeep=Tr.merge,Tr.mergeDeepWith=Tr.mergeWith,Tr.withMutations=yr.withMutations,Tr.asMutable=yr.asMutable,Tr.asImmutable=yr.asImmutable,Tr.__toJS=hr.__toJS,Tr.__toStringMapper=hr.__toStringMapper;var Fr,Gr=function(t){var e=Hr.empty();return t?t.constructor===Hr?t:e.merge(t):e},Hr=Gr;je.createClass(Gr,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){var r=this._map.get(t);return null!=r?this._vector.get(r)[1]:e},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this._vector.clear(),this):Hr.empty()},set:function(t,e){return qe(this,t,e)},remove:function(t){return qe(this,t,Ke)},wasAltered:function(){return this._map.wasAltered()||this._vector.wasAltered() <del>},__iterate:function(t,e){var r=this;return this._vector.__iterate(function(e){return e&&t(e[1],e[0],r)},e)},__iterator:function(t,e){return this._vector.fromEntrySeq().__iterator(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),r=this._vector.__ensureOwner(t);return t?Ie(e,r,t,this.__hash):(this.__ownerID=t,this._map=e,this._vector=r,this)}},{empty:function(){return Qr||(Qr=Ie(mr.empty(),Er.empty()))}},mr),Gr.from=Gr,Gr.prototype[Re]=Gr.prototype.remove;var Qr,Xr=function(t,e){var r=function(t){return this instanceof r?void(this._map=mr(t)):new r(t)},n=Object.keys(t),i=r.prototype=Object.create(Yr);i.constructor=r,e&&(i._name=e),i._defaultValues=t,i._keys=n,i.length=n.length;try{ir(t).forEach(function(t,e){Object.defineProperty(r.prototype,e,{get:function(){return this.get(e)},set:function(t){o(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})})}catch(u){}return r};je.createClass(Xr,{toString:function(){return this.__toString(this._name+" {","}")},has:function(t){return this._defaultValues.hasOwnProperty(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues[t]):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;var t=Object.getPrototypeOf(this).constructor;return t._empty||(t._empty=be(this,mr.empty()))},set:function(t,e){if(!this.has(t))throw Error('Cannot set unknown key "'+t+'" on '+this._name);var r=this._map.set(t,e);return this.__ownerID||r===this._map?this:be(this,r)},remove:function(t){if(null==t||!this.has(t))return this;var e=this._map.remove(t);return this.__ownerID||e===this._map?this:be(this,e)},keys:function(){return this._map.keys()},values:function(){return this._map.values()},entries:function(){return this._map.entries()},wasAltered:function(){return this._map.wasAltered()},__iterator:function(t,e){return this._map.__iterator(t,e)},__iterate:function(t,e){var r=this;return ir(this._defaultValues).map(function(t,e){return r.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this; <del>var e=this._map&&this._map.__ensureOwner(t);return t?be(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},ir);var Yr=Xr.prototype;Yr._name="Record",Yr[Re]=Yr.remove,Yr.merge=yr.merge,Yr.mergeWith=yr.mergeWith,Yr.mergeDeep=yr.mergeDeep,Yr.mergeDeepWith=yr.mergeDeepWith,Yr.update=yr.update,Yr.updateIn=yr.updateIn,Yr.cursor=yr.cursor,Yr.withMutations=yr.withMutations,Yr.asMutable=yr.asMutable,Yr.asImmutable=yr.asImmutable;var Zr=function(t,e,r){return this instanceof $r?(o(0!==r,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&en?en:(r=null==r?1:Math.abs(r),t>e&&(r=-r),this._start=t,this._end=e,this._step=r,void(this.length=Math.max(0,Math.ceil((e-t)/r-1)+1)))):new $r(t,e,r)},$r=Zr;je.createClass(Zr,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},get:function(t,e){return this.has(t)?this._start+A(this,t)*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e){return S(t,e,this.length)?this:(t=I(t,this.length),e=q(e,this.length),t>=e?en:new $r(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var r=e/this._step;if(r>=0&&this.length>r)return r}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,Math.max(0,t))},skip:function(t){return this.slice(Math.max(0,t))},__iterate:function(t,e){for(var r=this.length-1,n=this._step,i=e?this._start+r*n:this._start,u=0;r>=u;u++){if(t(i,u,this)===!1)return u+1;i+=e?-n:n}return u},__iterator:function(t,e){var r=this.length-1,n=this._step,i=e?this._start+r*n:this._start,u=0;return new rr(function(){var a=i;return i+=e?-n:n,u>r?g():v(t,u++,a)})},__deepEquals:function(t){return t instanceof $r?this._start===t._start&&this._end===t._end&&this._step===t._step:je.superCall(this,$r.prototype,"__deepEquals",[t])}},{},sr);var tn=Zr.prototype;tn.__toJS=tn.toArray,tn.first=Rr.first,tn.last=Rr.last;var en=Zr(0,0),rn=function(t,e){return 0===e&&an?an:this instanceof nn?(this._value=t,void(this.length=null==e?1/0:Math.max(0,e))):new nn(t,e) <del>},nn=rn;je.createClass(rn,{toString:function(){return 0===this.length?"Repeat []":"Repeat [ "+this._value+" "+this.length+" times ]"},get:function(t,e){return this.has(t)?this._value:e},contains:function(t){return n(this._value,t)},slice:function(t,e){var r=this.length;return t=0>t?Math.max(0,r+t):Math.min(r,t),e=null==e?r:e>0?Math.min(r,e):Math.max(0,r+e),e>t?new nn(this._value,e-t):an},reverse:function(){return this},indexOf:function(t){return n(this._value,t)?0:-1},lastIndexOf:function(t){return n(this._value,t)?this.length:-1},__iterate:function(t){for(var e=0;this.length>e;e++)if(t(this._value,e,this)===!1)return e+1;return e},__iterator:function(t){var e=this,r=0;return new rr(function(){return e.length>r?v(t,r++,e._value):g()})},__deepEquals:function(t){return t instanceof nn?n(this._value,t._value):je.superCall(this,nn.prototype,"__deepEquals",[t])}},{},sr);var un=rn.prototype;un.last=un.first,un.has=tn.has,un.take=tn.take,un.skip=tn.skip,un.__toJS=tn.__toJS;var an=new rn(void 0,0),sn=function(t,e,r,n){this.length=n,this._rootData=t,this._keyPath=e,this._onChange=r};je.createClass(sn,{equals:function(t){return n(this.deref(),t&&("function"==typeof t.deref?t.deref():t))},deref:function(t){return this._rootData.getIn(this._keyPath,t)},get:function(t,e){if(Array.isArray(t)&&0===t.length)return this;var r=this._rootData.getIn(this._keyPath.concat(t),Ke);return r===Ke?e:Oe(this,t,r)},set:function(t,e){return Ae(this,function(r){return r.set(t,e)},t)},remove:function(t){return Ae(this,function(e){return e.remove(t)},t)},clear:function(){return Ae(this,function(t){return t.clear()})},update:function(t,e,r){return 1===arguments.length?Ae(this,t):Ae(this,function(n){return n.update(t,e,r)},t)},withMutations:function(t){return Ae(this,function(e){return(e||mr.empty()).withMutations(t)})},cursor:function(t){return Array.isArray(t)&&0===t.length?this:Ce(this,t)},__iterate:function(t,e){var r=this,n=this.deref();return n&&n.__iterate?n.__iterate(function(e,n){return t(Oe(r,n,e),n,r)},e):0},__iterator:function(t,e){var r=this,n=this.deref(),i=n&&n.__iterator&&n.__iterator(Ze,e); <del>return new rr(function(){if(!i)return g();var e=i.next();if(e.done)return e;var n=e.value,u=n[0],a=n[1];return v(t,u,Oe(r,u,a),e)})}},{},ir);var on=sn.prototype;on[Re]=on.remove,on.getIn=on.get;var hn=function(t,e,r,n){this.length=n,this._rootData=t,this._keyPath=e,this._onChange=r};je.createClass(hn,{},{},sr);var cn=hn.prototype;cn.equals=on.equals,cn.deref=on.deref,cn.get=on.get,cn.getIn=on.getIn,cn.set=on.set,cn[Re]=cn.remove=on.remove,cn.clear=on.clear,cn.update=on.update,cn.withMutations=on.withMutations,cn.cursor=on.cursor,cn.__iterate=on.__iterate,cn.__iterator=on.__iterator;var fn={Sequence:ir,Map:mr,Vector:Er,Stack:zr,Set:Lr,OrderedMap:Gr,Record:Xr,Range:Zr,Repeat:rn,is:n,fromJS:xe};return fn}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t(); <ide>\ No newline at end of file <add>function t(){function t(t,e,r,n){var i;if(n){var u=n.prototype;i=Ee.create(u)}else i=t.prototype;return Ee.keys(e).forEach(function(t){i[t]=e[t]}),Ee.keys(r).forEach(function(e){t[e]=r[e]}),i.constructor=t,t.prototype=i,t}function e(t,e,r,n){return Ee.getPrototypeOf(e)[r].apply(t,n)}function r(t,r,n){e(t,r,"constructor",n)}function n(t,e){return t===e?0!==t||0!==e||1/t===1/e:t!==t?e!==e:t&&"function"==typeof t.equals?t.equals(e):!1}function i(t){return t.value=!1,t}function u(t){t&&(t.value=!0)}function a(){}function s(t,e){e=e||0;for(var r=Math.max(0,t.length-e),n=Array(r),i=0;r>i;i++)n[i]=t[i+e];return n}function o(t,e){if(!t)throw Error(e)}function h(t){if(!t)return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){if((0|t)===t)return t&Ne;t=""+t,e="string"}return"string"===e?t.length>Ge?c(t):f(t):t.hashCode?h("function"==typeof t.hashCode?t.hashCode():t.hashCode):_(t)}function c(t){var e=Xe[t];return null==e&&(e=f(t),Qe===He&&(Qe=0,Xe={}),Qe++,Xe[t]=e),e}function f(t){for(var e=0,r=0;t.length>r;r++)e=31*e+t.charCodeAt(r)&Ne;return e}function _(t){var e=Le&&Le.get(t);if(e)return e;if(e=t[Fe])return e;if(!Ve){if(e=t.propertyIsEnumerable&&t.propertyIsEnumerable[Fe])return e;if(e=l(t))return e}if(Ve&&!Object.isExtensible(t))throw Error("Non-extensible objects are not allowed as keys.");if(e=++Te&Ne,Le)Le.set(t,e);else if(Ve)Object.defineProperty(t,Fe,{enumerable:!1,configurable:!1,writable:!1,value:e});else if(Be&&t.propertyIsEnumerable===Be)t.propertyIsEnumerable=function(){return Be.apply(this,arguments)},t.propertyIsEnumerable[Fe]=e;else{if(!t.nodeType)throw Error("Unable to set a non-enumerable property on object.");t[Fe]=e}return e}function l(t){if(t&&t.nodeType>0)switch(t.nodeType){case 1:return t.uniqueID;case 9:return t.documentElement&&t.documentElement.uniqueID}}function v(t,e,r,n){var i=0===t?e:1===t?r:[e,r];return n?n.value=i:n={value:i,done:!1},n}function g(){return{value:void 0,done:!0}}function p(t){return!!y(t)}function m(t){return t&&"function"==typeof t.next}function d(t){var e=y(t);return e&&e.call(t) <add>}function y(t){var e=t&&(er&&t[er]||t[tr]);return"function"==typeof e?e:void 0}function w(t){return null==t.length&&t.cacheResult(),o(1/0>t.length,"Cannot reverse infinite range."),t.length}function S(t,e,r){return(0===t||null!=r&&-r>=t)&&(null==e||null!=r&&e>=r)}function I(t,e){return b(t,e,0)}function q(t,e){return b(t,e,e)}function b(t,e,r){return null==t?r:0>t?Math.max(0,e+t):e?Math.min(e,t):t}function k(t){return t}function M(t,e){return[e,t]}function x(){return!0}function D(t){return function(){return!t.apply(this,arguments)}}function O(t){return"string"==typeof t?JSON.stringify(t):t}function C(t,e){return t>e?1:e>t?-1:0}function A(t,e){return 0>e?(null==t.length&&t.cacheResult(),t.length+e):e}function E(t){o(1/0!==t,"Cannot perform this action with an infinite sequence.")}function j(t,e,r,n){var i=t._cache;if(i){for(var u=i.length-1,a=0;u>=a;a++){var s=i[r?u-a:a];if(e(s[1],n?s[0]:a,t)===!1)return a+1}return a}return t.__iterateUncached(e,r)}function R(t,e,r,n){var i=t._cache;if(i){var u=i.length-1,a=0;return new nr(function(){var t=i[r?u-a:a];return a++>u?g():v(e,n?t[0]:a-1,t[1])})}return t.__iteratorUncached(e,r)}function U(t){var e=t.__makeSequence();return e.length=t.length,e.flip=function(){return t},e.reverse=function(){var e=t.reverse.apply(this);return e.flip=function(){return t.reverse()},e},e.has=function(e){return t.contains(e)},e.contains=function(e){return t.has(e)},e.__iterateUncached=function(e,r){var n=this;return t.__iterate(function(t,r){return e(r,t,n)!==!1},r)},e.__iteratorUncached=function(e,r){if(e===$e){var n=t.__iterator(e,r);return new nr(function(){var t=n.next();if(!t.done){var e=t.value[0];t.value[0]=t.value[1],t.value[1]=e}return t})}return t.__iterator(e===Ze?Ye:Ze,r)},e}function W(t,e,r){var n=t.__makeSequence();return n.length=t.length,n.has=function(e){return t.has(e)},n.get=function(n,i){var u=t.get(n,Ke);return u===Ke?i:e.call(r,u,n,t)},n.__iterateUncached=function(n,i){var u=this;return t.__iterate(function(t,i,a){return n(e.call(r,t,i,a),i,u)!==!1},i)},n.__iteratorUncached=function(n,i){var u=t.__iterator($e,i); <add>return new nr(function(){var i=u.next();if(i.done)return i;var a=i.value,s=a[0];return v(n,s,e.call(r,a[1],s,t),i)})},n}function P(t,e){var r=t.__makeSequence();return r.length=t.length,r.reverse=function(){return t},r.flip=function(){var e=t.flip.apply(this);return e.reverse=function(){return t.flip()},e},r.get=function(r,n){return t.get(e?r:-1-r,n)},r.has=function(r){return t.has(e?r:-1-r)},r.contains=function(e){return t.contains(e)},r.cacheResult=function(){return t.cacheResult(),this.length=t.length,this},r.__iterate=function(e,r){var n=this;return t.__iterate(function(t,r){return e(t,r,n)},!r)},r.__iterator=function(e,r){return t.__iterator(e,!r)},r}function K(t,e,r,n){var i=t.__makeSequence();return n&&(i.has=function(n){var i=t.get(n,Ke);return i!==Ke&&!!e.call(r,i,n,t)},i.get=function(n,i){var u=t.get(n,Ke);return u!==Ke&&e.call(r,u,n,t)?u:i}),i.__iterateUncached=function(i,u){var a=this,s=0;return t.__iterate(function(t,u,o){return e.call(r,t,u,o)?(s++,i(t,n?u:s-1,a)):void 0},u),s},i.__iteratorUncached=function(i,u){var a=t.__iterator($e,u),s=0;return new nr(function(){for(;;){var u=a.next();if(u.done)return u;var o=u.value,h=o[0],c=o[1];if(e.call(r,c,h,t))return v(i,n?h:s++,c,u)}})},i}function z(t,e,r,n){var i={},u=[];return t.__iterate(function(a,s){var o=e.call(r,a,s,t),c=h(o),f=n?[s,a]:a;i.hasOwnProperty(c)?u[i[c]][1].push(f):(i[c]=u.length,u.push([o,[f]]))}),ur(u).fromEntrySeq().map(n?function(t){return ur(t).fromEntrySeq()}:function(t){return ur(t)})}function J(t,e){if(e>t.length)return t;0>e&&(e=0);var r=t.__makeSequence();return r.length=t.length&&Math.min(t.length,e),r.__iterateUncached=function(r,n){var i=this;if(0===e)return 0;if(n)return this.cacheResult().__iterate(r,n);var u=0;return t.__iterate(function(t,n){return++u&&r(t,n,i)!==!1&&e>u}),u},r.__iteratorUncached=function(r,n){if(n)return this.cacheResult().__iterator(r,n);var i=e&&t.__iterator(r,n),u=0;return new nr(function(){return u++>e?g():i.next()})},r}function B(t,e,r){var n=t.__makeSequence();return n.__iterateUncached=function(n,i){var u=this; <add>if(i)return this.cacheResult().__iterate(n,i);var a=0;return t.__iterate(function(t,i,s){return e.call(r,t,i,s)&&++a&&n(t,i,u)}),a},n.__iteratorUncached=function(n,i){var u=this;if(i)return this.cacheResult().__iterator(n,i);var a=t.__iterator($e,i),s=!0;return new nr(function(){if(!s)return g();var t=a.next();if(t.done)return t;var i=t.value,o=i[0],h=i[1];return e.call(r,h,o,u)?n===$e?t:v(n,o,h,t):(s=!1,g())})},n}function V(t,e,r){if(0>=e)return t;var n=t.__makeSequence();return n.length=t.length&&Math.max(0,t.length-e),n.__iterateUncached=function(n,i){var u=this;if(i)return this.cacheResult().__iterate(n,i);var a=0,s=!0,o=0;return t.__iterate(function(t,i){return s&&(s=a++<e)?void 0:(o++,n(t,r?i:o-1,u))}),o},n.__iteratorUncached=function(n,i){if(i)return this.cacheResult().__iterator(n,i);var u=e&&t.__iterator(n,i),a=0,s=0;return new nr(function(){for(;e>a;)a++,u.next();var t=u.next();return r||n===Ze?t:n===Ye?v(n,s++,null,t):v(n,s++,t.value[1],t)})},n}function L(t,e,r,n){var i=t.__makeSequence();return i.__iterateUncached=function(i,u){var a=this;if(u)return this.cacheResult().__iterate(i,u);var s=!0,o=0;return t.__iterate(function(t,u,h){return s&&(s=e.call(r,t,u,h))?void 0:(o++,i(t,n?u:o-1,a))}),o},i.__iteratorUncached=function(i,u){var a=this;if(u)return this.cacheResult().__iterator(i,u);var s=t.__iterator($e,u),o=!0,h=0;return new nr(function(){var t,u,c;do{if(t=s.next(),t.done)return n||i===Ze?t:i===Ye?v(i,h++,null,t):v(i,h++,t.value[1],t);var f=t.value;u=f[0],c=f[1],o&&(o=e.call(r,c,u,a))}while(o);return i===$e?t:v(i,u,c,t)})},i}function N(t,e,r){var n=[t].concat(e),i=ur(n);return r&&(i=i.toKeyedSeq()),i=i.flatMap(k),i.length=n.reduce(function(t,e){if(void 0!==t){var r=ur(e).length;if(null!=r)return t+r}},0),i}function T(t,e,r){var n=t.__makeSequence();return n.__iterateUncached=function(n,i){function u(t,o){var h=this;t.__iterate(function(t,i){return(!e||e>o)&&t instanceof ur?u(t,o+1):n(t,r?i:a++,h)===!1&&(s=!0),!s},i)}var a=0,s=!1;return u(t,0),a},n.__iteratorUncached=function(n,i){var u=t.__iterator(n,i),a=[],s=0; <add>return new nr(function(){for(;u;){var t=u.next();if(t.done===!1){var o=t.value;if(n===$e&&(o=o[1]),!((!e||e>a.length)&&o instanceof ur))return r?t:v(n,s++,o,t);a.push(u),u=o.__iterator(n,i)}else u=a.pop()}return g()})},n}function F(t,e){var r=t.__makeSequence();return r.length=t.length&&2*t.length-1,r.__iterateUncached=function(r,n){var i=this,u=0;return t.__iterate(function(t){return(!u||r(e,u++,i)!==!1)&&r(t,u++,i)!==!1},n),u},r.__iteratorUncached=function(r,n){var i,u=t.__iterator(Ze,n),a=0;return new nr(function(){return(!i||a%2)&&(i=u.next(),i.done)?i:a%2?v(r,a++,e):v(r,a++,i.value,i)})},r}function G(t,e){return v(t,e[0],e[1])}function H(t,e){return{node:t,index:0,__prev:e}}function Q(t,e,r,n){var i=Object.create(wr);return i.length=t,i._root=e,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function X(t,e,r){var n=i(ze),u=i(Je),a=Y(t._root,t.__ownerID,0,h(e),e,r,n,u);if(!u.value)return t;var s=t.length+(n.value?r===Ke?-1:1:0);return t.__ownerID?(t.length=s,t._root=a,t.__hash=void 0,t.__altered=!0,t):a?Q(s,a):dr.empty()}function Y(t,e,r,n,i,a,s,o){return t?t.update(e,r,n,i,a,s,o):a===Ke?t:(u(o),u(s),new xr(e,n,[i,a]))}function Z(t){return t.constructor===xr||t.constructor===kr}function $(t,e,r,n,i){if(t.hash===n)return new kr(e,n,[t.entry,i]);var u,a=(0===r?t.hash:t.hash>>>r)&Pe,s=(0===r?n:n>>>r)&Pe,o=a===s?[$(t,e,r+Ue,n,i)]:(u=new xr(e,n,i),s>a?[t,u]:[u,t]);return new Sr(e,1<<a|1<<s,o)}function te(t,e,r,n){for(var i=0,u=0,a=Array(r),s=0,o=1,h=e.length;h>s;s++,o<<=1){var c=e[s];null!=c&&s!==n&&(i|=o,a[u++]=c)}return new Sr(t,i,a)}function ee(t,e,r,n,i){for(var u=0,a=Array(We),s=0;0!==r;s++,r>>>=1)a[s]=1&r?e[u++]:null;return a[n]=i,new qr(t,u+1,a)}function re(t,e,r){for(var n=[],i=0;r.length>i;i++){var u=r[i];u instanceof ur||(u=ur(u),u instanceof or&&(u=u.fromEntrySeq())),u&&n.push(u)}return ie(t,e,n)}function ne(t){return function(e,r){return e&&e.mergeDeepWith?e.mergeDeepWith(t,r):t?t(e,r):r}}function ie(t,e,r){return 0===r.length?t:t.withMutations(function(t){for(var n=e?function(r,n){var i=t.get(n,Ke);t.set(n,i===Ke?r:e(i,r)) <add>}:function(e,r){t.set(r,e)},i=0;r.length>i;i++)r[i].forEach(n)})}function ue(t,e,r,n,i){var u=e.length;if(i===u)return n(t);o(t.set,"updateIn with invalid keyPath");var a=i===u-1?r:dr.empty(),s=e[i],h=t.get(s,a),c=ue(h,e,r,n,i+1);return c===h?t:t.set(s,c)}function ae(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function se(t,e,r,n){var i=n?t:s(t);return i[e]=r,i}function oe(t,e,r,n){var i=t.length+1;if(n&&e+1===i)return t[e]=r,t;for(var u=Array(i),a=0,s=0;i>s;s++)s===e?(u[s]=r,a=-1):u[s]=t[s+a];return u}function he(t,e,r){var n=t.length-1;if(r&&e===n)return t.pop(),t;for(var i=Array(n),u=0,a=0;n>a;a++)a===e&&(u=1),i[a]=t[a+u];return i}function ce(t,e,r,n,i,u){var a,s=t&&t.array;if(0===e){var o=0>r?-r:0,h=n-r;for(h>We&&(h=We),a=o;h>a;a++)if(i(s&&s[u?o+h-1-a:a])===!1)return!1}else{var c=1<<e,f=e-Ue;for(a=0;Pe>=a;a++){var _=u?Pe-a:a,l=r+(_<<e);if(n>l&&l+c>0){var v=s&&s[_];if(!ce(v,f,l,n,i,u))return!1}}}return!0}function fe(t,e,r,n,i){return{array:t,level:e,offset:r,max:n,rawMax:n-r>>e,index:0,__prev:i}}function _e(t,e,r,n,i,u,a){var s=Object.create(Ur);return s.length=e-t,s._origin=t,s._size=e,s._level=r,s._root=n,s._tail=i,s.__ownerID=u,s.__hash=a,s.__altered=!1,s}function le(t,e,r){if(e=A(t,e),e>=t.length||0>e)return r===Ke?t:t.withMutations(function(t){0>e?me(t,e).set(0,r):me(t,0,e+1).set(e,r)});e+=t._origin;var n=t._tail,u=t._root,a=i(Je);return e>=ye(t._size)?n=ve(n,t.__ownerID,0,e,r,a):u=ve(u,t.__ownerID,t._level,e,r,a),a.value?t.__ownerID?(t._root=u,t._tail=n,t.__hash=void 0,t.__altered=!0,t):_e(t._origin,t._size,t._level,u,n):t}function ve(t,e,r,n,i,a){var s,o=i===Ke,h=n>>>r&Pe,c=t&&t.array.length>h;if(o&&!c)return t;if(r>0){var f=t&&t.array[h],_=ve(f,e,r-Ue,n,i,a);return _===f?t:(s=ge(t,e),s.array[h]=_,s)}return!o&&c&&t.array[h]===i?t:(u(a),s=ge(t,e),o&&h===s.array.length-1?s.array.pop():s.array[h]=o?void 0:i,s)}function ge(t,e){return e&&t&&e===t.ownerID?t:new Wr(t?t.array.slice():[],e)}function pe(t,e){if(e>=ye(t._size))return t._tail;if(1<<t._level+Ue>e){for(var r=t._root,n=t._level;r&&n>0;)r=r.array[e>>>n&Pe],n-=Ue; <add>return r}}function me(t,e,r){var n=t.__ownerID||new a,i=t._origin,u=t._size,s=i+e,o=null==r?u:0>r?u+r:i+r;if(s===i&&o===u)return t;if(s>=o)return t.clear();for(var h=t._level,c=t._root,f=0;0>s+f;)c=new Wr(c&&c.array.length?[null,c]:[],n),h+=Ue,f+=1<<h;f&&(s+=f,i+=f,o+=f,u+=f);for(var _=ye(u),l=ye(o);l>=1<<h+Ue;)c=new Wr(c&&c.array.length?[c]:[],n),h+=Ue;var v=t._tail,g=_>l?pe(t,o-1):l>_?new Wr([],n):v;if(v&&l>_&&u>s&&v.array.length){c=ge(c,n);for(var p=c,m=h;m>Ue;m-=Ue){var d=_>>>m&Pe;p=p.array[d]=ge(p.array[d],n)}p.array[_>>>Ue&Pe]=v}if(u>o&&(g=g&&g.removeAfter(n,0,o)),s>=l)s-=l,o-=l,h=Ue,c=null,g=g&&g.removeBefore(n,0,s);else if(s>i||_>l){var y,w;f=0;do y=s>>>h&Pe,w=l-1>>>h&Pe,y===w&&(y&&(f+=(1<<h)*y),h-=Ue,c=c&&c.array[y]);while(c&&y===w);c&&s>i&&(c=c&&c.removeBefore(n,h,s-f)),c&&_>l&&(c=c&&c.removeAfter(n,h,l-f)),f&&(s-=f,o-=f)}return t.__ownerID?(t.length=o-s,t._origin=s,t._size=o,t._level=h,t._root=c,t._tail=g,t.__hash=void 0,t.__altered=!0,t):_e(s,o,h,c,g)}function de(t,e,r){for(var n=[],i=0;r.length>i;i++){var u=r[i];u&&n.push(ur(u))}var a=Math.max.apply(null,n.map(function(t){return t.length||0}));return a>t.length&&(t=t.setLength(a)),ie(t,e,n)}function ye(t){return We>t?0:t-1>>>Ue<<Ue}function we(t,e,r,n){var i=Object.create(Vr);return i.length=t,i._head=e,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function Se(t,e){var r=Object.create(Fr);return r.length=t?t.length:0,r._map=t,r.__ownerID=e,r}function Ie(t,e,r,n){var i=Object.create(Hr.prototype);return i.length=t?t.length:0,i._map=t,i._vector=e,i.__ownerID=r,i.__hash=n,i}function qe(t,e,r){var n=t._map,i=t._vector,u=n.get(e),a=void 0!==u,s=r===Ke;if(!a&&s||a&&r===i.get(u)[1])return t;a||(u=i.length);var o=s?n.remove(e):a?n:n.set(e,u),h=s?i.remove(u):i.set(u,[e,r]);return t.__ownerID?(t.length=o.length,t._map=o,t._vector=h,t.__hash=void 0,t):Ie(o,h)}function be(t,e,r){var n=Object.create(Object.getPrototypeOf(t));return n._map=e,n.__ownerID=r,n}function ke(t,e){return e?Me(e,t,"",{"":t}):xe(t)}function Me(t,e,r,n){return e&&(Array.isArray(e)||e.constructor===Object)?t.call(n,r,ur(e).map(function(r,n){return Me(t,r,n,e) <add>})):e}function xe(t){if(t){if(Array.isArray(t))return ur(t).map(xe).toVector();if(t.constructor===Object)return ur(t).map(xe).toMap()}return t}function De(t,e,r,n){4>arguments.length&&(n=t.getIn(e));var i=n instanceof ur?n.length:null,u=n instanceof or?cn:on;return new u(t,e,r,i)}function Oe(t,e,r){return r instanceof ur?Ce(t,e,r):r}function Ce(t,e,r){return De(t._rootData,t._keyPath.concat(e),t._onChange,r)}function Ae(t,e,r){var n=t._rootData.updateIn(t._keyPath,r?dr.empty():void 0,e),i=t._keyPath||[];return t._onChange&&t._onChange.call(void 0,n,t._rootData,r?i.concat(r):i),De(n,t._keyPath,t._onChange)}var Ee=Object,je={};je.createClass=t,je.superCall=e,je.defaultSuperCall=r;var Re="delete",Ue=5,We=1<<Ue,Pe=We-1,Ke={},ze={value:!1},Je={value:!1},Be=Object.prototype.propertyIsEnumerable,Ve=function(){try{return Object.defineProperty({},"x",{}),!0}catch(t){return!1}}(),Le="function"==typeof WeakMap&&new WeakMap,Ne=2147483647,Te=0,Fe="__immutablehash__";"function"==typeof Symbol&&(Fe=Symbol(Fe));var Ge=16,He=255,Qe=0,Xe={},Ye=0,Ze=1,$e=2,tr="@@iterator",er="function"==typeof Symbol&&Symbol.iterator,rr=er||tr,nr=function(t){this.next=t};je.createClass(nr,{toString:function(){return"[Iterator]"}},{});var ir=nr.prototype;ir.inspect=ir.toSource=function(){return""+this},ir[rr]=function(){return this};var ur=function(t){return ar.from(1===arguments.length?t:Array.prototype.slice.call(arguments))},ar=ur;je.createClass(ur,{toArray:function(){E(this.length);var t=Array(this.length||0);return this.valueSeq().__iterate(function(e,r){t[r]=e}),t},toJS:function(){return this.map(function(t){return t instanceof ar?t.toJS():t}).__toJS()},toMap:function(){return E(this.length),dr.from(this)},toObject:function(){E(this.length);var t={};return this.__iterate(function(e,r){t[r]=e}),t},toOrderedMap:function(){return E(this.length),Hr.from(this)},toSet:function(){return E(this.length),Nr.from(this)},toStack:function(){return E(this.length),Jr.from(this)},toVector:function(){return E(this.length),jr.from(this)},toString:function(){return this.__toString("Seq {","}") <add>},__toString:function(t,e){return 0===this.length?t+e:t+" "+this.map(this.__toStringMapper).join(", ")+" "+e},__toStringMapper:function(t,e){return e+": "+O(t)},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return N(this,t,!0)},contains:function(t){return this.find(function(e){return n(e,t)},null,Ke)!==Ke},entries:function(){return this.__iterator($e)},every:function(t,e){var r=!0;return this.__iterate(function(n,i,u){return t.call(e,n,i,u)?void 0:(r=!1,!1)}),r},filter:function(t,e){return K(this,t,e,!0)},find:function(t,e,r){var n=r;return this.__iterate(function(r,i,u){return t.call(e,r,i,u)?(n=r,!1):void 0}),n},forEach:function(t,e){return this.__iterate(e?t.bind(e):t)},join:function(t){t=void 0!==t?""+t:",";var e="",r=!0;return this.__iterate(function(n){r?r=!1:e+=t,e+=null!=n?n:""}),e},keys:function(){return this.__iterator(Ye)},map:function(t,e){return W(this,t,e)},reduce:function(t,e,r){var n,i;return 2>arguments.length?i=!0:n=e,this.__iterate(function(e,u,a){i?(i=!1,n=e):n=t.call(r,n,e,u,a)}),n},reduceRight:function(){var t=this.toKeyedSeq().reverse();return t.reduce.apply(t,arguments)},reverse:function(){return P(this,!0)},slice:function(t,e){if(S(t,e,this.length))return this;var r=I(t,this.length),n=q(e,this.length);if(r!==r||n!==n)return this.cacheResult().slice(t,e);var i=0===r?this:this.skip(r);return null==n||n===this.length?i:i.take(n-r)},some:function(t,e){return!this.every(D(t),e)},sort:function(t){return this.sortBy(k,t)},values:function(){return this.__iterator(Ze)},butLast:function(){return this.slice(0,-1)},count:function(t,e){return t?this.filter(t,e).count():(null==this.length&&(this.length=this.__iterate(x)),this.length)},countBy:function(t,e){var r=this,n={},i=[];return this.__iterate(function(u,a){var s=t.call(e,u,a,r),o=h(s);n.hasOwnProperty(o)?i[n[o]][1]++:(n[o]=i.length,i.push([s,1]))}),ar(i).fromEntrySeq()},equals:function(t){if(this===t)return!0;if(!(t instanceof ar))return!1;if(null!=this.length&&null!=t.length){if(this.length!==t.length)return!1;if(0===this.length&&0===t.length)return!0 <add>}return null!=this.__hash&&null!=t.__hash&&this.__hash!==t.__hash?!1:this.__deepEquals(t)},__deepEquals:function(t){var e=this.entries();return t.every(function(t,r){var i=e.next().value;return i&&n(i[0],r)&&n(i[1],t)})&&e.next().done},entrySeq:function(){var t=this;if(t._cache)return ar(t._cache);var e=t.toKeyedSeq().map(M).valueSeq();return e.fromEntries=function(){return t},e},findKey:function(t,e){var r;return this.__iterate(function(n,i,u){return t.call(e,n,i,u)?(r=i,!1):void 0}),r},findLast:function(t,e,r){return this.toKeyedSeq().reverse().find(t,e,r)},findLastKey:function(t,e){return this.toKeyedSeq().reverse().findKey(t,e)},first:function(){return this.find(x)},flatMap:function(t,e){return this.map(function(r,n,i){return ar(t.call(e,r,n,i))}).flatten(!0)},flatten:function(t){return T(this,t,!0)},flip:function(){return U(this)},get:function(t,e){return this.find(function(e,r){return n(r,t)},null,e)},getIn:function(t,e){var r=this;if(t)for(var n=0;t.length>n;n++)if(r=r&&r.get?r.get(t[n],Ke):Ke,r===Ke)return e;return r},groupBy:function(t,e){return z(this,t,e,!0)},has:function(t){return this.get(t,Ke)!==Ke},keySeq:function(){return this.flip().valueSeq()},last:function(){return this.reverse().first()},mapEntries:function(t,e){var r=this;return this.entrySeq().map(function(n,i){return t.call(e,n,i,r)}).fromEntrySeq()},mapKeys:function(t,e){var r=this;return this.flip().map(function(n,i){return t.call(e,n,i,r)}).flip()},rest:function(){return this.slice(1)},skip:function(t){return V(this,t,!0)},skipLast:function(t){return this.reverse().skip(t).reverse()},skipWhile:function(t,e){return L(this,t,e,!0)},skipUntil:function(t,e){return this.skipWhile(D(t),e)},sortBy:function(t,e){e=e||C;var r=this;return ar(this.entrySeq().entrySeq().toArray().sort(function(n,i){return e(t(n[1][1],n[1][0],r),t(i[1][1],i[1][0],r))||n[0]-i[0]})).fromEntrySeq().valueSeq().fromEntrySeq()},take:function(t){return J(this,t)},takeLast:function(t){return this.reverse().take(t).reverse()},takeWhile:function(t,e){return B(this,t,e)},takeUntil:function(t,e){return this.takeWhile(D(t),e) <add>},toKeyedSeq:function(){return this},valueSeq:function(){return new gr(this)},cacheResult:function(){return!this._cache&&this.__iterateUncached&&(E(this.length),this._cache=this.entrySeq().toArray(),null==this.length&&(this.length=this._cache.length)),this},hashCode:function(){return this.__hash||(this.__hash=1/0===this.length?0:this.reduce(function(t,e,r){return t+(h(e)^(e===r?0:h(r)))&Ne},0))},__makeSequence:function(){return Object.create(sr)},__iterate:function(t,e){return j(this,t,e,!0)},__iterator:function(t,e){return R(this,t,e,!0)}},{from:function(t){if(t instanceof ar)return t;if(!Array.isArray(t)){if(m(t))return new fr(t);if(p(t))return new _r(t);if(t&&t.constructor===Object)return new lr(t);t=[t]}return new vr(t)}});var sr=ur.prototype;sr[rr]=sr.entries,sr.toJSON=sr.toJS,sr.__toJS=sr.toObject,sr.inspect=sr.toSource=function(){return""+this},sr.chain=sr.flatMap;var or=function(){je.defaultSuperCall(this,hr.prototype,arguments)},hr=or;je.createClass(or,{toString:function(){return this.__toString("Seq [","]")},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return N(this,t,!1)},filter:function(t,e){return K(this,t,e,!1)},findIndex:function(t,e){var r=this.findKey(t,e);return null==r?-1:r},indexOf:function(t){return this.findIndex(function(e){return n(e,t)})},lastIndexOf:function(t){return this.toKeyedSeq().reverse().indexOf(t)},reverse:function(){return P(this,!1)},splice:function(t,e){var r=arguments.length;if(e=Math.max(0|e,0),0===r||2===r&&!e)return this;t=I(t,this.length);var n=this.slice(0,t);return 1===r?n:n.concat(s(arguments,2),this.slice(t+e))},findLastIndex:function(t,e){return this.toKeyedSeq().reverse().findIndex(t,e)},first:function(){return this.get(0)},flatten:function(t){return T(this,t,!1)},flip:function(){return U(this.toKeyedSeq())},fromEntrySeq:function(){return new mr(this)},get:function(t,e){return t=A(this,t),0>t||1/0===this.length||null!=this.length&&t>this.length?e:this.find(function(e,r){return r===t},null,e)},groupBy:function(t,e){return z(this,t,e,!1) <add>},has:function(t){return t=A(this,t),t>=0&&(null!=this.length?1/0===this.length||this.length>t:-1!==this.indexOf(t))},interpose:function(t){return F(this,t)},last:function(){return this.get(-1)},skip:function(t){var e=this,r=V(e,t,!1);return r!==e&&(r.get=function(r,n){return r=A(this,r),r>=0?e.get(r+t,n):n}),r},skipWhile:function(t,e){return L(this,t,e,!1)},sortBy:function(t,e){e=e||C;var r=this;return ur(this.entrySeq().toArray().sort(function(n,i){return e(t(n[1],n[0],r),t(i[1],i[0],r))||n[0]-i[0]})).fromEntrySeq().valueSeq()},take:function(t){var e=this,r=J(e,t);return r!==e&&(r.get=function(r,n){return r=A(this,r),r>=0&&t>r?e.get(r,n):n}),r},toKeyedSeq:function(){return new pr(this)},valueSeq:function(){return this},__makeSequence:function(){return Object.create(cr)},__iterate:function(t,e){return j(this,t,e,!1)},__iterator:function(t,e){return R(this,t,e,!1)}},{},ur);var cr=or.prototype;cr[rr]=cr.values,cr.__toJS=cr.toArray,cr.__toStringMapper=O;var fr=function(t){this._iterator=t,this._iteratorCache=[]};je.createClass(fr,{__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);for(var r=this._iterator,n=this._iteratorCache,i=0;n.length>i;)if(t(n[i],i++,this)===!1)return i;for(var u;!(u=r.next()).done;){var a=u.value;if(n[i]=a,t(a,i++,this)===!1)break}return i},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterator,n=this._iteratorCache,i=0;return new nr(function(){if(i>=n.length){var e=r.next();if(e.done)return e;n[i]=e.value}return v(t,i,n[i++])})}},{},or);var _r=function(t){this._iterable=t,this.length=t.length||t.size};je.createClass(_r,{__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);var r=this._iterable,n=d(r),i=0;if(m(n))for(var u;!(u=n.next()).done&&t(u.value,i++,this)!==!1;);return i},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterable,n=d(r);if(!m(n))return new nr(function(){return g()});var i=0;return new nr(function(){var e=n.next();return e.done?e:v(t,i++,e.value) <add>})}},{},or);var lr=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.length=e.length};je.createClass(lr,{toObject:function(){return this._object},get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var r=this._object,n=this._keys,i=n.length-1,u=0;i>=u;u++){var a=n[e?i-u:u];if(t(r[a],a,this)===!1)return u+1}return u},__iterator:function(t,e){var r=this._object,n=this._keys,i=n.length-1,u=0;return new nr(function(){var a=n[e?i-u:u];return u++>i?g():v(t,a,r[a])})}},{},ur);var vr=function(t){this._array=t,this.length=t.length};je.createClass(vr,{toArray:function(){return this._array},get:function(t,e){return this.has(t)?this._array[A(this,t)]:e},__iterate:function(t,e){for(var r=this._array,n=r.length-1,i=0;n>=i;i++)if(t(r[e?n-i:i],i,this)===!1)return i+1;return i},__iterator:function(t,e){var r=this._array,n=r.length-1,i=0;return new nr(function(){return i>n?g():v(t,i,r[e?n-i++:i++])})}},{},or);var gr=function(t){this._seq=t,this.length=t.length};je.createClass(gr,{contains:function(t){return this._seq.contains(t)},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this},__iterate:function(t,e){var r=this,n=0;return this._seq.__iterate(function(e){return t(e,n++,r)},e)},__iterator:function(t,e){var r=this._seq.__iterator(Ze,e),n=0;return new nr(function(){var e=r.next();return e.done?e:v(t,n++,e.value,e)})}},{},or);var pr=function(t){this._seq=t,this.length=t.length};je.createClass(pr,{get:function(t,e){return this._seq.get(t,e)},has:function(t){return this._seq.has(t)},valueSeq:function(){return this._seq},reverse:function(){var t=this,e=P(this,!0);return e.valueSeq=function(){return t._seq.reverse()},e},map:function(t,e){var r=this,n=W(this,t,e);return n.valueSeq=function(){return r._seq.map(t,e)},n},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this},__iterate:function(t,e){var r=this,n=e?w(this):0;return this._seq.__iterate(function(i){return t(i,e?--n:n++,r) <add>},e)},__iterator:function(t,e){var r=this._seq.__iterator(Ze,e),n=e?w(this):0;return new nr(function(){var i=r.next();return i.done?i:v(t,e?--n:n++,i.value,i)})}},{},ur);var mr=function(t){this._seq=t,this.length=t.length};je.createClass(mr,{entrySeq:function(){return this._seq},cacheResult:function(){return this._seq.cacheResult(),this.length=this._seq.length,this},__iterate:function(t,e){var r=this;return this._seq.__iterate(function(e){return e&&t(e[1],e[0],r)},e)},__iterator:function(t,e){var r=this._seq.__iterator(Ze,e);return new nr(function(){for(;;){var e=r.next();if(e.done)return e;var n=e.value;if(n)return t===$e?e:v(t,n[0],n[1],e)}})}},{},ur);var dr=function(t){var e=yr.empty();return t?t.constructor===yr?t:e.merge(t):e},yr=dr;je.createClass(dr,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return this._root?this._root.get(0,h(t),t,e):e},set:function(t,e){return X(this,t,e)},remove:function(t){return X(this,t,Ke)},update:function(t,e,r){return 1===arguments.length?this.updateIn([],void 0,t):this.updateIn([t],e,r)},updateIn:function(t,e,r){return r||(r=e,e=void 0),ue(this,t,e,r,0)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):yr.empty()},merge:function(){return re(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return re(this,t,e)},mergeDeep:function(){return re(this,ne(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return re(this,ne(t),e)},cursor:function(t,e){var r=0===arguments.length||"function"==typeof t&&(e=t)?[]:Array.isArray(t)?t:[t];return De(this,r,e)},withMutations:function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new a)},asImmutable:function(){return this.__ensureOwner()},wasAltered:function(){return this.__altered},__iterator:function(t,e){return new Or(this,t,e) <add>},__iterate:function(t,e){var r=this,n=0;return this._root&&this._root.iterate(function(e){return n++,t(e[1],e[0],r)},e),n},__ensureOwner:function(t){return t===this.__ownerID?this:t?Q(this.length,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)}},{empty:function(){return Cr||(Cr=Q(0))}},ur);var wr=dr.prototype;wr[Re]=wr.remove,dr.from=dr;var Sr=function(t,e,r){this.ownerID=t,this.bitmap=e,this.nodes=r},Ir=Sr;je.createClass(Sr,{get:function(t,e,r,n){var i=1<<((0===t?e:e>>>t)&Pe),u=this.bitmap;return 0===(u&i)?n:this.nodes[ae(u&i-1)].get(t+Ue,e,r,n)},update:function(t,e,r,n,i,u,a){var s=(0===e?r:r>>>e)&Pe,o=1<<s,h=this.bitmap,c=0!==(h&o);if(!c&&i===Ke)return this;var f=ae(h&o-1),_=this.nodes,l=c?_[f]:null,v=Y(l,t,e+Ue,r,n,i,u,a);if(v===l)return this;if(!c&&v&&_.length>=Ar)return ee(t,_,h,s,v);if(c&&!v&&2===_.length&&Z(_[1^f]))return _[1^f];if(c&&v&&1===_.length&&Z(v))return v;var g=t&&t===this.ownerID,p=c?v?h:h^o:h|o,m=c?v?se(_,f,v,g):he(_,f,g):oe(_,f,v,g);return g?(this.bitmap=p,this.nodes=m,this):new Ir(t,p,m)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++)if(r[e?i-n:n].iterate(t,e)===!1)return!1}},{});var qr=function(t,e,r){this.ownerID=t,this.count=e,this.nodes=r},br=qr;je.createClass(qr,{get:function(t,e,r,n){var i=(0===t?e:e>>>t)&Pe,u=this.nodes[i];return u?u.get(t+Ue,e,r,n):n},update:function(t,e,r,n,i,u,a){var s=(0===e?r:r>>>e)&Pe,o=i===Ke,h=this.nodes,c=h[s];if(o&&!c)return this;var f=Y(c,t,e+Ue,r,n,i,u,a);if(f===c)return this;var _=this.count;if(c){if(!f&&(_--,Er>_))return te(t,h,_,s)}else _++;var l=t&&t===this.ownerID,v=se(h,s,f,l);return l?(this.count=_,this.nodes=v,this):new br(t,_,v)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++){var u=r[e?i-n:n];if(u&&u.iterate(t,e)===!1)return!1}}},{});var kr=function(t,e,r){this.ownerID=t,this.hash=e,this.entries=r},Mr=kr;je.createClass(kr,{get:function(t,e,r,i){for(var u=this.entries,a=0,s=u.length;s>a;a++)if(n(r,u[a][0]))return u[a][1];return i},update:function(t,e,r,i,a,o,h){var c=a===Ke;if(r!==this.hash)return c?this:(u(h),u(o),$(this,t,e,r,[i,a])); <add>for(var f=this.entries,_=0,l=f.length;l>_&&!n(i,f[_][0]);_++);var v=l>_;if(c&&!v)return this;if(u(h),(c||!v)&&u(o),c&&2===l)return new xr(t,this.hash,f[1^_]);var g=t&&t===this.ownerID,p=g?f:s(f);return v?c?_===l-1?p.pop():p[_]=p.pop():p[_]=[i,a]:p.push([i,a]),g?(this.entries=p,this):new Mr(t,this.hash,p)},iterate:function(t,e){for(var r=this.entries,n=0,i=r.length-1;i>=n;n++)if(t(r[e?i-n:n])===!1)return!1}},{});var xr=function(t,e,r){this.ownerID=t,this.hash=e,this.entry=r},Dr=xr;je.createClass(xr,{get:function(t,e,r,i){return n(r,this.entry[0])?this.entry[1]:i},update:function(t,e,r,i,a,s,o){var h=a===Ke,c=n(i,this.entry[0]);return(c?a===this.entry[1]:h)?this:(u(o),h?(u(s),null):c?t&&t===this.ownerID?(this.entry[1]=a,this):new Dr(t,r,[i,a]):(u(s),$(this,t,e,r,[i,a])))},iterate:function(t){return t(this.entry)}},{});var Or=function(t,e,r){this._type=e,this._reverse=r,this._stack=t._root&&H(t._root)};je.createClass(Or,{next:function(){for(var t=this._type,e=this._stack;e;){var r,n=e.node,i=e.index++;if(n.entry){if(0===i)return G(t,n.entry)}else if(n.entries){if(r=n.entries.length-1,r>=i)return G(t,n.entries[this._reverse?r-i:i])}else if(r=n.nodes.length-1,r>=i){var u=n.nodes[this._reverse?r-i:i];if(u){if(u.entry)return G(t,u.entry);e=this._stack=H(u,e)}continue}e=this._stack=this._stack.__prev}return g()}},{},nr);var Cr,Ar=We/2,Er=We/4,jr=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Rr.from(t)},Rr=jr;je.createClass(jr,{toString:function(){return this.__toString("Vector [","]")},get:function(t,e){if(t=A(this,t),0>t||t>=this.length)return e;t+=this._origin;var r=pe(this,t);return r&&r.array[t&Pe]},set:function(t,e){return le(this,t,e)},remove:function(t){return le(this,t,Ke)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=this._origin=this._size=0,this._level=Ue,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):Rr.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(r){me(r,0,e+t.length);for(var n=0;t.length>n;n++)r.set(e+n,t[n]) <add>})},pop:function(){return me(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){me(e,-t.length);for(var r=0;t.length>r;r++)e.set(r,t[r])})},shift:function(){return me(this,1)},merge:function(){return de(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return de(this,t,e)},mergeDeep:function(){return de(this,ne(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return de(this,ne(t),e)},setLength:function(t){return me(this,0,t)},slice:function(t,e){var r=je.superCall(this,Rr.prototype,"slice",[t,e]);if(r!==this){var n=this,i=n.length;r.toVector=function(){return me(n,0>t?Math.max(0,i+t):i?Math.min(i,t):t,null==e?i:0>e?Math.max(0,i+e):i?Math.min(i,e):e)}}return r},__iterator:function(t,e){return new Kr(this,t,e)},__iterate:function(t,e){var r=this,n=0,i=function(e){return t(e,n++,r)},u=ye(this._size);return e?ce(this._tail,0,u-this._origin,this._size-this._origin,i,e)&&ce(this._root,this._level,-this._origin,u-this._origin,i,e):ce(this._root,this._level,-this._origin,u-this._origin,i,e)&&ce(this._tail,0,u-this._origin,this._size-this._origin,i,e),n},__ensureOwner:function(t){return t===this.__ownerID?this:t?_e(this._origin,this._size,this._level,this._root,this._tail,t,this.__hash):(this.__ownerID=t,this)}},{empty:function(){return zr||(zr=_e(0,0,Ue))},from:function(t){if(!t||0===t.length)return Rr.empty();if(t.constructor===Rr)return t;var e=Array.isArray(t);return t.length>0&&We>t.length?_e(0,t.length,Ue,null,new Wr(e?s(t):ur(t).toArray())):(e||(t=ur(t).valueSeq()),Rr.empty().merge(t))}},or);var Ur=jr.prototype;Ur[Re]=Ur.remove,Ur.update=wr.update,Ur.updateIn=wr.updateIn,Ur.cursor=wr.cursor,Ur.withMutations=wr.withMutations,Ur.asMutable=wr.asMutable,Ur.asImmutable=wr.asImmutable,Ur.wasAltered=wr.wasAltered;var Wr=function(t,e){this.array=t,this.ownerID=e},Pr=Wr;je.createClass(Wr,{removeBefore:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r>>>e&Pe;if(n>=this.array.length)return new Pr([],t); <add>var i,u=0===n;if(e>0){var a=this.array[n];if(i=a&&a.removeBefore(t,e-Ue,r),i===a&&u)return this}if(u&&!i)return this;var s=ge(this,t);if(!u)for(var o=0;n>o;o++)s.array[o]=void 0;return i&&(s.array[n]=i),s},removeAfter:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r-1>>>e&Pe;if(n>=this.array.length)return this;var i,u=n===this.array.length-1;if(e>0){var a=this.array[n];if(i=a&&a.removeAfter(t,e-Ue,r),i===a&&u)return this}if(u&&!i)return this;var s=ge(this,t);return u||s.array.pop(),i&&(s.array[n]=i),s}},{});var Kr=function(t,e,r){this._type=e,this._reverse=!!r,this._maxIndex=t.length-1;var n=ye(t._size),i=fe(t._root&&t._root.array,t._level,-t._origin,n-t._origin-1),u=fe(t._tail&&t._tail.array,0,n-t._origin,t._size-t._origin-1);this._stack=r?u:i,this._stack.__prev=r?i:u};je.createClass(Kr,{next:function(){for(var t=this._stack;t;){var e=t.array,r=t.index++;if(this._reverse&&(r=Pe-r,r>t.rawMax&&(r=t.rawMax,t.index=We-r)),r>=0&&We>r&&t.rawMax>=r){var n=e&&e[r];if(0===t.level){var i,u=this._type;return 1!==u&&(i=t.offset+(r<<t.level),this._reverse&&(i=this._maxIndex-i)),v(u,i,n)}this._stack=t=fe(n&&n.array,t.level-Ue,t.offset+(r<<t.level),t.max,t)}else t=this._stack=this._stack.__prev}return g()}},{},nr);var zr,Jr=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Br.from(t)},Br=Jr;je.createClass(Jr,{toString:function(){return this.__toString("Stack [","]")},get:function(t,e){for(var r=this._head;r&&t--;)r=r.next;return r?r.value:e},peek:function(){return this._head&&this._head.value},push:function(){if(0===arguments.length)return this;for(var t=this.length+arguments.length,e=this._head,r=arguments.length-1;r>=0;r--)e={value:arguments[r],next:e};return this.__ownerID?(this.length=t,this._head=e,this.__hash=void 0,this.__altered=!0,this):we(t,e)},pushAll:function(t){if(t=ur(t),0===t.length)return this;var e=this.length,r=this._head;return t.reverse().forEach(function(t){e++,r={value:t,next:r}}),this.__ownerID?(this.length=e,this._head=r,this.__hash=void 0,this.__altered=!0,this):we(e,r) <add>},pop:function(){return this.slice(1)},unshift:function(){return this.push.apply(this,arguments)},unshiftAll:function(t){return this.pushAll(t)},shift:function(){return this.pop.apply(this,arguments)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Br.empty()},slice:function(t,e){if(S(t,e,this.length))return this;var r=I(t,this.length),n=q(e,this.length);if(n!==this.length)return je.superCall(this,Br.prototype,"slice",[t,e]);for(var i=this.length-r,u=this._head;r--;)u=u.next;return this.__ownerID?(this.length=i,this._head=u,this.__hash=void 0,this.__altered=!0,this):we(i,u)},__ensureOwner:function(t){return t===this.__ownerID?this:t?we(this.length,this._head,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);for(var r=0,n=this._head;n&&t(n.value,r++,this)!==!1;)n=n.next;return r},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=0,n=this._head;return new nr(function(){if(n){var e=n.value;return n=n.next,v(t,r++,e)}return g()})}},{empty:function(){return Lr||(Lr=we(0))},from:function(t){var e=Br.empty();return t?t.constructor===Br?t:e.unshiftAll(t):e}},or);var Vr=Jr.prototype;Vr.withMutations=wr.withMutations,Vr.asMutable=wr.asMutable,Vr.asImmutable=wr.asImmutable,Vr.wasAltered=wr.wasAltered;var Lr,Nr=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Tr.from(t)},Tr=Nr;je.createClass(Nr,{toString:function(){return this.__toString("Set {","}")},get:function(t,e){return this._map.has(t)?t:e},contains:function(t){return this._map.has(t)},add:function(t){var e=this._map.set(t,null);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:Se(e)},remove:function(t){var e=this._map.remove(t);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:0===e.length?Tr.empty():Se(e)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this):Tr.empty() <add>},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var r=0;t.length>r;r++)ur(t[r]).forEach(function(t){return e.add(t)})})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ur(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.every(function(t){return t.contains(r)})||e.remove(r)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ur(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.some(function(t){return t.contains(r)})&&e.remove(r)})})},isSubset:function(t){return t=ur(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=ur(t),t.every(function(t){return e.contains(t)})},merge:function(){return this.union.apply(this,arguments)},mergeWith:function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return this.union.apply(this,t)},wasAltered:function(){return this._map.wasAltered()},__iterate:function(t,e){var r=this;return this._map.__iterate(function(e,n){return t(n,n,r)},e)},__iterator:function(t,e){return this._map.map(function(t,e){return e}).__iterator(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t);return t?Se(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return Gr||(Gr=Se(dr.empty()))},from:function(t){var e=Tr.empty();return t?t.constructor===Tr?t:e.union(t):e},fromKeys:function(t){return Tr.from(ur(t).flip())}},ur);var Fr=Nr.prototype;Fr[Re]=Fr.remove,Fr[rr]=Fr.values,Fr.mergeDeep=Fr.merge,Fr.mergeDeepWith=Fr.mergeWith,Fr.withMutations=wr.withMutations,Fr.asMutable=wr.asMutable,Fr.asImmutable=wr.asImmutable,Fr.__toJS=cr.__toJS,Fr.__toStringMapper=cr.__toStringMapper;var Gr,Hr=function(t){var e=Qr.empty();return t?t.constructor===Qr?t:e.merge(t):e},Qr=Hr;je.createClass(Hr,{toString:function(){return this.__toString("OrderedMap {","}") <add>},get:function(t,e){var r=this._map.get(t);return null!=r?this._vector.get(r)[1]:e},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this._vector.clear(),this):Qr.empty()},set:function(t,e){return qe(this,t,e)},remove:function(t){return qe(this,t,Ke)},wasAltered:function(){return this._map.wasAltered()||this._vector.wasAltered()},__iterate:function(t,e){var r=this;return this._vector.__iterate(function(e){return e&&t(e[1],e[0],r)},e)},__iterator:function(t,e){return this._vector.fromEntrySeq().__iterator(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),r=this._vector.__ensureOwner(t);return t?Ie(e,r,t,this.__hash):(this.__ownerID=t,this._map=e,this._vector=r,this)}},{empty:function(){return Xr||(Xr=Ie(dr.empty(),jr.empty()))}},dr),Hr.from=Hr,Hr.prototype[Re]=Hr.prototype.remove;var Xr,Yr=function(t,e){var r=function(t){return this instanceof r?void(this._map=dr(t)):new r(t)},n=Object.keys(t),i=r.prototype=Object.create(Zr);i.constructor=r,e&&(i._name=e),i._defaultValues=t,i._keys=n,i.length=n.length;try{ur(t).forEach(function(t,e){Object.defineProperty(r.prototype,e,{get:function(){return this.get(e)},set:function(t){o(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})})}catch(u){}return r};je.createClass(Yr,{toString:function(){return this.__toString(this._name+" {","}")},has:function(t){return this._defaultValues.hasOwnProperty(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues[t]):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;var t=Object.getPrototypeOf(this).constructor;return t._empty||(t._empty=be(this,dr.empty()))},set:function(t,e){if(!this.has(t))throw Error('Cannot set unknown key "'+t+'" on '+this._name);var r=this._map.set(t,e);return this.__ownerID||r===this._map?this:be(this,r)},remove:function(t){if(null==t||!this.has(t))return this;var e=this._map.remove(t);return this.__ownerID||e===this._map?this:be(this,e)},keys:function(){return this._map.keys() <add>},values:function(){return this._map.values()},entries:function(){return this._map.entries()},wasAltered:function(){return this._map.wasAltered()},__iterator:function(t,e){return this._map.__iterator(t,e)},__iterate:function(t,e){var r=this;return ur(this._defaultValues).map(function(t,e){return r.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?be(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},ur);var Zr=Yr.prototype;Zr._name="Record",Zr[Re]=Zr.remove,Zr.merge=wr.merge,Zr.mergeWith=wr.mergeWith,Zr.mergeDeep=wr.mergeDeep,Zr.mergeDeepWith=wr.mergeDeepWith,Zr.update=wr.update,Zr.updateIn=wr.updateIn,Zr.cursor=wr.cursor,Zr.withMutations=wr.withMutations,Zr.asMutable=wr.asMutable,Zr.asImmutable=wr.asImmutable;var $r=function(t,e,r){return this instanceof tn?(o(0!==r,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&rn?rn:(r=null==r?1:Math.abs(r),t>e&&(r=-r),this._start=t,this._end=e,this._step=r,void(this.length=Math.max(0,Math.ceil((e-t)/r-1)+1)))):new tn(t,e,r)},tn=$r;je.createClass($r,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},get:function(t,e){return this.has(t)?this._start+A(this,t)*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e){return S(t,e,this.length)?this:(t=I(t,this.length),e=q(e,this.length),t>=e?rn:new tn(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var r=e/this._step;if(r>=0&&this.length>r)return r}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,Math.max(0,t))},skip:function(t){return this.slice(Math.max(0,t))},__iterate:function(t,e){for(var r=this.length-1,n=this._step,i=e?this._start+r*n:this._start,u=0;r>=u;u++){if(t(i,u,this)===!1)return u+1;i+=e?-n:n}return u},__iterator:function(t,e){var r=this.length-1,n=this._step,i=e?this._start+r*n:this._start,u=0; <add>return new nr(function(){var a=i;return i+=e?-n:n,u>r?g():v(t,u++,a)})},__deepEquals:function(t){return t instanceof tn?this._start===t._start&&this._end===t._end&&this._step===t._step:je.superCall(this,tn.prototype,"__deepEquals",[t])}},{},or);var en=$r.prototype;en.__toJS=en.toArray,en.first=Ur.first,en.last=Ur.last;var rn=$r(0,0),nn=function(t,e){return 0===e&&sn?sn:this instanceof un?(this._value=t,void(this.length=null==e?1/0:Math.max(0,e))):new un(t,e)},un=nn;je.createClass(nn,{toString:function(){return 0===this.length?"Repeat []":"Repeat [ "+this._value+" "+this.length+" times ]"},get:function(t,e){return this.has(t)?this._value:e},contains:function(t){return n(this._value,t)},slice:function(t,e){var r=this.length;return t=0>t?Math.max(0,r+t):Math.min(r,t),e=null==e?r:e>0?Math.min(r,e):Math.max(0,r+e),e>t?new un(this._value,e-t):sn},reverse:function(){return this},indexOf:function(t){return n(this._value,t)?0:-1},lastIndexOf:function(t){return n(this._value,t)?this.length:-1},__iterate:function(t){for(var e=0;this.length>e;e++)if(t(this._value,e,this)===!1)return e+1;return e},__iterator:function(t){var e=this,r=0;return new nr(function(){return e.length>r?v(t,r++,e._value):g()})},__deepEquals:function(t){return t instanceof un?n(this._value,t._value):je.superCall(this,un.prototype,"__deepEquals",[t])}},{},or);var an=nn.prototype;an.last=an.first,an.has=en.has,an.take=en.take,an.skip=en.skip,an.__toJS=en.__toJS;var sn=new nn(void 0,0),on=function(t,e,r,n){this.length=n,this._rootData=t,this._keyPath=e,this._onChange=r};je.createClass(on,{equals:function(t){return n(this.deref(),t&&("function"==typeof t.deref?t.deref():t))},deref:function(t){return this._rootData.getIn(this._keyPath,t)},get:function(t,e){if(Array.isArray(t)&&0===t.length)return this;var r=this._rootData.getIn(this._keyPath.concat(t),Ke);return r===Ke?e:Oe(this,t,r)},set:function(t,e){return Ae(this,function(r){return r.set(t,e)},t)},remove:function(t){return Ae(this,function(e){return e.remove(t)},t)},clear:function(){return Ae(this,function(t){return t.clear() <add>})},update:function(t,e,r){return 1===arguments.length?Ae(this,t):Ae(this,function(n){return n.update(t,e,r)},t)},withMutations:function(t){return Ae(this,function(e){return(e||dr.empty()).withMutations(t)})},cursor:function(t){return Array.isArray(t)&&0===t.length?this:Ce(this,t)},__iterate:function(t,e){var r=this,n=this.deref();return n&&n.__iterate?n.__iterate(function(e,n){return t(Oe(r,n,e),n,r)},e):0},__iterator:function(t,e){var r=this,n=this.deref(),i=n&&n.__iterator&&n.__iterator($e,e);return new nr(function(){if(!i)return g();var e=i.next();if(e.done)return e;var n=e.value,u=n[0],a=n[1];return v(t,u,Oe(r,u,a),e)})}},{},ur);var hn=on.prototype;hn[Re]=hn.remove,hn.getIn=hn.get;var cn=function(t,e,r,n){this.length=n,this._rootData=t,this._keyPath=e,this._onChange=r};je.createClass(cn,{},{},or);var fn=cn.prototype;fn.equals=hn.equals,fn.deref=hn.deref,fn.get=hn.get,fn.getIn=hn.getIn,fn.set=hn.set,fn[Re]=fn.remove=hn.remove,fn.clear=hn.clear,fn.update=hn.update,fn.withMutations=hn.withMutations,fn.cursor=hn.cursor,fn.__iterate=hn.__iterate,fn.__iterator=hn.__iterator;var _n={Sequence:ur,Map:dr,Vector:jr,Stack:Jr,Set:Nr,OrderedMap:Hr,Record:Yr,Range:$r,Repeat:nn,is:n,fromJS:ke};return _n}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t(); <ide>\ No newline at end of file <ide><path>src/Hash.js <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> */ <ide> <del>/* global Symbol */ <add>/* global Symbol, WeakMap */ <ide> /* exported hash, HASH_MAX_VAL */ <ide> <ide> function hash(o) { <ide> function hashString(string) { <ide> } <ide> <ide> function hashJSObj(obj) { <del> var hash = obj[UID_HASH_KEY]; <add> var hash = weakMap && weakMap.get(obj); <add> if (hash) return hash; <add> <add> hash = obj[UID_HASH_KEY]; <ide> if (hash) return hash; <ide> <ide> if (!canDefineProperty) { <ide> function hashJSObj(obj) { <ide> if (hash) return hash; <ide> } <ide> <del> if (!canDefineProperty || Object.isExtensible(obj)) { <del> hash = ++objHashUID & HASH_MAX_VAL; <del> <del> if (canDefineProperty) { <del> Object.defineProperty(obj, UID_HASH_KEY, { <del> 'enumerable': false, <del> 'configurable': false, <del> 'writable': false, <del> 'value': hash <del> }); <del> } else if (propertyIsEnumerable && <del> obj.propertyIsEnumerable === propertyIsEnumerable) { <del> // Since we can't define a non-enumerable property on the object <del> // we'll hijack one of the less-used non-enumerable properties to <del> // save our hash on it. Since this is a function it will not show up in <del> // `JSON.stringify` which is what we want. <del> obj.propertyIsEnumerable = function() { <del> return propertyIsEnumerable.apply(this, arguments); <del> }; <del> obj.propertyIsEnumerable[UID_HASH_KEY] = hash; <del> } else if (obj.nodeType) { <del> // At this point we couldn't get the IE `uniqueID` to use as a hash <del> // and we couldn't use a non-enumerable property to exploit the <del> // dontEnum bug so we simply add the `UID_HASH_KEY` on the node <del> // itself. <del> obj[UID_HASH_KEY] = hash; <del> } else { <del> throw new Error('Unable to set a non-enumerable property on object.'); <del> } <del> return hash; <del> } else { <add> if (canDefineProperty && !Object.isExtensible(obj)) { <ide> throw new Error('Non-extensible objects are not allowed as keys.'); <ide> } <add> <add> hash = ++objHashUID & HASH_MAX_VAL; <add> <add> if (weakMap) { <add> weakMap.set(obj, hash); <add> } else if (canDefineProperty) { <add> Object.defineProperty(obj, UID_HASH_KEY, { <add> 'enumerable': false, <add> 'configurable': false, <add> 'writable': false, <add> 'value': hash <add> }); <add> } else if (propertyIsEnumerable && <add> obj.propertyIsEnumerable === propertyIsEnumerable) { <add> // Since we can't define a non-enumerable property on the object <add> // we'll hijack one of the less-used non-enumerable properties to <add> // save our hash on it. Since this is a function it will not show up in <add> // `JSON.stringify` which is what we want. <add> obj.propertyIsEnumerable = function() { <add> return propertyIsEnumerable.apply(this, arguments); <add> }; <add> obj.propertyIsEnumerable[UID_HASH_KEY] = hash; <add> } else if (obj.nodeType) { <add> // At this point we couldn't get the IE `uniqueID` to use as a hash <add> // and we couldn't use a non-enumerable property to exploit the <add> // dontEnum bug so we simply add the `UID_HASH_KEY` on the node <add> // itself. <add> obj[UID_HASH_KEY] = hash; <add> } else { <add> throw new Error('Unable to set a non-enumerable property on object.'); <add> } <add> <add> return hash; <ide> } <ide> <ide> var propertyIsEnumerable = Object.prototype.propertyIsEnumerable; <ide> function getIENodeHash(node) { <ide> } <ide> } <ide> <add>// If possible, use a WeakMap. <add>var weakMap = typeof WeakMap === 'function' && new WeakMap(); <add> <ide> var HASH_MAX_VAL = 0x7FFFFFFF; // 2^31 - 1 is an efficiently stored int <ide> <ide> var objHashUID = 0; <ide> <ide> var UID_HASH_KEY = '__immutablehash__'; <del>if (typeof Symbol !== 'undefined') { <add>if (typeof Symbol === 'function') { <ide> UID_HASH_KEY = Symbol(UID_HASH_KEY); <ide> } <ide>
3
Javascript
Javascript
show the right error message in the console
6d1277065de850f1a6c1e7d1e9d03d64958829dc
<ide><path>Libraries/Utilities/Alert.js <ide> class AlertAndroid { <ide> } <ide> DialogModuleAndroid.showAlert( <ide> config, <del> (errorMessage) => console.warn(message), <add> (errorMessage) => console.warn(errorMessage), <ide> (action, buttonKey) => { <ide> if (action !== DialogModuleAndroid.buttonClicked) { <ide> return;
1
Javascript
Javascript
add tests for postmortem and dtrace support
cc1b09d6b7c3cc6b8729804cbf644634ba5d0815
<ide><path>test/pummel/test-dtrace-jsstack.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add>var os = require('os'); <add>var util = require('util'); <add> <add>if (os.type() != 'SunOS') { <add> console.error('Skipping because DTrace not available.'); <add> process.exit(0); <add>} <add> <add>/* <add> * Some functions to create a recognizable stack. <add> */ <add>var frames = [ 'stalloogle', 'bagnoogle', 'doogle' ]; <add>var expected; <add> <add>var stalloogle = function (str) { <add> expected = str; <add> os.loadavg(); <add>}; <add> <add>var bagnoogle = function (arg0, arg1) { <add> stalloogle(arg0 + ' is ' + arg1 + ' except that it is read-only'); <add>}; <add> <add>var done = false; <add> <add>var doogle = function () { <add> if (!done) <add> setTimeout(doogle, 10); <add> <add> bagnoogle('The bfs command', '(almost) like ed(1)'); <add>}; <add> <add>var spawn = require('child_process').spawn; <add>var prefix = '/var/tmp/node'; <add>var corefile = prefix + '.' + process.pid; <add> <add>/* <add> * We're going to use DTrace to stop us, gcore us, and set us running again <add> * when we call getloadavg() -- with the implicit assumption that our <add> * deepest function is the only caller of os.loadavg(). <add> */ <add>var dtrace = spawn('dtrace', [ '-qwn', 'syscall::getloadavg:entry/pid == ' + <add> process.pid + '/{ustack(100, 8192); exit(0); }' ]); <add> <add>var output = ''; <add> <add>dtrace.stderr.on('data', function (data) { <add> console.log('dtrace: ' + data); <add>}); <add> <add>dtrace.stdout.on('data', function (data) { <add> output += data; <add>}); <add> <add>dtrace.on('exit', function (code) { <add> if (code != 0) { <add> console.error('dtrace exited with code ' + code); <add> process.exit(code); <add> } <add> <add> done = true; <add> <add> var sentinel = '(anon) as '; <add> var lines = output.split('\n'); <add> <add> for (var i = 0; i < lines.length; i++) { <add> var line = lines[i]; <add> <add> if (line.indexOf(sentinel) == -1 || frames.length === 0) <add> continue; <add> <add> var frame = line.substr(line.indexOf(sentinel) + sentinel.length); <add> var top = frames.shift(); <add> <add> assert.equal(frame.indexOf(top), 0, 'unexpected frame where ' + <add> top + ' was expected'); <add> } <add> <add> assert.equal(frames.length, 0, 'did not find expected frame ' + frames[0]); <add> process.exit(0); <add>}); <add> <add>setTimeout(doogle, 10); <add> <ide><path>test/pummel/test-postmortem-findjsobjects.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add>var os = require('os'); <add>var util = require('util'); <add> <add>if (os.type() != 'SunOS') { <add> console.error('Skipping because postmortem debugging not available.'); <add> process.exit(0); <add>} <add> <add>/* <add> * Now we're going to fork ourselves to gcore <add> */ <add>var spawn = require('child_process').spawn; <add>var prefix = '/var/tmp/node'; <add>var corefile = prefix + '.' + process.pid; <add>var gcore = spawn('gcore', [ '-o', prefix, process.pid + '' ]); <add>var output = ''; <add>var unlinkSync = require('fs').unlinkSync; <add>var args = [ corefile ]; <add> <add>if (process.env.MDB_LIBRARY_PATH && process.env.MDB_LIBRARY_PATH != '') <add> args = args.concat([ '-L', process.env.MDB_LIBRARY_PATH ]); <add> <add>function LanguageH(chapter) { this.OBEY = 'CHAPTER ' + parseInt(chapter, 10); } <add>var obj = new LanguageH(1); <add> <add>gcore.stderr.on('data', function (data) { <add> console.log('gcore: ' + data); <add>}); <add> <add>gcore.on('exit', function (code) { <add> if (code != 0) { <add> console.error('gcore exited with code ' + code); <add> process.exit(code); <add> } <add> <add> var mdb = spawn('mdb', args, { stdio: 'pipe' }); <add> <add> mdb.on('exit', function (code) { <add> var retained = '; core retained as ' + corefile; <add> <add> if (code != 0) { <add> console.error('mdb exited with code ' + util.inspect(code) + retained); <add> process.exit(code); <add> } <add> <add> var lines = output.split('\n'); <add> var found = 0, i, expected = 'OBEY: ' + obj.OBEY, nexpected = 2; <add> <add> for (var i = 0; i < lines.length; i++) { <add> if (lines[i].indexOf(expected) != -1) <add> found++; <add> } <add> <add> assert.equal(found, nexpected, 'expected ' + nexpected + <add> ' objects, found ' + found + retained); <add> <add> unlinkSync(corefile); <add> process.exit(0); <add> }); <add> <add> mdb.stdout.on('data', function (data) { <add> output += data; <add> }); <add> <add> mdb.stderr.on('data', function (data) { <add> console.log('mdb stderr: ' + data); <add> }); <add> <add> mdb.stdin.write('::load v8.so\n'); <add> mdb.stdin.write('::findjsobjects -c LanguageH | '); <add> mdb.stdin.write('::findjsobjects | ::jsprint\n'); <add> mdb.stdin.write('::findjsobjects -p OBEY | '); <add> mdb.stdin.write('::findjsobjects | ::jsprint\n'); <add> mdb.stdin.end(); <add>}); <add> <ide><path>test/pummel/test-postmortem-jsstack.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add>var os = require('os'); <add>var util = require('util'); <add> <add>if (os.type() != 'SunOS') { <add> console.error('Skipping because postmortem debugging not available.'); <add> process.exit(0); <add>} <add> <add>/* <add> * Some functions to create a recognizable stack. <add> */ <add>var frames = [ 'stalloogle', 'bagnoogle', 'doogle' ]; <add>var expected; <add> <add>var stalloogle = function (str) { <add> expected = str; <add> os.loadavg(); <add>}; <add> <add>var bagnoogle = function (arg0, arg1) { <add> stalloogle(arg0 + ' is ' + arg1 + ' except that it is read-only'); <add>}; <add> <add>var done = false; <add> <add>var doogle = function () { <add> if (!done) <add> setTimeout(doogle, 10); <add> <add> bagnoogle('The bfs command', '(almost) like ed(1)'); <add>}; <add> <add>var spawn = require('child_process').spawn; <add>var prefix = '/var/tmp/node'; <add>var corefile = prefix + '.' + process.pid; <add>var args = [ corefile ]; <add> <add>if (process.env.MDB_LIBRARY_PATH && process.env.MDB_LIBRARY_PATH != '') <add> args = args.concat([ '-L', process.env.MDB_LIBRARY_PATH ]); <add> <add>/* <add> * We're going to use DTrace to stop us, gcore us, and set us running again <add> * when we call getloadavg() -- with the implicit assumption that our <add> * deepest function is the only caller of os.loadavg(). <add> */ <add>var dtrace = spawn('dtrace', [ '-qwn', 'syscall::getloadavg:entry/pid == ' + <add> process.pid + '/{stop(); system("gcore -o ' + <add> prefix + ' %d", pid); system("prun %d", pid); exit(0); }' ]); <add> <add>var output = ''; <add>var unlinkSync = require('fs').unlinkSync; <add> <add>dtrace.stderr.on('data', function (data) { <add> console.log('dtrace: ' + data); <add>}); <add> <add>dtrace.on('exit', function (code) { <add> if (code != 0) { <add> console.error('dtrace exited with code ' + code); <add> process.exit(code); <add> } <add> <add> done = true; <add> <add> /* <add> * We have our core file. Now we need to fire up mdb to analyze it... <add> */ <add> var mdb = spawn('mdb', args, { stdio: 'pipe' }); <add> <add> mdb.on('exit', function (code) { <add> var retained = '; core retained as ' + corefile; <add> <add> if (code != 0) { <add> console.error('mdb exited with code ' + code + retained); <add> process.exit(code); <add> } <add> <add> var sentinel = '<anonymous> (as '; <add> var arg1 = ' arg1: '; <add> var lines = output.split('\n'); <add> var matched = 0; <add> var straddr = undefined; <add> <add> for (var i = 0; i < lines.length; i++) { <add> var line = lines[i]; <add> <add> if (matched == 1 && line.indexOf(arg1) === 0) { <add> straddr = line.substr(arg1.length).split(' ')[0]; <add> } <add> <add> if (line.indexOf(sentinel) == -1 || frames.length === 0) <add> continue; <add> <add> var frame = line.substr(line.indexOf(sentinel) + sentinel.length); <add> var top = frames.shift(); <add> <add> assert.equal(frame.indexOf(top), 0, 'unexpected frame where ' + <add> top + ' was expected' + retained); <add> <add> matched++; <add> } <add> <add> assert.equal(frames.length, 0, 'did not find expected frame ' + <add> frames[0] + retained); <add> <add> assert.notEqual(straddr, undefined, <add> 'did not find arg1 for top frame' + retained); <add> <add> /* <add> * Now we're going to take one more swing at the core file to print out <add> * the argument string that we found. <add> */ <add> output = ''; <add> mdb = spawn('mdb', args, { stdio: 'pipe' }); <add> <add> mdb.on('exit', function (code) { <add> if (code != 0) { <add> console.error('mdb (second) exited with code ' + code + retained); <add> process.exit(code); <add> } <add> <add> assert.notEqual(output.indexOf(expected), -1, 'did not find arg1 (' + <add> straddr + ') to contain expected string' + retained); <add> <add> unlinkSync(corefile); <add> process.exit(0); <add> }); <add> <add> mdb.stdout.on('data', function (data) { <add> output += data; <add> }); <add> <add> mdb.stderr.on('data', function (data) { <add> console.log('mdb (second) stderr: ' + data); <add> }); <add> <add> mdb.stdin.write('::load v8.so\n'); <add> mdb.stdin.write(straddr + '::v8str\n'); <add> mdb.stdin.end(); <add> }); <add> <add> mdb.stdout.on('data', function (data) { <add> output += data; <add> }); <add> <add> mdb.stderr.on('data', function (data) { <add> console.log('mdb stderr: ' + data); <add> }); <add> <add> mdb.stdin.write('::load v8.so\n'); <add> mdb.stdin.write('::jsstack -v\n'); <add> mdb.stdin.end(); <add>}); <add> <add>setTimeout(doogle, 10); <add>
3
Javascript
Javascript
remove logic to prepend wildcard on globs
8c80d13dd15574f37b9142a4a12ac0b45baa7124
<ide><path>spec/workspace-spec.js <ide> describe('Workspace', () => { <ide> expect(resultHandler).not.toHaveBeenCalled(); <ide> }); <ide> <del> it('does not excludes ignored files when core.excludeVcsIgnoredPaths is false', async () => { <add> it('does not exclude ignored files when core.excludeVcsIgnoredPaths is false', async () => { <ide> atom.project.setPaths([projectPath]); <ide> atom.config.set('core.excludeVcsIgnoredPaths', false); <ide> const resultHandler = jasmine.createSpy('result found'); <ide> describe('Workspace', () => { <ide> path.join(projectPath, 'ignored.txt') <ide> ); <ide> }); <add> <add> it('does not exclude files when searching on an ignored folder even when core.excludeVcsIgnoredPaths is true', async () => { <add> fs.mkdirSync(path.join(projectPath, 'poop')); <add> ignoredPath = path.join( <add> path.join(projectPath, 'poop', 'whatever.txt') <add> ); <add> fs.writeFileSync(ignoredPath, 'this match should be included'); <add> <add> atom.project.setPaths([projectPath]); <add> atom.config.set('core.excludeVcsIgnoredPaths', true); <add> const resultHandler = jasmine.createSpy('result found'); <add> <add> await scan(/match/, { paths: ['poop'] }, ({ filePath }) => <add> resultHandler(filePath) <add> ); <add> <add> expect(resultHandler).toHaveBeenCalledWith(ignoredPath); <add> }); <add> <add> // This is a current limitation of the ripgrep scanner: whenever it finds a folder <add> // ignored by the vcs, it stops there and it does not try to traverse their subfolders. <add> if (!ripgrep) { <add> it('does not exclude files when searching on an ignored subfolder even when core.excludeVcsIgnoredPaths is true', async () => { <add> fs.mkdirSync(path.join(projectPath, 'poop')); <add> fs.mkdirSync(path.join(projectPath, 'poop', 'subfolder')); <add> ignoredPath = path.join( <add> path.join(projectPath, 'poop', 'subfolder', 'whatever.txt') <add> ); <add> fs.writeFileSync(ignoredPath, 'this match should be included'); <add> <add> atom.project.setPaths([projectPath]); <add> atom.config.set('core.excludeVcsIgnoredPaths', true); <add> const resultHandler = jasmine.createSpy('result found'); <add> <add> await scan( <add> /match/, <add> { <add> paths: ['poop/subfolder'] <add> }, <add> ({ filePath }) => resultHandler(filePath) <add> ); <add> <add> expect(resultHandler).toHaveBeenCalledWith(ignoredPath); <add> }); <add> } <ide> }); <ide> <ide> describe('when the core.followSymlinks config is used', () => { <ide><path>src/ripgrep-directory-searcher.js <ide> module.exports = class RipgrepDirectorySearcher { <ide> args.push('--no-ignore-vcs'); <ide> } <ide> <del> args.push(directoryPath); <del> <ide> const child = spawn(this.rgPath, args, { <del> cwd: directory.getPath(), <add> cwd: directoryPath, <ide> stdio: ['pipe', 'pipe', 'pipe'] <ide> }); <ide> <ide> module.exports = class RipgrepDirectorySearcher { <ide> <ide> if (message.type === 'begin') { <ide> pendingEvent = { <del> filePath: getText(message.data.path), <add> filePath: path.join(directoryPath, getText(message.data.path)), <ide> matches: [] <ide> }; <ide> pendingLeadingContext = []; <ide> module.exports = class RipgrepDirectorySearcher { <ide> pattern = pattern.slice(0, -1); <ide> } <ide> <del> pattern = pattern.startsWith('**/') ? pattern : `**/${pattern}`; <del> <ide> output.push(pattern); <ide> output.push(pattern.endsWith('/**') ? pattern : `${pattern}/**`); <ide> }
2
Python
Python
fix super naming
1a3d4d8aff8ad3a9fdac6286e449f4756dcaecf6
<ide><path>libcloud/httplib_ssl.py <ide> class SignedHTTPSAdapter(HTTPAdapter): <ide> def __init__(self, cert_file, key_file): <ide> self.cert_file = cert_file <ide> self.key_file = key_file <del> super(SignedX509Adapter, self).__init__() <add> super(SignedHTTPSAdapter, self).__init__() <ide> <ide> def init_poolmanager(self, connections, maxsize, block=False): <ide> self.poolmanager = PoolManager(
1
Java
Java
fix remote context handling in urltag
8b545f47bd625aba2cd7d4d4877498d5a28f4f28
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/tags/UrlTag.java <ide> /* <del> * Copyright 2002-2013 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> private String createUrl() throws JspException { <ide> url.append(request.getContextPath()); <ide> } <ide> else { <del> url.append(this.context); <add> if(this.context.endsWith("/")) { <add> url.append(this.context.substring(0, this.context.length() - 1)); <add> } <add> else { <add> url.append(this.context); <add> } <ide> } <ide> } <ide> if (this.type != UrlType.RELATIVE && this.type != UrlType.ABSOLUTE && !this.value.startsWith("/")) { <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java <ide> /* <del> * Copyright 2002-2013 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 void testCreateUrlRemoteContextWithSlash() throws JspException { <ide> assertEquals("/some-other-context/url/path", uri); <ide> } <ide> <add> public void testCreateUrlRemoteContextSingleSlash() throws JspException { <add> ((MockHttpServletRequest) context.getRequest()) <add> .setContextPath("/app-context"); <add> <add> tag.setValue("/url/path"); <add> tag.setContext("/"); <add> <add> tag.doStartTag(); <add> <add> String uri = invokeCreateUrl(tag); <add> <add> assertEquals("/url/path", uri); <add> } <add> <ide> public void testCreateUrlWithParams() throws JspException { <ide> tag.setValue("url/path"); <ide>
2
Text
Text
add link to code ide configs
cf888ac105ffd02bbceef02c16d0df548676abd1
<ide><path>doc/guides/contributing/pull-requests.md <ide> To get started, you will need to have `git` installed locally. Depending on <ide> your operating system, there are also a number of other dependencies required. <ide> These are detailed in the [Building guide][]. <ide> <add>Depending on your environment you might want to grab IDE specific settings from <add>[IDE configs](https://github.com/nodejs/node-code-ide-configs). <add> <ide> Once you have `git` and are sure you have all of the necessary dependencies, <ide> it's time to create a fork. <ide>
1
PHP
PHP
add strict_types to mailer
3a769d5743a3620747fdda0a118312e0175cd570
<ide><path>src/Mailer/AbstractTransport.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Mailer/Email.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> protected function _validateEmail($email, $context) <ide> if (filter_var($email, FILTER_VALIDATE_EMAIL)) { <ide> return; <ide> } <del> } elseif (preg_match($this->_emailPattern, $email)) { <add> } elseif (preg_match($this->_emailPattern, (string)$email)) { <ide> return; <ide> } <ide> <ide> public function reset(): self <ide> $this->viewBuilder()->setTemplate(''); <ide> $this->viewBuilder()->setClassName('Cake\View\View'); <ide> $this->viewVars = []; <del> $this->viewBuilder()->setTheme(false); <add> $this->viewBuilder()->setTheme(null); <ide> $this->viewBuilder()->setHelpers(['Html'], false); <ide> <ide> return $this; <ide> protected function _encodeString($text, $charset) <ide> */ <ide> protected function _wrap($message, $wrapLength = Email::LINE_LENGTH_MUST) <ide> { <del> if (strlen($message) === 0) { <add> if ($message === null || strlen($message) === 0) { <ide> return ['']; <ide> } <ide> $message = str_replace(["\r\n", "\r"], "\n", $message); <ide> protected function _renderTemplates($content) <ide> $View = $this->createView(); <ide> <ide> list($templatePlugin) = pluginSplit($View->getTemplate()); <del> list($layoutPlugin) = pluginSplit($View->getLayout()); <add> list($layoutPlugin) = pluginSplit((string)$View->getLayout()); <ide> if ($templatePlugin) { <ide> $View->setPlugin($templatePlugin); <ide> } elseif ($layoutPlugin) { <ide><path>src/Mailer/Exception/MissingActionException.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Mailer/Exception/MissingMailerException.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Mailer/Mailer.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Mailer/MailerAwareTrait.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Mailer/Transport/DebugTransport.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * Emulates the email sending process for testing purposes <ide> * <ide><path>src/Mailer/Transport/MailTransport.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * Send mail using mail() function <ide> * <ide><path>src/Mailer/Transport/SmtpTransport.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function testSubject() <ide> <ide> $this->Email->setSubject('You have a new message, I think.'); <ide> $this->assertSame($this->Email->getSubject(), 'You have a new message, I think.'); <del> $this->Email->setSubject(1); <add> $this->Email->setSubject('1'); <ide> $this->assertSame('1', $this->Email->getSubject()); <ide> <ide> $input = 'هذه رسالة بعنوان طويل مرسل للمستلم'; <ide> public function testReset() <ide> <ide> $this->Email->reset(); <ide> $this->assertSame([], $this->Email->getTo()); <del> $this->assertSame('', $this->Email->getTheme()); <add> $this->assertNull($this->Email->getTheme()); <ide> $this->assertSame(Email::EMAIL_PATTERN, $this->Email->getEmailPattern()); <ide> } <ide> <ide><path>tests/TestCase/Mailer/MailerAwareTraitTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Mailer/MailerTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Mailer/Transport/DebugTransportTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * DebugTransportTest file <ide> * <ide><path>tests/TestCase/Mailer/Transport/MailTransportTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * MailTransportTest file <ide> * <ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
15
PHP
PHP
remove unused constant
2685f4c476ed2415d2e64b52f49bc901b4ae88c5
<ide><path>src/Core/functions.php <ide> <ide> use Cake\Core\Configure; <ide> <del>if (!defined('DS')) { <del> /** <del> * Define DS as short form of DIRECTORY_SEPARATOR. <del> */ <del> define('DS', DIRECTORY_SEPARATOR); <del>} <del> <ide> if (!function_exists('h')) { <ide> /** <ide> * Convenience method for htmlspecialchars.
1
Javascript
Javascript
use resolverfactory.get with dep category option
d7dd4ececb2da1ffa043a401502eaa7a00a5a3c6
<ide><path>lib/sharing/ConsumeSharedPlugin.js <ide> class ConsumeSharedPlugin { <ide> /** @type {LazySet<string>} */ <ide> missingDependencies: new LazySet() <ide> }; <del> const resolver = compilation.resolverFactory.get("normal"); <add> const resolver = compilation.resolverFactory.get( <add> "normal", <add> undefined, <add> "esm" <add> ); <ide> /** <ide> * @param {string} request imported request <ide> * @param {ConsumeOptions} options options <ide><path>lib/sharing/ProvideSharedPlugin.js <ide> class ProvideSharedPlugin { <ide> /** @type {LazySet<string>} */ <ide> missingDependencies: new LazySet() <ide> }; <del> const resolver = compiler.resolverFactory.get("normal"); <add> const resolver = compiler.resolverFactory.get( <add> "normal", <add> undefined, <add> "esm" <add> ); <ide> resolver.resolve( <ide> {}, <ide> compiler.context,
2
Javascript
Javascript
fix fs.realpath tests so that they actually run
65242abc3bdc249916a22daad289c005a7d93ead
<ide><path>test/simple/test-fs-realpath.js <ide> function bashRealpath(path, callback) { <ide> } <ide> <ide> // sub-tests: <del>function test_simple_error_callback() { <add>function test_simple_error_callback(cb) { <ide> var ncalls = 0; <ide> <ide> fs.realpath('/this/path/does/not/exist', function(err, s) { <ide> assert(err); <ide> assert(!s); <ide> ncalls++; <add> cb(); <ide> }); <ide> <ide> process.on('exit', function() { <ide> assert.equal(upone, uponeActual, <ide> // `-- d -> .. <ide> // realpath(a/b/e/d/a/b/e/d/a) ==> a <ide> function test_up_multiple(cb) { <del> fs.mkdirSync(common.tmpDir + '/a', 0755); <del> fs.mkdirSync(common.tmpDir + '/a/b', 0755); <del> fs.symlinkSync(common.tmpDir + '/a/d', '..'); <del> fs.symlinkSync(common.tmpDir + '/a/b/e', '..'); <add> console.error('test_up_multiple'); <add> fs.mkdirSync(tmp('a'), 0755); <add> fs.mkdirSync(tmp('a/b'), 0755); <add> fs.symlinkSync('..', tmp('a/d'), 'dir'); <add> unlink.push(tmp('a/d')); <add> fs.symlinkSync('..', tmp('a/b/e'), 'dir'); <add> unlink.push(tmp('a/b/e')); <ide> <ide> var abedabed = tmp('abedabed'.split('').join('/')); <del> var abedabeda_real = tmp(''); <add> var abedabed_real = tmp(''); <ide> <ide> var abedabeda = tmp('abedabeda'.split('').join('/')); <ide> var abedabeda_real = tmp('a'); <ide> function test_abs_with_kids(cb) { <ide> } <ide> <ide> function test_lying_cache_liar(cb) { <add> var n = 2; <add> <ide> // this should not require *any* stat calls, since everything <ide> // checked by realpath will be found in the cache. <ide> console.log('test_lying_cache_liar'); <ide> function test_lying_cache_liar(cb) { <ide> assert.equal(cache['/foo/bar/baz/bluff'], rps); <ide> fs.realpath('/1/2/3/4/5/6/7', cache, function(er, rp) { <ide> assert.equal(cache['/1/2/3/4/5/6/7'], rp); <add> if (--n === 0) cb(); <ide> }); <ide> <ide> var test = '/a/b/c/d', <ide> function test_lying_cache_liar(cb) { <ide> assert.equal(expect, actual); <ide> fs.realpath(test, cache, function(er, actual) { <ide> assert.equal(expect, actual); <add> if (--n === 0) cb(); <ide> }); <ide> } <ide> <ide> var tests = [ <ide> test_non_symlinks, <ide> test_escape_cwd, <ide> test_abs_with_kids, <del> test_lying_cache_liar <add> test_lying_cache_liar, <add> test_up_multiple <ide> ]; <ide> var numtests = tests.length; <add>var testsRun = 0; <ide> function runNextTest(err) { <ide> if (err) throw err; <ide> var test = tests.shift(); <del> if (!test) console.log(numtests + <del> ' subtests completed OK for fs.realpath'); <del> else test(runNextTest); <add> if (!test) { <add> return console.log(numtests + <add> ' subtests completed OK for fs.realpath'); <add> } <add> testsRun++; <add> test(runNextTest); <ide> } <add> <ide> getAbsPaths(function(er) { <ide> if (er) throw er; <ide> var tmpDirs = ['cycles', 'cycles/folder']; <ide> getAbsPaths(function(er) { <ide> fs.mkdirSync(t, 0700); <ide> }); <ide> fs.writeFileSync(tmp('cycles/root.js'), "console.error('roooot!');"); <add> console.error('start tests'); <ide> runNextTest(); <ide> }); <ide> <ide> fs.realpath('/', function(err, result) { <ide> <ide> <ide> process.on('exit', function() { <add> assert.equal(numtests, testsRun); <ide> unlink.forEach(function(path) { try {fs.unlinkSync(path);} catch (e) {} }); <ide> assert.equal(async_completed, async_expected); <ide> });
1
PHP
PHP
implement a psr7 routing middleware
637b9948e7030b0dd7a185412c833d6d9af5e279
<ide><path>src/Http/Middleware/RoutingMiddleware.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @since 3.3.0 <add> * @license http://www.opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Http\Middleware; <add> <add>use Cake\Routing\Exception\RedirectException; <add>use Cake\Routing\Router; <add>use Psr\Http\Message\ResponseInterface; <add>use Psr\Http\Message\ServerRequestInterface; <add>use Zend\Diactoros\Response\RedirectResponse; <add> <add>/** <add> * Applies routing rules to the request and creates the controller <add> * instance if possible. <add> */ <add>class RoutingMiddleware <add>{ <add> <add> /** <add> * @param ServerRequestInterface $request The request. <add> * @param ResponseInterface $response The response. <add> * @param callable $next The next middleware to call <add> * @return \Psr\Http\Message\ResponseInterface A response <add> */ <add> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next) <add> { <add> try { <add> $params = (array)$request->getAttribute('params', []); <add> if (empty($params['controller'])) { <add> $path = $request->getUri()->getPath(); <add> $request = $request->withAttribute('params', Router::parse($path, $request->getMethod())); <add> } <add> } catch (RedirectException $e) { <add> return new RedirectResponse( <add> $e->getMessage(), <add> $e->getCode(), <add> $response->getHeaders() <add> ); <add> } <add> return $next($request, $response); <add> } <add>} <ide><path>tests/TestCase/Http/Middleware/RoutingMiddlewareTest.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @since 3.3.0 <add> * @license http://www.opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Test\TestCase\Http\Middleware; <add> <add>use Cake\Http\Middleware\RoutingMiddleware; <add>use Cake\Routing\Router; <add>use Cake\TestSuite\TestCase; <add>use Zend\Diactoros\Request; <add>use Zend\Diactoros\Response; <add>use Zend\Diactoros\ServerRequestFactory; <add> <add>/** <add> * Test for RoutingMiddleware <add> */ <add>class RoutingMiddlewareTest extends TestCase <add>{ <add> /** <add> * Setup method <add> * <add> * @return void <add> */ <add> public function setUp() <add> { <add> parent::setUp(); <add> Router::reload(); <add> Router::connect('/articles', ['controller' => 'Articles', 'action' => 'index']); <add> } <add> <add> /** <add> * Test redirect responses from redirect routes <add> * <add> * @return void <add> */ <add> public function testRedirectResponse() <add> { <add> Router::redirect('/testpath', '/pages'); <add> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/testpath']); <add> $response = new Response(); <add> $next = function ($req, $res) { <add> }; <add> $middleware = new RoutingMiddleware(); <add> $response = $middleware($request, $response, $next); <add> <add> $this->assertEquals(301, $response->getStatusCode()); <add> $this->assertEquals('http://localhost/pages', $response->getHeaderLine('Location')); <add> } <add> <add> /** <add> * Test redirects with additional headers <add> * <add> * @return void <add> */ <add> public function testRedirectResponseWithHeaders() <add> { <add> Router::redirect('/testpath', '/pages'); <add> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/testpath']); <add> $response = new Response('php://memory', 200, ['X-testing' => 'Yes']); <add> $next = function ($req, $res) { <add> }; <add> $middleware = new RoutingMiddleware(); <add> $response = $middleware($request, $response, $next); <add> <add> $this->assertEquals(301, $response->getStatusCode()); <add> $this->assertEquals('http://localhost/pages', $response->getHeaderLine('Location')); <add> $this->assertEquals('Yes', $response->getHeaderLine('X-testing')); <add> } <add> <add> /** <add> * Test that Router sets parameters <add> * <add> * @return void <add> */ <add> public function testRouterSetParams() <add> { <add> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']); <add> $response = new Response(); <add> $next = function ($req, $res) { <add> $expected = [ <add> 'controller' => 'Articles', <add> 'action' => 'index', <add> 'plugin' => null, <add> 'pass' => [] <add> ]; <add> $this->assertEquals($expected, $req->getAttribute('params')); <add> }; <add> $middleware = new RoutingMiddleware(); <add> $middleware($request, $response, $next); <add> } <add> <add> /** <add> * Test that routing is not applied if a controller exists already <add> * <add> * @return void <add> */ <add> public function testRouterNoopOnController() <add> { <add> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']); <add> $request = $request->withAttribute('params', ['controller' => 'Articles']); <add> $response = new Response(); <add> $next = function ($req, $res) { <add> $this->assertEquals(['controller' => 'Articles'], $req->getAttribute('params')); <add> }; <add> $middleware = new RoutingMiddleware(); <add> $middleware($request, $response, $next); <add> } <add> <add> /** <add> * Test missing routes not being caught. <add> * <add> * @expectedException \Cake\Routing\Exception\MissingRouteException <add> */ <add> public function testMissingRouteNotCaught() <add> { <add> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/missing']); <add> $response = new Response(); <add> $next = function ($req, $res) { <add> }; <add> $middleware = new RoutingMiddleware(); <add> $middleware($request, $response, $next); <add> } <add>}
2
Go
Go
add support for identity token with token handler
e896d1d7c4459c4b357efdd780e9fb9dd9bc90e0
<ide><path>api/client/trust.go <ide> func (scs simpleCredentialStore) Basic(u *url.URL) (string, string) { <ide> return scs.auth.Username, scs.auth.Password <ide> } <ide> <add>func (scs simpleCredentialStore) RefreshToken(u *url.URL, service string) string { <add> return scs.auth.IdentityToken <add>} <add> <add>func (scs simpleCredentialStore) SetRefreshToken(*url.URL, string, string) { <add>} <add> <ide> // getNotaryRepository returns a NotaryRepository which stores all the <ide> // information needed to operate on a notary repository. <ide> // It creates a HTTP transport providing authentication support. <ide><path>api/server/router/system/backend.go <ide> type Backend interface { <ide> SystemVersion() types.Version <ide> SubscribeToEvents(since, sinceNano int64, ef filters.Args) ([]events.Message, chan interface{}) <ide> UnsubscribeFromEvents(chan interface{}) <del> AuthenticateToRegistry(authConfig *types.AuthConfig) (string, error) <add> AuthenticateToRegistry(authConfig *types.AuthConfig) (string, string, error) <ide> } <ide><path>api/server/router/system/system_routes.go <ide> func (s *systemRouter) postAuth(ctx context.Context, w http.ResponseWriter, r *h <ide> if err != nil { <ide> return err <ide> } <del> status, err := s.backend.AuthenticateToRegistry(config) <add> status, token, err := s.backend.AuthenticateToRegistry(config) <ide> if err != nil { <ide> return err <ide> } <ide> return httputils.WriteJSON(w, http.StatusOK, &types.AuthResponse{ <del> Status: status, <add> Status: status, <add> IdentityToken: token, <ide> }) <ide> } <ide><path>daemon/daemon.go <ide> func configureVolumes(config *Config, rootUID, rootGID int) (*store.VolumeStore, <ide> } <ide> <ide> // AuthenticateToRegistry checks the validity of credentials in authConfig <del>func (daemon *Daemon) AuthenticateToRegistry(authConfig *types.AuthConfig) (string, error) { <add>func (daemon *Daemon) AuthenticateToRegistry(authConfig *types.AuthConfig) (string, string, error) { <ide> return daemon.RegistryService.Auth(authConfig, dockerversion.DockerUserAgent()) <ide> } <ide> <ide><path>distribution/registry.go <ide> func (dcs dumbCredentialStore) Basic(*url.URL) (string, string) { <ide> return dcs.auth.Username, dcs.auth.Password <ide> } <ide> <add>func (dcs dumbCredentialStore) RefreshToken(*url.URL, string) string { <add> return dcs.auth.IdentityToken <add>} <add> <add>func (dcs dumbCredentialStore) SetRefreshToken(*url.URL, string, string) { <add>} <add> <ide> // NewV2Repository returns a repository (v2 only). It creates a HTTP transport <ide> // providing timeout settings and authentication support, and also verifies the <ide> // remote API version. <ide> func NewV2Repository(ctx context.Context, repoInfo *registry.RepositoryInfo, end <ide> modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, passThruTokenHandler)) <ide> } else { <ide> creds := dumbCredentialStore{auth: authConfig} <del> tokenHandler := auth.NewTokenHandler(authTransport, creds, repoName, actions...) <add> tokenHandlerOptions := auth.TokenHandlerOptions{ <add> Transport: authTransport, <add> Credentials: creds, <add> Scopes: []auth.Scope{ <add> auth.RepositoryScope{ <add> Repository: repoName, <add> Actions: actions, <add> }, <add> }, <add> ClientID: registry.AuthClientID, <add> } <add> tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions) <ide> basicHandler := auth.NewBasicHandler(creds) <ide> modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)) <ide> } <ide><path>registry/auth.go <ide> import ( <ide> registrytypes "github.com/docker/engine-api/types/registry" <ide> ) <ide> <add>const ( <add> // AuthClientID is used the ClientID used for the token server <add> AuthClientID = "docker" <add>) <add> <ide> // loginV1 tries to register/login to the v1 registry server. <del>func loginV1(authConfig *types.AuthConfig, apiEndpoint APIEndpoint, userAgent string) (string, error) { <add>func loginV1(authConfig *types.AuthConfig, apiEndpoint APIEndpoint, userAgent string) (string, string, error) { <ide> registryEndpoint, err := apiEndpoint.ToV1Endpoint(userAgent, nil) <ide> if err != nil { <del> return "", err <add> return "", "", err <ide> } <ide> <ide> serverAddress := registryEndpoint.String() <ide> <ide> logrus.Debugf("attempting v1 login to registry endpoint %s", registryEndpoint) <ide> <ide> if serverAddress == "" { <del> return "", fmt.Errorf("Server Error: Server Address not set.") <add> return "", "", fmt.Errorf("Server Error: Server Address not set.") <ide> } <ide> <ide> loginAgainstOfficialIndex := serverAddress == IndexServer <ide> <ide> req, err := http.NewRequest("GET", serverAddress+"users/", nil) <ide> if err != nil { <del> return "", err <add> return "", "", err <ide> } <ide> req.SetBasicAuth(authConfig.Username, authConfig.Password) <ide> resp, err := registryEndpoint.client.Do(req) <ide> if err != nil { <ide> // fallback when request could not be completed <del> return "", fallbackError{ <add> return "", "", fallbackError{ <ide> err: err, <ide> } <ide> } <ide> defer resp.Body.Close() <ide> body, err := ioutil.ReadAll(resp.Body) <ide> if err != nil { <del> return "", err <add> return "", "", err <ide> } <ide> if resp.StatusCode == http.StatusOK { <del> return "Login Succeeded", nil <add> return "Login Succeeded", "", nil <ide> } else if resp.StatusCode == http.StatusUnauthorized { <ide> if loginAgainstOfficialIndex { <del> return "", fmt.Errorf("Wrong login/password, please try again. Haven't got a Docker ID? Create one at https://hub.docker.com") <add> return "", "", fmt.Errorf("Wrong login/password, please try again. Haven't got a Docker ID? Create one at https://hub.docker.com") <ide> } <del> return "", fmt.Errorf("Wrong login/password, please try again") <add> return "", "", fmt.Errorf("Wrong login/password, please try again") <ide> } else if resp.StatusCode == http.StatusForbidden { <ide> if loginAgainstOfficialIndex { <del> return "", fmt.Errorf("Login: Account is not active. Please check your e-mail for a confirmation link.") <add> return "", "", fmt.Errorf("Login: Account is not active. Please check your e-mail for a confirmation link.") <ide> } <ide> // *TODO: Use registry configuration to determine what this says, if anything? <del> return "", fmt.Errorf("Login: Account is not active. Please see the documentation of the registry %s for instructions how to activate it.", serverAddress) <add> return "", "", fmt.Errorf("Login: Account is not active. Please see the documentation of the registry %s for instructions how to activate it.", serverAddress) <ide> } else if resp.StatusCode == http.StatusInternalServerError { // Issue #14326 <ide> logrus.Errorf("%s returned status code %d. Response Body :\n%s", req.URL.String(), resp.StatusCode, body) <del> return "", fmt.Errorf("Internal Server Error") <del> } else { <del> return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body, <del> resp.StatusCode, resp.Header) <add> return "", "", fmt.Errorf("Internal Server Error") <ide> } <add> return "", "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body, <add> resp.StatusCode, resp.Header) <ide> } <ide> <ide> type loginCredentialStore struct { <ide> func (lcs loginCredentialStore) Basic(*url.URL) (string, string) { <ide> return lcs.authConfig.Username, lcs.authConfig.Password <ide> } <ide> <add>func (lcs loginCredentialStore) RefreshToken(*url.URL, string) string { <add> return lcs.authConfig.IdentityToken <add>} <add> <add>func (lcs loginCredentialStore) SetRefreshToken(u *url.URL, service, token string) { <add> lcs.authConfig.IdentityToken = token <add>} <add> <ide> type fallbackError struct { <ide> err error <ide> } <ide> func (err fallbackError) Error() string { <ide> // loginV2 tries to login to the v2 registry server. The given registry <ide> // endpoint will be pinged to get authorization challenges. These challenges <ide> // will be used to authenticate against the registry to validate credentials. <del>func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent string) (string, error) { <add>func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent string) (string, string, error) { <ide> logrus.Debugf("attempting v2 login to registry endpoint %s", endpoint) <ide> <ide> modifiers := DockerHeaders(userAgent, nil) <ide> func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent strin <ide> if !foundV2 { <ide> err = fallbackError{err: err} <ide> } <del> return "", err <add> return "", "", err <ide> } <ide> <add> credentialAuthConfig := *authConfig <ide> creds := loginCredentialStore{ <del> authConfig: authConfig, <add> authConfig: &credentialAuthConfig, <ide> } <ide> <del> tokenHandler := auth.NewTokenHandler(authTransport, creds, "") <add> tokenHandlerOptions := auth.TokenHandlerOptions{ <add> Transport: authTransport, <add> Credentials: creds, <add> OfflineAccess: true, <add> ClientID: AuthClientID, <add> } <add> tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions) <ide> basicHandler := auth.NewBasicHandler(creds) <ide> modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)) <ide> tr := transport.NewTransport(authTransport, modifiers...) <ide> func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent strin <ide> if !foundV2 { <ide> err = fallbackError{err: err} <ide> } <del> return "", err <add> return "", "", err <ide> } <ide> <ide> resp, err := loginClient.Do(req) <ide> if err != nil { <ide> if !foundV2 { <ide> err = fallbackError{err: err} <ide> } <del> return "", err <add> return "", "", err <ide> } <ide> defer resp.Body.Close() <ide> <ide> func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent strin <ide> if !foundV2 { <ide> err = fallbackError{err: err} <ide> } <del> return "", err <add> return "", "", err <ide> } <ide> <del> return "Login Succeeded", nil <add> return "Login Succeeded", credentialAuthConfig.IdentityToken, nil <ide> <ide> } <ide> <ide><path>registry/service.go <ide> package registry <ide> <ide> import ( <ide> "crypto/tls" <add> "fmt" <ide> "net/http" <ide> "net/url" <ide> "strings" <ide> func NewService(options *Options) *Service { <ide> // Auth contacts the public registry with the provided credentials, <ide> // and returns OK if authentication was successful. <ide> // It can be used to verify the validity of a client's credentials. <del>func (s *Service) Auth(authConfig *types.AuthConfig, userAgent string) (status string, err error) { <del> endpoints, err := s.LookupPushEndpoints(authConfig.ServerAddress) <add>func (s *Service) Auth(authConfig *types.AuthConfig, userAgent string) (status, token string, err error) { <add> serverAddress := authConfig.ServerAddress <add> if !strings.HasPrefix(serverAddress, "https://") && !strings.HasPrefix(serverAddress, "http://") { <add> serverAddress = "https://" + serverAddress <add> } <add> u, err := url.Parse(serverAddress) <add> if err != nil { <add> return "", "", fmt.Errorf("unable to parse server address: %v", err) <add> } <add> <add> endpoints, err := s.LookupPushEndpoints(u.Host) <ide> if err != nil { <del> return "", err <add> return "", "", err <ide> } <ide> <ide> for _, endpoint := range endpoints { <ide> func (s *Service) Auth(authConfig *types.AuthConfig, userAgent string) (status s <ide> login = loginV1 <ide> } <ide> <del> status, err = login(authConfig, endpoint, userAgent) <add> status, token, err = login(authConfig, endpoint, userAgent) <ide> if err == nil { <ide> return <ide> } <ide> func (s *Service) Auth(authConfig *types.AuthConfig, userAgent string) (status s <ide> logrus.Infof("Error logging in to %s endpoint, trying next endpoint: %v", endpoint.Version, err) <ide> continue <ide> } <del> return "", err <add> return "", "", err <ide> } <ide> <del> return "", err <add> return "", "", err <ide> } <ide> <ide> // splitReposSearchTerm breaks a search term into an index name and remote name <ide><path>registry/service_v2.go <ide> import ( <ide> func (s *Service) lookupV2Endpoints(hostname string) (endpoints []APIEndpoint, err error) { <ide> var cfg = tlsconfig.ServerDefault <ide> tlsConfig := &cfg <del> if hostname == DefaultNamespace { <add> if hostname == DefaultNamespace || hostname == DefaultV1Registry.Host { <ide> // v2 mirrors <ide> for _, mirror := range s.Config.Mirrors { <ide> if !strings.HasPrefix(mirror, "http://") && !strings.HasPrefix(mirror, "https://") {
8
Go
Go
add apparmorprofile to container inspect json
fa1484d12c5b66f7db03a9c93002ba3df56cdb4e
<ide><path>daemon/inspect.go <ide> func (daemon *Daemon) ContainerInspect(job *engine.Job) engine.Status { <ide> out.Set("ProcessLabel", container.ProcessLabel) <ide> out.SetJson("Volumes", container.Volumes) <ide> out.SetJson("VolumesRW", container.VolumesRW) <add> out.SetJson("AppArmorProfile", container.AppArmorProfile) <ide> <ide> if children, err := daemon.Children(container.Name); err == nil { <ide> for linkAlias, child := range children {
1
Ruby
Ruby
allow am/pm in datetime selectors
a869382a9fa241f72a7a73d4a9738531c4c37ba5
<ide><path>actionpack/lib/action_view/helpers/date_helper.rb <ide> def select_minute(datetime, options = {}, html_options = {}) <ide> # # generic prompt. <ide> # select_hour(13, :prompt => 'Choose hour') <ide> # <add> # # Generate a select field for hours in the AM/PM format <add> # select_hour(my_time, :ampm => true) <add> # <ide> def select_hour(datetime, options = {}, html_options = {}) <ide> DateTimeSelector.new(datetime, options, html_options).select_hour <ide> end <ide> class DateTimeSelector #:nodoc: <ide> POSITION = { <ide> :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 <ide> }.freeze <add> ampm = ["AM","PM"].map do |s| <add> ["12 #{s}"] + (1..11).map{|x| "#{sprintf('%02d',x)} #{s}"} <add> end.flatten <add> <add> AMPM_TRANSLATION = Hash[ <add> [[0, "12 AM"], [1, "01 AM"], [2, "02 AM"], [3, "03 AM"], <add> [4, "04 AM"], [5, "05 AM"], [6, "06 AM"], [7, "07 AM"], <add> [8, "08 AM"], [9, "09 AM"], [10, "10 AM"], [11, "11 AM"], <add> [12, "12 PM"], [13, "01 PM"], [14, "02 PM"], [15, "03 PM"], <add> [16, "04 PM"], [17, "05 PM"], [18, "06 PM"], [19, "07 PM"], <add> [20, "08 PM"], [21, "09 PM"], [22, "10 PM"], [23, "11 PM"]] <add> ].freeze <ide> <ide> def initialize(datetime, options = {}, html_options = {}) <ide> @options = options.dup <ide> def select_minute <ide> def select_hour <ide> if @options[:use_hidden] || @options[:discard_hour] <ide> build_hidden(:hour, hour) <add> elsif @options[:ampm] <add> build_select(:hour, build_ampm_options(hour, :end => 23)) <ide> else <ide> build_options_and_select(:hour, hour, :end => 23) <ide> end <ide> def build_options_and_select(type, selected, options = {}) <ide> build_select(type, build_options(selected, options)) <ide> end <ide> <add> def build_ampm_options(selected, options = {}) <add> start = options.delete(:start) || 0 <add> stop = options.delete(:end) || 23 <add> step = options.delete(:step) || 1 <add> options.reverse_merge!({:leading_zeros => true}) <add> leading_zeros = options.delete(:leading_zeros) <add> <add> select_options = [] <add> start.step(stop, step) do |i| <add> text = AMPM_TRANSLATION[i] <add> value = leading_zeros ? sprintf("%02d", i) : i <add> tag_options = { :value => value } <add> tag_options[:selected] = "selected" if selected == i <add> select_options << content_tag(:option, text, tag_options) <add> end <add> (select_options.join("\n") + "\n").html_safe <add> end <add> <ide> # Build select option html from date value and options <ide> # build_options(15, :start => 1, :end => 31) <ide> # => "<option value="1">1</option> <ide><path>actionpack/test/template/date_helper_test.rb <ide> def test_select_hour <ide> assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18)) <ide> end <ide> <add> def test_select_hour_with_ampm <add> expected = %(<select id="date_hour" name="date[hour]">\n) <add> expected << %(<option value="00">12 AM</option>\n<option value="01">01 AM</option>\n<option value="02">02 AM</option>\n<option value="03">03 AM</option>\n<option value="04">04 AM</option>\n<option value="05">05 AM</option>\n<option value="06">06 AM</option>\n<option value="07">07 AM</option>\n<option value="08" selected="selected">08 AM</option>\n<option value="09">09 AM</option>\n<option value="10">10 AM</option>\n<option value="11">11 AM</option>\n<option value="12">12 PM</option>\n<option value="13">01 PM</option>\n<option value="14">02 PM</option>\n<option value="15">03 PM</option>\n<option value="16">04 PM</option>\n<option value="17">05 PM</option>\n<option value="18">06 PM</option>\n<option value="19">07 PM</option>\n<option value="20">08 PM</option>\n<option value="21">09 PM</option>\n<option value="22">10 PM</option>\n<option value="23">11 PM</option>\n) <add> expected << "</select>\n" <add> <add> assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :ampm => true) <add> end <add> <ide> def test_select_hour_with_disabled <ide> expected = %(<select id="date_hour" name="date[hour]" disabled="disabled">\n) <ide> expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n) <ide> def test_select_datetime <ide> assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :prefix => "date[first]") <ide> end <ide> <add> def test_select_datetime_with_ampm <add> expected = %(<select id="date_first_year" name="date[first][year]">\n) <add> expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) <add> expected << "</select>\n" <add> <add> expected << %(<select id="date_first_month" name="date[first][month]">\n) <add> expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) <add> expected << "</select>\n" <add> <add> expected << %(<select id="date_first_day" name="date[first][day]">\n) <add> expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) <add> expected << "</select>\n" <add> <add> expected << " &mdash; " <add> <add> expected << %(<select id="date_first_hour" name="date[first][hour]">\n) <add> expected << %(<option value="00">12 AM</option>\n<option value="01">01 AM</option>\n<option value="02">02 AM</option>\n<option value="03">03 AM</option>\n<option value="04">04 AM</option>\n<option value="05">05 AM</option>\n<option value="06">06 AM</option>\n<option value="07">07 AM</option>\n<option value="08" selected="selected">08 AM</option>\n<option value="09">09 AM</option>\n<option value="10">10 AM</option>\n<option value="11">11 AM</option>\n<option value="12">12 PM</option>\n<option value="13">01 PM</option>\n<option value="14">02 PM</option>\n<option value="15">03 PM</option>\n<option value="16">04 PM</option>\n<option value="17">05 PM</option>\n<option value="18">06 PM</option>\n<option value="19">07 PM</option>\n<option value="20">08 PM</option>\n<option value="21">09 PM</option>\n<option value="22">10 PM</option>\n<option value="23">11 PM</option>\n) <add> expected << "</select>\n" <add> <add> expected << " : " <add> <add> expected << %(<select id="date_first_minute" name="date[first][minute]">\n) <add> expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n) <add> expected << "</select>\n" <add> <add> assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :ampm => true) <add> end <add> <add> <ide> def test_select_datetime_with_separators <ide> expected = %(<select id="date_first_year" name="date[first][year]">\n) <ide> expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) <ide> def test_select_time <ide> assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :include_seconds => false) <ide> end <ide> <add> def test_select_time_with_ampm <add> expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) <add> expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n) <add> expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n) <add> <add> expected << %(<select id="date_hour" name="date[hour]">\n) <add> expected << %(<option value="00">12 AM</option>\n<option value="01">01 AM</option>\n<option value="02">02 AM</option>\n<option value="03">03 AM</option>\n<option value="04">04 AM</option>\n<option value="05">05 AM</option>\n<option value="06">06 AM</option>\n<option value="07">07 AM</option>\n<option value="08" selected="selected">08 AM</option>\n<option value="09">09 AM</option>\n<option value="10">10 AM</option>\n<option value="11">11 AM</option>\n<option value="12">12 PM</option>\n<option value="13">01 PM</option>\n<option value="14">02 PM</option>\n<option value="15">03 PM</option>\n<option value="16">04 PM</option>\n<option value="17">05 PM</option>\n<option value="18">06 PM</option>\n<option value="19">07 PM</option>\n<option value="20">08 PM</option>\n<option value="21">09 PM</option>\n<option value="22">10 PM</option>\n<option value="23">11 PM</option>\n) <add> expected << "</select>\n" <add> <add> expected << " : " <add> <add> expected << %(<select id="date_minute" name="date[minute]">\n) <add> expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n) <add> expected << "</select>\n" <add> <add> assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :include_seconds => false, :ampm => true) <add> end <add> <ide> def test_select_time_with_separator <ide> expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) <ide> expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n)
2
Ruby
Ruby
avoid leak into controller's action_methods
14c196e5a3f78ea4672b691a09ba60524b31fb73
<ide><path>actionpack/lib/abstract_controller/layouts.rb <ide> def _write_layout_method # :nodoc: <ide> RUBY <ide> when Proc <ide> define_method :_layout_from_proc, &_layout <add> protected :_layout_from_proc <ide> <<-RUBY <ide> result = _layout_from_proc(#{_layout.arity == 0 ? '' : 'self'}) <ide> return #{default_behavior} if result.nil? <ide><path>actionpack/test/abstract/layouts_test.rb <ide> class Base < AbstractController::Base <ide> include AbstractController::Rendering <ide> include AbstractController::Layouts <ide> <add> abstract! <add> <ide> self.view_paths = [ActionView::FixtureResolver.new( <ide> "layouts/hello.erb" => "With String <%= yield %>", <ide> "layouts/hello_override.erb" => "With Override <%= yield %>", <ide> class TestBase < ActiveSupport::TestCase <ide> assert_equal "Hello nil!", controller.response_body <ide> end <ide> <add> test "when layout is specified as a proc, do not leak any methods into controller's action_methods" do <add> assert_equal Set.new(['index']), WithProc.action_methods <add> end <add> <ide> test "when layout is specified as a proc, call it and use the layout returned" do <ide> controller = WithProc.new <ide> controller.process(:index)
2
Ruby
Ruby
fix false positive api credential error
f15681ccd9ae827551906c51c88bf64dd6634333
<ide><path>Library/Homebrew/utils/github.rb <ide> def api_credentials_error_message(response_headers, needed_scopes) <ide> return if response_headers.empty? <ide> <ide> scopes = response_headers["x-accepted-oauth-scopes"].to_s.split(", ") <del> return if scopes.present? <del> <del> needed_human_scopes = needed_scopes.join(", ") <add> needed_scopes = Set.new(scopes || needed_scopes) <ide> credentials_scopes = response_headers["x-oauth-scopes"] <del> return if needed_human_scopes.blank? && credentials_scopes.blank? <add> return if needed_scopes.subset?(Set.new(credentials_scopes.to_s.split(", "))) <ide> <del> needed_human_scopes = "none" if needed_human_scopes.blank? <add> needed_scopes = needed_scopes.to_a.join(", ").presence || "none" <ide> credentials_scopes = "none" if credentials_scopes.blank? <ide> <ide> what = case api_credentials_type <ide> def api_credentials_error_message(response_headers, needed_scopes) <ide> <ide> @api_credentials_error_message ||= onoe <<~EOS <ide> Your #{what} credentials do not have sufficient scope! <del> Scopes required: #{needed_human_scopes} <add> Scopes required: #{needed_scopes} <ide> Scopes present: #{credentials_scopes} <ide> Create a personal access token: <ide> #{ALL_SCOPES_URL}
1
Text
Text
add release notes for 1.8.2
9b3b6f7f79491de33b0183c2cea2fbe8dc4de06d
<ide><path>CHANGELOG.md <add><a name="1.8.2"></a> <add># 1.8.2 meteoric-mining (2020-10-21) <add> <add>## Bug Fixes <add>- **$sceDelegate:** ensure that `resourceUrlWhitelist()` is identical `trustedResourceUrlList()` <add> ([e41f01](https://github.com/angular/angular.js/commit/e41f018959934bfbf982ba996cd654b1fce88d43), <add> [#17090](https://github.com/angular/angular.js/issues/17090)) <add>- **$sanitize:** do not trigger CSP alert/report in Firefox and Chrome <add> ([2fab3d](https://github.com/angular/angular.js/commit/2fab3d4e00f4fe35bfa3cf255160cb97404baf24)) <add> <add> <ide> <a name="1.8.1"></a> <ide> # 1.8.1 mutually-supporting (2020-09-30) <ide>
1
Mixed
Ruby
replace okjson with ruby's core json
4278ec38e49285fe4ca4cb71878eef738154276c
<ide><path>Library/Homebrew/utils/json.rb <del>require "vendor/okjson" <add>require "json" <ide> <ide> module Utils <ide> module JSON <ide> module JSON <ide> Error = Class.new(StandardError) <ide> <ide> def load(str) <del> Vendor::OkJson.decode(str) <del> rescue Vendor::OkJson::Error => e <add> ::JSON.load(str) <add> rescue ::JSON::ParserError => e <ide> raise Error, e.message <ide> end <ide> <ide> def dump(obj) <del> Vendor::OkJson.encode(stringify_keys(obj)) <add> ::JSON.generate(obj) <ide> end <ide> <ide> def stringify_keys(obj) <ide><path>Library/Homebrew/vendor/README.md <ide> Vendored Dependencies <ide> ===================== <ide> <del>* [okjson](https://github.com/kr/okjson), version 43 <del> <ide> * [plist](https://github.com/bleything/plist), version 3.1.0 <ide> <ide> * [ruby-macho](https://github.com/Homebrew/ruby-macho), version 0.2.6 <ide> <ide> ## Licenses: <ide> <del>### okjson <del> <del>> Copyright 2011, 2012 Keith Rarick <del>> <del>> Permission is hereby granted, free of charge, to any person obtaining a copy <del>> of this software and associated documentation files (the "Software"), to deal <del>> in the Software without restriction, including without limitation the rights <del>> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell <del>> copies of the Software, and to permit persons to whom the Software is <del>> furnished to do so, subject to the following conditions: <del>> <del>> The above copyright notice and this permission notice shall be included in <del>> all copies or substantial portions of the Software. <del>> <del>> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR <del>> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <del>> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE <del>> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER <del>> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, <del>> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <del>> THE SOFTWARE. <del> <ide> ### plist <ide> <ide> > Copyright (c) 2006-2010, Ben Bleything and Patrick May <ide><path>Library/Homebrew/vendor/okjson.rb <del># encoding: UTF-8 <del># <del># Copyright 2011, 2012 Keith Rarick <del># <del># Permission is hereby granted, free of charge, to any person obtaining a copy <del># of this software and associated documentation files (the "Software"), to deal <del># in the Software without restriction, including without limitation the rights <del># to use, copy, modify, merge, publish, distribute, sublicense, and/or sell <del># copies of the Software, and to permit persons to whom the Software is <del># furnished to do so, subject to the following conditions: <del># <del># The above copyright notice and this permission notice shall be included in <del># all copies or substantial portions of the Software. <del># <del># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR <del># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <del># FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE <del># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER <del># LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, <del># OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <del># THE SOFTWARE. <del> <del># See https://github.com/kr/okjson for updates. <del> <del>require 'stringio' <del> <del># Some parts adapted from <del># http://golang.org/src/pkg/json/decode.go and <del># http://golang.org/src/pkg/utf8/utf8.go <del>module Vendor <del> module OkJson <del> Upstream = '43' <del> extend self <del> <del> <del> # Decodes a json document in string s and <del> # returns the corresponding ruby value. <del> # String s must be valid UTF-8. If you have <del> # a string in some other encoding, convert <del> # it first. <del> # <del> # String values in the resulting structure <del> # will be UTF-8. <del> def decode(s) <del> ts = lex(s) <del> v, ts = textparse(ts) <del> if ts.length > 0 <del> raise Error, 'trailing garbage' <del> end <del> v <del> end <del> <del> <del> # Encodes x into a json text. It may contain only <del> # Array, Hash, String, Numeric, true, false, nil. <del> # (Note, this list excludes Symbol.) <del> # X itself must be an Array or a Hash. <del> # No other value can be encoded, and an error will <del> # be raised if x contains any other value, such as <del> # Nan, Infinity, Symbol, and Proc, or if a Hash key <del> # is not a String. <del> # Strings contained in x must be valid UTF-8. <del> def encode(x) <del> case x <del> when Hash then objenc(x) <del> when Array then arrenc(x) <del> else <del> raise Error, 'root value must be an Array or a Hash' <del> end <del> end <del> <del> <del> def valenc(x) <del> case x <del> when Hash then objenc(x) <del> when Array then arrenc(x) <del> when String then strenc(x) <del> when Numeric then numenc(x) <del> when true then "true" <del> when false then "false" <del> when nil then "null" <del> else <del> raise Error, "cannot encode #{x.class}: #{x.inspect}" <del> end <del> end <del> <del> <del> private <del> <del> <del> # Parses a "json text" in the sense of RFC 4627. <del> # Returns the parsed value and any trailing tokens. <del> # Note: this is almost the same as valparse, <del> # except that it does not accept atomic values. <del> def textparse(ts) <del> if ts.length <= 0 <del> raise Error, 'empty' <del> end <del> <del> typ, _, val = ts[0] <del> case typ <del> when '{' then objparse(ts) <del> when '[' then arrparse(ts) <del> else <del> raise Error, "unexpected #{val.inspect}" <del> end <del> end <del> <del> <del> # Parses a "value" in the sense of RFC 4627. <del> # Returns the parsed value and any trailing tokens. <del> def valparse(ts) <del> if ts.length <= 0 <del> raise Error, 'empty' <del> end <del> <del> typ, _, val = ts[0] <del> case typ <del> when '{' then objparse(ts) <del> when '[' then arrparse(ts) <del> when :val,:str then [val, ts[1..-1]] <del> else <del> raise Error, "unexpected #{val.inspect}" <del> end <del> end <del> <del> <del> # Parses an "object" in the sense of RFC 4627. <del> # Returns the parsed value and any trailing tokens. <del> def objparse(ts) <del> ts = eat('{', ts) <del> obj = {} <del> <del> if ts[0][0] == '}' <del> return obj, ts[1..-1] <del> end <del> <del> k, v, ts = pairparse(ts) <del> obj[k] = v <del> <del> if ts[0][0] == '}' <del> return obj, ts[1..-1] <del> end <del> <del> loop do <del> ts = eat(',', ts) <del> <del> k, v, ts = pairparse(ts) <del> obj[k] = v <del> <del> if ts[0][0] == '}' <del> return obj, ts[1..-1] <del> end <del> end <del> end <del> <del> <del> # Parses a "member" in the sense of RFC 4627. <del> # Returns the parsed values and any trailing tokens. <del> def pairparse(ts) <del> (typ, _, k), ts = ts[0], ts[1..-1] <del> if typ != :str <del> raise Error, "unexpected #{k.inspect}" <del> end <del> ts = eat(':', ts) <del> v, ts = valparse(ts) <del> [k, v, ts] <del> end <del> <del> <del> # Parses an "array" in the sense of RFC 4627. <del> # Returns the parsed value and any trailing tokens. <del> def arrparse(ts) <del> ts = eat('[', ts) <del> arr = [] <del> <del> if ts[0][0] == ']' <del> return arr, ts[1..-1] <del> end <del> <del> v, ts = valparse(ts) <del> arr << v <del> <del> if ts[0][0] == ']' <del> return arr, ts[1..-1] <del> end <del> <del> loop do <del> ts = eat(',', ts) <del> <del> v, ts = valparse(ts) <del> arr << v <del> <del> if ts[0][0] == ']' <del> return arr, ts[1..-1] <del> end <del> end <del> end <del> <del> <del> def eat(typ, ts) <del> if ts[0][0] != typ <del> raise Error, "expected #{typ} (got #{ts[0].inspect})" <del> end <del> ts[1..-1] <del> end <del> <del> <del> # Scans s and returns a list of json tokens, <del> # excluding white space (as defined in RFC 4627). <del> def lex(s) <del> ts = [] <del> while s.length > 0 <del> typ, lexeme, val = tok(s) <del> if typ == nil <del> raise Error, "invalid character at #{s[0,10].inspect}" <del> end <del> if typ != :space <del> ts << [typ, lexeme, val] <del> end <del> s = s[lexeme.length..-1] <del> end <del> ts <del> end <del> <del> <del> # Scans the first token in s and <del> # returns a 3-element list, or nil <del> # if s does not begin with a valid token. <del> # <del> # The first list element is one of <del> # '{', '}', ':', ',', '[', ']', <del> # :val, :str, and :space. <del> # <del> # The second element is the lexeme. <del> # <del> # The third element is the value of the <del> # token for :val and :str, otherwise <del> # it is the lexeme. <del> def tok(s) <del> case s[0] <del> when ?{ then ['{', s[0,1], s[0,1]] <del> when ?} then ['}', s[0,1], s[0,1]] <del> when ?: then [':', s[0,1], s[0,1]] <del> when ?, then [',', s[0,1], s[0,1]] <del> when ?[ then ['[', s[0,1], s[0,1]] <del> when ?] then [']', s[0,1], s[0,1]] <del> when ?n then nulltok(s) <del> when ?t then truetok(s) <del> when ?f then falsetok(s) <del> when ?" then strtok(s) <del> when Spc, ?\t, ?\n, ?\r then [:space, s[0,1], s[0,1]] <del> else <del> numtok(s) <del> end <del> end <del> <del> <del> def nulltok(s); s[0,4] == 'null' ? [:val, 'null', nil] : [] end <del> def truetok(s); s[0,4] == 'true' ? [:val, 'true', true] : [] end <del> def falsetok(s); s[0,5] == 'false' ? [:val, 'false', false] : [] end <del> <del> <del> def numtok(s) <del> m = /-?([1-9][0-9]+|[0-9])([.][0-9]+)?([eE][+-]?[0-9]+)?/.match(s) <del> if m && m.begin(0) == 0 <del> if !m[2] && !m[3] <del> [:val, m[0], Integer(m[0])] <del> elsif m[2] <del> [:val, m[0], Float(m[0])] <del> else <del> [:val, m[0], Integer(m[1])*(10**Integer(m[3][1..-1]))] <del> end <del> else <del> [] <del> end <del> end <del> <del> <del> def strtok(s) <del> m = /"([^"\\]|\\["\/\\bfnrt]|\\u[0-9a-fA-F]{4})*"/.match(s) <del> if ! m <del> raise Error, "invalid string literal at #{abbrev(s)}" <del> end <del> [:str, m[0], unquote(m[0])] <del> end <del> <del> <del> def abbrev(s) <del> t = s[0,10] <del> p = t['`'] <del> t = t[0,p] if p <del> t = t + '...' if t.length < s.length <del> '`' + t + '`' <del> end <del> <del> <del> # Converts a quoted json string literal q into a UTF-8-encoded string. <del> # The rules are different than for Ruby, so we cannot use eval. <del> # Unquote will raise an error if q contains control characters. <del> def unquote(q) <del> q = q[1...-1] <del> a = q.dup # allocate a big enough string <del> # In ruby >= 1.9, a[w] is a codepoint, not a byte. <del> if rubydoesenc? <del> a.force_encoding('UTF-8') <del> end <del> r, w = 0, 0 <del> while r < q.length <del> c = q[r] <del> if c == ?\\ <del> r += 1 <del> if r >= q.length <del> raise Error, "string literal ends with a \"\\\": \"#{q}\"" <del> end <del> <del> case q[r] <del> when ?",?\\,?/,?' <del> a[w] = q[r] <del> r += 1 <del> w += 1 <del> when ?b,?f,?n,?r,?t <del> a[w] = Unesc[q[r]] <del> r += 1 <del> w += 1 <del> when ?u <del> r += 1 <del> uchar = begin <del> hexdec4(q[r,4]) <del> rescue RuntimeError => e <del> raise Error, "invalid escape sequence \\u#{q[r,4]}: #{e}" <del> end <del> r += 4 <del> if surrogate? uchar <del> if q.length >= r+6 <del> uchar1 = hexdec4(q[r+2,4]) <del> uchar = subst(uchar, uchar1) <del> if uchar != Ucharerr <del> # A valid pair; consume. <del> r += 6 <del> end <del> end <del> end <del> if rubydoesenc? <del> a[w] = '' << uchar <del> w += 1 <del> else <del> w += ucharenc(a, w, uchar) <del> end <del> else <del> raise Error, "invalid escape char #{q[r]} in \"#{q}\"" <del> end <del> elsif c == ?" || c < Spc <del> raise Error, "invalid character in string literal \"#{q}\"" <del> else <del> # Copy anything else byte-for-byte. <del> # Valid UTF-8 will remain valid UTF-8. <del> # Invalid UTF-8 will remain invalid UTF-8. <del> # In ruby >= 1.9, c is a codepoint, not a byte, <del> # in which case this is still what we want. <del> a[w] = c <del> r += 1 <del> w += 1 <del> end <del> end <del> a[0,w] <del> end <del> <del> <del> # Encodes unicode character u as UTF-8 <del> # bytes in string a at position i. <del> # Returns the number of bytes written. <del> def ucharenc(a, i, u) <del> if u <= Uchar1max <del> a[i] = (u & 0xff).chr <del> 1 <del> elsif u <= Uchar2max <del> a[i+0] = (Utag2 | ((u>>6)&0xff)).chr <del> a[i+1] = (Utagx | (u&Umaskx)).chr <del> 2 <del> elsif u <= Uchar3max <del> a[i+0] = (Utag3 | ((u>>12)&0xff)).chr <del> a[i+1] = (Utagx | ((u>>6)&Umaskx)).chr <del> a[i+2] = (Utagx | (u&Umaskx)).chr <del> 3 <del> else <del> a[i+0] = (Utag4 | ((u>>18)&0xff)).chr <del> a[i+1] = (Utagx | ((u>>12)&Umaskx)).chr <del> a[i+2] = (Utagx | ((u>>6)&Umaskx)).chr <del> a[i+3] = (Utagx | (u&Umaskx)).chr <del> 4 <del> end <del> end <del> <del> <del> def hexdec4(s) <del> if s.length != 4 <del> raise Error, 'short' <del> end <del> (nibble(s[0])<<12) | (nibble(s[1])<<8) | (nibble(s[2])<<4) | nibble(s[3]) <del> end <del> <del> <del> def subst(u1, u2) <del> if Usurr1 <= u1 && u1 < Usurr2 && Usurr2 <= u2 && u2 < Usurr3 <del> return ((u1-Usurr1)<<10) | (u2-Usurr2) + Usurrself <del> end <del> return Ucharerr <del> end <del> <del> <del> def surrogate?(u) <del> Usurr1 <= u && u < Usurr3 <del> end <del> <del> <del> def nibble(c) <del> if ?0 <= c && c <= ?9 then c.ord - ?0.ord <del> elsif ?a <= c && c <= ?z then c.ord - ?a.ord + 10 <del> elsif ?A <= c && c <= ?Z then c.ord - ?A.ord + 10 <del> else <del> raise Error, "invalid hex code #{c}" <del> end <del> end <del> <del> <del> def objenc(x) <del> '{' + x.map{|k,v| keyenc(k) + ':' + valenc(v)}.join(',') + '}' <del> end <del> <del> <del> def arrenc(a) <del> '[' + a.map{|x| valenc(x)}.join(',') + ']' <del> end <del> <del> <del> def keyenc(k) <del> case k <del> when String then strenc(k) <del> else <del> raise Error, "Hash key is not a string: #{k.inspect}" <del> end <del> end <del> <del> <del> def strenc(s) <del> t = StringIO.new <del> t.putc(?") <del> r = 0 <del> <del> while r < s.length <del> case s[r] <del> when ?" then t.print('\\"') <del> when ?\\ then t.print('\\\\') <del> when ?\b then t.print('\\b') <del> when ?\f then t.print('\\f') <del> when ?\n then t.print('\\n') <del> when ?\r then t.print('\\r') <del> when ?\t then t.print('\\t') <del> else <del> c = s[r] <del> # In ruby >= 1.9, s[r] is a codepoint, not a byte. <del> if rubydoesenc? <del> begin <del> # c.ord will raise an error if c is invalid UTF-8 <del> if c.ord < Spc.ord <del> c = "\\u%04x" % [c.ord] <del> end <del> t.write(c) <del> rescue <del> t.write(Ustrerr) <del> end <del> elsif c < Spc <del> t.write("\\u%04x" % c) <del> elsif Spc <= c && c <= ?~ <del> t.putc(c) <del> else <del> n = ucharcopy(t, s, r) # ensure valid UTF-8 output <del> r += n - 1 # r is incremented below <del> end <del> end <del> r += 1 <del> end <del> t.putc(?") <del> t.string <del> end <del> <del> <del> def numenc(x) <del> if ((x.nan? || x.infinite?) rescue false) <del> raise Error, "Numeric cannot be represented: #{x}" <del> end <del> "#{x}" <del> end <del> <del> <del> # Copies the valid UTF-8 bytes of a single character <del> # from string s at position i to I/O object t, and <del> # returns the number of bytes copied. <del> # If no valid UTF-8 char exists at position i, <del> # ucharcopy writes Ustrerr and returns 1. <del> def ucharcopy(t, s, i) <del> n = s.length - i <del> raise Utf8Error if n < 1 <del> <del> c0 = s[i].ord <del> <del> # 1-byte, 7-bit sequence? <del> if c0 < Utagx <del> t.putc(c0) <del> return 1 <del> end <del> <del> raise Utf8Error if c0 < Utag2 # unexpected continuation byte? <del> <del> raise Utf8Error if n < 2 # need continuation byte <del> c1 = s[i+1].ord <del> raise Utf8Error if c1 < Utagx || Utag2 <= c1 <del> <del> # 2-byte, 11-bit sequence? <del> if c0 < Utag3 <del> raise Utf8Error if ((c0&Umask2)<<6 | (c1&Umaskx)) <= Uchar1max <del> t.putc(c0) <del> t.putc(c1) <del> return 2 <del> end <del> <del> # need second continuation byte <del> raise Utf8Error if n < 3 <del> <del> c2 = s[i+2].ord <del> raise Utf8Error if c2 < Utagx || Utag2 <= c2 <del> <del> # 3-byte, 16-bit sequence? <del> if c0 < Utag4 <del> u = (c0&Umask3)<<12 | (c1&Umaskx)<<6 | (c2&Umaskx) <del> raise Utf8Error if u <= Uchar2max <del> t.putc(c0) <del> t.putc(c1) <del> t.putc(c2) <del> return 3 <del> end <del> <del> # need third continuation byte <del> raise Utf8Error if n < 4 <del> c3 = s[i+3].ord <del> raise Utf8Error if c3 < Utagx || Utag2 <= c3 <del> <del> # 4-byte, 21-bit sequence? <del> if c0 < Utag5 <del> u = (c0&Umask4)<<18 | (c1&Umaskx)<<12 | (c2&Umaskx)<<6 | (c3&Umaskx) <del> raise Utf8Error if u <= Uchar3max <del> t.putc(c0) <del> t.putc(c1) <del> t.putc(c2) <del> t.putc(c3) <del> return 4 <del> end <del> <del> raise Utf8Error <del> rescue Utf8Error <del> t.write(Ustrerr) <del> return 1 <del> end <del> <del> <del> def rubydoesenc? <del> ::String.method_defined?(:force_encoding) <del> end <del> <del> <del> class Utf8Error < ::StandardError <del> end <del> <del> <del> class Error < ::StandardError <del> end <del> <del> <del> Utagx = 0b1000_0000 <del> Utag2 = 0b1100_0000 <del> Utag3 = 0b1110_0000 <del> Utag4 = 0b1111_0000 <del> Utag5 = 0b1111_1000 <del> Umaskx = 0b0011_1111 <del> Umask2 = 0b0001_1111 <del> Umask3 = 0b0000_1111 <del> Umask4 = 0b0000_0111 <del> Uchar1max = (1<<7) - 1 <del> Uchar2max = (1<<11) - 1 <del> Uchar3max = (1<<16) - 1 <del> Ucharerr = 0xFFFD # unicode "replacement char" <del> Ustrerr = "\xef\xbf\xbd" # unicode "replacement char" <del> Usurrself = 0x10000 <del> Usurr1 = 0xd800 <del> Usurr2 = 0xdc00 <del> Usurr3 = 0xe000 <del> <del> Spc = ' '[0] <del> Unesc = {?b=>?\b, ?f=>?\f, ?n=>?\n, ?r=>?\r, ?t=>?\t} <del> end <del>end
3
PHP
PHP
fix styleci warnings
0f49665023a17b1c1127fc62fb5abb1ed7d709fd
<ide><path>src/Illuminate/Foundation/PackageAssetLoader.php <ide> private function retrieveAssets(string $key) <ide> <ide> foreach ($this->files->directories($this->vendorPath) as $vendor) { <ide> foreach ($this->files->directories($vendor) as $package) { <del> $config = json_decode($this->files->get($package . '/composer.json'), true); <add> $config = json_decode($this->files->get($package.'/composer.json'), true); <ide> <ide> $assets = array_merge($assets, (array) ($config['extra'][$key] ?? [])); <ide> } <ide><path>tests/Foundation/FoundationPackageAssetsTest.php <ide> class FoundationPackageAssetsTest extends TestCase <ide> { <ide> public function testAssetLoading() <ide> { <del> $assetLoader = new PackageAssetLoader(new Filesystem, __DIR__ . '/fixtures/vendor'); <add> $assetLoader = new PackageAssetLoader(new Filesystem, __DIR__.'/fixtures/vendor'); <ide> <ide> $this->assertEquals($assetLoader->get('providers'), ['foo', 'bar', 'baz']); <ide> }
2
Python
Python
replace assertion with exception
cc034f72eb6137f4c550e911fba67f8a0e1e98fa
<ide><path>src/transformers/models/big_bird/modeling_big_bird.py <ide> def load_tf_weights_trivia_qa(init_vars): <ide> # Load weights from TF model <ide> init_vars = tf.saved_model.load(tf_path).variables if is_trivia_qa else tf.train.list_variables(tf_path) <ide> <del> assert len(init_vars) > 0, "Loaded trained variables cannot be empty." <add> if len(init_vars) <= 0: <add> raise ValueError("Loaded trained variables cannot be empty.") <ide> <ide> pt_names = list(model.state_dict().keys()) <ide> <ide> def forward( <ide> to_seq_length = from_seq_length = seqlen <ide> from_block_size = to_block_size = self.block_size <ide> <del> assert from_seq_length % from_block_size == 0, "Query sided sequence length must be multiple of block size" <del> assert to_seq_length % to_block_size == 0, "Key/Value sided sequence length must be multiple of block size" <add> if from_seq_length % from_block_size != 0: <add> raise ValueError("Query sided sequence length must be multiple of block size") <add> <add> if to_seq_length % to_block_size != 0: <add> raise ValueError("Key/Value sided sequence length must be multiple of block size") <ide> <ide> query_layer = self.transpose_for_scores(self.query(hidden_states)) <ide> key_layer = self.transpose_for_scores(self.key(hidden_states)) <ide> def _bigbird_block_rand_mask( <ide> """ <ide> # using this method when from_seq_length in [1024, 3072, 4096] <ide> <del> assert ( <del> from_seq_length // from_block_size == to_seq_length // to_block_size <del> ), "Error the number of blocks needs to be same!" <add> if from_seq_length // from_block_size != to_seq_length // to_block_size: <add> raise ValueError("Error the number of blocks needs to be same!") <ide> <ide> rand_attn = np.zeros((from_seq_length // from_block_size - 2, num_rand_blocks), dtype=np.int32) <ide> middle_seq = np.arange(1, to_seq_length // to_block_size - 1, dtype=np.int32) <ide> def _bigbird_block_rand_mask_with_head( <ide> """ <ide> # using this method when from_seq_length not in [1024, 3072, 4096] <ide> <del> assert ( <del> from_seq_length // from_block_size == to_seq_length // to_block_size <del> ), "Error the number of blocks needs to be same!" <add> if from_seq_length // from_block_size != to_seq_length // to_block_size: <add> raise ValueError("Error the number of blocks needs to be same!") <ide> <del> assert from_seq_length in plan_from_length, "Error from sequence length not in plan!" <add> if from_seq_length not in plan_from_length: <add> raise ValueError("Error from sequence length not in plan!") <ide> <ide> # Total number of blocks in the mmask <ide> num_blocks = from_seq_length // from_block_size <ide> def forward( <ide> output_attentions, <ide> ) <ide> else: <del> assert ( <del> encoder_hidden_states is None <del> ), "BigBird cannot be used as a decoder when config.attention_type != 'original_full'" <add> if encoder_hidden_states is not None: <add> raise ValueError("BigBird cannot be used as a decoder when config.attention_type != 'original_full'") <ide> self_outputs = self.self( <ide> hidden_states, band_mask, from_mask, to_mask, from_blocked_mask, to_blocked_mask, output_attentions <ide> ) <ide> def __init__(self, config, seed=None): <ide> self.is_decoder = config.is_decoder <ide> self.add_cross_attention = config.add_cross_attention <ide> if self.add_cross_attention: <del> assert self.is_decoder, f"{self} should be used as a decoder model if cross attention is added" <add> if not self.is_decoder: <add> raise TypeError(f"{self} should be used as a decoder model if cross attention is added") <ide> self.crossattention = BigBirdAttention(config) <ide> self.intermediate = BigBirdIntermediate(config) <ide> self.output = BigBirdOutput(config) <ide> def forward( <ide> def create_masks_for_block_sparse_attn(attention_mask: torch.Tensor, block_size: int): <ide> <ide> batch_size, seq_length = attention_mask.size() <del> assert ( <del> seq_length % block_size == 0 <del> ), f"Sequence length must be multiple of block size, but sequence length is {seq_length}, while block size is {block_size}." <add> if seq_length % block_size != 0: <add> raise ValueError( <add> f"Sequence length must be multiple of block size, but sequence length is {seq_length}, while block size is {block_size}." <add> ) <ide> <ide> def create_band_mask_from_inputs(from_blocked_mask, to_blocked_mask): <ide> """ <ide> def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_ <ide> effective_batch_size = input_shape[0] <ide> <ide> # add a dummy token <del> assert self.config.pad_token_id is not None, "The PAD token should be defined for generation" <add> if self.config.pad_token_id is None: <add> raise ValueError("The PAD token should be defined for generation") <ide> attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1) <ide> dummy_token = torch.full( <ide> (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device <ide><path>src/transformers/models/big_bird/modeling_flax_big_bird.py <ide> def __call__( <ide> def create_masks_for_block_sparse_attn(attention_mask, block_size: int): <ide> <ide> batch_size, seq_length = attention_mask.shape <del> assert ( <del> seq_length % block_size == 0 <del> ), f"Sequence length must be multiple of block size, but sequence length is {seq_length}, while block size is {block_size}." <add> if seq_length % block_size != 0: <add> raise ValueError( <add> f"Sequence length must be multiple of block size, but sequence length is {seq_length}, while block size is {block_size}." <add> ) <ide> <ide> def create_band_mask_from_inputs(from_blocked_mask, to_blocked_mask): <ide> """ <ide> def bigbird_block_sparse_attention( <ide> to_seq_len = key_layer.shape[2] <ide> from_block_size = to_block_size = self.config.block_size <ide> <del> assert from_seq_len % from_block_size == 0, "Query sided sequence length must be multiple of block size" <del> assert to_seq_len % to_block_size == 0, "Key/Value sided sequence length must be multiple of block size" <add> if from_seq_len % from_block_size != 0: <add> raise ValueError("Query sided sequence length must be multiple of block size") <add> <add> if to_seq_len % to_block_size != 0: <add> raise ValueError("Key/Value sided sequence length must be multiple of block size") <add> <ide> if from_seq_len // from_block_size != to_seq_len // to_block_size: <ide> raise ValueError("Error the number of blocks needs to be same!") <ide> <ide> def _bigbird_block_rand_mask( <ide> """ <ide> # using this method when from_seq_length in [1024, 3072, 4096] <ide> <del> assert ( <del> from_seq_length // from_block_size == to_seq_length // to_block_size <del> ), "Error the number of blocks needs to be same!" <add> if from_seq_length // from_block_size != to_seq_length // to_block_size: <add> raise ValueError("Error the number of blocks needs to be same!") <ide> <ide> rand_attn = np.zeros((from_seq_length // from_block_size - 2, num_rand_blocks), dtype=np.int32) <ide> middle_seq = np.arange(1, to_seq_length // to_block_size - 1, dtype=np.int32) <ide> def _bigbird_block_rand_mask_with_head( <ide> """ <ide> # using this method when from_seq_length not in [1024, 3072, 4096] <ide> <del> assert ( <del> from_seq_length // from_block_size == to_seq_length // to_block_size <del> ), "Error the number of blocks needs to be same!" <add> if from_seq_length // from_block_size != to_seq_length // to_block_size: <add> raise ValueError("Error the number of blocks needs to be same!") <ide> <del> assert from_seq_length in plan_from_length, "Error from sequence length not in plan!" <add> if from_seq_length not in plan_from_length: <add> raise ValueError("Error from sequence length not in plan!") <ide> <ide> # Total number of blocks in the mmask <ide> num_blocks = from_seq_length // from_block_size <ide><path>src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py <ide> def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start <ide> shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() <ide> shifted_input_ids[:, 0] = decoder_start_token_id <ide> <del> assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined." <add> if pad_token_id is None: <add> raise ValueError("self.model.config.pad_token_id has to be defined.") <ide> # replace possible -100 values in labels by `pad_token_id` <ide> shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) <ide> <ide> def forward( <ide> to_seq_length = from_seq_length = seqlen <ide> from_block_size = to_block_size = self.block_size <ide> <del> assert from_seq_length % from_block_size == 0, "Query sided sequence length must be multiple of block size" <del> assert to_seq_length % to_block_size == 0, "Key/Value sided sequence length must be multiple of block size" <add> if from_seq_length % from_block_size != 0: <add> raise ValueError("Query sided sequence length must be multiple of block size") <add> <add> if to_seq_length % to_block_size != 0: <add> raise ValueError("Key/Value sided sequence length must be multiple of block size") <ide> <ide> query_layer = self.transpose_for_scores(self.query(hidden_states)) <ide> key_layer = self.transpose_for_scores(self.key(hidden_states)) <ide> def _bigbird_block_rand_mask( <ide> """ <ide> # using this method when from_seq_length in [1024, 3072, 4096] <ide> <del> assert ( <del> from_seq_length // from_block_size == to_seq_length // to_block_size <del> ), "Error the number of blocks needs to be same!" <add> if from_seq_length // from_block_size != to_seq_length // to_block_size: <add> raise ValueError("Error the number of blocks needs to be same!") <ide> <ide> rand_attn = np.zeros((from_seq_length // from_block_size - 2, num_rand_blocks), dtype=np.int32) <ide> middle_seq = np.arange(1, to_seq_length // to_block_size - 1, dtype=np.int32) <ide> def _bigbird_block_rand_mask_with_head( <ide> """ <ide> # using this method when from_seq_length not in [1024, 3072, 4096] <ide> <del> assert ( <del> from_seq_length // from_block_size == to_seq_length // to_block_size <del> ), "Error the number of blocks needs to be same!" <add> if from_seq_length // from_block_size != to_seq_length // to_block_size: <add> raise ValueError("Error the number of blocks needs to be same!") <ide> <del> assert from_seq_length in plan_from_length, "Error from sequence length not in plan!" <add> if from_seq_length not in plan_from_length: <add> raise ValueError("Error from sequence length not in plan!") <ide> <ide> # Total number of blocks in the mmask <ide> num_blocks = from_seq_length // from_block_size <ide> def forward( <ide> <ide> # check if head_mask has a correct number of layers specified if desired <ide> if head_mask is not None: <del> assert head_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if head_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> <ide> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> def set_attention_type(self, value: str): <ide> def create_masks_for_block_sparse_attn(attention_mask: torch.Tensor, block_size: int): <ide> <ide> batch_size, seq_length = attention_mask.size() <del> assert ( <del> seq_length % block_size == 0 <del> ), f"Sequence length must be multiple of block size, but sequence length is {seq_length}, while block size is {block_size}." <add> if seq_length % block_size != 0: <add> raise ValueError( <add> f"Sequence length must be multiple of block size, but sequence length is {seq_length}, while block size is {block_size}." <add> ) <ide> <ide> def create_band_mask_from_inputs(from_blocked_mask, to_blocked_mask): <ide> """ <ide> def forward( <ide> # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired <ide> for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]): <ide> if attn_mask is not None: <del> assert attn_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if attn_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide><path>src/transformers/models/blenderbot/modeling_blenderbot.py <ide> def forward( <ide> <ide> # check if head_mask has a correct number of layers specified if desired <ide> if head_mask is not None: <del> assert head_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if head_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> def forward( <ide> # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired <ide> for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]): <ide> if attn_mask is not None: <del> assert attn_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if attn_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide><path>src/transformers/models/blenderbot_small/modeling_blenderbot_small.py <ide> def forward( <ide> <ide> # check if head_mask has a correct number of layers specified if desired <ide> if head_mask is not None: <del> assert head_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if head_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> def forward( <ide> # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired <ide> for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]): <ide> if attn_mask is not None: <del> assert attn_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if attn_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide><path>src/transformers/models/canine/modeling_canine.py <ide> def load_tf_weights_in_canine(model, config, tf_checkpoint_path): <ide> pointer = getattr(pointer, "weight") <ide> elif m_name == "kernel": <ide> array = np.transpose(array) <del> try: <del> assert ( <del> pointer.shape == array.shape <del> ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" <del> except AssertionError as e: <del> e.args += (pointer.shape, array.shape) <del> raise <add> <add> if pointer.shape != array.shape: <add> raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched") <add> <ide> logger.info(f"Initialize PyTorch weight {name}") <ide> pointer.data = torch.from_numpy(array) <ide> return model <ide><path>src/transformers/models/clip/modeling_clip.py <ide> def __init__(self, config): <ide> self.embed_dim = config.hidden_size <ide> self.num_heads = config.num_attention_heads <ide> self.head_dim = self.embed_dim // self.num_heads <del> assert ( <del> self.head_dim * self.num_heads == self.embed_dim <del> ), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})." <add> if self.head_dim * self.num_heads != self.embed_dim: <add> raise ValueError( <add> f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})." <add> ) <ide> self.scale = self.head_dim**-0.5 <ide> self.dropout = config.attention_dropout <ide> <ide><path>src/transformers/models/clip/modeling_flax_clip.py <ide> def setup(self): <ide> self.embed_dim = self.config.hidden_size <ide> self.num_heads = self.config.num_attention_heads <ide> self.head_dim = self.embed_dim // self.num_heads <del> assert ( <del> self.head_dim * self.num_heads == self.embed_dim <del> ), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})." <add> if self.head_dim * self.num_heads != self.embed_dim: <add> raise ValueError( <add> f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})." <add> ) <ide> self.scale = self.head_dim**-0.5 <ide> self.dropout = self.config.attention_dropout <ide> <ide><path>src/transformers/models/convbert/modeling_convbert.py <ide> def __init__(self, config): <ide> self.head_ratio = config.head_ratio <ide> <ide> self.conv_kernel_size = config.conv_kernel_size <del> assert ( <del> config.hidden_size % self.num_attention_heads == 0 <del> ), "hidden_size should be divisible by num_attention_heads" <add> if config.hidden_size % self.num_attention_heads != 0: <add> raise ValueError("hidden_size should be divisible by num_attention_heads") <ide> <ide> self.attention_head_size = config.hidden_size // config.num_attention_heads <ide> self.all_head_size = self.num_attention_heads * self.attention_head_size <ide> def __init__(self, config): <ide> self.is_decoder = config.is_decoder <ide> self.add_cross_attention = config.add_cross_attention <ide> if self.add_cross_attention: <del> assert self.is_decoder, f"{self} should be used as a decoder model if cross attention is added" <add> if not self.is_decoder: <add> raise TypeError(f"{self} should be used as a decoder model if cross attention is added") <ide> self.crossattention = ConvBertAttention(config) <ide> self.intermediate = ConvBertIntermediate(config) <ide> self.output = ConvBertOutput(config) <ide> def forward( <ide> outputs = self_attention_outputs[1:] # add self attentions if we output attention weights <ide> <ide> if self.is_decoder and encoder_hidden_states is not None: <del> assert hasattr( <del> self, "crossattention" <del> ), f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`" <add> if not hasattr(self, "crossattention"): <add> raise AttributeError( <add> f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`" <add> ) <ide> cross_attention_outputs = self.crossattention( <ide> attention_output, <ide> encoder_attention_mask, <ide><path>src/transformers/models/convbert/modeling_tf_convbert.py <ide> def __init__(self, config, **kwargs): <ide> self.num_attention_heads = num_attention_heads <ide> self.conv_kernel_size = config.conv_kernel_size <ide> <del> assert ( <del> config.hidden_size % self.num_attention_heads == 0 <del> ), "hidden_size should be divisible by num_attention_heads" <add> if config.hidden_size % self.num_attention_heads != 0: <add> raise ValueError("hidden_size should be divisible by num_attention_heads") <ide> <ide> self.attention_head_size = config.hidden_size // config.num_attention_heads <ide> self.all_head_size = self.num_attention_heads * self.attention_head_size <ide><path>src/transformers/models/ctrl/modeling_ctrl.py <ide> def forward( <ide> <ide> # Attention mask. <ide> if attention_mask is not None: <del> assert batch_size > 0, "batch_size has to be defined and > 0" <add> if batch_size <= 0: <add> raise ValueError("batch_size has to be defined and > 0") <ide> attention_mask = attention_mask.view(batch_size, -1) <ide> # We create a 3D attention mask from a 2D tensor mask. <ide> # Sizes are [batch_size, 1, 1, to_seq_length] <ide> def forward( <ide> else: <ide> batch_size, sequence_length = inputs_embeds.shape[:2] <ide> <del> assert ( <del> self.config.pad_token_id is not None or batch_size == 1 <del> ), "Cannot handle batch sizes > 1 if no padding token is defined." <add> if self.config.pad_token_id is None and batch_size != 1: <add> raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") <ide> <ide> if self.config.pad_token_id is None: <ide> sequence_lengths = -1 <ide><path>src/transformers/models/ctrl/modeling_tf_ctrl.py <ide> def call( <ide> batch_size, sequence_length = shape_list(input_ids)[:2] <ide> else: <ide> batch_size, sequence_length = shape_list(inputs_embeds)[:2] <del> assert ( <del> self.config.pad_token_id is not None or batch_size == 1 <del> ), "Cannot handle batch sizes > 1 if no padding token is defined." <add> if self.config.pad_token_id is None and batch_size != 1: <add> raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") <ide> <ide> if not tf.is_tensor(sequence_lengths): <ide> in_logits = logits[0:batch_size, sequence_lengths] <ide><path>src/transformers/models/deberta_v2/tokenization_deberta_v2.py <ide> def __init__(self, vocab_file, split_by_punct=False, sp_model_kwargs: Optional[D <ide> self.vocab_file = vocab_file <ide> self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs <ide> spm = sp.SentencePieceProcessor(**self.sp_model_kwargs) <del> assert os.path.exists(vocab_file) <add> if not os.path.exists(vocab_file): <add> raise FileNotFoundError(f"{vocab_file} does not exist!") <ide> spm.load(vocab_file) <ide> bpe_vocab_size = spm.GetPieceSize() <ide> # Token map <ide><path>src/transformers/models/detr/modeling_detr.py <ide> def __init__(self, embedding_dim=64, temperature=10000, normalize=False, scale=N <ide> self.scale = scale <ide> <ide> def forward(self, pixel_values, pixel_mask): <del> assert pixel_mask is not None, "No pixel mask provided" <add> if pixel_mask is None: <add> raise ValueError("No pixel mask provided") <ide> y_embed = pixel_mask.cumsum(1, dtype=torch.float32) <ide> x_embed = pixel_mask.cumsum(2, dtype=torch.float32) <ide> if self.normalize: <ide> def __init__( <ide> self.num_heads = num_heads <ide> self.dropout = dropout <ide> self.head_dim = embed_dim // num_heads <del> assert ( <del> self.head_dim * num_heads == self.embed_dim <del> ), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {num_heads})." <add> if self.head_dim * num_heads != self.embed_dim: <add> raise ValueError( <add> f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {num_heads})." <add> ) <ide> self.scaling = self.head_dim**-0.5 <ide> <ide> self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) <ide> def forward( <ide> # get final feature map and downsampled mask <ide> feature_map, mask = features[-1] <ide> <del> assert mask is not None, "Backbone does not return downsampled pixel mask" <add> if mask is None: <add> raise ValueError("Backbone does not return downsampled pixel mask") <ide> <ide> # Second, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default) <ide> projected_feature_map = self.input_projection(feature_map) <ide> class DetrMaskHeadSmallConv(nn.Module): <ide> def __init__(self, dim, fpn_dims, context_dim): <ide> super().__init__() <ide> <del> assert ( <del> dim % 8 == 0 <del> ), "The hidden_size + number of attention heads must be divisible by 8 as the number of groups in GroupNorm is set to 8" <add> if dim % 8 != 0: <add> raise ValueError( <add> "The hidden_size + number of attention heads must be divisible by 8 as the number of groups in GroupNorm is set to 8" <add> ) <ide> <ide> inter_dims = [dim, context_dim // 2, context_dim // 4, context_dim // 8, context_dim // 16, context_dim // 64] <ide> <ide> def loss_labels(self, outputs, targets, indices, num_boxes): <ide> Classification loss (NLL) targets dicts must contain the key "class_labels" containing a tensor of dim <ide> [nb_target_boxes] <ide> """ <del> assert "logits" in outputs, "No logits were found in the outputs" <add> if "logits" not in outputs: <add> raise KeyError("No logits were found in the outputs") <ide> src_logits = outputs["logits"] <ide> <ide> idx = self._get_src_permutation_idx(indices) <ide> def loss_boxes(self, outputs, targets, indices, num_boxes): <ide> Targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]. The target boxes <ide> are expected in format (center_x, center_y, w, h), normalized by the image size. <ide> """ <del> assert "pred_boxes" in outputs, "No predicted boxes found in outputs" <add> if "pred_boxes" not in outputs: <add> raise KeyError("No predicted boxes found in outputs") <ide> idx = self._get_src_permutation_idx(indices) <ide> src_boxes = outputs["pred_boxes"][idx] <ide> target_boxes = torch.cat([t["boxes"][i] for t, (_, i) in zip(targets, indices)], dim=0) <ide> def loss_masks(self, outputs, targets, indices, num_boxes): <ide> <ide> Targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]. <ide> """ <del> assert "pred_masks" in outputs, "No predicted masks found in outputs" <add> if "pred_masks" not in outputs: <add> raise KeyError("No predicted masks found in outputs") <ide> <ide> src_idx = self._get_src_permutation_idx(indices) <ide> tgt_idx = self._get_tgt_permutation_idx(indices) <ide> def get_loss(self, loss, outputs, targets, indices, num_boxes): <ide> "boxes": self.loss_boxes, <ide> "masks": self.loss_masks, <ide> } <del> assert loss in loss_map, f"Loss {loss} not supported" <add> if loss not in loss_map: <add> raise ValueError(f"Loss {loss} not supported") <ide> return loss_map[loss](outputs, targets, indices, num_boxes) <ide> <ide> def forward(self, outputs, targets): <ide> def __init__(self, class_cost: float = 1, bbox_cost: float = 1, giou_cost: float <ide> self.class_cost = class_cost <ide> self.bbox_cost = bbox_cost <ide> self.giou_cost = giou_cost <del> assert class_cost != 0 or bbox_cost != 0 or giou_cost != 0, "All costs of the Matcher can't be 0" <add> if class_cost == 0 or bbox_cost == 0 or giou_cost == 0: <add> raise ValueError("All costs of the Matcher can't be 0") <ide> <ide> @torch.no_grad() <ide> def forward(self, outputs, targets): <ide><path>src/transformers/models/dpr/modeling_dpr.py <ide> class DPREncoder(DPRPreTrainedModel): <ide> def __init__(self, config: DPRConfig): <ide> super().__init__(config) <ide> self.bert_model = BertModel(config, add_pooling_layer=False) <del> assert self.bert_model.config.hidden_size > 0, "Encoder hidden_size can't be zero" <add> if self.bert_model.config.hidden_size <= 0: <add> raise ValueError("Encoder hidden_size can't be zero") <ide> self.projection_dim = config.projection_dim <ide> if self.projection_dim > 0: <ide> self.encode_proj = nn.Linear(self.bert_model.config.hidden_size, config.projection_dim) <ide><path>src/transformers/models/dpr/modeling_tf_dpr.py <ide> def __init__(self, config: DPRConfig, **kwargs): <ide> self.bert_model = TFBertMainLayer(config, add_pooling_layer=False, name="bert_model") <ide> self.config = config <ide> <del> assert self.config.hidden_size > 0, "Encoder hidden_size can't be zero" <add> if self.config.hidden_size <= 0: <add> raise ValueError("Encoder hidden_size can't be zero") <ide> self.projection_dim = config.projection_dim <ide> if self.projection_dim > 0: <ide> self.encode_proj = tf.keras.layers.Dense( <ide><path>src/transformers/models/dpr/tokenization_dpr.py <ide> def __call__( <ide> texts = texts if not isinstance(texts, str) else [texts] <ide> n_passages = len(titles) <ide> questions = questions if not isinstance(questions, str) else [questions] * n_passages <del> assert len(titles) == len( <del> texts <del> ), f"There should be as many titles than texts but got {len(titles)} titles and {len(texts)} texts." <add> if len(titles) != len(texts): <add> raise ValueError( <add> f"There should be as many titles than texts but got {len(titles)} titles and {len(texts)} texts." <add> ) <ide> encoded_question_and_titles = super().__call__(questions, titles, padding=False, truncation=False)["input_ids"] <ide> encoded_texts = super().__call__(texts, add_special_tokens=False, padding=False, truncation=False)["input_ids"] <ide> encoded_inputs = { <ide> def _get_best_spans( <ide> scores = sorted(scores, key=lambda x: x[1], reverse=True) <ide> chosen_span_intervals = [] <ide> for (start_index, end_index), score in scores: <del> assert start_index <= end_index, f"Wrong span indices: [{start_index}:{end_index}]" <add> if start_index > end_index: <add> raise ValueError(f"Wrong span indices: [{start_index}:{end_index}]") <ide> length = end_index - start_index + 1 <del> assert length <= max_answer_length, f"Span is too long: {length} > {max_answer_length}" <add> if length > max_answer_length: <add> raise ValueError(f"Span is too long: {length} > {max_answer_length}") <ide> if any( <ide> [ <ide> start_index <= prev_start_index <= prev_end_index <= end_index <ide><path>src/transformers/models/gpt_neo/modeling_gpt_neo.py <ide> def load_tf_weights_in_gpt_neo(model, config, gpt_neo_checkpoint_path): <ide> # if vocab is padded, then trim off the padding embeddings <ide> array = array[: config.vocab_size] <ide> <del> try: <del> assert ( <del> pointer.shape == array.shape <del> ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched {name}" <del> except AssertionError as e: <del> e.args += (pointer.shape, array.shape) <del> raise <add> if pointer.shape != array.shape: <add> raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched {name}") <add> <ide> print(f"Initialize PyTorch weight {name}") <ide> pointer.data = torch.from_numpy(array) <ide> <ide> def forward( <ide> <ide> # Attention mask. <ide> if attention_mask is not None: <del> assert batch_size > 0, "batch_size has to be defined and > 0" <add> if batch_size <= 0: <add> raise ValueError("batch_size has to be defined and > 0") <ide> attention_mask = attention_mask.view(batch_size, -1) <ide> # We create a 3D attention mask from a 2D tensor mask. <ide> # Sizes are [batch_size, 1, 1, to_seq_length] <ide> def forward( <ide> else: <ide> batch_size, sequence_length = inputs_embeds.shape[:2] <ide> <del> assert ( <del> self.config.pad_token_id is not None or batch_size == 1 <del> ), "Cannot handle batch sizes > 1 if no padding token is defined." <add> if self.config.pad_token_id is None and batch_size != 1: <add> raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") <ide> if self.config.pad_token_id is None: <ide> sequence_lengths = -1 <ide> else: <ide><path>src/transformers/models/gptj/modeling_gptj.py <ide> def forward( <ide> <ide> # Attention mask. <ide> if attention_mask is not None: <del> assert batch_size > 0, "batch_size has to be defined and > 0" <add> if batch_size <= 0: <add> raise ValueError("batch_size has to be defined and > 0") <ide> attention_mask = attention_mask.view(batch_size, -1) <ide> # We create a 3D attention mask from a 2D tensor mask. <ide> # Sizes are [batch_size, 1, 1, to_seq_length] <ide> def forward( <ide> else: <ide> batch_size = inputs_embeds.shape[0] <ide> <del> assert ( <del> self.config.pad_token_id is not None or batch_size == 1 <del> ), "Cannot handle batch sizes > 1 if no padding token is defined." <add> if self.config.pad_token_id is None and batch_size != 1: <add> raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") <ide> if self.config.pad_token_id is None: <ide> sequence_lengths = -1 <ide> else: <ide><path>src/transformers/models/gptj/modeling_tf_gptj.py <ide> def call( <ide> loss = None <ide> <ide> if labels is not None: <del> assert ( <del> self.config.pad_token_id is not None or logits_shape[0] == 1 <del> ), "Cannot handle batch sizes > 1 if no padding token is defined." <add> if self.config.pad_token_id is None and logits_shape[0] != 1: <add> raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") <ide> <ide> if not tf.is_tensor(sequence_lengths): <ide> in_logits = logits[0 : logits_shape[0], sequence_lengths] <ide><path>src/transformers/models/ibert/modeling_ibert.py <ide> def __init__(self, config): <ide> <ide> self.dropout = nn.Dropout(config.attention_probs_dropout_prob) <ide> self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") <del> assert ( <del> self.position_embedding_type == "absolute" <del> ), "I-BERT only supports 'absolute' for `config.position_embedding_type`" <add> if self.position_embedding_type != "absolute": <add> raise ValueError("I-BERT only supports 'absolute' for `config.position_embedding_type`") <ide> <ide> self.softmax = IntSoftmax(self.act_bit, quant_mode=self.quant_mode, force_dequant=config.force_dequant) <ide> <ide> def __init__(self, config): <ide> quant_mode=self.quant_mode, <ide> per_channel=True, <ide> ) <del> assert config.hidden_act == "gelu", "I-BERT only supports 'gelu' for `config.hidden_act`" <add> if config.hidden_act != "gelu": <add> raise ValueError("I-BERT only supports 'gelu' for `config.hidden_act`") <ide> self.intermediate_act_fn = IntGELU(quant_mode=self.quant_mode, force_dequant=config.force_dequant) <ide> self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode) <ide> <ide><path>src/transformers/models/led/modeling_led.py <ide> def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start <ide> shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() <ide> shifted_input_ids[:, 0] = decoder_start_token_id <ide> <del> assert pad_token_id is not None, "config.pad_token_id has to be defined." <add> if pad_token_id is None: <add> raise ValueError("config.pad_token_id has to be defined.") <ide> # replace possible -100 values in labels by `pad_token_id` <ide> shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) <ide> <ide> def __init__( <ide> self.num_heads = num_heads <ide> self.dropout = dropout <ide> self.head_dim = embed_dim // num_heads <del> assert ( <del> self.head_dim * num_heads == self.embed_dim <del> ), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {num_heads})." <add> if self.head_dim * num_heads != self.embed_dim: <add> raise ValueError( <add> f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {num_heads})." <add> ) <ide> self.scaling = self.head_dim**-0.5 <ide> self.is_decoder = is_decoder <ide> <ide> def forward( <ide> src_len = key_states.size(1) <ide> attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) <ide> <del> assert attn_weights.size() == ( <del> bsz * self.num_heads, <del> tgt_len, <del> src_len, <del> ), f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}" <add> if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len): <add> raise ValueError( <add> f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}" <add> ) <ide> <ide> if attention_mask is not None: <del> assert attention_mask.size() == ( <del> bsz, <del> 1, <del> tgt_len, <del> src_len, <del> ), f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" <add> if attention_mask.size() != (bsz, 1, tgt_len, src_len): <add> raise ValueError( <add> f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" <add> ) <ide> attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask <ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) <ide> <ide> attn_weights = nn.functional.softmax(attn_weights, dim=-1) <ide> if layer_head_mask is not None: <del> assert layer_head_mask.size() == ( <del> self.num_heads, <del> ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}" <add> if layer_head_mask.size() != (self.num_heads,): <add> raise ValueError( <add> f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}" <add> ) <ide> attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) <ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) <ide> <ide> def forward( <ide> <ide> attn_output = torch.bmm(attn_probs, value_states) <ide> <del> assert attn_output.size() == ( <del> bsz * self.num_heads, <del> tgt_len, <del> self.head_dim, <del> ), f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}" <add> if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim): <add> raise ValueError( <add> f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}" <add> ) <ide> <ide> attn_output = ( <ide> attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) <ide> def __init__(self, config: LEDConfig, embed_tokens: Optional[nn.Embedding] = Non <ide> self.max_source_positions = config.max_encoder_position_embeddings <ide> <ide> if isinstance(config.attention_window, int): <del> assert config.attention_window % 2 == 0, "`config.attention_window` has to be an even value" <del> assert config.attention_window > 0, "`config.attention_window` has to be positive" <add> if config.attention_window % 2 != 0: <add> raise ValueError("`config.attention_window` has to be an even value") <add> if config.attention_window <= 0: <add> raise ValueError("`config.attention_window` has to be positive") <ide> config.attention_window = [config.attention_window] * config.num_hidden_layers # one value per layer <ide> else: <del> assert len(config.attention_window) == config.num_hidden_layers, ( <del> "`len(config.attention_window)` should equal `config.num_hidden_layers`. " <del> f"Expected {config.num_hidden_layers}, given {len(config.attention_window)}" <del> ) <add> if len(config.attention_window) != config.num_hidden_layers: <add> raise ValueError( <add> "`len(config.attention_window)` should equal `config.num_hidden_layers`. " <add> f"Expected {config.num_hidden_layers}, given {len(config.attention_window)}" <add> ) <ide> <ide> if embed_tokens is not None: <ide> self.embed_tokens = embed_tokens <ide> def _pad_to_window_size( <ide> else max(self.config.attention_window) <ide> ) <ide> <del> assert attention_window % 2 == 0, f"`attention_window` should be an even value. Given {attention_window}" <add> if attention_window % 2 != 0: <add> raise ValueError(f"`attention_window` should be an even value. Given {attention_window}") <ide> input_shape = input_ids.shape if input_ids is not None else inputs_embeds.shape <ide> batch_size, seq_len = input_shape[:2] <ide> <ide> def forward( <ide> <ide> # check if head_mask has a correct number of layers specified if desired <ide> if head_mask is not None: <del> assert head_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if head_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> def forward( <ide> # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired <ide> for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]): <ide> if attn_mask is not None: <del> assert attn_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if attn_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide><path>src/transformers/models/m2m_100/modeling_m2m_100.py <ide> def forward( <ide> <ide> # check if head_mask has a correct number of layers specified if desired <ide> if head_mask is not None: <del> assert head_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if head_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> def forward( <ide> # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired <ide> for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]): <ide> if attn_mask is not None: <del> assert attn_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if attn_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide><path>src/transformers/models/m2m_100/tokenization_m2m_100.py <ide> def __setstate__(self, d: Dict) -> None: <ide> <ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: <ide> save_dir = Path(save_directory) <del> assert save_dir.is_dir(), f"{save_directory} should be a directory" <add> if not save_dir.is_dir(): <add> raise OSError(f"{save_directory} should be a directory") <ide> vocab_save_path = save_dir / ( <ide> (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] <ide> ) <ide><path>src/transformers/models/maskformer/modeling_maskformer.py <ide> def __init__( <ide> self.num_heads = num_heads <ide> self.dropout = dropout <ide> self.head_dim = embed_dim // num_heads <del> assert ( <del> self.head_dim * num_heads == self.embed_dim <del> ), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {num_heads})." <add> if self.head_dim * num_heads != self.embed_dim: <add> raise ValueError( <add> f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {num_heads})." <add> ) <ide> self.scaling = self.head_dim**-0.5 <ide> <ide> self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) <ide><path>src/transformers/models/mbart/modeling_flax_mbart.py <ide> def shift_tokens_right(input_ids: jnp.ndarray, pad_token_id: int) -> jnp.ndarray <ide> """ <ide> prev_output_tokens = np.array(input_ids).copy() <ide> <del> assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined." <add> if pad_token_id is None: <add> raise ValueError("self.model.config.pad_token_id has to be defined.") <ide> <ide> # replace possible -100 values in labels by `pad_token_id` <ide> prev_output_tokens = np.where(prev_output_tokens == -100, pad_token_id, input_ids) <ide><path>src/transformers/models/mbart/modeling_mbart.py <ide> def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int): <ide> """ <ide> prev_output_tokens = input_ids.clone() <ide> <del> assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined." <add> if pad_token_id is None: <add> raise ValueError("self.model.config.pad_token_id has to be defined.") <ide> # replace possible -100 values in labels by `pad_token_id` <ide> prev_output_tokens.masked_fill_(prev_output_tokens == -100, pad_token_id) <ide> <ide> def forward( <ide> <ide> # check if head_mask has a correct number of layers specified if desired <ide> if head_mask is not None: <del> assert head_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if head_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> def forward( <ide> # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired <ide> for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]): <ide> if attn_mask is not None: <del> assert attn_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if attn_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide><path>src/transformers/models/mbart/modeling_tf_mbart.py <ide> def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int): <ide> Shift input ids one token to the right, and wrap the last non pad token (the <LID> token) Note that MBart does not <ide> have a single `decoder_start_token_id` in contrast to other Bart-like models. <ide> """ <del> assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined." <add> if pad_token_id is None: <add> raise ValueError("self.model.config.pad_token_id has to be defined.") <ide> # replace possible -100 values in labels by `pad_token_id` <ide> input_ids = tf.where(input_ids == -100, tf.fill(shape_list(input_ids), pad_token_id), input_ids) <ide> language_id_index = ( <ide><path>src/transformers/models/megatron_bert/modeling_megatron_bert.py <ide> def load_tf_weights_in_megatron_bert(model, config, tf_checkpoint_path): <ide> pointer = getattr(pointer, "weight") <ide> elif m_name == "kernel": <ide> array = np.transpose(array) <del> try: <del> assert ( <del> pointer.shape == array.shape <del> ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" <del> except AssertionError as e: <del> e.args += (pointer.shape, array.shape) <del> raise <add> if pointer.shape != array.shape: <add> raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched") <ide> logger.info("Initialize PyTorch weight {}".format(name)) <ide> pointer.data = torch.from_numpy(array) <ide> return model <ide> def __init__(self, config): <ide> self.is_decoder = config.is_decoder <ide> self.add_cross_attention = config.add_cross_attention <ide> if self.add_cross_attention: <del> assert self.is_decoder, f"{self} should be used as a decoder model if cross attention is added" <add> if not self.is_decoder: <add> raise TypeError(f"{self} should be used as a decoder model if cross attention is added") <ide> self.crossattention = MegatronBertAttention(config) <ide> self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) <ide> self.intermediate = MegatronBertIntermediate(config) <ide> def forward( <ide> <ide> cross_attn_present_key_value = None <ide> if self.is_decoder and encoder_hidden_states is not None: <del> assert hasattr( <del> self, "crossattention" <del> ), f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`" <add> if not hasattr(self, "crossattention"): <add> raise AttributeError( <add> f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`" <add> ) <ide> <ide> # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple <ide> cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None <ide> def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_ <ide> effective_batch_size = input_shape[0] <ide> <ide> # add a dummy token <del> assert self.config.pad_token_id is not None, "The PAD token should be defined for generation" <add> if self.config.pad_token_id is None: <add> raise ValueError("The PAD token should be defined for generation") <ide> attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1) <ide> dummy_token = torch.full( <ide> (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device <ide><path>src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py <ide> def convert_megatron_checkpoint(args, input_state_dict, config): <ide> pos_embeddings = embeddings["position_embeddings"]["weight"] <ide> # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] <ide> n_positions = pos_embeddings.size(0) <del> assert ( <del> n_positions == config.n_positions <del> ), f"pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don't match" <add> if n_positions != config.n_positions: <add> raise ValueError( <add> f"pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don't match" <add> ) <ide> # Store the position embeddings. <ide> output_state_dict["transformer.wpe.weight"] = pos_embeddings <ide> <ide><path>src/transformers/models/pegasus/modeling_pegasus.py <ide> def forward( <ide> <ide> # check if head_mask has a correct number of layers specified if desired <ide> if head_mask is not None: <del> assert head_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if head_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> def forward( <ide> # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired <ide> for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]): <ide> if attn_mask is not None: <del> assert attn_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if attn_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide><path>src/transformers/models/pegasus/tokenization_pegasus.py <ide> def __init__( <ide> ) -> None: <ide> self.offset = offset <ide> if additional_special_tokens is not None: <del> assert isinstance( <del> additional_special_tokens, list <del> ), f"additional_special_tokens should be of type {type(list)}, but is {type(additional_special_tokens)}" <add> if not isinstance(additional_special_tokens, list): <add> raise TypeError( <add> f"additional_special_tokens should be of type {type(list)}, but is {type(additional_special_tokens)}" <add> ) <ide> <ide> additional_special_tokens_extended = ( <ide> ([mask_token_sent] + additional_special_tokens) <ide><path>src/transformers/models/pegasus/tokenization_pegasus_fast.py <ide> def __init__( <ide> self.offset = offset <ide> <ide> if additional_special_tokens is not None: <del> assert isinstance( <del> additional_special_tokens, list <del> ), f"additional_special_tokens should be of type {type(list)}, but is {type(additional_special_tokens)}" <add> if not isinstance(additional_special_tokens, list): <add> raise TypeError( <add> f"additional_special_tokens should be of type {type(list)}, but is {type(additional_special_tokens)}" <add> ) <ide> <ide> additional_special_tokens_extended = ( <ide> ([mask_token_sent] + additional_special_tokens) <ide> def _special_token_mask(self, seq): <ide> all_special_ids = set(self.all_special_ids) # call it once instead of inside list comp <ide> all_special_ids.remove(self.unk_token_id) # <unk> is only sometimes special <ide> <del> assert all_special_ids == set( <del> range(len(self.additional_special_tokens) + 3) <del> ), f"There should be 3 special tokens: mask_token, pad_token, and eos_token + {len(self.additional_special_tokens)} additional_special_tokens, but got {all_special_ids}" <add> if all_special_ids != set(range(len(self.additional_special_tokens) + 3)): <add> raise ValueError( <add> f"There should be 3 special tokens: mask_token, pad_token, and eos_token + {len(self.additional_special_tokens)} additional_special_tokens, but got {all_special_ids}" <add> ) <ide> <ide> return [1 if x in all_special_ids else 0 for x in seq] <ide> <ide><path>src/transformers/models/plbart/modeling_plbart.py <ide> def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int): <ide> """ <ide> prev_output_tokens = input_ids.clone() <ide> <del> assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined." <add> if pad_token_id is None: <add> raise ValueError("self.model.config.pad_token_id has to be defined.") <ide> # replace possible -100 values in labels by `pad_token_id` <ide> prev_output_tokens.masked_fill_(prev_output_tokens == -100, pad_token_id) <ide> <ide><path>src/transformers/models/unispeech/modeling_unispeech.py <ide> def __init__(self, config): <ide> self.num_groups = config.num_codevector_groups <ide> self.num_vars = config.num_codevectors_per_group <ide> <del> assert ( <del> config.codevector_dim % self.num_groups == 0 <del> ), f"`config.codevector_dim {config.codevector_dim} must be divisible by `config.num_codevector_groups` {self.num_groups} for concatenation" <add> if config.codevector_dim % self.num_groups != 0: <add> raise ValueError( <add> f"`config.codevector_dim {config.codevector_dim} must be divisible by `config.num_codevector_groups` {self.num_groups} for concatenation" <add> ) <ide> <ide> # storage for codebook variables (codewords) <ide> self.codevectors = nn.Parameter( <ide><path>src/transformers/models/unispeech_sat/convert_unispeech_sat_original_pytorch_checkpoint_to_pytorch.py <ide> def set_recursively(hf_pointer, key, value, full_name, weight_type): <ide> else: <ide> hf_shape = hf_pointer.shape <ide> <del> assert ( <del> hf_shape == value.shape <del> ), f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be {value.shape} for {full_name}" <add> if hf_shape != value.shape: <add> raise ValueError( <add> f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be {value.shape} for {full_name}" <add> ) <ide> <ide> if weight_type == "weight": <ide> hf_pointer.weight.data = value <ide> def load_conv_layer(full_name, value, feature_extractor, unused_weights, use_gro <ide> <ide> if type_id == 0: <ide> if "bias" in name: <del> assert ( <del> value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape <del> ), f"{full_name} has size {value.shape}, but {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." <add> if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: <add> raise ValueError( <add> f"{full_name} has size {value.shape}, but {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." <add> ) <ide> feature_extractor.conv_layers[layer_id].conv.bias.data = value <ide> logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.") <ide> elif "weight" in name: <del> assert ( <del> value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape <del> ), f"{full_name} has size {value.shape}, but {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." <add> if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: <add> raise ValueError( <add> f"{full_name} has size {value.shape}, but {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." <add> ) <ide> feature_extractor.conv_layers[layer_id].conv.weight.data = value <ide> logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.") <ide> elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): <ide> if "bias" in name: <del> assert ( <del> value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape <del> ), f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was found." <add> if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: <add> raise ValueError( <add> f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was found." <add> ) <ide> feature_extractor.conv_layers[layer_id].layer_norm.bias.data = value <ide> logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.") <ide> elif "weight" in name: <del> assert ( <del> value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape <del> ), f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." <add> if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: <add> raise ValueError( <add> f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." <add> ) <ide> feature_extractor.conv_layers[layer_id].layer_norm.weight.data = value <ide> logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.") <ide> else: <ide><path>src/transformers/models/unispeech_sat/modeling_unispeech_sat.py <ide> def __init__(self, config): <ide> self.num_groups = config.num_codevector_groups <ide> self.num_vars = config.num_codevectors_per_group <ide> <del> assert ( <del> config.codevector_dim % self.num_groups == 0 <del> ), f"`config.codevector_dim {config.codevector_dim} must be divisible by `config.num_codevector_groups` {self.num_groups} for concatenation" <add> if config.codevector_dim % self.num_groups != 0: <add> raise ValueError( <add> f"`config.codevector_dim {config.codevector_dim} must be divisible by `config.num_codevector_groups` {self.num_groups} for concatenation" <add> ) <ide> <ide> # storage for codebook variables (codewords) <ide> self.codevectors = nn.Parameter( <ide><path>src/transformers/models/van/convert_van_to_pytorch.py <ide> def convert_weight_and_push( <ide> module_transfer(x) <ide> our_model = copy_parameters(from_model, our_model) <ide> <del> assert torch.allclose(from_model(x), our_model(x).logits), "The model logits don't match the original one." <add> if not torch.allclose(from_model(x), our_model(x).logits): <add> raise ValueError("The model logits don't match the original one.") <ide> <ide> checkpoint_name = name <ide> print(checkpoint_name) <ide><path>src/transformers/models/xglm/modeling_xglm.py <ide> def forward( <ide> # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired <ide> for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]): <ide> if attn_mask is not None: <del> assert attn_mask.size()[0] == ( <del> len(self.layers) <del> ), f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> if attn_mask.size()[0] != len(self.layers): <add> raise ValueError( <add> f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> ) <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide><path>src/transformers/models/xlm/modeling_tf_xlm.py <ide> def __init__(self, config, **kwargs): <ide> self.n_layers = config.n_layers <ide> self.max_position_embeddings = config.max_position_embeddings <ide> self.embed_init_std = config.embed_init_std <del> assert self.dim % self.n_heads == 0, "transformer dim must be a multiple of n_heads" <add> if self.dim % self.n_heads != 0: <add> raise ValueError("transformer dim must be a multiple of n_heads") <ide> <ide> # embeddings <ide> self.dropout = tf.keras.layers.Dropout(config.dropout)
40
Javascript
Javascript
update underscore to 1.2.2
90d069b3f1a8df9fb77a8d5c0b3c2d35edc7ba27
<ide><path>vendor/underscore.js <del>// Underscore.js 1.1.7 <add>// Underscore.js 1.2.2 <ide> // (c) 2011 Jeremy Ashkenas, DocumentCloud Inc. <ide> // Underscore is freely distributable under the MIT license. <ide> // Portions of Underscore are inspired or borrowed from Prototype, <ide> // Create a safe reference to the Underscore object for use below. <ide> var _ = function(obj) { return new wrapper(obj); }; <ide> <del> // Export the Underscore object for **CommonJS**, with backwards-compatibility <del> // for the old `require()` API. If we're not in CommonJS, add `_` to the <del> // global object. <del> if (typeof module !== 'undefined' && module.exports) { <del> module.exports = _; <del> _._ = _; <add> // Export the Underscore object for **Node.js** and **"CommonJS"**, with <add> // backwards-compatibility for the old `require()` API. If we're not in <add> // CommonJS, add `_` to the global object. <add> if (typeof exports !== 'undefined') { <add> if (typeof module !== 'undefined' && module.exports) { <add> exports = module.exports = _; <add> } <add> exports._ = _; <add> } else if (typeof define === 'function' && define.amd) { <add> // Register as a named module with AMD. <add> define('underscore', function() { <add> return _; <add> }); <ide> } else { <ide> // Exported as a string, for Closure Compiler "advanced" mode. <ide> root['_'] = _; <ide> } <ide> <ide> // Current version. <del> _.VERSION = '1.1.7'; <add> _.VERSION = '1.2.2'; <ide> <ide> // Collection Functions <ide> // -------------------- <ide> if (obj == null) return result; <ide> if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); <ide> each(obj, function(value, index, list) { <del> if (result |= iterator.call(context, value, index, list)) return breaker; <add> if (result || (result = iterator.call(context, value, index, list))) return breaker; <ide> }); <ide> return !!result; <ide> }; <ide> var found = false; <ide> if (obj == null) return found; <ide> if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; <del> any(obj, function(value) { <del> if (found = value === target) return true; <add> found = any(obj, function(value) { <add> return value === target; <ide> }); <ide> return found; <ide> }; <ide> // Return the maximum element or (element-based computation). <ide> _.max = function(obj, iterator, context) { <ide> if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj); <add> if (!iterator && _.isEmpty(obj)) return -Infinity; <ide> var result = {computed : -Infinity}; <ide> each(obj, function(value, index, list) { <ide> var computed = iterator ? iterator.call(context, value, index, list) : value; <ide> // Return the minimum element (or element-based computation). <ide> _.min = function(obj, iterator, context) { <ide> if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj); <add> if (!iterator && _.isEmpty(obj)) return Infinity; <ide> var result = {computed : Infinity}; <ide> each(obj, function(value, index, list) { <ide> var computed = iterator ? iterator.call(context, value, index, list) : value; <ide> return result.value; <ide> }; <ide> <add> // Shuffle an array. <add> _.shuffle = function(obj) { <add> var shuffled = [], rand; <add> each(obj, function(value, index, list) { <add> if (index == 0) { <add> shuffled[0] = value; <add> } else { <add> rand = Math.floor(Math.random() * (index + 1)); <add> shuffled[index] = shuffled[rand]; <add> shuffled[rand] = value; <add> } <add> }); <add> return shuffled; <add> }; <add> <ide> // Sort the object's values by a criterion produced by an iterator. <ide> _.sortBy = function(obj, iterator, context) { <ide> return _.pluck(_.map(obj, function(value, index, list) { <ide> }), 'value'); <ide> }; <ide> <del> // Groups the object's values by a criterion produced by an iterator <del> _.groupBy = function(obj, iterator) { <add> // Groups the object's values by a criterion. Pass either a string attribute <add> // to group by, or a function that returns the criterion. <add> _.groupBy = function(obj, val) { <ide> var result = {}; <add> var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; }; <ide> each(obj, function(value, index) { <ide> var key = iterator(value, index); <ide> (result[key] || (result[key] = [])).push(value); <ide> return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; <ide> }; <ide> <add> // Returns everything but the last entry of the array. Especcialy useful on <add> // the arguments object. Passing **n** will return all the values in <add> // the array, excluding the last N. The **guard** check allows it to work with <add> // `_.map`. <add> _.initial = function(array, n, guard) { <add> return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); <add> }; <add> <add> // Get the last element of an array. Passing **n** will return the last N <add> // values in the array. The **guard** check allows it to work with `_.map`. <add> _.last = function(array, n, guard) { <add> if ((n != null) && !guard) { <add> return slice.call(array, Math.max(array.length - n, 0)); <add> } else { <add> return array[array.length - 1]; <add> } <add> }; <add> <ide> // Returns everything but the first entry of the array. Aliased as `tail`. <ide> // Especially useful on the arguments object. Passing an **index** will return <ide> // the rest of the values in the array from that index onward. The **guard** <ide> return slice.call(array, (index == null) || guard ? 1 : index); <ide> }; <ide> <del> // Get the last element of an array. <del> _.last = function(array) { <del> return array[array.length - 1]; <del> }; <del> <ide> // Trim out all falsy values from an array. <ide> _.compact = function(array) { <ide> return _.filter(array, function(value){ return !!value; }); <ide> }; <ide> <ide> // Return a completely flattened version of an array. <del> _.flatten = function(array) { <add> _.flatten = function(array, shallow) { <ide> return _.reduce(array, function(memo, value) { <del> if (_.isArray(value)) return memo.concat(_.flatten(value)); <add> if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value)); <ide> memo[memo.length] = value; <ide> return memo; <ide> }, []); <ide> // Produce a duplicate-free version of the array. If the array has already <ide> // been sorted, you have the option of using a faster algorithm. <ide> // Aliased as `unique`. <del> _.uniq = _.unique = function(array, isSorted) { <del> return _.reduce(array, function(memo, el, i) { <del> if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el; <add> _.uniq = _.unique = function(array, isSorted, iterator) { <add> var initial = iterator ? _.map(array, iterator) : array; <add> var result = []; <add> _.reduce(initial, function(memo, el, i) { <add> if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) { <add> memo[memo.length] = el; <add> result[result.length] = array[i]; <add> } <ide> return memo; <ide> }, []); <add> return result; <ide> }; <ide> <ide> // Produce an array that contains the union: each distinct element from all of <ide> // the passed-in arrays. <ide> _.union = function() { <del> return _.uniq(_.flatten(arguments)); <add> return _.uniq(_.flatten(arguments, true)); <ide> }; <ide> <ide> // Produce an array that contains every item shared between all the <ide> return -1; <ide> }; <ide> <del> <ide> // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. <ide> _.lastIndexOf = function(array, item) { <ide> if (array == null) return -1; <ide> // Function (ahem) Functions <ide> // ------------------ <ide> <add> // Reusable constructor function for prototype setting. <add> var ctor = function(){}; <add> <ide> // Create a function bound to a given object (assigning `this`, and arguments, <ide> // optionally). Binding with arguments is also known as `curry`. <ide> // Delegates to **ECMAScript 5**'s native `Function.bind` if available. <ide> // We check for `func.bind` first, to fail fast when `func` is undefined. <del> _.bind = function(func, obj) { <add> _.bind = function bind(func, context) { <add> var bound, args; <ide> if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); <del> var args = slice.call(arguments, 2); <del> return function() { <del> return func.apply(obj, args.concat(slice.call(arguments))); <add> if (!_.isFunction(func)) throw new TypeError; <add> args = slice.call(arguments, 2); <add> return bound = function() { <add> if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); <add> ctor.prototype = func.prototype; <add> var self = new ctor; <add> var result = func.apply(self, args.concat(slice.call(arguments))); <add> if (Object(result) === result) return result; <add> return self; <ide> }; <ide> }; <ide> <ide> return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); <ide> }; <ide> <del> // Internal function used to implement `_.throttle` and `_.debounce`. <del> var limit = function(func, wait, debounce) { <del> var timeout; <add> // Returns a function, that, when invoked, will only be triggered at most once <add> // during a given window of time. <add> _.throttle = function(func, wait) { <add> var context, args, timeout, throttling, more; <add> var whenDone = _.debounce(function(){ more = throttling = false; }, wait); <ide> return function() { <del> var context = this, args = arguments; <del> var throttler = function() { <add> context = this; args = arguments; <add> var later = function() { <ide> timeout = null; <del> func.apply(context, args); <add> if (more) func.apply(context, args); <add> whenDone(); <ide> }; <del> if (debounce) clearTimeout(timeout); <del> if (debounce || !timeout) timeout = setTimeout(throttler, wait); <add> if (!timeout) timeout = setTimeout(later, wait); <add> if (throttling) { <add> more = true; <add> } else { <add> func.apply(context, args); <add> } <add> whenDone(); <add> throttling = true; <ide> }; <ide> }; <ide> <del> // Returns a function, that, when invoked, will only be triggered at most once <del> // during a given window of time. <del> _.throttle = function(func, wait) { <del> return limit(func, wait, false); <del> }; <del> <ide> // Returns a function, that, as long as it continues to be invoked, will not <ide> // be triggered. The function will be called after it stops being called for <ide> // N milliseconds. <ide> _.debounce = function(func, wait) { <del> return limit(func, wait, true); <add> var timeout; <add> return function() { <add> var context = this, args = arguments; <add> var later = function() { <add> timeout = null; <add> func.apply(context, args); <add> }; <add> clearTimeout(timeout); <add> timeout = setTimeout(later, wait); <add> }; <ide> }; <ide> <ide> // Returns a function that will be executed at most one time, no matter how <ide> <ide> // Returns a function that will only be executed after being called N times. <ide> _.after = function(times, func) { <add> if (times <= 0) return func(); <ide> return function() { <ide> if (--times < 1) { return func.apply(this, arguments); } <ide> }; <ide> }; <ide> <del> <ide> // Object Functions <ide> // ---------------- <ide> <ide> <ide> // Create a (shallow-cloned) duplicate of an object. <ide> _.clone = function(obj) { <add> if (!_.isObject(obj)) return obj; <ide> return _.isArray(obj) ? obj.slice() : _.extend({}, obj); <ide> }; <ide> <ide> return obj; <ide> }; <ide> <del> // Perform a deep comparison to check if two objects are equal. <del> _.isEqual = function(a, b) { <del> // Check object identity. <del> if (a === b) return true; <del> // Different types? <del> var atype = typeof(a), btype = typeof(b); <del> if (atype != btype) return false; <del> // Basic equality test (watch out for coercions). <del> if (a == b) return true; <del> // One is falsy and the other truthy. <del> if ((!a && b) || (a && !b)) return false; <add> // Internal recursive comparison function. <add> function eq(a, b, stack) { <add> // Identical objects are equal. `0 === -0`, but they aren't identical. <add> // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. <add> if (a === b) return a !== 0 || 1 / a == 1 / b; <add> // A strict comparison is necessary because `null == undefined`. <add> if (a == null || b == null) return a === b; <ide> // Unwrap any wrapped objects. <ide> if (a._chain) a = a._wrapped; <ide> if (b._chain) b = b._wrapped; <del> // One of them implements an isEqual()? <del> if (a.isEqual) return a.isEqual(b); <del> if (b.isEqual) return b.isEqual(a); <del> // Check dates' integer values. <del> if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime(); <del> // Both are NaN? <del> if (_.isNaN(a) && _.isNaN(b)) return false; <del> // Compare regular expressions. <del> if (_.isRegExp(a) && _.isRegExp(b)) <del> return a.source === b.source && <del> a.global === b.global && <del> a.ignoreCase === b.ignoreCase && <del> a.multiline === b.multiline; <del> // If a is not an object by this point, we can't handle it. <del> if (atype !== 'object') return false; <del> // Check for different array lengths before comparing contents. <del> if (a.length && (a.length !== b.length)) return false; <del> // Nothing else worked, deep compare the contents. <del> var aKeys = _.keys(a), bKeys = _.keys(b); <del> // Different object sizes? <del> if (aKeys.length != bKeys.length) return false; <del> // Recursive comparison of contents. <del> for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false; <del> return true; <add> // Invoke a custom `isEqual` method if one is provided. <add> if (_.isFunction(a.isEqual)) return a.isEqual(b); <add> if (_.isFunction(b.isEqual)) return b.isEqual(a); <add> // Compare `[[Class]]` names. <add> var className = toString.call(a); <add> if (className != toString.call(b)) return false; <add> switch (className) { <add> // Strings, numbers, dates, and booleans are compared by value. <add> case '[object String]': <add> // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is <add> // equivalent to `new String("5")`. <add> return String(a) == String(b); <add> case '[object Number]': <add> a = +a; <add> b = +b; <add> // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for <add> // other numeric values. <add> return a != a ? b != b : (a == 0 ? 1 / a == 1 / b : a == b); <add> case '[object Date]': <add> case '[object Boolean]': <add> // Coerce dates and booleans to numeric primitive values. Dates are compared by their <add> // millisecond representations. Note that invalid dates with millisecond representations <add> // of `NaN` are not equivalent. <add> return +a == +b; <add> // RegExps are compared by their source patterns and flags. <add> case '[object RegExp]': <add> return a.source == b.source && <add> a.global == b.global && <add> a.multiline == b.multiline && <add> a.ignoreCase == b.ignoreCase; <add> } <add> if (typeof a != 'object' || typeof b != 'object') return false; <add> // Assume equality for cyclic structures. The algorithm for detecting cyclic <add> // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. <add> var length = stack.length; <add> while (length--) { <add> // Linear search. Performance is inversely proportional to the number of <add> // unique nested structures. <add> if (stack[length] == a) return true; <add> } <add> // Add the first object to the stack of traversed objects. <add> stack.push(a); <add> var size = 0, result = true; <add> // Recursively compare objects and arrays. <add> if (className == '[object Array]') { <add> // Compare array lengths to determine if a deep comparison is necessary. <add> size = a.length; <add> result = size == b.length; <add> if (result) { <add> // Deep compare the contents, ignoring non-numeric properties. <add> while (size--) { <add> // Ensure commutative equality for sparse arrays. <add> if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break; <add> } <add> } <add> } else { <add> // Objects with different constructors are not equivalent. <add> if ("constructor" in a != "constructor" in b || a.constructor != b.constructor) return false; <add> // Deep compare objects. <add> for (var key in a) { <add> if (hasOwnProperty.call(a, key)) { <add> // Count the expected number of properties. <add> size++; <add> // Deep compare each member. <add> if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], stack))) break; <add> } <add> } <add> // Ensure that both objects contain the same number of properties. <add> if (result) { <add> for (key in b) { <add> if (hasOwnProperty.call(b, key) && !(size--)) break; <add> } <add> result = !size; <add> } <add> } <add> // Remove the first object from the stack of traversed objects. <add> stack.pop(); <add> return result; <add> } <add> <add> // Perform a deep comparison to check if two objects are equal. <add> _.isEqual = function(a, b) { <add> return eq(a, b, []); <ide> }; <ide> <del> // Is a given array or object empty? <add> // Is a given array, string, or object empty? <add> // An "empty" object has no enumerable own-properties. <ide> _.isEmpty = function(obj) { <ide> if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; <ide> for (var key in obj) if (hasOwnProperty.call(obj, key)) return false; <ide> // Is a given value an array? <ide> // Delegates to ECMA5's native Array.isArray <ide> _.isArray = nativeIsArray || function(obj) { <del> return toString.call(obj) === '[object Array]'; <add> return toString.call(obj) == '[object Array]'; <ide> }; <ide> <ide> // Is a given variable an object? <ide> }; <ide> <ide> // Is a given variable an arguments object? <del> _.isArguments = function(obj) { <del> return !!(obj && hasOwnProperty.call(obj, 'callee')); <del> }; <add> if (toString.call(arguments) == '[object Arguments]') { <add> _.isArguments = function(obj) { <add> return toString.call(obj) == '[object Arguments]'; <add> }; <add> } else { <add> _.isArguments = function(obj) { <add> return !!(obj && hasOwnProperty.call(obj, 'callee')); <add> }; <add> } <ide> <ide> // Is a given value a function? <ide> _.isFunction = function(obj) { <del> return !!(obj && obj.constructor && obj.call && obj.apply); <add> return toString.call(obj) == '[object Function]'; <ide> }; <ide> <ide> // Is a given value a string? <ide> _.isString = function(obj) { <del> return !!(obj === '' || (obj && obj.charCodeAt && obj.substr)); <add> return toString.call(obj) == '[object String]'; <ide> }; <ide> <ide> // Is a given value a number? <ide> _.isNumber = function(obj) { <del> return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed)); <add> return toString.call(obj) == '[object Number]'; <ide> }; <ide> <del> // Is the given value `NaN`? `NaN` happens to be the only value in JavaScript <del> // that does not equal itself. <add> // Is the given value `NaN`? <ide> _.isNaN = function(obj) { <add> // `NaN` is the only value for which `===` is not reflexive. <ide> return obj !== obj; <ide> }; <ide> <ide> // Is a given value a boolean? <ide> _.isBoolean = function(obj) { <del> return obj === true || obj === false; <add> return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; <ide> }; <ide> <ide> // Is a given value a date? <ide> _.isDate = function(obj) { <del> return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear); <add> return toString.call(obj) == '[object Date]'; <ide> }; <ide> <ide> // Is the given value a regular expression? <ide> _.isRegExp = function(obj) { <del> return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false)); <add> return toString.call(obj) == '[object RegExp]'; <ide> }; <ide> <ide> // Is a given value equal to null? <ide> for (var i = 0; i < n; i++) iterator.call(context, i); <ide> }; <ide> <add> // Escape a string for HTML interpolation. <add> _.escape = function(string) { <add> return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;'); <add> }; <add> <ide> // Add your own custom functions to the Underscore object, ensuring that <ide> // they're correctly added to the OOP wrapper as well. <ide> _.mixin = function(obj) { <ide> // following template settings to use alternative delimiters. <ide> _.templateSettings = { <ide> evaluate : /<%([\s\S]+?)%>/g, <del> interpolate : /<%=([\s\S]+?)%>/g <add> interpolate : /<%=([\s\S]+?)%>/g, <add> escape : /<%-([\s\S]+?)%>/g <ide> }; <ide> <ide> // JavaScript micro-templating, similar to John Resig's implementation. <ide> 'with(obj||{}){__p.push(\'' + <ide> str.replace(/\\/g, '\\\\') <ide> .replace(/'/g, "\\'") <add> .replace(c.escape, function(match, code) { <add> return "',_.escape(" + code.replace(/\\'/g, "'") + "),'"; <add> }) <ide> .replace(c.interpolate, function(match, code) { <ide> return "'," + code.replace(/\\'/g, "'") + ",'"; <ide> }) <ide> .replace(c.evaluate || null, function(match, code) { <ide> return "');" + code.replace(/\\'/g, "'") <del> .replace(/[\r\n\t]/g, ' ') + "__p.push('"; <add> .replace(/[\r\n\t]/g, ' ') + ";__p.push('"; <ide> }) <ide> .replace(/\r/g, '\\r') <ide> .replace(/\n/g, '\\n') <ide> .replace(/\t/g, '\\t') <ide> + "');}return __p.join('');"; <del> var func = new Function('obj', tmpl); <del> return data ? func(data) : func; <add> var func = new Function('obj', '_', tmpl); <add> return data ? func(data, _) : function(data) { return func(data, _) }; <ide> }; <ide> <ide> // The OOP Wrapper <ide> return this._wrapped; <ide> }; <ide> <del>// fix for 'use strict' - need an explicit `this` <del>}).call(this || window); <add>}).call(this);
1
Text
Text
fix a typo in 5_2_release_notes.md
43366d5b78c886b9d63248310da6c2fcbce69e88
<ide><path>guides/source/5_2_release_notes.md <ide> Please refer to the [Changelog][action-view] for detailed changes. <ide> select divider `option`. <ide> ([Pull Request](https://github.com/rails/rails/pull/31088)) <ide> <del>* Change `form_with` to generates ids by default. <add>* Change `form_with` to generate ids by default. <ide> ([Commit](https://github.com/rails/rails/commit/260d6f112a0ffdbe03e6f5051504cb441c1e94cd)) <ide> <ide> * Add `preload_link_tag` helper.
1
Ruby
Ruby
remove dead code
75a60e5104702c8e65d6922cffec6828dc872f48
<ide><path>Library/Homebrew/cmd/fetch.rb <ide> def fetch <ide> the_tarball, _ = f.fetch <ide> next unless the_tarball.kind_of? Pathname <ide> <del> previous_md5 = f.active_spec.md5.to_s.downcase <del> previous_sha1 = f.active_spec.sha1.to_s.downcase <del> previous_sha2 = f.active_spec.sha256.to_s.downcase <del> <ide> puts "Downloaded to: #{the_tarball}" unless already_downloaded <ide> puts "MD5: #{the_tarball.md5}" <ide> puts "SHA1: #{the_tarball.sha1}"
1
Text
Text
improve yolo translation
2963af7592ac5b458ee89633273341f0ba93e36f
<ide><path>guide/portuguese/machine-learning/yolo-for-object-detection/index.md <ide> title: YOLO <ide> localeTitle: YOLO <ide> --- <del>## YOLO - Você só olha uma vez método para detecção de objetos em tempo real <add>## YOLO - (You Only Look Once) Método para detecção de objetos em tempo real <ide> <ide> O YOLO é uma estrutura combinada de classificação e detecção que é capaz de fazer previsões em tempo real e está de acordo com as estruturas de detecção de estado da arte. <ide> <ide> #### Mais Informações: <ide> <del>* [Papel](https://arxiv.org/abs/1506.02640) YOLO <add>* [Artigo](https://arxiv.org/abs/1506.02640) YOLO <ide> * [Web site do](https://pjreddie.com/darknet/yolo/) autor <del>* [Vídeo de](https://www.youtube.com/watch?v=VOC3huqHrss) demonstração <ide>\ No newline at end of file <add>* [Vídeo](https://www.youtube.com/watch?v=VOC3huqHrss) de demonstração
1