_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q63900
detectTakeout
test
function detectTakeout(selectors){ var properties = { takeout: false }; options.takeout.forEach(function (takeout) { selectors.forEach(function (selector) { if (selector.indexOf(takeout.ruleprefix) === 0) { properties.takeout = true; properties.filename = takeout.filename; } }); }); return properties; }
javascript
{ "resource": "" }
q63901
parseLineByLine
test
function parseLineByLine(text) { var lines = text.trim().split("\n"); var bookmarks = lines.splice(0, lines.length * 3 / 4); return { bookmarks: bookmarks, lines: lines }; }
javascript
{ "resource": "" }
q63902
CommonalityInterface
test
function CommonalityInterface(MatrixConstructor, top) { this.top = top; this.length = null; this.matrix = null; this.MatrixConstructor = MatrixConstructor; }
javascript
{ "resource": "" }
q63903
CommanalityMatrix
test
function CommanalityMatrix(classlist) { // space will identify a text node and/or an element node without any classnames this.rowKeys = {}; this.rowNames = []; this.collumKeys = {}; this.collumNames = []; this.nodeMatrix = []; this.summaryMatrix = []; this.dim = [0, 0]; this.bestIndex = [-1, -1]; this._bestNodes = {}; }
javascript
{ "resource": "" }
q63904
arrayVector
test
function arrayVector(size) { var vec = new Array(size); for (var i = 0; i < size; i++) vec[i] = []; return vec; }
javascript
{ "resource": "" }
q63905
buildAttributeMatcher
test
function buildAttributeMatcher(match) { var keys = Object.keys(match); var jskey, i, l; var transform = ''; var bool = ''; transform = 'transform = {\n'; for (i = 0, l = keys.length; i < l; i++) { jskey = JSON.stringify(keys[i]); transform += ' ' + jskey + ': attr.hasOwnProperty(' + jskey + ') ? attr[' + jskey + '].toLowerCase() : false'; if (i !== l - 1) transform += ','; transform += '\n'; } transform += '};\n'; bool = 'return !!('; for (i = 0, l = keys.length; i < l; i++) { jskey = JSON.stringify(keys[i]); if (i > 0) bool += ' || '; bool += ' ( transform[' + jskey + ']'; if (Array.isArray(match[keys[i]])) { bool += ' && ( '; for (var j = 0, s = match[keys[i]].length; j < s; j++) { if (j > 0) bool += ' || '; if (typeof match[keys[i]][j] === 'string') { bool += 'transform[' + jskey + '] === \'' + match[keys[i]][j].toLowerCase() + '\''; } else if (util.isRegExp(match[keys[i]][j])) { bool += 'match[' + jskey + '][' + j + '].test(transform[' + jskey + '])'; } } bool += ' )'; } bool += ' ) \n'; } bool += ' );'; var anonymous = new Function('attr', 'match', transform + '\n' + bool); return function (attr) { return anonymous(attr, match); }; }
javascript
{ "resource": "" }
q63906
containerOf
test
function containerOf(a, b) { while (b = b.parent) { if (a === b) return true; } return false; }
javascript
{ "resource": "" }
q63907
commonParent
test
function commonParent(a, b) { if (a === b) { return a; } else if (containerOf(a, b)) { return a; } else if (containerOf(b, a)) { return b; } else { // This will happen at some point, since the root is a container of // everything while (b = b.parent) { if (containerOf(b, a)) return b; } } }
javascript
{ "resource": "" }
q63908
styleParser
test
function styleParser(style) { style = style || ''; var tokens = style.trim().split(/\s*(?:;|:)\s*/); var output = {}; for (var i = 1, l = tokens.length; i < l; i += 2) { output[tokens[i - 1]] = tokens[i]; } return output; }
javascript
{ "resource": "" }
q63909
treeDistance
test
function treeDistance(a, b) { if (a === b) return 0; var parent = commonParent(a, b); var aParent = a; var aCount = 0; var bParent = b; var bCount = 0; if (parent !== a) { while (parent !== aParent.parent) { aCount += 1; aParent = aParent.parent; } } else { bCount += 1; } if (parent !== b) { while (parent !== bParent.parent) { bCount += 1; bParent = bParent.parent; } } else { aCount += 1; } var abCount = 0; if (parent !== a && parent !== b) { abCount = Math.abs( parent.children.indexOf(aParent) - parent.children.indexOf(bParent) ); } return aCount + bCount + abCount; }
javascript
{ "resource": "" }
q63910
Lexer
test
function Lexer(file, options) { this.options = utils.extend({}, options); this.file = file; this.regex = new RegexCache(); this.names = []; this.ast = { tags: {}, type: 'root', name: 'root', nodes: [] }; this.unknown = {tags: [], blocks: []}; this.known = { tags: ['extends', 'layout'], blocks: ['block'] }; this.delimiters = { variable: ['{{', '}}'], block: ['{%', '%}'], es6: ['${', '}'], }; this.tokens = [this.ast]; this.errors = []; this.stack = []; this.stash = []; this.lexers = {}; this.fns = []; }
javascript
{ "resource": "" }
q63911
test
function() { if (this.isInitialized) return; this.isInitialized = true; var lexer = this; this.lineno = 1; this.column = 1; this.lexed = ''; this.file = utils.normalize(this.file); this.file.orig = this.file.contents; this.input = this.file.contents.toString(); this.file.ast = this.ast; this.file.ast.variables = {}; this.file.ast.blocks = {}; this.input = this.input.split('{% body %}') .join('{% block "body" %}{% endblock %}'); if (this.file.extends) { this.prependNode(this.file, 'extends'); } /** * Tags */ this.captureTag('extends'); this.captureTag('layout'); /** * Block tags */ this.captureBlock('block'); /** * Captures */ this.capture('text', utils.negateDelims(this.delimiters)); this.capture('newline', /^\n+/); this.capture('es6', /^\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/); this.capture('variable', /^\{{2,}([^\\}]*(?:\\.[^\\}]*)*)\}{2,}/); this.capture('escape', /^\\(.)/); this.capture('space', /^[ \t]+/); /** * Custom helpers */ var helpers = this.options.helpers || {}; if (utils.isObject(helpers)) { helpers = Object.keys(helpers); } helpers.forEach(function(key) { lexer.known.blocks.push(key); lexer.captureBlock(key); }); /** * Add other names to return un-rendered */ var matches = this.input.match(/\{%\s*([^%}]+)/g); var names = utils.getNames(matches); names.tags.forEach(function(key) { if (!utils.isRegistered(lexer, key)) { lexer.unknown.tags.push(key); lexer.captureTag(key); } }); names.blocks.forEach(function(key) { if (!utils.isRegistered(lexer, key)) { lexer.unknown.blocks.push(key); lexer.captureBlock(key); } }); }
javascript
{ "resource": "" }
q63912
test
function(msg) { var message = this.file.relative + ' line:' + this.lineno + ' column:' + this.column + ': ' + msg; var err = new Error(message); err.reason = msg; err.line = this.lineno; err.column = this.column; err.source = this.input; err.path = this.file.path; if (this.options.silent) { this.errors.push(err); } else { throw err; } }
javascript
{ "resource": "" }
q63913
test
function(type) { var cached = this.regex.createVariable(type); var file = this.file; var lexer = this; var fn = this.lexers[type] = function() { var pos = lexer.position(); var m = lexer.match(cached.strict); if (!m) return; var parent = this.prev(); var node = pos({ type: type, known: utils.has(lexer.known.tags, type), val: m[0].trim() }); parent.known = node.known; var nodes = parent.nodes; Object.defineProperty(file.ast.variables, type, { configurable: true, set: function(val) { nodes = val; }, get: function() { return nodes; } }); Object.defineProperty(parent, 'nodes', { configurable: true, set: function(val) { nodes = val; }, get: function() { return nodes; } }); utils.define(node, 'parent', parent); parent.nodes.push(node); }; this.addLexer(fn); return this; }
javascript
{ "resource": "" }
q63914
test
function(type) { this.ast.tags[type] = null; this.names.push(type); var cached = this.regex.createTag(type); var file = this.file; var lexer = this; var fn = this.lexers[type] = function() { var pos = lexer.position(); var m = lexer.match(cached.strict); if (!m) return; var name = utils.getName(m[1]); if (this.options.strict) { var isKnown = utils.has(lexer.known.tags, type); if (isKnown && file.hasOwnProperty(type) && !file.hasOwnProperty('isParsed')) { throw new Error(`only one "${type}" tag may be defined per template`); } } file[type] = name; lexer.ast.tags[type] = name; lexer.createNode(type, name, m, pos); }; this.addLexer(fn); return this; }
javascript
{ "resource": "" }
q63915
test
function(type, name, m, pos) { var parent = this.prev(); var val = m[1]; var tok = { type: 'args', val: val }; var node = pos({ type: type, name: name, known: utils.has(this.known.tags, type), val: val.trim(), nodes: [tok] }); utils.define(node, 'parent', parent); utils.define(tok, 'parent', node); parent.nodes.push(node); }
javascript
{ "resource": "" }
q63916
test
function(type) { this.names.push(type); var cached = this.regex.createOpen(type); var file = this.file; var lexer = this; return function() { var pos = lexer.position(); var m = lexer.match(cached.strict); if (!m) return; var name = utils.getName(m[1]); var action = utils.getAction(m[1]); var val = m[0]; if (!name && lexer.options[type] && lexer.options[type].args === 'required') { throw new Error(`no arguments defined on "${type}": ${m[0]}`); } if (!name) name = 'unnamed'; var node = pos({ type: `${type}.open`, known: utils.has(lexer.known.blocks, type), name: name, val: val.trim() }); var parent = lexer.prev(); if (parent && parent.name && parent.name !== 'root') { name = parent.name + '.' + name; } var block = { type: type, name: name, known: node.known, action: action, nodes: [node] }; utils.define(node, 'parent', block); utils.define(block, 'parent', parent); block.rawArgs = m[1]; block.args = utils.parseArgs(m[1]); Object.defineProperty(file.ast.blocks[type], name, { configurable: true, enumerable: true, set: function(val) { block = val; }, get: function() { return block; } }); parent.nodes.push(block); lexer.tokens.push(block); return block; }; }
javascript
{ "resource": "" }
q63917
test
function(type) { var cached = this.regex.createClose(type); var file = this.file; var lexer = this; return function() { var pos = lexer.position(); var m = lexer.match(cached.strict); if (!m) return; var block = lexer.tokens.pop(); if (typeof block === 'undefined' || block.type !== type) { throw new Error(`missing opening ${type}`); } if (block.name === 'body') { lexer.ast.isLayout = true; file.ast.isLayout = true; } var nodes = block.nodes; Object.defineProperty(file.ast.blocks, block.name, { configurable: true, set: function(val) { nodes = val; }, get: function() { return nodes; } }); Object.defineProperty(block, 'nodes', { configurable: true, set: function(val) { nodes = val; }, get: function() { return nodes; } }); var tok = pos({ known: block.known, type: `${type}.close`, val: m[0].trim() }); utils.define(block, 'position', tok.position); utils.define(tok, 'parent', block); block.nodes.push(tok); return block; }; }
javascript
{ "resource": "" }
q63918
test
function(type) { this.file.ast.blocks[type] = this.file.ast.blocks[type] || {}; this.addLexer(this.captureOpen(type)); this.addLexer(this.captureClose(type)); return this; }
javascript
{ "resource": "" }
q63919
test
function(file, prop) { return this.createNode(prop, file[prop], `{% ${prop} "${file[prop]}" %}`, this.position()); }
javascript
{ "resource": "" }
q63920
test
function(str, len) { var lines = str.match(/\n/g); if (lines) this.lineno += lines.length; var i = str.lastIndexOf('\n'); this.column = ~i ? len - i : this.column + len; this.lexed += str; this.consume(str, len); }
javascript
{ "resource": "" }
q63921
test
function() { var len = this.fns.length; var idx = -1; while (++idx < len) { this.fns[idx].call(this); if (!this.input) { break; } } }
javascript
{ "resource": "" }
q63922
test
function() { while (this.input) { var prev = this.input; this.advance(); if (this.input && prev === this.input) { throw new Error(`no lexers registered for: "${this.input.substr(0, 10)}"`); } } }
javascript
{ "resource": "" }
q63923
test
function(file) { debug('lexing <%s>', this.file.path); if (file) this.file = file; this.init(); while (this.input) this.next(); return this.ast; }
javascript
{ "resource": "" }
q63924
notifyHook
test
function notifyHook(e) { message_count++; var message; if (!options.enabled) { return; } if (!e) { return; } if (e && e.length === 1) { e = e[0]; } if (/Task .* failed\./.test(e.message)) { message = e.message; } else if (e.message && e.stack) { message = exception(e); } else { message = e + ''; } if (message_count > 0 && message === 'Aborted due to warnings.') { // skip unhelpful message because there was probably another one that was more helpful return; } // shorten message by removing full path // TODO - make a global replace message = message.replace(cwd, '').replace('\x07', ''); return notify({ title: options.title + (grunt.task.current.nameArgs ? ' ' + grunt.task.current.nameArgs : ''), message: message }); }
javascript
{ "resource": "" }
q63925
test
function() { if (this._initialized && this._isPaused) { return false; } this._isPaused = true; raf.cancel(this._requestID); this._pauseTime = now(); this._onPause(); return true; }
javascript
{ "resource": "" }
q63926
test
function() { if (this._initialized && !this._isPaused) { return false; } var pauseDuration; this._isPaused = false; this._prevTime = now(); pauseDuration = this._prevTime - this._pauseTime; this._onResume(pauseDuration); this._requestID = raf.request(this._tick); return true; }
javascript
{ "resource": "" }
q63927
mktmpdir
test
function mktmpdir(prefixSuffix, tmpdir, callback, onend) { if ('function' == typeof prefixSuffix) { onend = tmpdir; callback = prefixSuffix; tmpdir = null; prefixSuffix = null; } else if ('function' == typeof tmpdir) { onend = callback; callback = tmpdir; tmpdir = null; } prefixSuffix = prefixSuffix || 'd'; onend = onend || function() {}; tmpname.create(prefixSuffix, tmpdir, function(err, path, next) { if (err) return callback(err); fs.mkdir(path, 0700, next); }, function(err, path) { if (err) return callback(err); callback(null, path, function(err) { if (!path) return onend(err); rimraf(path, function(_err) { onend(err || _err, path); }); }); }); }
javascript
{ "resource": "" }
q63928
copyString
test
function copyString(buffer, length, offsetBegin, offsetEnd) { if (length > 2048) { return buffer.toString('utf-8', offsetBegin, offsetEnd); } var string = ''; while(offsetBegin < offsetEnd) { string += String.fromCharCode(buffer[offsetBegin++]); } return string; }
javascript
{ "resource": "" }
q63929
parseSimpleString
test
function parseSimpleString(parser) { var offset = parser.offset; var length = parser.buffer.length; var string = ''; while (offset < length) { var c1 = parser.buffer[offset++]; if (c1 === 13) { var c2 = parser.buffer[offset++]; if (c2 === 10) { parser.offset = offset; return string; } string += String.fromCharCode(c1) + String.fromCharCode(c2); continue; } string += String.fromCharCode(c1); } return undefined; }
javascript
{ "resource": "" }
q63930
getBaseConfig
test
function getBaseConfig(isProd) { // get library details from JSON config const libraryEntryPoint = path.join('src', LIBRARY_DESC.entry); // generate webpack base config return { entry: [ // "babel-polyfill", path.join(__dirname, libraryEntryPoint), ], output: { devtoolLineToLine: true, pathinfo: true, }, module: { preLoaders: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: "eslint-loader", }, ], loaders: [ { exclude: /(node_modules|bower_components)/, loader: "babel-loader", plugins: [ "transform-runtime", ], query: { presets: [ "es2015", "stage-0", "stage-1", "stage-2", ], cacheDirectory: false, }, test: /\.js$/, }, ], }, eslint: { configFile: './.eslintrc', }, resolve: { root: path.resolve('./src'), extensions: ['', '.js'], }, devtool: isProd ? "source-map"/* null*/ : "source-map"/* '#eval-source-map'*/, debug: !isProd, plugins: isProd ? [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new UglifyJsPlugin({ compress: { warnings: true }, minimize: true, sourceMap: true, }), // Prod plugins here ] : [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"development"' } }), new UglifyJsPlugin({ compress: { warnings: true }, minimize: true, sourceMap: true, }), // Dev plugins here ], }; }
javascript
{ "resource": "" }
q63931
postNotification
test
function postNotification(options, cb) { options.title = removeColor(options.title); options.message = removeColor(options.message); if (!options.message) { return cb && cb(!options.message && 'Message is required'); } if (!notifyPlatform) { notifyPlatform = choosePlatform(); } function resetPreviousTimer(newMessage) { previousMessage = newMessage; clearTimeout(previousMessageTimer); previousMessageTimer = setTimeout(function(){previousMessage = false;}, previousMessageTimeoutMS); } if (options.message === previousMessage) { resetPreviousTimer(options.message); if (typeof cb === 'function') { cb(err); } return; } resetPreviousTimer(options.message); options.debug = debug(notifyPlatform.name); //for debug logging return notifyPlatform.notify(options, function(err){ if (err) { options.debug({ return_code: err }); } if (typeof cb === 'function') { cb(err); } }); }
javascript
{ "resource": "" }
q63932
generateUsername
test
function generateUsername(base) { base = base.toLowerCase(); var entries = []; var finalName; return userDB.allDocs({startkey: base, endkey: base + '\uffff', include_docs: false}) .then(function(results){ if(results.rows.length === 0) { return BPromise.resolve(base); } for(var i=0; i<results.rows.length; i++) { entries.push(results.rows[i].id); } if(entries.indexOf(base) === -1) { return BPromise.resolve(base); } var num = 0; while(!finalName) { num++; if(entries.indexOf(base+num) === -1) { finalName = base + num; } } return BPromise.resolve(finalName); }); }
javascript
{ "resource": "" }
q63933
linkSuccess
test
function linkSuccess(req, res, next) { var provider = getProvider(req.path); var result = { error: null, session: null, link: provider }; var template; if(config.getItem('testMode.oauthTest')) { template = fs.readFileSync(path.join(__dirname, '../templates/oauth/auth-callback-test.ejs'), 'utf8'); } else { template = fs.readFileSync(path.join(__dirname, '../templates/oauth/auth-callback.ejs'), 'utf8'); } var html = ejs.render(template, result); res.status(200).send(html); }
javascript
{ "resource": "" }
q63934
linkTokenSuccess
test
function linkTokenSuccess(req, res, next) { var provider = getProviderToken(req.path); res.status(200).json({ ok: true, success: util.capitalizeFirstLetter(provider) + ' successfully linked', provider: provider }); }
javascript
{ "resource": "" }
q63935
oauthErrorHandler
test
function oauthErrorHandler(err,req,res,next) { var template; if(config.getItem('testMode.oauthTest')) { template = fs.readFileSync(path.join(__dirname, '../templates/oauth/auth-callback-test.ejs'), 'utf8'); } else { template = fs.readFileSync(path.join(__dirname, '../templates/oauth/auth-callback.ejs'), 'utf8'); } var html = ejs.render(template, {error: err.message, session: null, link: null}); console.error(err); if(err.stack) { console.error(err.stack); } res.status(400).send(html); }
javascript
{ "resource": "" }
q63936
tokenAuthErrorHandler
test
function tokenAuthErrorHandler(err,req,res,next) { var status; if(req.user && req.user._id) { status = 403; } else { status = 401; } console.error(err); if(err.stack) { console.error(err.stack); delete err.stack; } res.status(status).json(err); }
javascript
{ "resource": "" }
q63937
registerProvider
test
function registerProvider(provider, configFunction) { provider = provider.toLowerCase(); var configRef = 'providers.' + provider; if (config.getItem(configRef + '.credentials')) { var credentials = config.getItem(configRef + '.credentials'); credentials.passReqToCallback = true; var options = config.getItem(configRef + '.options') || {}; configFunction.call(null, credentials, passport, authHandler); router.get('/' + provider, passportCallback(provider, options, 'login')); router.get('/' + provider + '/callback', passportCallback(provider, options, 'login'), initSession, oauthErrorHandler); if(!config.getItem('security.disableLinkAccounts')) { router.get('/link/' + provider, passport.authenticate('bearer', {session: false}), passportCallback(provider, options, 'link')); router.get('/link/' + provider + '/callback', passport.authenticate('bearer', {session: false}), passportCallback(provider, options, 'link'), linkSuccess, oauthErrorHandler); } console.log(provider + ' loaded.'); } }
javascript
{ "resource": "" }
q63938
registerOAuth2
test
function registerOAuth2 (providerName, Strategy) { registerProvider(providerName, function (credentials, passport, authHandler) { passport.use(new Strategy(credentials, function (req, accessToken, refreshToken, profile, done) { authHandler(req, providerName, {accessToken: accessToken, refreshToken: refreshToken}, profile) .asCallback(done); } )); }); }
javascript
{ "resource": "" }
q63939
registerTokenProvider
test
function registerTokenProvider (providerName, Strategy) { providerName = providerName.toLowerCase(); var configRef = 'providers.' + providerName; if (config.getItem(configRef + '.credentials')) { var credentials = config.getItem(configRef + '.credentials'); credentials.passReqToCallback = true; var options = config.getItem(configRef + '.options') || {}; // Configure the Passport Strategy passport.use(providerName + '-token', new Strategy(credentials, function (req, accessToken, refreshToken, profile, done) { authHandler(req, providerName, {accessToken: accessToken, refreshToken: refreshToken}, profile) .asCallback(done); })); router.post('/' + providerName + '/token', passportTokenCallback(providerName, options), initTokenSession, tokenAuthErrorHandler); if(!config.getItem('security.disableLinkAccounts')) { router.post('/link/' + providerName + '/token', passport.authenticate('bearer', {session: false}), passportTokenCallback(providerName, options), linkTokenSuccess, tokenAuthErrorHandler); } console.log(providerName + '-token loaded.'); } }
javascript
{ "resource": "" }
q63940
authHandler
test
function authHandler(req, provider, auth, profile) { if(req.user && req.user._id && req.user.key) { return user.linkSocial(req.user._id, provider, auth, profile, req); } else { return user.socialAuth(provider, auth, profile, req); } }
javascript
{ "resource": "" }
q63941
passportCallback
test
function passportCallback(provider, options, operation) { return function(req, res, next) { var theOptions = extend({}, options); if(provider === 'linkedin') { theOptions.state = true; } var accessToken = req.query.bearer_token || req.query.state; if(accessToken && (stateRequired.indexOf(provider) > -1 || config.getItem('providers.' + provider + '.stateRequired') === true)) { theOptions.state = accessToken; } theOptions.callbackURL = getLinkCallbackURLs(provider, req, operation, accessToken); theOptions.session = false; passport.authenticate(provider, theOptions)(req, res, next); }; }
javascript
{ "resource": "" }
q63942
passportTokenCallback
test
function passportTokenCallback(provider, options) { return function(req, res, next) { var theOptions = extend({}, options); theOptions.session = false; passport.authenticate(provider + '-token', theOptions)(req, res, next); }; }
javascript
{ "resource": "" }
q63943
getProvider
test
function getProvider(pathname) { var items = pathname.split('/'); var index = items.indexOf('callback'); if(index > 0) { return items[index-1]; } }
javascript
{ "resource": "" }
q63944
getProviderToken
test
function getProviderToken(pathname) { var items = pathname.split('/'); var index = items.indexOf('token'); if(index > 0) { return items[index-1]; } }
javascript
{ "resource": "" }
q63945
requireRole
test
function requireRole(requiredRole) { return function(req, res, next) { if(!req.user) { return next(superloginError); } var roles = req.user.roles; if(!roles || !roles.length || roles.indexOf(requiredRole) === -1) { res.status(forbiddenError.status); res.json(forbiddenError); } else { next(); } }; }
javascript
{ "resource": "" }
q63946
test
function() { var foundLayer = null; $.each(projectedTiles, function (layerName, layer) { if (map.hasLayer(layer)) { foundLayer = layer; } }); return foundLayer; }
javascript
{ "resource": "" }
q63947
test
function (crs, options) { switch(crs) { case "EPSG:3857": return L.CRS.EPSG3857; case "EPSG:3395": return L.CRS.EPSG3395; case "EPSG:4326": return L.CRS.EPSG4326; default: return this._defineMapCRS(crs, options); } }
javascript
{ "resource": "" }
q63948
test
function (group) { var map = this; if (group.eachLayer) { group.eachLayer(function (layer) { map._updateAllLayers(layer); }); } else { if (group.redraw) { group.redraw(); } else if (group.update) { group.update(); } else { console.log("Don't know how to update", group); } } }
javascript
{ "resource": "" }
q63949
test
function (layersArray) { var fg = this._featureGroup, npg = this._nonPointGroup, chunked = this.options.chunkedLoading, chunkInterval = this.options.chunkInterval, chunkProgress = this.options.chunkProgress, newMarkers, i, l, m; if (this._map) { var offset = 0, started = (new Date()).getTime(); var process = L.bind(function () { var start = (new Date()).getTime(); for (; offset < layersArray.length; offset++) { if (chunked && offset % 200 === 0) { // every couple hundred markers, instrument the time elapsed since processing started: var elapsed = (new Date()).getTime() - start; if (elapsed > chunkInterval) { break; // been working too hard, time to take a break :-) } } m = layersArray[offset]; //Not point data, can't be clustered if (!m.getLatLng) { npg.addLayer(m); continue; } if (this.hasLayer(m)) { continue; } this._addLayer(m, this._maxZoom); //If we just made a cluster of size 2 then we need to remove the other marker from the map (if it is) or we never will if (m.__parent) { if (m.__parent.getChildCount() === 2) { var markers = m.__parent.getAllChildMarkers(), otherMarker = markers[0] === m ? markers[1] : markers[0]; fg.removeLayer(otherMarker); } } } if (chunkProgress) { // report progress and time elapsed: chunkProgress(offset, layersArray.length, (new Date()).getTime() - started); } if (offset === layersArray.length) { //Update the icons of all those visible clusters that were affected this._featureGroup.eachLayer(function (c) { if (c instanceof L.MarkerCluster && c._iconNeedsUpdate) { c._updateIcon(); } }); this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds); } else { setTimeout(process, this.options.chunkDelay); } }, this); process(); } else { newMarkers = []; for (i = 0, l = layersArray.length; i < l; i++) { m = layersArray[i]; //Not point data, can't be clustered if (!m.getLatLng) { npg.addLayer(m); continue; } if (this.hasLayer(m)) { continue; } newMarkers.push(m); } this._needsClustering = this._needsClustering.concat(newMarkers); } return this; }
javascript
{ "resource": "" }
q63950
test
function (layersArray) { var i, l, m, fg = this._featureGroup, npg = this._nonPointGroup; if (!this._map) { for (i = 0, l = layersArray.length; i < l; i++) { m = layersArray[i]; this._arraySplice(this._needsClustering, m); npg.removeLayer(m); } return this; } for (i = 0, l = layersArray.length; i < l; i++) { m = layersArray[i]; if (!m.__parent) { npg.removeLayer(m); continue; } this._removeLayer(m, true, true); if (fg.hasLayer(m)) { fg.removeLayer(m); if (m.setOpacity) { m.setOpacity(1); } } } //Fix up the clusters and markers on the map this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds); fg.eachLayer(function (c) { if (c instanceof L.MarkerCluster) { c._updateIcon(); } }); return this; }
javascript
{ "resource": "" }
q63951
test
function () { var bounds = new L.LatLngBounds(); if (this._topClusterLevel) { bounds.extend(this._topClusterLevel._bounds); } for (var i = this._needsClustering.length - 1; i >= 0; i--) { bounds.extend(this._needsClustering[i].getLatLng()); } bounds.extend(this._nonPointGroup.getBounds()); return bounds; }
javascript
{ "resource": "" }
q63952
test
function (method, context) { var markers = this._needsClustering.slice(), i; if (this._topClusterLevel) { this._topClusterLevel.getAllChildMarkers(markers); } for (i = markers.length - 1; i >= 0; i--) { method.call(context, markers[i]); } this._nonPointGroup.eachLayer(method, context); }
javascript
{ "resource": "" }
q63953
test
function (layer) { if (!layer) { return false; } var i, anArray = this._needsClustering; for (i = anArray.length - 1; i >= 0; i--) { if (anArray[i] === layer) { return true; } } anArray = this._needsRemoving; for (i = anArray.length - 1; i >= 0; i--) { if (anArray[i] === layer) { return false; } } return !!(layer.__parent && layer.__parent._group === this) || this._nonPointGroup.hasLayer(layer); }
javascript
{ "resource": "" }
q63954
test
function (map) { this._map = map; var i, l, layer; if (!isFinite(this._map.getMaxZoom())) { throw "Map has no maxZoom specified"; } this._featureGroup.onAdd(map); this._nonPointGroup.onAdd(map); if (!this._gridClusters) { this._generateInitialClusters(); } for (i = 0, l = this._needsRemoving.length; i < l; i++) { layer = this._needsRemoving[i]; this._removeLayer(layer, true); } this._needsRemoving = []; //Remember the current zoom level and bounds this._zoom = this._map.getZoom(); this._currentShownBounds = this._getExpandedVisibleBounds(); this._map.on('zoomend', this._zoomEnd, this); this._map.on('moveend', this._moveEnd, this); if (this._spiderfierOnAdd) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely this._spiderfierOnAdd(); } this._bindEvents(); //Actually add our markers to the map: l = this._needsClustering; this._needsClustering = []; this.addLayers(l); }
javascript
{ "resource": "" }
q63955
test
function (map) { map.off('zoomend', this._zoomEnd, this); map.off('moveend', this._moveEnd, this); this._unbindEvents(); //In case we are in a cluster animation this._map._mapPane.className = this._map._mapPane.className.replace(' leaflet-cluster-anim', ''); if (this._spiderfierOnRemove) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely this._spiderfierOnRemove(); } //Clean up all the layers we added to the map this._hideCoverage(); this._featureGroup.onRemove(map); this._nonPointGroup.onRemove(map); this._featureGroup.clearLayers(); this._map = null; }
javascript
{ "resource": "" }
q63956
test
function (anArray, obj) { for (var i = anArray.length - 1; i >= 0; i--) { if (anArray[i] === obj) { anArray.splice(i, 1); return true; } } }
javascript
{ "resource": "" }
q63957
test
function (layer, newCluster) { if (newCluster === layer) { this._featureGroup.addLayer(layer); } else if (newCluster._childCount === 2) { newCluster._addToMap(); var markers = newCluster.getAllChildMarkers(); this._featureGroup.removeLayer(markers[0]); this._featureGroup.removeLayer(markers[1]); } else { newCluster._updateIcon(); } }
javascript
{ "resource": "" }
q63958
test
function (storageArray) { storageArray = storageArray || []; for (var i = this._childClusters.length - 1; i >= 0; i--) { this._childClusters[i].getAllChildMarkers(storageArray); } for (var j = this._markers.length - 1; j >= 0; j--) { storageArray.push(this._markers[j]); } return storageArray; }
javascript
{ "resource": "" }
q63959
test
function () { var childClusters = this._childClusters.slice(), map = this._group._map, boundsZoom = map.getBoundsZoom(this._bounds), zoom = this._zoom + 1, mapZoom = map.getZoom(), i; //calculate how far we need to zoom down to see all of the markers while (childClusters.length > 0 && boundsZoom > zoom) { zoom++; var newClusters = []; for (i = 0; i < childClusters.length; i++) { newClusters = newClusters.concat(childClusters[i]._childClusters); } childClusters = newClusters; } if (boundsZoom > zoom) { this._group._map.setView(this._latlng, zoom); } else if (boundsZoom <= mapZoom) { //If fitBounds wouldn't zoom us down, zoom us down instead this._group._map.setView(this._latlng, mapZoom + 1); } else { this._group._map.fitBounds(this._bounds); } }
javascript
{ "resource": "" }
q63960
test
function (marker) { var addedCount, addedLatLng = marker._wLatLng || marker._latlng; if (marker instanceof L.MarkerCluster) { this._bounds.extend(marker._bounds); addedCount = marker._childCount; } else { this._bounds.extend(addedLatLng); addedCount = 1; } if (!this._cLatLng) { // when clustering, take position of the first point as the cluster center this._cLatLng = marker._cLatLng || addedLatLng; } // when showing clusters, take weighted average of all points as cluster center var totalCount = this._childCount + addedCount; //Calculate weighted latlng for display if (!this._wLatLng) { this._latlng = this._wLatLng = new L.LatLng(addedLatLng.lat, addedLatLng.lng); } else { this._wLatLng.lat = (addedLatLng.lat * addedCount + this._wLatLng.lat * this._childCount) / totalCount; this._wLatLng.lng = (addedLatLng.lng * addedCount + this._wLatLng.lng * this._childCount) / totalCount; } }
javascript
{ "resource": "" }
q63961
test
function () { if (this._group._spiderfied === this || this._group._inZoomAnimation) { return; } var childMarkers = this.getAllChildMarkers(), group = this._group, map = group._map, center = map.latLngToLayerPoint(this._latlng), positions; this._group._unspiderfy(); this._group._spiderfied = this; //TODO Maybe: childMarkers order by distance to center if (childMarkers.length >= this._circleSpiralSwitchover) { positions = this._generatePointsSpiral(childMarkers.length, center); } else { center.y += 10; //Otherwise circles look wrong positions = this._generatePointsCircle(childMarkers.length, center); } this._animationSpiderfy(childMarkers, positions); }
javascript
{ "resource": "" }
q63962
test
function (childMarkers, positions) { var group = this._group, map = group._map, fg = group._featureGroup, i, m, leg, newPos; for (i = childMarkers.length - 1; i >= 0; i--) { newPos = map.layerPointToLatLng(positions[i]); m = childMarkers[i]; m._preSpiderfyLatlng = m._latlng; m.setLatLng(newPos); if (m.setZIndexOffset) { m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING } fg.addLayer(m); leg = new L.Polyline([this._latlng, newPos], { weight: 1.5, color: '#222' }); map.addLayer(leg); m._spiderLeg = leg; } this.setOpacity(0.3); group.fire('spiderfied'); }
javascript
{ "resource": "" }
q63963
test
function (layer) { if (layer._spiderLeg) { this._featureGroup.removeLayer(layer); layer.setOpacity(1); //Position will be fixed up immediately in _animationUnspiderfy layer.setZIndexOffset(0); this._map.removeLayer(layer._spiderLeg); delete layer._spiderLeg; } }
javascript
{ "resource": "" }
q63964
addToMap
test
function addToMap(location, map) { var marker = L.marker(location.coordinates); marker.addTo(map); }
javascript
{ "resource": "" }
q63965
interpolate
test
function interpolate (path, data) { return path.replace(/:(\w+)/g, function (match, param) { return data[param] }) }
javascript
{ "resource": "" }
q63966
createPagesUtility
test
function createPagesUtility (pages, index) { return function getPages (number) { var offset = Math.floor(number / 2) var start, end if (index + offset >= pages.length) { start = Math.max(0, pages.length - number) end = pages.length } else { start = Math.max(0, index - offset) end = Math.min(start + number, pages.length) } return pages.slice(start, end) } }
javascript
{ "resource": "" }
q63967
test
function() { var templates = { data: {} }; var stringTemplateSource = function(template) { this.text = function(value) { if (arguments.length === 0) { return templates[template]; } templates[template] = value; }; }; var templateEngine = new ko.nativeTemplateEngine(); templateEngine.makeTemplateSource = function(template) { return new stringTemplateSource(template); }; templateEngine.addTemplate = function(key, value) { templates[key] = value; }; return templateEngine; }
javascript
{ "resource": "" }
q63968
Job
test
function Job(collection, data) { this.collection = collection; if (data) { // Convert plain object to JobData type data.__proto__ = JobData.prototype; this.data = data; } else { this.data = new JobData(); } }
javascript
{ "resource": "" }
q63969
Worker
test
function Worker(queues, options) { options || (options = {}); this.empty = 0; this.queues = queues || []; this.interval = options.interval || 5000; this.callbacks = options.callbacks || {}; this.strategies = options.strategies || {}; this.universal = options.universal || false; // Default retry strategies this.strategies.linear || (this.strategies.linear = linear); this.strategies.exponential || (this.strategies.exponential = exponential); // This worker will only process jobs of this priority or higher this.minPriority = options.minPriority; }
javascript
{ "resource": "" }
q63970
handleDragEvents
test
function handleDragEvents(e) { e.stopPropagation(); e.preventDefault(); return this.emit(e.type, e); }
javascript
{ "resource": "" }
q63971
test
function(value) { if(value != value || value === 0) { for(var i = this.length; i-- && !is(this[i], value);){} } else { i = [].indexOf.call(this, value); } return i; }
javascript
{ "resource": "" }
q63972
Tor
test
function Tor(child, port, dir) { this.process = child; this.port = port; this.dir = dir; }
javascript
{ "resource": "" }
q63973
getIncluded
test
function getIncluded() { var args = config.files().included || getDefaultArgs() || getPackageJsonArgs() || getBowerJsonArgs() || []; return _expandGlobs(args); }
javascript
{ "resource": "" }
q63974
getDefaultArgs
test
function getDefaultArgs() { var results = []; DEFAULT_PATHS.forEach(function(dir) { if( fs.existsSync(dir) ) results.push(dir); }); return results.length == 0 ? null : results; }
javascript
{ "resource": "" }
q63975
getPackageJsonArgs
test
function getPackageJsonArgs() { var results = []; var config = _loadJson('package.json'); if( config.main ) results = results.concat(getMainFieldAsArray(config.main)); if( config.files ) results = results.concat(config.files); return results.length == 0 ? null : results.filter(_uniqfilter); }
javascript
{ "resource": "" }
q63976
getBowerJsonArgs
test
function getBowerJsonArgs() { var results = []; var config = _loadJson('bower.json'); if( config.main ) results = results.concat(getMainFieldAsArray(config.main)); return results.length == 0 ? null : results.filter(_uniqfilter); }
javascript
{ "resource": "" }
q63977
getMainFieldAsArray
test
function getMainFieldAsArray(main) { if( main.constructor === Array ) { return main; } else { if( fs.existsSync(main) ) { return [main]; } else if( fs.existsSync(main+'.js') ) { return [main+'.js']; } else { return []; } } }
javascript
{ "resource": "" }
q63978
TorAgent
test
function TorAgent(opts) { if (!(this instanceof TorAgent)) { return new TorAgent(); } http.Agent.call(this, opts); this.socksHost = opts.socksHost || 'localhost'; this.socksPort = opts.socksPort || 9050; this.defaultPort = 80; // Used when invoking TorAgent.create this.tor = opts.tor; // Prevent protocol check, wrap destroy this.protocol = null; this.defaultDestroy = this.destroy; this.destroy = this.destroyWrapper; }
javascript
{ "resource": "" }
q63979
run
test
function run(inch_args, options) { var callback = function(filename) { LocalInch.run(inch_args || ['suggest'], filename, noop); } if( options.dry_run ) callback = noop; retriever.run(PathExtractor.extractPaths(inch_args), callback); }
javascript
{ "resource": "" }
q63980
shutdown
test
function shutdown(addr, b) { if(addr<0 || addr>=maxDevices) throw 'address out of range'; if(b) spiTransfer(addr, OP_SHUTDOWN,0); else spiTransfer(addr, OP_SHUTDOWN,1); }
javascript
{ "resource": "" }
q63981
setScanLimit
test
function setScanLimit(addr, limit) { if(addr<0 || addr>=maxDevices) return; //console.log("OP_SCANLIMIT"); if(limit>=0 && limit<8) spiTransfer(addr, OP_SCANLIMIT,limit); }
javascript
{ "resource": "" }
q63982
setBrightness
test
function setBrightness(addr, intensity) { if(addr<0 || addr>=maxDevices) return; if (typeof intensity == 'undefined') return; intensity = constrain(intensity, 0, 15); spiTransfer(addr, OP_INTENSITY,intensity); }
javascript
{ "resource": "" }
q63983
clearDisplay
test
function clearDisplay(addr) { if(addr<0 || addr>=maxDevices) throw 'address out of range'; var offset; offset=addr*8; for(var i=0;i<8;i++) { status[offset+i]=0; spiTransfer(addr, i+1,status[offset+i]); } }
javascript
{ "resource": "" }
q63984
showNumber
test
function showNumber(addr, num, decimalplaces, mindigits, leftjustified, pos, dontclear) { if(addr<0 || addr>=maxDevices) throw 'address out of range'; num = formatNumber(num, decimalplaces, mindigits); // internally, pos is 0 on the right, so we set defaults, and convert if(typeof pos === 'undefined') { if(leftjustified) { pos = 7; } else { pos = 0; } } else pos = 7-pos; // get rid of the decimal place but remember where it was var decimalplace; if(num.indexOf('.')<0) decimalplace = -1; else { decimalplace = num.length - num.indexOf('.') -1; num = num.split('.').join(''); } if(leftjustified) { pos-=(num.length-1); } for(var i = 0; i<8; i++) { var offset = i+pos; var char = num.charAt(num.length-1-i); if((offset<8 && offset>=0) && (!dontclear || char!='')) { if(char=='-') setChar(addr, offset, char, i>0 && i==decimalplace); else setDigit(addr, offset, parseInt(char), i>0 && i==decimalplace); } } }
javascript
{ "resource": "" }
q63985
getExampleCode
test
function getExampleCode(comment) { var expectedResult = comment.expectedResult; var isAsync = comment.isAsync; var testCase = comment.testCase; if(isAsync) { return '\nfunction cb(err, result) {' + 'if(err) return done(err);' + 'result.should.eql(' + expectedResult + ');' + 'done();' + '}\n' + 'var returnValue = ' + testCase + ';' + 'if(returnValue && returnValue.then && typeof returnValue.then === \'function\') {' + 'returnValue.then(cb.bind(null, null), cb);' + '}'; } else { return '(' + testCase + ').should.eql(' + expectedResult + ');'; } }
javascript
{ "resource": "" }
q63986
test
function (options) { "use strict"; if ((options.setter && options.setter.indexOf('.') > -1) || (options.getter && options.getter.indexOf('.') > -1)) { throw new Error('Getter (' + options.getter + ') and setter (' + options.setter + ') methods cannot be nested, so they cannot contain dot(.)'); } this.options = Joi.attempt(options, optionsSchema); this.locales = this.getAvailableLocales(); this.default = this.options.default || this.locales[0]; //this.callback = this.getCallback(this.options.callback); }
javascript
{ "resource": "" }
q63987
fileExists
test
function fileExists(path, shouldBeDir) { "use strict"; try { var lstat = fs.lstatSync(path); if (shouldBeDir && lstat.isDirectory()) { return true; } if (!shouldBeDir && lstat.isFile()) { return true; } } catch (err) { return false; } return false; }
javascript
{ "resource": "" }
q63988
test
async function (server, options) { try { var internal = new Internal(options); } catch (err) { throw new Boom(err); } /** * @module exposed * @description * Exposed functions and attributes are listed under exposed name. * To access those attributes `request.server.plugins['hapi-locale']` can be used. * @example * var locales = request.server.plugins['hapi-locale'].getLocales(); // ['tr_TR', 'en_US'] etc. */ /** * Returns all available locales as an array. * @name getLocales * @function * @returns {Array.<string>} - Array of locales. * @example * var locales = request.server.plugins['hapi-locale'].getLocales(); // ['tr_TR', 'en_US'] etc. */ server.expose('getLocales', function getLocales() { return internal.locales; }); /** * Returns default locale. * @name getDefaultLocale * @function * @returns {string} - Default locale */ server.expose('getDefaultLocale', function getDefaultLocale() { return internal.default; }); /** * Returns requested language. * @name getLocale * @function * @param {Object} request - Hapi.js request object * @returns {string} Locale */ server.expose('getLocale', function getLocale(request) { try { return lodash.get(request, internal.options.getter)(); } catch (err) { return null; } }); server.ext(internal.options.onEvent, internal.processRequest, {bind: internal}); }
javascript
{ "resource": "" }
q63989
test
function (currDeps, loc) { loc.deps = loc.deps || []; var covered = []; // only cover unique paths once to avoid stack overflow currDeps.forEach(function (obj) { if (covered.indexOf(obj.path) < 0) { covered.push(obj.path); // cover unique paths only once per level var key = obj.name , isRelative = (['\\', '/', '.'].indexOf(key[0]) >= 0) , notCovered = notCoveredInArray(loc.deps, key) , isRecorded = (!isRelative || opts.showLocal) && notCovered , res = isRecorded ? { name: key } : loc; if (isRecorded) { // NB: !isRecorded => only inspect the file for recorded deps res.path = obj.path; loc.deps.push(res); } // recurse (!isRecorded => keep adding to previous location) traverse(lookup[obj.path] || [], res); } }); }
javascript
{ "resource": "" }
q63990
test
function (ms, cycles) { var removed = {}; cycles.forEach(function (c) { var last = c[c.length-1]; // last id in cycle //console.log('will try to trim from', last, ms[last]); // need to find a dependency in the cycle var depsInCycle = ms[last].filter(function (deps) { return deps.path && c.indexOf(deps.path) >= 0; }); if (!depsInCycle.length) { throw new Error("logic fail2"); // last thing in a cycle should have deps } var depToRemove = depsInCycle[0].path; //console.log('deps in cycle', depsInCycle); for (var i = 0; i < ms[last].length; i += 1) { var dep = ms[last][i]; if (dep.path && dep.path === depToRemove) { //console.log('removing', depToRemove); removed[last] = dep.name; ms[last].splice(i, 1); } } //console.log('after remove', ms[last]); }); return removed; }
javascript
{ "resource": "" }
q63991
test
function(options) { // Validate options assert(options, "options are required"); assert(options.name, "Series must be named"); options = _.defaults({}, options, { columns: {}, additionalColumns: null }); // Store options this._options = options; }
javascript
{ "resource": "" }
q63992
whenRead
test
function whenRead (args) { let value = getValue(args) if (value && typeof value.then === 'function') { value.then((val) => whenTest(args, val)).catch((error) => { console.error(`${action.displayName} caught an error whilst getting a value to test`, error) }) } else { whenTest(args, value) } }
javascript
{ "resource": "" }
q63993
findAndDelete
test
function findAndDelete(target, value) { if (!isIterable(target)) return false; if (isArray(target)) { for (let i = 0; i < target.length; i++) { if (deep_equal_1.default(target[i], value)) { target.splice(i, 1); return true; } } } else if (isObject(target)) { const keys = Object.keys(target); for (let i = 0; i < keys.length; i++) { if (deep_equal_1.default(target[keys[i]], value)) { delete target[keys[i]]; return true; } } } return false; }
javascript
{ "resource": "" }
q63994
findAndDeleteAll
test
function findAndDeleteAll(target, value) { let flag = false; while (findAndDelete(target, value)) { flag = true; } return flag; }
javascript
{ "resource": "" }
q63995
test
function(options) { assert(options, "options are required"); assert(options.connectionString, "options.connectionString is missing"); assert(url.parse(options.connectionString).protocol === 'https:' || options.allowHTTP, "InfluxDB connectionString must use HTTPS!"); options = _.defaults({}, options, { maxDelay: 60 * 5, maxPendingPoints: 250 }); this._options = options; this._pendingPoints = {}; this._nbPendingPoints = 0; this._flushTimeout = setTimeout( this.flush.bind(this, true), options.maxDelay * 1000 ); }
javascript
{ "resource": "" }
q63996
test
function(handler, options) { assert(handler instanceof Function, "A handler must be provided"); assert(options, "options required"); assert(options.drain, "options.drain is required"); assert(options.component, "options.component is required"); // Create a reporter var reporter = series.HandlerReports.reporter(options.drain); // Wrap handler and let that be it return function(message) { // Create most of the point var point = { component: options.component, duration: undefined, exchange: message.exchange || '', redelivered: (message.redelivered ? 'true' : 'false'), error: 'false' }; // Start timer var start = process.hrtime(); // Handle the message return Promise.resolve(handler(message)).then(function() { // Get duration var d = process.hrtime(start); // Convert to milliseconds point.duration = d[0] * 1000 + (d[1] / 1000000); // Send point to reporter reporter(point); }, function(err) { // Get duration var d = process.hrtime(start); // Convert to milliseconds point.duration = d[0] * 1000 + (d[1] / 1000000); // Flag and error point.error = 'true'; // Send point to reporter reporter(point); // Re-throw the error throw err; }); }; }
javascript
{ "resource": "" }
q63997
test
function(options) { // Validate options assert(options, "Options are required"); assert(options.drain, "A drain for the measurements must be provided!"); assert(options.component, "A component must be specified"); assert(options.process, "A process name must be specified"); // Provide default options options = _.defaults({}, options, { interval: 60 }); // Clear reporting if already started if (_processUsageReportingInterval) { debug("WARNING: startProcessUsageReporting() already started!"); clearInterval(_processUsageReportingInterval); _processUsageReportingInterval = null; } // Lazy load the usage monitor module var usage = require('usage'); // Create reporter var reporter = series.UsageReports.reporter(options.drain); // Set interval to report usage at interval _processUsageReportingInterval = setInterval(function() { // Lookup usage for the current process usage.lookup(process.pid, {keepHistory: true}, function(err, result) { // Check for error if (err) { debug("Failed to get usage statistics, err: %s, %j", err, err, err.stack); return; } // Report usage reporter({ component: options.component, process: options.process, cpu: result.cpu, memory: result.memory }); }); }, options.interval * 1000); }
javascript
{ "resource": "" }
q63998
test
function(options) { options = _.defaults({}, options || {}, { tags: {}, drain: undefined }); assert(options.drain, "options.drain is required"); assert(typeof options.tags === 'object', "options.tags is required"); assert(_.intersection( _.keys(options.tags), series.APIClientCalls.columns() ).length === 0, "Can't used reserved tag names!"); // Create a reporter return series.APIClientCalls.reporter(options.drain, options.tags); }
javascript
{ "resource": "" }
q63999
buildOptions
test
function buildOptions (options) { var result = []; var keys = Object.keys(options); keys.forEach(function (key) { var props = options[key]; // convert short to long form if (is.string(props)) { props = { type: props }; } // all names of an option // aliases come first // full name comes last var name = [ format('--%s', dasherize(key)) ]; // accept both string and array var aliases = props.alias || props.aliases || []; if (is.not.array(aliases)) { aliases = [aliases]; } // aliases are prefixed with "-" aliases.forEach(function (alias) { alias = format('-%s', alias); name.unshift(alias); }); result.push([ name.join(', '), props.desc || '' ]); }); return table(result); }
javascript
{ "resource": "" }