_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q8500
loadIntegrationsHook
train
function loadIntegrationsHook(region, context, endpoints, integrationResults) { return require('./hooks/load-integration').hook(region, context, endpoints, integrationResults); }
javascript
{ "resource": "" }
q8501
train
function (hash, capacity) { if (!hash) hash = 255; if (!capacity) capacity = hash * 4; this._hash = hash; this._capacity = capacity; this._nextId = 0; this._shards = []; this._indexes = []; }
javascript
{ "resource": "" }
q8502
setSelectValue
train
function setSelectValue (elem, value) { var optionSet, option var options = elem.options var values = makeArray(value) var i = options.length while (i--) { option = options[ i ] /* eslint-disable no-cond-assign */ if (values.indexOf(option.value) > -1) { option.setAttribute('selected', true) optionSet = true } /* eslint-enable no-cond-assign */ } // Force browsers to behave consistently when non-matching value is set if (!optionSet) { elem.selectedIndex = -1 } }
javascript
{ "resource": "" }
q8503
disambiguateInvocation
train
function disambiguateInvocation() { if (req.body && !req._explicitMime) { req.setHeader('Content-Type', req.body); req.removeHeader('Content-Length'); req.body = null; } }
javascript
{ "resource": "" }
q8504
realRequirPath
train
function realRequirPath(filePath) { // console.log('realRequirPath:filePath: ' + filePath); var jsFilePath = filePath + '.js'; if (fs.existsSync(filePath)) { if (fs.statSync(filePath).isDirectory()) { jsFilePath = filePath + '.js'; if (fs.existsSync(jsFilePath)) { return jsFilePath; } else { jsFilePath = path.join(filePath, 'index.js'); } // console.log('realRequirPath:jsFilePath: ' + jsFilePath); } else if (fs.statSync(filePath).isFile()) { return filePath; } else { return null; } } else { jsFilePath = filePath + '.js'; // console.log('realRequirPath:filePath: ' + filePath); } if (fs.existsSync(jsFilePath)) { // console.log('realRequirPath:filePath: ' + filePath); return jsFilePath; } else { return null; } }
javascript
{ "resource": "" }
q8505
subModulePath
train
function subModulePath(subModule, node_modules) { var index = subModule.indexOf("/"); var length = subModule.length; if (index <= 0 || index + 1 == length) { return null; } var module = subModule.substring(0, index); var relative = subModule.substring(index + 1, length); var moduleDirectory = path.join(node_modules, module); var filePath = path.join(moduleDirectory, relative); return realRequirPath(filePath); }
javascript
{ "resource": "" }
q8506
modulePath
train
function modulePath(module, node_modules) { var pkgFile = path.join(node_modules, module, 'package.json'); if (!fs.existsSync(pkgFile)) { return null; } var data = fs.readFileSync(pkgFile, 'utf8'); var pkg = JSON.parse(data); var fileName = pkg.main || 'index.js'; var filePath = path.join(node_modules, module, fileName); return realRequirPath(filePath); }
javascript
{ "resource": "" }
q8507
requirePath
train
function requirePath(fromPath, require) { // console.log('requirePath:fromPath: ' + fromPath); // console.log('requirePath:require: ' + require); if (fromPath === null || fromPath === undefined || require === null || require === undefined) { return null; } var filePath = path.resolve(path.dirname(fromPath), require); return realRequirPath(filePath); }
javascript
{ "resource": "" }
q8508
targetPath
train
function targetPath(fromPath, basePath, targetDirectory) { // console.log('targetPath:fromPath: ' + fromPath); // console.log('targetPath:basePath: ' + basePath); // console.log('targetPath:targetDirectory: ' + targetDirectory); var relativePath = path.relative(basePath, fromPath); // console.log('targetPath:relativePath: ' + relativePath); // console.log('targetPath: ' + path.resolve(targetDirectory, relativePath)); return path.resolve(targetDirectory, relativePath); }
javascript
{ "resource": "" }
q8509
relativePath
train
function relativePath(from, to) { // console.log('relativePath:from: ' + from); // console.log('relativePath:to: ' + to); var relative = path.relative(from, to); if (!relative || relative.length < 1) { return relative; } var first = relative.substr(0, 1); if (first !== '.' && first !== '/') { relative = './' + relative; } // especially used for windows relative = relative.split(path.sep).join('/'); return relative; }
javascript
{ "resource": "" }
q8510
replaceRenderer
train
function replaceRenderer(md, renderer) { var openMethodName = renderer.fullName + "_open"; replacedMethods[openMethodName] = md.renderer.rules[openMethodName]; md.renderer.rules[openMethodName] = function (tokens, idx) { var classy, result; // first get the result as per the original method we replaced result = replacedMethods[openMethodName].apply(null, arguments).trim(); if (renderer.inline) { classy = getClassyFromInlineElement(tokens, idx, renderer.fullName); } else { classy = getClassyFromBlockElement(tokens, idx, renderer.fullName); } if (classy) { result = result.replace(new RegExp("<" + renderer.pattern), "$& class=\"" + classy.content + "\""); } return result; }; }
javascript
{ "resource": "" }
q8511
Logger
train
function Logger(options) { if (!options) { options = { }; } if (typeof options.level === 'undefined') { options.level = 'debug'; } if (!options.transports) { options.transports = [new Transport(options)]; delete options.name; delete options.hostname; delete options.timestamp; delete options.formatter; } Logger.super_.call(this, options); this.setLevels(options.levels || Levels); }
javascript
{ "resource": "" }
q8512
Transport
train
function Transport(options) { if (!options) { options = { }; } this.name = options.name || 'ecs-logs'; this.level = options.level || 'debug'; this.output = options.output || function(s) { process.stdout.write(s + '\n'); }; this.timestamp = options.timestamp || Date.now; this.formatter = options.formatter || new Formatter({ hostname: options.hostname }); }
javascript
{ "resource": "" }
q8513
Formatter
train
function Formatter(options) { function format(entry) { // eslint-disable-line return stringify(makeEvent(entry, format.hostname)); } if (!options) { options = { }; } Object.setPrototypeOf(format, Formatter.prototype); format.hostname = options.hostname || os.hostname(); return format; }
javascript
{ "resource": "" }
q8514
makeEvent
train
function makeEvent(entry, hostname) { var errors = extractErrors(entry.meta); var event = { level: entry.level ? entry.level.toUpperCase() : 'NONE', time: new Date( entry.timestamp ? entry.timestamp() : Date.now() ).toISOString(), info: { }, data: entry.meta || { }, message: entry.message || '' }; if (hostname) { event.info.host = hostname; } if (errors.length) { errors.forEach(function(e, i) { errors[i] = makeEventError(e); }); event.info.errors = errors; } return event; }
javascript
{ "resource": "" }
q8515
makeEventError
train
function makeEventError(error) { var stack = error.stack.split('\n'); stack.splice(0, 1); stack.forEach(function(s, i) { stack[i] = s.trim(); }); return { type: typeName(error), error: error.message, stack: stack.filter(function(s) { return s; }) }; }
javascript
{ "resource": "" }
q8516
extractErrors
train
function extractErrors(obj) { if (obj instanceof Error) { return [obj]; } var errors = []; if (obj) { Object.keys(obj).forEach(function(key) { var val = obj[key]; if (val instanceof Error) { errors.push(val); delete obj[key]; } }); } return errors; }
javascript
{ "resource": "" }
q8517
addRemoveToggleClass
train
function addRemoveToggleClass (context, className, method) { // Split by spaces, then remove empty elements caused by extra whitespace const classNames = trimAndSplit(className); if (classNames.length) { context.forEach(element => { if (method !== "toggle") { // 'add' and 'remove' accept multiple parameters… element.classList[method](...classNames); } else { // while 'toggle' accepts only one classNames.forEach(className => element.classList.toggle(className)) } }); } return context; }
javascript
{ "resource": "" }
q8518
getSetRemoveProperty
train
function getSetRemoveProperty (collection, property, value) { if (isUndefined(value)) { // get property of first element if there is one return collection[0] ? collection[0][property] : undefined; } else if (value !== null) { collection.forEach(element => element[property] = value) } else { collection.forEach(element => delete element[property]) } return collection; }
javascript
{ "resource": "" }
q8519
getDimension
train
function getDimension (collection, dimension) { const first = collection[0]; if (first && typeof first.getBoundingClientRect === "function") { return first.getBoundingClientRect()[dimension]; } }
javascript
{ "resource": "" }
q8520
callNodeMethod
train
function callNodeMethod(targets, subjects, method, returnTargets) { targets.forEach(target => { const subject = targets.indexOf(target) ? clone(subjects, true) : subjects; if (isIterable(subjects)) { target[method](...subject); } else { target[method](subject); } normalize(target); }); return returnTargets ? targets : subjects; }
javascript
{ "resource": "" }
q8521
normalize
train
function normalize(node, method) { if (method === "prepend" || method === "append") { node.normalize(); } else if (node.parentNode) { node.parentNode.normalize(); } }
javascript
{ "resource": "" }
q8522
clone
train
function clone(collection, deep = true) { const clones = new Jamon(); collection.forEach(element => clones.push(element.cloneNode(deep))); return clones; }
javascript
{ "resource": "" }
q8523
getProxiedListener
train
function getProxiedListener (listener, selector) { // get existing proxy storage of the listener let proxies = listener[proxyKey]; // the proxy to return let proxy; // or create the storage if (isUndefined(proxies)) { proxies = new Map(); listener[proxyKey] = proxies; } if (proxies.has(selector)) { // a proxy for this selector already exists - get it proxy = proxies.get(selector); } else { // create a new proxy for this selector proxy = function (e) { const target = e.target; // only call the listener if the target matches the selector if (target.matches(selector)) { listener.call(target, e); } } // store proxy proxies.set(selector, proxy); } return proxy; }
javascript
{ "resource": "" }
q8524
walkDirRecursive
train
function walkDirRecursive(arr, currentDirPath) { fs.readdirSync(currentDirPath).forEach(function (name) { var filePath = path.join(currentDirPath, name); var stat = fs.statSync(filePath); if (stat.isDirectory()) { arr = walkDirRecursive(arr, filePath); } else { arr.push(filePath); } }); return arr; }
javascript
{ "resource": "" }
q8525
SVGSprite
train
function SVGSprite(options) { options = _.extend({}, options); // Validate & prepare the options this._options = _.extend(defaultOptions, options); this._options.prefix = (new String(this._options.prefix || '').trim()) || null; this._options.common = (new String(this._options.common || '').trim()) || null; this._options.maxwidth = Math.abs(parseInt(this._options.maxwidth || 1000, 10)); this._options.maxheight = Math.abs(parseInt(this._options.maxheight || 1000, 10)); this._options.padding = Math.abs(parseInt(this._options.padding, 10)); this._options.pseudo = (new String(this._options.pseudo).trim()) || '~'; this._options.dims = !!this._options.dims; this._options.verbose = Math.min(Math.max(0, parseInt(this._options.verbose, 10)), 3); this._options.render = _.extend({css: true}, this._options.render); this._options.cleanwith = (new String(this._options.cleanwith || '').trim()) || null; this._options.cleanconfig = _.extend({}, this._options.cleanconfig || {}); this.namespacePow = []; // Reset all internal stacks this._reset(); var SVGO = require('svgo'); this._options.cleanconfig.plugins = svgoDefaults.concat(this._options.cleanconfig.plugins || []); this._cleaner = new SVGO(this._options.cleanconfig); this._clean = this._cleanSVGO; }
javascript
{ "resource": "" }
q8526
executeCommand
train
function executeCommand(parameters) { if (parameters.colors === undefined) { parameters.colors = plugin.myrmex.getConfig('colors'); } return plugin.findApi(parameters.apiIdentifier) .then(api => { return api.generateSpec(parameters.specVersion); }) .then(jsonSpec => { let spec = JSON.stringify(jsonSpec, null, 2); if (parameters.colors) { spec = icli.highlight(spec, { json: true }); } icli.print(spec); return Promise.resolve(jsonSpec); }); }
javascript
{ "resource": "" }
q8527
check
train
function check(value, ...validators) { let valid = false; _.each(validators, (validator) => { return !(valid = validator(value)); }); if (!valid) { throw new TypeError('Argument is not any of the accepted types.'); } }
javascript
{ "resource": "" }
q8528
delimsObject
train
function delimsObject(delims) { var a = delims[0], b = delims[1]; var res = {}; res.interpolate = lazy.delimiters(a + '=', b); res.evaluate = lazy.delimiters(a, b); res.escape = lazy.delimiters(a + '-', b); return res; }
javascript
{ "resource": "" }
q8529
inspectHelpers
train
function inspectHelpers(settings, opts) { var helpers = Object.keys(settings.imports); for (var key in opts) { if (helpers.indexOf(key) !== -1) { conflictMessage(settings, opts, key); } } }
javascript
{ "resource": "" }
q8530
hasOfType
train
function hasOfType(value, path, validator) { return _.has(value, path) ? validator(_.get(value, path)) : false; }
javascript
{ "resource": "" }
q8531
mkdirParents
train
function mkdirParents(dirPath) { dirPath.split(/\/|\\/).reduce(function(parents, dir) { var path = pathUtil.resolve((parents += dir + pathUtil.sep)); // normalize if (!fs.existsSync(path)) { fs.mkdirSync(path); } else if (!fs.statSync(path).isDirectory()) { throw new Error('Non directory already exists: ' + path); } return parents; }, ''); }
javascript
{ "resource": "" }
q8532
readStdin
train
function readStdin() { var stdin = process.stdin, fd = stdin.isTTY && process.platform !== 'win32' ? fs.openSync('/dev/tty', 'rs') : stdin.fd, bufSize = stdin.isTTY ? DEFAULT_BUF_SIZE : (fs.fstatSync(fd).size || DEFAULT_BUF_SIZE), buffer = Buffer.allocUnsafe && Buffer.alloc ? Buffer.alloc(bufSize) : new Buffer(bufSize), rsize, input = ''; while (true) { rsize = 0; try { rsize = fs.readSync(fd, buffer, 0, bufSize); } catch (e) { if (e.code === 'EOF') { break; } throw e; } if (rsize === 0) { break; } input += buffer.toString(program.encoding, 0, rsize); } return input; }
javascript
{ "resource": "" }
q8533
dispatch
train
function dispatch(event, scope){ var key, handler, k, i, modifiersMatch; key = event.keyCode; // if a modifier key, set the key.<modifierkeyname> property to true and return if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko if(key in _mods) { _mods[key] = true; // 'assignKey' from inside this closure is exported to window.key for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true; return; } // see if we need to ignore the keypress (ftiler() can can be overridden) // by default ignore key presses if a select, textarea, or input is focused if(!assignKey.filter.call(this, event)) return; // abort if no potentially matching shortcuts found if (!(key in _handlers)) return; // for each potential shortcut for (i = 0; i < _handlers[key].length; i++) { handler = _handlers[key][i]; // see if it's in the current scope if(handler.scope == scope || handler.scope == 'all'){ // check if modifiers match if any modifiersMatch = handler.mods.length > 0; for(k in _mods) if((!_mods[k] && index(handler.mods, +k) > -1) || (_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false; // call the handler and stop the event if neccessary if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){ if(handler.method(event, handler)===false){ if(event.preventDefault) event.preventDefault(); else event.returnValue = false; if(event.stopPropagation) event.stopPropagation(); if(event.cancelBubble) event.cancelBubble = true; } } } } }
javascript
{ "resource": "" }
q8534
getMatches
train
function getMatches(str, re) { if (str == null) { return null; } if (re == null) { return null; } var results = []; var match; while ((match = re.exec(str)) !== null) { results.push(match[1]); } return results; }
javascript
{ "resource": "" }
q8535
transformFile
train
function transformFile(from, to, modulesDirectory) { var contents = fs.readFileSync(from, 'utf8'); // modules var modules = getModules(contents); for (var index in modules) { var module = modules[index]; if (modulesManifest.hasOwnProperty(module)) { continue; } var modulePath = path_util.modulePath(module, node_modules); if (modulePath === null) { continue; } var targetPath = path_util.targetPath(modulePath, node_modules, modulesDirectory); modulesManifest[module] = path.relative(process.cwd(), targetPath); if (!fs.existsSync(targetPath)) { transformFile(modulePath, targetPath, modulesDirectory); } var relativePath = path_util.relativePath(to, targetPath); var re = eval('\/require\\\(\[\'\"\]' + module + '\[\'\"\]\\\)\/ig'); contents = contents.replace(re, 'require(\'' + relativePath + '\')'); } // requires var requires = getRequires(contents); for (var index in requires) { var require = requires[index]; var requirePath = path_util.requirePath(from, require); if (requirePath === null) { continue; } if (requiresManifest.hasOwnProperty(requirePath)) { continue; } else { requiresManifest[requirePath] = true; } var targetPath = path_util.targetPath(requirePath, node_modules, modulesDirectory); if (!fs.existsSync(targetPath)) { transformFile(requirePath, targetPath, modulesDirectory); } } var dirname = path.dirname(to); fs.mkdirsSync(dirname); fs.writeFileSync(to, contents, 'utf8'); }
javascript
{ "resource": "" }
q8536
parseMappedStack
train
function parseMappedStack(stack) { let result = [] for (let line of stack) { // at ... (file:///namespace/path:line:column) const MATCHED = line.match(/\(.*?:\/{3}(.*?)\/(.*):(.*?):(.*?)\)$/) // The line couldn’t be parsed. if (!MATCHED){ result.push({stackLine: line}) continue } result.push({ column: MATCHED[4], line: MATCHED[3], namespace: MATCHED[1], path: MATCHED[2], stackLine: line, }) } return result }
javascript
{ "resource": "" }
q8537
sign
train
function sign(value) { let sign = NaN; if (_.isNumber(value)) { if (value === 0) { sign = value; } else if (value >= 1) { sign = 1; } else if (value <= -1) { sign = -1; } } return sign; }
javascript
{ "resource": "" }
q8538
baseGetType
train
function baseGetType(validator, baseDefault, value, replacement) { let result; if (validator(value)) { result = value; } else if (validator(replacement)) { result = replacement; } else { result = baseDefault; } return result; }
javascript
{ "resource": "" }
q8539
use
train
function use (hardware, callback) { if (!hardware) { // Set default configuration hardware = require('tessel').port['GPIO'].pin['A1']; } return new PulseSensor(hardware, callback); }
javascript
{ "resource": "" }
q8540
parse
train
function parse(fileString, callback) { return NginxConf.parse(fileString, function(err, _config) { if (err) { return callback(err); } return parseNginxConf(_config, callback); }); }
javascript
{ "resource": "" }
q8541
parseFile
train
function parseFile(filePath, encoding, callback) { return fs.readFile(filePath, encoding, function(err, fileString) { if (err) { return callback(err); } fileString = expandIncludes(fileString, path.dirname(filePath)); return parse(fileString, callback); }); }
javascript
{ "resource": "" }
q8542
isOPInt
train
function isOPInt (value) { return types.Number(value) && ((value === OPS.OP_0) || (value >= OPS.OP_1 && value <= OPS.OP_16) || (value === OPS.OP_1NEGATE)); }
javascript
{ "resource": "" }
q8543
getConnection
train
function getConnection(connectionString) { return new Promise(function(resolve, reject) { // If connectionString is null or undefined, return an error. if (_.isEmpty(connectionString)) { return reject('getConnection must be called with a mongo connection string'); } // Check if a connection already exists for the provided connectionString. var pool = _.findWhere(connections, { connectionString: connectionString }); // If a connection pool was found, resolve the promise with it. if (pool) { return resolve(pool.db); } // If the connection pool has not been instantiated, // instantiate it and return the connection. MongoClient.connect(connectionString, function(err, database) { if (err) { return reject(err); } // Store the connection in the connections array. connections.push({ connectionString: connectionString, db: database }); return resolve(database); }); }); }
javascript
{ "resource": "" }
q8544
initDB
train
function initDB () { return db.listDatabases() .then(response => { if (response.data.indexOf(dbName) !== -1) { // database already exists return Promise.resolve('ok') } else { // create new database return db.createDatabase(dbName).then(() => 'ok') } }) }
javascript
{ "resource": "" }
q8545
initDocument
train
function initDocument (docName) { return db.getDocument(dbName, docName) .then(response => response.data._rev) // document already exists .catch(response => { if (response.status === 404) { // create new document return db.createDocument(dbName, {foo: 'bar'}, docName) .then(response => response.data.rev) } else { // real error return Promise.reject(response) } }) }
javascript
{ "resource": "" }
q8546
addAttachment
train
function addAttachment (docName, docRev) { const args = os.type() === 'Darwin' ? ['-l', '1'] : ['-b', '-n', '1'] const stream = spawn('top', args).stdout const attName = `top-${Date.now()}.txt` const attContentType = 'text/plain' return db.addAttachment(dbName, docName, attName, docRev, attContentType, stream) .then(response => response.data.rev) }
javascript
{ "resource": "" }
q8547
outputDiagnostics
train
function outputDiagnostics(diagnostic) { var prefix = " "; var output = prefix + "---\n"; output += prefix + yaml.safeDump(diagnostic).split("\n").join("\n" + prefix); output += "...\n"; return output; }
javascript
{ "resource": "" }
q8548
train
function(element) { this.core = $(element).data('lightGallery'); this.$el = $(element); // Execute only if items are above 1 if (this.core.$items.length < 2) { return false; } this.core.s = $.extend({}, defaults, this.core.s); this.interval = false; // Identify if slide happened from autoplay this.fromAuto = true; // Identify if autoplay canceled from touch/drag this.canceledOnTouch = false; // save fourceautoplay value this.fourceAutoplayTemp = this.core.s.fourceAutoplay; // do not allow progress bar if browser does not support css3 transitions if (!this.core.doCss()) { this.core.s.progressBar = false; } this.init(); return this; }
javascript
{ "resource": "" }
q8549
getFunctionName
train
function getFunctionName(func) { if (func.name !== void(0)) { return func.name; } // Else use IE Shim var funcNameMatch = func.toString() .match(/function\s*([^\s]*)\s*\(/); func.name = (funcNameMatch && funcNameMatch[1]) || ''; return func.name; }
javascript
{ "resource": "" }
q8550
isGetSet
train
function isGetSet(obj) { var keys, length; if (obj && typeof obj === 'object') { keys = Object.getOwnPropertyNames(obj) .sort(); length = keys.length; if ((length === 1 && (keys[0] === 'get' && typeof obj.get === 'function' || keys[0] === 'set' && typeof obj.set === 'function' )) || (length === 2 && (keys[0] === 'get' && typeof obj.get === 'function' && keys[1] === 'set' && typeof obj.set === 'function' ))) { return true; } } return false; }
javascript
{ "resource": "" }
q8551
defineObjectProperties
train
function defineObjectProperties(obj, descriptor, properties) { var setProperties = {}, i, keys, length, p = properties || descriptor, d = properties && descriptor; properties = (p && typeof p === 'object') ? p : {}; descriptor = (d && typeof d === 'object') ? d : {}; keys = Object.getOwnPropertyNames(properties); length = keys.length; for (i = 0; i < length; i++) { if (isGetSet(properties[keys[i]])) { setProperties[keys[i]] = { configurable: !!descriptor.configurable, enumerable: !!descriptor.enumerable, get: properties[keys[i]].get, set: properties[keys[i]].set }; } else { setProperties[keys[i]] = { configurable: !!descriptor.configurable, enumerable: !!descriptor.enumerable, writable: !!descriptor.writable, value: properties[keys[i]] }; } } Object.defineProperties(obj, setProperties); return obj; }
javascript
{ "resource": "" }
q8552
isGeneration
train
function isGeneration(generator) { assertTypeError(generator, 'function'); var _ = this; return _.prototype.isPrototypeOf(generator.prototype); }
javascript
{ "resource": "" }
q8553
ChildBench
train
function ChildBench(name, file, opts){ opts || (opts = {}) var args = [file] var options = {} // extra process arguments if (opts.args) args.push.apply(args, opts.args) // bench subject if (opts.subject) options.env = { subject: opts.subject } var reqs = this.requests = {} this.child = fork(runner, args, options) .on('message', function(msg){ var result = reqs[msg.id] msg.value.name = name switch (msg.type) { case 'result': result.write(msg.value); break case 'error': var err = new Error(msg.value.message) err.stack = msg.value.stack result.error(err) break default: throw new Error('unknown message ' + JSON.stringify(msg)) } }) // clean up .on('exit', function(code){ if (code > 0) process.exit(code) }) }
javascript
{ "resource": "" }
q8554
train
function(settings) { this.key = settings.key; this.endpoint = settings.endpoint; if (this.endpoint) { console.log( 'Irelia has been updated to version 0.2 where we are using a new url system. You will have to update your config for using it. Check documentation at: ' .cyan + 'https://github.com/alexperezpaya/irelia'.underline.blue); } if (settings.debug === true) { this.debug = true; } this.secure = (settings.secure) ? settings.secure : false; this.host = settings.host; this.path = settings.path; return this; }
javascript
{ "resource": "" }
q8555
getLineInfo
train
function getLineInfo(bRet,bNum,code) { var numCount = 0, hintCount = 0; var bLn = code.split(ln_re_), len = bLn.length; var iLastLn = -1, sLastNum = '0'; for (var i=0; i < len; i++) { var item = bLn[i], hasHint = false; var sNew = item.replace(hint_re_, function(sMatch) { hasHint = true; hintCount += 1; var iTmp = sMatch.length; if (iLastLn + 1 == i) { iLastLn = i; sLastNum = (parseInt(sLastNum) + 1) + ''; iTmp -= 1; sLastNum = sLastNum.slice(-iTmp); // trim to same width: ~~ if (sLastNum.length < iTmp) sLastNum = (new Array(iTmp-sLastNum.length+1)).join('0') + sLastNum; bRet[i] = sLastNum + '!'; } else bRet[i] = (new Array(iTmp)).join(' ') + '!'; return ''; }); if (hasHint) bLn[i] = sNew; else { var hasNum = false; var sNew2 = item.replace(num_re_, function(sMatch) { hasNum = true; numCount += 1; sLastNum = bRet[i] = sMatch.slice(0,-1); iLastLn = i; return ''; }); if (hasNum) bLn[i] = sNew2; } } if (!bRet.length) // no changing return code; else { if (!hintCount && numCount <= 1) { // avoid accident preceed-number bRet.splice(0); return code; // no changing } else { if (numCount) bNum.push(numCount); return bLn.join('\n'); } } }
javascript
{ "resource": "" }
q8556
getAttrValue
train
function getAttrValue(obj, attr, strictCase) { assert.object(obj); assert.string(attr); // Check for exact case match first if (obj.hasOwnProperty(attr)) { return obj[attr]; } else if (strictCase) { return undefined; } // Perform case-insensitive enumeration after that var lower = attr.toLowerCase(); var result; Object.getOwnPropertyNames(obj).some(function (name) { if (name.toLowerCase() === lower) { result = obj[name]; return true; } return false; }); return result; }
javascript
{ "resource": "" }
q8557
train
function(callback, delay, repetitions) { var x = 0; var intervalID = setInterval(function () { if (++x === repetitions) { clearInterval(intervalID); receive_interval_timer = false; } callback(); }, delay); return intervalID; }
javascript
{ "resource": "" }
q8558
removePrefixFromFilepath
train
function removePrefixFromFilepath(filepath, prefix) { prefix += "/"; if (filepath.indexOf(prefix) === 0) { filepath = filepath.substr(prefix.length); } return filepath; }
javascript
{ "resource": "" }
q8559
resolveFilepath
train
function resolveFilepath(filepath, baseDir) { if (baseDir) { var base = normalizeFilepath(path.resolve(baseDir)); filepath = removePrefixFromFilepath(filepath, base); filepath = removePrefixFromFilepath(filepath, fs.realpathSync(base)); } filepath.replace(/^\//, ""); return filepath; }
javascript
{ "resource": "" }
q8560
addIgnoreFile
train
function addIgnoreFile(ig, filepath) { if (fs.existsSync(filepath)) { ig.add(fs.readFileSync(filepath).toString()); } return ig; }
javascript
{ "resource": "" }
q8561
train
function (header, prevToken) { var options = this.options; if (header.depth > options.maxDepth) return; var headerText = utils.getHeader(header.text, prevToken); if (!headerText) return; var anchor = this._getAnchor(header.text, prevToken), indent = utils.getIndent(this._usedHeaders, header.depth); this._usedHeaders.unshift({ depth: header.depth, indent: indent }); this.data += indent + options.bullet + ' [' + headerText.replace(/\\/g, '\\\\') + '](#' + anchor + ')' + EOL; }
javascript
{ "resource": "" }
q8562
train
function (headerText, prevToken) { if (prevToken && prevToken.type === 'paragraph' && utils.isHtml(prevToken.text)) { var anchorFromHtml = utils.getAnchorFromHtml(prevToken.text); if (anchorFromHtml) { return anchorFromHtml; } } var anchor = utils.getAnchorFromHeader(headerText, prevToken); if (this._cache.hasOwnProperty(anchor)) { anchor += '-' + this._cache[anchor]++; } else { this._cache[anchor] = 1; } return anchor; }
javascript
{ "resource": "" }
q8563
parseGoogleNewsRSSData
train
function parseGoogleNewsRSSData(fileData) { // sanity check that this is valid google news RSS if (fileData.indexOf('news-feedback@google.com') != -1) { // set an empty array of news story objects var allGoogleNewsData = [ ]; var params = {normalizeWhitespace: true, xmlMode: true}; // load the html into the cheerio doc var cheerio = require("cheerio"); var fullDoc = cheerio.load(fileData, params); // iterate through movies and strip useful parts, add each to return object fullDoc('item').each(function(i, elem) { // load current item var itemDoc = cheerio.load(fullDoc(this).html(), params); // break out parts of interest // some sections need cleaning so do that as well var fullTitleLine = itemDoc('title').text().trim(); var fullTitleSplitIndex = fullTitleLine.lastIndexOf(' - '); var titlePart = fullTitleLine.substring(0, fullTitleSplitIndex); var sourcePart = fullTitleLine.substring(fullTitleSplitIndex + 3, fullTitleSplitIndex.length); var fullURLPart = itemDoc('link').html().trim(); var cleanURLPart = fullURLPart.split(';url=')[1]; var categoryPart = itemDoc('category').html(); if (categoryPart != null) categoryPart = categoryPart.trim(); var pubDatePart = itemDoc('pubDate').html().trim(); var fullDescriptionPart = itemDoc('description').text().trim(); var descriptionStart = fullDescriptionPart.indexOf('</font><br><font size="-1">'); var descriptionEnd = fullDescriptionPart.indexOf('</font>', descriptionStart + 1); var cleanDescriptionPart = fullDescriptionPart.substring(descriptionStart, descriptionEnd); var cleanDescriptionPart = cleanDescriptionPart.replace('</font><br><font size="-1">', ''); var cleanDescriptionPart = cleanDescriptionPart.replace('<b>...</b>', '...'); // build final object for the current news story var fullObject = { title: titlePart , source: sourcePart , category: categoryPart , pubDate: pubDatePart , fullURL: fullURLPart , cleanURL: cleanURLPart , fullDescription: fullDescriptionPart , cleanDescription: cleanDescriptionPart }; // add thew news story obejct to the array allGoogleNewsData.push(fullObject); }); // return no error state and the collected news story objects return {error: false, data: allGoogleNewsData}; } // if sanity check failed, return true error state and an error message return {error: errorFlag, errorMessage: 'Fetched RSS data does not contain expected content.', data: null}; }
javascript
{ "resource": "" }
q8564
parseGoogleNewsRSSParamsErrorHelper
train
function parseGoogleNewsRSSParamsErrorHelper(errorMessage) { return {error: true , errorMessage: errorMessage , type: null , terms: null , url: null }; }
javascript
{ "resource": "" }
q8565
parseGoogleNewsRSSParams
train
function parseGoogleNewsRSSParams(params) { // get params of interest var newsType = params.newsType; var newsTypeTerms = params.newsTypeTerms; // if missing just one parameter flag error as such if ((newsType == undefined) && (newsTypeTerms != undefined)) return parseGoogleNewsRSSParamsErrorHelper('Parameter newsTypeTerms set with no newsType set.'); if ((newsType != undefined) && (newsTypeTerms == undefined)) return parseGoogleNewsRSSParamsErrorHelper('Parameter newsType set with no newsTypeTerms set.'); // if missing both parameters, set to default if ((newsType == undefined) && (newsTypeTerms == undefined)) { newsType = 'TOPIC'; newsTypeTerms = 'HEADLINES'; } // fix case parameters newsType = newsType.toUpperCase(); newsTypeTerms = newsTypeTerms.toUpperCase(); // expand newsType name if needed if (newsType == 'T') newsType = 'TOPIC'; if (newsType == 'Q') newsType = 'QUERY'; // if an invalid newsType set flag error as such if ((newsType != 'TOPIC') && (newsType != 'QUERY')) return parseGoogleNewsRSSParamsErrorHelper('Invalid newsType parameter specified.'); // if type is topic if (newsType == 'TOPIC') { // init the short and long term names of the topic type var newsTypeTermTopicShort = null; var newsTypeTermTopicLong = null; // check the term for either short or long name and then set names accordingly if ((newsTypeTerms == 'H') || (newsTypeTerms == 'HEADLINES')) { newsTypeTermTopicShort = 'H'; newsTypeTermTopicLong = 'HEADLINES'; } if ((newsTypeTerms == 'N') || (newsTypeTerms == 'NATIONAL')) { newsTypeTermTopicShort = 'N'; newsTypeTermTopicLong = 'NATIONAL'; } if ((newsTypeTerms == 'W') || (newsTypeTerms == 'WORLD')) { newsTypeTermTopicShort = 'W'; newsTypeTermTopicLong = 'WORLD'; } if ((newsTypeTerms == 'E') || (newsTypeTerms == 'ENTERTAINMENT')) { newsTypeTermTopicShort = 'E'; newsTypeTermTopicLong = 'ENTERTAINMENT'; } if ((newsTypeTerms == 'B') || (newsTypeTerms == 'BUSINESS')) { newsTypeTermTopicShort = 'B'; newsTypeTermTopicLong = 'BUSINESS'; } if ((newsTypeTerms == 'S') || (newsTypeTerms == 'SPORTS')) { newsTypeTermTopicShort = 'S'; newsTypeTermTopicLong = 'SPORTS'; } if ((newsTypeTerms == 'T') || (newsTypeTerms == 'SCI/TECH')) { newsTypeTermTopicShort = 'T'; newsTypeTermTopicLong = 'SCI/TECH'; } if ((newsTypeTerms == 'TC') || (newsTypeTerms == 'TECHNOLOGY')) { newsTypeTermTopicShort = 'TC'; newsTypeTermTopicLong = 'TECHNOLOGY'; } // if nothing was set it was a bad topic type flag error as such if (newsTypeTermTopicShort == null) return parseGoogleNewsRSSParamsErrorHelper('Parameter newsTypeTerms is unknown for newsType TOPIC.'); // build the request URL var newsURL = 'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&topic=' + newsTypeTermTopicShort.toLowerCase() + '&output=rss'; // build the return object return {error: false, errorMessage: null, type: 'TOPIC', terms: newsTypeTermTopicLong, url: newsURL}; } // if type is query if (newsType == 'QUERY') { var newsTypeTermsQuery = newsTypeTerms.toLowerCase().replace(',', '+OR+').replace(' ', '+'); var newsURL = 'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&q=' + newsTypeTermsQuery + '&output=rss'; // build the return object return {error: false, errorMessage: null, type: 'QUERY', terms: newsTypeTerms, url: newsURL}; } // otherwise return generic error state return parseGoogleNewsRSSParamsErrorHelper('Unknown parameter error occured.'); }
javascript
{ "resource": "" }
q8566
requestGoogleNewsRSS
train
function requestGoogleNewsRSS(params, callback) { // parse the params var returnObject = parseGoogleNewsRSSParams(params); returnObject.newsArray = null; // if no error from the parsing object if (!returnObject.error) { // make a request to the RSS using the URL var request = require("request"); request({uri: returnObject.url}, function(error, response, body) { // if no error in the call if (!error) { // parse the RSS data var parsedData = parseGoogleNewsRSSData(body); // if parsing runs okay, add data to the return object and return it if (parsedData.error == false) { returnObject.error = false; returnObject.errorMessage = null; returnObject.newsArray = parsedData.data; callback(returnObject); } // otherwise parsing failed, indicate such else { returnObject.error = true; returnObject.errorMessage = 'Error with parsing data return from Google News.'; callback(returnObject); } } // otherwise indicate bad request else { returnObject.error = true; returnObject.errorMessage = 'Error with request for data from Google News.'; callback(returnObject); } }); } // otherwise send back error true object from original params parsing else { callback(returnObject); } }
javascript
{ "resource": "" }
q8567
gist
train
function gist (options, callback) { if (!options.id) return callback(new Error('missing option: id')) request({ url: '/gists/' + options.id, qs: { access_token: options.token } }, function (err, json) { if (err) return callback(err) var results = [] async.forEachOf(json.files, function (item, key, callback) { processGithubFile({ item: item, key: key, json: json }, function (err, geojson) { if (err) return callback(err) if (geojson) results.push(geojson) callback(null) }) }, function (err) { if (err) return callback(err) if (!results.length) return callback(new Error('no geojson found in gist ' + options.id)) callback(null, results) }) }) }
javascript
{ "resource": "" }
q8568
processGithubFile
train
function processGithubFile (options, callback) { var item = options.item var key = options.key var json = options.json function respond (content) { if (isFeatureCollection(content)) { content.name = key content.updated_at = json.updated_at return content } return false } if (item.truncated) { return request({ url: item.raw_url }, function (err, content) { if (err) return callback(err) callback(null, respond(content)) }) } try { var content = JSON.parse(item.content) } catch (e) { var msg = 'could not parse file contents of ' + key + ': ' + e.message return callback(new Error(msg)) } callback(null, respond(content)) }
javascript
{ "resource": "" }
q8569
parse
train
function parse(fileString, callback) { try { return callback(null, Yaml.safeLoad(fileString)); } catch (err) { return callback(err); } }
javascript
{ "resource": "" }
q8570
parseFile
train
function parseFile(filePath, encoding, callback) { fs.readFile(filePath, encoding, function(err, fileString) { if (err) { return callback(err); } return parse(fileString, callback); }); }
javascript
{ "resource": "" }
q8571
write
train
function write(ngindoxMap, callback) { try { return callback(null, Yaml.safeDump(ngindoxMap)); } catch (err) { return callback(err); } }
javascript
{ "resource": "" }
q8572
writeFile
train
function writeFile(ngindoxObj, encoding, callback) { fs.writeFile(filePath, fileString, encoding, function(err) { if (err) { return callback(err); } return write(ngindoxObj, callback); }); }
javascript
{ "resource": "" }
q8573
merge_obj
train
function merge_obj(high, low) { if(!is_obj(high)) throw new Error('Bad merge high-priority'); if(!is_obj(low)) throw new Error('Bad merge low-priority'); var keys = []; function add_key(k) { if(!~ keys.indexOf(k)) keys.push(k); } _each(_keys(high), add_key); _each(_keys(low), add_key); var result = {}; _each(keys, function (key) { var high_val = high[key]; var low_val = low[key]; if(is_obj(high_val) && is_obj(low_val)) result[key] = merge_obj(high_val, low_val); else if (key in high) result[key] = high[key]; else if (key in low) result[key] = low[key]; else throw new Error('Unknown key type: ' + key); }) return result; }
javascript
{ "resource": "" }
q8574
Ratchet
train
function Ratchet(crypto) { const self = this; const hkdf = new HKDF(crypto); /** * Derive the main and sub ratchet states from the shared secrets derived from the handshake. * * @method * @param {number} sessionVersion * @param {Array.<ArrayBuffer>} agreements - an array of ArrayBuffers containing the shared secrets * @return {Promise.<Object, Error>} the root and chain keys */ this.deriveInitialRootKeyAndChain = co.wrap(function*(sessionVersion, agreements) { var secrets = []; if (sessionVersion >= 3) { secrets.push(discontinuityBytes); } secrets = secrets.concat(agreements); var masterSecret = ArrayBufferUtils.concat(secrets); var derivedSecret = yield hkdf.deriveSecrets(masterSecret, whisperText, ProtocolConstants.rootKeyByteCount + ProtocolConstants.chainKeyByteCount); return { rootKey: derivedSecret.slice(0, ProtocolConstants.rootKeyByteCount), chain: new Chain(derivedSecret.slice(ProtocolConstants.rootKeyByteCount)) }; }); /** * Derive the next main and sub ratchet states from the previous state. * <p> * This method "clicks" the Diffie-Hellman ratchet forwards. * * @method * @param {ArrayBuffer} rootKey - the current root key * @param {ArrayBuffer} theirEphemeralPublicKey - the receiving ephemeral/ratchet key * @param {ArrayBuffer} ourEphemeralPrivateKey - our current ephemeral/ratchet key * @return {Promise.<Object, Error>} the next root and chain keys */ this.deriveNextRootKeyAndChain = co.wrap(function*(rootKey, theirEphemeralPublicKey, ourEphemeralPrivateKey) { var sharedSecret = yield crypto.calculateAgreement(theirEphemeralPublicKey, ourEphemeralPrivateKey); var derivedSecretBytes = yield hkdf.deriveSecretsWithSalt(sharedSecret, rootKey, whisperRatchet, ProtocolConstants.rootKeyByteCount + ProtocolConstants.chainKeyByteCount); return { rootKey: derivedSecretBytes.slice(0, ProtocolConstants.rootKeyByteCount), chain: new Chain(derivedSecretBytes.slice(ProtocolConstants.rootKeyByteCount)) }; }); // /** * Derive the next sub ratchet state from the previous state. * <p> * This method "clicks" the hash iteration ratchet forwards. * * @method * @param {Chain} chain * @return {Promise.<void, Error>} */ this.clickSubRatchet = co.wrap(function*(chain) { chain.index++; chain.key = yield deriveNextChainKey(chain.key); }); /** * Derive the message keys from the chain key. * * @method * @param {ArrayBuffer} chainKey * @return {Promise.<object, Error>} an object containing the message keys. */ this.deriveMessageKeys = co.wrap(function*(chainKey) { var messageKey = yield deriveMessageKey(chainKey); var keyMaterialBytes = yield hkdf.deriveSecrets(messageKey, whisperMessageKeys, ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount + ProtocolConstants.ivByteCount); var cipherKeyBytes = keyMaterialBytes.slice(0, ProtocolConstants.cipherKeyByteCount); var macKeyBytes = keyMaterialBytes.slice(ProtocolConstants.cipherKeyByteCount, ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount); var ivBytes = keyMaterialBytes.slice(ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount); return { cipherKey: cipherKeyBytes, macKey: macKeyBytes, iv: ivBytes }; }); var hmacByte = co.wrap(function*(key, byte) { return yield crypto.hmac(key, ArrayBufferUtils.fromByte(byte)); }); var deriveMessageKey = co.wrap(function*(chainKey) { return yield hmacByte(chainKey, messageKeySeed); }); var deriveNextChainKey = co.wrap(function*(chainKey) { return yield hmacByte(chainKey, chainKeySeed); }); }
javascript
{ "resource": "" }
q8575
NormalizePkg
train
function NormalizePkg(options) { if (!(this instanceof NormalizePkg)) { return new NormalizePkg(options); } this.options = options || {}; this.schema = schema(this.options); this.data = this.schema.data; this.schema.on('warning', this.emit.bind(this, 'warning')); this.schema.on('error', this.emit.bind(this, 'error')); this.schema.union = function(key, config, arr) { config[key] = utils.arrayify(config[key]); config[key] = utils.union([], config[key], utils.arrayify(arr)); }; }
javascript
{ "resource": "" }
q8576
readerToStream
train
function readerToStream(reader) { return new ReadableStream({ pull(controller) { return reader.read() .then(res => { if (res.done) { controller.close(); } else { controller.enqueue(res.value); } }); }, cancel(reason) { return reader.cancel(reason); } }); }
javascript
{ "resource": "" }
q8577
validate
train
function validate (input, source, line, column, bemlintId) { for (var rule_id in currentRules) { var messageOptions = lodash.assign({}, { input: input, source: source, bemlintId: bemlintId, elem: options.elem, mod: options.mod, wordPattern: options.wordPattern }), message = new Message(cheerio.load(modifiedText), rule_id, messageOptions); if ( message.text ) { messages.push({ message: message.text, line: line, column: column, ruleId: rule_id }); } } }
javascript
{ "resource": "" }
q8578
buildDescriptor
train
function buildDescriptor(node, blueprintKey, descriptor /*, descriptorBuilder*/) { if (typeof descriptor.setup === 'function') { descriptor.setup(node, blueprintKey); } if (descriptor.value) { defineProperty(node, blueprintKey, descriptor.value); } else { defineProperty(node, blueprintKey, undefined, function() { return descriptor.get.call(this, blueprintKey); }); } }
javascript
{ "resource": "" }
q8579
buildObject
train
function buildObject(node, blueprintKey, blueprint /*, defaultBuilder*/) { var value = {}; // Create child component defineProperty(node, blueprintKey, value); // Set meta to object setMeta(value, blueprintKey); return [value, blueprint]; }
javascript
{ "resource": "" }
q8580
flags
train
function flags(o, pre='', z='') { for(var k in o) { if(o[k]==null || k==='stdio') continue; if(Array.isArray(o[k])) z += ` --${pre}${k} "${o[k].join()}"`; else if(typeof o[k]==='object') z = flags(o[k], `${pre}${k}_`, z); else if(typeof o[k]==='boolean') z += o[k]? ` --${pre}${k}`:''; else z += ` --${pre}${k} ${JSON.stringify(o[k])}`; } return z; }
javascript
{ "resource": "" }
q8581
youtubeuploader
train
function youtubeuploader(o) { var o = o||{}, cmd = 'youtubeuploader'+flags(o); var stdio = o.log || o.stdio==null? STDIO:o.stdio; if(stdio===STDIO) return Promise.resolve({stdout: cp.execSync(cmd, {stdio})}); return new Promise((fres, frej) => cp.exec(cmd, {stdio}, (err, stdout, stderr) => { return err? frej(err):fres({stdout, stderr}); })); }
javascript
{ "resource": "" }
q8582
lines
train
async function lines(o) { var {stdout} = await youtubeuploader(Object.assign({}, o, {stdio: []})); var out = stdout.toString().trim(); return out? out.split('\n'):[]; }
javascript
{ "resource": "" }
q8583
listFilesToProcess
train
function listFilesToProcess(globPatterns, options) { var ignoredPaths, ignoredPathsList, files = [], added = {}, globOptions, rulesKey = "_rules"; /** * Executes the linter on a file defined by the `filename`. Skips * unsupported file extensions and any files that are already linted. * @param {string} filename The file to be processed * @returns {void} */ function addFile(filename) { if (ignoredPaths.contains(filename)) { return; } filename = fs.realpathSync(filename); if (added[filename]) { return; } files.push(filename); added[filename] = true; } options = options || { ignore: true, dotfiles: true }; ignoredPaths = new IgnoredPaths(options); ignoredPathsList = ignoredPaths.ig.custom[rulesKey].map(function(rule) { return rule.pattern; }); globOptions = { nodir: true, ignore: ignoredPathsList }; debug("Creating list of files to process."); globPatterns.forEach(function(pattern) { if (shell.test("-f", pattern)) { addFile(pattern); } else { glob.sync(pattern, globOptions).forEach(addFile); } }); return files; }
javascript
{ "resource": "" }
q8584
hashObject
train
function hashObject (obj) { if (!isObject(obj)) return null; return shortHash(JSON.stringify(sortKeys(obj, { deep: true }))); }
javascript
{ "resource": "" }
q8585
length
train
function length(desiredLength, formatError) { 'use strict'; return function (value) { value = ((value !== null && value !== undefined) ? value : ''); if (value.length !== desiredLength) { return formatError(value.length); } return ''; }; }
javascript
{ "resource": "" }
q8586
minValue
train
function minValue(bound, formatError) { 'use strict'; return function (value) { if (value || !isNaN(parseFloat(value))) { var intValue = Number(value); if (!isNaN(intValue) && intValue < bound) { return formatError(intValue); } } return ''; }; }
javascript
{ "resource": "" }
q8587
detectConfig
train
function detectConfig(appDir) { var config = {}; var meteoriteUsed = fs.existsSync(path.resolve(appDir, './smart.json')); if(meteoriteUsed) { config.meteorite = true; config.nodeBinary = helpers.getMeteoriteNode(appDir); } else { config.meteorite = false; config.nodeBinary = helpers.getMeteorNode(); } return config; }
javascript
{ "resource": "" }
q8588
assignOneDual
train
function assignOneDual(bConns, item) { var fn = exprDict[item]; if (!fn) return; try { var bConn = gui.connectTo[item]; if (bConn) { // this action is listened var oldValue = comp.state[item]; fn(comp); // try update with expression var newValue = comp.state[item]; if (newValue !== oldValue) // succ update expression and get a new value bConns.push([bConn, newValue, oldValue, item]); // wait to fire listen-function } else fn(comp); } catch (e) { console.log(e); } }
javascript
{ "resource": "" }
q8589
train
function (filePath) { var name = path.relative(this.opts.cwd, filePath); name = path.join(path.dirname(name), path.basename(name, this.opts.extension)); return name; }
javascript
{ "resource": "" }
q8590
fromIndex
train
function fromIndex(a, index) { var arr = is.isArguments(a) ? arraySlice.call(a) : a; return arraySlice.call(arr, index, arr.length); }
javascript
{ "resource": "" }
q8591
each
train
function each(item, fn, thisArg) { var arr = toArray(item); return arr.forEach.call(arr, fn, thisArg); }
javascript
{ "resource": "" }
q8592
geohubRequest
train
function geohubRequest (options, callback) { if (options.url.indexOf('https://') !== 0) { options.url = apiBase + options.url } options.headers = { 'User-Agent': 'geohub/' + pkg.version } // delete null/undefined access token to avoid 401 from github if (options.qs && !options.qs.access_token) { delete options.qs.access_token } debug(options) request(options, function (err, res, body) { if (err) return callback(err) try { var json = JSON.parse(body) } catch (e) { var msg = 'Failed to parse JSON from ' + options.url msg += ' (status code: ' + res.statusCode + ', body: ' + body + ')' return callback(new Error(msg)) } if (json.message) { return callback(new Error(res.statusCode + ' (github): ' + json.message)) } callback(null, json) }) }
javascript
{ "resource": "" }
q8593
Benchmark
train
function Benchmark(name, fn) { this._name = name; this._fn = fn; this._async = fn.length > 1; }
javascript
{ "resource": "" }
q8594
processText
train
function processText(text, filename, options) { var filePath, messages, stats; if (filename) { filePath = path.resolve(filename); } filename = filename || "<text>"; debug("Linting " + filename); messages = bemlint.verify(text, lodash.assign(Object.create(null), { filename: filename }, options)); stats = calculateStatsPerFile(messages); var result = { filePath: filename, messages: messages, errorCount: stats.errorCount, warningCount: stats.warningCount }; return result; }
javascript
{ "resource": "" }
q8595
processFile
train
function processFile(filename, options) { var text = fs.readFileSync(path.resolve(filename), "utf8"), result = processText(text, filename, options); return result; }
javascript
{ "resource": "" }
q8596
train
function(filePath) { var ignoredPaths; if (this.options.ignore) { ignoredPaths = new IgnoredPaths(this.options); return ignoredPaths.contains(filePath); } return false; }
javascript
{ "resource": "" }
q8597
extractGroup
train
function extractGroup (xml, tagName) { var itens = [] var regex = new RegExp(`<${tagName}.+?>(.+?)</${tagName}>`, 'gi') var result = '' for (result = regex.exec(xml); regex.lastIndex !== 0; result = regex.exec(xml)) { itens.push(result[0]) } return itens }
javascript
{ "resource": "" }
q8598
extract
train
function extract (xml, tagName, attributeName) { if (!Array.isArray(tagName)) { tagName = [tagName] } var found = null var tagFound = null for (var i = 0; i < tagName.length; i++) { // without attributes found = new RegExp(`<${tagName[i]}\\s*>(.+?)</${tagName[i]}>`, 'i').exec(xml) if (found) { tagFound = tagName[i] break } // with attributes found = new RegExp(`<${tagName[i]} .*?>(.+?)</${tagName[i]}>`, 'i').exec(xml) if (found) { tagFound = tagName[i] break } } if (found && attributeName) { var attribute = new RegExp(`<${tagFound} .*?${attributeName}=\"(.+?)\".*?>`, 'i').exec(found[0]) if (attribute) { return attribute[1] } } return found ? found[1] : null }
javascript
{ "resource": "" }
q8599
routeType
train
function routeType(route) { var fields = Object.keys(RouteTypeFields); for (var i = 0, len = fields.length; i < len; i++) { var field = fields[i]; if (route[field]) { return RouteTypeFields[field]; } } return 'unknown'; }
javascript
{ "resource": "" }