_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q17500
toFormat
train
function toFormat (format, options) { if (is.object(format) && is.string(format.id)) { format = format.id; } if (format === 'jpg') format = 'jpeg'; if (!is.inArray(format, ['jpeg', 'png', 'webp', 'tiff', 'raw'])) { throw new Error('Unsupported output format ' + format); } return this[format](options); }
javascript
{ "resource": "" }
q17501
_updateFormatOut
train
function _updateFormatOut (formatOut, options) { if (!(is.object(options) && options.force === false)) { this.options.formatOut = formatOut; } return this; }
javascript
{ "resource": "" }
q17502
_setBooleanOption
train
function _setBooleanOption (key, val) { if (is.bool(val)) { this.options[key] = val; } else { throw new Error('Invalid ' + key + ' (boolean) ' + val); } }
javascript
{ "resource": "" }
q17503
tint
train
function tint (rgb) { const colour = color(rgb); this.options.tintA = colour.a(); this.options.tintB = colour.b(); return this; }
javascript
{ "resource": "" }
q17504
toColourspace
train
function toColourspace (colourspace) { if (!is.string(colourspace)) { throw new Error('Invalid output colourspace ' + colourspace); } this.options.colourspace = colourspace; return this; }
javascript
{ "resource": "" }
q17505
_setColourOption
train
function _setColourOption (key, val) { if (is.object(val) || is.string(val)) { const colour = color(val); this.options[key] = [ colour.red(), colour.green(), colour.blue(), Math.round(colour.alpha() * 255) ]; } }
javascript
{ "resource": "" }
q17506
extract
train
function extract (options) { const suffix = this.options.width === -1 && this.options.height === -1 ? 'Pre' : 'Post'; ['left', 'top', 'width', 'height'].forEach(function (name) { const value = options[name]; if (is.integer(value) && value >= 0) { this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value; } else { throw new Error('Non-integer value for ' + name + ' of ' + value); } }, this); // Ensure existing rotation occurs before pre-resize extraction if (suffix === 'Pre' && ((this.options.angle % 360) !== 0 || this.options.useExifOrientation === true)) { this.options.rotateBeforePreExtract = true; } return this; }
javascript
{ "resource": "" }
q17507
trim
train
function trim (threshold) { if (!is.defined(threshold)) { this.options.trimThreshold = 10; } else if (is.number(threshold) && threshold > 0) { this.options.trimThreshold = threshold; } else { throw is.invalidParameterError('threshold', 'number greater than zero', threshold); } return this; }
javascript
{ "resource": "" }
q17508
rotate
train
function rotate (angle, options) { if (!is.defined(angle)) { this.options.useExifOrientation = true; } else if (is.integer(angle) && !(angle % 90)) { this.options.angle = angle; } else if (is.number(angle)) { this.options.rotationAngle = angle; if (is.object(options) && options.background) { const backgroundColour = color(options.background); this.options.rotationBackground = [ backgroundColour.red(), backgroundColour.green(), backgroundColour.blue(), Math.round(backgroundColour.alpha() * 255) ]; } } else { throw new Error('Unsupported angle: must be a number.'); } return this; }
javascript
{ "resource": "" }
q17509
sharpen
train
function sharpen (sigma, flat, jagged) { if (!is.defined(sigma)) { // No arguments: default to mild sharpen this.options.sharpenSigma = -1; } else if (is.bool(sigma)) { // Boolean argument: apply mild sharpen? this.options.sharpenSigma = sigma ? -1 : 0; } else if (is.number(sigma) && is.inRange(sigma, 0.01, 10000)) { // Numeric argument: specific sigma this.options.sharpenSigma = sigma; // Control over flat areas if (is.defined(flat)) { if (is.number(flat) && is.inRange(flat, 0, 10000)) { this.options.sharpenFlat = flat; } else { throw new Error('Invalid sharpen level for flat areas (0.0 - 10000.0) ' + flat); } } // Control over jagged areas if (is.defined(jagged)) { if (is.number(jagged) && is.inRange(jagged, 0, 10000)) { this.options.sharpenJagged = jagged; } else { throw new Error('Invalid sharpen level for jagged areas (0.0 - 10000.0) ' + jagged); } } } else { throw new Error('Invalid sharpen sigma (0.01 - 10000) ' + sigma); } return this; }
javascript
{ "resource": "" }
q17510
median
train
function median (size) { if (!is.defined(size)) { // No arguments: default to 3x3 this.options.medianSize = 3; } else if (is.integer(size) && is.inRange(size, 1, 1000)) { // Numeric argument: specific sigma this.options.medianSize = size; } else { throw new Error('Invalid median size ' + size); } return this; }
javascript
{ "resource": "" }
q17511
blur
train
function blur (sigma) { if (!is.defined(sigma)) { // No arguments: default to mild blur this.options.blurSigma = -1; } else if (is.bool(sigma)) { // Boolean argument: apply mild blur? this.options.blurSigma = sigma ? -1 : 0; } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) { // Numeric argument: specific sigma this.options.blurSigma = sigma; } else { throw new Error('Invalid blur sigma (0.3 - 1000.0) ' + sigma); } return this; }
javascript
{ "resource": "" }
q17512
flatten
train
function flatten (options) { this.options.flatten = is.bool(options) ? options : true; if (is.object(options)) { this._setColourOption('flattenBackground', options.background); } return this; }
javascript
{ "resource": "" }
q17513
convolve
train
function convolve (kernel) { if (!is.object(kernel) || !Array.isArray(kernel.kernel) || !is.integer(kernel.width) || !is.integer(kernel.height) || !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) || kernel.height * kernel.width !== kernel.kernel.length ) { // must pass in a kernel throw new Error('Invalid convolution kernel'); } // Default scale is sum of kernel values if (!is.integer(kernel.scale)) { kernel.scale = kernel.kernel.reduce(function (a, b) { return a + b; }, 0); } // Clip scale to a minimum value of 1 if (kernel.scale < 1) { kernel.scale = 1; } if (!is.integer(kernel.offset)) { kernel.offset = 0; } this.options.convKernel = kernel; return this; }
javascript
{ "resource": "" }
q17514
threshold
train
function threshold (threshold, options) { if (!is.defined(threshold)) { this.options.threshold = 128; } else if (is.bool(threshold)) { this.options.threshold = threshold ? 128 : 0; } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) { this.options.threshold = threshold; } else { throw new Error('Invalid threshold (0 to 255) ' + threshold); } if (!is.object(options) || options.greyscale === true || options.grayscale === true) { this.options.thresholdGrayscale = true; } else { this.options.thresholdGrayscale = false; } return this; }
javascript
{ "resource": "" }
q17515
boolean
train
function boolean (operand, operator, options) { this.options.boolean = this._createInputDescriptor(operand, options); if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) { this.options.booleanOp = operator; } else { throw new Error('Invalid boolean operator ' + operator); } return this; }
javascript
{ "resource": "" }
q17516
recomb
train
function recomb (inputMatrix) { if (!Array.isArray(inputMatrix) || inputMatrix.length !== 3 || inputMatrix[0].length !== 3 || inputMatrix[1].length !== 3 || inputMatrix[2].length !== 3 ) { // must pass in a kernel throw new Error('Invalid Recomb Matrix'); } this.options.recombMatrix = [ inputMatrix[0][0], inputMatrix[0][1], inputMatrix[0][2], inputMatrix[1][0], inputMatrix[1][1], inputMatrix[1][2], inputMatrix[2][0], inputMatrix[2][1], inputMatrix[2][2] ].map(Number); return this; }
javascript
{ "resource": "" }
q17517
modulate
train
function modulate (options) { if (!is.plainObject(options)) { throw is.invalidParameterError('options', 'plain object', options); } if ('brightness' in options) { if (is.number(options.brightness) && options.brightness >= 0) { this.options.brightness = options.brightness; } else { throw is.invalidParameterError('brightness', 'number above zero', options.brightness); } } if ('saturation' in options) { if (is.number(options.saturation) && options.saturation >= 0) { this.options.saturation = options.saturation; } else { throw is.invalidParameterError('saturation', 'number above zero', options.saturation); } } if ('hue' in options) { if (is.integer(options.hue)) { this.options.hue = options.hue % 360; } else { throw is.invalidParameterError('hue', 'number', options.hue); } } return this; }
javascript
{ "resource": "" }
q17518
findWhereUnwrapped
train
function findWhereUnwrapped(wrapper, predicate, filter = treeFilter) { return wrapper.flatMap(n => filter(n.getNodeInternal(), predicate)); }
javascript
{ "resource": "" }
q17519
filterWhereUnwrapped
train
function filterWhereUnwrapped(wrapper, predicate) { return wrapper.wrap(wrapper.getNodesInternal().filter(predicate).filter(Boolean)); }
javascript
{ "resource": "" }
q17520
validateOptions
train
function validateOptions(options) { const { lifecycleExperimental, disableLifecycleMethods, enableComponentDidUpdateOnSetState, supportPrevContextArgumentOfComponentDidUpdate, lifecycles, } = options; if (typeof lifecycleExperimental !== 'undefined' && typeof lifecycleExperimental !== 'boolean') { throw new Error('lifecycleExperimental must be either true or false if provided'); } if (typeof disableLifecycleMethods !== 'undefined' && typeof disableLifecycleMethods !== 'boolean') { throw new Error('disableLifecycleMethods must be either true or false if provided'); } if ( lifecycleExperimental != null && disableLifecycleMethods != null && lifecycleExperimental === disableLifecycleMethods ) { throw new Error('lifecycleExperimental and disableLifecycleMethods cannot be set to the same value'); } if ( typeof enableComponentDidUpdateOnSetState !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.onSetState !== enableComponentDidUpdateOnSetState ) { throw new TypeError('the legacy enableComponentDidUpdateOnSetState option should be matched by `lifecycles: { componentDidUpdate: { onSetState: true } }`, for compatibility'); } if ( typeof supportPrevContextArgumentOfComponentDidUpdate !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.prevContext !== supportPrevContextArgumentOfComponentDidUpdate ) { throw new TypeError('the legacy supportPrevContextArgumentOfComponentDidUpdate option should be matched by `lifecycles: { componentDidUpdate: { prevContext: true } }`, for compatibility'); } }
javascript
{ "resource": "" }
q17521
getContextFromWrappingComponent
train
function getContextFromWrappingComponent(wrapper, adapter) { const rootFinder = deepRender(wrapper, wrapper[ROOT_FINDER], adapter); if (!rootFinder) { throw new Error('`wrappingComponent` must render its children!'); } return { legacyContext: rootFinder[OPTIONS].context, providerValues: rootFinder[PROVIDER_VALUES], }; }
javascript
{ "resource": "" }
q17522
updatePrimaryRootContext
train
function updatePrimaryRootContext(wrappingComponent) { const adapter = getAdapter(wrappingComponent[OPTIONS]); const primaryWrapper = wrappingComponent[PRIMARY_WRAPPER]; const primaryRenderer = primaryWrapper[RENDERER]; const primaryNode = primaryRenderer.getNode(); const { legacyContext, providerValues, } = getContextFromWrappingComponent(wrappingComponent, adapter); const prevProviderValues = primaryWrapper[PROVIDER_VALUES]; primaryWrapper.setContext({ ...wrappingComponent[PRIMARY_WRAPPER][OPTIONS].context, ...legacyContext, }); primaryWrapper[PROVIDER_VALUES] = new Map([...prevProviderValues, ...providerValues]); if (typeof adapter.isContextConsumer === 'function' && adapter.isContextConsumer(primaryNode.type)) { const Consumer = primaryNode.type; // Adapters with an `isContextConsumer` method will definitely have a `getProviderFromConsumer` // method. const Provider = adapter.getProviderFromConsumer(Consumer); const newValue = providerValues.get(Provider); const oldValue = prevProviderValues.get(Provider); // Use referential comparison like React if (newValue !== oldValue) { primaryWrapper.rerender(); } } }
javascript
{ "resource": "" }
q17523
nodeMatchesToken
train
function nodeMatchesToken(node, token, root) { if (node === null || typeof node === 'string') { return false; } switch (token.type) { /** * Match every node * @example '*' matches every node */ case UNIVERSAL_SELECTOR: return true; /** * Match against the className prop * @example '.active' matches <div className='active' /> */ case CLASS_SELECTOR: return hasClassName(node, token.name); /** * Simple type matching * @example 'div' matches <div /> */ case TYPE_SELECTOR: return nodeHasType(node, token.name); /** * Match against the `id` prop * @example '#nav' matches <ul id="nav" /> */ case ID_SELECTOR: return nodeHasId(node, token.name); /** * Matches if an attribute is present, regardless * of its value * @example '[disabled]' matches <a disabled /> */ case ATTRIBUTE_PRESENCE: return matchAttributeSelector(node, token); /** * Matches if an attribute is present with the * provided value * @example '[data-foo=foo]' matches <div data-foo="foo" /> */ case ATTRIBUTE_VALUE: return matchAttributeSelector(node, token); case PSEUDO_ELEMENT: case PSEUDO_CLASS: return matchPseudoSelector(node, token, root); default: throw new Error(`Unknown token type: ${token.type}`); } }
javascript
{ "resource": "" }
q17524
buildPredicateFromToken
train
function buildPredicateFromToken(token, root) { return node => token.body.every(bodyToken => nodeMatchesToken(node, bodyToken, root)); }
javascript
{ "resource": "" }
q17525
matchDescendant
train
function matchDescendant(nodes, predicate) { return uniqueReduce( (matches, node) => matches.concat(treeFilter(node, predicate)), flat(nodes.map(childrenOfNode)), ); }
javascript
{ "resource": "" }
q17526
getEntry
train
function getEntry(knownHashes, url, revision) { // We're assuming that if the URL contains any of the known hashes // (either the short or full chunk hash or compilation hash) then it's // already revisioned, and we don't need additional out-of-band revisioning. if (!revision || knownHashes.some((hash) => url.includes(hash))) { return {url}; } return {revision, url}; }
javascript
{ "resource": "" }
q17527
getKnownHashesFromAssets
train
function getKnownHashesFromAssets(assetMetadata) { const knownHashes = new Set(); for (const metadata of Object.values(assetMetadata)) { knownHashes.add(metadata.hash); } return knownHashes; }
javascript
{ "resource": "" }
q17528
getManifestEntriesFromCompilation
train
function getManifestEntriesFromCompilation(compilation, config) { const blacklistedChunkNames = config.excludeChunks; const whitelistedChunkNames = config.chunks; const {assets, chunks} = compilation; const {publicPath} = compilation.options.output; const assetMetadata = generateMetadataForAssets(assets, chunks); const filteredAssetMetadata = filterAssets(assetMetadata, whitelistedChunkNames, blacklistedChunkNames); const knownHashes = [ compilation.hash, compilation.fullHash, ...getKnownHashesFromAssets(filteredAssetMetadata), ].filter((hash) => !!hash); const manifestEntries = []; for (const [file, metadata] of Object.entries(filteredAssetMetadata)) { // Filter based on test/include/exclude options set in the config, // following webpack's conventions. // This matches the behavior of, e.g., UglifyJS's webpack plugin. if (!ModuleFilenameHelpers.matchObject(config, file)) { continue; } const publicURL = resolveWebpackURL(publicPath, file); const manifestEntry = getEntry(knownHashes, publicURL, metadata.hash); manifestEntries.push(manifestEntry); } return manifestEntries; }
javascript
{ "resource": "" }
q17529
getOptionsString
train
function getOptionsString(options = {}) { let plugins = []; if (options.plugins) { // Using libs because JSON.stringify won't handle functions. plugins = options.plugins.map(stringifyWithoutComments); delete options.plugins; } // Pull handler-specific config from the options object, since they are // not directly used to construct a Plugin instance. If set, need to be // passed as options to the handler constructor instead. const handlerOptionKeys = [ 'cacheName', 'networkTimeoutSeconds', 'fetchOptions', 'matchOptions', ]; const handlerOptions = {}; for (const key of handlerOptionKeys) { if (key in options) { handlerOptions[key] = options[key]; delete options[key]; } } const pluginsMapping = { backgroundSync: 'workbox.backgroundSync.Plugin', broadcastUpdate: 'workbox.broadcastUpdate.Plugin', expiration: 'workbox.expiration.Plugin', cacheableResponse: 'workbox.cacheableResponse.Plugin', }; for (const [pluginName, pluginConfig] of Object.entries(options)) { // Ensure that we have some valid configuration to pass to Plugin(). if (Object.keys(pluginConfig).length === 0) { continue; } const pluginString = pluginsMapping[pluginName]; if (!pluginString) { throw new Error(`${errors['bad-runtime-caching-config']} ${pluginName}`); } let pluginCode; switch (pluginName) { // Special case logic for plugins that have a required parameter, and then // an additional optional config parameter. case 'backgroundSync': { const name = pluginConfig.name; pluginCode = `new ${pluginString}(${JSON.stringify(name)}`; if ('options' in pluginConfig) { pluginCode += `, ${stringifyWithoutComments(pluginConfig.options)}`; } pluginCode += `)`; break; } case 'broadcastUpdate': { const channelName = pluginConfig.channelName; const opts = Object.assign({channelName}, pluginConfig.options); pluginCode = `new ${pluginString}(${stringifyWithoutComments(opts)})`; break; } // For plugins that just pass in an Object to the constructor, like // expiration and cacheableResponse default: { pluginCode = `new ${pluginString}(${stringifyWithoutComments( pluginConfig )})`; } } plugins.push(pluginCode); } if (Object.keys(handlerOptions).length > 0 || plugins.length > 0) { const optionsString = JSON.stringify(handlerOptions).slice(1, -1); return ol`{ ${optionsString ? optionsString + ',' : ''} plugins: [${plugins.join(', ')}] }`; } else { return ''; } }
javascript
{ "resource": "" }
q17530
generateSWString
train
async function generateSWString(config) { // This check needs to be done before validation, since the deprecated options // will be renamed. const deprecationWarnings = checkForDeprecatedOptions(config); const options = validate(config, generateSWStringSchema); const {manifestEntries, warnings} = await getFileManifestEntries(options); const swString = await populateSWTemplate(Object.assign({ manifestEntries, }, options)); // Add in any deprecation warnings. warnings.push(...deprecationWarnings); return {swString, warnings}; }
javascript
{ "resource": "" }
q17531
runBuildCommand
train
async function runBuildCommand({command, config, watch}) { try { const {size, count, warnings} = await workboxBuild[command](config); for (const warning of warnings) { logger.warn(warning); } logger.log(`The service worker was written to ${config.swDest}\n` + `${count} files will be precached, totalling ${prettyBytes(size)}.`); if (watch) { logger.log(`\nWatching for changes...`); } } catch (error) { // See https://github.com/hapijs/joi/blob/v11.3.4/API.md#errors if (typeof error.annotate === 'function') { throw new Error( `${errors['config-validation-failed']}\n${error.annotate()}`); } logger.error(errors['workbox-build-runtime-error']); throw error; } }
javascript
{ "resource": "" }
q17532
getManifest
train
async function getManifest(config) { // This check needs to be done before validation, since the deprecated options // will be renamed. const deprecationWarnings = checkForDeprecatedOptions(config); const options = validate(config, getManifestSchema); const {manifestEntries, count, size, warnings} = await getFileManifestEntries(options); // Add in any deprecation warnings. warnings.push(...deprecationWarnings); return {manifestEntries, count, size, warnings}; }
javascript
{ "resource": "" }
q17533
Seeder
train
function Seeder(knex) { this.knex = knex; this.config = this.setConfig(knex.client.config.seeds); }
javascript
{ "resource": "" }
q17534
JoinClause
train
function JoinClause(table, type, schema) { this.schema = schema; this.table = table; this.joinType = type; this.and = this; this.clauses = []; }
javascript
{ "resource": "" }
q17535
yyyymmddhhmmss
train
function yyyymmddhhmmss() { const d = new Date(); return ( d.getFullYear().toString() + padDate(d.getMonth() + 1) + padDate(d.getDate()) + padDate(d.getHours()) + padDate(d.getMinutes()) + padDate(d.getSeconds()) ); }
javascript
{ "resource": "" }
q17536
SchemaBuilder
train
function SchemaBuilder(client) { this.client = client; this._sequence = []; if (client.config) { this._debug = client.config.debug; saveAsyncStack(this, 4); } }
javascript
{ "resource": "" }
q17537
Client
train
function Client(config = {}) { this.config = config; this.logger = new Logger(config); //Client is a required field, so throw error if it's not supplied. //If 'this.dialect' is set, then this is a 'super()' call, in which case //'client' does not have to be set as it's already assigned on the client prototype. if (this.dialect && !this.config.client) { this.logger.warn( `Using 'this.dialect' to identify the client is deprecated and support for it will be removed in the future. Please use configuration option 'client' instead.` ); } const dbClient = this.config.client || this.dialect; if (!dbClient) { throw new Error(`knex: Required configuration option 'client' is missing.`); } if (config.version) { this.version = config.version; } this.connectionSettings = cloneDeep(config.connection || {}); if (this.driverName && config.connection) { this.initializeDriver(); if (!config.pool || (config.pool && config.pool.max !== 0)) { this.initializePool(config); } } this.valueForUndefined = this.raw('DEFAULT'); if (config.useNullAsDefault) { this.valueForUndefined = null; } }
javascript
{ "resource": "" }
q17538
SQLite3_DDL
train
function SQLite3_DDL(client, tableCompiler, pragma, connection) { this.client = client; this.tableCompiler = tableCompiler; this.pragma = pragma; this.tableNameRaw = this.tableCompiler.tableNameRaw; this.alteredName = uniqueId('_knex_temp_alter'); this.connection = connection; this.formatter = client && client.config && client.config.wrapIdentifier ? client.config.wrapIdentifier : (value) => value; }
javascript
{ "resource": "" }
q17539
makeTransactor
train
function makeTransactor(trx, connection, trxClient) { const transactor = makeKnex(trxClient); transactor.withUserParams = () => { throw new Error( 'Cannot set user params on a transaction - it can only inherit params from main knex instance' ); }; transactor.isTransaction = true; transactor.userParams = trx.userParams || {}; transactor.transaction = function(container, options) { return trxClient.transaction(container, options, trx); }; transactor.savepoint = function(container, options) { return transactor.transaction(container, options); }; if (trx.client.transacting) { transactor.commit = (value) => trx.release(connection, value); transactor.rollback = (error) => trx.rollbackTo(connection, error); } else { transactor.commit = (value) => trx.commit(connection, value); transactor.rollback = (error) => trx.rollback(connection, error); } return transactor; }
javascript
{ "resource": "" }
q17540
makeTxClient
train
function makeTxClient(trx, client, connection) { const trxClient = Object.create(client.constructor.prototype); trxClient.version = client.version; trxClient.config = client.config; trxClient.driver = client.driver; trxClient.connectionSettings = client.connectionSettings; trxClient.transacting = true; trxClient.valueForUndefined = client.valueForUndefined; trxClient.logger = client.logger; trxClient.on('query', function(arg) { trx.emit('query', arg); client.emit('query', arg); }); trxClient.on('query-error', function(err, obj) { trx.emit('query-error', err, obj); client.emit('query-error', err, obj); }); trxClient.on('query-response', function(response, obj, builder) { trx.emit('query-response', response, obj, builder); client.emit('query-response', response, obj, builder); }); const _query = trxClient.query; trxClient.query = function(conn, obj) { const completed = trx.isCompleted(); return Promise.try(function() { if (conn !== connection) throw new Error('Invalid connection for transaction query.'); if (completed) completedError(trx, obj); return _query.call(trxClient, conn, obj); }); }; const _stream = trxClient.stream; trxClient.stream = function(conn, obj, stream, options) { const completed = trx.isCompleted(); return Promise.try(function() { if (conn !== connection) throw new Error('Invalid connection for transaction query.'); if (completed) completedError(trx, obj); return _stream.call(trxClient, conn, obj, stream, options); }); }; trxClient.acquireConnection = function() { return Promise.resolve(connection); }; trxClient.releaseConnection = function() { return Promise.resolve(); }; return trxClient; }
javascript
{ "resource": "" }
q17541
getTable
train
function getTable(trxOrKnex, tableName, schemaName) { return schemaName ? trxOrKnex(tableName).withSchema(schemaName) : trxOrKnex(tableName); }
javascript
{ "resource": "" }
q17542
validateMigrationList
train
function validateMigrationList(migrationSource, migrations) { const all = migrations[0]; const completed = migrations[1]; const diff = getMissingMigrations(migrationSource, completed, all); if (!isEmpty(diff)) { throw new Error( `The migration directory is corrupt, the following files are missing: ${diff.join( ', ' )}` ); } }
javascript
{ "resource": "" }
q17543
findAccessibleSync
train
function findAccessibleSync (logprefix, dir, candidates) { for (var next = 0; next < candidates.length; next++) { var candidate = path.resolve(dir, candidates[next]) try { var fd = fs.openSync(candidate, 'r') } catch (e) { // this candidate was not found or not readable, do nothing log.silly(logprefix, 'Could not open %s: %s', candidate, e.message) continue } fs.closeSync(fd) log.silly(logprefix, 'Found readable %s', candidate) return candidate } return undefined }
javascript
{ "resource": "" }
q17544
findPython
train
function findPython() { const SKIP=0, FAIL=1 const toCheck = [ { before: () => { if (!this.configPython) { this.addLog( 'Python is not set from command line or npm configuration') return SKIP } this.addLog('checking Python explicitly set from command line or ' + 'npm configuration') this.addLog('- "--python=" or "npm config get python" is ' + `"${this.configPython}"`) }, check: this.checkCommand, arg: this.configPython, }, { before: () => { if (!this.env.PYTHON) { this.addLog('Python is not set from environment variable PYTHON') return SKIP } this.addLog( 'checking Python explicitly set from environment variable PYTHON') this.addLog(`- process.env.PYTHON is "${this.env.PYTHON}"`) }, check: this.checkCommand, arg: this.env.PYTHON, }, { before: () => { this.addLog('checking if "python2" can be used') }, check: this.checkCommand, arg: 'python2', }, { before: () => { this.addLog('checking if "python" can be used') }, check: this.checkCommand, arg: 'python', }, { before: () => { if (!this.win) { // Everything after this is Windows specific return FAIL } this.addLog( 'checking if the py launcher can be used to find Python 2') }, check: this.checkPyLauncher, }, { before: () => { this.addLog( 'checking if Python 2 is installed in the default location') }, check: this.checkExecPath, arg: this.defaultLocation, }, ] function runChecks(err) { this.log.silly('runChecks: err = %j', err && err.stack || err) const check = toCheck.shift() if (!check) { return this.fail() } const before = check.before.apply(this) if (before === SKIP) { return runChecks.apply(this) } if (before === FAIL) { return this.fail() } const args = [ runChecks.bind(this) ] if (check.arg) { args.unshift(check.arg) } check.check.apply(this, args) } runChecks.apply(this) }
javascript
{ "resource": "" }
q17545
checkExecPath
train
function checkExecPath (execPath, errorCallback) { this.log.verbose(`- executing "${execPath}" to get version`) this.run(execPath, this.argsVersion, false, function (err, version) { // Possible outcomes: // - Error: executable can not be run (likely meaning the command wasn't // a Python executable and the previous command produced gibberish) // - Gibberish: somehow the last command produced an executable path, // this will fail when verifying the version // - Version of the Python executable if (err) { this.addLog(`- "${execPath}" could not be run`) return errorCallback(err) } this.addLog(`- version is "${version}"`) const range = semver.Range(this.semverRange) var valid = false try { valid = range.test(version) } catch (err) { this.log.silly('range.test() threw:\n%s', err.stack) this.addLog(`- "${execPath}" does not have a valid version`) this.addLog('- is it a Python executable?') return errorCallback(err) } if (!valid) { this.addLog(`- version is ${version} - should be ${this.semverRange}`) this.addLog('- THIS VERSION OF PYTHON IS NOT SUPPORTED') return errorCallback(new Error( `Found unsupported Python version ${version}`)) } this.succeed(execPath, version) }.bind(this)) }
javascript
{ "resource": "" }
q17546
run
train
function run(exec, args, shell, callback) { var env = extend({}, this.env) env.TERM = 'dumb' const opts = { env: env, shell: shell } this.log.silly('execFile: exec = %j', exec) this.log.silly('execFile: args = %j', args) this.log.silly('execFile: opts = %j', opts) try { this.execFile(exec, args, opts, execFileCallback.bind(this)) } catch (err) { this.log.silly('execFile: threw:\n%s', err.stack) return callback(err) } function execFileCallback(err, stdout, stderr) { this.log.silly('execFile result: err = %j', err && err.stack || err) this.log.silly('execFile result: stdout = %j', stdout) this.log.silly('execFile result: stderr = %j', stderr) if (err) { return callback(err) } const execPath = stdout.trim() callback(null, execPath) } }
javascript
{ "resource": "" }
q17547
cb
train
function cb (err) { if (cb.done) return cb.done = true if (err) { log.warn('install', 'got an error, rolling back install') // roll-back the install if anything went wrong gyp.commands.remove([ release.versionDir ], function () { callback(err) }) } else { callback(null, release.version) } }
javascript
{ "resource": "" }
q17548
afterTarball
train
function afterTarball () { if (badDownload) return if (extractCount === 0) { return cb(new Error('There was a fatal problem while downloading/extracting the tarball')) } log.verbose('tarball', 'done parsing tarball') var async = 0 if (win) { // need to download node.lib async++ downloadNodeLib(deref) } // write the "installVersion" file async++ var installVersionPath = path.resolve(devDir, 'installVersion') fs.writeFile(installVersionPath, gyp.package.installVersion + '\n', deref) // Only download SHASUMS.txt if not using tarPath override if (!tarPath) { // download SHASUMS.txt async++ downloadShasums(deref) } if (async === 0) { // no async tasks required cb() } function deref (err) { if (err) return cb(err) async-- if (!async) { log.verbose('download contents checksum', JSON.stringify(contentShasums)) // check content shasums for (var k in contentShasums) { log.verbose('validating download checksum for ' + k, '(%s == %s)', contentShasums[k], expectShasums[k]) if (contentShasums[k] !== expectShasums[k]) { cb(new Error(k + ' local checksum ' + contentShasums[k] + ' not match remote ' + expectShasums[k])) return } } cb() } } }
javascript
{ "resource": "" }
q17549
loadConfigGypi
train
function loadConfigGypi () { var configPath = path.resolve('build', 'config.gypi') fs.readFile(configPath, 'utf8', function (err, data) { if (err) { if (err.code == 'ENOENT') { callback(new Error('You must run `node-gyp configure` first!')) } else { callback(err) } return } config = JSON.parse(data.replace(/\#.+\n/, '')) // get the 'arch', 'buildType', and 'nodeDir' vars from the config buildType = config.target_defaults.default_configuration arch = config.variables.target_arch nodeDir = config.variables.nodedir if ('debug' in gyp.opts) { buildType = gyp.opts.debug ? 'Debug' : 'Release' } if (!buildType) { buildType = 'Release' } log.verbose('build type', buildType) log.verbose('architecture', arch) log.verbose('node dev dir', nodeDir) if (win) { findSolutionFile() } else { doWhich() } }) }
javascript
{ "resource": "" }
q17550
findMsbuild
train
function findMsbuild () { log.verbose('could not find "msbuild.exe" in PATH - finding location in registry') var notfoundErr = 'Can\'t find "msbuild.exe". Do you have Microsoft Visual Studio C++ 2008+ installed?' var cmd = 'reg query "HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions" /s' if (process.arch !== 'ia32') cmd += ' /reg:32' exec(cmd, function (err, stdout) { if (err) { return callback(new Error(err.message + '\n' + notfoundErr)) } var reVers = /ToolsVersions\\([^\\]+)$/i , rePath = /\r\n[ \t]+MSBuildToolsPath[ \t]+REG_SZ[ \t]+([^\r]+)/i , msbuilds = [] , r , msbuildPath stdout.split('\r\n\r\n').forEach(function(l) { if (!l) return l = l.trim() if (r = reVers.exec(l.substring(0, l.indexOf('\r\n')))) { var ver = parseFloat(r[1], 10) if (ver >= 3.5) { if (r = rePath.exec(l)) { msbuilds.push({ version: ver, path: r[1] }) } } } }) msbuilds.sort(function (x, y) { return (x.version < y.version ? -1 : 1) }) ;(function verifyMsbuild () { if (!msbuilds.length) return callback(new Error(notfoundErr)) msbuildPath = path.resolve(msbuilds.pop().path, 'msbuild.exe') fs.stat(msbuildPath, function (err) { if (err) { if (err.code == 'ENOENT') { if (msbuilds.length) { return verifyMsbuild() } else { callback(new Error(notfoundErr)) } } else { callback(err) } return } command = msbuildPath doBuild() }) })() }) }
javascript
{ "resource": "" }
q17551
doBuild
train
function doBuild () { // Enable Verbose build var verbose = log.levels[log.level] <= log.levels.verbose if (!win && verbose) { argv.push('V=1') } if (win && !verbose) { argv.push('/clp:Verbosity=minimal') } if (win) { // Turn off the Microsoft logo on Windows argv.push('/nologo') } // Specify the build type, Release by default if (win) { // Convert .gypi config target_arch to MSBuild /Platform // Since there are many ways to state '32-bit Intel', default to it. // N.B. msbuild's Condition string equality tests are case-insensitive. var archLower = arch.toLowerCase() var p = archLower === 'x64' ? 'x64' : (archLower === 'arm' ? 'ARM' : (archLower === 'arm64' ? 'ARM64' : 'Win32')) argv.push('/p:Configuration=' + buildType + ';Platform=' + p) if (jobs) { var j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('/m:' + j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('/m:' + require('os').cpus().length) } } } else { argv.push('BUILDTYPE=' + buildType) // Invoke the Makefile in the 'build' dir. argv.push('-C') argv.push('build') if (jobs) { var j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('--jobs') argv.push(j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('--jobs') argv.push(require('os').cpus().length) } } } if (win) { // did the user specify their own .sln file? var hasSln = argv.some(function (arg) { return path.extname(arg) == '.sln' }) if (!hasSln) { argv.unshift(gyp.opts.solution || guessedSolution) } } var proc = gyp.spawn(command, argv) proc.on('exit', onExit) }
javascript
{ "resource": "" }
q17552
inflateOnData
train
function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if ( this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload ) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError('Max payload size exceeded'); this[kError][kStatusCode] = 1009; this.removeListener('data', inflateOnData); this.reset(); }
javascript
{ "resource": "" }
q17553
error
train
function error(ErrorCtor, message, prefix, statusCode) { const err = new ErrorCtor( prefix ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err, error); err[kStatusCode] = statusCode; return err; }
javascript
{ "resource": "" }
q17554
concat
train
function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); let offset = 0; for (let i = 0; i < list.length; i++) { const buf = list[i]; buf.copy(target, offset); offset += buf.length; } return target; }
javascript
{ "resource": "" }
q17555
_mask
train
function _mask(source, mask, output, offset, length) { for (let i = 0; i < length; i++) { output[offset + i] = source[i] ^ mask[i & 3]; } }
javascript
{ "resource": "" }
q17556
_unmask
train
function _unmask(buffer, mask) { // Required until https://github.com/nodejs/node/issues/9006 is resolved. const length = buffer.length; for (let i = 0; i < length; i++) { buffer[i] ^= mask[i & 3]; } }
javascript
{ "resource": "" }
q17557
toArrayBuffer
train
function toArrayBuffer(buf) { if (buf.byteLength === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); }
javascript
{ "resource": "" }
q17558
toBuffer
train
function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; let buf; if (data instanceof ArrayBuffer) { buf = Buffer.from(data); } else if (ArrayBuffer.isView(data)) { buf = viewToBuffer(data); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; }
javascript
{ "resource": "" }
q17559
viewToBuffer
train
function viewToBuffer(view) { const buf = Buffer.from(view.buffer); if (view.byteLength !== view.buffer.byteLength) { return buf.slice(view.byteOffset, view.byteOffset + view.byteLength); } return buf; }
javascript
{ "resource": "" }
q17560
abortHandshake
train
function abortHandshake(socket, code, message, headers) { if (socket.writable) { message = message || STATUS_CODES[code]; headers = { Connection: 'close', 'Content-type': 'text/html', 'Content-Length': Buffer.byteLength(message), ...headers }; socket.write( `HTTP/1.1 ${code} ${STATUS_CODES[code]}\r\n` + Object.keys(headers) .map((h) => `${h}: ${headers[h]}`) .join('\r\n') + '\r\n\r\n' + message ); } socket.removeListener('error', socketOnError); socket.destroy(); }
javascript
{ "resource": "" }
q17561
push
train
function push(dest, name, elem) { if (dest[name] === undefined) dest[name] = [elem]; else dest[name].push(elem); }
javascript
{ "resource": "" }
q17562
format
train
function format(extensions) { return Object.keys(extensions) .map((extension) => { let configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations .map((params) => { return [extension] .concat( Object.keys(params).map((k) => { let values = params[k]; if (!Array.isArray(values)) values = [values]; return values .map((v) => (v === true ? k : `${k}=${v}`)) .join('; '); }) ) .join('; '); }) .join(', '); }) .join(', '); }
javascript
{ "resource": "" }
q17563
tlsConnect
train
function tlsConnect(options) { options.path = undefined; options.servername = options.servername || options.host; return tls.connect(options); }
javascript
{ "resource": "" }
q17564
abortHandshake
train
function abortHandshake(websocket, stream, message) { websocket.readyState = WebSocket.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake); if (stream.setHeader) { stream.abort(); stream.once('abort', websocket.emitClose.bind(websocket)); websocket.emit('error', err); } else { stream.destroy(err); stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('close', websocket.emitClose.bind(websocket)); } }
javascript
{ "resource": "" }
q17565
receiverOnConclude
train
function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket._socket.resume(); websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (code === 1005) websocket.close(); else websocket.close(code, reason); }
javascript
{ "resource": "" }
q17566
receiverOnError
train
function receiverOnError(err) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket.readyState = WebSocket.CLOSING; websocket._closeCode = err[kStatusCode]; websocket.emit('error', err); websocket._socket.destroy(); }
javascript
{ "resource": "" }
q17567
receiverOnPing
train
function receiverOnPing(data) { const websocket = this[kWebSocket]; websocket.pong(data, !websocket._isServer, NOOP); websocket.emit('ping', data); }
javascript
{ "resource": "" }
q17568
socketOnClose
train
function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener('close', socketOnClose); this.removeListener('end', socketOnEnd); websocket.readyState = WebSocket.CLOSING; // // The close frame might not have been received or the `'end'` event emitted, // for example, if the socket was destroyed due to an error. Ensure that the // `receiver` stream is closed after writing any remaining buffered data to // it. If the readable side of the socket is in flowing mode then there is no // buffered data as everything has been already written and `readable.read()` // will return `null`. If instead, the socket is paused, any possible buffered // data will be read as a single chunk and emitted synchronously in a single // `'data'` event. // websocket._socket.read(); websocket._receiver.end(); this.removeListener('data', socketOnData); this[kWebSocket] = undefined; clearTimeout(websocket._closeTimer); if ( websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ) { websocket.emitClose(); } else { websocket._receiver.on('error', receiverOnFinish); websocket._receiver.on('finish', receiverOnFinish); } }
javascript
{ "resource": "" }
q17569
socketOnEnd
train
function socketOnEnd() { const websocket = this[kWebSocket]; websocket.readyState = WebSocket.CLOSING; websocket._receiver.end(); this.end(); }
javascript
{ "resource": "" }
q17570
socketOnError
train
function socketOnError() { const websocket = this[kWebSocket]; this.removeListener('error', socketOnError); this.on('error', NOOP); websocket.readyState = WebSocket.CLOSING; this.destroy(); }
javascript
{ "resource": "" }
q17571
all
train
function all(array, pred) { for (let idx = 0, len = array.length; idx < len; idx++) { if (!pred(array[idx])) { return false; } } return true; }
javascript
{ "resource": "" }
q17572
contains
train
function contains(array, item) { if (array && array.length && item) { return array.indexOf(item) !== -1; } return false; }
javascript
{ "resource": "" }
q17573
sum
train
function sum(array, fn) { fn = fn || func.self; return array.reduce(function(memo, v) { return memo + fn(v); }, 0); }
javascript
{ "resource": "" }
q17574
from
train
function from(collection) { const result = []; const length = collection.length; let idx = -1; while (++idx < length) { result[idx] = collection[idx]; } return result; }
javascript
{ "resource": "" }
q17575
compact
train
function compact(array) { const aResult = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (array[idx]) { aResult.push(array[idx]); } } return aResult; }
javascript
{ "resource": "" }
q17576
unique
train
function unique(array) { const results = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (!contains(results, array[idx])) { results.push(array[idx]); } } return results; }
javascript
{ "resource": "" }
q17577
prev
train
function prev(array, item) { if (array && array.length && item) { const idx = array.indexOf(item); return idx === -1 ? null : array[idx - 1]; } return null; }
javascript
{ "resource": "" }
q17578
listDescendant
train
function listDescendant(node, pred) { const descendants = []; pred = pred || func.ok; // start DFS(depth first search) with node (function fnWalk(current) { if (node !== current && pred(current)) { descendants.push(current); } for (let idx = 0, len = current.childNodes.length; idx < len; idx++) { fnWalk(current.childNodes[idx]); } })(node); return descendants; }
javascript
{ "resource": "" }
q17579
isLeftEdgeOf
train
function isLeftEdgeOf(node, ancestor) { while (node && node !== ancestor) { if (position(node) !== 0) { return false; } node = node.parentNode; } return true; }
javascript
{ "resource": "" }
q17580
prevPoint
train
function prevPoint(point, isSkipInnerOffset) { let node; let offset; if (point.offset === 0) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node); } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset - 1]; offset = nodeLength(node); } else { node = point.node; offset = isSkipInnerOffset ? 0 : point.offset - 1; } return { node: node, offset: offset, }; }
javascript
{ "resource": "" }
q17581
isSamePoint
train
function isSamePoint(pointA, pointB) { return pointA.node === pointB.node && pointA.offset === pointB.offset; }
javascript
{ "resource": "" }
q17582
textRangeToPoint
train
function textRangeToPoint(textRange, isStart) { let container = textRange.parentElement(); let offset; const tester = document.body.createTextRange(); let prevContainer; const childNodes = lists.from(container.childNodes); for (offset = 0; offset < childNodes.length; offset++) { if (dom.isText(childNodes[offset])) { continue; } tester.moveToElementText(childNodes[offset]); if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; } prevContainer = childNodes[offset]; } if (offset !== 0 && dom.isText(childNodes[offset - 1])) { const textRangeStart = document.body.createTextRange(); let curTextNode = null; textRangeStart.moveToElementText(prevContainer || container); textRangeStart.collapse(!prevContainer); curTextNode = prevContainer ? prevContainer.nextSibling : container.firstChild; const pointTester = textRange.duplicate(); pointTester.setEndPoint('StartToStart', textRangeStart); let textCount = pointTester.text.replace(/[\r\n]/g, '').length; while (textCount > curTextNode.nodeValue.length && curTextNode.nextSibling) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } // [workaround] enforce IE to re-reference curTextNode, hack const dummy = curTextNode.nodeValue; // eslint-disable-line if (isStart && curTextNode.nextSibling && dom.isText(curTextNode.nextSibling) && textCount === curTextNode.nodeValue.length) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } container = curTextNode; offset = textCount; } return { cont: container, offset: offset, }; }
javascript
{ "resource": "" }
q17583
isFontInstalled
train
function isFontInstalled(fontName) { const testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS'; const testText = 'mmmmmmmmmmwwwww'; const testSize = '200px'; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); context.font = testSize + " '" + testFontName + "'"; const originalWidth = context.measureText(testText).width; context.font = testSize + " '" + fontName + "', '" + testFontName + "'"; const width = context.measureText(testText).width; return originalWidth !== width; }
javascript
{ "resource": "" }
q17584
mapValues
train
function mapValues(fn, obj) { return keys(obj).reduce(function(acc, key) { acc[key] = fn(obj[key]); return acc; }, {}); }
javascript
{ "resource": "" }
q17585
getOffsetElement
train
function getOffsetElement(el) { return el ? 'offsetTop' in el ? el : getOffsetElement(el.parentNode) : document.body; }
javascript
{ "resource": "" }
q17586
root
train
function root (options$$1, next) { var url = next(options$$1); if (isString(options$$1.root) && !/^(https?:)?\//.test(url)) { url = trimEnd(options$$1.root, '/') + '/' + url; } return url; }
javascript
{ "resource": "" }
q17587
query
train
function query (options$$1, next) { var urlParams = Object.keys(Url.options.params), query = {}, url = next(options$$1); each(options$$1.params, function (value, key) { if (urlParams.indexOf(key) === -1) { query[key] = value; } }); query = Url.params(query); if (query) { url += (url.indexOf('?') == -1 ? '?' : '&') + query; } return url; }
javascript
{ "resource": "" }
q17588
form
train
function form (request) { if (isFormData(request.body)) { request.headers.delete('Content-Type'); } else if (isObject(request.body) && request.emulateJSON) { request.body = Url.params(request.body); request.headers.set('Content-Type', 'application/x-www-form-urlencoded'); } }
javascript
{ "resource": "" }
q17589
json
train
function json (request) { var type = request.headers.get('Content-Type') || ''; if (isObject(request.body) && type.indexOf('application/json') === 0) { request.body = JSON.stringify(request.body); } return function (response) { return response.bodyText ? when(response.text(), function (text) { var type = response.headers.get('Content-Type') || ''; if (type.indexOf('application/json') === 0 || isJson(text)) { try { response.body = JSON.parse(text); } catch (e) { response.body = null; } } else { response.body = text; } return response; }) : response; }; }
javascript
{ "resource": "" }
q17590
method
train
function method (request) { if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) { request.headers.set('X-HTTP-Method-Override', request.method); request.method = 'POST'; } }
javascript
{ "resource": "" }
q17591
header
train
function header (request) { var headers = assign({}, Http.headers.common, !request.crossOrigin ? Http.headers.custom : {}, Http.headers[toLower(request.method)] ); each(headers, function (value, name) { if (!request.headers.has(name)) { request.headers.set(name, value); } }); }
javascript
{ "resource": "" }
q17592
Client
train
function Client (context) { var reqHandlers = [sendRequest], resHandlers = []; if (!isObject(context)) { context = null; } function Client(request) { while (reqHandlers.length) { var handler = reqHandlers.pop(); if (isFunction(handler)) { var response = (void 0), next = (void 0); response = handler.call(context, request, function (val) { return next = val; }) || next; if (isObject(response)) { return new PromiseObj(function (resolve, reject) { resHandlers.forEach(function (handler) { response = when(response, function (response) { return handler.call(context, response) || response; }, reject); }); when(response, resolve, reject); }, context); } if (isFunction(response)) { resHandlers.unshift(response); } } else { warn(("Invalid interceptor of type " + (typeof handler) + ", must be a function")); } } } Client.use = function (handler) { reqHandlers.push(handler); }; return Client; }
javascript
{ "resource": "" }
q17593
Headers
train
function Headers(headers) { var this$1 = this; this.map = {}; each(headers, function (value, name) { return this$1.append(name, value); }); }
javascript
{ "resource": "" }
q17594
Response
train
function Response(body, ref) { var url = ref.url; var headers = ref.headers; var status = ref.status; var statusText = ref.statusText; this.url = url; this.ok = status >= 200 && status < 300; this.status = status || 0; this.statusText = statusText || ''; this.headers = new Headers(headers); this.body = body; if (isString(body)) { this.bodyText = body; } else if (isBlob(body)) { this.bodyBlob = body; if (isBlobText(body)) { this.bodyText = blobText(body); } } }
javascript
{ "resource": "" }
q17595
Request
train
function Request(options$$1) { this.body = null; this.params = {}; assign(this, options$$1, { method: toUpper(options$$1.method || 'GET') }); if (!(this.headers instanceof Headers)) { this.headers = new Headers(this.headers); } }
javascript
{ "resource": "" }
q17596
Resource
train
function Resource(url, params, actions, options$$1) { var self = this || {}, resource = {}; actions = assign({}, Resource.actions, actions ); each(actions, function (action, name) { action = merge({url: url, params: assign({}, params)}, options$$1, action); resource[name] = function () { return (self.$http || Http)(opts(action, arguments)); }; }); return resource; }
javascript
{ "resource": "" }
q17597
plugin
train
function plugin(Vue) { if (plugin.installed) { return; } Util(Vue); Vue.url = Url; Vue.http = Http; Vue.resource = Resource; Vue.Promise = PromiseObj; Object.defineProperties(Vue.prototype, { $url: { get: function get() { return options(Vue.url, this, this.$options.url); } }, $http: { get: function get() { return options(Vue.http, this, this.$options.http); } }, $resource: { get: function get() { return Vue.resource.bind(this); } }, $promise: { get: function get() { var this$1 = this; return function (executor) { return new Vue.Promise(executor, this$1); }; } } }); }
javascript
{ "resource": "" }
q17598
onLocationChange
train
async function onLocationChange(location, action) { // Remember the latest scroll position for the previous location scrollPositionsHistory[currentLocation.key] = { scrollX: window.pageXOffset, scrollY: window.pageYOffset, }; // Delete stored scroll position for next page if any if (action === 'PUSH') { delete scrollPositionsHistory[location.key]; } currentLocation = location; const isInitialRender = !action; try { context.pathname = location.pathname; context.query = queryString.parse(location.search); // Traverses the list of routes in the order they are defined until // it finds the first route that matches provided URL path string // and whose action method returns anything other than `undefined`. const route = await router.resolve(context); // Prevent multiple page renders during the routing process if (currentLocation.key !== location.key) { return; } if (route.redirect) { history.replace(route.redirect); return; } const renderReactApp = isInitialRender ? ReactDOM.hydrate : ReactDOM.render; appInstance = renderReactApp( <App context={context}>{route.component}</App>, container, () => { if (isInitialRender) { // Switch off the native scroll restoration behavior and handle it manually // https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration if (window.history && 'scrollRestoration' in window.history) { window.history.scrollRestoration = 'manual'; } const elem = document.getElementById('css'); if (elem) elem.parentNode.removeChild(elem); return; } document.title = route.title; updateMeta('description', route.description); // Update necessary tags in <head> at runtime here, ie: // updateMeta('keywords', route.keywords); // updateCustomMeta('og:url', route.canonicalUrl); // updateCustomMeta('og:image', route.imageUrl); // updateLink('canonical', route.canonicalUrl); // etc. let scrollX = 0; let scrollY = 0; const pos = scrollPositionsHistory[location.key]; if (pos) { scrollX = pos.scrollX; scrollY = pos.scrollY; } else { const targetHash = location.hash.substr(1); if (targetHash) { const target = document.getElementById(targetHash); if (target) { scrollY = window.pageYOffset + target.getBoundingClientRect().top; } } } // Restore the scroll position if it was saved into the state // or scroll to the given #hash anchor // or scroll to top of the page window.scrollTo(scrollX, scrollY); // Google Analytics tracking. Don't send 'pageview' event after // the initial rendering, as it was already sent if (window.ga) { window.ga('send', 'pageview', createPath(location)); } }, ); } catch (error) { if (__DEV__) { throw error; } console.error(error); // Do a full page reload if error occurs during client-side navigation if (!isInitialRender && currentLocation.key === location.key) { console.error('RSK will reload your page after error'); window.location.reload(); } } }
javascript
{ "resource": "" }
q17599
involuteXbez
train
function involuteXbez(t) { // map t (0 <= t <= 1) onto x (where -1 <= x <= 1) var x = t*2-1; //map theta (where ts <= theta <= te) from x (-1 <=x <= 1) var theta = x*(te-ts)/2 + (ts + te)/2; return Rb*(Math.cos(theta)+theta*Math.sin(theta)); }
javascript
{ "resource": "" }