_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q20400
_unsqueeze
train
function _unsqueeze (array, dims, dim) { let i, ii if (Array.isArray(array)) { const next = dim + 1 for (i = 0, ii = array.length; i < ii; i++) { array[i] = _unsqueeze(array[i], dims, next) } } else { for (let d = dim; d < dims; d++) { array = [array] } } return array }
javascript
{ "resource": "" }
q20401
getSafeProperty
train
function getSafeProperty (object, prop) { // only allow getting safe properties of a plain object if (isPlainObject(object) && isSafeProperty(object, prop)) { return object[prop] } if (typeof object[prop] === 'function' && isSafeMethod(object, prop)) { throw new Error('Cannot access method "' + prop + '" as a property') } throw new Error('No access to property "' + prop + '"') }
javascript
{ "resource": "" }
q20402
setSafeProperty
train
function setSafeProperty (object, prop, value) { // only allow setting safe properties of a plain object if (isPlainObject(object) && isSafeProperty(object, prop)) { object[prop] = value return value } throw new Error('No access to property "' + prop + '"') }
javascript
{ "resource": "" }
q20403
isSafeProperty
train
function isSafeProperty (object, prop) { if (!object || typeof object !== 'object') { return false } // SAFE: whitelisted // e.g length if (hasOwnProperty(safeNativeProperties, prop)) { return true } // UNSAFE: inherited from Object prototype // e.g constructor if (prop in Object.prototype) { // 'in' is used instead of hasOwnProperty for nodejs v0.10 // which is inconsistent on root prototypes. It is safe // here because Object.prototype is a root object return false } // UNSAFE: inherited from Function prototype // e.g call, apply if (prop in Function.prototype) { // 'in' is used instead of hasOwnProperty for nodejs v0.10 // which is inconsistent on root prototypes. It is safe // here because Function.prototype is a root object return false } return true }
javascript
{ "resource": "" }
q20404
_print
train
function _print (template, values, options) { return template.replace(/\$([\w.]+)/g, function (original, key) { const keys = key.split('.') let value = values[keys.shift()] while (keys.length && value !== undefined) { const k = keys.shift() value = k ? value[k] : value + '.' } if (value !== undefined) { if (!isString(value)) { return format(value, options) } else { return value } } return original } ) }
javascript
{ "resource": "" }
q20405
format
train
function format (value) { const math = getMath() return math.format(value, { fn: function (value) { if (typeof value === 'number') { // round numbers return math.format(value, PRECISION) } else { return math.format(value) } } }) }
javascript
{ "resource": "" }
q20406
completer
train
function completer (text) { const math = getMath() let matches = [] let keyword const m = /[a-zA-Z_0-9]+$/.exec(text) if (m) { keyword = m[0] // scope variables for (const def in scope) { if (scope.hasOwnProperty(def)) { if (def.indexOf(keyword) === 0) { matches.push(def) } } } // commandline keywords ['exit', 'quit', 'clear'].forEach(function (cmd) { if (cmd.indexOf(keyword) === 0) { matches.push(cmd) } }) // math functions and constants const ignore = ['expr', 'type'] for (const func in math.expression.mathWithTransform) { if (math.expression.mathWithTransform.hasOwnProperty(func)) { if (func.indexOf(keyword) === 0 && ignore.indexOf(func) === -1) { matches.push(func) } } } // units const Unit = math.Unit for (let name in Unit.UNITS) { if (Unit.UNITS.hasOwnProperty(name)) { if (name.indexOf(keyword) === 0) { matches.push(name) } } } for (let name in Unit.PREFIXES) { if (Unit.PREFIXES.hasOwnProperty(name)) { const prefixes = Unit.PREFIXES[name] for (const prefix in prefixes) { if (prefixes.hasOwnProperty(prefix)) { if (prefix.indexOf(keyword) === 0) { matches.push(prefix) } else if (keyword.indexOf(prefix) === 0) { const unitKeyword = keyword.substring(prefix.length) for (const n in Unit.UNITS) { if (Unit.UNITS.hasOwnProperty(n)) { if (n.indexOf(unitKeyword) === 0 && Unit.isValuelessUnit(prefix + n)) { matches.push(prefix + n) } } } } } } } } // remove duplicates matches = matches.filter(function (elem, pos, arr) { return arr.indexOf(elem) === pos }) } return [matches, keyword] }
javascript
{ "resource": "" }
q20407
runStream
train
function runStream (input, output, mode, parenthesis) { const readline = require('readline') const rl = readline.createInterface({ input: input || process.stdin, output: output || process.stdout, completer: completer }) if (rl.output.isTTY) { rl.setPrompt('> ') rl.prompt() } // load math.js now, right *after* loading the prompt. const math = getMath() // TODO: automatic insertion of 'ans' before operators like +, -, *, / rl.on('line', function (line) { const expr = line.trim() switch (expr.toLowerCase()) { case 'quit': case 'exit': // exit application rl.close() break case 'clear': // clear memory scope = {} console.log('memory cleared') // get next input if (rl.output.isTTY) { rl.prompt() } break default: if (!expr) { break } switch (mode) { case 'evaluate': // evaluate expression try { let node = math.parse(expr) let res = node.evaluate(scope) if (math.isResultSet(res)) { // we can have 0 or 1 results in the ResultSet, as the CLI // does not allow multiple expressions separated by a return res = res.entries[0] node = node.blocks .filter(function (entry) { return entry.visible }) .map(function (entry) { return entry.node })[0] } if (node) { if (math.isAssignmentNode(node)) { const name = findSymbolName(node) if (name !== null) { scope.ans = scope[name] console.log(name + ' = ' + format(scope[name])) } else { scope.ans = res console.log(format(res)) } } else if (math.isHelp(res)) { console.log(res.toString()) } else { scope.ans = res console.log(format(res)) } } } catch (err) { console.log(err.toString()) } break case 'string': try { const string = math.parse(expr).toString({ parenthesis: parenthesis }) console.log(string) } catch (err) { console.log(err.toString()) } break case 'tex': try { const tex = math.parse(expr).toTex({ parenthesis: parenthesis }) console.log(tex) } catch (err) { console.log(err.toString()) } break } } // get next input if (rl.output.isTTY) { rl.prompt() } }) rl.on('close', function () { console.log() process.exit(0) }) }
javascript
{ "resource": "" }
q20408
findSymbolName
train
function findSymbolName (node) { const math = getMath() let n = node while (n) { if (math.isSymbolNode(n)) { return n.name } n = n.object } return null }
javascript
{ "resource": "" }
q20409
outputVersion
train
function outputVersion () { fs.readFile(path.join(__dirname, '/../package.json'), function (err, data) { if (err) { console.log(err.toString()) } else { const pkg = JSON.parse(data) const version = pkg && pkg.version ? pkg.version : 'unknown' console.log(version) } process.exit(0) }) }
javascript
{ "resource": "" }
q20410
outputHelp
train
function outputHelp () { console.log('math.js') console.log('https://mathjs.org') console.log() console.log('Math.js is an extensive math library for JavaScript and Node.js. It features ') console.log('real and complex numbers, units, matrices, a large set of mathematical') console.log('functions, and a flexible expression parser.') console.log() console.log('Usage:') console.log(' mathjs [scriptfile(s)|expression] {OPTIONS}') console.log() console.log('Options:') console.log(' --version, -v Show application version') console.log(' --help, -h Show this message') console.log(' --tex Generate LaTeX instead of evaluating') console.log(' --string Generate string instead of evaluating') console.log(' --parenthesis= Set the parenthesis option to') console.log(' either of "keep", "auto" and "all"') console.log() console.log('Example usage:') console.log(' mathjs Open a command prompt') console.log(' mathjs 1+2 Evaluate expression') console.log(' mathjs script.txt Run a script file') console.log(' mathjs script.txt script2.txt Run two script files') console.log(' mathjs script.txt > results.txt Run a script file, output to file') console.log(' cat script.txt | mathjs Run input stream') console.log(' cat script.txt | mathjs > results.txt Run input stream, output to file') console.log() process.exit(0) }
javascript
{ "resource": "" }
q20411
compareArrays
train
function compareArrays (x, y) { // compare each value for (let i = 0, ii = Math.min(x.length, y.length); i < ii; i++) { const v = compareNatural(x[i], y[i]) if (v !== 0) { return v } } // compare the size of the arrays if (x.length > y.length) { return 1 } if (x.length < y.length) { return -1 } // both Arrays have equal size and content return 0 }
javascript
{ "resource": "" }
q20412
compareObjects
train
function compareObjects (x, y) { const keysX = Object.keys(x) const keysY = Object.keys(y) // compare keys keysX.sort(naturalSort) keysY.sort(naturalSort) const c = compareArrays(keysX, keysY) if (c !== 0) { return c } // compare values for (let i = 0; i < keysX.length; i++) { const v = compareNatural(x[keysX[i]], y[keysY[i]]) if (v !== 0) { return v } } return 0 }
javascript
{ "resource": "" }
q20413
validateDoc
train
function validateDoc (doc) { let issues = [] function ignore (field) { return IGNORE_WARNINGS[field].indexOf(doc.name) !== -1 } if (!doc.name) { issues.push('name missing in document') } if (!doc.description) { issues.push('function "' + doc.name + '": description missing') } if (!doc.syntax || doc.syntax.length === 0) { issues.push('function "' + doc.name + '": syntax missing') } if (!doc.examples || doc.examples.length === 0) { issues.push('function "' + doc.name + '": examples missing') } if (doc.parameters && doc.parameters.length) { doc.parameters.forEach(function (param, index) { if (!param.name || !param.name.trim()) { issues.push('function "' + doc.name + '": name missing of parameter ' + index + '') } if (!param.description || !param.description.trim()) { issues.push('function "' + doc.name + '": description missing for parameter ' + (param.name || index)) } if (!param.types || !param.types.length) { issues.push('function "' + doc.name + '": types missing for parameter ' + (param.name || index)) } }) } else { if (!ignore('parameters')) { issues.push('function "' + doc.name + '": parameters missing') } } if (doc.returns) { if (!doc.returns.description || !doc.returns.description.trim()) { issues.push('function "' + doc.name + '": description missing of returns') } if (!doc.returns.types || !doc.returns.types.length) { issues.push('function "' + doc.name + '": types missing of returns') } } else { if (!ignore('returns')) { issues.push('function "' + doc.name + '": returns missing') } } if (!doc.seeAlso || doc.seeAlso.length === 0) { if (!ignore('seeAlso')) { issues.push('function "' + doc.name + '": seeAlso missing') } } return issues }
javascript
{ "resource": "" }
q20414
functionEntry
train
function functionEntry (name) { const fn = functions[name] let syntax = SYNTAX[name] || (fn.doc && fn.doc.syntax && fn.doc.syntax[0]) || name syntax = syntax // .replace(/^math\./, '') .replace(/\s+\/\/.*$/, '') .replace(/;$/, '') if (syntax.length < 40) { syntax = syntax.replace(/ /g, '&nbsp;') } let description = '' if (fn.doc.description) { description = fn.doc.description.replace(/\n/g, ' ').split('.')[0] + '.' } return '[' + syntax + '](functions/' + name + '.md) | ' + description }
javascript
{ "resource": "" }
q20415
integrate
train
function integrate (f, start, end, step) { let total = 0 step = step || 0.01 for (let x = start; x < end; x += step) { total += f(x + step / 2) * step } return total }
javascript
{ "resource": "" }
q20416
mapTransform
train
function mapTransform (args, math, scope) { let x, callback if (args[0]) { x = args[0].compile().evaluate(scope) } if (args[1]) { if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) { // a function pointer, like filter([3, -2, 5], myTestFunction) callback = args[1].compile().evaluate(scope) } else { // an expression like filter([3, -2, 5], x > 0) callback = compileInlineExpression(args[1], math, scope) } } return map(x, callback) }
javascript
{ "resource": "" }
q20417
exclude
train
function exclude (object, excludedProperties) { const strippedObject = Object.assign({}, object) excludedProperties.forEach(excludedProperty => { delete strippedObject[excludedProperty] }) return strippedObject }
javascript
{ "resource": "" }
q20418
_getSubstring
train
function _getSubstring (str, index) { if (!isIndex(index)) { // TODO: better error message throw new TypeError('Index expected') } if (index.size().length !== 1) { throw new DimensionError(index.size().length, 1) } // validate whether the range is out of range const strLen = str.length validateIndex(index.min()[0], strLen) validateIndex(index.max()[0], strLen) const range = index.dimension(0) let substr = '' range.forEach(function (v) { substr += str.charAt(v) }) return substr }
javascript
{ "resource": "" }
q20419
_setSubstring
train
function _setSubstring (str, index, replacement, defaultValue) { if (!index || index.isIndex !== true) { // TODO: better error message throw new TypeError('Index expected') } if (index.size().length !== 1) { throw new DimensionError(index.size().length, 1) } if (defaultValue !== undefined) { if (typeof defaultValue !== 'string' || defaultValue.length !== 1) { throw new TypeError('Single character expected as defaultValue') } } else { defaultValue = ' ' } const range = index.dimension(0) const len = range.size()[0] if (len !== replacement.length) { throw new DimensionError(range.size()[0], replacement.length) } // validate whether the range is out of range const strLen = str.length validateIndex(index.min()[0]) validateIndex(index.max()[0]) // copy the string into an array with characters const chars = [] for (let i = 0; i < strLen; i++) { chars[i] = str.charAt(i) } range.forEach(function (v, i) { chars[v] = replacement.charAt(i[0]) }) // initialize undefined characters with a space if (chars.length > strLen) { for (let i = strLen - 1, len = chars.length; i < len; i++) { if (!chars[i]) { chars[i] = defaultValue } } } return chars.join('') }
javascript
{ "resource": "" }
q20420
_getObjectProperty
train
function _getObjectProperty (object, index) { if (index.size().length !== 1) { throw new DimensionError(index.size(), 1) } const key = index.dimension(0) if (typeof key !== 'string') { throw new TypeError('String expected as index to retrieve an object property') } return getSafeProperty(object, key) }
javascript
{ "resource": "" }
q20421
_setObjectProperty
train
function _setObjectProperty (object, index, replacement) { if (index.size().length !== 1) { throw new DimensionError(index.size(), 1) } const key = index.dimension(0) if (typeof key !== 'string') { throw new TypeError('String expected as index to retrieve an object property') } // clone the object, and apply the property to the clone const updated = clone(object) setSafeProperty(updated, key, replacement) return updated }
javascript
{ "resource": "" }
q20422
_switch
train
function _switch (mat) { const I = mat.length const J = mat[0].length let i, j const ret = [] for (j = 0; j < J; j++) { const tmp = [] for (i = 0; i < I; i++) { tmp.push(mat[i][j]) } ret.push(tmp) } return ret }
javascript
{ "resource": "" }
q20423
_concat
train
function _concat (a, b, concatDim, dim) { if (dim < concatDim) { // recurse into next dimension if (a.length !== b.length) { throw new DimensionError(a.length, b.length) } const c = [] for (let i = 0; i < a.length; i++) { c[i] = _concat(a[i], b[i], concatDim, dim + 1) } return c } else { // concatenate this dimension return a.concat(b) } }
javascript
{ "resource": "" }
q20424
filterTransform
train
function filterTransform (args, math, scope) { let x, callback if (args[0]) { x = args[0].compile().evaluate(scope) } if (args[1]) { if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) { // a function pointer, like filter([3, -2, 5], myTestFunction) callback = args[1].compile().evaluate(scope) } else { // an expression like filter([3, -2, 5], x > 0) callback = compileInlineExpression(args[1], math, scope) } } return filter(x, callback) }
javascript
{ "resource": "" }
q20425
_filter
train
function _filter (x, callback) { // figure out what number of arguments the callback function expects const args = maxArgumentCount(callback) return filter(x, function (value, index, array) { // invoke the callback function with the right number of arguments if (args === 1) { return callback(value) } else if (args === 2) { return callback(value, [index + 1]) } else { // 3 or -1 return callback(value, [index + 1], array) } }) }
javascript
{ "resource": "" }
q20426
checkEqualDimensions
train
function checkEqualDimensions (x, y) { const xsize = x.size() const ysize = y.size() if (xsize.length !== ysize.length) { throw new DimensionError(xsize.length, ysize.length) } }
javascript
{ "resource": "" }
q20427
camelize
train
function camelize(str) { return str .replace(STRING_CAMELIZE_REGEXP, (_match, _separator, chr) => { return chr ? chr.toUpperCase() : ''; }) .replace(/^([A-Z])/, (match) => match.toLowerCase()); }
javascript
{ "resource": "" }
q20428
interpolate
train
function interpolate(str, args) { return str.replace(/\$(\d{1,2})/g, function (match, index) { return args[index] || ''; }); }
javascript
{ "resource": "" }
q20429
replaceWord
train
function replaceWord(replaceMap, keepMap, rules) { return function (word) { // Get the correct token and case restoration functions. var token = word.toLowerCase(); // Check against the keep object map. if (keepMap.hasOwnProperty(token)) { return restoreCase(word, token); } // Check against the replacement map for a direct word replacement. if (replaceMap.hasOwnProperty(token)) { return restoreCase(word, replaceMap[token]); } // Run all the rules against the word. return sanitizeWord(token, word, rules); }; }
javascript
{ "resource": "" }
q20430
pluralize
train
function pluralize(word, count, inclusive) { var pluralized = count === 1 ? pluralize.singular(word) : pluralize.plural(word); return (inclusive ? count + ' ' : '') + pluralized; }
javascript
{ "resource": "" }
q20431
findNodes
train
function findNodes(node, kind, max = Infinity) { if (!node || max == 0) { return []; } const arr = []; if (node.kind === kind) { arr.push(node); max--; } if (max > 0) { for (const child of node.getChildren()) { findNodes(child, kind, max).forEach(node => { if (max > 0) { arr.push(node); } max--; }); if (max <= 0) { break; } } } return arr; }
javascript
{ "resource": "" }
q20432
getSourceNodes
train
function getSourceNodes(sourceFile) { const nodes = [sourceFile]; const result = []; while (nodes.length > 0) { const node = nodes.shift(); if (node) { result.push(node); if (node.getChildCount(sourceFile) >= 0) { nodes.unshift(...node.getChildren()); } } } return result; }
javascript
{ "resource": "" }
q20433
addImportToModule
train
function addImportToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath); }
javascript
{ "resource": "" }
q20434
addProviderToModule
train
function addProviderToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath); }
javascript
{ "resource": "" }
q20435
addEntryComponentToModule
train
function addEntryComponentToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'entryComponents', classifiedName, importPath); }
javascript
{ "resource": "" }
q20436
isImported
train
function isImported(source, classifiedName, importPath) { const allNodes = getSourceNodes(source); const matchingNodes = allNodes .filter(node => node.kind === ts.SyntaxKind.ImportDeclaration) .filter((imp) => imp.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral) .filter((imp) => { return imp.moduleSpecifier.text === importPath; }) .filter((imp) => { if (!imp.importClause) { return false; } const nodes = findNodes(imp.importClause, ts.SyntaxKind.ImportSpecifier).filter(n => n.getText() === classifiedName); return nodes.length > 0; }); return matchingNodes.length > 0; }
javascript
{ "resource": "" }
q20437
FfmpegCommand
train
function FfmpegCommand(input, options) { // Make 'new' optional if (!(this instanceof FfmpegCommand)) { return new FfmpegCommand(input, options); } EventEmitter.call(this); if (typeof input === 'object' && !('readable' in input)) { // Options object passed directly options = input; } else { // Input passed first options = options || {}; options.source = input; } // Add input if present this._inputs = []; if (options.source) { this.input(options.source); } // Add target-less output for backwards compatibility this._outputs = []; this.output(); // Create argument lists var self = this; ['_global', '_complexFilters'].forEach(function(prop) { self[prop] = utils.args(); }); // Set default option values options.stdoutLines = 'stdoutLines' in options ? options.stdoutLines : 100; options.presets = options.presets || options.preset || path.join(__dirname, 'presets'); options.niceness = options.niceness || options.priority || 0; // Save options this.options = options; // Setup logger this.logger = options.logger || { debug: function() {}, info: function() {}, warn: function() {}, error: function() {} }; }
javascript
{ "resource": "" }
q20438
normalizeTimemarks
train
function normalizeTimemarks(next) { config.timemarks = config.timemarks.map(function(mark) { return utils.timemarkToSeconds(mark); }).sort(function(a, b) { return a - b; }); next(); }
javascript
{ "resource": "" }
q20439
fixPattern
train
function fixPattern(next) { var pattern = config.filename || 'tn.png'; if (pattern.indexOf('.') === -1) { pattern += '.png'; } if (config.timemarks.length > 1 && !pattern.match(/%(s|0*i)/)) { var ext = path.extname(pattern); pattern = path.join(path.dirname(pattern), path.basename(pattern, ext) + '_%i' + ext); } next(null, pattern); }
javascript
{ "resource": "" }
q20440
train
function(ffprobe, cb) { if (ffprobe.length) { return cb(null, ffprobe); } self._getFfmpegPath(function(err, ffmpeg) { if (err) { cb(err); } else if (ffmpeg.length) { var name = utils.isWindows ? 'ffprobe.exe' : 'ffprobe'; var ffprobe = path.join(path.dirname(ffmpeg), name); fs.exists(ffprobe, function(exists) { cb(null, exists ? ffprobe : ''); }); } else { cb(null, ''); } }); }
javascript
{ "resource": "" }
q20441
train
function(flvtool, cb) { if (flvtool.length) { return cb(null, flvtool); } utils.which('flvmeta', function(err, flvmeta) { cb(err, flvmeta); }); }
javascript
{ "resource": "" }
q20442
train
function(flvtool, cb) { if (flvtool.length) { return cb(null, flvtool); } utils.which('flvtool2', function(err, flvtool2) { cb(err, flvtool2); }); }
javascript
{ "resource": "" }
q20443
train
function(formats, cb) { var unavailable; // Output format(s) unavailable = self._outputs .reduce(function(fmts, output) { var format = output.options.find('-f', 1); if (format) { if (!(format[0] in formats) || !(formats[format[0]].canMux)) { fmts.push(format); } } return fmts; }, []); if (unavailable.length === 1) { return cb(new Error('Output format ' + unavailable[0] + ' is not available')); } else if (unavailable.length > 1) { return cb(new Error('Output formats ' + unavailable.join(', ') + ' are not available')); } // Input format(s) unavailable = self._inputs .reduce(function(fmts, input) { var format = input.options.find('-f', 1); if (format) { if (!(format[0] in formats) || !(formats[format[0]].canDemux)) { fmts.push(format[0]); } } return fmts; }, []); if (unavailable.length === 1) { return cb(new Error('Input format ' + unavailable[0] + ' is not available')); } else if (unavailable.length > 1) { return cb(new Error('Input formats ' + unavailable.join(', ') + ' are not available')); } cb(); }
javascript
{ "resource": "" }
q20444
train
function(encoders, cb) { var unavailable; // Audio codec(s) unavailable = self._outputs.reduce(function(cdcs, output) { var acodec = output.audio.find('-acodec', 1); if (acodec && acodec[0] !== 'copy') { if (!(acodec[0] in encoders) || encoders[acodec[0]].type !== 'audio') { cdcs.push(acodec[0]); } } return cdcs; }, []); if (unavailable.length === 1) { return cb(new Error('Audio codec ' + unavailable[0] + ' is not available')); } else if (unavailable.length > 1) { return cb(new Error('Audio codecs ' + unavailable.join(', ') + ' are not available')); } // Video codec(s) unavailable = self._outputs.reduce(function(cdcs, output) { var vcodec = output.video.find('-vcodec', 1); if (vcodec && vcodec[0] !== 'copy') { if (!(vcodec[0] in encoders) || encoders[vcodec[0]].type !== 'video') { cdcs.push(vcodec[0]); } } return cdcs; }, []); if (unavailable.length === 1) { return cb(new Error('Video codec ' + unavailable[0] + ' is not available')); } else if (unavailable.length > 1) { return cb(new Error('Video codecs ' + unavailable.join(', ') + ' are not available')); } cb(); }
javascript
{ "resource": "" }
q20445
parseProgressLine
train
function parseProgressLine(line) { var progress = {}; // Remove all spaces after = and trim line = line.replace(/=\s+/g, '=').trim(); var progressParts = line.split(' '); // Split every progress part by "=" to get key and value for(var i = 0; i < progressParts.length; i++) { var progressSplit = progressParts[i].split('=', 2); var key = progressSplit[0]; var value = progressSplit[1]; // This is not a progress line if(typeof value === 'undefined') return null; progress[key] = value; } return progress; }
javascript
{ "resource": "" }
q20446
train
function() { var list = []; // Append argument(s) to the list var argfunc = function() { if (arguments.length === 1 && Array.isArray(arguments[0])) { list = list.concat(arguments[0]); } else { list = list.concat([].slice.call(arguments)); } }; // Clear argument list argfunc.clear = function() { list = []; }; // Return argument list argfunc.get = function() { return list; }; // Find argument 'arg' in list, and if found, return an array of the 'count' items that follow it argfunc.find = function(arg, count) { var index = list.indexOf(arg); if (index !== -1) { return list.slice(index + 1, index + 1 + (count || 0)); } }; // Find argument 'arg' in list, and if found, remove it as well as the 'count' items that follow it argfunc.remove = function(arg, count) { var index = list.indexOf(arg); if (index !== -1) { list.splice(index, (count || 0) + 1); } }; // Clone argument list argfunc.clone = function() { var cloned = utils.args(); cloned(list); return cloned; }; return argfunc; }
javascript
{ "resource": "" }
q20447
train
function(filters) { return filters.map(function(filterSpec) { if (typeof filterSpec === 'string') { return filterSpec; } var filterString = ''; // Filter string format is: // [input1][input2]...filter[output1][output2]... // The 'filter' part can optionaly have arguments: // filter=arg1:arg2:arg3 // filter=arg1=v1:arg2=v2:arg3=v3 // Add inputs if (Array.isArray(filterSpec.inputs)) { filterString += filterSpec.inputs.map(function(streamSpec) { return streamSpec.replace(streamRegexp, '[$1]'); }).join(''); } else if (typeof filterSpec.inputs === 'string') { filterString += filterSpec.inputs.replace(streamRegexp, '[$1]'); } // Add filter filterString += filterSpec.filter; // Add options if (filterSpec.options) { if (typeof filterSpec.options === 'string' || typeof filterSpec.options === 'number') { // Option string filterString += '=' + filterSpec.options; } else if (Array.isArray(filterSpec.options)) { // Option array (unnamed options) filterString += '=' + filterSpec.options.map(function(option) { if (typeof option === 'string' && option.match(filterEscapeRegexp)) { return '\'' + option + '\''; } else { return option; } }).join(':'); } else if (Object.keys(filterSpec.options).length) { // Option object (named options) filterString += '=' + Object.keys(filterSpec.options).map(function(option) { var value = filterSpec.options[option]; if (typeof value === 'string' && value.match(filterEscapeRegexp)) { value = '\'' + value + '\''; } return option + '=' + value; }).join(':'); } } // Add outputs if (Array.isArray(filterSpec.outputs)) { filterString += filterSpec.outputs.map(function(streamSpec) { return streamSpec.replace(streamRegexp, '[$1]'); }).join(''); } else if (typeof filterSpec.outputs === 'string') { filterString += filterSpec.outputs.replace(streamRegexp, '[$1]'); } return filterString; }); }
javascript
{ "resource": "" }
q20448
train
function(name, callback) { if (name in whichCache) { return callback(null, whichCache[name]); } which(name, function(err, result){ if (err) { // Treat errors as not found return callback(null, whichCache[name] = ''); } callback(null, whichCache[name] = result); }); }
javascript
{ "resource": "" }
q20449
train
function(command, stderrLine, codecsObject) { var inputPattern = /Input #[0-9]+, ([^ ]+),/; var durPattern = /Duration\: ([^,]+)/; var audioPattern = /Audio\: (.*)/; var videoPattern = /Video\: (.*)/; if (!('inputStack' in codecsObject)) { codecsObject.inputStack = []; codecsObject.inputIndex = -1; codecsObject.inInput = false; } var inputStack = codecsObject.inputStack; var inputIndex = codecsObject.inputIndex; var inInput = codecsObject.inInput; var format, dur, audio, video; if (format = stderrLine.match(inputPattern)) { inInput = codecsObject.inInput = true; inputIndex = codecsObject.inputIndex = codecsObject.inputIndex + 1; inputStack[inputIndex] = { format: format[1], audio: '', video: '', duration: '' }; } else if (inInput && (dur = stderrLine.match(durPattern))) { inputStack[inputIndex].duration = dur[1]; } else if (inInput && (audio = stderrLine.match(audioPattern))) { audio = audio[1].split(', '); inputStack[inputIndex].audio = audio[0]; inputStack[inputIndex].audio_details = audio; } else if (inInput && (video = stderrLine.match(videoPattern))) { video = video[1].split(', '); inputStack[inputIndex].video = video[0]; inputStack[inputIndex].video_details = video; } else if (/Output #\d+/.test(stderrLine)) { inInput = codecsObject.inInput = false; } else if (/Stream mapping:|Press (\[q\]|ctrl-c) to stop/.test(stderrLine)) { command.emit.apply(command, ['codecData'].concat(inputStack)); return true; } return false; }
javascript
{ "resource": "" }
q20450
train
function(command, stderrLine) { var progress = parseProgressLine(stderrLine); if (progress) { // build progress report object var ret = { frames: parseInt(progress.frame, 10), currentFps: parseInt(progress.fps, 10), currentKbps: progress.bitrate ? parseFloat(progress.bitrate.replace('kbits/s', '')) : 0, targetSize: parseInt(progress.size || progress.Lsize, 10), timemark: progress.time }; // calculate percent progress using duration if (command._ffprobeData && command._ffprobeData.format && command._ffprobeData.format.duration) { var duration = Number(command._ffprobeData.format.duration); if (!isNaN(duration)) ret.percent = (utils.timemarkToSeconds(ret.timemark) / duration) * 100; } command.emit('progress', ret); } }
javascript
{ "resource": "" }
q20451
createSizeFilters
train
function createSizeFilters(output, key, value) { // Store parameters var data = output.sizeData = output.sizeData || {}; data[key] = value; if (!('size' in data)) { // No size requested, keep original size return []; } // Try to match the different size string formats var fixedSize = data.size.match(/([0-9]+)x([0-9]+)/); var fixedWidth = data.size.match(/([0-9]+)x\?/); var fixedHeight = data.size.match(/\?x([0-9]+)/); var percentRatio = data.size.match(/\b([0-9]{1,3})%/); var width, height, aspect; if (percentRatio) { var ratio = Number(percentRatio[1]) / 100; return [{ filter: 'scale', options: { w: 'trunc(iw*' + ratio + '/2)*2', h: 'trunc(ih*' + ratio + '/2)*2' } }]; } else if (fixedSize) { // Round target size to multiples of 2 width = Math.round(Number(fixedSize[1]) / 2) * 2; height = Math.round(Number(fixedSize[2]) / 2) * 2; aspect = width / height; if (data.pad) { return getScalePadFilters(width, height, aspect, data.pad); } else { // No autopad requested, rescale to target size return [{ filter: 'scale', options: { w: width, h: height }}]; } } else if (fixedWidth || fixedHeight) { if ('aspect' in data) { // Specified aspect ratio width = fixedWidth ? fixedWidth[1] : Math.round(Number(fixedHeight[1]) * data.aspect); height = fixedHeight ? fixedHeight[1] : Math.round(Number(fixedWidth[1]) / data.aspect); // Round to multiples of 2 width = Math.round(width / 2) * 2; height = Math.round(height / 2) * 2; if (data.pad) { return getScalePadFilters(width, height, data.aspect, data.pad); } else { // No autopad requested, rescale to target size return [{ filter: 'scale', options: { w: width, h: height }}]; } } else { // Keep input aspect ratio if (fixedWidth) { return [{ filter: 'scale', options: { w: Math.round(Number(fixedWidth[1]) / 2) * 2, h: 'trunc(ow/a/2)*2' } }]; } else { return [{ filter: 'scale', options: { w: 'trunc(oh*a/2)*2', h: Math.round(Number(fixedHeight[1]) / 2) * 2 } }]; } } } else { throw new Error('Invalid size specified: ' + data.size); } }
javascript
{ "resource": "" }
q20452
train
function(cb) { if (!readMetadata) { return cb(); } self.ffprobe(0, function(err, data) { if (!err) { self._ffprobeData = data; } cb(); }); }
javascript
{ "resource": "" }
q20453
train
function(cb) { var args; try { args = self._getArguments(); } catch(e) { return cb(e); } cb(null, args); }
javascript
{ "resource": "" }
q20454
train
function(args, cb) { self.availableEncoders(function(err, encoders) { for (var i = 0; i < args.length; i++) { if (args[i] === '-acodec' || args[i] === '-vcodec') { i++; if ((args[i] in encoders) && encoders[args[i]].experimental) { args.splice(i + 1, 0, '-strict', 'experimental'); i += 2; } } } cb(null, args); }); }
javascript
{ "resource": "" }
q20455
serverMonitoringCleanup
train
function serverMonitoringCleanup(db, conn){ var exclude = { eventDate: 0, pid: 0, version: 0, uptime: 0, network: 0, connectionName: 0, connections: 0, memory: 0, dataRetrieved: 0, docCounts: 0 }; var retainedRecords = (24 * 60) * 60 / 30; // 24 hours worth of 30 sec blocks (data refresh interval) db.find({connectionName: conn}).skip(retainedRecords).sort({eventDate: -1}).projection(exclude).exec(function (err, serverEvents){ var idArray = []; _.each(serverEvents, function(value, key){ idArray.push(value._id); }); db.remove({'_id': {'$in': idArray}}, {multi: true}, function (err, newDoc){}); }); }
javascript
{ "resource": "" }
q20456
train
function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }
javascript
{ "resource": "" }
q20457
train
function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { if (!model.set(model.parse(resp, options), options)) return false; if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }
javascript
{ "resource": "" }
q20458
train
function(model, options) { model = this._prepareModel(model, options); this.add(model, _.extend({at: 0}, options)); return model; }
javascript
{ "resource": "" }
q20459
train
function(model, value, context) { value || (value = this.comparator); var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _.sortedIndex(this.models, model, iterator, context); }
javascript
{ "resource": "" }
q20460
train
function() { if (!this.routes) return; this.routes = _.result(this, 'routes'); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); } }
javascript
{ "resource": "" }
q20461
train
function(location, fragment, replace) { if (replace) { var href = location.href.replace(/(javascript:|#).*$/, ''); location.replace(href + '#' + fragment); } else { // Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment; } }
javascript
{ "resource": "" }
q20462
train
function (param, value) { var len = arguments.length, lastSelectedDate = this.lastSelectedDate; if (len == 2) { this.opts[param] = value; } else if (len == 1 && typeof param == 'object') { this.opts = $.extend(true, this.opts, param) } this._createShortCuts(); this._syncWithMinMaxDates(); this._defineLocale(this.opts.language); this.nav._addButtonsIfNeed(); if (!this.opts.onlyTimepicker) this.nav._render(); this.views[this.currentView]._render(); if (this.elIsInput && !this.opts.inline) { this._setPositionClasses(this.opts.position); if (this.visible) { this.setPosition(this.opts.position) } } if (this.opts.classes) { this.$datepicker.addClass(this.opts.classes) } if (this.opts.onlyTimepicker) { this.$datepicker.addClass('-only-timepicker-'); } if (this.opts.timepicker) { if (lastSelectedDate) this.timepicker._handleDate(lastSelectedDate); this.timepicker._updateRanges(); this.timepicker._updateCurrentTime(); // Change hours and minutes if it's values have been changed through min/max hours/minutes if (lastSelectedDate) { lastSelectedDate.setHours(this.timepicker.hours); lastSelectedDate.setMinutes(this.timepicker.minutes); } } this._setInputValue(); return this; }
javascript
{ "resource": "" }
q20463
train
function (date, type) { var time = date.getTime(), d = datepicker.getParsedDate(date), min = datepicker.getParsedDate(this.minDate), max = datepicker.getParsedDate(this.maxDate), dMinTime = new Date(d.year, d.month, min.date).getTime(), dMaxTime = new Date(d.year, d.month, max.date).getTime(), types = { day: time >= this.minTime && time <= this.maxTime, month: dMinTime >= this.minTime && dMaxTime <= this.maxTime, year: d.year >= min.year && d.year <= max.year }; return type ? types[type] : types.day }
javascript
{ "resource": "" }
q20464
train
function (date) { var totalMonthDays = dp.getDaysCount(date), firstMonthDay = new Date(date.getFullYear(), date.getMonth(), 1).getDay(), lastMonthDay = new Date(date.getFullYear(), date.getMonth(), totalMonthDays).getDay(), daysFromPevMonth = firstMonthDay - this.d.loc.firstDay, daysFromNextMonth = 6 - lastMonthDay + this.d.loc.firstDay; daysFromPevMonth = daysFromPevMonth < 0 ? daysFromPevMonth + 7 : daysFromPevMonth; daysFromNextMonth = daysFromNextMonth > 6 ? daysFromNextMonth - 7 : daysFromNextMonth; var startDayIndex = -daysFromPevMonth + 1, m, y, html = ''; for (var i = startDayIndex, max = totalMonthDays + daysFromNextMonth; i <= max; i++) { y = date.getFullYear(); m = date.getMonth(); html += this._getDayHtml(new Date(y, m, i)) } return html; }
javascript
{ "resource": "" }
q20465
train
function (date) { var html = '', d = dp.getParsedDate(date), i = 0; while(i < 12) { html += this._getMonthHtml(new Date(d.year, i)); i++ } return html; }
javascript
{ "resource": "" }
q20466
train
function (date) { this._setDefaultMinMaxTime(); if (date) { if (dp.isSame(date, this.d.opts.minDate)) { this._setMinTimeFromDate(this.d.opts.minDate); } else if (dp.isSame(date, this.d.opts.maxDate)) { this._setMaxTimeFromDate(this.d.opts.maxDate); } } this._validateHoursMinutes(date); }
javascript
{ "resource": "" }
q20467
train
function (date, ampm) { var d = date, hours = date; if (date instanceof Date) { d = dp.getParsedDate(date); hours = d.hours; } var _ampm = ampm || this.d.ampm, dayPeriod = 'am'; if (_ampm) { switch(true) { case hours == 0: hours = 12; break; case hours == 12: dayPeriod = 'pm'; break; case hours > 11: hours = hours - 12; dayPeriod = 'pm'; break; default: break; } } return { hours: hours, dayPeriod: dayPeriod } }
javascript
{ "resource": "" }
q20468
toggleEdit
train
function toggleEdit() { document.body.classList.toggle('form-rendered', editing) if (!editing) { $('.build-wrap').formBuilder('setData', $('.render-wrap').formRender('userData')) } else { const formRenderData = $('.build-wrap').formBuilder('getData', dataType) $('.render-wrap').formRender({ formData: formRenderData, templates: templates, dataType, }) window.sessionStorage.setItem('formData', formRenderData) } return (editing = !editing) }
javascript
{ "resource": "" }
q20469
train
function($field, isNew = false) { let field = {} if ($field instanceof jQuery) { // get the default type etc & label for this field field.type = $field[0].dataset.type if (field.type) { // check for a custom type const custom = controls.custom.lookup(field.type) if (custom) { field = Object.assign({}, custom) } else { const controlClass = controls.getClass(field.type) field.label = controlClass.label(field.type) } // @todo: any other attrs ever set in aFields? value or selected? } else { // is dataType XML const attrs = $field[0].attributes if (!isNew) { field.values = $field.children().map((index, elem) => { return { label: $(elem).text(), value: $(elem).attr('value'), selected: Boolean($(elem).attr('selected')), } }) } for (let i = attrs.length - 1; i >= 0; i--) { field[attrs[i].name] = attrs[i].value } } } else { field = Object.assign({}, $field) } if (!field.name) { field.name = nameAttr(field) } if (isNew && ['text', 'number', 'file', 'date', 'select', 'textarea', 'autocomplete'].includes(field.type)) { field.className = field.className || 'form-control' } const match = /(?:^|\s)btn-(.*?)(?:\s|$)/g.exec(field.className) if (match) { field.style = match[1] } if (isNew) { field = Object.assign({}, field, opts.onAddField(data.lastID, field)) setTimeout(() => document.dispatchEvent(events.fieldAdded), 10) } appendNewField(field, isNew) d.stage.classList.remove('empty') }
javascript
{ "resource": "" }
q20470
train
function(formData) { formData = h.getData(formData) if (formData && formData.length) { formData.forEach(fieldData => prepFieldVars(trimObj(fieldData))) d.stage.classList.remove('empty') } else if (opts.defaultFields && opts.defaultFields.length) { // Load default fields if none are set opts.defaultFields.forEach(field => prepFieldVars(field)) d.stage.classList.remove('empty') } else if (!opts.prepend && !opts.append) { d.stage.classList.add('empty') d.stage.dataset.content = mi18n.get('getStarted') } if (nonEditableFields()) { d.stage.classList.remove('empty') } h.save() }
javascript
{ "resource": "" }
q20471
userAttrType
train
function userAttrType(attr, attrData) { return ( [ ['array', ({ options }) => !!options], [typeof attrData.value, () => true], // string, number, ].find(typeCondition => typeCondition[1](attrData))[0] || 'string' ) }
javascript
{ "resource": "" }
q20472
inputUserAttrs
train
function inputUserAttrs(name, inputAttrs) { const { class: classname, className, ...attrs } = inputAttrs let textAttrs = { id: name + '-' + data.lastID, title: attrs.description || attrs.label || name.toUpperCase(), name: name, type: attrs.type || 'text', className: [`fld-${name}`, (classname || className || '').trim()], } const label = `<label for="${textAttrs.id}">${i18n[name] || ''}</label>` const optionInputs = ['checkbox', 'checkbox-group', 'radio-group'] if (!optionInputs.includes(textAttrs.type)) { textAttrs.className.push('form-control') } textAttrs = Object.assign({}, attrs, textAttrs) const textInput = `<input ${attrString(textAttrs)}>` const inputWrap = `<div class="input-wrap">${textInput}</div>` return `<div class="form-group ${name}-wrap">${label}${inputWrap}</div>` }
javascript
{ "resource": "" }
q20473
selectUserAttrs
train
function selectUserAttrs(name, fieldData) { const { multiple, options, label: labelText, value, class: classname, className, ...restData } = fieldData const optis = Object.keys(options).map(val => { const attrs = { value: val } const optionTextVal = options[val] const optionText = Array.isArray(optionTextVal) ? mi18n.get(...optionTextVal) || optionTextVal[0] : optionTextVal if (Array.isArray(value) ? value.includes(val) : val === value) { attrs.selected = null } return m('option', optionText, attrs) }) const selectAttrs = { id: `${name}-${data.lastID}`, title: restData.description || labelText || name.toUpperCase(), name, className: `fld-${name} form-control ${classname || className || ''}`.trim(), } if (multiple) { selectAttrs.multiple = true } const label = `<label for="${selectAttrs.id}">${i18n[name]}</label>` Object.keys(restData).forEach(function(attr) { selectAttrs[attr] = restData[attr] }) const select = m('select', optis, selectAttrs).outerHTML const inputWrap = `<div class="input-wrap">${select}</div>` return `<div class="form-group ${name}-wrap">${label}${inputWrap}</div>` }
javascript
{ "resource": "" }
q20474
train
function(name, optionData, multipleSelect) { const optionInputType = { selected: multipleSelect ? 'checkbox' : 'radio', } const optionDataOrder = ['value', 'label', 'selected'] const optionInputs = [] const optionTemplate = { selected: false, label: '', value: '' } optionData = Object.assign(optionTemplate, optionData) for (let i = optionDataOrder.length - 1; i >= 0; i--) { const prop = optionDataOrder[i] if (optionData.hasOwnProperty(prop)) { const attrs = { type: optionInputType[prop] || 'text', className: 'option-' + prop, value: optionData[prop], name: name + '-option', } attrs.placeholder = mi18n.get(`placeholder.${prop}`) || '' if (prop === 'selected' && optionData.selected === true) { attrs.checked = optionData.selected } optionInputs.push(m('input', null, attrs)) } } const removeAttrs = { className: 'remove btn icon-cancel', title: mi18n.get('removeMessage'), } optionInputs.push(m('a', null, removeAttrs)) return m('li', optionInputs).outerHTML }
javascript
{ "resource": "" }
q20475
isActuallyCombinator
train
function isActuallyCombinator(combinatorNode) { // `.foo /*comment*/, .bar` // ^^ // If include comments, this spaces is a combinator, but it is not combinators. if (!/^\s+$/.test(combinatorNode.value)) { return true; } let next = combinatorNode.next(); while (skipTest(next)) { next = next.next(); } if (isNonTarget(next)) { return false; } let prev = combinatorNode.prev(); while (skipTest(prev)) { prev = prev.prev(); } if (isNonTarget(prev)) { return false; } return true; function skipTest(node) { if (!node) { return false; } if (node.type === "comment") { return true; } if (node.type === "combinator" && /^\s+$/.test(node.value)) { return true; } return false; } function isNonTarget(node) { if (!node) { return true; } if (node.type === "combinator" && !/^\s+$/.test(node.value)) { return true; } return false; } }
javascript
{ "resource": "" }
q20476
hasInterpolatingAmpersand
train
function hasInterpolatingAmpersand(selector) { for (let i = 0, l = selector.length; i < l; i++) { if (selector[i] !== "&") { continue; } if (!_.isUndefined(selector[i - 1]) && !isCombinator(selector[i - 1])) { return true; } if (!_.isUndefined(selector[i + 1]) && !isCombinator(selector[i + 1])) { return true; } } return false; }
javascript
{ "resource": "" }
q20477
verifyMathExpressions
train
function verifyMathExpressions(expression, node) { if (expression.type === "MathExpression") { const { operator, left, right } = expression; if (operator === "+" || operator === "-") { if ( expression.source.operator.end.index === right.source.start.index ) { complain( messages.expectedSpaceAfterOperator(operator), node.sourceIndex + expression.source.operator.end.index ); } if ( expression.source.operator.start.index === left.source.end.index ) { complain( messages.expectedSpaceBeforeOperator(operator), node.sourceIndex + expression.source.operator.start.index ); } } else if (operator === "/") { if ( (right.type === "Value" && right.value === 0) || (right.type === "MathExpression" && getNumber(right) === 0) ) { complain( messages.rejectedDivisionByZero(), node.sourceIndex + expression.source.operator.end.index ); } } if (getResolvedType(expression) === "invalid") { complain( messages.expectedValidResolvedType(operator), node.sourceIndex + expression.source.operator.start.index ); } verifyMathExpressions(expression.left, node); verifyMathExpressions(expression.right, node); } }
javascript
{ "resource": "" }
q20478
getCommaCheckIndex
train
function getCommaCheckIndex(commaNode, nodeIndex) { let commaBefore = valueNode.before + argumentStrings.slice(0, nodeIndex).join("") + commaNode.before; // 1. Remove comments including preceeding whitespace (when only succeeded by whitespace) // 2. Remove all other comments, but leave adjacent whitespace intact commaBefore = commaBefore.replace( /( *\/(\*.*\*\/(?!\S)|\/.*)|(\/(\*.*\*\/|\/.*)))/, "" ); return commaBefore.length; }
javascript
{ "resource": "" }
q20479
isEofNode
train
function isEofNode(document, root) { if (!document || document.constructor.name !== "Document") { return true; } // In the `postcss-html` and `postcss-jsx` syntax, checks that there is text after the given node. let after; if (root === document.last) { after = _.get(document, "raws.afterEnd"); } else { const rootIndex = document.index(root); after = _.get(document.nodes[rootIndex + 1], "raws.beforeStart"); } return !(after + "").trim(); }
javascript
{ "resource": "" }
q20480
augmentConfigBasic
train
function augmentConfigBasic( stylelint /*: stylelint$internalApi*/, config /*: stylelint$config*/, configDir /*: string*/, allowOverrides /*:: ?: boolean*/ ) /*: Promise<stylelint$config>*/ { return Promise.resolve() .then(() => { if (!allowOverrides) return config; return _.merge(config, stylelint._options.configOverrides); }) .then(augmentedConfig => { return extendConfig(stylelint, augmentedConfig, configDir); }) .then(augmentedConfig => { return absolutizePaths(augmentedConfig, configDir); }); }
javascript
{ "resource": "" }
q20481
augmentConfigExtended
train
function augmentConfigExtended( stylelint /*: stylelint$internalApi*/, cosmiconfigResultArg /*: ?{ config: stylelint$config, filepath: string, }*/ ) /*: Promise<?{ config: stylelint$config, filepath: string }>*/ { const cosmiconfigResult = cosmiconfigResultArg; // Lock in for Flow if (!cosmiconfigResult) return Promise.resolve(null); const configDir = path.dirname(cosmiconfigResult.filepath || ""); const cleanedConfig = _.omit(cosmiconfigResult.config, "ignoreFiles"); return augmentConfigBasic(stylelint, cleanedConfig, configDir).then( augmentedConfig => { return { config: augmentedConfig, filepath: cosmiconfigResult.filepath }; } ); }
javascript
{ "resource": "" }
q20482
absolutizeProcessors
train
function absolutizeProcessors( processors /*: stylelint$configProcessors*/, configDir /*: string*/ ) /*: stylelint$configProcessors*/ { const normalizedProcessors = Array.isArray(processors) ? processors : [processors]; return normalizedProcessors.map(item => { if (typeof item === "string") { return getModulePath(configDir, item); } return [getModulePath(configDir, item[0]), item[1]]; }); }
javascript
{ "resource": "" }
q20483
addEmptyLineAfter
train
function addEmptyLineAfter( node /*: postcss$node*/, newline /*: '\n' | '\r\n'*/ ) /*: postcss$node*/ { const after = _.last(node.raws.after.split(";")); if (!/\r?\n/.test(after)) { node.raws.after = node.raws.after + _.repeat(newline, 2); } else { node.raws.after = node.raws.after.replace(/(\r?\n)/, `${newline}$1`); } return node; }
javascript
{ "resource": "" }
q20484
addEmptyLineBefore
train
function addEmptyLineBefore( node /*: postcss$node*/, newline /*: '\n' | '\r\n'*/ ) /*: postcss$node*/ { if (!/\r?\n/.test(node.raws.before)) { node.raws.before = _.repeat(newline, 2) + node.raws.before; } else { node.raws.before = node.raws.before.replace(/(\r?\n)/, `${newline}$1`); } return node; }
javascript
{ "resource": "" }
q20485
train
function(invokeId, errType, resultStr) { if (!invoked) return var diffMs = hrTimeMs(process.hrtime(start)) var billedMs = Math.min(100 * (Math.floor(diffMs / 100) + 1), TIMEOUT * 1000) systemLog('END RequestId: ' + invokeId) systemLog([ 'REPORT RequestId: ' + invokeId, 'Duration: ' + diffMs.toFixed(2) + ' ms', 'Billed Duration: ' + billedMs + ' ms', 'Memory Size: ' + MEM_SIZE + ' MB', 'Max Memory Used: ' + Math.round(process.memoryUsage().rss / (1024 * 1024)) + ' MB', '', ].join('\t')) var exitCode = errored || errType ? 1 : 0 if (typeof resultStr === 'string') { handleResult(resultStr, function() { process.exit(exitCode) }) } else { process.exit(exitCode) } }
javascript
{ "resource": "" }
q20486
uuid
train
function uuid() { return crypto.randomBytes(4).toString('hex') + '-' + crypto.randomBytes(2).toString('hex') + '-' + crypto.randomBytes(2).toString('hex').replace(/^./, '1') + '-' + crypto.randomBytes(2).toString('hex') + '-' + crypto.randomBytes(6).toString('hex') }
javascript
{ "resource": "" }
q20487
train
function(roomName, appRoomObj, callback) { // Join room. Creates a default connection room object e.app[appName].connection[easyrtcid].room[roomName] = { apiField: {}, enteredOn: Date.now(), gotListOn: Date.now(), clientList: {}, toRoom: e.app[appName].room[roomName] }; // Add easyrtcid to room clientList e.app[appName].room[roomName].clientList[easyrtcid] = { enteredOn: Date.now(), modifiedOn: Date.now(), toConnection: e.app[appName].connection[easyrtcid] }; // Returns connection room object to callback. connectionObj.room(roomName, callback); }
javascript
{ "resource": "" }
q20488
train
function (err) { if (err) { try{ pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("LOGIN_GEN_FAIL"), appObj); socket.disconnect(); pub.util.logError("["+easyrtcid+"] General authentication error. Socket disconnected.", err); }catch(e) {} } else { callback(null, connectionObj); } }
javascript
{ "resource": "" }
q20489
iceCandidateFilter
train
function iceCandidateFilter( iceCandidate, fromPeer) { var sdp = iceCandidate.candidate; if( sdp.indexOf("typ relay") > 0) { // is turn candidate if( document.getElementById("allowTurn").checked ) { return iceCandidate; } else { return null; } } else if( sdp.indexOf("typ srflx") > 0) { // is turn candidate if( document.getElementById("allowStun").checked ) { return iceCandidate; } else { return null; } } else if( sdp.indexOf("typ host") > 0) { // is turn candidate if( document.getElementById("allowLocal").checked ) { return iceCandidate; } else { return null; } } else { console.log("Unrecognized type of ice candidate, passing through: " + sdp); } }
javascript
{ "resource": "" }
q20490
setThumbSizeAspect
train
function setThumbSizeAspect(percentSize, percentLeft, percentTop, parentw, parenth, aspect) { var width, height; if( parentw < parenth*aspectRatio){ width = parentw * percentSize; height = width/aspect; } else { height = parenth * percentSize; width = height*aspect; } var left; if( percentLeft < 0) { left = parentw - width; } else { left = 0; } left += Math.floor(percentLeft*parentw); var top = 0; if( percentTop < 0) { top = parenth - height; } else { top = 0; } top += Math.floor(percentTop*parenth); return { left:left, top:top, width:width, height:height }; }
javascript
{ "resource": "" }
q20491
establishConnection
train
function establishConnection(position) { function callSuccess() { connectCount++; if( connectCount < maxCALLERS && position > 0) { establishConnection(position-1); } } function callFailure(errorCode, errorText) { easyrtc.showError(errorCode, errorText); if( connectCount < maxCALLERS && position > 0) { establishConnection(position-1); } } easyrtc.call(list[position], callSuccess, callFailure); }
javascript
{ "resource": "" }
q20492
getCommonCapabilities
train
function getCommonCapabilities(localCapabilities, remoteCapabilities) { var commonCapabilities = { codecs: [], headerExtensions: [], fecMechanisms: [] }; var findCodecByPayloadType = function(pt, codecs) { pt = parseInt(pt, 10); for (var i = 0; i < codecs.length; i++) { if (codecs[i].payloadType === pt || codecs[i].preferredPayloadType === pt) { return codecs[i]; } } }; var rtxCapabilityMatches = function(lRtx, rRtx, lCodecs, rCodecs) { var lCodec = findCodecByPayloadType(lRtx.parameters.apt, lCodecs); var rCodec = findCodecByPayloadType(rRtx.parameters.apt, rCodecs); return lCodec && rCodec && lCodec.name.toLowerCase() === rCodec.name.toLowerCase(); }; localCapabilities.codecs.forEach(function(lCodec) { for (var i = 0; i < remoteCapabilities.codecs.length; i++) { var rCodec = remoteCapabilities.codecs[i]; if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() && lCodec.clockRate === rCodec.clockRate) { if (lCodec.name.toLowerCase() === 'rtx' && lCodec.parameters && rCodec.parameters.apt) { // for RTX we need to find the local rtx that has a apt // which points to the same local codec as the remote one. if (!rtxCapabilityMatches(lCodec, rCodec, localCapabilities.codecs, remoteCapabilities.codecs)) { continue; } } rCodec = JSON.parse(JSON.stringify(rCodec)); // deepcopy // number of channels is the highest common number of channels rCodec.numChannels = Math.min(lCodec.numChannels, rCodec.numChannels); // push rCodec so we reply with offerer payload type commonCapabilities.codecs.push(rCodec); // determine common feedback mechanisms rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) { for (var j = 0; j < lCodec.rtcpFeedback.length; j++) { if (lCodec.rtcpFeedback[j].type === fb.type && lCodec.rtcpFeedback[j].parameter === fb.parameter) { return true; } } return false; }); // FIXME: also need to determine .parameters // see https://github.com/openpeer/ortc/issues/569 break; } } }); localCapabilities.headerExtensions.forEach(function(lHeaderExtension) { for (var i = 0; i < remoteCapabilities.headerExtensions.length; i++) { var rHeaderExtension = remoteCapabilities.headerExtensions[i]; if (lHeaderExtension.uri === rHeaderExtension.uri) { commonCapabilities.headerExtensions.push(rHeaderExtension); break; } } }); // FIXME: fecMechanisms return commonCapabilities; }
javascript
{ "resource": "" }
q20493
isActionAllowedInSignalingState
train
function isActionAllowedInSignalingState(action, type, signalingState) { return { offer: { setLocalDescription: ['stable', 'have-local-offer'], setRemoteDescription: ['stable', 'have-remote-offer'] }, answer: { setLocalDescription: ['have-remote-offer', 'have-local-pranswer'], setRemoteDescription: ['have-local-offer', 'have-remote-pranswer'] } }[type][action].indexOf(signalingState) !== -1; }
javascript
{ "resource": "" }
q20494
train
function(window) { var URL = window && window.URL; if (!(typeof window === 'object' && window.HTMLMediaElement && 'srcObject' in window.HTMLMediaElement.prototype && URL.createObjectURL && URL.revokeObjectURL)) { // Only shim CreateObjectURL using srcObject if srcObject exists. return undefined; } var nativeCreateObjectURL = URL.createObjectURL.bind(URL); var nativeRevokeObjectURL = URL.revokeObjectURL.bind(URL); var streams = new Map(), newId = 0; URL.createObjectURL = function(stream) { if ('getTracks' in stream) { var url = 'polyblob:' + (++newId); streams.set(url, stream); utils.deprecated('URL.createObjectURL(stream)', 'elem.srcObject = stream'); return url; } return nativeCreateObjectURL(stream); }; URL.revokeObjectURL = function(url) { nativeRevokeObjectURL(url); streams.delete(url); }; var dsc = Object.getOwnPropertyDescriptor(window.HTMLMediaElement.prototype, 'src'); Object.defineProperty(window.HTMLMediaElement.prototype, 'src', { get: function() { return dsc.get.apply(this); }, set: function(url) { this.srcObject = streams.get(url) || null; return dsc.set.apply(this, [url]); } }); var nativeSetAttribute = window.HTMLMediaElement.prototype.setAttribute; window.HTMLMediaElement.prototype.setAttribute = function() { if (arguments.length === 2 && ('' + arguments[0]).toLowerCase() === 'src') { this.srcObject = streams.get(arguments[1]) || null; } return nativeSetAttribute.apply(this, arguments); }; }
javascript
{ "resource": "" }
q20495
train
function(constraints, onSuccess, onError) { var constraintsToFF37_ = function(c) { if (typeof c !== 'object' || c.require) { return c; } var require = []; Object.keys(c).forEach(function(key) { if (key === 'require' || key === 'advanced' || key === 'mediaSource') { return; } var r = c[key] = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; if (r.min !== undefined || r.max !== undefined || r.exact !== undefined) { require.push(key); } if (r.exact !== undefined) { if (typeof r.exact === 'number') { r. min = r.max = r.exact; } else { c[key] = r.exact; } delete r.exact; } if (r.ideal !== undefined) { c.advanced = c.advanced || []; var oc = {}; if (typeof r.ideal === 'number') { oc[key] = {min: r.ideal, max: r.ideal}; } else { oc[key] = r.ideal; } c.advanced.push(oc); delete r.ideal; if (!Object.keys(r).length) { delete c[key]; } } }); if (require.length) { c.require = require; } return c; }; constraints = JSON.parse(JSON.stringify(constraints)); if (browserDetails.version < 38) { logging('spec: ' + JSON.stringify(constraints)); if (constraints.audio) { constraints.audio = constraintsToFF37_(constraints.audio); } if (constraints.video) { constraints.video = constraintsToFF37_(constraints.video); } logging('ff37: ' + JSON.stringify(constraints)); } return navigator.mozGetUserMedia(constraints, onSuccess, function(e) { onError(shimError_(e)); }); }
javascript
{ "resource": "" }
q20496
extractVersion
train
function extractVersion(uastring, expr, pos) { var match = uastring.match(expr); return match && match.length >= pos && parseInt(match[pos], 10); }
javascript
{ "resource": "" }
q20497
train
function(window) { var navigator = window && window.navigator; // Returned result object. var result = {}; result.browser = null; result.version = null; // Fail early if it's not a browser if (typeof window === 'undefined' || !window.navigator) { result.browser = 'Not a browser.'; return result; } if (navigator.mozGetUserMedia) { // Firefox. result.browser = 'firefox'; result.version = extractVersion(navigator.userAgent, /Firefox\/(\d+)\./, 1); } else if (navigator.webkitGetUserMedia) { // Chrome, Chromium, Webview, Opera. // Version matches Chrome/WebRTC version. result.browser = 'chrome'; result.version = extractVersion(navigator.userAgent, /Chrom(e|ium)\/(\d+)\./, 2); } else if (navigator.mediaDevices && navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { // Edge. result.browser = 'edge'; result.version = extractVersion(navigator.userAgent, /Edge\/(\d+).(\d+)$/, 2); } else if (window.RTCPeerConnection && navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) { // Safari. result.browser = 'safari'; result.version = extractVersion(navigator.userAgent, /AppleWebKit\/(\d+)\./, 1); } else { // Default fallthrough: not supported. result.browser = 'Not a supported browser.'; return result; } return result; }
javascript
{ "resource": "" }
q20498
addStreamToPeerConnection
train
function addStreamToPeerConnection(stream, peerConnection) { if( peerConnection.addStream ) { var existingStreams = peerConnection.getLocalStreams(); if (existingStreams.indexOf(stream) === -1) { peerConnection.addStream(stream); } } else { var existingTracks = peerConnection.getSenders(); var tracks = stream.getAudioTracks(); var i; for( i = 0; i < tracks.length; i++ ) { if (existingTracks.indexOf(tracks[i]) === -1) { peerConnection.addTrack( tracks[i]); } } tracks = stream.getVideoTracks(); for( i = 0; i < tracks.length; i++ ) { if (existingTracks.indexOf(tracks[i]) === -1) { peerConnection.addTrack( tracks[i]); } } } }
javascript
{ "resource": "" }
q20499
isSocketConnected
train
function isSocketConnected(socket) { return socket && ( (socket.socket && socket.socket.connected) || socket.connected ); }
javascript
{ "resource": "" }