_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q64300
startGc
test
function startGc(db, options) { this.options = options || {} var freqMs = options.gcFreqMs || 60000 var maxVersions = options.gcMaxVersions var maxAge = options.gcMaxAge var backup = options.gcBackup var callback = options.gcCallback if (maxAge || maxVersions) { maxAge = maxAge || Math.pow(2, 53) maxVersion = maxVersions || Math.pow(2, 53) function filter(record) { if (record.version != null) { if (Date.now() - record.version > maxAge) return true } if (record.key != this.currentKey) { this.currentKey = record.key this.currentCount = 0 } return this.currentCount++ >= maxVersions } this.scanner = gc(db, filter, backup) return looseInterval(scanner.run.bind(scanner), freqMs, callback) } }
javascript
{ "resource": "" }
q64301
test
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof NameFormInfo)){ return new NameFormInfo(json); } // If the given object is already an instance then just return it. DON'T copy it. if(NameFormInfo.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q64302
test
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof OAuth2)){ return new OAuth2(json); } // If the given object is already an instance then just return it. DON'T copy it. if(OAuth2.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q64303
forceInRange
test
function forceInRange (value, min, max) { if (value > max) {return max;} else if (value < min) {return min;} else {return value;} }
javascript
{ "resource": "" }
q64304
insertIntoList
test
function insertIntoList(item, position, list) { var before = list.slice(0, position); var after = list.slice(position); return before.push(item).concat(after) }
javascript
{ "resource": "" }
q64305
validateProps
test
function validateProps(token) { Object.keys(token.props).forEach(key => { if (!validateProp(key, token.props[key])) { throw Tools.syntaxError(`Invalid value for "${key}" property`, token); } }); }
javascript
{ "resource": "" }
q64306
Event
test
function Event(name, attributes) { this._name = name; this._stopped = false; this._attrs = {}; if (attributes) { this.setAttributes(attributes); } }
javascript
{ "resource": "" }
q64307
create
test
function create(text) { return Tools.instance({ text, pos: 0 }, { isDone, getPos, expect, accept, expectRE, acceptRE, goto }); }
javascript
{ "resource": "" }
q64308
test
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof FeedbackInfo)){ return new FeedbackInfo(json); } // If the given object is already an instance then just return it. DON'T copy it. if(FeedbackInfo.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q64309
test
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Reservation)){ return new Reservation(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Reservation.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q64310
test
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof SearchInfo)){ return new SearchInfo(json); } // If the given object is already an instance then just return it. DON'T copy it. if(SearchInfo.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q64311
asyncForEach
test
function asyncForEach (array, iterator, done) { if (array.length === 0) { // NOTE: Normally a bad idea to mix sync and async, but it's safe here because // of the way that this method is currently used by DirectoryReader. done(); return; } // Simultaneously process all items in the array. let pending = array.length; array.forEach(item => { iterator(item, () => { if (--pending === 0) { done(); } }); }); }
javascript
{ "resource": "" }
q64312
safeCall
test
function safeCall (fn, args) { // Get the function arguments as an array args = Array.prototype.slice.call(arguments, 1); // Replace the callback function with a wrapper that ensures it will only be called once let callback = call.once(args.pop()); args.push(callback); try { fn.apply(null, args); } catch (err) { callback(err); } }
javascript
{ "resource": "" }
q64313
callOnce
test
function callOnce (fn) { let fulfilled = false; return function onceWrapper (err) { if (!fulfilled) { fulfilled = true; return fn.apply(this, arguments); } else if (err) { // The callback has already been called, but now an error has occurred // (most likely inside the callback function). So re-throw the error, // so it gets handled further up the call stack throw err; } }; }
javascript
{ "resource": "" }
q64314
uniqNoSet
test
function uniqNoSet(arr) { var ret = []; for (var i = 0; i < arr.length; i++) { if (ret.indexOf(arr[i]) === -1) { ret.push(arr[i]); } } return ret; }
javascript
{ "resource": "" }
q64315
uniqSetWithForEach
test
function uniqSetWithForEach(arr) { var ret = []; (new Set(arr)).forEach(function (el) { ret.push(el); }); return ret; }
javascript
{ "resource": "" }
q64316
Base
test
function Base(config, options) { if (!(this instanceof Base)) { return new Base(config, options); } Cache.call(this, config); this.is('base'); this.initBase(config, options); }
javascript
{ "resource": "" }
q64317
memoize
test
function memoize(type, pattern, options, fn) { var key = utils.createKey(type + ':' + pattern, options); var disabled = options && options.cache === false; if (disabled) { braces.clearCache(); return fn(pattern, options); } if (cache.hasOwnProperty(key)) { return cache[key]; } var res = fn(pattern, options); cache[key] = res; return res; }
javascript
{ "resource": "" }
q64318
multiply
test
function multiply(queue, n, options) { return utils.flatten(utils.repeat(utils.arrayify(queue), n)); }
javascript
{ "resource": "" }
q64319
noInner
test
function noInner(node, type) { if (node.parent.queue.length === 1) { return true; } var nodes = node.parent.nodes; return nodes.length === 3 && isType(nodes[0], 'brace.open') && !isType(nodes[1], 'text') && isType(nodes[2], 'brace.close'); }
javascript
{ "resource": "" }
q64320
brackets
test
function brackets(pattern, options) { debug('initializing from <%s>', __filename); var res = brackets.create(pattern, options); return res.output; }
javascript
{ "resource": "" }
q64321
wrap
test
function wrap(arr, sep, opts) { if (sep === '~') { sep = '-'; } var str = arr.join(sep); var pre = opts && opts.regexPrefix; // regex logical `or` if (sep === '|') { str = pre ? pre + str : str; str = '(' + str + ')'; } // regex character class if (sep === '-') { str = (pre && pre === '^') ? pre + str : str; str = '[' + str + ']'; } return [str]; }
javascript
{ "resource": "" }
q64322
formatPadding
test
function formatPadding(ch, pad) { var res = pad ? pad + ch : ch; if (pad && ch.toString().charAt(0) === '-') { res = '-' + pad + ch.toString().substr(1); } return res.toString(); }
javascript
{ "resource": "" }
q64323
isPadded
test
function isPadded(origA, origB) { if (hasZeros(origA) || hasZeros(origB)) { var alen = length(origA); var blen = length(origB); var len = alen >= blen ? alen : blen; return function (a) { return repeatStr('0', len - length(a)); }; } return false; }
javascript
{ "resource": "" }
q64324
Extglob
test
function Extglob(options) { this.options = extend({source: 'extglob'}, options); this.snapdragon = this.options.snapdragon || new Snapdragon(this.options); this.snapdragon.patterns = this.snapdragon.patterns || {}; this.compiler = this.snapdragon.compiler; this.parser = this.snapdragon.parser; compilers(this.snapdragon); parsers(this.snapdragon); /** * Override Snapdragon `.parse` method */ define(this.snapdragon, 'parse', function(str, options) { var parsed = Snapdragon.prototype.parse.apply(this, arguments); parsed.input = str; // escape unmatched brace/bracket/parens var last = this.parser.stack.pop(); if (last && this.options.strict !== true) { var node = last.nodes[0]; node.val = '\\' + node.val; var sibling = node.parent.nodes[1]; if (sibling.type === 'star') { sibling.loose = true; } } // add non-enumerable parser reference define(parsed, 'parser', this.parser); return parsed; }); /** * Decorate `.parse` method */ define(this, 'parse', function(ast, options) { return this.snapdragon.parse.apply(this.snapdragon, arguments); }); /** * Decorate `.compile` method */ define(this, 'compile', function(ast, options) { return this.snapdragon.compile.apply(this.snapdragon, arguments); }); }
javascript
{ "resource": "" }
q64325
micromatch
test
function micromatch(list, patterns, options) { patterns = utils.arrayify(patterns); list = utils.arrayify(list); var len = patterns.length; if (list.length === 0 || len === 0) { return []; } if (len === 1) { return micromatch.match(list, patterns[0], options); } var omit = []; var keep = []; var idx = -1; while (++idx < len) { var pattern = patterns[idx]; if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options)); } else { keep.push.apply(keep, micromatch.match(list, pattern, options)); } } var matches = utils.diff(keep, omit); if (!options || options.nodupes !== false) { return utils.unique(matches); } return matches; }
javascript
{ "resource": "" }
q64326
sync
test
function sync(source, opts) { var works = getWorks(source, reader_sync_1.default, opts); return arrayUtils.flatten(works); }
javascript
{ "resource": "" }
q64327
stream
test
function stream(source, opts) { var works = getWorks(source, reader_stream_1.default, opts); return merge2(works); }
javascript
{ "resource": "" }
q64328
generateTasks
test
function generateTasks(source, opts) { var patterns = [].concat(source); var options = optionsManager.prepare(opts); return taskManager.generate(patterns, options); }
javascript
{ "resource": "" }
q64329
getWorks
test
function getWorks(source, _Reader, opts) { var patterns = [].concat(source); var options = optionsManager.prepare(opts); var tasks = taskManager.generate(patterns, options); var reader = new _Reader(options); return tasks.map(reader.read, reader); }
javascript
{ "resource": "" }
q64330
generate
test
function generate(patterns, options) { var unixPatterns = patterns.map(patternUtils.unixifyPattern); var unixIgnore = options.ignore.map(patternUtils.unixifyPattern); var positivePatterns = getPositivePatterns(unixPatterns); var negativePatterns = getNegativePatternsAsPositive(unixPatterns, unixIgnore); var staticPatterns = positivePatterns.filter(patternUtils.isStaticPattern); var dynamicPatterns = positivePatterns.filter(patternUtils.isDynamicPattern); var staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); var dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); return staticTasks.concat(dynamicTasks); }
javascript
{ "resource": "" }
q64331
convertPatternsToTasks
test
function convertPatternsToTasks(positive, negative, dynamic) { var positivePatternsGroup = groupPatternsByBaseDirectory(positive); var negativePatternsGroup = groupPatternsByBaseDirectory(negative); // When we have a global group – there is no reason to divide the patterns into independent tasks. // In this case, the global task covers the rest. if ('.' in positivePatternsGroup) { var task = convertPatternGroupToTask('.', positive, negative, dynamic); return [task]; } return convertPatternGroupsToTasks(positivePatternsGroup, negativePatternsGroup, dynamic); }
javascript
{ "resource": "" }
q64332
getNegativePatternsAsPositive
test
function getNegativePatternsAsPositive(patterns, ignore) { var negative = patternUtils.getNegativePatterns(patterns).concat(ignore); var positive = negative.map(patternUtils.convertToPositivePattern); return positive; }
javascript
{ "resource": "" }
q64333
groupPatternsByBaseDirectory
test
function groupPatternsByBaseDirectory(patterns) { return patterns.reduce(function (collection, pattern) { var base = patternUtils.getBaseDirectory(pattern); if (base in collection) { collection[base].push(pattern); } else { collection[base] = [pattern]; } return collection; }, {}); }
javascript
{ "resource": "" }
q64334
convertPatternGroupsToTasks
test
function convertPatternGroupsToTasks(positive, negative, dynamic) { var globalNegative = '.' in negative ? negative['.'] : []; return Object.keys(positive).map(function (base) { var localNegative = findLocalNegativePatterns(base, negative); var fullNegative = localNegative.concat(globalNegative); return convertPatternGroupToTask(base, positive[base], fullNegative, dynamic); }); }
javascript
{ "resource": "" }
q64335
findLocalNegativePatterns
test
function findLocalNegativePatterns(positiveBase, negative) { return Object.keys(negative).reduce(function (collection, base) { if (base.startsWith(positiveBase)) { collection.push.apply(collection, __spread(negative[base])); } return collection; }, []); }
javascript
{ "resource": "" }
q64336
convertPatternGroupToTask
test
function convertPatternGroupToTask(base, positive, negative, dynamic) { return { base: base, dynamic: dynamic, patterns: [].concat(positive, negative.map(patternUtils.convertToNegativePattern)), positive: positive, negative: negative }; }
javascript
{ "resource": "" }
q64337
matchAny
test
function matchAny(entry, patternsRe) { try { for (var patternsRe_1 = __values(patternsRe), patternsRe_1_1 = patternsRe_1.next(); !patternsRe_1_1.done; patternsRe_1_1 = patternsRe_1.next()) { var regexp = patternsRe_1_1.value; if (regexp.test(entry)) { return true; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (patternsRe_1_1 && !patternsRe_1_1.done && (_a = patternsRe_1.return)) _a.call(patternsRe_1); } finally { if (e_1) throw e_1.error; } } return false; var e_1, _a; }
javascript
{ "resource": "" }
q64338
test
function () { removeNotFoundFiles(); var entries = normalizedEntries; var keys = Object.keys( entries ); if ( keys.length === 0 ) { return; } keys.forEach( function ( entryName ) { var cacheEntry = entries[ entryName ]; try { var stat = fs.statSync( cacheEntry.key ); var meta = assign( cacheEntry.meta, { size: stat.size, mtime: stat.mtime.getTime() } ); cache.setKey( entryName, meta ); } catch (err) { // if the file does not exists we don't save it // other errors are just thrown if ( err.code !== 'ENOENT' ) { throw err; } } } ); cache.save( true ); }
javascript
{ "resource": "" }
q64339
test
function ( pathToFile ) { var me = this; var dir = path.dirname( pathToFile ); var fName = path.basename( pathToFile ); me.load( fName, dir ); }
javascript
{ "resource": "" }
q64340
test
function ( noPrune ) { var me = this; (!noPrune) && me._prune(); writeJSON( me._pathToFile, me._persisted ); }
javascript
{ "resource": "" }
q64341
test
function ( docId, cacheDir ) { var obj = Object.create( cache ); obj.load( docId, cacheDir ); return obj; }
javascript
{ "resource": "" }
q64342
test
function ( docId, cacheDir ) { var filePath = cacheDir ? path.resolve( cacheDir, docId ) : path.resolve( __dirname, './.cache/', docId ); return del( filePath, { force: true } ).length > 0; }
javascript
{ "resource": "" }
q64343
test
function(cacheName, key, val) { var cache = this.cache(cacheName); cache.set(key, val); return cache; }
javascript
{ "resource": "" }
q64344
LOOP
test
function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); }
javascript
{ "resource": "" }
q64345
micromatch
test
function micromatch(files, patterns, opts) { if (!files || !patterns) return []; opts = opts || {}; if (typeof opts.cache === 'undefined') { opts.cache = true; } if (!Array.isArray(patterns)) { return match(files, patterns, opts); } var len = patterns.length, i = 0; var omit = [], keep = []; while (len--) { var glob = patterns[i++]; if (typeof glob === 'string' && glob.charCodeAt(0) === 33 /* ! */) { omit.push.apply(omit, match(files, glob.slice(1), opts)); } else { keep.push.apply(keep, match(files, glob, opts)); } } return utils.diff(keep, omit); }
javascript
{ "resource": "" }
q64346
match
test
function match(files, pattern, opts) { if (utils.typeOf(files) !== 'string' && !Array.isArray(files)) { throw new Error(msg('match', 'files', 'a string or array')); } files = utils.arrayify(files); opts = opts || {}; var negate = opts.negate || false; var orig = pattern; if (typeof pattern === 'string') { negate = pattern.charAt(0) === '!'; if (negate) { pattern = pattern.slice(1); } // we need to remove the character regardless, // so the above logic is still needed if (opts.nonegate === true) { negate = false; } } var _isMatch = matcher(pattern, opts); var len = files.length, i = 0; var res = []; while (i < len) { var file = files[i++]; var fp = utils.unixify(file, opts); if (!_isMatch(fp)) { continue; } res.push(fp); } if (res.length === 0) { if (opts.failglob === true) { throw new Error('micromatch.match() found no matches for: "' + orig + '".'); } if (opts.nonull || opts.nullglob) { res.push(utils.unescapeGlob(orig)); } } // if `negate` was defined, diff negated files if (negate) { res = utils.diff(files, res); } // if `ignore` was defined, diff ignored filed if (opts.ignore && opts.ignore.length) { pattern = opts.ignore; opts = utils.omit(opts, ['ignore']); res = utils.diff(res, micromatch(res, pattern, opts)); } if (opts.nodupes) { return utils.unique(res); } return res; }
javascript
{ "resource": "" }
q64347
isMatch
test
function isMatch(fp, pattern, opts) { if (typeof fp !== 'string') { throw new TypeError(msg('isMatch', 'filepath', 'a string')); } fp = utils.unixify(fp, opts); if (utils.typeOf(pattern) === 'object') { return matcher(fp, pattern); } return matcher(pattern, opts)(fp); }
javascript
{ "resource": "" }
q64348
contains
test
function contains(fp, pattern, opts) { if (typeof fp !== 'string') { throw new TypeError(msg('contains', 'pattern', 'a string')); } opts = opts || {}; opts.contains = (pattern !== ''); fp = utils.unixify(fp, opts); if (opts.contains && !utils.isGlob(pattern)) { return fp.indexOf(pattern) !== -1; } return matcher(pattern, opts)(fp); }
javascript
{ "resource": "" }
q64349
any
test
function any(fp, patterns, opts) { if (!Array.isArray(patterns) && typeof patterns !== 'string') { throw new TypeError(msg('any', 'patterns', 'a string or array')); } patterns = utils.arrayify(patterns); var len = patterns.length; fp = utils.unixify(fp, opts); while (len--) { var isMatch = matcher(patterns[len], opts); if (isMatch(fp)) { return true; } } return false; }
javascript
{ "resource": "" }
q64350
matchKeys
test
function matchKeys(obj, glob, options) { if (utils.typeOf(obj) !== 'object') { throw new TypeError(msg('matchKeys', 'first argument', 'an object')); } var fn = matcher(glob, options); var res = {}; for (var key in obj) { if (obj.hasOwnProperty(key) && fn(key)) { res[key] = obj[key]; } } return res; }
javascript
{ "resource": "" }
q64351
matcher
test
function matcher(pattern, opts) { // pattern is a function if (typeof pattern === 'function') { return pattern; } // pattern is a regex if (pattern instanceof RegExp) { return function(fp) { return pattern.test(fp); }; } if (typeof pattern !== 'string') { throw new TypeError(msg('matcher', 'pattern', 'a string, regex, or function')); } // strings, all the way down... pattern = utils.unixify(pattern, opts); // pattern is a non-glob string if (!utils.isGlob(pattern)) { return utils.matchPath(pattern, opts); } // pattern is a glob string var re = makeRe(pattern, opts); // `matchBase` is defined if (opts && opts.matchBase) { return utils.hasFilename(re, opts); } // `matchBase` is not defined return function(fp) { fp = utils.unixify(fp, opts); return re.test(fp); }; }
javascript
{ "resource": "" }
q64352
toRegex
test
function toRegex(glob, options) { // clone options to prevent mutating the original object var opts = Object.create(options || {}); var flags = opts.flags || ''; if (opts.nocase && flags.indexOf('i') === -1) { flags += 'i'; } var parsed = expand(glob, opts); // pass in tokens to avoid parsing more than once opts.negated = opts.negated || parsed.negated; opts.negate = opts.negated; glob = wrapGlob(parsed.pattern, opts); var re; try { re = new RegExp(glob, flags); return re; } catch (err) { err.reason = 'micromatch invalid regex: (' + re + ')'; if (opts.strict) throw new SyntaxError(err); } // we're only here if a bad pattern was used and the user // passed `options.silent`, so match nothing return /$^/; }
javascript
{ "resource": "" }
q64353
wrapGlob
test
function wrapGlob(glob, opts) { var prefix = (opts && !opts.contains) ? '^' : ''; var after = (opts && !opts.contains) ? '$' : ''; glob = ('(?:' + glob + ')' + after); if (opts && opts.negate) { return prefix + ('(?!^' + glob + ').*$'); } return prefix + glob; }
javascript
{ "resource": "" }
q64354
makeRe
test
function makeRe(glob, opts) { if (utils.typeOf(glob) !== 'string') { throw new Error(msg('makeRe', 'glob', 'a string')); } return utils.cache(toRegex, glob, opts); }
javascript
{ "resource": "" }
q64355
collapse
test
function collapse(str, ch) { var res = str.split(ch); var isFirst = res[0] === ''; var isLast = res[res.length - 1] === ''; res = res.filter(Boolean); if (isFirst) res.unshift(''); if (isLast) res.push(''); return res.join(ch); }
javascript
{ "resource": "" }
q64356
exponential
test
function exponential(str, options, fn) { if (typeof options === 'function') { fn = options; options = null; } var opts = options || {}; var esc = '__ESC_EXP__'; var exp = 0; var res; var parts = str.split('{,}'); if (opts.nodupes) { return fn(parts.join(''), opts); } exp = parts.length - 1; res = fn(parts.join(esc), opts); var len = res.length; var arr = []; var i = 0; while (len--) { var ele = res[i++]; var idx = ele.indexOf(esc); if (idx === -1) { arr.push(ele); } else { ele = ele.split('__ESC_EXP__').join(''); if (!!ele && opts.nodupes !== false) { arr.push(ele); } else { var num = Math.pow(2, exp); arr.push.apply(arr, repeat(ele, num)); } } } return arr; }
javascript
{ "resource": "" }
q64357
splitWhitespace
test
function splitWhitespace(str) { var segs = str.split(' '); var len = segs.length; var res = []; var i = 0; while (len--) { res.push.apply(res, braces(segs[i++])); } return res; }
javascript
{ "resource": "" }
q64358
filter
test
function filter(arr, cb) { if (arr == null) return []; if (typeof cb !== 'function') { throw new TypeError('braces: filter expects a callback function.'); } var len = arr.length; var res = arr.slice(); var i = 0; while (len--) { if (!cb(arr[len], i++)) { res.splice(len, 1); } } return res; }
javascript
{ "resource": "" }
q64359
extglob
test
function extglob(str, opts) { opts = opts || {}; var o = {}, i = 0; // fix common character reversals // '*!(.js)' => '*.!(js)' str = str.replace(/!\(([^\w*()])/g, '$1!('); // support file extension negation str = str.replace(/([*\/])\.!\([*]\)/g, function (m, ch) { if (ch === '/') { return escape('\\/[^.]+'); } return escape('[^.]+'); }); // create a unique key for caching by // combining the string and options var key = str + String(!!opts.regex) + String(!!opts.contains) + String(!!opts.escape); if (cache.hasOwnProperty(key)) { return cache[key]; } if (!(re instanceof RegExp)) { re = regex(); } opts.negate = false; var m; while (m = re.exec(str)) { var prefix = m[1]; var inner = m[3]; if (prefix === '!') { opts.negate = true; } var id = '__EXTGLOB_' + (i++) + '__'; // use the prefix of the _last_ (outtermost) pattern o[id] = wrap(inner, prefix, opts.escape); str = str.split(m[0]).join(id); } var keys = Object.keys(o); var len = keys.length; // we have to loop again to allow us to convert // patterns in reverse order (starting with the // innermost/last pattern first) while (len--) { var prop = keys[len]; str = str.split(prop).join(o[prop]); } var result = opts.regex ? toRegex(str, opts.contains, opts.negate) : str; result = result.split('.').join('\\.'); // cache the result and return it return (cache[key] = result); }
javascript
{ "resource": "" }
q64360
wrap
test
function wrap(inner, prefix, esc) { if (esc) inner = escape(inner); switch (prefix) { case '!': return '(?!' + inner + ')[^/]' + (esc ? '%%%~' : '*?'); case '@': return '(?:' + inner + ')'; case '+': return '(?:' + inner + ')+'; case '*': return '(?:' + inner + ')' + (esc ? '%%' : '*') case '?': return '(?:' + inner + '|)'; default: return inner; } }
javascript
{ "resource": "" }
q64361
toRegex
test
function toRegex(pattern, contains, isNegated) { var prefix = contains ? '^' : ''; var after = contains ? '$' : ''; pattern = ('(?:' + pattern + ')' + after); if (isNegated) { pattern = prefix + negate(pattern); } return new RegExp(prefix + pattern); }
javascript
{ "resource": "" }
q64362
copy
test
function copy(val, key) { if (key === '__proto__') { return; } var obj = this[key]; if (isObject(val) && isObject(obj)) { mixinDeep(obj, val); } else { this[key] = val; } }
javascript
{ "resource": "" }
q64363
advanceTo
test
function advanceTo(input, endChar) { var ch = input.charAt(0); var tok = { len: 1, val: '', esc: '' }; var idx = 0; function advance() { if (ch !== '\\') { tok.esc += '\\' + ch; tok.val += ch; } ch = input.charAt(++idx); tok.len++; if (ch === '\\') { advance(); advance(); } } while (ch && ch !== endChar) { advance(); } return tok; }
javascript
{ "resource": "" }
q64364
BasicSourceMapConsumer
test
function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = util.parseSourceMapInput(aSourceMap); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } if (sourceRoot) { sourceRoot = util.normalize(sourceRoot); } sources = sources .map(String) // Some source maps produce relative source paths like "./foo.js" instead of // "foo.js". Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. .map(util.normalize) // Always ensure that absolute sources are internally stored relative to // the source root, if the source root is absolute. Not doing this would // be particularly problematic when the source root is a prefix of the // source (valid, but why??). See github issue #199 and bugzil.la/1188982. .map(function (source) { return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source; }); // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names.map(String), true); this._sources = ArraySet.fromArray(sources, true); this._absoluteSources = this._sources.toArray().map(function (s) { return util.computeSourceURL(sourceRoot, s, aSourceMapURL); }); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this._sourceMapURL = aSourceMapURL; this.file = file; }
javascript
{ "resource": "" }
q64365
compareByOriginalPositions
test
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); }
javascript
{ "resource": "" }
q64366
compareByGeneratedPositionsDeflated
test
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); }
javascript
{ "resource": "" }
q64367
computeSourceURL
test
function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { sourceURL = sourceURL || ''; if (sourceRoot) { // This follows what Chrome does. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { sourceRoot += '/'; } // The spec says: // Line 4: An optional source root, useful for relocating source // files on a server or removing repeated values in the // “sources” entry. This value is prepended to the individual // entries in the “source” field. sourceURL = sourceRoot + sourceURL; } // Historically, SourceMapConsumer did not take the sourceMapURL as // a parameter. This mode is still somewhat supported, which is why // this code block is conditional. However, it's preferable to pass // the source map URL to SourceMapConsumer, so that this function // can implement the source URL resolution algorithm as outlined in // the spec. This block is basically the equivalent of: // new URL(sourceURL, sourceMapURL).toString() // ... except it avoids using URL, which wasn't available in the // older releases of node still supported by this library. // // The spec says: // If the sources are not absolute URLs after prepending of the // “sourceRoot”, the sources are resolved relative to the // SourceMap (like resolving script src in a html document). if (sourceMapURL) { var parsed = urlParse(sourceMapURL); if (!parsed) { throw new Error("sourceMapURL could not be parsed"); } if (parsed.path) { // Strip the last path component, but keep the "/". var index = parsed.path.lastIndexOf('/'); if (index >= 0) { parsed.path = parsed.path.substring(0, index + 1); } } sourceURL = join(urlGenerate(parsed), sourceURL); } return normalize(sourceURL); }
javascript
{ "resource": "" }
q64368
CorkedRequest
test
function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; }
javascript
{ "resource": "" }
q64369
clearBuffer
test
function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; }
javascript
{ "resource": "" }
q64370
Node
test
function Node(val, type, parent) { if (typeof type !== 'string') { parent = type; type = null; } define(this, 'parent', parent); define(this, 'isNode', true); define(this, 'expect', null); if (typeof type !== 'string' && isObject(val)) { lazyKeys(); var keys = Object.keys(val); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (ownNames.indexOf(key) === -1) { this[key] = val[key]; } } } else { this.type = type; this.val = val; } }
javascript
{ "resource": "" }
q64371
append
test
function append(compiler, val, node) { if (typeof compiler.append !== 'function') { return compiler.emit(val, node); } return compiler.append(val, node); }
javascript
{ "resource": "" }
q64372
Snapdragon
test
function Snapdragon(options) { Base.call(this, null, options); this.options = utils.extend({source: 'string'}, this.options); this.compiler = new Compiler(this.options); this.parser = new Parser(this.options); Object.defineProperty(this, 'compilers', { get: function() { return this.compiler.compilers; } }); Object.defineProperty(this, 'parsers', { get: function() { return this.parser.parsers; } }); Object.defineProperty(this, 'regex', { get: function() { return this.parser.regex; } }); }
javascript
{ "resource": "" }
q64373
test
function(msg, node) { var pos = node.position || {start: {column: 0}}; var message = this.options.source + ' column:' + pos.start.column + ': ' + msg; var err = new Error(message); err.reason = msg; err.column = pos.start.column; err.source = this.pattern; if (this.options.silent) { this.errors.push(err); } else { throw err; } }
javascript
{ "resource": "" }
q64374
test
function(node, nodes, i) { var fn = this.compilers[node.type]; this.idx = i; if (typeof fn !== 'function') { throw this.error('compiler "' + node.type + '" is not registered', node); } return fn.call(this, node, nodes, i); }
javascript
{ "resource": "" }
q64375
test
function(ast, options) { var opts = utils.extend({}, this.options, options); this.ast = ast; this.parsingErrors = this.ast.errors; this.output = ''; // source map support if (opts.sourcemap) { var sourcemaps = require('./source-maps'); sourcemaps(this); this.mapVisit(this.ast.nodes); this.applySourceMaps(); this.map = opts.sourcemap === 'generator' ? this.map : this.map.toJSON(); return this; } this.mapVisit(this.ast.nodes); return this; }
javascript
{ "resource": "" }
q64376
Parser
test
function Parser(options) { debug('initializing', __filename); this.options = utils.extend({source: 'string'}, options); this.init(this.options); use(this); }
javascript
{ "resource": "" }
q64377
test
function(type, fn) { if (this.types.indexOf(type) === -1) { this.types.push(type); } this.parsers[type] = fn.bind(this); return this; }
javascript
{ "resource": "" }
q64378
test
function(type, token) { this.sets[type] = this.sets[type] || []; this.count++; this.stack.push(token); return this.sets[type].push(token); }
javascript
{ "resource": "" }
q64379
test
function(type) { this.sets[type] = this.sets[type] || []; this.count--; this.stack.pop(); return this.sets[type].pop(); }
javascript
{ "resource": "" }
q64380
test
function(n) { return this.stack.length > 0 ? utils.last(this.stack, n) : utils.last(this.nodes, n); }
javascript
{ "resource": "" }
q64381
test
function(str, len) { var lines = str.match(/\n/g); if (lines) this.line += lines.length; var i = str.lastIndexOf('\n'); this.column = ~i ? len - i : this.column + len; this.parsed += str; this.consume(len); }
javascript
{ "resource": "" }
q64382
test
function(type, openRegex, closeRegex, fn) { this.sets[type] = this.sets[type] || []; /** * Open */ this.set(type + '.open', function() { var parsed = this.parsed; var pos = this.position(); var m = this.match(openRegex); if (!m || !m[0]) return; var val = m[0]; this.setCount++; this.specialChars = true; var open = pos({ type: type + '.open', val: val, rest: this.input }); if (typeof m[1] !== 'undefined') { open.inner = m[1]; } var prev = this.prev(); var node = pos({ type: type, nodes: [open] }); define(node, 'rest', this.input); define(node, 'parsed', parsed); define(node, 'prefix', m[1]); define(node, 'parent', prev); define(open, 'parent', node); if (typeof fn === 'function') { fn.call(this, open, node); } this.push(type, node); prev.nodes.push(node); }); /** * Close */ this.set(type + '.close', function() { var pos = this.position(); var m = this.match(closeRegex); if (!m || !m[0]) return; var parent = this.pop(type); var node = pos({ type: type + '.close', rest: this.input, suffix: m[1], val: m[0] }); if (!this.isType(parent, type)) { if (this.options.strict) { throw new Error('missing opening "' + type + '"'); } this.setCount--; node.escaped = true; return node; } if (node.suffix === '\\') { parent.escaped = true; node.escaped = true; } parent.nodes.push(node); define(node, 'parent', parent); }); return this; }
javascript
{ "resource": "" }
q64383
test
function() { var pos = this.position(); if (this.input) return; var prev = this.prev(); while (prev.type !== 'root' && !prev.visited) { if (this.options.strict === true) { throw new SyntaxError('invalid syntax:' + util.inspect(prev, null, 2)); } if (!hasDelims(prev)) { prev.parent.escaped = true; prev.escaped = true; } visit(prev, function(node) { if (!hasDelims(node.parent)) { node.parent.escaped = true; node.escaped = true; } }); prev = prev.parent; } var tok = pos({ type: 'eos', val: this.append || '' }); define(tok, 'parent', this.ast); return tok; }
javascript
{ "resource": "" }
q64384
test
function() { var parsed = this.parsed; var len = this.types.length; var idx = -1; var tok; while (++idx < len) { if ((tok = this.parsers[this.types[idx]].call(this))) { define(tok, 'rest', this.input); define(tok, 'parsed', parsed); this.last = tok; return tok; } } }
javascript
{ "resource": "" }
q64385
test
function(input) { if (typeof input !== 'string') { throw new TypeError('expected a string'); } this.init(this.options); this.orig = input; this.input = input; var self = this; function parse() { // check input before calling `.next()` input = self.input; // get the next AST ndoe var node = self.next(); if (node) { var prev = self.prev(); if (prev) { define(node, 'parent', prev); if (prev.nodes) { prev.nodes.push(node); } } if (self.sets.hasOwnProperty(prev.type)) { self.currentType = prev.type; } } // if we got here but input is not changed, throw an error if (self.input && input === self.input) { throw new Error('no parsers registered for: "' + self.input.slice(0, 5) + '"'); } } while (this.input) parse(); if (this.stack.length && this.options.strict) { var node = this.stack.pop(); throw this.error('missing opening ' + node.type + ': "' + this.orig + '"'); } var eos = this.eos(); var tok = this.prev(); if (tok.type !== 'eos') { this.ast.nodes.push(eos); } return this.ast; }
javascript
{ "resource": "" }
q64386
mixin
test
function mixin(compiler) { define(compiler, '_comment', compiler.comment); compiler.map = new utils.SourceMap.SourceMapGenerator(); compiler.position = { line: 1, column: 1 }; compiler.content = {}; compiler.files = {}; for (var key in exports) { define(compiler, key, exports[key]); } }
javascript
{ "resource": "" }
q64387
utf8End
test
function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'; return r; }
javascript
{ "resource": "" }
q64388
rangeToPattern
test
function rangeToPattern(start, stop, options) { if (start === stop) { return {pattern: String(start), digits: []}; } var zipped = zip(String(start), String(stop)); var len = zipped.length, i = -1; var pattern = ''; var digits = 0; while (++i < len) { var numbers = zipped[i]; var startDigit = numbers[0]; var stopDigit = numbers[1]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit); } else { digits += 1; } } if (digits) { pattern += options.shorthand ? '\\d' : '[0-9]'; } return { pattern: pattern, digits: [digits] }; }
javascript
{ "resource": "" }
q64389
use
test
function use(type, fn, options) { var offset = 1; if (typeof type === 'string' || Array.isArray(type)) { fn = wrap(type, fn); offset++; } else { options = fn; fn = type; } if (typeof fn !== 'function') { throw new TypeError('expected a function'); } var self = this || app; var fns = self[prop]; var args = [].slice.call(arguments, offset); args.unshift(self); if (typeof opts.hook === 'function') { opts.hook.apply(self, args); } var val = fn.apply(self, args); if (typeof val === 'function' && fns.indexOf(val) === -1) { fns.push(val); } return self; }
javascript
{ "resource": "" }
q64390
wrap
test
function wrap(type, fn) { return function plugin() { return this.type === type ? fn.apply(this, arguments) : plugin; }; }
javascript
{ "resource": "" }
q64391
memoize
test
function memoize(fun) { // Making cache = {} an optional ES6 parameter breaks coverage. Why? /** @type {({ [key: string]: any })} */ const cache = {}; if (fun.length === 1) { return (/** @type {any} */ arg) => { if (arg in cache) { return cache[arg]; } const result = fun(arg); cache[arg] = result; return result; }; } return (/** @type {any} */ arg1, /** @type {any} */ arg2) => { if (cache[arg1] && arg2 in cache[arg1]) { return cache[arg1][arg2]; } const result = fun(arg1, arg2); if (!cache[arg1]) { cache[arg1] = {}; } cache[arg1][arg2] = result; return result; }; }
javascript
{ "resource": "" }
q64392
keyblade
test
function keyblade (obj, opts) { opts = Object.assign({ message: _defaultMessage, logBeforeThrow: true, ignore: [] }, opts) opts.ignore = (opts.ignore && Array.isArray(opts.ignore)) ? opts.ignore : [] return new Proxy(obj, { get (target, propKey, receiver) { const useGetter = Reflect.has(target, propKey, receiver) || _isReserved(propKey, opts.ignore) if (useGetter) { return Reflect.get(target, propKey, receiver) } // Leave symbols alone. if (typeof propKey === 'symbol') { return Reflect.get(target, propKey, receiver) } const message = opts.message(propKey) if (opts.logBeforeThrow) { if (typeof opts.logBeforeThrow === 'function') { opts.logBeforeThrow(message, propKey) } else { console.error(message) } } throw new UndefinedKeyError(message) } }) }
javascript
{ "resource": "" }
q64393
subRegister
test
function subRegister(obj, name) { var res; res = isPrimitive(obj[name]) ? {} : obj[name]; return obj[name] = mixable(res).mixin(proto, 'register', 'extend'); }
javascript
{ "resource": "" }
q64394
registerDir
test
function registerDir(leaf, dir, name) { var files; try { files = fs.readdirSync(dir); } catch (_error) {} if (files == null) { return false; } if (name != null) { leaf = subRegister(leaf, name); } for (var i = 0, len = files.length; i < len; i++) { name = files[i]; leaf.register(dir, name); } return true; }
javascript
{ "resource": "" }
q64395
containerStatus
test
function containerStatus(original, status, parent) { var state = { topology: { containers: {} } }; var container = { id: original.id }; if (parent === null) { // nothing to do } else if (parent !== undefined) { container.containedBy = parent; } else { container.containedBy = original.containedBy; } if (typeof status === 'string') { switch(status) { case 'detached': container.added = false; container.started = false; container.running = false; break; case 'added': container.added = true; break; case 'started': container.started = true; break; case 'running': container.running = true; break; default: throw new Error('unknown state'); } } else { _.forIn(status, function(value, key) { container[key] = value; }); } if (container.added === false) { delete container.containedBy; } state.topology.containers[container.id] = container; return state; }
javascript
{ "resource": "" }
q64396
lstatFiles
test
async function lstatFiles(dirPath, dirContent) { const readFiles = dirContent.map(async (relativePath) => { const path = join(dirPath, relativePath) const ls = await makePromise(lstat, path) return { lstat: ls, path, relativePath, } }) const res = await Promise.all(readFiles) return res }
javascript
{ "resource": "" }
q64397
readDirStructure
test
async function readDirStructure(dirPath) { if (!dirPath) { throw new Error('Please specify a path to the directory') } const ls = await makePromise(lstat, dirPath) if (!ls.isDirectory()) { const err = new Error('Path is not a directory') err.code = 'ENOTDIR' throw err } const dir = /** @type {!Array<string>} */ (await makePromise(readdir, dirPath)) const lsr = await lstatFiles(dirPath, dir) const directories = lsr.filter(isDirectory) // reduce at once const notDirectories = lsr.filter(isNotDirectory) const files = notDirectories.reduce((acc, current) => { const type = getType(current) return { ...acc, [current.relativePath]: { type, }, } }, {}) const dirs = await directories.reduce(async (acc, { path, relativePath }) => { const res = await acc const structure = await readDirStructure(path) return { ...res, [relativePath]: structure, } }, {}) const content = { ...files, ...dirs, } return { content, type: 'Directory', } }
javascript
{ "resource": "" }
q64398
propertyNameToAttribute
test
function propertyNameToAttribute(name) { var result = name.replace(/([A-Z])/g, function (match, letter) { return '-' + letter.toLowerCase(); }); return 'data-' + result; }
javascript
{ "resource": "" }
q64399
generateCommands
test
function generateCommands(origin, dest) { var destCmds = _.chain(dest.topology.containers) .values() .filter(function(container) { return container.containedBy === container.id || !container.containedBy; }) .map(function(container) { return { cmd: 'configure', id: container.id }; }) .value(); var originCmds = _.chain(origin.topology.containers) .values() .map(function(container) { if (!dest.topology.containers[container.id]) { return { cmd: 'detach', id: container.id }; } return null; }).filter(function(container) { return container !== null; }) .value(); return destCmds.concat(originCmds); }
javascript
{ "resource": "" }