id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
5,400
lihongxun945/jquery-weui
src/js/hammer.js
getRecognizerByNameIfManager
function getRecognizerByNameIfManager(otherRecognizer, recognizer) { var manager = recognizer.manager; if (manager) { return manager.get(otherRecognizer); } return otherRecognizer; }
javascript
function getRecognizerByNameIfManager(otherRecognizer, recognizer) { var manager = recognizer.manager; if (manager) { return manager.get(otherRecognizer); } return otherRecognizer; }
[ "function", "getRecognizerByNameIfManager", "(", "otherRecognizer", ",", "recognizer", ")", "{", "var", "manager", "=", "recognizer", ".", "manager", ";", "if", "(", "manager", ")", "{", "return", "manager", ".", "get", "(", "otherRecognizer", ")", ";", "}", "return", "otherRecognizer", ";", "}" ]
get a recognizer by name if it is bound to a manager @param {Recognizer|String} otherRecognizer @param {Recognizer} recognizer @returns {Recognizer}
[ "get", "a", "recognizer", "by", "name", "if", "it", "is", "bound", "to", "a", "manager" ]
e1efdff32318e8bf84e06778094a1705d5d99ddb
https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L1672-L1678
5,401
lihongxun945/jquery-weui
src/js/hammer.js
function(input) { var state = this.state; var eventType = input.eventType; var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); var isValid = this.attrTest(input); // on cancel input and we've recognized before, return STATE_CANCELLED if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { return state | STATE_CANCELLED; } else if (isRecognized || isValid) { if (eventType & INPUT_END) { return state | STATE_ENDED; } else if (!(state & STATE_BEGAN)) { return STATE_BEGAN; } return state | STATE_CHANGED; } return STATE_FAILED; }
javascript
function(input) { var state = this.state; var eventType = input.eventType; var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); var isValid = this.attrTest(input); // on cancel input and we've recognized before, return STATE_CANCELLED if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { return state | STATE_CANCELLED; } else if (isRecognized || isValid) { if (eventType & INPUT_END) { return state | STATE_ENDED; } else if (!(state & STATE_BEGAN)) { return STATE_BEGAN; } return state | STATE_CHANGED; } return STATE_FAILED; }
[ "function", "(", "input", ")", "{", "var", "state", "=", "this", ".", "state", ";", "var", "eventType", "=", "input", ".", "eventType", ";", "var", "isRecognized", "=", "state", "&", "(", "STATE_BEGAN", "|", "STATE_CHANGED", ")", ";", "var", "isValid", "=", "this", ".", "attrTest", "(", "input", ")", ";", "// on cancel input and we've recognized before, return STATE_CANCELLED", "if", "(", "isRecognized", "&&", "(", "eventType", "&", "INPUT_CANCEL", "||", "!", "isValid", ")", ")", "{", "return", "state", "|", "STATE_CANCELLED", ";", "}", "else", "if", "(", "isRecognized", "||", "isValid", ")", "{", "if", "(", "eventType", "&", "INPUT_END", ")", "{", "return", "state", "|", "STATE_ENDED", ";", "}", "else", "if", "(", "!", "(", "state", "&", "STATE_BEGAN", ")", ")", "{", "return", "STATE_BEGAN", ";", "}", "return", "state", "|", "STATE_CHANGED", ";", "}", "return", "STATE_FAILED", ";", "}" ]
Process the input and return the state for the recognizer @memberof AttrRecognizer @param {Object} input @returns {*} State
[ "Process", "the", "input", "and", "return", "the", "state", "for", "the", "recognizer" ]
e1efdff32318e8bf84e06778094a1705d5d99ddb
https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L1719-L1738
5,402
lihongxun945/jquery-weui
src/js/hammer.js
Hammer
function Hammer(element, options) { options = options || {}; options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); return new Manager(element, options); }
javascript
function Hammer(element, options) { options = options || {}; options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); return new Manager(element, options); }
[ "function", "Hammer", "(", "element", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "options", ".", "recognizers", "=", "ifUndefined", "(", "options", ".", "recognizers", ",", "Hammer", ".", "defaults", ".", "preset", ")", ";", "return", "new", "Manager", "(", "element", ",", "options", ")", ";", "}" ]
Simple way to create a manager with a default set of recognizers. @param {HTMLElement} element @param {Object} [options] @constructor
[ "Simple", "way", "to", "create", "a", "manager", "with", "a", "default", "set", "of", "recognizers", "." ]
e1efdff32318e8bf84e06778094a1705d5d99ddb
https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L2139-L2143
5,403
lihongxun945/jquery-weui
src/js/hammer.js
function(recognizer) { if (recognizer instanceof Recognizer) { return recognizer; } var recognizers = this.recognizers; for (var i = 0; i < recognizers.length; i++) { if (recognizers[i].options.event == recognizer) { return recognizers[i]; } } return null; }
javascript
function(recognizer) { if (recognizer instanceof Recognizer) { return recognizer; } var recognizers = this.recognizers; for (var i = 0; i < recognizers.length; i++) { if (recognizers[i].options.event == recognizer) { return recognizers[i]; } } return null; }
[ "function", "(", "recognizer", ")", "{", "if", "(", "recognizer", "instanceof", "Recognizer", ")", "{", "return", "recognizer", ";", "}", "var", "recognizers", "=", "this", ".", "recognizers", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "recognizers", ".", "length", ";", "i", "++", ")", "{", "if", "(", "recognizers", "[", "i", "]", ".", "options", ".", "event", "==", "recognizer", ")", "{", "return", "recognizers", "[", "i", "]", ";", "}", "}", "return", "null", ";", "}" ]
get a recognizer by its event name. @param {Recognizer|String} recognizer @returns {Recognizer|Null}
[ "get", "a", "recognizer", "by", "its", "event", "name", "." ]
e1efdff32318e8bf84e06778094a1705d5d99ddb
https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L2387-L2399
5,404
lihongxun945/jquery-weui
src/js/hammer.js
function(recognizer) { if (invokeArrayArg(recognizer, 'add', this)) { return this; } // remove existing var existing = this.get(recognizer.options.event); if (existing) { this.remove(existing); } this.recognizers.push(recognizer); recognizer.manager = this; this.touchAction.update(); return recognizer; }
javascript
function(recognizer) { if (invokeArrayArg(recognizer, 'add', this)) { return this; } // remove existing var existing = this.get(recognizer.options.event); if (existing) { this.remove(existing); } this.recognizers.push(recognizer); recognizer.manager = this; this.touchAction.update(); return recognizer; }
[ "function", "(", "recognizer", ")", "{", "if", "(", "invokeArrayArg", "(", "recognizer", ",", "'add'", ",", "this", ")", ")", "{", "return", "this", ";", "}", "// remove existing", "var", "existing", "=", "this", ".", "get", "(", "recognizer", ".", "options", ".", "event", ")", ";", "if", "(", "existing", ")", "{", "this", ".", "remove", "(", "existing", ")", ";", "}", "this", ".", "recognizers", ".", "push", "(", "recognizer", ")", ";", "recognizer", ".", "manager", "=", "this", ";", "this", ".", "touchAction", ".", "update", "(", ")", ";", "return", "recognizer", ";", "}" ]
add a recognizer to the manager existing recognizers with the same event name will be removed @param {Recognizer} recognizer @returns {Recognizer|Manager}
[ "add", "a", "recognizer", "to", "the", "manager", "existing", "recognizers", "with", "the", "same", "event", "name", "will", "be", "removed" ]
e1efdff32318e8bf84e06778094a1705d5d99ddb
https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L2407-L2423
5,405
lihongxun945/jquery-weui
src/js/hammer.js
function(event, data) { // we also want to trigger dom events if (this.options.domEvents) { triggerDomEvent(event, data); } // no handlers, so skip it all var handlers = this.handlers[event] && this.handlers[event].slice(); if (!handlers || !handlers.length) { return; } data.type = event; data.preventDefault = function() { data.srcEvent.preventDefault(); }; var i = 0; while (i < handlers.length) { handlers[i](data); i++; } }
javascript
function(event, data) { // we also want to trigger dom events if (this.options.domEvents) { triggerDomEvent(event, data); } // no handlers, so skip it all var handlers = this.handlers[event] && this.handlers[event].slice(); if (!handlers || !handlers.length) { return; } data.type = event; data.preventDefault = function() { data.srcEvent.preventDefault(); }; var i = 0; while (i < handlers.length) { handlers[i](data); i++; } }
[ "function", "(", "event", ",", "data", ")", "{", "// we also want to trigger dom events", "if", "(", "this", ".", "options", ".", "domEvents", ")", "{", "triggerDomEvent", "(", "event", ",", "data", ")", ";", "}", "// no handlers, so skip it all", "var", "handlers", "=", "this", ".", "handlers", "[", "event", "]", "&&", "this", ".", "handlers", "[", "event", "]", ".", "slice", "(", ")", ";", "if", "(", "!", "handlers", "||", "!", "handlers", ".", "length", ")", "{", "return", ";", "}", "data", ".", "type", "=", "event", ";", "data", ".", "preventDefault", "=", "function", "(", ")", "{", "data", ".", "srcEvent", ".", "preventDefault", "(", ")", ";", "}", ";", "var", "i", "=", "0", ";", "while", "(", "i", "<", "handlers", ".", "length", ")", "{", "handlers", "[", "i", "]", "(", "data", ")", ";", "i", "++", ";", "}", "}" ]
emit event to the listeners @param {String} event @param {Object} data
[ "emit", "event", "to", "the", "listeners" ]
e1efdff32318e8bf84e06778094a1705d5d99ddb
https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L2500-L2522
5,406
josdejong/mathjs
tools/entryGenerator.js
generateDependenciesFiles
function generateDependenciesFiles ({ suffix, factories, entryFolder }) { const braceOpen = '{' // a hack to be able to create a single brace open character in handlebars // a map containing: // { // 'sqrt': true, // 'subset': true, // ... // } const exists = {} Object.keys(factories).forEach(factoryName => { const factory = factories[factoryName] exists[factory.fn] = true }) mkdirSyncIfNotExists(path.join(entryFolder, 'dependencies' + suffix)) const data = { suffix, factories: Object.keys(factories).map((factoryName) => { const factory = factories[factoryName] return { suffix, factoryName, braceOpen, name: getDependenciesName(factoryName, factories), // FIXME: rename name with dependenciesName, and functionName with name fileName: './dependencies' + suffix + '/' + getDependenciesFileName(factoryName) + '.generated', eslintComment: factoryName === 'createSQRT1_2' ? ' // eslint-disable-line camelcase' : undefined, dependencies: factory.dependencies .map(stripOptionalNotation) .filter(dependency => !IGNORED_DEPENDENCIES[dependency]) .filter(dependency => { if (!exists[dependency]) { if (factory.dependencies.indexOf(dependency) !== -1) { throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`) } return false } return true }) .map(dependency => { const factoryName = findFactoryName(factories, dependency) const name = getDependenciesName(factoryName, factories) const fileName = './' + getDependenciesFileName(factoryName) + '.generated' return { suffix, name, fileName } }) } }) } // generate a file for every dependency data.factories.forEach(factoryData => { const generatedFactory = dependenciesFileTemplate(factoryData) const p = path.join(entryFolder, factoryData.fileName + '.js') fs.writeFileSync(p, generatedFactory) }) // generate a file with links to all dependencies const generated = dependenciesIndexTemplate(data) fs.writeFileSync(path.join(entryFolder, 'dependencies' + suffix + '.generated.js'), generated) }
javascript
function generateDependenciesFiles ({ suffix, factories, entryFolder }) { const braceOpen = '{' // a hack to be able to create a single brace open character in handlebars // a map containing: // { // 'sqrt': true, // 'subset': true, // ... // } const exists = {} Object.keys(factories).forEach(factoryName => { const factory = factories[factoryName] exists[factory.fn] = true }) mkdirSyncIfNotExists(path.join(entryFolder, 'dependencies' + suffix)) const data = { suffix, factories: Object.keys(factories).map((factoryName) => { const factory = factories[factoryName] return { suffix, factoryName, braceOpen, name: getDependenciesName(factoryName, factories), // FIXME: rename name with dependenciesName, and functionName with name fileName: './dependencies' + suffix + '/' + getDependenciesFileName(factoryName) + '.generated', eslintComment: factoryName === 'createSQRT1_2' ? ' // eslint-disable-line camelcase' : undefined, dependencies: factory.dependencies .map(stripOptionalNotation) .filter(dependency => !IGNORED_DEPENDENCIES[dependency]) .filter(dependency => { if (!exists[dependency]) { if (factory.dependencies.indexOf(dependency) !== -1) { throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`) } return false } return true }) .map(dependency => { const factoryName = findFactoryName(factories, dependency) const name = getDependenciesName(factoryName, factories) const fileName = './' + getDependenciesFileName(factoryName) + '.generated' return { suffix, name, fileName } }) } }) } // generate a file for every dependency data.factories.forEach(factoryData => { const generatedFactory = dependenciesFileTemplate(factoryData) const p = path.join(entryFolder, factoryData.fileName + '.js') fs.writeFileSync(p, generatedFactory) }) // generate a file with links to all dependencies const generated = dependenciesIndexTemplate(data) fs.writeFileSync(path.join(entryFolder, 'dependencies' + suffix + '.generated.js'), generated) }
[ "function", "generateDependenciesFiles", "(", "{", "suffix", ",", "factories", ",", "entryFolder", "}", ")", "{", "const", "braceOpen", "=", "'{'", "// a hack to be able to create a single brace open character in handlebars", "// a map containing:", "// {", "// 'sqrt': true,", "// 'subset': true,", "// ...", "// }", "const", "exists", "=", "{", "}", "Object", ".", "keys", "(", "factories", ")", ".", "forEach", "(", "factoryName", "=>", "{", "const", "factory", "=", "factories", "[", "factoryName", "]", "exists", "[", "factory", ".", "fn", "]", "=", "true", "}", ")", "mkdirSyncIfNotExists", "(", "path", ".", "join", "(", "entryFolder", ",", "'dependencies'", "+", "suffix", ")", ")", "const", "data", "=", "{", "suffix", ",", "factories", ":", "Object", ".", "keys", "(", "factories", ")", ".", "map", "(", "(", "factoryName", ")", "=>", "{", "const", "factory", "=", "factories", "[", "factoryName", "]", "return", "{", "suffix", ",", "factoryName", ",", "braceOpen", ",", "name", ":", "getDependenciesName", "(", "factoryName", ",", "factories", ")", ",", "// FIXME: rename name with dependenciesName, and functionName with name", "fileName", ":", "'./dependencies'", "+", "suffix", "+", "'/'", "+", "getDependenciesFileName", "(", "factoryName", ")", "+", "'.generated'", ",", "eslintComment", ":", "factoryName", "===", "'createSQRT1_2'", "?", "' // eslint-disable-line camelcase'", ":", "undefined", ",", "dependencies", ":", "factory", ".", "dependencies", ".", "map", "(", "stripOptionalNotation", ")", ".", "filter", "(", "dependency", "=>", "!", "IGNORED_DEPENDENCIES", "[", "dependency", "]", ")", ".", "filter", "(", "dependency", "=>", "{", "if", "(", "!", "exists", "[", "dependency", "]", ")", "{", "if", "(", "factory", ".", "dependencies", ".", "indexOf", "(", "dependency", ")", "!==", "-", "1", ")", "{", "throw", "new", "Error", "(", "`", "${", "dependency", "}", "${", "factory", ".", "fn", "}", "`", ")", "}", "return", "false", "}", "return", "true", "}", ")", ".", "map", "(", "dependency", "=>", "{", "const", "factoryName", "=", "findFactoryName", "(", "factories", ",", "dependency", ")", "const", "name", "=", "getDependenciesName", "(", "factoryName", ",", "factories", ")", "const", "fileName", "=", "'./'", "+", "getDependenciesFileName", "(", "factoryName", ")", "+", "'.generated'", "return", "{", "suffix", ",", "name", ",", "fileName", "}", "}", ")", "}", "}", ")", "}", "// generate a file for every dependency", "data", ".", "factories", ".", "forEach", "(", "factoryData", "=>", "{", "const", "generatedFactory", "=", "dependenciesFileTemplate", "(", "factoryData", ")", "const", "p", "=", "path", ".", "join", "(", "entryFolder", ",", "factoryData", ".", "fileName", "+", "'.js'", ")", "fs", ".", "writeFileSync", "(", "p", ",", "generatedFactory", ")", "}", ")", "// generate a file with links to all dependencies", "const", "generated", "=", "dependenciesIndexTemplate", "(", "data", ")", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "entryFolder", ",", "'dependencies'", "+", "suffix", "+", "'.generated.js'", ")", ",", "generated", ")", "}" ]
Generate index files like dependenciesAny.generated.js dependenciesNumber.generated.js And the individual files for every dependencies collection.
[ "Generate", "index", "files", "like", "dependenciesAny", ".", "generated", ".", "js", "dependenciesNumber", ".", "generated", ".", "js", "And", "the", "individual", "files", "for", "every", "dependencies", "collection", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/tools/entryGenerator.js#L186-L258
5,407
josdejong/mathjs
src/utils/object.js
_deepFlatten
function _deepFlatten (nestedObject, flattenedObject) { for (const prop in nestedObject) { if (nestedObject.hasOwnProperty(prop)) { const value = nestedObject[prop] if (typeof value === 'object' && value !== null) { _deepFlatten(value, flattenedObject) } else { flattenedObject[prop] = value } } } }
javascript
function _deepFlatten (nestedObject, flattenedObject) { for (const prop in nestedObject) { if (nestedObject.hasOwnProperty(prop)) { const value = nestedObject[prop] if (typeof value === 'object' && value !== null) { _deepFlatten(value, flattenedObject) } else { flattenedObject[prop] = value } } } }
[ "function", "_deepFlatten", "(", "nestedObject", ",", "flattenedObject", ")", "{", "for", "(", "const", "prop", "in", "nestedObject", ")", "{", "if", "(", "nestedObject", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "const", "value", "=", "nestedObject", "[", "prop", "]", "if", "(", "typeof", "value", "===", "'object'", "&&", "value", "!==", "null", ")", "{", "_deepFlatten", "(", "value", ",", "flattenedObject", ")", "}", "else", "{", "flattenedObject", "[", "prop", "]", "=", "value", "}", "}", "}", "}" ]
helper function used by deepFlatten
[ "helper", "function", "used", "by", "deepFlatten" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/utils/object.js#L174-L185
5,408
josdejong/mathjs
src/utils/number.js
zeros
function zeros (length) { const arr = [] for (let i = 0; i < length; i++) { arr.push(0) } return arr }
javascript
function zeros (length) { const arr = [] for (let i = 0; i < length; i++) { arr.push(0) } return arr }
[ "function", "zeros", "(", "length", ")", "{", "const", "arr", "=", "[", "]", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "arr", ".", "push", "(", "0", ")", "}", "return", "arr", "}" ]
Create an array filled with zeros. @param {number} length @return {Array}
[ "Create", "an", "array", "filled", "with", "zeros", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/utils/number.js#L521-L527
5,409
josdejong/mathjs
src/core/function/config.js
findIndex
function findIndex (array, item) { return array .map(function (i) { return i.toLowerCase() }) .indexOf(item.toLowerCase()) }
javascript
function findIndex (array, item) { return array .map(function (i) { return i.toLowerCase() }) .indexOf(item.toLowerCase()) }
[ "function", "findIndex", "(", "array", ",", "item", ")", "{", "return", "array", ".", "map", "(", "function", "(", "i", ")", "{", "return", "i", ".", "toLowerCase", "(", ")", "}", ")", ".", "indexOf", "(", "item", ".", "toLowerCase", "(", ")", ")", "}" ]
Find a string in an array. Case insensitive search @param {Array.<string>} array @param {string} item @return {number} Returns the index when found. Returns -1 when not found
[ "Find", "a", "string", "in", "an", "array", ".", "Case", "insensitive", "search" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/core/function/config.js#L100-L106
5,410
josdejong/mathjs
src/core/function/config.js
validateOption
function validateOption (options, name, values) { if (options[name] !== undefined && !contains(values, options[name])) { const index = findIndex(values, options[name]) if (index !== -1) { // right value, wrong casing // TODO: lower case values are deprecated since v3, remove this warning some day. console.warn('Warning: Wrong casing for configuration option "' + name + '", should be "' + values[index] + '" instead of "' + options[name] + '".') options[name] = values[index] // change the option to the right casing } else { // unknown value console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". Available options: ' + values.map(JSON.stringify).join(', ') + '.') } } }
javascript
function validateOption (options, name, values) { if (options[name] !== undefined && !contains(values, options[name])) { const index = findIndex(values, options[name]) if (index !== -1) { // right value, wrong casing // TODO: lower case values are deprecated since v3, remove this warning some day. console.warn('Warning: Wrong casing for configuration option "' + name + '", should be "' + values[index] + '" instead of "' + options[name] + '".') options[name] = values[index] // change the option to the right casing } else { // unknown value console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". Available options: ' + values.map(JSON.stringify).join(', ') + '.') } } }
[ "function", "validateOption", "(", "options", ",", "name", ",", "values", ")", "{", "if", "(", "options", "[", "name", "]", "!==", "undefined", "&&", "!", "contains", "(", "values", ",", "options", "[", "name", "]", ")", ")", "{", "const", "index", "=", "findIndex", "(", "values", ",", "options", "[", "name", "]", ")", "if", "(", "index", "!==", "-", "1", ")", "{", "// right value, wrong casing", "// TODO: lower case values are deprecated since v3, remove this warning some day.", "console", ".", "warn", "(", "'Warning: Wrong casing for configuration option \"'", "+", "name", "+", "'\", should be \"'", "+", "values", "[", "index", "]", "+", "'\" instead of \"'", "+", "options", "[", "name", "]", "+", "'\".'", ")", "options", "[", "name", "]", "=", "values", "[", "index", "]", "// change the option to the right casing", "}", "else", "{", "// unknown value", "console", ".", "warn", "(", "'Warning: Unknown value \"'", "+", "options", "[", "name", "]", "+", "'\" for configuration option \"'", "+", "name", "+", "'\". Available options: '", "+", "values", ".", "map", "(", "JSON", ".", "stringify", ")", ".", "join", "(", "', '", ")", "+", "'.'", ")", "}", "}", "}" ]
Validate an option @param {Object} options Object with options @param {string} name Name of the option to validate @param {Array.<string>} values Array with valid values for this option
[ "Validate", "an", "option" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/core/function/config.js#L114-L128
5,411
josdejong/mathjs
src/type/unit/physicalConstants.js
unitFactory
function unitFactory (name, valueStr, unitStr) { const dependencies = ['config', 'Unit', 'BigNumber'] return factory(name, dependencies, ({ config, Unit, BigNumber }) => { // Note that we can parse into number or BigNumber. // We do not parse into Fractions as that doesn't make sense: we would lose precision of the values // Therefore we dont use Unit.parse() const value = config.number === 'BigNumber' ? new BigNumber(valueStr) : parseFloat(valueStr) const unit = new Unit(value, unitStr) unit.fixPrefix = true return unit }) }
javascript
function unitFactory (name, valueStr, unitStr) { const dependencies = ['config', 'Unit', 'BigNumber'] return factory(name, dependencies, ({ config, Unit, BigNumber }) => { // Note that we can parse into number or BigNumber. // We do not parse into Fractions as that doesn't make sense: we would lose precision of the values // Therefore we dont use Unit.parse() const value = config.number === 'BigNumber' ? new BigNumber(valueStr) : parseFloat(valueStr) const unit = new Unit(value, unitStr) unit.fixPrefix = true return unit }) }
[ "function", "unitFactory", "(", "name", ",", "valueStr", ",", "unitStr", ")", "{", "const", "dependencies", "=", "[", "'config'", ",", "'Unit'", ",", "'BigNumber'", "]", "return", "factory", "(", "name", ",", "dependencies", ",", "(", "{", "config", ",", "Unit", ",", "BigNumber", "}", ")", "=>", "{", "// Note that we can parse into number or BigNumber.", "// We do not parse into Fractions as that doesn't make sense: we would lose precision of the values", "// Therefore we dont use Unit.parse()", "const", "value", "=", "config", ".", "number", "===", "'BigNumber'", "?", "new", "BigNumber", "(", "valueStr", ")", ":", "parseFloat", "(", "valueStr", ")", "const", "unit", "=", "new", "Unit", "(", "value", ",", "unitStr", ")", "unit", ".", "fixPrefix", "=", "true", "return", "unit", "}", ")", "}" ]
helper function to create a factory function which creates a physical constant, a Unit with either a number value or a BigNumber value depending on the configuration
[ "helper", "function", "to", "create", "a", "factory", "function", "which", "creates", "a", "physical", "constant", "a", "Unit", "with", "either", "a", "number", "value", "or", "a", "BigNumber", "value", "depending", "on", "the", "configuration" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/type/unit/physicalConstants.js#L74-L89
5,412
josdejong/mathjs
src/type/unit/physicalConstants.js
numberFactory
function numberFactory (name, value) { const dependencies = ['config', 'BigNumber'] return factory(name, dependencies, ({ config, BigNumber }) => { return config.number === 'BigNumber' ? new BigNumber(value) : value }) }
javascript
function numberFactory (name, value) { const dependencies = ['config', 'BigNumber'] return factory(name, dependencies, ({ config, BigNumber }) => { return config.number === 'BigNumber' ? new BigNumber(value) : value }) }
[ "function", "numberFactory", "(", "name", ",", "value", ")", "{", "const", "dependencies", "=", "[", "'config'", ",", "'BigNumber'", "]", "return", "factory", "(", "name", ",", "dependencies", ",", "(", "{", "config", ",", "BigNumber", "}", ")", "=>", "{", "return", "config", ".", "number", "===", "'BigNumber'", "?", "new", "BigNumber", "(", "value", ")", ":", "value", "}", ")", "}" ]
helper function to create a factory function which creates a numeric constant, either a number or BigNumber depending on the configuration
[ "helper", "function", "to", "create", "a", "factory", "function", "which", "creates", "a", "numeric", "constant", "either", "a", "number", "or", "BigNumber", "depending", "on", "the", "configuration" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/type/unit/physicalConstants.js#L93-L101
5,413
josdejong/mathjs
gulpfile.js
addDeprecatedFunctions
function addDeprecatedFunctions (done) { const code = String(fs.readFileSync(COMPILED_MAIN_ANY)) const updatedCode = code + '\n\n' + 'exports[\'var\'] = exports.deprecatedVar;\n' + 'exports[\'typeof\'] = exports.deprecatedTypeof;\n' + 'exports[\'eval\'] = exports.deprecatedEval;\n' + 'exports[\'import\'] = exports.deprecatedImport;\n' fs.writeFileSync(COMPILED_MAIN_ANY, updatedCode) log('Added deprecated functions to ' + COMPILED_MAIN_ANY) done() }
javascript
function addDeprecatedFunctions (done) { const code = String(fs.readFileSync(COMPILED_MAIN_ANY)) const updatedCode = code + '\n\n' + 'exports[\'var\'] = exports.deprecatedVar;\n' + 'exports[\'typeof\'] = exports.deprecatedTypeof;\n' + 'exports[\'eval\'] = exports.deprecatedEval;\n' + 'exports[\'import\'] = exports.deprecatedImport;\n' fs.writeFileSync(COMPILED_MAIN_ANY, updatedCode) log('Added deprecated functions to ' + COMPILED_MAIN_ANY) done() }
[ "function", "addDeprecatedFunctions", "(", "done", ")", "{", "const", "code", "=", "String", "(", "fs", ".", "readFileSync", "(", "COMPILED_MAIN_ANY", ")", ")", "const", "updatedCode", "=", "code", "+", "'\\n\\n'", "+", "'exports[\\'var\\'] = exports.deprecatedVar;\\n'", "+", "'exports[\\'typeof\\'] = exports.deprecatedTypeof;\\n'", "+", "'exports[\\'eval\\'] = exports.deprecatedEval;\\n'", "+", "'exports[\\'import\\'] = exports.deprecatedImport;\\n'", "fs", ".", "writeFileSync", "(", "COMPILED_MAIN_ANY", ",", "updatedCode", ")", "log", "(", "'Added deprecated functions to '", "+", "COMPILED_MAIN_ANY", ")", "done", "(", ")", "}" ]
Add links to deprecated functions in the node.js transpiled code mainAny.js These names are not valid in ES6 where we use them as functions instead of properties.
[ "Add", "links", "to", "deprecated", "functions", "in", "the", "node", ".", "js", "transpiled", "code", "mainAny", ".", "js", "These", "names", "are", "not", "valid", "in", "ES6", "where", "we", "use", "them", "as", "functions", "instead", "of", "properties", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/gulpfile.js#L228-L242
5,414
josdejong/mathjs
src/function/matrix/forEach.js
_forEach
function _forEach (array, callback) { // figure out what number of arguments the callback function expects const args = maxArgumentCount(callback) const recurse = function (value, index) { if (Array.isArray(value)) { forEachArray(value, function (child, i) { // we create a copy of the index array and append the new index value recurse(child, index.concat(i)) }) } else { // invoke the callback function with the right number of arguments if (args === 1) { callback(value) } else if (args === 2) { callback(value, index) } else { // 3 or -1 callback(value, index, array) } } } recurse(array, []) }
javascript
function _forEach (array, callback) { // figure out what number of arguments the callback function expects const args = maxArgumentCount(callback) const recurse = function (value, index) { if (Array.isArray(value)) { forEachArray(value, function (child, i) { // we create a copy of the index array and append the new index value recurse(child, index.concat(i)) }) } else { // invoke the callback function with the right number of arguments if (args === 1) { callback(value) } else if (args === 2) { callback(value, index) } else { // 3 or -1 callback(value, index, array) } } } recurse(array, []) }
[ "function", "_forEach", "(", "array", ",", "callback", ")", "{", "// figure out what number of arguments the callback function expects", "const", "args", "=", "maxArgumentCount", "(", "callback", ")", "const", "recurse", "=", "function", "(", "value", ",", "index", ")", "{", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "forEachArray", "(", "value", ",", "function", "(", "child", ",", "i", ")", "{", "// we create a copy of the index array and append the new index value", "recurse", "(", "child", ",", "index", ".", "concat", "(", "i", ")", ")", "}", ")", "}", "else", "{", "// invoke the callback function with the right number of arguments", "if", "(", "args", "===", "1", ")", "{", "callback", "(", "value", ")", "}", "else", "if", "(", "args", "===", "2", ")", "{", "callback", "(", "value", ",", "index", ")", "}", "else", "{", "// 3 or -1", "callback", "(", "value", ",", "index", ",", "array", ")", "}", "}", "}", "recurse", "(", "array", ",", "[", "]", ")", "}" ]
forEach for a multi dimensional array @param {Array} array @param {Function} callback @private
[ "forEach", "for", "a", "multi", "dimensional", "array" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/function/matrix/forEach.js#L49-L71
5,415
josdejong/mathjs
src/utils/array.js
_validate
function _validate (array, size, dim) { let i const len = array.length if (len !== size[dim]) { throw new DimensionError(len, size[dim]) } if (dim < size.length - 1) { // recursively validate each child array const dimNext = dim + 1 for (i = 0; i < len; i++) { const child = array[i] if (!Array.isArray(child)) { throw new DimensionError(size.length - 1, size.length, '<') } _validate(array[i], size, dimNext) } } else { // last dimension. none of the childs may be an array for (i = 0; i < len; i++) { if (Array.isArray(array[i])) { throw new DimensionError(size.length + 1, size.length, '>') } } } }
javascript
function _validate (array, size, dim) { let i const len = array.length if (len !== size[dim]) { throw new DimensionError(len, size[dim]) } if (dim < size.length - 1) { // recursively validate each child array const dimNext = dim + 1 for (i = 0; i < len; i++) { const child = array[i] if (!Array.isArray(child)) { throw new DimensionError(size.length - 1, size.length, '<') } _validate(array[i], size, dimNext) } } else { // last dimension. none of the childs may be an array for (i = 0; i < len; i++) { if (Array.isArray(array[i])) { throw new DimensionError(size.length + 1, size.length, '>') } } } }
[ "function", "_validate", "(", "array", ",", "size", ",", "dim", ")", "{", "let", "i", "const", "len", "=", "array", ".", "length", "if", "(", "len", "!==", "size", "[", "dim", "]", ")", "{", "throw", "new", "DimensionError", "(", "len", ",", "size", "[", "dim", "]", ")", "}", "if", "(", "dim", "<", "size", ".", "length", "-", "1", ")", "{", "// recursively validate each child array", "const", "dimNext", "=", "dim", "+", "1", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "const", "child", "=", "array", "[", "i", "]", "if", "(", "!", "Array", ".", "isArray", "(", "child", ")", ")", "{", "throw", "new", "DimensionError", "(", "size", ".", "length", "-", "1", ",", "size", ".", "length", ",", "'<'", ")", "}", "_validate", "(", "array", "[", "i", "]", ",", "size", ",", "dimNext", ")", "}", "}", "else", "{", "// last dimension. none of the childs may be an array", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "Array", ".", "isArray", "(", "array", "[", "i", "]", ")", ")", "{", "throw", "new", "DimensionError", "(", "size", ".", "length", "+", "1", ",", "size", ".", "length", ",", "'>'", ")", "}", "}", "}", "}" ]
Recursively validate whether each element in a multi dimensional array has a size corresponding to the provided size array. @param {Array} array Array to be validated @param {number[]} size Array with the size of each dimension @param {number} dim Current dimension @throws DimensionError @private
[ "Recursively", "validate", "whether", "each", "element", "in", "a", "multi", "dimensional", "array", "has", "a", "size", "corresponding", "to", "the", "provided", "size", "array", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/utils/array.js#L36-L62
5,416
josdejong/mathjs
src/utils/array.js
_resize
function _resize (array, size, dim, defaultValue) { let i let elem const oldLen = array.length const newLen = size[dim] const minLen = Math.min(oldLen, newLen) // apply new length array.length = newLen if (dim < size.length - 1) { // non-last dimension const dimNext = dim + 1 // resize existing child arrays for (i = 0; i < minLen; i++) { // resize child array elem = array[i] if (!Array.isArray(elem)) { elem = [elem] // add a dimension array[i] = elem } _resize(elem, size, dimNext, defaultValue) } // create new child arrays for (i = minLen; i < newLen; i++) { // get child array elem = [] array[i] = elem // resize new child array _resize(elem, size, dimNext, defaultValue) } } else { // last dimension // remove dimensions of existing values for (i = 0; i < minLen; i++) { while (Array.isArray(array[i])) { array[i] = array[i][0] } } // fill new elements with the default value for (i = minLen; i < newLen; i++) { array[i] = defaultValue } } }
javascript
function _resize (array, size, dim, defaultValue) { let i let elem const oldLen = array.length const newLen = size[dim] const minLen = Math.min(oldLen, newLen) // apply new length array.length = newLen if (dim < size.length - 1) { // non-last dimension const dimNext = dim + 1 // resize existing child arrays for (i = 0; i < minLen; i++) { // resize child array elem = array[i] if (!Array.isArray(elem)) { elem = [elem] // add a dimension array[i] = elem } _resize(elem, size, dimNext, defaultValue) } // create new child arrays for (i = minLen; i < newLen; i++) { // get child array elem = [] array[i] = elem // resize new child array _resize(elem, size, dimNext, defaultValue) } } else { // last dimension // remove dimensions of existing values for (i = 0; i < minLen; i++) { while (Array.isArray(array[i])) { array[i] = array[i][0] } } // fill new elements with the default value for (i = minLen; i < newLen; i++) { array[i] = defaultValue } } }
[ "function", "_resize", "(", "array", ",", "size", ",", "dim", ",", "defaultValue", ")", "{", "let", "i", "let", "elem", "const", "oldLen", "=", "array", ".", "length", "const", "newLen", "=", "size", "[", "dim", "]", "const", "minLen", "=", "Math", ".", "min", "(", "oldLen", ",", "newLen", ")", "// apply new length", "array", ".", "length", "=", "newLen", "if", "(", "dim", "<", "size", ".", "length", "-", "1", ")", "{", "// non-last dimension", "const", "dimNext", "=", "dim", "+", "1", "// resize existing child arrays", "for", "(", "i", "=", "0", ";", "i", "<", "minLen", ";", "i", "++", ")", "{", "// resize child array", "elem", "=", "array", "[", "i", "]", "if", "(", "!", "Array", ".", "isArray", "(", "elem", ")", ")", "{", "elem", "=", "[", "elem", "]", "// add a dimension", "array", "[", "i", "]", "=", "elem", "}", "_resize", "(", "elem", ",", "size", ",", "dimNext", ",", "defaultValue", ")", "}", "// create new child arrays", "for", "(", "i", "=", "minLen", ";", "i", "<", "newLen", ";", "i", "++", ")", "{", "// get child array", "elem", "=", "[", "]", "array", "[", "i", "]", "=", "elem", "// resize new child array", "_resize", "(", "elem", ",", "size", ",", "dimNext", ",", "defaultValue", ")", "}", "}", "else", "{", "// last dimension", "// remove dimensions of existing values", "for", "(", "i", "=", "0", ";", "i", "<", "minLen", ";", "i", "++", ")", "{", "while", "(", "Array", ".", "isArray", "(", "array", "[", "i", "]", ")", ")", "{", "array", "[", "i", "]", "=", "array", "[", "i", "]", "[", "0", "]", "}", "}", "// fill new elements with the default value", "for", "(", "i", "=", "minLen", ";", "i", "<", "newLen", ";", "i", "++", ")", "{", "array", "[", "i", "]", "=", "defaultValue", "}", "}", "}" ]
Recursively resize a multi dimensional array @param {Array} array Array to be resized @param {number[]} size Array with the size of each dimension @param {number} dim Current dimension @param {*} [defaultValue] Value to be filled in in new entries, undefined by default. @private
[ "Recursively", "resize", "a", "multi", "dimensional", "array" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/utils/array.js#L144-L193
5,417
josdejong/mathjs
src/utils/array.js
_reshape
function _reshape (array, sizes) { // testing if there are enough elements for the requested shape let tmpArray = array let tmpArray2 // for each dimensions starting by the last one and ignoring the first one for (let sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) { const size = sizes[sizeIndex] tmpArray2 = [] // aggregate the elements of the current tmpArray in elements of the requested size const length = tmpArray.length / size for (let i = 0; i < length; i++) { tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size)) } // set it as the new tmpArray for the next loop turn or for return tmpArray = tmpArray2 } return tmpArray }
javascript
function _reshape (array, sizes) { // testing if there are enough elements for the requested shape let tmpArray = array let tmpArray2 // for each dimensions starting by the last one and ignoring the first one for (let sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) { const size = sizes[sizeIndex] tmpArray2 = [] // aggregate the elements of the current tmpArray in elements of the requested size const length = tmpArray.length / size for (let i = 0; i < length; i++) { tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size)) } // set it as the new tmpArray for the next loop turn or for return tmpArray = tmpArray2 } return tmpArray }
[ "function", "_reshape", "(", "array", ",", "sizes", ")", "{", "// testing if there are enough elements for the requested shape", "let", "tmpArray", "=", "array", "let", "tmpArray2", "// for each dimensions starting by the last one and ignoring the first one", "for", "(", "let", "sizeIndex", "=", "sizes", ".", "length", "-", "1", ";", "sizeIndex", ">", "0", ";", "sizeIndex", "--", ")", "{", "const", "size", "=", "sizes", "[", "sizeIndex", "]", "tmpArray2", "=", "[", "]", "// aggregate the elements of the current tmpArray in elements of the requested size", "const", "length", "=", "tmpArray", ".", "length", "/", "size", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "tmpArray2", ".", "push", "(", "tmpArray", ".", "slice", "(", "i", "*", "size", ",", "(", "i", "+", "1", ")", "*", "size", ")", ")", "}", "// set it as the new tmpArray for the next loop turn or for return", "tmpArray", "=", "tmpArray2", "}", "return", "tmpArray", "}" ]
Iteratively re-shape a multi dimensional array to fit the specified dimensions @param {Array} array Array to be reshaped @param {Array.<number>} sizes List of sizes for each dimension @returns {Array} Array whose data has been formatted to fit the specified dimensions
[ "Iteratively", "re", "-", "shape", "a", "multi", "dimensional", "array", "to", "fit", "the", "specified", "dimensions" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/utils/array.js#L258-L277
5,418
josdejong/mathjs
src/utils/array.js
_squeeze
function _squeeze (array, dims, dim) { let i, ii if (dim < dims) { const next = dim + 1 for (i = 0, ii = array.length; i < ii; i++) { array[i] = _squeeze(array[i], dims, next) } } else { while (Array.isArray(array)) { array = array[0] } } return array }
javascript
function _squeeze (array, dims, dim) { let i, ii if (dim < dims) { const next = dim + 1 for (i = 0, ii = array.length; i < ii; i++) { array[i] = _squeeze(array[i], dims, next) } } else { while (Array.isArray(array)) { array = array[0] } } return array }
[ "function", "_squeeze", "(", "array", ",", "dims", ",", "dim", ")", "{", "let", "i", ",", "ii", "if", "(", "dim", "<", "dims", ")", "{", "const", "next", "=", "dim", "+", "1", "for", "(", "i", "=", "0", ",", "ii", "=", "array", ".", "length", ";", "i", "<", "ii", ";", "i", "++", ")", "{", "array", "[", "i", "]", "=", "_squeeze", "(", "array", "[", "i", "]", ",", "dims", ",", "next", ")", "}", "}", "else", "{", "while", "(", "Array", ".", "isArray", "(", "array", ")", ")", "{", "array", "=", "array", "[", "0", "]", "}", "}", "return", "array", "}" ]
Recursively squeeze a multi dimensional array @param {Array} array @param {number} dims Required number of dimensions @param {number} dim Current dimension @returns {Array | *} Returns the squeezed array @private
[ "Recursively", "squeeze", "a", "multi", "dimensional", "array" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/utils/array.js#L317-L332
5,419
josdejong/mathjs
src/utils/array.js
_unsqueeze
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
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 }
[ "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", "}" ]
Recursively unsqueeze a multi dimensional array @param {Array} array @param {number} dims Required number of dimensions @param {number} dim Current dimension @returns {Array | *} Returns the squeezed array @private
[ "Recursively", "unsqueeze", "a", "multi", "dimensional", "array" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/utils/array.js#L374-L389
5,420
josdejong/mathjs
src/utils/customs.js
getSafeProperty
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
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 + '"') }
[ "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", "+", "'\"'", ")", "}" ]
Get a property of a plain object Throws an error in case the object is not a plain object or the property is not defined on the object itself @param {Object} object @param {string} prop @return {*} Returns the property value when safe
[ "Get", "a", "property", "of", "a", "plain", "object", "Throws", "an", "error", "in", "case", "the", "object", "is", "not", "a", "plain", "object", "or", "the", "property", "is", "not", "defined", "on", "the", "object", "itself" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/utils/customs.js#L13-L24
5,421
josdejong/mathjs
src/utils/customs.js
setSafeProperty
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
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 + '"') }
[ "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", "+", "'\"'", ")", "}" ]
Set a property on a plain object. Throws an error in case the object is not a plain object or the property would override an inherited property like .constructor or .toString @param {Object} object @param {string} prop @param {*} value @return {*} Returns the value TODO: merge this function into access.js?
[ "Set", "a", "property", "on", "a", "plain", "object", ".", "Throws", "an", "error", "in", "case", "the", "object", "is", "not", "a", "plain", "object", "or", "the", "property", "would", "override", "an", "inherited", "property", "like", ".", "constructor", "or", ".", "toString" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/utils/customs.js#L36-L44
5,422
josdejong/mathjs
src/utils/customs.js
isSafeProperty
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
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 }
[ "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", "}" ]
Test whether a property is safe to use for an object. For example .toString and .constructor are not safe @param {string} prop @return {boolean} Returns true when safe
[ "Test", "whether", "a", "property", "is", "safe", "to", "use", "for", "an", "object", ".", "For", "example", ".", "toString", "and", ".", "constructor", "are", "not", "safe" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/utils/customs.js#L52-L78
5,423
josdejong/mathjs
src/function/string/print.js
_print
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
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 } ) }
[ "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", "}", ")", "}" ]
Interpolate values into a string template. @param {string} template @param {Object} values @param {number | Object} [options] @returns {string} Interpolated string @private
[ "Interpolate", "values", "into", "a", "string", "template", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/function/string/print.js#L70-L90
5,424
josdejong/mathjs
bin/cli.js
format
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
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) } } }) }
[ "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", ")", "}", "}", "}", ")", "}" ]
Helper function to format a value. Regular numbers will be rounded to 14 digits to prevent round-off errors from showing up. @param {*} value
[ "Helper", "function", "to", "format", "a", "value", ".", "Regular", "numbers", "will", "be", "rounded", "to", "14", "digits", "to", "prevent", "round", "-", "off", "errors", "from", "showing", "up", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/bin/cli.js#L69-L82
5,425
josdejong/mathjs
bin/cli.js
completer
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
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] }
[ "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", "]", "}" ]
auto complete a text @param {String} text @return {[Array, String]} completions
[ "auto", "complete", "a", "text" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/bin/cli.js#L89-L162
5,426
josdejong/mathjs
bin/cli.js
runStream
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
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) }) }
[ "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", ")", "}", ")", "}" ]
Run stream, read and evaluate input and stream that to output. Text lines read from the input are evaluated, and the results are send to the output. @param input Input stream @param output Output stream @param mode Output mode @param parenthesis Parenthesis option
[ "Run", "stream", "read", "and", "evaluate", "input", "and", "stream", "that", "to", "output", ".", "Text", "lines", "read", "from", "the", "input", "are", "evaluated", "and", "the", "results", "are", "send", "to", "the", "output", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/bin/cli.js#L173-L282
5,427
josdejong/mathjs
bin/cli.js
findSymbolName
function findSymbolName (node) { const math = getMath() let n = node while (n) { if (math.isSymbolNode(n)) { return n.name } n = n.object } return null }
javascript
function findSymbolName (node) { const math = getMath() let n = node while (n) { if (math.isSymbolNode(n)) { return n.name } n = n.object } return null }
[ "function", "findSymbolName", "(", "node", ")", "{", "const", "math", "=", "getMath", "(", ")", "let", "n", "=", "node", "while", "(", "n", ")", "{", "if", "(", "math", ".", "isSymbolNode", "(", "n", ")", ")", "{", "return", "n", ".", "name", "}", "n", "=", "n", ".", "object", "}", "return", "null", "}" ]
Find the symbol name of an AssignmentNode. Recurses into the chain of objects to the root object. @param {AssignmentNode} node @return {string | null} Returns the name when found, else returns null.
[ "Find", "the", "symbol", "name", "of", "an", "AssignmentNode", ".", "Recurses", "into", "the", "chain", "of", "objects", "to", "the", "root", "object", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/bin/cli.js#L290-L302
5,428
josdejong/mathjs
bin/cli.js
outputVersion
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
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) }) }
[ "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", ")", "}", ")", "}" ]
Output application version number. Version number is read version from package.json.
[ "Output", "application", "version", "number", ".", "Version", "number", "is", "read", "version", "from", "package", ".", "json", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/bin/cli.js#L308-L319
5,429
josdejong/mathjs
bin/cli.js
outputHelp
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
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) }
[ "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", ")", "}" ]
Output a help message
[ "Output", "a", "help", "message" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/bin/cli.js#L324-L353
5,430
josdejong/mathjs
src/function/relational/compareNatural.js
compareArrays
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
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 }
[ "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", "}" ]
Compare two Arrays - First, compares value by value - Next, if all corresponding values are equal, look at the length: longest array will be considered largest @param {Array} x @param {Array} y @returns {number} Returns the comparison result: -1, 0, or 1
[ "Compare", "two", "Arrays" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/function/relational/compareNatural.js#L206-L221
5,431
josdejong/mathjs
src/function/relational/compareNatural.js
compareObjects
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
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 }
[ "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", "}" ]
Compare two objects - First, compare sorted property names - Next, compare the property values @param {Object} x @param {Object} y @returns {number} Returns the comparison result: -1, 0, or 1
[ "Compare", "two", "objects" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/function/relational/compareNatural.js#L233-L254
5,432
josdejong/mathjs
tools/docgenerator.js
validateDoc
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
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 }
[ "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", "}" ]
Validate whether all required fields are available in given doc @param {Object} doc @return {String[]} issues
[ "Validate", "whether", "all", "required", "fields", "are", "available", "in", "given", "doc" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/tools/docgenerator.js#L333-L394
5,433
josdejong/mathjs
tools/docgenerator.js
functionEntry
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
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 }
[ "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", "}" ]
Helper function to generate a markdown list entry for a function. Used to generate both alphabetical and categorical index pages. @param {string} name Function name @returns {string} Returns a markdown list entry
[ "Helper", "function", "to", "generate", "a", "markdown", "list", "entry", "for", "a", "function", ".", "Used", "to", "generate", "both", "alphabetical", "and", "categorical", "index", "pages", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/tools/docgenerator.js#L548-L565
5,434
josdejong/mathjs
examples/advanced/custom_argument_parsing.js
integrate
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
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 }
[ "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", "}" ]
Calculate the numeric integration of a function @param {Function} f @param {number} start @param {number} end @param {number} [step=0.01]
[ "Calculate", "the", "numeric", "integration", "of", "a", "function" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/examples/advanced/custom_argument_parsing.js#L20-L27
5,435
josdejong/mathjs
src/expression/transform/map.transform.js
mapTransform
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
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) }
[ "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", ")", "}" ]
Attach a transform function to math.map Adds a property transform containing the transform function. This transform creates a one-based index instead of a zero-based index
[ "Attach", "a", "transform", "function", "to", "math", ".", "map", "Adds", "a", "property", "transform", "containing", "the", "transform", "function", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/expression/transform/map.transform.js#L19-L37
5,436
josdejong/mathjs
src/utils/snapshot.js
exclude
function exclude (object, excludedProperties) { const strippedObject = Object.assign({}, object) excludedProperties.forEach(excludedProperty => { delete strippedObject[excludedProperty] }) return strippedObject }
javascript
function exclude (object, excludedProperties) { const strippedObject = Object.assign({}, object) excludedProperties.forEach(excludedProperty => { delete strippedObject[excludedProperty] }) return strippedObject }
[ "function", "exclude", "(", "object", ",", "excludedProperties", ")", "{", "const", "strippedObject", "=", "Object", ".", "assign", "(", "{", "}", ",", "object", ")", "excludedProperties", ".", "forEach", "(", "excludedProperty", "=>", "{", "delete", "strippedObject", "[", "excludedProperty", "]", "}", ")", "return", "strippedObject", "}" ]
Create a copy of the provided `object` and delete all properties listed in `excludedProperties` @param {Object} object @param {string[]} excludedProperties @return {Object}
[ "Create", "a", "copy", "of", "the", "provided", "object", "and", "delete", "all", "properties", "listed", "in", "excludedProperties" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/utils/snapshot.js#L352-L360
5,437
josdejong/mathjs
src/function/matrix/subset.js
_getSubstring
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
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 }
[ "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", "}" ]
Retrieve a subset of a string @param {string} str string from which to get a substring @param {Index} index An index containing ranges for each dimension @returns {string} substring @private
[ "Retrieve", "a", "subset", "of", "a", "string" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/function/matrix/subset.js#L100-L122
5,438
josdejong/mathjs
src/function/matrix/subset.js
_setSubstring
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
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('') }
[ "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", "(", "''", ")", "}" ]
Replace a substring in a string @param {string} str string to be replaced @param {Index} index An index containing ranges for each dimension @param {string} replacement Replacement string @param {string} [defaultValue] Default value to be uses when resizing the string. is ' ' by default @returns {string} result @private
[ "Replace", "a", "substring", "in", "a", "string" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/function/matrix/subset.js#L134-L182
5,439
josdejong/mathjs
src/function/matrix/subset.js
_getObjectProperty
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
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) }
[ "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", ")", "}" ]
Retrieve a property from an object @param {Object} object @param {Index} index @return {*} Returns the value of the property @private
[ "Retrieve", "a", "property", "from", "an", "object" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/function/matrix/subset.js#L191-L202
5,440
josdejong/mathjs
src/function/matrix/subset.js
_setObjectProperty
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
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 }
[ "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", "}" ]
Set a property on an object @param {Object} object @param {Index} index @param {*} replacement @return {*} Returns the updated object @private
[ "Set", "a", "property", "on", "an", "object" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/function/matrix/subset.js#L212-L227
5,441
josdejong/mathjs
src/function/matrix/apply.js
_switch
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
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 }
[ "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", "}" ]
Transpose a matrix @param {Array} mat @returns {Array} ret @private
[ "Transpose", "a", "matrix" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/function/matrix/apply.js#L105-L118
5,442
josdejong/mathjs
src/function/matrix/concat.js
_concat
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
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) } }
[ "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", ")", "}", "}" ]
Recursively concatenate two matrices. The contents of the matrices is not cloned. @param {Array} a Multi dimensional array @param {Array} b Multi dimensional array @param {number} concatDim The dimension on which to concatenate (zero-based) @param {number} dim The current dim (zero-based) @return {Array} c The concatenated matrix @private
[ "Recursively", "concatenate", "two", "matrices", ".", "The", "contents", "of", "the", "matrices", "is", "not", "cloned", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/function/matrix/concat.js#L121-L137
5,443
josdejong/mathjs
src/expression/transform/filter.transform.js
filterTransform
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
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) }
[ "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", ")", "}" ]
Attach a transform function to math.filter Adds a property transform containing the transform function. This transform adds support for equations as test function for math.filter, so you can do something like 'filter([3, -2, 5], x > 0)'.
[ "Attach", "a", "transform", "function", "to", "math", ".", "filter", "Adds", "a", "property", "transform", "containing", "the", "transform", "function", "." ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/expression/transform/filter.transform.js#L20-L38
5,444
josdejong/mathjs
src/expression/transform/filter.transform.js
_filter
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
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) } }) }
[ "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", ")", "}", "}", ")", "}" ]
Filter values in a callback given a callback function !!! Passes a one-based index !!! @param {Array} x @param {Function} callback @return {Array} Returns the filtered array @private
[ "Filter", "values", "in", "a", "callback", "given", "a", "callback", "function" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/expression/transform/filter.transform.js#L69-L83
5,445
josdejong/mathjs
src/function/arithmetic/subtract.js
checkEqualDimensions
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
function checkEqualDimensions (x, y) { const xsize = x.size() const ysize = y.size() if (xsize.length !== ysize.length) { throw new DimensionError(xsize.length, ysize.length) } }
[ "function", "checkEqualDimensions", "(", "x", ",", "y", ")", "{", "const", "xsize", "=", "x", ".", "size", "(", ")", "const", "ysize", "=", "y", ".", "size", "(", ")", "if", "(", "xsize", ".", "length", "!==", "ysize", ".", "length", ")", "{", "throw", "new", "DimensionError", "(", "xsize", ".", "length", ",", "ysize", ".", "length", ")", "}", "}" ]
Check whether matrix x and y have the same number of dimensions. Throws a DimensionError when dimensions are not equal @param {Matrix} x @param {Matrix} y
[ "Check", "whether", "matrix", "x", "and", "y", "have", "the", "same", "number", "of", "dimensions", ".", "Throws", "a", "DimensionError", "when", "dimensions", "are", "not", "equal" ]
dd830a8892a5c78907a0f2a616df46c90ddd693e
https://github.com/josdejong/mathjs/blob/dd830a8892a5c78907a0f2a616df46c90ddd693e/src/function/arithmetic/subtract.js#L174-L181
5,446
datorama/akita
schematics/src/ng-g/utils/string.js
camelize
function camelize(str) { return str .replace(STRING_CAMELIZE_REGEXP, (_match, _separator, chr) => { return chr ? chr.toUpperCase() : ''; }) .replace(/^([A-Z])/, (match) => match.toLowerCase()); }
javascript
function camelize(str) { return str .replace(STRING_CAMELIZE_REGEXP, (_match, _separator, chr) => { return chr ? chr.toUpperCase() : ''; }) .replace(/^([A-Z])/, (match) => match.toLowerCase()); }
[ "function", "camelize", "(", "str", ")", "{", "return", "str", ".", "replace", "(", "STRING_CAMELIZE_REGEXP", ",", "(", "_match", ",", "_separator", ",", "chr", ")", "=>", "{", "return", "chr", "?", "chr", ".", "toUpperCase", "(", ")", ":", "''", ";", "}", ")", ".", "replace", "(", "/", "^([A-Z])", "/", ",", "(", "match", ")", "=>", "match", ".", "toLowerCase", "(", ")", ")", ";", "}" ]
Returns the lowerCamelCase form of a string. ```javascript camelize('innerHTML'); // 'innerHTML' camelize('action_name'); // 'actionName' camelize('css-class-name'); // 'cssClassName' camelize('my favorite items'); // 'myFavoriteItems' camelize('My Favorite Items'); // 'myFavoriteItems' ```
[ "Returns", "the", "lowerCamelCase", "form", "of", "a", "string", "." ]
fe86f506402b6c511f91245e6b4076c368f653f1
https://github.com/datorama/akita/blob/fe86f506402b6c511f91245e6b4076c368f653f1/schematics/src/ng-g/utils/string.js#L55-L61
5,447
datorama/akita
schematics/src/ng-g/utils/pluralize.js
interpolate
function interpolate(str, args) { return str.replace(/\$(\d{1,2})/g, function (match, index) { return args[index] || ''; }); }
javascript
function interpolate(str, args) { return str.replace(/\$(\d{1,2})/g, function (match, index) { return args[index] || ''; }); }
[ "function", "interpolate", "(", "str", ",", "args", ")", "{", "return", "str", ".", "replace", "(", "/", "\\$(\\d{1,2})", "/", "g", ",", "function", "(", "match", ",", "index", ")", "{", "return", "args", "[", "index", "]", "||", "''", ";", "}", ")", ";", "}" ]
Interpolate a regexp string. @param {string} str @param {Array} args @return {string}
[ "Interpolate", "a", "regexp", "string", "." ]
fe86f506402b6c511f91245e6b4076c368f653f1
https://github.com/datorama/akita/blob/fe86f506402b6c511f91245e6b4076c368f653f1/schematics/src/ng-g/utils/pluralize.js#L66-L70
5,448
datorama/akita
schematics/src/ng-g/utils/pluralize.js
replaceWord
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
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); }; }
[ "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", ")", ";", "}", ";", "}" ]
Replace a word with the updated word. @param {Object} replaceMap @param {Object} keepMap @param {Array} rules @return {Function}
[ "Replace", "a", "word", "with", "the", "updated", "word", "." ]
fe86f506402b6c511f91245e6b4076c368f653f1
https://github.com/datorama/akita/blob/fe86f506402b6c511f91245e6b4076c368f653f1/schematics/src/ng-g/utils/pluralize.js#L117-L132
5,449
datorama/akita
schematics/src/ng-g/utils/pluralize.js
pluralize
function pluralize(word, count, inclusive) { var pluralized = count === 1 ? pluralize.singular(word) : pluralize.plural(word); return (inclusive ? count + ' ' : '') + pluralized; }
javascript
function pluralize(word, count, inclusive) { var pluralized = count === 1 ? pluralize.singular(word) : pluralize.plural(word); return (inclusive ? count + ' ' : '') + pluralized; }
[ "function", "pluralize", "(", "word", ",", "count", ",", "inclusive", ")", "{", "var", "pluralized", "=", "count", "===", "1", "?", "pluralize", ".", "singular", "(", "word", ")", ":", "pluralize", ".", "plural", "(", "word", ")", ";", "return", "(", "inclusive", "?", "count", "+", "' '", ":", "''", ")", "+", "pluralized", ";", "}" ]
Pluralize or singularize a word based on the passed in count. @param {string} word @param {number} count @param {boolean} inclusive @return {string}
[ "Pluralize", "or", "singularize", "a", "word", "based", "on", "the", "passed", "in", "count", "." ]
fe86f506402b6c511f91245e6b4076c368f653f1
https://github.com/datorama/akita/blob/fe86f506402b6c511f91245e6b4076c368f653f1/schematics/src/ng-g/utils/pluralize.js#L154-L158
5,450
datorama/akita
schematics/src/ng-add/utils.js
findNodes
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
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; }
[ "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", ";", "}" ]
Find all nodes from the AST in the subtree of node of SyntaxKind kind. @param node @param kind @param max The maximum number of items to return. @return all nodes of kind, or [] if none is found
[ "Find", "all", "nodes", "from", "the", "AST", "in", "the", "subtree", "of", "node", "of", "SyntaxKind", "kind", "." ]
fe86f506402b6c511f91245e6b4076c368f653f1
https://github.com/datorama/akita/blob/fe86f506402b6c511f91245e6b4076c368f653f1/schematics/src/ng-add/utils.js#L153-L176
5,451
datorama/akita
schematics/src/ng-add/utils.js
getSourceNodes
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
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; }
[ "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", ";", "}" ]
Get all the nodes from a source. @param sourceFile The source file object. @returns {Observable<ts.Node>} An observable of all the nodes in the source.
[ "Get", "all", "the", "nodes", "from", "a", "source", "." ]
fe86f506402b6c511f91245e6b4076c368f653f1
https://github.com/datorama/akita/blob/fe86f506402b6c511f91245e6b4076c368f653f1/schematics/src/ng-add/utils.js#L183-L196
5,452
datorama/akita
schematics/src/ng-add/utils.js
addImportToModule
function addImportToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath); }
javascript
function addImportToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath); }
[ "function", "addImportToModule", "(", "source", ",", "modulePath", ",", "classifiedName", ",", "importPath", ")", "{", "return", "addSymbolToNgModuleMetadata", "(", "source", ",", "modulePath", ",", "'imports'", ",", "classifiedName", ",", "importPath", ")", ";", "}" ]
Custom function to insert an NgModule into NgModule imports. It also imports the module.
[ "Custom", "function", "to", "insert", "an", "NgModule", "into", "NgModule", "imports", ".", "It", "also", "imports", "the", "module", "." ]
fe86f506402b6c511f91245e6b4076c368f653f1
https://github.com/datorama/akita/blob/fe86f506402b6c511f91245e6b4076c368f653f1/schematics/src/ng-add/utils.js#L501-L503
5,453
datorama/akita
schematics/src/ng-add/utils.js
addProviderToModule
function addProviderToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath); }
javascript
function addProviderToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath); }
[ "function", "addProviderToModule", "(", "source", ",", "modulePath", ",", "classifiedName", ",", "importPath", ")", "{", "return", "addSymbolToNgModuleMetadata", "(", "source", ",", "modulePath", ",", "'providers'", ",", "classifiedName", ",", "importPath", ")", ";", "}" ]
Custom function to insert a provider into NgModule. It also imports it.
[ "Custom", "function", "to", "insert", "a", "provider", "into", "NgModule", ".", "It", "also", "imports", "it", "." ]
fe86f506402b6c511f91245e6b4076c368f653f1
https://github.com/datorama/akita/blob/fe86f506402b6c511f91245e6b4076c368f653f1/schematics/src/ng-add/utils.js#L508-L510
5,454
datorama/akita
schematics/src/ng-add/utils.js
addEntryComponentToModule
function addEntryComponentToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'entryComponents', classifiedName, importPath); }
javascript
function addEntryComponentToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'entryComponents', classifiedName, importPath); }
[ "function", "addEntryComponentToModule", "(", "source", ",", "modulePath", ",", "classifiedName", ",", "importPath", ")", "{", "return", "addSymbolToNgModuleMetadata", "(", "source", ",", "modulePath", ",", "'entryComponents'", ",", "classifiedName", ",", "importPath", ")", ";", "}" ]
Custom function to insert an entryComponent into NgModule. It also imports it.
[ "Custom", "function", "to", "insert", "an", "entryComponent", "into", "NgModule", ".", "It", "also", "imports", "it", "." ]
fe86f506402b6c511f91245e6b4076c368f653f1
https://github.com/datorama/akita/blob/fe86f506402b6c511f91245e6b4076c368f653f1/schematics/src/ng-add/utils.js#L529-L531
5,455
datorama/akita
schematics/src/ng-add/utils.js
isImported
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
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; }
[ "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", ";", "}" ]
Determine if an import already exists.
[ "Determine", "if", "an", "import", "already", "exists", "." ]
fe86f506402b6c511f91245e6b4076c368f653f1
https://github.com/datorama/akita/blob/fe86f506402b6c511f91245e6b4076c368f653f1/schematics/src/ng-add/utils.js#L536-L552
5,456
fluent-ffmpeg/node-fluent-ffmpeg
lib/fluent-ffmpeg.js
FfmpegCommand
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
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() {} }; }
[ "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", "(", ")", "{", "}", "}", ";", "}" ]
Create an ffmpeg command Can be called with or without the 'new' operator, and the 'input' parameter may be specified as 'options.source' instead (or passed later with the addInput method). @constructor @param {String|ReadableStream} [input] input file path or readable stream @param {Object} [options] command options @param {Object} [options.logger=<no logging>] logger object with 'error', 'warning', 'info' and 'debug' methods @param {Number} [options.niceness=0] ffmpeg process niceness, ignored on Windows @param {Number} [options.priority=0] alias for `niceness` @param {String} [options.presets="fluent-ffmpeg/lib/presets"] directory to load presets from @param {String} [options.preset="fluent-ffmpeg/lib/presets"] alias for `presets` @param {String} [options.stdoutLines=100] maximum lines of ffmpeg output to keep in memory, use 0 for unlimited @param {Number} [options.timeout=<no timeout>] ffmpeg processing timeout in seconds @param {String|ReadableStream} [options.source=<no input>] alias for the `input` parameter
[ "Create", "an", "ffmpeg", "command" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/fluent-ffmpeg.js#L31-L79
5,457
fluent-ffmpeg/node-fluent-ffmpeg
lib/recipes.js
normalizeTimemarks
function normalizeTimemarks(next) { config.timemarks = config.timemarks.map(function(mark) { return utils.timemarkToSeconds(mark); }).sort(function(a, b) { return a - b; }); next(); }
javascript
function normalizeTimemarks(next) { config.timemarks = config.timemarks.map(function(mark) { return utils.timemarkToSeconds(mark); }).sort(function(a, b) { return a - b; }); next(); }
[ "function", "normalizeTimemarks", "(", "next", ")", "{", "config", ".", "timemarks", "=", "config", ".", "timemarks", ".", "map", "(", "function", "(", "mark", ")", "{", "return", "utils", ".", "timemarkToSeconds", "(", "mark", ")", ";", "}", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", "-", "b", ";", "}", ")", ";", "next", "(", ")", ";", "}" ]
Turn all timemarks into numbers and sort them
[ "Turn", "all", "timemarks", "into", "numbers", "and", "sort", "them" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/recipes.js#L218-L224
5,458
fluent-ffmpeg/node-fluent-ffmpeg
lib/recipes.js
fixPattern
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
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); }
[ "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", ")", ";", "}" ]
Add '_%i' to pattern when requesting multiple screenshots and no variable token is present
[ "Add", "_%i", "to", "pattern", "when", "requesting", "multiple", "screenshots", "and", "no", "variable", "token", "is", "present" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/recipes.js#L227-L240
5,459
fluent-ffmpeg/node-fluent-ffmpeg
lib/capabilities.js
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
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, ''); } }); }
[ "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", ",", "''", ")", ";", "}", "}", ")", ";", "}" ]
Search in the same directory as ffmpeg
[ "Search", "in", "the", "same", "directory", "as", "ffmpeg" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/capabilities.js#L171-L189
5,460
fluent-ffmpeg/node-fluent-ffmpeg
lib/capabilities.js
function(flvtool, cb) { if (flvtool.length) { return cb(null, flvtool); } utils.which('flvmeta', function(err, flvmeta) { cb(err, flvmeta); }); }
javascript
function(flvtool, cb) { if (flvtool.length) { return cb(null, flvtool); } utils.which('flvmeta', function(err, flvmeta) { cb(err, flvmeta); }); }
[ "function", "(", "flvtool", ",", "cb", ")", "{", "if", "(", "flvtool", ".", "length", ")", "{", "return", "cb", "(", "null", ",", "flvtool", ")", ";", "}", "utils", ".", "which", "(", "'flvmeta'", ",", "function", "(", "err", ",", "flvmeta", ")", "{", "cb", "(", "err", ",", "flvmeta", ")", ";", "}", ")", ";", "}" ]
Search for flvmeta in the PATH
[ "Search", "for", "flvmeta", "in", "the", "PATH" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/capabilities.js#L243-L251
5,461
fluent-ffmpeg/node-fluent-ffmpeg
lib/capabilities.js
function(flvtool, cb) { if (flvtool.length) { return cb(null, flvtool); } utils.which('flvtool2', function(err, flvtool2) { cb(err, flvtool2); }); }
javascript
function(flvtool, cb) { if (flvtool.length) { return cb(null, flvtool); } utils.which('flvtool2', function(err, flvtool2) { cb(err, flvtool2); }); }
[ "function", "(", "flvtool", ",", "cb", ")", "{", "if", "(", "flvtool", ".", "length", ")", "{", "return", "cb", "(", "null", ",", "flvtool", ")", ";", "}", "utils", ".", "which", "(", "'flvtool2'", ",", "function", "(", "err", ",", "flvtool2", ")", "{", "cb", "(", "err", ",", "flvtool2", ")", ";", "}", ")", ";", "}" ]
Search for flvtool2 in the PATH
[ "Search", "for", "flvtool2", "in", "the", "PATH" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/capabilities.js#L254-L262
5,462
fluent-ffmpeg/node-fluent-ffmpeg
lib/capabilities.js
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
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(); }
[ "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", "(", ")", ";", "}" ]
Check whether specified formats are available
[ "Check", "whether", "specified", "formats", "are", "available" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/capabilities.js#L572-L614
5,463
fluent-ffmpeg/node-fluent-ffmpeg
lib/capabilities.js
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
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(); }
[ "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", "(", ")", ";", "}" ]
Check whether specified codecs are available and add strict experimental options if needed
[ "Check", "whether", "specified", "codecs", "are", "available", "and", "add", "strict", "experimental", "options", "if", "needed" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/capabilities.js#L622-L662
5,464
fluent-ffmpeg/node-fluent-ffmpeg
lib/utils.js
parseProgressLine
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
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; }
[ "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", ";", "}" ]
Parse progress line from ffmpeg stderr @param {String} line progress line @return progress object @private
[ "Parse", "progress", "line", "from", "ffmpeg", "stderr" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/utils.js#L20-L41
5,465
fluent-ffmpeg/node-fluent-ffmpeg
lib/utils.js
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
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; }
[ "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", ";", "}" ]
Create an argument list Returns a function that adds new arguments to the list. It also has the following methods: - clear() empties the argument list - get() returns the argument list - find(arg, count) finds 'arg' in the list and return the following 'count' items, or undefined if not found - remove(arg, count) remove 'arg' in the list as well as the following 'count' items @private
[ "Create", "an", "argument", "list" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/utils.js#L75-L121
5,466
fluent-ffmpeg/node-fluent-ffmpeg
lib/utils.js
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
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; }); }
[ "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", ";", "}", ")", ";", "}" ]
Generate filter strings @param {String[]|Object[]} filters filter specifications. When using objects, each must have the following properties: @param {String} filters.filter filter name @param {String|Array} [filters.inputs] (array of) input stream specifier(s) for the filter, defaults to ffmpeg automatically choosing the first unused matching streams @param {String|Array} [filters.outputs] (array of) output stream specifier(s) for the filter, defaults to ffmpeg automatically assigning the output to the output file @param {Object|String|Array} [filters.options] filter options, can be omitted to not set any options @return String[] @private
[ "Generate", "filter", "strings" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/utils.js#L138-L203
5,467
fluent-ffmpeg/node-fluent-ffmpeg
lib/utils.js
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
Search for an executable Uses 'which' or 'where' depending on platform @param {String} name executable name @param {Function} callback callback with signature (err, path) @private
[ "Search", "for", "an", "executable" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/utils.js#L215-L227
5,468
fluent-ffmpeg/node-fluent-ffmpeg
lib/utils.js
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
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; }
[ "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", ";", "}" ]
Extract codec data from ffmpeg stderr and emit 'codecData' event if appropriate Call it with an initially empty codec object once with each line of stderr output until it returns true @param {FfmpegCommand} command event emitter @param {String} stderrLine ffmpeg stderr output line @param {Object} codecObject object used to accumulate codec data between calls @return {Boolean} true if codec data is complete (and event was emitted), false otherwise @private
[ "Extract", "codec", "data", "from", "ffmpeg", "stderr", "and", "emit", "codecData", "event", "if", "appropriate", "Call", "it", "with", "an", "initially", "empty", "codec", "object", "once", "with", "each", "line", "of", "stderr", "output", "until", "it", "returns", "true" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/utils.js#L275-L316
5,469
fluent-ffmpeg/node-fluent-ffmpeg
lib/utils.js
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
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); } }
[ "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", ")", ";", "}", "}" ]
Extract progress data from ffmpeg stderr and emit 'progress' event if appropriate @param {FfmpegCommand} command event emitter @param {String} stderrLine ffmpeg stderr data @private
[ "Extract", "progress", "data", "from", "ffmpeg", "stderr", "and", "emit", "progress", "event", "if", "appropriate" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/utils.js#L326-L347
5,470
fluent-ffmpeg/node-fluent-ffmpeg
lib/options/videosize.js
createSizeFilters
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
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); } }
[ "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", ")", ";", "}", "}" ]
Recompute size filters @param {Object} output @param {String} key newly-added parameter name ('size', 'aspect' or 'pad') @param {String} value newly-added parameter value @return filter string array @private
[ "Recompute", "size", "filters" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/options/videosize.js#L68-L147
5,471
fluent-ffmpeg/node-fluent-ffmpeg
lib/processor.js
function(cb) { if (!readMetadata) { return cb(); } self.ffprobe(0, function(err, data) { if (!err) { self._ffprobeData = data; } cb(); }); }
javascript
function(cb) { if (!readMetadata) { return cb(); } self.ffprobe(0, function(err, data) { if (!err) { self._ffprobeData = data; } cb(); }); }
[ "function", "(", "cb", ")", "{", "if", "(", "!", "readMetadata", ")", "{", "return", "cb", "(", ")", ";", "}", "self", ".", "ffprobe", "(", "0", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "!", "err", ")", "{", "self", ".", "_ffprobeData", "=", "data", ";", "}", "cb", "(", ")", ";", "}", ")", ";", "}" ]
Read metadata if required
[ "Read", "metadata", "if", "required" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/processor.js#L302-L314
5,472
fluent-ffmpeg/node-fluent-ffmpeg
lib/processor.js
function(cb) { var args; try { args = self._getArguments(); } catch(e) { return cb(e); } cb(null, args); }
javascript
function(cb) { var args; try { args = self._getArguments(); } catch(e) { return cb(e); } cb(null, args); }
[ "function", "(", "cb", ")", "{", "var", "args", ";", "try", "{", "args", "=", "self", ".", "_getArguments", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "cb", "(", "e", ")", ";", "}", "cb", "(", "null", ",", "args", ")", ";", "}" ]
Build argument list
[ "Build", "argument", "list" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/processor.js#L338-L347
5,473
fluent-ffmpeg/node-fluent-ffmpeg
lib/processor.js
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
Add "-strict experimental" option where needed
[ "Add", "-", "strict", "experimental", "option", "where", "needed" ]
bee107787dcdccd7e4749e062c2601c47870d776
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/blob/bee107787dcdccd7e4749e062c2601c47870d776/lib/processor.js#L350-L365
5,474
mrvautin/adminMongo
monitoring.js
serverMonitoringCleanup
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
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){}); }); }
[ "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", ")", "{", "}", ")", ";", "}", ")", ";", "}" ]
Removes old monitoring data. We only want basic monitoring with the last 100 events. We keep last 80 and remove the rest to be sure.
[ "Removes", "old", "monitoring", "data", ".", "We", "only", "want", "basic", "monitoring", "with", "the", "last", "100", "events", ".", "We", "keep", "last", "80", "and", "remove", "the", "rest", "to", "be", "sure", "." ]
edcef9d12f22298e0ef4e509f88f06ea8967647c
https://github.com/mrvautin/adminMongo/blob/edcef9d12f22298e0ef4e509f88f06ea8967647c/monitoring.js#L5-L29
5,475
adobe-webplatform/Snap.svg
demos/animated-game/js/backbone.js
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
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); }
[ "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", ")", ";", "}" ]
Bind an event to only be triggered a single time. After the first time the callback is invoked, it will be removed.
[ "Bind", "an", "event", "to", "only", "be", "triggered", "a", "single", "time", ".", "After", "the", "first", "time", "the", "callback", "is", "invoked", "it", "will", "be", "removed", "." ]
b242f49e6798ac297a3dad0dfb03c0893e394464
https://github.com/adobe-webplatform/Snap.svg/blob/b242f49e6798ac297a3dad0dfb03c0893e394464/demos/animated-game/js/backbone.js#L90-L99
5,476
adobe-webplatform/Snap.svg
demos/animated-game/js/backbone.js
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
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); }
[ "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", ")", ";", "}" ]
Fetch the model from the server. If the server's representation of the model differs from its current attributes, they will be overridden, triggering a `"change"` event.
[ "Fetch", "the", "model", "from", "the", "server", ".", "If", "the", "server", "s", "representation", "of", "the", "model", "differs", "from", "its", "current", "attributes", "they", "will", "be", "overridden", "triggering", "a", "change", "event", "." ]
b242f49e6798ac297a3dad0dfb03c0893e394464
https://github.com/adobe-webplatform/Snap.svg/blob/b242f49e6798ac297a3dad0dfb03c0893e394464/demos/animated-game/js/backbone.js#L429-L441
5,477
adobe-webplatform/Snap.svg
demos/animated-game/js/backbone.js
function(model, options) { model = this._prepareModel(model, options); this.add(model, _.extend({at: 0}, options)); return model; }
javascript
function(model, options) { model = this._prepareModel(model, options); this.add(model, _.extend({at: 0}, options)); return model; }
[ "function", "(", "model", ",", "options", ")", "{", "model", "=", "this", ".", "_prepareModel", "(", "model", ",", "options", ")", ";", "this", ".", "add", "(", "model", ",", "_", ".", "extend", "(", "{", "at", ":", "0", "}", ",", "options", ")", ")", ";", "return", "model", ";", "}" ]
Add a model to the beginning of the collection.
[ "Add", "a", "model", "to", "the", "beginning", "of", "the", "collection", "." ]
b242f49e6798ac297a3dad0dfb03c0893e394464
https://github.com/adobe-webplatform/Snap.svg/blob/b242f49e6798ac297a3dad0dfb03c0893e394464/demos/animated-game/js/backbone.js#L763-L767
5,478
adobe-webplatform/Snap.svg
demos/animated-game/js/backbone.js
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
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); }
[ "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", ")", ";", "}" ]
Figure out the smallest index at which a model should be inserted so as to maintain order.
[ "Figure", "out", "the", "smallest", "index", "at", "which", "a", "model", "should", "be", "inserted", "so", "as", "to", "maintain", "order", "." ]
b242f49e6798ac297a3dad0dfb03c0893e394464
https://github.com/adobe-webplatform/Snap.svg/blob/b242f49e6798ac297a3dad0dfb03c0893e394464/demos/animated-game/js/backbone.js#L830-L836
5,479
adobe-webplatform/Snap.svg
demos/animated-game/js/backbone.js
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
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]); } }
[ "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", "]", ")", ";", "}", "}" ]
Bind all defined routes to `Backbone.history`. We have to reverse the order of the routes here to support behavior where the most general routes can be defined at the bottom of the route map.
[ "Bind", "all", "defined", "routes", "to", "Backbone", ".", "history", ".", "We", "have", "to", "reverse", "the", "order", "of", "the", "routes", "here", "to", "support", "behavior", "where", "the", "most", "general", "routes", "can", "be", "defined", "at", "the", "bottom", "of", "the", "route", "map", "." ]
b242f49e6798ac297a3dad0dfb03c0893e394464
https://github.com/adobe-webplatform/Snap.svg/blob/b242f49e6798ac297a3dad0dfb03c0893e394464/demos/animated-game/js/backbone.js#L1262-L1269
5,480
adobe-webplatform/Snap.svg
demos/animated-game/js/backbone.js
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
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; } }
[ "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", ";", "}", "}" ]
Update the hash location, either replacing the current entry, or adding a new one to the browser history.
[ "Update", "the", "hash", "location", "either", "replacing", "the", "current", "entry", "or", "adding", "a", "new", "one", "to", "the", "browser", "history", "." ]
b242f49e6798ac297a3dad0dfb03c0893e394464
https://github.com/adobe-webplatform/Snap.svg/blob/b242f49e6798ac297a3dad0dfb03c0893e394464/demos/animated-game/js/backbone.js#L1498-L1506
5,481
t1m0n/air-datepicker
dist/js/datepicker.js
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
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; }
[ "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", ";", "}" ]
Updates datepicker options @param {String|Object} param - parameter's name to update. If object then it will extend current options @param {String|Number|Object} [value] - new param value
[ "Updates", "datepicker", "options" ]
004188d9480e3711c08491d6bb988814314a2b13
https://github.com/t1m0n/air-datepicker/blob/004188d9480e3711c08491d6bb988814314a2b13/dist/js/datepicker.js#L607-L653
5,482
t1m0n/air-datepicker
dist/js/datepicker.js
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
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 }
[ "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", "}" ]
Check if date is between minDate and maxDate @param date {object} - date object @param type {string} - cell type @returns {boolean} @private
[ "Check", "if", "date", "is", "between", "minDate", "and", "maxDate" ]
004188d9480e3711c08491d6bb988814314a2b13
https://github.com/t1m0n/air-datepicker/blob/004188d9480e3711c08491d6bb988814314a2b13/dist/js/datepicker.js#L709-L722
5,483
t1m0n/air-datepicker
dist/js/datepicker.js
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
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; }
[ "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", ";", "}" ]
Calculates days number to render. Generates days html and returns it. @param {object} date - Date object @returns {string} @private
[ "Calculates", "days", "number", "to", "render", ".", "Generates", "days", "html", "and", "returns", "it", "." ]
004188d9480e3711c08491d6bb988814314a2b13
https://github.com/t1m0n/air-datepicker/blob/004188d9480e3711c08491d6bb988814314a2b13/dist/js/datepicker.js#L1643-L1665
5,484
t1m0n/air-datepicker
dist/js/datepicker.js
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
function (date) { var html = '', d = dp.getParsedDate(date), i = 0; while(i < 12) { html += this._getMonthHtml(new Date(d.year, i)); i++ } return html; }
[ "function", "(", "date", ")", "{", "var", "html", "=", "''", ",", "d", "=", "dp", ".", "getParsedDate", "(", "date", ")", ",", "i", "=", "0", ";", "while", "(", "i", "<", "12", ")", "{", "html", "+=", "this", ".", "_getMonthHtml", "(", "new", "Date", "(", "d", ".", "year", ",", "i", ")", ")", ";", "i", "++", "}", "return", "html", ";", "}" ]
Generates months html @param {object} date - date instance @returns {string} @private
[ "Generates", "months", "html" ]
004188d9480e3711c08491d6bb988814314a2b13
https://github.com/t1m0n/air-datepicker/blob/004188d9480e3711c08491d6bb988814314a2b13/dist/js/datepicker.js#L1682-L1693
5,485
t1m0n/air-datepicker
dist/js/datepicker.js
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
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); }
[ "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", ")", ";", "}" ]
Sets minHours, minMinutes etc. from date. If date is not passed, than sets values from options @param [date] {object} - Date object, to get values from @private
[ "Sets", "minHours", "minMinutes", "etc", ".", "from", "date", ".", "If", "date", "is", "not", "passed", "than", "sets", "values", "from", "options" ]
004188d9480e3711c08491d6bb988814314a2b13
https://github.com/t1m0n/air-datepicker/blob/004188d9480e3711c08491d6bb988814314a2b13/dist/js/datepicker.js#L2125-L2136
5,486
t1m0n/air-datepicker
dist/js/datepicker.js
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
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 } }
[ "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", "}", "}" ]
Calculates valid hour value to display in text input and datepicker's body. @param date {Date|Number} - date or hours @param [ampm] {Boolean} - 12 hours mode @returns {{hours: *, dayPeriod: string}} @private
[ "Calculates", "valid", "hour", "value", "to", "display", "in", "text", "input", "and", "datepicker", "s", "body", "." ]
004188d9480e3711c08491d6bb988814314a2b13
https://github.com/t1m0n/air-datepicker/blob/004188d9480e3711c08491d6bb988814314a2b13/dist/js/datepicker.js#L2150-L2183
5,487
kevinchappell/formBuilder
src/demo/js/demo.js
toggleEdit
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
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) }
[ "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", ")", "}" ]
Toggles the edit mode for the demo @return {Boolean} editMode
[ "Toggles", "the", "edit", "mode", "for", "the", "demo" ]
a5028073576002af518aabab93ca48efd5ed8514
https://github.com/kevinchappell/formBuilder/blob/a5028073576002af518aabab93ca48efd5ed8514/src/demo/js/demo.js#L242-L256
5,488
kevinchappell/formBuilder
src/js/form-builder.js
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
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') }
[ "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'", ")", "}" ]
builds the standard formbuilder datastructure for a field definition
[ "builds", "the", "standard", "formbuilder", "datastructure", "for", "a", "field", "definition" ]
a5028073576002af518aabab93ca48efd5ed8514
https://github.com/kevinchappell/formBuilder/blob/a5028073576002af518aabab93ca48efd5ed8514/src/js/form-builder.js#L181-L239
5,489
kevinchappell/formBuilder
src/js/form-builder.js
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
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() }
[ "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", "(", ")", "}" ]
Parse saved XML template data
[ "Parse", "saved", "XML", "template", "data" ]
a5028073576002af518aabab93ca48efd5ed8514
https://github.com/kevinchappell/formBuilder/blob/a5028073576002af518aabab93ca48efd5ed8514/src/js/form-builder.js#L242-L261
5,490
kevinchappell/formBuilder
src/js/form-builder.js
userAttrType
function userAttrType(attr, attrData) { return ( [ ['array', ({ options }) => !!options], [typeof attrData.value, () => true], // string, number, ].find(typeCondition => typeCondition[1](attrData))[0] || 'string' ) }
javascript
function userAttrType(attr, attrData) { return ( [ ['array', ({ options }) => !!options], [typeof attrData.value, () => true], // string, number, ].find(typeCondition => typeCondition[1](attrData))[0] || 'string' ) }
[ "function", "userAttrType", "(", "attr", ",", "attrData", ")", "{", "return", "(", "[", "[", "'array'", ",", "(", "{", "options", "}", ")", "=>", "!", "!", "options", "]", ",", "[", "typeof", "attrData", ".", "value", ",", "(", ")", "=>", "true", "]", ",", "// string, number,", "]", ".", "find", "(", "typeCondition", "=>", "typeCondition", "[", "1", "]", "(", "attrData", ")", ")", "[", "0", "]", "||", "'string'", ")", "}" ]
Detects the type of user defined attribute @param {String} attr attribute name @param {Object} attrData attribute config @return {String} type of user attr
[ "Detects", "the", "type", "of", "user", "defined", "attribute" ]
a5028073576002af518aabab93ca48efd5ed8514
https://github.com/kevinchappell/formBuilder/blob/a5028073576002af518aabab93ca48efd5ed8514/src/js/form-builder.js#L507-L514
5,491
kevinchappell/formBuilder
src/js/form-builder.js
inputUserAttrs
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
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>` }
[ "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", ":", "[", "`", "${", "name", "}", "`", ",", "(", "classname", "||", "className", "||", "''", ")", ".", "trim", "(", ")", "]", ",", "}", "const", "label", "=", "`", "${", "textAttrs", ".", "id", "}", "${", "i18n", "[", "name", "]", "||", "''", "}", "`", "const", "optionInputs", "=", "[", "'checkbox'", ",", "'checkbox-group'", ",", "'radio-group'", "]", "if", "(", "!", "optionInputs", ".", "includes", "(", "textAttrs", ".", "type", ")", ")", "{", "textAttrs", ".", "className", ".", "push", "(", "'form-control'", ")", "}", "textAttrs", "=", "Object", ".", "assign", "(", "{", "}", ",", "attrs", ",", "textAttrs", ")", "const", "textInput", "=", "`", "${", "attrString", "(", "textAttrs", ")", "}", "`", "const", "inputWrap", "=", "`", "${", "textInput", "}", "`", "return", "`", "${", "name", "}", "${", "label", "}", "${", "inputWrap", "}", "`", "}" ]
Text input value for attribute @param {String} name @param {Object} inputAttrs also known as values @return {String} input markup
[ "Text", "input", "value", "for", "attribute" ]
a5028073576002af518aabab93ca48efd5ed8514
https://github.com/kevinchappell/formBuilder/blob/a5028073576002af518aabab93ca48efd5ed8514/src/js/form-builder.js#L562-L582
5,492
kevinchappell/formBuilder
src/js/form-builder.js
selectUserAttrs
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
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>` }
[ "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", ":", "`", "${", "name", "}", "${", "classname", "||", "className", "||", "''", "}", "`", ".", "trim", "(", ")", ",", "}", "if", "(", "multiple", ")", "{", "selectAttrs", ".", "multiple", "=", "true", "}", "const", "label", "=", "`", "${", "selectAttrs", ".", "id", "}", "${", "i18n", "[", "name", "]", "}", "`", "Object", ".", "keys", "(", "restData", ")", ".", "forEach", "(", "function", "(", "attr", ")", "{", "selectAttrs", "[", "attr", "]", "=", "restData", "[", "attr", "]", "}", ")", "const", "select", "=", "m", "(", "'select'", ",", "optis", ",", "selectAttrs", ")", ".", "outerHTML", "const", "inputWrap", "=", "`", "${", "select", "}", "`", "return", "`", "${", "name", "}", "${", "label", "}", "${", "inputWrap", "}", "`", "}" ]
Select input for multiple choice user attributes @todo replace with selectAttr @param {String} name @param {Object} fieldData @return {String} select markup
[ "Select", "input", "for", "multiple", "choice", "user", "attributes" ]
a5028073576002af518aabab93ca48efd5ed8514
https://github.com/kevinchappell/formBuilder/blob/a5028073576002af518aabab93ca48efd5ed8514/src/js/form-builder.js#L591-L624
5,493
kevinchappell/formBuilder
src/js/form-builder.js
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
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 }
[ "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", "(", "`", "${", "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", "}" ]
Select field html, since there may be multiple
[ "Select", "field", "html", "since", "there", "may", "be", "multiple" ]
a5028073576002af518aabab93ca48efd5ed8514
https://github.com/kevinchappell/formBuilder/blob/a5028073576002af518aabab93ca48efd5ed8514/src/js/form-builder.js#L954-L991
5,494
stylelint/stylelint
lib/rules/selector-descendant-combinator-no-non-space/index.js
isActuallyCombinator
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
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; } }
[ "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", ";", "}", "}" ]
Check whether is actually a combinator. @param {Node} combinatorNode The combinator node @returns {boolean} `true` if is actually a combinator.
[ "Check", "whether", "is", "actually", "a", "combinator", "." ]
b35c55f6144d0cb03924498f275cc39c39de3816
https://github.com/stylelint/stylelint/blob/b35c55f6144d0cb03924498f275cc39c39de3816/lib/rules/selector-descendant-combinator-no-non-space/index.js#L97-L154
5,495
stylelint/stylelint
lib/rules/selector-class-pattern/index.js
hasInterpolatingAmpersand
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
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; }
[ "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", ";", "}" ]
An "interpolating ampersand" means an "&" used to interpolate within another simple selector, rather than an "&" that stands on its own as a simple selector
[ "An", "interpolating", "ampersand", "means", "an", "&", "used", "to", "interpolate", "within", "another", "simple", "selector", "rather", "than", "an", "&", "that", "stands", "on", "its", "own", "as", "a", "simple", "selector" ]
b35c55f6144d0cb03924498f275cc39c39de3816
https://github.com/stylelint/stylelint/blob/b35c55f6144d0cb03924498f275cc39c39de3816/lib/rules/selector-class-pattern/index.js#L104-L120
5,496
stylelint/stylelint
lib/rules/function-calc-no-invalid/index.js
verifyMathExpressions
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
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); } }
[ "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", ")", ";", "}", "}" ]
Verify that each operation expression is valid. Reports when a invalid operation expression is found. @param {object} expression expression node. @param {object} node calc function node. @returns {void}
[ "Verify", "that", "each", "operation", "expression", "is", "valid", ".", "Reports", "when", "a", "invalid", "operation", "expression", "is", "found", "." ]
b35c55f6144d0cb03924498f275cc39c39de3816
https://github.com/stylelint/stylelint/blob/b35c55f6144d0cb03924498f275cc39c39de3816/lib/rules/function-calc-no-invalid/index.js#L85-L129
5,497
stylelint/stylelint
lib/rules/functionCommaSpaceChecker.js
getCommaCheckIndex
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
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; }
[ "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", ";", "}" ]
Gets the index of the comma for checking. @param {Node} commaNode The comma node @param {number} nodeIndex The index of the comma node @returns {number} The index of the comma for checking
[ "Gets", "the", "index", "of", "the", "comma", "for", "checking", "." ]
b35c55f6144d0cb03924498f275cc39c39de3816
https://github.com/stylelint/stylelint/blob/b35c55f6144d0cb03924498f275cc39c39de3816/lib/rules/functionCommaSpaceChecker.js#L55-L69
5,498
stylelint/stylelint
lib/rules/max-empty-lines/index.js
isEofNode
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
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(); }
[ "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", "(", ")", ";", "}" ]
Checks whether the given node is the last node of file. @param {Document|null} document the document node with `postcss-html` and `postcss-jsx`. @param {Root} root the root node of css
[ "Checks", "whether", "the", "given", "node", "is", "the", "last", "node", "of", "file", "." ]
b35c55f6144d0cb03924498f275cc39c39de3816
https://github.com/stylelint/stylelint/blob/b35c55f6144d0cb03924498f275cc39c39de3816/lib/rules/max-empty-lines/index.js#L109-L126
5,499
stylelint/stylelint
lib/augmentConfig.js
augmentConfigBasic
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
- Merges config and configOverrides - Makes all paths absolute - Merges extends
[ "-", "Merges", "config", "and", "configOverrides", "-", "Makes", "all", "paths", "absolute", "-", "Merges", "extends" ]
b35c55f6144d0cb03924498f275cc39c39de3816
https://github.com/stylelint/stylelint/blob/b35c55f6144d0cb03924498f275cc39c39de3816/lib/augmentConfig.js#L16-L34