_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q40300
DataChanneMessageEvent
train
function DataChanneMessageEvent (event) { this.data = event.data; this.source = event.source; this.lastEventId = event.lastEventId; this.origin = event.origin; this.timeStamp = event.timeStamp; this.type = event.type; this.ports = event.ports; this.path = event.path; }
javascript
{ "resource": "" }
q40301
PeerConnectionChannels
train
function PeerConnectionChannels (pc) { /// Private Data var channels = [], api = {}; /// Private API var remove = function remove (channel) { OT.$.filter(channels, function(c) { return channel !== c; }); }; var add = function add (nativeChannel) { var channe...
javascript
{ "resource": "" }
q40302
train
function(messageDelegate) { return function(event) { if (event.candidate) { messageDelegate(OT.Raptor.Actions.CANDIDATE, { candidate: event.candidate.candidate, sdpMid: event.candidate.sdpMid || '', sdpMLineIndex: event.candidate.sdpMLineIndex || 0 }); } els...
javascript
{ "resource": "" }
q40303
fixFitModeCover
train
function fixFitModeCover(element, containerWidth, containerHeight, intrinsicRatio, rotated) { var $video = OT.$('.OT_video-element', element); if ($video.length > 0) { var cssProps = {left: '', top: ''}; if (OTPlugin.isInstalled()) { cssProps.width = '100%'; cssProps....
javascript
{ "resource": "" }
q40304
train
function(config) { _cleanup(); if (!config) config = {}; _global = config.global || {}; _partners = config.partners || {}; if (!_loaded) _loaded = true; this.trigger('dynamicConfigChanged'); }
javascript
{ "resource": "" }
q40305
train
function(key, value, oldValue) { if (oldValue) { self.trigger('styleValueChanged', key, value, oldValue); } else { self.trigger('styleValueChanged', key, value); } }
javascript
{ "resource": "" }
q40306
handleInvalidStateChanges
train
function handleInvalidStateChanges(newState) { if (!isValidState(newState)) { signalChangeFailed('\'' + newState + '\' is not a valid state', newState); return false; } if (!isValidTransition(currentState, newState)) { signalChangeFailed('\'' + currentState + '\' ...
javascript
{ "resource": "" }
q40307
fileSort
train
function fileSort(a, b) { return Number(b.stat && b.stat.isDirectory()) - Number(a.stat && a.stat.isDirectory()) || String(a.name).toLocaleLowerCase().localeCompare(String(b.name).toLocaleLowerCase()); }
javascript
{ "resource": "" }
q40308
htmlPath
train
function htmlPath(dir) { var parts = dir.split('/'); var crumb = new Array(parts.length); for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (part) { parts[i] = encodeURIComponent(part); crumb[i] = '<a href="' + escapeHtml(parts.slice(0, i + 1).join('/')) + '">' + escapeHtml(pa...
javascript
{ "resource": "" }
q40309
iconLookup
train
function iconLookup(filename) { var ext = extname(filename); // try by extension if (icons[ext]) { return { className: 'icon-' + ext.substring(1), fileName: icons[ext] }; } var mimetype = mime.lookup(ext); // default if no mime type if (mimetype === false) { return { class...
javascript
{ "resource": "" }
q40310
iconStyle
train
function iconStyle (files, useIcons) { if (!useIcons) return ''; var className; var i; var iconName; var list = []; var rules = {}; var selector; var selectors = {}; var style = ''; for (i = 0; i < files.length; i++) { var file = files[i]; var isDir = '..' == file.name || (file.stat && fil...
javascript
{ "resource": "" }
q40311
html
train
function html(files, dir, useIcons, view, req) { return '<ul id="files" class="view-' + escapeHtml(view) + '">' + (view == 'details' ? ( '<li class="header">' + '<span class="name">Name</span>' + '<span class="size">Size</span>' + '<span class="date">Modified</span>' + '</li>') : '')...
javascript
{ "resource": "" }
q40312
load
train
function load(icon) { if (cache[icon]) return cache[icon]; return cache[icon] = fs.readFileSync(__dirname + '/public/icons/' + icon, 'base64'); }
javascript
{ "resource": "" }
q40313
stat
train
function stat(dir, files, cb) { var batch = new Batch(); batch.concurrency(10); files.forEach(function(file){ batch.push(function(done){ fs.stat(join(dir, file), function(err, stat){ if (err && err.code !== 'ENOENT') return done(err); // pass ENOENT as null stat, not error don...
javascript
{ "resource": "" }
q40314
getMiddlePaths
train
function getMiddlePaths(paths, ext, new_ext) { if (Array.isArray(paths)) { return paths.map(function eachEntry(entry) { return getMiddlePaths(entry, ext, new_ext); }); } if (ext && new_ext) { paths = paths.replace(ext, new_ext); } return paths; }
javascript
{ "resource": "" }
q40315
train
function(name, autoFlushExpired) { var storeName; function __construct(name) { try { storeName = validateStoreName(name); if (autoFlushExpired === undefined || autoFlushExpired !== false) { flushExpired(); } ...
javascript
{ "resource": "" }
q40316
set
train
function set(key, data, expiresAt) { try { if (expiresAt !== undefined && typeof expiresAt === 'number') { STORE.setItem(storeName + key + EXPIRE_KEY, expiresAt.toString()); } STORE.setItem(storeName + key, decodeObjectString(data));...
javascript
{ "resource": "" }
q40317
get
train
function get(key) { try { if (key !== undefined) { var result = encodeObjectString(STORE.getItem(storeName + key)); return result !== null ? result : false; } else { var resultAll = {}; O...
javascript
{ "resource": "" }
q40318
validateStoreName
train
function validateStoreName(storeName) { if (storeName === undefined) { throw new TypeError('Please provide a storename'); } if (typeof(storeName) !== 'string') { throw new TypeError('The storename has to be a string'); } ...
javascript
{ "resource": "" }
q40319
invert
train
function invert(obj) { let result = {}; let keys = Object.keys(obj); for (let i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }
javascript
{ "resource": "" }
q40320
train
function(context, property, params) { context = context || this; var parent = context.__isClazz ? this.__parent : this.__parent.prototype; if (!property) { return parent; } if (!(property in parent)) { ...
javascript
{ "resource": "" }
q40321
loadIfNeeded
train
function loadIfNeeded (elementScope) { const notPreProcessed = elementScope.querySelectorAll('[img-src]') // image elements which have attribute 'i-lazy-src' were elements // that had been preprocessed by lib-img-core, but not loaded yet, and // must be loaded when 'appear' events were fired. It turns out the ...
javascript
{ "resource": "" }
q40322
train
function(configArray, validExt) { var success = true, fileMask, filePath, dirContent; configArray.forEach(function(cfg) { var files = []; // setup files' paths (join file's input directory path with name) // check for the wildcards ...
javascript
{ "resource": "" }
q40323
train
function(prefix, obj) { return '\n'+prefix.cyan+'\n - '+ (Array.isArray(obj) ? obj.join('\n - ') : obj.toString()); }
javascript
{ "resource": "" }
q40324
train
function(cfg, callback) { var lessCompiledCode = ""; // Filter all Less files var lessFiles = filterInput(cfg.input_files, '.less'); // Filter all Css files var cssFiles = filterInput(cfg.input_files, '.css'); // Output file path var outputPath = path.join(cfg.output_dir, cfg.output_file); // Callba...
javascript
{ "resource": "" }
q40325
train
function(cfg, callback) { // Input dir var inputPath = cfg.input_dir; // Output dir var outputPath = cfg.output_dir; if (inputPath && outputPath) { new gear.Queue({registry: taskRegistry}) // register tasks .log(formatLog('Copying directory:', inputPath)) .copyDir({input: inputPath, output: outp...
javascript
{ "resource": "" }
q40326
train
function(cfg, callback) { // Input dir var inputPath = cfg.input_dir; if (inputPath) { new gear.Queue({registry: taskRegistry}) // register tasks .log(formatLog('Removing directory:', inputPath)) .removeDir({input: inputPath}, callback) .run(callback); } else { callback(); } }
javascript
{ "resource": "" }
q40327
train
function(cfg, callback) { var paths = cfg.input_files || cfg.input_file || cfg.input_dir; if (!Array.isArray(paths)) { paths = [paths]; } watchr.watch({ paths: paths, listener: function(eventName,filePath,fileCurrentStat,filePreviousStat){ console.log(formatLog('File changed:', filePath)); ...
javascript
{ "resource": "" }
q40328
getWindowForElement
train
function getWindowForElement(element) { const e = element.documentElement || element; const doc = e.ownerDocument; return doc.defaultView; }
javascript
{ "resource": "" }
q40329
handler
train
function handler(req, res) { var origin = req.headers.origin if (origin) { res.setHeader('Access-Control-Allow-Origin', origin) } var rating = {} rating.uri = req.body.uri rating.rating = req.body.rating rating.reviewer = req.session.userId debug(rating) if (!rating.reviewer) { res.s...
javascript
{ "resource": "" }
q40330
toc
train
function toc(node, options) { var settings = options || {}; var heading = settings.heading ? toExpression(settings.heading) : null; var result = search(node, heading, settings.maxDepth || 6); var map = result.map; result.map = map.length === 0 ? null : contents(map, settings.tight); /* No give...
javascript
{ "resource": "" }
q40331
Configurator
train
function Configurator(){ // Store reference to the tree/template this.__tree = {}; // Cached instance of the fully rendered tree. this.__cachedResolvedTree = null; // Configuration for the GraphBuilder this.__config = { directives: { file: new (require('./directives/file.js')), http: new (requi...
javascript
{ "resource": "" }
q40332
commit
train
function commit(options) { assert.ok(options.message, 'message is mandatory'); var args = [ 'commit', options.force ? '--amend' : null, options.noVerify ? '-n' : null, options.message ? '-m' : null, options.message ? options.message : null ]; return git(args) .cat...
javascript
{ "resource": "" }
q40333
clone
train
function clone(options) { assert.ok(options.repository, 'repository is mandatory'); var branchOrTag = options.branch || options.tag; var args = [ 'clone', options.repository, options.directory, branchOrTag ? ('-b' + branchOrTag) : null, options.origin ? ('-o' + options.origin)...
javascript
{ "resource": "" }
q40334
add
train
function add(options) { assert.ok(options.files, 'files is mandatory'); return options.files .filter(function(file) { //Git exits OK with empty filenames. //Avoid an unnecessary call to git in these cases by removing the filename return !!file; }) .reduce(f...
javascript
{ "resource": "" }
q40335
push
train
function push(options) { var branchOrTag = options.branch || options.tag; var args = [ 'push', options.remote || 'origin', branchOrTag || 'HEAD', options.force ? '--force' : null ]; return git(args) .then(silent); }
javascript
{ "resource": "" }
q40336
pull
train
function pull(options) { options = options || {}; var branchOrTag = options.branch || options.tag; var args = [ 'pull', options.rebase ? '--rebase' : null, options.remote || 'origin', branchOrTag || git.getCurrentBranch ]; return git(args) .then(silent); }
javascript
{ "resource": "" }
q40337
checkout
train
function checkout(options) { var branchOrTag = options.branch || options.tag; assert.ok(branchOrTag, 'branch or tag is mandatory'); if ((options.create || options.oldCreate) && options.orphan) { throw new Error('create and orphan cannot be specified both together'); } if (options.create && ...
javascript
{ "resource": "" }
q40338
removeLocalBranch
train
function removeLocalBranch(options) { assert.ok(options.branch, 'branch is mandatory'); var args = [ 'branch', options.force ? '-D' : '-d', options.branch ]; return git(args) .then(silent); }
javascript
{ "resource": "" }
q40339
removeRemoteBranch
train
function removeRemoteBranch(options) { assert.ok(options.branch, 'branch is mandatory'); var args = [ 'push', options.remote || 'origin', ':' + options.branch ]; return git(args) .then(silent); }
javascript
{ "resource": "" }
q40340
tag
train
function tag(options) { assert.ok(options.tag, 'tag name is mandatory'); if (options.annotated) { assert.ok(options.message, 'message is mandatory when creating an annotated tag'); } var args = [ 'tag', options.tag, options.annotated ? '-a' : null, options.message ? '-m' :...
javascript
{ "resource": "" }
q40341
removeLocalTags
train
function removeLocalTags(options) { assert.ok(options.tags, 'tags is mandatory'); return options.tags .reduce(function(soFar, tag) { var args = [ 'tag', '-d', tag ]; return soFar .then(gitFn(args)) .catch(pass...
javascript
{ "resource": "" }
q40342
removeTags
train
function removeTags(options) { return Promise.resolve() .then(git.removeLocalTags.bind(null, options)) .then(git.removeRemoteTags.bind(null, options)); }
javascript
{ "resource": "" }
q40343
parseVersion
train
function parseVersion(str) { var match = /git version ([0-9\.]+)/.exec(str); if (match) { return match[1]; } else { throw new Error('Unable to parse version response', str); } }
javascript
{ "resource": "" }
q40344
_render
train
function _render(text, fields, fileInfo, context) { var options = _.extend({}, default_options, this.plugin_options); if (options.disable === true) return text; //l.vvlogd(l.dump(options)); _collateData(fields, options, fileInfo, context); if (!fields.dynamic_list) fields.dynamic_list = _field_dynamic_list; ...
javascript
{ "resource": "" }
q40345
getHostname
train
function getHostname() { var interfaces = networkInterfaces() for(var name in interfaces) { var info = interfaces[name].filter(filterIPv4)[0] if(info) return info.address } }
javascript
{ "resource": "" }
q40346
createEventSource
train
function createEventSource(webhook, options) { var self = this var eventSource = new EventSource(webhook, options) eventSource.addEventListener('open', this.emit.bind(this, 'open', webhook)) eventSource.addEventListener('message', function(message) { self.push(message.data) }) return eventSource }
javascript
{ "resource": "" }
q40347
createServer
train
function createServer(webhook) { var self = this var onError = this.emit.bind(this, 'error') var port = webhook.port || 0 var hostname = webhook.hostname || HOSTNAME var server = http.createServer(function(req, res) { if(req.method === 'GET') { res.end() return self.push(pars...
javascript
{ "resource": "" }
q40348
WebhookPost
train
function WebhookPost(webhook, options) { if(!(this instanceof WebhookPost)) return new WebhookPost(webhook, options) var self = this options = options || {} options.objectMode = true WebhookPost.super_.call(this, options) // Remote ServerSendEvent server if(typeof webhook === 'string') { var ev...
javascript
{ "resource": "" }
q40349
train
function(conf) { Object.defineProperty(this, 'conf', { enumerable: false, configurable: false, writable: false, value: conf || {} } ); if(this.conf.initialize) { this.load(); } }
javascript
{ "resource": "" }
q40350
getKey
train
function getKey(key) { if(this.conf.transform) { if(typeof(this.conf.transform.key) == 'function') { return this.conf.transform.key.call(this, key); } } key = delimited(key, this.conf.delimiter); key = key.replace(/- /, this.conf.delimiter); key = key.replace(/[^a-zA-Z0-9_]/, ''); if(this.conf...
javascript
{ "resource": "" }
q40351
getValue
train
function getValue (key, name, raw) { if(this.conf.transform) { if(typeof(this.conf.transform.value) == 'function') { return this.conf.transform.value.call(this, key, name, raw); } } var value = process.env[raw] || this[name]; if(this.conf.native && typeof(value) == 'string') { value = native.t...
javascript
{ "resource": "" }
q40352
getName
train
function getName(key) { if(key == '_') return key; if(this.conf.transform) { if(typeof(this.conf.transform.name) == 'function') { return this.conf.transform.name.call(this, key); } } if(this.conf.prefix) { key = key.replace(this.conf.prefix + '_', ''); } // guard against silly variables su...
javascript
{ "resource": "" }
q40353
set
train
function set(key, value) { var k = this.getKey(key); var name = this.getName(key); if(this.conf.native && typeof(value) == 'string') { try { value = native.to( value, this.conf.native.delimiter, this.conf.native.json); }catch(e){} } this[name] = process.env[k] = value; }
javascript
{ "resource": "" }
q40354
get
train
function get(key) { var k = this.getKey(key); var name = this.getName(key); var value = this.getValue(k, name, key); return value; }
javascript
{ "resource": "" }
q40355
load
train
function load(match) { match = match || this.conf.match; for(var z in process.env) { if(match instanceof RegExp) { if(match.test(z)) { this.set(z.toLowerCase(), process.env[z]); } }else{ this.set(z.toLowerCase(), process.env[z]); } } // expand out camel case strings using ...
javascript
{ "resource": "" }
q40356
env
train
function env(root, env, escaping) { walk(root, function visit(props) { return (props.value instanceof String) || typeof props.value === 'string'; }, function transform(props) { props.parent[props.name] = replace(props.value, env, escaping); }) }
javascript
{ "resource": "" }
q40357
isTruthy
train
function isTruthy(val) { return val >= 0 && !isNaN(val) && val !== false && val !== undefined && val !== null && val !== ''; }
javascript
{ "resource": "" }
q40358
parseVer
train
function parseVer(idx, set, setting) { var parsed = tryParseInt(idx); if (parsed === false || parsed < 0 || isNaN(parsed)) return false; if (set) return parseVer(argv[parsed + 1], null, true); if (setting) return parsed; return true; }
javascript
{ "resource": "" }
q40359
setVersion
train
function setVersion(type, ver) { const idx = verMap[type]; let cur = verArr[idx]; let next = cur + 1; if (isTruthy(ver)) next = ver; if (isTruthy(ver)) { verArr[idx] = ver; } else { if (type === 'patch') { if (next > maxPatch) { // zero current stepping // up to minor...
javascript
{ "resource": "" }
q40360
repeat
train
function repeat(str, n) { var result = ''; for (var i = 0; i < n; i++) { result += str; } return result; }
javascript
{ "resource": "" }
q40361
bufferSlice
train
function bufferSlice(code, range, format) { format = format || varThrough; return JSON.stringify( code.slice(Math.max(0, code.index - range), code.index) ) .slice(1, -1) + format( JSON.stringify(code.charAt(code.index) || 'EOF') .slice(1, -1) )...
javascript
{ "resource": "" }
q40362
train
function(segment, strict) { if (!_.isString(segment)) { throw new TypeError('segment must be of type string'); } if (!_.isBoolean(strict)) { strict = true; } segment = segment.replace(illegalCharacters, ''); if (strict && osType === "Windows_NT") { segment = segment.replace(illegalNames, ''); wh...
javascript
{ "resource": "" }
q40363
train
function(fsPath, strict) { if (!_.isString(fsPath)) { throw new TypeError('path must be of type string'); } var segments = _.filter(fsPath.substring(fsPath.indexOf(path.sep) + 1).split(path.sep), function(segment) { return segment !== ''; }); for (var i = 0; i < segments.length; i++) { var replaceWit...
javascript
{ "resource": "" }
q40364
train
function(fsPath, strict) { if (!_.isString(fsPath)) { throw new TypeError('path must be of type string'); } return fsPath === module.exports.reformatPath(fsPath, strict); }
javascript
{ "resource": "" }
q40365
train
function(segment, strict) { if (!_.isString(segment)) { throw new TypeError('segment must be of type string'); } return segment === module.exports.reformatSegment(segment, strict); }
javascript
{ "resource": "" }
q40366
update
train
function update() { while (waiting.length && count < concurrency) (function() { var t = waiting.shift() if (inProg[t.task.id]) { inProg[t.task.id].push(t.cb) return } else { inProg[t.task.id] = [t.cb] count++ processor(t.task, function() { var args = arguments if (!inProg[t...
javascript
{ "resource": "" }
q40367
Circle
train
function Circle(x, y, radius) { /** * @member {number} * @default 0 */ this.x = x || 0; /** * @member {number} * @default 0 */ this.y = y || 0; /** * @member {number} * @default 0 */ this.radius = radius || 0; /** * The type of the object,...
javascript
{ "resource": "" }
q40368
train
function (words, options) { var puzzle = [], i, j, len; // initialize the puzzle with blanks for (i = 0; i < options.height; i++) { puzzle.push([]); for (j = 0; j < options.width; j++) { puzzle[i].push(''); } ...
javascript
{ "resource": "" }
q40369
train
function (puzzle, options, word) { // find all of the best locations where this word would fit var locations = findBestLocations(puzzle, options, word); if (locations.length === 0) { return false; } // select a location at random and place the ...
javascript
{ "resource": "" }
q40370
train
function (puzzle, options, word) { var locations = [], height = options.height, width = options.width, wordLength = word.length, maxOverlap = 0; // we'll start looking at overlap = 0 // loop through all of the possible orientations at this position for (var k = 0, len = options.orien...
javascript
{ "resource": "" }
q40371
train
function (word, puzzle, x, y, fnGetSquare) { var overlap = 0; // traverse the squares to determine if the word fits for (var i = 0, len = word.length; i < len; i++) { var next = fnGetSquare(x, y, i), square = puzzle[next.y][next.x]; // if the puzzle sq...
javascript
{ "resource": "" }
q40372
train
function (locations, overlap) { var pruned = []; for (var i = 0, len = locations.length; i < len; i++) { if (locations[i].overlap >= overlap) { pruned.push(locations[i]); } } return pruned; }
javascript
{ "resource": "" }
q40373
train
function (puzzle) { for (var i = 0, height = puzzle.length; i < height; i++) { var row = puzzle[i]; for (var j = 0, width = row.length; j < width; j++) { if (!puzzle[i][j]) { var randomLetter = Math.floor(Math.ra...
javascript
{ "resource": "" }
q40374
train
function (puzzle, words) { var options = { height: puzzle.length, width: puzzle[0].length, orientations: allOrientations, preferOverlap: true }, found = [], notFound = []; for (var i = 0, len ...
javascript
{ "resource": "" }
q40375
train
function (puzzle) { var puzzleString = ''; for (var i = 0, height = puzzle.length; i < height; i++) { var row = puzzle[i]; for (var j = 0, width = row.length; j < width; j++) { puzzleString += (row[j] === '' ? ' ' : row[j]) ...
javascript
{ "resource": "" }
q40376
train
function (connection, attempt) { var clonedAttempt = EJSON.clone(attempt); clonedAttempt.connection = connection; return clonedAttempt; }
javascript
{ "resource": "" }
q40377
train
function (methodInvocation, options) { for (var i = 0; i < loginHandlers.length; ++i) { var handler = loginHandlers[i]; var result = tryLoginMethod( handler.name, function () { return handler.handler.call(methodInvocation, options); } ); if (result) return result; ...
javascript
{ "resource": "" }
q40378
train
function () { var self = this; var user = Meteor.users.findOne(self.userId, { fields: { "services.resume.loginTokens": 1 } }); if (! self.userId || ! user) { throw new Meteor.Error("You are not logged in."); } // Be careful not to generate a new token that has a later // expirati...
javascript
{ "resource": "" }
q40379
train
function () { var self = this; if (! self.userId) { throw new Meteor.Error("You are not logged in."); } var currentToken = Accounts._getLoginToken(self.connection.id); Meteor.users.update(self.userId, { $pull: { "services.resume.loginTokens": { hashedToken: { $ne: currentToken } ...
javascript
{ "resource": "" }
q40380
train
function (serviceData, userId) { _.each(_.keys(serviceData), function (key) { var value = serviceData[key]; if (OAuthEncryption && OAuthEncryption.isSealed(value)) value = OAuthEncryption.seal(OAuthEncryption.open(value), userId); serviceData[key] = value; }); }
javascript
{ "resource": "" }
q40381
train
function (userId, user, fields, modifier) { // make sure it is our record if (user._id !== userId) return false; // user can only modify the 'profile' field. sets to multiple // sub-keys (eg profile.foo and profile.bar) are merged into entry // in the fields list. if (fields.length !== 1 ...
javascript
{ "resource": "" }
q40382
logMessage
train
function logMessage(fig, st, lns) { return lns.reduce((a, b) => a.concat(` ${b}`), [`\n${fig} ${st}`]); }
javascript
{ "resource": "" }
q40383
log
train
function log(first, ...lines) { console.log(logMessage(figures.bullet, first, lines).join('\n')); }
javascript
{ "resource": "" }
q40384
_singlePromise
train
function _singlePromise () { let done, cancel; const x = new Promise ( (resolve, reject ) => { done = resolve cancel = reject }) return { promise : x ...
javascript
{ "resource": "" }
q40385
_manyPromises
train
function _manyPromises ( list ) { let askObject = list.map ( el => _singlePromise() ) let askList = askObject.map ( o => o.promise ) askObject [ 'promises' ] = askList ...
javascript
{ "resource": "" }
q40386
onServerMessage
train
function onServerMessage(message, rinfo) { var packet, respond; alchemy.setStatus('multicast_messages', ++messages); try { packet = bson.deserialize(message); } catch(err) { log.warn('Received corrupt multicast message from ' + rinfo.address); return; } // Ignore packets that come from here if (pa...
javascript
{ "resource": "" }
q40387
tree
train
async function tree(dir, files) { log.trace.configure({ reading: dir }); const { filter } = conf; const ls = await readdir(dir, conf.options); for (let i = 0; i < ls.length; i += 1) { const file = path.join(dir, ls[i]); if (!filter || filter([file]).length) { log.trac...
javascript
{ "resource": "" }
q40388
regenerateLink
train
function regenerateLink(base, link) { const parsedBase = (0, _url.parse)(base); const parsedLink = link.split("/"); let parts = []; let port = ""; if (!link.startsWith("/")) { parts = parsedBase.pathname.split("/"); parts.pop(); } for (const part of parsedLink) { // Current directory: if...
javascript
{ "resource": "" }
q40389
_default
train
function _default(base, link) { // Dynamic stuff: if (typeof link !== "string" || link.match(REGEX_DYNAMIC)) { return base; } // Link is absolute: if (link.match(REGEX_ABSOLUTE)) { try { const parsedBase = parseLink(base); const parsedLink = parseLink(link); // Both `base` and `link` are o...
javascript
{ "resource": "" }
q40390
gzip
train
function gzip(data) { var unit8Array = new Uint8Array(toBuffer(data)); return new Buffer(pako.gzip(unit8Array)); }
javascript
{ "resource": "" }
q40391
dynamic
train
function dynamic (val, toType, ctx) { if (Array.isArray(val)) { return _.map(val, function (v) { return dynamic(v, toType, ctx); }); } return (new Dynamic(val, ctx)).to(toType); }
javascript
{ "resource": "" }
q40392
glob2regexp
train
function glob2regexp(glob, sensitive){ return new RegExp('^' + glob.replace(ESCAPE_REG_EXP, '\\$1').replace(/\*/g, '.*') + '$', sensitive ? '' : 'i') }
javascript
{ "resource": "" }
q40393
getSysInfo
train
function getSysInfo(callback) { if (process.platform === 'windows') return; var reData = getBasicInfo(); exec('iostat ', function(err, output) { if (!!err) { console.error('getSysInfo failed! ' + err.stack); } else { reData.iostat = format(output); } callback(reData); }); }
javascript
{ "resource": "" }
q40394
verify
train
function verify(publicKeys, sig, text) { // Parse signature. validateBase64(sig); const binsig = Buffer.from(sig, 'base64'); // Check signature length. if (binsig.length !== 10 + nacl.sign.signatureLength) { throw new Error('Bad signature length'); } // Check signature algorithm. ...
javascript
{ "resource": "" }
q40395
sign
train
function sign(secretKey, text) { const sec = parseSecretKey(secretKey); const bintext = Buffer.from(text, 'utf8'); const sig = nacl.sign.detached(bintext, sec.key); // Full signature includes algorithm id ('Ed'), key number, // and the signature itself. const fullsig = new Uint8Array(2 + 8 + 64)...
javascript
{ "resource": "" }
q40396
parseSecretKey
train
function parseSecretKey(secretKey) { const k = Buffer.from(secretKey, 'base64'); if (k.length < 2 + 2 + 4 + 16 + 8 + 8 + 64) { throw new Error('Incorrect secret key length'); } // Check signature algorithm. if (k[0] !== 69 /* 'E' */ || k[1] !== 100 /* 'd' */) { throw new Error('Unk...
javascript
{ "resource": "" }
q40397
_normaliseExt
train
function _normaliseExt(ext) { // we don't use '.' in our extension info... but some might leak in here and there ext = (ext||'').trim(); if (ext.length && ext[0]=='.') return ext.substr(1); return ext; }
javascript
{ "resource": "" }
q40398
normalize
train
function normalize(def) { if (~noMergeCmds.indexOf(command)) return stiks.argv.splitArgs(def); return stiks.argv.mergeArgs(def, input); }
javascript
{ "resource": "" }
q40399
createSignedAWSRequest
train
function createSignedAWSRequest(params) { const { body, credentials, endpoint, headers, method = 'GET', path, region } = params const request = new AWS.HttpRequest(endpoint) Object.assign(request, { body, headers: { Host: endpoint.host, 'presigned-expires': false, }, method, path,...
javascript
{ "resource": "" }