_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q42400
train
function(size) { size = size || 1; var numChunks = Math.ceil(this.length / size); var result = new Array(numChunks); for (var i = 0, index = 0; i < numChunks; i++) { result[i] = chunkSlice(this, index, index += size); } return result; }
javascript
{ "resource": "" }
q42401
train
function() { var result = []; for (var i = 0; i < this.length; i++) { var value = this[i]; if (Array.isArray(value)) { for (var j = 0; j < value.length; j++) { result.push(value[j]); } } else { result.push(value); } } return result; }
javascript
{ "resource": "" }
q42402
train
function() { var remStartIndex = 0; var numToRemove = 0; for (var i = 0; i < this.length; i++) { var removeCurrentIndex = false; for (var j = 0; j < arguments.length; j++) { if (this[i] === arguments[j]) { removeCurrentIndex = true; break; } } if (removeCurrentIndex) { if (!numToRemove) { remStartIndex = i; } ++numToRemove; } else if (numToRemove) { this.splice(remStartIndex, numToRemove); i -= numToRemove; numToRemove = 0; } } if (numToRemove) { this.splice(remStartIndex, numToRemove); } return this; }
javascript
{ "resource": "" }
q42403
train
function(isSorted) { var result = []; var length = this.length; if (!length) { return result; } result[0] = this[0]; var i = 1; if (isSorted) { for (; i < length; i++) { if (this[i] !== this[i - 1]) { result.push(this[i]); } } } else { for (; i < length; i++) { if (result.indexOf(this[i]) < 0) { result.push(this[i]); } } } return result; }
javascript
{ "resource": "" }
q42404
train
function() { var result = []; next: for (var i = 0; i < this.length; i++) { for (var j = 0; j < arguments.length; j++) { if (this[i] === arguments[j]) { continue next; } } result.push(this[i]); } return result; }
javascript
{ "resource": "" }
q42405
flattenArray
train
function flattenArray(arrayToFlatten, arrayFlatten) { // check if the arg is a array, if not a error is thrown if(!Array.isArray(arrayToFlatten)) throw new Error('Only can flat arrays and you pass a ' + typeof arrayToFlatten) // set the default value of arrayFlatten, this validation is used only in the first call of // recursive function arrayFlatten = arrayFlatten || [] // loop over the array to get flatten the array for (let i = 0; i < arrayToFlatten.length; ++i) { // if the item in the arrray is a array then the flattenArray function is callen again if (Array.isArray(arrayToFlatten[i])) { // the function is called with the element what is a array and pass the arrayFlatten as second arg flattenArray(arrayToFlatten[i], arrayFlatten) // break the loop continue } // if the element is not a array only push the element arrayFlatten.push(arrayToFlatten[i]); } // return the array flatten return arrayFlatten }
javascript
{ "resource": "" }
q42406
nextQuestion
train
function nextQuestion() { if ( !hooks.length ) { if ( !!options.onDone ) { grunt.log.writeln( '' ); grunt.log.writeln( options.onDone.blue ); } done(); } else { var hookConfig = hooks.shift(); promptHook( hookConfig ); } }
javascript
{ "resource": "" }
q42407
actuallyInstallHook
train
function actuallyInstallHook( hookToCopy, whereToPutIt, sourceCanonicalName ) { mkpath.sync( path.join( './', path.dirname( whereToPutIt ) ) ); exec( 'cp ' + hookToCopy + ' ' + whereToPutIt ); grunt.log.writeln( [ 'Installed ', sourceCanonicalName, ' hook in ', whereToPutIt ].join( '' ).green ); }
javascript
{ "resource": "" }
q42408
train
function(e) { var touch = e.touches[0] // Make sure click doesn't fire touchClientX = touch.clientX touchClientY = touch.clientY timestamp = Date.now() }
javascript
{ "resource": "" }
q42409
login
train
function login(){ console.log('Login called'); var username = document.getElementById('login-username').value; var password = document.getElementById('login-password').value; // {username:username, password:password} grout.login('google').then(function (loginInfo){ console.log('successful login:', loginInfo); setStatus(); }, function (err){ console.error('login() : Error logging in:', err); }); }
javascript
{ "resource": "" }
q42410
logout
train
function logout(){ console.log('Logout called'); grout.logout().then(function(){ console.log('successful logout'); setStatus(); }, function (err){ console.error('logout() : Error logging out:', err); }); }
javascript
{ "resource": "" }
q42411
signup
train
function signup(){ console.log('signup called'); var name = document.getElementById('signup-name').value; var username = document.getElementById('signup-username').value; var email = document.getElementById('signup-email').value; var password = document.getElementById('signup-password').value; grout.signup().then(function(){ console.log('successful logout'); setStatus(); }, function(err){ console.error('logout() : Error logging out:', err); }); }
javascript
{ "resource": "" }
q42412
getProjects
train
function getProjects(){ console.log('getProjects called'); grout.Projects.get().then(function(appsList){ console.log('apps list loaded:', appsList); var outHtml = '<h2>No app data</h2>'; if (appsList) { outHtml = '<ul>'; appsList.forEach(function(app){ outHtml += '<li>' + app.name + '</li></br>' }); outHtml += '</ul>'; } document.getElementById("output").innerHTML = outHtml; }); }
javascript
{ "resource": "" }
q42413
getFile
train
function getFile() { var file = grout.Project('test', 'scott').File({key: 'index.html', path: 'index.html'}); console.log('fbUrl', file.fbUrl); console.log('fbRef', file.fbRef); file.get().then(function(app){ console.log('file loaded:', app); document.getElementById("output").innerHTML = JSON.stringify(app); }); }
javascript
{ "resource": "" }
q42414
getUsers
train
function getUsers(){ console.log('getUsers called'); grout.Users.get().then(function(app){ console.log('apps list loaded:', app); document.getElementById("output").innerHTML = JSON.stringify(app); }, function(err){ console.error('Error getting users:', err); }); }
javascript
{ "resource": "" }
q42415
searchUsers
train
function searchUsers(searchStr){ console.log('getUsers called'); if(!searchStr){ searchStr = document.getElementById('search').value; } grout.Users.search(searchStr).then(function(users){ console.log('search users loaded:', users); document.getElementById("search-output").innerHTML = JSON.stringify(users); }); }
javascript
{ "resource": "" }
q42416
write
train
function write(msg, color, prefix) { if (!prefix) prefix = clc.cyan('[conquer]'); // Print each line of the message on its own line. var messages = msg.split('\n'); for (var i = 0; i < messages.length; i++) { var message = messages[i].replace(/(\s?$)|(\n?$)/gm, ''); if (message && message.length > 0) console.log(prefix, color ? color(message) : message); } }
javascript
{ "resource": "" }
q42417
log
train
function log() { var msg = util.format.apply(null, Array.prototype.slice.call(arguments, 0)); write(msg); }
javascript
{ "resource": "" }
q42418
warn
train
function warn() { var msg = util.format.apply(null, Array.prototype.slice.call(arguments, 0)); write(msg, clc.yellow); }
javascript
{ "resource": "" }
q42419
error
train
function error() { var msg = util.format.apply(null, Array.prototype.slice.call(arguments, 0)); write(msg, clc.red); }
javascript
{ "resource": "" }
q42420
scriptLog
train
function scriptLog(script, msg, isError) { write(msg, isError ? clc.red : null, clc.yellow('[' + script + ']')); }
javascript
{ "resource": "" }
q42421
Plugin
train
function Plugin(element, options, jsonData) { // same the DOM element. this.element = element; this.jsonData = jsonData; // merge the options. // the jQuery extend function, the later object will // overwrite the former object. this.options = $.extend({}, defaultOptions, options); // set the plugin name. this._name = pluginName; // call the initialize function. this.init(); }
javascript
{ "resource": "" }
q42422
train
function(options, jsonData) { //console.log(jsonData); var self = this; // remove the existing one. $('#' + self.attrId).empty(); // need merge the options with default options. self.options = $.extend({}, defaultOptions, options); self.jsonData = jsonData; self.init(); }
javascript
{ "resource": "" }
q42423
train
function() { var self = this; var bsExplanation = ''; if(self.options.explanationBuilder) { // call customized explanation builder. bsExplanation = self.options.explanationBuilder(self.attrId); } else { bsExplanation = self.buildDefaultExplanation(self.attrId); } $('body').append(bsExplanation); }
javascript
{ "resource": "" }
q42424
train
function() { var self = this; // calculate the location and offset. // the largest rectangle that can be inscribed in a // circle is a square. // calculate the offset for the center of the chart. var offset = $('#' + self.getGenericId('svg')).offset(); var top = offset['top'] + self.options.diameter / 2; var left = offset['left'] + self.options.diameter / 2; // the center circle's the diameter is a third of the // self.options.diameter. var centerRadius = self.options.diameter / 6; var squareX = Math.sqrt(centerRadius * centerRadius / 2); // top and left for the explanation div. top = top - squareX; left = left - squareX - 25; // the main explanation div. $('#' + self.getGenericId('explanation')) .css('position', 'absolute') .css('text-align', 'center') // The z-index property specifies the z-order of a // positioned element and its descendants. // When elements overlap, z-order determines // which one covers the other. // An element with a larger z-index // generally covers an element with a lower one. // FIXME: seems we need use class to utilize the // -1 z-index, which will help position // the explanation div under the circle. .css('z-index', '-1') // it turns out the bootstrap panel has something // to do with the z-index. // In general the z-index should work fine. //.attr('class', 'bs-explanation') // set the border, most time is for debugging.. .css('border', '0px solid black') .css('width', '180px') .css('top', top + 'px') .css('left', left + 'px'); $('#' + self.getGenericId('pageviews')) .css('font-size', '2.5em') .css('color', '#316395'); $('#' + self.getGenericId('percentage')) .css('font-size', '1.5em') .css('color', '#316395'); $('#' + self.getGenericId('date')) .css('font-weight', 'bold'); $('#' + self.getGenericId('group')) .css('font-weight', 'bold'); }
javascript
{ "resource": "" }
q42425
train
function(p) { var self = this; if (p.depth > 1) p = p.parent; // no children if (!p.children) return; //console.log("zoom in p.value = " + p.value); //console.log("zoom in p.name = " + p.name); self.updateExplanation(p.value, p.name); self.zoom(p, p); }
javascript
{ "resource": "" }
q42426
train
function(pageviews, name) { var self = this; $("#" + self.getGenericId('pageviews')) .text(self.formatNumber(pageviews)); $("#" + self.getGenericId("group")).text(name); var percentage = pageviews / self.totalValue; $("#" + self.getGenericId("percentage")) .text(self.formatPercentage(percentage)); }
javascript
{ "resource": "" }
q42427
train
function(p) { var self = this; if (!p) return; if (!p.parent) return; //console.log("zoom out p.value = " + p.parent.value); //console.log("zoom out p.name = " + p.parent.name); //console.log(p.parent); self.updateExplanation(p.parent.sum, p.parent.name); self.zoom(p.parent, p); }
javascript
{ "resource": "" }
q42428
onFile
train
function onFile(filePath, stat) { if (filePath.match(ignore) || filePath.match(globalIgnore)) { return; } var newTimestamp = updateTimestamp(stat.mtime); if (manifest['CACHE'].insert(toUrl(cleanPath(filePath))) || newTimestamp) { updateListener(manifest); } }
javascript
{ "resource": "" }
q42429
filterPrompts
train
function filterPrompts( PromptAnswers, generator_prompts ) { return filter( generator_prompts, function iteratee( prompt ) { return typeof PromptAnswers.get( prompt.name ) === 'undefined'; } ); }
javascript
{ "resource": "" }
q42430
Through
train
function Through (options, transform, flush) { var self = this if (!(this instanceof Through)) { return new Through(options, transform, flush) } if (typeof options === 'function') { flush = transform transform = options options = {} } options = options || {} Transform.call(this, options) if (typeof transform !== 'function') { transform = function (data) { this.push(data) } } if (typeof flush !== 'function') { flush = null } this._transform = transform this._flush = flush self.on('pipe', function (src) { if (options.passError !== false) { src.on('error', function (err) { self.emit('error', err) }) } }) if (this._transform.length < 3) { this._transform = wrap.transform.call(this, transform) } if (this._flush && this._flush.length < 1) { this._flush = wrap.flush.call(this, flush) } return this }
javascript
{ "resource": "" }
q42431
finishSpec
train
function finishSpec(spec, opts, field) { if (opts.unique) { var keylength = parseInt(opts.unique, 10) ? opts.unique : undefined; if (opts.unique === true && spec.sql.match(/^(text|blob)/i)) { var msg = 'When adding a unique key to an unsized type (text or blob), unique must be set with a length e.g. { unique: 128 }'; throw new Error(msg); } spec.keysql = _.strjoin( _.upcase('unique key'), _.backtick(field), _.paren(_.strjoin( _.backtick(field), _.paren(keylength) )) ); } if (opts['null'] === false || opts.required === true) { spec.sql = _.strjoin(spec.sql, 'NOT NULL'); spec.validators.unshift(Validators.Require); } if (opts['default'] !== undefined) { var defval = opts['default']; var textType = opts.type.match(/blob|text|char|enum|binary/i); spec.sql = _.strjoin( spec.sql, 'DEFAULT', (textType ? _.quote(defval) : defval) ); } return spec; }
javascript
{ "resource": "" }
q42432
pprintSEXP
train
function pprintSEXP(formJson, opts, indentLevel, priorNodeStr) { opts = opts || {}; opts.lbracket = "("; opts.rbracket = ")"; opts.separator = " "; opts.bareSymbols = true; return pprintJSON(formJson, opts, indentLevel, priorNodeStr); }
javascript
{ "resource": "" }
q42433
isQuotedString
train
function isQuotedString(str) { var is = false; if(typeof str === 'string') { var firstChar = str.charAt(0); is = (['"', "'", '`'].indexOf(firstChar) !== -1); } return is; }
javascript
{ "resource": "" }
q42434
stripQuotes
train
function stripQuotes(text) { var sansquotes = text; if(isQuotedString(text)) { if(text.length === 2) { sanquotes = ""; // empty string } else { sansquotes = text.substring(1, text.length-1); // DELETE? sansquotes = unescapeQuotes(sansquotes); } } return sansquotes; }
javascript
{ "resource": "" }
q42435
addQuotes
train
function addQuotes(text, quoteChar) { var withquotes = text; if(!isQuotedString(text)) { var delim = quoteChar && quoteChar.length === 1 ? quoteChar : '"'; withquotes = delim + text + delim; } return withquotes; }
javascript
{ "resource": "" }
q42436
getPixels
train
function getPixels(texture, opts) { var gl = texture.gl if (!gl) throw new Error("must provide gl-texture2d object with a valid 'gl' context") if (!fbo) { var handle = gl.createFramebuffer() fbo = { handle: handle, dispose: dispose, gl: gl } } // make this the current frame buffer gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.handle) // attach the texture to the framebuffer. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture.handle, 0) // check if you can read from this type of texture. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER) if (status !== gl.FRAMEBUFFER_COMPLETE) throw new Error("cannot read GL framebuffer: " + status) opts = opts||{} opts.x = opts.x|0 opts.y = opts.y|0 opts.width = typeof opts.width === 'number' ? opts.width : (texture.shape[0]|0) opts.height = typeof opts.height === 'number' ? opts.height : (texture.shape[1]|0) var array = new Uint8Array(opts.width * opts.height * 4) gl.readPixels(opts.x, opts.y, opts.width, opts.height, gl.RGBA, gl.UNSIGNED_BYTE, array) gl.bindFramebuffer(gl.FRAMEBUFFER, null) return array }
javascript
{ "resource": "" }
q42437
train
function(listsEnabled, lineAttributesEnabled) { if ((!hasList() && !hasLineAttributes) || (!listsEnabled && !lineAttributesEnabled)) { return { lineAttributes: [], inlineAttributeString: rawAttributeString, inlinePlaintext: rawText }; } if (listsEnabled && !lineAttributesEnabled) { if (hasList() && _hasNonlistLineAttributes()) { return { lineAttributes: [], inlineAttributeString: _attributeStringWithoutListAttributes(rawAttributeString), inlinePlaintext: rawText }; } else if (hasList() && !_hasNonlistLineAttributes()){ return { lineAttributes: [], inlineAttributeString: inlineAttributeString, inlinePlaintext: extractedText }; } else if (!hasList() && hasLineAttributes){ return { lineAttributes: [], inlineAttributeString: rawAttributeString, inlinePlaintext: rawText }; } else { console.error("Plugin error: it seems the developer missed a case here."); } } else if (listsEnabled && lineAttributesEnabled) { if (_hasNonlistLineAttributes()) { return { lineAttributes: _withoutListAttributes(lineAttributes), inlineAttributeString: inlineAttributeString, inlinePlaintext: extractedText }; } else { return { lineAttributes: [], inlineAttributeString: inlineAttributeString, inlinePlaintext: extractedText }; } } else if (!listsEnabled && lineAttributesEnabled) { return { lineAttributes: lineAttributes, inlineAttributeString: inlineAttributeString, inlinePlaintext: extractedText }; } else { console.error("Plugin error: it seems the developer missed a case here."); } }
javascript
{ "resource": "" }
q42438
train
function( userID ) { var id = curId; curId++; if( curId == Number.MAX_VALUE ) curId = Number.MIN_VALUE; roomUsers[ id ] = []; return this.setRoomData( id, {} ) .then( this.joinRoom.bind( this, userID, id ) ) .then( function() { return id; }); }
javascript
{ "resource": "" }
q42439
train
function( userID, roomID ) { var userCount; if( roomUsers[ roomID ] === undefined ) { return promise.reject( 'No room with the id: ' + roomID ); } else { var userIDX = roomUsers[ roomID ].indexOf( userID ); if( userIDX != -1 ) { roomUsers[ roomID ].splice( userIDX, 1 ); userCount = roomUsers[ roomID ].length; if( userCount == 0 ) { delete roomUsers[ roomID ]; } return promise.resolve( userCount ); } else { return promise.reject( 'User ' + userID + ' is not in the room: ' + roomID ); } } }
javascript
{ "resource": "" }
q42440
train
function( roomID ) { if( keys.length > 0 ) { var randIdx = Math.round( Math.random() * ( keys.length - 1 ) ), key = keys.splice( randIdx, 1 )[ 0 ]; keyToId[ key ] = roomID; idToKey[ roomID ] = key; return promise.resolve( key ); } else { return promise.reject( 'Run out of keys' ); } }
javascript
{ "resource": "" }
q42441
train
function( roomID, key ) { return this.getRoomIdForKey( key ) .then( function( savedRoomId ) { if( savedRoomId == roomID ) { delete idToKey[ roomID ]; delete keyToId[ key ]; keys.push( key ); return promise.resolve(); } else { return promise.reject( 'roomID and roomID for key do not match' ); } }); }
javascript
{ "resource": "" }
q42442
train
function( key ) { var savedRoomId = keyToId[ key ]; if( savedRoomId ) { return promise.resolve( savedRoomId ); } else { return promise.reject(); } }
javascript
{ "resource": "" }
q42443
train
function( roomID, key, value ) { if( roomData[ roomID ] === undefined ) roomData[ roomID ] = {}; roomData[ roomID ][ key ] = value; return promise.resolve( value ); }
javascript
{ "resource": "" }
q42444
train
function( roomID, key ) { if( roomData[ roomID ] === undefined ) { return promise.reject( 'There is no room by that id' ); } else { return promise.resolve( roomData[ roomID ][ key ] ); } }
javascript
{ "resource": "" }
q42445
train
function( roomID, key ) { var oldVal; if( roomData[ roomID ] === undefined ) { return promise.reject( 'There is no room by that id' ); } else { oldVal = roomData[ roomID ][ key ]; delete roomData[ roomID ][ key ]; return promise.resolve( oldVal ); } }
javascript
{ "resource": "" }
q42446
Tag
train
function Tag(tagDict){ if(!(this instanceof Tag)) return new Tag(tagDict) // Check tagDict has the required fields checkType('String', 'tagDict.key', tagDict.key, {required: true}); checkType('String', 'tagDict.value', tagDict.value, {required: true}); // Init parent class Tag.super_.call(this, tagDict) // Set object properties Object.defineProperties(this, { key: { writable: true, enumerable: true, value: tagDict.key }, value: { writable: true, enumerable: true, value: tagDict.value } }) }
javascript
{ "resource": "" }
q42447
readJSON
train
function readJSON(filepath){ var buffer = {}; try{ buffer = JSON.parse(fs.readFileSync(filepath, { encoding:'utf8' })); } catch(error){} return buffer; }
javascript
{ "resource": "" }
q42448
readYAML
train
function readYAML(filepath){ var buffer = {}; try{ buffer = YAML.safeLoad(fs.readFileSync(filepath, { schema:YAML.DEFAULT_FULL_SCHEMA })); }catch(error){ console.error(error); } return buffer; }
javascript
{ "resource": "" }
q42449
createMultitasks
train
function createMultitasks(gulp, aliases){ for(var task in aliases){ if(aliases.hasOwnProperty(task)){ var cmds = []; aliases[task].forEach(function(cmd){ cmds.push(cmd); }); gulp.task(task, cmds); } } return aliases; }
javascript
{ "resource": "" }
q42450
filterFiles
train
function filterFiles(gulp, options, taskFile){ var ext = path.extname(taskFile); if(/\.(js|coffee)$/i.test(ext)){ createTask(gulp, options, taskFile); }else if(/\.(json)$/i.test(ext)){ createMultitasks(gulp, require(taskFile)); }else if(/\.(ya?ml)$/i.test(ext)){ createMultitasks(gulp, readYAML(taskFile)); } }
javascript
{ "resource": "" }
q42451
loadGulpConfig
train
function loadGulpConfig(gulp, options){ options = Object.assign({ data:{} }, options); options.dirs = isObject(options.dirs) ? options.dirs : {}; options.configPath = isString(options.configPath) ? options.configPath : 'tasks'; glob.sync(options.configPath, { realpath:true }).forEach(filterFiles.bind(this, gulp, options)); loadGulpConfig.util.dir = rgdirs(options.dirs); }
javascript
{ "resource": "" }
q42452
setAfter
train
function setAfter (pipes, ai, bi) { // console.log(' move %s => %s', ai, bi); var ap = pipes[ai]; pipes.splice(ai, 1); pipes.splice(bi, 0, ap); }
javascript
{ "resource": "" }
q42453
setBefore
train
function setBefore (pipes, ai, bi) { // console.log(' move %s => %s', ai, bi); var ap = pipes[ai]; pipes.splice(ai, 1); pipes.splice(bi, 0, ap); }
javascript
{ "resource": "" }
q42454
arity
train
function arity(cmd, args, info, sub) { var subcommand = sub !== undefined; // command validation decorated the info var def = sub || info.command.def , expected = def.arity , first = def.first , last = def.last , step = def.step , min = Math.abs(expected) , max // account for command, redis includes command // in the arity , count = args.length + 1; //console.dir(def); // only command is allowed - zero args (COMMAND etc) if(expected === 0 && first === 0 && last === 0) { min = max = 1; // positive fixed args length (TYPE etc) }else if(expected > 0) { min = max = expected; // variable length arguments (MGET/MSET etc) }else{ max = Number.MAX_VALUE; // test for step if(step > 1 && (args.length % step !== 0)) { throw new CommandArgLength(cmd); } } // made it this far, check subcommands // for commands that require a subcommand if(!subcommand && Constants.SUBCOMMAND[cmd] && args.length && arity !== 1) { sub = Constants.SUBCOMMAND[cmd][args[0]]; arity(args[0], args.slice(1), info, sub); }else if(count < min || count > max) { if(subcommand) throw UnknownSubcommand; throw new CommandArgLength(cmd); } return true; }
javascript
{ "resource": "" }
q42455
createGenerateDocs
train
function createGenerateDocs(inPath, outPath) { if (!inPath) { throw new Error('Input path(s) argument is required'); } if (!outPath) { throw new Error('Output path argument is required'); } const jsDocConfig = { opts: { destination: outPath, }, }; return function generateDocs(done) { gulp.src(inPath, { read: false }) .pipe(jsdoc(jsDocConfig, done)); }; }
javascript
{ "resource": "" }
q42456
Feedsme
train
function Feedsme(opts) { if (!this) new Feedsme(opts); // eslint-disable-line no-new if (typeof opts === 'string') { this.base = opts; } else if (opts.protocol && opts.href) { this.base = url.format(opts); } else if (opts.url || opts.uri) { this.base = opts.url || opts.uri; } else { throw new Error('Feedsme URL required'); } this.version = (opts.version === '1' || opts.version === 'v1' || opts.version === 1) ? '' : 'v2'; // // Handle all possible cases // this.base = typeof this.base === 'object' ? url.format(this.base) : this.base; this.agent = opts.agent; this.retry = opts.retry; }
javascript
{ "resource": "" }
q42457
validateBody
train
function validateBody(err, body) { body = tryParse(body); if (err || !body) { return next(err || new Error('Unparsable response with statusCode ' + statusCode)); } if (statusCode !== 200) { return next(new Error(body.message || 'Invalid status code ' + statusCode)); } next(null, body); }
javascript
{ "resource": "" }
q42458
AsLate
train
function AsLate(arg, u, ments) { this.args = arg + u + ments; this.started = false; }
javascript
{ "resource": "" }
q42459
getObjectClassname
train
function getObjectClassname (listener) { if (!listener) return DEFAULT_LISTENER; if (typeof listener === 'string') return listener; var constr = listener.constructor; return constr.name || constr.toString().split(/ |\(/, 2)[1]; }
javascript
{ "resource": "" }
q42460
SansServer
train
function SansServer(configuration) { if (!(this instanceof SansServer)) return new SansServer(configuration); const config = configuration && typeof configuration === 'object' ? Object.assign(configuration) : {}; config.logs = config.hasOwnProperty('logs') ? config.logs : true; config.rejectable = config.hasOwnProperty('rejectable') ? config.rejectable : false; config.timeout = config.hasOwnProperty('timeout') && !isNaN(config.timeout) && config.timeout >= 0 ? config.timeout : 30; config.useBuiltInHooks = config.hasOwnProperty('useBuiltInHooks') ? config.useBuiltInHooks : true; const hooks = {}; const keys = {}; const runners = { symbols: {}, types: {} }; const server = this; /** * Define a hook that is applied to all requests. * @param {string} type * @param {number} [weight=0] * @param {...function} hook * @returns {SansServer} */ this.hook = addHook.bind(server, hooks); /** * Define a hook runner and get back a Symbol that is used to execute the hooks. * @name SansServer#hook.define * @function * @param {string} type * @returns {Symbol} */ this.hook.define = type => defineHookRunner(runners, type); /** * Get the hook type for a specific symbol. * @name SansServer#hook.type * @function * @param {Symbol} key The symbol to use to get they type. * @returns {string} */ this.hook.type = key => runners.symbols[key]; /** * Have the server execute a request. * @param {object|string} [req={}] An object that has request details or a string that is a GET endpoint. * @param {function} [callback] The function to call once the request has been processed. * @returns {Request} * @listens Request#log */ this.request = (req, callback) => request(server, config, hooks, keys, req, callback); /** * Specify a middleware to use. * @param {...Function} middleware * @throws {Error} * @returns {SansServer} */ this.use = this.hook.bind(this, 'request', 0); // define the request and response hooks keys.request = this.hook.define('request'); keys.response = this.hook.define('response'); // set request hooks if (config.timeout) this.hook('request', Number.MIN_SAFE_INTEGER + 10, timeout(config.timeout)); if (config.useBuiltInHooks) this.hook('request', -100000, validMethod); // set response hooks if (config.useBuiltInHooks) this.hook('response', -100000, transform); }
javascript
{ "resource": "" }
q42461
addHook
train
function addHook(hooks, type, weight, hook) { const length = arguments.length; let start = 2; if (typeof type !== 'string') { const err = Error('Expected first parameter to be a string. Received: ' + type); err.code = 'ESHOOK'; throw err; } // handle variable input parameters if (typeof arguments[2] === 'number') { start = 3; } else { weight = 0; } if (!hooks[type]) hooks[type] = []; const store = hooks[type]; for (let i = start; i < length; i++) { const hook = arguments[i]; if (typeof hook !== 'function') { const err = Error('Invalid hook specified. Expected a function. Received: ' + hook); err.code = 'ESHOOK'; throw err; } store.push({ weight: weight, hook: hook }); } return this; }
javascript
{ "resource": "" }
q42462
defineHookRunner
train
function defineHookRunner(runners, type) { if (runners.types.hasOwnProperty(type)) { const err = Error('There is already a hook runner defined for this type: ' + type); err.code = 'ESHOOK'; throw err; } const s = Symbol(type); runners.types[type] = s; runners.symbols[s] = type; return s; }
javascript
{ "resource": "" }
q42463
request
train
function request(server, config, hooks, keys, request, callback) { const start = Date.now(); if (typeof request === 'function' && typeof callback !== 'function') { callback = request; request = {}; } // handle argument variations and get Request instance const args = Array.from(arguments).slice(4).filter(v => v !== undefined); const req = (function() { const length = args.length; if (length === 0) { return new Request(server, keys, config.rejectable); } else if (length === 1 && typeof args[0] === 'function') { callback = args[0]; return new Request(server, keys, config.rejectable); } else { return new Request(server, keys, config.rejectable, request); } })(); // event log aggregation const queue = config.logs ? [] : null; if (queue) req.on('log', event => queue.push(event)); // if logging enabled then produce the log when the request is fulfilled or rejected if (queue) { const log = function(state) { const events = queue.map((event, index) => { const seconds = util.seconds(event.timestamp - (index > 0 ? queue[index - 1].timestamp : start)); return '[+' + seconds + 's] ' + event.category + ':' + event.type + ' ' + event.data; }); console.log(state.statusCode + ' ' + req.method + ' ' + req.url + (state.statusCode === 302 ? '\n Redirect To: ' + state.headers['location'] : '') + '\n ID: ' + req.id + '\n Start: ' + new Date(start).toISOString() + '\n Duration: ' + prettyPrint.seconds(Date.now() - start) + '\n Events:\n ' + events.join('\n ')); }; req.then(log, () => log(req.res.state)); } // copy hooks into request req.log('initialized'); Object.keys(hooks).forEach(type => { hooks[type].forEach(d => { req.hook(type, d.weight, d.hook) }); }); req.log('hooks applied'); // is using a callback paradigm then execute the callback if (typeof callback === 'function') req.then(state => callback(null, state), err => callback(err, req.res.state)); return req; }
javascript
{ "resource": "" }
q42464
timeout
train
function timeout(seconds) { return function timeoutSet(req, res, next) { const timeoutId = setTimeout(() => { if (!res.sent) res.sendStatus(504) }, 1000 * seconds); req.hook('response', Number.MAX_SAFE_INTEGER - 1000, function timeoutClear(req, res, next) { clearTimeout(timeoutId); next(); }); next(); }; }
javascript
{ "resource": "" }
q42465
transform
train
function transform(req, res, next) { const state = res.state; const body = state.body; const type = typeof body; const isBuffer = body instanceof Buffer; let contentType; // error conversion if (body instanceof Error) { res.log('transform', 'Converting Error to response'); res.status(500).body(httpStatus[500]).set('content-type', 'text/plain'); // buffer conversion } else if (isBuffer) { res.log('transform', 'Converting Buffer to base64 string'); res.body(body.toString('base64')); contentType = 'application/octet-stream'; // object conversion } else if (type === 'object') { res.log('transform', 'Converting object to JSON string'); res.body(JSON.stringify(body)); contentType = 'application/json'; // not string conversion } else if (type !== 'string') { res.log('transform', 'Converting ' + type + ' to string'); res.body(String(body)); contentType = 'text/plain'; } else { contentType = 'text/html'; } // set content type if not yet set if (!state.headers.hasOwnProperty('content-type') && contentType) { res.log('transform', 'Set content type'); res.set('Content-Type', contentType); } next(); }
javascript
{ "resource": "" }
q42466
validMethod
train
function validMethod(req, res, next) { if (httpMethods.indexOf(req.method) === -1) { res.sendStatus(405); } else { next(); } }
javascript
{ "resource": "" }
q42467
train
function (name) { if (!this.instances[name]) { this.instances[name] = DevFixturesModel.create({name: name}); } return this.instances[name]; }
javascript
{ "resource": "" }
q42468
sliceOf
train
function sliceOf(ars, i, parts) { return ars.slice( Math.floor(i/parts*ars.length), Math.floor((i+1)/parts*ars.length)); }
javascript
{ "resource": "" }
q42469
train
function(className, viewArgs) { var self = this, view = this.views[className], dfd = $.Deferred(); if (view) { view.undelegateEvents(); } this.loader.load(className) .then(function(Constructor) { viewArgs.manager = self; view = new Constructor(viewArgs); self.views[className] = view; dfd.resolve(view); }); return dfd.promise(); }
javascript
{ "resource": "" }
q42470
Directive
train
function Directive(filename, directiveArguments) { this.filename = filename; this.name = directiveArguments[0].value; var directiveConfiguration = directiveArguments[1]; // Extract the last attribute of the array if (directiveConfiguration.type === 'ArrayExpression' && directiveConfiguration.elements.length) { directiveConfiguration = directiveConfiguration.elements[directiveConfiguration.elements.length - 1]; } // Parse the function if (directiveConfiguration && directiveConfiguration.type === 'FunctionExpression') { directiveConfiguration = esprimaHelper.getFirstReturnStatement(directiveConfiguration); } // Get the returnStatement if (directiveConfiguration && directiveConfiguration.type === 'ReturnStatement') { directiveConfiguration = directiveConfiguration.argument; } // Parse the object if (directiveConfiguration && directiveConfiguration.type === 'ObjectExpression') { var properties = esprimaHelper.parseObjectExpressions(directiveConfiguration); this.replace = !!properties.replace; this.transclude = !!properties.transclude; this.template = properties.template; this.templateUrl = properties.templateUrl; if (properties.restrict) { this.restrict = { A: properties.restrict.toUpperCase().indexOf('A') >= 0, E: properties.restrict.toUpperCase().indexOf('E') >= 0, C: properties.restrict.toUpperCase().indexOf('C') >= 0 }; } } // Add parse warning if (!this.restrict) { module.exports.logger('no restriction set for', this.filename, this.name); this.restrict = { A: true, E: false, C: false }; } }
javascript
{ "resource": "" }
q42471
parseAst
train
function parseAst(filename, ast) { var directives = []; esprimaHelper.traverse(ast, function (node) { var calleeExpressionName = esprimaHelper.getCallExpressionName(node); if (calleeExpressionName === 'directive') { var directiveArguments = node['arguments'] || []; if (directiveArguments.length >= 2 && directiveArguments[0].type === 'Literal') { directives.push(new Directive(filename, directiveArguments)); } } }); return directives; }
javascript
{ "resource": "" }
q42472
parseFile
train
function parseFile(filename, code) { if (/directive/.test(code)) { return ngDirectiveParser.parseAst(filename, esprima.parse(code)); } return []; }
javascript
{ "resource": "" }
q42473
connStr
train
function connStr(conn) { var conf = mergeDefaults(conn); var connString = conf.driver + '://' + conf.username + (conf.password ? ':' + conf.password : '') + '@' + conf.host + (conf.port ? ':' + conf.port : '') + '/' + conf.database; return connString; }
javascript
{ "resource": "" }
q42474
createPool
train
function createPool(conn) { var conf = connectionConfig[conn.app][conn.env]; conf.connStr = connStr(conn); console.log('Creating pool to : ' + conf.connStr); // Create the pool on the conf object for easy future access conf.pool = anydb.createPool(conf.connStr, { min: conf.min, max: conf.max, onConnect: function (conn, done) { done(null, conn); }, reset: function (conn, done) { done(null); } }); // Remember all connection pools for easy termination pools.push(conf.pool); return conf.pool; }
javascript
{ "resource": "" }
q42475
parseML
train
function parseML(memberLog, required) { return memberLog.map(member => { const cloned = clone(member); const key = Reflect.ownKeys(cloned)[0]; const value = cloned[key]; cloned[key] = value.filter(elem => (elem !== required)); return cloned; }); }
javascript
{ "resource": "" }
q42476
addSourceInfoToML
train
function addSourceInfoToML(memberLog, source) { let cloned = memberLog.slice(); for (const [key, value] of getIterableObjectEntries(source)) { if (Talent.typeCheck(value)) { cloned = addSourceInfoToML(cloned, value); } const foundAndCloned = clone(findWhereKey(cloned, key)); if (!foundAndCloned && !Talent.typeCheck(value)) { cloned.push({[key]: [value]}); } else if (!Talent.typeCheck(value)) { foundAndCloned[key].push(value); } } return cloned; }
javascript
{ "resource": "" }
q42477
translate
train
function translate(content, langFile) { return content.replace(templateRegEx, function (match, capture) { return (0, _lodash2.default)(langMap.get(langFile), capture); }); }
javascript
{ "resource": "" }
q42478
train
function (promise) { var targets = this._targets; targets.push(promise); promise['catch']( function() { return true; } ).then( function() { targets.splice(targets.indexOf(promise), 1); } ); return Notifier.decorate(promise); }
javascript
{ "resource": "" }
q42479
train
function (type) { var targets = this._targets.slice(), known = {}, args = arguments.length > 1 && toArray(arguments, 1, true), target, subs, i, j, jlen, guid, callback; // Add index 0 and 1 entries for use in Y.bind.apply(Y, args) below. // Index 0 will be set to the callback, and index 1 will be left as null // resulting in Y.bind.apply(Y, [callback, null, arg0,...argN]) if (args) { args.unshift(null, null); } // Breadth-first notification order, mimicking resolution order // Note: Not caching a length comparator because this pushes to the end // of the targets array as it iterates. for (i = 0; i < targets.length; ++i) { target = targets[i]; if (targets[i]._evts) { // Not that this should ever happen, but don't push known // promise targets onto the list again. That would make for an // infinite loop guid = Y.stamp(targets[i]); if (known[guid]) { continue; } known[guid] = 1; // Queue any child promises to get notified targets.push.apply(targets, targets[i]._evts.targets); // Notify subscribers subs = target._evts.subs[type]; if (subs) { for (j = 0, jlen = subs.length; j < jlen; ++j) { callback = subs[j]; if (args) { args[0] = callback; callback = Y.bind.apply(Y, args); } // Force async to mimic resolution lifecycle, and // each callback in its own event loop turn to // avoid swallowing errors and errors breaking the // current js thread. // TODO: would synchronous notifications be better? Y.soon(callback); } } } } return this; }
javascript
{ "resource": "" }
q42480
train
function(anchornode) { var valid = (anchornode.get('tagName')==='A') && anchornode.getAttribute('data-pjax-mojit'), attributes, i, parheader; if (valid) { attributes = { 'data-pjax-mojit': anchornode.getAttribute('data-pjax-mojit'), 'data-pjax-action': anchornode.getAttribute('data-pjax-action'), 'data-pjax-container': anchornode.getAttribute('data-pjax-container'), 'data-pjax-preload': anchornode.getAttribute('data-pjax-preload') }; i = 0; /*jshint boss:true */ while (parheader=anchornode.getAttribute('data-pjax-par'+(++i))) { attributes['data-pjax-par'+i] = parheader; } /*jshint boss:false */ Y.fire(EVT_PJAX, {uri: anchornode.getAttribute('href'), targetid: anchornode.get('id'), attributes: attributes, fromhistorychange: false}); } }
javascript
{ "resource": "" }
q42481
_getRef
train
function _getRef (refOrQuery) { if (typeof refOrQuery.ref === 'function') { refOrQuery = refOrQuery.ref() } else if (typeof refOrQuery.ref === 'object') { refOrQuery = refOrQuery.ref } return refOrQuery }
javascript
{ "resource": "" }
q42482
createRecord
train
function createRecord (snapshot) { var value = snapshot.val() var res = isObject(value) ? value : { '.value': value } res['.key'] = _getKey(snapshot) return res }
javascript
{ "resource": "" }
q42483
indexForKey
train
function indexForKey (array, key) { for (var i = 0; i < array.length; i++) { if (array[i]['.key'] === key) { return i } } /* istanbul ignore next */ return -1 }
javascript
{ "resource": "" }
q42484
bind
train
function bind (vm, key, source) { var asObject = false var cancelCallback = null var readyCallback = null // check { source, asArray, cancelCallback } syntax if (isObject(source) && source.hasOwnProperty('source')) { asObject = source.asObject cancelCallback = source.cancelCallback readyCallback = source.readyCallback source = source.source } if (!isObject(source)) { throw new Error('VueWild: invalid Wilddog binding source.') } var ref = _getRef(source) vm.$wilddogRefs[key] = ref vm._wilddogSources[key] = source if (cancelCallback) { cancelCallback = cancelCallback.bind(vm) } // bind based on initial value type if (asObject) { bindAsObject(vm, key, source, cancelCallback) } else { bindAsArray(vm, key, source, cancelCallback) } if (readyCallback) { source.once('value', readyCallback.bind(vm)) } }
javascript
{ "resource": "" }
q42485
defineReactive
train
function defineReactive (vm, key, val) { if (key in vm) { vm[key] = val } else { Vue.util.defineReactive(vm, key, val) } }
javascript
{ "resource": "" }
q42486
bindAsArray
train
function bindAsArray (vm, key, source, cancelCallback) { var array = [] defineReactive(vm, key, array) var onAdd = source.on('child_added', function (snapshot, prevKey) { var index = prevKey ? indexForKey(array, prevKey) + 1 : 0 array.splice(index, 0, createRecord(snapshot)) }, cancelCallback) var onRemove = source.on('child_removed', function (snapshot) { var index = indexForKey(array, _getKey(snapshot)) array.splice(index, 1) }, cancelCallback) var onChange = source.on('child_changed', function (snapshot) { var index = indexForKey(array, _getKey(snapshot)) array.splice(index, 1, createRecord(snapshot)) }, cancelCallback) var onMove = source.on('child_moved', function (snapshot, prevKey) { var index = indexForKey(array, _getKey(snapshot)) var record = array.splice(index, 1)[0] var newIndex = prevKey ? indexForKey(array, prevKey) + 1 : 0 array.splice(newIndex, 0, record) }, cancelCallback) vm._wilddogListeners[key] = { child_added: onAdd, child_removed: onRemove, child_changed: onChange, child_moved: onMove } }
javascript
{ "resource": "" }
q42487
bindAsObject
train
function bindAsObject (vm, key, source, cancelCallback) { defineReactive(vm, key, {}) var cb = source.on('value', function (snapshot) { vm[key] = createRecord(snapshot) }, cancelCallback) vm._wilddogListeners[key] = { value: cb } }
javascript
{ "resource": "" }
q42488
unbind
train
function unbind (vm, key) { var source = vm._wilddogSources && vm._wilddogSources[key] if (!source) { throw new Error( 'VueWild: unbind failed: "' + key + '" is not bound to ' + 'a Wilddog reference.' ) } var listeners = vm._wilddogListeners[key] for (var event in listeners) { source.off(event, listeners[event]) } vm[key] = null vm.$wilddogRefs[key] = null vm._wilddogSources[key] = null vm._wilddogListeners[key] = null }
javascript
{ "resource": "" }
q42489
ensureRefs
train
function ensureRefs (vm) { if (!vm.$wilddogRefs) { vm.$wilddogRefs = Object.create(null) vm._wilddogSources = Object.create(null) vm._wilddogListeners = Object.create(null) } }
javascript
{ "resource": "" }
q42490
getRequireNameForPackage
train
function getRequireNameForPackage(pkgName) { if (this.options.rename[pkgName]) { return this.options.rename[pkgName]; } var requireName = pkgName.replace(this.options.replaceExp, ''); return this.options.camelize ? camelize(requireName) : requireName; }
javascript
{ "resource": "" }
q42491
ReadArray
train
function ReadArray (options, array) { if (!(this instanceof ReadArray)) { return new ReadArray(options, array) } if (Array.isArray(options)) { array = options options = {} } options = Object.assign({}, options) Readable.call(this, options) this._array = array || [] this._cnt = this._array.length return this }
javascript
{ "resource": "" }
q42492
select
train
function select(rule, prefix) { return rule.selectors && rule.selectors[0] && rule.selectors[0].indexOf(prefix) === 0; }
javascript
{ "resource": "" }
q42493
assertKeys
train
function assertKeys (routes) { Object.keys(routes).forEach(function (route) { assert.ok(meths.indexOf(route) !== -1, route + ' is an invalid method') }) }
javascript
{ "resource": "" }
q42494
getQueryResponse
train
function getQueryResponse(url) { var response; if (options.stopQueryParam) { var parsedUrl = parseUrl(url, true); if (parsedUrl.query && parsedUrl.query[options.stopQueryParam]) { var queryResponse = parseInt(parsedUrl.query[options.stopQueryParam]); if (queryResponse > 1) { response = queryResponse; } } } return response; }
javascript
{ "resource": "" }
q42495
engine
train
function engine(url) { var ret; var parts = /^(\w+):/.exec(url); if (!parts) { d.fatal("Invalid engine URI", url); } try { var Engine = angular.injector(['ng', 'coa.store']).get('Engine' + parts[1].ucfirst()); ret = new Engine(url); } catch(e) { d.fatal("Unable to instantiate engine for URI", url, e); } d('STORE', 'Creating an engine for URI', url, ':', ret); return ret; }
javascript
{ "resource": "" }
q42496
getEngine
train
function getEngine(name) { if (!dbconfig.has(name)) { d.fatal("Trying to access data storage that is not configured:", name); } var conf = dbconfig.get(name); if (!conf.engine) { conf.engine = engine(conf.url); } return conf.engine; }
javascript
{ "resource": "" }
q42497
runDriver
train
function runDriver(location, driver, options) { options.testComplete = options.testComplete || 'return window.TESTS_COMPLETE'; options.testPassed = options.testPassed || 'return window.TESTS_PASSED && !window.TESTS_FAILED'; var startTime = Date.now(); var jobInfo = { name: options.name, build: process.env.TRAVIS_JOB_ID }; Object.keys(options.jobInfo || {}).forEach(function (key) { jobInfo[key] = options.jobInfo[key]; }); return Promise.resolve(null).then(function () { return retry(function () { return driver.sauceJobUpdate(jobInfo); }, 3, '500ms', {debug: options.debug}) }).then(function () { return retry(function () { return driver.browser().activeWindow().navigator().navigateTo(location.url) }, 3, '500ms', {debug: options.debug}).catch(err => { err.message += ' (while navigating to url)'; throw err; }); }).then(function () { return waitForJobToFinish(driver, { allowExceptions: options.allowExceptions, testComplete: options.testComplete, timeout: options.timeout, debug: options.debug }); }).then(function () { return retry(function () { if (typeof options.testPassed === 'string') { return driver.browser().activeWindow().execute(options.testPassed); } else { return Promise.resolve(options.testPassed(driver)); } }, 5, '500ms', {debug: options.debug}); }).then(function (result) { result = {passed: result, duration: Date.now() - startTime}; return retry(function () { return driver.dispose({passed: result.passed}); }, 5, {debug: options.debug}).then(function () { return result; }); }, function (err) { err.duration = Date.now() - startTime; return retry(function () { return driver.dispose({passed: false}); }, 2, {debug: options.debug}).then(function () { throw err; }, function () { throw err; }); }); }
javascript
{ "resource": "" }
q42498
mergeAttributes
train
function mergeAttributes( target, source ) { const propNames = Object.keys( source ); for ( let i = 0, numNames = propNames.length; i < numNames; i++ ) { const name = propNames[i]; const attribute = source[name]; switch ( typeof attribute ) { case "object" : if ( attribute ) { break; } // falls through default : throw new TypeError( `invalid definition of attribute named "${name}": must be object` ); } target[name] = attribute; } }
javascript
{ "resource": "" }
q42499
mergeComputeds
train
function mergeComputeds( target, source ) { const propNames = Object.keys( source ); for ( let i = 0, numNames = propNames.length; i < numNames; i++ ) { const name = propNames[i]; const computer = source[name]; switch ( typeof computer ) { case "function" : break; default : throw new TypeError( `invalid definition of computed attribute named "${name}": must be a function` ); } target[name] = computer; } }
javascript
{ "resource": "" }