_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 channel = new DataChannel(nativeChannel); channels.push(channel); channel.on('close', function() { remove(channel); }); return channel; }; /// Public API api.add = function (label, options) { return add(pc.createDataChannel(label, options)); }; api.addMany = function (newChannels) { for (var label in newChannels) { if (newChannels.hasOwnProperty(label)) { api.add(label, newChannels[label]); } } }; api.get = function (label, options) { return OT.$.find(channels, function(channel) { return channel.equals(label, options); }); }; api.getOrAdd = function (label, options) { var channel = api.get(label, options); if (!channel) { channel = api.add(label, options); } return channel; }; api.destroy = function () { OT.$.forEach(channels, function(channel) { channel.close(); }); channels = []; }; /// Init pc.addEventListener('datachannel', function(event) { add(event.channel); }, false); return api; }
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 }); } else { OT.debug('IceCandidateForwarder: No more ICE candidates.'); } }; }
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.height = '100%'; } else { intrinsicRatio = intrinsicRatio || defaultAspectRatio; intrinsicRatio = rotated ? 1 / intrinsicRatio : intrinsicRatio; var containerRatio = containerWidth / containerHeight; var enforcedVideoWidth, enforcedVideoHeight; if (rotated) { // in case of rotation same code works for both kind of ration enforcedVideoHeight = containerWidth; enforcedVideoWidth = enforcedVideoHeight * intrinsicRatio; cssProps.width = enforcedVideoWidth + 'px'; cssProps.height = enforcedVideoHeight + 'px'; cssProps.top = (enforcedVideoWidth + containerHeight) / 2 + 'px'; } else { if (intrinsicRatio < containerRatio) { // the container is wider than the video -> we will crop the height of the video enforcedVideoWidth = containerWidth; enforcedVideoHeight = enforcedVideoWidth / intrinsicRatio; cssProps.width = enforcedVideoWidth + 'px'; cssProps.height = enforcedVideoHeight + 'px'; cssProps.top = (-enforcedVideoHeight + containerHeight) / 2 + 'px'; } else { enforcedVideoHeight = containerHeight; enforcedVideoWidth = enforcedVideoHeight * intrinsicRatio; cssProps.width = enforcedVideoWidth + 'px'; cssProps.height = enforcedVideoHeight + 'px'; cssProps.left = (-enforcedVideoWidth + containerWidth) / 2 + 'px'; } } } $video.css(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 + '\' cannot transition to \'' + newState + '\'', newState); return false; } return true; }
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(part) + '</a>'; } } return crumb.join(' / '); }
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 { className: 'icon-default', fileName: icons.default }; } // try by mime type if (icons[mimetype]) { return { className: 'icon-' + mimetype.replace('/', '-'), fileName: icons[mimetype] }; } var suffix = mimetype.split('+')[1]; if (suffix && icons['+' + suffix]) { return { className: 'icon-' + suffix, fileName: icons['+' + suffix] }; } var type = mimetype.split('/')[0]; // try by type only if (icons[type]) { return { className: 'icon-' + type, fileName: icons[type] }; } return { className: 'icon-default', fileName: icons.default }; }
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 && file.stat.isDirectory()); var icon = isDir ? { className: 'icon-directory', fileName: icons.folder } : iconLookup(file.name); var iconName = icon.fileName; selector = '#files .' + icon.className + ' .name'; if (!rules[iconName]) { rules[iconName] = 'background-image: url(data:image/png;base64,' + load(iconName) + ');' selectors[iconName] = []; list.push(iconName); } if (selectors[iconName].indexOf(selector) === -1) { selectors[iconName].push(selector); } } for (i = 0; i < list.length; i++) { iconName = list[i]; style += selectors[iconName].join(',\n') + ' {\n ' + rules[iconName] + '\n}\n'; } return style; }
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>') : '') + files.map(function(file){ var isDir = '..' == file.name || (file.stat && file.stat.isDirectory()) , classes = [] , path = dir.split('/').map(function (c) { return encodeURIComponent(c); }); if (useIcons) { classes.push('icon'); if (isDir) { classes.push('icon-directory'); } else { var ext = extname(file.name); var icon = iconLookup(file.name); classes.push('icon'); classes.push('icon-' + ext.substring(1)); if (classes.indexOf(icon.className) === -1) { classes.push(icon.className); } } } path.push(encodeURIComponent(file.name)); var date = file.stat && file.name !== '..' ? file.stat.mtime.toDateString() + ' ' + file.stat.mtime.toLocaleTimeString() : ''; var size = file.stat && !isDir ? file.stat.size : ''; return '<li><a href="' + escapeHtml(normalizeSlashes(normalize(req.prefixPath + path.join('/')))) + '" class="' + escapeHtml(classes.join(' ')) + '"' + ' title="' + escapeHtml(file.name) + '">' + '<span class="name">' + escapeHtml(file.name) + '</span>' + '<span class="size">' + escapeHtml(size) + '</span>' + '<span class="date">' + escapeHtml(date) + '</span>' + '</a></li>'; }).join('\n') + '</ul>'; }
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 done(null, stat || null); }); }); }); batch.end(cb); }
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(); } } catch(error) { console.error(error); } } /** * Set a defined key with the given value * @param {string} key The name of the value * @param {mixed} data The data to store, can be any datatype * @param {int} [expiresAt] When should this value expire * @return {void} */ 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)); return true; } catch(error) { console.error(error); return false; } } /** * Get the value stored under the given key, or the whole store * @param {string} [key] Index defined in @set * @return {mixed} Stored value */ function get(key) { try { if (key !== undefined) { var result = encodeObjectString(STORE.getItem(storeName + key)); return result !== null ? result : false; } else { var resultAll = {}; Object.keys(STORE).map(function(key) { if (key.indexOf(storeName) === 0 && key.indexOf(EXPIRE_KEY) === -1) { var varKey = key.replace(storeName, ''); resultAll[varKey] = get(varKey); } }); return resultAll; } } catch(error) { console.error(error) return false; } } /** * Check if the given key exists in the store * @param {string} key index of the value to test * @return {boolean} Key defined or not */ function isset(key) { return STORE.getItem(storeName + key) !== null ? true : false; } /** * Flush all values, that are stored in the store instance * @return {void} */ function flush() { util.flush(storeName); } /** * Remove an item, by the given key and its expire if set * @param {string} key Index of the value * @return {void} */ function remove(key) { util.remove(storeName + key); } /** * flush expired values defined in this store * @return {void} */ function flushExpired() { util.flushExpired(storeName); } /** * generate a store name * @param {string} storeName The name of the store instance * @return {string} The generated name * @throws {TypeError} */ 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'); } var chargedStoreName = storeName = ROOT + storeName + '-'; return chargedStoreName; } /** * decode a value if its type is a object * @private * @param {mixed} data Value to decode * @return {mixed} The decoded value */ function decodeObjectString(data) { if (typeof data === 'object') { return JSON.stringify(data); } return data; } /** * encode a value if the value is a object * @param {mixed} data The value to encode * @return {mixed} The encoded value */ function encodeObjectString(data) { if (typeof data === 'string') { try { return JSON.parse(data); } catch(e) { return data; } } } __construct(name); // define public interface return { set : set, get : get, flush : flush, remove : remove, isset : isset } }
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)); return true; } catch(error) { console.error(error); return false; } }
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 = {}; Object.keys(STORE).map(function(key) { if (key.indexOf(storeName) === 0 && key.indexOf(EXPIRE_KEY) === -1) { var varKey = key.replace(storeName, ''); resultAll[varKey] = get(varKey); } }); return resultAll; } } catch(error) { console.error(error) return false; } }
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'); } var chargedStoreName = storeName = ROOT + storeName + '-'; return chargedStoreName; }
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)) { throw new Error('Parent does not have property "' + property + '"!'); } return _.isFunction(parent[property]) ? parent[property].apply(context, params || []) : parent[property]; }
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 // 'appear' event was not fired correctly in the css-translate-transition // situation, so 'i-lazy-src' must be checked and lazyload must be // fired manually. const preProcessed = elementScope.querySelectorAll('[i-lazy-src]') if (notPreProcessed.length > 0 || preProcessed.length > 0) { fire() } }
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 cfg.input_files.forEach(function(f,i,array) { f = cfg.input_dir + "/" + f; fileMask = new RegExp(f.replace(/\*/g, '(.*)')); if (~f.indexOf('*')) { filePath = f.substr(0, f.lastIndexOf('/')+1); dirContent = fs.readdirSync(filePath); dirContent.forEach(function(ff) { var fp = filePath+ff; if (fileMask.test(fp)) { files.push(fp); } }); } else { files.push(f); } }); // Set the input files array after parsing the wildcards cfg.input_files = files.concat(); // check type of files (to reject unsupported scripts/styles) success = cfg.input_files.every(function(file) { if (validExt && validExt.indexOf(path.extname(file)) < 0) { callback(new Error('Cannot compile. Invalid type of file: ' + file)); return false; } else { return true; } }); }); return success; }
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); // Callback for Less compilation completed var onLessCompileComplete = function(result) { lessCompiledCode = result; }; // Callback for style concatenation task var concatWithCssCompiledCode = function(result) { return result + '\n' + lessCompiledCode; }; // Callback for lint task var onCSSLinted = function(blob) { if (blob.csslint && blob.csslint.length && blob.csslint[0].line !== undefined) { console.log('\nCSSLint reports issues in: '.red + blob.name); blob.csslint.forEach(function(i){ if (i) { console.log(' Line ' + i.line + ', Col ' + i.col + ': ' + i.message); } }); } }; // Build Styles if (cssFiles.length+lessFiles.length > 0) { new gear.Queue({registry: taskRegistry}) // register tasks .log(formatLog('Building styles:', cssFiles.concat(lessFiles))) .tasks({ readless: {task: ['read', lessFiles]}, combineless: {requires: 'readless', task: 'safeconcat'}, lesstocss: {requires: 'combineless', task: ['lesscompile', {callback: onLessCompileComplete}]}, readcss: {requires: 'lesstocss', task: ['read', cssFiles]}, lint: {requires: 'readcss', task: cfg.lint ? ['csslint', {config: cfg.lint_config, callback: onCSSLinted}] : 'noop'}, combinecss: {requires: 'lint', task: 'safeconcat'}, combineall: {requires: 'combinecss', task: ['concat', {callback: concatWithCssCompiledCode}]}, minify: {requires: 'combineall', task: cfg.minify ? ['stylesminify', {minify: cfg.minify, yuicompress: cfg.minify_config.yuicompress}] : 'noop'}, write: {requires: 'minify', task: ['write', outputPath]} }) .log(formatLog('Saved styles to: ', outputPath)) .run(callback); } else { callback(); } }
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: outputPath}, callback) .log(formatLog('Copied directory to: ', outputPath)) .run(callback); } else { callback(); } }
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)); var singleFileCfg, outputDir, logTaskError = function(msg) { console.log('\n'+msg.red); }; // Detect what build configuration the file belongs to if (config.scripts.indexOf(cfg) !== -1) { // rebuild scripts buildScripts(cfg, function(err){ if (err) { logTaskError('Scripts not saved!'); } }); } else if (config.styles.indexOf(cfg) !== -1) { // rebuild styles buildStyles(cfg, function(err){ if (err) { logTaskError('Styles not saved!'); } }); } else if (config.copy_files.indexOf(cfg) !== -1) { // copy files singleFileCfg = {input_files: [filePath], output_dir: cfg.output_dir}; copyFiles(singleFileCfg, function(err){ if (err) { logTaskError('File not copied!'); } }); } else if (config.copy_file.indexOf(cfg) !== -1) { // copy/rename single file singleFileCfg = {input_file: filePath, output_file: cfg.output_file}; copyFile(singleFileCfg, function(err){ if (err) { logTaskError('File not copied!'); } }); } else if (config.copy_dir.indexOf(cfg) !== -1) { // copy single directory outputDir = path.dirname(filePath).replace(cfg.input_dir, cfg.output_dir); singleFileCfg = {input_files: [filePath], output_dir: outputDir}; copyFiles(singleFileCfg, function(err){ if (err) { logTaskError('Directory not copied!'); } }); } }, next: function(err,watcher){ if (err) { callback(err); } else { callback(); } } }); }
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.send('must be authenticated') return } config = res.locals.config conn = res.locals.sequelize if (isNaN(rating.rating) || !rating.uri) { res.status(200) res.header('Content-Type', 'text/html') res.render('pages/media/rate_input', { ui : config.ui }) return } else { qpm_media.addRating(rating, config, conn).then(function(ret) { res.status(200) res.header('Content-Type', 'text/html') res.render('pages/media/rate_success', { ui : config.ui }) debug(ret) return }).catch(function(err){ res.status(200) res.header('Content-Type', 'text/html') res.render('pages/media/rate_error', { ui : config.ui }) debug(ret) return }) } }
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 given heading */ if (!heading) { result.index = null; result.endIndex = null; } return result; }
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 (require('./directives/http.js')), require: new (require('./directives/require.js')) }, resolvers: { absolute: { order: 1, resolve: Path.resolve(__dirname, './resolvers/absolute.js') }, relative: { order: 2, resolve: Path.resolve(__dirname, './resolvers/relative.js') }, environment: { order: 3, resolve: Path.resolve(__dirname, './resolvers/environment.js') } } }; }
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) .catch(passWarning) .then(silent); }
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) : null, options.recursive ? '--recursive' : null, options.bare ? '--bare' : null, options.depth ? '--depth' : null, options.depth ? '' + options.depth : null ]; return git(args) .then(silent); }
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(function(soFar, file) { var args = ['add', file]; return soFar .then(gitFn(args)) .then(silent); }, Promise.resolve()); }
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 && options.oldCreate) { throw new Error('create and oldCreate cannot be specified both together'); } var args = [ 'checkout', options.create ? '-B' : options.oldCreate ? '-b' : null, options.orphan ? '--orphan' : null, branchOrTag, options.force ? '-f' : null ]; return git(args) .then(silent); }
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' : null, options.message ? options.message : null ]; return git(args) .then(silent); }
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(passWarning) .then(silent); }, Promise.resolve()); }
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; var dl = fields.dynamic_list; /*//debug dynlists... fields.dynamic_list = function() { l.vlog("Dynlist for: " + fileInfo.relPath) dl.call(this) } */ return fields.content; }
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(parse(req.url).query) } req.pipe(concat(function(body) { res.end() self.push(body.toString()) })) }) .listen(port, hostname, function() { var address = this.address() if(hostname === HOSTNAME) hostname = getHostname() if(!hostname) { self.emit('error', new Error("There's no public available interfaces")) return this.close() } self.emit('open', 'http://'+hostname+':'+address.port) }) .on('error' , onError) .on('clientError', onError) return server }
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 eventSource = createEventSource.call(this, webhook, options) eventSource.addEventListener('error', function(error) { if(this.readyState !== EventSource.CLOSED) return self.emit('error', error) self.push(null) eventSource = null }) } // Ad-hoc local web server else { if(webhook == null) webhook = {} else if(typeof webhook === 'number') webhook = {port: webhook} var server = createServer.call(this, webhook) .on('close', function() { self.push(null) server = null }) } // // Public API // /** * Close the connection and stop emitting more data updates */ this.close = function() { var connection = eventSource || server if(!connection) return connection.close() } }
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.prefix) { return this.conf.prefix + this.conf.delimiter + key.toLowerCase() } return key.toLowerCase(); }
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.to( value, this.conf.native.delimiter, this.conf.native.json); } return value; }
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 such as npm_config_cache____foo key = key.replace( new RegExp(this.conf.delimiter + '+', 'g'), this.conf.delimiter); return camelcase(key, this.conf.delimiter) }
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 another delimiter if(this.conf.expand && this.conf.expand.delimiter) { var o = {}, k, v, val; for(k in this) { val = this[k]; v = delimited(k, this.conf.expand.delimiter); if(typeof this.conf.expand.transform === 'function') { v = this.conf.expand.transform(v); } this.set(v, val); delete this[k]; } } }
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. verArr[idx] = 0; return setVersion('minor'); } else { verArr[idx] = next; } } else if (type === 'minor') { if (next > maxMinor) { // zero current stepping // up to major. verArr[idx] = 0; return setVersion('major'); } else { verArr[idx] = next; } } else { verArr[idx] = next; } } }
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) ) + JSON.stringify( code.slice( code.index + 1, Math.min(code.length, code.index + 1 + range) ) ) .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, ''); while (illegalTrailingCharacters.test(segment)) { segment = segment.replace(illegalTrailingCharacters, ''); } } return segment; }
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 replaceWith = module.exports.reformatSegment(segments[i], strict); var find = util.format('%s%s', replaceWith === '' ? path.sep : '', segments[i]); fsPath = fsPath.replace(find, replaceWith); } return fsPath; }
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.task.id]) return // probably callback called twice count-- inProg[t.task.id].forEach(function(cb) { cb.apply(null, args) }) delete inProg[t.task.id] setImmediate(update) }) } })() }
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, mainly used to avoid `instanceof` checks * * @member {number} */ this.type = CONST.SHAPES.CIRC; }
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(''); } } // add each word into the puzzle one at a time for (i = 0, len = words.length; i < len; i++) { if (!placeWordInPuzzle(puzzle, options, words[i])) { // if a word didn't fit in the puzzle, give up return null; } } // return the puzzle return puzzle; }
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 word there var sel = locations[Math.floor(Math.random() * locations.length)]; placeWord(puzzle, word, sel.x, sel.y, orientations[sel.orientation]); return true; }
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.orientations.length; k < len; k++) { var orientation = options.orientations[k], check = checkOrientations[orientation], next = orientations[orientation], skipTo = skipOrientations[orientation], x = 0, y = 0; // loop through every position on the board while (y < height) { // see if this orientation is even possible at this location if (check(x, y, height, width, wordLength)) { // determine if the word fits at the current position var overlap = calcOverlap(word, puzzle, x, y, next); // if the overlap was bigger than previous overlaps that we've seen if (overlap >= maxOverlap || (!options.preferOverlap && overlap > -1)) { maxOverlap = overlap; locations.push({ x: x, y: y, orientation: orientation, overlap: overlap }); } x++; if (x >= width) { x = 0; y++; } } else { // if current cell is invalid, then skip to the next cell where // this orientation is possible. this greatly reduces the number // of checks that we have to do overall var nextPossible = skipTo(x, y, wordLength); x = nextPossible.x; y = nextPossible.y; } } } // finally prune down all of the possible locations we found by // only using the ones with the maximum overlap that we calculated return options.preferOverlap ? pruneLocations(locations, maxOverlap) : locations; }
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 square already contains the letter we // are looking for, then count it as an overlap square if (square === word[i]) { overlap++; } else if (square !== '') { return -1; } } // if the entire word is overlapping, skip it to ensure words aren't // hidden in other words return overlap; }
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.random() * letters.length); puzzle[i][j] = letters[randomLetter]; } } } }
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 = words.length; i < len; i++) { var word = words[i], locations = findBestLocations(puzzle, options, word); if (locations.length > 0 && locations[0].overlap === word.length) { if (locations.length > 0 && locations[0].overlap === word.length) { locations[0].word = word; found.push(locations[0]); } else { notFound.push(word); } } } return { found: found, notFound: notFound }; }
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]) + ' '; } puzzleString += '\n'; } console.log(puzzleString); return puzzleString; }
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; else if (result !== undefined) throw new Meteor.Error(400, "A login handler should return a result or undefined"); } return { type: null, error: new Meteor.Error(400, "Unrecognized options for login request") }; }
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 // expiration than the curren token. Otherwise, a bad guy with a // stolen token could use this method to stop his stolen token from // ever expiring. var currentHashedToken = Accounts._getLoginToken(self.connection.id); var currentStampedToken = _.find( user.services.resume.loginTokens, function (stampedToken) { return stampedToken.hashedToken === currentHashedToken; } ); if (! currentStampedToken) { // safety belt: this should never happen throw new Meteor.Error("Invalid login token"); } var newStampedToken = Accounts._generateStampedLoginToken(); newStampedToken.when = currentStampedToken.when; Accounts._insertLoginToken(self.userId, newStampedToken); return loginUser(self, self.userId, newStampedToken); }
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 || fields[0] !== 'profile') return false; return true; }
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 , done : done , cancel : cancel , onComplete : _after(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 askObject [ 'onComplete' ] = _after ( Promise.all (askList) ) return askObject }
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 (packet.origin == alchemy.discovery_id) { return; } packet.remote = rinfo; if (packet.respond) { respond = function respond(data) { var response_packet = { type : 'response', response_to : packet.id, data : data }; submit(response_packet); }; } // Emit it as a multicast event alchemy.emit('multicast', packet, respond, null); if (packet.response_to) { if (typeof callbacks[packet.response_to] === 'function') { callbacks[packet.response_to](packet.data, packet); } } else { // Emit it for multicast listeners only mevents.emit(packet.type, packet.data, packet, respond, null); } }
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.trace.configure({ passed_fitler: file }); files.push(file); // eslint-disable-next-line no-await-in-loop if ((await stat(file)).isDirectory()) { log.trace.configure({ recursing: file }); // eslint-disable-next-line no-await-in-loop await tree(file, files); } } } return files; }
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 (part === ".") { continue; } // Parent directory: if (part === "..") { // Accessing non-existing parent directories: if (!parts.pop() || parts.length === 0) { return null; } } else { parts.push(part); } } if (parsedBase.port) { port = ":" + parsedBase.port; } // eslint-disable-next-line max-len return `${parsedBase.protocol}//${parsedBase.hostname}${port}${parts.join("/")}`; }
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 on different domains: if (parsedBase.domain !== parsedLink.domain) { return false; } // Absolute path from same domain: if (parsedLink.path) { return (0, _url.resolve)(base, parsedLink.path); } // Same domains without path: return (0, _url.parse)(base).href; } catch (err) { return false; } } // Relative stuff: return regenerateLink(base, link); }
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. if (binsig[0] !== 69 /* 'E' */ || binsig[1] !== 100 /* 'd' */) { throw new Error('Unknown signature algorithm'); } // Find the appropriate key for signature based on // algorithm and public key fingerprint embedded into signature. let key = null; for (let i = 0; i < publicKeys.length; i++) { const binkey = Buffer.from(publicKeys[i], 'base64'); // Check public key format. if (binkey.length !== 10 + nacl.sign.publicKeyLength) { throw new Error('Bad public key length'); } // If algorithm (2 bytes) and key number (8) bytes match, // we found the needed key. if (nacl.verify(binkey.subarray(0, 10), binsig.subarray(0, 10))) { key = binkey; break; } } if (!key) { throw new Error('Invalid signature: no matching key found'); } const bintext = Buffer.from(text, 'utf8'); if (!nacl.sign.detached.verify(bintext, binsig.subarray(10), key.subarray(10))) { throw new Error('Invalid signature'); } }
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); fullsig[0] = 69 // 'E' fullsig[1] = 100; // 'd' fullsig.set(sec.num, 2) // key number fullsig.set(sig, 10); // signature return Buffer.from(fullsig.buffer).toString('base64'); }
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('Unknown signature algorithm'); } // Check KDF algorithm if (k[2] !== 66 /* 'B' */ || k[3] !== 75 /* 'K' */) { throw new Error('Unsupported KDF algorithm'); } // Extract fields. const rounds = k.slice(4, 8).readUInt32BE(0); if (rounds !== 0) { throw new Error('Rounds must be 0; unlock key before passing to sign.') } const checksum = k.slice(24, 32); const num = Buffer.from(k.slice(32, 40)); const key = Buffer.from(k.slice(40, 104)); // Verify key checksum. if (!nacl.verify(checksum, nacl.hash(key).subarray(0, 8))) { throw new Error('Key checksum verification failure'); } return { num, key }; }
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, region, }) const signed = signAWSRequest({ credentials, request }) return mergeAllowedClientHeaders({ headers, request: signed }) }
javascript
{ "resource": "" }