_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q9700
getComponent
train
function getComponent(tn) { var cid = tn.toLowerCase() var compDef components.some(function (comp) { if (comp.hasOwnProperty(cid)) { compDef = comp[cid] return true } }) return compDef }
javascript
{ "resource": "" }
q9701
compileElement
train
function compileElement(node, scope, isRoot) { var tagName = node.tagName var inst switch(true) { /** * <*-if></*-if> */ case is.IfElement(tagName): var children = _slice(node.children) var exprs = [$(node).attr('is')] children.forEach(function(c) { if (is.ElseElement(c)) { exprs.push($(c).attr(conf.namespace + 'else') || '') } }) inst = new ElementDirective( vm, scope, node, elements['if'], NS + 'if', exprs ) if (!isRoot) { inst.$mount(node) } // save elements refs _directives.push(inst) // save bindins to scope _setBindings2Scope(scope, inst) return inst /** * <*-repeat></*-repeat> */ case is.RepeatElement(tagName): inst = new ElementDirective( vm, scope, node, elements.repeat, NS + 'repeat', $(node).attr('items') ) if (!isRoot) { inst.$mount(node) } _directives.push(inst) _setBindings2Scope(scope, inst) return inst } }
javascript
{ "resource": "" }
q9702
compileDirective
train
function compileDirective (node, scope) { var ast = { attrs: {}, dires: {} } var dirtDefs = _getAllDirts() /** * attributes walk */ _slice(node.attributes).forEach(function(att) { var aname = att.name var v = att.value // parse att if (~componentProps.indexOf(aname)) { return } else if (_isExpr(aname)) { // variable attribute name ast.attrs[aname] = v } else if (aname.indexOf(NS) === 0) { var def = dirtDefs[aname] if (def) { // directive ast.dires[aname] = { def: def, expr: v } } else { return } } else if (_isExpr(v.trim())) { // named attribute with expression ast.attrs[aname] = v } else { return } node.removeAttribute(aname) }) /** * Attributes binding */ util.objEach(ast.attrs, function(name, value) { var attd = new AttributeDirective(vm, scope, node, name, value) _directives.push(attd) _setBindings2Scope(scope, attd) }) /** * Directives binding */ util.objEach(ast.dires, function(dname, spec) { var def = spec.def var expr = spec.expr var sep = ';' var d // multiple defines expression parse if (def.multi && expr.match(sep)) { Expression.strip(expr) .split(sep) .forEach(function(item) { // discard empty expression if (!item.trim()) return d = new Directive(vm, scope, node, def, dname, '{' + item + '}') _directives.push(d) _setBindings2Scope(scope, d) }) } else { d = new Directive(vm, scope, node, def, dname, expr) _directives.push(d) _setBindings2Scope(scope, d) } }) }
javascript
{ "resource": "" }
q9703
train
function(){ var node = this.parseAdd(); while(this.skipValue(lexer.TOKEN_TILDE, '~')) { var node2 = this.parseAdd(); node = new nodes.Concat(node.lineno, node.colno, node, node2); } return node; }
javascript
{ "resource": "" }
q9704
Store
train
function Store(conString, options) { var self = this; this._table = "passwordless"; this._client = mysql.createPool(conString); this._client.query("CREATE TABLE IF NOT EXISTS " + this._table + " " + "( id serial NOT NULL, uid character varying(160), token character varying(60) NOT NULL, origin text, ttl bigint, " + "CONSTRAINT passwordless_pkey PRIMARY KEY (id), CONSTRAINT passwordless_token_key UNIQUE (token), CONSTRAINT passwordless_uid_key UNIQUE (uid) )"); }
javascript
{ "resource": "" }
q9705
$merge
train
function $merge(params, fn) { if ( Array.isArray(params) && params.length === 2 && params.every(p => typeof p === 'object') ) { return fn.merge(params[0], params[1]); } throw new Error('$merge expects an array of two objects'); }
javascript
{ "resource": "" }
q9706
$keys
train
function $keys(params) { if (params == null) { return params; } if (params != null && typeof params === 'object') { return Object.keys(params); } throw new Error('$keys expects object'); }
javascript
{ "resource": "" }
q9707
$vals
train
function $vals(params) { if (params == null) { return params; } if (params != null && typeof params === 'object') { return Object.keys(params).map(k => params[k]); } throw new Error('$vals expects object'); }
javascript
{ "resource": "" }
q9708
$zip
train
function $zip(params) { if ( Array.isArray(params) && params.every(p => Array.isArray(p) && p.length === 2) ) { return params.reduce((o, p) => Object.assign(o, { [p[0]]: p[1] }), {}); } throw new Error('$zip expects an array of two-element-array'); }
javascript
{ "resource": "" }
q9709
resolvePackageRoot
train
function resolvePackageRoot (file) { try { const fullPath = path.resolve(file) for (let lead = fullPath; path.dirname(lead) !== lead; lead = path.dirname(lead)) { debug('Looking for package.json in ' + lead) let packagePath = path.join(lead, 'package.json') try { if (fs.statSync(packagePath).isFile()) { return fs.readFile(packagePath, 'utf-8') .then(JSON.parse) .then(packageJson => { return { packageRoot: path.relative(process.cwd(), lead) || '.', relativeFile: path.relative(lead, fullPath), packageJson } }) } } catch (e) { /* istanbul ignore else */ switch (e.code) { case 'ENOTDIR': case 'ENOENT': continue default: throw e } } } } catch (e) { return Promise.reject(e) } }
javascript
{ "resource": "" }
q9710
train
function(pluginIdx) { if (pluginIdx >= plugins.length) return callback(hooks.collectionHook); var plugin = plugins[pluginIdx]; var next = function() {iterPlugins(pluginIdx + 1);}; var func = plugin[stage]; // call the plugin's stage hook, if defined if (func) { // T is database operation object func.call(plugin, T, next); } else next(); }
javascript
{ "resource": "" }
q9711
include
train
function include (filename, language) { return fs.readFile(filename, 'utf-8').then(function (contents) { return '```' + (typeof language === 'string' ? language : path.extname(filename).substr(1)) + '\n' + contents + '\n```\n' }) }
javascript
{ "resource": "" }
q9712
exec
train
function exec (command, options) { let start let end const lang = options.hash && options.hash.lang switch (lang) { case 'raw': start = end = '' break case 'inline': start = end = '`' break default: const fenceLanguage = lang || '' start = '```' + fenceLanguage + '\n' end = '\n```' } const output = cp.execSync(command, { encoding: 'utf8', cwd: options.hash && options.hash.cwd }) return start + output.trim() + end }
javascript
{ "resource": "" }
q9713
renderTree
train
function renderTree (object, options) { const tree = require('archy')(transformTree(object, options.fn)) return '<pre><code>\n' + tree + '</code></pre>' }
javascript
{ "resource": "" }
q9714
transformTree
train
function transformTree (object, fn) { const label = fn(object).trim() if (object.children) { return { label: label, nodes: object.children.map(function (child) { return transformTree(child, fn) }) } } else { return label } }
javascript
{ "resource": "" }
q9715
repoWebUrl
train
function repoWebUrl (gitUrl) { if (!gitUrl) { return undefined } const orgRepo = _githubOrgRepo(gitUrl) if (orgRepo) { return 'https://github.com/' + orgRepo } else { return null } }
javascript
{ "resource": "" }
q9716
regex
train
function regex (strings, ...args) { return String.raw(strings, ...args.map(_.escapeRegExp)) }
javascript
{ "resource": "" }
q9717
_rawGithubUrl
train
function _rawGithubUrl (resolvedPackageRoot) { var { packageJson, relativeFile } = resolvedPackageRoot const orgRepo = _githubOrgRepo(packageJson && packageJson.repository && packageJson.repository.url) if (orgRepo) { return `https://raw.githubusercontent.com/${orgRepo}/v${packageJson.version}/${relativeFile}` } }
javascript
{ "resource": "" }
q9718
train
function (subject) { var kb = UI.store var t = kb.findTypeURIs(subject) if (t['http://www.w3.org/2005/01/wf/flow#Task'] || kb.holds(subject, UI.ns.wf('tracker'))) return 'issue' // in case ontology not available if (t['http://www.w3.org/2005/01/wf/flow#Tracker']) return 'tracker' // Later: Person. For a list of things assigned to them, // open bugs on projects they are developer on, etc return null // No under other circumstances (while testing at least!) }
javascript
{ "resource": "" }
q9719
train
function (root) { if (root.refresh) { root.refresh() return } for (var i = 0; i < root.children.length; i++) { refreshTree(root.children[i]) } }
javascript
{ "resource": "" }
q9720
getPossibleAssignees
train
async function getPossibleAssignees () { var devs = [] var devGroups = kb.each(subject, ns.wf('assigneeGroup')) for (let i = 0; i < devGroups.length; i++) { let group = devGroups[i] await kb.fetcher.load() devs = devs.concat(kb.each(group, ns.vcard('member'))) } // Anyone who is a developer of any project which uses this tracker var proj = kb.any(null, ns.doap('bug-database'), tracker) // What project? if (proj) { await kb.fetcher.load(proj) devs = devs.concat(kb.each(proj, ns.doap('developer'))) } return devs }
javascript
{ "resource": "" }
q9721
merge
train
function merge(source, target) { if (target == null) { return clone(source); } if (source == null) { return clone(target); } if (typeof source !== 'object' || typeof target !== 'object') { return clone(target); } const merge = (source, target) => { Object.keys(target).forEach(key => { if (source[key] == null) { source[key] = target[key]; } else if (typeof source[key] === 'object') { if (typeof target[key] === 'object') { merge(source[key], target[key]); } else { source[key] = target[key]; } } else { source[key] = target[key]; } }); return source; }; return merge(clone(source), clone(target)); }
javascript
{ "resource": "" }
q9722
env
train
function env(file, inject) { const envs = {}; if (!path.isAbsolute(file)) { file = path.resolve(process.cwd(), file); } if (fs.existsSync(file) && fs.lstatSync(file).isFile()) { const content = fs.readFileSync(file, 'utf8'); content.split('\n').forEach(line => { const kv = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/); if (kv) { const k = kv[1]; let v = kv[2] || ''; if ( v && v.length > 0 && v.charAt(0) === '"' && v.charAt(v.length - 1) === '"' ) { v = v.replace(/\\n/gm, '\n'); } v = v.replace(/(^['"]|['"]$)/g, '').trim(); envs[k] = v; } }); } if (inject) { Object.keys(envs).forEach(k => { if (!(k in process.env)) { process.env[k] = envs[k]; } }); } return envs; }
javascript
{ "resource": "" }
q9723
toDelete
train
function toDelete(datetimes, options) { // We can't just a function like _.difference, because moment objects can't be compared that simply // and the incoming values might not already be moment objects var seenSurvivors = {}; toKeep(datetimes, options).map(function (dt) { seenSurvivors[dt.toISOString()] = true; }) datetimes = datetimes.map(function (dt) { return moment.utc(dt) }); // The dates to delete are the ones not returned by toKeep return _.filter(datetimes, function (dt) { return !seenSurvivors[ dt.toISOString() ] }); }
javascript
{ "resource": "" }
q9724
EqualsContext
train
function EqualsContext(value, other, equals, options) { if (options == null) { options = {}; } /** * A reference to {@link Nevis.equals} which can be called within an {@link EqualsComparator}. * * @private * @type {Function} */ this._equals = equals; /** * The options to be used to test equality for both of the values. * * @public * @type {Nevis~EqualsOptions} */ this.options = { filterProperty: options.filterProperty != null ? options.filterProperty : function() { return true; }, ignoreCase: Boolean(options.ignoreCase), ignoreEquals: Boolean(options.ignoreEquals), ignoreInherited: Boolean(options.ignoreInherited), ignoreMethods: Boolean(options.ignoreMethods) }; /** * The other value to be checked against the <code>value</code>. * * @public * @type {*} */ this.other = other; /** * The string representation of the values to be tested for equality. * * This is generated using <code>Object.prototype.toString</code> and is intended to be primarily used for more * specific type-checking. * * @public * @type {string} */ this.string = Object.prototype.toString.call(value); /** * The type of the values to be tested for equality. * * This is generated using <code>typeof</code> and is intended to be primarily used for simple type-checking. * * @public * @type {string} */ this.type = typeof value; /** * The value to be checked against the <code>other</code>. * * @public * @type {*} */ this.value = value; }
javascript
{ "resource": "" }
q9725
findSupported
train
function findSupported(apiList, document) { let standardApi = apiList[0]; let supportedApi = null; for (let i = 0, len = apiList.length; i < len; i++) { let api = apiList[ i ]; if (api[1] in document) { supportedApi = api; break; } } if (Array.isArray(supportedApi)) { return supportedApi.reduce((result, funcName, i) => { result[ standardApi[ i ] ] = funcName; return result; }, {}); } else { return null; } }
javascript
{ "resource": "" }
q9726
HashCodeBuilder
train
function HashCodeBuilder(initial, multiplier) { if (initial == null) { initial = HashCodeBuilder.DEFAULT_INITIAL_VALUE; } else if (initial % 2 === 0) { throw new Error('initial must be an odd number'); } if (multiplier == null) { multiplier = HashCodeBuilder.DEFAULT_MULTIPLIER_VALUE; } else if (multiplier % 2 === 0) { throw new Error('multiplier must be an odd number'); } /** * The current hash code for this {@link HashCodeBuilder}. * * @private * @type {number} */ this._hash = initial; /** * The multiplier to be used by this {@link HashCodeBuilder}. * * @private * @type {number} */ this._multiplier = multiplier; }
javascript
{ "resource": "" }
q9727
train
function(next) { // already connected to service? stop if (targetServiceProperties.state === STATES.READY || targetServiceProperties.state === STATES.ONLINE) { debug('already connected'); if (callback) callback(); _lockJoin = false; return; } else { next(); } }
javascript
{ "resource": "" }
q9728
train
function(next) { function finishJoining(err) { targetService.removeListener('PropertyChanged', onChange); if (typeof(passphraseSender) == 'function') { self.connman.Agent.removeListener('RequestInput', passphraseSender); passphraseSender = null } next(err); } function onChange(type, value) { if (type !== 'State') return; debug('service State: ', value); switch (value) { // when wifi ready and online case STATES.READY: case STATES.ONLINE: clearTimeout(timeout); finishJoining() break; case STATES.DISCONNECT: case STATES.FAILURE: clearTimeout(timeout); var err = new Error('Joining network failed (wrong password?)'); finishJoining(err); // ToDo include error... (sometimes there is a Error property change, with a value like 'invalid-key') break; } } timeout = setTimeout(function(){ var err = new Error('Joining network failed (Timeout)'); finishJoining(err); }, _timeoutJoin); targetService.on('PropertyChanged', onChange); }
javascript
{ "resource": "" }
q9729
SerialDeviceLoader
train
function SerialDeviceLoader(Device, useGlobal) { // call super class DeviceLoader.call(this); this.Device = Device; this.useGlobal = (useGlobal === undefined || useGlobal === null) ? true : useGlobal; if (this.useGlobal) { this.globalSerialDeviceLoader = globalSerialDeviceLoader.create(Device, this.filter); } }
javascript
{ "resource": "" }
q9730
keysIndexes
train
function keysIndexes(children, startIndex, endIndex) { var i, keys = Object.create(null), key; for (i = startIndex; i <= endIndex; ++i) { if (children[i]) { key = children[i].key; if (key !== undefined) { keys[key] = i; } } } return keys; }
javascript
{ "resource": "" }
q9731
patch
train
function patch(element, previous, dataset) { if (!previous && !dataset) { return dataset; } var name; previous = previous || {}; dataset = dataset || {}; for (name in previous) { if (dataset[name] === undefined) { delete element.dataset[name]; } } for (name in dataset) { if (previous[name] === dataset[name]) { continue; } element.dataset[name] = dataset[name]; } return dataset; }
javascript
{ "resource": "" }
q9732
train
function(stem, p) { var avDOB = Math.pow( ( stem / p.stemCnt / p.stemC) , (1 / p.stemP) ); var ppfs= p.pfsC * Math.pow(avDOB , p.pfsP); return Math.min(p.pfsMx,ppfs); }
javascript
{ "resource": "" }
q9733
train
function (stemG, wsVI, laVI, SLA) { if (stemG < 10) { stemG=10; } var VI = Math.pow( (stemG / wsVI.stems_per_stump / wsVI.constant),(1 / wsVI.power) ); // Add up for all stems var la = laVI.constant * Math.pow(VI,laVI.power) * wsVI.stems_per_stump; var wf = 1000 * (la / SLA); // Foilage Weight in g; var pfs = wf/stemG; return pfs; }
javascript
{ "resource": "" }
q9734
globals
train
function globals() { return { range: function(start, stop, step) { if(typeof stop === 'undefined') { stop = start; start = 0; step = 1; } else if(!step) { step = 1; } var arr = []; var i; if (step > 0) { for (i=start; i<stop; i+=step) { arr.push(i); } } else { for (i=start; i>stop; i+=step) { arr.push(i); } } return arr; }, // lipsum: function(n, html, min, max) { // }, cycler: function() { return cycler(Array.prototype.slice.call(arguments)); }, joiner: function(sep) { return joiner(sep); } }; }
javascript
{ "resource": "" }
q9735
filterFiles
train
function filterFiles(files, check) { return files.filter(function(file) { if (typeof check == 'string') { // ignore typecase equal return check.toLowerCase() === file.toLowerCase(); } else if (Util.isRegExp(check)) { // regexp test return check.test(file); } else if (typeof check == 'function') { // function callback return check(file); } }); }
javascript
{ "resource": "" }
q9736
train
function() { var hooks = {}; return { // ignore hook error ignore: false, // provide async api async: async, /** * add a new hook * @param {String} hook [hook name] * @param {Object} rules [hook trigger rules] * @return Githook */ hook: function(hook, rules) { if (cfg.AVAILABLE_HOOKS.indexOf(hook) < 0 && !this.ignore) { this.error('hook "' + hook + '" not support'); } if (!hooks[hook]) { hooks[hook] = new Githook(rules); } return hooks[hook]; }, /** * remove hook * @param {String} hook [hook name] */ removeHook: function(hook) { if (hooks[hook]) { delete hooks[hook]; } }, /** * return all pending hooks * @return {Array} hook names */ pendingHooks: function() { return Object.keys(hooks); }, /** * trigger Githook * @param {String} hook [hook name] */ trigger: function(hook) { hooks[hook] && hooks[hook].trigger.apply(hooks[hook], Array.prototype.slice.call(arguments, 1)); }, /** * output error message and exit with ERROR_EXIT * @param {String|Error} error */ error: function(error) { if (error) { console.error(error.toString()); } process.exit(cfg.ERROR_EXIT); }, /** * pass immediately * output notice message and exit with SUCCESS_EXIT * @param {[type]} notice [description] * @return {[type]} [description] */ pass: function(notice) { if (notice) { console.log('Notice: ' + notice); } process.exit(cfg.SUCCESS_EXIT); } } }
javascript
{ "resource": "" }
q9737
train
function(hook, rules) { if (cfg.AVAILABLE_HOOKS.indexOf(hook) < 0 && !this.ignore) { this.error('hook "' + hook + '" not support'); } if (!hooks[hook]) { hooks[hook] = new Githook(rules); } return hooks[hook]; }
javascript
{ "resource": "" }
q9738
train
function(error) { if (error) { console.error(error.toString()); } process.exit(cfg.ERROR_EXIT); }
javascript
{ "resource": "" }
q9739
configurePaths
train
function configurePaths(cfg) { var sourcesBasePath = path.resolve(appPath, cfg.get('sourcesBasePath')) ,sources = cfg.get('sources') ,build = cfg.get('build') ,buildBaseUri ,buildDir = nodeEnv == 'development' ? build.baseDirNameDev : build.baseDirNameDist ,buildPath = path.join( path.resolve(appPath, cfg.get('buildBasePath')), buildDir) ,keys, key ,i ; buildBaseUri = cfg.get('staticBaseUri') + '/' + buildDir +'/'; cfg.set('buildBaseUri', buildBaseUri); cfg.set('cssUri', buildBaseUri + build.css.dirName + build.css.external[nodeEnv]); cfg.set('jsUri', buildBaseUri + build.js.dirName + build.js.external[nodeEnv]); cfg.set('testUri', buildBaseUri + build.js.dirName + 'test.js'); // Resolve absolute paths from relative paths in config files cfg.set('staticPath', path.resolve(appPath, cfg.get('staticPath'))); cfg.set('routesPath', path.resolve(appPath, cfg.get('routesPath'))); cfg.set('buildBasePath', path.resolve(appPath, cfg.get('buildBasePath'))); cfg.set('helpersPath', path.resolve(appPath, cfg.get('helpersPath'))); cfg.set('handlebarsHelpersPath', path.resolve(appPath, cfg.get('handlebarsHelpersPath'))); cfg.set('repoWebViewBaseUri', cfg.get('repository').replace('.git', '/') ); keys = Object.keys(sources); for (i = 0; i < keys.length; i++) { key = keys[i]; cfg.set( 'sources.'+key, path.resolve( sourcesBasePath, sources[key]) ); } build.css.inline[nodeEnv] && cfg.set('build.css.inline', path.resolve( buildPath, build.css.inline[nodeEnv] )); build.css.external[nodeEnv] && cfg.set('build.css.external', path.resolve( buildPath, build.css.external[nodeEnv] )); build.js.inline[nodeEnv] && cfg.set('build.js.inline', path.resolve( buildPath, build.js.inline[nodeEnv] )); build.js.external[nodeEnv] && cfg.set('build.js.external', path.resolve( buildPath, build.js.external[nodeEnv] )); cfg.set('build.spritesheets', path.resolve( buildPath, build.spriteSheets.dirName )); return cfg; }
javascript
{ "resource": "" }
q9740
ServerClientStream
train
function ServerClientStream(app){ var StreamHandler; app.use(function(req, res, next){ if(req.originalUrl == '/promise-pipe-connector' && req.method=='POST'){ var message = req.body; message._response = res; StreamHandler(message) } else { return next(); } }); return { send: function(message){ if(!message._response) throw Error("no response defined"); var res = message._response; message._response = undefined; res.json(message); }, listen: function(handler){ StreamHandler = handler; } } }
javascript
{ "resource": "" }
q9741
train
function(url, body, func) { if (typeof url !== 'object') { url = parse(url); } if (!func) { func = body; body = undefined; } var opt = { host: url.hostname, port: url.port || 80, path: url.pathname //agent: false }; if (body) { opt.headers = { 'Content-Type': 'application/xml; charset=utf-8', 'Content-Length': Buffer.byteLength(body), 'Range': 'bytes=0-5120' }; opt.method = 'POST'; } else { opt.method = 'GET'; } var req = http.request(opt); req.on('response', function(res) { var decoder = new StringDecoder('utf8') , total = 0 , body = '' , done = false; var end = function() { if (done) return; done = true; res.body = body; func(null, res); }; res.on('data', function(data) { total += data.length; body += decoder.write(data); if (total > 5120) { res.destroy(); end(); } }).on('error', function(err) { res.destroy(); func(err); }); res.on('end', end); // an agent socket's `end` sometimes // wont be emitted on the response res.socket.on('end', end); }); req.end(body); }
javascript
{ "resource": "" }
q9742
status
train
function status() { console.log('\n'); console.log('Name: ' + chalk.cyan(tiapp.name)); console.log('AppId: ' + chalk.cyan(tiapp.id)); console.log('Version: ' + chalk.cyan(tiapp.version)); console.log('GUID: ' + chalk.cyan(tiapp.guid)); console.log('\n'); }
javascript
{ "resource": "" }
q9743
select
train
function select(name, outfilename) { var regex = /\$tiapp\.(.*)\$/; if (!name) { if (fs.existsSync('./app/config.json')) { var alloyCfg = JSON.parse(fs.readFileSync("./app/config.json", "utf-8")); if (alloyCfg.global.theme) { console.log('\nFound a theme in config.json, trying ' + chalk.cyan(alloyCfg.global.theme)); select(alloyCfg.global.theme); } else { status(); } } } else { // find the config name specified cfg.configs.forEach(function(config) { if (config.name === name) { console.log('\nFound a config for ' + chalk.cyan(config.name) + '\n'); if (fs.existsSync('./app/config.json')) { var alloyCfg = JSON.parse(fs.readFileSync("./app/config.json", "utf-8")); if (alloyCfg.global.theme) { var original = alloyCfg.global.theme; alloyCfg.global.theme = name; fs.writeFile("./app/config.json", JSON.stringify(alloyCfg, null, 2), function (err) { if (err) return console.log(err); console.log('\nChanging theme value in config.json from ' + chalk.cyan(original) + ' to ' + chalk.cyan(name)); }); } } for (var setting in config.settings) { if (!config.settings.hasOwnProperty(setting)) continue; if (setting != "properties" && setting != "raw") { var now = new Date(); var replaceWith = config.settings[setting] .replace('$DATE$', now.toLocaleDateString()) .replace('$TIME$', now.toLocaleTimeString()) .replace('$DATETIME$', now.toLocaleString()) .replace('$TIME_EPOCH$', now.getTime().toString()); var matches = regex.exec(replaceWith); if (matches && matches[1]) { var propName = matches[1]; replaceWith = replaceWith.replace(regex, tiapp[propName]); } tiapp[setting] = replaceWith; console.log('Changing ' + chalk.cyan(setting) + ' to ' + chalk.yellow(replaceWith)); } } if (config.settings.properties) { for (var property in config.settings.properties) { if (!config.settings.properties.hasOwnProperty(property)) continue; var replaceWith = config.settings.properties[property] .replace('$DATE$', new Date().toLocaleDateString()) .replace('$TIME$', new Date().toLocaleTimeString()) .replace('$DATETIME$', new Date().toLocaleString()) .replace('$TIME_EPOCH$', new Date().getTime().toString()); var matches = regex.exec(replaceWith); if (matches && matches[1]) { var propName = matches[1]; replaceWith = replaceWith.replace(regex, tiapp[propName]); } tiapp.setProperty(property, replaceWith); console.log('Changing App property ' + chalk.cyan(property) + ' to ' + chalk.yellow(replaceWith)); } } if (config.settings.raw) { var doc = tiapp.doc; var select = xpath.useNamespaces({ "ti": "http://ti.appcelerator.org", "android": "http://schemas.android.com/apk/res/android" }); for (var path in config.settings.raw) { if (!config.settings.raw.hasOwnProperty(path)) continue; var node = select(path, doc, true); if (!node) { console.log(chalk.yellow('Could not find ' + path + ", skipping")); continue; } var replaceWith = config.settings.raw[path] .replace('$DATE$', new Date().toLocaleDateString()) .replace('$TIME$', new Date().toLocaleTimeString()) .replace('$DATETIME$', new Date().toLocaleString()) .replace('$TIME_EPOCH$', new Date().getTime().toString()); var matches = regex.exec(replaceWith); if (matches && matches[1]) { var propName = matches[1]; replaceWith = replaceWith.replace(regex, tiapp[propName]); } if (typeof(node.value) === 'undefined'){ node.firstChild.data = replaceWith; } else{ node.value = replaceWith; } console.log('Changing Raw property ' + chalk.cyan(path) + ' to ' + chalk.yellow(replaceWith)); } } if (fs.existsSync("./app/themes/" + name + "/assets/iphone/DefaultIcon.png")) { // if it exists in the themes folder, in a platform subfolder console.log(chalk.blue('Found a DefaultIcon.png in the theme\'s assets/iphone folder\n')); copyFile("./app/themes/" + name + "/assets/iphone/DefaultIcon.png", "./DefaultIcon.png") } else if (fs.existsSync("./app/themes/" + name + "/DefaultIcon.png")) { // if it exists in the top level theme folder console.log(chalk.blue('Found a DefaultIcon.png in the theme folder\n')); copyFile("./app/themes/" + name + "/" + "/DefaultIcon.png", "./DefaultIcon.png") } console.log(chalk.green('\n' + outfilename + ' updated\n')); tiapp.write(outfilename); } }); //console.log(chalk.red('\nCouldn\'t find a config called: ' + name + '\n')); } }
javascript
{ "resource": "" }
q9744
$max
train
function $max(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return Math.max(...params); } throw new Error('$max expects an array of number'); }
javascript
{ "resource": "" }
q9745
$min
train
function $min(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return Math.min(...params); } throw new Error('$min expects an array of number'); }
javascript
{ "resource": "" }
q9746
$sum
train
function $sum(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return params.reduce((t, n) => t + n, 0); } throw new Error('$sum expects an array of number'); }
javascript
{ "resource": "" }
q9747
$concat
train
function $concat(params) { if ( Array.isArray(params) && (params.every(p => typeof p === 'string') || params.every(p => Array.isArray(p))) ) { return params[0].concat(...params.slice(1)); } throw new Error('$concat expects an array of array or string'); }
javascript
{ "resource": "" }
q9748
htmlToJsonController
train
function htmlToJsonController (fileContents, filePath, output, p) { var matches; var includePaths = false; while (matches = _DIRECTIVE_REGEX.exec(fileContents)) { var relPath = path.dirname(filePath), fullPath = path.join(relPath, matches[3].replace(/['"]/g, '')).trim(), jsonVar = matches[2], extension = matches[3].split('.').pop(); var fileMatches = []; if (p.includePaths) { if (typeof p.includePaths == "string") { // Arrayify the string includePaths = [params.includePaths]; }else if (Array.isArray(p.includePaths)) { // Set this array to the includepaths includePaths = p.includePaths; } var includePath = ''; for (var y = 0; y < includePaths.length; y++) { includePath = path.join(includePaths[y], matches[3].replace(/['"]/g, '')).trim(); if (fs.existsSync(includePath)) { var globResults = glob.sync(includePath, {mark: true}); fileMatches = fileMatches.concat(globResults); } } } else { var globResults = glob.sync(fullPath, {mark: true}); fileMatches = fileMatches.concat(globResults); } try { fileMatches.forEach(function(value){ var _inc = _parse(value); if (_inc.length > 0) { var ind = (jsonVar.trim() == '*') ? indName(value) : jsonVar; output[ind] = _inc; } }) } catch (err) { console.log(err) } } }
javascript
{ "resource": "" }
q9749
angularTemplate
train
function angularTemplate (p, json) { var prefix = (p.prefix !== "") ? p.prefix + "." : "", tpl = 'angular.module("'+ prefix + p.filename +'",["ng"]).run(["$templateCache",'; tpl += 'function($templateCache) {'; for (var key in json) { if (json.hasOwnProperty(key)) { tpl += '$templateCache.put("'+ key +'",'; tpl += JSON.stringify(json[key]); tpl += ');' } } tpl += '}])'; return tpl; }
javascript
{ "resource": "" }
q9750
getDependencies
train
async function getDependencies(includePaths, file) { const result = await util.promisify(sass.render)({ includePaths, file }); return result.stats.includedFiles.map(path.normalize); }
javascript
{ "resource": "" }
q9751
reduceEntryPointsToDependencies
train
async function reduceEntryPointsToDependencies(includePaths, entryPoints) { return await entryPoints.reduce(async function (allDeps, entry) { const resolvedDeps = await allDeps.then(); const newDeps = await getDependencies(includePaths, entry); return Promise.resolve([ ...resolvedDeps, ...newDeps ]); }, Promise.resolve([])); }
javascript
{ "resource": "" }
q9752
train
async function (directory, filesInSassTree, exclusions) { const filesInDirectory = (await recursive(directory)); const unusedFiles = filesInDirectory .filter((file) => isUnused(file, filesInSassTree, exclusions)); return unusedFiles; }
javascript
{ "resource": "" }
q9753
readIntoBuf
train
function readIntoBuf(stream) { return new Promise((resolve, reject) => { const chunks = [] stream.on('data', chunk => { chunks.push(chunk) }) stream.on('error', err => { reject(err) }) stream.on('end', () => { resolve(Buffer.concat(chunks)) }) }) }
javascript
{ "resource": "" }
q9754
readStr
train
function readStr(buf) { let size = 0 while (buf.readUInt8(size++) != 0x00) continue let str = buf.toString('utf8', 0, size - 1) return [str, size] }
javascript
{ "resource": "" }
q9755
readAppInfo
train
function readAppInfo(buf) { // First byte varies across installs, only the 2nd and 3rd seem consistent if (buf.readUInt8(1) != 0x44 || buf.readUInt8(2) != 0x56) throw new Error('Invalid file signature') return readAppEntries(buf.slice(8)) }
javascript
{ "resource": "" }
q9756
readAppEntries
train
function readAppEntries(buf) { const entries = [] // App entry collection is terminated by null dword for (let off = 0; buf.readUInt32LE(off) != 0x00000000; ++off) { let [entry, size] = readAppEntry(buf.slice(off)) entries.push(entry) off += size } return entries }
javascript
{ "resource": "" }
q9757
readAppEntry
train
function readAppEntry(buf) { let off = 0 const id = buf.readUInt32LE(off) off += 49 // Skip a bunch of fields we don't care about const [name, nameSize] = readStr(buf.slice(off)) off += nameSize const [entries, entriesSize] = readEntries(buf.slice(off)) off += entriesSize return [{id, name, entries}, off] }
javascript
{ "resource": "" }
q9758
readEntries
train
function readEntries(buf) { const entries = {} let off = 0 // Entry collection is terminated by 0x08 byte for (; buf.readUInt8(off) != 0x08;) { let [key, val, size] = readEntry(buf.slice(off)) entries[key] = val off += size } return [entries, off + 1] }
javascript
{ "resource": "" }
q9759
readEntry
train
function readEntry(buf) { let off = 0 let type = buf.readUInt8(off) off += 1 let [key, keySize] = readStr(buf.slice(off)) off += keySize switch (type) { case 0x00: // Nested entries let [kvs, kvsSize] = readEntries(buf.slice(off)) return [key, kvs, off + kvsSize] case 0x01: // String let [str, strSize] = readStr(buf.slice(off)) return [key, str, off + strSize] case 0x02: // Int return [key, buf.readUInt32LE(off), off + 4] default: throw new Error(`Unhandled entry type: ${type}`) } }
javascript
{ "resource": "" }
q9760
renderModule
train
function renderModule(context, options) { var cacheKey ,modSourceTemplate ,mergedData ,html ; // this check is used when rendering isolated modules or views for development and testing (in the default layout!). // skip any modules that are not THE module or THE view. // view: skip all modules that have the attribute _isLayout="true" // module: skip all other modules if ( context.skipModules === true || // case: module context.skipModules == 'layout' && options._isLayout // case: view ) { return ''; } options.template = options.template || options.name; options.tag = options.tag || defaults.tag; options.data = options.data || {}; options.data.moduleNestingLevel = typeof context.moduleNestingLevel === 'undefined' ? 0 : context.moduleNestingLevel + 1; autoIncrementIndent = options.data.moduleNestingLevel > 0 ? 1 : false; options.data.indent = options.indent || autoIncrementIndent || context.indent || 0; // merge the request context and data in the module include, with the latter trumping the former. mergedData = _.merge({}, context, options.data); // create a unique identifier for the module/template combination cacheKey = options.name + ' ' + options.template; // If addTest exists it means we should pass module options into it for later client-side module testing. context._locals && context._locals.addTest && context._locals.addTest(options); // force reading from disk in development mode NODE_ENV == 'development' && (cache[cacheKey] = null); // if the module/template combination is cached use it, else read from disk and cache it. modSourceTemplate = cache[cacheKey] || (cache[cacheKey] = getModTemplate(options)); // render the module source in the locally merged context // moduleSrc is a {{variable}} in the moduleWrapper template try { options.moduleSrc = modSourceTemplate.fn(mergedData); } catch (e) { if (process.env.NODE_ENV != 'test') { if (e instanceof RenderError) // if this is our error from a nested template rethrow it. throw e; else // if this is the original Handlebars error, make it useful throw new RenderError('Module: ' + options.name + ', Template: ' + options.template + cfg.templateExtension +'\n'+ e.toString().replace(/^Error/, 'Reason')); } } if (options.noWrapper) { html = options.moduleSrc; } else { // if we have a persisted read error, add the error class to the module. modSourceTemplate.err && (options.classes = options.classes ? options.classes + ' xtc-error' : 'xtc-error'); if (annotateModules) { options._module = modSourceTemplate.name; options._file = modSourceTemplate.file; options._path = modSourceTemplate.path; options._repository = modSourceTemplate.repository; } // render the wrapper template html = wrapperFn(options); } // manage indentation if (mergedData.indent) { html = utils.indent(html, mergedData.indent, cfg.indentString); } return html; }
javascript
{ "resource": "" }
q9761
_recurseFolder
train
function _recurseFolder(src) { // Ignore var relativeSrc = path.relative(process.cwd(), src); if(_isIgnored(relativeSrc)) return; // Process fs.readdir(src, function(err, files) { files.forEach(function(filename) { fs.stat(src+path.sep+filename, function(err, stat) { if(stat && stat.isDirectory()) { _recurseFolder(src+path.sep+filename); } }); }); }); // Watch current folder _track(src); }
javascript
{ "resource": "" }
q9762
factory
train
function factory(name, schema = {}, options = {}) { class TangModel extends Model { constructor(data) { super(data, schema, options) } } TangModel.options = options TangModel.schema = schema Object.defineProperty(TangModel, 'name', { value: name }) for (let name in schema.statics) { TangModel[name] = function() { return schema.statics[name].apply(TangModel, arguments) } } return TangModel }
javascript
{ "resource": "" }
q9763
UsbDeviceLoader
train
function UsbDeviceLoader(Device, vendorId, productId) { // call super class DeviceLoader.call(this); this.Device = Device; this.vidPidPairs = []; if (!productId && _.isArray(vendorId)) { this.vidPidPairs = vendorId; } else { this.vidPidPairs = [{vendorId: vendorId, productId: productId}]; } }
javascript
{ "resource": "" }
q9764
train
function () { var childNodes = this.nodes(); if (childNodes.length < 1) { return null; } var elementValue = ''; for (var i = 0; i < childNodes.length; i++) { var node = childNodes[i]; var valueToAdd; if (!TypeUtils.isNullOrUndefined(node.value)) { valueToAdd = node.value; } else { valueToAdd = node.toString(); } if (!TypeUtils.isNullOrUndefined(valueToAdd)) { elementValue += valueToAdd; } } return elementValue; }
javascript
{ "resource": "" }
q9765
parse
train
function parse(xml, processNamespaces, angularSyntax) { var doc = new XDocument(); var errors = []; var elementStack = []; var currentContainer = function () { return elementStack.length > 0 ? elementStack[elementStack.length - 1] : doc; }; var xParser = new Xml.XmlParser(function (e) { var c = currentContainer(); if (e.eventType === Xml.ParserEventType.StartElement) { var newElement = new XElement(e.elementName); newElement.add(e.data); var attribs = getOwnProperties(e.attributes); if (!TypeUtils.isNullOrUndefined(attribs)) { for (var p in attribs) { var a = new XAttribute(p); a.value = attribs[p]; newElement.add(a); } } currentContainer().add(newElement); elementStack.push(newElement); } else if (e.eventType === Xml.ParserEventType.Text) { var newText = new XText(); newText.value = e.data; currentContainer().add(newText); } else if (e.eventType === Xml.ParserEventType.CDATA) { var newCData = new XCData(); newCData.value = e.data; currentContainer().add(newCData); } else if (e.eventType === Xml.ParserEventType.Comment) { var newComment = new XComment(); newComment.value = e.data; currentContainer().add(newComment); } else if (e.eventType === Xml.ParserEventType.EndElement) { elementStack.pop(); } }, function (error, position) { errors.push([error, position]); }, processNamespaces, angularSyntax); xParser.parse(xml); if (errors.length > 0) { // collect errors and throw var exceptionMsg = 'XML parse error:'; for (var i = 0; i < errors.length; i++) { var err = errors[i][0]; var pos = errors[i][1]; exceptionMsg += "\n(" + pos.column + "," + pos.line + "): [" + err.name + "] " + err.message; } throw exceptionMsg; } return doc; }
javascript
{ "resource": "" }
q9766
train
function(options) { options = options || {}; this.type = options.type; this.body = options.body; this.actions = options.actions; this.links = options.links; this.embedded = options.embedded; }
javascript
{ "resource": "" }
q9767
outboundPayload
train
function outboundPayload( pipe ){ //Clone first var result = JSON.parse(JSON.stringify( pipe ) ); if ( result.hasOwnProperty("tables")){ //Filtered down the table object as the info it contains is too big to be transported back and forth result.tables = _.map( result.tables, function( table ){ var ret = { name: table.name, label: table.label, labelPlural: table.labelPlural }; //Check for field that start with prefix CLIENT_ which means that the connector expects the value to be sent to client _.map(table, function(value, key){ if ( _.startsWith(key, "CLIENT_")){ ret[key] = value; } }); return ret; }); } if ( result.hasOwnProperty( "sf") ){ delete result.sf; } return result; }
javascript
{ "resource": "" }
q9768
inboundPayload
train
function inboundPayload( storedPipe, pipe ){ if ( storedPipe && storedPipe.hasOwnProperty( "tables" ) ){ pipe.tables = storedPipe.tables; } if ( !pipe.hasOwnProperty("sf") ){ if ( storedPipe && storedPipe.hasOwnProperty( "sf" ) ){ pipe.sf = storedPipe.sf; } } return pipe; }
javascript
{ "resource": "" }
q9769
mergeClassOptions
train
function mergeClassOptions(classes, clazz) { if (!clazz || !clazz.length) { return; } clazz = clazz[0]; var merged = []; var propChecked = {}; var clazzChecking = clazz; while (clazzChecking) { //find class's options var filtered = find({kind: 'member', memberof: clazzChecking.longname, name : 'options'}); if (filtered) { var properties = filtered.length ? filtered[0].properties : null; if (properties) { properties.forEach(function (prop) { //append 'options.' at the head of the property name if (prop.name.indexOf('options') < 0) { prop.name = 'options.' + prop.name; } if (!propChecked[prop.name]) { merged.push(prop); propChecked[prop.name] = 1; } }); } } //find class's parent class var parents = clazzChecking.augments ? helper.find(classes, {longname: clazzChecking.augments[0]}) : null; if (!parents || !parents.length) { break; } clazzChecking = parents[0]; } var toMerge = find({kind: 'member', memberof: clazz.longname, name : 'options'}); if (toMerge.length) { toMerge[0].properties = merged; } }
javascript
{ "resource": "" }
q9770
SerialDevice
train
function SerialDevice(port, settings, Connection) { // call super class Device.call(this, Connection); this.set('portName', port); this.set('settings', settings); this.set('state', 'close'); }
javascript
{ "resource": "" }
q9771
dependencyMatch
train
function dependencyMatch (expected, actual) { // expand github:user/repo#hash to git://github.com/... if (expected.indexOf('github:') === 0) { expected = expected.replace(/^github:/, 'git://github.com/') var parsed = url.parse(expected) parsed.pathname += '.git' expected = url.format(parsed) } // normalize git+https prefix actual = actual.replace(/^git\+https/, 'git') expected = expected.replace(/^git\+https/, 'git') expected = ngu(expected) actual = ngu(actual) expected.url = expected.url.replace('https://', 'git://') actual.url = actual.url.replace('https://', 'git://') if (expected.url !== actual.url) { return false } if (actual.branch && actual.branch.indexOf(expected.branch) !== 0) { return false } return true }
javascript
{ "resource": "" }
q9772
_watch
train
function _watch(vm, vars, update) { var watchKeys = [] function _handler (kp) { if (watchKeys.some(function(key) { if (_relative(kp, key)) { return true } })) update.apply(null, arguments) } if (vars && vars.length) { vars.forEach(function (k) { if (~keywords.indexOf(k)) return while (k) { if (!~watchKeys.indexOf(k)) watchKeys.push(k) k = util.digest(k) } }) if (!watchKeys.length) return noop return vm.$watch(_handler) } return noop }
javascript
{ "resource": "" }
q9773
$asce
train
function $asce(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return params.sort((a, b) => a - b); } throw new Error('$asce expects an array of number'); }
javascript
{ "resource": "" }
q9774
$rand
train
function $rand(params) { if (Array.isArray(params)) { return params[Math.floor(Math.random() * params.length)]; } throw new Error('$rand expects an array'); }
javascript
{ "resource": "" }
q9775
$rands
train
function $rands(params) { if ( Array.isArray(params) && params.length === 2 && Array.isArray(params[0]) && typeof params[1] === 'number' ) { return Array(params[1]) .fill() .map(() => params[0].splice( Math.floor(Math.random() * params[0].length), 1 ) )[0]; } throw new Error( '$rands expects an array of two elements of which the first must be an array and the second be a number' ); }
javascript
{ "resource": "" }
q9776
$slice
train
function $slice(params) { if ( Array.isArray(params) && (params.length === 2 || params.length === 3) && Array.isArray(params[0]) && typeof params[1] === 'number' && (params[2] === undefined || typeof params[2] === 'number') ) { return params[0].slice(params[1], params[2]); } throw new Error( '$slice expects an array of two or three elements of which the first must be an array and the second/third be a number' ); }
javascript
{ "resource": "" }
q9777
getVitalUnits
train
function getVitalUnits(vitalType) { /*for height and weight, you need some kind of realistic numberical evaluator to determine the weight and height units */ if (vitalType.toLowerCase() === 'blood pressure') { return 'mm[Hg]'; } else if (vitalType.toLowerCase().indexOf('glucose') >= 0) { return 'mg/dL'; } else if (vitalType.toLowerCase().indexOf('height') >= 0) { return 'cm'; } else if (vitalType.toLowerCase().indexOf('weight') >= 0) { return 'kg'; } return null; }
javascript
{ "resource": "" }
q9778
applyMixins
train
function applyMixins(derivedCtor, baseCtors) { baseCtors.forEach(baseCtor => { Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => { if (name !== 'constructor') { derivedCtor.prototype[name] = baseCtor.prototype[name]; } }); }); }
javascript
{ "resource": "" }
q9779
stat
train
function stat(file, cb) { utils.fileExists(file); utils.fs.stat(file.path, function(err, stat) { if (err) { file.stat = null; cb(err, file); return; } file.stat = stat; cb(null, file); }); }
javascript
{ "resource": "" }
q9780
statSync
train
function statSync(file) { utils.fileExists(file); Object.defineProperty(file, 'stat', { configurable: true, set: function(val) { file._stat = val; }, get: function() { if (file._stat) { return file._stat; } if (this.exists) { file._stat = utils.fs.statSync(this.path); return file._stat; } return null; } }); }
javascript
{ "resource": "" }
q9781
lstatSync
train
function lstatSync(file) { utils.fileExists(file); Object.defineProperty(file, 'lstat', { configurable: true, set: function(val) { file._lstat = val; }, get: function() { if (file._lstat) { return file._lstat; } if (this.exists) { file._lstat = utils.fs.lstatSync(this.path); return file._lstat; } return null; } }); }
javascript
{ "resource": "" }
q9782
cleanUpModel
train
function cleanUpModel(bbDocumentModel) { var x; for (x in bbDocumentModel) { if (Object.keys(bbDocumentModel[x]).length === 0) { delete bbDocumentModel[x]; } } var data = bbDocumentModel.data; for (x in data) { if (Object.keys(data[x]).length === 0) { delete data[x]; } } }
javascript
{ "resource": "" }
q9783
Tag
train
function Tag(tagName, config, children) { this.tagName = tagName || 'div'; config = config || {}; this.children = children || []; this.props = config.props; this.attrs = config.attrs; this.attrsNS = config.attrsNS; this.events = config.events; this.hooks = config.hooks; this.data = config.data; this.params = config.params; this.element = undefined; this.parent = undefined; this.key = config.key != null ? config.key : undefined; this.namespace = config.attrs && config.attrs.xmlns || null; this.is = config.attrs && config.attrs.is || null; }
javascript
{ "resource": "" }
q9784
broadcastRemove
train
function broadcastRemove(node) { if (node.children) { for (var i = 0, len = node.children.length; i < len; i++) { if (node.children[i]) { broadcastRemove(node.children[i]); } } } if (node.hooks && node.hooks.remove) { node.hooks.remove(node, node.element); } }
javascript
{ "resource": "" }
q9785
$split
train
function $split(params) { if (typeof params === 'string') { return params.split(/\s+/); } if ( Array.isArray(params) && (params.length === 2 || params.length === 3) && typeof params[0] === 'string' && typeof params[1] === 'string' && (params[3] == null || typeof params[3] === 'number') ) { return params[0].split(params[1], params[2]); } throw new Error( '$split expects an array of two string elements with an additional number element' ); }
javascript
{ "resource": "" }
q9786
triangleDraw
train
function triangleDraw(c, params) { const size = params.size const half = params.size / 2 c.beginPath() c.fillStyle = '#' + params.color.toString(16) c.moveTo(half, 0) c.lineTo(0, size) c.lineTo(size, size) c.closePath() c.fill() c.fillStyle = 'white' c.font = '40px Arial' const measure = c.measureText(n) c.fillText(n++, size / 2 - measure.width / 2, size / 2 + 10) }
javascript
{ "resource": "" }
q9787
visit
train
function visit(state, filePath, one, done) { var file // Don’t walk into places multiple times. if (own.call(state.checked, filePath)) { done([]) return } state.checked[filePath] = true file = vfile(filePath) stat(resolve(filePath), onstat) function onstat(error, stats) { var real = Boolean(stats) var results = [] var result if (state.broken || !real) { done([]) } else { result = state.test(file, stats) if (mask(result, INCLUDE)) { results.push(file) if (one) { state.broken = true return done(results) } } if (mask(result, BREAK)) { state.broken = true } if (state.broken || !stats.isDirectory() || mask(result, SKIP)) { return done(results) } readdir(filePath, onread) } function onread(error, entries) { visitAll(state, entries, filePath, one, onvisit) } function onvisit(files) { done(results.concat(files)) } } }
javascript
{ "resource": "" }
q9788
visitAll
train
function visitAll(state, paths, cwd, one, done) { var expected = paths.length var actual = -1 var result = [] paths.forEach(each) next() function each(filePath) { visit(state, join(cwd || '', filePath), one, onvisit) } function onvisit(files) { result = result.concat(files) next() } function next() { actual++ if (actual === expected) { done(result) } } }
javascript
{ "resource": "" }
q9789
isArrayLike
train
function isArrayLike (a) { if ('object' != typeof a) return false else if (null == a) return false else return Boolean( Array.isArray(a) || null != a.length || a[0] ) }
javascript
{ "resource": "" }
q9790
mkdux
train
function mkdux (node, data = {}) { if (node instanceof Container) node = node.domElement node[STARDUX_PRIVATE_ATTR] = ( node[STARDUX_PRIVATE_ATTR] || data ) return node[STARDUX_PRIVATE_ATTR] }
javascript
{ "resource": "" }
q9791
rmdux
train
function rmdux (node) { if (null == node) return if (node instanceof Container) node = node.domElement delete node[STARDUX_PRIVATE_ATTR] }
javascript
{ "resource": "" }
q9792
getTokens
train
function getTokens (string) { let tokens = null try { tokens = esprima.tokenize('`'+ string +'`') } catch (e) { tokens = [] } return tokens }
javascript
{ "resource": "" }
q9793
getIdentifiersFromTokens
train
function getIdentifiersFromTokens (tokens) { const identifiers = {} /** * Predicate to determine if token is an identifier. * * @private * @param {Object} token * @return {Boolean} */ const isIdentifier = token => 'Identifier' == token.type /** * Mark token as a function identifier. * * @private * @param {Object} token * @param {Number} index * @return {Object} token */ const markFunction = (token, index) => { const next = tokens[index + 1] || null token.isFunction = ( 'Identifier' == token.type && 'object' == typeof next && next && 'Punctuator' == next.type && '(' == next.value ? true : false ) return token } /** * Mark token as a object identifier. * * @private * @param {Object} token * @param {Number} index * @return {Object} token */ const markObject = (token, index) => { const next = tokens[index + 1] || null token.isObject = ( 'Identifier' == token.type && 'object' == typeof next && next && 'Punctuator' == next.type && '.' == next.value ? true : false ) return token } /** * Assign token value to identifierss map. * * @private * @param {Object} map * @param {Object} token * @return {Object} map */ const assign = (map, token) => { const value = token.value if (token.isFunction) map[value] = _ => '' else if (token.isObject) map[value] = {} else map[value] = '' return map } // resolve identifierss and return map return ( tokens .map((t, i) => markFunction(t, i)) .map((t, i) => markObject(t, i)) .filter(t => isIdentifier(t)) .reduce((map, t) => assign(map, t), identifiers) ) }
javascript
{ "resource": "" }
q9794
ensureDOMElement
train
function ensureDOMElement (input) { let domElement = null let tmp = null if (input instanceof Element) { return input } else if ('string' == typeof input) { tmp = document.createElement('div') tmp.innerHTML = input domElement = tmp.innerHTML.length ? tmp.children[0] : new Template(input) } else { domElement = document.createElement('div') } return domElement }
javascript
{ "resource": "" }
q9795
getTemplateFromDomElement
train
function getTemplateFromDomElement (domElement) { let data = {} let src = null if (domElement && domElement[STARDUX_PRIVATE_ATTR]) data = mkdux(domElement) if ('string' == typeof domElement) src = domElement else if (data.src) src = data.src else if (domElement.children && 0 == domElement.children.length) src = ensureDOMString(domElement.textContent) else if (domElement.firstChild instanceof Text) src = ensureDOMString(domElement.innerHTML) else if (domElement instanceof Text) src = ensureDOMString(domElement.textContent) else if (domElement) src = domElement.innerHTML || domElement.textContent return src }
javascript
{ "resource": "" }
q9796
createRootReducer
train
function createRootReducer (container, ...reducers) { return (state = {}, action = {}) => { const identifiers = ensureContainerStateIdentifiers(container) const domElement = container[$domElement] const template = getTemplateFromDomElement(domElement) const middleware = container[$middleware].entries() const isBody = domElement == document.body if (action.data) { state = extend(state, action.data) } /** * Loops over each pipe function * providing state and action values * given to use from redux. * * @private */ const reducerSet = new Set([ ...reducers ]) const reducerEntires = reducerSet.entries() reduce() function reduce () { const step = reducerEntires.next() const done = step.done const reducer = step.value ? step.value[1] : null if (done) return const newState = reducer(state, action) if (null != newState) state = newState reduce() } if ($UPDATE_ACTION == action.type) { /** * Loops over each middleware function * providing state and action values * given to use from redux. * * @private */ void function next () { const step = middleware.next() const done = step.done const reducer = step.value ? step.value[0] : null if (done) return else if (null == reducer) next() else if (false === reducer(state, action)) return else next() }() container.define(state) if (!isBody && identifiers) { const parser = new Parser() const partial = new Template(template) const src = partial.render(container.state, container) const patch = parser.createPatch(src) patch(domElement) } } return state } }
javascript
{ "resource": "" }
q9797
createPipeReducer
train
function createPipeReducer (container) { return (state, action = {data: {}}) => { const pipes = container[$pipes].entries() reduce() return state /** * Loops over each pipe function * providing state and action values * given to use from redux. * * @private */ function reduce () { const step = pipes.next() const done = step.done const pipe = step.value ? step.value[1] : null if (done) return else if (false === pipe(state, action)) return else return reduce() } } }
javascript
{ "resource": "" }
q9798
reduce
train
function reduce () { const step = pipes.next() const done = step.done const pipe = step.value ? step.value[1] : null if (done) return else if (false === pipe(state, action)) return else return reduce() }
javascript
{ "resource": "" }
q9799
orphanContainerChildren
train
function orphanContainerChildren (container, rouge = false) { container = fetchContainer(container) const children = container.children if (null == container) throw new TypeError( "orphanContainerChildren() Expecting a container " ) for (let child of children) { container.removeChild(child) if (true === rouge) { orphanContainerChildren(child, true) CONTAINERS.delete(child.id) } } }
javascript
{ "resource": "" }