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
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
11,900
whitecolor/ts-node-dev
lib/index.js
start
function start() { console.log( 'Using ts-node version', tsNodeVersion + ', typescript version', tsVersion ) var cmd = nodeArgs.concat(wrapper, script, scriptArgs) var childHookPath = compiler.getChildHookPath() cmd = ['-r', childHookPath].concat(cmd) log.debug('Starting child process %s', cmd.join(' ')) child = fork(cmd[0], cmd.slice(1), { cwd: process.cwd(), env: process.env }) starting = false var compileReqWatcher = filewatcher({ forcePolling: opts.poll }) var currentCompilePath fs.writeFileSync(compiler.getCompileReqFilePath(), '') compileReqWatcher.add(compiler.getCompileReqFilePath()) compileReqWatcher.on('change', function(file) { fs.readFile(file, 'utf-8', function(err, data) { if (err) { log.error('Error reading compile request file', err) return } var split = data.split('\n') var compile = split[0] var compiledPath = split[1] if (currentCompilePath == compiledPath) return currentCompilePath = compiledPath // console.log('compileReqWatcher file change', compile); if (compiledPath) { compiler.compile({ compile: compile, compiledPath: compiledPath }) } }) }) child.on('message', function(message) { if (!message.compiledPath || currentCompilePath === message.compiledPath) return currentCompilePath = message.compiledPath compiler.compile(message) }) child.on('exit', function(code) { log.debug('Child exited with code %s', code) if (!child) return if (!child.respawn) process.exit(code) child = undefined }) if (cfg.respawn) { child.respawn = true } if (compiler.tsConfigPath) { watcher.add(compiler.tsConfigPath) } // Listen for `required` messages and watch the required file. ipc.on(child, 'required', function(m) { var isIgnored = cfg.ignore.some(isPrefixOf(m.required)) || cfg.ignore.some(isRegExpMatch(m.required)) if (!isIgnored && (cfg.deps === -1 || getLevel(m.required) <= cfg.deps)) { watcher.add(m.required) } }) // Upon errors, display a notification and tell the child to exit. ipc.on(child, 'error', function(m) { notify(m.error, m.message, 'error') stop(m.willTerminate) }) compiler.writeReadyFile() }
javascript
function start() { console.log( 'Using ts-node version', tsNodeVersion + ', typescript version', tsVersion ) var cmd = nodeArgs.concat(wrapper, script, scriptArgs) var childHookPath = compiler.getChildHookPath() cmd = ['-r', childHookPath].concat(cmd) log.debug('Starting child process %s', cmd.join(' ')) child = fork(cmd[0], cmd.slice(1), { cwd: process.cwd(), env: process.env }) starting = false var compileReqWatcher = filewatcher({ forcePolling: opts.poll }) var currentCompilePath fs.writeFileSync(compiler.getCompileReqFilePath(), '') compileReqWatcher.add(compiler.getCompileReqFilePath()) compileReqWatcher.on('change', function(file) { fs.readFile(file, 'utf-8', function(err, data) { if (err) { log.error('Error reading compile request file', err) return } var split = data.split('\n') var compile = split[0] var compiledPath = split[1] if (currentCompilePath == compiledPath) return currentCompilePath = compiledPath // console.log('compileReqWatcher file change', compile); if (compiledPath) { compiler.compile({ compile: compile, compiledPath: compiledPath }) } }) }) child.on('message', function(message) { if (!message.compiledPath || currentCompilePath === message.compiledPath) return currentCompilePath = message.compiledPath compiler.compile(message) }) child.on('exit', function(code) { log.debug('Child exited with code %s', code) if (!child) return if (!child.respawn) process.exit(code) child = undefined }) if (cfg.respawn) { child.respawn = true } if (compiler.tsConfigPath) { watcher.add(compiler.tsConfigPath) } // Listen for `required` messages and watch the required file. ipc.on(child, 'required', function(m) { var isIgnored = cfg.ignore.some(isPrefixOf(m.required)) || cfg.ignore.some(isRegExpMatch(m.required)) if (!isIgnored && (cfg.deps === -1 || getLevel(m.required) <= cfg.deps)) { watcher.add(m.required) } }) // Upon errors, display a notification and tell the child to exit. ipc.on(child, 'error', function(m) { notify(m.error, m.message, 'error') stop(m.willTerminate) }) compiler.writeReadyFile() }
[ "function", "start", "(", ")", "{", "console", ".", "log", "(", "'Using ts-node version'", ",", "tsNodeVersion", "+", "', typescript version'", ",", "tsVersion", ")", "var", "cmd", "=", "nodeArgs", ".", "concat", "(", "wrapper", ",", "script", ",", "scriptArgs", ")", "var", "childHookPath", "=", "compiler", ".", "getChildHookPath", "(", ")", "cmd", "=", "[", "'-r'", ",", "childHookPath", "]", ".", "concat", "(", "cmd", ")", "log", ".", "debug", "(", "'Starting child process %s'", ",", "cmd", ".", "join", "(", "' '", ")", ")", "child", "=", "fork", "(", "cmd", "[", "0", "]", ",", "cmd", ".", "slice", "(", "1", ")", ",", "{", "cwd", ":", "process", ".", "cwd", "(", ")", ",", "env", ":", "process", ".", "env", "}", ")", "starting", "=", "false", "var", "compileReqWatcher", "=", "filewatcher", "(", "{", "forcePolling", ":", "opts", ".", "poll", "}", ")", "var", "currentCompilePath", "fs", ".", "writeFileSync", "(", "compiler", ".", "getCompileReqFilePath", "(", ")", ",", "''", ")", "compileReqWatcher", ".", "add", "(", "compiler", ".", "getCompileReqFilePath", "(", ")", ")", "compileReqWatcher", ".", "on", "(", "'change'", ",", "function", "(", "file", ")", "{", "fs", ".", "readFile", "(", "file", ",", "'utf-8'", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "log", ".", "error", "(", "'Error reading compile request file'", ",", "err", ")", "return", "}", "var", "split", "=", "data", ".", "split", "(", "'\\n'", ")", "var", "compile", "=", "split", "[", "0", "]", "var", "compiledPath", "=", "split", "[", "1", "]", "if", "(", "currentCompilePath", "==", "compiledPath", ")", "return", "currentCompilePath", "=", "compiledPath", "// console.log('compileReqWatcher file change', compile);", "if", "(", "compiledPath", ")", "{", "compiler", ".", "compile", "(", "{", "compile", ":", "compile", ",", "compiledPath", ":", "compiledPath", "}", ")", "}", "}", ")", "}", ")", "child", ".", "on", "(", "'message'", ",", "function", "(", "message", ")", "{", "if", "(", "!", "message", ".", "compiledPath", "||", "currentCompilePath", "===", "message", ".", "compiledPath", ")", "return", "currentCompilePath", "=", "message", ".", "compiledPath", "compiler", ".", "compile", "(", "message", ")", "}", ")", "child", ".", "on", "(", "'exit'", ",", "function", "(", "code", ")", "{", "log", ".", "debug", "(", "'Child exited with code %s'", ",", "code", ")", "if", "(", "!", "child", ")", "return", "if", "(", "!", "child", ".", "respawn", ")", "process", ".", "exit", "(", "code", ")", "child", "=", "undefined", "}", ")", "if", "(", "cfg", ".", "respawn", ")", "{", "child", ".", "respawn", "=", "true", "}", "if", "(", "compiler", ".", "tsConfigPath", ")", "{", "watcher", ".", "add", "(", "compiler", ".", "tsConfigPath", ")", "}", "// Listen for `required` messages and watch the required file.", "ipc", ".", "on", "(", "child", ",", "'required'", ",", "function", "(", "m", ")", "{", "var", "isIgnored", "=", "cfg", ".", "ignore", ".", "some", "(", "isPrefixOf", "(", "m", ".", "required", ")", ")", "||", "cfg", ".", "ignore", ".", "some", "(", "isRegExpMatch", "(", "m", ".", "required", ")", ")", "if", "(", "!", "isIgnored", "&&", "(", "cfg", ".", "deps", "===", "-", "1", "||", "getLevel", "(", "m", ".", "required", ")", "<=", "cfg", ".", "deps", ")", ")", "{", "watcher", ".", "add", "(", "m", ".", "required", ")", "}", "}", ")", "// Upon errors, display a notification and tell the child to exit.", "ipc", ".", "on", "(", "child", ",", "'error'", ",", "function", "(", "m", ")", "{", "notify", "(", "m", ".", "error", ",", "m", ".", "message", ",", "'error'", ")", "stop", "(", "m", ".", "willTerminate", ")", "}", ")", "compiler", ".", "writeReadyFile", "(", ")", "}" ]
Run the wrapped script.
[ "Run", "the", "wrapped", "script", "." ]
0f90573b0ee0cf3981ad3017df0848fd7cf192fd
https://github.com/whitecolor/ts-node-dev/blob/0f90573b0ee0cf3981ad3017df0848fd7cf192fd/lib/index.js#L77-L155
11,901
whitecolor/ts-node-dev
lib/index.js
getPrefix
function getPrefix(mod) { var n = 'node_modules' var i = mod.lastIndexOf(n) return ~i ? mod.slice(0, i + n.length) : '' }
javascript
function getPrefix(mod) { var n = 'node_modules' var i = mod.lastIndexOf(n) return ~i ? mod.slice(0, i + n.length) : '' }
[ "function", "getPrefix", "(", "mod", ")", "{", "var", "n", "=", "'node_modules'", "var", "i", "=", "mod", ".", "lastIndexOf", "(", "n", ")", "return", "~", "i", "?", "mod", ".", "slice", "(", "0", ",", "i", "+", "n", ".", "length", ")", ":", "''", "}" ]
Returns the path up to the last occurence of `node_modules` or an empty string if the path does not contain a node_modules dir.
[ "Returns", "the", "path", "up", "to", "the", "last", "occurence", "of", "node_modules", "or", "an", "empty", "string", "if", "the", "path", "does", "not", "contain", "a", "node_modules", "dir", "." ]
0f90573b0ee0cf3981ad3017df0848fd7cf192fd
https://github.com/whitecolor/ts-node-dev/blob/0f90573b0ee0cf3981ad3017df0848fd7cf192fd/lib/index.js#L196-L200
11,902
crossbario/autobahn-js
lib/auth/cra.js
derive_key
function derive_key (secret, salt, iterations, keylen) { var iterations = iterations || 1000; var keylen = keylen || 32; var config = { keySize: keylen / 4, iterations: iterations, hasher: crypto.algo.SHA256 } var key = crypto.PBKDF2(secret, salt, config); return key.toString(crypto.enc.Base64); }
javascript
function derive_key (secret, salt, iterations, keylen) { var iterations = iterations || 1000; var keylen = keylen || 32; var config = { keySize: keylen / 4, iterations: iterations, hasher: crypto.algo.SHA256 } var key = crypto.PBKDF2(secret, salt, config); return key.toString(crypto.enc.Base64); }
[ "function", "derive_key", "(", "secret", ",", "salt", ",", "iterations", ",", "keylen", ")", "{", "var", "iterations", "=", "iterations", "||", "1000", ";", "var", "keylen", "=", "keylen", "||", "32", ";", "var", "config", "=", "{", "keySize", ":", "keylen", "/", "4", ",", "iterations", ":", "iterations", ",", "hasher", ":", "crypto", ".", "algo", ".", "SHA256", "}", "var", "key", "=", "crypto", ".", "PBKDF2", "(", "secret", ",", "salt", ",", "config", ")", ";", "return", "key", ".", "toString", "(", "crypto", ".", "enc", ".", "Base64", ")", ";", "}" ]
PBKDF2-base key derivation function for salted WAMP-CRA
[ "PBKDF2", "-", "base", "key", "derivation", "function", "for", "salted", "WAMP", "-", "CRA" ]
881928f11a9e612b6a9b6ec3176be8c8e49cfea4
https://github.com/crossbario/autobahn-js/blob/881928f11a9e612b6a9b6ec3176be8c8e49cfea4/lib/auth/cra.js#L21-L31
11,903
crossbario/autobahn-js
lib/util.js
function () { // Return an empty object if no arguments are passed if (arguments.length === 0) return {}; var base = arguments[0]; var recursive = false; var len = arguments.length; // Check for recursive mode param if (typeof arguments[len - 1] === 'boolean') { recursive = arguments[len - 1]; len -= 1; // Ignore the last arg } // Merging function used by Array#forEach() var do_merge = function (key) { var val = obj[key]; // Set if unset if (!(key in base)) { base[key] = val; // If the value is an object and we use recursive mode, use defaults on // the value } else if (recursive && typeof val === 'object' && typeof base[key] === 'object') { defaults(base[key], val); } // Otherwise ignore the value }; // Iterate over source objects for (var i=1; i < len; i++) { var obj = arguments[i]; // Ignore falsy values if (!obj) continue; // Require object if (typeof obj !== 'object') { throw new Error('Expected argument at index ' + i + ' to be an object'); } // Merge keys Object.keys(obj).forEach(do_merge); } // Return the mutated base object return base; }
javascript
function () { // Return an empty object if no arguments are passed if (arguments.length === 0) return {}; var base = arguments[0]; var recursive = false; var len = arguments.length; // Check for recursive mode param if (typeof arguments[len - 1] === 'boolean') { recursive = arguments[len - 1]; len -= 1; // Ignore the last arg } // Merging function used by Array#forEach() var do_merge = function (key) { var val = obj[key]; // Set if unset if (!(key in base)) { base[key] = val; // If the value is an object and we use recursive mode, use defaults on // the value } else if (recursive && typeof val === 'object' && typeof base[key] === 'object') { defaults(base[key], val); } // Otherwise ignore the value }; // Iterate over source objects for (var i=1; i < len; i++) { var obj = arguments[i]; // Ignore falsy values if (!obj) continue; // Require object if (typeof obj !== 'object') { throw new Error('Expected argument at index ' + i + ' to be an object'); } // Merge keys Object.keys(obj).forEach(do_merge); } // Return the mutated base object return base; }
[ "function", "(", ")", "{", "// Return an empty object if no arguments are passed", "if", "(", "arguments", ".", "length", "===", "0", ")", "return", "{", "}", ";", "var", "base", "=", "arguments", "[", "0", "]", ";", "var", "recursive", "=", "false", ";", "var", "len", "=", "arguments", ".", "length", ";", "// Check for recursive mode param", "if", "(", "typeof", "arguments", "[", "len", "-", "1", "]", "===", "'boolean'", ")", "{", "recursive", "=", "arguments", "[", "len", "-", "1", "]", ";", "len", "-=", "1", ";", "// Ignore the last arg", "}", "// Merging function used by Array#forEach()", "var", "do_merge", "=", "function", "(", "key", ")", "{", "var", "val", "=", "obj", "[", "key", "]", ";", "// Set if unset", "if", "(", "!", "(", "key", "in", "base", ")", ")", "{", "base", "[", "key", "]", "=", "val", ";", "// If the value is an object and we use recursive mode, use defaults on", "// the value", "}", "else", "if", "(", "recursive", "&&", "typeof", "val", "===", "'object'", "&&", "typeof", "base", "[", "key", "]", "===", "'object'", ")", "{", "defaults", "(", "base", "[", "key", "]", ",", "val", ")", ";", "}", "// Otherwise ignore the value", "}", ";", "// Iterate over source objects", "for", "(", "var", "i", "=", "1", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "obj", "=", "arguments", "[", "i", "]", ";", "// Ignore falsy values", "if", "(", "!", "obj", ")", "continue", ";", "// Require object", "if", "(", "typeof", "obj", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'Expected argument at index '", "+", "i", "+", "' to be an object'", ")", ";", "}", "// Merge keys", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "do_merge", ")", ";", "}", "// Return the mutated base object", "return", "base", ";", "}" ]
Merge a list of objects from left to right For each object passed to the function, add to the previous object the keys that are present in the former but not the latter. If the last argument is a boolean, it sets whether or not to recursively merge objects. This function mutates the first passed object. To avopid this, you can pass a new empty object as the first arg: defaults({}, obj1, obj2, ...) @example defaults({ a: 1 }, { a: 2, b: 2 }, { b: 3, c: 3 }) // { a: 1, b: 2, c: 3 } defaults({ a: { k1: 1 } }, { a: { k2: 2 } }) // { a: { k1: 1 } } defaults({ a: { k1: 1 } }, { a: { k2: 2 } }) // { a: { k1: 1 } } @param {Object} base The object to merge defaults to @param {Object} source[, ...] The default values source @param {Boolean} [recursive] Whether to recurse fro object values* (default: false) @returns {Object} The mutated `base` object
[ "Merge", "a", "list", "of", "objects", "from", "left", "to", "right" ]
881928f11a9e612b6a9b6ec3176be8c8e49cfea4
https://github.com/crossbario/autobahn-js/blob/881928f11a9e612b6a9b6ec3176be8c8e49cfea4/lib/util.js#L216-L265
11,904
crossbario/autobahn-js
lib/util.js
function(handler, error, error_message) { if(typeof handler === 'function') { handler(error, error_message); } else { console.error(error_message || 'Unhandled exception raised: ', error); } }
javascript
function(handler, error, error_message) { if(typeof handler === 'function') { handler(error, error_message); } else { console.error(error_message || 'Unhandled exception raised: ', error); } }
[ "function", "(", "handler", ",", "error", ",", "error_message", ")", "{", "if", "(", "typeof", "handler", "===", "'function'", ")", "{", "handler", "(", "error", ",", "error_message", ")", ";", "}", "else", "{", "console", ".", "error", "(", "error_message", "||", "'Unhandled exception raised: '", ",", "error", ")", ";", "}", "}" ]
If an error handler function is given, it is called with the error instance, otherwise log the error to the console with a possible custom error message prefix. The custom message is passed also the error handler. @param {function} handler - The error handler function. @param {object | Error} error - The error instance. @param {string} [error_message] - The custom error message, optional.
[ "If", "an", "error", "handler", "function", "is", "given", "it", "is", "called", "with", "the", "error", "instance", "otherwise", "log", "the", "error", "to", "the", "console", "with", "a", "possible", "custom", "error", "message", "prefix", ".", "The", "custom", "message", "is", "passed", "also", "the", "error", "handler", "." ]
881928f11a9e612b6a9b6ec3176be8c8e49cfea4
https://github.com/crossbario/autobahn-js/blob/881928f11a9e612b6a9b6ec3176be8c8e49cfea4/lib/util.js#L275-L281
11,905
idyll-lang/idyll
packages/idyll-ast/src/converters/index.js
convertHelper
function convertHelper(jsonElement) { let elementArray = []; if (jsonElement.type === 'textnode') { return jsonElement.value; } else if (jsonElement.type === 'var' || jsonElement.type === 'derived') { elementArray = [jsonElement.type]; elementArray.push([ ['name', ['value', jsonElement.name]], ['value', ['value', jsonElement.value]] ]); elementArray.push([]); } else if (jsonElement.type === 'data') { elementArray = ['data']; elementArray.push([ ['name', ['value', jsonElement.name]], ['source', ['value', jsonElement.source]] ]); elementArray.push([]); } else { elementArray.push(jsonElement.name); let propertiesArray = []; if ('properties' in jsonElement) { Object.keys(jsonElement.properties).forEach(key => { let propertyArray = [key]; propertyArray.push([ jsonElement.properties[key].type, jsonElement.properties[key].value ]); propertiesArray.push(propertyArray); }); } elementArray.push(propertiesArray); if ('children' in jsonElement) { let childArray = []; jsonElement.children.forEach(children => { childArray.push(convertHelper(children)); }); elementArray.push(childArray); } } return elementArray; }
javascript
function convertHelper(jsonElement) { let elementArray = []; if (jsonElement.type === 'textnode') { return jsonElement.value; } else if (jsonElement.type === 'var' || jsonElement.type === 'derived') { elementArray = [jsonElement.type]; elementArray.push([ ['name', ['value', jsonElement.name]], ['value', ['value', jsonElement.value]] ]); elementArray.push([]); } else if (jsonElement.type === 'data') { elementArray = ['data']; elementArray.push([ ['name', ['value', jsonElement.name]], ['source', ['value', jsonElement.source]] ]); elementArray.push([]); } else { elementArray.push(jsonElement.name); let propertiesArray = []; if ('properties' in jsonElement) { Object.keys(jsonElement.properties).forEach(key => { let propertyArray = [key]; propertyArray.push([ jsonElement.properties[key].type, jsonElement.properties[key].value ]); propertiesArray.push(propertyArray); }); } elementArray.push(propertiesArray); if ('children' in jsonElement) { let childArray = []; jsonElement.children.forEach(children => { childArray.push(convertHelper(children)); }); elementArray.push(childArray); } } return elementArray; }
[ "function", "convertHelper", "(", "jsonElement", ")", "{", "let", "elementArray", "=", "[", "]", ";", "if", "(", "jsonElement", ".", "type", "===", "'textnode'", ")", "{", "return", "jsonElement", ".", "value", ";", "}", "else", "if", "(", "jsonElement", ".", "type", "===", "'var'", "||", "jsonElement", ".", "type", "===", "'derived'", ")", "{", "elementArray", "=", "[", "jsonElement", ".", "type", "]", ";", "elementArray", ".", "push", "(", "[", "[", "'name'", ",", "[", "'value'", ",", "jsonElement", ".", "name", "]", "]", ",", "[", "'value'", ",", "[", "'value'", ",", "jsonElement", ".", "value", "]", "]", "]", ")", ";", "elementArray", ".", "push", "(", "[", "]", ")", ";", "}", "else", "if", "(", "jsonElement", ".", "type", "===", "'data'", ")", "{", "elementArray", "=", "[", "'data'", "]", ";", "elementArray", ".", "push", "(", "[", "[", "'name'", ",", "[", "'value'", ",", "jsonElement", ".", "name", "]", "]", ",", "[", "'source'", ",", "[", "'value'", ",", "jsonElement", ".", "source", "]", "]", "]", ")", ";", "elementArray", ".", "push", "(", "[", "]", ")", ";", "}", "else", "{", "elementArray", ".", "push", "(", "jsonElement", ".", "name", ")", ";", "let", "propertiesArray", "=", "[", "]", ";", "if", "(", "'properties'", "in", "jsonElement", ")", "{", "Object", ".", "keys", "(", "jsonElement", ".", "properties", ")", ".", "forEach", "(", "key", "=>", "{", "let", "propertyArray", "=", "[", "key", "]", ";", "propertyArray", ".", "push", "(", "[", "jsonElement", ".", "properties", "[", "key", "]", ".", "type", ",", "jsonElement", ".", "properties", "[", "key", "]", ".", "value", "]", ")", ";", "propertiesArray", ".", "push", "(", "propertyArray", ")", ";", "}", ")", ";", "}", "elementArray", ".", "push", "(", "propertiesArray", ")", ";", "if", "(", "'children'", "in", "jsonElement", ")", "{", "let", "childArray", "=", "[", "]", ";", "jsonElement", ".", "children", ".", "forEach", "(", "children", "=>", "{", "childArray", ".", "push", "(", "convertHelper", "(", "children", ")", ")", ";", "}", ")", ";", "elementArray", ".", "push", "(", "childArray", ")", ";", "}", "}", "return", "elementArray", ";", "}" ]
Helper function for convert @param {*} jsonElement @return array representation of the corresponding jsonElement
[ "Helper", "function", "for", "convert" ]
19bb5a19238ba56a5a77d158372eb41ddd04189a
https://github.com/idyll-lang/idyll/blob/19bb5a19238ba56a5a77d158372eb41ddd04189a/packages/idyll-ast/src/converters/index.js#L26-L67
11,906
idyll-lang/idyll
packages/idyll-ast/src/converters/index.js
inverseConvertHelper
function inverseConvertHelper(arrayElement, id) { let elementJson = new Object(); elementJson.id = ++id; if (typeof arrayElement === 'string') { elementJson.type = 'textnode'; elementJson.value = arrayElement; } else if (['var', 'derived', 'data', 'meta'].indexOf(arrayElement[0]) > -1) { elementJson.type = arrayElement[0]; elementJson.properties = {}; arrayElement[1].forEach(property => { elementJson.properties[property[0]] = { type: property[1][0], value: property[1][1] }; }); } else { elementJson.type = 'component'; elementJson.name = arrayElement[0]; if (arrayElement[1].length !== 0) { elementJson.properties = {}; arrayElement[1].forEach(property => { elementJson.properties[property[0]] = { type: property[1][0], value: property[1][1] }; }); } if (arrayElement[2]) { let children = []; arrayElement[2].forEach(element => { let childData = inverseConvertHelper(element, id); id = childData.id; children.push(childData.data); }); elementJson.children = children; } } let result = new Object(); result.id = id; result.data = elementJson; return result; }
javascript
function inverseConvertHelper(arrayElement, id) { let elementJson = new Object(); elementJson.id = ++id; if (typeof arrayElement === 'string') { elementJson.type = 'textnode'; elementJson.value = arrayElement; } else if (['var', 'derived', 'data', 'meta'].indexOf(arrayElement[0]) > -1) { elementJson.type = arrayElement[0]; elementJson.properties = {}; arrayElement[1].forEach(property => { elementJson.properties[property[0]] = { type: property[1][0], value: property[1][1] }; }); } else { elementJson.type = 'component'; elementJson.name = arrayElement[0]; if (arrayElement[1].length !== 0) { elementJson.properties = {}; arrayElement[1].forEach(property => { elementJson.properties[property[0]] = { type: property[1][0], value: property[1][1] }; }); } if (arrayElement[2]) { let children = []; arrayElement[2].forEach(element => { let childData = inverseConvertHelper(element, id); id = childData.id; children.push(childData.data); }); elementJson.children = children; } } let result = new Object(); result.id = id; result.data = elementJson; return result; }
[ "function", "inverseConvertHelper", "(", "arrayElement", ",", "id", ")", "{", "let", "elementJson", "=", "new", "Object", "(", ")", ";", "elementJson", ".", "id", "=", "++", "id", ";", "if", "(", "typeof", "arrayElement", "===", "'string'", ")", "{", "elementJson", ".", "type", "=", "'textnode'", ";", "elementJson", ".", "value", "=", "arrayElement", ";", "}", "else", "if", "(", "[", "'var'", ",", "'derived'", ",", "'data'", ",", "'meta'", "]", ".", "indexOf", "(", "arrayElement", "[", "0", "]", ")", ">", "-", "1", ")", "{", "elementJson", ".", "type", "=", "arrayElement", "[", "0", "]", ";", "elementJson", ".", "properties", "=", "{", "}", ";", "arrayElement", "[", "1", "]", ".", "forEach", "(", "property", "=>", "{", "elementJson", ".", "properties", "[", "property", "[", "0", "]", "]", "=", "{", "type", ":", "property", "[", "1", "]", "[", "0", "]", ",", "value", ":", "property", "[", "1", "]", "[", "1", "]", "}", ";", "}", ")", ";", "}", "else", "{", "elementJson", ".", "type", "=", "'component'", ";", "elementJson", ".", "name", "=", "arrayElement", "[", "0", "]", ";", "if", "(", "arrayElement", "[", "1", "]", ".", "length", "!==", "0", ")", "{", "elementJson", ".", "properties", "=", "{", "}", ";", "arrayElement", "[", "1", "]", ".", "forEach", "(", "property", "=>", "{", "elementJson", ".", "properties", "[", "property", "[", "0", "]", "]", "=", "{", "type", ":", "property", "[", "1", "]", "[", "0", "]", ",", "value", ":", "property", "[", "1", "]", "[", "1", "]", "}", ";", "}", ")", ";", "}", "if", "(", "arrayElement", "[", "2", "]", ")", "{", "let", "children", "=", "[", "]", ";", "arrayElement", "[", "2", "]", ".", "forEach", "(", "element", "=>", "{", "let", "childData", "=", "inverseConvertHelper", "(", "element", ",", "id", ")", ";", "id", "=", "childData", ".", "id", ";", "children", ".", "push", "(", "childData", ".", "data", ")", ";", "}", ")", ";", "elementJson", ".", "children", "=", "children", ";", "}", "}", "let", "result", "=", "new", "Object", "(", ")", ";", "result", ".", "id", "=", "id", ";", "result", ".", "data", "=", "elementJson", ";", "return", "result", ";", "}" ]
Helper function for inverseConvert @param {*} arrayElement @return JSON representation of the corresponding arrayElement
[ "Helper", "function", "for", "inverseConvert" ]
19bb5a19238ba56a5a77d158372eb41ddd04189a
https://github.com/idyll-lang/idyll/blob/19bb5a19238ba56a5a77d158372eb41ddd04189a/packages/idyll-ast/src/converters/index.js#L95-L137
11,907
idyll-lang/idyll
packages/idyll-ast/src/index.js
walkNodesHelper
function walkNodesHelper(astArray, f) { (astArray || []).forEach(node => { let children = getChildren(node); if (children.length > 0) { walkNodesHelper(children, f); } f(node); }); }
javascript
function walkNodesHelper(astArray, f) { (astArray || []).forEach(node => { let children = getChildren(node); if (children.length > 0) { walkNodesHelper(children, f); } f(node); }); }
[ "function", "walkNodesHelper", "(", "astArray", ",", "f", ")", "{", "(", "astArray", "||", "[", "]", ")", ".", "forEach", "(", "node", "=>", "{", "let", "children", "=", "getChildren", "(", "node", ")", ";", "if", "(", "children", ".", "length", ">", "0", ")", "{", "walkNodesHelper", "(", "children", ",", "f", ")", ";", "}", "f", "(", "node", ")", ";", "}", ")", ";", "}" ]
Helper function for walkNodes
[ "Helper", "function", "for", "walkNodes" ]
19bb5a19238ba56a5a77d158372eb41ddd04189a
https://github.com/idyll-lang/idyll/blob/19bb5a19238ba56a5a77d158372eb41ddd04189a/packages/idyll-ast/src/index.js#L704-L712
11,908
idyll-lang/idyll
packages/idyll-ast/src/index.js
walkNodesBreadthFirstHelper
function walkNodesBreadthFirstHelper(ast, f) { let childAst = []; (ast || []).forEach(node => { f(node); childAst = childAst.concat(getChildren(node)); }); if (childAst.length > 0) { walkNodesBreadthFirstHelper(childAst, f); } }
javascript
function walkNodesBreadthFirstHelper(ast, f) { let childAst = []; (ast || []).forEach(node => { f(node); childAst = childAst.concat(getChildren(node)); }); if (childAst.length > 0) { walkNodesBreadthFirstHelper(childAst, f); } }
[ "function", "walkNodesBreadthFirstHelper", "(", "ast", ",", "f", ")", "{", "let", "childAst", "=", "[", "]", ";", "(", "ast", "||", "[", "]", ")", ".", "forEach", "(", "node", "=>", "{", "f", "(", "node", ")", ";", "childAst", "=", "childAst", ".", "concat", "(", "getChildren", "(", "node", ")", ")", ";", "}", ")", ";", "if", "(", "childAst", ".", "length", ">", "0", ")", "{", "walkNodesBreadthFirstHelper", "(", "childAst", ",", "f", ")", ";", "}", "}" ]
Helper function for walkNodeBreadthFirst
[ "Helper", "function", "for", "walkNodeBreadthFirst" ]
19bb5a19238ba56a5a77d158372eb41ddd04189a
https://github.com/idyll-lang/idyll/blob/19bb5a19238ba56a5a77d158372eb41ddd04189a/packages/idyll-ast/src/index.js#L728-L737
11,909
idyll-lang/idyll
packages/idyll-compiler/src/processors/post.js
autoLinkifyHelper
function autoLinkifyHelper(node) { if (typeof node === 'string') { return hyperLinkifiedVersion(node); } else if ( ['a', 'code', 'pre', 'equation'].indexOf(getNodeName(node).toLowerCase()) > -1 ) { return node; } else { return modifyChildren(node, autoLinkifyHelper); } }
javascript
function autoLinkifyHelper(node) { if (typeof node === 'string') { return hyperLinkifiedVersion(node); } else if ( ['a', 'code', 'pre', 'equation'].indexOf(getNodeName(node).toLowerCase()) > -1 ) { return node; } else { return modifyChildren(node, autoLinkifyHelper); } }
[ "function", "autoLinkifyHelper", "(", "node", ")", "{", "if", "(", "typeof", "node", "===", "'string'", ")", "{", "return", "hyperLinkifiedVersion", "(", "node", ")", ";", "}", "else", "if", "(", "[", "'a'", ",", "'code'", ",", "'pre'", ",", "'equation'", "]", ".", "indexOf", "(", "getNodeName", "(", "node", ")", ".", "toLowerCase", "(", ")", ")", ">", "-", "1", ")", "{", "return", "node", ";", "}", "else", "{", "return", "modifyChildren", "(", "node", ",", "autoLinkifyHelper", ")", ";", "}", "}" ]
Helper function for autoLinkify to check the type of node and modify them if necessary. @param {*} node node to be checked and modified if necessary. @return modified node, if modification was required, else returns node.
[ "Helper", "function", "for", "autoLinkify", "to", "check", "the", "type", "of", "node", "and", "modify", "them", "if", "necessary", "." ]
19bb5a19238ba56a5a77d158372eb41ddd04189a
https://github.com/idyll-lang/idyll/blob/19bb5a19238ba56a5a77d158372eb41ddd04189a/packages/idyll-compiler/src/processors/post.js#L184-L195
11,910
idyll-lang/idyll
packages/idyll-compiler/src/processors/post.js
hyperLinkifiedVersion
function hyperLinkifiedVersion(node) { let hyperLinks = getHyperLinksFromText(node); if (hyperLinks) { return seperateTextAndHyperLink(node, hyperLinks); } else { return node; } }
javascript
function hyperLinkifiedVersion(node) { let hyperLinks = getHyperLinksFromText(node); if (hyperLinks) { return seperateTextAndHyperLink(node, hyperLinks); } else { return node; } }
[ "function", "hyperLinkifiedVersion", "(", "node", ")", "{", "let", "hyperLinks", "=", "getHyperLinksFromText", "(", "node", ")", ";", "if", "(", "hyperLinks", ")", "{", "return", "seperateTextAndHyperLink", "(", "node", ",", "hyperLinks", ")", ";", "}", "else", "{", "return", "node", ";", "}", "}" ]
Helper function for autoLinkifyHelper that modfies the text node if any hyperlinks are present. @param {*} node @return a modified node if any hyperlinks are present in the node, else returns node
[ "Helper", "function", "for", "autoLinkifyHelper", "that", "modfies", "the", "text", "node", "if", "any", "hyperlinks", "are", "present", "." ]
19bb5a19238ba56a5a77d158372eb41ddd04189a
https://github.com/idyll-lang/idyll/blob/19bb5a19238ba56a5a77d158372eb41ddd04189a/packages/idyll-compiler/src/processors/post.js#L202-L209
11,911
idyll-lang/idyll
packages/idyll-compiler/src/processors/post.js
seperateTextAndHyperLink
function seperateTextAndHyperLink(textnode, hyperlinks) { let match; let hyperLinkIndex = 0; let substringIndex = 0; let newChildNodes = []; while (hyperLinkIndex < hyperlinks.length) { let regexURL = new RegExp(hyperlinks[hyperLinkIndex], 'g'); match = regexURL.exec(textnode.substring(substringIndex)); if (match) { let linkEndIndex = regexURL.lastIndex; let linkStartIndex = linkEndIndex - hyperlinks[hyperLinkIndex].length; let textNodeValue = textnode.substring(substringIndex, linkStartIndex); if (textNodeValue !== '') { newChildNodes.push( createTextNode(textnode.substring(substringIndex, linkStartIndex)) ); } let anchorElement = createNode('a', [], [hyperlinks[hyperLinkIndex]]); setProperty(anchorElement, 'href', hyperlinks[hyperLinkIndex]); newChildNodes.push(anchorElement); textnode = textnode.substring(linkEndIndex); substringIndex = 0; } hyperLinkIndex++; } if (textnode != '') { newChildNodes.push(createTextNode(textnode)); } return createNode('span', [], newChildNodes); }
javascript
function seperateTextAndHyperLink(textnode, hyperlinks) { let match; let hyperLinkIndex = 0; let substringIndex = 0; let newChildNodes = []; while (hyperLinkIndex < hyperlinks.length) { let regexURL = new RegExp(hyperlinks[hyperLinkIndex], 'g'); match = regexURL.exec(textnode.substring(substringIndex)); if (match) { let linkEndIndex = regexURL.lastIndex; let linkStartIndex = linkEndIndex - hyperlinks[hyperLinkIndex].length; let textNodeValue = textnode.substring(substringIndex, linkStartIndex); if (textNodeValue !== '') { newChildNodes.push( createTextNode(textnode.substring(substringIndex, linkStartIndex)) ); } let anchorElement = createNode('a', [], [hyperlinks[hyperLinkIndex]]); setProperty(anchorElement, 'href', hyperlinks[hyperLinkIndex]); newChildNodes.push(anchorElement); textnode = textnode.substring(linkEndIndex); substringIndex = 0; } hyperLinkIndex++; } if (textnode != '') { newChildNodes.push(createTextNode(textnode)); } return createNode('span', [], newChildNodes); }
[ "function", "seperateTextAndHyperLink", "(", "textnode", ",", "hyperlinks", ")", "{", "let", "match", ";", "let", "hyperLinkIndex", "=", "0", ";", "let", "substringIndex", "=", "0", ";", "let", "newChildNodes", "=", "[", "]", ";", "while", "(", "hyperLinkIndex", "<", "hyperlinks", ".", "length", ")", "{", "let", "regexURL", "=", "new", "RegExp", "(", "hyperlinks", "[", "hyperLinkIndex", "]", ",", "'g'", ")", ";", "match", "=", "regexURL", ".", "exec", "(", "textnode", ".", "substring", "(", "substringIndex", ")", ")", ";", "if", "(", "match", ")", "{", "let", "linkEndIndex", "=", "regexURL", ".", "lastIndex", ";", "let", "linkStartIndex", "=", "linkEndIndex", "-", "hyperlinks", "[", "hyperLinkIndex", "]", ".", "length", ";", "let", "textNodeValue", "=", "textnode", ".", "substring", "(", "substringIndex", ",", "linkStartIndex", ")", ";", "if", "(", "textNodeValue", "!==", "''", ")", "{", "newChildNodes", ".", "push", "(", "createTextNode", "(", "textnode", ".", "substring", "(", "substringIndex", ",", "linkStartIndex", ")", ")", ")", ";", "}", "let", "anchorElement", "=", "createNode", "(", "'a'", ",", "[", "]", ",", "[", "hyperlinks", "[", "hyperLinkIndex", "]", "]", ")", ";", "setProperty", "(", "anchorElement", ",", "'href'", ",", "hyperlinks", "[", "hyperLinkIndex", "]", ")", ";", "newChildNodes", ".", "push", "(", "anchorElement", ")", ";", "textnode", "=", "textnode", ".", "substring", "(", "linkEndIndex", ")", ";", "substringIndex", "=", "0", ";", "}", "hyperLinkIndex", "++", ";", "}", "if", "(", "textnode", "!=", "''", ")", "{", "newChildNodes", ".", "push", "(", "createTextNode", "(", "textnode", ")", ")", ";", "}", "return", "createNode", "(", "'span'", ",", "[", "]", ",", "newChildNodes", ")", ";", "}" ]
Helper function that seperates hyperlinks from textnodes @param {*} textnode @param {*} hyperlinks Hyperlink array that has all the hyperlinks occuring in the textnode in order of appearance. @return a new span element encampassing all the new textnodes and anchor tag.
[ "Helper", "function", "that", "seperates", "hyperlinks", "from", "textnodes" ]
19bb5a19238ba56a5a77d158372eb41ddd04189a
https://github.com/idyll-lang/idyll/blob/19bb5a19238ba56a5a77d158372eb41ddd04189a/packages/idyll-compiler/src/processors/post.js#L217-L246
11,912
MurhafSousli/ngx-sharebuttons
.config/styles.js
processCss
function processCss(cssData) { var CSS_PROCESSORS = [stripInlineComments, autoprefixer, cssnano]; var process$ = postcss(CSS_PROCESSORS).process(cssData.toString('utf8')); return rxjs_1.from(process$); }
javascript
function processCss(cssData) { var CSS_PROCESSORS = [stripInlineComments, autoprefixer, cssnano]; var process$ = postcss(CSS_PROCESSORS).process(cssData.toString('utf8')); return rxjs_1.from(process$); }
[ "function", "processCss", "(", "cssData", ")", "{", "var", "CSS_PROCESSORS", "=", "[", "stripInlineComments", ",", "autoprefixer", ",", "cssnano", "]", ";", "var", "process$", "=", "postcss", "(", "CSS_PROCESSORS", ")", ".", "process", "(", "cssData", ".", "toString", "(", "'utf8'", ")", ")", ";", "return", "rxjs_1", ".", "from", "(", "process$", ")", ";", "}" ]
Process CSS file
[ "Process", "CSS", "file" ]
b072e51264a9d45381800d75d80c6d9f42180aa5
https://github.com/MurhafSousli/ngx-sharebuttons/blob/b072e51264a9d45381800d75d80c6d9f42180aa5/.config/styles.js#L18-L22
11,913
MurhafSousli/ngx-sharebuttons
.config/styles.js
createCssFile
function createCssFile(target, cssContent) { var cssData = Buffer.from(cssContent); var writeFile$ = rxjs_1.bindNodeCallback(fs_1.writeFile); // Write css file to dist return writeFile$(target, cssData); }
javascript
function createCssFile(target, cssContent) { var cssData = Buffer.from(cssContent); var writeFile$ = rxjs_1.bindNodeCallback(fs_1.writeFile); // Write css file to dist return writeFile$(target, cssData); }
[ "function", "createCssFile", "(", "target", ",", "cssContent", ")", "{", "var", "cssData", "=", "Buffer", ".", "from", "(", "cssContent", ")", ";", "var", "writeFile$", "=", "rxjs_1", ".", "bindNodeCallback", "(", "fs_1", ".", "writeFile", ")", ";", "// Write css file to dist", "return", "writeFile$", "(", "target", ",", "cssData", ")", ";", "}" ]
Create css file and save it to dist
[ "Create", "css", "file", "and", "save", "it", "to", "dist" ]
b072e51264a9d45381800d75d80c6d9f42180aa5
https://github.com/MurhafSousli/ngx-sharebuttons/blob/b072e51264a9d45381800d75d80c6d9f42180aa5/.config/styles.js#L24-L29
11,914
MurhafSousli/ngx-sharebuttons
.config/utils.js
readFiles
function readFiles(filePath, fileType, callback) { if (path_1.extname(filePath) === fileType) { callback(filePath); } else if (fs_1.lstatSync(filePath).isDirectory()) { // src is directory var filesOrDirectories = fs_1.readdirSync(filePath); filesOrDirectories.map(function (fileName) { var fileOrDirectory = path_1.join(filePath, fileName); readFiles(fileOrDirectory, fileType, callback); }); } }
javascript
function readFiles(filePath, fileType, callback) { if (path_1.extname(filePath) === fileType) { callback(filePath); } else if (fs_1.lstatSync(filePath).isDirectory()) { // src is directory var filesOrDirectories = fs_1.readdirSync(filePath); filesOrDirectories.map(function (fileName) { var fileOrDirectory = path_1.join(filePath, fileName); readFiles(fileOrDirectory, fileType, callback); }); } }
[ "function", "readFiles", "(", "filePath", ",", "fileType", ",", "callback", ")", "{", "if", "(", "path_1", ".", "extname", "(", "filePath", ")", "===", "fileType", ")", "{", "callback", "(", "filePath", ")", ";", "}", "else", "if", "(", "fs_1", ".", "lstatSync", "(", "filePath", ")", ".", "isDirectory", "(", ")", ")", "{", "// src is directory", "var", "filesOrDirectories", "=", "fs_1", ".", "readdirSync", "(", "filePath", ")", ";", "filesOrDirectories", ".", "map", "(", "function", "(", "fileName", ")", "{", "var", "fileOrDirectory", "=", "path_1", ".", "join", "(", "filePath", ",", "fileName", ")", ";", "readFiles", "(", "fileOrDirectory", ",", "fileType", ",", "callback", ")", ";", "}", ")", ";", "}", "}" ]
Loop over all files from directory and sub-directories
[ "Loop", "over", "all", "files", "from", "directory", "and", "sub", "-", "directories" ]
b072e51264a9d45381800d75d80c6d9f42180aa5
https://github.com/MurhafSousli/ngx-sharebuttons/blob/b072e51264a9d45381800d75d80c6d9f42180aa5/.config/utils.js#L21-L33
11,915
MurhafSousli/ngx-sharebuttons
.config/utils.js
dirMaker
function dirMaker(target) { // check if parent directory exists var parentDir = path_1.dirname(target); if (!fs_1.existsSync(parentDir)) { dirMaker(parentDir); } // check if directory exists if (!fs_1.existsSync(target)) { fs_1.mkdirSync(target); } }
javascript
function dirMaker(target) { // check if parent directory exists var parentDir = path_1.dirname(target); if (!fs_1.existsSync(parentDir)) { dirMaker(parentDir); } // check if directory exists if (!fs_1.existsSync(target)) { fs_1.mkdirSync(target); } }
[ "function", "dirMaker", "(", "target", ")", "{", "// check if parent directory exists", "var", "parentDir", "=", "path_1", ".", "dirname", "(", "target", ")", ";", "if", "(", "!", "fs_1", ".", "existsSync", "(", "parentDir", ")", ")", "{", "dirMaker", "(", "parentDir", ")", ";", "}", "// check if directory exists", "if", "(", "!", "fs_1", ".", "existsSync", "(", "target", ")", ")", "{", "fs_1", ".", "mkdirSync", "(", "target", ")", ";", "}", "}" ]
Creates directories recursively
[ "Creates", "directories", "recursively" ]
b072e51264a9d45381800d75d80c6d9f42180aa5
https://github.com/MurhafSousli/ngx-sharebuttons/blob/b072e51264a9d45381800d75d80c6d9f42180aa5/.config/utils.js#L36-L46
11,916
MurhafSousli/ngx-sharebuttons
docs/core/js/search/search.js
handleUpdate
function handleUpdate(item) { var q = item.val(); if (q.length == 0) { closeSearch(); window.location.href = window.location.href.replace(window.location.search, ''); } else { launchSearch(q); } }
javascript
function handleUpdate(item) { var q = item.val(); if (q.length == 0) { closeSearch(); window.location.href = window.location.href.replace(window.location.search, ''); } else { launchSearch(q); } }
[ "function", "handleUpdate", "(", "item", ")", "{", "var", "q", "=", "item", ".", "val", "(", ")", ";", "if", "(", "q", ".", "length", "==", "0", ")", "{", "closeSearch", "(", ")", ";", "window", ".", "location", ".", "href", "=", "window", ".", "location", ".", "href", ".", "replace", "(", "window", ".", "location", ".", "search", ",", "''", ")", ";", "}", "else", "{", "launchSearch", "(", "q", ")", ";", "}", "}" ]
Launch query based on input content
[ "Launch", "query", "based", "on", "input", "content" ]
b072e51264a9d45381800d75d80c6d9f42180aa5
https://github.com/MurhafSousli/ngx-sharebuttons/blob/b072e51264a9d45381800d75d80c6d9f42180aa5/docs/core/js/search/search.js#L164-L173
11,917
dmitrizzle/chat-bubble
component/Bubbles.js
function(q, callback) { var start = function() { setTimeout(function() { callback() }, animationTime) } var position = 0 for ( var nextCallback = position + q.length - 1; nextCallback >= position; nextCallback-- ) { ;(function(callback, index) { start = function() { addBubble(q[index], callback) } })(start, nextCallback) } start() }
javascript
function(q, callback) { var start = function() { setTimeout(function() { callback() }, animationTime) } var position = 0 for ( var nextCallback = position + q.length - 1; nextCallback >= position; nextCallback-- ) { ;(function(callback, index) { start = function() { addBubble(q[index], callback) } })(start, nextCallback) } start() }
[ "function", "(", "q", ",", "callback", ")", "{", "var", "start", "=", "function", "(", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "callback", "(", ")", "}", ",", "animationTime", ")", "}", "var", "position", "=", "0", "for", "(", "var", "nextCallback", "=", "position", "+", "q", ".", "length", "-", "1", ";", "nextCallback", ">=", "position", ";", "nextCallback", "--", ")", "{", ";", "(", "function", "(", "callback", ",", "index", ")", "{", "start", "=", "function", "(", ")", "{", "addBubble", "(", "q", "[", "index", "]", ",", "callback", ")", "}", "}", ")", "(", "start", ",", "nextCallback", ")", "}", "start", "(", ")", "}" ]
"type" each message within the group
[ "type", "each", "message", "within", "the", "group" ]
7c34f50184ce9562ff89a37132481371bd57a4dc
https://github.com/dmitrizzle/chat-bubble/blob/7c34f50184ce9562ff89a37132481371bd57a4dc/component/Bubbles.js#L192-L211
11,918
FormidableLabs/nodejs-dashboard
lib/views/panel.js
Panel
function Panel(options) { var panelLayout = options.layoutConfig; var viewLayouts = createLayout(panelLayout.view.views); this.getPosition = panelLayout.getPosition; this.views = _.map(viewLayouts, function (viewLayout) { viewLayout.getPosition = wrapGetPosition(viewLayout.getPosition, panelLayout.getPosition); return options.creator(viewLayout); }); }
javascript
function Panel(options) { var panelLayout = options.layoutConfig; var viewLayouts = createLayout(panelLayout.view.views); this.getPosition = panelLayout.getPosition; this.views = _.map(viewLayouts, function (viewLayout) { viewLayout.getPosition = wrapGetPosition(viewLayout.getPosition, panelLayout.getPosition); return options.creator(viewLayout); }); }
[ "function", "Panel", "(", "options", ")", "{", "var", "panelLayout", "=", "options", ".", "layoutConfig", ";", "var", "viewLayouts", "=", "createLayout", "(", "panelLayout", ".", "view", ".", "views", ")", ";", "this", ".", "getPosition", "=", "panelLayout", ".", "getPosition", ";", "this", ".", "views", "=", "_", ".", "map", "(", "viewLayouts", ",", "function", "(", "viewLayout", ")", "{", "viewLayout", ".", "getPosition", "=", "wrapGetPosition", "(", "viewLayout", ".", "getPosition", ",", "panelLayout", ".", "getPosition", ")", ";", "return", "options", ".", "creator", "(", "viewLayout", ")", ";", "}", ")", ";", "}" ]
A psudeo view that creates sub views and lays them out in columns and rows @param {Object} options view creation options @returns {null} The class needs to be created with new
[ "A", "psudeo", "view", "that", "creates", "sub", "views", "and", "lays", "them", "out", "in", "columns", "and", "rows" ]
74ab60f04301476a6e78c21823bb8b8ffc086f5b
https://github.com/FormidableLabs/nodejs-dashboard/blob/74ab60f04301476a6e78c21823bb8b8ffc086f5b/lib/views/panel.js#L120-L128
11,919
FormidableLabs/nodejs-dashboard
lib/views/index.js
function (customizations, layoutConfig) { var customization = customizations[layoutConfig.view.type]; if (!customization) { return layoutConfig; } return _.merge(layoutConfig, { view: customization }); }
javascript
function (customizations, layoutConfig) { var customization = customizations[layoutConfig.view.type]; if (!customization) { return layoutConfig; } return _.merge(layoutConfig, { view: customization }); }
[ "function", "(", "customizations", ",", "layoutConfig", ")", "{", "var", "customization", "=", "customizations", "[", "layoutConfig", ".", "view", ".", "type", "]", ";", "if", "(", "!", "customization", ")", "{", "return", "layoutConfig", ";", "}", "return", "_", ".", "merge", "(", "layoutConfig", ",", "{", "view", ":", "customization", "}", ")", ";", "}" ]
Customize view types based on a settings class
[ "Customize", "view", "types", "based", "on", "a", "settings", "class" ]
74ab60f04301476a6e78c21823bb8b8ffc086f5b
https://github.com/FormidableLabs/nodejs-dashboard/blob/74ab60f04301476a6e78c21823bb8b8ffc086f5b/lib/views/index.js#L32-L38
11,920
FormidableLabs/nodejs-dashboard
lib/providers/metrics-provider.js
MetricsProvider
function MetricsProvider(screen) { /** * Setup the process to aggregate the data as and when it is necessary. * * @returns {void} */ var setupAggregation = function setupAggregation() { // construct the aggregation container this._aggregation = _.reduce(AGGREGATE_TIME_LEVELS, function (prev, timeLevel) { prev[timeLevel] = { data: [], lastTimeIndex: undefined, lastAggregateIndex: 0, scrollOffset: 0 }; return prev; }, {}); // an array of all available aggregation levels and metadata this.aggregationLevels = _.keys(this._aggregation); this.lowestAggregateTimeUnits = +this.aggregationLevels[0]; this.highestAggregationKey = _.last(this.aggregationLevels); // remember when all this started this._startTime = Date.now(); // this is where we stopped aggregating this._lastAggregationIndex = 0; }.bind(this); EventEmitter.call(this); // the low-level container of all metrics provided this._metrics = []; // setup for aggregation setupAggregation(); // initialize the zoom level to the lowest level this.setZoomLevel(0); // callback handlers screen.on("metrics", this._onMetrics.bind(this)); screen.on("zoomGraphs", this.adjustZoomLevel.bind(this)); screen.on("scrollGraphs", this.adjustScrollOffset.bind(this)); screen.on("startGraphs", this.startGraphs.bind(this)); screen.on("resetGraphs", this.resetGraphs.bind(this)); }
javascript
function MetricsProvider(screen) { /** * Setup the process to aggregate the data as and when it is necessary. * * @returns {void} */ var setupAggregation = function setupAggregation() { // construct the aggregation container this._aggregation = _.reduce(AGGREGATE_TIME_LEVELS, function (prev, timeLevel) { prev[timeLevel] = { data: [], lastTimeIndex: undefined, lastAggregateIndex: 0, scrollOffset: 0 }; return prev; }, {}); // an array of all available aggregation levels and metadata this.aggregationLevels = _.keys(this._aggregation); this.lowestAggregateTimeUnits = +this.aggregationLevels[0]; this.highestAggregationKey = _.last(this.aggregationLevels); // remember when all this started this._startTime = Date.now(); // this is where we stopped aggregating this._lastAggregationIndex = 0; }.bind(this); EventEmitter.call(this); // the low-level container of all metrics provided this._metrics = []; // setup for aggregation setupAggregation(); // initialize the zoom level to the lowest level this.setZoomLevel(0); // callback handlers screen.on("metrics", this._onMetrics.bind(this)); screen.on("zoomGraphs", this.adjustZoomLevel.bind(this)); screen.on("scrollGraphs", this.adjustScrollOffset.bind(this)); screen.on("startGraphs", this.startGraphs.bind(this)); screen.on("resetGraphs", this.resetGraphs.bind(this)); }
[ "function", "MetricsProvider", "(", "screen", ")", "{", "/**\n * Setup the process to aggregate the data as and when it is necessary.\n *\n * @returns {void}\n */", "var", "setupAggregation", "=", "function", "setupAggregation", "(", ")", "{", "// construct the aggregation container", "this", ".", "_aggregation", "=", "_", ".", "reduce", "(", "AGGREGATE_TIME_LEVELS", ",", "function", "(", "prev", ",", "timeLevel", ")", "{", "prev", "[", "timeLevel", "]", "=", "{", "data", ":", "[", "]", ",", "lastTimeIndex", ":", "undefined", ",", "lastAggregateIndex", ":", "0", ",", "scrollOffset", ":", "0", "}", ";", "return", "prev", ";", "}", ",", "{", "}", ")", ";", "// an array of all available aggregation levels and metadata", "this", ".", "aggregationLevels", "=", "_", ".", "keys", "(", "this", ".", "_aggregation", ")", ";", "this", ".", "lowestAggregateTimeUnits", "=", "+", "this", ".", "aggregationLevels", "[", "0", "]", ";", "this", ".", "highestAggregationKey", "=", "_", ".", "last", "(", "this", ".", "aggregationLevels", ")", ";", "// remember when all this started", "this", ".", "_startTime", "=", "Date", ".", "now", "(", ")", ";", "// this is where we stopped aggregating", "this", ".", "_lastAggregationIndex", "=", "0", ";", "}", ".", "bind", "(", "this", ")", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "// the low-level container of all metrics provided", "this", ".", "_metrics", "=", "[", "]", ";", "// setup for aggregation", "setupAggregation", "(", ")", ";", "// initialize the zoom level to the lowest level", "this", ".", "setZoomLevel", "(", "0", ")", ";", "// callback handlers", "screen", ".", "on", "(", "\"metrics\"", ",", "this", ".", "_onMetrics", ".", "bind", "(", "this", ")", ")", ";", "screen", ".", "on", "(", "\"zoomGraphs\"", ",", "this", ".", "adjustZoomLevel", ".", "bind", "(", "this", ")", ")", ";", "screen", ".", "on", "(", "\"scrollGraphs\"", ",", "this", ".", "adjustScrollOffset", ".", "bind", "(", "this", ")", ")", ";", "screen", ".", "on", "(", "\"startGraphs\"", ",", "this", ".", "startGraphs", ".", "bind", "(", "this", ")", ")", ";", "screen", ".", "on", "(", "\"resetGraphs\"", ",", "this", ".", "resetGraphs", ".", "bind", "(", "this", ")", ")", ";", "}" ]
This is the constructor for the MetricsProvider @param {Object} screen The blessed screen object. @returns {void}
[ "This", "is", "the", "constructor", "for", "the", "MetricsProvider" ]
74ab60f04301476a6e78c21823bb8b8ffc086f5b
https://github.com/FormidableLabs/nodejs-dashboard/blob/74ab60f04301476a6e78c21823bb8b8ffc086f5b/lib/providers/metrics-provider.js#L27-L77
11,921
FormidableLabs/nodejs-dashboard
lib/providers/metrics-provider.js
getInitializedAverage
function getInitializedAverage(data) { return _.reduce(data, function (prev, a, dataKey) { // create a first-level object of the key prev[dataKey] = {}; _.each(data[dataKey], function (b, dataMetricKey) { // the metrics are properties inside this object prev[dataKey][dataMetricKey] = 0; }); return prev; }, {}); }
javascript
function getInitializedAverage(data) { return _.reduce(data, function (prev, a, dataKey) { // create a first-level object of the key prev[dataKey] = {}; _.each(data[dataKey], function (b, dataMetricKey) { // the metrics are properties inside this object prev[dataKey][dataMetricKey] = 0; }); return prev; }, {}); }
[ "function", "getInitializedAverage", "(", "data", ")", "{", "return", "_", ".", "reduce", "(", "data", ",", "function", "(", "prev", ",", "a", ",", "dataKey", ")", "{", "// create a first-level object of the key", "prev", "[", "dataKey", "]", "=", "{", "}", ";", "_", ".", "each", "(", "data", "[", "dataKey", "]", ",", "function", "(", "b", ",", "dataMetricKey", ")", "{", "// the metrics are properties inside this object", "prev", "[", "dataKey", "]", "[", "dataMetricKey", "]", "=", "0", ";", "}", ")", ";", "return", "prev", ";", "}", ",", "{", "}", ")", ";", "}" ]
Given a metric data object, construct an initialized average. @param {Object} data The metric data received. @returns {Object} The initialized average object is returned.
[ "Given", "a", "metric", "data", "object", "construct", "an", "initialized", "average", "." ]
74ab60f04301476a6e78c21823bb8b8ffc086f5b
https://github.com/FormidableLabs/nodejs-dashboard/blob/74ab60f04301476a6e78c21823bb8b8ffc086f5b/lib/providers/metrics-provider.js#L298-L310
11,922
FormidableLabs/nodejs-dashboard
lib/providers/metrics-provider.js
aggregateMetrics
function aggregateMetrics(currentTime, metricData) { var aggregateKey; /** * Place aggregate data into the specified slot. If the current zoom * level matches the aggregate level, the data is emitted to keep the * display in sync. * * @param {Number} index * The desired slot for the aggregate. * * @param {Object} data * The aggregate data. * * @returns {void} */ var setAggregateData = function setAggregateData(index, data) { this._aggregation[aggregateKey].data[index] = data; // if this view (current or not) is scrolled, adjust it if (this._aggregation[aggregateKey].scrollOffset) { this._aggregation[aggregateKey].scrollOffset--; } // emit to keep the display in sync if (this.isCurrentZoom(aggregateKey)) { if (this.isScrolled()) { this.emit("refreshMetrics"); } else { this.emit("metrics", data); } } }.bind(this); /** * Given the current time time index, add any missing logical * time slots to have a complete picture of data. * * @param {Number} currentTimeIndex * The time index currently being processed. * * @returns {void} */ var addMissingTimeSlots = function addMissingTimeSlots(currentTimeIndex) { var aggregateIndex = this._aggregation[aggregateKey].data.length; while (aggregateIndex < currentTimeIndex) { setAggregateData(aggregateIndex++, this.emptyAverage); } }.bind(this); /** * After having detected a new sampling, aggregate the relevant data points * * @param {Object[]} rows * The array reference. * * @param {Number} startIndex * The starting index to derive an average. * * @param {Number} endIndex * The ending index to derive an average. * * @returns {void} */ var getAveragedAggregate = function getAveragedAggregate(rows, startIndex, endIndex) { var averagedAggregate = getInitializedAverage(metricData); // this is the number of elements we will aggregate var aggregateCount = endIndex - startIndex + 1; // you can compute an average of a set of numbers two ways // first, you can add all the numbers together and then divide by the count // second, you call divide each number by the count and add the quotients // the first method is more accurate, however you can overflow an accumulator // and result with NaN // the second method is employed here to ensure no overflows for (var dataKey in metricData) { for (var dataMetricKey in metricData[dataKey]) { for (var rowIndex = startIndex; rowIndex <= endIndex; rowIndex++) { averagedAggregate[dataKey][dataMetricKey] += rows[rowIndex][dataKey][dataMetricKey] / aggregateCount; } // after the average is done, truncate the averages to one decimal point averagedAggregate[dataKey][dataMetricKey] = +averagedAggregate[dataKey][dataMetricKey].toFixed(1); } } return averagedAggregate; }; /** * Process one row of metric data into aggregate. * * @param {Number} rowIndex * The index of the row being processed. * * @param {Object[]} rows * The array reference. * * @returns {void} */ var processRow = function processRow(rowIndex, rows) { var averagedAggregate; var lastTimeIndex = this._aggregation[aggregateKey].lastTimeIndex; // get the time index of the aggregate var currentTimeIndex = convertElapsedTimeToTimeIndex(currentTime, this._startTime, +aggregateKey); // when the time index changes, average the data for the time band if (currentTimeIndex !== lastTimeIndex) { // except for the first one if (lastTimeIndex !== undefined) { // add in any missing logical time slots addMissingTimeSlots.call(this, lastTimeIndex); // get the average across the discovered time band averagedAggregate = getAveragedAggregate( rows, this._aggregation[aggregateKey].lastAggregateIndex, rowIndex - 1 ); // place the average setAggregateData(lastTimeIndex, averagedAggregate); // now we know where the next aggregate begins this._aggregation[aggregateKey].lastAggregateIndex = rowIndex; } // level-break this._aggregation[aggregateKey].lastTimeIndex = currentTimeIndex; } }.bind(this); // iterate over the configured aggregation time buckets for (aggregateKey in this._aggregation) { // iterate through metrics, beginning where we left off processRow(this._lastAggregationIndex, this._metrics); } // remember where we will begin again this._lastAggregationIndex++; }
javascript
function aggregateMetrics(currentTime, metricData) { var aggregateKey; /** * Place aggregate data into the specified slot. If the current zoom * level matches the aggregate level, the data is emitted to keep the * display in sync. * * @param {Number} index * The desired slot for the aggregate. * * @param {Object} data * The aggregate data. * * @returns {void} */ var setAggregateData = function setAggregateData(index, data) { this._aggregation[aggregateKey].data[index] = data; // if this view (current or not) is scrolled, adjust it if (this._aggregation[aggregateKey].scrollOffset) { this._aggregation[aggregateKey].scrollOffset--; } // emit to keep the display in sync if (this.isCurrentZoom(aggregateKey)) { if (this.isScrolled()) { this.emit("refreshMetrics"); } else { this.emit("metrics", data); } } }.bind(this); /** * Given the current time time index, add any missing logical * time slots to have a complete picture of data. * * @param {Number} currentTimeIndex * The time index currently being processed. * * @returns {void} */ var addMissingTimeSlots = function addMissingTimeSlots(currentTimeIndex) { var aggregateIndex = this._aggregation[aggregateKey].data.length; while (aggregateIndex < currentTimeIndex) { setAggregateData(aggregateIndex++, this.emptyAverage); } }.bind(this); /** * After having detected a new sampling, aggregate the relevant data points * * @param {Object[]} rows * The array reference. * * @param {Number} startIndex * The starting index to derive an average. * * @param {Number} endIndex * The ending index to derive an average. * * @returns {void} */ var getAveragedAggregate = function getAveragedAggregate(rows, startIndex, endIndex) { var averagedAggregate = getInitializedAverage(metricData); // this is the number of elements we will aggregate var aggregateCount = endIndex - startIndex + 1; // you can compute an average of a set of numbers two ways // first, you can add all the numbers together and then divide by the count // second, you call divide each number by the count and add the quotients // the first method is more accurate, however you can overflow an accumulator // and result with NaN // the second method is employed here to ensure no overflows for (var dataKey in metricData) { for (var dataMetricKey in metricData[dataKey]) { for (var rowIndex = startIndex; rowIndex <= endIndex; rowIndex++) { averagedAggregate[dataKey][dataMetricKey] += rows[rowIndex][dataKey][dataMetricKey] / aggregateCount; } // after the average is done, truncate the averages to one decimal point averagedAggregate[dataKey][dataMetricKey] = +averagedAggregate[dataKey][dataMetricKey].toFixed(1); } } return averagedAggregate; }; /** * Process one row of metric data into aggregate. * * @param {Number} rowIndex * The index of the row being processed. * * @param {Object[]} rows * The array reference. * * @returns {void} */ var processRow = function processRow(rowIndex, rows) { var averagedAggregate; var lastTimeIndex = this._aggregation[aggregateKey].lastTimeIndex; // get the time index of the aggregate var currentTimeIndex = convertElapsedTimeToTimeIndex(currentTime, this._startTime, +aggregateKey); // when the time index changes, average the data for the time band if (currentTimeIndex !== lastTimeIndex) { // except for the first one if (lastTimeIndex !== undefined) { // add in any missing logical time slots addMissingTimeSlots.call(this, lastTimeIndex); // get the average across the discovered time band averagedAggregate = getAveragedAggregate( rows, this._aggregation[aggregateKey].lastAggregateIndex, rowIndex - 1 ); // place the average setAggregateData(lastTimeIndex, averagedAggregate); // now we know where the next aggregate begins this._aggregation[aggregateKey].lastAggregateIndex = rowIndex; } // level-break this._aggregation[aggregateKey].lastTimeIndex = currentTimeIndex; } }.bind(this); // iterate over the configured aggregation time buckets for (aggregateKey in this._aggregation) { // iterate through metrics, beginning where we left off processRow(this._lastAggregationIndex, this._metrics); } // remember where we will begin again this._lastAggregationIndex++; }
[ "function", "aggregateMetrics", "(", "currentTime", ",", "metricData", ")", "{", "var", "aggregateKey", ";", "/**\n * Place aggregate data into the specified slot. If the current zoom\n * level matches the aggregate level, the data is emitted to keep the\n * display in sync.\n *\n * @param {Number} index\n * The desired slot for the aggregate.\n *\n * @param {Object} data\n * The aggregate data.\n *\n * @returns {void}\n */", "var", "setAggregateData", "=", "function", "setAggregateData", "(", "index", ",", "data", ")", "{", "this", ".", "_aggregation", "[", "aggregateKey", "]", ".", "data", "[", "index", "]", "=", "data", ";", "// if this view (current or not) is scrolled, adjust it", "if", "(", "this", ".", "_aggregation", "[", "aggregateKey", "]", ".", "scrollOffset", ")", "{", "this", ".", "_aggregation", "[", "aggregateKey", "]", ".", "scrollOffset", "--", ";", "}", "// emit to keep the display in sync", "if", "(", "this", ".", "isCurrentZoom", "(", "aggregateKey", ")", ")", "{", "if", "(", "this", ".", "isScrolled", "(", ")", ")", "{", "this", ".", "emit", "(", "\"refreshMetrics\"", ")", ";", "}", "else", "{", "this", ".", "emit", "(", "\"metrics\"", ",", "data", ")", ";", "}", "}", "}", ".", "bind", "(", "this", ")", ";", "/**\n * Given the current time time index, add any missing logical\n * time slots to have a complete picture of data.\n *\n * @param {Number} currentTimeIndex\n * The time index currently being processed.\n *\n * @returns {void}\n */", "var", "addMissingTimeSlots", "=", "function", "addMissingTimeSlots", "(", "currentTimeIndex", ")", "{", "var", "aggregateIndex", "=", "this", ".", "_aggregation", "[", "aggregateKey", "]", ".", "data", ".", "length", ";", "while", "(", "aggregateIndex", "<", "currentTimeIndex", ")", "{", "setAggregateData", "(", "aggregateIndex", "++", ",", "this", ".", "emptyAverage", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ";", "/**\n * After having detected a new sampling, aggregate the relevant data points\n *\n * @param {Object[]} rows\n * The array reference.\n *\n * @param {Number} startIndex\n * The starting index to derive an average.\n *\n * @param {Number} endIndex\n * The ending index to derive an average.\n *\n * @returns {void}\n */", "var", "getAveragedAggregate", "=", "function", "getAveragedAggregate", "(", "rows", ",", "startIndex", ",", "endIndex", ")", "{", "var", "averagedAggregate", "=", "getInitializedAverage", "(", "metricData", ")", ";", "// this is the number of elements we will aggregate", "var", "aggregateCount", "=", "endIndex", "-", "startIndex", "+", "1", ";", "// you can compute an average of a set of numbers two ways", "// first, you can add all the numbers together and then divide by the count", "// second, you call divide each number by the count and add the quotients", "// the first method is more accurate, however you can overflow an accumulator", "// and result with NaN", "// the second method is employed here to ensure no overflows", "for", "(", "var", "dataKey", "in", "metricData", ")", "{", "for", "(", "var", "dataMetricKey", "in", "metricData", "[", "dataKey", "]", ")", "{", "for", "(", "var", "rowIndex", "=", "startIndex", ";", "rowIndex", "<=", "endIndex", ";", "rowIndex", "++", ")", "{", "averagedAggregate", "[", "dataKey", "]", "[", "dataMetricKey", "]", "+=", "rows", "[", "rowIndex", "]", "[", "dataKey", "]", "[", "dataMetricKey", "]", "/", "aggregateCount", ";", "}", "// after the average is done, truncate the averages to one decimal point", "averagedAggregate", "[", "dataKey", "]", "[", "dataMetricKey", "]", "=", "+", "averagedAggregate", "[", "dataKey", "]", "[", "dataMetricKey", "]", ".", "toFixed", "(", "1", ")", ";", "}", "}", "return", "averagedAggregate", ";", "}", ";", "/**\n * Process one row of metric data into aggregate.\n *\n * @param {Number} rowIndex\n * The index of the row being processed.\n *\n * @param {Object[]} rows\n * The array reference.\n *\n * @returns {void}\n */", "var", "processRow", "=", "function", "processRow", "(", "rowIndex", ",", "rows", ")", "{", "var", "averagedAggregate", ";", "var", "lastTimeIndex", "=", "this", ".", "_aggregation", "[", "aggregateKey", "]", ".", "lastTimeIndex", ";", "// get the time index of the aggregate", "var", "currentTimeIndex", "=", "convertElapsedTimeToTimeIndex", "(", "currentTime", ",", "this", ".", "_startTime", ",", "+", "aggregateKey", ")", ";", "// when the time index changes, average the data for the time band", "if", "(", "currentTimeIndex", "!==", "lastTimeIndex", ")", "{", "// except for the first one", "if", "(", "lastTimeIndex", "!==", "undefined", ")", "{", "// add in any missing logical time slots", "addMissingTimeSlots", ".", "call", "(", "this", ",", "lastTimeIndex", ")", ";", "// get the average across the discovered time band", "averagedAggregate", "=", "getAveragedAggregate", "(", "rows", ",", "this", ".", "_aggregation", "[", "aggregateKey", "]", ".", "lastAggregateIndex", ",", "rowIndex", "-", "1", ")", ";", "// place the average", "setAggregateData", "(", "lastTimeIndex", ",", "averagedAggregate", ")", ";", "// now we know where the next aggregate begins", "this", ".", "_aggregation", "[", "aggregateKey", "]", ".", "lastAggregateIndex", "=", "rowIndex", ";", "}", "// level-break", "this", ".", "_aggregation", "[", "aggregateKey", "]", ".", "lastTimeIndex", "=", "currentTimeIndex", ";", "}", "}", ".", "bind", "(", "this", ")", ";", "// iterate over the configured aggregation time buckets", "for", "(", "aggregateKey", "in", "this", ".", "_aggregation", ")", "{", "// iterate through metrics, beginning where we left off", "processRow", "(", "this", ".", "_lastAggregationIndex", ",", "this", ".", "_metrics", ")", ";", "}", "// remember where we will begin again", "this", ".", "_lastAggregationIndex", "++", ";", "}" ]
Perform event-driven aggregation at all configured units of time. @param {Number} currentTime The current time of the aggregation. @param {Object} metricData The metric data template received. @this MetricsProvider @returns {void}
[ "Perform", "event", "-", "driven", "aggregation", "at", "all", "configured", "units", "of", "time", "." ]
74ab60f04301476a6e78c21823bb8b8ffc086f5b
https://github.com/FormidableLabs/nodejs-dashboard/blob/74ab60f04301476a6e78c21823bb8b8ffc086f5b/lib/providers/metrics-provider.js#L326-L475
11,923
FormidableLabs/nodejs-dashboard
lib/providers/metrics-provider.js
getAveragedAggregate
function getAveragedAggregate(rows, startIndex, endIndex) { var averagedAggregate = getInitializedAverage(metricData); // this is the number of elements we will aggregate var aggregateCount = endIndex - startIndex + 1; // you can compute an average of a set of numbers two ways // first, you can add all the numbers together and then divide by the count // second, you call divide each number by the count and add the quotients // the first method is more accurate, however you can overflow an accumulator // and result with NaN // the second method is employed here to ensure no overflows for (var dataKey in metricData) { for (var dataMetricKey in metricData[dataKey]) { for (var rowIndex = startIndex; rowIndex <= endIndex; rowIndex++) { averagedAggregate[dataKey][dataMetricKey] += rows[rowIndex][dataKey][dataMetricKey] / aggregateCount; } // after the average is done, truncate the averages to one decimal point averagedAggregate[dataKey][dataMetricKey] = +averagedAggregate[dataKey][dataMetricKey].toFixed(1); } } return averagedAggregate; }
javascript
function getAveragedAggregate(rows, startIndex, endIndex) { var averagedAggregate = getInitializedAverage(metricData); // this is the number of elements we will aggregate var aggregateCount = endIndex - startIndex + 1; // you can compute an average of a set of numbers two ways // first, you can add all the numbers together and then divide by the count // second, you call divide each number by the count and add the quotients // the first method is more accurate, however you can overflow an accumulator // and result with NaN // the second method is employed here to ensure no overflows for (var dataKey in metricData) { for (var dataMetricKey in metricData[dataKey]) { for (var rowIndex = startIndex; rowIndex <= endIndex; rowIndex++) { averagedAggregate[dataKey][dataMetricKey] += rows[rowIndex][dataKey][dataMetricKey] / aggregateCount; } // after the average is done, truncate the averages to one decimal point averagedAggregate[dataKey][dataMetricKey] = +averagedAggregate[dataKey][dataMetricKey].toFixed(1); } } return averagedAggregate; }
[ "function", "getAveragedAggregate", "(", "rows", ",", "startIndex", ",", "endIndex", ")", "{", "var", "averagedAggregate", "=", "getInitializedAverage", "(", "metricData", ")", ";", "// this is the number of elements we will aggregate", "var", "aggregateCount", "=", "endIndex", "-", "startIndex", "+", "1", ";", "// you can compute an average of a set of numbers two ways", "// first, you can add all the numbers together and then divide by the count", "// second, you call divide each number by the count and add the quotients", "// the first method is more accurate, however you can overflow an accumulator", "// and result with NaN", "// the second method is employed here to ensure no overflows", "for", "(", "var", "dataKey", "in", "metricData", ")", "{", "for", "(", "var", "dataMetricKey", "in", "metricData", "[", "dataKey", "]", ")", "{", "for", "(", "var", "rowIndex", "=", "startIndex", ";", "rowIndex", "<=", "endIndex", ";", "rowIndex", "++", ")", "{", "averagedAggregate", "[", "dataKey", "]", "[", "dataMetricKey", "]", "+=", "rows", "[", "rowIndex", "]", "[", "dataKey", "]", "[", "dataMetricKey", "]", "/", "aggregateCount", ";", "}", "// after the average is done, truncate the averages to one decimal point", "averagedAggregate", "[", "dataKey", "]", "[", "dataMetricKey", "]", "=", "+", "averagedAggregate", "[", "dataKey", "]", "[", "dataMetricKey", "]", ".", "toFixed", "(", "1", ")", ";", "}", "}", "return", "averagedAggregate", ";", "}" ]
After having detected a new sampling, aggregate the relevant data points @param {Object[]} rows The array reference. @param {Number} startIndex The starting index to derive an average. @param {Number} endIndex The ending index to derive an average. @returns {void}
[ "After", "having", "detected", "a", "new", "sampling", "aggregate", "the", "relevant", "data", "points" ]
74ab60f04301476a6e78c21823bb8b8ffc086f5b
https://github.com/FormidableLabs/nodejs-dashboard/blob/74ab60f04301476a6e78c21823bb8b8ffc086f5b/lib/providers/metrics-provider.js#L393-L420
11,924
FormidableLabs/nodejs-dashboard
lib/providers/metrics-provider.js
getFixedScrollOffset
function getFixedScrollOffset(offset, length) { if (offset && length + offset <= limit) { return Math.min(limit - length, 0); } return Math.min(offset, 0); }
javascript
function getFixedScrollOffset(offset, length) { if (offset && length + offset <= limit) { return Math.min(limit - length, 0); } return Math.min(offset, 0); }
[ "function", "getFixedScrollOffset", "(", "offset", ",", "length", ")", "{", "if", "(", "offset", "&&", "length", "+", "offset", "<=", "limit", ")", "{", "return", "Math", ".", "min", "(", "limit", "-", "length", ",", "0", ")", ";", "}", "return", "Math", ".", "min", "(", "offset", ",", "0", ")", ";", "}" ]
Given an offset and length, get the corrected offset. @param {Number} offset The current offset value. @param {Number} length The length of available data to offset. @returns {Number} The corrected scroll offset is returned.
[ "Given", "an", "offset", "and", "length", "get", "the", "corrected", "offset", "." ]
74ab60f04301476a6e78c21823bb8b8ffc086f5b
https://github.com/FormidableLabs/nodejs-dashboard/blob/74ab60f04301476a6e78c21823bb8b8ffc086f5b/lib/providers/metrics-provider.js#L532-L537
11,925
CodeboxIDE/codebox
lib/utils/logger.js
function(logType, logSection) { if (!enabled) return; var args = Array.prototype.slice.call(arguments, 2); args.splice(0, 0, colors[logType][0]+"["+logType+"]"+colors[logType][1]+"["+logSection+"]"); console.log.apply(console, args); }
javascript
function(logType, logSection) { if (!enabled) return; var args = Array.prototype.slice.call(arguments, 2); args.splice(0, 0, colors[logType][0]+"["+logType+"]"+colors[logType][1]+"["+logSection+"]"); console.log.apply(console, args); }
[ "function", "(", "logType", ",", "logSection", ")", "{", "if", "(", "!", "enabled", ")", "return", ";", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", ";", "args", ".", "splice", "(", "0", ",", "0", ",", "colors", "[", "logType", "]", "[", "0", "]", "+", "\"[\"", "+", "logType", "+", "\"]\"", "+", "colors", "[", "logType", "]", "[", "1", "]", "+", "\"[\"", "+", "logSection", "+", "\"]\"", ")", ";", "console", ".", "log", ".", "apply", "(", "console", ",", "args", ")", ";", "}" ]
Base print method
[ "Base", "print", "method" ]
98b4710f1bdba615dddbab56011a86cd5f16897b
https://github.com/CodeboxIDE/codebox/blob/98b4710f1bdba615dddbab56011a86cd5f16897b/lib/utils/logger.js#L14-L20
11,926
CodeboxIDE/codebox
editor/utils/taphold.js
mousemove_callback
function mousemove_callback(e) { var x = e.pageX || e.originalEvent.touches[0].pageX; var y = e.pageY || e.originalEvent.touches[0].pageY; if (Math.abs(oX - x) > maxMove || Math.abs(oY - y) > maxMove) { if (timeout) clearTimeout(timeout); } }
javascript
function mousemove_callback(e) { var x = e.pageX || e.originalEvent.touches[0].pageX; var y = e.pageY || e.originalEvent.touches[0].pageY; if (Math.abs(oX - x) > maxMove || Math.abs(oY - y) > maxMove) { if (timeout) clearTimeout(timeout); } }
[ "function", "mousemove_callback", "(", "e", ")", "{", "var", "x", "=", "e", ".", "pageX", "||", "e", ".", "originalEvent", ".", "touches", "[", "0", "]", ".", "pageX", ";", "var", "y", "=", "e", ".", "pageY", "||", "e", ".", "originalEvent", ".", "touches", "[", "0", "]", ".", "pageY", ";", "if", "(", "Math", ".", "abs", "(", "oX", "-", "x", ")", ">", "maxMove", "||", "Math", ".", "abs", "(", "oY", "-", "y", ")", ">", "maxMove", ")", "{", "if", "(", "timeout", ")", "clearTimeout", "(", "timeout", ")", ";", "}", "}" ]
mousemove or touchmove callback
[ "mousemove", "or", "touchmove", "callback" ]
98b4710f1bdba615dddbab56011a86cd5f16897b
https://github.com/CodeboxIDE/codebox/blob/98b4710f1bdba615dddbab56011a86cd5f16897b/editor/utils/taphold.js#L26-L33
11,927
CodeboxIDE/codebox
editor/models/package.js
function() { var context, main, pkgRequireConfig, pkgRequire, that = this var d = Q.defer(); if (!this.get("browser")) return Q(); logger.log("Load", this.get("name")); getScript(this.url()+"/pkg-build.js", function(err) { if (!err) return d.resolve(); logger.exception("Error loading plugin:", err); d.reject(err); }); return d.promise.timeout(10000, "This addon took to long to load (> 10seconds)"); }
javascript
function() { var context, main, pkgRequireConfig, pkgRequire, that = this var d = Q.defer(); if (!this.get("browser")) return Q(); logger.log("Load", this.get("name")); getScript(this.url()+"/pkg-build.js", function(err) { if (!err) return d.resolve(); logger.exception("Error loading plugin:", err); d.reject(err); }); return d.promise.timeout(10000, "This addon took to long to load (> 10seconds)"); }
[ "function", "(", ")", "{", "var", "context", ",", "main", ",", "pkgRequireConfig", ",", "pkgRequire", ",", "that", "=", "this", "var", "d", "=", "Q", ".", "defer", "(", ")", ";", "if", "(", "!", "this", ".", "get", "(", "\"browser\"", ")", ")", "return", "Q", "(", ")", ";", "logger", ".", "log", "(", "\"Load\"", ",", "this", ".", "get", "(", "\"name\"", ")", ")", ";", "getScript", "(", "this", ".", "url", "(", ")", "+", "\"/pkg-build.js\"", ",", "function", "(", "err", ")", "{", "if", "(", "!", "err", ")", "return", "d", ".", "resolve", "(", ")", ";", "logger", ".", "exception", "(", "\"Error loading plugin:\"", ",", "err", ")", ";", "d", ".", "reject", "(", "err", ")", ";", "}", ")", ";", "return", "d", ".", "promise", ".", "timeout", "(", "10000", ",", "\"This addon took to long to load (> 10seconds)\"", ")", ";", "}" ]
Load the addon
[ "Load", "the", "addon" ]
98b4710f1bdba615dddbab56011a86cd5f16897b
https://github.com/CodeboxIDE/codebox/blob/98b4710f1bdba615dddbab56011a86cd5f16897b/editor/models/package.js#L59-L74
11,928
CodeboxIDE/codebox
lib/packages.js
cleanFolder
function cleanFolder(outPath) { try { var stat = fs.lstatSync(outPath); if (stat.isDirectory()) { wrench.rmdirSyncRecursive(outPath); } else { fs.unlinkSync(outPath); } } catch (e) { if (e.code != "ENOENT") throw e; } }
javascript
function cleanFolder(outPath) { try { var stat = fs.lstatSync(outPath); if (stat.isDirectory()) { wrench.rmdirSyncRecursive(outPath); } else { fs.unlinkSync(outPath); } } catch (e) { if (e.code != "ENOENT") throw e; } }
[ "function", "cleanFolder", "(", "outPath", ")", "{", "try", "{", "var", "stat", "=", "fs", ".", "lstatSync", "(", "outPath", ")", ";", "if", "(", "stat", ".", "isDirectory", "(", ")", ")", "{", "wrench", ".", "rmdirSyncRecursive", "(", "outPath", ")", ";", "}", "else", "{", "fs", ".", "unlinkSync", "(", "outPath", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "if", "(", "e", ".", "code", "!=", "\"ENOENT\"", ")", "throw", "e", ";", "}", "}" ]
Remove output if folder or symlink
[ "Remove", "output", "if", "folder", "or", "symlink" ]
98b4710f1bdba615dddbab56011a86cd5f16897b
https://github.com/CodeboxIDE/codebox/blob/98b4710f1bdba615dddbab56011a86cd5f16897b/lib/packages.js#L17-L28
11,929
dbashford/textract
lib/extract.js
cleanseText
function cleanseText( options, cb ) { return function( error, text ) { if ( !error ) { // clean up text text = util.replaceBadCharacters( text ); if ( options.preserveLineBreaks || options.preserveOnlyMultipleLineBreaks ) { if ( options.preserveOnlyMultipleLineBreaks ) { text = text.replace( STRIP_ONLY_SINGLE_LINEBREAKS, '$1 ' ).trim(); } text = text.replace( WHITELIST_PRESERVE_LINEBREAKS, ' ' ); } else { text = text.replace( WHITELIST_STRIP_LINEBREAKS, ' ' ); } // multiple spaces, tabs, vertical tabs, non-breaking space] text = text.replace( / (?! )/g, '' ) .replace( /[ \t\v\u00A0]{2,}/g, ' ' ); text = entities.decode( text ); } cb( error, text ); }; }
javascript
function cleanseText( options, cb ) { return function( error, text ) { if ( !error ) { // clean up text text = util.replaceBadCharacters( text ); if ( options.preserveLineBreaks || options.preserveOnlyMultipleLineBreaks ) { if ( options.preserveOnlyMultipleLineBreaks ) { text = text.replace( STRIP_ONLY_SINGLE_LINEBREAKS, '$1 ' ).trim(); } text = text.replace( WHITELIST_PRESERVE_LINEBREAKS, ' ' ); } else { text = text.replace( WHITELIST_STRIP_LINEBREAKS, ' ' ); } // multiple spaces, tabs, vertical tabs, non-breaking space] text = text.replace( / (?! )/g, '' ) .replace( /[ \t\v\u00A0]{2,}/g, ' ' ); text = entities.decode( text ); } cb( error, text ); }; }
[ "function", "cleanseText", "(", "options", ",", "cb", ")", "{", "return", "function", "(", "error", ",", "text", ")", "{", "if", "(", "!", "error", ")", "{", "// clean up text", "text", "=", "util", ".", "replaceBadCharacters", "(", "text", ")", ";", "if", "(", "options", ".", "preserveLineBreaks", "||", "options", ".", "preserveOnlyMultipleLineBreaks", ")", "{", "if", "(", "options", ".", "preserveOnlyMultipleLineBreaks", ")", "{", "text", "=", "text", ".", "replace", "(", "STRIP_ONLY_SINGLE_LINEBREAKS", ",", "'$1 '", ")", ".", "trim", "(", ")", ";", "}", "text", "=", "text", ".", "replace", "(", "WHITELIST_PRESERVE_LINEBREAKS", ",", "' '", ")", ";", "}", "else", "{", "text", "=", "text", ".", "replace", "(", "WHITELIST_STRIP_LINEBREAKS", ",", "' '", ")", ";", "}", "// multiple spaces, tabs, vertical tabs, non-breaking space]", "text", "=", "text", ".", "replace", "(", "/", " (?! )", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "[ \\t\\v\\u00A0]{2,}", "/", "g", ",", "' '", ")", ";", "text", "=", "entities", ".", "decode", "(", "text", ")", ";", "}", "cb", "(", "error", ",", "text", ")", ";", "}", ";", "}" ]
global, all file type, content cleansing
[ "global", "all", "file", "type", "content", "cleansing" ]
dc6004b78619c169044433d24a862228af6895fa
https://github.com/dbashford/textract/blob/dc6004b78619c169044433d24a862228af6895fa/lib/extract.js#L53-L76
11,930
dbashford/textract
lib/util.js
replaceBadCharacters
function replaceBadCharacters( text ) { var i, repl; for ( i = 0; i < rLen; i++ ) { repl = replacements[i]; text = text.replace( repl[0], repl[1] ); } return text; }
javascript
function replaceBadCharacters( text ) { var i, repl; for ( i = 0; i < rLen; i++ ) { repl = replacements[i]; text = text.replace( repl[0], repl[1] ); } return text; }
[ "function", "replaceBadCharacters", "(", "text", ")", "{", "var", "i", ",", "repl", ";", "for", "(", "i", "=", "0", ";", "i", "<", "rLen", ";", "i", "++", ")", "{", "repl", "=", "replacements", "[", "i", "]", ";", "text", "=", "text", ".", "replace", "(", "repl", "[", "0", "]", ",", "repl", "[", "1", "]", ")", ";", "}", "return", "text", ";", "}" ]
replace nasty quotes with simple ones
[ "replace", "nasty", "quotes", "with", "simple", "ones" ]
dc6004b78619c169044433d24a862228af6895fa
https://github.com/dbashford/textract/blob/dc6004b78619c169044433d24a862228af6895fa/lib/util.js#L21-L28
11,931
dbashford/textract
lib/util.js
runExecIntoFile
function runExecIntoFile( label, filePath, options, execOptions, genCommand, cb ) { // escape the file paths var fileTempOutPath = path.join( outDir, path.basename( filePath, path.extname( filePath ) ) ) , escapedFilePath = filePath.replace( /\s/g, '\\ ' ) , escapedFileTempOutPath = fileTempOutPath.replace( /\s/g, '\\ ' ) , cmd = genCommand( options, escapedFilePath, escapedFileTempOutPath ) ; exec( cmd, execOptions, function( error /* , stdout, stderr */ ) { if ( error !== null ) { error = new Error( 'Error extracting [[ ' + path.basename( filePath ) + ' ]], exec error: ' + error.message ); cb( error, null ); return; } fs.exists( fileTempOutPath + '.txt', function( exists ) { if ( exists ) { fs.readFile( fileTempOutPath + '.txt', 'utf8', function( error2, text ) { if ( error2 ) { error2 = new Error( 'Error reading' + label + ' output at [[ ' + fileTempOutPath + ' ]], error: ' + error2.message ); cb( error2, null ); } else { fs.unlink( fileTempOutPath + '.txt', function( error3 ) { if ( error3 ) { error3 = new Error( 'Error, ' + label + ' , cleaning up temp file [[ ' + fileTempOutPath + ' ]], error: ' + error3.message ); cb( error3, null ); } else { cb( null, text.toString() ); } }); } }); } else { error = new Error( 'Error reading ' + label + ' output at [[ ' + fileTempOutPath + ' ]], file does not exist' ); cb( error, null ); } }); } ); }
javascript
function runExecIntoFile( label, filePath, options, execOptions, genCommand, cb ) { // escape the file paths var fileTempOutPath = path.join( outDir, path.basename( filePath, path.extname( filePath ) ) ) , escapedFilePath = filePath.replace( /\s/g, '\\ ' ) , escapedFileTempOutPath = fileTempOutPath.replace( /\s/g, '\\ ' ) , cmd = genCommand( options, escapedFilePath, escapedFileTempOutPath ) ; exec( cmd, execOptions, function( error /* , stdout, stderr */ ) { if ( error !== null ) { error = new Error( 'Error extracting [[ ' + path.basename( filePath ) + ' ]], exec error: ' + error.message ); cb( error, null ); return; } fs.exists( fileTempOutPath + '.txt', function( exists ) { if ( exists ) { fs.readFile( fileTempOutPath + '.txt', 'utf8', function( error2, text ) { if ( error2 ) { error2 = new Error( 'Error reading' + label + ' output at [[ ' + fileTempOutPath + ' ]], error: ' + error2.message ); cb( error2, null ); } else { fs.unlink( fileTempOutPath + '.txt', function( error3 ) { if ( error3 ) { error3 = new Error( 'Error, ' + label + ' , cleaning up temp file [[ ' + fileTempOutPath + ' ]], error: ' + error3.message ); cb( error3, null ); } else { cb( null, text.toString() ); } }); } }); } else { error = new Error( 'Error reading ' + label + ' output at [[ ' + fileTempOutPath + ' ]], file does not exist' ); cb( error, null ); } }); } ); }
[ "function", "runExecIntoFile", "(", "label", ",", "filePath", ",", "options", ",", "execOptions", ",", "genCommand", ",", "cb", ")", "{", "// escape the file paths", "var", "fileTempOutPath", "=", "path", ".", "join", "(", "outDir", ",", "path", ".", "basename", "(", "filePath", ",", "path", ".", "extname", "(", "filePath", ")", ")", ")", ",", "escapedFilePath", "=", "filePath", ".", "replace", "(", "/", "\\s", "/", "g", ",", "'\\\\ '", ")", ",", "escapedFileTempOutPath", "=", "fileTempOutPath", ".", "replace", "(", "/", "\\s", "/", "g", ",", "'\\\\ '", ")", ",", "cmd", "=", "genCommand", "(", "options", ",", "escapedFilePath", ",", "escapedFileTempOutPath", ")", ";", "exec", "(", "cmd", ",", "execOptions", ",", "function", "(", "error", "/* , stdout, stderr */", ")", "{", "if", "(", "error", "!==", "null", ")", "{", "error", "=", "new", "Error", "(", "'Error extracting [[ '", "+", "path", ".", "basename", "(", "filePath", ")", "+", "' ]], exec error: '", "+", "error", ".", "message", ")", ";", "cb", "(", "error", ",", "null", ")", ";", "return", ";", "}", "fs", ".", "exists", "(", "fileTempOutPath", "+", "'.txt'", ",", "function", "(", "exists", ")", "{", "if", "(", "exists", ")", "{", "fs", ".", "readFile", "(", "fileTempOutPath", "+", "'.txt'", ",", "'utf8'", ",", "function", "(", "error2", ",", "text", ")", "{", "if", "(", "error2", ")", "{", "error2", "=", "new", "Error", "(", "'Error reading'", "+", "label", "+", "' output at [[ '", "+", "fileTempOutPath", "+", "' ]], error: '", "+", "error2", ".", "message", ")", ";", "cb", "(", "error2", ",", "null", ")", ";", "}", "else", "{", "fs", ".", "unlink", "(", "fileTempOutPath", "+", "'.txt'", ",", "function", "(", "error3", ")", "{", "if", "(", "error3", ")", "{", "error3", "=", "new", "Error", "(", "'Error, '", "+", "label", "+", "' , cleaning up temp file [[ '", "+", "fileTempOutPath", "+", "' ]], error: '", "+", "error3", ".", "message", ")", ";", "cb", "(", "error3", ",", "null", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "text", ".", "toString", "(", ")", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", "else", "{", "error", "=", "new", "Error", "(", "'Error reading '", "+", "label", "+", "' output at [[ '", "+", "fileTempOutPath", "+", "' ]], file does not exist'", ")", ";", "cb", "(", "error", ",", "null", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
1) builds an exec command using provided `genCommand` callback 2) runs that command against an input file path resulting in an output file 3) reads that output file in 4) cleans the output file up 5) executes a callback with the contents of the file @param {string} label Name for the extractor, e.g. `Tesseract` @param {string} filePath path to file to be extractor @param {object} options extractor options as provided via user configuration @param {object} execOptions execution options passed to `exec` commmand as provided via user configuration @param {function} genCommand function used to generate the command to be executed @param {string} cb callback that is passed error/text
[ "1", ")", "builds", "an", "exec", "command", "using", "provided", "genCommand", "callback", "2", ")", "runs", "that", "command", "against", "an", "input", "file", "path", "resulting", "in", "an", "output", "file", "3", ")", "reads", "that", "output", "file", "in", "4", ")", "cleans", "the", "output", "file", "up", "5", ")", "executes", "a", "callback", "with", "the", "contents", "of", "the", "file" ]
dc6004b78619c169044433d24a862228af6895fa
https://github.com/dbashford/textract/blob/dc6004b78619c169044433d24a862228af6895fa/lib/util.js#L109-L154
11,932
dbashford/textract
lib/extractors/doc-osx.js
extractText
function extractText( filePath, options, cb ) { var result = '' , error = null , textutil = spawn( 'textutil', ['-convert', 'txt', '-stdout', filePath] ) ; textutil.stdout.on( 'data', function( buffer ) { result += buffer.toString(); }); textutil.stderr.on( 'error', function( buffer ) { if ( !error ) { error = ''; } error += buffer.toString(); }); textutil.on( 'close', function( /* code */ ) { if ( error ) { error = new Error( 'textutil read of file named [[ ' + path.basename( filePath ) + ' ]] failed: ' + error ); cb( error, null ); return; } cb( null, result.trim() ); }); }
javascript
function extractText( filePath, options, cb ) { var result = '' , error = null , textutil = spawn( 'textutil', ['-convert', 'txt', '-stdout', filePath] ) ; textutil.stdout.on( 'data', function( buffer ) { result += buffer.toString(); }); textutil.stderr.on( 'error', function( buffer ) { if ( !error ) { error = ''; } error += buffer.toString(); }); textutil.on( 'close', function( /* code */ ) { if ( error ) { error = new Error( 'textutil read of file named [[ ' + path.basename( filePath ) + ' ]] failed: ' + error ); cb( error, null ); return; } cb( null, result.trim() ); }); }
[ "function", "extractText", "(", "filePath", ",", "options", ",", "cb", ")", "{", "var", "result", "=", "''", ",", "error", "=", "null", ",", "textutil", "=", "spawn", "(", "'textutil'", ",", "[", "'-convert'", ",", "'txt'", ",", "'-stdout'", ",", "filePath", "]", ")", ";", "textutil", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "(", "buffer", ")", "{", "result", "+=", "buffer", ".", "toString", "(", ")", ";", "}", ")", ";", "textutil", ".", "stderr", ".", "on", "(", "'error'", ",", "function", "(", "buffer", ")", "{", "if", "(", "!", "error", ")", "{", "error", "=", "''", ";", "}", "error", "+=", "buffer", ".", "toString", "(", ")", ";", "}", ")", ";", "textutil", ".", "on", "(", "'close'", ",", "function", "(", "/* code */", ")", "{", "if", "(", "error", ")", "{", "error", "=", "new", "Error", "(", "'textutil read of file named [[ '", "+", "path", ".", "basename", "(", "filePath", ")", "+", "' ]] failed: '", "+", "error", ")", ";", "cb", "(", "error", ",", "null", ")", ";", "return", ";", "}", "cb", "(", "null", ",", "result", ".", "trim", "(", ")", ")", ";", "}", ")", ";", "}" ]
textutil -convert txt -stdout foo.doc
[ "textutil", "-", "convert", "txt", "-", "stdout", "foo", ".", "doc" ]
dc6004b78619c169044433d24a862228af6895fa
https://github.com/dbashford/textract/blob/dc6004b78619c169044433d24a862228af6895fa/lib/extractors/doc-osx.js#L9-L35
11,933
APIDevTools/json-schema-ref-parser
lib/util/yaml.js
yamlParse
function yamlParse (text, reviver) { try { return yaml.safeLoad(text); } catch (e) { if (e instanceof Error) { throw e; } else { // https://github.com/nodeca/js-yaml/issues/153 throw ono(e, e.message); } } }
javascript
function yamlParse (text, reviver) { try { return yaml.safeLoad(text); } catch (e) { if (e instanceof Error) { throw e; } else { // https://github.com/nodeca/js-yaml/issues/153 throw ono(e, e.message); } } }
[ "function", "yamlParse", "(", "text", ",", "reviver", ")", "{", "try", "{", "return", "yaml", ".", "safeLoad", "(", "text", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", "instanceof", "Error", ")", "{", "throw", "e", ";", "}", "else", "{", "// https://github.com/nodeca/js-yaml/issues/153", "throw", "ono", "(", "e", ",", "e", ".", "message", ")", ";", "}", "}", "}" ]
Parses a YAML string and returns the value. @param {string} text - The YAML string to be parsed @param {function} [reviver] - Not currently supported. Provided for consistency with {@link JSON.parse} @returns {*}
[ "Parses", "a", "YAML", "string", "and", "returns", "the", "value", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/util/yaml.js#L18-L31
11,934
APIDevTools/json-schema-ref-parser
lib/util/yaml.js
yamlStringify
function yamlStringify (value, replacer, space) { try { var indent = (typeof space === "string" ? space.length : space) || 2; return yaml.safeDump(value, { indent: indent }); } catch (e) { if (e instanceof Error) { throw e; } else { // https://github.com/nodeca/js-yaml/issues/153 throw ono(e, e.message); } } }
javascript
function yamlStringify (value, replacer, space) { try { var indent = (typeof space === "string" ? space.length : space) || 2; return yaml.safeDump(value, { indent: indent }); } catch (e) { if (e instanceof Error) { throw e; } else { // https://github.com/nodeca/js-yaml/issues/153 throw ono(e, e.message); } } }
[ "function", "yamlStringify", "(", "value", ",", "replacer", ",", "space", ")", "{", "try", "{", "var", "indent", "=", "(", "typeof", "space", "===", "\"string\"", "?", "space", ".", "length", ":", "space", ")", "||", "2", ";", "return", "yaml", ".", "safeDump", "(", "value", ",", "{", "indent", ":", "indent", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", "instanceof", "Error", ")", "{", "throw", "e", ";", "}", "else", "{", "// https://github.com/nodeca/js-yaml/issues/153", "throw", "ono", "(", "e", ",", "e", ".", "message", ")", ";", "}", "}", "}" ]
Converts a JavaScript value to a YAML string. @param {*} value - The value to convert to YAML @param {function|array} replacer - Not currently supported. Provided for consistency with {@link JSON.stringify} @param {string|number} space - The number of spaces to use for indentation, or a string containing the number of spaces. @returns {string}
[ "Converts", "a", "JavaScript", "value", "to", "a", "YAML", "string", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/util/yaml.js#L41-L55
11,935
APIDevTools/json-schema-ref-parser
lib/parsers/json.js
parseJSON
function parseJSON (file) { return new Promise(function (resolve, reject) { var data = file.data; if (Buffer.isBuffer(data)) { data = data.toString(); } if (typeof data === "string") { if (data.trim().length === 0) { resolve(undefined); // This mirrors the YAML behavior } else { resolve(JSON.parse(data)); } } else { // data is already a JavaScript value (object, array, number, null, NaN, etc.) resolve(data); } }); }
javascript
function parseJSON (file) { return new Promise(function (resolve, reject) { var data = file.data; if (Buffer.isBuffer(data)) { data = data.toString(); } if (typeof data === "string") { if (data.trim().length === 0) { resolve(undefined); // This mirrors the YAML behavior } else { resolve(JSON.parse(data)); } } else { // data is already a JavaScript value (object, array, number, null, NaN, etc.) resolve(data); } }); }
[ "function", "parseJSON", "(", "file", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "data", "=", "file", ".", "data", ";", "if", "(", "Buffer", ".", "isBuffer", "(", "data", ")", ")", "{", "data", "=", "data", ".", "toString", "(", ")", ";", "}", "if", "(", "typeof", "data", "===", "\"string\"", ")", "{", "if", "(", "data", ".", "trim", "(", ")", ".", "length", "===", "0", ")", "{", "resolve", "(", "undefined", ")", ";", "// This mirrors the YAML behavior", "}", "else", "{", "resolve", "(", "JSON", ".", "parse", "(", "data", ")", ")", ";", "}", "}", "else", "{", "// data is already a JavaScript value (object, array, number, null, NaN, etc.)", "resolve", "(", "data", ")", ";", "}", "}", ")", ";", "}" ]
Parses the given file as JSON @param {object} file - An object containing information about the referenced file @param {string} file.url - The full URL of the referenced file @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver @returns {Promise}
[ "Parses", "the", "given", "file", "as", "JSON" ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/parsers/json.js#L37-L57
11,936
APIDevTools/json-schema-ref-parser
lib/parse.js
parse
function parse (path, $refs, options) { try { // Remove the URL fragment, if any path = url.stripHash(path); // Add a new $Ref for this file, even though we don't have the value yet. // This ensures that we don't simultaneously read & parse the same file multiple times var $ref = $refs._add(path); // This "file object" will be passed to all resolvers and parsers. var file = { url: path, extension: url.getExtension(path), }; // Read the file and then parse the data return readFile(file, options) .then(function (resolver) { $ref.pathType = resolver.plugin.name; file.data = resolver.result; return parseFile(file, options); }) .then(function (parser) { $ref.value = parser.result; return parser.result; }); } catch (e) { return Promise.reject(e); } }
javascript
function parse (path, $refs, options) { try { // Remove the URL fragment, if any path = url.stripHash(path); // Add a new $Ref for this file, even though we don't have the value yet. // This ensures that we don't simultaneously read & parse the same file multiple times var $ref = $refs._add(path); // This "file object" will be passed to all resolvers and parsers. var file = { url: path, extension: url.getExtension(path), }; // Read the file and then parse the data return readFile(file, options) .then(function (resolver) { $ref.pathType = resolver.plugin.name; file.data = resolver.result; return parseFile(file, options); }) .then(function (parser) { $ref.value = parser.result; return parser.result; }); } catch (e) { return Promise.reject(e); } }
[ "function", "parse", "(", "path", ",", "$refs", ",", "options", ")", "{", "try", "{", "// Remove the URL fragment, if any", "path", "=", "url", ".", "stripHash", "(", "path", ")", ";", "// Add a new $Ref for this file, even though we don't have the value yet.", "// This ensures that we don't simultaneously read & parse the same file multiple times", "var", "$ref", "=", "$refs", ".", "_add", "(", "path", ")", ";", "// This \"file object\" will be passed to all resolvers and parsers.", "var", "file", "=", "{", "url", ":", "path", ",", "extension", ":", "url", ".", "getExtension", "(", "path", ")", ",", "}", ";", "// Read the file and then parse the data", "return", "readFile", "(", "file", ",", "options", ")", ".", "then", "(", "function", "(", "resolver", ")", "{", "$ref", ".", "pathType", "=", "resolver", ".", "plugin", ".", "name", ";", "file", ".", "data", "=", "resolver", ".", "result", ";", "return", "parseFile", "(", "file", ",", "options", ")", ";", "}", ")", ".", "then", "(", "function", "(", "parser", ")", "{", "$ref", ".", "value", "=", "parser", ".", "result", ";", "return", "parser", ".", "result", ";", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "Promise", ".", "reject", "(", "e", ")", ";", "}", "}" ]
Reads and parses the specified file path or URL. @param {string} path - This path MUST already be resolved, since `read` doesn't know the resolution context @param {$Refs} $refs @param {$RefParserOptions} options @returns {Promise} The promise resolves with the parsed file contents, NOT the raw (Buffer) contents.
[ "Reads", "and", "parses", "the", "specified", "file", "path", "or", "URL", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/parse.js#L19-L49
11,937
APIDevTools/json-schema-ref-parser
lib/parse.js
parseFile
function parseFile (file, options) { return new Promise(function (resolve, reject) { // console.log('Parsing %s', file.url); // Find the parsers that can read this file type. // If none of the parsers are an exact match for this file, then we'll try ALL of them. // This handles situations where the file IS a supported type, just with an unknown extension. var allParsers = plugins.all(options.parse); var filteredParsers = plugins.filter(allParsers, "canParse", file); var parsers = filteredParsers.length > 0 ? filteredParsers : allParsers; // Run the parsers, in order, until one of them succeeds plugins.sort(parsers); plugins.run(parsers, "parse", file) .then(onParsed, onError); function onParsed (parser) { if (!parser.plugin.allowEmpty && isEmpty(parser.result)) { reject(ono.syntax('Error parsing "%s" as %s. \nParsed value is empty', file.url, parser.plugin.name)); } else { resolve(parser); } } function onError (err) { if (err) { err = err instanceof Error ? err : new Error(err); reject(ono.syntax(err, "Error parsing %s", file.url)); } else { reject(ono.syntax("Unable to parse %s", file.url)); } } }); }
javascript
function parseFile (file, options) { return new Promise(function (resolve, reject) { // console.log('Parsing %s', file.url); // Find the parsers that can read this file type. // If none of the parsers are an exact match for this file, then we'll try ALL of them. // This handles situations where the file IS a supported type, just with an unknown extension. var allParsers = plugins.all(options.parse); var filteredParsers = plugins.filter(allParsers, "canParse", file); var parsers = filteredParsers.length > 0 ? filteredParsers : allParsers; // Run the parsers, in order, until one of them succeeds plugins.sort(parsers); plugins.run(parsers, "parse", file) .then(onParsed, onError); function onParsed (parser) { if (!parser.plugin.allowEmpty && isEmpty(parser.result)) { reject(ono.syntax('Error parsing "%s" as %s. \nParsed value is empty', file.url, parser.plugin.name)); } else { resolve(parser); } } function onError (err) { if (err) { err = err instanceof Error ? err : new Error(err); reject(ono.syntax(err, "Error parsing %s", file.url)); } else { reject(ono.syntax("Unable to parse %s", file.url)); } } }); }
[ "function", "parseFile", "(", "file", ",", "options", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "// console.log('Parsing %s', file.url);", "// Find the parsers that can read this file type.", "// If none of the parsers are an exact match for this file, then we'll try ALL of them.", "// This handles situations where the file IS a supported type, just with an unknown extension.", "var", "allParsers", "=", "plugins", ".", "all", "(", "options", ".", "parse", ")", ";", "var", "filteredParsers", "=", "plugins", ".", "filter", "(", "allParsers", ",", "\"canParse\"", ",", "file", ")", ";", "var", "parsers", "=", "filteredParsers", ".", "length", ">", "0", "?", "filteredParsers", ":", "allParsers", ";", "// Run the parsers, in order, until one of them succeeds", "plugins", ".", "sort", "(", "parsers", ")", ";", "plugins", ".", "run", "(", "parsers", ",", "\"parse\"", ",", "file", ")", ".", "then", "(", "onParsed", ",", "onError", ")", ";", "function", "onParsed", "(", "parser", ")", "{", "if", "(", "!", "parser", ".", "plugin", ".", "allowEmpty", "&&", "isEmpty", "(", "parser", ".", "result", ")", ")", "{", "reject", "(", "ono", ".", "syntax", "(", "'Error parsing \"%s\" as %s. \\nParsed value is empty'", ",", "file", ".", "url", ",", "parser", ".", "plugin", ".", "name", ")", ")", ";", "}", "else", "{", "resolve", "(", "parser", ")", ";", "}", "}", "function", "onError", "(", "err", ")", "{", "if", "(", "err", ")", "{", "err", "=", "err", "instanceof", "Error", "?", "err", ":", "new", "Error", "(", "err", ")", ";", "reject", "(", "ono", ".", "syntax", "(", "err", ",", "\"Error parsing %s\"", ",", "file", ".", "url", ")", ")", ";", "}", "else", "{", "reject", "(", "ono", ".", "syntax", "(", "\"Unable to parse %s\"", ",", "file", ".", "url", ")", ")", ";", "}", "}", "}", ")", ";", "}" ]
Parses the given file's contents, using the configured parser plugins. @param {object} file - An object containing information about the referenced file @param {string} file.url - The full URL of the referenced file @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver @param {$RefParserOptions} options @returns {Promise} The promise resolves with the parsed file contents and the parser that was used.
[ "Parses", "the", "given", "file", "s", "contents", "using", "the", "configured", "parser", "plugins", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/parse.js#L100-L135
11,938
APIDevTools/json-schema-ref-parser
lib/parse.js
isEmpty
function isEmpty (value) { return value === undefined || (typeof value === "object" && Object.keys(value).length === 0) || (typeof value === "string" && value.trim().length === 0) || (Buffer.isBuffer(value) && value.length === 0); }
javascript
function isEmpty (value) { return value === undefined || (typeof value === "object" && Object.keys(value).length === 0) || (typeof value === "string" && value.trim().length === 0) || (Buffer.isBuffer(value) && value.length === 0); }
[ "function", "isEmpty", "(", "value", ")", "{", "return", "value", "===", "undefined", "||", "(", "typeof", "value", "===", "\"object\"", "&&", "Object", ".", "keys", "(", "value", ")", ".", "length", "===", "0", ")", "||", "(", "typeof", "value", "===", "\"string\"", "&&", "value", ".", "trim", "(", ")", ".", "length", "===", "0", ")", "||", "(", "Buffer", ".", "isBuffer", "(", "value", ")", "&&", "value", ".", "length", "===", "0", ")", ";", "}" ]
Determines whether the parsed value is "empty". @param {*} value @returns {boolean}
[ "Determines", "whether", "the", "parsed", "value", "is", "empty", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/parse.js#L143-L148
11,939
APIDevTools/json-schema-ref-parser
lib/options.js
merge
function merge (target, source) { if (isMergeable(source)) { var keys = Object.keys(source); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var sourceSetting = source[key]; var targetSetting = target[key]; if (isMergeable(sourceSetting)) { // It's a nested object, so merge it recursively target[key] = merge(targetSetting || {}, sourceSetting); } else if (sourceSetting !== undefined) { // It's a scalar value, function, or array. No merging necessary. Just overwrite the target value. target[key] = sourceSetting; } } } return target; }
javascript
function merge (target, source) { if (isMergeable(source)) { var keys = Object.keys(source); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var sourceSetting = source[key]; var targetSetting = target[key]; if (isMergeable(sourceSetting)) { // It's a nested object, so merge it recursively target[key] = merge(targetSetting || {}, sourceSetting); } else if (sourceSetting !== undefined) { // It's a scalar value, function, or array. No merging necessary. Just overwrite the target value. target[key] = sourceSetting; } } } return target; }
[ "function", "merge", "(", "target", ",", "source", ")", "{", "if", "(", "isMergeable", "(", "source", ")", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "source", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", ";", "var", "sourceSetting", "=", "source", "[", "key", "]", ";", "var", "targetSetting", "=", "target", "[", "key", "]", ";", "if", "(", "isMergeable", "(", "sourceSetting", ")", ")", "{", "// It's a nested object, so merge it recursively", "target", "[", "key", "]", "=", "merge", "(", "targetSetting", "||", "{", "}", ",", "sourceSetting", ")", ";", "}", "else", "if", "(", "sourceSetting", "!==", "undefined", ")", "{", "// It's a scalar value, function, or array. No merging necessary. Just overwrite the target value.", "target", "[", "key", "]", "=", "sourceSetting", ";", "}", "}", "}", "return", "target", ";", "}" ]
Merges the properties of the source object into the target object. @param {object} target - The object that we're populating @param {?object} source - The options that are being merged @returns {object}
[ "Merges", "the", "properties", "of", "the", "source", "object", "into", "the", "target", "object", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/options.js#L80-L99
11,940
APIDevTools/json-schema-ref-parser
lib/options.js
isMergeable
function isMergeable (val) { return val && (typeof val === "object") && !Array.isArray(val) && !(val instanceof RegExp) && !(val instanceof Date); }
javascript
function isMergeable (val) { return val && (typeof val === "object") && !Array.isArray(val) && !(val instanceof RegExp) && !(val instanceof Date); }
[ "function", "isMergeable", "(", "val", ")", "{", "return", "val", "&&", "(", "typeof", "val", "===", "\"object\"", ")", "&&", "!", "Array", ".", "isArray", "(", "val", ")", "&&", "!", "(", "val", "instanceof", "RegExp", ")", "&&", "!", "(", "val", "instanceof", "Date", ")", ";", "}" ]
Determines whether the given value can be merged, or if it is a scalar value that should just override the target value. @param {*} val @returns {Boolean}
[ "Determines", "whether", "the", "given", "value", "can", "be", "merged", "or", "if", "it", "is", "a", "scalar", "value", "that", "should", "just", "override", "the", "target", "value", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/options.js#L108-L114
11,941
APIDevTools/json-schema-ref-parser
lib/resolve-external.js
crawl
function crawl (obj, path, $refs, options) { var promises = []; if (obj && typeof obj === "object") { if ($Ref.isExternal$Ref(obj)) { promises.push(resolve$Ref(obj, path, $refs, options)); } else { Object.keys(obj).forEach(function (key) { var keyPath = Pointer.join(path, key); var value = obj[key]; if ($Ref.isExternal$Ref(value)) { promises.push(resolve$Ref(value, keyPath, $refs, options)); } else { promises = promises.concat(crawl(value, keyPath, $refs, options)); } }); } } return promises; }
javascript
function crawl (obj, path, $refs, options) { var promises = []; if (obj && typeof obj === "object") { if ($Ref.isExternal$Ref(obj)) { promises.push(resolve$Ref(obj, path, $refs, options)); } else { Object.keys(obj).forEach(function (key) { var keyPath = Pointer.join(path, key); var value = obj[key]; if ($Ref.isExternal$Ref(value)) { promises.push(resolve$Ref(value, keyPath, $refs, options)); } else { promises = promises.concat(crawl(value, keyPath, $refs, options)); } }); } } return promises; }
[ "function", "crawl", "(", "obj", ",", "path", ",", "$refs", ",", "options", ")", "{", "var", "promises", "=", "[", "]", ";", "if", "(", "obj", "&&", "typeof", "obj", "===", "\"object\"", ")", "{", "if", "(", "$Ref", ".", "isExternal$Ref", "(", "obj", ")", ")", "{", "promises", ".", "push", "(", "resolve$Ref", "(", "obj", ",", "path", ",", "$refs", ",", "options", ")", ")", ";", "}", "else", "{", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "keyPath", "=", "Pointer", ".", "join", "(", "path", ",", "key", ")", ";", "var", "value", "=", "obj", "[", "key", "]", ";", "if", "(", "$Ref", ".", "isExternal$Ref", "(", "value", ")", ")", "{", "promises", ".", "push", "(", "resolve$Ref", "(", "value", ",", "keyPath", ",", "$refs", ",", "options", ")", ")", ";", "}", "else", "{", "promises", "=", "promises", ".", "concat", "(", "crawl", "(", "value", ",", "keyPath", ",", "$refs", ",", "options", ")", ")", ";", "}", "}", ")", ";", "}", "}", "return", "promises", ";", "}" ]
Recursively crawls the given value, and resolves any external JSON references. @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored. @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash @param {$Refs} $refs @param {$RefParserOptions} options @returns {Promise[]} Returns an array of promises. There will be one promise for each JSON reference in `obj`. If `obj` does not contain any JSON references, then the array will be empty. If any of the JSON references point to files that contain additional JSON references, then the corresponding promise will internally reference an array of promises.
[ "Recursively", "crawls", "the", "given", "value", "and", "resolves", "any", "external", "JSON", "references", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/resolve-external.js#L53-L76
11,942
APIDevTools/json-schema-ref-parser
lib/resolve-external.js
resolve$Ref
function resolve$Ref ($ref, path, $refs, options) { // console.log('Resolving $ref pointer "%s" at %s', $ref.$ref, path); var resolvedPath = url.resolve(path, $ref.$ref); var withoutHash = url.stripHash(resolvedPath); // Do we already have this $ref? $ref = $refs._$refs[withoutHash]; if ($ref) { // We've already parsed this $ref, so use the existing value return Promise.resolve($ref.value); } // Parse the $referenced file/url return parse(resolvedPath, $refs, options) .then(function (result) { // Crawl the parsed value // console.log('Resolving $ref pointers in %s', withoutHash); var promises = crawl(result, withoutHash + "#", $refs, options); return Promise.all(promises); }); }
javascript
function resolve$Ref ($ref, path, $refs, options) { // console.log('Resolving $ref pointer "%s" at %s', $ref.$ref, path); var resolvedPath = url.resolve(path, $ref.$ref); var withoutHash = url.stripHash(resolvedPath); // Do we already have this $ref? $ref = $refs._$refs[withoutHash]; if ($ref) { // We've already parsed this $ref, so use the existing value return Promise.resolve($ref.value); } // Parse the $referenced file/url return parse(resolvedPath, $refs, options) .then(function (result) { // Crawl the parsed value // console.log('Resolving $ref pointers in %s', withoutHash); var promises = crawl(result, withoutHash + "#", $refs, options); return Promise.all(promises); }); }
[ "function", "resolve$Ref", "(", "$ref", ",", "path", ",", "$refs", ",", "options", ")", "{", "// console.log('Resolving $ref pointer \"%s\" at %s', $ref.$ref, path);", "var", "resolvedPath", "=", "url", ".", "resolve", "(", "path", ",", "$ref", ".", "$ref", ")", ";", "var", "withoutHash", "=", "url", ".", "stripHash", "(", "resolvedPath", ")", ";", "// Do we already have this $ref?", "$ref", "=", "$refs", ".", "_$refs", "[", "withoutHash", "]", ";", "if", "(", "$ref", ")", "{", "// We've already parsed this $ref, so use the existing value", "return", "Promise", ".", "resolve", "(", "$ref", ".", "value", ")", ";", "}", "// Parse the $referenced file/url", "return", "parse", "(", "resolvedPath", ",", "$refs", ",", "options", ")", ".", "then", "(", "function", "(", "result", ")", "{", "// Crawl the parsed value", "// console.log('Resolving $ref pointers in %s', withoutHash);", "var", "promises", "=", "crawl", "(", "result", ",", "withoutHash", "+", "\"#\"", ",", "$refs", ",", "options", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ";", "}", ")", ";", "}" ]
Resolves the given JSON Reference, and then crawls the resulting value. @param {{$ref: string}} $ref - The JSON Reference to resolve @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash @param {$Refs} $refs @param {$RefParserOptions} options @returns {Promise} The promise resolves once all JSON references in the object have been resolved, including nested references that are contained in externally-referenced files.
[ "Resolves", "the", "given", "JSON", "Reference", "and", "then", "crawls", "the", "resulting", "value", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/resolve-external.js#L90-L111
11,943
APIDevTools/json-schema-ref-parser
lib/bundle.js
crawl
function crawl (parent, key, path, pathFromRoot, indirections, inventory, $refs, options) { var obj = key === null ? parent : parent[key]; if (obj && typeof obj === "object") { if ($Ref.isAllowed$Ref(obj)) { inventory$Ref(parent, key, path, pathFromRoot, indirections, inventory, $refs, options); } else { // Crawl the object in a specific order that's optimized for bundling. // This is important because it determines how `pathFromRoot` gets built, // which later determines which keys get dereferenced and which ones get remapped var keys = Object.keys(obj) .sort(function (a, b) { // Most people will expect references to be bundled into the the "definitions" property, // so we always crawl that property first, if it exists. if (a === "definitions") { return -1; } else if (b === "definitions") { return 1; } else { // Otherwise, crawl the keys based on their length. // This produces the shortest possible bundled references return a.length - b.length; } }); keys.forEach(function (key) { var keyPath = Pointer.join(path, key); var keyPathFromRoot = Pointer.join(pathFromRoot, key); var value = obj[key]; if ($Ref.isAllowed$Ref(value)) { inventory$Ref(obj, key, path, keyPathFromRoot, indirections, inventory, $refs, options); } else { crawl(obj, key, keyPath, keyPathFromRoot, indirections, inventory, $refs, options); } }); } } }
javascript
function crawl (parent, key, path, pathFromRoot, indirections, inventory, $refs, options) { var obj = key === null ? parent : parent[key]; if (obj && typeof obj === "object") { if ($Ref.isAllowed$Ref(obj)) { inventory$Ref(parent, key, path, pathFromRoot, indirections, inventory, $refs, options); } else { // Crawl the object in a specific order that's optimized for bundling. // This is important because it determines how `pathFromRoot` gets built, // which later determines which keys get dereferenced and which ones get remapped var keys = Object.keys(obj) .sort(function (a, b) { // Most people will expect references to be bundled into the the "definitions" property, // so we always crawl that property first, if it exists. if (a === "definitions") { return -1; } else if (b === "definitions") { return 1; } else { // Otherwise, crawl the keys based on their length. // This produces the shortest possible bundled references return a.length - b.length; } }); keys.forEach(function (key) { var keyPath = Pointer.join(path, key); var keyPathFromRoot = Pointer.join(pathFromRoot, key); var value = obj[key]; if ($Ref.isAllowed$Ref(value)) { inventory$Ref(obj, key, path, keyPathFromRoot, indirections, inventory, $refs, options); } else { crawl(obj, key, keyPath, keyPathFromRoot, indirections, inventory, $refs, options); } }); } } }
[ "function", "crawl", "(", "parent", ",", "key", ",", "path", ",", "pathFromRoot", ",", "indirections", ",", "inventory", ",", "$refs", ",", "options", ")", "{", "var", "obj", "=", "key", "===", "null", "?", "parent", ":", "parent", "[", "key", "]", ";", "if", "(", "obj", "&&", "typeof", "obj", "===", "\"object\"", ")", "{", "if", "(", "$Ref", ".", "isAllowed$Ref", "(", "obj", ")", ")", "{", "inventory$Ref", "(", "parent", ",", "key", ",", "path", ",", "pathFromRoot", ",", "indirections", ",", "inventory", ",", "$refs", ",", "options", ")", ";", "}", "else", "{", "// Crawl the object in a specific order that's optimized for bundling.", "// This is important because it determines how `pathFromRoot` gets built,", "// which later determines which keys get dereferenced and which ones get remapped", "var", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "// Most people will expect references to be bundled into the the \"definitions\" property,", "// so we always crawl that property first, if it exists.", "if", "(", "a", "===", "\"definitions\"", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "b", "===", "\"definitions\"", ")", "{", "return", "1", ";", "}", "else", "{", "// Otherwise, crawl the keys based on their length.", "// This produces the shortest possible bundled references", "return", "a", ".", "length", "-", "b", ".", "length", ";", "}", "}", ")", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "keyPath", "=", "Pointer", ".", "join", "(", "path", ",", "key", ")", ";", "var", "keyPathFromRoot", "=", "Pointer", ".", "join", "(", "pathFromRoot", ",", "key", ")", ";", "var", "value", "=", "obj", "[", "key", "]", ";", "if", "(", "$Ref", ".", "isAllowed$Ref", "(", "value", ")", ")", "{", "inventory$Ref", "(", "obj", ",", "key", ",", "path", ",", "keyPathFromRoot", ",", "indirections", ",", "inventory", ",", "$refs", ",", "options", ")", ";", "}", "else", "{", "crawl", "(", "obj", ",", "key", ",", "keyPath", ",", "keyPathFromRoot", ",", "indirections", ",", "inventory", ",", "$refs", ",", "options", ")", ";", "}", "}", ")", ";", "}", "}", "}" ]
Recursively crawls the given value, and inventories all JSON references. @param {object} parent - The object containing the value to crawl. If the value is not an object or array, it will be ignored. @param {string} key - The property key of `parent` to be crawled @param {string} path - The full path of the property being crawled, possibly with a JSON Pointer in the hash @param {string} pathFromRoot - The path of the property being crawled, from the schema root @param {object[]} inventory - An array of already-inventoried $ref pointers @param {$Refs} $refs @param {$RefParserOptions} options
[ "Recursively", "crawls", "the", "given", "value", "and", "inventories", "all", "JSON", "references", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/bundle.js#L39-L81
11,944
APIDevTools/json-schema-ref-parser
lib/parsers/text.js
parseText
function parseText (file) { if (typeof file.data === "string") { return file.data; } else if (Buffer.isBuffer(file.data)) { return file.data.toString(this.encoding); } else { throw new Error("data is not text"); } }
javascript
function parseText (file) { if (typeof file.data === "string") { return file.data; } else if (Buffer.isBuffer(file.data)) { return file.data.toString(this.encoding); } else { throw new Error("data is not text"); } }
[ "function", "parseText", "(", "file", ")", "{", "if", "(", "typeof", "file", ".", "data", "===", "\"string\"", ")", "{", "return", "file", ".", "data", ";", "}", "else", "if", "(", "Buffer", ".", "isBuffer", "(", "file", ".", "data", ")", ")", "{", "return", "file", ".", "data", ".", "toString", "(", "this", ".", "encoding", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"data is not text\"", ")", ";", "}", "}" ]
Parses the given file as text @param {object} file - An object containing information about the referenced file @param {string} file.url - The full URL of the referenced file @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver @returns {Promise<string>}
[ "Parses", "the", "given", "file", "as", "text" ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/parsers/text.js#L53-L63
11,945
APIDevTools/json-schema-ref-parser
lib/refs.js
getPaths
function getPaths ($refs, types) { var paths = Object.keys($refs); // Filter the paths by type types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types); if (types.length > 0 && types[0]) { paths = paths.filter(function (key) { return types.indexOf($refs[key].pathType) !== -1; }); } // Decode local filesystem paths return paths.map(function (path) { return { encoded: path, decoded: $refs[path].pathType === "file" ? url.toFileSystemPath(path, true) : path }; }); }
javascript
function getPaths ($refs, types) { var paths = Object.keys($refs); // Filter the paths by type types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types); if (types.length > 0 && types[0]) { paths = paths.filter(function (key) { return types.indexOf($refs[key].pathType) !== -1; }); } // Decode local filesystem paths return paths.map(function (path) { return { encoded: path, decoded: $refs[path].pathType === "file" ? url.toFileSystemPath(path, true) : path }; }); }
[ "function", "getPaths", "(", "$refs", ",", "types", ")", "{", "var", "paths", "=", "Object", ".", "keys", "(", "$refs", ")", ";", "// Filter the paths by type\r", "types", "=", "Array", ".", "isArray", "(", "types", "[", "0", "]", ")", "?", "types", "[", "0", "]", ":", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "types", ")", ";", "if", "(", "types", ".", "length", ">", "0", "&&", "types", "[", "0", "]", ")", "{", "paths", "=", "paths", ".", "filter", "(", "function", "(", "key", ")", "{", "return", "types", ".", "indexOf", "(", "$refs", "[", "key", "]", ".", "pathType", ")", "!==", "-", "1", ";", "}", ")", ";", "}", "// Decode local filesystem paths\r", "return", "paths", ".", "map", "(", "function", "(", "path", ")", "{", "return", "{", "encoded", ":", "path", ",", "decoded", ":", "$refs", "[", "path", "]", ".", "pathType", "===", "\"file\"", "?", "url", ".", "toFileSystemPath", "(", "path", ",", "true", ")", ":", "path", "}", ";", "}", ")", ";", "}" ]
Returns the encoded and decoded paths keys of the given object. @param {object} $refs - The object whose keys are URL-encoded paths @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.) @returns {object[]}
[ "Returns", "the", "encoded", "and", "decoded", "paths", "keys", "of", "the", "given", "object", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/refs.js#L178-L196
11,946
APIDevTools/json-schema-ref-parser
lib/pointer.js
Pointer
function Pointer ($ref, path, friendlyPath) { /** * The {@link $Ref} object that contains this {@link Pointer} object. * @type {$Ref} */ this.$ref = $ref; /** * The file path or URL, containing the JSON pointer in the hash. * This path is relative to the path of the main JSON schema file. * @type {string} */ this.path = path; /** * The original path or URL, used for error messages. * @type {string} */ this.originalPath = friendlyPath || path; /** * The value of the JSON pointer. * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays). * @type {?*} */ this.value = undefined; /** * Indicates whether the pointer references itself. * @type {boolean} */ this.circular = false; /** * The number of indirect references that were traversed to resolve the value. * Resolving a single pointer may require resolving multiple $Refs. * @type {number} */ this.indirections = 0; }
javascript
function Pointer ($ref, path, friendlyPath) { /** * The {@link $Ref} object that contains this {@link Pointer} object. * @type {$Ref} */ this.$ref = $ref; /** * The file path or URL, containing the JSON pointer in the hash. * This path is relative to the path of the main JSON schema file. * @type {string} */ this.path = path; /** * The original path or URL, used for error messages. * @type {string} */ this.originalPath = friendlyPath || path; /** * The value of the JSON pointer. * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays). * @type {?*} */ this.value = undefined; /** * Indicates whether the pointer references itself. * @type {boolean} */ this.circular = false; /** * The number of indirect references that were traversed to resolve the value. * Resolving a single pointer may require resolving multiple $Refs. * @type {number} */ this.indirections = 0; }
[ "function", "Pointer", "(", "$ref", ",", "path", ",", "friendlyPath", ")", "{", "/**\n * The {@link $Ref} object that contains this {@link Pointer} object.\n * @type {$Ref}\n */", "this", ".", "$ref", "=", "$ref", ";", "/**\n * The file path or URL, containing the JSON pointer in the hash.\n * This path is relative to the path of the main JSON schema file.\n * @type {string}\n */", "this", ".", "path", "=", "path", ";", "/**\n * The original path or URL, used for error messages.\n * @type {string}\n */", "this", ".", "originalPath", "=", "friendlyPath", "||", "path", ";", "/**\n * The value of the JSON pointer.\n * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays).\n * @type {?*}\n */", "this", ".", "value", "=", "undefined", ";", "/**\n * Indicates whether the pointer references itself.\n * @type {boolean}\n */", "this", ".", "circular", "=", "false", ";", "/**\n * The number of indirect references that were traversed to resolve the value.\n * Resolving a single pointer may require resolving multiple $Refs.\n * @type {number}\n */", "this", ".", "indirections", "=", "0", ";", "}" ]
This class represents a single JSON pointer and its resolved value. @param {$Ref} $ref @param {string} path @param {string} [friendlyPath] - The original user-specified path (used for error messages) @constructor
[ "This", "class", "represents", "a", "single", "JSON", "pointer", "and", "its", "resolved", "value", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/pointer.js#L21-L60
11,947
APIDevTools/json-schema-ref-parser
lib/dereference.js
dereference
function dereference (parser, options) { // console.log('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path); var dereferenced = crawl(parser.schema, parser.$refs._root$Ref.path, "#", [], parser.$refs, options); parser.$refs.circular = dereferenced.circular; parser.schema = dereferenced.value; }
javascript
function dereference (parser, options) { // console.log('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path); var dereferenced = crawl(parser.schema, parser.$refs._root$Ref.path, "#", [], parser.$refs, options); parser.$refs.circular = dereferenced.circular; parser.schema = dereferenced.value; }
[ "function", "dereference", "(", "parser", ",", "options", ")", "{", "// console.log('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path);\r", "var", "dereferenced", "=", "crawl", "(", "parser", ".", "schema", ",", "parser", ".", "$refs", ".", "_root$Ref", ".", "path", ",", "\"#\"", ",", "[", "]", ",", "parser", ".", "$refs", ",", "options", ")", ";", "parser", ".", "$refs", ".", "circular", "=", "dereferenced", ".", "circular", ";", "parser", ".", "schema", "=", "dereferenced", ".", "value", ";", "}" ]
Crawls the JSON schema, finds all JSON references, and dereferences them. This method mutates the JSON schema object, replacing JSON references with their resolved value. @param {$RefParser} parser @param {$RefParserOptions} options
[ "Crawls", "the", "JSON", "schema", "finds", "all", "JSON", "references", "and", "dereferences", "them", ".", "This", "method", "mutates", "the", "JSON", "schema", "object", "replacing", "JSON", "references", "with", "their", "resolved", "value", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/dereference.js#L17-L22
11,948
APIDevTools/json-schema-ref-parser
lib/dereference.js
crawl
function crawl (obj, path, pathFromRoot, parents, $refs, options) { var dereferenced; var result = { value: obj, circular: false }; if (obj && typeof obj === "object") { parents.push(obj); if ($Ref.isAllowed$Ref(obj, options)) { dereferenced = dereference$Ref(obj, path, pathFromRoot, parents, $refs, options); result.circular = dereferenced.circular; result.value = dereferenced.value; } else { Object.keys(obj).forEach(function (key) { var keyPath = Pointer.join(path, key); var keyPathFromRoot = Pointer.join(pathFromRoot, key); var value = obj[key]; var circular = false; if ($Ref.isAllowed$Ref(value, options)) { dereferenced = dereference$Ref(value, keyPath, keyPathFromRoot, parents, $refs, options); circular = dereferenced.circular; obj[key] = dereferenced.value; } else { if (parents.indexOf(value) === -1) { dereferenced = crawl(value, keyPath, keyPathFromRoot, parents, $refs, options); circular = dereferenced.circular; obj[key] = dereferenced.value; } else { circular = foundCircularReference(keyPath, $refs, options); } } // Set the "isCircular" flag if this or any other property is circular result.circular = result.circular || circular; }); } parents.pop(); } return result; }
javascript
function crawl (obj, path, pathFromRoot, parents, $refs, options) { var dereferenced; var result = { value: obj, circular: false }; if (obj && typeof obj === "object") { parents.push(obj); if ($Ref.isAllowed$Ref(obj, options)) { dereferenced = dereference$Ref(obj, path, pathFromRoot, parents, $refs, options); result.circular = dereferenced.circular; result.value = dereferenced.value; } else { Object.keys(obj).forEach(function (key) { var keyPath = Pointer.join(path, key); var keyPathFromRoot = Pointer.join(pathFromRoot, key); var value = obj[key]; var circular = false; if ($Ref.isAllowed$Ref(value, options)) { dereferenced = dereference$Ref(value, keyPath, keyPathFromRoot, parents, $refs, options); circular = dereferenced.circular; obj[key] = dereferenced.value; } else { if (parents.indexOf(value) === -1) { dereferenced = crawl(value, keyPath, keyPathFromRoot, parents, $refs, options); circular = dereferenced.circular; obj[key] = dereferenced.value; } else { circular = foundCircularReference(keyPath, $refs, options); } } // Set the "isCircular" flag if this or any other property is circular result.circular = result.circular || circular; }); } parents.pop(); } return result; }
[ "function", "crawl", "(", "obj", ",", "path", ",", "pathFromRoot", ",", "parents", ",", "$refs", ",", "options", ")", "{", "var", "dereferenced", ";", "var", "result", "=", "{", "value", ":", "obj", ",", "circular", ":", "false", "}", ";", "if", "(", "obj", "&&", "typeof", "obj", "===", "\"object\"", ")", "{", "parents", ".", "push", "(", "obj", ")", ";", "if", "(", "$Ref", ".", "isAllowed$Ref", "(", "obj", ",", "options", ")", ")", "{", "dereferenced", "=", "dereference$Ref", "(", "obj", ",", "path", ",", "pathFromRoot", ",", "parents", ",", "$refs", ",", "options", ")", ";", "result", ".", "circular", "=", "dereferenced", ".", "circular", ";", "result", ".", "value", "=", "dereferenced", ".", "value", ";", "}", "else", "{", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "keyPath", "=", "Pointer", ".", "join", "(", "path", ",", "key", ")", ";", "var", "keyPathFromRoot", "=", "Pointer", ".", "join", "(", "pathFromRoot", ",", "key", ")", ";", "var", "value", "=", "obj", "[", "key", "]", ";", "var", "circular", "=", "false", ";", "if", "(", "$Ref", ".", "isAllowed$Ref", "(", "value", ",", "options", ")", ")", "{", "dereferenced", "=", "dereference$Ref", "(", "value", ",", "keyPath", ",", "keyPathFromRoot", ",", "parents", ",", "$refs", ",", "options", ")", ";", "circular", "=", "dereferenced", ".", "circular", ";", "obj", "[", "key", "]", "=", "dereferenced", ".", "value", ";", "}", "else", "{", "if", "(", "parents", ".", "indexOf", "(", "value", ")", "===", "-", "1", ")", "{", "dereferenced", "=", "crawl", "(", "value", ",", "keyPath", ",", "keyPathFromRoot", ",", "parents", ",", "$refs", ",", "options", ")", ";", "circular", "=", "dereferenced", ".", "circular", ";", "obj", "[", "key", "]", "=", "dereferenced", ".", "value", ";", "}", "else", "{", "circular", "=", "foundCircularReference", "(", "keyPath", ",", "$refs", ",", "options", ")", ";", "}", "}", "// Set the \"isCircular\" flag if this or any other property is circular\r", "result", ".", "circular", "=", "result", ".", "circular", "||", "circular", ";", "}", ")", ";", "}", "parents", ".", "pop", "(", ")", ";", "}", "return", "result", ";", "}" ]
Recursively crawls the given value, and dereferences any JSON references. @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored. @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash @param {string} pathFromRoot - The path of `obj` from the schema root @param {object[]} parents - An array of the parent objects that have already been dereferenced @param {$Refs} $refs @param {$RefParserOptions} options @returns {{value: object, circular: boolean}}
[ "Recursively", "crawls", "the", "given", "value", "and", "dereferences", "any", "JSON", "references", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/dereference.js#L35-L82
11,949
APIDevTools/json-schema-ref-parser
lib/dereference.js
dereference$Ref
function dereference$Ref ($ref, path, pathFromRoot, parents, $refs, options) { // console.log('Dereferencing $ref pointer "%s" at %s', $ref.$ref, path); var $refPath = url.resolve(path, $ref.$ref); var pointer = $refs._resolve($refPath, options); // Check for circular references var directCircular = pointer.circular; var circular = directCircular || parents.indexOf(pointer.value) !== -1; circular && foundCircularReference(path, $refs, options); // Dereference the JSON reference var dereferencedValue = $Ref.dereference($ref, pointer.value); // Crawl the dereferenced value (unless it's circular) if (!circular) { // Determine if the dereferenced value is circular var dereferenced = crawl(dereferencedValue, pointer.path, pathFromRoot, parents, $refs, options); circular = dereferenced.circular; dereferencedValue = dereferenced.value; } if (circular && !directCircular && options.dereference.circular === "ignore") { // The user has chosen to "ignore" circular references, so don't change the value dereferencedValue = $ref; } if (directCircular) { // The pointer is a DIRECT circular reference (i.e. it references itself). // So replace the $ref path with the absolute path from the JSON Schema root dereferencedValue.$ref = pathFromRoot; } return { circular: circular, value: dereferencedValue }; }
javascript
function dereference$Ref ($ref, path, pathFromRoot, parents, $refs, options) { // console.log('Dereferencing $ref pointer "%s" at %s', $ref.$ref, path); var $refPath = url.resolve(path, $ref.$ref); var pointer = $refs._resolve($refPath, options); // Check for circular references var directCircular = pointer.circular; var circular = directCircular || parents.indexOf(pointer.value) !== -1; circular && foundCircularReference(path, $refs, options); // Dereference the JSON reference var dereferencedValue = $Ref.dereference($ref, pointer.value); // Crawl the dereferenced value (unless it's circular) if (!circular) { // Determine if the dereferenced value is circular var dereferenced = crawl(dereferencedValue, pointer.path, pathFromRoot, parents, $refs, options); circular = dereferenced.circular; dereferencedValue = dereferenced.value; } if (circular && !directCircular && options.dereference.circular === "ignore") { // The user has chosen to "ignore" circular references, so don't change the value dereferencedValue = $ref; } if (directCircular) { // The pointer is a DIRECT circular reference (i.e. it references itself). // So replace the $ref path with the absolute path from the JSON Schema root dereferencedValue.$ref = pathFromRoot; } return { circular: circular, value: dereferencedValue }; }
[ "function", "dereference$Ref", "(", "$ref", ",", "path", ",", "pathFromRoot", ",", "parents", ",", "$refs", ",", "options", ")", "{", "// console.log('Dereferencing $ref pointer \"%s\" at %s', $ref.$ref, path);\r", "var", "$refPath", "=", "url", ".", "resolve", "(", "path", ",", "$ref", ".", "$ref", ")", ";", "var", "pointer", "=", "$refs", ".", "_resolve", "(", "$refPath", ",", "options", ")", ";", "// Check for circular references\r", "var", "directCircular", "=", "pointer", ".", "circular", ";", "var", "circular", "=", "directCircular", "||", "parents", ".", "indexOf", "(", "pointer", ".", "value", ")", "!==", "-", "1", ";", "circular", "&&", "foundCircularReference", "(", "path", ",", "$refs", ",", "options", ")", ";", "// Dereference the JSON reference\r", "var", "dereferencedValue", "=", "$Ref", ".", "dereference", "(", "$ref", ",", "pointer", ".", "value", ")", ";", "// Crawl the dereferenced value (unless it's circular)\r", "if", "(", "!", "circular", ")", "{", "// Determine if the dereferenced value is circular\r", "var", "dereferenced", "=", "crawl", "(", "dereferencedValue", ",", "pointer", ".", "path", ",", "pathFromRoot", ",", "parents", ",", "$refs", ",", "options", ")", ";", "circular", "=", "dereferenced", ".", "circular", ";", "dereferencedValue", "=", "dereferenced", ".", "value", ";", "}", "if", "(", "circular", "&&", "!", "directCircular", "&&", "options", ".", "dereference", ".", "circular", "===", "\"ignore\"", ")", "{", "// The user has chosen to \"ignore\" circular references, so don't change the value\r", "dereferencedValue", "=", "$ref", ";", "}", "if", "(", "directCircular", ")", "{", "// The pointer is a DIRECT circular reference (i.e. it references itself).\r", "// So replace the $ref path with the absolute path from the JSON Schema root\r", "dereferencedValue", ".", "$ref", "=", "pathFromRoot", ";", "}", "return", "{", "circular", ":", "circular", ",", "value", ":", "dereferencedValue", "}", ";", "}" ]
Dereferences the given JSON Reference, and then crawls the resulting value. @param {{$ref: string}} $ref - The JSON Reference to resolve @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash @param {string} pathFromRoot - The path of `$ref` from the schema root @param {object[]} parents - An array of the parent objects that have already been dereferenced @param {$Refs} $refs @param {$RefParserOptions} options @returns {{value: object, circular: boolean}}
[ "Dereferences", "the", "given", "JSON", "Reference", "and", "then", "crawls", "the", "resulting", "value", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/dereference.js#L95-L132
11,950
APIDevTools/json-schema-ref-parser
lib/resolvers/http.js
readHttp
function readHttp (file) { var u = url.parse(file.url); if (process.browser && !u.protocol) { // Use the protocol of the current page u.protocol = url.parse(location.href).protocol; } return download(u, this); }
javascript
function readHttp (file) { var u = url.parse(file.url); if (process.browser && !u.protocol) { // Use the protocol of the current page u.protocol = url.parse(location.href).protocol; } return download(u, this); }
[ "function", "readHttp", "(", "file", ")", "{", "var", "u", "=", "url", ".", "parse", "(", "file", ".", "url", ")", ";", "if", "(", "process", ".", "browser", "&&", "!", "u", ".", "protocol", ")", "{", "// Use the protocol of the current page", "u", ".", "protocol", "=", "url", ".", "parse", "(", "location", ".", "href", ")", ".", "protocol", ";", "}", "return", "download", "(", "u", ",", "this", ")", ";", "}" ]
Reads the given URL and returns its raw contents as a Buffer. @param {object} file - An object containing information about the referenced file @param {string} file.url - The full URL of the referenced file @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) @returns {Promise<Buffer>}
[ "Reads", "the", "given", "URL", "and", "returns", "its", "raw", "contents", "as", "a", "Buffer", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/resolvers/http.js#L74-L83
11,951
APIDevTools/json-schema-ref-parser
lib/resolvers/http.js
get
function get (u, httpOptions) { return new Promise(function (resolve, reject) { // console.log('GET', u.href); var protocol = u.protocol === "https:" ? https : http; var req = protocol.get({ hostname: u.hostname, port: u.port, path: u.path, auth: u.auth, protocol: u.protocol, headers: httpOptions.headers || {}, withCredentials: httpOptions.withCredentials }); if (typeof req.setTimeout === "function") { req.setTimeout(httpOptions.timeout); } req.on("timeout", function () { req.abort(); }); req.on("error", reject); req.once("response", function (res) { res.body = new Buffer(0); res.on("data", function (data) { res.body = Buffer.concat([res.body, new Buffer(data)]); }); res.on("error", reject); res.on("end", function () { resolve(res); }); }); }); }
javascript
function get (u, httpOptions) { return new Promise(function (resolve, reject) { // console.log('GET', u.href); var protocol = u.protocol === "https:" ? https : http; var req = protocol.get({ hostname: u.hostname, port: u.port, path: u.path, auth: u.auth, protocol: u.protocol, headers: httpOptions.headers || {}, withCredentials: httpOptions.withCredentials }); if (typeof req.setTimeout === "function") { req.setTimeout(httpOptions.timeout); } req.on("timeout", function () { req.abort(); }); req.on("error", reject); req.once("response", function (res) { res.body = new Buffer(0); res.on("data", function (data) { res.body = Buffer.concat([res.body, new Buffer(data)]); }); res.on("error", reject); res.on("end", function () { resolve(res); }); }); }); }
[ "function", "get", "(", "u", ",", "httpOptions", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "// console.log('GET', u.href);", "var", "protocol", "=", "u", ".", "protocol", "===", "\"https:\"", "?", "https", ":", "http", ";", "var", "req", "=", "protocol", ".", "get", "(", "{", "hostname", ":", "u", ".", "hostname", ",", "port", ":", "u", ".", "port", ",", "path", ":", "u", ".", "path", ",", "auth", ":", "u", ".", "auth", ",", "protocol", ":", "u", ".", "protocol", ",", "headers", ":", "httpOptions", ".", "headers", "||", "{", "}", ",", "withCredentials", ":", "httpOptions", ".", "withCredentials", "}", ")", ";", "if", "(", "typeof", "req", ".", "setTimeout", "===", "\"function\"", ")", "{", "req", ".", "setTimeout", "(", "httpOptions", ".", "timeout", ")", ";", "}", "req", ".", "on", "(", "\"timeout\"", ",", "function", "(", ")", "{", "req", ".", "abort", "(", ")", ";", "}", ")", ";", "req", ".", "on", "(", "\"error\"", ",", "reject", ")", ";", "req", ".", "once", "(", "\"response\"", ",", "function", "(", "res", ")", "{", "res", ".", "body", "=", "new", "Buffer", "(", "0", ")", ";", "res", ".", "on", "(", "\"data\"", ",", "function", "(", "data", ")", "{", "res", ".", "body", "=", "Buffer", ".", "concat", "(", "[", "res", ".", "body", ",", "new", "Buffer", "(", "data", ")", "]", ")", ";", "}", ")", ";", "res", ".", "on", "(", "\"error\"", ",", "reject", ")", ";", "res", ".", "on", "(", "\"end\"", ",", "function", "(", ")", "{", "resolve", "(", "res", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Sends an HTTP GET request. @param {Url} u - A parsed {@link Url} object @param {object} httpOptions - The `options.resolve.http` object @returns {Promise<Response>} The promise resolves with the HTTP Response object.
[ "Sends", "an", "HTTP", "GET", "request", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/resolvers/http.js#L140-L179
11,952
APIDevTools/json-schema-ref-parser
lib/util/plugins.js
getResult
function getResult (obj, prop, file, callback) { var value = obj[prop]; if (typeof value === "function") { return value.apply(obj, [file, callback]); } if (!callback) { // The synchronous plugin functions (canParse and canRead) // allow a "shorthand" syntax, where the user can match // files by RegExp or by file extension. if (value instanceof RegExp) { return value.test(file.url); } else if (typeof value === "string") { return value === file.extension; } else if (Array.isArray(value)) { return value.indexOf(file.extension) !== -1; } } return value; }
javascript
function getResult (obj, prop, file, callback) { var value = obj[prop]; if (typeof value === "function") { return value.apply(obj, [file, callback]); } if (!callback) { // The synchronous plugin functions (canParse and canRead) // allow a "shorthand" syntax, where the user can match // files by RegExp or by file extension. if (value instanceof RegExp) { return value.test(file.url); } else if (typeof value === "string") { return value === file.extension; } else if (Array.isArray(value)) { return value.indexOf(file.extension) !== -1; } } return value; }
[ "function", "getResult", "(", "obj", ",", "prop", ",", "file", ",", "callback", ")", "{", "var", "value", "=", "obj", "[", "prop", "]", ";", "if", "(", "typeof", "value", "===", "\"function\"", ")", "{", "return", "value", ".", "apply", "(", "obj", ",", "[", "file", ",", "callback", "]", ")", ";", "}", "if", "(", "!", "callback", ")", "{", "// The synchronous plugin functions (canParse and canRead)", "// allow a \"shorthand\" syntax, where the user can match", "// files by RegExp or by file extension.", "if", "(", "value", "instanceof", "RegExp", ")", "{", "return", "value", ".", "test", "(", "file", ".", "url", ")", ";", "}", "else", "if", "(", "typeof", "value", "===", "\"string\"", ")", "{", "return", "value", "===", "file", ".", "extension", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "return", "value", ".", "indexOf", "(", "file", ".", "extension", ")", "!==", "-", "1", ";", "}", "}", "return", "value", ";", "}" ]
Returns the value of the given property. If the property is a function, then the result of the function is returned. If the value is a RegExp, then it will be tested against the file URL. If the value is an aray, then it will be compared against the file extension. @param {object} obj - The object whose property/method is called @param {string} prop - The name of the property/method to invoke @param {object} file - A file info object, which will be passed to the method @param {function} [callback] - A callback function, which will be passed to the method @returns {*}
[ "Returns", "the", "value", "of", "the", "given", "property", ".", "If", "the", "property", "is", "a", "function", "then", "the", "result", "of", "the", "function", "is", "returned", ".", "If", "the", "value", "is", "a", "RegExp", "then", "it", "will", "be", "tested", "against", "the", "file", "URL", ".", "If", "the", "value", "is", "an", "aray", "then", "it", "will", "be", "compared", "against", "the", "file", "extension", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/util/plugins.js#L131-L154
11,953
APIDevTools/json-schema-ref-parser
lib/parsers/yaml.js
parseYAML
function parseYAML (file) { return new Promise(function (resolve, reject) { var data = file.data; if (Buffer.isBuffer(data)) { data = data.toString(); } if (typeof data === "string") { resolve(YAML.parse(data)); } else { // data is already a JavaScript value (object, array, number, null, NaN, etc.) resolve(data); } }); }
javascript
function parseYAML (file) { return new Promise(function (resolve, reject) { var data = file.data; if (Buffer.isBuffer(data)) { data = data.toString(); } if (typeof data === "string") { resolve(YAML.parse(data)); } else { // data is already a JavaScript value (object, array, number, null, NaN, etc.) resolve(data); } }); }
[ "function", "parseYAML", "(", "file", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "data", "=", "file", ".", "data", ";", "if", "(", "Buffer", ".", "isBuffer", "(", "data", ")", ")", "{", "data", "=", "data", ".", "toString", "(", ")", ";", "}", "if", "(", "typeof", "data", "===", "\"string\"", ")", "{", "resolve", "(", "YAML", ".", "parse", "(", "data", ")", ")", ";", "}", "else", "{", "// data is already a JavaScript value (object, array, number, null, NaN, etc.)", "resolve", "(", "data", ")", ";", "}", "}", ")", ";", "}" ]
JSON is valid YAML Parses the given file as YAML @param {object} file - An object containing information about the referenced file @param {string} file.url - The full URL of the referenced file @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver @returns {Promise}
[ "JSON", "is", "valid", "YAML", "Parses", "the", "given", "file", "as", "YAML" ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/parsers/yaml.js#L39-L54
11,954
APIDevTools/json-schema-ref-parser
lib/normalize-args.js
normalizeArgs
function normalizeArgs (args) { var path, schema, options, callback; args = Array.prototype.slice.call(args); if (typeof args[args.length - 1] === "function") { // The last parameter is a callback function callback = args.pop(); } if (typeof args[0] === "string") { // The first parameter is the path path = args[0]; if (typeof args[2] === "object") { // The second parameter is the schema, and the third parameter is the options schema = args[1]; options = args[2]; } else { // The second parameter is the options schema = undefined; options = args[1]; } } else { // The first parameter is the schema path = ""; schema = args[0]; options = args[1]; } if (!(options instanceof Options)) { options = new Options(options); } return { path: path, schema: schema, options: options, callback: callback }; }
javascript
function normalizeArgs (args) { var path, schema, options, callback; args = Array.prototype.slice.call(args); if (typeof args[args.length - 1] === "function") { // The last parameter is a callback function callback = args.pop(); } if (typeof args[0] === "string") { // The first parameter is the path path = args[0]; if (typeof args[2] === "object") { // The second parameter is the schema, and the third parameter is the options schema = args[1]; options = args[2]; } else { // The second parameter is the options schema = undefined; options = args[1]; } } else { // The first parameter is the schema path = ""; schema = args[0]; options = args[1]; } if (!(options instanceof Options)) { options = new Options(options); } return { path: path, schema: schema, options: options, callback: callback }; }
[ "function", "normalizeArgs", "(", "args", ")", "{", "var", "path", ",", "schema", ",", "options", ",", "callback", ";", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "args", ")", ";", "if", "(", "typeof", "args", "[", "args", ".", "length", "-", "1", "]", "===", "\"function\"", ")", "{", "// The last parameter is a callback function", "callback", "=", "args", ".", "pop", "(", ")", ";", "}", "if", "(", "typeof", "args", "[", "0", "]", "===", "\"string\"", ")", "{", "// The first parameter is the path", "path", "=", "args", "[", "0", "]", ";", "if", "(", "typeof", "args", "[", "2", "]", "===", "\"object\"", ")", "{", "// The second parameter is the schema, and the third parameter is the options", "schema", "=", "args", "[", "1", "]", ";", "options", "=", "args", "[", "2", "]", ";", "}", "else", "{", "// The second parameter is the options", "schema", "=", "undefined", ";", "options", "=", "args", "[", "1", "]", ";", "}", "}", "else", "{", "// The first parameter is the schema", "path", "=", "\"\"", ";", "schema", "=", "args", "[", "0", "]", ";", "options", "=", "args", "[", "1", "]", ";", "}", "if", "(", "!", "(", "options", "instanceof", "Options", ")", ")", "{", "options", "=", "new", "Options", "(", "options", ")", ";", "}", "return", "{", "path", ":", "path", ",", "schema", ":", "schema", ",", "options", ":", "options", ",", "callback", ":", "callback", "}", ";", "}" ]
Normalizes the given arguments, accounting for optional args. @param {Arguments} args @returns {object}
[ "Normalizes", "the", "given", "arguments", "accounting", "for", "optional", "args", "." ]
29ea8693e288e5ced3ebd670d545925f16a4ed17
https://github.com/APIDevTools/json-schema-ref-parser/blob/29ea8693e288e5ced3ebd670d545925f16a4ed17/lib/normalize-args.js#L13-L53
11,955
cyrus-and/chrome-remote-interface
lib/devtools.js
promisesWrapper
function promisesWrapper(func) { return (options, callback) => { // options is an optional argument if (typeof options === 'function') { callback = options; options = undefined; } options = options || {}; // just call the function otherwise wrap a promise around its execution if (typeof callback === 'function') { func(options, callback); return undefined; } else { return new Promise((fulfill, reject) => { func(options, (err, result) => { if (err) { reject(err); } else { fulfill(result); } }); }); } }; }
javascript
function promisesWrapper(func) { return (options, callback) => { // options is an optional argument if (typeof options === 'function') { callback = options; options = undefined; } options = options || {}; // just call the function otherwise wrap a promise around its execution if (typeof callback === 'function') { func(options, callback); return undefined; } else { return new Promise((fulfill, reject) => { func(options, (err, result) => { if (err) { reject(err); } else { fulfill(result); } }); }); } }; }
[ "function", "promisesWrapper", "(", "func", ")", "{", "return", "(", "options", ",", "callback", ")", "=>", "{", "// options is an optional argument", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "undefined", ";", "}", "options", "=", "options", "||", "{", "}", ";", "// just call the function otherwise wrap a promise around its execution", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "func", "(", "options", ",", "callback", ")", ";", "return", "undefined", ";", "}", "else", "{", "return", "new", "Promise", "(", "(", "fulfill", ",", "reject", ")", "=>", "{", "func", "(", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "fulfill", "(", "result", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "}", ";", "}" ]
wrapper that allows to return a promise if the callback is omitted, it works for DevTools methods
[ "wrapper", "that", "allows", "to", "return", "a", "promise", "if", "the", "callback", "is", "omitted", "it", "works", "for", "DevTools", "methods" ]
68309828ce3a08136fda1fc5224fababb49769f1
https://github.com/cyrus-and/chrome-remote-interface/blob/68309828ce3a08136fda1fc5224fababb49769f1/lib/devtools.js#L20-L44
11,956
xCss/Valine
src/utils/domReady.js
domReady
function domReady(callback) { if (doc.readyState === "complete" || (doc.readyState !== "loading" && !doc.documentElement.doScroll)) setTimeout(() => callback && callback(), 0) else { let handler = () => { doc.removeEventListener("DOMContentLoaded", handler, false) win.removeEventListener("load", handler, false) callback && callback() } doc.addEventListener("DOMContentLoaded", handler, false) win.addEventListener("load", handler, false) } }
javascript
function domReady(callback) { if (doc.readyState === "complete" || (doc.readyState !== "loading" && !doc.documentElement.doScroll)) setTimeout(() => callback && callback(), 0) else { let handler = () => { doc.removeEventListener("DOMContentLoaded", handler, false) win.removeEventListener("load", handler, false) callback && callback() } doc.addEventListener("DOMContentLoaded", handler, false) win.addEventListener("load", handler, false) } }
[ "function", "domReady", "(", "callback", ")", "{", "if", "(", "doc", ".", "readyState", "===", "\"complete\"", "||", "(", "doc", ".", "readyState", "!==", "\"loading\"", "&&", "!", "doc", ".", "documentElement", ".", "doScroll", ")", ")", "setTimeout", "(", "(", ")", "=>", "callback", "&&", "callback", "(", ")", ",", "0", ")", "else", "{", "let", "handler", "=", "(", ")", "=>", "{", "doc", ".", "removeEventListener", "(", "\"DOMContentLoaded\"", ",", "handler", ",", "false", ")", "win", ".", "removeEventListener", "(", "\"load\"", ",", "handler", ",", "false", ")", "callback", "&&", "callback", "(", ")", "}", "doc", ".", "addEventListener", "(", "\"DOMContentLoaded\"", ",", "handler", ",", "false", ")", "win", ".", "addEventListener", "(", "\"load\"", ",", "handler", ",", "false", ")", "}", "}" ]
Detection DOM is Ready @param {Function} callback
[ "Detection", "DOM", "is", "Ready" ]
fd1b2ecf8b0bfffe57da84f978053316c4d1897f
https://github.com/xCss/Valine/blob/fd1b2ecf8b0bfffe57da84f978053316c4d1897f/src/utils/domReady.js#L7-L19
11,957
xCss/Valine
src/utils/index.js
oReady
function oReady(o, callback) { !!o && (callback && callback()) || setTimeout(() => oReady(o, callback), 10) }
javascript
function oReady(o, callback) { !!o && (callback && callback()) || setTimeout(() => oReady(o, callback), 10) }
[ "function", "oReady", "(", "o", ",", "callback", ")", "{", "!", "!", "o", "&&", "(", "callback", "&&", "callback", "(", ")", ")", "||", "setTimeout", "(", "(", ")", "=>", "oReady", "(", "o", ",", "callback", ")", ",", "10", ")", "}" ]
Detection target Object is ready @param {Object} o @param {Function} callback
[ "Detection", "target", "Object", "is", "ready" ]
fd1b2ecf8b0bfffe57da84f978053316c4d1897f
https://github.com/xCss/Valine/blob/fd1b2ecf8b0bfffe57da84f978053316c4d1897f/src/utils/index.js#L16-L18
11,958
xCss/Valine
src/utils/deepClone.js
isCyclic
function isCyclic (data) { // Create an array that will store the nodes of the array that have already been iterated over let seenObjects = []; function detect (data) { // If the data pass is an object if (data && getType(data) === "Object") { // If the data is already in the seen nodes array then we know there is a circular reference // Therefore return true if (seenObjects.indexOf(data) !== -1) { return true; } // Add the data to the seen objects array seenObjects.push(data); // Begin iterating through the data passed to the method for (var key in data) { // Recall this method with the objects key if (data.hasOwnProperty(key) === true && detect(data[key])) { return true; } } } return false; } // Return the method return detect(data); }
javascript
function isCyclic (data) { // Create an array that will store the nodes of the array that have already been iterated over let seenObjects = []; function detect (data) { // If the data pass is an object if (data && getType(data) === "Object") { // If the data is already in the seen nodes array then we know there is a circular reference // Therefore return true if (seenObjects.indexOf(data) !== -1) { return true; } // Add the data to the seen objects array seenObjects.push(data); // Begin iterating through the data passed to the method for (var key in data) { // Recall this method with the objects key if (data.hasOwnProperty(key) === true && detect(data[key])) { return true; } } } return false; } // Return the method return detect(data); }
[ "function", "isCyclic", "(", "data", ")", "{", "// Create an array that will store the nodes of the array that have already been iterated over", "let", "seenObjects", "=", "[", "]", ";", "function", "detect", "(", "data", ")", "{", "// If the data pass is an object", "if", "(", "data", "&&", "getType", "(", "data", ")", "===", "\"Object\"", ")", "{", "// If the data is already in the seen nodes array then we know there is a circular reference", "// Therefore return true", "if", "(", "seenObjects", ".", "indexOf", "(", "data", ")", "!==", "-", "1", ")", "{", "return", "true", ";", "}", "// Add the data to the seen objects array", "seenObjects", ".", "push", "(", "data", ")", ";", "// Begin iterating through the data passed to the method", "for", "(", "var", "key", "in", "data", ")", "{", "// Recall this method with the objects key", "if", "(", "data", ".", "hasOwnProperty", "(", "key", ")", "===", "true", "&&", "detect", "(", "data", "[", "key", "]", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}", "// Return the method", "return", "detect", "(", "data", ")", ";", "}" ]
Create a method to detect whether an object contains a circular reference
[ "Create", "a", "method", "to", "detect", "whether", "an", "object", "contains", "a", "circular", "reference" ]
fd1b2ecf8b0bfffe57da84f978053316c4d1897f
https://github.com/xCss/Valine/blob/fd1b2ecf8b0bfffe57da84f978053316c4d1897f/src/utils/deepClone.js#L12-L43
11,959
flightjs/flight
lib/component.js
teardownAll
function teardownAll() { var componentInfo = registry.findComponentInfo(this); componentInfo && Object.keys(componentInfo.instances).forEach(function(k) { var info = componentInfo.instances[k]; // It's possible that a previous teardown caused another component to teardown, // so we can't assume that the instances object is as it was. if (info && info.instance) { info.instance.teardown(); } }); }
javascript
function teardownAll() { var componentInfo = registry.findComponentInfo(this); componentInfo && Object.keys(componentInfo.instances).forEach(function(k) { var info = componentInfo.instances[k]; // It's possible that a previous teardown caused another component to teardown, // so we can't assume that the instances object is as it was. if (info && info.instance) { info.instance.teardown(); } }); }
[ "function", "teardownAll", "(", ")", "{", "var", "componentInfo", "=", "registry", ".", "findComponentInfo", "(", "this", ")", ";", "componentInfo", "&&", "Object", ".", "keys", "(", "componentInfo", ".", "instances", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "var", "info", "=", "componentInfo", ".", "instances", "[", "k", "]", ";", "// It's possible that a previous teardown caused another component to teardown,", "// so we can't assume that the instances object is as it was.", "if", "(", "info", "&&", "info", ".", "instance", ")", "{", "info", ".", "instance", ".", "teardown", "(", ")", ";", "}", "}", ")", ";", "}" ]
teardown for all instances of this constructor
[ "teardown", "for", "all", "instances", "of", "this", "constructor" ]
f15b32277d2c55c6c595845a87109b09c913c556
https://github.com/flightjs/flight/blob/f15b32277d2c55c6c595845a87109b09c913c556/lib/component.js#L25-L36
11,960
twitter/hogan.js
web/builds/1.0.5/hogan-1.0.5.js
function(name, context, partials, indent) { var partial = partials[name]; if (!partial) { return ''; } if (this.c && typeof partial == 'string') { partial = this.c.compile(partial, this.options); } return partial.ri(context, partials, indent); }
javascript
function(name, context, partials, indent) { var partial = partials[name]; if (!partial) { return ''; } if (this.c && typeof partial == 'string') { partial = this.c.compile(partial, this.options); } return partial.ri(context, partials, indent); }
[ "function", "(", "name", ",", "context", ",", "partials", ",", "indent", ")", "{", "var", "partial", "=", "partials", "[", "name", "]", ";", "if", "(", "!", "partial", ")", "{", "return", "''", ";", "}", "if", "(", "this", ".", "c", "&&", "typeof", "partial", "==", "'string'", ")", "{", "partial", "=", "this", ".", "c", ".", "compile", "(", "partial", ",", "this", ".", "options", ")", ";", "}", "return", "partial", ".", "ri", "(", "context", ",", "partials", ",", "indent", ")", ";", "}" ]
tries to find a partial in the curent scope and render it
[ "tries", "to", "find", "a", "partial", "in", "the", "curent", "scope", "and", "render", "it" ]
7e340e9e4dde8faebd1ff34e62abc1c5dd8adb55
https://github.com/twitter/hogan.js/blob/7e340e9e4dde8faebd1ff34e62abc1c5dd8adb55/web/builds/1.0.5/hogan-1.0.5.js#L49-L61
11,961
twitter/hogan.js
web/builds/1.0.5/hogan-1.0.5.js
function(val, ctx, partials, inverted, start, end, tags) { var cx = ctx[ctx.length - 1], t = null; if (!inverted && this.c && val.length > 0) { return this.ho(val, cx, partials, this.text.substring(start, end), tags); } t = val.call(cx); if (typeof t == 'function') { if (inverted) { return true; } else if (this.c) { return this.ho(t, cx, partials, this.text.substring(start, end), tags); } } return t; }
javascript
function(val, ctx, partials, inverted, start, end, tags) { var cx = ctx[ctx.length - 1], t = null; if (!inverted && this.c && val.length > 0) { return this.ho(val, cx, partials, this.text.substring(start, end), tags); } t = val.call(cx); if (typeof t == 'function') { if (inverted) { return true; } else if (this.c) { return this.ho(t, cx, partials, this.text.substring(start, end), tags); } } return t; }
[ "function", "(", "val", ",", "ctx", ",", "partials", ",", "inverted", ",", "start", ",", "end", ",", "tags", ")", "{", "var", "cx", "=", "ctx", "[", "ctx", ".", "length", "-", "1", "]", ",", "t", "=", "null", ";", "if", "(", "!", "inverted", "&&", "this", ".", "c", "&&", "val", ".", "length", ">", "0", ")", "{", "return", "this", ".", "ho", "(", "val", ",", "cx", ",", "partials", ",", "this", ".", "text", ".", "substring", "(", "start", ",", "end", ")", ",", "tags", ")", ";", "}", "t", "=", "val", ".", "call", "(", "cx", ")", ";", "if", "(", "typeof", "t", "==", "'function'", ")", "{", "if", "(", "inverted", ")", "{", "return", "true", ";", "}", "else", "if", "(", "this", ".", "c", ")", "{", "return", "this", ".", "ho", "(", "t", ",", "cx", ",", "partials", ",", "this", ".", "text", ".", "substring", "(", "start", ",", "end", ")", ",", "tags", ")", ";", "}", "}", "return", "t", ";", "}" ]
lambda replace section
[ "lambda", "replace", "section" ]
7e340e9e4dde8faebd1ff34e62abc1c5dd8adb55
https://github.com/twitter/hogan.js/blob/7e340e9e4dde8faebd1ff34e62abc1c5dd8adb55/web/builds/1.0.5/hogan-1.0.5.js#L177-L196
11,962
twitter/hogan.js
web/builds/1.0.5/hogan-1.0.5.js
function(val, ctx, partials) { var cx = ctx[ctx.length - 1]; var result = val.call(cx); if (typeof result == 'function') { result = result.call(cx); } result = coerceToString(result); if (this.c && ~result.indexOf("{\u007B")) { return this.c.compile(result, this.options).render(cx, partials); } return result; }
javascript
function(val, ctx, partials) { var cx = ctx[ctx.length - 1]; var result = val.call(cx); if (typeof result == 'function') { result = result.call(cx); } result = coerceToString(result); if (this.c && ~result.indexOf("{\u007B")) { return this.c.compile(result, this.options).render(cx, partials); } return result; }
[ "function", "(", "val", ",", "ctx", ",", "partials", ")", "{", "var", "cx", "=", "ctx", "[", "ctx", ".", "length", "-", "1", "]", ";", "var", "result", "=", "val", ".", "call", "(", "cx", ")", ";", "if", "(", "typeof", "result", "==", "'function'", ")", "{", "result", "=", "result", ".", "call", "(", "cx", ")", ";", "}", "result", "=", "coerceToString", "(", "result", ")", ";", "if", "(", "this", ".", "c", "&&", "~", "result", ".", "indexOf", "(", "\"{\\u007B\"", ")", ")", "{", "return", "this", ".", "c", ".", "compile", "(", "result", ",", "this", ".", "options", ")", ".", "render", "(", "cx", ",", "partials", ")", ";", "}", "return", "result", ";", "}" ]
lambda replace variable
[ "lambda", "replace", "variable" ]
7e340e9e4dde8faebd1ff34e62abc1c5dd8adb55
https://github.com/twitter/hogan.js/blob/7e340e9e4dde8faebd1ff34e62abc1c5dd8adb55/web/builds/1.0.5/hogan-1.0.5.js#L199-L212
11,963
webtorrent/bittorrent-tracker
server.js
getOrCreateSwarm
function getOrCreateSwarm (cb) { self.getSwarm(params.info_hash, (err, swarm) => { if (err) return cb(err) if (swarm) return cb(null, swarm) self.createSwarm(params.info_hash, (err, swarm) => { if (err) return cb(err) cb(null, swarm) }) }) }
javascript
function getOrCreateSwarm (cb) { self.getSwarm(params.info_hash, (err, swarm) => { if (err) return cb(err) if (swarm) return cb(null, swarm) self.createSwarm(params.info_hash, (err, swarm) => { if (err) return cb(err) cb(null, swarm) }) }) }
[ "function", "getOrCreateSwarm", "(", "cb", ")", "{", "self", ".", "getSwarm", "(", "params", ".", "info_hash", ",", "(", "err", ",", "swarm", ")", "=>", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "if", "(", "swarm", ")", "return", "cb", "(", "null", ",", "swarm", ")", "self", ".", "createSwarm", "(", "params", ".", "info_hash", ",", "(", "err", ",", "swarm", ")", "=>", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "cb", "(", "null", ",", "swarm", ")", "}", ")", "}", ")", "}" ]
Get existing swarm, or create one if one does not exist
[ "Get", "existing", "swarm", "or", "create", "one", "if", "one", "does", "not", "exist" ]
c0331ea5418b9fb8927a337172623d6985a7a403
https://github.com/webtorrent/bittorrent-tracker/blob/c0331ea5418b9fb8927a337172623d6985a7a403/server.js#L651-L660
11,964
webtorrent/bittorrent-tracker
lib/server/parse-udp.js
fromUInt64
function fromUInt64 (buf) { var high = buf.readUInt32BE(0) | 0 // force var low = buf.readUInt32BE(4) | 0 var lowUnsigned = (low >= 0) ? low : TWO_PWR_32 + low return (high * TWO_PWR_32) + lowUnsigned }
javascript
function fromUInt64 (buf) { var high = buf.readUInt32BE(0) | 0 // force var low = buf.readUInt32BE(4) | 0 var lowUnsigned = (low >= 0) ? low : TWO_PWR_32 + low return (high * TWO_PWR_32) + lowUnsigned }
[ "function", "fromUInt64", "(", "buf", ")", "{", "var", "high", "=", "buf", ".", "readUInt32BE", "(", "0", ")", "|", "0", "// force", "var", "low", "=", "buf", ".", "readUInt32BE", "(", "4", ")", "|", "0", "var", "lowUnsigned", "=", "(", "low", ">=", "0", ")", "?", "low", ":", "TWO_PWR_32", "+", "low", "return", "(", "high", "*", "TWO_PWR_32", ")", "+", "lowUnsigned", "}" ]
Return the closest floating-point representation to the buffer value. Precision will be lost for big numbers.
[ "Return", "the", "closest", "floating", "-", "point", "representation", "to", "the", "buffer", "value", ".", "Precision", "will", "be", "lost", "for", "big", "numbers", "." ]
c0331ea5418b9fb8927a337172623d6985a7a403
https://github.com/webtorrent/bittorrent-tracker/blob/c0331ea5418b9fb8927a337172623d6985a7a403/lib/server/parse-udp.js#L69-L75
11,965
Mermade/oas-kit
packages/reftools/lib/clone.js
shallowClone
function shallowClone(obj) { let result = {}; for (let p in obj) { if (obj.hasOwnProperty(p)) { result[p] = obj[p]; } } return result; }
javascript
function shallowClone(obj) { let result = {}; for (let p in obj) { if (obj.hasOwnProperty(p)) { result[p] = obj[p]; } } return result; }
[ "function", "shallowClone", "(", "obj", ")", "{", "let", "result", "=", "{", "}", ";", "for", "(", "let", "p", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "p", ")", ")", "{", "result", "[", "p", "]", "=", "obj", "[", "p", "]", ";", "}", "}", "return", "result", ";", "}" ]
clones the given object's properties shallowly, ignores properties from prototype @param obj the object to clone @return the cloned object
[ "clones", "the", "given", "object", "s", "properties", "shallowly", "ignores", "properties", "from", "prototype" ]
4eecb5c1689726e413734c536a0bd1f93a334c02
https://github.com/Mermade/oas-kit/blob/4eecb5c1689726e413734c536a0bd1f93a334c02/packages/reftools/lib/clone.js#L32-L40
11,966
Mermade/oas-kit
packages/reftools/lib/clone.js
deepClone
function deepClone(obj) { let result = Array.isArray(obj) ? [] : {}; for (let p in obj) { if (obj.hasOwnProperty(p) || Array.isArray(obj)) { result[p] = (typeof obj[p] === 'object') ? deepClone(obj[p]) : obj[p]; } } return result; }
javascript
function deepClone(obj) { let result = Array.isArray(obj) ? [] : {}; for (let p in obj) { if (obj.hasOwnProperty(p) || Array.isArray(obj)) { result[p] = (typeof obj[p] === 'object') ? deepClone(obj[p]) : obj[p]; } } return result; }
[ "function", "deepClone", "(", "obj", ")", "{", "let", "result", "=", "Array", ".", "isArray", "(", "obj", ")", "?", "[", "]", ":", "{", "}", ";", "for", "(", "let", "p", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "p", ")", "||", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "result", "[", "p", "]", "=", "(", "typeof", "obj", "[", "p", "]", "===", "'object'", ")", "?", "deepClone", "(", "obj", "[", "p", "]", ")", ":", "obj", "[", "p", "]", ";", "}", "}", "return", "result", ";", "}" ]
clones the given object's properties deeply, ignores properties from prototype @param obj the object to clone @return the cloned object
[ "clones", "the", "given", "object", "s", "properties", "deeply", "ignores", "properties", "from", "prototype" ]
4eecb5c1689726e413734c536a0bd1f93a334c02
https://github.com/Mermade/oas-kit/blob/4eecb5c1689726e413734c536a0bd1f93a334c02/packages/reftools/lib/clone.js#L47-L55
11,967
Mermade/oas-kit
packages/reftools/lib/recurse.js
recurse
function recurse(object, state, callback) { if (!state) state = {depth:0}; if (!state.depth) { state = Object.assign({},defaultState(),state); } if (typeof object !== 'object') return; let oPath = state.path; for (let key in object) { state.key = key; state.path = state.path + '/' + encodeURIComponent(jpescape(key)); state.identityPath = state.seen.get(object[key]); state.identity = (typeof state.identityPath !== 'undefined'); callback(object, key, state); if ((typeof object[key] === 'object') && (!state.identity)) { if (state.identityDetection && !Array.isArray(object[key]) && object[key] !== null) { state.seen.set(object[key],state.path); } let newState = {}; newState.parent = object; newState.path = state.path; newState.depth = state.depth ? state.depth+1 : 1; newState.pkey = key; newState.payload = state.payload; newState.seen = state.seen; newState.identity = false; newState.identityDetection = state.identityDetection; recurse(object[key], newState, callback); } state.path = oPath; } }
javascript
function recurse(object, state, callback) { if (!state) state = {depth:0}; if (!state.depth) { state = Object.assign({},defaultState(),state); } if (typeof object !== 'object') return; let oPath = state.path; for (let key in object) { state.key = key; state.path = state.path + '/' + encodeURIComponent(jpescape(key)); state.identityPath = state.seen.get(object[key]); state.identity = (typeof state.identityPath !== 'undefined'); callback(object, key, state); if ((typeof object[key] === 'object') && (!state.identity)) { if (state.identityDetection && !Array.isArray(object[key]) && object[key] !== null) { state.seen.set(object[key],state.path); } let newState = {}; newState.parent = object; newState.path = state.path; newState.depth = state.depth ? state.depth+1 : 1; newState.pkey = key; newState.payload = state.payload; newState.seen = state.seen; newState.identity = false; newState.identityDetection = state.identityDetection; recurse(object[key], newState, callback); } state.path = oPath; } }
[ "function", "recurse", "(", "object", ",", "state", ",", "callback", ")", "{", "if", "(", "!", "state", ")", "state", "=", "{", "depth", ":", "0", "}", ";", "if", "(", "!", "state", ".", "depth", ")", "{", "state", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultState", "(", ")", ",", "state", ")", ";", "}", "if", "(", "typeof", "object", "!==", "'object'", ")", "return", ";", "let", "oPath", "=", "state", ".", "path", ";", "for", "(", "let", "key", "in", "object", ")", "{", "state", ".", "key", "=", "key", ";", "state", ".", "path", "=", "state", ".", "path", "+", "'/'", "+", "encodeURIComponent", "(", "jpescape", "(", "key", ")", ")", ";", "state", ".", "identityPath", "=", "state", ".", "seen", ".", "get", "(", "object", "[", "key", "]", ")", ";", "state", ".", "identity", "=", "(", "typeof", "state", ".", "identityPath", "!==", "'undefined'", ")", ";", "callback", "(", "object", ",", "key", ",", "state", ")", ";", "if", "(", "(", "typeof", "object", "[", "key", "]", "===", "'object'", ")", "&&", "(", "!", "state", ".", "identity", ")", ")", "{", "if", "(", "state", ".", "identityDetection", "&&", "!", "Array", ".", "isArray", "(", "object", "[", "key", "]", ")", "&&", "object", "[", "key", "]", "!==", "null", ")", "{", "state", ".", "seen", ".", "set", "(", "object", "[", "key", "]", ",", "state", ".", "path", ")", ";", "}", "let", "newState", "=", "{", "}", ";", "newState", ".", "parent", "=", "object", ";", "newState", ".", "path", "=", "state", ".", "path", ";", "newState", ".", "depth", "=", "state", ".", "depth", "?", "state", ".", "depth", "+", "1", ":", "1", ";", "newState", ".", "pkey", "=", "key", ";", "newState", ".", "payload", "=", "state", ".", "payload", ";", "newState", ".", "seen", "=", "state", ".", "seen", ";", "newState", ".", "identity", "=", "false", ";", "newState", ".", "identityDetection", "=", "state", ".", "identityDetection", ";", "recurse", "(", "object", "[", "key", "]", ",", "newState", ",", "callback", ")", ";", "}", "state", ".", "path", "=", "oPath", ";", "}", "}" ]
recurses through the properties of an object, given an optional starting state anything you pass in state.payload is passed to the callback each time @param object the object to recurse through @param state optional starting state, can be set to null or {} @param callback the function which receives object,key,state on each property
[ "recurses", "through", "the", "properties", "of", "an", "object", "given", "an", "optional", "starting", "state", "anything", "you", "pass", "in", "state", ".", "payload", "is", "passed", "to", "the", "callback", "each", "time" ]
4eecb5c1689726e413734c536a0bd1f93a334c02
https://github.com/Mermade/oas-kit/blob/4eecb5c1689726e413734c536a0bd1f93a334c02/packages/reftools/lib/recurse.js#L25-L55
11,968
Mermade/oas-kit
packages/oas-schema-walker/index.js
getDefaultState
function getDefaultState() { return { depth: 0, seen: new WeakMap(), top: true, combine: false, allowRefSiblings: false }; }
javascript
function getDefaultState() { return { depth: 0, seen: new WeakMap(), top: true, combine: false, allowRefSiblings: false }; }
[ "function", "getDefaultState", "(", ")", "{", "return", "{", "depth", ":", "0", ",", "seen", ":", "new", "WeakMap", "(", ")", ",", "top", ":", "true", ",", "combine", ":", "false", ",", "allowRefSiblings", ":", "false", "}", ";", "}" ]
functions to walk an OpenAPI schema object and traverse all subschemas calling a callback function on each one obtains the default starting state for the `state` object used by walkSchema @return the state object suitable for use in walkSchema
[ "functions", "to", "walk", "an", "OpenAPI", "schema", "object", "and", "traverse", "all", "subschemas", "calling", "a", "callback", "function", "on", "each", "one", "obtains", "the", "default", "starting", "state", "for", "the", "state", "object", "used", "by", "walkSchema" ]
4eecb5c1689726e413734c536a0bd1f93a334c02
https://github.com/Mermade/oas-kit/blob/4eecb5c1689726e413734c536a0bd1f93a334c02/packages/oas-schema-walker/index.js#L13-L15
11,969
Mermade/oas-kit
packages/reftools/lib/toposort.js
hasIncomingEdge
function hasIncomingEdge(list, node) { for (var i = 0, l = list.length; i < l; ++i) { if (list[i].links.find(function(e,i,a){ return node._id == e; })) return true; } return false; }
javascript
function hasIncomingEdge(list, node) { for (var i = 0, l = list.length; i < l; ++i) { if (list[i].links.find(function(e,i,a){ return node._id == e; })) return true; } return false; }
[ "function", "hasIncomingEdge", "(", "list", ",", "node", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "list", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "{", "if", "(", "list", "[", "i", "]", ".", "links", ".", "find", "(", "function", "(", "e", ",", "i", ",", "a", ")", "{", "return", "node", ".", "_id", "==", "e", ";", "}", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Test if a node has got any incoming edges
[ "Test", "if", "a", "node", "has", "got", "any", "incoming", "edges" ]
4eecb5c1689726e413734c536a0bd1f93a334c02
https://github.com/Mermade/oas-kit/blob/4eecb5c1689726e413734c536a0bd1f93a334c02/packages/reftools/lib/toposort.js#L41-L48
11,970
Mermade/oas-kit
packages/reftools/lib/flatten.js
flatten
function flatten(obj,callback) { let arr = []; let iDepth, oDepth = 0; let state = {identityDetection:true}; recurse(obj,state,function(obj,key,state){ let entry = {}; entry.name = key; entry.value = obj[key]; entry.path = state.path; entry.parent = obj; entry.key = key; if (callback) entry = callback(entry); if (entry) { if (state.depth > iDepth) { oDepth++; } else if (state.depth < iDepth) { oDepth--; } entry.depth = oDepth; iDepth = state.depth; arr.push(entry); } }); return arr; }
javascript
function flatten(obj,callback) { let arr = []; let iDepth, oDepth = 0; let state = {identityDetection:true}; recurse(obj,state,function(obj,key,state){ let entry = {}; entry.name = key; entry.value = obj[key]; entry.path = state.path; entry.parent = obj; entry.key = key; if (callback) entry = callback(entry); if (entry) { if (state.depth > iDepth) { oDepth++; } else if (state.depth < iDepth) { oDepth--; } entry.depth = oDepth; iDepth = state.depth; arr.push(entry); } }); return arr; }
[ "function", "flatten", "(", "obj", ",", "callback", ")", "{", "let", "arr", "=", "[", "]", ";", "let", "iDepth", ",", "oDepth", "=", "0", ";", "let", "state", "=", "{", "identityDetection", ":", "true", "}", ";", "recurse", "(", "obj", ",", "state", ",", "function", "(", "obj", ",", "key", ",", "state", ")", "{", "let", "entry", "=", "{", "}", ";", "entry", ".", "name", "=", "key", ";", "entry", ".", "value", "=", "obj", "[", "key", "]", ";", "entry", ".", "path", "=", "state", ".", "path", ";", "entry", ".", "parent", "=", "obj", ";", "entry", ".", "key", "=", "key", ";", "if", "(", "callback", ")", "entry", "=", "callback", "(", "entry", ")", ";", "if", "(", "entry", ")", "{", "if", "(", "state", ".", "depth", ">", "iDepth", ")", "{", "oDepth", "++", ";", "}", "else", "if", "(", "state", ".", "depth", "<", "iDepth", ")", "{", "oDepth", "--", ";", "}", "entry", ".", "depth", "=", "oDepth", ";", "iDepth", "=", "state", ".", "depth", ";", "arr", ".", "push", "(", "entry", ")", ";", "}", "}", ")", ";", "return", "arr", ";", "}" ]
flattens an object into an array of properties @param obj the object to flatten @param callback a function which can mutate or filter the entries (by returning null) @return the flattened object as an array of properties
[ "flattens", "an", "object", "into", "an", "array", "of", "properties" ]
4eecb5c1689726e413734c536a0bd1f93a334c02
https://github.com/Mermade/oas-kit/blob/4eecb5c1689726e413734c536a0bd1f93a334c02/packages/reftools/lib/flatten.js#L11-L36
11,971
Mermade/oas-kit
packages/oas-resolver/index.js
optionalResolve
function optionalResolve(options) { setupOptions(options); return new Promise(function (res, rej) { if (options.resolve) loopReferences(options, res, rej) else res(options); }); }
javascript
function optionalResolve(options) { setupOptions(options); return new Promise(function (res, rej) { if (options.resolve) loopReferences(options, res, rej) else res(options); }); }
[ "function", "optionalResolve", "(", "options", ")", "{", "setupOptions", "(", "options", ")", ";", "return", "new", "Promise", "(", "function", "(", "res", ",", "rej", ")", "{", "if", "(", "options", ".", "resolve", ")", "loopReferences", "(", "options", ",", "res", ",", "rej", ")", "else", "res", "(", "options", ")", ";", "}", ")", ";", "}" ]
compatibility function for swagger2openapi
[ "compatibility", "function", "for", "swagger2openapi" ]
4eecb5c1689726e413734c536a0bd1f93a334c02
https://github.com/Mermade/oas-kit/blob/4eecb5c1689726e413734c536a0bd1f93a334c02/packages/oas-resolver/index.js#L474-L482
11,972
jeffijoe/awilix
examples/simple/services/functionalService.js
getStuffAndDeleteSecret
function getStuffAndDeleteSecret(opts, someArgument) { // We depend on "stuffs" repository. const stuffs = opts.stuffs // We may now carry on. return stuffs.getStuff(someArgument).then(stuff => { // Modify return value. Just to prove this is testable. delete stuff.secret return stuff }) }
javascript
function getStuffAndDeleteSecret(opts, someArgument) { // We depend on "stuffs" repository. const stuffs = opts.stuffs // We may now carry on. return stuffs.getStuff(someArgument).then(stuff => { // Modify return value. Just to prove this is testable. delete stuff.secret return stuff }) }
[ "function", "getStuffAndDeleteSecret", "(", "opts", ",", "someArgument", ")", "{", "// We depend on \"stuffs\" repository.", "const", "stuffs", "=", "opts", ".", "stuffs", "// We may now carry on.", "return", "stuffs", ".", "getStuff", "(", "someArgument", ")", ".", "then", "(", "stuff", "=>", "{", "// Modify return value. Just to prove this is testable.", "delete", "stuff", ".", "secret", "return", "stuff", "}", ")", "}" ]
By exporting this function as-is, we can inject mocks as the first argument!!!!!
[ "By", "exporting", "this", "function", "as", "-", "is", "we", "can", "inject", "mocks", "as", "the", "first", "argument!!!!!" ]
7dec4cc462b8d2886a0be72811c1687ca761586a
https://github.com/jeffijoe/awilix/blob/7dec4cc462b8d2886a0be72811c1687ca761586a/examples/simple/services/functionalService.js#L15-L25
11,973
EventSource/eventsource
lib/eventsource.js
get
function get () { var listener = this.listeners(method)[0] return listener ? (listener._listener ? listener._listener : listener) : undefined }
javascript
function get () { var listener = this.listeners(method)[0] return listener ? (listener._listener ? listener._listener : listener) : undefined }
[ "function", "get", "(", ")", "{", "var", "listener", "=", "this", ".", "listeners", "(", "method", ")", "[", "0", "]", "return", "listener", "?", "(", "listener", ".", "_listener", "?", "listener", ".", "_listener", ":", "listener", ")", ":", "undefined", "}" ]
Returns the current listener @return {Mixed} the set function or undefined @api private
[ "Returns", "the", "current", "listener" ]
82d38b0b0028ba92e861240eb6a943cbcafc8dff
https://github.com/EventSource/eventsource/blob/82d38b0b0028ba92e861240eb6a943cbcafc8dff/lib/eventsource.js#L311-L314
11,974
zhangyuanwei/node-images
scripts/util/extensions.js
getBinaryUrl
function getBinaryUrl() { var site = getArgument('--fis-binary-site') || process.env.FIS_BINARY_SITE || process.env.npm_config_FIS_binary_site || (pkg.nodeConfig && pkg.nodeConfig.binarySite) || 'https://github.com/' + repositoryName + '/releases/download'; return [site, 'v' + pkg.version, getBinaryName()].join('/'); }
javascript
function getBinaryUrl() { var site = getArgument('--fis-binary-site') || process.env.FIS_BINARY_SITE || process.env.npm_config_FIS_binary_site || (pkg.nodeConfig && pkg.nodeConfig.binarySite) || 'https://github.com/' + repositoryName + '/releases/download'; return [site, 'v' + pkg.version, getBinaryName()].join('/'); }
[ "function", "getBinaryUrl", "(", ")", "{", "var", "site", "=", "getArgument", "(", "'--fis-binary-site'", ")", "||", "process", ".", "env", ".", "FIS_BINARY_SITE", "||", "process", ".", "env", ".", "npm_config_FIS_binary_site", "||", "(", "pkg", ".", "nodeConfig", "&&", "pkg", ".", "nodeConfig", ".", "binarySite", ")", "||", "'https://github.com/'", "+", "repositoryName", "+", "'/releases/download'", ";", "return", "[", "site", ",", "'v'", "+", "pkg", ".", "version", ",", "getBinaryName", "(", ")", "]", ".", "join", "(", "'/'", ")", ";", "}" ]
Determine the URL to fetch binary file from. By default fetch from the addon for fis distribution site on GitHub. The default URL can be overriden using the environment variable FIS_BINARY_SITE, .npmrc variable FIS_binary_site or or a command line option --fis-binary-site: node scripts/install.js --fis-binary-site http://example.com/ The URL should to the mirror of the repository laid out as follows: FIS_BINARY_SITE/ v3.0.0 v3.0.0/freebsd-x64-14_binding.node .... v3.0.0 v3.0.0/freebsd-ia32-11_binding.node v3.0.0/freebsd-x64-42_binding.node ... etc. for all supported versions and platforms @api public
[ "Determine", "the", "URL", "to", "fetch", "binary", "file", "from", ".", "By", "default", "fetch", "from", "the", "addon", "for", "fis", "distribution", "site", "on", "GitHub", "." ]
634bd909a7fb9cf0656b70b7bcb98dbe4f7f1920
https://github.com/zhangyuanwei/node-images/blob/634bd909a7fb9cf0656b70b7bcb98dbe4f7f1920/scripts/util/extensions.js#L239-L247
11,975
qiqiboy/react-formutil
dist/react-formutil.cjs.development.js
deepClone
function deepClone(obj) { if (obj && typeof obj === 'object') { if (Array.isArray(obj)) { var newObj = []; for (var i = 0, j = obj.length; i < j; i++) { newObj[i] = deepClone(obj[i]); } return newObj; } else if (isPlainObj(obj)) { var _newObj = {}; for (var _i in obj) { _newObj[_i] = deepClone(obj[_i]); } return _newObj; } } return obj; }
javascript
function deepClone(obj) { if (obj && typeof obj === 'object') { if (Array.isArray(obj)) { var newObj = []; for (var i = 0, j = obj.length; i < j; i++) { newObj[i] = deepClone(obj[i]); } return newObj; } else if (isPlainObj(obj)) { var _newObj = {}; for (var _i in obj) { _newObj[_i] = deepClone(obj[_i]); } return _newObj; } } return obj; }
[ "function", "deepClone", "(", "obj", ")", "{", "if", "(", "obj", "&&", "typeof", "obj", "===", "'object'", ")", "{", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "var", "newObj", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "j", "=", "obj", ".", "length", ";", "i", "<", "j", ";", "i", "++", ")", "{", "newObj", "[", "i", "]", "=", "deepClone", "(", "obj", "[", "i", "]", ")", ";", "}", "return", "newObj", ";", "}", "else", "if", "(", "isPlainObj", "(", "obj", ")", ")", "{", "var", "_newObj", "=", "{", "}", ";", "for", "(", "var", "_i", "in", "obj", ")", "{", "_newObj", "[", "_i", "]", "=", "deepClone", "(", "obj", "[", "_i", "]", ")", ";", "}", "return", "_newObj", ";", "}", "}", "return", "obj", ";", "}" ]
quick clone deeply
[ "quick", "clone", "deeply" ]
5ca93ce18dd7df80ca62491e3f671a7b1282cb41
https://github.com/qiqiboy/react-formutil/blob/5ca93ce18dd7df80ca62491e3f671a7b1282cb41/dist/react-formutil.cjs.development.js#L221-L243
11,976
openid/AppAuth-JS
built/logger.js
profile
function profile(target, propertyKey, descriptor) { if (flags_1.IS_PROFILE) { return performProfile(target, propertyKey, descriptor); } else { // return as-is return descriptor; } }
javascript
function profile(target, propertyKey, descriptor) { if (flags_1.IS_PROFILE) { return performProfile(target, propertyKey, descriptor); } else { // return as-is return descriptor; } }
[ "function", "profile", "(", "target", ",", "propertyKey", ",", "descriptor", ")", "{", "if", "(", "flags_1", ".", "IS_PROFILE", ")", "{", "return", "performProfile", "(", "target", ",", "propertyKey", ",", "descriptor", ")", ";", "}", "else", "{", "// return as-is", "return", "descriptor", ";", "}", "}" ]
A decorator that can profile a function.
[ "A", "decorator", "that", "can", "profile", "a", "function", "." ]
9b502f68857432939013864c74e37deab12abb14
https://github.com/openid/AppAuth-JS/blob/9b502f68857432939013864c74e37deab12abb14/built/logger.js#L39-L47
11,977
BetterJS/badjs-report
dist/bj-report-tryjs.js
function(foo, self) { return function() { var arg, tmp, args = []; for (var i = 0, l = arguments.length; i < l; i++) { arg = arguments[i]; if (_isFunction(arg)) { if (arg.tryWrap) { arg = arg.tryWrap; } else { tmp = cat(arg); arg.tryWrap = tmp; arg = tmp; } } args.push(arg); } return foo.apply(self || this, args); }; }
javascript
function(foo, self) { return function() { var arg, tmp, args = []; for (var i = 0, l = arguments.length; i < l; i++) { arg = arguments[i]; if (_isFunction(arg)) { if (arg.tryWrap) { arg = arg.tryWrap; } else { tmp = cat(arg); arg.tryWrap = tmp; arg = tmp; } } args.push(arg); } return foo.apply(self || this, args); }; }
[ "function", "(", "foo", ",", "self", ")", "{", "return", "function", "(", ")", "{", "var", "arg", ",", "tmp", ",", "args", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "arguments", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "arg", "=", "arguments", "[", "i", "]", ";", "if", "(", "_isFunction", "(", "arg", ")", ")", "{", "if", "(", "arg", ".", "tryWrap", ")", "{", "arg", "=", "arg", ".", "tryWrap", ";", "}", "else", "{", "tmp", "=", "cat", "(", "arg", ")", ";", "arg", ".", "tryWrap", "=", "tmp", ";", "arg", "=", "tmp", ";", "}", "}", "args", ".", "push", "(", "arg", ")", ";", "}", "return", "foo", ".", "apply", "(", "self", "||", "this", ",", "args", ")", ";", "}", ";", "}" ]
makeArgsTry wrap a function's arguments with try & catch @param {Function} foo @param {Object} self @returns {Function}
[ "makeArgsTry", "wrap", "a", "function", "s", "arguments", "with", "try", "&", "catch" ]
a4444c7d790edc1c9b79d79cf46d8719598bd91e
https://github.com/BetterJS/badjs-report/blob/a4444c7d790edc1c9b79d79cf46d8719598bd91e/dist/bj-report-tryjs.js#L689-L707
11,978
BetterJS/badjs-report
dist/bj-report-tryjs.js
function(obj) { var key, value; for (key in obj) { value = obj[key]; if (_isFunction(value)) obj[key] = cat(value); } return obj; }
javascript
function(obj) { var key, value; for (key in obj) { value = obj[key]; if (_isFunction(value)) obj[key] = cat(value); } return obj; }
[ "function", "(", "obj", ")", "{", "var", "key", ",", "value", ";", "for", "(", "key", "in", "obj", ")", "{", "value", "=", "obj", "[", "key", "]", ";", "if", "(", "_isFunction", "(", "value", ")", ")", "obj", "[", "key", "]", "=", "cat", "(", "value", ")", ";", "}", "return", "obj", ";", "}" ]
makeObjTry wrap a object's all value with try & catch @param {Function} foo @param {Object} self @returns {Function}
[ "makeObjTry", "wrap", "a", "object", "s", "all", "value", "with", "try", "&", "catch" ]
a4444c7d790edc1c9b79d79cf46d8719598bd91e
https://github.com/BetterJS/badjs-report/blob/a4444c7d790edc1c9b79d79cf46d8719598bd91e/dist/bj-report-tryjs.js#L716-L723
11,979
filamentgroup/tablesaw
dist/tablesaw.js
encasedCallback
function encasedCallback( e, namespace, triggeredElement ){ var result; if( e._namespace && e._namespace !== namespace ) { return; } e.data = data; e.namespace = e._namespace; var returnTrue = function(){ return true; }; e.isDefaultPrevented = function(){ return false; }; var originalPreventDefault = e.preventDefault; var preventDefaultConstructor = function(){ if( originalPreventDefault ) { return function(){ e.isDefaultPrevented = returnTrue; originalPreventDefault.call(e); }; } else { return function(){ e.isDefaultPrevented = returnTrue; e.returnValue = false; }; } }; // thanks https://github.com/jonathantneal/EventListener e.target = triggeredElement || e.target || e.srcElement; e.preventDefault = preventDefaultConstructor(); e.stopPropagation = e.stopPropagation || function () { e.cancelBubble = true; }; result = originalCallback.apply(this, [ e ].concat( e._args ) ); if( result === false ){ e.preventDefault(); e.stopPropagation(); } return result; }
javascript
function encasedCallback( e, namespace, triggeredElement ){ var result; if( e._namespace && e._namespace !== namespace ) { return; } e.data = data; e.namespace = e._namespace; var returnTrue = function(){ return true; }; e.isDefaultPrevented = function(){ return false; }; var originalPreventDefault = e.preventDefault; var preventDefaultConstructor = function(){ if( originalPreventDefault ) { return function(){ e.isDefaultPrevented = returnTrue; originalPreventDefault.call(e); }; } else { return function(){ e.isDefaultPrevented = returnTrue; e.returnValue = false; }; } }; // thanks https://github.com/jonathantneal/EventListener e.target = triggeredElement || e.target || e.srcElement; e.preventDefault = preventDefaultConstructor(); e.stopPropagation = e.stopPropagation || function () { e.cancelBubble = true; }; result = originalCallback.apply(this, [ e ].concat( e._args ) ); if( result === false ){ e.preventDefault(); e.stopPropagation(); } return result; }
[ "function", "encasedCallback", "(", "e", ",", "namespace", ",", "triggeredElement", ")", "{", "var", "result", ";", "if", "(", "e", ".", "_namespace", "&&", "e", ".", "_namespace", "!==", "namespace", ")", "{", "return", ";", "}", "e", ".", "data", "=", "data", ";", "e", ".", "namespace", "=", "e", ".", "_namespace", ";", "var", "returnTrue", "=", "function", "(", ")", "{", "return", "true", ";", "}", ";", "e", ".", "isDefaultPrevented", "=", "function", "(", ")", "{", "return", "false", ";", "}", ";", "var", "originalPreventDefault", "=", "e", ".", "preventDefault", ";", "var", "preventDefaultConstructor", "=", "function", "(", ")", "{", "if", "(", "originalPreventDefault", ")", "{", "return", "function", "(", ")", "{", "e", ".", "isDefaultPrevented", "=", "returnTrue", ";", "originalPreventDefault", ".", "call", "(", "e", ")", ";", "}", ";", "}", "else", "{", "return", "function", "(", ")", "{", "e", ".", "isDefaultPrevented", "=", "returnTrue", ";", "e", ".", "returnValue", "=", "false", ";", "}", ";", "}", "}", ";", "// thanks https://github.com/jonathantneal/EventListener", "e", ".", "target", "=", "triggeredElement", "||", "e", ".", "target", "||", "e", ".", "srcElement", ";", "e", ".", "preventDefault", "=", "preventDefaultConstructor", "(", ")", ";", "e", ".", "stopPropagation", "=", "e", ".", "stopPropagation", "||", "function", "(", ")", "{", "e", ".", "cancelBubble", "=", "true", ";", "}", ";", "result", "=", "originalCallback", ".", "apply", "(", "this", ",", "[", "e", "]", ".", "concat", "(", "e", ".", "_args", ")", ")", ";", "if", "(", "result", "===", "false", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "e", ".", "stopPropagation", "(", ")", ";", "}", "return", "result", ";", "}" ]
NOTE the `triggeredElement` is purely for custom events from IE
[ "NOTE", "the", "triggeredElement", "is", "purely", "for", "custom", "events", "from", "IE" ]
6c3387b71d659773e1c7dcb5d7aa5bcb83f53932
https://github.com/filamentgroup/tablesaw/blob/6c3387b71d659773e1c7dcb5d7aa5bcb83f53932/dist/tablesaw.js#L1442-L1490
11,980
panva/node-openid-client
lib/client.js
checkBasicSupport
function checkBasicSupport(client, metadata, properties) { try { const supported = client.issuer.token_endpoint_auth_methods_supported; if (!supported.includes(properties.token_endpoint_auth_method)) { if (supported.includes('client_secret_post')) { properties.token_endpoint_auth_method = 'client_secret_post'; } } } catch (err) {} }
javascript
function checkBasicSupport(client, metadata, properties) { try { const supported = client.issuer.token_endpoint_auth_methods_supported; if (!supported.includes(properties.token_endpoint_auth_method)) { if (supported.includes('client_secret_post')) { properties.token_endpoint_auth_method = 'client_secret_post'; } } } catch (err) {} }
[ "function", "checkBasicSupport", "(", "client", ",", "metadata", ",", "properties", ")", "{", "try", "{", "const", "supported", "=", "client", ".", "issuer", ".", "token_endpoint_auth_methods_supported", ";", "if", "(", "!", "supported", ".", "includes", "(", "properties", ".", "token_endpoint_auth_method", ")", ")", "{", "if", "(", "supported", ".", "includes", "(", "'client_secret_post'", ")", ")", "{", "properties", ".", "token_endpoint_auth_method", "=", "'client_secret_post'", ";", "}", "}", "}", "catch", "(", "err", ")", "{", "}", "}" ]
if an OP doesnt support client_secret_basic but supports client_secret_post, use it instead this is in place to take care of most common pitfalls when first using discovered Issuers without the support for default values defined by Discovery 1.0
[ "if", "an", "OP", "doesnt", "support", "client_secret_basic", "but", "supports", "client_secret_post", "use", "it", "instead", "this", "is", "in", "place", "to", "take", "care", "of", "most", "common", "pitfalls", "when", "first", "using", "discovered", "Issuers", "without", "the", "support", "for", "default", "values", "defined", "by", "Discovery", "1", ".", "0" ]
571d9011c7a9b12731cda3e7b0b2e33bfd785bf0
https://github.com/panva/node-openid-client/blob/571d9011c7a9b12731cda3e7b0b2e33bfd785bf0/lib/client.js#L157-L166
11,981
chenz24/vue-blu
build/vue-markdown-loader2/index.js
function (html) { var $ = cheerio.load(html, { decodeEntities: false, lowerCaseAttributeNames: false, lowerCaseTags: false }); var output = { style: $.html('style'), script: $.html('script') }; var result; $('style').remove(); $('script').remove(); result = '<template><section>' + $.html() + '</section></template>\n' + output.style + '\n' + output.script; return result }
javascript
function (html) { var $ = cheerio.load(html, { decodeEntities: false, lowerCaseAttributeNames: false, lowerCaseTags: false }); var output = { style: $.html('style'), script: $.html('script') }; var result; $('style').remove(); $('script').remove(); result = '<template><section>' + $.html() + '</section></template>\n' + output.style + '\n' + output.script; return result }
[ "function", "(", "html", ")", "{", "var", "$", "=", "cheerio", ".", "load", "(", "html", ",", "{", "decodeEntities", ":", "false", ",", "lowerCaseAttributeNames", ":", "false", ",", "lowerCaseTags", ":", "false", "}", ")", ";", "var", "output", "=", "{", "style", ":", "$", ".", "html", "(", "'style'", ")", ",", "script", ":", "$", ".", "html", "(", "'script'", ")", "}", ";", "var", "result", ";", "$", "(", "'style'", ")", ".", "remove", "(", ")", ";", "$", "(", "'script'", ")", ".", "remove", "(", ")", ";", "result", "=", "'<template><section>'", "+", "$", ".", "html", "(", ")", "+", "'</section></template>\\n'", "+", "output", ".", "style", "+", "'\\n'", "+", "output", ".", "script", ";", "return", "result", "}" ]
html => vue file template @param {[type]} html [description] @return {[type]} [description]
[ "html", "=", ">", "vue", "file", "template" ]
2db168776a8fbcd28263e14f8e0043aa258c0fa6
https://github.com/chenz24/vue-blu/blob/2db168776a8fbcd28263e14f8e0043aa258c0fa6/build/vue-markdown-loader2/index.js#L48-L69
11,982
jantimon/favicons-webpack-plugin
index.js
guessAppName
function guessAppName (compilerWorkingDirectory) { var packageJson = path.resolve(compilerWorkingDirectory, 'package.json'); if (!fs.existsSync(packageJson)) { packageJson = path.resolve(compilerWorkingDirectory, '../package.json'); if (!fs.existsSync(packageJson)) { return 'Webpack App'; } } return JSON.parse(fs.readFileSync(packageJson)).name; }
javascript
function guessAppName (compilerWorkingDirectory) { var packageJson = path.resolve(compilerWorkingDirectory, 'package.json'); if (!fs.existsSync(packageJson)) { packageJson = path.resolve(compilerWorkingDirectory, '../package.json'); if (!fs.existsSync(packageJson)) { return 'Webpack App'; } } return JSON.parse(fs.readFileSync(packageJson)).name; }
[ "function", "guessAppName", "(", "compilerWorkingDirectory", ")", "{", "var", "packageJson", "=", "path", ".", "resolve", "(", "compilerWorkingDirectory", ",", "'package.json'", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "packageJson", ")", ")", "{", "packageJson", "=", "path", ".", "resolve", "(", "compilerWorkingDirectory", ",", "'../package.json'", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "packageJson", ")", ")", "{", "return", "'Webpack App'", ";", "}", "}", "return", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "packageJson", ")", ")", ".", "name", ";", "}" ]
Tries to guess the name from the package.json
[ "Tries", "to", "guess", "the", "name", "from", "the", "package", ".", "json" ]
7845e4f20a54776555674ecc0537ca3d89aa2ccd
https://github.com/jantimon/favicons-webpack-plugin/blob/7845e4f20a54776555674ecc0537ca3d89aa2ccd/index.js#L94-L103
11,983
jantimon/favicons-webpack-plugin
lib/cache.js
emitCacheInformationFile
function emitCacheInformationFile (loader, query, cacheFile, fileHash, iconResult) { if (!query.persistentCache) { return; } loader.emitFile(cacheFile, JSON.stringify({ hash: fileHash, version: pluginVersion, optionHash: generateHashForOptions(query), result: iconResult })); }
javascript
function emitCacheInformationFile (loader, query, cacheFile, fileHash, iconResult) { if (!query.persistentCache) { return; } loader.emitFile(cacheFile, JSON.stringify({ hash: fileHash, version: pluginVersion, optionHash: generateHashForOptions(query), result: iconResult })); }
[ "function", "emitCacheInformationFile", "(", "loader", ",", "query", ",", "cacheFile", ",", "fileHash", ",", "iconResult", ")", "{", "if", "(", "!", "query", ".", "persistentCache", ")", "{", "return", ";", "}", "loader", ".", "emitFile", "(", "cacheFile", ",", "JSON", ".", "stringify", "(", "{", "hash", ":", "fileHash", ",", "version", ":", "pluginVersion", ",", "optionHash", ":", "generateHashForOptions", "(", "query", ")", ",", "result", ":", "iconResult", "}", ")", ")", ";", "}" ]
Stores the given iconResult together with the control hashes as JSON file
[ "Stores", "the", "given", "iconResult", "together", "with", "the", "control", "hashes", "as", "JSON", "file" ]
7845e4f20a54776555674ecc0537ca3d89aa2ccd
https://github.com/jantimon/favicons-webpack-plugin/blob/7845e4f20a54776555674ecc0537ca3d89aa2ccd/lib/cache.js#L15-L25
11,984
jantimon/favicons-webpack-plugin
lib/cache.js
isCacheValid
function isCacheValid (cache, fileHash, query) { // Verify that the source file is the same return cache.hash === fileHash && // Verify that the options are the same cache.optionHash === generateHashForOptions(query) && // Verify that the favicons version of the cache maches this version cache.version === pluginVersion; }
javascript
function isCacheValid (cache, fileHash, query) { // Verify that the source file is the same return cache.hash === fileHash && // Verify that the options are the same cache.optionHash === generateHashForOptions(query) && // Verify that the favicons version of the cache maches this version cache.version === pluginVersion; }
[ "function", "isCacheValid", "(", "cache", ",", "fileHash", ",", "query", ")", "{", "// Verify that the source file is the same", "return", "cache", ".", "hash", "===", "fileHash", "&&", "// Verify that the options are the same", "cache", ".", "optionHash", "===", "generateHashForOptions", "(", "query", ")", "&&", "// Verify that the favicons version of the cache maches this version", "cache", ".", "version", "===", "pluginVersion", ";", "}" ]
Checks if the given cache object is still valid
[ "Checks", "if", "the", "given", "cache", "object", "is", "still", "valid" ]
7845e4f20a54776555674ecc0537ca3d89aa2ccd
https://github.com/jantimon/favicons-webpack-plugin/blob/7845e4f20a54776555674ecc0537ca3d89aa2ccd/lib/cache.js#L30-L37
11,985
jantimon/favicons-webpack-plugin
lib/cache.js
loadIconsFromDiskCache
function loadIconsFromDiskCache (loader, query, cacheFile, fileHash, callback) { // Stop if cache is disabled if (!query.persistentCache) return callback(null); var resolvedCacheFile = path.resolve(loader._compiler.parentCompilation.compiler.outputPath, cacheFile); fs.exists(resolvedCacheFile, function (exists) { if (!exists) return callback(null); fs.readFile(resolvedCacheFile, function (err, content) { if (err) return callback(err); var cache; try { cache = JSON.parse(content); // Bail out if the file or the option changed if (!isCacheValid(cache, fileHash, query)) { return callback(null); } } catch (e) { return callback(e); } callback(null, cache.result); }); }); }
javascript
function loadIconsFromDiskCache (loader, query, cacheFile, fileHash, callback) { // Stop if cache is disabled if (!query.persistentCache) return callback(null); var resolvedCacheFile = path.resolve(loader._compiler.parentCompilation.compiler.outputPath, cacheFile); fs.exists(resolvedCacheFile, function (exists) { if (!exists) return callback(null); fs.readFile(resolvedCacheFile, function (err, content) { if (err) return callback(err); var cache; try { cache = JSON.parse(content); // Bail out if the file or the option changed if (!isCacheValid(cache, fileHash, query)) { return callback(null); } } catch (e) { return callback(e); } callback(null, cache.result); }); }); }
[ "function", "loadIconsFromDiskCache", "(", "loader", ",", "query", ",", "cacheFile", ",", "fileHash", ",", "callback", ")", "{", "// Stop if cache is disabled", "if", "(", "!", "query", ".", "persistentCache", ")", "return", "callback", "(", "null", ")", ";", "var", "resolvedCacheFile", "=", "path", ".", "resolve", "(", "loader", ".", "_compiler", ".", "parentCompilation", ".", "compiler", ".", "outputPath", ",", "cacheFile", ")", ";", "fs", ".", "exists", "(", "resolvedCacheFile", ",", "function", "(", "exists", ")", "{", "if", "(", "!", "exists", ")", "return", "callback", "(", "null", ")", ";", "fs", ".", "readFile", "(", "resolvedCacheFile", ",", "function", "(", "err", ",", "content", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "var", "cache", ";", "try", "{", "cache", "=", "JSON", ".", "parse", "(", "content", ")", ";", "// Bail out if the file or the option changed", "if", "(", "!", "isCacheValid", "(", "cache", ",", "fileHash", ",", "query", ")", ")", "{", "return", "callback", "(", "null", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "return", "callback", "(", "e", ")", ";", "}", "callback", "(", "null", ",", "cache", ".", "result", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Try to load the file from the disc cache
[ "Try", "to", "load", "the", "file", "from", "the", "disc", "cache" ]
7845e4f20a54776555674ecc0537ca3d89aa2ccd
https://github.com/jantimon/favicons-webpack-plugin/blob/7845e4f20a54776555674ecc0537ca3d89aa2ccd/lib/cache.js#L42-L64
11,986
jantimon/favicons-webpack-plugin
lib/cache.js
generateHashForOptions
function generateHashForOptions (options) { var hash = crypto.createHash('md5'); hash.update(JSON.stringify(options)); return hash.digest('hex'); }
javascript
function generateHashForOptions (options) { var hash = crypto.createHash('md5'); hash.update(JSON.stringify(options)); return hash.digest('hex'); }
[ "function", "generateHashForOptions", "(", "options", ")", "{", "var", "hash", "=", "crypto", ".", "createHash", "(", "'md5'", ")", ";", "hash", ".", "update", "(", "JSON", ".", "stringify", "(", "options", ")", ")", ";", "return", "hash", ".", "digest", "(", "'hex'", ")", ";", "}" ]
Generates a md5 hash for the given options
[ "Generates", "a", "md5", "hash", "for", "the", "given", "options" ]
7845e4f20a54776555674ecc0537ca3d89aa2ccd
https://github.com/jantimon/favicons-webpack-plugin/blob/7845e4f20a54776555674ecc0537ca3d89aa2ccd/lib/cache.js#L69-L73
11,987
davestewart/vuex-pathify
src/services/store.js
getValueIfEnabled
function getValueIfEnabled(expr, source, path) { if (!options.deep && expr.includes('@')) { console.error(`[Vuex Pathify] Unable to access sub-property for path '${expr}': - Set option 'deep' to 1 to allow it`) return } return getValue(source, path) }
javascript
function getValueIfEnabled(expr, source, path) { if (!options.deep && expr.includes('@')) { console.error(`[Vuex Pathify] Unable to access sub-property for path '${expr}': - Set option 'deep' to 1 to allow it`) return } return getValue(source, path) }
[ "function", "getValueIfEnabled", "(", "expr", ",", "source", ",", "path", ")", "{", "if", "(", "!", "options", ".", "deep", "&&", "expr", ".", "includes", "(", "'@'", ")", ")", "{", "console", ".", "error", "(", "`", "${", "expr", "}", "`", ")", "return", "}", "return", "getValue", "(", "source", ",", "path", ")", "}" ]
Utility function to get value from store, but only if options allow @param {string} expr The full path expression @param {object} source The source object to get property from @param {string} path The full dot-path on the source object @returns {*}
[ "Utility", "function", "to", "get", "value", "from", "store", "but", "only", "if", "options", "allow" ]
c5480a86f4f25b772862ffe68927988d81ca7306
https://github.com/davestewart/vuex-pathify/blob/c5480a86f4f25b772862ffe68927988d81ca7306/src/services/store.js#L96-L103
11,988
davestewart/vuex-pathify
src/helpers/decorators.js
Get
function Get(path) { if (typeof path !== 'string' || arguments.length > 1) { throw new Error('Property decorators can be used for single property access') } return createDecorator((options, key) => { if (!options.computed) options.computed = {} options.computed[key] = get(path) }) }
javascript
function Get(path) { if (typeof path !== 'string' || arguments.length > 1) { throw new Error('Property decorators can be used for single property access') } return createDecorator((options, key) => { if (!options.computed) options.computed = {} options.computed[key] = get(path) }) }
[ "function", "Get", "(", "path", ")", "{", "if", "(", "typeof", "path", "!==", "'string'", "||", "arguments", ".", "length", ">", "1", ")", "{", "throw", "new", "Error", "(", "'Property decorators can be used for single property access'", ")", "}", "return", "createDecorator", "(", "(", "options", ",", "key", ")", "=>", "{", "if", "(", "!", "options", ".", "computed", ")", "options", ".", "computed", "=", "{", "}", "options", ".", "computed", "[", "key", "]", "=", "get", "(", "path", ")", "}", ")", "}" ]
Decortaor for `get` component helper. @param {string} path - Path in store @returns {VueDecorator} - Vue decortaor to be used in cue class component.
[ "Decortaor", "for", "get", "component", "helper", "." ]
c5480a86f4f25b772862ffe68927988d81ca7306
https://github.com/davestewart/vuex-pathify/blob/c5480a86f4f25b772862ffe68927988d81ca7306/src/helpers/decorators.js#L25-L31
11,989
davestewart/vuex-pathify
src/helpers/decorators.js
Sync
function Sync(path) { if (typeof path !== 'string' || arguments.length > 1) { throw new Error('Property decorators can be used for single property access') } return createDecorator((options, key) => { if (!options.computed) options.computed = {} options.computed[key] = sync(path) }) }
javascript
function Sync(path) { if (typeof path !== 'string' || arguments.length > 1) { throw new Error('Property decorators can be used for single property access') } return createDecorator((options, key) => { if (!options.computed) options.computed = {} options.computed[key] = sync(path) }) }
[ "function", "Sync", "(", "path", ")", "{", "if", "(", "typeof", "path", "!==", "'string'", "||", "arguments", ".", "length", ">", "1", ")", "{", "throw", "new", "Error", "(", "'Property decorators can be used for single property access'", ")", "}", "return", "createDecorator", "(", "(", "options", ",", "key", ")", "=>", "{", "if", "(", "!", "options", ".", "computed", ")", "options", ".", "computed", "=", "{", "}", "options", ".", "computed", "[", "key", "]", "=", "sync", "(", "path", ")", "}", ")", "}" ]
Decortaor for `sync` component helper. @param {string} path - Path in store @returns {VueDecorator} - Vue decortaor to be used in cue class component.
[ "Decortaor", "for", "sync", "component", "helper", "." ]
c5480a86f4f25b772862ffe68927988d81ca7306
https://github.com/davestewart/vuex-pathify/blob/c5480a86f4f25b772862ffe68927988d81ca7306/src/helpers/decorators.js#L38-L44
11,990
davestewart/vuex-pathify
src/helpers/decorators.js
Call
function Call(path) { if (typeof path !== 'string' || arguments.length > 1) { throw new Error('Property decorators can be used for single property access') } return createDecorator((options, key) => { if (!options.methods) options.methods = {} options.methods[key] = call(path) }) }
javascript
function Call(path) { if (typeof path !== 'string' || arguments.length > 1) { throw new Error('Property decorators can be used for single property access') } return createDecorator((options, key) => { if (!options.methods) options.methods = {} options.methods[key] = call(path) }) }
[ "function", "Call", "(", "path", ")", "{", "if", "(", "typeof", "path", "!==", "'string'", "||", "arguments", ".", "length", ">", "1", ")", "{", "throw", "new", "Error", "(", "'Property decorators can be used for single property access'", ")", "}", "return", "createDecorator", "(", "(", "options", ",", "key", ")", "=>", "{", "if", "(", "!", "options", ".", "methods", ")", "options", ".", "methods", "=", "{", "}", "options", ".", "methods", "[", "key", "]", "=", "call", "(", "path", ")", "}", ")", "}" ]
Decortaor for `call` component helper. @param {string} path - Path in store @returns {VueDecorator} - Vue decortaor to be used in cue class component.
[ "Decortaor", "for", "call", "component", "helper", "." ]
c5480a86f4f25b772862ffe68927988d81ca7306
https://github.com/davestewart/vuex-pathify/blob/c5480a86f4f25b772862ffe68927988d81ca7306/src/helpers/decorators.js#L51-L57
11,991
davestewart/vuex-pathify
docs/assets/js/plugins.js
fixAnchors
function fixAnchors (hook) { hook.afterEach(function (html, next) { // find all headings and replace them html = html.replace(/<(h\d).+?<\/\1>/g, function (html) { // create temp node var div = document.createElement('div') div.innerHTML = html // get anchor var link = div.querySelector('a[href*="?id"]') if (!link) { return html } // work out id var text = link.innerText var id = text .split('(') .shift() .toLowerCase() .replace(/\W+/g, '-') .replace(/^-+|-+$/g, '') var href = link.getAttribute('href') .replace(/\?id=.+/, '?id=' + id) // update dom link.setAttribute('href', href) link.setAttribute('data-id', id) link.parentElement.setAttribute('id', id) // return html return div.innerHTML }) // continue next(html) }) }
javascript
function fixAnchors (hook) { hook.afterEach(function (html, next) { // find all headings and replace them html = html.replace(/<(h\d).+?<\/\1>/g, function (html) { // create temp node var div = document.createElement('div') div.innerHTML = html // get anchor var link = div.querySelector('a[href*="?id"]') if (!link) { return html } // work out id var text = link.innerText var id = text .split('(') .shift() .toLowerCase() .replace(/\W+/g, '-') .replace(/^-+|-+$/g, '') var href = link.getAttribute('href') .replace(/\?id=.+/, '?id=' + id) // update dom link.setAttribute('href', href) link.setAttribute('data-id', id) link.parentElement.setAttribute('id', id) // return html return div.innerHTML }) // continue next(html) }) }
[ "function", "fixAnchors", "(", "hook", ")", "{", "hook", ".", "afterEach", "(", "function", "(", "html", ",", "next", ")", "{", "// find all headings and replace them", "html", "=", "html", ".", "replace", "(", "/", "<(h\\d).+?<\\/\\1>", "/", "g", ",", "function", "(", "html", ")", "{", "// create temp node", "var", "div", "=", "document", ".", "createElement", "(", "'div'", ")", "div", ".", "innerHTML", "=", "html", "// get anchor", "var", "link", "=", "div", ".", "querySelector", "(", "'a[href*=\"?id\"]'", ")", "if", "(", "!", "link", ")", "{", "return", "html", "}", "// work out id", "var", "text", "=", "link", ".", "innerText", "var", "id", "=", "text", ".", "split", "(", "'('", ")", ".", "shift", "(", ")", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "\\W+", "/", "g", ",", "'-'", ")", ".", "replace", "(", "/", "^-+|-+$", "/", "g", ",", "''", ")", "var", "href", "=", "link", ".", "getAttribute", "(", "'href'", ")", ".", "replace", "(", "/", "\\?id=.+", "/", ",", "'?id='", "+", "id", ")", "// update dom", "link", ".", "setAttribute", "(", "'href'", ",", "href", ")", "link", ".", "setAttribute", "(", "'data-id'", ",", "id", ")", "link", ".", "parentElement", ".", "setAttribute", "(", "'id'", ",", "id", ")", "// return html", "return", "div", ".", "innerHTML", "}", ")", "// continue", "next", "(", "html", ")", "}", ")", "}" ]
Fix anchors for all headings with code in them @param hook
[ "Fix", "anchors", "for", "all", "headings", "with", "code", "in", "them" ]
c5480a86f4f25b772862ffe68927988d81ca7306
https://github.com/davestewart/vuex-pathify/blob/c5480a86f4f25b772862ffe68927988d81ca7306/docs/assets/js/plugins.js#L84-L125
11,992
infinitered/ignite-andross
boilerplate.js
function(context) { const androidHome = process.env['ANDROID_HOME'] const hasAndroidEnv = !context.strings.isBlank(androidHome) const hasAndroid = hasAndroidEnv && context.filesystem.exists(`${androidHome}/tools`) === 'dir' return Boolean(hasAndroid) }
javascript
function(context) { const androidHome = process.env['ANDROID_HOME'] const hasAndroidEnv = !context.strings.isBlank(androidHome) const hasAndroid = hasAndroidEnv && context.filesystem.exists(`${androidHome}/tools`) === 'dir' return Boolean(hasAndroid) }
[ "function", "(", "context", ")", "{", "const", "androidHome", "=", "process", ".", "env", "[", "'ANDROID_HOME'", "]", "const", "hasAndroidEnv", "=", "!", "context", ".", "strings", ".", "isBlank", "(", "androidHome", ")", "const", "hasAndroid", "=", "hasAndroidEnv", "&&", "context", ".", "filesystem", ".", "exists", "(", "`", "${", "androidHome", "}", "`", ")", "===", "'dir'", "return", "Boolean", "(", "hasAndroid", ")", "}" ]
Is Android installed? $ANDROID_HOME/tools folder has to exist. @param {*} context - The gluegun context. @returns {boolean}
[ "Is", "Android", "installed?" ]
f1548bf721d36fb724af1b4ea95288f4e576ee94
https://github.com/infinitered/ignite-andross/blob/f1548bf721d36fb724af1b4ea95288f4e576ee94/boilerplate.js#L13-L19
11,993
dwyl/aws-sdk-mock
index.js
restoreService
function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } }
javascript
function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } }
[ "function", "restoreService", "(", "service", ")", "{", "if", "(", "services", "[", "service", "]", ")", "{", "restoreAllMethods", "(", "service", ")", ";", "if", "(", "services", "[", "service", "]", ".", "stub", ")", "services", "[", "service", "]", ".", "stub", ".", "restore", "(", ")", ";", "delete", "services", "[", "service", "]", ";", "}", "else", "{", "console", ".", "log", "(", "'Service '", "+", "service", "+", "' was never instantiated yet you try to restore it.'", ")", ";", "}", "}" ]
Restores a single mocked service and its corresponding methods.
[ "Restores", "a", "single", "mocked", "service", "and", "its", "corresponding", "methods", "." ]
5607af878387515beb71e130a651017dfe6e7107
https://github.com/dwyl/aws-sdk-mock/blob/5607af878387515beb71e130a651017dfe6e7107/index.js#L250-L259
11,994
Microsoft/fast-dna
build/copy-readme.js
copyReadmeFiles
function copyReadmeFiles() { const resolvedSrcReadmePaths = path.resolve(rootDir, srcReadmePaths); glob(resolvedSrcReadmePaths, void(0), function(error, files) { files.forEach((filePath) => { const destReadmePath = filePath.replace(/(\bsrc\b)(?!.*\1)/, destDir); fs.copyFileSync(filePath, destReadmePath); }); }); }
javascript
function copyReadmeFiles() { const resolvedSrcReadmePaths = path.resolve(rootDir, srcReadmePaths); glob(resolvedSrcReadmePaths, void(0), function(error, files) { files.forEach((filePath) => { const destReadmePath = filePath.replace(/(\bsrc\b)(?!.*\1)/, destDir); fs.copyFileSync(filePath, destReadmePath); }); }); }
[ "function", "copyReadmeFiles", "(", ")", "{", "const", "resolvedSrcReadmePaths", "=", "path", ".", "resolve", "(", "rootDir", ",", "srcReadmePaths", ")", ";", "glob", "(", "resolvedSrcReadmePaths", ",", "void", "(", "0", ")", ",", "function", "(", "error", ",", "files", ")", "{", "files", ".", "forEach", "(", "(", "filePath", ")", "=>", "{", "const", "destReadmePath", "=", "filePath", ".", "replace", "(", "/", "(\\bsrc\\b)(?!.*\\1)", "/", ",", "destDir", ")", ";", "fs", ".", "copyFileSync", "(", "filePath", ",", "destReadmePath", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Function to copy readme files to their dist folder
[ "Function", "to", "copy", "readme", "files", "to", "their", "dist", "folder" ]
807a3ad3252ef8685da95e57490f5015287b0566
https://github.com/Microsoft/fast-dna/blob/807a3ad3252ef8685da95e57490f5015287b0566/build/copy-readme.js#L16-L25
11,995
Microsoft/fast-dna
build/documentation/generate-typedocs.js
execute
function execute() { if (dryRun) { console.log(`In ${destDir}, this script would...`); } else { console.log(`Generating API documentation using TypeDoc...`); } const packages = path.resolve(rootDir, srcDir); glob(packages, {realpath:true}, function(error, srcFiles) { srcFiles.forEach((srcPath) => { var valid = true; var packageName = srcPath .split(path.sep) .pop(); excludedPackages.forEach((excludedPackageName) => { if (packageName === excludedPackageName) { console.log(chalk.yellow(`...skip generating TypeDoc API files for ${packageName}`)); valid = false; } }); if(valid) { dryRun ? console.log(`...generate TypeDoc API files for ${packageName}`) : createAPIFiles(packageName, srcPath); } }); }); }
javascript
function execute() { if (dryRun) { console.log(`In ${destDir}, this script would...`); } else { console.log(`Generating API documentation using TypeDoc...`); } const packages = path.resolve(rootDir, srcDir); glob(packages, {realpath:true}, function(error, srcFiles) { srcFiles.forEach((srcPath) => { var valid = true; var packageName = srcPath .split(path.sep) .pop(); excludedPackages.forEach((excludedPackageName) => { if (packageName === excludedPackageName) { console.log(chalk.yellow(`...skip generating TypeDoc API files for ${packageName}`)); valid = false; } }); if(valid) { dryRun ? console.log(`...generate TypeDoc API files for ${packageName}`) : createAPIFiles(packageName, srcPath); } }); }); }
[ "function", "execute", "(", ")", "{", "if", "(", "dryRun", ")", "{", "console", ".", "log", "(", "`", "${", "destDir", "}", "`", ")", ";", "}", "else", "{", "console", ".", "log", "(", "`", "`", ")", ";", "}", "const", "packages", "=", "path", ".", "resolve", "(", "rootDir", ",", "srcDir", ")", ";", "glob", "(", "packages", ",", "{", "realpath", ":", "true", "}", ",", "function", "(", "error", ",", "srcFiles", ")", "{", "srcFiles", ".", "forEach", "(", "(", "srcPath", ")", "=>", "{", "var", "valid", "=", "true", ";", "var", "packageName", "=", "srcPath", ".", "split", "(", "path", ".", "sep", ")", ".", "pop", "(", ")", ";", "excludedPackages", ".", "forEach", "(", "(", "excludedPackageName", ")", "=>", "{", "if", "(", "packageName", "===", "excludedPackageName", ")", "{", "console", ".", "log", "(", "chalk", ".", "yellow", "(", "`", "${", "packageName", "}", "`", ")", ")", ";", "valid", "=", "false", ";", "}", "}", ")", ";", "if", "(", "valid", ")", "{", "dryRun", "?", "console", ".", "log", "(", "`", "${", "packageName", "}", "`", ")", ":", "createAPIFiles", "(", "packageName", ",", "srcPath", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Generate TypeDocs for each package
[ "Generate", "TypeDocs", "for", "each", "package" ]
807a3ad3252ef8685da95e57490f5015287b0566
https://github.com/Microsoft/fast-dna/blob/807a3ad3252ef8685da95e57490f5015287b0566/build/documentation/generate-typedocs.js#L72-L106
11,996
Microsoft/fast-dna
build/documentation/generate-typedocs.js
addHeaderToReadme
function addHeaderToReadme(packageName) { const readmePath = path.join(destDir, packageName, 'api', 'README.md'); const readmeText = fs.readFileSync(readmePath).toString(); var docusaurusHeader = `---\n` + `id: index\n` + `---\n\n`; try { fs.writeFileSync(readmePath, docusaurusHeader); fs.appendFileSync(readmePath, readmeText); } catch (err) { console.log(chalk.red(err)); } }
javascript
function addHeaderToReadme(packageName) { const readmePath = path.join(destDir, packageName, 'api', 'README.md'); const readmeText = fs.readFileSync(readmePath).toString(); var docusaurusHeader = `---\n` + `id: index\n` + `---\n\n`; try { fs.writeFileSync(readmePath, docusaurusHeader); fs.appendFileSync(readmePath, readmeText); } catch (err) { console.log(chalk.red(err)); } }
[ "function", "addHeaderToReadme", "(", "packageName", ")", "{", "const", "readmePath", "=", "path", ".", "join", "(", "destDir", ",", "packageName", ",", "'api'", ",", "'README.md'", ")", ";", "const", "readmeText", "=", "fs", ".", "readFileSync", "(", "readmePath", ")", ".", "toString", "(", ")", ";", "var", "docusaurusHeader", "=", "`", "\\n", "`", "+", "`", "\\n", "`", "+", "`", "\\n", "\\n", "`", ";", "try", "{", "fs", ".", "writeFileSync", "(", "readmePath", ",", "docusaurusHeader", ")", ";", "fs", ".", "appendFileSync", "(", "readmePath", ",", "readmeText", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "chalk", ".", "red", "(", "err", ")", ")", ";", "}", "}" ]
If the TypeDoc readme doesn't have this header It won't be accessible in docusaurus
[ "If", "the", "TypeDoc", "readme", "doesn", "t", "have", "this", "header", "It", "won", "t", "be", "accessible", "in", "docusaurus" ]
807a3ad3252ef8685da95e57490f5015287b0566
https://github.com/Microsoft/fast-dna/blob/807a3ad3252ef8685da95e57490f5015287b0566/build/documentation/generate-typedocs.js#L157-L174
11,997
Microsoft/fast-dna
build/documentation/generate-typedocs.js
addAPILinkToReadme
function addAPILinkToReadme(packageName) { var readmePath = path.join(destDir, packageName, 'README.md'); var apiLink = "api"; var usageText = "\n" + `[API Reference](${apiLink})`; fs.appendFile(readmePath, usageText, function (err) { if (err) { console.log(chalk.red(err)); } }) }
javascript
function addAPILinkToReadme(packageName) { var readmePath = path.join(destDir, packageName, 'README.md'); var apiLink = "api"; var usageText = "\n" + `[API Reference](${apiLink})`; fs.appendFile(readmePath, usageText, function (err) { if (err) { console.log(chalk.red(err)); } }) }
[ "function", "addAPILinkToReadme", "(", "packageName", ")", "{", "var", "readmePath", "=", "path", ".", "join", "(", "destDir", ",", "packageName", ",", "'README.md'", ")", ";", "var", "apiLink", "=", "\"api\"", ";", "var", "usageText", "=", "\"\\n\"", "+", "`", "${", "apiLink", "}", "`", ";", "fs", ".", "appendFile", "(", "readmePath", ",", "usageText", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "chalk", ".", "red", "(", "err", ")", ")", ";", "}", "}", ")", "}" ]
Creates link in package readme.md docs used by Docusaurus Said link routes to the TypeDoc API docs generated by this script
[ "Creates", "link", "in", "package", "readme", ".", "md", "docs", "used", "by", "Docusaurus", "Said", "link", "routes", "to", "the", "TypeDoc", "API", "docs", "generated", "by", "this", "script" ]
807a3ad3252ef8685da95e57490f5015287b0566
https://github.com/Microsoft/fast-dna/blob/807a3ad3252ef8685da95e57490f5015287b0566/build/documentation/generate-typedocs.js#L180-L195
11,998
Microsoft/fast-dna
build/documentation/copy-package-readme.js
createDirectory
function createDirectory(dir) { if (!fs.existsSync(dir)) { dryRun ? console.log(`...CREATE the '${dir}' folder.`) : fs.mkdirSync(dir); } }
javascript
function createDirectory(dir) { if (!fs.existsSync(dir)) { dryRun ? console.log(`...CREATE the '${dir}' folder.`) : fs.mkdirSync(dir); } }
[ "function", "createDirectory", "(", "dir", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "dir", ")", ")", "{", "dryRun", "?", "console", ".", "log", "(", "`", "${", "dir", "}", "`", ")", ":", "fs", ".", "mkdirSync", "(", "dir", ")", ";", "}", "}" ]
Utility function that creates new folders based off dir argument
[ "Utility", "function", "that", "creates", "new", "folders", "based", "off", "dir", "argument" ]
807a3ad3252ef8685da95e57490f5015287b0566
https://github.com/Microsoft/fast-dna/blob/807a3ad3252ef8685da95e57490f5015287b0566/build/documentation/copy-package-readme.js#L156-L160
11,999
Microsoft/fast-dna
build/convert-readme.js
exportReadme
function exportReadme(readmePath) { const readmePaths = path.resolve(process.cwd(), srcDir); glob(readmePaths, void(0), function(error, files) { files.forEach((filePath) => { let documentation = startFile; const markdown = fs.readFileSync(filePath, "utf8"); const exportPath = filePath.replace(/README\.md/, readmePath); if (markdown.length !== 0) { documentation += md.render(markdown); } else { documentation += emptyFile; } documentation += endFile; if (!fs.existsSync(exportPath)){ fs.mkdirSync(exportPath); } fs.writeFileSync(path.resolve(exportPath, "documentation.tsx"), documentation); }); }); }
javascript
function exportReadme(readmePath) { const readmePaths = path.resolve(process.cwd(), srcDir); glob(readmePaths, void(0), function(error, files) { files.forEach((filePath) => { let documentation = startFile; const markdown = fs.readFileSync(filePath, "utf8"); const exportPath = filePath.replace(/README\.md/, readmePath); if (markdown.length !== 0) { documentation += md.render(markdown); } else { documentation += emptyFile; } documentation += endFile; if (!fs.existsSync(exportPath)){ fs.mkdirSync(exportPath); } fs.writeFileSync(path.resolve(exportPath, "documentation.tsx"), documentation); }); }); }
[ "function", "exportReadme", "(", "readmePath", ")", "{", "const", "readmePaths", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "srcDir", ")", ";", "glob", "(", "readmePaths", ",", "void", "(", "0", ")", ",", "function", "(", "error", ",", "files", ")", "{", "files", ".", "forEach", "(", "(", "filePath", ")", "=>", "{", "let", "documentation", "=", "startFile", ";", "const", "markdown", "=", "fs", ".", "readFileSync", "(", "filePath", ",", "\"utf8\"", ")", ";", "const", "exportPath", "=", "filePath", ".", "replace", "(", "/", "README\\.md", "/", ",", "readmePath", ")", ";", "if", "(", "markdown", ".", "length", "!==", "0", ")", "{", "documentation", "+=", "md", ".", "render", "(", "markdown", ")", ";", "}", "else", "{", "documentation", "+=", "emptyFile", ";", "}", "documentation", "+=", "endFile", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "exportPath", ")", ")", "{", "fs", ".", "mkdirSync", "(", "exportPath", ")", ";", "}", "fs", ".", "writeFileSync", "(", "path", ".", "resolve", "(", "exportPath", ",", "\"documentation.tsx\"", ")", ",", "documentation", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Function to create string exports of a given path
[ "Function", "to", "create", "string", "exports", "of", "a", "given", "path" ]
807a3ad3252ef8685da95e57490f5015287b0566
https://github.com/Microsoft/fast-dna/blob/807a3ad3252ef8685da95e57490f5015287b0566/build/convert-readme.js#L46-L70