_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q42600
matchToHolders
train
function matchToHolders(match, tag) { return object(match.map(function(val, index) { return [tag+":"+index, val]; })); }
javascript
{ "resource": "" }
q42601
filterValidRule
train
function filterValidRule(rule) { return (rule.hasOwnProperty('match')&&typeof rule.match === "object") && (rule.hasOwnProperty('use') && ( typeof rule.use === "object" || typeof rule.use === "function" )) && ( (rule.match.hasOwnProperty('request')) || (rule.match.hasOwnProperty('base')) ) }
javascript
{ "resource": "" }
q42602
mapDefaults
train
function mapDefaults(rule) { return Object.assign({}, rule, { match: Object.assign({ request: defaultExpr, base: defaultExpr, module: defaultExpr }, rule.match), use: rule.use, }); }
javascript
{ "resource": "" }
q42603
wrapPlaceholders
train
function wrapPlaceholders(placeholders) { const keys = Object.keys(placeholders); const wrappedPlaceholders = {}; for (let i = 0; i < keys.length; i++) { wrappedPlaceholders['<'+keys[i]+'>'] = placeholders[keys[i]]; } return wrappedPlaceholders; }
javascript
{ "resource": "" }
q42604
isRequiresEarlyResolve
train
function isRequiresEarlyResolve(rules) { for (let i = 0; i < rules.length; ++i) { if ( Object.prototype.hasOwnProperty.call(rules[i], 'module') || (Object.prototype.hasOwnProperty.call(rules[i], 'append') && rules[i].append) ) { return true; } } return false; }
javascript
{ "resource": "" }
q42605
toArray
train
function toArray (id) { if (!isValid(id)) throw new Error('random#toArray: Need valid id'); // Decode var result = []; for (var i = 0; i < id.length; i++) { result.push(baseURL.ALPHABET.indexOf(id[i])); } return result; }
javascript
{ "resource": "" }
q42606
request
train
function request(packet, json) { return _create(packet, 1, (METHODS[packet.method] || '') + packet.resource, json); }
javascript
{ "resource": "" }
q42607
reply
train
function reply(packet, json) { return _create(packet, packet.status || 500, (METHODS[packet.method] || '') + packet.resource, json); }
javascript
{ "resource": "" }
q42608
train
function () { var date = new Date(); date.setHours(0, 0, 0); date.setDate(date.getDate() + 4 - (date.getDay() || 7)); return Math.ceil((((date - new Date(date.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7); }
javascript
{ "resource": "" }
q42609
methodQualified
train
function methodQualified(name, func) { var funcStr = func.toString(); // Only public methodds (i.e. methods that do not start with '_') which have // 'callback' as last parameter are qualified for thunkification. return (/^[^_]/.test(name) && /function.*\(.*,?.*callback\)/.test(funcStr)); }
javascript
{ "resource": "" }
q42610
registerUserTasks
train
function registerUserTasks() { var tasks = options.tasks, task = that.task.bind(that), before = that.before.bind(that), after = that.after.bind(that), taskName; // register user tasks for (taskName in tasks) { if ( tasks.hasOwnProperty(taskName) ) { task(taskName, tasks[taskName]); } } // register predefined user tasks order before('deploy', 'beforeDeploy'); before('updateCode', 'beforeUpdateCode'); after('updateCode', 'afterUpdateCode'); before('npm', 'beforeNpm'); after('npm', 'afterNpm'); before('createSymlink', 'beforeCreateSymlink'); after('createSymlink', 'afterCreateSymlink'); before('restart', 'beforeRestart'); after('restart', 'afterRestart'); after('deploy', 'afterDeploy'); }
javascript
{ "resource": "" }
q42611
combine
train
function combine(...objects) { inv(Array.isArray(objects) && objects.length > 0, 'You must pass at least one object to instantiate' ); inv(objects.every(isObj), 'Expecting only plain objects as parameter(s)' ); return assign({}, ...objects); }
javascript
{ "resource": "" }
q42612
fetchConfiguration
train
function fetchConfiguration(environment, applicationId, callback) { if(!applicationId) { logger.error("No application ID specified"); return; } var deviceDetails = deviceDetector.getDeviceDetails(); var pathname = environment.getPathname(); var formFactor = deviceDetails.formFactor; var requestUrl = ""; var queryParams = {}; if (appSettings.overrides && appSettings.overrides.configFileLocation) { requestUrl = appSettings.overrides.configFileLocation; }else{ requestUrl = appSettings.configurationsApiUrl; queryParams = { path: pathname, device: formFactor, "application_id":applicationId }; } ajax.get({ url: requestUrl, query: queryParams, success: function (data) { if (appSettings.overrides && appSettings.overrides.configFileLocation){ callback(null, data.adUnits); }else{ callback(null, data); } }, error: function (err) { callback(err, null); } }); }
javascript
{ "resource": "" }
q42613
write
train
function write(src, lvl, obj) { var stack = null; var lvlInt = levels[lvl]; var msg; if ( typeof process.env.LOG_LEVEL == "string" && levels[process.env.LOG_LEVEL.toLowerCase()] > lvlInt) { return false; } if (process.env.JSONCONSOLE_DISABLE_JSON_OUTPUT) { return src.write(util.format(obj)+os.EOL); } if (lvlInt >= 40) { if (obj instanceof Error) { stack = obj.stack; } else { stack = new Error().stack.split("\n"); stack.splice(1, 4); // obfuscate the trace inside the logger. stack = stack.join('\n'); } } if (obj instanceof RawValue) { msg = util.inspect(obj.raw); } else if (typeof obj == "string") { msg = obj; } else { msg = util.inspect(obj); } var log = { name: options.name, hostname, pid: process.pid, level: lvlInt, msg: msg, time: options.localDate ? formatLocalDate() : new Date().toISOString(), src: getCaller3Info(), levelName: levelNames[lvlInt], }; if (obj instanceof RawValue) { log.raw = obj.raw; } stack = stack && options.root ? stack.replace(new RegExp(options.root, 'g'), '{root}') : stack; if (stack) { log.stack = stack; } log.v = options.v; log.src.r = options.root; return src.write(JSON.stringify(log) + os.EOL); }
javascript
{ "resource": "" }
q42614
replace
train
function replace() { if (!isOriginal) return; else isOriginal = false; function replaceWith(fn) { return function() { /* eslint prefer-rest-params:0 */ // todo: once node v4 support dropped, use rest parameter instead fn.apply(logger, Array.from(arguments)); }; } ['log', 'debug', 'info', 'warn', 'error'].forEach((lvl) => { console[lvl] = function() { Array.prototype.slice.call(arguments).forEach((arg) => { write(lvl == "error" ? process.stderr : process.stdout, lvl, arg); }); }; }); }
javascript
{ "resource": "" }
q42615
restore
train
function restore() { if (isOriginal) return; else isOriginal = true; ['log', 'debug', 'info', 'warn', 'error'].forEach((item) => { console[item] = originalConsoleFunctions[item]; }); }
javascript
{ "resource": "" }
q42616
setup
train
function setup(userOptions) { Object.assign(options, userOptions); /* Try to automatically grab the app name from the root directory */ if (!options.root) { try { var p = require(path.dirname(process.mainModule.filename) + '/package.json'); options.root = path.dirname(process.mainModule.filename); options.name = p.name; } catch (e) { options.root = null; } } if (options.root && !options.name) { try { var p = require(options.root + '/package.json'); options.name = p.name; } catch (e) { } } /* In production mode, define default log threshold to info */ if (process.env.LOG_LEVEL === undefined && process.env.NODE_ENV === "production") { process.env.LOG_LEVEL = "info"; } options.name = options.name || "."; replace(); return restore; }
javascript
{ "resource": "" }
q42617
train
function(inX, inY) { var o = inX + "px, " + inY + "px" + (this.accel ? ",0" : ""); enyo.dom.transformValue(this.$.client, this.translation, o); }
javascript
{ "resource": "" }
q42618
deus
train
function deus(one, two, fn) { var types = [one, two]; var type = function(args, arg) { var idx = index(types, typeof arg); if(idx > -1 && !args[idx]) args[idx] = arg; else if(arg) args.splice(args.length, 0, arg); }; return function() { var args = [,,]; for(var i = 0, l = arguments.length; i < l; i++) { type(args, arguments[i]); } return fn.apply(this, args); }; }
javascript
{ "resource": "" }
q42619
ensureDoc
train
function ensureDoc($node) { // FIXME if isVNode(node) use cx on node var cx = (0, _vnode.getContext)(this, inode); return (0, _just.default)($node).pipe((0, _operators.concatMap)(function (node) { if (!(0, _vnode.isVNode)(node)) { var type = cx.getType(node); if (type == 9 || type == 11) { var root = cx.first(node); return (0, _just.default)(cx.vnode(root, cx.vnode(node), 1, 0)); } else { // create a document-fragment by default! var doc = t.bind(cx)(); var _root = cx.vnode(node, doc, 1, 0); return (0, _just.default)(doc).pipe((0, _operators.concatMap)(function (doc) { doc = doc.push([0, _root.node]); var next = doc.first(); return next ? (0, _just.default)(doc.vnode(next, doc, doc.depth + 1, 0)) : (0, _just.default)(); })); } } if (typeof node.node === "function") { // NOTE never bind to current node.cx, but purposely allow cross-binding return (0, _just.default)(t.bind(cx)(node)).pipe((0, _operators.concatMap)(function (node) { var next = node.first(); return next ? (0, _just.default)(node.vnode(next, node, node.depth + 1, 0)) : (0, _just.default)(); })); } return (0, _just.default)(node); })); }
javascript
{ "resource": "" }
q42620
Tree2Json
train
function Tree2Json(inputTree) { if (!(this instanceof Tree2Json)) return new Tree2Json(inputTree); this.inputTree = inputTree.replace(/\/$/, ''); this.walker = new TreeTraverser(inputTree, this); }
javascript
{ "resource": "" }
q42621
cov
train
function cov(x) { // Useful variables let N = x.length; // Step 1: Find expected value for each variable (columns are variables, rows are samples) let E = []; for (let c = 0; c < x[0].length; c++) { let u = 0; for (let r = 0; r < N; r++) { u += x[r][c]; } E.push(u / N); } // Step 2: Center each variable at 0 let centered = []; for (let r = 0; r < N; r++) { centered.push([]); for (let c = 0; c < x[0].length; c++) { centered[r].push(x[r][c] - E[c]); } } // Step 3: Calculate covariance between each possible combination of variables let S = []; for (let i = 0; i < x[0].length; i++) { S.push([]); } for (let c1 = 0; c1 < x[0].length; c1++) { // Doing c2 = c1; because, for example, cov(1,2) = cov(2, 1) // so no need to recalculate for (let c2 = c1; c2 < x[0].length; c2++) { // Solve cov(c1, c2) = average of elementwise products of each variable sample let cov = 0; for (let r = 0; r < N; r++) { cov += centered[r][c1] * centered[r][c2]; } cov /= (N - 1); // N-1 for sample covariance, N for population. In this case, using sample covariance S[c1][c2] = cov; S[c2][c1] = cov; // Matrix is symmetric } } return S; }
javascript
{ "resource": "" }
q42622
mean
train
function mean(x) { let result = []; for(let c = 0; c<x[0].length; c++){ result.push(0); } for (let r = 0; r < x.length; r++) { for(let c = 0; c<x[r].length; c++){ result[c] += x[r][c]; } } for(let c = 0; c<x[0].length; c++){ result[c] /= x.length; } return result; }
javascript
{ "resource": "" }
q42623
train
function (config) { config = config || {}; this.api_key = config.api_key; this.host = config.host || undefined; this.api_version = config.api_version || undefined; this.dev_mode = config.dev_mode || false; return this; }
javascript
{ "resource": "" }
q42624
train
function (context_uid, sender, receiver, channel, message, meta) { if (!this.api_key) throw new ChangeTipException(300); if (!channel) throw new ChangeTipException(301); var deferred = Q.defer(), data; data = { context_uid: context_uid, sender: sender, receiver: receiver, channel: channel, message: message, meta: meta }; this._send_request(data, 'tips', null, Methods.POST, deferred); return deferred.promise; }
javascript
{ "resource": "" }
q42625
train
function (tips, channel) { if (!this.api_key) throw new ChangeTipException(300); var deferred = Q.defer(), params; params = { tips: tips instanceof Array ? tips.join(",") : tips, channel: channel || '' }; this._send_request({}, 'tips', params, Methods.GET, deferred); return deferred.promise; }
javascript
{ "resource": "" }
q42626
train
function (data, path, params, method, deferred) { var options, query_params, req, dataString = JSON.stringify(data); query_params = querystring.stringify(params); options = { host: this.host, port: 443, path: '/v' + this.api_version + '/' + path + '/?api_key=' + this.api_key + (query_params ? ('&' + query_params) : ''), method: method, headers: { 'Content-Type': 'application/json', 'Content-Length': dataString.length } }; if (!this.dev_mode) { req = https.request(options, function (res) { res.setEncoding('utf-8'); var response = '', result; res.on('data', function (response_data) { response += response_data; }); res.on('end', function () { result = JSON.parse(response); deferred.resolve(result); }); }); req.write(dataString); req.end(); } else { deferred.resolve({status:"dev_mode", data: data, params: params, path: options.path}); } }
javascript
{ "resource": "" }
q42627
quickTemplate
train
function quickTemplate (pTemplate, pValues) { return pTemplate.replace(templateRegex, function(i, pMatch) { return pValues[pMatch]; }); }
javascript
{ "resource": "" }
q42628
ObjectInfo
train
function ObjectInfo(name, contentType) { this._name = name; this._type = contentType || ObjectInfo.DEFAULT_CONTENT_TYPE; this._partial = false; }
javascript
{ "resource": "" }
q42629
initCheckApi
train
function initCheckApi(logger, config) { return new Promise((resolve, reject) => { var check = new Check(logger, config); var promises = []; var checkers = require('mazaid-checkers'); for (var checker of checkers) { promises.push(check.add(checker)); } Promise.all(promises) .then(() => { return check.init(); }) .then(() => { checkApi = check; resolve(); }) .catch((error) => { reject(error); }); }); }
javascript
{ "resource": "" }
q42630
runCheckTask
train
function runCheckTask(logger, checkTask) { return new Promise((resolve, reject) => { // create check task object // raw.id = uuid(); // var checkTask = new CheckTask(raw); // validate check task checkTask.validate(logger) .then((checkTask) => { // set check task status to queued checkTask.queued(); // prepare exec task by check task data return checkApi.prepare(checkTask); }) .then((execData) => { // create exec task and validate execData.id = uuid(); checkTask.execTaskId = execData.id; var execTask = new ExecTask(execData); return execTask.validate(); }) .then((execTask) => { // set check task to started checkTask.started(); // execute exec task return exec(logger, execTask); }) .then((execTask) => { // got exec task response and parse it return checkApi.parse(checkTask, execTask); }) .then((parsedResult) => { // got parsed response // set to check task checkTask.rawResult = parsedResult; // run analyze stage return checkApi.analyze(checkTask); }) .then((result) => { // got status and message result, and custom checker data in result // set result to check task and validate checkTask.result = result; checkTask.finished(); return checkTask.validate(); }) .then((task) => { resolve(task); }) .catch((error) => { checkTask.result = { status: 'fail', message: error.message }; error.checkTask = checkTask; reject(error); }); }); }
javascript
{ "resource": "" }
q42631
parseRequires
train
function parseRequires(js) { return js .replace(/require\('events'\)/g, "require('browser/events')") .replace(/require\('debug'\)/g, "require('browser/debug')") .replace(/require\('path'\)/g, "require('browser/path')") .replace(/require\('diff'\)/g, "require('browser/diff')") .replace(/require\('tty'\)/g, "require('browser/tty')") .replace(/require\('fs'\)/g, "require('browser/fs')") }
javascript
{ "resource": "" }
q42632
train
function(obj, parts) { if (parts.length === 0) { return true; } var key = parts.shift(); if (!_(obj).has(key)) { return false; } else { return hasKeyPath(obj[key], parts); } }
javascript
{ "resource": "" }
q42633
train
function(obj, env, keypath) { if (!_.isObject(obj) || _.isArray(obj)) { return; } if (hasKeyPath(obj, ['options', 'reconfigureOverrides', env])) { var options = obj.options, overrides = obj.options.reconfigureOverrides[env]; for (var key in overrides) { var update = { key: keypath+'.options.'+key, oldVal: (typeof options[key] === 'undefined') ? 'undefined' : util.inspect(options[key]), }; if (_.isObject(options[key]) && _.isObject(overrides[key])) { var newVal = _.extend(options[key], overrides[key]); update.newVal = util.inspect(newVal); } else { options[key] = overrides[key]; update.newVal = util.inspect(overrides[key]); } updates.push(update); } } for (var objKey in obj) { updateOptions(obj[objKey], env, keypath+'.'+objKey); } }
javascript
{ "resource": "" }
q42634
pushLogEntry
train
function pushLogEntry(logEntry) { var logger = window[appSettings.loggerVar]; if (logger) { logger.logs.push(logEntry); if (window.console) { if (typeof console.error === "function" && typeof console.warn === "function") { switch (logEntry.type) { case enumerations.logType.wtf: console.error(toFriendlyString(logEntry)); break; case enumerations.logType.error: if (appSettings.logLevel <= enumerations.logLevel.error && appSettings.logLevel > enumerations.logLevel.off) { console.error(toFriendlyString(logEntry)); } break; case enumerations.logType.warning: if (appSettings.logLevel <= enumerations.logLevel.warn && appSettings.logLevel > enumerations.logLevel.off) { console.warn(toFriendlyString(logEntry)); } break; default: if (appSettings.logLevel <= enumerations.logLevel.debug && appSettings.logLevel > enumerations.logLevel.off) { console.log(toFriendlyString(logEntry)); break; } } } else { console.log(toFriendlyString(logEntry)); } } } }
javascript
{ "resource": "" }
q42635
getCurrentTimeString
train
function getCurrentTimeString() { var today = new Date(); var hh = today.getHours(); var mm = today.getMinutes(); //January is 0 var ss = today.getSeconds(); var ms = today.getMilliseconds(); if (hh < 10) { hh = '0' + hh; } if (mm < 10) { mm = '0' + mm; } if (ss < 10) { ss = '0' + ss; } if (ms < 10) { ms = '0' + ms; } return hh + ":" + mm + ":" + ss + ":" + ms; }
javascript
{ "resource": "" }
q42636
read_from_source
train
function read_from_source(codestr, filenameOrLexer, options) { var lexer; if(typeof filenameOrLexer === 'string') { lexer = initLexerFor(codestr, filenameOrLexer, options); } else { lexer = filenameOrLexer; lexer.set_source_text(codestr, options); } // read the forms var forms = read(lexer); // it's useful to sometimes look "up" the lexical nesting of forms... // to make this easy/reliable - walk the form tree setting "parent" // I SHOULD TIME THIS? IF IT'S EXPENSIVE - I'M NOT SURE I EVEN NEED IT ANYMORE? if(options.setParents !== 'no' && forms.setParents) { forms.setParents(); } return forms; }
javascript
{ "resource": "" }
q42637
unuse_dialect
train
function unuse_dialect(dialectName, lexer, options) { options = options || {}; if(dialectName && options.validate && lexer.dialects[0].name !== dialectName) { lexer.error('Attempt to exit dialect "' + dialectName + '" while "' + lexer.dialects[0].name + '" was still active'); } slinfo('removing dialect', dialectName ? ": " + dialectName : ""); var removedDialect = lexer.pop_dialect(dialectName); if(!removedDialect) { lexer.error('The dialect ' + (dialectName ? '"' + dialectName + '"': '') + ' has never been used'); } }
javascript
{ "resource": "" }
q42638
invokeInitDialectFunctions
train
function invokeInitDialectFunctions(dialect, lexer, options) { var initfnkey = "__init"; if(dialect[initfnkey]) { dialect[initfnkey](lexer, dialect, options); } if(dialect.lextab[initfnkey]) { dialect.lextab[initfnkey](lexer, dialect, options); } if(dialect.readtab[initfnkey]) { dialect.readtab[initfnkey](lexer, dialect, options); } if(dialect.gentab[initfnkey]) { dialect.gentab[initfnkey](lexer, dialect, options); } }
javascript
{ "resource": "" }
q42639
read
train
function read(lexer, precedence) { precedence = precedence || 0; var form = read_via_closest_dialect(lexer); // are we a prefix unary operator? var leftForm = form; if(sl.isAtom(form)) { var opSpec = getOperatorSpecFor(form, lexer.dialects); if(opSpec && isEnabled(opSpec.prefix) && opSpec.prefix.transform && // "nospace" prefix ops must butt up against their arg so // "--i" not "-- i" this way we can't confuse e.g. (- x y) // with (-x y) (!opSpec.options || !opSpec.options.nospace || !lexer.onwhitespace(-1))) { leftForm = opSpec.prefix.transform(lexer, opSpec.prefix, form); } } // note flipped check below from < to > because our precedences // are currently as you see them here: http://www.scriptingmaster.com/javascript/operator-precedence.asp // not as you see them here: http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/ var token, opSpecObj; while(!lexer.eos() && (token = lexer.peek_token()) && (opSpecObj = getOperatorSpecFor(token.text, lexer.dialects)) && opSpecObj && (isEnabled(opSpecObj.infix) || isEnabled(opSpecObj.postfix))) { // make sure we don't misinterpet e.g. "(get ++i)" as "(get++ i)" if(opSpecObj.prefix && opSpecObj.postfix && (lexer.onwhitespace(-1) && !lexer.onwhitespace(token.text.length))) { break; // let it be prefix next time round } // we don't distinguish infix from postfix below: var opSpec = opSpecObj.infix || opSpecObj.postfix; // we only keep scanning if we're hitting *higher* precedence if((opSpec.precedence || 0) <= precedence) { trace("read of infix/postfix stopping because op precedence " + (opSpec.precedence || 0) + " is <= the current precendence of " + precedence); break; // stop scanning } token = lexer.next_token(); leftForm = opSpec.transform(lexer, opSpec, leftForm, sl.atom(token)); } if(sl.isList(leftForm)) { // now that we've finished reading the list, // pop any local dialects whose scope has ended pop_local_dialects(lexer, leftForm); } return leftForm; }
javascript
{ "resource": "" }
q42640
read_via_closest_dialect
train
function read_via_closest_dialect(lexer, options) { trace(lexer.message_src_loc("", lexer, {file:false})); // options allow this function to be used when a readtab // handler needs to read by invoking a handler that it's // overridden, without knowing what dialect was overridden. // (see invoke_readfn_overridden_by below) options = options || {}; // normally we start with the close dialect (0) var startingDialect = options.startingDialect || 0; // And normally we read the source text under the current position // unless they give us a token that's already been read) var token = options.token; if(!token) { // we *peek* when determining which readtab read function to call, // so the read functions can consume the *entire* form, including the // first token (which makes the design of the read functions easier // easier to understand and test in isolation). token = lexer.peek_token(); } debug('reading expression starting "' + token.text + '"'); var form = retry; var readfn; // try the dialects from beginning (inner scope) to end (outer scope)... for(var i = startingDialect; isretry(form) && i < lexer.dialects.length; i++) { var dialect = lexer.dialects[i]; debug('looking for "' + token.text + '" in ' + dialect.name + ' readtab'); readfn = findReadfn(dialect.readtab, token) if(readfn) { form = read_via_readfn(readfn, lexer, token.text); if(!form) { lexer.error('Invalid response from "' + token.text + '" readtab function in "' + dialect.name + '"'); } } } // if we've tried all the dialects and either didn't find a match, // or found a match that returned "reader.retry"... if(isretry(form)) { // try all the dialects again, this time looking for "__default" // note: most likely this will get all the way to core's __default, // but dialect's *can* override __default if they need to, and // could e.g. "selectively" override it by returning reader.retry in // cases where they want core's __default to handle it instead. for(var i = startingDialect; isretry(form) && i < lexer.dialects.length; i++) { var dialect = lexer.dialects[i]; debug('looking for "__default" in ' + dialect.name + ' readtab'); readfn = dialect.readtab !== undefined ? dialect.readtab['__default'] : undefined; if(readfn) { form = read_via_readfn(readfn, lexer, token.text); if(!form) { lexer.error('Invalid response for "' + token.text + '" returned by __default function in "' + dialect.name + '"'); } } } } // this should never happen (because of __default) but JIC: if(!form || isretry(form)) { lexer.error('No dialect handled the text starting "' + lexer.snoop(10) + '...'); } return form; }
javascript
{ "resource": "" }
q42641
pop_local_dialects
train
function pop_local_dialects(lexer, list) { if(list && list.length > 0) { // we go in reverse order since the most recently // used (pushed) dialects will be at the end for(var i = list.length-1; i >= 0; i--) { if(list[i].dialect) { unuse_dialect(list[i].dialect, lexer); } } } }
javascript
{ "resource": "" }
q42642
read_delimited_text
train
function read_delimited_text(lexer, start, end, options) { options = options || {includeDelimiters: true}; var delimited = lexer.next_delimited_token(start, end, options); return sl.atom(delimited); }
javascript
{ "resource": "" }
q42643
symbol
train
function symbol(lexer, text) { var token = lexer.next_token(text); return sl.atom(text, {token: token}); }
javascript
{ "resource": "" }
q42644
callback
train
function callback(req, res, resolve, reject, error, result, permissions, action) { if (error) { reqlog.error('internal server error', error); if (exports.handleErrors) { responseBuilder.error(req, res, 'INTERNAL_SERVER_ERROR'); } else { reject(error); } } else { // filter the result attributes to send only those that this userType can see // check if the result is an array, to iterate it if (Array.isArray(result)) { for (var i = 0, length = result.length; i < length; i++) { result[i] = filterAttributes(result[i], permissions); } } else { result = filterAttributes(result, permissions); } reqlog.info(action + '.success', result); resolve(result); } /** * Delete the attributes that the activeUser cant see * @method filterAttributes * @param {object} object The result object * @param {object} permissions The permissions object * @return {object} The filtered object */ function filterAttributes(object, permissions) { if (object) { var userType = req.activeUser && req.activeUser.type || 'null'; for (var attribute in object._doc) { if (object._doc.hasOwnProperty(attribute)) { // dont return this attribute when: if (!permissions[attribute] || // if this attribute is not defined in permissions permissions[attribute][0] !== 'null' && // this attribute is not set as public permissions[attribute].indexOf(userType) === -1 && // this attribute is not available to this userType userType !== 'admin' // the user is not admin ) { delete object._doc[attribute]; } } } } return object; } }
javascript
{ "resource": "" }
q42645
filterAttributes
train
function filterAttributes(object, permissions) { if (object) { var userType = req.activeUser && req.activeUser.type || 'null'; for (var attribute in object._doc) { if (object._doc.hasOwnProperty(attribute)) { // dont return this attribute when: if (!permissions[attribute] || // if this attribute is not defined in permissions permissions[attribute][0] !== 'null' && // this attribute is not set as public permissions[attribute].indexOf(userType) === -1 && // this attribute is not available to this userType userType !== 'admin' // the user is not admin ) { delete object._doc[attribute]; } } } } return object; }
javascript
{ "resource": "" }
q42646
hasNext
train
function hasNext(cursor, callback) { const Cursor = require('../cursor'); if (cursor.s.currentDoc) { return callback(null, true); } if (cursor.isNotified()) { return callback(null, false); } nextObject(cursor, (err, doc) => { if (err) return callback(err, null); if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) return callback(null, false); if (!doc) return callback(null, false); cursor.s.currentDoc = doc; callback(null, true); }); }
javascript
{ "resource": "" }
q42647
nextObject
train
function nextObject(cursor, callback) { const Cursor = require('../cursor'); if (cursor.s.state === Cursor.CLOSED || (cursor.isDead && cursor.isDead())) return handleCallback( callback, MongoError.create({ message: 'Cursor is closed', driver: true }) ); if (cursor.s.state === Cursor.INIT && cursor.s.cmd.sort) { try { cursor.s.cmd.sort = formattedOrderClause(cursor.s.cmd.sort); } catch (err) { return handleCallback(callback, err); } } // Get the next object cursor._next((err, doc) => { cursor.s.state = Cursor.OPEN; if (err) return handleCallback(callback, err); handleCallback(callback, null, doc); }); }
javascript
{ "resource": "" }
q42648
toArray
train
function toArray(cursor, callback) { const Cursor = require('../cursor'); const items = []; // Reset cursor cursor.rewind(); cursor.s.state = Cursor.INIT; // Fetch all the documents const fetchDocs = () => { cursor._next((err, doc) => { if (err) { return cursor._endSession ? cursor._endSession(() => handleCallback(callback, err)) : handleCallback(callback, err); } if (doc == null) { return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); } // Add doc to items items.push(doc); // Get all buffered objects if (cursor.bufferedCount() > 0) { let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); // Transform the doc if transform method added if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { docs = docs.map(cursor.s.transforms.doc); } push.apply(items, docs); } // Attempt a fetch fetchDocs(); }); }; fetchDocs(); }
javascript
{ "resource": "" }
q42649
get
train
function get(key, store = getDefaultStore()) { let req return store[IDBStore]('readonly', store => { req = store.get(key) }).then(() => req.result) }
javascript
{ "resource": "" }
q42650
train
function( config ) { !is_obj( config ) || Object.keys( config ).forEach( function( key ) { if ( typeof config[key] == 'function' && typeof this[key] == 'function' ) // this allows you to override a method for a this[__override__]( key, config[key] ); // specific instance of a Class, rather than require else // you extend the Class for a few minor changes this[key] = config[key]; // NB: can also be achieved by creating a `singleton` }, this ); util.def( this, __config__, { value : config }, 'r', true ); }
javascript
{ "resource": "" }
q42651
makeBookmarkedTabItem
train
function makeBookmarkedTabItem(bm) { var urlStr = bm.url; if (!urlStr) { console.error('makeBookmarkedTabItem: Malformed bookmark: missing URL!: ', bm); urlStr = ''; // better than null or undefined! } if (bm.title === undefined) { console.warn('makeBookmarkedTabItem: Bookmark title undefined (ignoring...): ', bm); } var tabItem = new TabItem({ url: urlStr, saved: true, savedTitle: _.get(bm, 'title', urlStr), savedBookmarkId: bm.id, savedBookmarkIndex: bm.index }); return tabItem; }
javascript
{ "resource": "" }
q42652
makeOpenTabItem
train
function makeOpenTabItem(tab) { var urlStr = tab.url; if (!urlStr) { console.error('malformed tab -- no URL: ', tab); urlStr = ''; } /* if (!tab.title) { console.warn("tab missing title (ignoring...): ", tab); } */ var tabItem = new TabItem({ url: urlStr, audible: tab.audible, favIconUrl: tab.favIconUrl, open: true, tabTitle: _.get(tab, 'title', urlStr), openTabId: tab.id, active: tab.active, openTabIndex: tab.index }); return tabItem; }
javascript
{ "resource": "" }
q42653
mergeOpenTabs
train
function mergeOpenTabs(tabItems, openTabs) { var tabInfo = getOpenTabInfo(tabItems, openTabs); /* TODO: Use algorithm from OLDtabWindow.js to determine tab order. * For now, let's just concat open and closed tabs, in their sorted order. */ var openTabItems = tabInfo.get(true, Immutable.Seq()).sortBy(function (ti) { return ti.openTabIndex; }); var closedTabItems = tabInfo.get(false, Immutable.Seq()).sortBy(function (ti) { return ti.savedBookmarkIndex; }); var mergedTabItems = openTabItems.concat(closedTabItems); return mergedTabItems; }
javascript
{ "resource": "" }
q42654
updateWindow
train
function updateWindow(tabWindow, chromeWindow) { // console.log("updateWindow: ", tabWindow.toJS(), chromeWindow); var mergedTabItems = mergeOpenTabs(tabWindow.tabItems, chromeWindow.tabs); var updWindow = tabWindow.set('tabItems', mergedTabItems).set('focused', chromeWindow.focused).set('open', true).set('openWindowId', chromeWindow.id); return updWindow; }
javascript
{ "resource": "" }
q42655
saveTab
train
function saveTab(tabWindow, tabItem, tabNode) { var _tabWindow$tabItems$f3 = tabWindow.tabItems.findEntry(function (ti) { return ti.open && ti.openTabId === tabItem.openTabId; }); var _tabWindow$tabItems$f4 = _slicedToArray(_tabWindow$tabItems$f3, 1); var index = _tabWindow$tabItems$f4[0]; var updTabItem = tabItem.set('saved', true).set('savedTitle', tabNode.title).set('savedBookmarkId', tabNode.id).set('savedBookmarkIndex', tabNode.index); var updItems = tabWindow.tabItems.splice(index, 1, updTabItem); return tabWindow.set('tabItems', updItems); }
javascript
{ "resource": "" }
q42656
pushin
train
function pushin( path, record, setter, newValue ) { var context = record; var parent = record; var lastPart = null; var _i; var _len; var part; var keys; for ( _i = 0, _len = path.length; _i < _len; _i++ ) { part = path[_i]; lastPart = part; parent = context; context = context[part]; if ( sys.isNull( context ) || sys.isUndefined( context ) ) { parent[part] = {}; context = parent[part]; } } if ( sys.isEmpty( setter ) || setter === '$set' ) { parent[lastPart] = newValue; return parent[lastPart]; } else { switch ( setter ) { case '$inc': /** * Increments a field by the amount you specify. It takes the form * `{ $inc: { field1: amount } }` * @name $inc * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * probe.update( obj, {'name.last' : 'Owen', 'name.first' : 'LeRoy'}, * {$inc : {'password.changes' : 2}} ); */ if ( !sys.isNumber( newValue ) ) { newValue = 1; } if ( sys.isNumber( parent[lastPart] ) ) { parent[lastPart] = parent[lastPart] + newValue; return parent[lastPart]; } break; case '$dec': /** * Decrements a field by the amount you specify. It takes the form * `{ $dec: { field1: amount }` * @name $dec * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * probe.update( obj, {'name.last' : 'Owen', 'name.first' : 'LeRoy'}, * {$dec : {'password.changes' : 2}} ); */ if ( !sys.isNumber( newValue ) ) { newValue = 1; } if ( sys.isNumber( parent[lastPart] ) ) { parent[lastPart] = parent[lastPart] - newValue; return parent[lastPart]; } break; case '$unset': /** * Removes the field from the object. It takes the form * `{ $unset: { field1: "" } }` * @name $unset * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * probe.update( data, {'name.first' : 'Yogi'}, {$unset : {'name.first' : ''}} ); */ return delete parent[lastPart]; case '$pop': /** * The $pop operator removes the first or last element of an array. Pass $pop a value of 1 to remove the last element * in an array and a value of -1 to remove the first element of an array. This will only work on arrays. Syntax: * `{ $pop: { field: 1 } }` or `{ $pop: { field: -1 } }` * @name $pop * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * // attr is the name of the array field * probe.update( data, {_id : '511d18827da2b88b09000133'}, {$pop : {attr : 1}} ); */ if ( sys.isArray( parent[lastPart] ) ) { if ( !sys.isNumber( newValue ) ) { newValue = 1; } if ( newValue === 1 ) { return parent[lastPart].pop(); } else { return parent[lastPart].shift(); } } break; case '$push': /** * The $push operator appends a specified value to an array. It looks like this: * `{ $push: { <field>: <value> } }` * @name $push * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * // attr is the name of the array field * probe.update( data, {_id : '511d18827da2b88b09000133'}, * {$push : {attr : {"hand" : "new", "color" : "new"}}} ); */ if ( sys.isArray( parent[lastPart] ) ) { return parent[lastPart].push( newValue ); } break; case '$pull': /** * The $pull operator removes all instances of a value from an existing array. It looks like this: * `{ $pull: { field: <query> } }` * @name $pull * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * // attr is the name of the array field * probe.update( data, {'email' : 'EWallace.43@fauxprisons.com'}, * {$pull : {attr : {"color" : "green"}}} ); */ if ( sys.isArray( parent[lastPart] ) ) { keys = exports.findKeys( parent[lastPart], newValue ); sys.each( keys, function ( val, index ) { return delete parent[lastPart][index]; } ); parent[lastPart] = sys.compact( parent[lastPart] ); return parent[lastPart]; } } } }
javascript
{ "resource": "" }
q42657
handle
train
function handle(options, callback) { if (_.isString(options)) { options = { path: options }; } if (_.isObject(options)) { const opts = { }; _.merge(opts, config, options); options = opts; } else { options = _.cloneDeep(config); } options.path = options.path || config.get("home"); return stat(options.path, function(err, stats) { if (err) { return callback(err); } const done = wrap(stats, callback); if (stats.isDirectory()) { options.dirStats = stats; return processDir(options, done); } else if (stats.isFile()) { return processFile(options, done); } return callback(null, null); }); }
javascript
{ "resource": "" }
q42658
Component
train
function Component(opts) { if (typeof opts === "function") { var _constructor = opts;opts = null; return register(_constructor); } opts = opts || {}; var _opts = opts; var _opts$restrict = _opts.restrict; var restrict = _opts$restrict === undefined ? "EA" : _opts$restrict; var _opts$replace = _opts.replace; var replace = _opts$replace === undefined ? false : _opts$replace; var _opts$transclude = _opts.transclude; var transclude = _opts$transclude === undefined ? false : _opts$transclude; var _opts$scope = _opts.scope; var scope = _opts$scope === undefined ? {} : _opts$scope; var template = _opts.template; var templateUrl = _opts.templateUrl; return register; function register(constructor) { (0, _Controller.Controller)(constructor); var meta = (0, _utils.funcMeta)(constructor); var name = meta.name; name = name[0].toLowerCase() + name.substr(1, name.length - DEFAULT_SUFFIX.length - 1); if (!template && !templateUrl && template !== false) { var tmplName = (0, _utils.dashCase)(name); templateUrl = "./components/" + tmplName + "/" + tmplName + ".html"; } if (template === false) { template = undefined; templateUrl = undefined; } _app.app.directive(name, function () { return { restrict: restrict, scope: scope, bindToController: true, controller: meta.controller.name, controllerAs: name, template: template, templateUrl: templateUrl, replace: replace, transclude: transclude }; }); } }
javascript
{ "resource": "" }
q42659
safesocket
train
function safesocket (expected, fn) { return function () { var _args = []; for (var idx in arguments) { _args.push(arguments[idx]); } var args = _args.filter(notFunction).slice(0, expected); for (var i = args.length; i < expected; i++) { args.push(undefined); } var arg = _args.pop(); args.push((arg instanceof Function) ? arg : noop); fn.apply(this, args); }; }
javascript
{ "resource": "" }
q42660
Scrib
train
function Scrib(adapters, callback) { EventEmitter.call(this); // Convert array to object if(Array.isArray(adapters)) { var am = adapters; adapters = {}; am.forEach(function(m) { adapters[m] = {}; }); } var all = [], self = this; for(var m in adapters) { try { var adapter; try { adapter = require("scrib-" + m); } catch(e) { adapter = require(path.join(path.dirname(module.parent.filename), m)); } all.push(async.apply(adapter, self, adapters[m])); } catch(e) { return callback(e); } } async.parallel(all, function done(err) { callback(err); }); }
javascript
{ "resource": "" }
q42661
train
function(header, key, cert) { var parsedHeader; if (header) { if (!header.isBase64()) { throw new CError('missing header or wrong format').log(); } else { parsedHeader = JSON.parse(forge.util.decode64(header)); this.isModeAllowed.call(this, parsedHeader.payload.mode); } var Handshake = app.class.Handshake, Authentication = app.class.Authentication, Authorization = app.class.Authorization, mode = parsedHeader.payload.mode, sid = parsedHeader.payload.sid, result = {}; var options = { sid: sid, key: key || config.key, cert: cert || config.cert }; switch (mode) { case 'handshake': result.header = new Handshake(options); break; case 'auth-init': result.header = new Authentication(options); break; default : result.header = new Authorization(options); break; } try { var ecryptedSecret = parsedHeader.payload.secret; if (ecryptedSecret) { var secret = result.header.keychain.decryptRsa(ecryptedSecret); result.header.setSecret(secret); } parsedHeader.content = result.header.decryptContent(parsedHeader.content); } catch (e) { throw new CError({ body: { code: 'ImATeapot', message: 'unable to decrypt content', cause: e } }).log('body'); } delete result.header; if (debug) { log.debug('%s parsed header', app.name); log.debug(parsedHeader); } } return parsedHeader; }
javascript
{ "resource": "" }
q42662
train
function(data) { try { data = data || this.getContent(); return this.keychain.sign(JSON.stringify(data)); } catch(e) { throw new CError({ body: { code: 'ImATeapot', message: 'unable to sign content', cause: e } }).log('body'); } }
javascript
{ "resource": "" }
q42663
train
function() { var content = this.getContent(); var out = { payload: this.getPayload(), content: this.cryptContent(content), signature: this.generateSignature() }; if (debug) { log.debug('%s encode with sid %s', app.name, out.payload.sid); log.debug('%s encode with token %s', app.name, content.token); } return forge.util.encode64(JSON.stringify(out)); }
javascript
{ "resource": "" }
q42664
stringIterator
train
function stringIterator(str) { let index = 0; return { next() { return index < bmpLength(str) ? { value: bmpCharAt(str, index++), done: false } : { done: true }; } }; }
javascript
{ "resource": "" }
q42665
objectIterator
train
function objectIterator(obj, sort, kv = false) { let keys = Object.keys(obj); keys = typeof sort === 'function' ? keys.sort(sort) : keys.sort(); let index = 0; return { next() { if (index < keys.length) { const k = keys[index++]; const value = {}; if (kv) { value.k = k; value.v = obj[k]; } else { value[k] = obj[k]; } return { value, done: false }; } return { done: true }; } }; }
javascript
{ "resource": "" }
q42666
functionIterator
train
function functionIterator(fn) { return function* () { let current; let index = 0; for (;;) { current = fn(index++, current); if (current === undefined) { break; } yield current; } }(); }
javascript
{ "resource": "" }
q42667
isKvFormObject
train
function isKvFormObject(obj) { const keys = Object.keys(obj); if (keys.length !== 2) { return false; } return !!~keys.indexOf('k') && !!~keys.indexOf('v'); }
javascript
{ "resource": "" }
q42668
isIterable
train
function isIterable(obj) { return isImplemented(obj, 'iterator') || isString(obj) || isArray(obj) || isObject(obj); }
javascript
{ "resource": "" }
q42669
relationship
train
function relationship(mood) { var verb = void 0, talk = void 0; if (mood === "good") { verb = "strengthened"; talk = "discussion"; } else { verb = "strained"; talk = "argument"; } var familiar_people = _word_library2.default.getWords("familiar_people"); var conversation_topics = _word_library2.default.getWords("conversation_topics"); var person = nu.chooseFrom(familiar_people); var topic = nu.chooseFrom(conversation_topics); var sentence = 'Your relationship with ' + person + ' may be ' + verb + ' '; sentence += 'as the result of ' + nu.an(talk) + ' about ' + topic; return nu.sentenceCase(sentence); }
javascript
{ "resource": "" }
q42670
datePredict
train
function datePredict() { var daysAhead = Math.floor(Math.random() * 5) + 2; var day = new Date(); day.setDate(day.getDate() + daysAhead); var monthStr = (0, _dateformat2.default)(day, "mmmm"); var dayStr = (0, _dateformat2.default)(day, "d"); var rnum = Math.floor(Math.random() * 10); var str = void 0; if (rnum <= 4) { str = monthStr + ' ' + dayStr + ' will be an important day for you'; } else if (rnum <= 7) { str = 'Interesting things await you on ' + monthStr + ' ' + dayStr; } else { str = 'The events of ' + monthStr + ' ' + dayStr + ' have the potential to change your life.'; } return nu.sentenceCase(str); }
javascript
{ "resource": "" }
q42671
modifyStatsObject
train
function modifyStatsObject ( stats, path ) { stats.path = path; stats.basename = fs.basename(path); stats.dirname = fs.dirname(path); stats.extname = fs.extname(path); return stats; }
javascript
{ "resource": "" }
q42672
parse
train
function parse() { var msie = /MSIE.(\d+)/i.exec(ua); var rv = /Trident.+rv:(\d+)/i.exec(ua); var version = msie || rv || undefined; return version ? +version[1] : version; }
javascript
{ "resource": "" }
q42673
stat
train
function stat(path, callback) { if (!callback) return stat.bind(this, path); fs.lstat(path, function (err, stat) { if (err) return callback(err); var ctime = stat.ctime / 1000; var cseconds = Math.floor(ctime); var mtime = stat.mtime / 1000; var mseconds = Math.floor(mtime); var mode; if (stat.isSymbolicLink()) { mode = 0120000; } else if (stat.mode & 0111) { mode = 0100755; } else { mode = 0100644; } callback(null, { ctime: [cseconds, Math.floor((ctime - cseconds) * 1000000000)], mtime: [mseconds, Math.floor((mtime - mseconds) * 1000000000)], dev: stat.dev, ino: stat.ino, mode: mode, uid: stat.uid, gid: stat.gid, size: stat.size }); }); }
javascript
{ "resource": "" }
q42674
find
train
function find(param) { var fn , asInt = Number(param); fn = isNaN(asInt) ? findBySlug : findById; fn.apply(null, arguments); }
javascript
{ "resource": "" }
q42675
update
train
function update(id, body, cb) { body.updated_at = new Date(); var q = qb.update(id, body); db.getClient(function(err, client, done) { client.query(q[0], q[1], function(err, r) { var result = r && r.rows[0]; if(!err && !result) { err = new exceptions.NotFound(); } if(err) { cb(err); done(err); } else { cb(null, result); done(); } }); }); }
javascript
{ "resource": "" }
q42676
archive
train
function archive(cb) { db.getClient(function(err, client, done) { client.query(qb.select() + ' WHERE published = true', function(err, r) { if(err) { cb(err); done(err); } else { cb(null, r.rows); done(); } }); }); }
javascript
{ "resource": "" }
q42677
getTargetSize
train
function getTargetSize(size, buffer) { size *= 1000000; // Converting to MB to B. // 10% is default. buffer = 1 + (buffer ? buffer / 100 : 0.1); return Math.round(size * buffer); }
javascript
{ "resource": "" }
q42678
shrinkImage
train
function shrinkImage(base64Image, targetSize) { return new Promise( (resolve, reject) => { let canvas = document.createElement('canvas'); let image = new Image(); image.onload = _ => { canvas.height = image.naturalHeight; canvas.width = image.naturalWidth; canvas.getContext('2d').drawImage(image, 0, 0); return resolve(shrink(95)); function shrink(quality) { let redrawnImage = canvas.toDataURL('image/jpeg', quality/100); // 1. Stop at zero because quality can't get any worse! // 2. Base64 encoded images are 1.33 times larger than once they are converted back to a blob. return quality !== 0 && redrawnImage.length / 1.33 > targetSize ? shrink(quality - 5) : redrawnImage; } }; image.src = base64Image; }); }
javascript
{ "resource": "" }
q42679
base64ToBlob
train
function base64ToBlob(base64Image, contentType) { // http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript // Remove leading 'data:image/jpeg;base64,' or 'data:image/png;base64,' base64Image = base64Image.split(',')[1]; let byteCharacters = atob(base64Image); // http://stackoverflow.com/questions/6259515/javascript-elegant-way-to-split-string-into-segments-n-characters-long let byteArrays = byteCharacters.match(/[\s\S]{1,512}/g).map( slice => { let byteNumbers = slice.split('').map( x => x.charCodeAt(0) ); return new Uint8Array(byteNumbers); }); let blob = new Blob(byteArrays, { type: contentType || 'image/jpg' /* or 'image/png' */ }); return blob; }
javascript
{ "resource": "" }
q42680
convertImageToBase64
train
function convertImageToBase64(image) { let fileReader = new FileReader(); return new Promise( (resolve, reject) => { fileReader.onload = fileLoadedEvent => resolve(fileLoadedEvent.target.result); fileReader.readAsDataURL(image); }); }
javascript
{ "resource": "" }
q42681
handler
train
function handler(req, res) { var path = cog.getConfig('options.api_data'); var urlRegex = cog.getConfig('options.api_url_regex'); var url = req.url.replace(/^\//, '').replace(/\/$/, ''); console.log(req.method + ' ' + req.url); // Find the JSON-data file and serve it, if URL points to the API. if (path && urlRegex && urlRegex.test(url)) { var file = path + '/' + url + '.json'; if (grunt.file.exists(file)) { res.end(grunt.file.read(file)); return; } } if (req.method == 'POST') { // TODO: This needs fixing, since it throws an error. res.end('{"message": "OK"}'); } }
javascript
{ "resource": "" }
q42682
train
function(name, type, filename, code) { this.name = name; this.type = type; this.filename = filename; this.code = code; }
javascript
{ "resource": "" }
q42683
vorto
train
function vorto() { var length = arguments.length; var format, options, callback; if (typeof arguments[length-1] !== 'function') { throw new Error('The last argument must be a callback function: function(err, version){...}'); } else { callback = arguments[length-1]; } if (length === 1) { format = '%h'; options = DEFAULTS; } else if (length === 2) { if (typeof arguments[0] === 'string') { format = arguments[0]; options = DEFAULTS; } else if (typeof arguments[0] === 'object'){ format = '%h'; options = createOptions(arguments[0], DEFAULTS); } else { throw new Error('First argument must be a \'string\' or an \'object\''); } } else if (length === 3) { if (typeof arguments[0] !== 'string') { throw new Error('First argument must be a string'); } if (typeof arguments[1] !== 'object') { throw new Error('Second argument must be an object'); } format = arguments[0]; options = createOptions(arguments[1], DEFAULTS); } if (format.indexOf('%j')>-1) { var j = packageVersion(options.repo); git(format, options, function(err, version) { if (err) { callback(err, null); } else { callback(null, version.replace('%j', j)); } }); } else { git(format, options, callback); } }
javascript
{ "resource": "" }
q42684
packageVersion
train
function packageVersion(repo) { var location = repo ? path.join(repo, 'package.json') : './package.json'; var pack = require(location); return pack['version']; }
javascript
{ "resource": "" }
q42685
train
function(name, value, iType) { var type = iType , coded , attach = { '_attachments': this.get('_attachments') || {} } , types = { "html": {"content_type":"text\/html"}, "text": {"content_type":"text\/plain"}, "xml": {"content_type":"text\/plain"}, "jpeg": {"content_type":"image\/jpeg"}, "png": {"content_type":"image\/png"} } // base64 chokes on charCodes > 255 , filterCharCodes = function(s) { // replace newlines and carriage returns with a space. then filter the non-ascii return _.reduce(s.replace(/\n/g, ' ').replace(/\r/g, ' '), function(result, x, i) { if (s.charCodeAt(i) < 256) { result += s[i]; } return result; }, ''); };; // as a prelude to a 'read', the second argument is the 'type' if (arguments.length === 2) { this.options.set('Content-Type', (types && types[value] && types[value].content_type) || 'text\/plain'); } else if (arguments.length === 3) { type = (types && types[type]) ? type : 'xml'; types[type].data = _.encode(filterCharCodes(value)); attach._attachments[name] = types[type]; } this.set('_attachments', attach._attachments); return this; }
javascript
{ "resource": "" }
q42686
EventReactor
train
function EventReactor(options, proto) { // allow initialization without a new prefix if (!(this instanceof EventReactor)) return new EventReactor(options, proto); options = options || {}; this.restore = {}; // don't attach the extra event reactor methods, we are going to apply them // manually to the prototypes if (options.manual) return this; var methods = EventReactor.generation , method; for (method in methods) { if (methods.hasOwnProperty(method)) { this[method](proto); } } // such as aliases and emit overrides this.aliases(proto); this.emit(proto); }
javascript
{ "resource": "" }
q42687
every
train
function every() { for ( var args = slice.call(arguments, 0) , callback = args.pop() , length = args.length , i = 0; i < length; this.on(args[i++], callback) ){} return this; }
javascript
{ "resource": "" }
q42688
handle
train
function handle() { for ( var i = 0 , length = args.length; i < length; self.removeListener(args[i++], handle) ){} // call the function as last as the function might be calling on of // events that where in our either queue, so we need to make sure that // everything is removed callback.apply(self, arguments); }
javascript
{ "resource": "" }
q42689
handle
train
function handle() { self.removeListener(event, reset); callback.apply(self, [event].concat(args)); }
javascript
{ "resource": "" }
q42690
reset
train
function reset() { clearTimeout(timer); self.idle.apply(self, [event, callback, timeout].concat(args)); }
javascript
{ "resource": "" }
q42691
listen
train
function listen(pw, type, listener, fnm, rf, cbtype, passes) { var fn = function pulseListener(flow, artery, pulse) { if (!rf || !(artery instanceof cat.Artery) || !(pulse instanceof cat.Pulse) || flow instanceof Error) return arguments.length ? fn._callback.apply(pw, Array.prototype.slice.call(arguments)) : fn._callback.call(pw); var isRfCb = rf === 'callback', emitErrs = pulse.emitErrors || (pulse.emitErrors !== false && artery.emitErrors) || (pulse.emitErrors !== false && artery.emitErrors !== false && pw.options && pw.options.emitErrors); var args = arguments.length > fn.length ? Array.prototype.slice.call(arguments, isRfCb ? fn.length : 1) : null; if (isRfCb) { (args = args || []).push(function retrofitCb(err) { // last argument should be the callback function if (err instanceof Error) emitError(pw, err, pulse.type, [artery, pulse]); // emit any callback errors var pi = 0, al; if (passes) for (var pl = passes.length; pi < pl; ++pi) { artery.passes[passes[pi]] = arguments[pi]; // pass by name before any other arguments are passed } if ((al = arguments.length - (pi += pi > 0)) === 1) artery.pass.push(arguments[pi]); else if (al) artery.pass.push.apply(artery.pass, Array.prototype.slice.call(arguments, pi)); }); } if (emitErrs) { try { args && args.length ? fn._callback.apply(pw, args) : fn._callback.call(pw, artery, pulse); } catch (e) { emitError(pw, e, pulse.type, [artery, pulse]); } } else args && args.length ? fn._callback.apply(pw, args) : fn._callback.call(pw, artery, pulse); }; fn._callback = listener; if (cbtype) fn._cbtype = cbtype; return PulseEmitter.super_.prototype[fnm || 'addListener'].call(pw, type, fn); }
javascript
{ "resource": "" }
q42692
complete
train
function complete ( err, msg ){ b9.off('hello', success ); // cleanup // optional callback, error-first... if ( typeof callback == 'function' ){ callback( err, msg ); } }
javascript
{ "resource": "" }
q42693
receive
train
function receive ( str ){ ping(); // clear/schedule next ping var msg = typeof str === 'string' ? JSON.parse( str ) : str; b9.emit('rtm.read', msg, replyTo( null ) ); // acknowledge that a pending message was sent successfully if ( msg.reply_to ){ delete pending[ msg.reply_to ]; } else if ( msg.type != null ){ b9.emit( msg.type, msg, replyTo( msg.channel ) ); } }
javascript
{ "resource": "" }
q42694
ping
train
function ping (){ clearTimeout( ping.timer ); ping.timer = setTimeout(function(){ b9.send({ type: 'ping', time: Date.now() }); }, b9._interval ); }
javascript
{ "resource": "" }
q42695
assertEqualsDelta
train
function assertEqualsDelta(msg, expected, actual, epsilon) { var args = this.argsWithOptionalMsg_(arguments, 4); jstestdriver.assertCount++; msg = args[0]; expected = args[1]; actual = args[2]; epsilon = args[3]; if (!compareDelta_(expected, actual, epsilon)) { this.fail(msg + 'expected ' + epsilon + ' within ' + this.prettyPrintEntity_(expected) + ' but was ' + this.prettyPrintEntity_(actual) + ''); } return true; }
javascript
{ "resource": "" }
q42696
parseName
train
function parseName(name) { if (name) { const arr = name.split('.') const len = arr.length if (len > 2) { return arr.slice(0, -1).join('.') } else if (len === 2 || len === 1) { return arr[0] } } return name }
javascript
{ "resource": "" }
q42697
train
function (object) { var methodName; methodName = this.test(object, true); if (methodName !== true) { throw new exports.NotImplementedError({ code: 'interface', message: 'Object %(object) does not implement %(interface)#%(method)()', //Additional information interface: this.name, object: object, method: methodName }); } return this; }
javascript
{ "resource": "" }
q42698
train
function (object, returnName) { var methodName; for (methodName in this.methods) { if (!(object[methodName] instanceof Function)) { return returnName ? methodName : false; } } return true; }
javascript
{ "resource": "" }
q42699
train
function (_module) { if (! this.name) { throw new exports.ValueError({message: 'name is empty'}); } var _exports = _module.exports || _module; _exports[this.name] = this; return this; }
javascript
{ "resource": "" }