_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q5600
nudge
train
function nudge(emitter, eventSpecs) { 'use strict'; checkValidity(eventSpecs); var proxy = makeProxyEmitter(emitter, eventSpecs); return function middleware(req, res) { function write(string) { res.write(string); } proxy.on('data', write); req.once('close', function removeListener() { proxy.removeListener('data', write); }); // Necessary headers for SSE. res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' // Tell Nginx not to buffer this response. }); // SSE required newline. write('\n'); }; }
javascript
{ "resource": "" }
q5601
train
function (point, size, isRelative) { return {left: Math.ceil(point.x), top: Math.ceil(point.y), width: Math.ceil(size.width), height: Math.ceil(size.height), relative: isRelative}; }
javascript
{ "resource": "" }
q5602
train
function(grunt, context) { grunt.config.data = _.defaults(context || {}, _.cloneDeep(grunt.config.data)); return grunt.config.process(grunt.config.data); }
javascript
{ "resource": "" }
q5603
mapCoerceFunction
train
function mapCoerceFunction(type, strType, coerceFunction) { coerceFunction = coerceFunction || type.coerce; if (typeof strType !== 'string' || typeof coerceFunction !== 'function') { getLogger('map-coerce-function') .warn(`Bad attempt at mapping coerce function for type: ${type.name} to: ${strType}`); return; } coerceFunctions[strType] = coerceFunction; coerceFunctionMap.set(type, strType); }
javascript
{ "resource": "" }
q5604
parseOptions
train
function parseOptions(options) { ttl = options.ttl || (3600 * 24); // cache for 1 day by default. tmpCacheTTL = options.tmpCacheTTL || 5; // small by default decodeFn = options.decodeFn || exports.decodeURL; presets = options.presets || defaultPresets(); tmpDir = options.tmpDir || '/tmp/nodethumbnails'; var rootPath = options.rootPath || '/thumbs'; if (rootPath[0] === '/') { rootPath = rootPath.substring(1); } // be forgiving to user errors! var allowedExtensions = options.allowedExtensions || ['gif', 'png', 'jpg', 'jpeg']; for (var i=0; i < allowedExtensions.length; i++) { // be forgiving to user errors! if (allowedExtensions[i][0] === '.') { allowedExtensions[i] = allowedExtensions[i].substring(1); } } var szExtensions = allowedExtensions.join('|'); // Example: http://example.com/thumbs/small/images/AB23DC16Hash.jpg regexp = new RegExp('^\/' + rootPath.replace(/\//ig, '\\/') + '\/([A-Za-z0-9_]+)\/images\/([%\.\-A-Za-z0-9_=\+]+)\.(?:' + szExtensions + ')$', 'i'); }
javascript
{ "resource": "" }
q5605
train
function () { var text = '' var regx = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' for (var idx = 0; idx < 8; idx++) { text = text + regx.charAt(Math.floor(Math.random() * regx.length)) } return text }
javascript
{ "resource": "" }
q5606
performResize
train
function performResize(deviceInfo) { const {windowPhysicalPixels} = deviceInfo; const {width, height} = windowPhysicalPixels; // Force RN to re-set the Dimensions sizes Dimensions.set({windowPhysicalPixels}); console.log(`Resizing window to physical pixels ${width}x${height}`); // TODO: Android uses screenPhysicalPixels - see https://github.com/facebook/react-native/blob/master/Libraries/Utilities/Dimensions.js }
javascript
{ "resource": "" }
q5607
writeJson
train
function writeJson(filepath, value, cb) { var args = [].slice.call(arguments, 1); if (typeof args[args.length - 1] === 'function') { cb = args.pop(); } return writeFile(filepath, stringify.apply(null, args), cb); }
javascript
{ "resource": "" }
q5608
stringify
train
function stringify(value, replacer, indent) { if (isObject(replacer)) { var opts = replacer; replacer = opts.replacer; indent = opts.indent; } if (indent == null) { indent = 2; } return JSON.stringify(value, replacer, indent); }
javascript
{ "resource": "" }
q5609
compareByRelevance
train
function compareByRelevance(o1, o2) { var result = 0; if (Math.abs(0.5 - o1.percentage) > Math.abs(0.5 - o2.percentage)) { result = -1; // A trait with 1% is more interesting than one with 60%. } if (Math.abs(0.5 - o1.percentage) < Math.abs(0.5 - o2.percentage)) { result = 1; } return result; }
javascript
{ "resource": "" }
q5610
minimize
train
function minimize(data) { if (!Array.isArray(data)) { throw new Error('EspressoLogicMinimizer: expected an array, got a ' + typeof data); } const badContent = data.filter((element) => typeof element != 'string'); if (badContent.length > 0) { throw new Error('EspressoLogicMinimizer: incorrect data content. Only strings are supported: ' + badContent); } return EspressoLogicMinimizer.minimize_from_data(data); }
javascript
{ "resource": "" }
q5611
findPrototypeForProperty
train
function findPrototypeForProperty(object,property){ while(false==object.hasOwnProperty(property)){ object = Object.getPrototypeOf(object); } return object; }
javascript
{ "resource": "" }
q5612
setShouldAutoRotate
train
function setShouldAutoRotate(bool){ var prototypeForNavController = findPrototypeForProperty(frameModule.topmost().ios.controller,"shouldAutorotate"); Object.defineProperty(prototypeForNavController,"shouldAutorotate",{ configurable:true, enumerable:false, get:function(){ return bool; } }) }
javascript
{ "resource": "" }
q5613
setCurrentOrientation
train
function setCurrentOrientation(orientationType,callback){ if("landscape"==orientationType.toLowerCase()){ UIDevice.currentDevice.setValueForKey(UIInterfaceOrientationLandscapeLeft,"orientation"); setShouldAutoRotate(false); } else if("portrait"==orientationType.toLowerCase()){ UIDevice.currentDevice.setValueForKey(UIInterfaceOrientationPortrait,"orientation"); setShouldAutoRotate(false); }else if("all" == orientationType.toLowerCase()){ setShouldAutoRotate(true); } if(undefined!==callback){ callback(); } }
javascript
{ "resource": "" }
q5614
removeUnusedProperties
train
function removeUnusedProperties(node) { if (typeof node !== "object") { return; } ["position"].forEach(function (key) { if (node.hasOwnProperty(key)) { delete node[key]; } }); }
javascript
{ "resource": "" }
q5615
executeAll
train
function executeAll (cfg) { console.log(`${clr.DIM+clr.LIGHT_MAGENTA}Package: ${cfg.packageRoot}${clr.RESET}`); return new Promise((resolve, reject) => { createObservable(cfg).subscribe({ next ({command, exitCode}) { if (exitCode == 0) cfg.log(`${EMIT_COLOR}just-build ${cfg.tasksToRun.join(' ')}`+ ` done.${clr.RESET}${cfg.watchMode ? NOW_WATCHING_COLOR+' Still watching...'+clr.RESET : ''}`); else cfg.log(`just-build ${cfg.tasksToRun.join(' ')} failed. ${command} returned ${exitCode}`); }, error (err) { reject(err); }, complete () { resolve(); } }); }); }
javascript
{ "resource": "" }
q5616
createObservable
train
function createObservable (cfg) { const {dir, taskSet, tasksToRun, watchMode, spawn, env, log} = cfg; const tasks = tasksToRun.map(taskName => { const commandList = taskSet[taskName]; if (!commandList) throw new Error (`No such task name: ${taskName} was configured`); return commandList; }); return createParallellCommandsExecutor ( tasks, dir, env, watchMode, {spawn, log}); }
javascript
{ "resource": "" }
q5617
createSequencialCommandExecutor
train
function createSequencialCommandExecutor (commands, workingDir, envVars, watchMode, host) { const source = Observable.from([{ cwd: workingDir, env: envVars, exitCode: 0 }]); return commands.reduce((prev, command) => createCommandExecutor(command, prev, watchMode, host), source); }
javascript
{ "resource": "" }
q5618
getPackageRoot
train
function getPackageRoot (dir) { let lastDir = null; while (lastDir !== dir && !fs.existsSync(path.resolve(dir, "./package.json"))) { lastDir = dir; dir = path.dirname(dir); } return (lastDir === dir ? null : dir); }
javascript
{ "resource": "" }
q5619
train
function() { var self = this; self._modules = []; return new Promise(function(resolve, reject) { var base; var processors = []; if (self._options.base) { base = fs.readFileSync(path.resolve(self._options.base), 'utf8'); } // For every file or folder, create a promise, // parse the file, extract the config and store it // to the global modules array. // Once all files are being processed, store the generated config. for (var i = 0; i < self._options.args.length; i++) { var file = self._options.args[i]; var fileStats = fs.statSync(file); if (fileStats.isDirectory(file)) { var walker = walk.walk(file, { followLinks: false }); walker.on('file', self._onWalkerFile.bind(self)); processors.push(self._onWalkerEnd(walker)); } else if (fileStats.isFile()) { processors.push(self._processFile(file)); } } Promise.all(processors) .then(function(uselessPromises) { return self._generateConfig(); }) .then(function(config) { var content; if (self._options.config) { if (base) { content = base + self._options.config + '.modules = ' + JSON.stringify(config) + ';'; } else { content = 'var ' + self._options.config + ' = {modules: ' + JSON.stringify(config) + '};'; } } else { content = JSON.stringify(config); } return self._saveConfig(beautify(content)); }) .then(function(config) { resolve(config); }) .catch(function(error) { reject(error); }); }); }
javascript
{ "resource": "" }
q5620
train
function(ast) { var self = this; var found; var meta = ast; var values = {}; jsstana.traverse(ast, function(node) { if (!found) { var match = jsstana.match('(ident META)', node); if (match) { jsstana.traverse(meta, function(node) { if (!found) { match = jsstana.match('(return)', node) || jsstana.match('(object)', node); if (match) { values = self._extractObjectValues(['path', 'fullPath', 'condition', 'group'], node); found = true; } } }); } else { meta = node; } } }); return values; }
javascript
{ "resource": "" }
q5621
train
function(idents, ast) { var self = this; var result = Object.create(null); var found; var ident; if (ast) { jsstana.traverse(ast, function(node) { if (found) { found = false; result[ident] = self._extractValue(node); } for (var i = 0; i < idents.length; i++) { ident = idents[i]; if (jsstana.match('(ident ' + ident + ')', node)) { found = true; break; } } }); } return result; }
javascript
{ "resource": "" }
q5622
train
function(node) { var self = this; var i; if (node.type === 'Literal') { return node.value; } else if (node.type === 'ObjectExpression') { var obj = {}; for (i = 0; i < node.properties.length; i++) { var property = node.properties[i]; obj[property.key.name] = self._extractValue(property.value); } return obj; } else if (node.type === 'ArrayExpression') { var arr = []; for (i = 0; i < node.elements.length; i++) { arr.push(self._extractValue(node.elements[i])); } return arr; } else if (node.type === 'FunctionExpression') { return recast.print(node, { wrapColumn: Number.Infinity }).code; } }
javascript
{ "resource": "" }
q5623
train
function() { var self = this; return new Promise(function(resolve, reject) { var config = {}; for (var i = 0; i < self._modules.length; i++) { var module = self._modules[i]; var storedModule = config[module.name] = { dependencies: module.dependencies }; if (module.condition) { storedModule.condition = module.condition; } if (!self._options.ignorePath) { if (module.fullPath) { storedModule.fullPath = upath.toUnix(module.fullPath); } else { var dirname = path.dirname(module.name); var modulePath = module.path || (dirname !== '.' ? dirname + '/' + module.file : module.file); storedModule.path = upath.toUnix(modulePath); } } } resolve(config); }); }
javascript
{ "resource": "" }
q5624
train
function(file) { var self = this; var ext; if (!self._options.keepExtension) { ext = self._options.extension || path.extname(file); } var fileName = path.basename(file, ext); if (self._options.format) { var formatRegex = self._options.format[0].split('/'); formatRegex = new RegExp(formatRegex[1], formatRegex[2]); var replaceValue = self._options.format[1]; fileName = fileName.replace(formatRegex, replaceValue); } var moduleConfig = { name: '', version: '1.0.0' }; if (self._options.moduleConfig) { if (typeof self._options.moduleConfig === 'string') { var fileModuleConfig = path.resolve(self._options.moduleConfig); if (fs.existsSync(fileModuleConfig)) { moduleConfig = require(fileModuleConfig); } } else { moduleConfig = self._options.moduleConfig; } } fileName = path.join(path.dirname(file), fileName); var moduleName = ''; if (moduleConfig.name) { moduleName = moduleConfig.name + '@' + moduleConfig.version; } moduleName = path.join(moduleName, fileName.substring(self._options.moduleRoot.length)); if (self._options.lowerCase) { moduleName = moduleName.toLowerCase(); } return upath.toUnix(moduleName); }
javascript
{ "resource": "" }
q5625
train
function(root, fileStats, next) { var self = this; var file = path.join(root, fileStats.name); if (minimatch(file, self._options.filePattern, { dot: true })) { self._processFile(file) .then(function(config) { next(); }); } else { next(); } }
javascript
{ "resource": "" }
q5626
train
function(file, content) { return new Promise(function(resolve, reject) { var ast = recast.parse(content); resolve(ast); }); }
javascript
{ "resource": "" }
q5627
train
function(file) { var self = this; return new Promise(function(resolve) { fs.readFileAsync(file, 'utf-8') .then(function(content) { return self._parseFile(file, content); }) .then(function(ast) { return self._getConfig(file, ast); }) .then(function(config) { self._modules = self._modules.concat(config); resolve(config); }); }); }
javascript
{ "resource": "" }
q5628
train
function(file, ast) { var content = recast.print(ast, { wrapColumn: Number.Infinity }).code; content = this._updateSourceMap(file, content); fs.writeFileSync(file, content); }
javascript
{ "resource": "" }
q5629
train
function(config) { var self = this; return new Promise(function(resolve, reject) { if (self._options.output) { fs.writeFileAsync(self._options.output, config) .then(function() { resolve(config); }); } else { resolve(config); } }); }
javascript
{ "resource": "" }
q5630
train
function(file, content) { var sourceMapURLMatch = REGEX_SOURCEMAP.exec(content); if (sourceMapURLMatch) { var sourceMapURL = sourceMapURLMatch[1]; if (sourceMapURL) { var sourceMapContent = fs.readFileSync(path.resolve(path.dirname(file), sourceMapURL), 'utf-8'); var consumer = new sourceMap.SourceMapConsumer(sourceMapContent); var node = sourceMap.SourceNode.fromStringWithSourceMap(content, consumer); var result = node.toStringWithSourceMap(); content = result.code; var map = result.map; fs.writeFileSync(path.resolve(path.dirname(file), sourceMapURL), JSON.stringify(map)); } } return content; }
javascript
{ "resource": "" }
q5631
train
function(cmd, showLog, next){ connection.exec(cmd, function(err, stream) { if (err) { grunt.log.errorlns(err); grunt.log.subhead('ERROR DEPLOYING. CLOSING CONNECTION AND DELETING RELEASE.'); deleteRelease(closeConnection); } stream.on('data', function(data, extended) { grunt.log.debug((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ') + data); }); stream.on('end', function() { grunt.log.debug('REMOTE: ' + cmd); if(!err) { next(); } }); }); }
javascript
{ "resource": "" }
q5632
train
function(callback) { connection.end(); client.close(); client.__sftp = null; client.__ssh = null; callback(); }
javascript
{ "resource": "" }
q5633
doMerge
train
function doMerge(source, target, opts) { return target instanceof Array ? mergeArrays(source, target) : mergeObjects(source, target, opts) }
javascript
{ "resource": "" }
q5634
getPackages
train
function getPackages() { var results = []; if (extensions && extensions.hasOwnProperty('packages')) { var sourceArray = extensions.packages; for (index = 0; index < sourceArray.length; ++index) { results.push(sourceArray[index]); } } return results; }
javascript
{ "resource": "" }
q5635
getPackagesTasks
train
function getPackagesTasks(baseTask) { var packages = getPackages(); var tasks = []; for (index = 0; index < packages.length; ++index) { tasks.push(baseTask + '.' + packages[index]); } return tasks; }
javascript
{ "resource": "" }
q5636
readModuleDirectory
train
function readModuleDirectory() { return _fsExtra2.default.existsSync((0, _config2.default)().moduleDirectoryPath()) ? _fsExtra2.default.readdirSync((0, _config2.default)().moduleDirectoryPath(), function (err, files) { return files; }).filter(_isNotModulesImportFile) : []; }
javascript
{ "resource": "" }
q5637
load
train
function load(PATH, sequelize, opts) { var files = fs.readdirSync(PATH), models = {}; opts = opts || {}; if (opts.exclude) { removeAll(opts.exclude, files); } files.forEach(function (file) { if (fs.statSync(path.join(PATH, file)).isDirectory()) { models[file] = load(path.join(PATH, file), sequelize, opts); } else { file = file.split('.')[0]; var model = sequelize.import(path.join(PATH, file)) models[model.name] = model; } }); return models; }
javascript
{ "resource": "" }
q5638
wrapAsyncFunction
train
function wrapAsyncFunction(fn, isSubAction) { if (!fn || fn.__asyncWrapped__) { return fn; } var wrapedFn = fn; if (typeof fn === 'function') { wrapedFn = function asyncWrap(req, res, next) { var maybePromise = fn(req, res, next); if (maybePromise && maybePromise.catch && typeof maybePromise.catch === 'function') { maybePromise.catch(next); } }; } for (var key in fn) { if (fn.hasOwnProperty(key)) { if (!isSubAction && VERB[key.toLowerCase()]) { // 仅在顶级Action中自动寻找VERB Action进行异步包裹 wrapedFn[key] = wrapAsyncFunction(fn[key], true); } else { // 其余对象仅复制 wrapedFn[key] = fn[key]; } } } wrapedFn.__asyncWrapped__ = true; return wrapedFn; }
javascript
{ "resource": "" }
q5639
getTemplates
train
function getTemplates(app) { var results = []; if (extensions && extensions.hasOwnProperty('templates') && extensions.templates.hasOwnProperty(app) ) { var sourceArray = extensions.templates[app]; for (index = 0; index < sourceArray.length; ++index) { results.push(app + '.' + sourceArray[index]); } } return results; }
javascript
{ "resource": "" }
q5640
parseNPMLL
train
function parseNPMLL(cb) { /* read the original package.json file and parse it */ const packagePath = path.join(process.cwd(), 'package.json') const packageJsonContent = fs.readFileSync(packagePath, 'utf8') const packageJson = JSON.parse(packageJsonContent) /* save a version of package.json with the privateSubmodules added to the dependencies object */ const privateSubmodules = packageJson.privateSubmodules const dependencies = packageJson.dependencies Object.keys(privateSubmodules || {}).forEach(key => { if (!dependencies.hasOwnProperty(key)) { dependencies[key] = privateSubmodules[key] } }) fs.writeFile(packagePath, JSON.stringify(packageJson), err => { if (err) throw err /* process the output of `npm ll` */ let output try { output = cp.execSync('npm ll --json', { env: process.env }) } catch (e) { output = e.stdout } /* restore the previous package.json */ fs.writeFile(packagePath, packageJsonContent, err => { if (err) throw err /* parse the output and call the callback */ let parsed try { parsed = JSON.parse(output) } catch (e) { console.warn('Cannot parse `npm ll` output:', e) parsed = null } cb(parsed) }) }) }
javascript
{ "resource": "" }
q5641
readObjectValue
train
function readObjectValue(object) { let result = '' if (typeof object === 'string' || object instanceof String) { result = object } else if (typeof object === 'number' || object instanceof Number) { result = object.toString() } else if (object) { Object.keys(object).forEach(key => { result += key + ': ' + object[key] + '\t' }) } if (!result.length) { result = 'Not Specified' } return result.replace(new RegExp('"', 'g'), '""') }
javascript
{ "resource": "" }
q5642
parseDependencies
train
function parseDependencies(info, runtimeDependencies, isParentRoot) { const dependencies = info.dependencies const devDependencies = info.devDependencies const nodeModulesPath = path.join(path.resolve('./'), 'node_modules/') let csv = '' /* licence */ /* URL */ /* description */ /* version */ /* type */ /* usage */ /* included in product */ /* in git repository */ /* dependency */ Object.keys(dependencies).forEach(key => { const dependency = dependencies[key] const name = readObjectValue(dependency.name) const version = readObjectValue(dependency.version) if (dependency.name && dependency.version) { const type = isParentRoot ? 'dependency' : 'sub-dependency' const usage = devDependencies.hasOwnProperty(key) ? 'development' : 'runtime' const included = !runtimeDependencies.hasOwnProperty(key) || !runtimeDependencies[key] ? 'No' : 'Yes' /* TODO: This could be done using `git check-ignore` for better results */ const inRepo = dependency.link && !dependency.link.startsWith(nodeModulesPath) ? 'Yes' : 'No' const license = readObjectValue(dependency.license) const url = readObjectValue( dependency.homepage || dependency.repository || null ) const description = readObjectValue(dependency.description) csv += '"' + name + '","' + version + '","' + type + '","' + usage + '","' + included + '","' + inRepo + '","' + license + '","' + url + '","' + description + '"\n' } if (dependency.dependencies) { csv += parseDependencies(dependency, runtimeDependencies, false) } }) return csv }
javascript
{ "resource": "" }
q5643
findRuntimeDependencies
train
function findRuntimeDependencies(webpackModules) { const runtimeDependencies = {} webpackModules.forEach(module => { const name = module.name if ( name.startsWith('./~/') || name.startsWith('./node_modules/') || name.startsWith('./lib/') ) { const components = name.split('/') let i = 2 let moduleName = '' let moduleComponent = components[i++] while (moduleComponent.startsWith('@')) { moduleName += moduleComponent + '/' moduleComponent = components[i++] } moduleName += moduleComponent runtimeDependencies[moduleName] = module.built && module.cacheable } }) return Object.assign({}, runtimeDependencies, alwaysRuntimeDependencies) }
javascript
{ "resource": "" }
q5644
buildOSSReport
train
function buildOSSReport(webpackModules, cb) { parseNPMLL(dependencies => { const runtimeDependencies = findRuntimeDependencies(webpackModules) const dependenciesCSV = parseDependencies( dependencies, runtimeDependencies, true ) cb( '"Dependency","Version","Type","Usage","Included In Product","In Git Repository","License","URL","Description"\n' + dependenciesCSV ) }) }
javascript
{ "resource": "" }
q5645
maybeMapOverVal
train
function maybeMapOverVal(fn, val) { var vals = val.split(','); if (vals.length > 1) { return vals.map(function(v) { return v == '.' ? null : fn(v); }); } return val == '.' ? null : fn(val); }
javascript
{ "resource": "" }
q5646
parseVCF
train
function parseVCF(text) { var lines = U.reject(text.split('\n'), function(line) { return line === ''; }); var partitions = U.partition(lines, function(line) { return line[0] === '#'; }); var header = parseHeader(partitions[0]), records = U.map(partitions[1], function(line) { return new Record(line, header); }); return {header: header, records: records}; }
javascript
{ "resource": "" }
q5647
runHook
train
function runHook (instance, type) { var hook = type ? 'response' : 'request' hook += 'Hook' if (instance[hook] && isFunction(instance[hook])) { instance[hook]() } }
javascript
{ "resource": "" }
q5648
isCustomMediaQuery
train
function isCustomMediaQuery(node) { return node.type === 'atrule' && node.name === 'custom-media' && customMediaQueryMatch.test(node.params); }
javascript
{ "resource": "" }
q5649
defaultAssigner
train
function defaultAssigner(rawproperty, rawvalue) { const property = rawproperty.replace(/-+(.|$)/g, ([ , letter]) => letter.toUpperCase()); return { [property]: rawvalue }; }
javascript
{ "resource": "" }
q5650
defaultJsExporter
train
function defaultJsExporter(variables, options, root) { const pathname = options.destination || root.source && root.source.input && root.source.input.file && root.source.input.file + '.js' || 'custom-variables.js'; const contents = Object.keys(variables).reduce( (buffer, key) => `${ buffer }export const ${ key } = ${ JSON.stringify(variables[key]).replace(/(^|{|,)"(.+?)":/g, '$1$2:') };\n`, '' ); return new Promise((resolve, reject) => { fs.writeFile( pathname, contents, (error) => error ? reject(error) : resolve() ); }); }
javascript
{ "resource": "" }
q5651
checkCacheResponse
train
function checkCacheResponse(key, err, result, type, cacheIndex){ if(err){ log(true, 'Error when getting key ' + key + ' from cache of type ' + type + ':', err); if(cacheIndex < self.caches.length - 1){ return {status:'continue'}; } } //THIS ALLOWS false AS A VALID CACHE VALUE, BUT DO I WANT null TO BE VALID AS WELL? if(result !== null && typeof result !== 'undefined'){ log(false, 'Key found:', {key: key, value: result}); return {status: 'break', result: result}; } var curCache = self.caches[cacheIndex]; for(var i = cacheIndex + 1; i < self.cachesLength; i++) { var nextCache = self.caches[i]; if(nextCache.checkOnPreviousEmpty || nextCache.expiration > curCache.expiration){ return {status:'continue', toIndex: i}; } } return {status: 'else'}; }
javascript
{ "resource": "" }
q5652
writeToVolatileCaches
train
function writeToVolatileCaches(currentCacheIndex, key, value){ if(currentCacheIndex > 0){ var curExpiration = self.caches[currentCacheIndex].expiration; for(var tempIndex = currentCacheIndex; tempIndex > -1; tempIndex--){ var preExpiration = self.caches[tempIndex].expiration; if(preExpiration <= curExpiration){ var preCache = self.caches[currentCacheIndex]; if(value){ preCache.set(key, value); /*This means that a more volatile cache can have a key longer than a less volatile cache. Should I adjust this?*/ } else if(typeof key === 'object'){ preCache.mset(key); } } } } }
javascript
{ "resource": "" }
q5653
log
train
function log(isError, message, data){ var indentifier = 'cacheService: '; if(self.verbose || isError){ if(data) { console.log(indentifier + message, data); } else { console.log(indentifier + message); } } }
javascript
{ "resource": "" }
q5654
getPlugins
train
function getPlugins() { var results = [] if (extensions && extensions.hasOwnProperty('plugins')) { for(var type in extensions.plugins) { var sourceArray = extensions.plugins[type]; for (index = 0; index < sourceArray.length; ++index) { results.push(type + '.' + sourceArray[index]); } } } return results; }
javascript
{ "resource": "" }
q5655
getPluginsTasks
train
function getPluginsTasks(baseTask) { var tasks = []; var plugins = getPlugins(); if (plugins) { for (pos = 0; pos < plugins.length; ++pos) { tasks.push(baseTask + '.' + plugins[pos]); } } return tasks; }
javascript
{ "resource": "" }
q5656
getModules
train
function getModules(app) { var results = []; if (extensions && extensions.hasOwnProperty('modules') && extensions.modules.hasOwnProperty(app) ) { var sourceArray = extensions.modules[app]; for (index = 0; index < sourceArray.length; ++index) { results.push(app + '.' + sourceArray[index]); } } return results; }
javascript
{ "resource": "" }
q5657
getModulesTasks
train
function getModulesTasks(baseTask, app) { var tasks = []; var modules = getModules(app); if (modules) { for (index = 0; index < modules.length; ++index) { tasks.push(baseTask + '.' + modules[index]); } } return tasks; }
javascript
{ "resource": "" }
q5658
getComponents
train
function getComponents() { var results = []; if (extensions && extensions.hasOwnProperty('components')) { var sourceArray = extensions.components; for (index = 0; index < sourceArray.length; ++index) { results.push(sourceArray[index]); } } return results; }
javascript
{ "resource": "" }
q5659
getComponentsTasks
train
function getComponentsTasks(baseTask) { var components = getComponents(); var tasks = []; for (index = 0; index < components.length; ++index) { tasks.push(baseTask + '.' + components[index]); } return tasks; }
javascript
{ "resource": "" }
q5660
get
train
function get(key, cb) { return type(key) != 'array' ? localForage.getItem(key).then(wrap(cb, true), cb) : Promise.all(key.map(getSubkey)).then(wrap(cb, true), cb); function getSubkey(key) { return get(key, function() {}); // noob function to prevent logs } }
javascript
{ "resource": "" }
q5661
set
train
function set(key, val, cb) { return type(key) != 'object' ? localForage.setItem(key, val).then(wrap(cb), cb) : Promise.all(Object.keys(key).map(setSubkey)).then(wrap(val), val); function setSubkey(subkey, next) { return key[subkey] === null ? del(subkey, next) : set(subkey, key[subkey], next); } }
javascript
{ "resource": "" }
q5662
del
train
function del(key, cb) { return type(key) != 'array' ? localForage.removeItem(key).then(wrap(cb), cb) : Promise.all(key.map(del)).then(wrap(cb), cb); }
javascript
{ "resource": "" }
q5663
wrap
train
function wrap(cb, hasResult) { return function(res) { if (type(cb) == 'function') { hasResult ? cb(null, res) : cb(); } else if (hasResult && storage.development) { console.log(res); } return res; }; }
javascript
{ "resource": "" }
q5664
getLibrariesTasks
train
function getLibrariesTasks(baseTask) { var libraries = getLibraries(); var tasks = []; for (index = 0; index < libraries.length; ++index) { tasks.push(baseTask + '.' + libraries[index]); } return tasks; }
javascript
{ "resource": "" }
q5665
init
train
function init(){ self.caches = []; if(isEmpty(cacheModules)){ log(false, 'No cacheModules array provided--using the default configuration.'); getDefaultConfiguration(); } else{ log(false, 'cacheModules array provided--using a custom configuration.'); getCustomConfiguration(); if(self.caches.length < 1){ throw new Exception('NoCacheException', 'No caches were succesfully initialized.'); } } }
javascript
{ "resource": "" }
q5666
getDefaultConfiguration
train
function getDefaultConfiguration(){ var CModule = require('cache-service-cache-module'); var cacheModule = new CModule(); cacheModule = addSettings(cacheModule); self.caches.push(cacheModule); }
javascript
{ "resource": "" }
q5667
getCustomConfiguration
train
function getCustomConfiguration(){ for(var i = 0; i < cacheModules.length; i++){ var cacheModule = cacheModules[i]; if(isEmpty(cacheModule)){ log(true, 'Cache module at index ' + i + ' is \'empty\'.'); continue; } cacheModule = addSettings(cacheModule); self.caches.push(cacheModule); } }
javascript
{ "resource": "" }
q5668
addSettings
train
function addSettings(cacheModule){ cacheModule.nameSpace = settings.nameSpace; cacheModule.verbose = settings.verbose; return cacheModule; }
javascript
{ "resource": "" }
q5669
isEmpty
train
function isEmpty (val) { return (val === undefined || val === false || val === null || (typeof val === 'object' && Object.keys(val).length === 0)); }
javascript
{ "resource": "" }
q5670
injectAdditionalFunctions
train
function injectAdditionalFunctions (funcs, additionalFunctions) { // Nothing to do if no additional function is given. if (no(additionalFunctions)) return /** * Validate and insert an additional function. */ function injectAdditionalFunction (key) { var isAFunction = typeof additionalFunctions[key] === 'function' if (isAFunction) funcs[key] = additionalFunctions[key] } Object.keys(additionalFunctions) .forEach(injectAdditionalFunction) }
javascript
{ "resource": "" }
q5671
injectAdditionalFunction
train
function injectAdditionalFunction (key) { var isAFunction = typeof additionalFunctions[key] === 'function' if (isAFunction) funcs[key] = additionalFunctions[key] }
javascript
{ "resource": "" }
q5672
walkGlobal
train
function walkGlobal (taskName) { // Skip dot operator and tasks that start with a dot. if (taskName.indexOf('.') === 0) return // Skip stuff that may include dots: // * comments // * strings // * numbers // * references if (regexComment.test(taskName)) return if (parseFloat(taskName)) return if (regexQuoted.test(taskName)) return if (regexReference.test(taskName)) return function toNextProp (next, prop) { return next[prop] } return taskName.split('.') .reduce(toNextProp, globalContext) }
javascript
{ "resource": "" }
q5673
compileSubgraph
train
function compileSubgraph (key) { var subGraph = graph.func[key] var funcName = '/' + key funcs[funcName] = fun(subGraph, additionalFunctions) }
javascript
{ "resource": "" }
q5674
byLevel
train
function byLevel (a, b) { if (no(cachedLevelOf[a])) cachedLevelOf[a] = computeLevelOf(a) if (no(cachedLevelOf[b])) cachedLevelOf[b] = computeLevelOf(b) return cachedLevelOf[a] - cachedLevelOf[b] }
javascript
{ "resource": "" }
q5675
checkTaskIsCompiled
train
function checkTaskIsCompiled (taskKey) { var taskName = task[taskKey] // Ignore tasks injected at run time. if (reservedKeys.indexOf(taskName) > -1) return var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' // Check subgraphs. if (regexSubgraph.test(taskName)) { var subgraphKey = taskName.substring(1) if (no(graph.func[subgraphKey])) { var subgraphNotFound = new Error(msg) subgraphNotFound.taskKey = taskKey subgraphNotFound.taskName = taskName throw subgraphNotFound } else return } // Skip dflow DSL. if (isDflowDSL(taskName)) return // Skip globals. if (walkGlobal(taskName)) return if (no(funcs[taskName])) { var subgraphNotCompiled = new Error(msg) subgraphNotCompiled.taskKey = taskKey subgraphNotCompiled.taskName = taskName throw subgraphNotCompiled } }
javascript
{ "resource": "" }
q5676
run
train
function run (taskKey) { var args = inputArgs(outs, pipe, taskKey) var taskName = task[taskKey] var f = funcs[taskName] // Behave like a JavaScript function: // if found a return, skip all other tasks. if (gotReturn) return if ((taskName === 'return') && (!gotReturn)) { returnValue = args[0] gotReturn = true return } // If task is not defined at run time, throw an error. if (no(f)) { var taskNotFound = new Error('Task not found: ' + taskName + ' [' + taskKey + '] ') taskNotFound.taskKey = taskKey taskNotFound.taskName = taskName } // Try to execute task. try { outs[taskKey] = f.apply(null, args) } catch (err) { // Enrich error with useful dflow task info. err.taskName = taskName err.taskKey = taskKey throw err } }
javascript
{ "resource": "" }
q5677
mount
train
function mount(data) { var promises = []; this.each(function() { var view = select(this).view(); if (view) promises.push(mountElement(this, view, data)); else warn("Cannot mount, no view object available to mount to"); }); return Promise.all(promises); }
javascript
{ "resource": "" }
q5678
Manager
train
function Manager(records) { let sel, nodes, node, vm; records.forEach(record => { nodes = record.removedNodes; if (!nodes || !nodes.length) return; vm = record.target ? select(record.target).view() : null; for (let i = 0; i < nodes.length; ++i) { node = nodes[i]; if (!node.querySelectorAll || node.__d3_component__) continue; sel = select(node); if (vm || sel.view()) { sel.selectAll("*").each(destroy); destroy.call(nodes[i]); } } }); }
javascript
{ "resource": "" }
q5679
appendCwd
train
function appendCwd (givenPath) { return path.isAbsolute(givenPath) ? givenPath : path.join(process.cwd(), givenPath) }
javascript
{ "resource": "" }
q5680
HttpError
train
function HttpError(message, options) { // handle constructor call without 'new' if (!(this instanceof HttpError)) { return new HttpError(message, options); } HttpError.super_.call(this); Error.captureStackTrace(this, this.constructor); this.name = 'HttpError'; this.message = message; this.status = 500; options = options || {}; if (options.code) { this.code = options.code; } if (options.errors) { this.errors = options.errors; } if (options.headers) { this.headers = options.headers; } if (options.cause) { this.cause = options.cause; } }
javascript
{ "resource": "" }
q5681
getErrorNameFromStatusCode
train
function getErrorNameFromStatusCode(statusCode) { statusCode = parseInt(statusCode, 10); var status = http.STATUS_CODES[statusCode]; if (!status) { return false; } var name = ''; var words = status.split(/\s+/); words.forEach(function(w) { name += w.charAt(0).toUpperCase() + w.slice(1).toLowerCase(); }); name = name.replace(/\W+/g, ''); if (!/\w+Error$/.test(name)) { name += 'Error'; } return name; }
javascript
{ "resource": "" }
q5682
parents
train
function parents (pipe, taskKey) { var inputPipesOf = inputPipes.bind(null, pipe) var parentTaskIds = [] function pushParentTaskId (pipe) { parentTaskIds.push(pipe[0]) } inputPipesOf(taskKey).forEach(pushParentTaskId) return parentTaskIds }
javascript
{ "resource": "" }
q5683
injectNumbers
train
function injectNumbers (funcs, task) { /** * Inject a function that returns a number. */ function inject (taskKey) { var taskName = task[taskKey] var num = parseFloat(taskName) if (!isNaN(num)) { funcs[taskName] = function () { return num } } } Object.keys(task) .forEach(inject) }
javascript
{ "resource": "" }
q5684
inject
train
function inject (taskKey) { var taskName = task[taskKey] var num = parseFloat(taskName) if (!isNaN(num)) { funcs[taskName] = function () { return num } } }
javascript
{ "resource": "" }
q5685
Model
train
function Model(schema, examples, options) { options = options || {}; this._schema = schema || null; this._examples = examples || {}; this._additionalValidators = options.additionalValidators || []; this.debugConstructor = options.debug || debug; this.debug = this.debugConstructor(this.debugTopic || 'oada:model'); this.errorConstructor = options.error || debug; this.error = this.errorConstructor(this.errorTopic || 'oada:model:error'); }
javascript
{ "resource": "" }
q5686
injectAccessors
train
function injectAccessors (funcs, graph) { if (no(graph.data)) graph.data = {} funcs['this.graph.data'] = function () { return graph.data } /** * Inject accessor. * * @param {String} taskKey */ function inject (taskKey) { var accessorName = null var taskName = graph.task[taskKey] /** * Accessor-like function. * * @param {*} data that JSON can serialize */ function accessor (data) { // Behave like a setter if an argument is provided. if (arguments.length === 1) { var json = JSON.stringify(data) if (no(json)) { throw new Error('JSON do not serialize data:' + data) } graph.data[accessorName] = data } // Always behave also like a getter. return graph.data[accessorName] } if (regexAccessor.test(taskName)) { accessorName = taskName.substring(1) funcs[taskName] = accessor } } Object.keys(graph.task).forEach(inject) }
javascript
{ "resource": "" }
q5687
inject
train
function inject (taskKey) { var accessorName = null var taskName = graph.task[taskKey] /** * Accessor-like function. * * @param {*} data that JSON can serialize */ function accessor (data) { // Behave like a setter if an argument is provided. if (arguments.length === 1) { var json = JSON.stringify(data) if (no(json)) { throw new Error('JSON do not serialize data:' + data) } graph.data[accessorName] = data } // Always behave also like a getter. return graph.data[accessorName] } if (regexAccessor.test(taskName)) { accessorName = taskName.substring(1) funcs[taskName] = accessor } }
javascript
{ "resource": "" }
q5688
accessor
train
function accessor (data) { // Behave like a setter if an argument is provided. if (arguments.length === 1) { var json = JSON.stringify(data) if (no(json)) { throw new Error('JSON do not serialize data:' + data) } graph.data[accessorName] = data } // Always behave also like a getter. return graph.data[accessorName] }
javascript
{ "resource": "" }
q5689
injectDotOperators
train
function injectDotOperators (funcs, task) { /** * Inject dot operator. */ function inject (taskKey) { var taskName = task[taskKey] /** * Dot operator function. * * @param {String} attributeName * @param {Object} obj * @param {...} rest of arguments * * @returns {*} result */ function dotOperatorFunc (attributeName, obj) { var func if (obj) func = obj[attributeName] if (typeof func === 'function') { return func.apply(obj, Array.prototype.slice.call(arguments, 2)) } } if (regexDotOperator.func.test(taskName)) { // .foo() -> foo funcs[taskName] = dotOperatorFunc.bind(null, taskName.substring(1, taskName.length - 2)) } /** * Dot operator attribute write. * * @param {String} attributeName * @param {Object} obj * @param {*} attributeValue * * @returns {Object} obj modified */ function dotOperatorAttributeWrite (attributeName, obj, attributeValue) { obj[attributeName] = attributeValue return obj } if (regexDotOperator.attrWrite.test(taskName)) { // .foo= -> foo funcs[taskName] = dotOperatorAttributeWrite.bind(null, taskName.substring(1, taskName.length - 1)) } /** * Dot operator attribute read. * * @param {String} attributeName * @param {Object} obj * * @returns {*} attribute */ function dotOperatorAttributeRead (attributeName, obj) { var attr if (obj) attr = obj[attributeName] if (typeof attr === 'function') return attr.bind(obj) return attr } if (regexDotOperator.attrRead.test(taskName)) { // .foo -> foo funcs[taskName] = dotOperatorAttributeRead.bind(null, taskName.substring(1)) } } Object.keys(task).forEach(inject) }
javascript
{ "resource": "" }
q5690
dotOperatorFunc
train
function dotOperatorFunc (attributeName, obj) { var func if (obj) func = obj[attributeName] if (typeof func === 'function') { return func.apply(obj, Array.prototype.slice.call(arguments, 2)) } }
javascript
{ "resource": "" }
q5691
dotOperatorAttributeRead
train
function dotOperatorAttributeRead (attributeName, obj) { var attr if (obj) attr = obj[attributeName] if (typeof attr === 'function') return attr.bind(obj) return attr }
javascript
{ "resource": "" }
q5692
defaultResponse
train
function defaultResponse(response) { var level = response.status < 300 ? "info" : response.status < 500 ? "warning" : "error"; this.$emit("formMessage", { level: level, data: response.data, response: response }); }
javascript
{ "resource": "" }
q5693
displayButton
train
function displayButton(state, button) { lcd.clear(); lcd.message('Button: ' + lcd.buttonName(button) + '\nState: ' + state); console.log(state, lcd.buttonName(button)); }
javascript
{ "resource": "" }
q5694
train
function (values) { // first assume ret is already object with 'known': var ret = values; // if it's an array, replace with object that has 'known': if (_.isArray(values)) { ret = { known: values }; } // Make sure it has a type: if (!ret.type) { ret.type = 'string' }; // Add enum if running in strict mode: if (config.get('strict')) { ret.enum = ret.known; } return ret; }
javascript
{ "resource": "" }
q5695
evalTasks
train
function evalTasks (funcs, task) { /** * Evaluate a single task and inject it. * * @param {String} taskKey */ function inject (taskKey) { var taskName = task[taskKey] try { var e = eval(taskName) // eslint-disable-line if (typeof e === 'function') { funcs[taskName] = e } else { funcs[taskName] = function () { return e } } } catch (err) { var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' + err throw new Error(msg) } } Object.keys(task) .filter(reserved(task)) .filter(dflowDSL(task)) .filter(alreadyDefined(funcs, task)) .forEach(inject) }
javascript
{ "resource": "" }
q5696
inject
train
function inject (taskKey) { var taskName = task[taskKey] try { var e = eval(taskName) // eslint-disable-line if (typeof e === 'function') { funcs[taskName] = e } else { funcs[taskName] = function () { return e } } } catch (err) { var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' + err throw new Error(msg) } }
javascript
{ "resource": "" }
q5697
addVocabAsProperties
train
function addVocabAsProperties(schema, terms_array) { if (!schema.properties) schema.properties = {}; var propertySchema = schema.propertySchema || {}; _.each(terms_array, function(term) { schema.properties[term] = vocab(term) if (propertySchema) { if (propertySchema.known) { propertySchema.known.push(term); } if (propertySchema.enum) { propertySchema.enum.push(term); } } }); }
javascript
{ "resource": "" }
q5698
recursivelyChangeAllAdditionalProperties
train
function recursivelyChangeAllAdditionalProperties(schema, newvalue) { if (!schema) return; // First set additionalProperties if it's here: if (typeof schema.additionalProperties !== 'undefined') { schema.additionalProperties = newvalue; } // Then check any child properties for the same: _.each(_.keys(schema.properties), function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); // Then check any child patternProperties for the same: _.each(_.keys(schema.patternProperties), function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); // Then check for anyOf, allOf, oneOf _.each(schema.anyOf, function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); _.each(schema.allOf, function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); _.each(schema.oneOf, function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); // ignoring 'not' for now }
javascript
{ "resource": "" }
q5699
inputPipes
train
function inputPipes (pipe, taskKey) { var pipes = [] function pushPipe (key) { pipes.push(pipe[key]) } function ifIsInputPipe (key) { return pipe[key][1] === taskKey } Object.keys(pipe).filter(ifIsInputPipe).forEach(pushPipe) return pipes }
javascript
{ "resource": "" }