_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q38000
compileSingleFile
train
function compileSingleFile (filePath, isDebug, options) { var outputPath = "./" + path.dirname(filePath).replace(/(^|\/)assets\/js/, "$1public/js"); var uglifyOptions = {}; gulpUtil.log(gulpUtil.colors.blue("Uglify"), pathHelper.makeRelative(filePath), " -> ", pathHelper.makeRelative(outputPath) + "/" + path.basename(filePath)); if (options.lint) { jsHintHelper.lintFile(filePath); } if (isDebug) { uglifyOptions.compress = false; uglifyOptions.preserveComments = "all"; } return gulp.src(filePath) .pipe(plumber()) .pipe(uglify(uglifyOptions)) .pipe(gulp.dest(outputPath)); }
javascript
{ "resource": "" }
q38001
validateParameters
train
function validateParameters() { grunt.verbose.writeln( 'BowerMap::validateParameters' ); //flag used to determine if validation passes var check = true; //lib path must be set //TODO: get default bowerpath from .bowerrc bowerPath = bowerPath || "bower_components"; if ( typeof bowerPath !== 'string' ) { grunt.log.error( 'Bower path must be a string.' ); check = false; } //lib path must be set if ( !destPath || typeof destPath !== 'string' ) { grunt.log.error( 'Default destination path must be configured.' ); check = false; } //shim isn't required, but must be a key value object shim = shim || {}; if ( typeof shim !== "object" ) { grunt.log.error( 'shim must be an object.' ); check = false; } //map isn't required, but must be a key value object map = map || {}; if ( typeof map !== "object" ) { grunt.log.error( 'map must be an object.' ); check = false; } //ignore isn't required, but must be an array ignore = ignore || []; if ( !Array.isArray( ignore ) ) { grunt.log.error( 'ignore must be an array of strings.' ); check = false; } //maintainCommonPaths isn't required, but must be boolean maintainCommonPaths = maintainCommonPaths || false; if ( typeof maintainCommonPaths !== "boolean" ) { grunt.log.error( 'maintainCommonPaths must be a boolean value.' ); check = false; } //useNamespace isn't required, but must be undefined or boolean if ( useNamespace !== undefined && typeof useNamespace !== "boolean" ) { grunt.log.error( 'useNamespace must be boolean or undefined.' ); check = false; } //extensions isn't required, but must be an array extensions = extensions || undefined; if ( extensions !== undefined && !Array.isArray( extensions ) ) { grunt.log.error( 'extensions must be an array or undefined.' ); check = false; } return check; }
javascript
{ "resource": "" }
q38002
handleListResults
train
function handleListResults( results ) { grunt.verbose.writeln( 'BowerMap::handleListResults' ); for ( var k in results ) { if ( results.hasOwnProperty( k ) ) { grunt.verbose.writeln( '------------------------------------' ); grunt.verbose.writeln( ' ' + k + ' - ' + results[k] ); if ( ignore.indexOf( k ) >= 0 ){ grunt.verbose.writeln( ' ' + k + ' - IGNORED' ); } else{ copyComponentFiles( k, results[k] ); } } } done(); }
javascript
{ "resource": "" }
q38003
copyComponentFiles
train
function copyComponentFiles( name, files ) { grunt.verbose.writeln( 'BowerMap::copyComponentFiles - ' + name ); //get map of files to copy var componentMap = getComponentMapping( name, files ); //copy files for ( var k in componentMap ) { if ( componentMap.hasOwnProperty( k ) ) { //console.log( path.fix( k ) ); //console.log( path.fix( componentMap[ k ] ) ); //grunt.file.copy( path.fix( k ), path.fix( componentMap[ k ] ) ); var replacements = replace ? replace[ name ] || false : false; if ( componentMap[ k ] !== false){ copyReplace( path.fix( k ), path.fix( componentMap[ k ] ), replacements ); } } } }
javascript
{ "resource": "" }
q38004
getComponentMapping
train
function getComponentMapping( name, files ) { grunt.verbose.writeln( 'BowerMap::getComponentMapping - ' + name ); //first get list of all files var fileList = []; if ( shim[ name ] !== undefined ) { grunt.verbose.writeln( ' using shim value' ); //use shim value fileList = fileList.concat( shim[ name ] ); } else { grunt.verbose.writeln( ' using result value - ' + files ); //make sure files is an array if (typeof files === 'string'){ files = [files]; } //we just need the path relative to the module directory files.forEach( function( file ){ file = path.fix( file ); fileList.push( file.replace( path.fix( path.join( bowerPath, name ) ) , "" ) ); }); } //expand list var expandedList = []; fileList.forEach( function( file ){ grunt.verbose.writeln( ' globbing - ' + path.join( name, file ) ); glob.sync( path.join( name, file ), { cwd: bowerPath, dot: true } ).forEach( function( filename ) { var src = path.fix( path.join( bowerPath, filename ) ); grunt.verbose.writeln( 'src ' + src ); expandedList.push( src ); }); }); //filter filetypes expandedList = expandedList.filter( function( file ){ var ext = path.extname( file ).substr(1); if ( extensions ){ return extensions.indexOf( ext ) >= 0; } else{ return true; } }); //get common path for building destination var commonPath = maintainCommonPaths ? "" : getCommonPathBase( expandedList ); grunt.verbose.writeln( ' common path: ' + commonPath ); //build default mapping var componentMap = {}; grunt.verbose.writeln( ' mapping files:' ); expandedList.forEach( function( file ){ if ( expandedMap[ file ] !== undefined ) { //use user configured mapping if set componentMap[ file ] = expandedMap[ file ]; grunt.log.writeln( ' * '+file+' -> '+ expandedMap[ file ] ); } else { var newFilename = commonPath === "" ? file : file.replace( commonPath, "" ); //console.log(' newfileName:',newFilename); var dest = path.join( destPath, newFilename ); //console.log(' dest:',dest); if ( useNamespace === true || ( useNamespace === undefined && expandedList.length > 1 ) ){ dest = dest.replace( destPath, path.join( destPath, name ) ); } componentMap[ file ] = dest; grunt.log.writeln( ' '+file+' -> '+ dest ); } }); return componentMap; }
javascript
{ "resource": "" }
q38005
getCommonPathBase
train
function getCommonPathBase( paths ) { var list = []; var minLength = 999999999; var commonPath = ""; //break up paths into parts paths.forEach( function( file ) { //normalize path seperators file = file.replace( pathSepRegExp, path.sep ); //get resolved path parts for file directory if ( file.charAt(0) === path.sep ){ file = file.substr(1); } //console.log(" "+file); //console.log(" "+path.dirname( file )); var dirname = path.dirname( file ); var parts = dirname === "." ? [] : dirname.split( path.sep ); list.push( parts ); //save minimum path length for next step minLength = Math.min( minLength, parts.length ); } ); var listLength = list.length; grunt.verbose.writeln( JSON.stringify( list, undefined, " ") ); //check for common parts if ( listLength > 1 ) { var common = true; var index = -1; //iterate parts up to minLength for ( var i = 0; i < minLength; i++ ) { for ( var j = 1; j < listLength; j++ ) { if ( list[ j ][ i ] !== list[ j - 1 ][ i ] ) { common = false; break; } } if ( !common ) { index = i; break; } } //catch case where all paths are common if ( index < 0 ){ index = minLength; } //build new paths array //for ( var n=0; n<listLength; n++ ) { // newPaths.push( path.join( list[n].slice( index ) ) ); //} commonPath = list[0].slice( 0, index ).join( path.sep ); } else if ( listLength === 1 ) { commonPath = list[0].join( path.sep ); } return commonPath; }
javascript
{ "resource": "" }
q38006
urlWeight
train
function urlWeight(config) { if (isUndefined(config) || config.url == undefined) { // eslint-disable-line eqeqeq return 0; } if (config.url instanceof RegExp) { return 1 + config.url.toString().length; } if (isFunction(config.url)) { return 1; } return 100 + config.url.length; }
javascript
{ "resource": "" }
q38007
defineProperty
train
function defineProperty(element, propertyName, descriptor, scope) { assert(element, 'Parameter \'element\' must be defined'); assertType(descriptor, 'object', false, 'Parameter \'descriptor\' must be an object literal'); assertType(descriptor.configurable, 'boolean', true, 'Optional configurable key in descriptor must be a boolean'); assertType(descriptor.enumerable, 'boolean', true, 'Optional enumerable key in descriptor must be a boolean'); assertType(descriptor.writable, 'boolean', true, 'Optional writable key in descriptor must be a boolean'); assertType(descriptor.unique, 'boolean', true, 'Optional unique key in descriptor must be a boolean'); assertType(descriptor.dirtyType, 'number', true, 'Optional dirty type must be of DirtyType enum (number)'); assertType(descriptor.eventType, 'string', true, 'Optional event type must be a string'); assertType(descriptor.attributed, 'boolean', true, 'Optional attributed must be a boolean'); assertType(descriptor.onChange, 'function', true, 'Optional change handler must be a function'); assertType(scope, 'string', true, 'Optional parameter \'scope\' must be a string'); let dirtyType = descriptor.dirtyType; let defaultValue = descriptor.defaultValue; let attributed = descriptor.attributed; let attributeName = Directive.DATA+propertyName.replace(/([A-Z])/g, ($1) => ('-'+$1.toLowerCase())); let eventType = descriptor.eventType; let unique = descriptor.unique; assert(!attributeName || !hasOwnValue(Directive, attributeName), 'Attribute \'' + attributeName + '\' is reserved'); if (unique === undefined) unique = true; if (scope === undefined) { scope = element; } else { assert(element.hasOwnProperty(scope), 'The specified Element instance does not have a property called \'' + scope + '\''); scope = element[scope]; } if (defaultValue !== undefined) { scope.__private__ = scope.__private__ || {}; Object.defineProperty(scope.__private__, propertyName, { value: defaultValue, writable: true }); } let newDescriptor = {}; if (descriptor.configurable !== undefined) newDescriptor.configurable = descriptor.configurable; if (descriptor.enumerable !== undefined) newDescriptor.enumerable = descriptor.enumerable; if (descriptor.value !== undefined) newDescriptor.value = descriptor.value; if (descriptor.writable !== undefined) newDescriptor.writable = descriptor.writable; if (descriptor.get) { newDescriptor.get = () => ((typeof descriptor.get === 'function') ? descriptor.get(scope.__private__[propertyName]) : scope.__private__[propertyName]); } if (descriptor.set) { newDescriptor.set = (val) => { let oldVal = scope.__private__[propertyName]; if (typeof descriptor.set === 'function') val = descriptor.set(val); if (unique && (oldVal === val)) return; if (oldVal === undefined) { scope.__private__ = scope.__private__ || {}; Object.defineProperty(scope.__private__, propertyName, { value: val, writable: true }); } else { scope.__private__[propertyName] = val; } if (descriptor.onChange !== undefined) descriptor.onChange(oldVal, val); if (attributed === true) dom.setAttribute(element, attributeName, val); if ((dirtyType !== undefined) && (element.setDirty)) element.setDirty(dirtyType); if (eventType !== undefined) { let event = new CustomEvent(eventType, { detail: { property: propertyName, oldValue: oldVal, newValue: val } }); if (element.dispatchEvent) element.dispatchEvent(event); } }; } Object.defineProperty(scope, propertyName, newDescriptor); if (defaultValue !== undefined && attributed === true) { dom.setAttribute(element, attributeName, defaultValue); } if (defaultValue !== undefined && dirtyType !== undefined && element.nodeState >= NodeState.UPDATED && element.setDirty) { element.setDirty(dirtyType); } }
javascript
{ "resource": "" }
q38008
train
function(file, opt) { //Check the file if(typeof file !== 'string'){ throw new Error('Missing file argument'); return null; } //Check the options if(typeof opt === 'undefined'){ var opt = {}; } //Save the file name this._file = file; //Check the encoding option this._encoding = (typeof opt.encoding === 'undefined') ? 'utf8' : opt.encoding.toString(); //Check the chunk option this._chunk = (typeof opt.chunk === 'undefined') ? 10240 : opt.chunk; //Check the line break option this._endl = (typeof opt.endl === 'undefined') ? 0x0a : opt.endl; //Check the emptylines option this._emptyLines = (typeof opt.emptyLines === 'undefined') ? true : opt.emptyLines; //File object this._fd = null; //Actual position this._position = (typeof opt.start === 'undefined') ? 0 : opt.start; //Line count this._count = 0; //Events this._events = {}; //Return this return this; }
javascript
{ "resource": "" }
q38009
setup
train
function setup(done) { crontab.load(function(err, ct) { if (err) return done(err); clean(ct); load(ct); ct.save(done); }); }
javascript
{ "resource": "" }
q38010
readCronFile
train
function readCronFile(cronfile) { var substitutes = { project: { baseDir: process.cwd() }, pkg: pkg } var content = _.template(grunt.file.read(cronfile), substitutes); return JSON.parse(content).jobs; }
javascript
{ "resource": "" }
q38011
resolveLink
train
function resolveLink(srcUrl, targetUrl) { // Parse the src URL var srcUrlObj = url.parse(srcUrl); // If there isn't a protocol // DEV: `node@0.8` has this as `undefined`, `node@0.10` has this as `null` if (!srcUrlObj.protocol) { // With no protocol, we have everything in pathname. Add on `//` and force treatment of `host` var tmpSrcUrl = '//' + srcUrl; var tmpSrcUrlObj = url.parse(tmpSrcUrl, null, true); // If this new hostname has a TLD, then keep it as the srcUrlObj // DEV: We are trading accuracy for size (technically not all dots mean a tld // If we want to be accurate, use https://github.com/ramitos/tld.js/blob/305a285fd8f5d618417178521d8729855baadb37/src/tld.js if (tmpSrcUrlObj.hostname && tldRegexp.test(tmpSrcUrlObj.hostname)) { srcUrl = tmpSrcUrl; srcUrlObj = tmpSrcUrlObj; } } // Fallback pathname srcUrlObj.pathname = srcUrlObj.pathname || '/'; // If we still have no protocol // DEV: `node@0.8` has this as `undefined`, `node@0.10` has this as `null` if (!srcUrlObj.protocol) { // Parse our targetUrl var targetUrlObj = url.parse(targetUrl); // If there is a hostname // DEV: `node@0.8` has this as `undefined`, `node@0.10` has this as `null` if (srcUrlObj.hostname) { // If the hostname is the same as our original, add on a protocol if (srcUrlObj.hostname === targetUrlObj.hostname) { srcUrlObj.protocol = targetUrlObj.protocol; // Otherwise, default to HTTP } else { srcUrlObj.protocol = 'http:'; } // Otherwise, pickup the target protocol and hostname } else { srcUrlObj.protocol = targetUrlObj.protocol; srcUrlObj.hostname = targetUrlObj.hostname; } } // Return our completed src url return url.format(srcUrlObj); }
javascript
{ "resource": "" }
q38012
RenderTexture
train
function RenderTexture(renderer, width, height, scaleMode, resolution) { if (!renderer) { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } width = width || 100; height = height || 100; resolution = resolution || CONST.RESOLUTION; /** * The base texture object that this texture uses * * @member {BaseTexture} */ var baseTexture = new BaseTexture(); baseTexture.width = width; baseTexture.height = height; baseTexture.resolution = resolution; baseTexture.scaleMode = scaleMode || CONST.SCALE_MODES.DEFAULT; baseTexture.hasLoaded = true; Texture.call(this, baseTexture, new math.Rectangle(0, 0, width, height) ); /** * The with of the render texture * * @member {number} */ this.width = width; /** * The height of the render texture * * @member {number} */ this.height = height; /** * The Resolution of the texture. * * @member {number} */ this.resolution = resolution; /** * The framing rectangle of the render texture * * @member {Rectangle} */ //this._frame = new math.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); /** * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) * * @member {Rectangle} */ //this.crop = new math.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); /** * Draw/render the given DisplayObject onto the texture. * * The displayObject and descendents are transformed during this operation. * If `updateTransform` is true then the transformations will be restored before the * method returns. Otherwise it is up to the calling code to correctly use or reset * the transformed display objects. * * The display object is always rendered with a worldAlpha value of 1. * * @method * @param displayObject {DisplayObject} The display object to render this texture on * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. * @param [clear=false] {boolean} If true the texture will be cleared before the displayObject is drawn * @param [updateTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ this.render = null; /** * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. * * @member {CanvasRenderer|WebGLRenderer} */ this.renderer = renderer; if (this.renderer.type === CONST.RENDERER_TYPE.WEBGL) { var gl = this.renderer.gl; this.textureBuffer = new RenderTarget(gl, this.width, this.height, baseTexture.scaleMode, this.resolution);//, this.baseTexture.scaleMode); this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture; //TODO refactor filter manager.. as really its no longer a manager if we use it here.. this.filterManager = new FilterManager(this.renderer); this.filterManager.onContextChange(); this.filterManager.resize(width, height); this.render = this.renderWebGL; // the creation of a filter manager unbinds the buffers.. this.renderer.currentRenderer.start(); this.renderer.currentRenderTarget.activate(); } else { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; } /** * @member {boolean} */ this.valid = true; this._updateUvs(); }
javascript
{ "resource": "" }
q38013
train
function (args, done) { var q = _.clone(args.q) var qent = args.qent q.limit$ = 1 var qs = schemastm(qent) self.connection.all(qs.text, function (err, results) { if (err) { return done(err) } var schema = {} results.forEach(function (row) { schema[row.name] = row.type.toLowerCase() }) var query = selectstm(qent, q) self.connection.get(query.text, query.values, function (err, row) { if (err) { return done(err) } if (row) { var fent = makeent(qent, row, schema) seneca.log.debug('load', q, fent, desc) return done(null, fent) } return done(null, null) }) }) }
javascript
{ "resource": "" }
q38014
promptAsync
train
function promptAsync(prompts) { return new Promise(function(resolve, reject) { parent.prompt.call(parent, prompts, function(answers) { resolve(answers) }); }); }
javascript
{ "resource": "" }
q38015
remoteAsync
train
function remoteAsync() { var generator = this.generator; var username; var repo; var branch; var refresh; var url; // With URL and refresh if (arguments.length <= 2) { url = arguments[0]; refresh = arguments[1]; } else { username = arguments[0]; repo = arguments[1]; branch = arguments[2]; refresh = arguments[3]; url = 'https://github.com/' + [username, repo, 'archive', branch].join('/') + '.tar.gz'; } return new Promise(function(resolve, reject) { parent.remote.call(parent, url, function(err, remote) { if (err) { reject(err); } else { resolve(remote); } }, refresh); }); }
javascript
{ "resource": "" }
q38016
TimedSample
train
function TimedSample(dt, timeStamp, persistObj, scaleFactor) { var time = (dt[0] + dt[1] / 1e9) * 1000 / scaleFactor; this.scaleFactor = scaleFactor; this.min = time; this.max = time; this.sigma = new StandardDeviation(time); this.average = new Average(time); this.timeStamp = timeStamp; if (persistObj) { var that = this; persistObj.on('reset', function (timeStamp) { that.reset(timeStamp); }); } }
javascript
{ "resource": "" }
q38017
addMode
train
function addMode(middle, mode, settings) { if (!modes.includes(mode)) throw `Incorrect bodyparser mode ${mode}`; middle.push(bodyParser[mode](settings[mode])); }
javascript
{ "resource": "" }
q38018
initEndpoint
train
function initEndpoint(brest, description) { const settings = _.defaultsDeep(description.bodyParser, settingsDefault); if (description.bodyParserModes) { description.bodyParserModes.forEach((mode) => addMode(description.middle, mode, settings)); } else { const mode = description.bodyParserMode || BODY_PARSER_JSON; addMode(description.middle, mode, settings); } // return bodyParser[mode](settings[mode]); }
javascript
{ "resource": "" }
q38019
train
function (e, data) { ctrl.coreWistia.setError(); //clear any previous errors data .submit() .then(function (result, textStatus, jqXHR) { ctrl.coreWistia.playVideo(result.hashed_id); }) .catch(function (jqXHR, textStatus, errorThrown) { $timeout(function() { ctrl.coreWistia.setError('WistiaError: ' + jqXHR.responseJSON ? jqXHR.responseJSON.error : errorThrown); }); }) ; }
javascript
{ "resource": "" }
q38020
train
function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $timeout(function() { ctrl.coreWistia.setProgress(progress); }); }
javascript
{ "resource": "" }
q38021
MongoCrud
train
function MongoCrud(uri, options, gridFS) { this.uri = uri || 'mongodb://localhost:27017/mongo-crud-test'; this.options = options || {}; this.gridFS = gridFS; }
javascript
{ "resource": "" }
q38022
help
train
function help() { var padBtm = [0, 0, 1, 0]; var msg = ' See additional required/optional arguments for each command below. \n'; pargv .logo('Mustr', 'cyan') .ui(95) .join(chalk.magenta('Usage:'), 'mu', chalk.cyan('<cmd>'), '\n') .div({ text: chalk.bgBlue.white(msg) }) .div({ text: chalk.cyan('help, h'), width: 35, padding: padBtm }, { text: chalk.gray('displays help and usage information.'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('init, i'), width: 35, padding: padBtm }, { text: chalk.gray('initialize the application for use with Mustr.'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('generate, g') + " " + chalk.white('<template>') + " " + chalk.magenta('[output]'), width: 35, padding: padBtm }, { text: chalk.gray('generates and renders a template.'), width: 40, padding: padBtm }) .div({ text: chalk.white('<template>'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('template to generate and compile.'), width: 40 }, { text: chalk.red('[required]'), align: 'right' }) .div({ text: chalk.white('[output]'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('output name/path for template'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('rollback, r') + " " + chalk.white('<name/id>') + " " + chalk.magenta('[output]'), width: 35, padding: padBtm }, { text: chalk.gray('Rolls back a template or component.'), width: 40, padding: padBtm }) .div({ text: chalk.white('<name/id>'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('the rollback id, index or template name.'), width: 40 }) .div({ text: chalk.white('[output]'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('output name/path for template'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('show, s') + " " + chalk.white('<type>'), width: 35, padding: padBtm }, { text: chalk.gray('shows details/stats for the given type.'), width: 40, padding: padBtm }) .div({ text: chalk.white('<type>'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('currently there is only one type "rollbacks"'), width: 40 }) .show(); }
javascript
{ "resource": "" }
q38023
generate
train
function generate() { var parsed = ensureConfig(); if (!parsed.name) mu.log.error('cannot generate template using name of undefined.\n').write().exit(); // Generate the template. mu.render(parsed.name, parsed.output, parsed.options); }
javascript
{ "resource": "" }
q38024
rollback
train
function rollback() { var parsed = ensureConfig(); var name = parsed.name; // check if is an index number. // if yes try to lookup the id // by its index. try { var idx = void 0; if (/^[0-9]+$/.test(name)) { idx = parseInt(parsed.name) - 1; if (idx >= 0) { var keys = Object.keys(mu.rollbacks); var key = keys[idx]; if (key) name = key; } } } catch (ex) { } mu.rollback(parsed.name, parsed.output); }
javascript
{ "resource": "" }
q38025
show
train
function show() { var parsed = ensureConfig(); function showRollbacks() { var rollbacks = mu.getRollbacks(); var keys = Object.keys(rollbacks); var padBtm = [0, 0, 1, 0]; var ui = pargv.ui(105); var i = keys.length; var hdrNo = { text: " ", width: 5 }; var hdrId = { text: "" + chalk.underline.gray('ID'), width: 20 }; var hdrTs = { text: "" + chalk.underline.gray('Timestamp'), width: 30 }; var hdrCt = { text: "" + chalk.underline.gray('Count'), width: 10 }; var hdrTpl = { text: "" + chalk.underline.gray('Templates'), width: 35, padding: padBtm }; ui.div(hdrNo, hdrId, hdrTs, hdrCt, hdrTpl); while (i--) { var key = keys[i]; var rb = rollbacks[key]; var no = { text: i + 1 + ")", width: 5 }; var id = { text: "" + chalk.cyan(rb.id), width: 20 }; var ts = { text: "" + chalk.yellow(rb.timestamp), width: 30 }; var ct = { text: "" + chalk.green(rb.count + ''), width: 10 }; var tpl = { text: "" + chalk.magenta(rb.templates.join(', ')), width: 35 }; ui.div(no, id, ts, ct, tpl); } ui.show(); } switch (parsed.name) { case 'r': showRollbacks(); break; case 'rollbacks': showRollbacks(); break; default: break; } }
javascript
{ "resource": "" }
q38026
train
function(username, pw) { return _.ajax({ verb: 'POST', url: '/login', data: { username: username, password: pw } }).then(function(id) { document.cookie = 'user=' + id; return id; }); }
javascript
{ "resource": "" }
q38027
multiaddrFromUri
train
function multiaddrFromUri (uriStr, opts) { opts = opts || {} const defaultDnsType = opts.defaultDnsType || 'dns4' const { scheme, hostname, port } = parseUri(uriStr) const parts = [ tupleForHostname(hostname, defaultDnsType), tupleForPort(port, scheme), tupleForScheme(scheme) ] const multiaddrStr = '/' + parts .filter(x => !!x) .reduce((a, b) => a.concat(b)) .join('/') return Multiaddr(multiaddrStr) }
javascript
{ "resource": "" }
q38028
sign
train
function sign(custom, request) { /** * An Epoch timestamp is required for the digital signature. */ let epoch = Util.epochInMilliseconds(); /** * Override the generated Epoch timestamp if a timestamp was included in the * custom headers. */ if (custom.WMSecurity && custom.WMSecurity.Timestamp) { epoch = custom.WMSecurity.Timestamp; } /** * The generated digital signature. */ let signature = digitalSignature(custom, request, epoch); /** * Override the generated digital signature if a signature was included in the * custom headers. */ if (custom.WMSecurity && custom.WMSecurity.AuthSignature) { signature = custom.WMSecurity.AuthSignature; } /** * The signed request headers according to Walmart API spec. */ let signedHeaders = { 'WM_SVC.NAME': custom.WMService.Name, 'WM_QOS.CORRELATION_ID': custom.WMQOS.CorrelationId, 'WM_SEC.TIMESTAMP': epoch, 'WM_SEC.AUTH_SIGNATURE': signature, 'WM_CONSUMER.CHANNEL.TYPE': custom.WMConsumer.Channel.Type, 'WM_CONSUMER.ID': custom.WMConsumer.ConsumerId, 'Accept': custom.Accept, 'Content-Type': custom.Accept }; return signedHeaders; }
javascript
{ "resource": "" }
q38029
digitalSignature
train
function digitalSignature(custom, request, epoch) { /** * Node Crypto Sign object that uses the given algorithm. * * @see {@link https://nodejs.org/api/crypto.html#crypto_class_sign} */ const signer = crypto_1.createSign('RSA-SHA256'); /** * Walmart API request string to be signed. */ let stringToSign = custom.WMConsumer.ConsumerId + "\n" + request.RequestUrl + "\n" + request.RequestMethod.toUpperCase() + "\n" + epoch + "\n"; /** * Updates the Sign content with the given data. * @see {@link https://nodejs.org/api/crypto.html#crypto_sign_update_data_inputencoding} */ signer.update(stringToSign); /** * Private key wrapped in key header and footer. */ let privateKey = "-----BEGIN PRIVATE KEY-----\n" + request.PrivateKey + "\n-----END PRIVATE KEY-----"; return signer.sign(privateKey, 'base64'); }
javascript
{ "resource": "" }
q38030
namespace
train
function namespace(path, scope) { assertType(path, 'string', true, 'Invalid parameter: path'); assertType(scope, 'object', true, 'Invalid optional parameter: scope'); if (!scope) scope = (window) ? window : {}; if (path === undefined || path === '') return scope; let groups = path.split('.'); let currentScope = scope; for (let i = 0; i < groups.length; i++) { currentScope = currentScope[groups[i]] || (currentScope[groups[i]] = {}); } return currentScope; }
javascript
{ "resource": "" }
q38031
isSpecial
train
function isSpecial( obj, name ) { if ( !obj ) return false; if ( typeof obj[ 0 ] !== 'string' ) return false; if ( typeof name === 'string' ) { return obj[ 0 ].toLowerCase() === name; } return true; }
javascript
{ "resource": "" }
q38032
createSectionStructure
train
function createSectionStructure() { return { init: null, comments: [], attribs: { define: [], init: [] }, elements: { define: [], init: [] }, events: [], links: [], ons: [], statics: [] }; }
javascript
{ "resource": "" }
q38033
findPath
train
function findPath(path, directories) { var cwd = directories[0]; if (!cwd) { return null; } return findup(path, {cwd: cwd}) || findPath(path, slice.call(directories, 1)); }
javascript
{ "resource": "" }
q38034
log
train
function log(txt) { var p = document.createElement("p"); p.style.margin = '2px'; p.style.padding = '1px'; p.style.backgroundColor = "#FFFFF0"; p.style.border = "solid"; p.style.borderWidth = "1px"; p.style.borderColor = "#7F7F8F"; p.style.lineHeight = "1.0"; p.appendChild(document.createTextNode(txt)); document.body.appendChild(p); }
javascript
{ "resource": "" }
q38035
train
function (ppunit, writer) { Dependencies.super_.call(this, ppunit, writer) var self = this self.subGraphs = [] ppunit.on('start', function () { writer.write('digraph PPUnit {') self.printNodes() self.printSubGraphs() self.printDependencies() writer.write('}') }) }
javascript
{ "resource": "" }
q38036
abortXHRRequest
train
function abortXHRRequest(uid, fn) { if (reqs.hasOwnProperty(uid)) { if (!reqs[uid]) return; if (fn) { fn(); } else { reqs[uid].abort(); } delete reqs[uid]; return reqs; } }
javascript
{ "resource": "" }
q38037
customError
train
function customError(name, error) { return { error: error, message: error.message, name: name }; }
javascript
{ "resource": "" }
q38038
responseStatus
train
function responseStatus(res) { if (res.status >= 200 && res.status < 300) { return res; } else { var error = new Error(res.statusText); error.response = res; throw customError('responseStatus', error); } }
javascript
{ "resource": "" }
q38039
buildUploadURL
train
function buildUploadURL(url, uuid, expiration, hmac, filename) { return url + '?uuid=' + uuid + '&expiration=' + expiration + '&hmac=' + hmac + '&file=' + filename; }
javascript
{ "resource": "" }
q38040
uploadRequest
train
function uploadRequest(res, fileObject, showProgress) { var url = res.url; var expiration = res.expiration; var hmac = res.hmac; var uuid = res.uuid; var file = fileObject.file; var uid = fileObject.uid; var upload_url = buildUploadURL(url, uuid, expiration, hmac, file.name); return new Promise(function (resolve, reject) { reqs[uid] = _superagent2.default.put(upload_url).send(file).set({ 'Accept': 'application/json', 'Content-Type': 'application/json' }).on('progress', function (e) { showProgress(e, fileObject); }).end(function (err, res) { delete reqs[uid]; // throw a custom error message if (err) return reject(customError('uploadRequest', err)); resolve(res); }); }); }
javascript
{ "resource": "" }
q38041
parseMiddleware
train
function parseMiddleware(ctx, next) { try { ctx.event = JSON.parse(ctx.content.toString()); next(); } catch (e) { throw e; } }
javascript
{ "resource": "" }
q38042
train
function (e) { if (!RGraph.Resizing || !RGraph.Resizing.div || !RGraph.Resizing.mousedown) { return; } if (RGraph.Resizing.div) { var div = RGraph.Resizing.div; var canvas = div.__canvas__; var coords = RGraph.getCanvasXY(div.__canvas__); var parentNode = canvas.parentNode; if (canvas.style.position != 'absolute') { // Create a DIV to go in the canvases place var placeHolderDIV = document.createElement('DIV'); placeHolderDIV.style.width = RGraph.Resizing.originalw + 'px'; placeHolderDIV.style.height = RGraph.Resizing.originalh + 'px'; //placeHolderDIV.style.backgroundColor = 'red'; placeHolderDIV.style.display = 'inline-block'; // Added 5th Nov 2010 placeHolderDIV.style.position = canvas.style.position; placeHolderDIV.style.left = canvas.style.left; placeHolderDIV.style.top = canvas.style.top; placeHolderDIV.style.cssFloat = canvas.style.cssFloat; parentNode.insertBefore(placeHolderDIV, canvas); } // Now set the canvas to be positioned absolutely canvas.style.backgroundColor = 'white'; canvas.style.position = 'absolute'; canvas.style.border = '1px dashed gray'; canvas.style.left = (RGraph.Resizing.originalCanvasX - 1) + 'px'; canvas.style.top = (RGraph.Resizing.originalCanvasY - 1) + 'px'; /** * Set the dimensions of the canvas using the HTML attributes */ canvas.width = parseInt(div.style.width); canvas.height = parseInt(div.style.height); /** * Because resizing the canvas resets any tranformation - the antialias fix needs to be reapplied. */ canvas.getContext('2d').translate(0.5,0.5); /** * Reset the gradient parsing status by setting all of the color values back to their original * values before Draw was first called */ var objects = RGraph.ObjectRegistry.getObjectsByCanvasID(canvas.id); for (var i=0,len=objects.length; i<len; i+=1) { RGraph.resetColorsToOriginalValues(objects[i]); if (typeof objects[i].reset === 'function') { objects[i].reset(); } } /** * Kill the background cache */ RGraph.cache = []; /** * Fire the onresize event */ RGraph.FireCustomEvent(canvas.__object__, 'onresizebeforedraw'); RGraph.RedrawCanvas(canvas); // Get rid of transparent semi-opaque DIV RGraph.Resizing.mousedown = false; div.style.display = 'none'; document.body.removeChild(div); } /** * If there is zoom enabled in thumbnail mode, lose the zoom image */ if (RGraph.Registry.Get('chart.zoomed.div') || RGraph.Registry.Get('chart.zoomed.img')) { RGraph.Registry.Set('chart.zoomed.div', null); RGraph.Registry.Set('chart.zoomed.img', null); } /** * Fire the onresize event */ RGraph.FireCustomEvent(canvas.__object__, 'onresizeend'); }
javascript
{ "resource": "" }
q38043
_shuffle
train
function _shuffle(sample) { var shuffle = function shuffle(a, i, j) { sample(j - i, a, i, j); }; return shuffle; }
javascript
{ "resource": "" }
q38044
train
function (token, path, payload, contentFormat) { return new Promise((resolve,reject)=>{ let zh = NewZestHeader(); zh.code = 2; zh.token = token; zh.tkl = token.length; zh.payload = payload; zh.oc = 3; zh.options.push(NewZestOptionHeader(11,path,path.length)); let hostname = os.hostname(); zh.options.push(NewZestOptionHeader(3,hostname,hostname.length)); zh.options.push(NewZestOptionHeader(12,contentFormatToInt(contentFormat),2)); //uint32 let msg = MarshalZestHeader(zh) sendRequestAndAwaitResponse(this.ZMQsoc,msg) .then((resp)=>{ handleResponse(resp,(zh)=>{resolve(zh.payload)},reject); }) .catch((err)=>{ reject(err); }); }); }
javascript
{ "resource": "" }
q38045
positionAfter
train
function positionAfter (arr, prevChild) { var idx if (prevChild === null) { return 0 } else { idx = findIndex(arr, prevChild) return (idx === -1) ? arr.length : idx + 1 } }
javascript
{ "resource": "" }
q38046
toJS
train
function toJS(node, options, context) { switch (node.type) { // process numeric values and units case 'Dimension': var value = node.value; var unit = options.units ? node.unit.toCSS(context) : null; // if given a list of units to preserve, check if compiled unit is present in that list if (Array.isArray(options.units)) unit = options.units.includes(unit) && unit; // if we should keep the units, compile the entire node to perform necessary checks, // otherwise just return the node value return unit ? node.toCSS(context) : value; // drop quotes from quoted values case 'Quoted': return node.value; // recursively transform expressions into arrays case 'Expression': return node.value.map(function (child) { return toJS(child, options, context); }); } return node.toCSS(context); }
javascript
{ "resource": "" }
q38047
createElement
train
function createElement(value) { if (!document) return null; assertType(value, 'string', true, 'Value must be a string'); if (value.match(/^([a-z0-9]+-)+[a-z0-9]+$/)) { return new (getElementRegistry(value))(); } else { let div = document.createElement('div'); if (value.indexOf('<') !== 0 && value.indexOf('>') !== (value.length - 1)) value = `<${value}>`; div.innerHTML = value; return div.firstChild; } }
javascript
{ "resource": "" }
q38048
install
train
function install(definition, Component) { const Ctor = register(definition, Component); // no dependencies if (!definition.components) { return Ctor; } const components = definition.components || {}; // avoid unnecessary re-registering for next time delete definition.components; // register components for (const name in components) { Ctor.component(name, register(components[name], Component)); install(components[name], Component); } return Ctor; }
javascript
{ "resource": "" }
q38049
parseHttpHeaders
train
function parseHttpHeaders(headers) { var meta = {}; for (var headerName in headers) { var headerValue = headers[headerName]; if (headerName=="x-ratelimit-limit") { meta.rateLimit = headerValue; } else if (headerName=="x-ratelimit-remaining") { meta.rateLimitRemaining = headerValue; } else if (headerName=="x-ratelimit-reset") { meta.rateLimitReset = headerValue; } else if (headerName=="link") { var regexp = /<(.+)>; rel=(.+),?/g; var match; do { match = regexp.exec(headerValue); if (match) { var url = match[1]; var rel = match[2]; var regexp2 = /[\?|&]page=(\d+)/; var match2 = regexp2.exec(url); if (match2) { var page = match2[1]; if (rel=='prev') { meta.prevPage = page; } else if (rel=='next') { meta.nextPage = page; } else if (rel=='last') { meta.lastPage = page; } } } } while (match); } } return meta; }
javascript
{ "resource": "" }
q38050
getter_THREE_CubeTexture
train
function getter_THREE_CubeTexture(inst) { return [ inst.name, inst.mipmaps, inst.flipY, inst.mapping, inst.wrapS, inst.wrapT, inst.magFilter, inst.minFilter, inst.anisotropy, inst.format, inst.type, inst.offset, inst.repeat, inst.unpackAlignment, inst.image]; }
javascript
{ "resource": "" }
q38051
getter_THREE_LineBasicMaterial
train
function getter_THREE_LineBasicMaterial(inst) { return [ inst.name, inst.side, inst.opacity, inst.blending, inst.blendSrc, inst.blendDst, inst.blendEquation, inst.depthFunc, inst.polygonOffsetFactor, inst.polygonOffsetUnits, inst.alphaTest, inst.overdraw, inst.blendSrcAlpha, inst.blendDstAlpha, inst.blendEquationAlpha, inst.transparent, inst.depthTest, inst.depthWrite, inst.colorWrite, inst.polygonOffset, inst.visible, inst.precision, inst.color, inst.linewidth, inst.linecap, inst.linejoin, inst.vertexColors, inst.fog]; }
javascript
{ "resource": "" }
q38052
getter_THREE_SpriteMaterial
train
function getter_THREE_SpriteMaterial(inst) { return [ inst.name, inst.side, inst.opacity, inst.blending, inst.blendSrc, inst.blendDst, inst.blendEquation, inst.depthFunc, inst.polygonOffsetFactor, inst.polygonOffsetUnits, inst.alphaTest, inst.overdraw, inst.blendSrcAlpha, inst.blendDstAlpha, inst.blendEquationAlpha, inst.transparent, inst.depthTest, inst.depthWrite, inst.colorWrite, inst.polygonOffset, inst.visible, inst.precision, inst.color, inst.map, inst.rotation, inst.fog]; }
javascript
{ "resource": "" }
q38053
getter_THREE_MeshDepthMaterial
train
function getter_THREE_MeshDepthMaterial(inst) { return [ inst.name, inst.side, inst.opacity, inst.blending, inst.blendSrc, inst.blendDst, inst.blendEquation, inst.depthFunc, inst.polygonOffsetFactor, inst.polygonOffsetUnits, inst.alphaTest, inst.overdraw, inst.blendSrcAlpha, inst.blendDstAlpha, inst.blendEquationAlpha, inst.transparent, inst.depthTest, inst.depthWrite, inst.colorWrite, inst.polygonOffset, inst.visible, inst.precision, inst.wireframeLinewidth, inst.wireframe, inst.morphTargets]; }
javascript
{ "resource": "" }
q38054
getter_THREE_MeshLambertMaterial
train
function getter_THREE_MeshLambertMaterial(inst) { return [ inst.name, inst.side, inst.opacity, inst.blending, inst.blendSrc, inst.blendDst, inst.blendEquation, inst.depthFunc, inst.polygonOffsetFactor, inst.polygonOffsetUnits, inst.alphaTest, inst.overdraw, inst.blendSrcAlpha, inst.blendDstAlpha, inst.blendEquationAlpha, inst.transparent, inst.depthTest, inst.depthWrite, inst.colorWrite, inst.polygonOffset, inst.visible, inst.precision, inst.wireframeLinecap, inst.wireframeLinejoin, inst.color, inst.emissive, inst.vertexColors, inst.map, inst.specularMap, inst.alphaMap, inst.envMap, inst.combine, inst.reflectivity, inst.wireframeLinewidth, inst.refractionRatio, inst.fog, inst.wireframe, inst.skinning, inst.morphTargets, inst.morphNormals]; }
javascript
{ "resource": "" }
q38055
getter_THREE_MeshPhongMaterial
train
function getter_THREE_MeshPhongMaterial(inst) { return [ inst.name, inst.side, inst.opacity, inst.blending, inst.blendSrc, inst.blendDst, inst.blendEquation, inst.depthFunc, inst.polygonOffsetFactor, inst.polygonOffsetUnits, inst.alphaTest, inst.overdraw, inst.blendSrcAlpha, inst.blendDstAlpha, inst.blendEquationAlpha, inst.transparent, inst.depthTest, inst.depthWrite, inst.colorWrite, inst.polygonOffset, inst.visible, inst.precision, inst.color, inst.emissive, inst.specular, inst.shininess, inst.vertexColors, inst.metal, inst.fog, inst.skinning, inst.morphTargets, inst.morphNormals, inst.map, inst.lightMap, inst.emissiveMap, inst.aoMap, inst.emissiveMap, inst.bumpMap, inst.normalMap, inst.displacementMap, inst.specularMap, inst.alphaMap, inst.envMap, inst.lightMapIntensity, inst.aoMapIntensity, inst.bumpScale, inst.normalScale, inst.displacementScale, inst.displacementBias, inst.reflectivity, inst.refractionRatio, inst.combine, inst.shading, inst.wireframe, inst.wireframeLinewidth, inst.wireframeLinecap, inst.wireframeLinecap]; }
javascript
{ "resource": "" }
q38056
getter_THREE_Scene
train
function getter_THREE_Scene(inst) { return [ inst.name, inst.up, inst.position, inst.quaternion, inst.scale, inst.rotationAutoUpdate, inst.matrix, inst.matrixWorld, inst.matrixAutoUpdate, inst.visible, inst.castShadow, inst.receiveShadow, inst.frustumCulled, inst.renderOrder, inst.userData, inst.children, inst.fog, inst.overrideMaterial]; }
javascript
{ "resource": "" }
q38057
getter_THREE_Mesh
train
function getter_THREE_Mesh(inst) { return [ inst.name, inst.up, inst.position, inst.quaternion, inst.scale, inst.rotationAutoUpdate, inst.matrix, inst.matrixWorld, inst.matrixAutoUpdate, inst.visible, inst.castShadow, inst.receiveShadow, inst.frustumCulled, inst.renderOrder, inst.userData, inst.children, inst.geometry, inst.material, inst.materialTexture, inst.materialWireframe]; }
javascript
{ "resource": "" }
q38058
getter_THREE_BufferGeometry
train
function getter_THREE_BufferGeometry(inst) { return [ inst.vertices, inst.faces, inst.faceVertexUvs, inst.morphTargets, inst.morphNormals, inst.morphColors, inst.animations, inst.boundingSphere, inst.boundingBox, inst.name, inst.attributes, inst.index]; }
javascript
{ "resource": "" }
q38059
getter_THREE_Geometry
train
function getter_THREE_Geometry(inst) { return [ inst.vertices, inst.faces, inst.faceVertexUvs, inst.morphTargets, inst.morphNormals, inst.morphColors, inst.animations, inst.boundingSphere, inst.boundingBox, inst.name]; }
javascript
{ "resource": "" }
q38060
getter_THREE_Vector4
train
function getter_THREE_Vector4(inst) { return [ inst.x, inst.y, inst.z, inst.w]; }
javascript
{ "resource": "" }
q38061
getter_THREE_Face3
train
function getter_THREE_Face3(inst) { return [ inst.a, inst.b, inst.c, inst.materialIndex, inst.normal, inst.color, inst.vertexNormals, inst.vertexColors]; }
javascript
{ "resource": "" }
q38062
getter_THREE_Quaternion
train
function getter_THREE_Quaternion(inst) { return [ inst._x, inst._y, inst._z, inst._w]; }
javascript
{ "resource": "" }
q38063
getter_THREE_Euler
train
function getter_THREE_Euler(inst) { return [ inst._x, inst._y, inst._z, inst._order]; }
javascript
{ "resource": "" }
q38064
getter_THREE_BufferAttribute
train
function getter_THREE_BufferAttribute(inst) { return [ inst.array, inst.itemSize, inst.dynamic, inst.updateRange]; }
javascript
{ "resource": "" }
q38065
getter_THREE_PerspectiveCamera
train
function getter_THREE_PerspectiveCamera(inst) { return [ inst.fov, inst.aspect, inst.near, inst.far]; }
javascript
{ "resource": "" }
q38066
getter_THREE_OrthographicCamera
train
function getter_THREE_OrthographicCamera(inst) { return [ inst.left, inst.right, inst.top, inst.bottom, inst.near, inst.far]; }
javascript
{ "resource": "" }
q38067
getter_THREE_MD2Character
train
function getter_THREE_MD2Character(inst) { return [ inst.scale, inst.animationFPS, inst.root, inst.meshBody, inst.skinsBody, inst.meshWeapon, inst.skinsWeapon, inst.weapons, inst.activeAnimation]; }
javascript
{ "resource": "" }
q38068
addSetValues
train
function addSetValues(args) { for (var key in args.from) { if (args.from[key]) { args.to[key] = true; } } }
javascript
{ "resource": "" }
q38069
HTTPError
train
function HTTPError() { var args = Array.prototype.slice.call(arguments); if(!(this instanceof HTTPError)) { if(args.length === 1) { return new HTTPError(args[0]); } else if(args.length === 2) { return new HTTPError(args[0], args[1]); } else if(args.length === 3) { return new HTTPError(args[0], args[1], args[2]); } else { throw new TypeError("Too many arguments (" + args.length + ") for new HTTPError()"); } } var headers, msg, code; ARRAY(args).forEach(function(arg) { if(typeof arg === 'object') { headers = arg; } if(typeof arg === 'string') { msg = arg; } if(typeof arg === 'number') { code = arg; } }); code = code || 500; msg = msg || (''+code+' '+require('http').STATUS_CODES[code]); headers = headers || {}; Error.call(this); Error.captureStackTrace(this, this); this.code = code; this.message = msg; this.headers = headers; }
javascript
{ "resource": "" }
q38070
reduce
train
function reduce(data, fn) { delete data.package.readmeFilename; // README is already parsed. delete data.package.versions; // Adds to much bloat. delete data.package.readme; // README is already parsed. // // Remove circular references as it would prevent us from caching in Redis or // what ever because there's a circular reference. Keep track of what are main // dependencies by providing them with a number, useful for sorting later on. // if ('object' === typeof data.shrinkwrap) { Object.keys(data.shrinkwrap).forEach(function each(_id) { var shrinkwrap = data.shrinkwrap[_id]; delete shrinkwrap.dependencies; delete shrinkwrap.dependent; delete shrinkwrap.parents; }); } // // Extract github data from array. // if (data.github && data.github.length) data.github = data.github.pop(); // // Make sure we default to something so we don't get template errors // data.readme = data.readme || data.package.description || ''; // // Transform shrinkwrap to an array and prioritize on depth. // data.shrinkwrap = Object.keys(data.shrinkwrap || {}).map(function wrap(_id) { return data.shrinkwrap[_id]; }).sort(function sort(a, b) { return a.depth - b.depth; }); // // Remove empty objects from the package. // [ 'repository', 'homepage', 'bugs' ].forEach(function each(key) { if (Array.isArray(data.package[key])) { if (!data.package[key].length) delete data.package[key]; } else if ('object' === typeof data.package[key] && !Object.keys(data.package[key]).length) { delete data.package[key]; } }); fn(undefined, data); }
javascript
{ "resource": "" }
q38071
clients
train
function clients(options) { options = options || {}; options.registry = options.registry || Registry.mirrors.nodejitsu; var githulk = options.githulk || new GitHulk(); // // Only create a new Registry instance if we've been supplied with a string. // var npm = 'string' !== typeof options.registry ? options.registry : new Registry({ registry: options.registry, githulk: githulk }); return { git: githulk, npm: npm }; }
javascript
{ "resource": "" }
q38072
train
function(text, options) { var execute, queried; queried = p.defer(); // caching disabled unless duration is specified options = options != null ? options : { duration: 0 }; execute = function(params) { return db.prepare(text).then(function(stmt) { return stmt.execute(params).then(function(results) { if (options.duration > 0) { cache.store(text, results.rows, options.duration); } return queried.resolve(results.rows); }).done(); }).done(); }; // return results directly if cache hit, run query if cache miss cache.get(text).then(function(results) { return queried.resolve(results); }, function(err) { if (err != null) { return queried.reject(err); } else { return execute(); } }).done(); return queried.promise; }
javascript
{ "resource": "" }
q38073
findOrCreateMbaasApp
train
function findOrCreateMbaasApp(req, res, next){ log.logger.debug("findOrCreateMbaasApp ", req.params); var models = mbaas.getModels(); //Checking For Required Params var missingParams = _.filter(["appGuid", "apiKey", "coreHost"], function(requiredKey){ return validation.validateParamPresent(requiredKey, req); }); if(missingParams.length > 0){ log.logger.debug("findOrCreateMbaasApp Missing Param ", missingParams[0]); return validation.requireParam(missingParams[0], req, res); } findMbaasApp(req, res, function(err){ if(err){ log.logger.debug("Error Finding Mbaas App ", err); return next(err); } var appMbaas = req.appMbaasModel; //App Found, moving on. if(_.isObject(appMbaas)){ log.logger.debug("Mbaas App Already Exists "); return next(); } //App mbaas does not exist, create it. log.logger.debug("Mbaas App Does Not Exist, Creating New App Model ", {params: req.params, body: req.body}); models.AppMbaas.createModel({ name: req.params.appname, domain: req.params.domain, environment: req.params.environment, guid: req.body.appGuid, apiKey: req.body.apiKey, coreHost: req.body.coreHost, type: req.body.type, mbaasUrl: req.body.mbaasUrl, isServiceApp: req.body.isServiceApp, url: req.body.url }, function(err, createdMbaasApp){ if(err){ log.logger.debug("Error Creating New Mbaas App Model ", err); return next(err); } req.appMbaasModel = createdMbaasApp; next(); }); }); }
javascript
{ "resource": "" }
q38074
findMbaasApp
train
function findMbaasApp(req, res, next){ log.logger.debug("findMbaasApp for appname " + req.params.appname); getMbaasApp({ '$or': [{name: req.params.appname}, {guid: req.params.appname}] }, function(err, appMbaas){ if(err){ log.logger.debug("findMbaasApp Error ", err); return next(err); } req.appMbaasModel = appMbaas; return next(); }); }
javascript
{ "resource": "" }
q38075
getMbaasApp
train
function getMbaasApp(params, cb){ var models = mbaas.getModels(); models.AppMbaas.findOne(params, cb); }
javascript
{ "resource": "" }
q38076
updateMbaasApp
train
function updateMbaasApp(req, res, next){ var model = req.appMbaasModel; model.name = req.params.appname; model.domain = req.params.domain; model.environment = req.params.environment; model.guid = req.body.appGuid; model.apiKey = req.body.apiKey; model.coreHost = req.body.coreHost; model.type = req.body.type; model.mbaasUrl = req.body.mbaasUrl; //If the serviceApp is not set yet and it is a service app, then make sure it is set. model.isServiceApp = typeof model.isServiceApp === "undefined" ? req.body.isServiceApp : model.isServiceApp; model.url = req.body.url || model.url; model.accessKey = model.accessKey || new mongoose.Types.ObjectId(); model.save(next); }
javascript
{ "resource": "" }
q38077
execute
train
function execute(req, res) { // unwatch keys, clear references, // and destroy the transaction reference on the conn // and send the reply req.conn.transaction.destroy(req, res, null, Constants.OK); }
javascript
{ "resource": "" }
q38078
validate
train
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); if(!info.conn.transaction) { throw DiscardWithoutMulti; } }
javascript
{ "resource": "" }
q38079
ErrorUnauthorized
train
function ErrorUnauthorized (message) { Error.call(this); // Add Information this.name = 'ErrorUnauthorized'; this.type = 'client'; this.status = 401; if (message) { this.message = message; } }
javascript
{ "resource": "" }
q38080
allKeys
train
function allKeys(obj) { if (!isObject(obj)) return []; var keys = []; for (var key in obj) keys.push(key); return keys; }
javascript
{ "resource": "" }
q38081
showArray
train
function showArray(maxDepth, array) { return '[' + array.map(function(a) { return show(maxDepth - 1, a) }).join(', ') + ']'; }
javascript
{ "resource": "" }
q38082
showObject
train
function showObject(maxDepth, object) { return '{' + pairs(object).map(function(pair){ return showString(pair.key) + ': ' + show(maxDepth - 1, pair.value) }).join(', ') + '}' }
javascript
{ "resource": "" }
q38083
styledJsxOptions
train
function styledJsxOptions(opts) { if (!opts) { return {}; } if (!Array.isArray(opts.plugins)) { return opts; } opts.plugins = opts.plugins.map(plugin => { if (Array.isArray(plugin)) { const [ name, options ] = plugin; return [ require.resolve(name), options ]; } return require.resolve(plugin); }); return opts; }
javascript
{ "resource": "" }
q38084
MongoDB
train
function MongoDB(config) { var self = this; this.events = new EventEmitter(); config = protos.extend({ host: 'localhost', port: 27017, database: 'default', storage: null, username: '', password: '', safe: true }, config || {}); if (typeof config.port != 'number') config.port = parseInt(config.port, 10); this.className = this.constructor.name; app.debug(util.format('Initializing MongoDB for %s:%s', config.host, config.port)); /** config: { host: 'localhost', port: 27017, database: 'db_name', storage: 'redis' } */ this.config = config; var reportError = function(err) { app.log(util.format("MongoDB [%s:%s] %s", config.host, config.port, err)); self.client = null; } // Set db self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: config.safe}); // Add async task app.addReadyTask(); // Get client self.db.open(function(err, client) { if (err) { reportError(err); } else { // Set client self.client = client; // Set storage if (typeof config.storage == 'string') { self.storage = app.getResource('storages/' + config.storage); } else if (config.storage instanceof protos.lib.storage) { self.storage = config.storage; } // Authenticate if (config.username && config.password) { self.db.authenticate(config.username, config.password, function(err, success) { if (err) { var msg = util.format('MongoDB: unable to authenticate %s@%s', config.username, config.host); app.log(new Error(msg)); throw err; } else { // Emit initialization event self.events.emit('init', self.db, self.client); } }); } else { // Emit initialization event self.events.emit('init', self.db, self.client); } } }); // Flush async task this.events.once('init', function() { app.flushReadyTask(); }); // Only set important properties enumerable protos.util.onlySetEnumerable(this, ['className', 'db']); }
javascript
{ "resource": "" }
q38085
debounce
train
function debounce(method, delay, leading) { assertType(method, 'function', false, 'Invalid parameter: method'); assertType(delay, 'number', true, 'Invalid optional parameter: delay'); assertType(leading, 'boolean', true, 'Invalid optional parameter: leading'); if (delay === undefined) delay = 0; if (leading === undefined) leading = false; let timeout; return function() { let context = this; let args = arguments; let later = function() { timeout = null; if (!leading) method.apply(context, args); }; let callNow = leading && !timeout; clearTimeout(timeout); timeout = setTimeout(later, delay); if (callNow) method.apply(context, args); }; }
javascript
{ "resource": "" }
q38086
exec
train
function exec(sqlQuery, poolName) { return new Promise((resolve, reject) => { db.connect((err, client, done) => { if (err) { reject(err); } client.query(sqlQuery, (err, results) => { if (err) { reject(err); } resolve(results); }); }, poolName || 'default', ); }); }
javascript
{ "resource": "" }
q38087
_cors
train
function _cors (cookieDomain, publicUrl) { return ({ acceptServers, acceptAllOrigins }) => { // accept server 2 server requests by default acceptServers = acceptServers === undefined ? true : acceptServers // do not accept call by outside origins by default acceptAllOrigins = acceptAllOrigins === undefined ? false : acceptAllOrigins return corsBuilder({ credentials: true, origin (origin, callback) { // Case of server to server requests if (!origin) { if (acceptServers) return callback(null, true) return callback(new Error('No CORS allowed for server to server requests')) } // Case where we accept any domain as origin if (acceptAllOrigins) return callback(null, true) const originDomain = new URL(origin).host // Case of mono-domain acceptance if (!cookieDomain) { if (originDomain === new URL(publicUrl).host) return callback(null, true) return callback(new Error(`No CORS allowed from origin ${origin}`)) } // Case of subdomains acceptance if (originDomain === cookieDomain || originDomain.endsWith('.' + cookieDomain)) { return callback(null, true) } callback(new Error(`No CORS allowed from origin ${origin}`)) } }) } }
javascript
{ "resource": "" }
q38088
_getCookieToken
train
function _getCookieToken (cookies, req, cookieName, cookieDomain, publicUrl) { let token = cookies.get(cookieName) if (!token) return null const reqOrigin = req.headers['origin'] const originDomain = reqOrigin && new URL(reqOrigin).host // check that the origin of the request is part of the accepted domain if (reqOrigin && cookieDomain && originDomain !== cookieDomain && !originDomain.endsWith('.' + cookieDomain)) { debug(`A cookie was sent from origin ${reqOrigin} while cookie domain is ${cookieDomain}, ignore it`) return null } // or simply that it is strictly equal to current target if domain is unspecified // in this case we are also protected by sameSite if (reqOrigin && !cookieDomain && reqOrigin !== new URL(publicUrl).origin) { debug(`A cookie was sent from origin ${reqOrigin} while public url is ${publicUrl}, ignore it`) return null } // Putting the signature in a second token is recommended but optional // and we accept full JWT in id_token cooke const signature = cookies.get(cookieName + '_sign') if (signature && (token.match(/\./g) || []).length === 1) { token += '.' + signature } return token }
javascript
{ "resource": "" }
q38089
_setCookieToken
train
function _setCookieToken (cookies, cookieName, cookieDomain, token, payload) { const parts = token.split('.') const opts = { sameSite: 'lax', expires: new Date(payload.exp * 1000) } if (cookieDomain) { opts.domain = cookieDomain // to support subdomains we can't use the sameSite opt // we rely on our manual check of the origin delete opts.sameSite } cookies.set(cookieName, parts[0] + '.' + parts[1], { ...opts, httpOnly: false }) cookies.set(cookieName + '_sign', parts[2], { ...opts, httpOnly: true }) }
javascript
{ "resource": "" }
q38090
_setOrganization
train
function _setOrganization (cookies, cookieName, req, user) { if (!user) return // The order is important. The header can set explicitly on a query even if the cookie contradicts. const organizationId = req.headers['x-organizationid'] || cookies.get(cookieName + '_org') if (organizationId) { user.organization = (user.organizations || []).find(o => o.id === organizationId) if (user.organization) { user.consumerFlag = user.organization.id } else if (organizationId === '' || organizationId.toLowerCase() === 'user') { user.consumerFlag = 'user' } } }
javascript
{ "resource": "" }
q38091
_verifyToken
train
async function _verifyToken (jwksClient, token) { const decoded = jwt.decode(token, { complete: true }) const signingKey = await jwksClient.getSigningKeyAsync(decoded.header.kid) return jwt.verifyAsync(token, signingKey.publicKey || signingKey.rsaPublicKey) }
javascript
{ "resource": "" }
q38092
_decode
train
function _decode (cookieName, cookieDomain, publicUrl) { return (req, res, next) => { // JWT in a cookie = already active session const cookies = new Cookies(req, res) const token = _getCookieToken(cookies, req, cookieName, cookieDomain, publicUrl) if (token) { req.user = jwt.decode(token) _setOrganization(cookies, cookieName, req, req.user) } next() } }
javascript
{ "resource": "" }
q38093
_auth
train
function _auth (privateDirectoryUrl, publicUrl, jwksClient, cookieName, cookieDomain, forceExchange) { return asyncWrap(async (req, res, next) => { // JWT in a cookie = already active session const cookies = new Cookies(req, res) const token = _getCookieToken(cookies, req, cookieName, cookieDomain, publicUrl) if (token) { try { debug(`Verify JWT token from the ${cookieName} cookie`) req.user = await _verifyToken(jwksClient, token) _setOrganization(cookies, cookieName, req, req.user) debug('JWT token from cookie is ok', req.user) } catch (err) { // Token expired or bad in another way.. delete the cookie debug('JWT token from cookie is broken, clear it', err) cookies.set(cookieName, null, { domain: cookieDomain }) cookies.set(cookieName + '_sign', null, { domain: cookieDomain }) // case where the cookies were set before assigning domain if (cookies.get(cookieName)) { cookies.set(cookieName, null) cookies.set(cookieName + '_sign', null) } } } // We have a token from cookie // Does it need to be exchanged to prolongate the session ? if (req.user && req.user.exp) { debug('JWT token from cookie is set to expire on', new Date(req.user.exp * 1000)) const timestamp = Date.now() / 1000 // Token is more than 12 hours old or has less than half an hour left const tooOld = timestamp > (req.user.iat + 43200) const shortLife = timestamp > (req.user.exp - 1800) if (tooOld) debug('The token was issued more than 12 hours ago, exchange it for a new one') if (shortLife) debug('The token will expire in less than half an hour, exchange it for a new one') if (forceExchange) debug('The token was explicitly required to be exchanged (keepalive route), exchange it for a new one') if (tooOld || shortLife || forceExchange) { const exchangedToken = await _exchangeToken(privateDirectoryUrl, token) req.user = await _verifyToken(jwksClient, exchangedToken) _setOrganization(cookies, cookieName, req, req.user) debug('Exchanged token is ok, store it', req.user) _setCookieToken(cookies, cookieName, cookieDomain, exchangedToken, req.user) } } next() }) }
javascript
{ "resource": "" }
q38094
_login
train
function _login (directoryUrl, publicUrl) { return (req, res) => { res.redirect(directoryUrl + '/login?redirect=' + encodeURIComponent(req.query.redirect || publicUrl)) } }
javascript
{ "resource": "" }
q38095
_logout
train
function _logout (cookieName, cookieDomain) { return (req, res) => { const cookies = new Cookies(req, res) cookies.set(cookieName, null, { domain: cookieDomain }) cookies.set(cookieName + '_sign', null, { domain: cookieDomain }) // case where the cookies were set before assigning domain if (cookies.get(cookieName)) { cookies.set(cookieName, null) cookies.set(cookieName + '_sign', null) } res.status(204).send() } }
javascript
{ "resource": "" }
q38096
refineRangeBoundaries
train
function refineRangeBoundaries(range) { let startContainer = range.startContainer, endContainer = range.endContainer, ancestor = range.commonAncestorContainer, goDeeper = true; if (range.endOffset === 0) { while (!endContainer.previousSibling && endContainer.parentNode !== ancestor) { endContainer = endContainer.parentNode; } endContainer = endContainer.previousSibling; } else if (endContainer.nodeType === NODE_TYPE.TEXT_NODE) { if (range.endOffset < endContainer.nodeValue.length) { endContainer.splitText(range.endOffset); } } else if (range.endOffset > 0) { endContainer = endContainer.childNodes.item(range.endOffset - 1); } if (startContainer.nodeType === NODE_TYPE.TEXT_NODE) { if (range.startOffset === startContainer.nodeValue.length) { goDeeper = false; } else if (range.startOffset > 0) { startContainer = startContainer.splitText(range.startOffset); if (endContainer === startContainer.previousSibling) { endContainer = startContainer; } } } else if (range.startOffset < startContainer.childNodes.length) { startContainer = startContainer.childNodes.item(range.startOffset); } else { startContainer = startContainer.nextSibling; } return { startContainer: startContainer, endContainer: endContainer, goDeeper: goDeeper }; }
javascript
{ "resource": "" }
q38097
groupHighlights
train
function groupHighlights(highlights) { let order = [], chunks = {}, grouped = []; highlights.forEach(function (hl) { let timestamp = hl.getAttribute(TIMESTAMP_ATTR); if (typeof chunks[timestamp] === 'undefined') { chunks[timestamp] = []; order.push(timestamp); } chunks[timestamp].push(hl); }); order.forEach(function (timestamp) { let group = chunks[timestamp]; grouped.push({ chunks: group, timestamp: timestamp, toString: function () { return group.map(function (h) { return h.textContent; }).join(''); } }); }); return grouped; }
javascript
{ "resource": "" }
q38098
train
function (nodesToAppend) { let nodes = Array.prototype.slice.call(nodesToAppend); for (let i = 0, len = nodes.length; i < len; ++i) { el.appendChild(nodes[i]); } }
javascript
{ "resource": "" }
q38099
train
function () { if (!el) { return; } if (el.nodeType === NODE_TYPE.TEXT_NODE) { while (el.nextSibling && el.nextSibling.nodeType === NODE_TYPE.TEXT_NODE) { el.nodeValue += el.nextSibling.nodeValue; el.parentNode.removeChild(el.nextSibling); } } else { dom(el.firstChild).normalizeTextNodes(); } dom(el.nextSibling).normalizeTextNodes(); }
javascript
{ "resource": "" }