_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q38100
train
function () { let selection = dom(el).getSelection(), range; if (selection.rangeCount > 0) { range = selection.getRangeAt(0); } return range; }
javascript
{ "resource": "" }
q38101
_isTHIS
train
function _isTHIS (obj) { if (obj && obj._this && (obj._this === true)) { return true } return false }
javascript
{ "resource": "" }
q38102
_isField
train
function _isField (obj) { if (obj && obj._modelAttribute && (obj._modelAttribute === true)) { return true } return false }
javascript
{ "resource": "" }
q38103
_updateTHIS
train
function _updateTHIS (model, obj) { const RESULT = {} if (Array.isArray(obj)) { return [_updateTHIS(model, obj[0])] } Object.keys(obj).forEach(prop => { const OBJ = obj[prop] if (_isTHIS(OBJ)) { delete OBJ._this RESULT[prop] = Object.assign(_.cloneDeep(model.attributes[prop]), OBJ) return } if (_isField(OBJ)) { OBJ.fieldName = OBJ.fieldName || prop OBJ.field = OBJ.field || prop RESULT[prop] = OBJ return } if (typeof OBJ === 'object') { const SUB_MODEL = (model && model.associations[prop]) ? model.associations[prop].target : undefined RESULT[prop] = _updateTHIS(SUB_MODEL, OBJ) } }) return RESULT }
javascript
{ "resource": "" }
q38104
_createValidate
train
function _createValidate (type, defaultValidate = {}, customValidate) { if (customValidate === null) { return null } let val = {} if (type.key === 'STRING') { val = { len: [0, type.options.length] } } if (type.key === 'TEXT') { val = { len: [0, 2147483647] } } if (type.key === 'INTEGER') { val = { isInt: true, min: -2147483647, max: 2147483647 } } if (type.key === 'FLOAT') { val = { isFloat: true, min: -1E+308, max: 1E+308 } } if (type.key === 'ENUM') { val = { isIn: [type.values] } } if (type.key === 'BOOLEAN') { val = { isBoolean: true } } if (type.key === 'DATE') { val = { isDate: true } } if (type.key === 'DATEONLY') { val = { isDate: true } } if (type.key === 'TIME') { val = { isTime: _isTimeValidate() } } if (type.key === 'JSON') { val = { isJson: _isJsonValidate() } } if (type.key === 'JSONB') { val = { isJson: _isJsonValidate() } } if (type.key === 'UUID') { val = { isUUID: 4 } } if (type.key === 'ARRAY') { val = { isArray: _isArrayValidate(type.type) } } const FIELD = { validate: Object.assign(Object.assign(val, defaultValidate), customValidate) } _normalizeValidate(FIELD) return FIELD.validate }
javascript
{ "resource": "" }
q38105
_normalizeValidate
train
function _normalizeValidate (field) { if (field.validate) { Object.keys(field.validate).forEach(key => { let validateItem = field.validate[key] if (typeof validateItem === 'function') { return } // Adiciona la propiedad args, si el validador no lo tuviera. // Ejemplo: min: 10 -> min: { args: 10 } isInt: true -> isInt: { args: true } if ((typeof validateItem !== 'object') || (typeof validateItem.args === 'undefined')) { field.validate[key] = { args: validateItem } } // Convierte los validadores booleanos: isInt: { args: true } -> isInt: true // Sequelize no admite validateKey: { args: true }, es por eso que si existe, ésta se elimina. if (typeof field.validate[key].args === 'boolean') { delete field.validate[key].args if (typeof field.validate[key].msg === 'undefined') { field.validate[key] = true } } // Corrige el problema cuando se declaran args con valores de 0 y 1. // Se corrige porque Sequelize los toma como valores booleanos, cuando debería tomarlos como números enteros. // Ejemplo: min: { args: 0 } -> min: { args: [0] } y min: { args: 1 } -> min: { args: [1] } if ((typeof field.validate[key].args !== 'undefined') && ((field.validate[key].args === 0) || (field.validate[key].args === 1))) { field.validate[key].args = [field.validate[key].args] } }) } }
javascript
{ "resource": "" }
q38106
train
function(v) { return _.isNil(v) || (_.isString(v) && _.isEmpty(v)); }
javascript
{ "resource": "" }
q38107
train
function(v) { return _.isNull(v) || (_.isString(v) && _.isEmpty(v)); }
javascript
{ "resource": "" }
q38108
train
function(v) { return !_.isNil(v) && (_.isString(v) || _.isNumber(v) || _.isBoolean) && !_.isObject(v); }
javascript
{ "resource": "" }
q38109
normalize
train
function normalize(opts) { if (typeof opts === 'string') { opts = {path: opts}; } opts.path = path.resolve(opts.path); return opts; }
javascript
{ "resource": "" }
q38110
mapObjects
train
function mapObjects(root, list, callback) { var ret = {}; var sent = false; var count = list.length; if (count === 0) { callback(null, ret); } list.forEach(function (pointer) { var name = path.join(root._path, pointer); fp.define({filePath: name, parent: root}, function (err, obj) { if (err) { if (!sent) { callback(err); sent = true; } return; } ret[name] = obj; if (ret[name]._type === 'directory') { addMaping(ret[name]); } if (--count === 0) { callback(null, ret); } }); }); }
javascript
{ "resource": "" }
q38111
filter
train
function filter(pObjects, opts, returnArray) { var filtered = returnArray ? [] : {}; function addToFiltered(key) { if(returnArray) { filtered.push((returnArray === 'keys' ? key : pObjects[key])); } else { filtered[key] = pObjects[key]; } } if (!opts) { Object.keys(pObjects).forEach(); return; } function checkMatch(match, prop) { if(utils.isArray(match)){ return match.indexOf(prop) !== -1; } return match === prop; } Object.keys(pObjects).forEach(function (key) { //Return only fp objects if(['File','Folder'].indexOf(pObjects[key].constructor.name) === -1) { return; } //Recursive directories always added if (opts.recursive && pObjects[key]._type === 'directory') { addToFiltered(key); return; } if (!opts.dotStart && pObjects[key]._name.charAt(0) === '.') { return; } if(opts.type && !checkMatch(opts.type, pObjects[key]._type)) { return; } if(opts.ext && pObjects[key]._type === 'file' && !checkMatch(opts.ext, pObjects[key]._ext)) { return; } if (opts.match && !pObjects[key]._name.match(opts.match)) { return; } if (opts.pathMatch && !pObjects[key]._path.match(opts.pathMatch)) { return; } addToFiltered(key); }); return filtered; }
javascript
{ "resource": "" }
q38112
transfer
train
function transfer(root, map, opts) { map = filter(map, opts); var folders = []; function getIndex(k) { var index = k; if (opts.relative) { var replace = opts.relative === true ? (root._path + path.sep) : opts.relative; index = k.replace(replace, ''); } return index; } Object.keys(map).forEach(function (k) { var index = getIndex(map[k]._path); if (map[k]._type === 'directory') { folders.push(map[k]); if (opts.type !== 'file' && !(opts.match || opts.ext)) { root[index] = map[k]; } } if (map[k]._type === 'file' && (!opts.type || opts.type === 'file')) { root[index] = map[k]; } }); return folders; }
javascript
{ "resource": "" }
q38113
simpleMap
train
function simpleMap(map, lvls, opts, type, ext, callback) { opts = utils.clone(opts); lvls--; if(lvls < 1) { opts.simple = false; opts.recursive = true; opts.type = type; opts.ext = ext; } var folders = map.__filter({type:'directory'}, true); var count = folders.length; var errs = []; function end(err) { if(err) { errs.push(err); } if(--count !== 0) { return; } if(errs.length) { callback(errs); return; } callback(null, map); } folders.forEach(function (folder) { folder.__map(opts, function (err, fMap) { if(err) { end(err); return; } if(lvls < 1) { end(); } else { simpleMap(fMap, lvls, opts, type, ext, end); } }); }); }
javascript
{ "resource": "" }
q38114
map
train
function map(opts, callback) { if(utils.isArray(opts)) { mapWithArrayInput(opts, callback); return; } opts = normalize(opts); // Assume that the root is a folder var root = new fp.Folder(opts.path); var sent = false; root.__listen('error', function (err) { if (!sent) { callback(err); sent = true; } }); root.__listen('missing', function (err) { if (!sent) { callback(err); sent = true; } }); root.__stats(function (err, stats) { if (err) { if (!sent) { callback(err); } return; } // If the root is a file simply return it if (!stats.isDirectory()) { callback(null, new fp.File(opts.path)); return; } // Add functions addMaping(root); if(typeof opts.simple !== 'number' || !opts.recursive) { root.__map(opts, callback); } else { var lvls = opts.simple; var type = opts.type; var ext = opts.ext; opts.recursive = false; opts.simple = true; if(opts.type === 'file') { delete opts.type; } if(opts.ext) { delete opts.ext; } root.__map(opts, function (err, map) { if(err) { callback(err); return; } simpleMap(map, lvls, opts, type, ext, callback); }); } }); }
javascript
{ "resource": "" }
q38115
increment
train
function increment(value, skip, incrementBy) { var str = (typeof value === 'string'); var incrementBy = incrementBy || 1; var numeric = !isNaN(value); var skip = skip || []; var nextVal; if (numeric) { value = parseInt(value) + parseInt(incrementBy); } else { value = String.fromCharCode(value.charCodeAt(0) + parseInt(incrementBy)); } if (str) value = value.toString(); if (skip.indexOf(value) === -1) return value; return increment(value, skip, incrementBy); }
javascript
{ "resource": "" }
q38116
discover
train
function discover(from) { from = from || caller(); // check 'from' validity if ("string" != typeof from) { var given = typeof from; throw new Error("'from' must be a string, [" + given + "] given"); } // if 'from' is not absolute, make it absolute if (!pathIsAbsolute(from)) { from = path.join( path.dirname(caller()), from ); } // if 'from' is a file, keep its dirname if (fs.existsSync(from)) { var stat = fs.lstatSync(from); if (stat.isFile()) { from = path.dirname(from); } } // check path cache if (discoverCache[from]) { return discoverCache[from]; } // process directories from 'from' to system root directory until we find a package.json file var dir = from; var old = null; var processedDirList = []; while (true) { if (discoverCache[dir]) { // path from cache return discoverCache[dir]; } else if (fs.existsSync(dir + "/package.json")) { // package.json found processedDirList.push(dir); var discoveredDir = dir + "/package.json"; for (var i in processedDirList) { discoverCache[processedDirList[i]] = discoveredDir; } return discoveredDir; } else { // process parent directory old = dir; dir = path.dirname(dir); // check if we reached the system root directory if (old === dir) { break; } // add processed dir to the list processedDirList.push(old); } } throw new Error("Unabe to find a package.json from '" + from + "'"); }
javascript
{ "resource": "" }
q38117
Logger
train
function Logger(name) { var prjName = module.exports.PROJECT_NAME; this.name = prjName ? prjName + ':' + name : name; this._debug = debug(this.name); this._debug.log = logDebug; this.debugEnabled = debug.enabled(this.name); if (this.debugEnabled) { logDebug('[%s] debug is %s', this.name.blue, 'ENABLED'.green); } }
javascript
{ "resource": "" }
q38118
extractWords
train
function extractWords(str, store) { if (!str) return [] if (Array.isArray(str)) return str assert.equal(typeof str, 'string', 'first parameter must be an array or string') switch (store) { case undefined: if (cache) return parseWordListCached(str, cache) else return parseWordList(str) case null: case false: return parseWordList(str) default: assert.equal(typeof store, 'object', 'second parameter must be an object or null') return parseWordListCached(str, store) } }
javascript
{ "resource": "" }
q38119
registerBreakpoints
train
function registerBreakpoints(breakpoints) { let register = []; Object.keys(breakpoints).forEach(name => { register.push('(^' + escRgx(name) + '$)'); }); if (! register.length) { return false; } return new RegExp(register.join('|')); }
javascript
{ "resource": "" }
q38120
convertBreakpointToMedia
train
function convertBreakpointToMedia(rule) { rule.params = `(min-width: ${breakpoints[rule.name]}px)`; rule.name = 'media'; rule.raws.afterName = ' '; rule.raws.between = ' '; return rule; }
javascript
{ "resource": "" }
q38121
addToRegistry
train
function addToRegistry(rule) { let name = rule.name; if (registry.hasOwnProperty(name)) { // `each` allows for safe looping while modifying the // array being looped over. `append` is removing the rule // from the array being looped over, so it is necessary // to use this method instead of forEach rule.each(r => registry[name].append(r)); } else { registry[name] = rule.clone(); } }
javascript
{ "resource": "" }
q38122
processRoute
train
function processRoute(opts) { if (routeHandler) { routeHandler(opts.request, opts.reply, opts.urlOverride, opts.returnCode); } else { opts.reply.continue(); } }
javascript
{ "resource": "" }
q38123
getServerPreProcessing
train
function getServerPreProcessing(request, reply) { var me = this; return function (routeInfo, page, model) { if (!page.serverPreprocessing) { return false; } var deps = { request: request, reply: reply, model: model, routeInfo: routeInfo }; return me.pancakes.cook(page.serverPreprocessing, { dependencies: deps }); }; }
javascript
{ "resource": "" }
q38124
getWebRouteHandler
train
function getWebRouteHandler(opts) { var webRouteHandler = this.pancakes.webRouteHandler; var me = this; return function handleWebRoute(request, reply, urlOverride, returnCode) { var appName = request.app.name; var url = urlOverride || request.url.pathname; var routeInfo = null; var referrer = request && request.headers && request.headers.referer ? request.headers.referer : ''; var routeHelper = me.pancakes.cook('routeHelper'); // var newrelic = require('newrelic'); Q.fcall(function () { routeInfo = webRouteHandler.getRouteInfo(appName, url, request.query, request.app.lang, request.user, referrer); // newrelic.setTransactionName(routeInfo.appName + '||' + routeInfo.lang + '||' + routeInfo.urlPattern); // if redirect URL exists, just redirect right away if (routeInfo.redirect) { // make sure tokens in the redirect URL are replaced var redirectUrl = routeInfo.redirect; _.each(routeInfo.tokens, function (value, key) { redirectUrl = redirectUrl.replace('{' + key + '}', value); }); if (redirectUrl.indexOf('{') >= 0) { //throw new Error('Redirect URL has token that was not replaced: ' + redirectUrl); // we can't just throw errors in here console.log('Bad redirect: ' + redirectUrl); reply(new Error('So sorry, but there is an error here right now, and we are trying to fix it. Please try again later.')); return new Q(); } // do full url for all redirects if (redirectUrl.indexOf('http') !== 0) { redirectUrl = (routeHelper.getBaseUrl(routeInfo.appName) + '') + redirectUrl; } reply().redirect(redirectUrl).permanent(true); return new Q(); } // if the app is handling this request, don't do anything if (opts.preProcess && opts.preProcess(request, reply)) { return new Q(); } var callbacks = { serverPreprocessing: me.getServerPreProcessing(request, reply), addToModel: opts.addToModel, pageCacheService: opts.pageCacheService }; return webRouteHandler.processWebRequest(routeInfo, callbacks) .then(function (renderedPage) { // if no rendered page, it means request was handled earlier somewhere (ex. serverPreprocess redirect) if (!renderedPage) { //console.log('No rendered page for ' + url); return false; } var response = reply(renderedPage).code(returnCode || 200); // add content type if in the route info if (routeInfo.contentType) { response.header('Content-Type', routeInfo.contentType); } // as long as the nocache attribute is NOT set, add cache headers (sorry for double negative :-)) if (!routeInfo.nocache) { response.header('cache-control', 'public, max-age=60'); } return true; }); }) .catch(function (err) { console.error(err); reply(err); }); }; }
javascript
{ "resource": "" }
q38125
error
train
function error(message) { if (EventEmitter.listenerCount(wanted, 'error') > 0) { return wanted.emit('error', message); } throw new Error(message); }
javascript
{ "resource": "" }
q38126
processed
train
function processed(module) { pool.processed.push(module); if (!module.installed) { pool.install.push(module); } setImmediate(next); }
javascript
{ "resource": "" }
q38127
next
train
function next() { var module; if (pool.queue.length <= 0) { if (pool.install.length) { error('Update needed: ' + pool.install.map(function(module) { return module.name; }).join(', ')); } else { wanted.emit('ready', pool.processed.map(shallow)); } return reset(); } module = pool.queue.shift(); fileExists(module.path + '/package.json', function(file) { var json; if (file) { json = require(file); module.installed = json.version; module.upgrade = !semver.satisfies(json.version, module.version); } if (!module.installed || module.upgrade) { request(module); } else { module.current = true; wanted.emit('current', shallow(module)); processed(module); } }); }
javascript
{ "resource": "" }
q38128
fileExists
train
function fileExists(file, handle) { fs.exists(file, function(exists) { handle.apply(null, exists ? [file] : []); }); }
javascript
{ "resource": "" }
q38129
shallow
train
function shallow(module) { return { name: module.name, version: module.version, installed: module.installed, scope: module.scope, state: module.current ? 'current' : (module.upgrade ? 'upgrade' : 'install') }; }
javascript
{ "resource": "" }
q38130
train
function(name) { var handler = function(e) { //XXX add id to element _declaireLog.push(e); }; var html = document.getElementsByTagName('html')[0]; html.addEventListener(name, handler); return handler; }
javascript
{ "resource": "" }
q38131
Server
train
function Server(opts){ // Shorthand, no "new" required. if (!(this instanceof Server)) return new Server(...arguments); if (typeof opts !== 'object') opts = {}; this.clients = opts.dummies || []; this.server = opts.server || new SocketServer(socket => { let client = new Client(socket); this.clients.push(client); this.emit('connection', client); client._socket.once('data', handshake.bind(client)); client.on('handshake-done', () => { client._socket.on('data', message.bind(client)); }); }); }
javascript
{ "resource": "" }
q38132
train
function (obj, keys) { return _.all(obj, function (v, k) { return _.contains(keys, k); }); }
javascript
{ "resource": "" }
q38133
train
function(clazz, metaData) { this.applyMethods(clazz, metaData.clazz_methods || {}); this.applyMethods(clazz.prototype, metaData.methods || {}); }
javascript
{ "resource": "" }
q38134
train
function(object, methods) { _.each(methods, function(method, name) { if (!_.isFunction(method)) { throw new Error('Method "' + name + '" must be a function!'); } object[name] = method }); }
javascript
{ "resource": "" }
q38135
sanitize
train
function sanitize(lang, filter) { if(!(typeof lang == 'string')) return lang; lang = lang.replace(/\..*$/, '').toLowerCase(); if(typeof filter == 'function') { lang = filter(lang); } return lang; }
javascript
{ "resource": "" }
q38136
find
train
function find(search, filter, strict) { var lang, search = search || [], i, k, v, re = /^(LC_|LANG)/; for(i = 0;i < search.length;i++) { lang = sanitize(process.env[search[i]] || '', filter); if(lang) return c(lang); } // nothing found in search array, find first available for(k in process.env) { v = process.env[k]; if(re.test(k) && v) { lang = sanitize(v, filter); if(lang) break; } } if(!lang) lang = c(sanitize(process.env.LANG, filter)); return c(lang) || (!strict ? language : null); }
javascript
{ "resource": "" }
q38137
flattenBrunchMap
train
function flattenBrunchMap (sourceFile, compiled, sourceMap) { let asString = false let prevMap = sourceFile.map let newMap = sourceMap // make sure the current map is an object if (prevMap && (typeof prevMap == 'string' || prevMap instanceof String)) { prevMap = JSON.parse(prevMap) } const result = { data: compiled } if (newMap) { // make sure the new map is an object if (typeof newMap == 'string' || newMap instanceof String) { asString = true } else { newMap = JSON.stringify(sourceMap) // normalize } newMap = JSON.parse(newMap) // check the required mappings property if (typeof newMap.mappings != 'string') { throw new Error('Source map to be applied is missing the "mappings" property') } // sources defaults to current source file if (!newMap.sources || !newMap.sources[0]) { newMap.sources = [sourceFile.path] } // have a valid previous map? if (prevMap && prevMap.mappings) { if (!newMap.file && prevMap.file) { newMap.file = prevMap.file } result.map = transfer(newMap, prevMap, asString) } else { // return the received source map already normalized result.map = asString ? JSON.stringify(newMap) : newMap } } else if (prevMap) { // no new map, return the previous source map as-is result.map = sourceFile.map } return result }
javascript
{ "resource": "" }
q38138
pathToRegExp
train
function pathToRegExp(path) { if (path instanceof RegExp) { return { keys: [], regexp: path }; } if (path instanceof Array) { path = '(' + path.join('|') + ')'; } var rtn = { keys: [], regexp: null }; rtn.regexp = new RegExp((isHashRouter(path) ? '' : '^') + path.replace(/([\/\(]+):/g, '(?:').replace(/\(\?:(\w+)((\(.*?\))*)/g, function (_, key, optional) { rtn.keys.push(key); var match = null; if (optional) { match = optional.replace(/\(|\)/g, ''); } else { match = '/?([^/]+)'; } return '(?:' + match + '?)'; }) // fix double closing brackets, are there any better cases? // make a commit and send us a pull request. XD .replace('))', ')').replace(/\*/g, '(.*)') + '((#.+)?)$', 'i'); return rtn; }
javascript
{ "resource": "" }
q38139
paramsParser
train
function paramsParser(url, rule) { var matches = rule.regexp.exec(url).slice(1); var keys = rule.keys; var params = {}; for (var i = 0; i < keys.length; i++) { params[keys[i]] = matches[i]; } return params; }
javascript
{ "resource": "" }
q38140
sendHeartbeat
train
function sendHeartbeat() { _.forOwn(_this.socks, function (sock) { sock.write('hb'); }); setTimeout(sendHeartbeat, _this.heartbeatFreq); }
javascript
{ "resource": "" }
q38141
checkClientsHeartbeat
train
function checkClientsHeartbeat() { var now = Date.now(); _.forOwn(_this.socks, function (sock) { if (sock.hb + _this.clientTimeout < now) { logout(sock); } }); setTimeout(checkClientsHeartbeat, 1000) }
javascript
{ "resource": "" }
q38142
EJS
train
function EJS() { var opts = (app.config.engines && app.config.engines.ejs) || {}; this.options = protos.extend({ delimiter: '?' }, opts); this.module = ejs; this.multiPart = true; this.extensions = ['ejs', 'ejs.html']; }
javascript
{ "resource": "" }
q38143
cloneEvents
train
function cloneEvents(origin, clone, deep) { var listeners = origin._listeners if (listeners) { clone._listeners = listeners for (var type in listeners) { clone.addEventListener(type, listeners[type]) } } if (deep && origin.children && origin.children.length) { for (var i = 0, l = origin.children.length; i < l; i++) { cloneEvents(origin.children[i], clone.children[i], deep) } } }
javascript
{ "resource": "" }
q38144
promiseReadFiles
train
function promiseReadFiles(pattern) { return glob(pattern) .then(foundFiles => { const promisesToReadFiles = foundFiles.map(fileName => pReadFile(fileName)); return Promise.all(promisesToReadFiles); }) .catch(log.error); }
javascript
{ "resource": "" }
q38145
isAuthorized
train
function isAuthorized(acl, user) { acl = u.str(acl).toUpperCase(); user = u.str(user).toUpperCase(); if (user && user === acl) return true; if (!aclRe[acl]) { aclRe[acl] = reAccess(sessionOpts.acl[acl] || process.env['ACL_' + acl]); } return aclRe[acl].test(user) || aclRe.ADMIN.test(user); }
javascript
{ "resource": "" }
q38146
reAccess
train
function reAccess(s) { var list = s ? s.split(/[, ]+/) : []; // avoid [''] return new RegExp( u.map(list, function(s) { return '^' + u.escapeRegExp(s) + '$'; // exact matches only }).join('|') // join([]) returns '' || '$(?=.)' // avoid default regexp /(?:)/ , 'i'); // not case-sensitive }
javascript
{ "resource": "" }
q38147
saveOldSessions
train
function saveOldSessions() { var db = self.store; var oldDestroy = db.destroy; db.destroy = newDestroy; return; // rename instead of delete function newDestroy(sid, cb) { db.get(sid, function(err, session) { if (err) return cb(err); if (!session) return cb(); db.set(sid + '_d', session, function(err) { if (err) return cb(err); oldDestroy.call(db, sid, cb); }); }); } }
javascript
{ "resource": "" }
q38148
newDestroy
train
function newDestroy(sid, cb) { db.get(sid, function(err, session) { if (err) return cb(err); if (!session) return cb(); db.set(sid + '_d', session, function(err) { if (err) return cb(err); oldDestroy.call(db, sid, cb); }); }); }
javascript
{ "resource": "" }
q38149
train
function (i) { var self = this; var invert = !self._sortSpecParts[i].ascending; return function (key1, key2) { var compare = LocalCollection._f._cmp(key1[i], key2[i]); if (invert) compare = -compare; return compare; }; }
javascript
{ "resource": "" }
q38150
doClose
train
function doClose(next, err) { if (fd > 0 && file_path !== fd) { fs.close(fd, function closed() { // Ignore errors next(err); }); } else { next(err); } }
javascript
{ "resource": "" }
q38151
mcFile
train
function mcFile(type, source, target, cb) { var targetDir, bin, cmd; if (type == 'cp' || type == 'copy') { bin = '/bin/cp'; } else if (type == 'mv' || type == 'move') { bin = '/bin/mv'; } // We assume the last piece of the target is the file name // Split the string by slashes targetDir = target.split('/'); // Remove the last piece targetDir.splice(targetDir.length-1, 1); // Join it again targetDir = targetDir.join('/'); // Make sure the target directory exists alchemy.createDir(targetDir, function ensuredDir(err) { if (err) { return cb(err); } spawnQueue.add(function queuecp(done) { var options = []; if (process.platform == 'linux') { options = ['--no-target-directory', source, target]; } else { if (source.endsWith('/')) { source = source.slice(0, -1); } if (target.endsWith('/')) { target = target.slice(0, -1); } options = [source, target]; } cmd = child.execFile(bin, options); cmd.on('exit', function onExit(code, signal) { var message; done(); if (code > 0) { message = 'File "' + type + '" operation failed:\n'; message += bin + ' ' + options.join(' '); cb(new Error(message)); } else { cb(null); } }); }); }); }
javascript
{ "resource": "" }
q38152
Preferences
train
function Preferences(preferencesArray, namespace) { if (!preferencesArray) { throw new Error('Cannot create config. Must pass an array of properties!'); } this.store = {}; // store the keys we know this.keys = preferencesArray.map((item) => { this.store[item.key] = preference.newPreference(item.key, item.defaultValue, item.allowedValues, namespace); return item.key; }); }
javascript
{ "resource": "" }
q38153
train
function(object, setters, property) { _.each(setters, function(setter, name) { object.__addSetter(property, name, setter); }); }
javascript
{ "resource": "" }
q38154
removeLeftMargin
train
function removeLeftMargin( code ) { var margin = 999; var lines = code.split("\n"); lines.forEach(function (line) { var s = line.length; var m = 0; while( m < s && line.charAt(m) == ' ' ) m++; margin = Math.min( m, margin ); }); return lines.map(function(line) { return line.substr( margin ); }).join("\n"); }
javascript
{ "resource": "" }
q38155
restrictToSection
train
function restrictToSection( code, section ) { var linesToKeep = []; var outOfSection = true; var lookFor = '#(' + section + ')'; code.split('\n').forEach(function( line ) { if (outOfSection) { if (line.indexOf( lookFor ) > -1) { outOfSection = false; } } else { if (line.indexOf( lookFor ) > -1) { outOfSection = true; } else { linesToKeep.push( line ); } } }); return linesToKeep.join('\n'); }
javascript
{ "resource": "" }
q38156
Server
train
function Server(root) { if (!(this instanceof Server)) return new Server(root); this.settings = defaults({}, Server.defaults); if (root) this.root(root); this.plugins = []; this.entries = {}; var auth = netrc('api.github.com'); if ('GH_TOKEN' in process.env) this.token(process.env.GH_TOKEN); else if (auth.password) this.token(auth.password); }
javascript
{ "resource": "" }
q38157
onComplete
train
function onComplete(options, callback) { return function (req) { var resp; if (ctype = req.getResponseHeader('Content-Type')) { ctype = ctype.split(';')[0]; } if (ctype === 'application/json' || ctype === 'text/json') { try { resp = $.parseJSON(req.responseText) } catch (e) { return callback(e, null, req); } } else { var ct = req.getResponseHeader("content-type") || ""; var xml = ct.indexOf("xml") >= 0; resp = xml ? req.responseXML : req.responseText; } if (req.status == 200 || req.status == 201 || req.status == 202) { callback(null, resp, req); } else if (resp && (resp.error || resp.reason)) { var err = new Error(resp.reason || resp.error); err.error = resp.error; err.reason = resp.reason; err.code = resp.code; err.status = req.status; callback(err, null, req); } else { // TODO: map status code to meaningful error message var msg = req.statusText; if (!msg || msg === 'error') { msg = 'Returned status code: ' + req.status; } var err2 = new Error(msg); err2.status = req.status; callback(err2, null, req); } }; }
javascript
{ "resource": "" }
q38158
train
function(permalink) { permalink = permalink || ''; if (permalink.slice(0, 1) !== PATH_SEP) { permalink = PATH_SEP + permalink; } permalink = permalink.replace(INDEX_RE, PATH_SEP); return permalink; }
javascript
{ "resource": "" }
q38159
parse
train
function parse(str) { str = '(' + str.trim() + ')'; /** * expr */ return expr(); /** * Assert `expr`. */ function error(expr, msg) { if (expr) return; var ctx = str.slice(0, 10); assert(0, msg + ' near `' + ctx + '`'); } /** * '(' binop ')' */ function expr() { error('(' == str[0], "missing opening '('"); str = str.slice(1); var node = binop(); error(')' == str[0], "missing closing ')'"); str = str.slice(1); return node; } /** * field | expr */ function primary() { return field() || expr(); } /** * primary (OR|AND) binop */ function binop() { var left = primary(); var m = str.match(/^ *(OR|AND) */i); if (!m) return left; str = str.slice(m[0].length); var right = binop(); return { type: 'op', op: m[1].toLowerCase(), left: left, right: right } } /** * FIELD[:VALUE] */ function field() { var val = true; var m = str.match(/^([-.\w]+)/); if (!m) return; var name = m[0]; str = str.slice(name.length); var m = str.match(/^:([-*\w.]+|".*?"|'.*?'|\/(.*?)\/) */); if (m) { str = str.slice(m[0].length); val = m[1]; if (numeric(val)) val = parseFloat(val); } return { type: 'field', name: name, value: coerce(val) } } }
javascript
{ "resource": "" }
q38160
error
train
function error(expr, msg) { if (expr) return; var ctx = str.slice(0, 10); assert(0, msg + ' near `' + ctx + '`'); }
javascript
{ "resource": "" }
q38161
loadIgnoreFile
train
function loadIgnoreFile(filepath) { var ignoredDeps = []; /** * Check if string is not empty * @param {string} line string to examine * @returns {boolean} True is its not empty * @private */ function nonEmpty(line) { return line.trim() !== '' && line[0] !== '#'; } if (filepath) { try { ignoredDeps = fs.readFileSync(filepath, 'utf8') .split(/\r?\n/) .filter(nonEmpty); } catch (e) { e.message = 'Cannot read ignore file: ' + filepath + '\nError: ' + e.message; throw e; } } return ignoredDeps; }
javascript
{ "resource": "" }
q38162
getJSON
train
function getJSON(filepath) { const jsonString = "g = " + fs.readFileSync(filepath, 'utf8') + "; g"; return (new vm.Script(jsonString)).runInNewContext(); }
javascript
{ "resource": "" }
q38163
emitAsync
train
async function emitAsync (eventName, ...args) { // using a copy to avoid error when listener array changed let listeners = this.listeners(eventName) for (let i = 0; i < listeners.length; i++) { let fn = listeners[i] let obj = fn(...args) if (!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function') obj = await obj if (obj !== undefined) return obj } }
javascript
{ "resource": "" }
q38164
getDatabase
train
function getDatabase(index, opts) { var db; if(!this._databases[index]) { db = new Database(this, opts); this._databases[index] = db; } return this._databases[index]; }
javascript
{ "resource": "" }
q38165
getPeriod
train
function getPeriod(dates, granularity, forced) { var isArray = angular.isArray(dates); var isRange = (isArray && dates.length > 1); if ((isArray && dates.length === 0) || dates === null || dates === undefined) { return null; } if (granularity === 'month') { return (isRange || forced) ? getMonthPeriod(dates) : getYearPeriod(dates); } if (granularity === 'day') { return (isRange || forced) ? getDayPeriod(dates) : getMonthPeriod(dates); } if (granularity === 'week' && !isRange) { // Special case. Week is no actual granularity. This returns a week period // starting at the specified date. No checks are made to determine if the // provided date actually is the first day in a week. var start = (isArray) ? dates[0] : dates; var end = new Date(start.getTime()); end.setDate(end.getDate() + 6); return getDayPeriod([start, end]); } return getDayPeriod(dates); }
javascript
{ "resource": "" }
q38166
daysInMonth
train
function daysInMonth(date) { var d = new Date(date.getTime()); d.setMonth(d.getMonth() + 1); d.setDate(0); return d.getDate(); }
javascript
{ "resource": "" }
q38167
DirectiveContext
train
function DirectiveContext(strategy, expression, arrayPath){ this.resolved = false; this.strategy = strategy; this.expression = expression; this.path = arrayPath; this.sympath = treeUtils.joinPaths(arrayPath); }
javascript
{ "resource": "" }
q38168
Table
train
function Table(tableName, registry) { this.id = 'id'; this.tableName = tableName; this.joins = {}; this.defaultJoins = []; this.columns = null; this.selectColumns = null; this.defaultSelectCriteria = null; this.columnMap = null; this.isInitialized = false; this.defaultJoinsNeedPostProcessing = false; this.registry = registry; }
javascript
{ "resource": "" }
q38169
camelCaseToUnderscoreMap
train
function camelCaseToUnderscoreMap(columns) { var map = {}; for (var i = 0; i < columns.length; i++) map[columns[i]] = toUnderscore(columns[i]); return map; }
javascript
{ "resource": "" }
q38170
checkForDisallowedCharactersInString
train
function checkForDisallowedCharactersInString(node, identifier) { if (typeof identifier !== "undefined" && isNotAllowed(identifier)) { context.report(node, "Unexpected umlaut in \"" + identifier + "\"."); } }
javascript
{ "resource": "" }
q38171
processOptions
train
function processOptions(opt) { keys(opt).forEach(function (key) { var value = opt[key]; if (typeof value === 'string') { opt[key] = grunt.template.process(value); } else if (Array.isArray(value)) { opt[key] = value.slice().map(function (i) { return grunt.template.process(i); }); } }); }
javascript
{ "resource": "" }
q38172
RedisStorage
train
function RedisStorage(config) { var self = this; config = protos.extend({ host: 'localhost', port: 6379, db: undefined, password: undefined }, config || {}); app.debug(util.format('Initializing Redis Storage for %s:%s', config.host, config.port)); this.db = 0; this.config = config; this.className = this.constructor.name; // Set redis client self.client = redis.createClient(config.port, config.host, config.options); // Authenticate if password provided if (config.password) self.client.auth(config.password); // Handle error event self.client.on('error', function(err) { throw err; }); // Select db if specified if (typeof config.db == 'number' && config.db !== 0) { app.addReadyTask(); self.db = config.db; self.client.select(config.db, function(err, res) { if (err) { throw err; } else { app.flushReadyTask(); } }); } // Set enumerable properties protos.util.onlySetEnumerable(this, ['className', 'db']); }
javascript
{ "resource": "" }
q38173
rpcToSpecifiedServer
train
function rpcToSpecifiedServer(client, msg, serverType, routeParam, cb) { if (typeof routeParam !== 'string') { logger.error('[dreamix-rpc] server id is not a string, server id: %j', routeParam); return; } if (routeParam === '*') { const servers = client._station.servers; async.each(Object.keys(servers), (serverId, next) => { const server = servers[serverId]; if (server.serverType === serverType) { client.rpcInvoke(serverId, msg, (err) => { next(err); }); } }, cb); } client.rpcInvoke(routeParam, msg, cb); }
javascript
{ "resource": "" }
q38174
checkModuleLicense
train
function checkModuleLicense(folder) { var licensePath = folder + "/LICENSE", readMePath = folder + "/README.md", licenseContent; //check for LICENSE File First if(fs.existsSync(licensePath)){ licenseContent = fs.readFileSync(licensePath, "utf-8"); return { isMIT : isLicense.mit(licenseContent), content : licenseContent }; } //Maybe in the README else if(fs.existsSync(readMePath)) { licenseContent = fs.readFileSync(readMePath, "utf-8"); return { isMIT : isLicense.mit(licenseContent), content : "Check the README" }; } else { return { isMIT : false, content : "not found" }; } }
javascript
{ "resource": "" }
q38175
checkLicenses
train
function checkLicenses(rootDir){ var licenses = {}, nodeModulesFolder = path.resolve(rootDir, "./node_modules"), moduleFolders = fs.readdirSync(nodeModulesFolder), res; _(moduleFolders).each(function(module) { licenses[module] = checkModuleLicense(nodeModulesFolder + "/" + module); }); return licenses; }
javascript
{ "resource": "" }
q38176
writeLicensesFile
train
function writeLicensesFile(rootDir) { var licenses = checkLicenses(rootDir), licensesFileContent = "LICENSES " + "\n \n"; _(licenses).each(function(licenseData, licenseName) { licensesFileContent += licenseName + " : "; if(licenseData.isMIT) { licensesFileContent += "MIT"; } else { licensesFileContent += "Unknown License"; } licensesFileContent += "\n \n"; if(licenseData.content) { licensesFileContent += licenseData.content + "\n \n"; } }); fs.writeFileSync(rootDir + "/LICENSES", licensesFileContent, "utf-8"); }
javascript
{ "resource": "" }
q38177
check
train
function check( input, expected ) { const output = Util.replaceDotsWithSlashes( input ); expect( output ).toBe( expected.split( '/' ).join( Path.sep ) ); }
javascript
{ "resource": "" }
q38178
memoizedTagFunction
train
function memoizedTagFunction (computeStaticHelper, computeResultHelper) { const memoTable = new LruCache() /** * @param {!Array.<string>} staticStrings * @return {T} */ function staticStateFor (staticStrings) { let staticState = null const canMemoize = Object.isFrozen(staticStrings) && Object.isFrozen(staticStrings.raw) if (canMemoize) { staticState = memoTable.get(staticStrings) } let failure = null if (!staticState) { try { staticState = { pass: computeStaticHelper(staticStrings) } } catch (exc) { failure = exc staticState = { fail: exc.message || 'Failure' } } if (canMemoize) { memoTable.set(staticStrings, staticState) } } if (staticState.fail) { throw failure || new Error(staticState.fail) } return staticState.pass } /** @param {O} options */ function usingOptions (options) { return (staticStringsOrOptions, ...dynamicValues) => { // If we've only been passed an options object, // return a template tag that uses it. if (dynamicValues.length === 0 && !Array.isArray(staticStringsOrOptions)) { return usingOptions(staticStringsOrOptions) } const staticStrings = staticStringsOrOptions requireValidTagInputs(staticStrings, dynamicValues) return computeResultHelper( options, staticStateFor(staticStrings), staticStrings, dynamicValues) } } // eslint-disable-next-line no-inline-comments return usingOptions(/** @type {O} */ ({})) }
javascript
{ "resource": "" }
q38179
commonPrefixOf
train
function commonPrefixOf (a, b) { // eslint-disable-line id-length const minLen = Math.min(a.length, b.length) let i = 0 for (; i < minLen; ++i) { if (a[i] !== b[i]) { break } } return a.substring(0, i) }
javascript
{ "resource": "" }
q38180
trimCommonWhitespaceFromLines
train
function trimCommonWhitespaceFromLines ( templateStrings, { trimEolAtStart = false, trimEolAtEnd = false } = {}) { // Find a common prefix to remove const commonPrefix = commonPrefixOfTemplateStrings(templateStrings) let prefixPattern = null if (commonPrefix) { // commonPrefix contains no RegExp metacharacters since it only contains // whitespace. prefixPattern = new RegExp( `(${LINE_TERMINATORS.source})${commonPrefix}`, 'g') } else if (trimEolAtStart || trimEolAtEnd) { // We don't need to remove a prefix, but we might need to do some // post processing, so just use a prefix pattern that never matches. prefixPattern = /(?!)/ } else { // Fast path. return templateStrings } const { raw, length } = templateStrings // Apply slice so that raw is in the same realm as the tag function. const trimmedRaw = Array.prototype.slice.apply(raw).map( (chunk) => chunk.replace(prefixPattern, '$1')) if (trimEolAtStart) { trimmedRaw[0] = trimmedRaw[0].replace(LINE_TERMINATOR_AT_START, '') } if (trimEolAtEnd) { trimmedRaw[length - 1] = trimmedRaw[length - 1] .replace(LINE_TERMINATOR_AT_END, '') } const trimmedCooked = trimmedRaw.map(cook) trimmedCooked.raw = trimmedRaw Object.freeze(trimmedRaw) Object.freeze(trimmedCooked) return trimmedCooked }
javascript
{ "resource": "" }
q38181
Set
train
function Set(source) { HashMap.call(this); this._rtype = TYPE_NAMES.SET; if(source) { this.sadd(source); } }
javascript
{ "resource": "" }
q38182
sadd
train
function sadd(members) { var i , c = 0; for(i = 0;i < members.length;i++) { if(!this._data[members[i]]) { this.setKey(members[i], 1); c++; } } return c; }
javascript
{ "resource": "" }
q38183
spop
train
function spop() { var ind = Math.floor(Math.random() * this._keys.length) , val = this._keys[ind]; this.delKey(val); return val; }
javascript
{ "resource": "" }
q38184
srem
train
function srem(members) { var i , c = 0; for(i = 0;i < members.length;i++) { if(this.keyExists(members[i])) { this.delKey(members[i]); c++; } } return c; }
javascript
{ "resource": "" }
q38185
lchoose
train
function lchoose(n, k) { k = Math.round(k); if (utils.hasNaN(n, k)) { return NaN; } if (k < 0) { return -Infinity; } if (k === 0) { return 0; } if (k === 1) { return Math.log(Math.abs(n)); } if (n < 0) { return lchoose(-n + k - 1, k); } if (n === Math.round(n)) { if (n < k) { return -Infinity; } if (n - k < 2) { return lchoose(n, n - k); } return lfastchoose(n, k); } if (n < k - 1) { return lfastchoose2(n, k); } return lfastchoose(n, k); }
javascript
{ "resource": "" }
q38186
choose
train
function choose(n, k) { var ret, j; k = Math.round(k); if (utils.hasNaN(n, k)) { return NaN; } if (k < kSmallMax) { if (n - k < k && n >= 0 && n === Math.round(n)) { k = n - k; } if (k < 0) { return 0; } if (k === 0) { return 1; } ret = n; for (j = 2; j <= k; j += 1) { ret *= (n - j + 1) / j; } return n === Math.round(n) ? Math.round(ret) : ret; } if (n < 0) { ret = choose(-n + k - 1, k); return k % 2 === 1 ? -ret : ret; } if (n === Math.round(n)) { if (n < k) { return 0; } if (n - k < kSmallMax) { return choose(n, n - k); } return Math.round(Math.exp(lfastchoose(n, k))); } if (n < k - 1) { return signGamma(n - k + 1) * Math.exp(lfastchoose2(n, k)); } return Math.exp(lfastchoose(n, k)); }
javascript
{ "resource": "" }
q38187
train
function(item) { var self = this; var items = Array.isArray(item) ? item : [item]; var added = false; _.each(items, function(item) { if(!_.contains(self.items, item)) { self.items.push(item); if(item && item.klass == 'Instance') { item.once('delete', function() { self.remove(item); }); }; added = true; } }); if(added) { self.emit('add'); self.emit('change:size'); self.emit('change'); } return self; }
javascript
{ "resource": "" }
q38188
myOnresizebeforedraw
train
function myOnresizebeforedraw (obj) { var gutterLeft = obj.Get('chart.gutter.left'); var gutterRight = obj.Get('chart.gutter.right'); obj.Set('chart.hmargin', (obj.canvas.width - gutterLeft - gutterRight) / (obj.original_data[0].length * 2)); }
javascript
{ "resource": "" }
q38189
compare
train
function compare(data, encrypted) { var deferred = Q.defer(); bcrypt.compare(data, encrypted, function (err, res) { err ? deferred.reject(err) : deferred.resolve(res); }); return deferred.promise; }
javascript
{ "resource": "" }
q38190
generateHash
train
function generateHash(data) { var deferred = Q.defer(); bcrypt.hash(data, 10, function (err, res) { err ? deferred.reject(err) : deferred.resolve(res); }); return deferred.promise; }
javascript
{ "resource": "" }
q38191
isDisabled
train
function isDisabled(app, key, prop) { // key + '.plugin' if (app.isFalse([key, prop])) { return true; } // key + '.plugin.disable' if (app.isTrue([key, prop, 'disable'])) { return true; } return false; }
javascript
{ "resource": "" }
q38192
bh
train
function bh(name, options, cb) { var filePath; var bhModule; var html; var lang; if (typeof options.lang === 'string') { lang = options.lang; } // reject rendering for empty options.bemjson if (!options.bemjson) { cb(Error('No bemjson was passed')); return; } filePath = U.fulfillName({ name: name, ext: opts.ext || this.ext, mask: opts.source, lang: lang }); // drop cache if (opts.force || options.forceExec || options.forceLoad) { dropRequireCache = dropRequireCache || require('enb/lib/fs/drop-require-cache'); dropRequireCache(require, filePath); } try { bhModule = require(filePath); } catch (e) { cb(e); return; } // add data to use in templates if (opts.dataKey) { options.bemjson[opts.dataKey] = bhModule.utils.extend({}, options); delete options.bemjson[opts.dataKey].bemjson; } try { html = bhModule.apply(options.bemjson); } catch (e) { cb(e); return; } cb(null, html); }
javascript
{ "resource": "" }
q38193
request
train
function request (app) { app = app || blueprint.app.server.express; return supertest (app); }
javascript
{ "resource": "" }
q38194
train
function (id) { var span = document.createElement('span') span.title = id api.sbot.names.getSignifier(id, function (err, name) { span.textContent = name }) if(!span.textContent) span.textContent = id return span }
javascript
{ "resource": "" }
q38195
generateBundleName
train
function generateBundleName(mains) { // Join mains into a string. var joinedMains = mains.sort().join('-'); // Create hash. var hash = crypto.createHash('md5').update(joinedMains).digest('hex'); // Replace any special chars. joinedMains = joinedMains.replace(/\/|\\|\./g, '_'); // Truncate and append hash. var bundleName = joinedMains.slice(0, 16) + '-' + hash.slice(0, 6); return bundleName; }
javascript
{ "resource": "" }
q38196
getDirectCustomChildren
train
function getDirectCustomChildren(element, inclusive) { if (!inclusive && element.nodeState !== undefined) return []; let childRegistry = getChildRegistry(element); let children = []; for (let name in childRegistry) { let child = [].concat(childRegistry[name]); child.forEach((c) => { if (isCustomElement(c)) children.push(c); else children = children.concat(getDirectCustomChildren(c)); }); } return children; }
javascript
{ "resource": "" }
q38197
setStyle
train
function setStyle(element, key, value) { assertType(element, Node, false, 'Invalid element specified'); if (typeof value === 'number') value = String(value); if (value === null || value === undefined) value = ''; element.style[key] = value; }
javascript
{ "resource": "" }
q38198
TimeTraveler
train
function TimeTraveler(settings) { // coerce the +starts_at+ value into a moment var starts_at_moment = moment(settings.starts_at); // initialize new TimeTraveler object attributes this.starts_at = starts_at_moment; this.steps = settings.steps; this.time_units = settings.time_units; this.time_scale = settings.time_scale || 1; this.current = { time: starts_at_moment, step: 0 }; }
javascript
{ "resource": "" }
q38199
train
function (t, timerName) { if (this.enabled) { var id = _.uniqueId('jt'); this._startDate[id] = t || (+new Date()); if (console.profile && timerName) { this._timerConsoleName[id] = timerName; console.profile(timerName); } return id; } }
javascript
{ "resource": "" }