_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)
... | 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 = { isIn... | 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... | 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 (!s... | 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) {
... | 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(func... | 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.le... | 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)... | 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.... | 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)) {
... | 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.... | 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, c... | 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
... | 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.serverPreprocessi... | 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;
... | 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 = poo... | 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... | 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) {
... | 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 = ... | 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)... | 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) {
... | 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 ''
|| '$(?=.)' ... | 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.se... | 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... | 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.newPref... | 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 ... | 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.indexO... | 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 (... | 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 {
... | 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], "mi... | 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) ... | 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 === 'functio... | 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) ? getMonthPerio... | 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.defaultJoinsNeedPo... | 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) {
... | 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;
th... | 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;
asyn... | 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... | 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 + "/" + modu... | 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"... | 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) &&
... | 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 Reg... | 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... | 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... | 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', funct... | 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 bem... | 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... | 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 (isCusto... | 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 = set... | 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);
... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.