_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q43700
train
function (files, callback) { //loop on all files and write them async.each(files, function (fileObj, mCb) { var data = swagger.cloneObj(fileObj.data); //if tokens, replace all occurences with corresponding values if (fileObj.tokens) { for (var i in fileObj.tokens) { var regexp = new RegExp("%" + i + "%", "g"); data = data.replace(regexp, fileObj.tokens[i]); } } if (fileObj.purify) { data = data.replace(/\\"/g, '"').replace(/["]+/g, '"').replace(/"__dirname/g, '__dirname'); data = data.replace(/("group": "__empty__")/g, '"group": ""'); data = data.replace(/("prefix": "(\s?|\s+),)/g, '"prefix": "",'); data = data.replace(/("l": "__empty__")/g, '"l": ""'); //"__dirname + \"/lib/mw/_get.js\"" //"__dirname + "/lib/mw/_get.js"" //"__dirname + "/lib/mw/_get.js" //__dirname + "/lib/mw/_get.js" } console.log("creating file:", fileObj.file); fs.writeFile(fileObj.file, data, "utf8", mCb); }, function (error) { if (error) { return callback({"code": 854, "msg": error.message}); } return callback(null, true); }); }
javascript
{ "resource": "" }
q43701
train
function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this.testCategory = name; return construct(original, args); }
javascript
{ "resource": "" }
q43702
createWordNode
train
function createWordNode (item) { var wordNode = parser.createParentNode('Word') if (options && options.pos) { wordNode.data = item } var textNode = parser.createTextNode('Text', item.surface_form) parser.add(textNode, wordNode) return wordNode }
javascript
{ "resource": "" }
q43703
createTextNode
train
function createTextNode (type, item) { var node = parser.createTextNode(type, item.surface_form) if (options && options.pos) { node.data = item } return node }
javascript
{ "resource": "" }
q43704
XError
train
function XError(/*code, message, data, privateData, cause*/) { if (Error.captureStackTrace) Error.captureStackTrace(this, this); else this.stack = new Error().stack; var code, message, data, cause, privateData; for(var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if(XError.isXError(arg) || arg instanceof Error) { if(cause !== undefined) { data = cause; } cause = arg; } else if(typeof arg === 'string' || typeof arg === 'number') { if(typeof arg !== 'string') arg = '' + arg; if(code === undefined && arg.indexOf(' ') == -1) code = arg; else if(message === undefined) message = arg; else if(data === undefined) data = arg; else if(privateData === undefined) privateData = arg; else if(cause === undefined) cause = new Error(arg); } else if(arg === null || arg === undefined) { if(code === undefined) code = null; else if(message === undefined) message = null; else if(data === undefined) data = null; else if(privateData === undefined) privateData = null; else if(cause === undefined) cause = null; } else { if(data === undefined) data = arg; else if(privateData === undefined) privateData = arg; } } code = code || (cause && cause.code) || XError.INTERNAL_ERROR; message = message || (cause && cause.message); if(code) { var errorCodeInfo = registry.getErrorCode(code); if(errorCodeInfo) { if(errorCodeInfo.code) code = errorCodeInfo.code; // in case of aliased error codes if(!message && errorCodeInfo.message) message = errorCodeInfo.message; } } this.code = code; this.message = message || 'An error occurred'; this.data = data; this.privateData = privateData; this.cause = cause; this.name = 'XError'; Object.defineProperty(this, '_isXError', { configurable: false, enumerable: false, writable: false, value: true }); }
javascript
{ "resource": "" }
q43705
cpuAverage
train
function cpuAverage() { //Initialise sum of idle and time of cores and fetch CPU info var totalIdle = 0, totalTick = 0; var cpus = os.cpus(); //Loop through CPU cores for(var i = 0, len = cpus.length; i < len; i++) { //Select CPU core var cpu = cpus[i]; //Total up the time in the cores tick for(type in cpu.times) { totalTick += cpu.times[type]; } //Total up the idle time of the core totalIdle += cpu.times.idle; } //Return the average Idle and Tick times return {idle: totalIdle / cpus.length, total: totalTick / cpus.length}; }
javascript
{ "resource": "" }
q43706
train
function(r, g, b, a) { var rnum = typeof r === "number"; if (rnum && typeof g === "number" && typeof b === "number") { //default alpha to one a = typeof a === "number" ? a : 1.0; } else { r = g = b = a = rnum ? r : 1.0; } if (this.premultiplied) { r *= a; g *= a; b *= a; } this.color = colorToFloat( ~~(r * 255), ~~(g * 255), ~~(b * 255), ~~(a * 255) ); }
javascript
{ "resource": "" }
q43707
ParseJapaneseBasic
train
function ParseJapaneseBasic (file, options) { var offset = 0 var line = 1 var column = 1 var position if (!(this instanceof ParseJapaneseBasic)) { return new ParseJapaneseBasic(file, options) } if (file && file.message) { this.file = file } else { options = file } position = options && options.position if (position !== null && position !== undefined) { this.position = Boolean(position) } this.offset = offset this.line = line this.column = column }
javascript
{ "resource": "" }
q43708
ParamedicRunner
train
function ParamedicRunner(_platformId,_plugins,_callback,bJustBuild,nPort,msTimeout,browserify,bSilent,bVerbose,platformPath) { this.tunneledUrl = ""; this.port = nPort; this.justBuild = bJustBuild; this.plugins = _plugins; this.platformId = _platformId; this.callback = _callback; this.tempFolder = null; this.timeout = msTimeout; this.verbose = bVerbose; this.platformPath = platformPath; if(browserify) { this.browserify = "--browserify"; } else { this.browserify = ''; } if(bSilent) { var logOutput = this.logOutput = []; this.logMessage = function(msg) { logOutput.push(msg); }; } else { this.logMessage = function(msg) { console.log(msg); }; } }
javascript
{ "resource": "" }
q43709
findImports
train
function findImports(filePath, result) { var importPaths = getImportPaths(filePath); var importPathsAbs = resolveImportPaths(filePath, importPaths); if( importPathsAbs.length ) result.full[filePath] = importPathsAbs; importPathsAbs.forEach(function(path){ if (result.simple.indexOf(path) === -1) { result.simple.push(path); findImports(path, result); } }); return result; }
javascript
{ "resource": "" }
q43710
getImportPaths
train
function getImportPaths(filePath){ var importPaths = []; try{ var contents = fs.readFileSync(filePath).toString('utf8'); importPaths = parseImpt(contents); } catch(exception){} return importPaths; }
javascript
{ "resource": "" }
q43711
updatePosition
train
function updatePosition(instance, tetherBounds) { const x = tetherBounds.x + (instance.horizontalAlignment === HORIZONTAL_ALIGN.LEFT ? 0 : tetherBounds.width) const y = tetherBounds.y + (instance.verticalAlignment === VERTICAL_ALIGN.TOP ? 0 : tetherBounds.height) if (transformsSupported) { instance._root.style.transform = `translate(${x}px, ${y}px)` } else { instance._root.style.left = `${x}px` instance._root.style.top = `${y}px` } }
javascript
{ "resource": "" }
q43712
updateAttributes
train
function updateAttributes(instance) { if (instance.horizontalAlignment !== instance._lastHorizontalAlignment) { const horizontalAlignment = instance.horizontalAlignment === HORIZONTAL_ALIGN.LEFT ? 'left' : 'right' instance._root.setAttribute('data-horizontal-align', horizontalAlignment) instance._lastHorizontalAlignment = instance.horizontalAlignment } if (instance.verticalAlignment !== instance._lastVerticalAlignment) { const verticalAlignment = instance.verticalAlignment === VERTICAL_ALIGN.TOP ? 'top' : 'bottom' instance._root.setAttribute('data-vertical-align', verticalAlignment) instance._lastVerticalAlignment = instance.verticalAlignment } }
javascript
{ "resource": "" }
q43713
getTetherBounds
train
function getTetherBounds(tether) { const bounds = tether.getBoundingClientRect() const width = bounds.width const height = bounds.height let x = 0 let y = 0 let tetherOffsetContainer = tether while (tetherOffsetContainer) { x += tetherOffsetContainer.offsetLeft y += tetherOffsetContainer.offsetTop tetherOffsetContainer = tetherOffsetContainer.offsetParent } return { screenX: bounds.left, screenY: bounds.top, x, y, width, height, } }
javascript
{ "resource": "" }
q43714
getContentDimensions
train
function getContentDimensions(instance) { const contentElement = instance._root.firstElementChild if (!contentElement) { return { width: 0, height: 0, } } let width let height if (window.devicePixelRatio > 1) { // This is much less performant, so we use in only on HiDPi displays const bounds = contentElement.getBoundingClientRect() width = bounds.width height = bounds.height } else { width = contentElement.scrollWidth height = contentElement.scrollHeight } return { width, height, } }
javascript
{ "resource": "" }
q43715
train
function( collectionID, criteria, cursor, limit) { collectionID = collectionID.toLowerCase(); var deferred = q.defer(); // acquire a connection from the pool db.getClient().then( function(dbClient) { if ( !dbClient ) { throw Error("Failed to acquire sqlite client"); } // do any necessary dynamic schema syncs, if its supported schemaSyncer.prepCollection(collectionID) .then( function() { return expandIfNecessary(collectionID, schemaSyncer.getTableSchema(collectionID), null, criteria); }) // perform the query .then( function() { var sql = sqlAdaptor.createSelectSQL(collectionID, criteria, limit); query(dbClient, sql).then( // success function(r) { var results = dbClient.results(); if ( !results || results.rowCount < 1 ) { // if no results, return empty array deferred.resolve([]); return; } var hydratedResults = sqlAdaptor.hydrateResults(results); if ( !cursor ) { deferred.resolve( hydratedResults ); } else { var stream = createStreamFrom(hydratedResults); deferred.resolve(stream ); } }, // error function(e) { jive.logger.error(e.stack); deferred.reject(e); } ); }) .fail(function(e){ deferred.reject(e); }) // always try to release the client, if it exists .finally(function() { if ( dbClient ) { // always try to release the client, if it exists dbClient.release(); } }); }) // failed to acquire the client .fail( function(e) { deferred.reject(e); }); return deferred.promise; }
javascript
{ "resource": "" }
q43716
train
function( collectionID, key ) { collectionID = collectionID.toLowerCase(); var deferred = q.defer(); schemaSyncer.prepCollection(collectionID) .then( function() { sqliteObj.find( collectionID, {'_id': key}, false, 1 ).then( // success function(r) { if ( r && r.length > 0 ) { var firstElement = r[0]; if ( isValue(firstElement[key]) ) { var value = firstElement[key]; deferred.resolve(value); } else { deferred.resolve(firstElement); } } return deferred.resolve(null); }, // failure function(e) { return q.reject(e); } ); }); return deferred.promise; }
javascript
{ "resource": "" }
q43717
train
function( collectionID, key ) { collectionID = collectionID.toLowerCase(); var deferred = q.defer(); // acquire a connection from the pool db.getClient().then( function(dbClient) { if ( !dbClient ) { throw Error("Failed to acquire sqlite client"); } // start a transaction using the acquired db connection startTx(dbClient) .then( function() { var sql = sqlAdaptor.createDeleteSQL(collectionID, key); return query(dbClient, sql); }) // commit the transaction if no problems are encountered, this should also close the acquired db client // and return it to the connection pool .then( function(r) { return commitTx(dbClient).then( function() { deferred.resolve(r); } ); }) // ultimately rollback if there is any upstream thrown exception caught .catch( function(e) { return rollbackTx(dbClient, e).finally( function() { deferred.reject(e); }); }) // always try to release the client, if it exists .finally(function() { if ( dbClient ) { // always try to release the client, if it exists dbClient.release(); } }); }) // failed to acquire the client .fail( function(e) { deferred.reject(e); }); return deferred.promise; }
javascript
{ "resource": "" }
q43718
Comment
train
function Comment() { this.type = 'func'; //func or attr this.descs = []; this.attr = { name: null }; this.func = { name: null, params: null }; this.clazz = null; //class this.zuper = null; //super this.tags = { /* name:[val1,val2] */ }; }
javascript
{ "resource": "" }
q43719
train
function(name, value) { name = name.trim(); value = (value || "").trim(); switch (name) { //The following are single allowed. case 'return': case 'copyright': case 'author': case 'since': case 'description': case 'example': case 'version': case 'override': case 'todo': case 'type': case 'ignore': case 'deprecated': this.tags[name] = value; break; //The following are multiple allowed case 'param': case 'see': case 'throws': if (!Array.isArray(this.tags[name])) { this.tags[name] = [value]; } else { this.tags[name].push(value); } break; //The following are meaning stuff. case 'class': this.clazz = value; break; case 'extends': this.zuper = value; break; default: //ignore others } }
javascript
{ "resource": "" }
q43720
SourceTextParser
train
function SourceTextParser(sourceText, classes, methods) { this.Comments = []; this.sourceText = sourceText; this.classes = classes; this.methods = methods; }
javascript
{ "resource": "" }
q43721
train
function() { var line, lines = this.sourceText.split(/\n/mg), lineLen = lines.length; var inCommenting, curComment, closeCommentIdx; for (var i = 0; i < lineLen; ++i) { line = lines[i].trim(); if (line.startsWith('/**')) { inCommenting = true; curComment = new Comment(); //Comment closed has to starts with "*/" } else if (line.startsWith('*/')) { inCommenting = false; closeCommentIdx = i; } else if (!inCommenting && (1 === i - closeCommentIdx) && /(\bfunction\b\s*?(\w+?)\s*\(([^\(\)]*)\))|((\w+)?\s*(?::|=)\s*function\s*\(([^\(\)]*)\))/.test(line)) { curComment.setFunc(RegExp.$2 || RegExp.$5, RegExp.$3 || RegExp.$6); if ('string' !== typeof curComment.getTag('ignore')) { this.Comments.push(curComment); } curComment = null; } else if (!inCommenting && (1 === i - closeCommentIdx) && /(\w+)\s*(?::|=)(?!\s*function)/.test(line)) { curComment.setAttr(RegExp.$1); if ('string' !== typeof curComment.getTag('ignore')) { this.Comments.push(curComment); } curComment = null; } else if (inCommenting) { line = line.replace(/^\*/, '').trim(); if (/^@(\w+)([^\r\n]*)/.test(line)) { curComment.addTag(RegExp.$1, RegExp.$2 || ""); } else { curComment.addDesc(line); } } } //for this._merge(); }
javascript
{ "resource": "" }
q43722
createPage
train
function createPage(filename) { let page = { path: filename, rawContent: fs.readFileSync(filename, "utf8"), name: path.basename(filename).replace(/\.[^/.]+$/, ""), filename: path.basename(filename), folder: path.dirname(filename), ext: path.extname(filename), userData: {} }; page.isMarkdown = page.ext.toLocaleUpperCase() == ".MD"; if (page.isMarkdown) page.ext = ".html"; page.template = doT.template(page.rawContent, null, page.userData); page.outPath = path.join(path.relative(CONTENT, page.folder), page.name + page.ext); page.href = CONFIG.prefix + page.outPath; return page; }
javascript
{ "resource": "" }
q43723
train
function( model ) { model.unbind( 'destroy', this.unregister ); var coll = this.getCollection( model ); coll && coll.remove( model ); }
javascript
{ "resource": "" }
q43724
train
function( collection ) { if ( this.related ) { this.related .unbind( 'relational:add', this.handleAddition ) .unbind( 'relational:remove', this.handleRemoval ) .unbind( 'relational:reset', this.handleReset ) } if ( !collection || !( collection instanceof Backbone.Collection ) ) { collection = new this.collectionType( [], this._getCollectionOptions() ); } collection.model = this.relatedModel; if ( this.options.collectionKey ) { var key = this.options.collectionKey === true ? this.options.reverseRelation.key : this.options.collectionKey; if ( collection[ key ] && collection[ key ] !== this.instance ) { if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) { console.warn( 'Relation=%o; collectionKey=%s already exists on collection=%o', this, key, this.options.collectionKey ); } } else if ( key ) { collection[ key ] = this.instance; } } collection .bind( 'relational:add', this.handleAddition ) .bind( 'relational:remove', this.handleRemoval ) .bind( 'relational:reset', this.handleReset ); return collection; }
javascript
{ "resource": "" }
q43725
train
function( attributes, options ) { var model = this; // 'build' is a possible entrypoint; it's possible no model hierarchy has been determined yet. this.initializeModelHierarchy(); // Determine what type of (sub)model should be built if applicable. // Lookup the proper subModelType in 'this._subModels'. if ( this._subModels && this.prototype.subModelTypeAttribute in attributes ) { var subModelTypeAttribute = attributes[ this.prototype.subModelTypeAttribute ]; var subModelType = this._subModels[ subModelTypeAttribute ]; if ( subModelType ) { model = subModelType; } } return new model( attributes, options ); }
javascript
{ "resource": "" }
q43726
train
function (element) { var event = document.createEvent('MouseEvents'); event.initMouseEvent('mousedown', true, true, window); element.dispatchEvent(event); }
javascript
{ "resource": "" }
q43727
train
function(event) { var inputs = $(event.target).parents("form").eq(0).find(":input:visible"); var inputIndex = inputs.index(event.target); // If at end of focusable elements return false, if not move forward one. if (inputIndex == inputs.length - 1) { // return false on last form input so we know to let the form submit. return false } else {inputs[inputIndex + 1].focus();} }
javascript
{ "resource": "" }
q43728
valid
train
function valid(connote) { if (typeof connote != "string") { return false; } connote = connote.trim().toUpperCase(); // handle 14 character couriers please if (connote.length === 14 && connote.indexOf("CP") === 0) { return false; } return [10, 14, 18, 21, 39, 40].indexOf(connote.length) != -1; }
javascript
{ "resource": "" }
q43729
enforce
train
function enforce(targetFunction) { assert(_.isFunction(targetFunction), 'argument to wrap must be a function'); assert( _.isObject(targetFunction.$schema), `Function "${targetFunction.name}" has no $schema property.`); assert( _.isArray(targetFunction.$schema.arguments), `Function "${targetFunction.name}" has an invalid $schema.arguments property.`); assert( _.isArray(targetFunction.$schema.callbackResult), `Function "${targetFunction.name}" has an invalid ` + '$schema.callbackResult property.'); const fnName = _.toString(targetFunction.name); // Return wrapped function, executes in a new context.. const wrappedFunc = function wrappedFunc(...args) { if (!args.length) { throw new Error( `Function "${fnName}" invoked without arguments, callback required.`); } // // Splice callback out of arguments array. // let originalCb = _.last(args); assert( _.isFunction(originalCb), `Function "${fnName}" requires a callback function as its last argument.`); args.splice(args.length - 1, 1); originalCb = _.once(originalCb); // // Type-check arguments against "arguments" schema, invoke callback with // schema validation errors. This will throw its own errors. // const schemaArgs = { type: 'array', elements: targetFunction.$schema.arguments, }; try { construct(schemaArgs, args); } catch (e) { return originalCb(new Error( `Function "${fnName}" called with invalid arguments: ${e.message}`)); } // // Replace callback argument with an intercepting callback function. // args.push((...resultArray) => { const err = resultArray.length ? resultArray[0] : undefined; const results = resultArray.slice(1); if (err) { // Pass errors through unfiltered. return originalCb(err); } // Type-check results, these must be passed to the callback, since they // cannot be thrown. const schemaCbResult = { type: 'array', elements: targetFunction.$schema.callbackResult, }; try { construct(schemaCbResult, results); } catch (e) { return originalCb(new Error( `Function "${fnName}" invoked its callback with invalid arguments: ` + `${e.message}`)); } // Success, invoke original callback with results. return originalCb(...resultArray); }); // // Invoke target function, pass exceptions to callback. // let rv; try { rv = targetFunction.call(this, ...args); } catch (e) { return originalCb(e); } return rv; }; wrappedFunc.$schema = targetFunction.$schema; return wrappedFunc; }
javascript
{ "resource": "" }
q43730
wrappedFunc
train
function wrappedFunc(...args) { if (!args.length) { throw new Error( `Function "${fnName}" invoked without arguments, callback required.`); } // // Splice callback out of arguments array. // let originalCb = _.last(args); assert( _.isFunction(originalCb), `Function "${fnName}" requires a callback function as its last argument.`); args.splice(args.length - 1, 1); originalCb = _.once(originalCb); // // Type-check arguments against "arguments" schema, invoke callback with // schema validation errors. This will throw its own errors. // const schemaArgs = { type: 'array', elements: targetFunction.$schema.arguments, }; try { construct(schemaArgs, args); } catch (e) { return originalCb(new Error( `Function "${fnName}" called with invalid arguments: ${e.message}`)); } // // Replace callback argument with an intercepting callback function. // args.push((...resultArray) => { const err = resultArray.length ? resultArray[0] : undefined; const results = resultArray.slice(1); if (err) { // Pass errors through unfiltered. return originalCb(err); } // Type-check results, these must be passed to the callback, since they // cannot be thrown. const schemaCbResult = { type: 'array', elements: targetFunction.$schema.callbackResult, }; try { construct(schemaCbResult, results); } catch (e) { return originalCb(new Error( `Function "${fnName}" invoked its callback with invalid arguments: ` + `${e.message}`)); } // Success, invoke original callback with results. return originalCb(...resultArray); }); // // Invoke target function, pass exceptions to callback. // let rv; try { rv = targetFunction.call(this, ...args); } catch (e) { return originalCb(e); } return rv; }
javascript
{ "resource": "" }
q43731
countSubTreeDepth
train
function countSubTreeDepth(scope) { var thisLevelDepth = 0, childNodes = scope.childNodes(), childNode, childDepth, i; if (!childNodes || childNodes.length === 0) { return 0; } for (i = childNodes.length - 1; i >= 0 ; i--) { childNode = childNodes[i], childDepth = 1 + countSubTreeDepth(childNode); thisLevelDepth = Math.max(thisLevelDepth, childDepth); } return thisLevelDepth; }
javascript
{ "resource": "" }
q43732
train
function (parent, siblings, index) { this.parent = parent; this.siblings = siblings.slice(0); // If source node is in the target nodes var i = this.siblings.indexOf(this.source); if (i > -1) { this.siblings.splice(i, 1); if (this.source.index() < index) { index--; } } this.siblings.splice(index, 0, this.source); this.index = index; }
javascript
{ "resource": "" }
q43733
encrypt
train
function encrypt(message) { if (this.secure && this.cipher && this.secret) { if (this.secret === 'secret') { console.warn('PLEASE change default secret password!'); } debug('%s encrypt message with %s', this.name, this.cipher); var cipher = crypto.createCipher(this.cipher, this.secret); return Buffer.concat([cipher.update(message), cipher.final()]); } return message; }
javascript
{ "resource": "" }
q43734
decrypt
train
function decrypt(message) { if (this.secure && this.cipher && this.secret) { if (this.secret === 'secret') { console.warn('PLEASE change default secret password!'); } debug('%s decrypt message with %s', this.name, this.cipher); var decipher = crypto.createDecipher(this.cipher, this.secret); return Buffer.concat([decipher.update(message), decipher.final()]); } return message; }
javascript
{ "resource": "" }
q43735
verifyAddress
train
function verifyAddress(address) { var ifs = os.networkInterfaces(); var nics = Object.keys(ifs); var i, j, match = false; nicLoop: for (i = 0; i < nics.length; i++) { var nic = ifs[nics[i]]; for (j = 0; j < nic.length; j++) { if (nic[j].address === address && !nic[j].internal) { match = true; break nicLoop; } } } return match; }
javascript
{ "resource": "" }
q43736
flatten
train
function flatten(arr) { return arr.reduce(function (flat, toFlatten) { // See if this index is an array that itself needs to be flattened. if(toFlatten.some && toFlatten.some(Array.isArray)) { return flat.concat(flatten(toFlatten)); // Otherwise just add the current index to the end of the flattened array. } else { return flat.concat(toFlatten); } }, []); }
javascript
{ "resource": "" }
q43737
Registrations
train
function Registrations() { Object.defineProperty(this,'_registrations',{ value: {} ,enumerable: false ,configurable: false ,writable: false }) this.get = this.get.bind(this) this.put = this.put.bind(this) this.clear = this.clear.bind(this) this.has = this.has.bind(this) }
javascript
{ "resource": "" }
q43738
assembleAttrsFromServer
train
function assembleAttrsFromServer(seedData, formObjectClass) { // Early return when there was no serialized object provided by the server if (!seedData) { return {} } // Otherwise assemble main and submodels' fields let attrs = merge({}, seedData.fields, seedData.errors) // TODO: reenable this, but consider there might be ids/ id arrays in there // for (let submodel of formObjectClass.submodels) { // if (seedData.fields[submodel]) { // let submodelData = seedData.fields[submodel] // attrs[submodel] = merge({}, submodelData.fields, submodelData.errors) // } // } return attrs }
javascript
{ "resource": "" }
q43739
addCtrActionsToRouter
train
function addCtrActionsToRouter(ctr, router, name, options) { for(let prop in ctr) { if(ctr[prop] instanceof Function) { const info = new RouteInfo(ctr, name, prop, ctr[prop], options) /** * e.g. router.get(path, Middleware). */ const path = name ? '/' + name + info.path : info.path const mw = newMiddleware(info) debug('Add route to %s %s', info.method, path) router[info.method].call(router, path, mw) } } return router }
javascript
{ "resource": "" }
q43740
train
function( path) { var stat = null; try { stat = fs.statSync( path ); } catch (err) { console.log(err); } return ( stat && stat.isFile() ); }
javascript
{ "resource": "" }
q43741
loadHighlighter
train
function loadHighlighter () { var headElem = d.querySelector('head'); headElem.appendChild(h('link', { rel: 'stylesheet', href: 'http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css' })); headElem.appendChild(h('script', { src: 'http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js' })); var interval = setInterval(function () { if (!!window.hljs) { clearInterval(interval); applyHighlighter(); } }, 100); }
javascript
{ "resource": "" }
q43742
algebraRing
train
function algebraRing (identities, given) { // A ring is a group, with multiplication. const ring = group({ identity: identities[0], contains: given.contains, equality: given.equality, compositionLaw: given.addition, inversion: given.negation }) // operators function multiplication () { return [].slice.call(arguments).reduce(given.multiplication) } function inversion (a) { if (ring.equality(a, ring.zero)) { throw new TypeError(error.cannotDivideByZero) } return given.inversion(a) } function division (a) { const rest = [].slice.call(arguments, 1) return given.multiplication(a, rest.map(inversion).reduce(given.multiplication)) } ring.multiplication = multiplication ring.inversion = inversion ring.division = division // Multiplicative identity. const one = identities[1] if (ring.notContains(one)) { throw new TypeError(error.doesNotContainIdentity) } // Check that one*one=one. if (ring.disequality(given.multiplication(one, one), one)) { throw new TypeError(error.identityIsNotNeutral) } if (ring.notContains(identities[1])) { throw new TypeError(error.doesNotContainIdentity) } ring.one = identities[1] return ring }
javascript
{ "resource": "" }
q43743
__pandocAvailable
train
function __pandocAvailable(cb) { var test = spawn('pandoc', ['--help']); test.on('error', function() { console.error('Pandoc not found'); cb('Pandoc not found'); }); test.on('exit', function() { cb(null); }); test.stdin.end(); }
javascript
{ "resource": "" }
q43744
train
function(user, permissions, options) { if (!permissions || _.isString(permissions)) { if (!initialized) { throw "You must initialize FacebookUtils before calling link."; } requestedPermissions = permissions; return user._linkWith("facebook", options); } else { var newOptions = _.clone(options) || {}; newOptions.authData = permissions; return user._linkWith("facebook", newOptions); } }
javascript
{ "resource": "" }
q43745
expand
train
function expand(source, opts) { opts = opts || {}; var re = opts.re = opts.re || '.' , isre = (re instanceof RegExp) , o = {}, k, v, parts, i, p; for(k in source) { v = source[k]; if(isre ? !re.test(k) : !~k.indexOf(re)) { o[k] = v; }else{ parts = k.split(re); p = o; for(i = 0;i < parts.length;i++) { k = parts[i]; if(i < parts.length - 1) { p[k] = p[k] || {}; p = p[k]; }else{ p[k] = v; } } } } return o; }
javascript
{ "resource": "" }
q43746
validateFile
train
function validateFile(path, rollCall) { var stat = path ? fs.statSync(path) : { size : 0 }; if (!stat.size) { rollCall.error('Failed to find any entries in "' + path + '" (file size: ' + stat.size + ')'); return false; } return true; }
javascript
{ "resource": "" }
q43747
updateFiles
train
function updateFiles(files, func, bpath, eh) { try { if (Array.isArray(files) && typeof func === 'function') { for (var i = 0; i < files.length; i++) { var p = path.join(bpath, files[i]), au = ''; var content = rbot.file.read(p, { encoding : rbot.file.defaultEncoding }); var ec = func(content, p); if (content !== ec) { rbot.file.write(p, ec); return au; } } } } catch (e) { if (typeof eh === 'function') { return eh('Unable to update "' + (Array.isArray(files) ? files.join(',') : '') + '" using: ' + func, e); } throw e; } }
javascript
{ "resource": "" }
q43748
pickToArray
train
function pickToArray (entities, property, deep) { if (!(entities instanceof Array) && !isPlainObject(entities)) { throw new Error('Expecting entity to be object or array of objects') } else if (typeof property !== 'string' && !(property instanceof Array)) { throw new Error('Expecting property to be string or array') } var arr = entities instanceof Array ? entities : [entities] return arr.reduce(function (result, obj) { if (!(obj instanceof Array) && !isPlainObject(obj)) { return result } forEach(obj, function (value, key) { if ( (property instanceof Array && property.indexOf(key) !== -1) || (key === property) ) { result.push(value) if (!(property instanceof Array)) { return false } } else if (deep && (value instanceof Array || isPlainObject(value))) { result = result.concat(pickToArray(value, property, deep)) } }) return result }, []) }
javascript
{ "resource": "" }
q43749
loadFile
train
function loadFile(path) { if ( config.asReference && config.asReference.loadFile ) { return config.asReference.loadFile( path ); } else if (typeof process !== "undefined" && process.versions && !!process.versions.node && require.nodeRequire) { var fs = require.nodeRequire('fs'); var file = fs.readFileSync(path, 'utf8'); if (file.indexOf('\uFEFF') === 0) return file.substring(1); return file; } else { var file = new java.io.File(path), lineSeparator = java.lang.System.getProperty("line.separator"), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), 'utf-8')), stringBuffer, line; try { stringBuffer = new java.lang.StringBuffer(); line = input.readLine(); if (line && line.length() && line.charAt(0) === 0xfeff) line = line.substring(1); stringBuffer.append(line); while ((line = input.readLine()) !== null) { stringBuffer.append(lineSeparator).append(line); } return String(stringBuffer.toString()); } finally { input.close(); } } }
javascript
{ "resource": "" }
q43750
escape
train
function escape(content) { return content.replace(/(["'\\])/g, '\\$1') .replace(/[\f]/g, "\\f") .replace(/[\b]/g, "\\b") .replace(/[\n]/g, "\\n") .replace(/[\t]/g, "\\t") .replace(/[\r]/g, "\\r"); }
javascript
{ "resource": "" }
q43751
areArgumentsValid
train
function areArgumentsValid(args) { var isValid = args.every(function(arg) { if (Array.isArray(arg)) { return areArgumentsValid(arg); } return (arg !== null && typeof arg === 'object'); }); return isValid; }
javascript
{ "resource": "" }
q43752
mapStateToProps
train
function mapStateToProps (state) { return { account: state.account ? state.entities.accounts[state.account.id] : null, router: state.router } }
javascript
{ "resource": "" }
q43753
train
function() { var clone = new CKEDITOR.dom.range( this.root ); clone.startContainer = this.startContainer; clone.startOffset = this.startOffset; clone.endContainer = this.endContainer; clone.endOffset = this.endOffset; clone.collapsed = this.collapsed; return clone; }
javascript
{ "resource": "" }
q43754
getLengthOfPrecedingTextNodes
train
function getLengthOfPrecedingTextNodes( node ) { var sum = 0; while ( ( node = node.getPrevious() ) && node.type == CKEDITOR.NODE_TEXT ) sum += node.getLength(); return sum; }
javascript
{ "resource": "" }
q43755
train
function() { var startNode = this.startContainer, endNode = this.endContainer, startOffset = this.startOffset, endOffset = this.endOffset, childCount; if ( startNode.type == CKEDITOR.NODE_ELEMENT ) { childCount = startNode.getChildCount(); if ( childCount > startOffset ) startNode = startNode.getChild( startOffset ); else if ( childCount < 1 ) startNode = startNode.getPreviousSourceNode(); else // startOffset > childCount but childCount is not 0 { // Try to take the node just after the current position. startNode = startNode.$; while ( startNode.lastChild ) startNode = startNode.lastChild; startNode = new CKEDITOR.dom.node( startNode ); // Normally we should take the next node in DFS order. But it // is also possible that we've already reached the end of // document. startNode = startNode.getNextSourceNode() || startNode; } } if ( endNode.type == CKEDITOR.NODE_ELEMENT ) { childCount = endNode.getChildCount(); if ( childCount > endOffset ) endNode = endNode.getChild( endOffset ).getPreviousSourceNode( true ); else if ( childCount < 1 ) endNode = endNode.getPreviousSourceNode(); else // endOffset > childCount but childCount is not 0 { // Try to take the node just before the current position. endNode = endNode.$; while ( endNode.lastChild ) endNode = endNode.lastChild; endNode = new CKEDITOR.dom.node( endNode ); } } // Sometimes the endNode will come right before startNode for collapsed // ranges. Fix it. (#3780) if ( startNode.getPosition( endNode ) & CKEDITOR.POSITION_FOLLOWING ) startNode = endNode; return { startNode: startNode, endNode: endNode }; }
javascript
{ "resource": "" }
q43756
train
function( includeSelf, ignoreTextNode ) { var start = this.startContainer, end = this.endContainer, ancestor; if ( start.equals( end ) ) { if ( includeSelf && start.type == CKEDITOR.NODE_ELEMENT && this.startOffset == this.endOffset - 1 ) ancestor = start.getChild( this.startOffset ); else ancestor = start; } else { ancestor = start.getCommonAncestor( end ); } return ignoreTextNode && !ancestor.is ? ancestor.getParent() : ancestor; }
javascript
{ "resource": "" }
q43757
getValidEnlargeable
train
function getValidEnlargeable( enlargeable ) { return enlargeable && enlargeable.type == CKEDITOR.NODE_ELEMENT && enlargeable.hasAttribute( 'contenteditable' ) ? null : enlargeable; }
javascript
{ "resource": "" }
q43758
train
function( mode, selectContents, shrinkOnBlockBoundary ) { // Unable to shrink a collapsed range. if ( !this.collapsed ) { mode = mode || CKEDITOR.SHRINK_TEXT; var walkerRange = this.clone(); var startContainer = this.startContainer, endContainer = this.endContainer, startOffset = this.startOffset, endOffset = this.endOffset; // Whether the start/end boundary is moveable. var moveStart = 1, moveEnd = 1; if ( startContainer && startContainer.type == CKEDITOR.NODE_TEXT ) { if ( !startOffset ) walkerRange.setStartBefore( startContainer ); else if ( startOffset >= startContainer.getLength() ) walkerRange.setStartAfter( startContainer ); else { // Enlarge the range properly to avoid walker making // DOM changes caused by triming the text nodes later. walkerRange.setStartBefore( startContainer ); moveStart = 0; } } if ( endContainer && endContainer.type == CKEDITOR.NODE_TEXT ) { if ( !endOffset ) walkerRange.setEndBefore( endContainer ); else if ( endOffset >= endContainer.getLength() ) walkerRange.setEndAfter( endContainer ); else { walkerRange.setEndAfter( endContainer ); moveEnd = 0; } } var walker = new CKEDITOR.dom.walker( walkerRange ), isBookmark = CKEDITOR.dom.walker.bookmark(); walker.evaluator = function( node ) { return node.type == ( mode == CKEDITOR.SHRINK_ELEMENT ? CKEDITOR.NODE_ELEMENT : CKEDITOR.NODE_TEXT ); }; var currentElement; walker.guard = function( node, movingOut ) { if ( isBookmark( node ) ) return true; // Stop when we're shrink in element mode while encountering a text node. if ( mode == CKEDITOR.SHRINK_ELEMENT && node.type == CKEDITOR.NODE_TEXT ) return false; // Stop when we've already walked "through" an element. if ( movingOut && node.equals( currentElement ) ) return false; if ( shrinkOnBlockBoundary === false && node.type == CKEDITOR.NODE_ELEMENT && node.isBlockBoundary() ) return false; // Stop shrinking when encountering an editable border. if ( node.type == CKEDITOR.NODE_ELEMENT && node.hasAttribute( 'contenteditable' ) ) return false; if ( !movingOut && node.type == CKEDITOR.NODE_ELEMENT ) currentElement = node; return true; }; if ( moveStart ) { var textStart = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastForward' : 'next' ](); textStart && this.setStartAt( textStart, selectContents ? CKEDITOR.POSITION_AFTER_START : CKEDITOR.POSITION_BEFORE_START ); } if ( moveEnd ) { walker.reset(); var textEnd = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastBackward' : 'previous' ](); textEnd && this.setEndAt( textEnd, selectContents ? CKEDITOR.POSITION_BEFORE_END : CKEDITOR.POSITION_AFTER_END ); } return !!( moveStart || moveEnd ); } }
javascript
{ "resource": "" }
q43759
train
function( node ) { this.optimizeBookmark(); this.trim( false, true ); var startContainer = this.startContainer; var startOffset = this.startOffset; var nextNode = startContainer.getChild( startOffset ); if ( nextNode ) node.insertBefore( nextNode ); else startContainer.append( node ); // Check if we need to update the end boundary. if ( node.getParent() && node.getParent().equals( this.endContainer ) ) this.endOffset++; // Expand the range to embrace the new node. this.setStartBefore( node ); }
javascript
{ "resource": "" }
q43760
train
function( range ) { this.setStart( range.startContainer, range.startOffset ); this.setEnd( range.endContainer, range.endOffset ); }
javascript
{ "resource": "" }
q43761
train
function( startNode, startOffset ) { // W3C requires a check for the new position. If it is after the end // boundary, the range should be collapsed to the new start. It seams // we will not need this check for our use of this class so we can // ignore it for now. // Fixing invalid range start inside dtd empty elements. if ( startNode.type == CKEDITOR.NODE_ELEMENT && CKEDITOR.dtd.$empty[ startNode.getName() ] ) startOffset = startNode.getIndex(), startNode = startNode.getParent(); this.startContainer = startNode; this.startOffset = startOffset; if ( !this.endContainer ) { this.endContainer = startNode; this.endOffset = startOffset; } updateCollapsed( this ); }
javascript
{ "resource": "" }
q43762
train
function( endNode, endOffset ) { // W3C requires a check for the new position. If it is before the start // boundary, the range should be collapsed to the new end. It seams we // will not need this check for our use of this class so we can ignore // it for now. // Fixing invalid range end inside dtd empty elements. if ( endNode.type == CKEDITOR.NODE_ELEMENT && CKEDITOR.dtd.$empty[ endNode.getName() ] ) endOffset = endNode.getIndex() + 1, endNode = endNode.getParent(); this.endContainer = endNode; this.endOffset = endOffset; if ( !this.startContainer ) { this.startContainer = endNode; this.startOffset = endOffset; } updateCollapsed( this ); }
javascript
{ "resource": "" }
q43763
train
function( toSplit ) { if ( !this.collapsed ) return null; // Extract the contents of the block from the selection point to the end // of its contents. this.setEndAt( toSplit, CKEDITOR.POSITION_BEFORE_END ); var documentFragment = this.extractContents(); // Duplicate the element after it. var clone = toSplit.clone( false ); // Place the extracted contents into the duplicated element. documentFragment.appendTo( clone ); clone.insertAfter( toSplit ); this.moveToPosition( toSplit, CKEDITOR.POSITION_AFTER_END ); return clone; }
javascript
{ "resource": "" }
q43764
train
function() { var walkerRange = this.clone(); // Optimize and analyze the range to avoid DOM destructive nature of walker. (#5780) walkerRange.optimize(); if ( walkerRange.startContainer.type != CKEDITOR.NODE_ELEMENT || walkerRange.endContainer.type != CKEDITOR.NODE_ELEMENT ) return null; var walker = new CKEDITOR.dom.walker( walkerRange ), isNotBookmarks = CKEDITOR.dom.walker.bookmark( false, true ), isNotWhitespaces = CKEDITOR.dom.walker.whitespaces( true ); walker.evaluator = function( node ) { return isNotWhitespaces( node ) && isNotBookmarks( node ); }; var node = walker.next(); walker.reset(); return node && node.equals( walker.previous() ) ? node : null; }
javascript
{ "resource": "" }
q43765
train
function() { // The reference element contains a zero-width space to avoid // a premature removal. The view is to be scrolled with respect // to this element. var reference = new CKEDITOR.dom.element.createFromHtml( '<span>&nbsp;</span>', this.document ), afterCaretNode, startContainerText, isStartText; var range = this.clone(); // Work with the range to obtain a proper caret position. range.optimize(); // Currently in a text node, so we need to split it into two // halves and put the reference between. if ( isStartText = range.startContainer.type == CKEDITOR.NODE_TEXT ) { // Keep the original content. It will be restored. startContainerText = range.startContainer.getText(); // Split the startContainer at the this position. afterCaretNode = range.startContainer.split( range.startOffset ); // Insert the reference between two text nodes. reference.insertAfter( range.startContainer ); } // If not in a text node, simply insert the reference into the range. else { range.insertNode( reference ); } // Scroll with respect to the reference element. reference.scrollIntoView(); // Get rid of split parts if "in a text node" case. // Revert the original text of the startContainer. if ( isStartText ) { range.startContainer.setText( startContainerText ); afterCaretNode.remove(); } // Get rid of the reference node. It is no longer necessary. reference.remove(); }
javascript
{ "resource": "" }
q43766
shallowEquals
train
function shallowEquals(objA, objB) { var returnVal = false; if (objA === objB || objA === null && objB === null) { returnVal = true; } if (!returnVal) { var propsEqual = true; if (Object.keys(objA).length === Object.keys(objB).length) { for (var key in objA) { propsEqual = propsEqual && objA[key] === objB[key]; } returnVal = propsEqual; } } return returnVal; }
javascript
{ "resource": "" }
q43767
checkCommentForSuppress
train
function checkCommentForSuppress(node) { // Skip if types aren't provided or the comment is empty. if (!node || !node.value || node.value.length === 0) { return; } const match = node.value.match(/@suppress \{(.*?)\}/); if (match && match.length === 2) { if (!blacklistedTypes || blacklistedTypes.length === 0) { // Array is not present or empty, so block all types. context.report(node, '@suppress not allowed for any types'); } else { // Report which matched types are blocked. const matched = []; const types = match[1].split('|'); types.forEach(function(type) { if (blacklistedTypes.indexOf(type) !== -1 && matched.indexOf(type) === -1) { matched.push(type); } }); if (matched.length > 0) { const typeString = matched.join(', '); context.report(node, `@suppress not allowed for: ${typeString}`); } } } }
javascript
{ "resource": "" }
q43768
toBoolFunction
train
function toBoolFunction(selector, condition) { if (arguments.length == 2) { selector = toBoolFunction(selector); condition = toBoolFunction(condition); return function () { return condition(selector.apply(this, arguments)); }; } else { condition = selector; } var alternate = false; try { switch (type(condition)) { case 'regexp': alternate = regexpToFunction(condition); break; case 'string': alternate = stringToFunction(condition); break; case 'function': alternate = condition; break; case 'object': alternate = objectToFunction(condition); break; } } catch (ex) { //ignore things that aren't valid functions } return function (val) { return (val === condition) || (alternate && alternate.apply(this, arguments)); } }
javascript
{ "resource": "" }
q43769
objectToFunction
train
function objectToFunction(obj) { var fns = Object.keys(obj) .map(function (key) { return toBoolFunction(key, obj[key]); }); return function(o){ for (var i = 0; i < fns.length; i++) { if (!fns[i](o)) return false; } return true; } }
javascript
{ "resource": "" }
q43770
stringToFunction
train
function stringToFunction(str) { // immediate such as "> 20" if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str); // properties such as "name.first" or "age > 18" var fn = new Function('_', 'return _.' + str); return fn }
javascript
{ "resource": "" }
q43771
train
function(apiKey, host, port, reqOpts) { var iod = this if (_.isObject(host)) { reqOpts = host host = null } else if (_.isObject(port)) { reqOpts = port port = null } if (!apiKey) throw Error('IOD apiKey is missing!') else if (host && !url.parse(host, false, true).protocol) { throw Error('Protocol not found on host: ' + host) } var httpHost = 'http://api.idolondemand.com' var httpsHost = 'https://api.idolondemand.com' var httpPort = 80 var httpsPort = 443 // If Https port point to Https host and vice versa if (host == null && port === httpsPort) host = httpsHost else if (host == null && port === httpPort) host = httpHost else if (port == null && host && host.toLowerCase() === httpsHost) port = httpsPort else if (port == null && host && host.toLowerCase() === httpHost) port = httpPort iod.apiKey = apiKey iod.host = host || httpsHost iod.port = port || httpsPort iod.reqOpts = _.defaults(reqOpts || {}, { timeout: 300000 }) iod.ACTIONS = _.cloneDeep(CONSTANTS.ACTIONS) iod.eventEmitter = eventEmitter SchemaU.initSchemas(iod) _.bindAll.apply(_, [iod].concat(_.functions(IOD.prototype))) }
javascript
{ "resource": "" }
q43772
insert_token
train
function insert_token(item) { var $this_token = $($(input).data("settings").tokenFormatter(item)); var readonly = item.readonly === true ? true : false; if(readonly) $this_token.addClass($(input).data("settings").classes.tokenReadOnly); $this_token.addClass($(input).data("settings").classes.token).insertBefore(input_token); // The 'delete token' button if(!readonly) { $("<span>" + $(input).data("settings").deleteText + "</span>") .addClass($(input).data("settings").classes.tokenDelete) .appendTo($this_token) .click(function () { if (!$(input).data("settings").disabled) { delete_token($(this).parent()); hidden_input.change(); return false; } }); } // Store data on the token var token_data = item; $.data($this_token.get(0), "tokeninput", item); // Save this token for duplicate checking saved_tokens = saved_tokens.slice(0,selected_token_index).concat([token_data]).concat(saved_tokens.slice(selected_token_index)); selected_token_index++; // Update the hidden input update_hidden_input(saved_tokens, hidden_input); token_count += 1; // Check the token limit if($(input).data("settings").tokenLimit !== null && token_count >= $(input).data("settings").tokenLimit) { input_box.hide(); hide_dropdown(); } return $this_token; }
javascript
{ "resource": "" }
q43773
add_token
train
function add_token (item) { var callback = $(input).data("settings").onAdd; // See if the token already exists and select it if we don't want duplicates if(token_count > 0 && $(input).data("settings").preventDuplicates) { var found_existing_token = null; token_list.children().each(function () { var existing_token = $(this); var existing_data = $.data(existing_token.get(0), "tokeninput"); if(existing_data && existing_data[settings.tokenValue] === item[settings.tokenValue]) { found_existing_token = existing_token; return false; } }); if(found_existing_token) { select_token(found_existing_token); input_token.insertAfter(found_existing_token); focus_with_timeout(input_box); return; } } // Squeeze input_box so we force no unnecessary line break input_box.width(1); // Insert the new tokens if($(input).data("settings").tokenLimit == null || token_count < $(input).data("settings").tokenLimit) { insert_token(item); // Remove the placeholder so it's not seen after you've added a token input_box.attr("placeholder", null) checkTokenLimit(); } // Clear input box input_box.val(""); // Don't show the help dropdown, they've got the idea hide_dropdown(); // Execute the onAdd callback if defined if($.isFunction(callback)) { callback.call(hidden_input,item); } }
javascript
{ "resource": "" }
q43774
select_token
train
function select_token (token) { if (!$(input).data("settings").disabled) { token.addClass($(input).data("settings").classes.selectedToken); selected_token = token.get(0); // Hide input box input_box.val(""); // Hide dropdown if it is visible (eg if we clicked to select token) hide_dropdown(); } }
javascript
{ "resource": "" }
q43775
deselect_token
train
function deselect_token (token, position) { token.removeClass($(input).data("settings").classes.selectedToken); selected_token = null; if(position === POSITION.BEFORE) { input_token.insertBefore(token); selected_token_index--; } else if(position === POSITION.AFTER) { input_token.insertAfter(token); selected_token_index++; } else { input_token.appendTo(token_list); selected_token_index = token_count; } // Show the input box and give it focus again focus_with_timeout(input_box); }
javascript
{ "resource": "" }
q43776
toggle_select_token
train
function toggle_select_token(token) { var previous_selected_token = selected_token; if(selected_token) { deselect_token($(selected_token), POSITION.END); } if(previous_selected_token === token.get(0)) { deselect_token(token, POSITION.END); } else { select_token(token); } }
javascript
{ "resource": "" }
q43777
delete_token
train
function delete_token (token) { // Remove the id from the saved list var token_data = $.data(token.get(0), "tokeninput"); var callback = $(input).data("settings").onDelete; var index = token.prevAll().length; if(index > selected_token_index) index--; // Delete the token token.remove(); selected_token = null; // Show the input box and give it focus again focus_with_timeout(input_box); // Remove this token from the saved list saved_tokens = saved_tokens.slice(0,index).concat(saved_tokens.slice(index+1)); if (saved_tokens.length == 0) { input_box.attr("placeholder", settings.placeholder) } if(index < selected_token_index) selected_token_index--; // Update the hidden input update_hidden_input(saved_tokens, hidden_input); token_count -= 1; if($(input).data("settings").tokenLimit !== null) { input_box .show() .val(""); focus_with_timeout(input_box); } // Execute the onDelete callback if defined if($.isFunction(callback)) { callback.call(hidden_input,token_data); } }
javascript
{ "resource": "" }
q43778
update_hidden_input
train
function update_hidden_input(saved_tokens, hidden_input) { var token_values = $.map(saved_tokens, function (el) { if(typeof $(input).data("settings").tokenValue == 'function') return $(input).data("settings").tokenValue.call(this, el); return el[$(input).data("settings").tokenValue]; }); hidden_input.val(token_values.join($(input).data("settings").tokenDelimiter)); }
javascript
{ "resource": "" }
q43779
highlight_term
train
function highlight_term(value, term) { return value.replace( new RegExp( "(?![^&;]+;)(?!<[^<>]*)(" + regexp_escape(term) + ")(?![^<>]*>)(?![^&;]+;)", "gi" ), function(match, p1) { return "<b>" + escapeHTML(p1) + "</b>"; } ); }
javascript
{ "resource": "" }
q43780
excludeCurrent
train
function excludeCurrent(results) { if ($(input).data("settings").excludeCurrent) { var currentTokens = $(input).data("tokenInputObject").getTokens(), trimmedList = []; if (currentTokens.length) { $.each(results, function(index, value) { var notFound = true; $.each(currentTokens, function(cIndex, cValue) { if (value[$(input).data("settings").propertyToSearch] == cValue[$(input).data("settings").propertyToSearch]) { notFound = false; return false; } }); if (notFound) { trimmedList.push(value); } }); results = trimmedList; } } return results; }
javascript
{ "resource": "" }
q43781
populate_dropdown
train
function populate_dropdown (query, results) { // exclude current tokens if configured results = excludeCurrent(results); if(results && results.length) { dropdown.empty(); var dropdown_ul = $("<ul/>") .appendTo(dropdown) .mouseover(function (event) { select_dropdown_item($(event.target).closest("li")); }) .mousedown(function (event) { add_token($(event.target).closest("li").data("tokeninput")); hidden_input.change(); return false; }) .hide(); if ($(input).data("settings").resultsLimit && results.length > $(input).data("settings").resultsLimit) { results = results.slice(0, $(input).data("settings").resultsLimit); } $.each(results, function(index, value) { var this_li = $(input).data("settings").resultsFormatter(value); this_li = find_value_and_highlight_term(this_li ,value[$(input).data("settings").propertyToSearch], query); this_li = $(this_li).appendTo(dropdown_ul); if(index % 2) { this_li.addClass($(input).data("settings").classes.dropdownItem); } else { this_li.addClass($(input).data("settings").classes.dropdownItem2); } if(index === 0 && $(input).data("settings").autoSelectFirstResult) { select_dropdown_item(this_li); } $.data(this_li.get(0), "tokeninput", value); }); show_dropdown(); if($(input).data("settings").animateDropdown) { dropdown_ul.slideDown("fast"); } else { dropdown_ul.show(); } } else { if($(input).data("settings").noResultsText) { dropdown.html("<p>" + escapeHTML($(input).data("settings").noResultsText) + "</p>"); show_dropdown(); } } }
javascript
{ "resource": "" }
q43782
select_dropdown_item
train
function select_dropdown_item (item) { if(item) { if(selected_dropdown_item) { deselect_dropdown_item($(selected_dropdown_item)); } item.addClass($(input).data("settings").classes.selectedDropdownItem); selected_dropdown_item = item.get(0); } }
javascript
{ "resource": "" }
q43783
deselect_dropdown_item
train
function deselect_dropdown_item (item) { item.removeClass($(input).data("settings").classes.selectedDropdownItem); selected_dropdown_item = null; }
javascript
{ "resource": "" }
q43784
computeURL
train
function computeURL() { var url = $(input).data("settings").url; if(typeof $(input).data("settings").url == 'function') { url = $(input).data("settings").url.call($(input).data("settings")); } return url; }
javascript
{ "resource": "" }
q43785
_matchAllFields
train
function _matchAllFields(fields, matchAnyRegex) { var regExp = regExps ? matchAnyRegex ? regExps.any : regExps.all : null; if (regExp) { for (var i = 0; i < fields.length; ++i) { parentBuilder.field(fields[i]).is("$regex", regExp); } } return parentBuilder; }
javascript
{ "resource": "" }
q43786
_matchAnyField
train
function _matchAnyField(fields, matchAnyRegex) { var regExp = regExps ? matchAnyRegex ? regExps.any : regExps.all : null; if (regExp) { var orBuilder = parentBuilder.either(); for (var i = 0; i < fields.length; ++i) { orBuilder = orBuilder.or().field(fields[i]).is("$regex", regExp); } } return parentBuilder; }
javascript
{ "resource": "" }
q43787
train
function (parentBuilder, field) { if (!dataUtils.isValidStr(field)) throw "Invalid field, should be a string: " + dataUtils.JSONstringify(field); /** * Ensures a comparison of the field with the value. * @param {string} comparator e.g. "$gt", "$gte", etc. * @param {*} value * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.is = function (comparator, value) { return parentBuilder._compare(field, comparator, value); }; /** * Ensures that the field matches the given value. This is same * as calling matchAll([value]). * @param {*} value * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.matches = function (value) { return parentBuilder._matchesAll(field, [value]); }; /** * Ensures that the field matches all the values. * @param {Array.<*>} values * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.matchesAll = function (values) { return parentBuilder._matchesAll(field, values); }; /** * Ensures that the field matches at least one of the values. * @param {Array.<*>} values * @param {boolean} [addToExistingOr=false] If true, this will * be added to the existing OR list ($in), if any. * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.matchesAny = function (values, addToExistingOr) { return parentBuilder._matchesAny(field, values, addToExistingOr); }; }
javascript
{ "resource": "" }
q43788
train
function () { var _orBuilder = this; var _queries = []; var _currentChildBuilder = new ChildQueryBuilder(_orBuilder); /** * Process the current OR entry, and continue adding to this OR * query group. * @returns {ChildQueryBuilder} A new {@link ChildQueryBuilder} * child in this OR group. */ this.or = function () { _orBuilder.flush(); return _currentChildBuilder; }; /** * Returns the array of query objects generated by this * builder. * @returns {Array.<{}>} the array of query objects generated * by this builder. */ this.flush = function () { // save current builder var q = _currentChildBuilder.build(); // only if the query is non-empty if (Object.keys(q).length) { if (!dataUtils.arrayContainsValue(_queries, q)) _queries.push(q); // renew current builder _currentChildBuilder = new ChildQueryBuilder(_orBuilder); } return _queries; }; }
javascript
{ "resource": "" }
q43789
init
train
function init(configuration){ var self = { config : configuration, adapters : [], getWhenCurrentWritesDone : getWhenCurrentWritesDone }; _.each(self.config.adapters, function(adapter){ var adapterInstance; try { adapterInstance = require('./adapters/' + adapter.type).init(adapter); } catch (e) { console.log(chalk.red('Initialization Error: '), e); throw e; } adapterInstance.writeQueue = BB.resolve(); self.adapters.push(adapterInstance); }); [ 'error', 'info', 'debug', 'warn', 'trace', 'critical' ].forEach(function (type) { /** * Create a TYPE log entry * @param category Categorize your error with a user defined label * @param args Include your customized messages. This should be a comma separated list just like `console.log` */ self[type] = function () { // If we are still logging and there are messages to write if(arguments.length > 0){ var category = (arguments.length > 1 && _.isString(arguments[0])) ? arguments[0] : '', startIdx = (arguments.length > 1) ? 1 : 0; _write.call(self, type, category, Array.prototype.slice.call(arguments, startIdx)); } }; }); return self; }
javascript
{ "resource": "" }
q43790
initWithFile
train
function initWithFile(configPath){ var configString = fs.readFileSync(path.resolve(configPath)); this.config = JSON.parse(configString); this.init(this.config); return this; }
javascript
{ "resource": "" }
q43791
_write
train
function _write(type, category, message){ var config = this.config; this.adapters.forEach(function(adapter) { //Check configuration to see if we should continue. if(adapter.config.filter && (adapter.config.filter.indexOf(type) > -1)){ return; } //We are not filtering this out. Continue adapter.write(type, category, message); }); }
javascript
{ "resource": "" }
q43792
clone
train
function clone(args, baseDir, privKey, cb) { run(baseDir, privKey, "git clone " + args, cb) }
javascript
{ "resource": "" }
q43793
train
function (spec) { spec.addMatchers({ /** * Array contains all elements of another array * @param needles another array * @returns {Boolean} true/false */ toContainAll: function(needles) { var haystack = this.actual; return needles.every(function (elem) { return haystack.some(function (sackElem) { return spec.env.equals_(elem, sackElem); }); }); } }); }
javascript
{ "resource": "" }
q43794
train
function(data) { var filePath = data.filePath; var noExtensionFilePath = data.noExtensionFilePath; var fileName = data.fileName; var noExtensionFileName = data.noExtensionFileName; return [ "describe('" + noExtensionFilePath + "', function() {", "});", ].join('\n'); }
javascript
{ "resource": "" }
q43795
extract
train
function extract (query) { var toSplice = [] var extracted = [] return function (prev, curr, index, array) { if (prev !== extracted) { if (testValue(prev, query)) { extracted.push(prev) toSplice.push(index - 1) } } if (testValue(curr, query)) { extracted.push(curr) toSplice.push(index) } if (index === array.length - 1) { toSplice.reverse() for (var i = 0; i < toSplice.length; i++) { array.splice(toSplice[i], 1) } } return extracted } }
javascript
{ "resource": "" }
q43796
getNewRouteInfo
train
function getNewRouteInfo(that, newRoutePath, path, pathToEmit) { var indexes = getDivergenceIndexes(that.currentPath, path, newRoutePath) if(indexes === undefined) { return undefined } var routeDivergenceIndex = indexes.routeIndex var pathDivergenceIndex = indexes.pathIndex var lastRoute = newRoutePath[routeDivergenceIndex-1].route var newPathSegment = path.slice(pathDivergenceIndex) // routing var newRoutes = traverseRoute(that, lastRoute, newPathSegment, pathDivergenceIndex) if(newRoutes === undefined) { var pathAdditions = [] for(var n=routeDivergenceIndex-1; n>=0; n--) { // go in reverse and take the closest default handler if(that.currentRoutes[n].route.defaultHandler !== undefined) { var defaultHandler = that.currentRoutes[n].route.defaultHandler break; } else { pathAdditions = that.currentRoutes[n].route.pathSegment.concat(pathAdditions) } } if(defaultHandler !== undefined) { var handlerParameters = [getPathSegementToOutput(that.transform, pathAdditions.concat(newPathSegment))] var subroute = new Route(newPathSegment, that.transform, true) defaultHandler.apply(subroute, handlerParameters) var pathIndexEnd = pathDivergenceIndex+newPathSegment.length if(newPathSegment.length !== 0) { pathIndexEnd-- } newRoutes = [{route: subroute, pathIndexes: {start:pathDivergenceIndex, end: pathIndexEnd}}] } else { throw new Error("No route matched path: "+JSON.stringify(getPathToOutput(that.transform, path))) } } else { var newRouteInfo = getRedirectRoute(that, path, newRoutePath, newRoutes, routeDivergenceIndex) if(newRouteInfo !== false) { return newRouteInfo } } return {newRoutes: newRoutes, divergenceIndex: routeDivergenceIndex, pathToEmit: pathToEmit} }
javascript
{ "resource": "" }
q43797
loopThroughHandlers
train
function loopThroughHandlers(lastFuture, n) { if(n < routes.length) { var route = routes[n].route var handler = route[handlerProperty] if(direction === -1) { var originalIndexFromCurrentRoutes = currentRoutes.length - n - 1 var distance = routes.length - n // divergenceDistance } else { var originalIndexFromCurrentRoutes = routeVergenceIndex+n var distance = undefined // no more leafDistance: routes.length - n - 1 // leafDistance } return lastFuture.then(function() { if(handler !== undefined) { if(originalIndexFromCurrentRoutes > 0) { var parentRoute = currentRoutes[originalIndexFromCurrentRoutes-1] var lastValue = parentRoute.route.lastValue } var nextFuture = handler.call(route, lastValue, distance) if(nextFuture !== undefined) { nextFuture.then(function(value) { route.lastValue = value }) // no done because nextFuture's errors are handled elsewhere } } if(nextFuture === undefined) { nextFuture = Future(undefined) } return loopThroughHandlers(nextFuture, n+1) }).catch(function(e){ return handleError(currentRoutes, originalIndexFromCurrentRoutes, type, e, []).then(function() { if(direction === 1) { return Future(n + routeVergenceIndex) } else { // -1 exit handlers return loopThroughHandlers(Future(undefined), n+1) // continue executing the parent exit handlers } }) }) } else { return lastFuture.then(function() { return Future(n + routeVergenceIndex) }).catch(function(e) { throw e // propagate the error not the value }) } }
javascript
{ "resource": "" }
q43798
urlToId
train
function urlToId(hypemUrl) { var trimmedUrl = _.trim(hypemUrl); if (_.startsWith(trimmedUrl, HYPEM_TRACK_URL)) { var parsedUrl = url.parse(hypemUrl); var pathname = parsedUrl.pathname; // '/trach/31jfi/...' var hypemId = pathname.split("/")[2]; return hypemId; } return ""; }
javascript
{ "resource": "" }
q43799
getById
train
function getById(hypemId, callback) { var options = { method: 'HEAD', url: HYPEM_GO_URL + hypemId, followRedirect: false, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (error || response.statusCode !== 302) { callback(error, null); return; } var songUrl = response.headers.location; if (isSoundcloudUrl(songUrl)) { var soundcloudUrl = getNormalizedSoundcloudUrl(songUrl); callback(null, soundcloudUrl); } else { requestHypemKey(hypemId, function (error, hypemKey) { if (error) { callback(error, null); return; } requestMp3Url(hypemId, hypemKey, callback); }); } }); }
javascript
{ "resource": "" }