_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q21200
doBidderSync
train
function doBidderSync(type, url, bidder, done) { if (!url) { utils.logError(`No sync url for bidder "${bidder}": ${url}`); done(); } else if (type === 'image' || type === 'redirect') { utils.logMessage(`Invoking image pixel user sync for bidder: "${bidder}"`); utils.triggerPixel(url, done); } else if (type == 'iframe') { utils.logMessage(`Invoking iframe user sync for bidder: "${bidder}"`); utils.insertUserSyncIframe(url, done); } else { utils.logError(`User sync type "${type}" not supported for bidder: "${bidder}"`); done(); } }
javascript
{ "resource": "" }
q21201
doClientSideSyncs
train
function doClientSideSyncs(bidders) { bidders.forEach(bidder => { let clientAdapter = adapterManager.getBidAdapter(bidder); if (clientAdapter && clientAdapter.registerSyncs) { clientAdapter.registerSyncs([]); } }); }
javascript
{ "resource": "" }
q21202
isModuleDirectory
train
function isModuleDirectory(filePath) { try { const manifestPath = path.join(filePath, MANIFEST); if (fs.statSync(manifestPath).isFile()) { const module = require(manifestPath); return module && module.main; } } catch (error) {} }
javascript
{ "resource": "" }
q21203
buildUrlFromAdserverUrlComponents
train
function buildUrlFromAdserverUrlComponents(components, bid, options) { const descriptionUrl = getDescriptionUrl(bid, components, 'search'); if (descriptionUrl) { components.search.description_url = descriptionUrl; } const encodedCustomParams = getCustParams(bid, options); components.search.cust_params = (components.search.cust_params) ? components.search.cust_params + '%26' + encodedCustomParams : encodedCustomParams; return buildUrl(components); }
javascript
{ "resource": "" }
q21204
getDescriptionUrl
train
function getDescriptionUrl(bid, components, prop) { if (config.getConfig('cache.url')) { return; } if (!deepAccess(components, `${prop}.description_url`)) { const vastUrl = bid && bid.vastUrl; if (vastUrl) { return encodeURIComponent(vastUrl); } } else { logError(`input cannnot contain description_url`); } }
javascript
{ "resource": "" }
q21205
getCustParams
train
function getCustParams(bid, options) { const adserverTargeting = (bid && bid.adserverTargeting) || {}; let allTargetingData = {}; const adUnit = options && options.adUnit; if (adUnit) { let allTargeting = targeting.getAllTargeting(adUnit.code); allTargetingData = (allTargeting) ? allTargeting[adUnit.code] : {}; } const optCustParams = deepAccess(options, 'params.cust_params'); let customParams = Object.assign({}, // Why are we adding standard keys here ? Refer https://github.com/prebid/Prebid.js/issues/3664 { hb_uuid: bid && bid.videoCacheKey }, // hb_uuid will be deprecated and replaced by hb_cache_id { hb_cache_id: bid && bid.videoCacheKey }, allTargetingData, adserverTargeting, optCustParams, ); return encodeURIComponent(formatQS(customParams)); }
javascript
{ "resource": "" }
q21206
readValue
train
function readValue(name) { let value; if (pubcidConfig.typeEnabled === COOKIE) { value = getCookie(name); } else if (pubcidConfig.typeEnabled === LOCAL_STORAGE) { value = getStorageItem(name); if (!value) { value = getCookie(name); } } if (value === 'undefined' || value === 'null') { return null; } return value; }
javascript
{ "resource": "" }
q21207
writeValue
train
function writeValue(name, value, expInterval) { if (name && value) { if (pubcidConfig.typeEnabled === COOKIE) { setCookie(name, value, expInterval); } else if (pubcidConfig.typeEnabled === LOCAL_STORAGE) { setStorageItem(name, value, expInterval); } } }
javascript
{ "resource": "" }
q21208
train
function () { next = false; // add listener to all next steps to provide next() functionality event.dispatcher.on(event.step.after, () => { recorder.add('Start next pause session', () => { if (!next) return; return pauseSession(); }); }); recorder.add('Start new session', pauseSession); }
javascript
{ "resource": "" }
q21209
convertColorToRGBA
train
function convertColorToRGBA(color) { const cstr = `${color}`.toLowerCase().trim() || ''; if (!/^rgba?\(.+?\)$/.test(cstr)) { // Convert both color names and hex colors to rgba const hexColor = convertColorNameToHex(color); return convertHexColorToRgba(hexColor); } // Convert rgb to rgba const channels = cstr.match(/([\-0-9.]+)/g) || []; switch (channels.length) { case 3: // Convert rgb to rgba return `rgba(${channels.join(', ')}, 1)`; case 4: // Format rgba return `rgba(${channels.join(', ')})`; default: // Unexpected color format. Leave it untouched (let the user handle it) return color; } }
javascript
{ "resource": "" }
q21210
replaceValue
train
function replaceValue(obj, key, value) { if (!obj) return; if (obj instanceof Array) { for (const i in obj) { replaceValue(obj[i], key, value); } } if (obj[key]) obj[key] = value; if (typeof obj === 'object' && obj !== null) { const children = Object.keys(obj); for (let childIndex = 0; childIndex < children.length; childIndex++) { replaceValue(obj[children[childIndex]], key, value); } } return obj; }
javascript
{ "resource": "" }
q21211
AssertionFailedError
train
function AssertionFailedError(params, template) { this.params = params; this.template = template; // this.message = "AssertionFailedError"; let stack = new Error().stack; // this.showDiff = true; stack = stack ? stack.split('\n').filter(line => // @todo cut assert things nicer line.indexOf('lib/assert') < 0).join('\n') : ''; this.showDiff = true; this.actual = this.params.actual; this.expected = this.params.expected; this.inspect = () => { const params = this.params || {}; const msg = params.customMessage || ''; return msg + subs(this.template, params); }; this.cliMessage = () => this.inspect(); }
javascript
{ "resource": "" }
q21212
onlyForApps
train
function onlyForApps(expectedPlatform) { const stack = new Error().stack || ''; const re = /Appium.(\w+)/g; const caller = stack.split('\n')[2].trim(); const m = re.exec(caller); if (!m) { throw new Error(`Invalid caller ${caller}`); } const callerName = m[1] || m[2]; if (!expectedPlatform) { if (!this.platform) { throw new Error(`${callerName} method can be used only with apps`); } } else if (this.platform !== expectedPlatform.toLowerCase()) { throw new Error(`${callerName} method can be used only with ${expectedPlatform} apps`); } }
javascript
{ "resource": "" }
q21213
train
function(done) { gzip(info.filePath, info.gzFilePath, function() { info.gzTime = Date.now(); // Open and read the size of the minified+gzip output readSize(info.gzFilePath, function(size) { info.gzSize = size; done(); }); }); }
javascript
{ "resource": "" }
q21214
train
function(done) { readBuffer(info.filePath, function(data) { lzma.compress(data, 1, function(result, error) { if (error) { throw error; } writeBuffer(info.lzFilePath, new Buffer(result), function() { info.lzTime = Date.now(); // Open and read the size of the minified+lzma output readSize(info.lzFilePath, function(size) { info.lzSize = size; done(); }); }); }); }); }
javascript
{ "resource": "" }
q21215
trimTrailingWhitespace
train
function trimTrailingWhitespace(index, nextTag) { for (var endTag = null; index >= 0 && _canTrimWhitespace(endTag); index--) { var str = buffer[index]; var match = str.match(/^<\/([\w:-]+)>$/); if (match) { endTag = match[1]; } else if (/>$/.test(str) || (buffer[index] = collapseWhitespaceSmart(str, null, nextTag, options))) { break; } } }
javascript
{ "resource": "" }
q21216
squashTrailingWhitespace
train
function squashTrailingWhitespace(nextTag) { var charsIndex = buffer.length - 1; if (buffer.length > 1) { var item = buffer[buffer.length - 1]; if (/^(?:<!|$)/.test(item) && item.indexOf(uidIgnore) === -1) { charsIndex--; } } trimTrailingWhitespace(charsIndex, nextTag); }
javascript
{ "resource": "" }
q21217
stripLoaderPrefix
train
function stripLoaderPrefix(str) { if (typeof str === 'string') { str = str.replace( /(?:(\()|(^|\b|@))(\.\/~|\.{0,2}\/(?:[^\s]+\/)?node_modules)\/\w+-loader(\/[^?!]+)?(\?\?[\w_.-]+|\?({[\s\S]*?})?)?!/g, '$1' ); str = str.replace(/(\.?\.?(?:\/[^/ ]+)+)\s+\(\1\)/g, '$1'); str = replaceAll(str, process.cwd(), '.'); return str; } return str; }
javascript
{ "resource": "" }
q21218
intersect
train
function intersect(a, b, not) { return a.filter((c) => { const index = ~indexOfDeclaration(b, c); return not ? !index : index; }); }
javascript
{ "resource": "" }
q21219
isSupportedCached
train
function isSupportedCached(feature, browsers) { const key = JSON.stringify({ feature, browsers }); let result = isSupportedCache[key]; if (!result) { result = isSupported(feature, browsers); isSupportedCache[key] = result; } return result; }
javascript
{ "resource": "" }
q21220
normalize
train
function normalize(values) { if (values[0].toLowerCase() === auto) { return values[1]; } if (values[1].toLowerCase() === auto) { return values[0]; } if ( values[0].toLowerCase() === inherit && values[1].toLowerCase() === inherit ) { return inherit; } return values.join(' '); }
javascript
{ "resource": "" }
q21221
filterFont
train
function filterFont({ atRules, values }) { values = uniqs(values); atRules.forEach((r) => { const families = r.nodes.filter(({ prop }) => prop === 'font-family'); // Discard the @font-face if it has no font-family if (!families.length) { return r.remove(); } families.forEach((family) => { if (!hasFont(family.value.toLowerCase(), values)) { r.remove(); } }); }); }
javascript
{ "resource": "" }
q21222
SessionStrategy
train
function SessionStrategy(options, deserializeUser) { if (typeof options == 'function') { deserializeUser = options; options = undefined; } options = options || {}; Strategy.call(this); this.name = 'session'; this._deserializeUser = deserializeUser; }
javascript
{ "resource": "" }
q21223
Authenticator
train
function Authenticator() { this._key = 'passport'; this._strategies = {}; this._serializers = []; this._deserializers = []; this._infoTransformers = []; this._framework = null; this._userProperty = 'user'; this.init(); }
javascript
{ "resource": "" }
q21224
getHelpContents
train
async function getHelpContents(args, output) { if ('!' in args) { return getAllCommands(process.stdout); } if (args._.length == 0) { return getGeneralHelpContents(output); } else if (args._.length == 1) { return getVerbHelp(args._[0], output); } else if (args._.length >= 2) { const operation = getOperation(args._[0], args._[1]); if (operation) { output.write(`${operation.description}\n\n`); output.write(`Usage:\n${chalk.cyan.bold(operation.command)}\n\n`); return getHelpContentsForOperation(operation, output); } else { return getVerbHelp(args._[0], output); } } return getGeneralHelpContents(output); }
javascript
{ "resource": "" }
q21225
getGeneralHelpContents
train
function getGeneralHelpContents() { let options = { head: chalk.bold(`Available actions are:`), table: [ [chalk.cyan.bold("add"), "add a resource"], [chalk.cyan.bold("clone"), "clone a resource"], [chalk.cyan.bold("delete"), "delete a resource"], [chalk.cyan.bold("export"), "export resources"], [chalk.cyan.bold("package"), "package resources"], [chalk.cyan.bold("get"), "get a resource"], [chalk.cyan.bold("import"), "import resources"], [chalk.cyan.bold('init'), 'Initializes the .luisrc file with settings specific to your LUIS instance'], [chalk.cyan.bold("list"), "list resources"], [chalk.cyan.bold("publish"), "publish resource"], [chalk.cyan.bold("query"), "query model for prediction"], [chalk.cyan.bold("rename"), "change the name of a resource"], [chalk.cyan.bold("set"), "change the .luisrc settings"], [chalk.cyan.bold("suggest"), "suggest resources"], [chalk.cyan.bold("train"), "train resource"], [chalk.cyan.bold("update"), "update resources"] ] }; let sections = []; sections.push(options); sections.push(configSection); sections.push(globalArgs); return sections; }
javascript
{ "resource": "" }
q21226
getAllCommands
train
function getAllCommands() { let resourceTypes = []; let tables = {}; operations.forEach((operation) => { let opCategory = operation.target[0]; if (resourceTypes.indexOf(opCategory) < 0) { resourceTypes.push(opCategory); tables[opCategory] = []; } tables[opCategory].push([chalk.cyan.bold(operation.command), operation.description]); }); resourceTypes.sort(); let sections = []; for (let resourceType of resourceTypes) { tables[resourceType].sort((a, b) => a[0].localeCompare(b[0])); sections.push({ head: chalk.white.bold(resourceType), table: tables[resourceType] }); } return sections; }
javascript
{ "resource": "" }
q21227
getFileInput
train
async function getFileInput(args) { if (typeof args.in !== 'string') { return null; } // Let any errors fall through to the runProgram() promise return JSON.parse(await txtfile.read(path.resolve(args.in))); }
javascript
{ "resource": "" }
q21228
composeConfig
train
async function composeConfig() { const { LUIS_APP_ID, LUIS_AUTHORING_KEY, LUIS_VERSION_ID, LUIS_REGION } = process.env; const { appId: args_appId, authoringKey: args_authoringKey, versionId: args_versionId, region: args_region } = args; let luisrcJson = {}; let config; try { await fs.access(path.join(process.cwd(), '.luisrc'), fs.R_OK); luisrcJson = JSON.parse(await txtfile.read(path.join(process.cwd(), '.luisrc'))); } catch (e) { // Do nothing } finally { config = { appId: (args_appId || luisrcJson.appId || LUIS_APP_ID), authoringKey: (args_authoringKey || luisrcJson.authoringKey || LUIS_AUTHORING_KEY), versionId: (args_versionId || luisrcJson.versionId || LUIS_VERSION_ID), region: (args_region || luisrcJson.region || LUIS_REGION) }; } return config; }
javascript
{ "resource": "" }
q21229
composeConfig
train
async function composeConfig() { const {QNAMAKER_SUBSCRIPTION_KEY, QNAMAKER_HOSTNAME, QNAMAKER_ENDPOINTKEY, QNAMAKER_KBID} = process.env; const {subscriptionKey, hostname, endpointKey, kbId} = args; let qnamakerrcJson = {}; let config; try { await fs.access(path.join(process.cwd(), '.qnamakerrc'), fs.R_OK); qnamakerrcJson = JSON.parse(await txtfile.read(path.join(process.cwd(), '.qnamakerrc'))); } catch (e) { // Do nothing } finally { config = { subscriptionKey: (subscriptionKey || qnamakerrcJson.subscriptionKey || QNAMAKER_SUBSCRIPTION_KEY), hostname: (hostname || qnamakerrcJson.hostname || QNAMAKER_HOSTNAME), endpointKey: (endpointKey || qnamakerrcJson.endpointKey || QNAMAKER_ENDPOINTKEY), kbId: (kbId || qnamakerrcJson.kbId || QNAMAKER_KBID) }; } return config; }
javascript
{ "resource": "" }
q21230
handleError
train
async function handleError(error) { process.stderr.write('\n' + chalk.red.bold(error + '\n\n')); await help(args); return 1; }
javascript
{ "resource": "" }
q21231
processFiles
train
async function processFiles(inputDir, outputDir) { return new Promise(async (resolve, reject) => { let files = glob.sync(inputDir, { "ignore": ["**/node_modules/**"] }); for (let i = 0; i < files.length; i++) { try { let fileName = files[i]; if (files[i].lastIndexOf("/") != -1) { fileName = files[i].substr(files[i].lastIndexOf("/")) } fileName = fileName.split(".")[0]; let activities = await chatdown(txtfile.readSync(files[i])); let writeFile = `${outputDir}/${fileName}.transcript`; await fs.ensureFile(writeFile); await fs.writeJson(writeFile, activities, { spaces: 2 }); } catch (e) { reject(e); } } resolve(files.length); }); }
javascript
{ "resource": "" }
q21232
runProgram
train
async function runProgram() { const args = minimist(process.argv.slice(2)); if (args.prefix) { intercept(function(txt) { return `[${pkg.name}]\n${txt}`; }); } let latest = await latestVersion(pkg.name, { version: `>${pkg.version}` }) .catch(error => pkg.version); if (semver.gt(latest, pkg.version)) { process.stderr.write(chalk.default.white(`\n Update available `)); process.stderr.write(chalk.default.grey(`${pkg.version}`)); process.stderr.write(chalk.default.white(` -> `)); process.stderr.write(chalk.default.greenBright(`${latest}\n`)); process.stderr.write(chalk.default.white(` Run `)); process.stderr.write(chalk.default.blueBright(`npm i -g ${pkg.name} `)); process.stderr.write(chalk.default.white(`to update.\n`)); } if (args.version || args.v) { process.stdout.write(pkg.version); return 0; } if (args.h || args.help) { help(process.stdout); return 0; } if (args.f || args.folder) { let inputDir = args.f.trim(); let outputDir = (args.o || args.out_folder) ? args.o.trim() : "./"; if (outputDir.substr(0, 2) === "./") { outputDir = path.resolve(process.cwd(), outputDir.substr(2)) } const len = await processFiles(inputDir, outputDir); process.stdout.write(chalk`{green Successfully wrote ${len} files}\n`); return len; } else { const fileContents = await getInput(args); if (fileContents) { const activities = await chatdown(fileContents, args); const writeConfirmation = await writeOut(activities, args); if (typeof writeConfirmation === 'string') { process.stdout.write(chalk`{green Successfully wrote file:} {blue ${writeConfirmation}}\n`); } return 0; } else { help(); return -1; } } }
javascript
{ "resource": "" }
q21233
exitWithError
train
function exitWithError(error) { if (error instanceof Error) { process.stderr.write(chalk.red(error)); } else { help(); } process.exit(1); }
javascript
{ "resource": "" }
q21234
getHelpContents
train
async function getHelpContents(args, output) { if ('!' in args) { return getAllCommands(output); } if (args._.length == 0) { return getGeneralHelpContents(output); } else if (args._.length == 1) { return getVerbHelp(args._[0], output); } else if (args._.length >= 2) { const serviceManifest = getServiceManifest(args); if (serviceManifest) { const { operation } = serviceManifest; output.write(`${operation.description}\n\n`); output.write(`Usage:\n${chalk.cyan.bold(operation.command)}\n\n`); } else { return getVerbHelp(args._[0], output); } } const serviceManifest = getServiceManifest(args); if (serviceManifest) { return getHelpContentsForService(serviceManifest, output); } return getGeneralHelpContents(output); }
javascript
{ "resource": "" }
q21235
getAllCommands
train
function getAllCommands() { let resourceTypes = []; let tables = {}; Object.keys(manifest).forEach(key => { const { [key]: category } = manifest; Object.keys(category.operations).forEach((operationKey) => { let operation = category.operations[operationKey]; let opCategory = operation.target[0] || operation.methodAlias; if (resourceTypes.indexOf(opCategory) < 0) { resourceTypes.push(opCategory); tables[opCategory] = []; } tables[opCategory].push([chalk.cyan.bold(operation.command), operation.description]); }); }); resourceTypes.sort(); let sections = []; for (let resourceType of resourceTypes) { tables[resourceType].sort((a, b) => a[0].localeCompare(b[0])); sections.push({ head: chalk.white.bold(resourceType), table: tables[resourceType] }); } return sections; }
javascript
{ "resource": "" }
q21236
createConversationUpdate
train
function createConversationUpdate(args, membersAdded, membersRemoved) { let conversationUpdateActivity = createActivity({ type: activitytypes.conversationupdate, recipient: args[args.botId], conversationId: args.conversation.id }); conversationUpdateActivity.membersAdded = membersAdded || []; conversationUpdateActivity.membersRemoved = membersRemoved || []; conversationUpdateActivity.timestamp = getIncrementedDate(100); return conversationUpdateActivity; }
javascript
{ "resource": "" }
q21237
addAttachment
train
async function addAttachment(activity, arg) { let parts = arg.trim().split(' '); let contentUrl = parts[0].trim(); let contentType = (parts.length > 1) ? parts[1].trim() : undefined; if (contentType) { contentType = contentType.toLowerCase(); if (cardContentTypes[contentType]) contentType = cardContentTypes[contentType]; } else { contentType = mime.lookup(contentUrl) || cardContentTypes[path.extname(contentUrl)]; if (!contentType && contentUrl && contentUrl.indexOf('http') == 0) { let options = { method: 'HEAD', uri: contentUrl }; let response = await request(options); contentType = response['content-type'].split(';')[0]; } } const charset = mime.charset(contentType); // if not a url if (contentUrl.indexOf('http') != 0) { // read the file let content = await readAttachmentFile(contentUrl, contentType); // if it is not a card if (!isCard(contentType) && charset !== 'UTF-8') { // send as base64 contentUrl = `data:${contentType};base64,${new Buffer(content).toString('base64')}`; content = undefined; } else { contentUrl = undefined; } return (activity.attachments || (activity.attachments = [])).push(new Attachment({ contentType, contentUrl, content })); } // send as contentUrl return (activity.attachments || (activity.attachments = [])).push(new Attachment({ contentType, contentUrl })); }
javascript
{ "resource": "" }
q21238
readAttachmentFile
train
async function readAttachmentFile(fileLocation, contentType) { let resolvedFileLocation = path.join(workingDirectory, fileLocation); let exists = fs.pathExistsSync(resolvedFileLocation); // fallback to cwd if (!exists) { resolvedFileLocation = path.resolve(fileLocation); } // Throws if the fallback does not exist. if (contentType.includes('json') || isCard(contentType)) { return fs.readJsonSync(resolvedFileLocation); } else { return fs.readFileSync(resolvedFileLocation); } }
javascript
{ "resource": "" }
q21239
createActivity
train
function createActivity({ type = ActivityTypes.Message, recipient, from, conversationId }) { const activity = new Activity({ from, recipient, type, id: '' + activityId++ }); activity.conversation = new ConversationAccount({ id: conversationId }); return activity; }
javascript
{ "resource": "" }
q21240
insertParametersFromObject
train
function insertParametersFromObject(parameterizedString, sourceObj) { let result; let payload = parameterizedString; while ((result = tokenRegExp.exec(parameterizedString))) { const token = result[1]; const propertyName = token.replace(/[{}]/g, ''); if (!(propertyName in sourceObj)) { continue; } payload = payload.replace(token, '' + sourceObj[propertyName]); } return payload; }
javascript
{ "resource": "" }
q21241
createPathRewriter
train
function createPathRewriter(rewriteConfig) { let rulesCache; if (!isValidRewriteConfig(rewriteConfig)) { return; } if (_.isFunction(rewriteConfig)) { const customRewriteFn = rewriteConfig; return customRewriteFn; } else { rulesCache = parsePathRewriteRules(rewriteConfig); return rewritePath; } function rewritePath(path) { let result = path; _.forEach(rulesCache, rule => { if (rule.regex.test(path)) { result = result.replace(rule.regex, rule.value); logger.debug('[HPM] Rewriting path from "%s" to "%s"', path, result); return false; } }); return result; } }
javascript
{ "resource": "" }
q21242
train
function () { vid2.read(function (err, m2) { if (writer2 === null) writer2 = new cv.VideoWriter(filename2, 'DIVX', vid2.getFPS(), m2.size(), true); x++; writer2.write(m2, function(err){ if (x < 100) { iter(); } else { vid2.release(); writer2.release(); } }); m2.release(); delete m2; }); }
javascript
{ "resource": "" }
q21243
getPixelValues
train
function getPixelValues (pixelData) { let minPixelValue = Number.MAX_VALUE; let maxPixelValue = Number.MIN_VALUE; const len = pixelData.length; let pixel; for (let i = 0; i < len; i++) { pixel = pixelData[i]; minPixelValue = minPixelValue < pixel ? minPixelValue : pixel; maxPixelValue = maxPixelValue > pixel ? maxPixelValue : pixel; } return { minPixelValue, maxPixelValue }; }
javascript
{ "resource": "" }
q21244
getRestoreImageMethod
train
function getRestoreImageMethod (image) { if (image.restore) { return image.restore; } const color = image.color; const rgba = image.rgba; const cachedLut = image.cachedLut; const slope = image.slope; const windowWidth = image.windowWidth; const windowCenter = image.windowCenter; const minPixelValue = image.minPixelValue; const maxPixelValue = image.maxPixelValue; return function () { image.color = color; image.rgba = rgba; image.cachedLut = cachedLut; image.slope = slope; image.windowWidth = windowWidth; image.windowCenter = windowCenter; image.minPixelValue = minPixelValue; image.maxPixelValue = maxPixelValue; if (image.origPixelData) { const pixelData = image.origPixelData; image.getPixelData = () => pixelData; } // Remove some attributes added by false color mapping image.origPixelData = undefined; image.colormapId = undefined; image.falseColor = undefined; }; }
javascript
{ "resource": "" }
q21245
restoreImage
train
function restoreImage (image) { if (image.restore && (typeof image.restore === 'function')) { image.restore(); return true; } return false; }
javascript
{ "resource": "" }
q21246
convertImageToFalseColorImage
train
function convertImageToFalseColorImage (image, colormap) { if (image.color && !image.falseColor) { throw new Error('Color transforms are not implemented yet'); } // User can pass a colormap id or a colormap object colormap = ensuresColormap(colormap); const colormapId = colormap.getId(); // Doesn't do anything if colormapId hasn't changed if (image.colormapId === colormapId) { // It has already being converted into a false color image // Using the colormapId passed as parameter return false; } // Restore the image attributes updated when converting to a false color image restoreImage(image); // Convert the image to a false color image if (colormapId) { const minPixelValue = image.minPixelValue || 0; const maxPixelValue = image.maxPixelValue || 255; image.restore = getRestoreImageMethod(image); const lookupTable = colormap.createLookupTable(); lookupTable.setTableRange(minPixelValue, maxPixelValue); // Update the pixel data and render the new image pixelDataToFalseColorData(image, lookupTable); // Update min and max pixel values const pixelValues = getPixelValues(image.getPixelData()); image.minPixelValue = pixelValues.minPixelValue; image.maxPixelValue = pixelValues.maxPixelValue; image.windowWidth = 255; image.windowCenter = 128; // Cache the last colormapId used for performance // Then it doesn't need to be re-rendered on next // Time if the user hasn't updated it image.colormapId = colormapId; } // Return `true` to tell the caller that the image has got updated return true; }
javascript
{ "resource": "" }
q21247
convertToFalseColorImage
train
function convertToFalseColorImage (element, colormap) { const enabledElement = getEnabledElement(element); return convertImageToFalseColorImage(enabledElement.image, colormap); }
javascript
{ "resource": "" }
q21248
compileShader
train
function compileShader (gl, shaderSource, shaderType) { // Create the shader object const shader = gl.createShader(shaderType); // Set the shader source code. gl.shaderSource(shader, shaderSource); // Compile the shader gl.compileShader(shader); // Check if it compiled const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!success && !gl.isContextLost()) { // Something went wrong during compilation; get the error const infoLog = gl.getShaderInfoLog(shader); console.error(`Could not compile shader:\n${infoLog}`); } return shader; }
javascript
{ "resource": "" }
q21249
createProgram
train
function createProgram (gl, vertexShader, fragmentShader) { // Create a program. const program = gl.createProgram(); // Attach the shaders. gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); // Link the program. gl.linkProgram(program); // Check if it linked. const success = gl.getProgramParameter(program, gl.LINK_STATUS); if (!success && !gl.isContextLost()) { // Something went wrong with the link const infoLog = gl.getProgramInfoLog(program); console.error(`WebGL program filed to link:\n${infoLog}`); } return program; }
javascript
{ "resource": "" }
q21250
createViewport
train
function createViewport () { const displayedArea = createDefaultDisplayedArea(); return { scale: 1, translation: { x: 0, y: 0 }, voi: { windowWidth: undefined, windowCenter: undefined }, invert: false, pixelReplication: false, rotation: 0, hflip: false, vflip: false, modalityLUT: undefined, voiLUT: undefined, colormap: undefined, labelmap: false, displayedArea }; }
javascript
{ "resource": "" }
q21251
linearIndexLookupMain
train
function linearIndexLookupMain (v, p) { let dIndex; // NOTE: Added Math.floor since values were not integers? Check VTK source if (v < p.Range[0]) { dIndex = p.MaxIndex + BELOW_RANGE_COLOR_INDEX + 1.5; } else if (v > p.Range[1]) { dIndex = p.MaxIndex + ABOVE_RANGE_COLOR_INDEX + 1.5; } else { dIndex = (v + p.Shift) * p.Scale; } return Math.floor(dIndex); }
javascript
{ "resource": "" }
q21252
hasVoi
train
function hasVoi (viewport) { const hasLut = viewport.voiLUT && viewport.voiLUT.lut && viewport.voiLUT.lut.length > 0; return hasLut || (viewport.voi.windowWidth !== undefined && viewport.voi.windowCenter !== undefined); }
javascript
{ "resource": "" }
q21253
compare
train
function compare (a, b) { if (a.timeStamp > b.timeStamp) { return -1; } if (a.timeStamp < b.timeStamp) { return 1; } return 0; }
javascript
{ "resource": "" }
q21254
getImageDataType
train
function getImageDataType (image) { if (image.color) { return 'rgb'; } const pixelData = image.getPixelData(); if (pixelData instanceof Int16Array) { return 'int16'; } if (pixelData instanceof Uint16Array) { return 'uint16'; } if (pixelData instanceof Int8Array) { return 'int8'; } return 'uint8'; }
javascript
{ "resource": "" }
q21255
purgeCacheIfNecessary
train
function purgeCacheIfNecessary () { // If max cache size has not been exceeded, do nothing if (cacheSizeInBytes <= maximumSizeInBytes) { return; } // Cache size has been exceeded, create list of images sorted by timeStamp // So we can purge the least recently used image function compare (a, b) { if (a.timeStamp > b.timeStamp) { return -1; } if (a.timeStamp < b.timeStamp) { return 1; } return 0; } cachedImages.sort(compare); // Remove images as necessary) while (cacheSizeInBytes > maximumSizeInBytes) { const lastCachedImage = cachedImages[cachedImages.length - 1]; const imageId = lastCachedImage.imageId; removeImageLoadObject(imageId); triggerEvent(events, EVENTS.IMAGE_CACHE_PROMISE_REMOVED, { imageId }); } const cacheInfo = getCacheInfo(); triggerEvent(events, EVENTS.IMAGE_CACHE_FULL, cacheInfo); }
javascript
{ "resource": "" }
q21256
createCanvas
train
function createCanvas (element) { const canvas = document.createElement('canvas'); canvas.style.display = 'block'; canvas.classList.add(CANVAS_CSS_CLASS); element.appendChild(canvas); return canvas; }
javascript
{ "resource": "" }
q21257
generateNonLinearVOILUT
train
function generateNonLinearVOILUT (voiLUT) { // We don't trust the voiLUT.numBitsPerEntry, mainly thanks to Agfa! const bitsPerEntry = Math.max(...voiLUT.lut).toString(2).length; const shift = bitsPerEntry - 8; const minValue = voiLUT.lut[0] >> shift; const maxValue = voiLUT.lut[voiLUT.lut.length - 1] >> shift; const maxValueMapped = voiLUT.firstValueMapped + voiLUT.lut.length - 1; return function (modalityLutValue) { if (modalityLutValue < voiLUT.firstValueMapped) { return minValue; } else if (modalityLutValue >= maxValueMapped) { return maxValue; } return voiLUT.lut[modalityLutValue - voiLUT.firstValueMapped] >> shift; }; }
javascript
{ "resource": "" }
q21258
syncViewports
train
function syncViewports (layers, activeLayer) { // If we intend to keep the viewport's scale, translation and rotation in sync, // loop through the layers layers.forEach((layer) => { // Don't do anything to the active layer // Don't do anything if this layer has no viewport if (layer === activeLayer || !layer.viewport || !activeLayer.viewport) { return; } if (!layer.syncProps) { updateLayerSyncProps(layer); } const viewportRatio = getViewportRatio(activeLayer, layer); // Update the layer's translation and scale to keep them in sync with the first image // based on the ratios between the images layer.viewport.scale = activeLayer.viewport.scale * viewportRatio; layer.viewport.rotation = activeLayer.viewport.rotation; layer.viewport.translation = { x: (activeLayer.viewport.translation.x / viewportRatio), y: (activeLayer.viewport.translation.y / viewportRatio) }; layer.viewport.hflip = activeLayer.viewport.hflip; layer.viewport.vflip = activeLayer.viewport.vflip; }); }
javascript
{ "resource": "" }
q21259
renderLayers
train
function renderLayers (context, layers, invalidated) { // Loop through each layer and draw it to the canvas layers.forEach((layer, index) => { if (!layer.image) { return; } context.save(); // Set the layer's canvas to the pixel coordinate system layer.canvas = context.canvas; setToPixelCoordinateSystem(layer, context); // Render into the layer's canvas const colormap = layer.viewport.colormap || layer.options.colormap; const labelmap = layer.viewport.labelmap; const isInvalid = layer.invalid || invalidated; if (colormap && colormap !== '' && labelmap === true) { addLabelMapLayer(layer, isInvalid); } else if (colormap && colormap !== '') { addPseudoColorLayer(layer, isInvalid); } else if (layer.image.color === true) { addColorLayer(layer, isInvalid); } else { // If this is the base layer, use the alpha channel for rendering of the grayscale image const useAlphaChannel = (index === 0); addGrayscaleLayer(layer, isInvalid, useAlphaChannel); } // Apply any global opacity settings that have been defined for this layer if (layer.options && layer.options.opacity) { context.globalAlpha = layer.options.opacity; } else { context.globalAlpha = 1; } if (layer.options && layer.options.fillStyle) { context.fillStyle = layer.options.fillStyle; } // Set the pixelReplication property before drawing from the layer into the // composite canvas context.imageSmoothingEnabled = !layer.viewport.pixelReplication; context.mozImageSmoothingEnabled = context.imageSmoothingEnabled; // Draw from the current layer's canvas onto the enabled element's canvas const sx = layer.viewport.displayedArea.tlhc.x - 1; const sy = layer.viewport.displayedArea.tlhc.y - 1; const width = layer.viewport.displayedArea.brhc.x - sx; const height = layer.viewport.displayedArea.brhc.y - sy; context.drawImage(layer.canvas, sx, sy, width, height, 0, 0, width, height); context.restore(); layer.invalid = false; }); }
javascript
{ "resource": "" }
q21260
createLinearSegmentedColormap
train
function createLinearSegmentedColormap (segmentedData, N, gamma) { let i; const lut = []; N = N === null ? 256 : N; gamma = gamma === null ? 1 : gamma; const redLut = makeMappingArray(N, segmentedData.red, gamma); const greenLut = makeMappingArray(N, segmentedData.green, gamma); const blueLut = makeMappingArray(N, segmentedData.blue, gamma); for (i = 0; i < N; i++) { const red = Math.round(redLut[i] * 255); const green = Math.round(greenLut[i] * 255); const blue = Math.round(blueLut[i] * 255); const rgba = [red, green, blue, 255]; lut.push(rgba); } return lut; }
javascript
{ "resource": "" }
q21261
setCanvasSize
train
function setCanvasSize (element, canvas) { // The device pixel ratio is 1.0 for normal displays and > 1.0 // For high DPI displays like Retina /* This functionality is disabled due to buggy behavior on systems with mixed DPI's. If the canvas is created on a display with high DPI (e.g. 2.0) and then the browser window is dragged to a different display with a different DPI (e.g. 1.0), the canvas is not recreated so the pageToPixel produces incorrect results. I couldn't find any way to determine when the DPI changed other than by polling which is not very clean. If anyone has any ideas here, please let me know, but for now we will disable this functionality. We may want to add a mechanism to optionally enable this functionality if we can determine it is safe to do so (e.g. iPad or iPhone or perhaps enumerate the displays on the system. I am choosing to be cautious here since I would rather not have bug reports or safety issues related to this scenario. var devicePixelRatio = window.devicePixelRatio; if(devicePixelRatio === undefined) { devicePixelRatio = 1.0; } */ // Avoid setting the same value because it flashes the canvas with IE and Edge if (canvas.width !== element.clientWidth) { canvas.width = element.clientWidth; canvas.style.width = `${element.clientWidth}px`; } // Avoid setting the same value because it flashes the canvas with IE and Edge if (canvas.height !== element.clientHeight) { canvas.height = element.clientHeight; canvas.style.height = `${element.clientHeight}px`; } }
javascript
{ "resource": "" }
q21262
wasFitToWindow
train
function wasFitToWindow (enabledElement, oldCanvasWidth, oldCanvasHeight) { const scale = enabledElement.viewport.scale; const imageSize = getImageSize(enabledElement.image, enabledElement.viewport.rotation); const imageWidth = Math.round(imageSize.width * scale); const imageHeight = Math.round(imageSize.height * scale); const x = enabledElement.viewport.translation.x; const y = enabledElement.viewport.translation.y; return (imageWidth === oldCanvasWidth && imageHeight <= oldCanvasHeight) || (imageWidth <= oldCanvasWidth && imageHeight === oldCanvasHeight) && (x === 0 && y === 0); }
javascript
{ "resource": "" }
q21263
relativeRescale
train
function relativeRescale (enabledElement, oldCanvasWidth, oldCanvasHeight) { const scale = enabledElement.viewport.scale; const canvasWidth = enabledElement.canvas.width; const canvasHeight = enabledElement.canvas.height; const relWidthChange = canvasWidth / oldCanvasWidth; const relHeightChange = canvasHeight / oldCanvasHeight; const relChange = Math.sqrt(relWidthChange * relHeightChange); enabledElement.viewport.scale = relChange * scale; }
javascript
{ "resource": "" }
q21264
loadImageFromImageLoader
train
function loadImageFromImageLoader (imageId, options) { const colonIndex = imageId.indexOf(':'); const scheme = imageId.substring(0, colonIndex); const loader = imageLoaders[scheme]; if (loader === undefined || loader === null) { if (unknownImageLoader !== undefined) { return unknownImageLoader(imageId); } throw new Error('loadImageFromImageLoader: no image loader for imageId'); } const imageLoadObject = loader(imageId, options); // Broadcast an image loaded event once the image is loaded imageLoadObject.promise.then(function (image) { triggerEvent(events, EVENTS.IMAGE_LOADED, { image }); }, function (error) { const errorObject = { imageId, error }; triggerEvent(events, EVENTS.IMAGE_LOAD_FAILED, errorObject); }); return imageLoadObject; }
javascript
{ "resource": "" }
q21265
getMetaData
train
function getMetaData (type, imageId) { // Invoke each provider in priority order until one returns something for (let i = 0; i < providers.length; i++) { const result = providers[i].provider(type, imageId); if (result !== undefined) { return result; } } }
javascript
{ "resource": "" }
q21266
run
train
async function run () { if (options.help || Object.keys(options).length === 1) { showHelp() return } if (!options.name) { console.error('You need to input -n, --name argv') return } if (!options.title) { options.title = options.name.split('-').join(' ') } let content = (await fs.readFile(`${__dirname}/example.tpl`)).toString() content = content.replace(/@title@/, options.title || '') .replace(/@desc@/, options.desc || '') await fs.writeFile(`${__dirname}/../docs/examples/${options.name}.html`, content) console.info(`${options.name}.html`) let list = (await fs.readFile(`${__dirname}/../docs/_includes/example-list.md`)).toString() list += `<li><a href="../examples#${options.name}.html">${options.title}</a></li>\n` await fs.writeFile(`${__dirname}/../docs/_includes/example-list.md`, list) }
javascript
{ "resource": "" }
q21267
addKeyword
train
function addKeyword(keyword, definition) { /* jshint validthis: true */ /* eslint no-shadow: 0 */ var RULES = this.RULES; if (RULES.keywords[keyword]) throw new Error('Keyword ' + keyword + ' is already defined'); if (!IDENTIFIER.test(keyword)) throw new Error('Keyword ' + keyword + ' is not a valid identifier'); if (definition) { this.validateKeyword(definition, true); var dataType = definition.type; if (Array.isArray(dataType)) { for (var i=0; i<dataType.length; i++) _addRule(keyword, dataType[i], definition); } else { _addRule(keyword, dataType, definition); } var metaSchema = definition.metaSchema; if (metaSchema) { if (definition.$data && this._opts.$data) { metaSchema = { anyOf: [ metaSchema, { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' } ] }; } definition.validateSchema = this.compile(metaSchema, true); } } RULES.keywords[keyword] = RULES.all[keyword] = true; function _addRule(keyword, dataType, definition) { var ruleGroup; for (var i=0; i<RULES.length; i++) { var rg = RULES[i]; if (rg.type == dataType) { ruleGroup = rg; break; } } if (!ruleGroup) { ruleGroup = { type: dataType, rules: [] }; RULES.push(ruleGroup); } var rule = { keyword: keyword, definition: definition, custom: true, code: customRuleCode, implements: definition.implements }; ruleGroup.rules.push(rule); RULES.custom[keyword] = rule; } return this; }
javascript
{ "resource": "" }
q21268
validateKeyword
train
function validateKeyword(definition, throwError) { validateKeyword.errors = null; var v = this._validateKeyword = this._validateKeyword || this.compile(definitionSchema, true); if (v(definition)) return true; validateKeyword.errors = v.errors; if (throwError) throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors)); else return false; }
javascript
{ "resource": "" }
q21269
resolveSchema
train
function resolveSchema(root, ref) { /* jshint validthis: true */ var p = URI.parse(ref) , refPath = _getFullPath(p) , baseId = getFullPath(this._getId(root.schema)); if (Object.keys(root.schema).length === 0 || refPath !== baseId) { var id = normalizeId(refPath); var refVal = this._refs[id]; if (typeof refVal == 'string') { return resolveRecursive.call(this, root, refVal, p); } else if (refVal instanceof SchemaObject) { if (!refVal.validate) this._compile(refVal); root = refVal; } else { refVal = this._schemas[id]; if (refVal instanceof SchemaObject) { if (!refVal.validate) this._compile(refVal); if (id == normalizeId(ref)) return { schema: refVal, root: root, baseId: baseId }; root = refVal; } else { return; } } if (!root.schema) return; baseId = getFullPath(this._getId(root.schema)); } return getJsonPointer.call(this, p, baseId, root.schema, root); }
javascript
{ "resource": "" }
q21270
compile
train
function compile(schema, _meta) { var schemaObj = this._addSchema(schema, undefined, _meta); return schemaObj.validate || this._compile(schemaObj); }
javascript
{ "resource": "" }
q21271
addSchema
train
function addSchema(schema, key, _skipValidation, _meta) { if (Array.isArray(schema)){ for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta); return this; } var id = this._getId(schema); if (id !== undefined && typeof id != 'string') throw new Error('schema id must be string'); key = resolve.normalizeId(key || id); checkUnique(this, key); this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true); return this; }
javascript
{ "resource": "" }
q21272
getSchema
train
function getSchema(keyRef) { var schemaObj = _getSchemaObj(this, keyRef); switch (typeof schemaObj) { case 'object': return schemaObj.validate || this._compile(schemaObj); case 'string': return this.getSchema(schemaObj); case 'undefined': return _getSchemaFragment(this, keyRef); } }
javascript
{ "resource": "" }
q21273
errorsText
train
function errorsText(errors, options) { errors = errors || this.errors; if (!errors) return 'No errors'; options = options || {}; var separator = options.separator === undefined ? ', ' : options.separator; var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; var text = ''; for (var i=0; i<errors.length; i++) { var e = errors[i]; if (e) text += dataVar + e.dataPath + ' ' + e.message + separator; } return text.slice(0, -separator.length); }
javascript
{ "resource": "" }
q21274
addFormat
train
function addFormat(name, format) { if (typeof format == 'string') format = new RegExp(format); this._formats[name] = format; return this; }
javascript
{ "resource": "" }
q21275
checkCompiling
train
function checkCompiling(schema, root, baseId) { /* jshint validthis: true */ var index = compIndex.call(this, schema, root, baseId); if (index >= 0) return { index: index, compiling: true }; index = this._compilations.length; this._compilations[index] = { schema: schema, root: root, baseId: baseId }; return { index: index, compiling: false }; }
javascript
{ "resource": "" }
q21276
endCompiling
train
function endCompiling(schema, root, baseId) { /* jshint validthis: true */ var i = compIndex.call(this, schema, root, baseId); if (i >= 0) this._compilations.splice(i, 1); }
javascript
{ "resource": "" }
q21277
compIndex
train
function compIndex(schema, root, baseId) { /* jshint validthis: true */ for (var i=0; i<this._compilations.length; i++) { var c = this._compilations[i]; if (c.schema == schema && c.root == root && c.baseId == baseId) return i; } return -1; }
javascript
{ "resource": "" }
q21278
compileAsync
train
function compileAsync(schema, meta, callback) { /* eslint no-shadow: 0 */ /* global Promise */ /* jshint validthis: true */ var self = this; if (typeof this._opts.loadSchema != 'function') throw new Error('options.loadSchema should be a function'); if (typeof meta == 'function') { callback = meta; meta = undefined; } var p = loadMetaSchemaOf(schema).then(function () { var schemaObj = self._addSchema(schema, undefined, meta); return schemaObj.validate || _compileAsync(schemaObj); }); if (callback) { p.then( function(v) { callback(null, v); }, callback ); } return p; function loadMetaSchemaOf(sch) { var $schema = sch.$schema; return $schema && !self.getSchema($schema) ? compileAsync.call(self, { $ref: $schema }, true) : Promise.resolve(); } function _compileAsync(schemaObj) { try { return self._compile(schemaObj); } catch(e) { if (e instanceof MissingRefError) return loadMissingSchema(e); throw e; } function loadMissingSchema(e) { var ref = e.missingSchema; if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); var schemaPromise = self._loadingSchemas[ref]; if (!schemaPromise) { schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); schemaPromise.then(removePromise, removePromise); } return schemaPromise.then(function (sch) { if (!added(ref)) { return loadMetaSchemaOf(sch).then(function () { if (!added(ref)) self.addSchema(sch, ref, undefined, meta); }); } }).then(function() { return _compileAsync(schemaObj); }); function removePromise() { delete self._loadingSchemas[ref]; } function added(ref) { return self._refs[ref] || self._schemas[ref]; } } } }
javascript
{ "resource": "" }
q21279
train
function() { var self = this, vars, j; // If this editor needs to be rendered by a macro template if(this.template) { vars = this.getWatchedFieldValues(); this.setValue(this.template(vars),false,true); } this._super(); }
javascript
{ "resource": "" }
q21280
train
function (event, type) { if (!this.getMap()) { return; } const eventType = type || this._getEventTypeToFire(event); if (eventType === 'contextmenu' && this.listens('contextmenu')) { stopPropagation(event); preventDefault(event); } const params = this._getEventParams(event); this._fireEvent(eventType, params); }
javascript
{ "resource": "" }
q21281
train
function (e) { const map = this.getMap(); const eventParam = { 'domEvent': e }; const actual = e.touches && e.touches.length > 0 ? e.touches[0] : e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches[0] : e; if (actual) { const containerPoint = getEventContainerPoint(actual, map._containerDOM); eventParam['coordinate'] = map.containerPointToCoordinate(containerPoint); eventParam['containerPoint'] = containerPoint; eventParam['viewPoint'] = map.containerPointToViewPoint(containerPoint); eventParam['pont2d'] = map._containerPointToPoint(containerPoint); } return eventParam; }
javascript
{ "resource": "" }
q21282
train
function (coord1, coord2) { if (!this.getProjection()) { return null; } const p1 = new Coordinate(coord1), p2 = new Coordinate(coord2); if (p1.equals(p2)) { return 0; } return this.getProjection().measureLength(p1, p2); }
javascript
{ "resource": "" }
q21283
train
function (opts, callback) { if (!opts) { return this; } const reqLayers = opts['layers']; if (!isArrayHasData(reqLayers)) { return this; } const layers = []; for (let i = 0, len = reqLayers.length; i < len; i++) { if (isString(reqLayers[i])) { layers.push(this.getLayer(reqLayers[i])); } else { layers.push(reqLayers[i]); } } const coordinate = new Coordinate(opts['coordinate']); const options = extend({}, opts); const hits = []; for (let i = layers.length - 1; i >= 0; i--) { if (opts['count'] && hits.length >= opts['count']) { break; } const layer = layers[i]; if (!layer || !layer.getMap() || (!opts['includeInvisible'] && !layer.isVisible()) || (!opts['includeInternals'] && layer.getId().indexOf(INTERNAL_LAYER_PREFIX) >= 0)) { continue; } const layerHits = layer.identify(coordinate, options); if (layerHits) { if (Array.isArray(layerHits)) { pushIn(hits, layerHits); } else { hits.push(layerHits); } } } callback.call(this, hits); return this; }
javascript
{ "resource": "" }
q21284
train
function (styles, options, step) { if (this._animPlayer) { this._animPlayer.finish(); } if (isFunction(options)) { step = options; } if (!options) { options = {}; } const map = this.getMap(), projection = this._getProjection(), symbol = this.getSymbol() || {}, stylesToAnimate = this._prepareAnimationStyles(styles); let preTranslate; const isFocusing = options['focus']; delete this._animationStarted; // geometry.animate can be called without map if (map) { // merge geometry animation framing into map's frame loop const renderer = map._getRenderer(); const framer = function (fn) { renderer.callInNextFrame(fn); }; options['framer'] = framer; } const player = Animation.animate(stylesToAnimate, options, frame => { if (map && map.isRemoved()) { player.finish(); return; } if (map && !this._animationStarted && isFocusing) { map.onMoveStart(); } const styles = frame.styles; for (const p in styles) { if (p !== 'symbol' && p !== 'translate' && styles.hasOwnProperty(p)) { const fnName = 'set' + p[0].toUpperCase() + p.slice(1); this[fnName](styles[p]); } } const translate = styles['translate']; if (translate) { let toTranslate = translate; if (preTranslate) { toTranslate = translate.sub(preTranslate); } preTranslate = translate; this.translate(toTranslate); } const dSymbol = styles['symbol']; if (dSymbol) { this.setSymbol(extendSymbol(symbol, dSymbol)); } if (map && isFocusing) { const pcenter = projection.project(this.getCenter()); map._setPrjCenter(pcenter); const e = map._parseEventFromCoord(projection.unproject(pcenter)); if (player.playState !== 'running') { map.onMoveEnd(e); } else { map.onMoving(e); } } this._fireAnimateEvent(player.playState); if (step) { step(frame); } }); this._animPlayer = player; return this._animPlayer.play(); }
javascript
{ "resource": "" }
q21285
train
function (styles) { const symbol = this._getInternalSymbol(); const stylesToAnimate = {}; for (const p in styles) { if (styles.hasOwnProperty(p)) { const v = styles[p]; if (p !== 'translate' && p !== 'symbol') { //this.getRadius() / this.getWidth(), etc. const fnName = 'get' + p[0].toUpperCase() + p.substring(1); const current = this[fnName](); stylesToAnimate[p] = [current, v]; } else if (p === 'symbol') { let symbolToAnimate; if (Array.isArray(styles['symbol'])) { if (!Array.isArray(symbol)) { throw new Error('geometry\'symbol isn\'t a composite symbol, while the symbol in styles is.'); } symbolToAnimate = []; const symbolInStyles = styles['symbol']; for (let i = 0; i < symbolInStyles.length; i++) { if (!symbolInStyles[i]) { symbolToAnimate.push(null); continue; } const a = {}; for (const sp in symbolInStyles[i]) { if (symbolInStyles[i].hasOwnProperty(sp)) { a[sp] = [symbol[i][sp], symbolInStyles[i][sp]]; } } symbolToAnimate.push(a); } } else { if (Array.isArray(symbol)) { throw new Error('geometry\'symbol is a composite symbol, while the symbol in styles isn\'t.'); } symbolToAnimate = {}; for (const sp in v) { if (v.hasOwnProperty(sp)) { symbolToAnimate[sp] = [symbol[sp], v[sp]]; } } } stylesToAnimate['symbol'] = symbolToAnimate; } else if (p === 'translate') { stylesToAnimate['translate'] = new Coordinate(v); } } } return stylesToAnimate; }
javascript
{ "resource": "" }
q21286
train
function (url, options, cb) { if (isFunction(options)) { const t = cb; cb = options; options = t; } if (IS_NODE && Ajax.get.node) { return Ajax.get.node(url, cb, options); } const client = Ajax._getClient(cb); client.open('GET', url, true); if (options) { for (const k in options.headers) { client.setRequestHeader(k, options.headers[k]); } client.withCredentials = options.credentials === 'include'; if (options['responseType']) { client.responseType = options['responseType']; } } client.send(null); return client; }
javascript
{ "resource": "" }
q21287
train
function (url, options, cb) { let postData; if (!isString(url)) { //for compatible //options, postData, cb const t = cb; postData = options; options = url; url = options.url; cb = t; } else { if (isFunction(options)) { const t = cb; cb = options; options = t; } options = options || {}; postData = options.postData; } if (IS_NODE && Ajax.post.node) { options.url = url; return Ajax.post.node(options, postData, cb); } const client = Ajax._getClient(cb); client.open('POST', options.url, true); if (!options.headers) { options.headers = {}; } if (!options.headers['Content-Type']) { options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; } if ('setRequestHeader' in client) { for (const p in options.headers) { if (options.headers.hasOwnProperty(p)) { client.setRequestHeader(p, options.headers[p]); } } } if (!isString(postData)) { postData = JSON.stringify(postData); } client.send(postData); return client; }
javascript
{ "resource": "" }
q21288
train
function (coordinate, options = {}, step) { if (!coordinate) { return this; } if (isFunction(options)) { step = options; options = {}; } coordinate = new Coordinate(coordinate); if (typeof (options['animation']) === 'undefined' || options['animation']) { return this._panAnimation(coordinate, options['duration'], step); } else { this.setCenter(coordinate); return this; } }
javascript
{ "resource": "" }
q21289
train
function (offset, options = {}, step) { if (!offset) { return this; } if (isFunction(options)) { step = options; options = {}; } offset = new Point(offset); this.onMoveStart(); if (typeof (options['animation']) === 'undefined' || options['animation']) { offset = offset.multi(-1); const target = this.locateByPoint(this.getCenter(), offset.x, offset.y); this._panAnimation(target, options['duration'], step); } else { this._offsetCenterByPixel(offset); this.onMoveEnd(this._parseEventFromCoord(this.getCenter())); } return this; }
javascript
{ "resource": "" }
q21290
rhumbBearing
train
function rhumbBearing(start, end, options = {}) { let bear360; if (options.final) bear360 = calculateRhumbBearing(end, start); else bear360 = calculateRhumbBearing(start, end); const bear180 = (bear360 > 180) ? -(360 - bear360) : bear360; return bear180; }
javascript
{ "resource": "" }
q21291
train
function (helpers) { Y.log('Importing helpers: ' + helpers, 'info', 'builder'); helpers.forEach(function (imp) { if (!Y.Files.exists(imp) || Y.Files.exists(path.join(process.cwd(), imp))) { imp = path.join(process.cwd(), imp); } var h = require(imp); Object.keys(h).forEach(function (name) { Y.Handlebars.registerHelper(name, h[name]); }); }); }
javascript
{ "resource": "" }
q21292
train
function (md) { var html = marked(md, this.options.markdown); //Only reprocess if helpers were asked for if (this.options.helpers || (html.indexOf('{{#crossLink') > -1)) { //console.log('MD: ', html); try { // marked auto-escapes quotation marks (and unfortunately // does not expose the escaping function) html = html.replace(/&quot;/g, "\""); html = (Y.Handlebars.compile(html))({}); } catch (hError) { //Remove all the extra escapes html = html.replace(/\\{/g, '{').replace(/\\}/g, '}'); Y.log('Failed to parse Handlebars, probably an unknown helper, skipping..', 'warn', 'builder'); } //console.log('HB: ', html); } return html; }
javascript
{ "resource": "" }
q21293
train
function () { var self = this; Y.log('External data received, mixing', 'info', 'builder'); self.options.externalData.forEach(function (exData) { ['files', 'classes', 'modules'].forEach(function (k) { Y.each(exData[k], function (item, key) { item.external = true; var file = item.name; if (!item.file) { file = self.filterFileName(item.name); } if (item.type) { item.type = fixType(item.type); } item.path = exData.base + path.join(k, file + '.html'); self.data[k][key] = item; }); }); Y.each(exData.classitems, function (item) { item.external = true; item.path = exData.base + path.join('files', self.filterFileName(item.file) + '.html'); if (item.type) { item.type = fixType(item.type); } if (item.params) { item.params.forEach(function (p) { if (p.type) { p.type = fixType(p.type); } }); } if (item["return"]) { item["return"].type = fixType(item["return"].type); } self.data.classitems.push(item); }); }); }
javascript
{ "resource": "" }
q21294
train
function (cb) { var self = this, info = self.options.external; if (!info) { cb(); return; } if (!info.merge) { info.merge = 'mix'; } if (!info.data) { Y.log('External config found but no data path defined, skipping import.', 'warn', 'builder'); cb(); return; } if (!Y.Lang.isArray(info.data)) { info.data = [info.data]; } Y.log('Importing external documentation data.', 'info', 'builder'); var stack = new Y.Parallel(); info.data.forEach(function (i) { var base; if (i.match(/^https?:\/\//)) { base = i.replace('data.json', ''); Y.use('io-base', stack.add(function () { Y.log('Fetching: ' + i, 'info', 'builder'); Y.io(i, { on: { complete: stack.add(function (id, e) { Y.log('Received: ' + i, 'info', 'builder'); var data = JSON.parse(e.responseText); data.base = base; //self.options.externalData = Y.mix(self.options.externalData || {}, data); if (!self.options.externalData) { self.options.externalData = []; } self.options.externalData.push(data); }) } }); })); } else { base = path.dirname(path.resolve(i)); var data = Y.Files.getJSON(i); data.base = base; //self.options.externalData = Y.mix(self.options.externalData || {}, data); if (!self.options.externalData) { self.options.externalData = []; } self.options.externalData.push(data); } }); stack.done(function () { Y.log('Finished fetching remote data', 'info', 'builder'); self._mixExternal(); cb(); }); }
javascript
{ "resource": "" }
q21295
train
function () { var obj = { meta: { yuiSeedUrl: 'http://yui.yahooapis.com/3.5.0/build/yui/yui-min.js', yuiGridsUrl: 'http://yui.yahooapis.com/3.5.0/build/cssgrids/cssgrids-min.css' } }; if (!this._meta) { try { var meta, theme = path.join(themeDir, 'theme.json'); if (Y.Files.exists(theme)) { Y.log('Loading theme from ' + theme, 'info', 'builder'); meta = Y.Files.getJSON(theme); } else if (DEFAULT_THEME !== themeDir) { theme = path.join(DEFAULT_THEME, 'theme.json'); if (Y.Files.exists(theme)) { Y.log('Loading theme from ' + theme, 'info', 'builder'); meta = Y.Files.getJSON(theme); } } if (meta) { obj.meta = meta; this._meta = meta; } } catch (e) { console.error('Error', e); } } else { obj.meta = this._meta; } Y.each(this.data.project, function (v, k) { var key = k.substring(0, 1).toUpperCase() + k.substring(1, k.length); obj.meta['project' + key] = v; }); return obj; }
javascript
{ "resource": "" }
q21296
train
function (opts) { opts.meta.classes = []; Y.each(this.data.classes, function (v) { if (v.external) { return; } opts.meta.classes.push({ displayName: v.name, name: v.name, namespace: v.namespace, module: v.module, description: v.description, access: v.access || 'public' }); }); opts.meta.classes.sort(this.nameSort); return opts; }
javascript
{ "resource": "" }
q21297
train
function (opts) { var self = this; opts.meta.modules = []; opts.meta.allModules = []; Y.each(this.data.modules, function (v) { if (v.external) { return; } opts.meta.allModules.push({ displayName: v.displayName || v.name, name: self.filterFileName(v.name), description: v.description }); if (!v.is_submodule) { var o = { displayName: v.displayName || v.name, name: self.filterFileName(v.name) }; if (v.submodules) { o.submodules = []; Y.each(v.submodules, function (i, k) { var moddef = self.data.modules[k]; if (moddef) { o.submodules.push({ displayName: k, description: moddef.description }); // } else { // Y.log('Submodule data missing: ' + k + ' for ' + v.name, 'warn', 'builder'); } }); o.submodules.sort(self.nameSort); } opts.meta.modules.push(o); } }); opts.meta.modules.sort(this.nameSort); opts.meta.allModules.sort(this.nameSort); return opts; }
javascript
{ "resource": "" }
q21298
train
function (opts) { var self = this; opts.meta.files = []; Y.each(this.data.files, function (v) { if (v.external) { return; } opts.meta.files.push({ displayName: v.name, name: self.filterFileName(v.name), path: v.path || v.name }); }); var tree = {}; var files = []; Y.each(this.data.files, function (v) { if (v.external) { return; } files.push(v.name); }); files.sort(); Y.each(files, function (v) { var p = v.split('/'), par; p.forEach(function (i, k) { if (!par) { if (!tree[i]) { tree[i] = {}; } par = tree[i]; } else { if (!par[i]) { par[i] = {}; } if (k + 1 === p.length) { par[i] = { path: v, name: self.filterFileName(v) }; } par = par[i]; } }); }); opts.meta.fileTree = tree; return opts; }
javascript
{ "resource": "" }
q21299
train
function (a) { var self = this; if (a.file && a.line && !self.options.nocode) { a.foundAt = '../files/' + self.filterFileName(a.file) + '.html#l' + a.line; if (a.path) { a.foundAt = a.path + '#l' + a.line; } } return a; }
javascript
{ "resource": "" }