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
41,000
nightwolfz/mobx-connect
src/connect.js
provide
function provide() { if (console) console.warn('@provide is now deprecated. Use @connect instead'); return composeWithContext(Array.prototype.slice.call(arguments)) }
javascript
function provide() { if (console) console.warn('@provide is now deprecated. Use @connect instead'); return composeWithContext(Array.prototype.slice.call(arguments)) }
[ "function", "provide", "(", ")", "{", "if", "(", "console", ")", "console", ".", "warn", "(", "'@provide is now deprecated. Use @connect instead'", ")", ";", "return", "composeWithContext", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", "}" ]
Grant components access to store and state without making observable @param args {Component|...String} @returns {Component|Object}
[ "Grant", "components", "access", "to", "store", "and", "state", "without", "making", "observable" ]
139636954359079717f4ac522fe5943efab6744d
https://github.com/nightwolfz/mobx-connect/blob/139636954359079717f4ac522fe5943efab6744d/src/connect.js#L76-L79
41,001
dailymotion/vmap-js
src/parser_utils.js
parseNodeValue
function parseNodeValue(node) { const childNodes = node && node.childNodes && [...node.childNodes]; if (!childNodes) { return {}; } // Trying to find and parse CDATA as JSON const cdatas = childNodes.filter((childNode) => childNode.nodeName === '#cdata-section'); if (cdatas && cdatas.length > 0) { try { return JSON.parse(cdatas[0].data); } catch (e) {} } // Didn't find any CDATA or failed to parse it as JSON return childNodes.reduce((previousText, childNode) => { let nodeText = ''; switch (childNode.nodeName) { case '#text': nodeText = childNode.textContent.trim(); break; case '#cdata-section': nodeText = childNode.data; break; } return previousText + nodeText; }, ''); }
javascript
function parseNodeValue(node) { const childNodes = node && node.childNodes && [...node.childNodes]; if (!childNodes) { return {}; } // Trying to find and parse CDATA as JSON const cdatas = childNodes.filter((childNode) => childNode.nodeName === '#cdata-section'); if (cdatas && cdatas.length > 0) { try { return JSON.parse(cdatas[0].data); } catch (e) {} } // Didn't find any CDATA or failed to parse it as JSON return childNodes.reduce((previousText, childNode) => { let nodeText = ''; switch (childNode.nodeName) { case '#text': nodeText = childNode.textContent.trim(); break; case '#cdata-section': nodeText = childNode.data; break; } return previousText + nodeText; }, ''); }
[ "function", "parseNodeValue", "(", "node", ")", "{", "const", "childNodes", "=", "node", "&&", "node", ".", "childNodes", "&&", "[", "...", "node", ".", "childNodes", "]", ";", "if", "(", "!", "childNodes", ")", "{", "return", "{", "}", ";", "}", "// Trying to find and parse CDATA as JSON", "const", "cdatas", "=", "childNodes", ".", "filter", "(", "(", "childNode", ")", "=>", "childNode", ".", "nodeName", "===", "'#cdata-section'", ")", ";", "if", "(", "cdatas", "&&", "cdatas", ".", "length", ">", "0", ")", "{", "try", "{", "return", "JSON", ".", "parse", "(", "cdatas", "[", "0", "]", ".", "data", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "// Didn't find any CDATA or failed to parse it as JSON", "return", "childNodes", ".", "reduce", "(", "(", "previousText", ",", "childNode", ")", "=>", "{", "let", "nodeText", "=", "''", ";", "switch", "(", "childNode", ".", "nodeName", ")", "{", "case", "'#text'", ":", "nodeText", "=", "childNode", ".", "textContent", ".", "trim", "(", ")", ";", "break", ";", "case", "'#cdata-section'", ":", "nodeText", "=", "childNode", ".", "data", ";", "break", ";", "}", "return", "previousText", "+", "nodeText", ";", "}", ",", "''", ")", ";", "}" ]
Parses a node value giving priority to CDATA as a JSON over text, if CDATA is not a valid JSON it is converted to text @param {Object} node - The node to parse the value from. @return {String|Object}
[ "Parses", "a", "node", "value", "giving", "priority", "to", "CDATA", "as", "a", "JSON", "over", "text", "if", "CDATA", "is", "not", "a", "valid", "JSON", "it", "is", "converted", "to", "text" ]
7c16cc5745dc819343856de4f7252659a66c463e
https://github.com/dailymotion/vmap-js/blob/7c16cc5745dc819343856de4f7252659a66c463e/src/parser_utils.js#L21-L48
41,002
dailymotion/vmap-js
src/parser_utils.js
parseXMLNode
function parseXMLNode(node) { const parsedNode = { attributes: {}, children: {}, value: {}, }; parsedNode.value = parseNodeValue(node); if (node.attributes) { [...node.attributes].forEach((nodeAttr) => { if (nodeAttr.nodeName && nodeAttr.nodeValue !== undefined && nodeAttr.nodeValue !== null) { parsedNode.attributes[nodeAttr.nodeName] = nodeAttr.nodeValue; } }); } if (node.childNodes) { [...node.childNodes] .filter((childNode) => childNode.nodeName.substring(0, 1) !== '#') .forEach((childNode) => { parsedNode.children[childNode.nodeName] = parseXMLNode(childNode); }); } return parsedNode; }
javascript
function parseXMLNode(node) { const parsedNode = { attributes: {}, children: {}, value: {}, }; parsedNode.value = parseNodeValue(node); if (node.attributes) { [...node.attributes].forEach((nodeAttr) => { if (nodeAttr.nodeName && nodeAttr.nodeValue !== undefined && nodeAttr.nodeValue !== null) { parsedNode.attributes[nodeAttr.nodeName] = nodeAttr.nodeValue; } }); } if (node.childNodes) { [...node.childNodes] .filter((childNode) => childNode.nodeName.substring(0, 1) !== '#') .forEach((childNode) => { parsedNode.children[childNode.nodeName] = parseXMLNode(childNode); }); } return parsedNode; }
[ "function", "parseXMLNode", "(", "node", ")", "{", "const", "parsedNode", "=", "{", "attributes", ":", "{", "}", ",", "children", ":", "{", "}", ",", "value", ":", "{", "}", ",", "}", ";", "parsedNode", ".", "value", "=", "parseNodeValue", "(", "node", ")", ";", "if", "(", "node", ".", "attributes", ")", "{", "[", "...", "node", ".", "attributes", "]", ".", "forEach", "(", "(", "nodeAttr", ")", "=>", "{", "if", "(", "nodeAttr", ".", "nodeName", "&&", "nodeAttr", ".", "nodeValue", "!==", "undefined", "&&", "nodeAttr", ".", "nodeValue", "!==", "null", ")", "{", "parsedNode", ".", "attributes", "[", "nodeAttr", ".", "nodeName", "]", "=", "nodeAttr", ".", "nodeValue", ";", "}", "}", ")", ";", "}", "if", "(", "node", ".", "childNodes", ")", "{", "[", "...", "node", ".", "childNodes", "]", ".", "filter", "(", "(", "childNode", ")", "=>", "childNode", ".", "nodeName", ".", "substring", "(", "0", ",", "1", ")", "!==", "'#'", ")", ".", "forEach", "(", "(", "childNode", ")", "=>", "{", "parsedNode", ".", "children", "[", "childNode", ".", "nodeName", "]", "=", "parseXMLNode", "(", "childNode", ")", ";", "}", ")", ";", "}", "return", "parsedNode", ";", "}" ]
Parses an XML node recursively. @param {Object} node - The node to parse. @return {Object}
[ "Parses", "an", "XML", "node", "recursively", "." ]
7c16cc5745dc819343856de4f7252659a66c463e
https://github.com/dailymotion/vmap-js/blob/7c16cc5745dc819343856de4f7252659a66c463e/src/parser_utils.js#L55-L81
41,003
c-h-/node-run-cmd
index.js
async
function async(makeGenerator) { return () => { const generator = makeGenerator(...arguments); function handle(result) { // result => { done: [Boolean], value: [Object] } if (result.done) { return Promise.resolve(result.value); } return Promise.resolve(result.value).then(res => { return handle(generator.next(res)); }, err => { return handle(generator.throw(err)); }); } try { return handle(generator.next()); } catch (ex) { return Promise.reject(ex); } }; }
javascript
function async(makeGenerator) { return () => { const generator = makeGenerator(...arguments); function handle(result) { // result => { done: [Boolean], value: [Object] } if (result.done) { return Promise.resolve(result.value); } return Promise.resolve(result.value).then(res => { return handle(generator.next(res)); }, err => { return handle(generator.throw(err)); }); } try { return handle(generator.next()); } catch (ex) { return Promise.reject(ex); } }; }
[ "function", "async", "(", "makeGenerator", ")", "{", "return", "(", ")", "=>", "{", "const", "generator", "=", "makeGenerator", "(", "...", "arguments", ")", ";", "function", "handle", "(", "result", ")", "{", "// result => { done: [Boolean], value: [Object] }", "if", "(", "result", ".", "done", ")", "{", "return", "Promise", ".", "resolve", "(", "result", ".", "value", ")", ";", "}", "return", "Promise", ".", "resolve", "(", "result", ".", "value", ")", ".", "then", "(", "res", "=>", "{", "return", "handle", "(", "generator", ".", "next", "(", "res", ")", ")", ";", "}", ",", "err", "=>", "{", "return", "handle", "(", "generator", ".", "throw", "(", "err", ")", ")", ";", "}", ")", ";", "}", "try", "{", "return", "handle", "(", "generator", ".", "next", "(", ")", ")", ";", "}", "catch", "(", "ex", ")", "{", "return", "Promise", ".", "reject", "(", "ex", ")", ";", "}", "}", ";", "}" ]
Returns a function that resolves any yielded promises inside the generator. @param {Function} makeGenerator - the function to turn into an async generator/promise @returns {Function} the function that will iterate over interior promises on each call when invoked
[ "Returns", "a", "function", "that", "resolves", "any", "yielded", "promises", "inside", "the", "generator", "." ]
2cca799e75cbb6afba63dc6ae1598324143a71d6
https://github.com/c-h-/node-run-cmd/blob/2cca799e75cbb6afba63dc6ae1598324143a71d6/index.js#L107-L130
41,004
c-h-/node-run-cmd
index.js
runMultiple
function runMultiple(input, options) { return new Promise((resolve, reject) => { let commands = input; // set default options const defaultOpts = { cwd: process.cwd(), verbose: DEFAULT_VERBOSE, mode: SEQUENTIAL, logger: console.log, }; // set global options const globalOpts = Object.assign({}, defaultOpts, options); // resolve string to proper input type if (typeof commands === 'string') { commands = [{ command: commands }]; } // start execution if (commands && typeof commands === 'object') { if (Object.prototype.toString.call(commands) !== '[object Array]') { // not array commands = [commands]; } else { // is array, check type of children commands = commands.map(cmd => typeof cmd === 'object' ? cmd : { command: cmd }); } // run commands in parallel if (globalOpts.mode === PARALLEL) { const promises = commands.map(cmd => { const resolvedOpts = Object.assign({}, globalOpts, cmd); return run(resolvedOpts); }); Promise.all(promises).then(resolve, reject); } else { // run commands in sequence (default) async(function* () { try { const results = []; for (const i in commands) { const cmd = commands[i]; const resolvedOpts = Object.assign({}, globalOpts, cmd); const result = yield run(resolvedOpts); results.push(result); } if (results) { resolve(results); } else { reject('Falsy value in results'); } } catch (e) { reject(e); } })(); } } else { reject('Invalid input'); } }); }
javascript
function runMultiple(input, options) { return new Promise((resolve, reject) => { let commands = input; // set default options const defaultOpts = { cwd: process.cwd(), verbose: DEFAULT_VERBOSE, mode: SEQUENTIAL, logger: console.log, }; // set global options const globalOpts = Object.assign({}, defaultOpts, options); // resolve string to proper input type if (typeof commands === 'string') { commands = [{ command: commands }]; } // start execution if (commands && typeof commands === 'object') { if (Object.prototype.toString.call(commands) !== '[object Array]') { // not array commands = [commands]; } else { // is array, check type of children commands = commands.map(cmd => typeof cmd === 'object' ? cmd : { command: cmd }); } // run commands in parallel if (globalOpts.mode === PARALLEL) { const promises = commands.map(cmd => { const resolvedOpts = Object.assign({}, globalOpts, cmd); return run(resolvedOpts); }); Promise.all(promises).then(resolve, reject); } else { // run commands in sequence (default) async(function* () { try { const results = []; for (const i in commands) { const cmd = commands[i]; const resolvedOpts = Object.assign({}, globalOpts, cmd); const result = yield run(resolvedOpts); results.push(result); } if (results) { resolve(results); } else { reject('Falsy value in results'); } } catch (e) { reject(e); } })(); } } else { reject('Invalid input'); } }); }
[ "function", "runMultiple", "(", "input", ",", "options", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "commands", "=", "input", ";", "// set default options", "const", "defaultOpts", "=", "{", "cwd", ":", "process", ".", "cwd", "(", ")", ",", "verbose", ":", "DEFAULT_VERBOSE", ",", "mode", ":", "SEQUENTIAL", ",", "logger", ":", "console", ".", "log", ",", "}", ";", "// set global options", "const", "globalOpts", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultOpts", ",", "options", ")", ";", "// resolve string to proper input type", "if", "(", "typeof", "commands", "===", "'string'", ")", "{", "commands", "=", "[", "{", "command", ":", "commands", "}", "]", ";", "}", "// start execution", "if", "(", "commands", "&&", "typeof", "commands", "===", "'object'", ")", "{", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "commands", ")", "!==", "'[object Array]'", ")", "{", "// not array", "commands", "=", "[", "commands", "]", ";", "}", "else", "{", "// is array, check type of children", "commands", "=", "commands", ".", "map", "(", "cmd", "=>", "typeof", "cmd", "===", "'object'", "?", "cmd", ":", "{", "command", ":", "cmd", "}", ")", ";", "}", "// run commands in parallel", "if", "(", "globalOpts", ".", "mode", "===", "PARALLEL", ")", "{", "const", "promises", "=", "commands", ".", "map", "(", "cmd", "=>", "{", "const", "resolvedOpts", "=", "Object", ".", "assign", "(", "{", "}", ",", "globalOpts", ",", "cmd", ")", ";", "return", "run", "(", "resolvedOpts", ")", ";", "}", ")", ";", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "resolve", ",", "reject", ")", ";", "}", "else", "{", "// run commands in sequence (default)", "async", "(", "function", "*", "(", ")", "{", "try", "{", "const", "results", "=", "[", "]", ";", "for", "(", "const", "i", "in", "commands", ")", "{", "const", "cmd", "=", "commands", "[", "i", "]", ";", "const", "resolvedOpts", "=", "Object", ".", "assign", "(", "{", "}", ",", "globalOpts", ",", "cmd", ")", ";", "const", "result", "=", "yield", "run", "(", "resolvedOpts", ")", ";", "results", ".", "push", "(", "result", ")", ";", "}", "if", "(", "results", ")", "{", "resolve", "(", "results", ")", ";", "}", "else", "{", "reject", "(", "'Falsy value in results'", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "}", ")", "(", ")", ";", "}", "}", "else", "{", "reject", "(", "'Invalid input'", ")", ";", "}", "}", ")", ";", "}" ]
Run multiple commands. @param {Array} commands - an array of objects or strings containing details of commands to run @param {Object} options - an object containing global options for each command @example runMultiple(['mkdir test', 'cd test', 'ls']); @example runMultiple(['mkdir test', 'cd test', 'ls'], { cwd: '../myCustomWorkingDirectory' }); @example const commandsToRun = [ { command: 'ls', onData: function(data) { console.log(data) } }, override globalOptions working directory with each commands' options { command: 'mkdir test', cwd: '../../customCwdNumber2', onDone: function() { console.log('done mkdir!') } }, 'ls ~/Desktop' // finish up with simple string command ]; const globalOptions = { cwd: '../myCustomWorkingDirectory' }; runMultiple(commandsToRun, globalOptions);
[ "Run", "multiple", "commands", "." ]
2cca799e75cbb6afba63dc6ae1598324143a71d6
https://github.com/c-h-/node-run-cmd/blob/2cca799e75cbb6afba63dc6ae1598324143a71d6/index.js#L151-L216
41,005
parkerd/statsd-zabbix-backend
lib/zabbix.js
itemsForCounter
function itemsForCounter(flushInterval, host, key, value) { const avg = value / (flushInterval / 1000); // calculate "per second" rate return [ { host, key: `${key}[total]`, value, }, { host, key: `${key}[avg]`, value: avg, }, ]; }
javascript
function itemsForCounter(flushInterval, host, key, value) { const avg = value / (flushInterval / 1000); // calculate "per second" rate return [ { host, key: `${key}[total]`, value, }, { host, key: `${key}[avg]`, value: avg, }, ]; }
[ "function", "itemsForCounter", "(", "flushInterval", ",", "host", ",", "key", ",", "value", ")", "{", "const", "avg", "=", "value", "/", "(", "flushInterval", "/", "1000", ")", ";", "// calculate \"per second\" rate", "return", "[", "{", "host", ",", "key", ":", "`", "${", "key", "}", "`", ",", "value", ",", "}", ",", "{", "host", ",", "key", ":", "`", "${", "key", "}", "`", ",", "value", ":", "avg", ",", "}", ",", "]", ";", "}" ]
Generate items for a counter. @param {number} flushInterval How long stats were collected, for calculating average. @param {string} host Hostname in Zabbix. @param {string} key Item key in Zabbix. @param {number} value Total collected during interval. @returns {array} Array of {host, key, value} objects.
[ "Generate", "items", "for", "a", "counter", "." ]
e459939108ae6aee3b155eed6b76eba1dc053af9
https://github.com/parkerd/statsd-zabbix-backend/blob/e459939108ae6aee3b155eed6b76eba1dc053af9/lib/zabbix.js#L116-L131
41,006
parkerd/statsd-zabbix-backend
lib/zabbix.js
itemsForTimer
function itemsForTimer(percentiles, host, key, data) { const values = data.sort((a, b) => (a - b)); const count = values.length; const min = values[0]; const max = values[count - 1]; let mean = min; let maxAtThreshold = max; const items = [ { host, key: `${key}[lower]`, value: min || 0, }, { host, key: `${key}[upper]`, value: max || 0, }, { host, key: `${key}[count]`, value: count, }, ]; percentiles.forEach((percentile) => { const strPercentile = percentile.toString().replace('.', '_'); if (count > 1) { const thresholdIndex = Math.round(((100 - percentile) / 100) * count); const numInThreshold = count - thresholdIndex; const percentValues = values.slice(0, numInThreshold); maxAtThreshold = percentValues[numInThreshold - 1]; // Average the remaining timings let sum = 0; for (let i = 0; i < numInThreshold; i += 1) { sum += percentValues[i]; } mean = sum / numInThreshold; } items.push({ host, key: `${key}[mean][${strPercentile}]`, value: mean || 0, }); items.push({ host, key: `${key}[upper][${strPercentile}]`, value: maxAtThreshold || 0, }); }); return items; }
javascript
function itemsForTimer(percentiles, host, key, data) { const values = data.sort((a, b) => (a - b)); const count = values.length; const min = values[0]; const max = values[count - 1]; let mean = min; let maxAtThreshold = max; const items = [ { host, key: `${key}[lower]`, value: min || 0, }, { host, key: `${key}[upper]`, value: max || 0, }, { host, key: `${key}[count]`, value: count, }, ]; percentiles.forEach((percentile) => { const strPercentile = percentile.toString().replace('.', '_'); if (count > 1) { const thresholdIndex = Math.round(((100 - percentile) / 100) * count); const numInThreshold = count - thresholdIndex; const percentValues = values.slice(0, numInThreshold); maxAtThreshold = percentValues[numInThreshold - 1]; // Average the remaining timings let sum = 0; for (let i = 0; i < numInThreshold; i += 1) { sum += percentValues[i]; } mean = sum / numInThreshold; } items.push({ host, key: `${key}[mean][${strPercentile}]`, value: mean || 0, }); items.push({ host, key: `${key}[upper][${strPercentile}]`, value: maxAtThreshold || 0, }); }); return items; }
[ "function", "itemsForTimer", "(", "percentiles", ",", "host", ",", "key", ",", "data", ")", "{", "const", "values", "=", "data", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "(", "a", "-", "b", ")", ")", ";", "const", "count", "=", "values", ".", "length", ";", "const", "min", "=", "values", "[", "0", "]", ";", "const", "max", "=", "values", "[", "count", "-", "1", "]", ";", "let", "mean", "=", "min", ";", "let", "maxAtThreshold", "=", "max", ";", "const", "items", "=", "[", "{", "host", ",", "key", ":", "`", "${", "key", "}", "`", ",", "value", ":", "min", "||", "0", ",", "}", ",", "{", "host", ",", "key", ":", "`", "${", "key", "}", "`", ",", "value", ":", "max", "||", "0", ",", "}", ",", "{", "host", ",", "key", ":", "`", "${", "key", "}", "`", ",", "value", ":", "count", ",", "}", ",", "]", ";", "percentiles", ".", "forEach", "(", "(", "percentile", ")", "=>", "{", "const", "strPercentile", "=", "percentile", ".", "toString", "(", ")", ".", "replace", "(", "'.'", ",", "'_'", ")", ";", "if", "(", "count", ">", "1", ")", "{", "const", "thresholdIndex", "=", "Math", ".", "round", "(", "(", "(", "100", "-", "percentile", ")", "/", "100", ")", "*", "count", ")", ";", "const", "numInThreshold", "=", "count", "-", "thresholdIndex", ";", "const", "percentValues", "=", "values", ".", "slice", "(", "0", ",", "numInThreshold", ")", ";", "maxAtThreshold", "=", "percentValues", "[", "numInThreshold", "-", "1", "]", ";", "// Average the remaining timings", "let", "sum", "=", "0", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "numInThreshold", ";", "i", "+=", "1", ")", "{", "sum", "+=", "percentValues", "[", "i", "]", ";", "}", "mean", "=", "sum", "/", "numInThreshold", ";", "}", "items", ".", "push", "(", "{", "host", ",", "key", ":", "`", "${", "key", "}", "${", "strPercentile", "}", "`", ",", "value", ":", "mean", "||", "0", ",", "}", ")", ";", "items", ".", "push", "(", "{", "host", ",", "key", ":", "`", "${", "key", "}", "${", "strPercentile", "}", "`", ",", "value", ":", "maxAtThreshold", "||", "0", ",", "}", ")", ";", "}", ")", ";", "return", "items", ";", "}" ]
Generate items for a timer. @param {array} percentiles Array of numbers, percentiles to calculate mean and max for. @param {string} host Hostname in Zabbix. @param {string} key Item key in Zabbix. @param {number} data All timing values collected during interval. @returns {array} Array of {host, key, value} objects.
[ "Generate", "items", "for", "a", "timer", "." ]
e459939108ae6aee3b155eed6b76eba1dc053af9
https://github.com/parkerd/statsd-zabbix-backend/blob/e459939108ae6aee3b155eed6b76eba1dc053af9/lib/zabbix.js#L141-L199
41,007
parkerd/statsd-zabbix-backend
lib/zabbix.js
flush
function flush(targetBuilder, sender, flushInterval, timestamp, metrics) { debug(`starting flush for timestamp ${timestamp}`); const flushStart = tsNow(); const handle = (processor, stat, value) => { try { const { host, key } = targetBuilder(stat); processor(host, key, value).forEach((item) => { sender.addItem(item.host, item.key, item.value); debug(`${item.host} -> ${item.key} -> ${item.value}`); }); } catch (err) { stats.last_exception = tsNow(); error(err); } }; const counterProcessor = itemsForCounter.bind(undefined, flushInterval); Object.keys(metrics.counters).forEach((stat) => { handle(counterProcessor, stat, metrics.counters[stat]); }); const timerProcessor = itemsForTimer.bind(undefined, metrics.pctThreshold); Object.keys(metrics.timers).forEach((stat) => { handle(timerProcessor, stat, metrics.timers[stat]); }); Object.keys(metrics.gauges).forEach((stat) => { handle(itemsForGauge, stat, metrics.gauges[stat]); }); stats.flush_length = sender.items.length; debug(`flushing ${stats.flush_length} items to zabbix`); // Send the items to Zabbix sender.send((err, res) => { if (err) { stats.last_exception = tsNow(); error(err); // eslint-disable-next-line no-param-reassign sender.items = []; } else { stats.last_flush = timestamp; stats.flush_time = flushStart - stats.last_flush; debug(`flush completed in ${stats.flush_time} seconds`); } if (res.info) { info(res.info); } }); }
javascript
function flush(targetBuilder, sender, flushInterval, timestamp, metrics) { debug(`starting flush for timestamp ${timestamp}`); const flushStart = tsNow(); const handle = (processor, stat, value) => { try { const { host, key } = targetBuilder(stat); processor(host, key, value).forEach((item) => { sender.addItem(item.host, item.key, item.value); debug(`${item.host} -> ${item.key} -> ${item.value}`); }); } catch (err) { stats.last_exception = tsNow(); error(err); } }; const counterProcessor = itemsForCounter.bind(undefined, flushInterval); Object.keys(metrics.counters).forEach((stat) => { handle(counterProcessor, stat, metrics.counters[stat]); }); const timerProcessor = itemsForTimer.bind(undefined, metrics.pctThreshold); Object.keys(metrics.timers).forEach((stat) => { handle(timerProcessor, stat, metrics.timers[stat]); }); Object.keys(metrics.gauges).forEach((stat) => { handle(itemsForGauge, stat, metrics.gauges[stat]); }); stats.flush_length = sender.items.length; debug(`flushing ${stats.flush_length} items to zabbix`); // Send the items to Zabbix sender.send((err, res) => { if (err) { stats.last_exception = tsNow(); error(err); // eslint-disable-next-line no-param-reassign sender.items = []; } else { stats.last_flush = timestamp; stats.flush_time = flushStart - stats.last_flush; debug(`flush completed in ${stats.flush_time} seconds`); } if (res.info) { info(res.info); } }); }
[ "function", "flush", "(", "targetBuilder", ",", "sender", ",", "flushInterval", ",", "timestamp", ",", "metrics", ")", "{", "debug", "(", "`", "${", "timestamp", "}", "`", ")", ";", "const", "flushStart", "=", "tsNow", "(", ")", ";", "const", "handle", "=", "(", "processor", ",", "stat", ",", "value", ")", "=>", "{", "try", "{", "const", "{", "host", ",", "key", "}", "=", "targetBuilder", "(", "stat", ")", ";", "processor", "(", "host", ",", "key", ",", "value", ")", ".", "forEach", "(", "(", "item", ")", "=>", "{", "sender", ".", "addItem", "(", "item", ".", "host", ",", "item", ".", "key", ",", "item", ".", "value", ")", ";", "debug", "(", "`", "${", "item", ".", "host", "}", "${", "item", ".", "key", "}", "${", "item", ".", "value", "}", "`", ")", ";", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "stats", ".", "last_exception", "=", "tsNow", "(", ")", ";", "error", "(", "err", ")", ";", "}", "}", ";", "const", "counterProcessor", "=", "itemsForCounter", ".", "bind", "(", "undefined", ",", "flushInterval", ")", ";", "Object", ".", "keys", "(", "metrics", ".", "counters", ")", ".", "forEach", "(", "(", "stat", ")", "=>", "{", "handle", "(", "counterProcessor", ",", "stat", ",", "metrics", ".", "counters", "[", "stat", "]", ")", ";", "}", ")", ";", "const", "timerProcessor", "=", "itemsForTimer", ".", "bind", "(", "undefined", ",", "metrics", ".", "pctThreshold", ")", ";", "Object", ".", "keys", "(", "metrics", ".", "timers", ")", ".", "forEach", "(", "(", "stat", ")", "=>", "{", "handle", "(", "timerProcessor", ",", "stat", ",", "metrics", ".", "timers", "[", "stat", "]", ")", ";", "}", ")", ";", "Object", ".", "keys", "(", "metrics", ".", "gauges", ")", ".", "forEach", "(", "(", "stat", ")", "=>", "{", "handle", "(", "itemsForGauge", ",", "stat", ",", "metrics", ".", "gauges", "[", "stat", "]", ")", ";", "}", ")", ";", "stats", ".", "flush_length", "=", "sender", ".", "items", ".", "length", ";", "debug", "(", "`", "${", "stats", ".", "flush_length", "}", "`", ")", ";", "// Send the items to Zabbix", "sender", ".", "send", "(", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "err", ")", "{", "stats", ".", "last_exception", "=", "tsNow", "(", ")", ";", "error", "(", "err", ")", ";", "// eslint-disable-next-line no-param-reassign", "sender", ".", "items", "=", "[", "]", ";", "}", "else", "{", "stats", ".", "last_flush", "=", "timestamp", ";", "stats", ".", "flush_time", "=", "flushStart", "-", "stats", ".", "last_flush", ";", "debug", "(", "`", "${", "stats", ".", "flush_time", "}", "`", ")", ";", "}", "if", "(", "res", ".", "info", ")", "{", "info", "(", "res", ".", "info", ")", ";", "}", "}", ")", ";", "}" ]
Flush metrics data to Zabbix. @param {function} targetBuilder Returns a {host,key} object based on the stat provided. @param {ZabbixSender} sender Instance of ZabbixSender for sending stats to Zabbix. @param {number} flushInterval How long stats were collected, for calculating average. @param {number} timestamp Time of flush as unix timestamp. @param {Object} metrics Metrics provided by StatsD. @returns {undefined}
[ "Flush", "metrics", "data", "to", "Zabbix", "." ]
e459939108ae6aee3b155eed6b76eba1dc053af9
https://github.com/parkerd/statsd-zabbix-backend/blob/e459939108ae6aee3b155eed6b76eba1dc053af9/lib/zabbix.js#L227-L277
41,008
parkerd/statsd-zabbix-backend
lib/zabbix.js
status
function status(writeCb) { Object.keys(stats).forEach((stat) => { writeCb(null, 'zabbix', stat, stats[stat]); }); }
javascript
function status(writeCb) { Object.keys(stats).forEach((stat) => { writeCb(null, 'zabbix', stat, stats[stat]); }); }
[ "function", "status", "(", "writeCb", ")", "{", "Object", ".", "keys", "(", "stats", ")", ".", "forEach", "(", "(", "stat", ")", "=>", "{", "writeCb", "(", "null", ",", "'zabbix'", ",", "stat", ",", "stats", "[", "stat", "]", ")", ";", "}", ")", ";", "}" ]
Dump plugin stats. @param {function} writeCb Callback to write stats to. @returns {undefined}
[ "Dump", "plugin", "stats", "." ]
e459939108ae6aee3b155eed6b76eba1dc053af9
https://github.com/parkerd/statsd-zabbix-backend/blob/e459939108ae6aee3b155eed6b76eba1dc053af9/lib/zabbix.js#L284-L288
41,009
parkerd/statsd-zabbix-backend
lib/zabbix.js
init
function init(startupTime, config, events, l) { logger = l; let targetBuilder; if (config.zabbixTargetHostname) { targetBuilder = targetStatic.bind(undefined, config.zabbixTargetHostname); } else { targetBuilder = targetDecode; } const sender = new ZabbixSender({ host: config.zabbixHost || 'localhost', port: config.zabbixPort || '10051', with_timestamps: config.zabbixSendTimestamps || false, }); stats.last_flush = 0; stats.last_exception = 0; stats.flush_time = 0; stats.flush_length = 0; events.on('flush', flush.bind(undefined, targetBuilder, sender, config.flushInterval)); events.on('status', status); return true; }
javascript
function init(startupTime, config, events, l) { logger = l; let targetBuilder; if (config.zabbixTargetHostname) { targetBuilder = targetStatic.bind(undefined, config.zabbixTargetHostname); } else { targetBuilder = targetDecode; } const sender = new ZabbixSender({ host: config.zabbixHost || 'localhost', port: config.zabbixPort || '10051', with_timestamps: config.zabbixSendTimestamps || false, }); stats.last_flush = 0; stats.last_exception = 0; stats.flush_time = 0; stats.flush_length = 0; events.on('flush', flush.bind(undefined, targetBuilder, sender, config.flushInterval)); events.on('status', status); return true; }
[ "function", "init", "(", "startupTime", ",", "config", ",", "events", ",", "l", ")", "{", "logger", "=", "l", ";", "let", "targetBuilder", ";", "if", "(", "config", ".", "zabbixTargetHostname", ")", "{", "targetBuilder", "=", "targetStatic", ".", "bind", "(", "undefined", ",", "config", ".", "zabbixTargetHostname", ")", ";", "}", "else", "{", "targetBuilder", "=", "targetDecode", ";", "}", "const", "sender", "=", "new", "ZabbixSender", "(", "{", "host", ":", "config", ".", "zabbixHost", "||", "'localhost'", ",", "port", ":", "config", ".", "zabbixPort", "||", "'10051'", ",", "with_timestamps", ":", "config", ".", "zabbixSendTimestamps", "||", "false", ",", "}", ")", ";", "stats", ".", "last_flush", "=", "0", ";", "stats", ".", "last_exception", "=", "0", ";", "stats", ".", "flush_time", "=", "0", ";", "stats", ".", "flush_length", "=", "0", ";", "events", ".", "on", "(", "'flush'", ",", "flush", ".", "bind", "(", "undefined", ",", "targetBuilder", ",", "sender", ",", "config", ".", "flushInterval", ")", ")", ";", "events", ".", "on", "(", "'status'", ",", "status", ")", ";", "return", "true", ";", "}" ]
Initalize the plugin. @param {number} startupTime Timestamp StatsD started. @param {Object} config Global configuration provided to StatsD. @param {Object} events Event handler to register actions on. @param {Object} l Global logger instance. @returns {boolean} Status of initialization.
[ "Initalize", "the", "plugin", "." ]
e459939108ae6aee3b155eed6b76eba1dc053af9
https://github.com/parkerd/statsd-zabbix-backend/blob/e459939108ae6aee3b155eed6b76eba1dc053af9/lib/zabbix.js#L298-L323
41,010
gagan-bansal/json-groupby
json-groupby.js
collectProperties
function collectProperties(groups, properties) { var collection = {}; for (var key in groups) { if (Array.isArray(groups[key])) { collection[key] = groups[key].reduce(function(coll, item) { properties.forEach(function(prop) { if (!coll[prop]) coll[prop] = []; coll[prop] = coll[prop].concat(propertyAt(item,prop)); }) return coll; }, {}) } else { collection[key] = collectProperties(groups[key], properties); } } return collection; }
javascript
function collectProperties(groups, properties) { var collection = {}; for (var key in groups) { if (Array.isArray(groups[key])) { collection[key] = groups[key].reduce(function(coll, item) { properties.forEach(function(prop) { if (!coll[prop]) coll[prop] = []; coll[prop] = coll[prop].concat(propertyAt(item,prop)); }) return coll; }, {}) } else { collection[key] = collectProperties(groups[key], properties); } } return collection; }
[ "function", "collectProperties", "(", "groups", ",", "properties", ")", "{", "var", "collection", "=", "{", "}", ";", "for", "(", "var", "key", "in", "groups", ")", "{", "if", "(", "Array", ".", "isArray", "(", "groups", "[", "key", "]", ")", ")", "{", "collection", "[", "key", "]", "=", "groups", "[", "key", "]", ".", "reduce", "(", "function", "(", "coll", ",", "item", ")", "{", "properties", ".", "forEach", "(", "function", "(", "prop", ")", "{", "if", "(", "!", "coll", "[", "prop", "]", ")", "coll", "[", "prop", "]", "=", "[", "]", ";", "coll", "[", "prop", "]", "=", "coll", "[", "prop", "]", ".", "concat", "(", "propertyAt", "(", "item", ",", "prop", ")", ")", ";", "}", ")", "return", "coll", ";", "}", ",", "{", "}", ")", "}", "else", "{", "collection", "[", "key", "]", "=", "collectProperties", "(", "groups", "[", "key", "]", ",", "properties", ")", ";", "}", "}", "return", "collection", ";", "}" ]
collect the properties in an array
[ "collect", "the", "properties", "in", "an", "array" ]
4955b1ccb13320d4732147b2500cb162b69b076c
https://github.com/gagan-bansal/json-groupby/blob/4955b1ccb13320d4732147b2500cb162b69b076c/json-groupby.js#L56-L72
41,011
TooTallNate/file-uri-to-path
index.js
fileUriToPath
function fileUriToPath (uri) { if ('string' != typeof uri || uri.length <= 7 || 'file://' != uri.substring(0, 7)) { throw new TypeError('must pass in a file:// URI to convert to a file path'); } var rest = decodeURI(uri.substring(7)); var firstSlash = rest.indexOf('/'); var host = rest.substring(0, firstSlash); var path = rest.substring(firstSlash + 1); // 2. Scheme Definition // As a special case, <host> can be the string "localhost" or the empty // string; this is interpreted as "the machine from which the URL is // being interpreted". if ('localhost' == host) host = ''; if (host) { host = sep + sep + host; } // 3.2 Drives, drive letters, mount points, file system root // Drive letters are mapped into the top of a file URI in various ways, // depending on the implementation; some applications substitute // vertical bar ("|") for the colon after the drive letter, yielding // "file:///c|/tmp/test.txt". In some cases, the colon is left // unchanged, as in "file:///c:/tmp/test.txt". In other cases, the // colon is simply omitted, as in "file:///c/tmp/test.txt". path = path.replace(/^(.+)\|/, '$1:'); // for Windows, we need to invert the path separators from what a URI uses if (sep == '\\') { path = path.replace(/\//g, '\\'); } if (/^.+\:/.test(path)) { // has Windows drive at beginning of path } else { // unix path… path = sep + path; } return host + path; }
javascript
function fileUriToPath (uri) { if ('string' != typeof uri || uri.length <= 7 || 'file://' != uri.substring(0, 7)) { throw new TypeError('must pass in a file:// URI to convert to a file path'); } var rest = decodeURI(uri.substring(7)); var firstSlash = rest.indexOf('/'); var host = rest.substring(0, firstSlash); var path = rest.substring(firstSlash + 1); // 2. Scheme Definition // As a special case, <host> can be the string "localhost" or the empty // string; this is interpreted as "the machine from which the URL is // being interpreted". if ('localhost' == host) host = ''; if (host) { host = sep + sep + host; } // 3.2 Drives, drive letters, mount points, file system root // Drive letters are mapped into the top of a file URI in various ways, // depending on the implementation; some applications substitute // vertical bar ("|") for the colon after the drive letter, yielding // "file:///c|/tmp/test.txt". In some cases, the colon is left // unchanged, as in "file:///c:/tmp/test.txt". In other cases, the // colon is simply omitted, as in "file:///c/tmp/test.txt". path = path.replace(/^(.+)\|/, '$1:'); // for Windows, we need to invert the path separators from what a URI uses if (sep == '\\') { path = path.replace(/\//g, '\\'); } if (/^.+\:/.test(path)) { // has Windows drive at beginning of path } else { // unix path… path = sep + path; } return host + path; }
[ "function", "fileUriToPath", "(", "uri", ")", "{", "if", "(", "'string'", "!=", "typeof", "uri", "||", "uri", ".", "length", "<=", "7", "||", "'file://'", "!=", "uri", ".", "substring", "(", "0", ",", "7", ")", ")", "{", "throw", "new", "TypeError", "(", "'must pass in a file:// URI to convert to a file path'", ")", ";", "}", "var", "rest", "=", "decodeURI", "(", "uri", ".", "substring", "(", "7", ")", ")", ";", "var", "firstSlash", "=", "rest", ".", "indexOf", "(", "'/'", ")", ";", "var", "host", "=", "rest", ".", "substring", "(", "0", ",", "firstSlash", ")", ";", "var", "path", "=", "rest", ".", "substring", "(", "firstSlash", "+", "1", ")", ";", "// 2. Scheme Definition", "// As a special case, <host> can be the string \"localhost\" or the empty", "// string; this is interpreted as \"the machine from which the URL is", "// being interpreted\".", "if", "(", "'localhost'", "==", "host", ")", "host", "=", "''", ";", "if", "(", "host", ")", "{", "host", "=", "sep", "+", "sep", "+", "host", ";", "}", "// 3.2 Drives, drive letters, mount points, file system root", "// Drive letters are mapped into the top of a file URI in various ways,", "// depending on the implementation; some applications substitute", "// vertical bar (\"|\") for the colon after the drive letter, yielding", "// \"file:///c|/tmp/test.txt\". In some cases, the colon is left", "// unchanged, as in \"file:///c:/tmp/test.txt\". In other cases, the", "// colon is simply omitted, as in \"file:///c/tmp/test.txt\".", "path", "=", "path", ".", "replace", "(", "/", "^(.+)\\|", "/", ",", "'$1:'", ")", ";", "// for Windows, we need to invert the path separators from what a URI uses", "if", "(", "sep", "==", "'\\\\'", ")", "{", "path", "=", "path", ".", "replace", "(", "/", "\\/", "/", "g", ",", "'\\\\'", ")", ";", "}", "if", "(", "/", "^.+\\:", "/", ".", "test", "(", "path", ")", ")", "{", "// has Windows drive at beginning of path", "}", "else", "{", "// unix path…", "path", "=", "sep", "+", "path", ";", "}", "return", "host", "+", "path", ";", "}" ]
File URI to Path function. @param {String} uri @return {String} path @api public
[ "File", "URI", "to", "Path", "function", "." ]
db012b4db2c9da9f6eeb5202b4a493450482e0e4
https://github.com/TooTallNate/file-uri-to-path/blob/db012b4db2c9da9f6eeb5202b4a493450482e0e4/index.js#L22-L66
41,012
stephanebachelier/superapi-cache
dist/hydrate.js
parseHeaders
function parseHeaders() { var str = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; var lines = str.split(/\r?\n/); var fields = {}; var index = undefined; var line = undefined; var field = undefined; var val = undefined; lines.pop(); // trailing CRLF for (var i = 0, len = lines.length; i < len; i += 1) { line = lines[i]; index = line.indexOf(':'); field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val; } return fields; }
javascript
function parseHeaders() { var str = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; var lines = str.split(/\r?\n/); var fields = {}; var index = undefined; var line = undefined; var field = undefined; var val = undefined; lines.pop(); // trailing CRLF for (var i = 0, len = lines.length; i < len; i += 1) { line = lines[i]; index = line.indexOf(':'); field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val; } return fields; }
[ "function", "parseHeaders", "(", ")", "{", "var", "str", "=", "arguments", ".", "length", "<=", "0", "||", "arguments", "[", "0", "]", "===", "undefined", "?", "''", ":", "arguments", "[", "0", "]", ";", "var", "lines", "=", "str", ".", "split", "(", "/", "\\r?\\n", "/", ")", ";", "var", "fields", "=", "{", "}", ";", "var", "index", "=", "undefined", ";", "var", "line", "=", "undefined", ";", "var", "field", "=", "undefined", ";", "var", "val", "=", "undefined", ";", "lines", ".", "pop", "(", ")", ";", "// trailing CRLF", "for", "(", "var", "i", "=", "0", ",", "len", "=", "lines", ".", "length", ";", "i", "<", "len", ";", "i", "+=", "1", ")", "{", "line", "=", "lines", "[", "i", "]", ";", "index", "=", "line", ".", "indexOf", "(", "':'", ")", ";", "field", "=", "line", ".", "slice", "(", "0", ",", "index", ")", ".", "toLowerCase", "(", ")", ";", "val", "=", "trim", "(", "line", ".", "slice", "(", "index", "+", "1", ")", ")", ";", "fields", "[", "field", "]", "=", "val", ";", "}", "return", "fields", ";", "}" ]
borrow from superagent
[ "borrow", "from", "superagent" ]
0d9ff011a52b369d8cf82cea135418a1d021e80c
https://github.com/stephanebachelier/superapi-cache/blob/0d9ff011a52b369d8cf82cea135418a1d021e80c/dist/hydrate.js#L28-L49
41,013
wanchain/wanx
src/btc/utils.js
buildHashTimeLockContract
function buildHashTimeLockContract(network, xHash, destH160Addr, revokerH160Addr, lockTime) { const bitcoinNetwork = bitcoin.networks[network]; const redeemScript = bitcoin.script.compile([ bitcoin.opcodes.OP_IF, bitcoin.opcodes.OP_SHA256, Buffer.from(xHash, 'hex'), bitcoin.opcodes.OP_EQUALVERIFY, bitcoin.opcodes.OP_DUP, bitcoin.opcodes.OP_HASH160, Buffer.from(hex.stripPrefix(destH160Addr), 'hex'), bitcoin.opcodes.OP_ELSE, bitcoin.script.number.encode(lockTime), bitcoin.opcodes.OP_CHECKLOCKTIMEVERIFY, bitcoin.opcodes.OP_DROP, bitcoin.opcodes.OP_DUP, bitcoin.opcodes.OP_HASH160, Buffer.from(hex.stripPrefix(revokerH160Addr), 'hex'), bitcoin.opcodes.OP_ENDIF, bitcoin.opcodes.OP_EQUALVERIFY, bitcoin.opcodes.OP_CHECKSIG, ]); const addressPay = bitcoin.payments.p2sh({ redeem: { output: redeemScript, network: bitcoinNetwork }, network: bitcoinNetwork, }); const { address } = addressPay; return { // contract address, redeemScript: redeemScript.toString('hex'), // params xHash, lockTime, redeemer: hex.ensurePrefix(destH160Addr), revoker: hex.ensurePrefix(revokerH160Addr), }; }
javascript
function buildHashTimeLockContract(network, xHash, destH160Addr, revokerH160Addr, lockTime) { const bitcoinNetwork = bitcoin.networks[network]; const redeemScript = bitcoin.script.compile([ bitcoin.opcodes.OP_IF, bitcoin.opcodes.OP_SHA256, Buffer.from(xHash, 'hex'), bitcoin.opcodes.OP_EQUALVERIFY, bitcoin.opcodes.OP_DUP, bitcoin.opcodes.OP_HASH160, Buffer.from(hex.stripPrefix(destH160Addr), 'hex'), bitcoin.opcodes.OP_ELSE, bitcoin.script.number.encode(lockTime), bitcoin.opcodes.OP_CHECKLOCKTIMEVERIFY, bitcoin.opcodes.OP_DROP, bitcoin.opcodes.OP_DUP, bitcoin.opcodes.OP_HASH160, Buffer.from(hex.stripPrefix(revokerH160Addr), 'hex'), bitcoin.opcodes.OP_ENDIF, bitcoin.opcodes.OP_EQUALVERIFY, bitcoin.opcodes.OP_CHECKSIG, ]); const addressPay = bitcoin.payments.p2sh({ redeem: { output: redeemScript, network: bitcoinNetwork }, network: bitcoinNetwork, }); const { address } = addressPay; return { // contract address, redeemScript: redeemScript.toString('hex'), // params xHash, lockTime, redeemer: hex.ensurePrefix(destH160Addr), revoker: hex.ensurePrefix(revokerH160Addr), }; }
[ "function", "buildHashTimeLockContract", "(", "network", ",", "xHash", ",", "destH160Addr", ",", "revokerH160Addr", ",", "lockTime", ")", "{", "const", "bitcoinNetwork", "=", "bitcoin", ".", "networks", "[", "network", "]", ";", "const", "redeemScript", "=", "bitcoin", ".", "script", ".", "compile", "(", "[", "bitcoin", ".", "opcodes", ".", "OP_IF", ",", "bitcoin", ".", "opcodes", ".", "OP_SHA256", ",", "Buffer", ".", "from", "(", "xHash", ",", "'hex'", ")", ",", "bitcoin", ".", "opcodes", ".", "OP_EQUALVERIFY", ",", "bitcoin", ".", "opcodes", ".", "OP_DUP", ",", "bitcoin", ".", "opcodes", ".", "OP_HASH160", ",", "Buffer", ".", "from", "(", "hex", ".", "stripPrefix", "(", "destH160Addr", ")", ",", "'hex'", ")", ",", "bitcoin", ".", "opcodes", ".", "OP_ELSE", ",", "bitcoin", ".", "script", ".", "number", ".", "encode", "(", "lockTime", ")", ",", "bitcoin", ".", "opcodes", ".", "OP_CHECKLOCKTIMEVERIFY", ",", "bitcoin", ".", "opcodes", ".", "OP_DROP", ",", "bitcoin", ".", "opcodes", ".", "OP_DUP", ",", "bitcoin", ".", "opcodes", ".", "OP_HASH160", ",", "Buffer", ".", "from", "(", "hex", ".", "stripPrefix", "(", "revokerH160Addr", ")", ",", "'hex'", ")", ",", "bitcoin", ".", "opcodes", ".", "OP_ENDIF", ",", "bitcoin", ".", "opcodes", ".", "OP_EQUALVERIFY", ",", "bitcoin", ".", "opcodes", ".", "OP_CHECKSIG", ",", "]", ")", ";", "const", "addressPay", "=", "bitcoin", ".", "payments", ".", "p2sh", "(", "{", "redeem", ":", "{", "output", ":", "redeemScript", ",", "network", ":", "bitcoinNetwork", "}", ",", "network", ":", "bitcoinNetwork", ",", "}", ")", ";", "const", "{", "address", "}", "=", "addressPay", ";", "return", "{", "// contract", "address", ",", "redeemScript", ":", "redeemScript", ".", "toString", "(", "'hex'", ")", ",", "// params", "xHash", ",", "lockTime", ",", "redeemer", ":", "hex", ".", "ensurePrefix", "(", "destH160Addr", ")", ",", "revoker", ":", "hex", ".", "ensurePrefix", "(", "revokerH160Addr", ")", ",", "}", ";", "}" ]
Generate P2SH timelock contract @param {string} network - Network name (mainnet, testnet) @param {string} xHash - The xHash string @param {string} destH160Addr - Hash160 of the receiver's bitcoin address @param {string} revokerH160Addr - Hash160 of the revoker's bitcoin address @param {number} lockTime - The timestamp when the revoker is allowed to spend @returns {Object} Generated P2SH address and redeemScript
[ "Generate", "P2SH", "timelock", "contract" ]
1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875
https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/btc/utils.js#L42-L85
41,014
wanchain/wanx
src/btc/utils.js
hashForRedeemSig
function hashForRedeemSig(network, txid, address, value, redeemScript) { const tx = btcUtil.buildIncompleteRedeem(network, txid, address, value); const sigHash = tx.hashForSignature( 0, new Buffer.from(redeemScript, 'hex'), bitcoin.Transaction.SIGHASH_ALL ); return sigHash.toString('hex'); }
javascript
function hashForRedeemSig(network, txid, address, value, redeemScript) { const tx = btcUtil.buildIncompleteRedeem(network, txid, address, value); const sigHash = tx.hashForSignature( 0, new Buffer.from(redeemScript, 'hex'), bitcoin.Transaction.SIGHASH_ALL ); return sigHash.toString('hex'); }
[ "function", "hashForRedeemSig", "(", "network", ",", "txid", ",", "address", ",", "value", ",", "redeemScript", ")", "{", "const", "tx", "=", "btcUtil", ".", "buildIncompleteRedeem", "(", "network", ",", "txid", ",", "address", ",", "value", ")", ";", "const", "sigHash", "=", "tx", ".", "hashForSignature", "(", "0", ",", "new", "Buffer", ".", "from", "(", "redeemScript", ",", "'hex'", ")", ",", "bitcoin", ".", "Transaction", ".", "SIGHASH_ALL", ")", ";", "return", "sigHash", ".", "toString", "(", "'hex'", ")", ";", "}" ]
Get the hash to be signed for a redeem transaction @param {string} network - Network name (mainnet, testnet) @param {string} txid - The txid for the UTXO being spent @param {string} address - The address to receive funds @param {string|number} value - The amount of funds to be sent (in Satoshis) @param {string} redeemScript - The redeemScript of the P2SH address @returns {string} Hash to be signed
[ "Get", "the", "hash", "to", "be", "signed", "for", "a", "redeem", "transaction" ]
1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875
https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/btc/utils.js#L96-L105
41,015
wanchain/wanx
src/btc/utils.js
hashForRevokeSig
function hashForRevokeSig(network, txid, address, value, lockTime, redeemScript) { const tx = btcUtil.buildIncompleteRevoke(network, txid, address, value, lockTime); const sigHash = tx.hashForSignature( 0, new Buffer.from(redeemScript, 'hex'), bitcoin.Transaction.SIGHASH_ALL ); return sigHash.toString('hex'); }
javascript
function hashForRevokeSig(network, txid, address, value, lockTime, redeemScript) { const tx = btcUtil.buildIncompleteRevoke(network, txid, address, value, lockTime); const sigHash = tx.hashForSignature( 0, new Buffer.from(redeemScript, 'hex'), bitcoin.Transaction.SIGHASH_ALL ); return sigHash.toString('hex'); }
[ "function", "hashForRevokeSig", "(", "network", ",", "txid", ",", "address", ",", "value", ",", "lockTime", ",", "redeemScript", ")", "{", "const", "tx", "=", "btcUtil", ".", "buildIncompleteRevoke", "(", "network", ",", "txid", ",", "address", ",", "value", ",", "lockTime", ")", ";", "const", "sigHash", "=", "tx", ".", "hashForSignature", "(", "0", ",", "new", "Buffer", ".", "from", "(", "redeemScript", ",", "'hex'", ")", ",", "bitcoin", ".", "Transaction", ".", "SIGHASH_ALL", ")", ";", "return", "sigHash", ".", "toString", "(", "'hex'", ")", ";", "}" ]
Get the hash to be signed for a revoke transaction @param {string} network - Network name (mainnet, testnet) @param {string} txid - The txid for the UTXO being spent @param {string} address - The address to receive funds @param {string|number} value - The amount of funds to be sent (in Satoshis) @param {number} lockTime - The lockTime of the P2SH address @param {string} redeemScript - The redeemScript of the P2SH address @returns {string} Hash to be signed
[ "Get", "the", "hash", "to", "be", "signed", "for", "a", "revoke", "transaction" ]
1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875
https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/btc/utils.js#L117-L126
41,016
wanchain/wanx
src/btc/utils.js
buildIncompleteRedeem
function buildIncompleteRedeem(network, txid, address, value) { const bitcoinNetwork = bitcoin.networks[network]; // NB: storemen address validation requires that vout is 0 const vout = 0; const txb = new bitcoin.TransactionBuilder(bitcoinNetwork); txb.setVersion(1); txb.addInput(hex.stripPrefix(txid), vout); txb.addOutput(address, parseInt(value)); return txb.buildIncomplete(); }
javascript
function buildIncompleteRedeem(network, txid, address, value) { const bitcoinNetwork = bitcoin.networks[network]; // NB: storemen address validation requires that vout is 0 const vout = 0; const txb = new bitcoin.TransactionBuilder(bitcoinNetwork); txb.setVersion(1); txb.addInput(hex.stripPrefix(txid), vout); txb.addOutput(address, parseInt(value)); return txb.buildIncomplete(); }
[ "function", "buildIncompleteRedeem", "(", "network", ",", "txid", ",", "address", ",", "value", ")", "{", "const", "bitcoinNetwork", "=", "bitcoin", ".", "networks", "[", "network", "]", ";", "// NB: storemen address validation requires that vout is 0", "const", "vout", "=", "0", ";", "const", "txb", "=", "new", "bitcoin", ".", "TransactionBuilder", "(", "bitcoinNetwork", ")", ";", "txb", ".", "setVersion", "(", "1", ")", ";", "txb", ".", "addInput", "(", "hex", ".", "stripPrefix", "(", "txid", ")", ",", "vout", ")", ";", "txb", ".", "addOutput", "(", "address", ",", "parseInt", "(", "value", ")", ")", ";", "return", "txb", ".", "buildIncomplete", "(", ")", ";", "}" ]
Build incomplete redeem transaction @param {string} network - Network name (mainnet, testnet) @param {string} txid - The txid for the UTXO being spent @param {string} address - The address to receive funds @param {string|number} value - The amount of funds to be sent (in Satoshis) @returns {Object} Incomplete redeem transaction
[ "Build", "incomplete", "redeem", "transaction" ]
1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875
https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/btc/utils.js#L136-L149
41,017
wanchain/wanx
src/btc/utils.js
buildRedeemTx
function buildRedeemTx(network, txid, value, redeemScript, x, publicKey, signedSigHash, toAddress) { const bitcoinNetwork = bitcoin.networks[network]; // if toAddress is not supplied, derive it from the publicKey if (! toAddress) { const { address } = bitcoin.payments.p2pkh({ network: bitcoinNetwork, pubkey: Buffer.from(publicKey, 'hex'), }); toAddress = address; } const tx = btcUtil.buildIncompleteRedeem(network, txid, toAddress, value); const signature = bitcoin.script.signature.encode( new Buffer.from(signedSigHash, 'base64'), bitcoin.Transaction.SIGHASH_ALL ); const scriptSig = bitcoin.payments.p2sh({ redeem: { input: bitcoin.script.compile([ signature, Buffer.from(publicKey, 'hex'), Buffer.from(x, 'hex'), bitcoin.opcodes.OP_TRUE, ]), output: new Buffer.from(redeemScript, 'hex'), }, network: bitcoinNetwork, }).input; tx.setInputScript(0, scriptSig); return tx.toHex(); }
javascript
function buildRedeemTx(network, txid, value, redeemScript, x, publicKey, signedSigHash, toAddress) { const bitcoinNetwork = bitcoin.networks[network]; // if toAddress is not supplied, derive it from the publicKey if (! toAddress) { const { address } = bitcoin.payments.p2pkh({ network: bitcoinNetwork, pubkey: Buffer.from(publicKey, 'hex'), }); toAddress = address; } const tx = btcUtil.buildIncompleteRedeem(network, txid, toAddress, value); const signature = bitcoin.script.signature.encode( new Buffer.from(signedSigHash, 'base64'), bitcoin.Transaction.SIGHASH_ALL ); const scriptSig = bitcoin.payments.p2sh({ redeem: { input: bitcoin.script.compile([ signature, Buffer.from(publicKey, 'hex'), Buffer.from(x, 'hex'), bitcoin.opcodes.OP_TRUE, ]), output: new Buffer.from(redeemScript, 'hex'), }, network: bitcoinNetwork, }).input; tx.setInputScript(0, scriptSig); return tx.toHex(); }
[ "function", "buildRedeemTx", "(", "network", ",", "txid", ",", "value", ",", "redeemScript", ",", "x", ",", "publicKey", ",", "signedSigHash", ",", "toAddress", ")", "{", "const", "bitcoinNetwork", "=", "bitcoin", ".", "networks", "[", "network", "]", ";", "// if toAddress is not supplied, derive it from the publicKey", "if", "(", "!", "toAddress", ")", "{", "const", "{", "address", "}", "=", "bitcoin", ".", "payments", ".", "p2pkh", "(", "{", "network", ":", "bitcoinNetwork", ",", "pubkey", ":", "Buffer", ".", "from", "(", "publicKey", ",", "'hex'", ")", ",", "}", ")", ";", "toAddress", "=", "address", ";", "}", "const", "tx", "=", "btcUtil", ".", "buildIncompleteRedeem", "(", "network", ",", "txid", ",", "toAddress", ",", "value", ")", ";", "const", "signature", "=", "bitcoin", ".", "script", ".", "signature", ".", "encode", "(", "new", "Buffer", ".", "from", "(", "signedSigHash", ",", "'base64'", ")", ",", "bitcoin", ".", "Transaction", ".", "SIGHASH_ALL", ")", ";", "const", "scriptSig", "=", "bitcoin", ".", "payments", ".", "p2sh", "(", "{", "redeem", ":", "{", "input", ":", "bitcoin", ".", "script", ".", "compile", "(", "[", "signature", ",", "Buffer", ".", "from", "(", "publicKey", ",", "'hex'", ")", ",", "Buffer", ".", "from", "(", "x", ",", "'hex'", ")", ",", "bitcoin", ".", "opcodes", ".", "OP_TRUE", ",", "]", ")", ",", "output", ":", "new", "Buffer", ".", "from", "(", "redeemScript", ",", "'hex'", ")", ",", "}", ",", "network", ":", "bitcoinNetwork", ",", "}", ")", ".", "input", ";", "tx", ".", "setInputScript", "(", "0", ",", "scriptSig", ")", ";", "return", "tx", ".", "toHex", "(", ")", ";", "}" ]
Create redeem transaction using signed sigHash @param {string} network - Network name (mainnet, testnet) @param {string} txid - The txid for the UTXO being spent @param {string|number} value - The amount of funds to be sent (in Satoshis) @param {string} redeemScript - The redeemScript of the P2SH address @param {string} x - The x value for the transaction @param {string} publicKey - The publicKey of the redeemer @param {string} signedSigHash - The sigHash signed by the redeemer @param {string} toAddress - The address where to send funds (defaults to redeemer) @returns {string} Signed transaction as hex string
[ "Create", "redeem", "transaction", "using", "signed", "sigHash" ]
1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875
https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/btc/utils.js#L188-L225
41,018
aantthony/javascript-cas
examples/solver.js
solveLinearIntersect
function solveLinearIntersect(a,b, c, d,e, f) { // ax + by = c; // dx + ey = d; console.log('WORKED: ', arguments); if(a === 0) { var y = c/b; var x = (d-e*y)/x; return [x, y]; } var denom = e-d/a * b; if(denom === 0) { // Either infinite solutions or no solutions return [undefined, undefined]; } var y = (f-d*c/a)/denom; var x = (c-b*y) / a; return [x, y]; }
javascript
function solveLinearIntersect(a,b, c, d,e, f) { // ax + by = c; // dx + ey = d; console.log('WORKED: ', arguments); if(a === 0) { var y = c/b; var x = (d-e*y)/x; return [x, y]; } var denom = e-d/a * b; if(denom === 0) { // Either infinite solutions or no solutions return [undefined, undefined]; } var y = (f-d*c/a)/denom; var x = (c-b*y) / a; return [x, y]; }
[ "function", "solveLinearIntersect", "(", "a", ",", "b", ",", "c", ",", "d", ",", "e", ",", "f", ")", "{", "// ax + by = c;", "// dx + ey = d;", "console", ".", "log", "(", "'WORKED: '", ",", "arguments", ")", ";", "if", "(", "a", "===", "0", ")", "{", "var", "y", "=", "c", "/", "b", ";", "var", "x", "=", "(", "d", "-", "e", "*", "y", ")", "/", "x", ";", "return", "[", "x", ",", "y", "]", ";", "}", "var", "denom", "=", "e", "-", "d", "/", "a", "*", "b", ";", "if", "(", "denom", "===", "0", ")", "{", "// Either infinite solutions or no solutions", "return", "[", "undefined", ",", "undefined", "]", ";", "}", "var", "y", "=", "(", "f", "-", "d", "*", "c", "/", "a", ")", "/", "denom", ";", "var", "x", "=", "(", "c", "-", "b", "*", "y", ")", "/", "a", ";", "return", "[", "x", ",", "y", "]", ";", "}" ]
Does not work!!!, but a general idea of how it would once bugs are fixed.
[ "Does", "not", "work!!!", "but", "a", "general", "idea", "of", "how", "it", "would", "once", "bugs", "are", "fixed", "." ]
d13ca4eb1a8aee3b712a8d48e06280b87bf96ed3
https://github.com/aantthony/javascript-cas/blob/d13ca4eb1a8aee3b712a8d48e06280b87bf96ed3/examples/solver.js#L3-L20
41,019
wanchain/wanx
src/lib/hex.js
fromString
function fromString(str) { const bytes = []; for (let n = 0, l = str.length; n < l; n++) { const hex = Number(str.charCodeAt(n)).toString(16); bytes.push(hex); } return '0x' + bytes.join(''); }
javascript
function fromString(str) { const bytes = []; for (let n = 0, l = str.length; n < l; n++) { const hex = Number(str.charCodeAt(n)).toString(16); bytes.push(hex); } return '0x' + bytes.join(''); }
[ "function", "fromString", "(", "str", ")", "{", "const", "bytes", "=", "[", "]", ";", "for", "(", "let", "n", "=", "0", ",", "l", "=", "str", ".", "length", ";", "n", "<", "l", ";", "n", "++", ")", "{", "const", "hex", "=", "Number", "(", "str", ".", "charCodeAt", "(", "n", ")", ")", ".", "toString", "(", "16", ")", ";", "bytes", ".", "push", "(", "hex", ")", ";", "}", "return", "'0x'", "+", "bytes", ".", "join", "(", "''", ")", ";", "}" ]
Convert ascii `String` to hex @param {String} str @return {String}
[ "Convert", "ascii", "String", "to", "hex" ]
1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875
https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/lib/hex.js#L62-L71
41,020
siffogh/eslint-plugin-better-styled-components
lib/rules/sort-declarations-alphabetically.js
isValidAtomicRule
function isValidAtomicRule(rule) { const decls = rule.nodes.filter(node => node.type === "decl"); if (decls.length < 0) { return { isValid: true }; } for (let i = 1; i < decls.length; i++) { const current = decls[i].prop; const prev = decls[i - 1].prop; if (current < prev) { const loc = { start: { line: decls[i - 1].source.start.line, column: decls[i - 1].source.start.column - 1 }, end: { line: decls[i].source.end.line, column: decls[i].source.end.column - 1 } }; return { isValid: false, loc }; } } return { isValid: true }; }
javascript
function isValidAtomicRule(rule) { const decls = rule.nodes.filter(node => node.type === "decl"); if (decls.length < 0) { return { isValid: true }; } for (let i = 1; i < decls.length; i++) { const current = decls[i].prop; const prev = decls[i - 1].prop; if (current < prev) { const loc = { start: { line: decls[i - 1].source.start.line, column: decls[i - 1].source.start.column - 1 }, end: { line: decls[i].source.end.line, column: decls[i].source.end.column - 1 } }; return { isValid: false, loc }; } } return { isValid: true }; }
[ "function", "isValidAtomicRule", "(", "rule", ")", "{", "const", "decls", "=", "rule", ".", "nodes", ".", "filter", "(", "node", "=>", "node", ".", "type", "===", "\"decl\"", ")", ";", "if", "(", "decls", ".", "length", "<", "0", ")", "{", "return", "{", "isValid", ":", "true", "}", ";", "}", "for", "(", "let", "i", "=", "1", ";", "i", "<", "decls", ".", "length", ";", "i", "++", ")", "{", "const", "current", "=", "decls", "[", "i", "]", ".", "prop", ";", "const", "prev", "=", "decls", "[", "i", "-", "1", "]", ".", "prop", ";", "if", "(", "current", "<", "prev", ")", "{", "const", "loc", "=", "{", "start", ":", "{", "line", ":", "decls", "[", "i", "-", "1", "]", ".", "source", ".", "start", ".", "line", ",", "column", ":", "decls", "[", "i", "-", "1", "]", ".", "source", ".", "start", ".", "column", "-", "1", "}", ",", "end", ":", "{", "line", ":", "decls", "[", "i", "]", ".", "source", ".", "end", ".", "line", ",", "column", ":", "decls", "[", "i", "]", ".", "source", ".", "end", ".", "column", "-", "1", "}", "}", ";", "return", "{", "isValid", ":", "false", ",", "loc", "}", ";", "}", "}", "return", "{", "isValid", ":", "true", "}", ";", "}" ]
An atomic rule is a rule without nested rules.
[ "An", "atomic", "rule", "is", "a", "rule", "without", "nested", "rules", "." ]
0728200fa2f0a58af5fac6c94538bda292ab1d2a
https://github.com/siffogh/eslint-plugin-better-styled-components/blob/0728200fa2f0a58af5fac6c94538bda292ab1d2a/lib/rules/sort-declarations-alphabetically.js#L14-L40
41,021
frozzare/json-to-html
index.js
html
function html(obj, indents) { indents = indents || 1; function indent() { return Array(indents).join(' '); } if ('string' == typeof obj) { var str = escape(obj); if (urlRegex().test(obj)) { str = '<a href="' + str + '">' + str + '</a>'; } return span('string value', '"' + str + '"'); } if ('number' == typeof obj) { return span('number', obj); } if ('boolean' == typeof obj) { return span('boolean', obj); } if (null === obj) { return span('null', 'null'); } var buf; if (Array.isArray(obj)) { ++indents; buf = '[\n' + obj.map(function(val){ return indent() + html(val, indents); }).join(',\n'); --indents; buf += '\n' + indent() + ']'; return buf; } buf = '{'; var keys = Object.keys(obj); var len = keys.length; if (len) buf += '\n'; ++indents; buf += keys.map(function(key){ var val = obj[key]; key = '"' + key + '"'; key = span('string key', key); return indent() + key + ': ' + html(val, indents); }).join(',\n'); --indents; if (len) buf += '\n' + indent(); buf += '}'; return buf; }
javascript
function html(obj, indents) { indents = indents || 1; function indent() { return Array(indents).join(' '); } if ('string' == typeof obj) { var str = escape(obj); if (urlRegex().test(obj)) { str = '<a href="' + str + '">' + str + '</a>'; } return span('string value', '"' + str + '"'); } if ('number' == typeof obj) { return span('number', obj); } if ('boolean' == typeof obj) { return span('boolean', obj); } if (null === obj) { return span('null', 'null'); } var buf; if (Array.isArray(obj)) { ++indents; buf = '[\n' + obj.map(function(val){ return indent() + html(val, indents); }).join(',\n'); --indents; buf += '\n' + indent() + ']'; return buf; } buf = '{'; var keys = Object.keys(obj); var len = keys.length; if (len) buf += '\n'; ++indents; buf += keys.map(function(key){ var val = obj[key]; key = '"' + key + '"'; key = span('string key', key); return indent() + key + ': ' + html(val, indents); }).join(',\n'); --indents; if (len) buf += '\n' + indent(); buf += '}'; return buf; }
[ "function", "html", "(", "obj", ",", "indents", ")", "{", "indents", "=", "indents", "||", "1", ";", "function", "indent", "(", ")", "{", "return", "Array", "(", "indents", ")", ".", "join", "(", "' '", ")", ";", "}", "if", "(", "'string'", "==", "typeof", "obj", ")", "{", "var", "str", "=", "escape", "(", "obj", ")", ";", "if", "(", "urlRegex", "(", ")", ".", "test", "(", "obj", ")", ")", "{", "str", "=", "'<a href=\"'", "+", "str", "+", "'\">'", "+", "str", "+", "'</a>'", ";", "}", "return", "span", "(", "'string value'", ",", "'\"'", "+", "str", "+", "'\"'", ")", ";", "}", "if", "(", "'number'", "==", "typeof", "obj", ")", "{", "return", "span", "(", "'number'", ",", "obj", ")", ";", "}", "if", "(", "'boolean'", "==", "typeof", "obj", ")", "{", "return", "span", "(", "'boolean'", ",", "obj", ")", ";", "}", "if", "(", "null", "===", "obj", ")", "{", "return", "span", "(", "'null'", ",", "'null'", ")", ";", "}", "var", "buf", ";", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "++", "indents", ";", "buf", "=", "'[\\n'", "+", "obj", ".", "map", "(", "function", "(", "val", ")", "{", "return", "indent", "(", ")", "+", "html", "(", "val", ",", "indents", ")", ";", "}", ")", ".", "join", "(", "',\\n'", ")", ";", "--", "indents", ";", "buf", "+=", "'\\n'", "+", "indent", "(", ")", "+", "']'", ";", "return", "buf", ";", "}", "buf", "=", "'{'", ";", "var", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ";", "var", "len", "=", "keys", ".", "length", ";", "if", "(", "len", ")", "buf", "+=", "'\\n'", ";", "++", "indents", ";", "buf", "+=", "keys", ".", "map", "(", "function", "(", "key", ")", "{", "var", "val", "=", "obj", "[", "key", "]", ";", "key", "=", "'\"'", "+", "key", "+", "'\"'", ";", "key", "=", "span", "(", "'string key'", ",", "key", ")", ";", "return", "indent", "(", ")", "+", "key", "+", "': '", "+", "html", "(", "val", ",", "indents", ")", ";", "}", ")", ".", "join", "(", "',\\n'", ")", ";", "--", "indents", ";", "if", "(", "len", ")", "buf", "+=", "'\\n'", "+", "indent", "(", ")", ";", "buf", "+=", "'}'", ";", "return", "buf", ";", "}" ]
Convert JSON Object to html. @param {Object} obj @return {String} @api public
[ "Convert", "JSON", "Object", "to", "html", "." ]
07c45bf5e686855fd7ccab0c99d58effef3e744c
https://github.com/frozzare/json-to-html/blob/07c45bf5e686855fd7ccab0c99d58effef3e744c/index.js#L47-L106
41,022
thauburger/js-heap
heap.js
function(sort) { this._array = []; this._sort = sort; Object.defineProperty(this, 'length', { enumerable: true, get: function() { return this._array.length }, }); if (typeof this._sort !== 'function') { this._sort = function(a, b) { return a - b; } } }
javascript
function(sort) { this._array = []; this._sort = sort; Object.defineProperty(this, 'length', { enumerable: true, get: function() { return this._array.length }, }); if (typeof this._sort !== 'function') { this._sort = function(a, b) { return a - b; } } }
[ "function", "(", "sort", ")", "{", "this", ".", "_array", "=", "[", "]", ";", "this", ".", "_sort", "=", "sort", ";", "Object", ".", "defineProperty", "(", "this", ",", "'length'", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "this", ".", "_array", ".", "length", "}", ",", "}", ")", ";", "if", "(", "typeof", "this", ".", "_sort", "!==", "'function'", ")", "{", "this", ".", "_sort", "=", "function", "(", "a", ",", "b", ")", "{", "return", "a", "-", "b", ";", "}", "}", "}" ]
heap.js JS heap implementation
[ "heap", ".", "js", "JS", "heap", "implementation" ]
019d4b6ad4aa8a424760d17405d99a1fc5bca84d
https://github.com/thauburger/js-heap/blob/019d4b6ad4aa8a424760d17405d99a1fc5bca84d/heap.js#L6-L20
41,023
ozum/auto-generate
lib/auto-generate.js
autoStartLine
function autoStartLine(name) { var pre = new Array(Math.floor((60 - name.length) / 2) - 3).join('-'); var post = new Array(60 - pre.length - name.length).join('-'); return signature + 'S' + pre + ' Auto Start: ' + name + ' ' + post + '\n'; }
javascript
function autoStartLine(name) { var pre = new Array(Math.floor((60 - name.length) / 2) - 3).join('-'); var post = new Array(60 - pre.length - name.length).join('-'); return signature + 'S' + pre + ' Auto Start: ' + name + ' ' + post + '\n'; }
[ "function", "autoStartLine", "(", "name", ")", "{", "var", "pre", "=", "new", "Array", "(", "Math", ".", "floor", "(", "(", "60", "-", "name", ".", "length", ")", "/", "2", ")", "-", "3", ")", ".", "join", "(", "'-'", ")", ";", "var", "post", "=", "new", "Array", "(", "60", "-", "pre", ".", "length", "-", "name", ".", "length", ")", ".", "join", "(", "'-'", ")", ";", "return", "signature", "+", "'S'", "+", "pre", "+", "' Auto Start: '", "+", "name", "+", "' '", "+", "post", "+", "'\\n'", ";", "}" ]
Object which contains detailed info of an auto generated part. @private @typedef {Object} partInfo @property {string} startLine - Start line (opening tag / marker) of auto generated part. @property {string} warningLine - Warning message line of auto generated part. @property {string} content - Auto generated content. @property {string} md5Line - Line which contains md5 of the content. @property {string} oldDigest - MD5 which is written in the file. @property {string} newDigest - MD5 calculated freshly for the content. @property {boolean} isChanged - Indicates if part is modified by comparing MD5 written in file with new calculated MD5 @property {string} endLine - End line (closing tag / marker) of auto generated part. Generates and returns start line (opening tag / marker) of auto generated part. @private @param {string} name - name of the auto generated part @returns {string} - first line of the auto generated part.
[ "Object", "which", "contains", "detailed", "info", "of", "an", "auto", "generated", "part", "." ]
5b8574514d5095d647545e93e6042cd585f90d48
https://github.com/ozum/auto-generate/blob/5b8574514d5095d647545e93e6042cd585f90d48/lib/auto-generate.js#L105-L109
41,024
ozum/auto-generate
lib/auto-generate.js
makeBackup
function makeBackup(filePath) { var dateString = new Date().toISOString().replace(/:/g, '.').replace('Z', '').replace('T', ' '); try { fs.mkdirSync(path.join(path.dirname(filePath), 'BACKUP')); } catch(err) { if (err.code != 'EEXIST') { throw err } } fs.writeFileSync(path.join(path.dirname(filePath), 'BACKUP', dateString + ' ' + path.basename(filePath) ), fs.readFileSync(path.normalize(filePath))); }
javascript
function makeBackup(filePath) { var dateString = new Date().toISOString().replace(/:/g, '.').replace('Z', '').replace('T', ' '); try { fs.mkdirSync(path.join(path.dirname(filePath), 'BACKUP')); } catch(err) { if (err.code != 'EEXIST') { throw err } } fs.writeFileSync(path.join(path.dirname(filePath), 'BACKUP', dateString + ' ' + path.basename(filePath) ), fs.readFileSync(path.normalize(filePath))); }
[ "function", "makeBackup", "(", "filePath", ")", "{", "var", "dateString", "=", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ".", "replace", "(", "/", ":", "/", "g", ",", "'.'", ")", ".", "replace", "(", "'Z'", ",", "''", ")", ".", "replace", "(", "'T'", ",", "' '", ")", ";", "try", "{", "fs", ".", "mkdirSync", "(", "path", ".", "join", "(", "path", ".", "dirname", "(", "filePath", ")", ",", "'BACKUP'", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "if", "(", "err", ".", "code", "!=", "'EEXIST'", ")", "{", "throw", "err", "}", "}", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "path", ".", "dirname", "(", "filePath", ")", ",", "'BACKUP'", ",", "dateString", "+", "' '", "+", "path", ".", "basename", "(", "filePath", ")", ")", ",", "fs", ".", "readFileSync", "(", "path", ".", "normalize", "(", "filePath", ")", ")", ")", ";", "}" ]
Creates backup of a file. To do this, it creates a directory called BACKUP in the same directory where original file is located in. Backup file name has a suffix of ISO style date and time. ie. 'model.js' becomes '2014-01-12 22.02.23.345 model.js' @private @param {string} filePath - Absolute path of file
[ "Creates", "backup", "of", "a", "file", ".", "To", "do", "this", "it", "creates", "a", "directory", "called", "BACKUP", "in", "the", "same", "directory", "where", "original", "file", "is", "located", "in", ".", "Backup", "file", "name", "has", "a", "suffix", "of", "ISO", "style", "date", "and", "time", ".", "ie", ".", "model", ".", "js", "becomes", "2014", "-", "01", "-", "12", "22", ".", "02", ".", "23", ".", "345", "model", ".", "js" ]
5b8574514d5095d647545e93e6042cd585f90d48
https://github.com/ozum/auto-generate/blob/5b8574514d5095d647545e93e6042cd585f90d48/lib/auto-generate.js#L130-L135
41,025
ozum/auto-generate
lib/auto-generate.js
getPart
function getPart(name, fileContent, options) { if (!name || !options) { throw new Error('name and options are required.'); } var parts = fileContent.match(getRegularExpression(name)); if ( parts ) { // Aranan bölüm varsa var fileContentDigest = calculateMD5(parts[3], options); return { all : parts[0], startLine : parts[1], warningLine : parts[2], content : parts[3], md5Line : parts[4], oldDigest : parts[5], newDigest : fileContentDigest, isChanged : fileContentDigest != parts[5], endLine : parts[6] } } else { return null; } }
javascript
function getPart(name, fileContent, options) { if (!name || !options) { throw new Error('name and options are required.'); } var parts = fileContent.match(getRegularExpression(name)); if ( parts ) { // Aranan bölüm varsa var fileContentDigest = calculateMD5(parts[3], options); return { all : parts[0], startLine : parts[1], warningLine : parts[2], content : parts[3], md5Line : parts[4], oldDigest : parts[5], newDigest : fileContentDigest, isChanged : fileContentDigest != parts[5], endLine : parts[6] } } else { return null; } }
[ "function", "getPart", "(", "name", ",", "fileContent", ",", "options", ")", "{", "if", "(", "!", "name", "||", "!", "options", ")", "{", "throw", "new", "Error", "(", "'name and options are required.'", ")", ";", "}", "var", "parts", "=", "fileContent", ".", "match", "(", "getRegularExpression", "(", "name", ")", ")", ";", "if", "(", "parts", ")", "{", "// Aranan bölüm varsa", "var", "fileContentDigest", "=", "calculateMD5", "(", "parts", "[", "3", "]", ",", "options", ")", ";", "return", "{", "all", ":", "parts", "[", "0", "]", ",", "startLine", ":", "parts", "[", "1", "]", ",", "warningLine", ":", "parts", "[", "2", "]", ",", "content", ":", "parts", "[", "3", "]", ",", "md5Line", ":", "parts", "[", "4", "]", ",", "oldDigest", ":", "parts", "[", "5", "]", ",", "newDigest", ":", "fileContentDigest", ",", "isChanged", ":", "fileContentDigest", "!=", "parts", "[", "5", "]", ",", "endLine", ":", "parts", "[", "6", "]", "}", "}", "else", "{", "return", "null", ";", "}", "}" ]
Finds auto generated part and returns an object which contains information about auto generated part. If auto part with requested name cannot be found, it returns null. @private @param name - Name of the auto generated part. @param fileContent - content of the file which part is searched in. @param {genOptions} options - Options how part is generated. @returns {partInfo|null} - Object which contains info about auto generated part.
[ "Finds", "auto", "generated", "part", "and", "returns", "an", "object", "which", "contains", "information", "about", "auto", "generated", "part", ".", "If", "auto", "part", "with", "requested", "name", "cannot", "be", "found", "it", "returns", "null", "." ]
5b8574514d5095d647545e93e6042cd585f90d48
https://github.com/ozum/auto-generate/blob/5b8574514d5095d647545e93e6042cd585f90d48/lib/auto-generate.js#L180-L202
41,026
ozum/auto-generate
lib/auto-generate.js
fileExists
function fileExists(file) { try { var targetStat = fs.statSync(file); if (targetStat.isDirectory() ) { throw new Error("File exists but it's a driectory: " + file); } } catch(err) { if (err.code == 'ENOENT') { // No such file or directory return false; } else { throw err; } } return true; }
javascript
function fileExists(file) { try { var targetStat = fs.statSync(file); if (targetStat.isDirectory() ) { throw new Error("File exists but it's a driectory: " + file); } } catch(err) { if (err.code == 'ENOENT') { // No such file or directory return false; } else { throw err; } } return true; }
[ "function", "fileExists", "(", "file", ")", "{", "try", "{", "var", "targetStat", "=", "fs", ".", "statSync", "(", "file", ")", ";", "if", "(", "targetStat", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "Error", "(", "\"File exists but it's a driectory: \"", "+", "file", ")", ";", "}", "}", "catch", "(", "err", ")", "{", "if", "(", "err", ".", "code", "==", "'ENOENT'", ")", "{", "// No such file or directory", "return", "false", ";", "}", "else", "{", "throw", "err", ";", "}", "}", "return", "true", ";", "}" ]
Checks if the file exists at the given path. Returns true if it exists, false otherwise. @private @param {string} file - Path of the file to check @returns {boolean}
[ "Checks", "if", "the", "file", "exists", "at", "the", "given", "path", ".", "Returns", "true", "if", "it", "exists", "false", "otherwise", "." ]
5b8574514d5095d647545e93e6042cd585f90d48
https://github.com/ozum/auto-generate/blob/5b8574514d5095d647545e93e6042cd585f90d48/lib/auto-generate.js#L210-L226
41,027
goto-bus-stop/browser-pack-flat
example/out/flat.js
walk
function walk (newNode, oldNode) { // if (DEBUG) { // console.log( // 'walk\nold\n %s\nnew\n %s', // oldNode && oldNode.outerHTML, // newNode && newNode.outerHTML // ) // } if (!oldNode) { return newNode } else if (!newNode) { return null } else if (newNode.isSameNode && newNode.isSameNode(oldNode)) { return oldNode } else if (newNode.tagName !== oldNode.tagName) { return newNode } else { _$morph_11(newNode, oldNode) updateChildren(newNode, oldNode) return oldNode } }
javascript
function walk (newNode, oldNode) { // if (DEBUG) { // console.log( // 'walk\nold\n %s\nnew\n %s', // oldNode && oldNode.outerHTML, // newNode && newNode.outerHTML // ) // } if (!oldNode) { return newNode } else if (!newNode) { return null } else if (newNode.isSameNode && newNode.isSameNode(oldNode)) { return oldNode } else if (newNode.tagName !== oldNode.tagName) { return newNode } else { _$morph_11(newNode, oldNode) updateChildren(newNode, oldNode) return oldNode } }
[ "function", "walk", "(", "newNode", ",", "oldNode", ")", "{", "// if (DEBUG) {", "// console.log(", "// 'walk\\nold\\n %s\\nnew\\n %s',", "// oldNode && oldNode.outerHTML,", "// newNode && newNode.outerHTML", "// )", "// }", "if", "(", "!", "oldNode", ")", "{", "return", "newNode", "}", "else", "if", "(", "!", "newNode", ")", "{", "return", "null", "}", "else", "if", "(", "newNode", ".", "isSameNode", "&&", "newNode", ".", "isSameNode", "(", "oldNode", ")", ")", "{", "return", "oldNode", "}", "else", "if", "(", "newNode", ".", "tagName", "!==", "oldNode", ".", "tagName", ")", "{", "return", "newNode", "}", "else", "{", "_$morph_11", "(", "newNode", ",", "oldNode", ")", "updateChildren", "(", "newNode", ",", "oldNode", ")", "return", "oldNode", "}", "}" ]
Walk and morph a dom tree
[ "Walk", "and", "morph", "a", "dom", "tree" ]
c12e407a027a0a07c6d750781125317d6a166327
https://github.com/goto-bus-stop/browser-pack-flat/blob/c12e407a027a0a07c6d750781125317d6a166327/example/out/flat.js#L270-L291
41,028
byteclubfr/js-hal
hal.js
Link
function Link (rel, value) { if (!(this instanceof Link)) { return new Link(rel, value); } if (!rel) throw new Error('Required <link> attribute "rel"'); this.rel = rel; if (typeof value === 'object') { // If value is a hashmap, just copy properties if (!value.href) throw new Error('Required <link> attribute "href"'); var expectedAttributes = ['rel', 'href', 'name', 'hreflang', 'title', 'templated', 'icon', 'align', 'method']; for (var attr in value) { if (value.hasOwnProperty(attr)) { if (!~expectedAttributes.indexOf(attr)) { // Unexpected attribute: ignore it continue; } this[attr] = value[attr]; } } } else { // value is a scalar: use its value as href if (!value) throw new Error('Required <link> attribute "href"'); this.href = String(value); } }
javascript
function Link (rel, value) { if (!(this instanceof Link)) { return new Link(rel, value); } if (!rel) throw new Error('Required <link> attribute "rel"'); this.rel = rel; if (typeof value === 'object') { // If value is a hashmap, just copy properties if (!value.href) throw new Error('Required <link> attribute "href"'); var expectedAttributes = ['rel', 'href', 'name', 'hreflang', 'title', 'templated', 'icon', 'align', 'method']; for (var attr in value) { if (value.hasOwnProperty(attr)) { if (!~expectedAttributes.indexOf(attr)) { // Unexpected attribute: ignore it continue; } this[attr] = value[attr]; } } } else { // value is a scalar: use its value as href if (!value) throw new Error('Required <link> attribute "href"'); this.href = String(value); } }
[ "function", "Link", "(", "rel", ",", "value", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Link", ")", ")", "{", "return", "new", "Link", "(", "rel", ",", "value", ")", ";", "}", "if", "(", "!", "rel", ")", "throw", "new", "Error", "(", "'Required <link> attribute \"rel\"'", ")", ";", "this", ".", "rel", "=", "rel", ";", "if", "(", "typeof", "value", "===", "'object'", ")", "{", "// If value is a hashmap, just copy properties", "if", "(", "!", "value", ".", "href", ")", "throw", "new", "Error", "(", "'Required <link> attribute \"href\"'", ")", ";", "var", "expectedAttributes", "=", "[", "'rel'", ",", "'href'", ",", "'name'", ",", "'hreflang'", ",", "'title'", ",", "'templated'", ",", "'icon'", ",", "'align'", ",", "'method'", "]", ";", "for", "(", "var", "attr", "in", "value", ")", "{", "if", "(", "value", ".", "hasOwnProperty", "(", "attr", ")", ")", "{", "if", "(", "!", "~", "expectedAttributes", ".", "indexOf", "(", "attr", ")", ")", "{", "// Unexpected attribute: ignore it", "continue", ";", "}", "this", "[", "attr", "]", "=", "value", "[", "attr", "]", ";", "}", "}", "}", "else", "{", "// value is a scalar: use its value as href", "if", "(", "!", "value", ")", "throw", "new", "Error", "(", "'Required <link> attribute \"href\"'", ")", ";", "this", ".", "href", "=", "String", "(", "value", ")", ";", "}", "}" ]
Link to another hypermedia @param String rel → the relation identifier @param String|Object value → the href, or the hash of all attributes (including href)
[ "Link", "to", "another", "hypermedia" ]
16c1e6d15093b7eee28f874b56081a58ed7f4f03
https://github.com/byteclubfr/js-hal/blob/16c1e6d15093b7eee28f874b56081a58ed7f4f03/hal.js#L8-L39
41,029
byteclubfr/js-hal
hal.js
Resource
function Resource (object, uri) { // new Resource(resource) === resource if (object instanceof Resource) { return object; } // Still work if "new" is omitted if (!(this instanceof Resource)) { return new Resource(object, uri); } // Initialize _links and _embedded properties this._links = {}; this._embedded = {}; // Copy properties from object // we copy AFTER initializing _links and _embedded so that user // **CAN** (but should not) overwrite them for (var property in object) { if (object.hasOwnProperty(property)) { this[property] = object[property]; } } // Use uri or object.href to initialize the only required <link>: rel = self uri = uri || this.href; if (uri === this.href) { delete this.href; } // If we have a URI, add this link // If not, we won't have a valid object (this may lead to a fatal error later) if (uri) this.link(new Link('self', uri)); }
javascript
function Resource (object, uri) { // new Resource(resource) === resource if (object instanceof Resource) { return object; } // Still work if "new" is omitted if (!(this instanceof Resource)) { return new Resource(object, uri); } // Initialize _links and _embedded properties this._links = {}; this._embedded = {}; // Copy properties from object // we copy AFTER initializing _links and _embedded so that user // **CAN** (but should not) overwrite them for (var property in object) { if (object.hasOwnProperty(property)) { this[property] = object[property]; } } // Use uri or object.href to initialize the only required <link>: rel = self uri = uri || this.href; if (uri === this.href) { delete this.href; } // If we have a URI, add this link // If not, we won't have a valid object (this may lead to a fatal error later) if (uri) this.link(new Link('self', uri)); }
[ "function", "Resource", "(", "object", ",", "uri", ")", "{", "// new Resource(resource) === resource", "if", "(", "object", "instanceof", "Resource", ")", "{", "return", "object", ";", "}", "// Still work if \"new\" is omitted", "if", "(", "!", "(", "this", "instanceof", "Resource", ")", ")", "{", "return", "new", "Resource", "(", "object", ",", "uri", ")", ";", "}", "// Initialize _links and _embedded properties", "this", ".", "_links", "=", "{", "}", ";", "this", ".", "_embedded", "=", "{", "}", ";", "// Copy properties from object", "// we copy AFTER initializing _links and _embedded so that user", "// **CAN** (but should not) overwrite them", "for", "(", "var", "property", "in", "object", ")", "{", "if", "(", "object", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "this", "[", "property", "]", "=", "object", "[", "property", "]", ";", "}", "}", "// Use uri or object.href to initialize the only required <link>: rel = self", "uri", "=", "uri", "||", "this", ".", "href", ";", "if", "(", "uri", "===", "this", ".", "href", ")", "{", "delete", "this", ".", "href", ";", "}", "// If we have a URI, add this link", "// If not, we won't have a valid object (this may lead to a fatal error later)", "if", "(", "uri", ")", "this", ".", "link", "(", "new", "Link", "(", "'self'", ",", "uri", ")", ")", ";", "}" ]
A hypertext resource @param Object object → the base properties Define "href" if you choose not to pass parameter "uri" Do not define "_links" and "_embedded" unless you know what you're doing @param String uri → href for the <link rel="self"> (can use reserved "href" property instead)
[ "A", "hypertext", "resource" ]
16c1e6d15093b7eee28f874b56081a58ed7f4f03
https://github.com/byteclubfr/js-hal/blob/16c1e6d15093b7eee28f874b56081a58ed7f4f03/hal.js#L74-L107
41,030
byteclubfr/js-hal
hal.js
resourceToJsonObject
function resourceToJsonObject (resource) { var result = {}; for (var prop in resource) { if (prop === '_links') { if (Object.keys(resource._links).length > 0) { // Note: we need to copy data to remove "rel" property without corrupting original Link object result._links = Object.keys(resource._links).reduce(function (links, rel) { if (Array.isArray(resource._links[rel])) { links[rel] = new Array() for (var i=0; i < resource._links[rel].length; i++) links[rel].push(resource._links[rel][i].toJSON()) } else { var link = resource._links[rel].toJSON(); links[rel] = link; delete link.rel; } return links; }, {}); } } else if (prop === '_embedded') { if (Object.keys(resource._embedded).length > 0) { // Note that we do not reformat _embedded // which means we voluntarily DO NOT RESPECT the following constraint: // > Relations with one corresponding Resource/Link have a single object // > value, relations with multiple corresponding HAL elements have an // > array of objects as their value. // Come on, resource one is *really* dumb. result._embedded = {}; for (var rel in resource._embedded) { result._embedded[rel] = resource._embedded[rel].map(resourceToJsonObject); } } } else if (resource.hasOwnProperty(prop)) { result[prop] = resource[prop]; } } return result; }
javascript
function resourceToJsonObject (resource) { var result = {}; for (var prop in resource) { if (prop === '_links') { if (Object.keys(resource._links).length > 0) { // Note: we need to copy data to remove "rel" property without corrupting original Link object result._links = Object.keys(resource._links).reduce(function (links, rel) { if (Array.isArray(resource._links[rel])) { links[rel] = new Array() for (var i=0; i < resource._links[rel].length; i++) links[rel].push(resource._links[rel][i].toJSON()) } else { var link = resource._links[rel].toJSON(); links[rel] = link; delete link.rel; } return links; }, {}); } } else if (prop === '_embedded') { if (Object.keys(resource._embedded).length > 0) { // Note that we do not reformat _embedded // which means we voluntarily DO NOT RESPECT the following constraint: // > Relations with one corresponding Resource/Link have a single object // > value, relations with multiple corresponding HAL elements have an // > array of objects as their value. // Come on, resource one is *really* dumb. result._embedded = {}; for (var rel in resource._embedded) { result._embedded[rel] = resource._embedded[rel].map(resourceToJsonObject); } } } else if (resource.hasOwnProperty(prop)) { result[prop] = resource[prop]; } } return result; }
[ "function", "resourceToJsonObject", "(", "resource", ")", "{", "var", "result", "=", "{", "}", ";", "for", "(", "var", "prop", "in", "resource", ")", "{", "if", "(", "prop", "===", "'_links'", ")", "{", "if", "(", "Object", ".", "keys", "(", "resource", ".", "_links", ")", ".", "length", ">", "0", ")", "{", "// Note: we need to copy data to remove \"rel\" property without corrupting original Link object", "result", ".", "_links", "=", "Object", ".", "keys", "(", "resource", ".", "_links", ")", ".", "reduce", "(", "function", "(", "links", ",", "rel", ")", "{", "if", "(", "Array", ".", "isArray", "(", "resource", ".", "_links", "[", "rel", "]", ")", ")", "{", "links", "[", "rel", "]", "=", "new", "Array", "(", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "resource", ".", "_links", "[", "rel", "]", ".", "length", ";", "i", "++", ")", "links", "[", "rel", "]", ".", "push", "(", "resource", ".", "_links", "[", "rel", "]", "[", "i", "]", ".", "toJSON", "(", ")", ")", "}", "else", "{", "var", "link", "=", "resource", ".", "_links", "[", "rel", "]", ".", "toJSON", "(", ")", ";", "links", "[", "rel", "]", "=", "link", ";", "delete", "link", ".", "rel", ";", "}", "return", "links", ";", "}", ",", "{", "}", ")", ";", "}", "}", "else", "if", "(", "prop", "===", "'_embedded'", ")", "{", "if", "(", "Object", ".", "keys", "(", "resource", ".", "_embedded", ")", ".", "length", ">", "0", ")", "{", "// Note that we do not reformat _embedded", "// which means we voluntarily DO NOT RESPECT the following constraint:", "// > Relations with one corresponding Resource/Link have a single object", "// > value, relations with multiple corresponding HAL elements have an", "// > array of objects as their value.", "// Come on, resource one is *really* dumb.", "result", ".", "_embedded", "=", "{", "}", ";", "for", "(", "var", "rel", "in", "resource", ".", "_embedded", ")", "{", "result", ".", "_embedded", "[", "rel", "]", "=", "resource", ".", "_embedded", "[", "rel", "]", ".", "map", "(", "resourceToJsonObject", ")", ";", "}", "}", "}", "else", "if", "(", "resource", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "result", "[", "prop", "]", "=", "resource", "[", "prop", "]", ";", "}", "}", "return", "result", ";", "}" ]
Convert a resource to a stringifiable anonymous object @private @param Resource resource
[ "Convert", "a", "resource", "to", "a", "stringifiable", "anonymous", "object" ]
16c1e6d15093b7eee28f874b56081a58ed7f4f03
https://github.com/byteclubfr/js-hal/blob/16c1e6d15093b7eee28f874b56081a58ed7f4f03/hal.js#L169-L211
41,031
byteclubfr/js-hal
hal.js
resourceToXml
function resourceToXml (resource, rel, currentIndent, nextIndent) { // Do not add line feeds if no indentation is asked var LF = (currentIndent || nextIndent) ? '\n' : ''; // Resource tag var xml = currentIndent + '<resource'; // Resource attributes: rel, href, name if (rel) xml += ' rel="' + escapeXml(rel) + '"'; if (resource.href || resource._links.self) xml += ' href="' + escapeXml(resource.href || resource._links.self.href) + '"'; if (resource.name) xml += ' name="' + escapeXml(resource.name) + '"'; xml += '>' + LF; // Add <link> tags for (var rel in resource._links) { if (!resource.href && rel === 'self') continue; xml += currentIndent + nextIndent + resource._links[rel].toXML() + LF; } // Add embedded for (var embed in resource._embedded) { // [Naive singularize](https://github.com/naholyr/js-hal#why-this-crappy-singularplural-management%E2%80%AF) var rel = embed.replace(/s$/, ''); resource._embedded[embed].forEach(function (res) { xml += resourceToXml(res, rel, currentIndent + nextIndent, currentIndent + nextIndent + nextIndent) + LF; }); } // Add properties as tags for (var prop in resource) { if (resource.hasOwnProperty(prop) && prop !== '_links' && prop !== '_embedded') { xml += currentIndent + nextIndent + '<' + prop + '>' + String(resource[prop]) + '</' + prop + '>' + LF; } } // Close tag and return the shit xml += currentIndent + '</resource>'; return xml; }
javascript
function resourceToXml (resource, rel, currentIndent, nextIndent) { // Do not add line feeds if no indentation is asked var LF = (currentIndent || nextIndent) ? '\n' : ''; // Resource tag var xml = currentIndent + '<resource'; // Resource attributes: rel, href, name if (rel) xml += ' rel="' + escapeXml(rel) + '"'; if (resource.href || resource._links.self) xml += ' href="' + escapeXml(resource.href || resource._links.self.href) + '"'; if (resource.name) xml += ' name="' + escapeXml(resource.name) + '"'; xml += '>' + LF; // Add <link> tags for (var rel in resource._links) { if (!resource.href && rel === 'self') continue; xml += currentIndent + nextIndent + resource._links[rel].toXML() + LF; } // Add embedded for (var embed in resource._embedded) { // [Naive singularize](https://github.com/naholyr/js-hal#why-this-crappy-singularplural-management%E2%80%AF) var rel = embed.replace(/s$/, ''); resource._embedded[embed].forEach(function (res) { xml += resourceToXml(res, rel, currentIndent + nextIndent, currentIndent + nextIndent + nextIndent) + LF; }); } // Add properties as tags for (var prop in resource) { if (resource.hasOwnProperty(prop) && prop !== '_links' && prop !== '_embedded') { xml += currentIndent + nextIndent + '<' + prop + '>' + String(resource[prop]) + '</' + prop + '>' + LF; } } // Close tag and return the shit xml += currentIndent + '</resource>'; return xml; }
[ "function", "resourceToXml", "(", "resource", ",", "rel", ",", "currentIndent", ",", "nextIndent", ")", "{", "// Do not add line feeds if no indentation is asked", "var", "LF", "=", "(", "currentIndent", "||", "nextIndent", ")", "?", "'\\n'", ":", "''", ";", "// Resource tag", "var", "xml", "=", "currentIndent", "+", "'<resource'", ";", "// Resource attributes: rel, href, name", "if", "(", "rel", ")", "xml", "+=", "' rel=\"'", "+", "escapeXml", "(", "rel", ")", "+", "'\"'", ";", "if", "(", "resource", ".", "href", "||", "resource", ".", "_links", ".", "self", ")", "xml", "+=", "' href=\"'", "+", "escapeXml", "(", "resource", ".", "href", "||", "resource", ".", "_links", ".", "self", ".", "href", ")", "+", "'\"'", ";", "if", "(", "resource", ".", "name", ")", "xml", "+=", "' name=\"'", "+", "escapeXml", "(", "resource", ".", "name", ")", "+", "'\"'", ";", "xml", "+=", "'>'", "+", "LF", ";", "// Add <link> tags", "for", "(", "var", "rel", "in", "resource", ".", "_links", ")", "{", "if", "(", "!", "resource", ".", "href", "&&", "rel", "===", "'self'", ")", "continue", ";", "xml", "+=", "currentIndent", "+", "nextIndent", "+", "resource", ".", "_links", "[", "rel", "]", ".", "toXML", "(", ")", "+", "LF", ";", "}", "// Add embedded", "for", "(", "var", "embed", "in", "resource", ".", "_embedded", ")", "{", "// [Naive singularize](https://github.com/naholyr/js-hal#why-this-crappy-singularplural-management%E2%80%AF)", "var", "rel", "=", "embed", ".", "replace", "(", "/", "s$", "/", ",", "''", ")", ";", "resource", ".", "_embedded", "[", "embed", "]", ".", "forEach", "(", "function", "(", "res", ")", "{", "xml", "+=", "resourceToXml", "(", "res", ",", "rel", ",", "currentIndent", "+", "nextIndent", ",", "currentIndent", "+", "nextIndent", "+", "nextIndent", ")", "+", "LF", ";", "}", ")", ";", "}", "// Add properties as tags", "for", "(", "var", "prop", "in", "resource", ")", "{", "if", "(", "resource", ".", "hasOwnProperty", "(", "prop", ")", "&&", "prop", "!==", "'_links'", "&&", "prop", "!==", "'_embedded'", ")", "{", "xml", "+=", "currentIndent", "+", "nextIndent", "+", "'<'", "+", "prop", "+", "'>'", "+", "String", "(", "resource", "[", "prop", "]", ")", "+", "'</'", "+", "prop", "+", "'>'", "+", "LF", ";", "}", "}", "// Close tag and return the shit", "xml", "+=", "currentIndent", "+", "'</resource>'", ";", "return", "xml", ";", "}" ]
Convert a resource to its XML representation @private @param Resource resource @param String rel → relation identifier for embedded object @param String currentIdent → current indentation @param String nextIndent → next indentation
[ "Convert", "a", "resource", "to", "its", "XML", "representation" ]
16c1e6d15093b7eee28f874b56081a58ed7f4f03
https://github.com/byteclubfr/js-hal/blob/16c1e6d15093b7eee28f874b56081a58ed7f4f03/hal.js#L238-L277
41,032
akamai/akamai-gen-edgerc
bin/gen-edgerc.js
init
function init() { // Retrieve any arguments passed in via the command line args = cliConfig.getArguments(); // Supply usage info if help argument was passed if (args.help) { console.log(cliConfig.getUsage()); process.exit(0); } getClientAuth(function(data) { parseClientAuth(data, function(err, data) { if (err) { console.error(err.message); process.exit(0); } writeEdgerc(data, function(err) { if (err) { if (err.errno == -13) { console.error("Unable to access " + err.path + ". Please make sure you " + "have permission to access this file or perhaps try running the " + "command as sudo."); process.exit(0); } } console.log("The section '" + args.section + "' has been succesfully added to " + args.path + "\n"); }); }); }); }
javascript
function init() { // Retrieve any arguments passed in via the command line args = cliConfig.getArguments(); // Supply usage info if help argument was passed if (args.help) { console.log(cliConfig.getUsage()); process.exit(0); } getClientAuth(function(data) { parseClientAuth(data, function(err, data) { if (err) { console.error(err.message); process.exit(0); } writeEdgerc(data, function(err) { if (err) { if (err.errno == -13) { console.error("Unable to access " + err.path + ". Please make sure you " + "have permission to access this file or perhaps try running the " + "command as sudo."); process.exit(0); } } console.log("The section '" + args.section + "' has been succesfully added to " + args.path + "\n"); }); }); }); }
[ "function", "init", "(", ")", "{", "// Retrieve any arguments passed in via the command line", "args", "=", "cliConfig", ".", "getArguments", "(", ")", ";", "// Supply usage info if help argument was passed", "if", "(", "args", ".", "help", ")", "{", "console", ".", "log", "(", "cliConfig", ".", "getUsage", "(", ")", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "getClientAuth", "(", "function", "(", "data", ")", "{", "parseClientAuth", "(", "data", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "err", ".", "message", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "writeEdgerc", "(", "data", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "errno", "==", "-", "13", ")", "{", "console", ".", "error", "(", "\"Unable to access \"", "+", "err", ".", "path", "+", "\". Please make sure you \"", "+", "\"have permission to access this file or perhaps try running the \"", "+", "\"command as sudo.\"", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "}", "console", ".", "log", "(", "\"The section '\"", "+", "args", ".", "section", "+", "\"' has been succesfully added to \"", "+", "args", ".", "path", "+", "\"\\n\"", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Initialize the script, setting up default values, and prepping the CLI params.
[ "Initialize", "the", "script", "setting", "up", "default", "values", "and", "prepping", "the", "CLI", "params", "." ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/bin/gen-edgerc.js#L35-L64
41,033
akamai/akamai-gen-edgerc
bin/gen-edgerc.js
getClientAuth
function getClientAuth(callback) { console.log("This script will create a section named '" + args.section + "'" + "in the local file " + args.path + ".\n"); // Read the client authorization file. If not found, notify user. if (args.file) { clientAuthData = fs.readFileSync(args.file, 'utf8'); console.log("+++ Found authorization file: " + args.file); callback(clientAuthData); } else { // Present user with input dialogue requesting copy and paste of // client auth data. var input = []; var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var msg = "After authorizing your client in the OPEN API Administration " + "tool, \nexport the credentials and paste the contents of the export file " + "below (making sure to include the final blank line). \nThen enter " + "control-D to continue: \n\n>>>\n"; rl.setPrompt(msg); rl.prompt(); rl.on('line', function(cmd) { input.push(cmd); }); rl.on('close', function(cmd) { if (input.length < 1) { // Data was not input, assumed early exit from the program. console.log("Kill command received without input. Exiting program."); process.exit(0); } console.log("\n<<<\n\n"); clientAuthData = input.join('\n'); callback(clientAuthData); }); } }
javascript
function getClientAuth(callback) { console.log("This script will create a section named '" + args.section + "'" + "in the local file " + args.path + ".\n"); // Read the client authorization file. If not found, notify user. if (args.file) { clientAuthData = fs.readFileSync(args.file, 'utf8'); console.log("+++ Found authorization file: " + args.file); callback(clientAuthData); } else { // Present user with input dialogue requesting copy and paste of // client auth data. var input = []; var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var msg = "After authorizing your client in the OPEN API Administration " + "tool, \nexport the credentials and paste the contents of the export file " + "below (making sure to include the final blank line). \nThen enter " + "control-D to continue: \n\n>>>\n"; rl.setPrompt(msg); rl.prompt(); rl.on('line', function(cmd) { input.push(cmd); }); rl.on('close', function(cmd) { if (input.length < 1) { // Data was not input, assumed early exit from the program. console.log("Kill command received without input. Exiting program."); process.exit(0); } console.log("\n<<<\n\n"); clientAuthData = input.join('\n'); callback(clientAuthData); }); } }
[ "function", "getClientAuth", "(", "callback", ")", "{", "console", ".", "log", "(", "\"This script will create a section named '\"", "+", "args", ".", "section", "+", "\"'\"", "+", "\"in the local file \"", "+", "args", ".", "path", "+", "\".\\n\"", ")", ";", "// Read the client authorization file. If not found, notify user.", "if", "(", "args", ".", "file", ")", "{", "clientAuthData", "=", "fs", ".", "readFileSync", "(", "args", ".", "file", ",", "'utf8'", ")", ";", "console", ".", "log", "(", "\"+++ Found authorization file: \"", "+", "args", ".", "file", ")", ";", "callback", "(", "clientAuthData", ")", ";", "}", "else", "{", "// Present user with input dialogue requesting copy and paste of", "// client auth data.", "var", "input", "=", "[", "]", ";", "var", "rl", "=", "readline", ".", "createInterface", "(", "{", "input", ":", "process", ".", "stdin", ",", "output", ":", "process", ".", "stdout", "}", ")", ";", "var", "msg", "=", "\"After authorizing your client in the OPEN API Administration \"", "+", "\"tool, \\nexport the credentials and paste the contents of the export file \"", "+", "\"below (making sure to include the final blank line). \\nThen enter \"", "+", "\"control-D to continue: \\n\\n>>>\\n\"", ";", "rl", ".", "setPrompt", "(", "msg", ")", ";", "rl", ".", "prompt", "(", ")", ";", "rl", ".", "on", "(", "'line'", ",", "function", "(", "cmd", ")", "{", "input", ".", "push", "(", "cmd", ")", ";", "}", ")", ";", "rl", ".", "on", "(", "'close'", ",", "function", "(", "cmd", ")", "{", "if", "(", "input", ".", "length", "<", "1", ")", "{", "// Data was not input, assumed early exit from the program.", "console", ".", "log", "(", "\"Kill command received without input. Exiting program.\"", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "console", ".", "log", "(", "\"\\n<<<\\n\\n\"", ")", ";", "clientAuthData", "=", "input", ".", "join", "(", "'\\n'", ")", ";", "callback", "(", "clientAuthData", ")", ";", "}", ")", ";", "}", "}" ]
Gets the client authorization data by either reading the file path passed in by the user or requesting the user to copy and paste the data directly into the command line. @param {Function} callback Callback function accepting a data param which will be called once the data is ready.
[ "Gets", "the", "client", "authorization", "data", "by", "either", "reading", "the", "file", "path", "passed", "in", "by", "the", "user", "or", "requesting", "the", "user", "to", "copy", "and", "paste", "the", "data", "directly", "into", "the", "command", "line", "." ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/bin/gen-edgerc.js#L76-L118
41,034
akamai/akamai-gen-edgerc
bin/gen-edgerc.js
parseClientAuth
function parseClientAuth(data, callback) { authParser.parseAuth(data, function(err, data) { if (err) callback(err, null); callback(null, data); }); }
javascript
function parseClientAuth(data, callback) { authParser.parseAuth(data, function(err, data) { if (err) callback(err, null); callback(null, data); }); }
[ "function", "parseClientAuth", "(", "data", ",", "callback", ")", "{", "authParser", ".", "parseAuth", "(", "data", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "callback", "(", "err", ",", "null", ")", ";", "callback", "(", "null", ",", "data", ")", ";", "}", ")", ";", "}" ]
Parses the client authorization file. @param {String} data Parsed array of client authorization data @param {Function} callback Callback function accepting an error parameter
[ "Parses", "the", "client", "authorization", "file", "." ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/bin/gen-edgerc.js#L126-L131
41,035
akamai/akamai-gen-edgerc
bin/gen-edgerc.js
writeEdgerc
function writeEdgerc(data, callback) { try { edgercWriter.writeEdgercSection( args.path, args.section, data["URL:"], data["Secret:"], data["Tokens:"], data["token:"], data["max-body"] ); } catch (err) { callback(err); } return callback(); }
javascript
function writeEdgerc(data, callback) { try { edgercWriter.writeEdgercSection( args.path, args.section, data["URL:"], data["Secret:"], data["Tokens:"], data["token:"], data["max-body"] ); } catch (err) { callback(err); } return callback(); }
[ "function", "writeEdgerc", "(", "data", ",", "callback", ")", "{", "try", "{", "edgercWriter", ".", "writeEdgercSection", "(", "args", ".", "path", ",", "args", ".", "section", ",", "data", "[", "\"URL:\"", "]", ",", "data", "[", "\"Secret:\"", "]", ",", "data", "[", "\"Tokens:\"", "]", ",", "data", "[", "\"token:\"", "]", ",", "data", "[", "\"max-body\"", "]", ")", ";", "}", "catch", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "return", "callback", "(", ")", ";", "}" ]
Writes the parsed client auth data to the .edgerc file. @param {Array} data Array of parsed client auth data @param {Function} callback unction to receive errors and handle completion
[ "Writes", "the", "parsed", "client", "auth", "data", "to", "the", ".", "edgerc", "file", "." ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/bin/gen-edgerc.js#L139-L155
41,036
shannonmoeller/handlebars-group-by
index.js
groupBy
function groupBy(handlebars) { var helpers = { /** * @method group * @param {Array} list * @param {Object} options * @param {Object} options.hash * @param {String} options.hash.by * @return {String} Rendered partial. */ group: function (list, options) { options = options || {}; var fn = options.fn || noop, inverse = options.inverse || noop, hash = options.hash, prop = hash && hash.by, keys = [], groups = {}; if (!prop || !list || !list.length) { return inverse(this); } function groupKey(item) { var key = get(item, prop); if (keys.indexOf(key) === -1) { keys.push(key); } if (!groups[key]) { groups[key] = { value: key, items: [] }; } groups[key].items.push(item); } function renderGroup(buffer, key) { return buffer + fn(groups[key]); } list.forEach(groupKey); return keys.reduce(renderGroup, ''); } }; handlebars.registerHelper(helpers); return handlebars; }
javascript
function groupBy(handlebars) { var helpers = { /** * @method group * @param {Array} list * @param {Object} options * @param {Object} options.hash * @param {String} options.hash.by * @return {String} Rendered partial. */ group: function (list, options) { options = options || {}; var fn = options.fn || noop, inverse = options.inverse || noop, hash = options.hash, prop = hash && hash.by, keys = [], groups = {}; if (!prop || !list || !list.length) { return inverse(this); } function groupKey(item) { var key = get(item, prop); if (keys.indexOf(key) === -1) { keys.push(key); } if (!groups[key]) { groups[key] = { value: key, items: [] }; } groups[key].items.push(item); } function renderGroup(buffer, key) { return buffer + fn(groups[key]); } list.forEach(groupKey); return keys.reduce(renderGroup, ''); } }; handlebars.registerHelper(helpers); return handlebars; }
[ "function", "groupBy", "(", "handlebars", ")", "{", "var", "helpers", "=", "{", "/**\n\t\t * @method group\n\t\t * @param {Array} list\n\t\t * @param {Object} options\n\t\t * @param {Object} options.hash\n\t\t * @param {String} options.hash.by\n\t\t * @return {String} Rendered partial.\n\t\t */", "group", ":", "function", "(", "list", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "fn", "=", "options", ".", "fn", "||", "noop", ",", "inverse", "=", "options", ".", "inverse", "||", "noop", ",", "hash", "=", "options", ".", "hash", ",", "prop", "=", "hash", "&&", "hash", ".", "by", ",", "keys", "=", "[", "]", ",", "groups", "=", "{", "}", ";", "if", "(", "!", "prop", "||", "!", "list", "||", "!", "list", ".", "length", ")", "{", "return", "inverse", "(", "this", ")", ";", "}", "function", "groupKey", "(", "item", ")", "{", "var", "key", "=", "get", "(", "item", ",", "prop", ")", ";", "if", "(", "keys", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "keys", ".", "push", "(", "key", ")", ";", "}", "if", "(", "!", "groups", "[", "key", "]", ")", "{", "groups", "[", "key", "]", "=", "{", "value", ":", "key", ",", "items", ":", "[", "]", "}", ";", "}", "groups", "[", "key", "]", ".", "items", ".", "push", "(", "item", ")", ";", "}", "function", "renderGroup", "(", "buffer", ",", "key", ")", "{", "return", "buffer", "+", "fn", "(", "groups", "[", "key", "]", ")", ";", "}", "list", ".", "forEach", "(", "groupKey", ")", ";", "return", "keys", ".", "reduce", "(", "renderGroup", ",", "''", ")", ";", "}", "}", ";", "handlebars", ".", "registerHelper", "(", "helpers", ")", ";", "return", "handlebars", ";", "}" ]
Registers a group helper on an instance of Handlebars. @type {Function} @param {Object} handlebars Handlebars instance. @return {Object} Handlebars instance.
[ "Registers", "a", "group", "helper", "on", "an", "instance", "of", "Handlebars", "." ]
bd3e48f787ea253b8beaec6145b9151b326bcb32
https://github.com/shannonmoeller/handlebars-group-by/blob/bd3e48f787ea253b8beaec6145b9151b326bcb32/index.js#L29-L83
41,037
goto-bus-stop/browser-pack-flat
index.js
markDuplicateVariableNames
function markDuplicateVariableNames (row, i, rows) { var ast = row[kAst] var scope = scan.scope(ast) if (scope) { scope.forEach(function (binding, name) { binding[kShouldRename] = rows.usedGlobalVariables.has(name) rows.usedGlobalVariables.add(name) }) } }
javascript
function markDuplicateVariableNames (row, i, rows) { var ast = row[kAst] var scope = scan.scope(ast) if (scope) { scope.forEach(function (binding, name) { binding[kShouldRename] = rows.usedGlobalVariables.has(name) rows.usedGlobalVariables.add(name) }) } }
[ "function", "markDuplicateVariableNames", "(", "row", ",", "i", ",", "rows", ")", "{", "var", "ast", "=", "row", "[", "kAst", "]", "var", "scope", "=", "scan", ".", "scope", "(", "ast", ")", "if", "(", "scope", ")", "{", "scope", ".", "forEach", "(", "function", "(", "binding", ",", "name", ")", "{", "binding", "[", "kShouldRename", "]", "=", "rows", ".", "usedGlobalVariables", ".", "has", "(", "name", ")", "rows", ".", "usedGlobalVariables", ".", "add", "(", "name", ")", "}", ")", "}", "}" ]
Mark module variables that collide with variable names from other modules so we can rewrite them.
[ "Mark", "module", "variables", "that", "collide", "with", "variable", "names", "from", "other", "modules", "so", "we", "can", "rewrite", "them", "." ]
c12e407a027a0a07c6d750781125317d6a166327
https://github.com/goto-bus-stop/browser-pack-flat/blob/c12e407a027a0a07c6d750781125317d6a166327/index.js#L295-L305
41,038
goto-bus-stop/browser-pack-flat
index.js
detectCycles
function detectCycles (rows) { var cyclicalModules = new Set() var checked = new Set() rows.forEach(function (module) { var visited = [] check(module) function check (row) { var i = visited.indexOf(row) if (i !== -1) { checked.add(row) for (; i < visited.length; i++) { cyclicalModules.add(visited[i]) } return } if (checked.has(row)) return visited.push(row) Object.keys(row.deps).forEach(function (k) { var dep = row.deps[k] var other = rows.byId[dep] if (other) check(other, visited) }) visited.pop() } }) // mark cyclical dependencies for (var i = 0; i < rows.length; i++) { rows[i][kEvaluateOnDemand] = cyclicalModules.has(rows[i]) } return cyclicalModules.size > 0 }
javascript
function detectCycles (rows) { var cyclicalModules = new Set() var checked = new Set() rows.forEach(function (module) { var visited = [] check(module) function check (row) { var i = visited.indexOf(row) if (i !== -1) { checked.add(row) for (; i < visited.length; i++) { cyclicalModules.add(visited[i]) } return } if (checked.has(row)) return visited.push(row) Object.keys(row.deps).forEach(function (k) { var dep = row.deps[k] var other = rows.byId[dep] if (other) check(other, visited) }) visited.pop() } }) // mark cyclical dependencies for (var i = 0; i < rows.length; i++) { rows[i][kEvaluateOnDemand] = cyclicalModules.has(rows[i]) } return cyclicalModules.size > 0 }
[ "function", "detectCycles", "(", "rows", ")", "{", "var", "cyclicalModules", "=", "new", "Set", "(", ")", "var", "checked", "=", "new", "Set", "(", ")", "rows", ".", "forEach", "(", "function", "(", "module", ")", "{", "var", "visited", "=", "[", "]", "check", "(", "module", ")", "function", "check", "(", "row", ")", "{", "var", "i", "=", "visited", ".", "indexOf", "(", "row", ")", "if", "(", "i", "!==", "-", "1", ")", "{", "checked", ".", "add", "(", "row", ")", "for", "(", ";", "i", "<", "visited", ".", "length", ";", "i", "++", ")", "{", "cyclicalModules", ".", "add", "(", "visited", "[", "i", "]", ")", "}", "return", "}", "if", "(", "checked", ".", "has", "(", "row", ")", ")", "return", "visited", ".", "push", "(", "row", ")", "Object", ".", "keys", "(", "row", ".", "deps", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "var", "dep", "=", "row", ".", "deps", "[", "k", "]", "var", "other", "=", "rows", ".", "byId", "[", "dep", "]", "if", "(", "other", ")", "check", "(", "other", ",", "visited", ")", "}", ")", "visited", ".", "pop", "(", ")", "}", "}", ")", "// mark cyclical dependencies", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "i", "++", ")", "{", "rows", "[", "i", "]", "[", "kEvaluateOnDemand", "]", "=", "cyclicalModules", ".", "has", "(", "rows", "[", "i", "]", ")", "}", "return", "cyclicalModules", ".", "size", ">", "0", "}" ]
Detect cyclical dependencies in the bundle. All modules in a dependency cycle are moved to the top of the bundle and wrapped in functions so they're not evaluated immediately. When other modules need a module that's in a dependency cycle, instead of using the module's exportName, it'll call the `createModuleFactory` runtime function, which will execute the requested module and return its exports.
[ "Detect", "cyclical", "dependencies", "in", "the", "bundle", ".", "All", "modules", "in", "a", "dependency", "cycle", "are", "moved", "to", "the", "top", "of", "the", "bundle", "and", "wrapped", "in", "functions", "so", "they", "re", "not", "evaluated", "immediately", ".", "When", "other", "modules", "need", "a", "module", "that", "s", "in", "a", "dependency", "cycle", "instead", "of", "using", "the", "module", "s", "exportName", "it", "ll", "call", "the", "createModuleFactory", "runtime", "function", "which", "will", "execute", "the", "requested", "module", "and", "return", "its", "exports", "." ]
c12e407a027a0a07c6d750781125317d6a166327
https://github.com/goto-bus-stop/browser-pack-flat/blob/c12e407a027a0a07c6d750781125317d6a166327/index.js#L567-L600
41,039
akamai/akamai-gen-edgerc
src/edgerc-writer.js
createSectionObj
function createSectionObj( host, secret, accessToken, clientToken, maxBody) { var section = {}; section.client_secret = secret; section.host = host; section.access_token = accessToken; section.client_token = clientToken; section["max-body"] = maxBody ? maxBody : "131072"; return section; }
javascript
function createSectionObj( host, secret, accessToken, clientToken, maxBody) { var section = {}; section.client_secret = secret; section.host = host; section.access_token = accessToken; section.client_token = clientToken; section["max-body"] = maxBody ? maxBody : "131072"; return section; }
[ "function", "createSectionObj", "(", "host", ",", "secret", ",", "accessToken", ",", "clientToken", ",", "maxBody", ")", "{", "var", "section", "=", "{", "}", ";", "section", ".", "client_secret", "=", "secret", ";", "section", ".", "host", "=", "host", ";", "section", ".", "access_token", "=", "accessToken", ";", "section", ".", "client_token", "=", "clientToken", ";", "section", "[", "\"max-body\"", "]", "=", "maxBody", "?", "maxBody", ":", "\"131072\"", ";", "return", "section", ";", "}" ]
Creates a properly formatted .edgerc section Object @param {String} section The section title @param {String} host The host value @param {String} secret The secret value @param {String} accessToken The access token value @param {String} clientToken The client token value @param {String} max-body The max body value @return {String} A properly formatted section block Object
[ "Creates", "a", "properly", "formatted", ".", "edgerc", "section", "Object" ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/src/edgerc-writer.js#L94-L108
41,040
nknapp/html5-media-converter
src/VideoConverter.js
VideoConverter
function VideoConverter(options) { var _this = this; this.name = function() { return options.name; }; this.extName = function () { return options.ext; }; /** * Generate a stream from the video converter * @param size * @returns {*} */ this.toStream = function (size) { var factory = ps.factory(false, !options.streamEncoding, function (input, output, callback) { var stream = this; var ffm = _this.convert(input, size, output, callback); ['start','progress','error'].forEach(function(event) { ffm.on(event, function() { stream.emit.apply(stream,[event].concat(arguments)); }); }); }); factory.videoConverter = this; return factory; }; this.convert = function (input, size, output, callback) { var ffm = ffmpeg(input).outputOptions(options.args); ffm.on('start', function(commandLine) { console.log('Spawned Ffmpeg with command: ' + commandLine); }); if (size) { var match = size.match(/(\d+)x(\d+)/); if (match) { ffm.addOutputOptions("-vf", scale(match[1], match[2])); } else { throw new Error("Illegal size specification: "+size); } } ffm.output(output); ffm.on("error", function (error, stdout, stderr) { error.stderr = stderr; callback(error); }); ffm.run(); if (typeof(output) === "string") { // If 'output' is a file, the callback must be called after ffmpeg has finished (only then is the file ready) ffm.on("end", function () { callback(); }); } else { callback(); } return ffm; } }
javascript
function VideoConverter(options) { var _this = this; this.name = function() { return options.name; }; this.extName = function () { return options.ext; }; /** * Generate a stream from the video converter * @param size * @returns {*} */ this.toStream = function (size) { var factory = ps.factory(false, !options.streamEncoding, function (input, output, callback) { var stream = this; var ffm = _this.convert(input, size, output, callback); ['start','progress','error'].forEach(function(event) { ffm.on(event, function() { stream.emit.apply(stream,[event].concat(arguments)); }); }); }); factory.videoConverter = this; return factory; }; this.convert = function (input, size, output, callback) { var ffm = ffmpeg(input).outputOptions(options.args); ffm.on('start', function(commandLine) { console.log('Spawned Ffmpeg with command: ' + commandLine); }); if (size) { var match = size.match(/(\d+)x(\d+)/); if (match) { ffm.addOutputOptions("-vf", scale(match[1], match[2])); } else { throw new Error("Illegal size specification: "+size); } } ffm.output(output); ffm.on("error", function (error, stdout, stderr) { error.stderr = stderr; callback(error); }); ffm.run(); if (typeof(output) === "string") { // If 'output' is a file, the callback must be called after ffmpeg has finished (only then is the file ready) ffm.on("end", function () { callback(); }); } else { callback(); } return ffm; } }
[ "function", "VideoConverter", "(", "options", ")", "{", "var", "_this", "=", "this", ";", "this", ".", "name", "=", "function", "(", ")", "{", "return", "options", ".", "name", ";", "}", ";", "this", ".", "extName", "=", "function", "(", ")", "{", "return", "options", ".", "ext", ";", "}", ";", "/**\n * Generate a stream from the video converter\n * @param size\n * @returns {*}\n */", "this", ".", "toStream", "=", "function", "(", "size", ")", "{", "var", "factory", "=", "ps", ".", "factory", "(", "false", ",", "!", "options", ".", "streamEncoding", ",", "function", "(", "input", ",", "output", ",", "callback", ")", "{", "var", "stream", "=", "this", ";", "var", "ffm", "=", "_this", ".", "convert", "(", "input", ",", "size", ",", "output", ",", "callback", ")", ";", "[", "'start'", ",", "'progress'", ",", "'error'", "]", ".", "forEach", "(", "function", "(", "event", ")", "{", "ffm", ".", "on", "(", "event", ",", "function", "(", ")", "{", "stream", ".", "emit", ".", "apply", "(", "stream", ",", "[", "event", "]", ".", "concat", "(", "arguments", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "factory", ".", "videoConverter", "=", "this", ";", "return", "factory", ";", "}", ";", "this", ".", "convert", "=", "function", "(", "input", ",", "size", ",", "output", ",", "callback", ")", "{", "var", "ffm", "=", "ffmpeg", "(", "input", ")", ".", "outputOptions", "(", "options", ".", "args", ")", ";", "ffm", ".", "on", "(", "'start'", ",", "function", "(", "commandLine", ")", "{", "console", ".", "log", "(", "'Spawned Ffmpeg with command: '", "+", "commandLine", ")", ";", "}", ")", ";", "if", "(", "size", ")", "{", "var", "match", "=", "size", ".", "match", "(", "/", "(\\d+)x(\\d+)", "/", ")", ";", "if", "(", "match", ")", "{", "ffm", ".", "addOutputOptions", "(", "\"-vf\"", ",", "scale", "(", "match", "[", "1", "]", ",", "match", "[", "2", "]", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Illegal size specification: \"", "+", "size", ")", ";", "}", "}", "ffm", ".", "output", "(", "output", ")", ";", "ffm", ".", "on", "(", "\"error\"", ",", "function", "(", "error", ",", "stdout", ",", "stderr", ")", "{", "error", ".", "stderr", "=", "stderr", ";", "callback", "(", "error", ")", ";", "}", ")", ";", "ffm", ".", "run", "(", ")", ";", "if", "(", "typeof", "(", "output", ")", "===", "\"string\"", ")", "{", "// If 'output' is a file, the callback must be called after ffmpeg has finished (only then is the file ready)", "ffm", ".", "on", "(", "\"end\"", ",", "function", "(", ")", "{", "callback", "(", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "return", "ffm", ";", "}", "}" ]
Creates a new @param options.streamEncoding {Boolean} @param options.args {Array.<String>} @param options.ext {String} @param options.name {String} a name for the converter @constructor
[ "Creates", "a", "new" ]
1411ac7dd2102facfaa0d08f9b9e2f0718d12690
https://github.com/nknapp/html5-media-converter/blob/1411ac7dd2102facfaa0d08f9b9e2f0718d12690/src/VideoConverter.js#L13-L73
41,041
parro-it/libui-napi
index.js
initAsyncResource
function initAsyncResource(asyncId, type, triggerAsyncId, resource) { if (wakingup) { return; } wakingup = true; setImmediate(() => { EventLoop.wakeupBackgroundThread(); wakingup = false; }); }
javascript
function initAsyncResource(asyncId, type, triggerAsyncId, resource) { if (wakingup) { return; } wakingup = true; setImmediate(() => { EventLoop.wakeupBackgroundThread(); wakingup = false; }); }
[ "function", "initAsyncResource", "(", "asyncId", ",", "type", ",", "triggerAsyncId", ",", "resource", ")", "{", "if", "(", "wakingup", ")", "{", "return", ";", "}", "wakingup", "=", "true", ";", "setImmediate", "(", "(", ")", "=>", "{", "EventLoop", ".", "wakeupBackgroundThread", "(", ")", ";", "wakingup", "=", "false", ";", "}", ")", ";", "}" ]
This is called when a new async handle is created. It's used to signal the background thread to stop awaiting calls and upgrade it's list of handles it's awaiting for.
[ "This", "is", "called", "when", "a", "new", "async", "handle", "is", "created", ".", "It", "s", "used", "to", "signal", "the", "background", "thread", "to", "stop", "awaiting", "calls", "and", "upgrade", "it", "s", "list", "of", "handles", "it", "s", "awaiting", "for", "." ]
5e32314516a163bc91da36cb709382cbc656e56f
https://github.com/parro-it/libui-napi/blob/5e32314516a163bc91da36cb709382cbc656e56f/index.js#L268-L277
41,042
NiklasGollenstede/native-ext
extension/common/exe-url.js
getUrl
function getUrl(version = current) { const name = `native-ext-v${version}-${os}-${arch}.${ext}`; return `https://github.com/NiklasGollenstede/native-ext/releases/download/v${version}/`+ name; }
javascript
function getUrl(version = current) { const name = `native-ext-v${version}-${os}-${arch}.${ext}`; return `https://github.com/NiklasGollenstede/native-ext/releases/download/v${version}/`+ name; }
[ "function", "getUrl", "(", "version", "=", "current", ")", "{", "const", "name", "=", "`", "${", "version", "}", "${", "os", "}", "${", "arch", "}", "${", "ext", "}", "`", ";", "return", "`", "${", "version", "}", "`", "+", "name", ";", "}" ]
no support for other OSs or ARM
[ "no", "support", "for", "other", "OSs", "or", "ARM" ]
c353d551d5890343faa9e89309a6fcf7fbdd5569
https://github.com/NiklasGollenstede/native-ext/blob/c353d551d5890343faa9e89309a6fcf7fbdd5569/extension/common/exe-url.js#L11-L14
41,043
dawsbot/satoshi-bitcoin
index.js
function(satoshi) { //validate arg var satoshiType = typeof satoshi; if (satoshiType === 'string') { satoshi = toNumber(satoshi); satoshiType = 'number'; } if (satoshiType !== 'number'){ throw new TypeError('toBitcoin must be called on a number or string, got ' + satoshiType); } if (!Number.isInteger(satoshi)) { throw new TypeError('toBitcoin must be called on a whole number or string format whole number'); } var bigSatoshi = new Big(satoshi); return Number(bigSatoshi.div(conversion)); }
javascript
function(satoshi) { //validate arg var satoshiType = typeof satoshi; if (satoshiType === 'string') { satoshi = toNumber(satoshi); satoshiType = 'number'; } if (satoshiType !== 'number'){ throw new TypeError('toBitcoin must be called on a number or string, got ' + satoshiType); } if (!Number.isInteger(satoshi)) { throw new TypeError('toBitcoin must be called on a whole number or string format whole number'); } var bigSatoshi = new Big(satoshi); return Number(bigSatoshi.div(conversion)); }
[ "function", "(", "satoshi", ")", "{", "//validate arg", "var", "satoshiType", "=", "typeof", "satoshi", ";", "if", "(", "satoshiType", "===", "'string'", ")", "{", "satoshi", "=", "toNumber", "(", "satoshi", ")", ";", "satoshiType", "=", "'number'", ";", "}", "if", "(", "satoshiType", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'toBitcoin must be called on a number or string, got '", "+", "satoshiType", ")", ";", "}", "if", "(", "!", "Number", ".", "isInteger", "(", "satoshi", ")", ")", "{", "throw", "new", "TypeError", "(", "'toBitcoin must be called on a whole number or string format whole number'", ")", ";", "}", "var", "bigSatoshi", "=", "new", "Big", "(", "satoshi", ")", ";", "return", "Number", "(", "bigSatoshi", ".", "div", "(", "conversion", ")", ")", ";", "}" ]
Convert Satoshi to Bitcoin @param {number|string} satoshi Amount of Satoshi to convert. Must be a whole number @throws {TypeError} Thrown if input is not a number or string @throws {TypeError} Thrown if input is not a whole number or string format whole number @returns {number}
[ "Convert", "Satoshi", "to", "Bitcoin" ]
bf3d74d4f58f0bc98c340f065937a786ce3cf86d
https://github.com/dawsbot/satoshi-bitcoin/blob/bf3d74d4f58f0bc98c340f065937a786ce3cf86d/index.js#L31-L47
41,044
dawsbot/satoshi-bitcoin
index.js
function(bitcoin) { //validate arg var bitcoinType = typeof bitcoin; if (bitcoinType === 'string') { bitcoin = toNumber(bitcoin); bitcoinType = 'number'; } if (bitcoinType !== 'number'){ throw new TypeError('toSatoshi must be called on a number or string, got ' + bitcoinType); } var bigBitcoin = new Big(bitcoin); return Number(bigBitcoin.times(conversion)); }
javascript
function(bitcoin) { //validate arg var bitcoinType = typeof bitcoin; if (bitcoinType === 'string') { bitcoin = toNumber(bitcoin); bitcoinType = 'number'; } if (bitcoinType !== 'number'){ throw new TypeError('toSatoshi must be called on a number or string, got ' + bitcoinType); } var bigBitcoin = new Big(bitcoin); return Number(bigBitcoin.times(conversion)); }
[ "function", "(", "bitcoin", ")", "{", "//validate arg", "var", "bitcoinType", "=", "typeof", "bitcoin", ";", "if", "(", "bitcoinType", "===", "'string'", ")", "{", "bitcoin", "=", "toNumber", "(", "bitcoin", ")", ";", "bitcoinType", "=", "'number'", ";", "}", "if", "(", "bitcoinType", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'toSatoshi must be called on a number or string, got '", "+", "bitcoinType", ")", ";", "}", "var", "bigBitcoin", "=", "new", "Big", "(", "bitcoin", ")", ";", "return", "Number", "(", "bigBitcoin", ".", "times", "(", "conversion", ")", ")", ";", "}" ]
Convert Bitcoin to Satoshi @param {number|string} bitcoin Amount of Bitcoin to convert @throws {TypeError} Thrown if input is not a number or string @returns {number}
[ "Convert", "Bitcoin", "to", "Satoshi" ]
bf3d74d4f58f0bc98c340f065937a786ce3cf86d
https://github.com/dawsbot/satoshi-bitcoin/blob/bf3d74d4f58f0bc98c340f065937a786ce3cf86d/index.js#L55-L68
41,045
akamai/akamai-gen-edgerc
src/cli-config.js
createArguments
function createArguments() { var cli = commandLineArgs([{ name: 'file', alias: 'f', type: String, defaultValue: "", description: "Full path to the credentials file.", required: true }, { name: 'section', alias: 's', type: String, defaultValue: "default", description: "Title of the section that will be added to the .edgerc file." }, { name: 'path', alias: 'p', type: String, defaultValue: os.homedir() + "/.edgerc", description: "Full path to the .edgerc file." }, { name: 'help', alias: 'h', description: "Display help and usage information." }]); return cli; }
javascript
function createArguments() { var cli = commandLineArgs([{ name: 'file', alias: 'f', type: String, defaultValue: "", description: "Full path to the credentials file.", required: true }, { name: 'section', alias: 's', type: String, defaultValue: "default", description: "Title of the section that will be added to the .edgerc file." }, { name: 'path', alias: 'p', type: String, defaultValue: os.homedir() + "/.edgerc", description: "Full path to the .edgerc file." }, { name: 'help', alias: 'h', description: "Display help and usage information." }]); return cli; }
[ "function", "createArguments", "(", ")", "{", "var", "cli", "=", "commandLineArgs", "(", "[", "{", "name", ":", "'file'", ",", "alias", ":", "'f'", ",", "type", ":", "String", ",", "defaultValue", ":", "\"\"", ",", "description", ":", "\"Full path to the credentials file.\"", ",", "required", ":", "true", "}", ",", "{", "name", ":", "'section'", ",", "alias", ":", "'s'", ",", "type", ":", "String", ",", "defaultValue", ":", "\"default\"", ",", "description", ":", "\"Title of the section that will be added to the .edgerc file.\"", "}", ",", "{", "name", ":", "'path'", ",", "alias", ":", "'p'", ",", "type", ":", "String", ",", "defaultValue", ":", "os", ".", "homedir", "(", ")", "+", "\"/.edgerc\"", ",", "description", ":", "\"Full path to the .edgerc file.\"", "}", ",", "{", "name", ":", "'help'", ",", "alias", ":", "'h'", ",", "description", ":", "\"Display help and usage information.\"", "}", "]", ")", ";", "return", "cli", ";", "}" ]
Create and return an instance of the CommandLineArgs object with the desired arguments specified.
[ "Create", "and", "return", "an", "instance", "of", "the", "CommandLineArgs", "object", "with", "the", "desired", "arguments", "specified", "." ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/src/cli-config.js#L36-L63
41,046
Streampunk/ledger
model/Device.js
Device
function Device(id, version, label, type, node_id, senders, receivers) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * [Device type]{@link deviceTypes} URN. * @type {string} * @readonly */ this.type = this.generateType(type); /** * Globally unique UUID identifier for the {@link Node} which initially created * the Device. * @type {string} * @readonly */ this.node_id = this.generateNodeID(node_id); /** * UUIDs of [Senders]{@link Sender} attached to the Device. * @type {string[]} * @readonly */ this.senders = this.generateSenders(senders); /** * UUIDs of [Receivers]{@link Receiver} attached to the Device. * @type {string[]} * @readonly */ this.receivers = this.generateReceivers(receivers); return immutable(this, { prototype: Device.prototype }); }
javascript
function Device(id, version, label, type, node_id, senders, receivers) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * [Device type]{@link deviceTypes} URN. * @type {string} * @readonly */ this.type = this.generateType(type); /** * Globally unique UUID identifier for the {@link Node} which initially created * the Device. * @type {string} * @readonly */ this.node_id = this.generateNodeID(node_id); /** * UUIDs of [Senders]{@link Sender} attached to the Device. * @type {string[]} * @readonly */ this.senders = this.generateSenders(senders); /** * UUIDs of [Receivers]{@link Receiver} attached to the Device. * @type {string[]} * @readonly */ this.receivers = this.generateReceivers(receivers); return immutable(this, { prototype: Device.prototype }); }
[ "function", "Device", "(", "id", ",", "version", ",", "label", ",", "type", ",", "node_id", ",", "senders", ",", "receivers", ")", "{", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "/**\n * [Device type]{@link deviceTypes} URN.\n * @type {string}\n * @readonly\n */", "this", ".", "type", "=", "this", ".", "generateType", "(", "type", ")", ";", "/**\n * Globally unique UUID identifier for the {@link Node} which initially created\n * the Device.\n * @type {string}\n * @readonly\n */", "this", ".", "node_id", "=", "this", ".", "generateNodeID", "(", "node_id", ")", ";", "/**\n * UUIDs of [Senders]{@link Sender} attached to the Device.\n * @type {string[]}\n * @readonly\n */", "this", ".", "senders", "=", "this", ".", "generateSenders", "(", "senders", ")", ";", "/**\n * UUIDs of [Receivers]{@link Receiver} attached to the Device.\n * @type {string[]}\n * @readonly\n */", "this", ".", "receivers", "=", "this", ".", "generateReceivers", "(", "receivers", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Device", ".", "prototype", "}", ")", ";", "}" ]
Describes a Device. Immutable value. @constructor @augments Versionned @param {String} id Globally unique UUID identifier for the Device. @param {string} version String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;) indicating precisely when an attribute of the resource last changed. @param {string} label Freeform string label for the Device. @param {string} type [Device type]{@link deviceTypes} URN. @param {string} node_id Globally unique UUID identifier for the {@link Node} which initially created the Device. @param {string[]} senders UUIDs of {@link Senders} attached to the Device. @param {string[]} receivers UUIDs of Receivers attached to the Device
[ "Describes", "a", "Device", ".", "Immutable", "value", "." ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Device.js#L36-L66
41,047
DeMille/node-usbmux
lib/usbmux.js
pack
function pack(payload_obj) { var payload_plist = plist.build(payload_obj) , payload_buf = new Buffer(payload_plist); var header = { len: payload_buf.length + 16, version: 1, request: 8, tag: 1 }; var header_buf = new Buffer(16); header_buf.fill(0); header_buf.writeUInt32LE(header.len, 0); header_buf.writeUInt32LE(header.version, 4); header_buf.writeUInt32LE(header.request, 8); header_buf.writeUInt32LE(header.tag, 12); return Buffer.concat([header_buf, payload_buf]); }
javascript
function pack(payload_obj) { var payload_plist = plist.build(payload_obj) , payload_buf = new Buffer(payload_plist); var header = { len: payload_buf.length + 16, version: 1, request: 8, tag: 1 }; var header_buf = new Buffer(16); header_buf.fill(0); header_buf.writeUInt32LE(header.len, 0); header_buf.writeUInt32LE(header.version, 4); header_buf.writeUInt32LE(header.request, 8); header_buf.writeUInt32LE(header.tag, 12); return Buffer.concat([header_buf, payload_buf]); }
[ "function", "pack", "(", "payload_obj", ")", "{", "var", "payload_plist", "=", "plist", ".", "build", "(", "payload_obj", ")", ",", "payload_buf", "=", "new", "Buffer", "(", "payload_plist", ")", ";", "var", "header", "=", "{", "len", ":", "payload_buf", ".", "length", "+", "16", ",", "version", ":", "1", ",", "request", ":", "8", ",", "tag", ":", "1", "}", ";", "var", "header_buf", "=", "new", "Buffer", "(", "16", ")", ";", "header_buf", ".", "fill", "(", "0", ")", ";", "header_buf", ".", "writeUInt32LE", "(", "header", ".", "len", ",", "0", ")", ";", "header_buf", ".", "writeUInt32LE", "(", "header", ".", "version", ",", "4", ")", ";", "header_buf", ".", "writeUInt32LE", "(", "header", ".", "request", ",", "8", ")", ";", "header_buf", ".", "writeUInt32LE", "(", "header", ".", "tag", ",", "12", ")", ";", "return", "Buffer", ".", "concat", "(", "[", "header_buf", ",", "payload_buf", "]", ")", ";", "}" ]
Pack a request object into a buffer for usbmuxd @param {object} payload_obj @return {Buffer}
[ "Pack", "a", "request", "object", "into", "a", "buffer", "for", "usbmuxd" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/lib/usbmux.js#L98-L117
41,048
DeMille/node-usbmux
lib/usbmux.js
UsbmuxdError
function UsbmuxdError(message, number) { this.name = 'UsbmuxdError'; this.message = message; if (number) { this.number = number; this.message += ', Err #' + number; } if (number === 2) this.message += ": Device isn't connected"; if (number === 3) this.message += ": Port isn't available or open"; if (number === 5) this.message += ": Malformed request"; }
javascript
function UsbmuxdError(message, number) { this.name = 'UsbmuxdError'; this.message = message; if (number) { this.number = number; this.message += ', Err #' + number; } if (number === 2) this.message += ": Device isn't connected"; if (number === 3) this.message += ": Port isn't available or open"; if (number === 5) this.message += ": Malformed request"; }
[ "function", "UsbmuxdError", "(", "message", ",", "number", ")", "{", "this", ".", "name", "=", "'UsbmuxdError'", ";", "this", ".", "message", "=", "message", ";", "if", "(", "number", ")", "{", "this", ".", "number", "=", "number", ";", "this", ".", "message", "+=", "', Err #'", "+", "number", ";", "}", "if", "(", "number", "===", "2", ")", "this", ".", "message", "+=", "\": Device isn't connected\"", ";", "if", "(", "number", "===", "3", ")", "this", ".", "message", "+=", "\": Port isn't available or open\"", ";", "if", "(", "number", "===", "5", ")", "this", ".", "message", "+=", "\": Malformed request\"", ";", "}" ]
Custom usbmuxd error There's no documentation for usbmuxd responses, but I think I've figured out these result numbers: 0 - Success 2 - Device requested isn't connected 3 - Port requested isn't available \ open 5 - Malformed request @param {string} message - Error message @param {integer} [number] - Error number given from usbmuxd response
[ "Custom", "usbmuxd", "error" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/lib/usbmux.js#L229-L240
41,049
DeMille/node-usbmux
lib/usbmux.js
createListener
function createListener() { var conn = net.connect(address) , req = protocol.listen; /** * Handle complete messages from usbmuxd * @function */ var parse = protocol.makeParser(function onMsgComplete(msg) { debug.listen('Response: \n%o', msg); // first response always acknowledges / denies the request: if (msg.MessageType === 'Result' && msg.Number !== 0) { conn.emit('error', new UsbmuxdError('Listen failed', msg.Number)); conn.end(); } // subsequent responses report on connected device status: if (msg.MessageType === 'Attached') { devices[msg.Properties.SerialNumber] = msg.Properties; conn.emit('attached', msg.Properties.SerialNumber); } if (msg.MessageType === 'Detached') { // given msg.DeviceID, find matching device and remove it Object.keys(devices).forEach(function(key) { if (devices[key].DeviceID === msg.DeviceID) { conn.emit('detached', devices[key].SerialNumber); delete devices[key]; } }); } }); debug.listen('Request: \n%s', req.slice(16).toString()); conn.on('data', parse); process.nextTick(function() { conn.write(req); }); return conn; }
javascript
function createListener() { var conn = net.connect(address) , req = protocol.listen; /** * Handle complete messages from usbmuxd * @function */ var parse = protocol.makeParser(function onMsgComplete(msg) { debug.listen('Response: \n%o', msg); // first response always acknowledges / denies the request: if (msg.MessageType === 'Result' && msg.Number !== 0) { conn.emit('error', new UsbmuxdError('Listen failed', msg.Number)); conn.end(); } // subsequent responses report on connected device status: if (msg.MessageType === 'Attached') { devices[msg.Properties.SerialNumber] = msg.Properties; conn.emit('attached', msg.Properties.SerialNumber); } if (msg.MessageType === 'Detached') { // given msg.DeviceID, find matching device and remove it Object.keys(devices).forEach(function(key) { if (devices[key].DeviceID === msg.DeviceID) { conn.emit('detached', devices[key].SerialNumber); delete devices[key]; } }); } }); debug.listen('Request: \n%s', req.slice(16).toString()); conn.on('data', parse); process.nextTick(function() { conn.write(req); }); return conn; }
[ "function", "createListener", "(", ")", "{", "var", "conn", "=", "net", ".", "connect", "(", "address", ")", ",", "req", "=", "protocol", ".", "listen", ";", "/**\n * Handle complete messages from usbmuxd\n * @function\n */", "var", "parse", "=", "protocol", ".", "makeParser", "(", "function", "onMsgComplete", "(", "msg", ")", "{", "debug", ".", "listen", "(", "'Response: \\n%o'", ",", "msg", ")", ";", "// first response always acknowledges / denies the request:", "if", "(", "msg", ".", "MessageType", "===", "'Result'", "&&", "msg", ".", "Number", "!==", "0", ")", "{", "conn", ".", "emit", "(", "'error'", ",", "new", "UsbmuxdError", "(", "'Listen failed'", ",", "msg", ".", "Number", ")", ")", ";", "conn", ".", "end", "(", ")", ";", "}", "// subsequent responses report on connected device status:", "if", "(", "msg", ".", "MessageType", "===", "'Attached'", ")", "{", "devices", "[", "msg", ".", "Properties", ".", "SerialNumber", "]", "=", "msg", ".", "Properties", ";", "conn", ".", "emit", "(", "'attached'", ",", "msg", ".", "Properties", ".", "SerialNumber", ")", ";", "}", "if", "(", "msg", ".", "MessageType", "===", "'Detached'", ")", "{", "// given msg.DeviceID, find matching device and remove it", "Object", ".", "keys", "(", "devices", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "devices", "[", "key", "]", ".", "DeviceID", "===", "msg", ".", "DeviceID", ")", "{", "conn", ".", "emit", "(", "'detached'", ",", "devices", "[", "key", "]", ".", "SerialNumber", ")", ";", "delete", "devices", "[", "key", "]", ";", "}", "}", ")", ";", "}", "}", ")", ";", "debug", ".", "listen", "(", "'Request: \\n%s'", ",", "req", ".", "slice", "(", "16", ")", ".", "toString", "(", ")", ")", ";", "conn", ".", "on", "(", "'data'", ",", "parse", ")", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "conn", ".", "write", "(", "req", ")", ";", "}", ")", ";", "return", "conn", ";", "}" ]
Connects to usbmuxd and listens for ios devices This connection stays open, listening as devices are plugged/unplugged and cant be upgraded into a tcp tunnel. You have to start a second connection with connect() to actually make tunnel. @return {net.Socket} - Socket with 2 bolted on events, attached & detached: Fires when devices are plugged in or first found by the listener @event net.Socket#attached @type {string} - UDID Fires when devices are unplugged @event net.Socket#detached @type {string} - UDID @public
[ "Connects", "to", "usbmuxd", "and", "listens", "for", "ios", "devices" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/lib/usbmux.js#L264-L306
41,050
DeMille/node-usbmux
lib/usbmux.js
connect
function connect(deviceID, devicePort) { return Q.Promise(function(resolve, reject) { var conn = net.connect(address) , req = protocol.connect(deviceID, devicePort); /** * Handle complete messages from usbmuxd * @function */ var parse = protocol.makeParser(function onMsgComplete(msg) { debug.connect('Response: \n%o', msg); if (msg.MessageType === 'Result' && msg.Number === 0) { conn.removeListener('data', parse); resolve(conn); return; } // anything other response means it failed reject(new UsbmuxdError('Tunnel failed', msg.Number)); conn.end(); }); debug.connect('Request: \n%s', req.slice(16).toString()); conn.on('data', parse); process.nextTick(function() { conn.write(req); }); }); }
javascript
function connect(deviceID, devicePort) { return Q.Promise(function(resolve, reject) { var conn = net.connect(address) , req = protocol.connect(deviceID, devicePort); /** * Handle complete messages from usbmuxd * @function */ var parse = protocol.makeParser(function onMsgComplete(msg) { debug.connect('Response: \n%o', msg); if (msg.MessageType === 'Result' && msg.Number === 0) { conn.removeListener('data', parse); resolve(conn); return; } // anything other response means it failed reject(new UsbmuxdError('Tunnel failed', msg.Number)); conn.end(); }); debug.connect('Request: \n%s', req.slice(16).toString()); conn.on('data', parse); process.nextTick(function() { conn.write(req); }); }); }
[ "function", "connect", "(", "deviceID", ",", "devicePort", ")", "{", "return", "Q", ".", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "conn", "=", "net", ".", "connect", "(", "address", ")", ",", "req", "=", "protocol", ".", "connect", "(", "deviceID", ",", "devicePort", ")", ";", "/**\n * Handle complete messages from usbmuxd\n * @function\n */", "var", "parse", "=", "protocol", ".", "makeParser", "(", "function", "onMsgComplete", "(", "msg", ")", "{", "debug", ".", "connect", "(", "'Response: \\n%o'", ",", "msg", ")", ";", "if", "(", "msg", ".", "MessageType", "===", "'Result'", "&&", "msg", ".", "Number", "===", "0", ")", "{", "conn", ".", "removeListener", "(", "'data'", ",", "parse", ")", ";", "resolve", "(", "conn", ")", ";", "return", ";", "}", "// anything other response means it failed", "reject", "(", "new", "UsbmuxdError", "(", "'Tunnel failed'", ",", "msg", ".", "Number", ")", ")", ";", "conn", ".", "end", "(", ")", ";", "}", ")", ";", "debug", ".", "connect", "(", "'Request: \\n%s'", ",", "req", ".", "slice", "(", "16", ")", ".", "toString", "(", ")", ")", ";", "conn", ".", "on", "(", "'data'", ",", "parse", ")", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "conn", ".", "write", "(", "req", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Connects to a device through usbmuxd for a tunneled tcp connection @param {string} deviceID - Target device's usbmuxd ID @param {integer} devicePort - Port on ios device to connect to @return {Q.promise} - resolves {net.Socket} - Tunneled tcp connection to device - rejects {Error}
[ "Connects", "to", "a", "device", "through", "usbmuxd", "for", "a", "tunneled", "tcp", "connection" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/lib/usbmux.js#L318-L348
41,051
DeMille/node-usbmux
lib/usbmux.js
Relay
function Relay(devicePort, relayPort, opts) { if (!(this instanceof Relay)) return new Relay(arguments); this._devicePort = devicePort; this._relayPort = relayPort; opts = opts || {}; this._udid = opts.udid; this._startListener(opts.timeout); this._startServer(); }
javascript
function Relay(devicePort, relayPort, opts) { if (!(this instanceof Relay)) return new Relay(arguments); this._devicePort = devicePort; this._relayPort = relayPort; opts = opts || {}; this._udid = opts.udid; this._startListener(opts.timeout); this._startServer(); }
[ "function", "Relay", "(", "devicePort", ",", "relayPort", ",", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Relay", ")", ")", "return", "new", "Relay", "(", "arguments", ")", ";", "this", ".", "_devicePort", "=", "devicePort", ";", "this", ".", "_relayPort", "=", "relayPort", ";", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "_udid", "=", "opts", ".", "udid", ";", "this", ".", "_startListener", "(", "opts", ".", "timeout", ")", ";", "this", ".", "_startServer", "(", ")", ";", "}" ]
Creates a new tcp relay to a port on connected usb device @constructor @param {integer} devicePort - Port to connect to on device @param {integer} relayPort - Local port that will listen as relay @param {object} [opts] - Options @param {integer} [opts.timeout=1000] - Search time (ms) before warning @param {string} [opts.udid] - UDID of specific device to connect to @public
[ "Creates", "a", "new", "tcp", "relay", "to", "a", "port", "on", "connected", "usb", "device" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/lib/usbmux.js#L363-L374
41,052
layerhq/web-xdk
src/ui/adapters/angular.js
initAngular
function initAngular(angular) { // Define the layerXDKController const controllers = angular.module('layerXDKControllers', []); // Setup the properties for the given widget that is being generated function setupProps(scope, elem, attrs, props) { /* * For each property we are going to do the following: * * 1. See if there is an initial value * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value * 3. $observe() for any changes in the property * 4. $watch() for any changes in the output of scope.$eval() * * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE * this code triggers and corrects those values. This can cause errors. * * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER * its been evaluated. * * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-` * works better. * * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files. */ props.forEach((prop) => { const ngPropertyName = prop.propertyName.indexOf('on') === 0 ? 'ng' + prop.propertyName.substring(2) : 'ng' + prop.propertyName.substring(0, 1).toUpperCase() + prop.propertyName.substring(1); // Observe for changes to the attribute value and apply them to the property value attrs.$observe(prop.propertyName, (value) => { if (elem.properties) { elem[prop.propertyName] = value; } else { if (!elem.properties) elem.properties = {}; elem.properties[prop.propertyName] = value; } }); // Observe for changes to the attribute value prefixed with "ng-" and watch the scoped expression for changes // that need to be applied to the property value. attrs.$observe(ngPropertyName, (expression) => { scope.$watch(expression, (value) => { if (!elem.properties) elem.properties = {}; if (elem.properties._internalState && !elem.properties._internalState.disableSetters) { elem[prop.propertyName] = value; } else { elem.properties[prop.propertyName] = value; } }); }); }); } // Gather all UI Components Object.keys(ComponentsHash) .forEach((componentName) => { const component = ComponentsHash[componentName]; // Get the camel case controller name const controllerName = componentName.replace(/-(.)/g, (str, value) => value.toUpperCase()); controllers.directive(controllerName, () => ({ restrict: 'E', link: (scope, elem, attrs) => { const functionProps = component.properties; setupProps(scope, elem[0], attrs, functionProps); }, })); }); }
javascript
function initAngular(angular) { // Define the layerXDKController const controllers = angular.module('layerXDKControllers', []); // Setup the properties for the given widget that is being generated function setupProps(scope, elem, attrs, props) { /* * For each property we are going to do the following: * * 1. See if there is an initial value * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value * 3. $observe() for any changes in the property * 4. $watch() for any changes in the output of scope.$eval() * * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE * this code triggers and corrects those values. This can cause errors. * * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER * its been evaluated. * * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-` * works better. * * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files. */ props.forEach((prop) => { const ngPropertyName = prop.propertyName.indexOf('on') === 0 ? 'ng' + prop.propertyName.substring(2) : 'ng' + prop.propertyName.substring(0, 1).toUpperCase() + prop.propertyName.substring(1); // Observe for changes to the attribute value and apply them to the property value attrs.$observe(prop.propertyName, (value) => { if (elem.properties) { elem[prop.propertyName] = value; } else { if (!elem.properties) elem.properties = {}; elem.properties[prop.propertyName] = value; } }); // Observe for changes to the attribute value prefixed with "ng-" and watch the scoped expression for changes // that need to be applied to the property value. attrs.$observe(ngPropertyName, (expression) => { scope.$watch(expression, (value) => { if (!elem.properties) elem.properties = {}; if (elem.properties._internalState && !elem.properties._internalState.disableSetters) { elem[prop.propertyName] = value; } else { elem.properties[prop.propertyName] = value; } }); }); }); } // Gather all UI Components Object.keys(ComponentsHash) .forEach((componentName) => { const component = ComponentsHash[componentName]; // Get the camel case controller name const controllerName = componentName.replace(/-(.)/g, (str, value) => value.toUpperCase()); controllers.directive(controllerName, () => ({ restrict: 'E', link: (scope, elem, attrs) => { const functionProps = component.properties; setupProps(scope, elem[0], attrs, functionProps); }, })); }); }
[ "function", "initAngular", "(", "angular", ")", "{", "// Define the layerXDKController", "const", "controllers", "=", "angular", ".", "module", "(", "'layerXDKControllers'", ",", "[", "]", ")", ";", "// Setup the properties for the given widget that is being generated", "function", "setupProps", "(", "scope", ",", "elem", ",", "attrs", ",", "props", ")", "{", "/*\n * For each property we are going to do the following:\n *\n * 1. See if there is an initial value\n * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value\n * 3. $observe() for any changes in the property\n * 4. $watch() for any changes in the output of scope.$eval()\n *\n * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these\n * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE\n * this code triggers and corrects those values. This can cause errors.\n *\n * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property\n * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER\n * its been evaluated.\n *\n * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-`\n * works better.\n *\n * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files.\n */", "props", ".", "forEach", "(", "(", "prop", ")", "=>", "{", "const", "ngPropertyName", "=", "prop", ".", "propertyName", ".", "indexOf", "(", "'on'", ")", "===", "0", "?", "'ng'", "+", "prop", ".", "propertyName", ".", "substring", "(", "2", ")", ":", "'ng'", "+", "prop", ".", "propertyName", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "prop", ".", "propertyName", ".", "substring", "(", "1", ")", ";", "// Observe for changes to the attribute value and apply them to the property value", "attrs", ".", "$observe", "(", "prop", ".", "propertyName", ",", "(", "value", ")", "=>", "{", "if", "(", "elem", ".", "properties", ")", "{", "elem", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "else", "{", "if", "(", "!", "elem", ".", "properties", ")", "elem", ".", "properties", "=", "{", "}", ";", "elem", ".", "properties", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "}", ")", ";", "// Observe for changes to the attribute value prefixed with \"ng-\" and watch the scoped expression for changes", "// that need to be applied to the property value.", "attrs", ".", "$observe", "(", "ngPropertyName", ",", "(", "expression", ")", "=>", "{", "scope", ".", "$watch", "(", "expression", ",", "(", "value", ")", "=>", "{", "if", "(", "!", "elem", ".", "properties", ")", "elem", ".", "properties", "=", "{", "}", ";", "if", "(", "elem", ".", "properties", ".", "_internalState", "&&", "!", "elem", ".", "properties", ".", "_internalState", ".", "disableSetters", ")", "{", "elem", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "else", "{", "elem", ".", "properties", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "// Gather all UI Components", "Object", ".", "keys", "(", "ComponentsHash", ")", ".", "forEach", "(", "(", "componentName", ")", "=>", "{", "const", "component", "=", "ComponentsHash", "[", "componentName", "]", ";", "// Get the camel case controller name", "const", "controllerName", "=", "componentName", ".", "replace", "(", "/", "-(.)", "/", "g", ",", "(", "str", ",", "value", ")", "=>", "value", ".", "toUpperCase", "(", ")", ")", ";", "controllers", ".", "directive", "(", "controllerName", ",", "(", ")", "=>", "(", "{", "restrict", ":", "'E'", ",", "link", ":", "(", "scope", ",", "elem", ",", "attrs", ")", "=>", "{", "const", "functionProps", "=", "component", ".", "properties", ";", "setupProps", "(", "scope", ",", "elem", "[", "0", "]", ",", "attrs", ",", "functionProps", ")", ";", "}", ",", "}", ")", ")", ";", "}", ")", ";", "}" ]
Call this function to initialize all of the angular 1.x directives needed to handle the Layer UI for Web widgets. When passing scope values/function into widget properties, prefix the property with `ng-`; for functions, replace `on-` with `ng-`. If passing in a literal, do NOT prefix with `ng-`: ``` <layer-notifier notify-in-foreground="toast"></layer-notifier> <layer-conversation-view ng-query="myscopeProp.query"></layer-conversation-view> <layer-conversation-list ng-conversation-selected="myscope.handleSelectionFunc"></layer-conversation-list> <layer-send-button></layer-send-button> <layer-file-upload-button></layer-file-upload-button> ``` Call this function to initialize angular 1.x Directives which will be part of the "layerXDKControllers" controller: ``` import '@layerhq/web-xdk/ui/adapters/angular'; Layer.UI.adapters.angular(angular); // Creates the layerXDKControllers controller angular.module('MyApp', ['layerXDKControllers']); ``` Now you can put `<layer-conversation-view>` and other widgets into angular templates and expect them to work. Prefix ALL property names with `ng-` to insure that scope is evaluated prior to passing the value on to the webcomponent. ### Bindings Bindings should work... except when put within Replaceable Content; the following will *not* work: ``` <layer-conversation-view> <div layer-replaceable-name="composerButtonPanelRight"> <div>{{displayName}}</div> <layer-send-button></layer-send-button> <layer-file-upload-button></layer-file-upload-button> </div> </layer-conversation-view> ``` The above code correctly inserts the send button and upload button, but will not lookup `displayName` in your scope. Note that the above technique of using `layer-replaceable-name` only works for non-repeating content; to customize nodes that repeat, you will need to use a callback function, best accomplished using: ```javascript document.getElementById('my-layer-conversation-view').replaceableContent = { conversationRowRightSide: function(widget) { return domNodeOrInnerHTML; } }; ``` ### Importing Not included with the standard build. To import: ``` import '@layerhq/web-xdk/ui/adapters/angular'; ``` @class Layer.UI.adapters.angular @singleton @param {Object} angular Pass in the AngularJS library
[ "Call", "this", "function", "to", "initialize", "all", "of", "the", "angular", "1", ".", "x", "directives", "needed", "to", "handle", "the", "Layer", "UI", "for", "Web", "widgets", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/adapters/angular.js#L69-L145
41,053
layerhq/web-xdk
src/ui/adapters/angular.js
setupProps
function setupProps(scope, elem, attrs, props) { /* * For each property we are going to do the following: * * 1. See if there is an initial value * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value * 3. $observe() for any changes in the property * 4. $watch() for any changes in the output of scope.$eval() * * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE * this code triggers and corrects those values. This can cause errors. * * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER * its been evaluated. * * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-` * works better. * * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files. */ props.forEach((prop) => { const ngPropertyName = prop.propertyName.indexOf('on') === 0 ? 'ng' + prop.propertyName.substring(2) : 'ng' + prop.propertyName.substring(0, 1).toUpperCase() + prop.propertyName.substring(1); // Observe for changes to the attribute value and apply them to the property value attrs.$observe(prop.propertyName, (value) => { if (elem.properties) { elem[prop.propertyName] = value; } else { if (!elem.properties) elem.properties = {}; elem.properties[prop.propertyName] = value; } }); // Observe for changes to the attribute value prefixed with "ng-" and watch the scoped expression for changes // that need to be applied to the property value. attrs.$observe(ngPropertyName, (expression) => { scope.$watch(expression, (value) => { if (!elem.properties) elem.properties = {}; if (elem.properties._internalState && !elem.properties._internalState.disableSetters) { elem[prop.propertyName] = value; } else { elem.properties[prop.propertyName] = value; } }); }); }); }
javascript
function setupProps(scope, elem, attrs, props) { /* * For each property we are going to do the following: * * 1. See if there is an initial value * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value * 3. $observe() for any changes in the property * 4. $watch() for any changes in the output of scope.$eval() * * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE * this code triggers and corrects those values. This can cause errors. * * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER * its been evaluated. * * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-` * works better. * * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files. */ props.forEach((prop) => { const ngPropertyName = prop.propertyName.indexOf('on') === 0 ? 'ng' + prop.propertyName.substring(2) : 'ng' + prop.propertyName.substring(0, 1).toUpperCase() + prop.propertyName.substring(1); // Observe for changes to the attribute value and apply them to the property value attrs.$observe(prop.propertyName, (value) => { if (elem.properties) { elem[prop.propertyName] = value; } else { if (!elem.properties) elem.properties = {}; elem.properties[prop.propertyName] = value; } }); // Observe for changes to the attribute value prefixed with "ng-" and watch the scoped expression for changes // that need to be applied to the property value. attrs.$observe(ngPropertyName, (expression) => { scope.$watch(expression, (value) => { if (!elem.properties) elem.properties = {}; if (elem.properties._internalState && !elem.properties._internalState.disableSetters) { elem[prop.propertyName] = value; } else { elem.properties[prop.propertyName] = value; } }); }); }); }
[ "function", "setupProps", "(", "scope", ",", "elem", ",", "attrs", ",", "props", ")", "{", "/*\n * For each property we are going to do the following:\n *\n * 1. See if there is an initial value\n * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value\n * 3. $observe() for any changes in the property\n * 4. $watch() for any changes in the output of scope.$eval()\n *\n * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these\n * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE\n * this code triggers and corrects those values. This can cause errors.\n *\n * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property\n * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER\n * its been evaluated.\n *\n * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-`\n * works better.\n *\n * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files.\n */", "props", ".", "forEach", "(", "(", "prop", ")", "=>", "{", "const", "ngPropertyName", "=", "prop", ".", "propertyName", ".", "indexOf", "(", "'on'", ")", "===", "0", "?", "'ng'", "+", "prop", ".", "propertyName", ".", "substring", "(", "2", ")", ":", "'ng'", "+", "prop", ".", "propertyName", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "prop", ".", "propertyName", ".", "substring", "(", "1", ")", ";", "// Observe for changes to the attribute value and apply them to the property value", "attrs", ".", "$observe", "(", "prop", ".", "propertyName", ",", "(", "value", ")", "=>", "{", "if", "(", "elem", ".", "properties", ")", "{", "elem", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "else", "{", "if", "(", "!", "elem", ".", "properties", ")", "elem", ".", "properties", "=", "{", "}", ";", "elem", ".", "properties", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "}", ")", ";", "// Observe for changes to the attribute value prefixed with \"ng-\" and watch the scoped expression for changes", "// that need to be applied to the property value.", "attrs", ".", "$observe", "(", "ngPropertyName", ",", "(", "expression", ")", "=>", "{", "scope", ".", "$watch", "(", "expression", ",", "(", "value", ")", "=>", "{", "if", "(", "!", "elem", ".", "properties", ")", "elem", ".", "properties", "=", "{", "}", ";", "if", "(", "elem", ".", "properties", ".", "_internalState", "&&", "!", "elem", ".", "properties", ".", "_internalState", ".", "disableSetters", ")", "{", "elem", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "else", "{", "elem", ".", "properties", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Setup the properties for the given widget that is being generated
[ "Setup", "the", "properties", "for", "the", "given", "widget", "that", "is", "being", "generated" ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/adapters/angular.js#L75-L126
41,054
layerhq/web-xdk
src/ui/components/component.js
setupDomNodes
function setupDomNodes() { this.nodes = {}; this._findNodesWithin(this, (node, isComponent) => { const layerId = node.getAttribute && node.getAttribute('layer-id'); if (layerId) this.nodes[layerId] = node; if (isComponent) { if (!node.properties) node.properties = {}; node.properties.parentComponent = this; } }); }
javascript
function setupDomNodes() { this.nodes = {}; this._findNodesWithin(this, (node, isComponent) => { const layerId = node.getAttribute && node.getAttribute('layer-id'); if (layerId) this.nodes[layerId] = node; if (isComponent) { if (!node.properties) node.properties = {}; node.properties.parentComponent = this; } }); }
[ "function", "setupDomNodes", "(", ")", "{", "this", ".", "nodes", "=", "{", "}", ";", "this", ".", "_findNodesWithin", "(", "this", ",", "(", "node", ",", "isComponent", ")", "=>", "{", "const", "layerId", "=", "node", ".", "getAttribute", "&&", "node", ".", "getAttribute", "(", "'layer-id'", ")", ";", "if", "(", "layerId", ")", "this", ".", "nodes", "[", "layerId", "]", "=", "node", ";", "if", "(", "isComponent", ")", "{", "if", "(", "!", "node", ".", "properties", ")", "node", ".", "properties", "=", "{", "}", ";", "node", ".", "properties", ".", "parentComponent", "=", "this", ";", "}", "}", ")", ";", "}" ]
The setupDomNodes method looks at all child nodes of this node that have layer-id properties and indexes them in the `nodes` property. Typically, this node has child nodes loaded via its template, and ready by the time your `created` method is called. This call is made on your behalf prior to calling `created`, but if using templates after `created` is called, you may need to call this directly. @method setupDomNodes @protected
[ "The", "setupDomNodes", "method", "looks", "at", "all", "child", "nodes", "of", "this", "node", "that", "have", "layer", "-", "id", "properties", "and", "indexes", "them", "in", "the", "nodes", "property", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1550-L1562
41,055
layerhq/web-xdk
src/ui/components/component.js
_findNodesWithin
function _findNodesWithin(node, callback) { const children = node.childNodes; for (let i = 0; i < children.length; i++) { const innerNode = children[i]; if (innerNode instanceof HTMLElement) { const isLUIComponent = Boolean(ComponentsHash[innerNode.tagName.toLowerCase()]); const result = callback(innerNode, isLUIComponent); if (result) return result; // If its not a custom webcomponent with children that it manages and owns, iterate on it if (!isLUIComponent) { const innerResult = this._findNodesWithin(innerNode, callback); if (innerResult) return innerResult; } } } }
javascript
function _findNodesWithin(node, callback) { const children = node.childNodes; for (let i = 0; i < children.length; i++) { const innerNode = children[i]; if (innerNode instanceof HTMLElement) { const isLUIComponent = Boolean(ComponentsHash[innerNode.tagName.toLowerCase()]); const result = callback(innerNode, isLUIComponent); if (result) return result; // If its not a custom webcomponent with children that it manages and owns, iterate on it if (!isLUIComponent) { const innerResult = this._findNodesWithin(innerNode, callback); if (innerResult) return innerResult; } } } }
[ "function", "_findNodesWithin", "(", "node", ",", "callback", ")", "{", "const", "children", "=", "node", ".", "childNodes", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "children", ".", "length", ";", "i", "++", ")", "{", "const", "innerNode", "=", "children", "[", "i", "]", ";", "if", "(", "innerNode", "instanceof", "HTMLElement", ")", "{", "const", "isLUIComponent", "=", "Boolean", "(", "ComponentsHash", "[", "innerNode", ".", "tagName", ".", "toLowerCase", "(", ")", "]", ")", ";", "const", "result", "=", "callback", "(", "innerNode", ",", "isLUIComponent", ")", ";", "if", "(", "result", ")", "return", "result", ";", "// If its not a custom webcomponent with children that it manages and owns, iterate on it", "if", "(", "!", "isLUIComponent", ")", "{", "const", "innerResult", "=", "this", ".", "_findNodesWithin", "(", "innerNode", ",", "callback", ")", ";", "if", "(", "innerResult", ")", "return", "innerResult", ";", "}", "}", "}", "}" ]
Iterate over all child nodes generated by the template; skip all subcomponent's child nodes. If callback returns a value, then what is sought has been found; stop searching. The returned value is the return value for this function. If searching for ALL matches, do not return a value in your callback. @method _findNodesWithin @private @param {HTMLElement} node Node whose subtree should be called with the callback @param {Function} callback Function to call on each node in the tree @param {HTMLElement} callback.node Node that the callback is called on @param {Boolean} callback.isComponent Is the node a Component from this framework
[ "Iterate", "over", "all", "child", "nodes", "generated", "by", "the", "template", ";", "skip", "all", "subcomponent", "s", "child", "nodes", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1579-L1595
41,056
layerhq/web-xdk
src/ui/components/component.js
getTemplate
function getTemplate() { const tagName = this.tagName.toLocaleLowerCase(); if (ComponentsHash[tagName].style) { const styleNode = document.createElement('style'); styleNode.id = 'style-' + this.tagName.toLowerCase(); styleNode.innerHTML = ComponentsHash[tagName].style; document.getElementsByTagName('head')[0].appendChild(styleNode); ComponentsHash[tagName].style = ''; // insure it doesn't get added to head a second time } return ComponentsHash[tagName].template; }
javascript
function getTemplate() { const tagName = this.tagName.toLocaleLowerCase(); if (ComponentsHash[tagName].style) { const styleNode = document.createElement('style'); styleNode.id = 'style-' + this.tagName.toLowerCase(); styleNode.innerHTML = ComponentsHash[tagName].style; document.getElementsByTagName('head')[0].appendChild(styleNode); ComponentsHash[tagName].style = ''; // insure it doesn't get added to head a second time } return ComponentsHash[tagName].template; }
[ "function", "getTemplate", "(", ")", "{", "const", "tagName", "=", "this", ".", "tagName", ".", "toLocaleLowerCase", "(", ")", ";", "if", "(", "ComponentsHash", "[", "tagName", "]", ".", "style", ")", "{", "const", "styleNode", "=", "document", ".", "createElement", "(", "'style'", ")", ";", "styleNode", ".", "id", "=", "'style-'", "+", "this", ".", "tagName", ".", "toLowerCase", "(", ")", ";", "styleNode", ".", "innerHTML", "=", "ComponentsHash", "[", "tagName", "]", ".", "style", ";", "document", ".", "getElementsByTagName", "(", "'head'", ")", "[", "0", "]", ".", "appendChild", "(", "styleNode", ")", ";", "ComponentsHash", "[", "tagName", "]", ".", "style", "=", "''", ";", "// insure it doesn't get added to head a second time", "}", "return", "ComponentsHash", "[", "tagName", "]", ".", "template", ";", "}" ]
Return the template for this Component. Get the default template: ``` var template = widget.getTemplate(); ``` Typical components should not need to call this; this will be called automatically prior to calling the Component's `created` method. Some components wanting to reset dom to initial state may use this method explicitly: ``` var template = this.getTemplate(); var clone = document.importNode(template.content, true); this.appendChild(clone); this.setupDomNodes(); ``` @method getTemplate @protected @returns {HTMLTemplateElement}
[ "Return", "the", "template", "for", "this", "Component", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1620-L1631
41,057
layerhq/web-xdk
src/ui/components/component.js
trigger
function trigger(eventName, details) { const evt = new CustomEvent(eventName, { detail: details, bubbles: true, cancelable: true, }); this.dispatchEvent(evt); return !evt.defaultPrevented; }
javascript
function trigger(eventName, details) { const evt = new CustomEvent(eventName, { detail: details, bubbles: true, cancelable: true, }); this.dispatchEvent(evt); return !evt.defaultPrevented; }
[ "function", "trigger", "(", "eventName", ",", "details", ")", "{", "const", "evt", "=", "new", "CustomEvent", "(", "eventName", ",", "{", "detail", ":", "details", ",", "bubbles", ":", "true", ",", "cancelable", ":", "true", ",", "}", ")", ";", "this", ".", "dispatchEvent", "(", "evt", ")", ";", "return", "!", "evt", ".", "defaultPrevented", ";", "}" ]
Triggers a dom level event which bubbles up the dom. Call with an event name and a `detail` object: ``` this.trigger('something-happened', { someSortOf: 'value' }); ``` The `someSortOf` key, and any other keys you pass into that object can be accessed via `evt.detail.someSortOf` or `evt.detail.xxxx`: ``` // Listen for the something-happened event which because it bubbles up the dom, // can be listened for from any parent node document.body.addEventListener('something-happened', function(evt) { console.log(evt.detail.someSortOf); }); ``` {@link Layer.UI.Component#events} can be used to generate properties to go with your events, allowing the following widget property to be used: ``` this.onSomethingHappened = function(evt) { console.log(evt.detail.someSortOf); }); ``` Note that events may be canceled via `evt.preventDefault()` and your code may need to handle this: ``` if (this.trigger('something-is-happening')) { doSomething(); } else { cancelSomething(); } ``` @method trigger @protected @param {String} eventName @param {Object} detail @returns {Boolean} True if process should continue with its actions, false if application has canceled the default action using `evt.preventDefault()`
[ "Triggers", "a", "dom", "level", "event", "which", "bubbles", "up", "the", "dom", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1680-L1688
41,058
layerhq/web-xdk
src/ui/components/component.js
toggleClass
function toggleClass(...args) { const cssClass = args[0]; const enable = (args.length === 2) ? args[1] : !this.classList.contains(cssClass); this.classList[enable ? 'add' : 'remove'](cssClass); }
javascript
function toggleClass(...args) { const cssClass = args[0]; const enable = (args.length === 2) ? args[1] : !this.classList.contains(cssClass); this.classList[enable ? 'add' : 'remove'](cssClass); }
[ "function", "toggleClass", "(", "...", "args", ")", "{", "const", "cssClass", "=", "args", "[", "0", "]", ";", "const", "enable", "=", "(", "args", ".", "length", "===", "2", ")", "?", "args", "[", "1", "]", ":", "!", "this", ".", "classList", ".", "contains", "(", "cssClass", ")", ";", "this", ".", "classList", "[", "enable", "?", "'add'", ":", "'remove'", "]", "(", "cssClass", ")", ";", "}" ]
Toggle a CSS Class. Why do we have this? Well, sadly as long as we support IE11 which has an incorrect implementation of node.classList.toggle, we will have to do this ourselves. @method toggleClass @param {String} className @param {Boolean} [enable=!enable]
[ "Toggle", "a", "CSS", "Class", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1714-L1718
41,059
layerhq/web-xdk
src/ui/components/component.js
createElement
function createElement(tagName, properties) { const node = document.createElement(tagName); node.parentComponent = this; const ignore = ['parentNode', 'name', 'classList', 'noCreate']; Object.keys(properties).forEach((propName) => { if (ignore.indexOf(propName) === -1) node[propName] = properties[propName]; }); if (properties.classList) properties.classList.forEach(className => node.classList.add(className)); if (properties.parentNode) properties.parentNode.appendChild(node); if (properties.name) this.nodes[properties.name] = node; if (!properties.noCreate) { if (typeof CustomElements !== 'undefined') CustomElements.upgradeAll(node); if (node._onAfterCreate) node._onAfterCreate(); } return node; }
javascript
function createElement(tagName, properties) { const node = document.createElement(tagName); node.parentComponent = this; const ignore = ['parentNode', 'name', 'classList', 'noCreate']; Object.keys(properties).forEach((propName) => { if (ignore.indexOf(propName) === -1) node[propName] = properties[propName]; }); if (properties.classList) properties.classList.forEach(className => node.classList.add(className)); if (properties.parentNode) properties.parentNode.appendChild(node); if (properties.name) this.nodes[properties.name] = node; if (!properties.noCreate) { if (typeof CustomElements !== 'undefined') CustomElements.upgradeAll(node); if (node._onAfterCreate) node._onAfterCreate(); } return node; }
[ "function", "createElement", "(", "tagName", ",", "properties", ")", "{", "const", "node", "=", "document", ".", "createElement", "(", "tagName", ")", ";", "node", ".", "parentComponent", "=", "this", ";", "const", "ignore", "=", "[", "'parentNode'", ",", "'name'", ",", "'classList'", ",", "'noCreate'", "]", ";", "Object", ".", "keys", "(", "properties", ")", ".", "forEach", "(", "(", "propName", ")", "=>", "{", "if", "(", "ignore", ".", "indexOf", "(", "propName", ")", "===", "-", "1", ")", "node", "[", "propName", "]", "=", "properties", "[", "propName", "]", ";", "}", ")", ";", "if", "(", "properties", ".", "classList", ")", "properties", ".", "classList", ".", "forEach", "(", "className", "=>", "node", ".", "classList", ".", "add", "(", "className", ")", ")", ";", "if", "(", "properties", ".", "parentNode", ")", "properties", ".", "parentNode", ".", "appendChild", "(", "node", ")", ";", "if", "(", "properties", ".", "name", ")", "this", ".", "nodes", "[", "properties", ".", "name", "]", "=", "node", ";", "if", "(", "!", "properties", ".", "noCreate", ")", "{", "if", "(", "typeof", "CustomElements", "!==", "'undefined'", ")", "CustomElements", ".", "upgradeAll", "(", "node", ")", ";", "if", "(", "node", ".", "_onAfterCreate", ")", "node", ".", "_onAfterCreate", "(", ")", ";", "}", "return", "node", ";", "}" ]
Shorthand for `document.createElement` followed by a bunch of standard setup. ``` var avatar = this.createElement({ name: "myavatar", size: "large", users: [client.user], parentNode: this.nodes.avatarContainer }); console.log(avatar === this.nodes.myavatar); // returns true ``` TODO: Most `document.createElement` calls in this UI Framework should be updated to use this. Note that because all properties are initialized by this call, there is no need for asynchronous initialization, so unless suppressed with the `noCreate` parameter, all initialization is completed synchronously. @method createElement @param {String} tagName The type of HTMLElement to create (includes Layer.UI.Component instances) @param {Object} properties The properties to initialize the HTMLElement with @param {HTMLElement} [properties.parentNode] The node to setup as the `parentNode` of our new UI Component @param {String} [properties.name] Set `this.nodes[name] = newUIElement` @param {String[]} [properties.classList] Array of CSS Class names to add to the new UI Component @param {Boolean} [properties.noCreate=false] Do not call `_onAfterCreate()`; allow the lifecycle to flow asyncrhonously instead of rush it through synchronously.
[ "Shorthand", "for", "document", ".", "createElement", "followed", "by", "a", "bunch", "of", "standard", "setup", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1746-L1763
41,060
layerhq/web-xdk
src/ui/components/component.js
destroy
function destroy() { if (this.properties._internalState.onDestroyCalled) return; if (this.parentNode) { this.parentNode.removeChild(this); } Object.keys(this.nodes || {}).forEach((name) => { if (this.nodes[name] && this.nodes[name].destroy) this.nodes[name].destroy(); }); this.onDestroy(); }
javascript
function destroy() { if (this.properties._internalState.onDestroyCalled) return; if (this.parentNode) { this.parentNode.removeChild(this); } Object.keys(this.nodes || {}).forEach((name) => { if (this.nodes[name] && this.nodes[name].destroy) this.nodes[name].destroy(); }); this.onDestroy(); }
[ "function", "destroy", "(", ")", "{", "if", "(", "this", ".", "properties", ".", "_internalState", ".", "onDestroyCalled", ")", "return", ";", "if", "(", "this", ".", "parentNode", ")", "{", "this", ".", "parentNode", ".", "removeChild", "(", "this", ")", ";", "}", "Object", ".", "keys", "(", "this", ".", "nodes", "||", "{", "}", ")", ".", "forEach", "(", "(", "name", ")", "=>", "{", "if", "(", "this", ".", "nodes", "[", "name", "]", "&&", "this", ".", "nodes", "[", "name", "]", ".", "destroy", ")", "this", ".", "nodes", "[", "name", "]", ".", "destroy", "(", ")", ";", "}", ")", ";", "this", ".", "onDestroy", "(", ")", ";", "}" ]
Call this to destroy the UI Component. Destroying will cause it to be removed from its parent node, it will call destroy on all child nodes, and then call the {@link #onDestroy} method. > *Note* > > destroy is called to remove a component, but it is not a lifecycle method; a component that has been removed > from the DOM some otherway will cause {@link #onDestroy} to be called but `destroy()` will _not_ be called. @method destroy
[ "Call", "this", "to", "destroy", "the", "UI", "Component", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L2078-L2087
41,061
layerhq/web-xdk
src/ui/components/component.js
_registerAll
function _registerAll() { if (!registerAllCalled) { registerAllCalled = true; Object.keys(ComponentsHash) .filter(tagName => typeof ComponentsHash[tagName] !== 'function') .forEach(tagName => _registerComponent(tagName)); } }
javascript
function _registerAll() { if (!registerAllCalled) { registerAllCalled = true; Object.keys(ComponentsHash) .filter(tagName => typeof ComponentsHash[tagName] !== 'function') .forEach(tagName => _registerComponent(tagName)); } }
[ "function", "_registerAll", "(", ")", "{", "if", "(", "!", "registerAllCalled", ")", "{", "registerAllCalled", "=", "true", ";", "Object", ".", "keys", "(", "ComponentsHash", ")", ".", "filter", "(", "tagName", "=>", "typeof", "ComponentsHash", "[", "tagName", "]", "!==", "'function'", ")", ".", "forEach", "(", "tagName", "=>", "_registerComponent", "(", "tagName", ")", ")", ";", "}", "}" ]
Registers all defined components with the browser as WebComponents. This is called by `Layer.init()` and should not be called directly. @private @method _registerAll
[ "Registers", "all", "defined", "components", "with", "the", "browser", "as", "WebComponents", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L2137-L2144
41,062
layerhq/web-xdk
src/ui/components/layer-message-list/layer-message-item-mixin.js
onRender
function onRender() { try { // Setup the layer-sender-name if (this.nodes.sender) { this.nodes.sender.innerHTML = this.item.sender.displayName; } if (this.nodes.avatar) { this.nodes.avatar.users = [this.item.sender]; } // Setup the layer-date if (this.nodes.date && !this.item.isNew()) { if (this.dateRenderer) this.nodes.date.dateRenderer = this.dateRenderer; this.nodes.date.date = this.item.sentAt; } // Setup the layer-message-status if (this.nodes.status && this.messageStatusRenderer) { this.nodes.status.messageStatusRenderer = this.messageStatusRenderer; } // Setup the layer-delete if (this.nodes.delete) { this.nodes.delete.enabled = this.getDeleteEnabled ? this.getDeleteEnabled(this.properties.item) : true; } // Generate the renderer for this Message's MessageParts. this._applyContentTag(); // Render all mutable data this.onRerender(); } catch (err) { logger.error('layer-message-item.render(): ', err); } }
javascript
function onRender() { try { // Setup the layer-sender-name if (this.nodes.sender) { this.nodes.sender.innerHTML = this.item.sender.displayName; } if (this.nodes.avatar) { this.nodes.avatar.users = [this.item.sender]; } // Setup the layer-date if (this.nodes.date && !this.item.isNew()) { if (this.dateRenderer) this.nodes.date.dateRenderer = this.dateRenderer; this.nodes.date.date = this.item.sentAt; } // Setup the layer-message-status if (this.nodes.status && this.messageStatusRenderer) { this.nodes.status.messageStatusRenderer = this.messageStatusRenderer; } // Setup the layer-delete if (this.nodes.delete) { this.nodes.delete.enabled = this.getDeleteEnabled ? this.getDeleteEnabled(this.properties.item) : true; } // Generate the renderer for this Message's MessageParts. this._applyContentTag(); // Render all mutable data this.onRerender(); } catch (err) { logger.error('layer-message-item.render(): ', err); } }
[ "function", "onRender", "(", ")", "{", "try", "{", "// Setup the layer-sender-name", "if", "(", "this", ".", "nodes", ".", "sender", ")", "{", "this", ".", "nodes", ".", "sender", ".", "innerHTML", "=", "this", ".", "item", ".", "sender", ".", "displayName", ";", "}", "if", "(", "this", ".", "nodes", ".", "avatar", ")", "{", "this", ".", "nodes", ".", "avatar", ".", "users", "=", "[", "this", ".", "item", ".", "sender", "]", ";", "}", "// Setup the layer-date", "if", "(", "this", ".", "nodes", ".", "date", "&&", "!", "this", ".", "item", ".", "isNew", "(", ")", ")", "{", "if", "(", "this", ".", "dateRenderer", ")", "this", ".", "nodes", ".", "date", ".", "dateRenderer", "=", "this", ".", "dateRenderer", ";", "this", ".", "nodes", ".", "date", ".", "date", "=", "this", ".", "item", ".", "sentAt", ";", "}", "// Setup the layer-message-status", "if", "(", "this", ".", "nodes", ".", "status", "&&", "this", ".", "messageStatusRenderer", ")", "{", "this", ".", "nodes", ".", "status", ".", "messageStatusRenderer", "=", "this", ".", "messageStatusRenderer", ";", "}", "// Setup the layer-delete", "if", "(", "this", ".", "nodes", ".", "delete", ")", "{", "this", ".", "nodes", ".", "delete", ".", "enabled", "=", "this", ".", "getDeleteEnabled", "?", "this", ".", "getDeleteEnabled", "(", "this", ".", "properties", ".", "item", ")", ":", "true", ";", "}", "// Generate the renderer for this Message's MessageParts.", "this", ".", "_applyContentTag", "(", ")", ";", "// Render all mutable data", "this", ".", "onRerender", "(", ")", ";", "}", "catch", "(", "err", ")", "{", "logger", ".", "error", "(", "'layer-message-item.render(): '", ",", "err", ")", ";", "}", "}" ]
Lifecycle method sets up the Message to render
[ "Lifecycle", "method", "sets", "up", "the", "Message", "to", "render" ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/layer-message-list/layer-message-item-mixin.js#L237-L273
41,063
Streampunk/ledger
model/Versionned.js
Versionned
function Versionned(id, version, label) { /** * Globally unique UUID identifier for the resource. * @type {string} * @readonly */ this.id = this.generateID(id); /** * String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;) * indicating precisely when an attribute of the resource last changed. * @type {string} * @readonly */ this.version = this.generateVersion(version); /** * Freeform string label for the resource. * @type {string} * @readonly */ this.label = this.generateLabel(label); return immutable(this, {prototype: Versionned.prototype}); }
javascript
function Versionned(id, version, label) { /** * Globally unique UUID identifier for the resource. * @type {string} * @readonly */ this.id = this.generateID(id); /** * String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;) * indicating precisely when an attribute of the resource last changed. * @type {string} * @readonly */ this.version = this.generateVersion(version); /** * Freeform string label for the resource. * @type {string} * @readonly */ this.label = this.generateLabel(label); return immutable(this, {prototype: Versionned.prototype}); }
[ "function", "Versionned", "(", "id", ",", "version", ",", "label", ")", "{", "/**\n * Globally unique UUID identifier for the resource.\n * @type {string}\n * @readonly\n */", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "/**\n * String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;)\n * indicating precisely when an attribute of the resource last changed.\n * @type {string}\n * @readonly\n */", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "/**\n * Freeform string label for the resource.\n * @type {string}\n * @readonly\n */", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Versionned", ".", "prototype", "}", ")", ";", "}" ]
Supertype of every class that has UUID identity, version numbers and labels. Methods are designed to be mixed in piecemeal as required. @constructor @param {string} id Globally unique UUID identifier for the resource. @param {string} version String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds<em>&gt;) indicating precisely when an attribute of the resource last changed. @param {string} label Freeform string label for the resource.
[ "Supertype", "of", "every", "class", "that", "has", "UUID", "identity", "version", "numbers", "and", "labels", ".", "Methods", "are", "designed", "to", "be", "mixed", "in", "piecemeal", "as", "required", "." ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Versionned.js#L41-L62
41,064
layerhq/web-xdk
src/core/root.js
initClass
function initClass(newClass, className, namespace) { // Make sure our new class has a name property try { if (newClass.name !== className) newClass.altName = className; } catch (e) { // No-op } // Make sure our new class has a _supportedEvents, _ignoredEvents, _inObjectIgnore and EVENTS properties if (!newClass._supportedEvents) newClass._supportedEvents = Root._supportedEvents; if (!newClass._ignoredEvents) newClass._ignoredEvents = Root._ignoredEvents; if (newClass.mixins) { newClass.mixins.forEach((mixin) => { if (mixin.events) newClass._supportedEvents = newClass._supportedEvents.concat(mixin.events); Object.keys(mixin.staticMethods || {}) .forEach(methodName => (newClass[methodName] = mixin.staticMethods[methodName])); if (mixin.properties) { Object.keys(mixin.properties).forEach((key) => { newClass.prototype[key] = mixin.properties[key]; }); } if (mixin.methods) { Object.keys(mixin.methods).forEach((key) => { newClass.prototype[key] = mixin.methods[key]; }); } }); } // Generate a list of properties for this class; we don't include any // properties from Layer.Core.Root const keys = Object.keys(newClass.prototype).filter(key => newClass.prototype.hasOwnProperty(key) && !Root.prototype.hasOwnProperty(key) && typeof newClass.prototype[key] !== 'function'); // Define getters/setters for any property that has __adjust or __update methods defined keys.forEach(name => defineProperty(newClass, name)); if (namespace) namespace[className] = newClass; }
javascript
function initClass(newClass, className, namespace) { // Make sure our new class has a name property try { if (newClass.name !== className) newClass.altName = className; } catch (e) { // No-op } // Make sure our new class has a _supportedEvents, _ignoredEvents, _inObjectIgnore and EVENTS properties if (!newClass._supportedEvents) newClass._supportedEvents = Root._supportedEvents; if (!newClass._ignoredEvents) newClass._ignoredEvents = Root._ignoredEvents; if (newClass.mixins) { newClass.mixins.forEach((mixin) => { if (mixin.events) newClass._supportedEvents = newClass._supportedEvents.concat(mixin.events); Object.keys(mixin.staticMethods || {}) .forEach(methodName => (newClass[methodName] = mixin.staticMethods[methodName])); if (mixin.properties) { Object.keys(mixin.properties).forEach((key) => { newClass.prototype[key] = mixin.properties[key]; }); } if (mixin.methods) { Object.keys(mixin.methods).forEach((key) => { newClass.prototype[key] = mixin.methods[key]; }); } }); } // Generate a list of properties for this class; we don't include any // properties from Layer.Core.Root const keys = Object.keys(newClass.prototype).filter(key => newClass.prototype.hasOwnProperty(key) && !Root.prototype.hasOwnProperty(key) && typeof newClass.prototype[key] !== 'function'); // Define getters/setters for any property that has __adjust or __update methods defined keys.forEach(name => defineProperty(newClass, name)); if (namespace) namespace[className] = newClass; }
[ "function", "initClass", "(", "newClass", ",", "className", ",", "namespace", ")", "{", "// Make sure our new class has a name property", "try", "{", "if", "(", "newClass", ".", "name", "!==", "className", ")", "newClass", ".", "altName", "=", "className", ";", "}", "catch", "(", "e", ")", "{", "// No-op", "}", "// Make sure our new class has a _supportedEvents, _ignoredEvents, _inObjectIgnore and EVENTS properties", "if", "(", "!", "newClass", ".", "_supportedEvents", ")", "newClass", ".", "_supportedEvents", "=", "Root", ".", "_supportedEvents", ";", "if", "(", "!", "newClass", ".", "_ignoredEvents", ")", "newClass", ".", "_ignoredEvents", "=", "Root", ".", "_ignoredEvents", ";", "if", "(", "newClass", ".", "mixins", ")", "{", "newClass", ".", "mixins", ".", "forEach", "(", "(", "mixin", ")", "=>", "{", "if", "(", "mixin", ".", "events", ")", "newClass", ".", "_supportedEvents", "=", "newClass", ".", "_supportedEvents", ".", "concat", "(", "mixin", ".", "events", ")", ";", "Object", ".", "keys", "(", "mixin", ".", "staticMethods", "||", "{", "}", ")", ".", "forEach", "(", "methodName", "=>", "(", "newClass", "[", "methodName", "]", "=", "mixin", ".", "staticMethods", "[", "methodName", "]", ")", ")", ";", "if", "(", "mixin", ".", "properties", ")", "{", "Object", ".", "keys", "(", "mixin", ".", "properties", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "newClass", ".", "prototype", "[", "key", "]", "=", "mixin", ".", "properties", "[", "key", "]", ";", "}", ")", ";", "}", "if", "(", "mixin", ".", "methods", ")", "{", "Object", ".", "keys", "(", "mixin", ".", "methods", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "newClass", ".", "prototype", "[", "key", "]", "=", "mixin", ".", "methods", "[", "key", "]", ";", "}", ")", ";", "}", "}", ")", ";", "}", "// Generate a list of properties for this class; we don't include any", "// properties from Layer.Core.Root", "const", "keys", "=", "Object", ".", "keys", "(", "newClass", ".", "prototype", ")", ".", "filter", "(", "key", "=>", "newClass", ".", "prototype", ".", "hasOwnProperty", "(", "key", ")", "&&", "!", "Root", ".", "prototype", ".", "hasOwnProperty", "(", "key", ")", "&&", "typeof", "newClass", ".", "prototype", "[", "key", "]", "!==", "'function'", ")", ";", "// Define getters/setters for any property that has __adjust or __update methods defined", "keys", ".", "forEach", "(", "name", "=>", "defineProperty", "(", "newClass", ",", "name", ")", ")", ";", "if", "(", "namespace", ")", "namespace", "[", "className", "]", "=", "newClass", ";", "}" ]
Initialize a class definition that is a subclass of Root. ``` class myClass extends Root { } Root.initClass(myClass, 'myClass'); console.log(Layer.Core.myClass); ``` With namespace: ``` const MyNameSpace = {}; class myClass extends Root { } Root.initClass(myClass, 'myClass', MyNameSpace); console.log(MyNameSpace.myClass); ``` Defining a class without calling this method means * none of the property getters/setters/adjusters will work; * Mixins won't be used * _supportedEvents won't be setup which means no events can be subscribed to on this class @method initClass @static @param {Function} newClass Class definition @param {String} className Class name @param {Object} [namespace=] Object to write this class definition to
[ "Initialize", "a", "class", "definition", "that", "is", "a", "subclass", "of", "Root", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/core/root.js#L661-L703
41,065
Streampunk/ledger
model/Receiver.js
Receiver
function Receiver(id, version, label, description, format, caps, tags, device_id, transport, subscription) { // Globally unique identifier for the Receiver this.id = this.generateID(id); // String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating // precisely when an attribute of the resource last changed. this.version = this.generateVersion(version); // Freeform string label for the Receiver this.label = this.generateLabel(label); // Detailed description of the Receiver this.description = this.generateDescription(description); // Type of Flow accepted by the Receiver as a URN this.format = this.generateFormat(format); // Capabilities (not yet defined) this.caps = this.generateCaps(caps); // Key value set of freeform string tags to aid in filtering sources. // Values should be represented as an array of strings. Can be empty. this.tags = this.generateTags(tags); // Device ID which this Receiver forms part of. this.device_id = this.generateDeviceID(device_id); // Transport type accepted by the Receiver in URN format this.transport = this.generateTransport(transport); // Object containing the 'sender_id' currently subscribed to. Sender_id // should be null on initialisation. this.subscription = this.generateSubscription(subscription); return immutable(this, { prototype : Receiver.prototype }); }
javascript
function Receiver(id, version, label, description, format, caps, tags, device_id, transport, subscription) { // Globally unique identifier for the Receiver this.id = this.generateID(id); // String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating // precisely when an attribute of the resource last changed. this.version = this.generateVersion(version); // Freeform string label for the Receiver this.label = this.generateLabel(label); // Detailed description of the Receiver this.description = this.generateDescription(description); // Type of Flow accepted by the Receiver as a URN this.format = this.generateFormat(format); // Capabilities (not yet defined) this.caps = this.generateCaps(caps); // Key value set of freeform string tags to aid in filtering sources. // Values should be represented as an array of strings. Can be empty. this.tags = this.generateTags(tags); // Device ID which this Receiver forms part of. this.device_id = this.generateDeviceID(device_id); // Transport type accepted by the Receiver in URN format this.transport = this.generateTransport(transport); // Object containing the 'sender_id' currently subscribed to. Sender_id // should be null on initialisation. this.subscription = this.generateSubscription(subscription); return immutable(this, { prototype : Receiver.prototype }); }
[ "function", "Receiver", "(", "id", ",", "version", ",", "label", ",", "description", ",", "format", ",", "caps", ",", "tags", ",", "device_id", ",", "transport", ",", "subscription", ")", "{", "// Globally unique identifier for the Receiver\r", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "// String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating\r", "// precisely when an attribute of the resource last changed.\r", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "// Freeform string label for the Receiver\r", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "// Detailed description of the Receiver\r", "this", ".", "description", "=", "this", ".", "generateDescription", "(", "description", ")", ";", "// Type of Flow accepted by the Receiver as a URN\r", "this", ".", "format", "=", "this", ".", "generateFormat", "(", "format", ")", ";", "// Capabilities (not yet defined)\r", "this", ".", "caps", "=", "this", ".", "generateCaps", "(", "caps", ")", ";", "// Key value set of freeform string tags to aid in filtering sources.\r", "// Values should be represented as an array of strings. Can be empty.\r", "this", ".", "tags", "=", "this", ".", "generateTags", "(", "tags", ")", ";", "// Device ID which this Receiver forms part of.\r", "this", ".", "device_id", "=", "this", ".", "generateDeviceID", "(", "device_id", ")", ";", "// Transport type accepted by the Receiver in URN format\r", "this", ".", "transport", "=", "this", ".", "generateTransport", "(", "transport", ")", ";", "// Object containing the 'sender_id' currently subscribed to. Sender_id\r", "// should be null on initialisation.\r", "this", ".", "subscription", "=", "this", ".", "generateSubscription", "(", "subscription", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Receiver", ".", "prototype", "}", ")", ";", "}" ]
Describes a receiver
[ "Describes", "a", "receiver" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Receiver.js#L21-L47
41,066
Streampunk/ledger
api/NodeAPI.js
registerResources
function registerResources(rs) { registerPromise = registerPromise.then(() => { return Promise.all(rs.map((r) => { return Promise.denodeify(pushResource)(r); })); }); }
javascript
function registerResources(rs) { registerPromise = registerPromise.then(() => { return Promise.all(rs.map((r) => { return Promise.denodeify(pushResource)(r); })); }); }
[ "function", "registerResources", "(", "rs", ")", "{", "registerPromise", "=", "registerPromise", ".", "then", "(", "(", ")", "=>", "{", "return", "Promise", ".", "all", "(", "rs", ".", "map", "(", "(", "r", ")", "=>", "{", "return", "Promise", ".", "denodeify", "(", "pushResource", ")", "(", "r", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}" ]
only use registerResources for independent resources
[ "only", "use", "registerResources", "for", "independent", "resources" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/api/NodeAPI.js#L680-L684
41,067
DeMille/node-usbmux
bin/cli.js
info
function info() { if (argv.verbose !== 1) return; var args = Array.prototype.slice.call(arguments); if (!args[args.length-1]) args.pop(); // if last arg is undefined, remove it console.log.apply(console, args); }
javascript
function info() { if (argv.verbose !== 1) return; var args = Array.prototype.slice.call(arguments); if (!args[args.length-1]) args.pop(); // if last arg is undefined, remove it console.log.apply(console, args); }
[ "function", "info", "(", ")", "{", "if", "(", "argv", ".", "verbose", "!==", "1", ")", "return", ";", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "if", "(", "!", "args", "[", "args", ".", "length", "-", "1", "]", ")", "args", ".", "pop", "(", ")", ";", "// if last arg is undefined, remove it", "console", ".", "log", ".", "apply", "(", "console", ",", "args", ")", ";", "}" ]
Shows debugging info only for verbosity = 1 @param {*...} arguments
[ "Shows", "debugging", "info", "only", "for", "verbosity", "=", "1" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/bin/cli.js#L32-L37
41,068
DeMille/node-usbmux
bin/cli.js
onErr
function onErr(err) { // local port is in use if (err.code === 'EADDRINUSE') { panic('Local port is in use \nFailing...'); } // usbmux not there if (err.code === 'ECONNREFUSED' || err.code === 'EADDRNOTAVAIL') { panic('Usbmuxd not found at', usbmux.address, '\nFailing...'); } // other panic('%s \nFailing...', err); }
javascript
function onErr(err) { // local port is in use if (err.code === 'EADDRINUSE') { panic('Local port is in use \nFailing...'); } // usbmux not there if (err.code === 'ECONNREFUSED' || err.code === 'EADDRNOTAVAIL') { panic('Usbmuxd not found at', usbmux.address, '\nFailing...'); } // other panic('%s \nFailing...', err); }
[ "function", "onErr", "(", "err", ")", "{", "// local port is in use", "if", "(", "err", ".", "code", "===", "'EADDRINUSE'", ")", "{", "panic", "(", "'Local port is in use \\nFailing...'", ")", ";", "}", "// usbmux not there", "if", "(", "err", ".", "code", "===", "'ECONNREFUSED'", "||", "err", ".", "code", "===", "'EADDRNOTAVAIL'", ")", "{", "panic", "(", "'Usbmuxd not found at'", ",", "usbmux", ".", "address", ",", "'\\nFailing...'", ")", ";", "}", "// other", "panic", "(", "'%s \\nFailing...'", ",", "err", ")", ";", "}" ]
Error handler for listener and relay @param {Error} err
[ "Error", "handler", "for", "listener", "and", "relay" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/bin/cli.js#L54-L65
41,069
DeMille/node-usbmux
bin/cli.js
listenForDevices
function listenForDevices() { console.log('Listening for connected devices... \n'); usbmux.createListener() .on('error', onErr) .on('attached', function(udid) { console.log('Device found: ', udid); }) .on('detached', function(udid) { console.log('Device removed: ', udid); }); }
javascript
function listenForDevices() { console.log('Listening for connected devices... \n'); usbmux.createListener() .on('error', onErr) .on('attached', function(udid) { console.log('Device found: ', udid); }) .on('detached', function(udid) { console.log('Device removed: ', udid); }); }
[ "function", "listenForDevices", "(", ")", "{", "console", ".", "log", "(", "'Listening for connected devices... \\n'", ")", ";", "usbmux", ".", "createListener", "(", ")", ".", "on", "(", "'error'", ",", "onErr", ")", ".", "on", "(", "'attached'", ",", "function", "(", "udid", ")", "{", "console", ".", "log", "(", "'Device found: '", ",", "udid", ")", ";", "}", ")", ".", "on", "(", "'detached'", ",", "function", "(", "udid", ")", "{", "console", ".", "log", "(", "'Device removed: '", ",", "udid", ")", ";", "}", ")", ";", "}" ]
Listen for and report connected devices
[ "Listen", "for", "and", "report", "connected", "devices" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/bin/cli.js#L70-L81
41,070
DeMille/node-usbmux
bin/cli.js
startRelay
function startRelay(portPair) { var devicePort = portPair[0] , relayPort = portPair[1]; console.log('Starting relay from local port: %s -> device port: %s', relayPort, devicePort); new usbmux.Relay(devicePort, relayPort, {udid: argv.udid}) .on('error', onErr) .on('warning', console.log.bind(console, 'Warning: device not found...')) .on('ready', info.bind(this, 'Device ready: ')) .on('attached', info.bind(this, 'Device attached: ')) .on('detached', info.bind(this, 'Device detached: ')) .on('connect', info.bind(this, 'New connection to relay started.')) .on('disconnect', info.bind(this, 'Connection to relay closed.')) .on('close', info.bind(this, 'Relay has closed.')); }
javascript
function startRelay(portPair) { var devicePort = portPair[0] , relayPort = portPair[1]; console.log('Starting relay from local port: %s -> device port: %s', relayPort, devicePort); new usbmux.Relay(devicePort, relayPort, {udid: argv.udid}) .on('error', onErr) .on('warning', console.log.bind(console, 'Warning: device not found...')) .on('ready', info.bind(this, 'Device ready: ')) .on('attached', info.bind(this, 'Device attached: ')) .on('detached', info.bind(this, 'Device detached: ')) .on('connect', info.bind(this, 'New connection to relay started.')) .on('disconnect', info.bind(this, 'Connection to relay closed.')) .on('close', info.bind(this, 'Relay has closed.')); }
[ "function", "startRelay", "(", "portPair", ")", "{", "var", "devicePort", "=", "portPair", "[", "0", "]", ",", "relayPort", "=", "portPair", "[", "1", "]", ";", "console", ".", "log", "(", "'Starting relay from local port: %s -> device port: %s'", ",", "relayPort", ",", "devicePort", ")", ";", "new", "usbmux", ".", "Relay", "(", "devicePort", ",", "relayPort", ",", "{", "udid", ":", "argv", ".", "udid", "}", ")", ".", "on", "(", "'error'", ",", "onErr", ")", ".", "on", "(", "'warning'", ",", "console", ".", "log", ".", "bind", "(", "console", ",", "'Warning: device not found...'", ")", ")", ".", "on", "(", "'ready'", ",", "info", ".", "bind", "(", "this", ",", "'Device ready: '", ")", ")", ".", "on", "(", "'attached'", ",", "info", ".", "bind", "(", "this", ",", "'Device attached: '", ")", ")", ".", "on", "(", "'detached'", ",", "info", ".", "bind", "(", "this", ",", "'Device detached: '", ")", ")", ".", "on", "(", "'connect'", ",", "info", ".", "bind", "(", "this", ",", "'New connection to relay started.'", ")", ")", ".", "on", "(", "'disconnect'", ",", "info", ".", "bind", "(", "this", ",", "'Connection to relay closed.'", ")", ")", ".", "on", "(", "'close'", ",", "info", ".", "bind", "(", "this", ",", "'Relay has closed.'", ")", ")", ";", "}" ]
Start a new relay from a pair of given ports @param {integer[]} portPair - [devicePort, relayPort]
[ "Start", "a", "new", "relay", "from", "a", "pair", "of", "given", "ports" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/bin/cli.js#L111-L127
41,071
Streampunk/ledger
model/Source.js
Source
function Source(id, version, label, description, format, caps, tags, device_id, parents) { // Globally unique identifier for the Source this.id = this.generateID(id); // String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating // precisely when an attribute of the resource last changed this.version = this.generateVersion(version); // Freeform string label for the Source this.label = this.generateLabel(label); // Detailed description of the Source this.description = this.generateDescription(description); // Format of the data coming from the Source as a URN this.format = this.generateFormat(format); // Capabilities (not yet defined) this.caps = this.generateCaps(caps); // Key value set of freeform string tags to aid in filtering Sources. Values // should be represented as an array of strings. Can be empty. this.tags = this.generateTags(tags); // Globally unique identifier for the Device which initially created the Source this.device_id = this.generateDeviceID(device_id); // Array of UUIDs representing the Source IDs of Grains which came together at // the input to this Source (may change over the lifetime of this Source) this.parents = this.generateParents(parents); return immutable(this, { prototype: Source.prototype }); }
javascript
function Source(id, version, label, description, format, caps, tags, device_id, parents) { // Globally unique identifier for the Source this.id = this.generateID(id); // String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating // precisely when an attribute of the resource last changed this.version = this.generateVersion(version); // Freeform string label for the Source this.label = this.generateLabel(label); // Detailed description of the Source this.description = this.generateDescription(description); // Format of the data coming from the Source as a URN this.format = this.generateFormat(format); // Capabilities (not yet defined) this.caps = this.generateCaps(caps); // Key value set of freeform string tags to aid in filtering Sources. Values // should be represented as an array of strings. Can be empty. this.tags = this.generateTags(tags); // Globally unique identifier for the Device which initially created the Source this.device_id = this.generateDeviceID(device_id); // Array of UUIDs representing the Source IDs of Grains which came together at // the input to this Source (may change over the lifetime of this Source) this.parents = this.generateParents(parents); return immutable(this, { prototype: Source.prototype }); }
[ "function", "Source", "(", "id", ",", "version", ",", "label", ",", "description", ",", "format", ",", "caps", ",", "tags", ",", "device_id", ",", "parents", ")", "{", "// Globally unique identifier for the Source\r", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "// String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating\r", "// precisely when an attribute of the resource last changed\r", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "// Freeform string label for the Source\r", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "// Detailed description of the Source\r", "this", ".", "description", "=", "this", ".", "generateDescription", "(", "description", ")", ";", "// Format of the data coming from the Source as a URN\r", "this", ".", "format", "=", "this", ".", "generateFormat", "(", "format", ")", ";", "// Capabilities (not yet defined)\r", "this", ".", "caps", "=", "this", ".", "generateCaps", "(", "caps", ")", ";", "// Key value set of freeform string tags to aid in filtering Sources. Values\r", "// should be represented as an array of strings. Can be empty.\r", "this", ".", "tags", "=", "this", ".", "generateTags", "(", "tags", ")", ";", "// Globally unique identifier for the Device which initially created the Source\r", "this", ".", "device_id", "=", "this", ".", "generateDeviceID", "(", "device_id", ")", ";", "// Array of UUIDs representing the Source IDs of Grains which came together at\r", "// the input to this Source (may change over the lifetime of this Source)\r", "this", ".", "parents", "=", "this", ".", "generateParents", "(", "parents", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Source", ".", "prototype", "}", ")", ";", "}" ]
Describes a source
[ "Describes", "a", "source" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Source.js#L21-L46
41,072
Streampunk/ledger
api/RegistrationAPI.js
validStore
function validStore(store) { return store && typeof store.getNodes === 'function' && typeof store.getNode === 'function' && typeof store.getDevices === 'function' && typeof store.getDevice === 'function' && typeof store.getSources === 'function' && typeof store.getSource === 'function' && typeof store.getSenders === 'function' && typeof store.getSender === 'function' && typeof store.getReceivers === 'function' && typeof store.getReceiver === 'function' && typeof store.getFlows === 'function' && typeof store.getFlow === 'function'; // TODO add more of the required methods ... or drop this check? }
javascript
function validStore(store) { return store && typeof store.getNodes === 'function' && typeof store.getNode === 'function' && typeof store.getDevices === 'function' && typeof store.getDevice === 'function' && typeof store.getSources === 'function' && typeof store.getSource === 'function' && typeof store.getSenders === 'function' && typeof store.getSender === 'function' && typeof store.getReceivers === 'function' && typeof store.getReceiver === 'function' && typeof store.getFlows === 'function' && typeof store.getFlow === 'function'; // TODO add more of the required methods ... or drop this check? }
[ "function", "validStore", "(", "store", ")", "{", "return", "store", "&&", "typeof", "store", ".", "getNodes", "===", "'function'", "&&", "typeof", "store", ".", "getNode", "===", "'function'", "&&", "typeof", "store", ".", "getDevices", "===", "'function'", "&&", "typeof", "store", ".", "getDevice", "===", "'function'", "&&", "typeof", "store", ".", "getSources", "===", "'function'", "&&", "typeof", "store", ".", "getSource", "===", "'function'", "&&", "typeof", "store", ".", "getSenders", "===", "'function'", "&&", "typeof", "store", ".", "getSender", "===", "'function'", "&&", "typeof", "store", ".", "getReceivers", "===", "'function'", "&&", "typeof", "store", ".", "getReceiver", "===", "'function'", "&&", "typeof", "store", ".", "getFlows", "===", "'function'", "&&", "typeof", "store", ".", "getFlow", "===", "'function'", ";", "// TODO add more of the required methods ... or drop this check?\r", "}" ]
Check that a store has a sufficient contract for this API
[ "Check", "that", "a", "store", "has", "a", "sufficient", "contract", "for", "this", "API" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/api/RegistrationAPI.js#L460-L475
41,073
Streampunk/ledger
api/NodeRAMStore.js
checkSkip
function checkSkip (skip, keys) { if (skip && typeof skip === 'string') skip = +skip; if (!skip || Number(skip) !== skip || skip % 1 !== 0 || skip < 0) skip = 0; if (skip > keys.length) skip = keys.length; return skip; }
javascript
function checkSkip (skip, keys) { if (skip && typeof skip === 'string') skip = +skip; if (!skip || Number(skip) !== skip || skip % 1 !== 0 || skip < 0) skip = 0; if (skip > keys.length) skip = keys.length; return skip; }
[ "function", "checkSkip", "(", "skip", ",", "keys", ")", "{", "if", "(", "skip", "&&", "typeof", "skip", "===", "'string'", ")", "skip", "=", "+", "skip", ";", "if", "(", "!", "skip", "||", "Number", "(", "skip", ")", "!==", "skip", "||", "skip", "%", "1", "!==", "0", "||", "skip", "<", "0", ")", "skip", "=", "0", ";", "if", "(", "skip", ">", "keys", ".", "length", ")", "skip", "=", "keys", ".", "length", ";", "return", "skip", ";", "}" ]
Check that the skip parameter is withing range, or set defaults
[ "Check", "that", "the", "skip", "parameter", "is", "withing", "range", "or", "set", "defaults" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/api/NodeRAMStore.js#L34-L41
41,074
Streampunk/ledger
api/NodeRAMStore.js
checkLimit
function checkLimit (limit, keys) { if (limit && typeof limit === 'string') limit = +limit; if (!limit || Number(limit) !== limit || limit % 1 !== 0 || limit > keys.length) limit = keys.length; if (limit < 0) limit = 0; return limit; }
javascript
function checkLimit (limit, keys) { if (limit && typeof limit === 'string') limit = +limit; if (!limit || Number(limit) !== limit || limit % 1 !== 0 || limit > keys.length) limit = keys.length; if (limit < 0) limit = 0; return limit; }
[ "function", "checkLimit", "(", "limit", ",", "keys", ")", "{", "if", "(", "limit", "&&", "typeof", "limit", "===", "'string'", ")", "limit", "=", "+", "limit", ";", "if", "(", "!", "limit", "||", "Number", "(", "limit", ")", "!==", "limit", "||", "limit", "%", "1", "!==", "0", "||", "limit", ">", "keys", ".", "length", ")", "limit", "=", "keys", ".", "length", ";", "if", "(", "limit", "<", "0", ")", "limit", "=", "0", ";", "return", "limit", ";", "}" ]
Check that the limit parameter is withing range, or set defaults
[ "Check", "that", "the", "limit", "parameter", "is", "withing", "range", "or", "set", "defaults" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/api/NodeRAMStore.js#L44-L51
41,075
Streampunk/ledger
api/NodeRAMStore.js
getCollection
function getCollection(items, query, cb, argsLength) { var skip = 0, limit = Number.MAX_SAFE_INTEGER; setImmediate(function() { if (argsLength === 1) { cb = query; } else { skip = (query.skip) ? query.skip : 0; limit = (query.limit) ? query.limit : Number.MAX_SAFE_INTEGER; } var sortedKeys = Object.keys(items); var qKeys = remove(remove(Object.keys(query), /skip/), /limit/); qKeys.forEach(function (k) { try { var re = new RegExp(query[k]); sortedKeys = sortedKeys.filter(function (l) { return items[l][k].toString().match(re); }); } catch (e) { console.error(`Problem filtering collection for parameter ${k}.`, e.message); } }); skip = checkSkip(skip, sortedKeys); limit = checkLimit(limit, sortedKeys); if (sortedKeys.length === 0 || limit === 0 || skip >= sortedKeys.length) { return cb(null, [], sortedKeys.length, 1, 1, 0); } var pages = Math.ceil(sortedKeys.length / limit); var pageOf = Math.ceil(skip / limit) + 1; var itemArray = new Array(); for ( var x = skip ; x < Math.min(skip + limit, sortedKeys.length) ; x++ ) { itemArray.push(items[sortedKeys[x]]); } cb(null, itemArray, sortedKeys.length, pageOf, pages, itemArray.length); }); }
javascript
function getCollection(items, query, cb, argsLength) { var skip = 0, limit = Number.MAX_SAFE_INTEGER; setImmediate(function() { if (argsLength === 1) { cb = query; } else { skip = (query.skip) ? query.skip : 0; limit = (query.limit) ? query.limit : Number.MAX_SAFE_INTEGER; } var sortedKeys = Object.keys(items); var qKeys = remove(remove(Object.keys(query), /skip/), /limit/); qKeys.forEach(function (k) { try { var re = new RegExp(query[k]); sortedKeys = sortedKeys.filter(function (l) { return items[l][k].toString().match(re); }); } catch (e) { console.error(`Problem filtering collection for parameter ${k}.`, e.message); } }); skip = checkSkip(skip, sortedKeys); limit = checkLimit(limit, sortedKeys); if (sortedKeys.length === 0 || limit === 0 || skip >= sortedKeys.length) { return cb(null, [], sortedKeys.length, 1, 1, 0); } var pages = Math.ceil(sortedKeys.length / limit); var pageOf = Math.ceil(skip / limit) + 1; var itemArray = new Array(); for ( var x = skip ; x < Math.min(skip + limit, sortedKeys.length) ; x++ ) { itemArray.push(items[sortedKeys[x]]); } cb(null, itemArray, sortedKeys.length, pageOf, pages, itemArray.length); }); }
[ "function", "getCollection", "(", "items", ",", "query", ",", "cb", ",", "argsLength", ")", "{", "var", "skip", "=", "0", ",", "limit", "=", "Number", ".", "MAX_SAFE_INTEGER", ";", "setImmediate", "(", "function", "(", ")", "{", "if", "(", "argsLength", "===", "1", ")", "{", "cb", "=", "query", ";", "}", "else", "{", "skip", "=", "(", "query", ".", "skip", ")", "?", "query", ".", "skip", ":", "0", ";", "limit", "=", "(", "query", ".", "limit", ")", "?", "query", ".", "limit", ":", "Number", ".", "MAX_SAFE_INTEGER", ";", "}", "var", "sortedKeys", "=", "Object", ".", "keys", "(", "items", ")", ";", "var", "qKeys", "=", "remove", "(", "remove", "(", "Object", ".", "keys", "(", "query", ")", ",", "/", "skip", "/", ")", ",", "/", "limit", "/", ")", ";", "qKeys", ".", "forEach", "(", "function", "(", "k", ")", "{", "try", "{", "var", "re", "=", "new", "RegExp", "(", "query", "[", "k", "]", ")", ";", "sortedKeys", "=", "sortedKeys", ".", "filter", "(", "function", "(", "l", ")", "{", "return", "items", "[", "l", "]", "[", "k", "]", ".", "toString", "(", ")", ".", "match", "(", "re", ")", ";", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "`", "${", "k", "}", "`", ",", "e", ".", "message", ")", ";", "}", "}", ")", ";", "skip", "=", "checkSkip", "(", "skip", ",", "sortedKeys", ")", ";", "limit", "=", "checkLimit", "(", "limit", ",", "sortedKeys", ")", ";", "if", "(", "sortedKeys", ".", "length", "===", "0", "||", "limit", "===", "0", "||", "skip", ">=", "sortedKeys", ".", "length", ")", "{", "return", "cb", "(", "null", ",", "[", "]", ",", "sortedKeys", ".", "length", ",", "1", ",", "1", ",", "0", ")", ";", "}", "var", "pages", "=", "Math", ".", "ceil", "(", "sortedKeys", ".", "length", "/", "limit", ")", ";", "var", "pageOf", "=", "Math", ".", "ceil", "(", "skip", "/", "limit", ")", "+", "1", ";", "var", "itemArray", "=", "new", "Array", "(", ")", ";", "for", "(", "var", "x", "=", "skip", ";", "x", "<", "Math", ".", "min", "(", "skip", "+", "limit", ",", "sortedKeys", ".", "length", ")", ";", "x", "++", ")", "{", "itemArray", ".", "push", "(", "items", "[", "sortedKeys", "[", "x", "]", "]", ")", ";", "}", "cb", "(", "null", ",", "itemArray", ",", "sortedKeys", ".", "length", ",", "pageOf", ",", "pages", ",", "itemArray", ".", "length", ")", ";", "}", ")", ";", "}" ]
Generic get collection methods that returns an ordered sequence of items
[ "Generic", "get", "collection", "methods", "that", "returns", "an", "ordered", "sequence", "of", "items" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/api/NodeRAMStore.js#L68-L103
41,076
Streampunk/ledger
model/Node.js
Node
function Node(id, version, label, href, hostname, caps, services) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * HTTP access href for the Node's API. * @type {string} * @readonly */ this.href = this.generateHref(href); /** * Node hostname - set to null when not present. * @type {string} * @readonly */ this.hostname = this.generateHostname(hostname); /** * [Capabilities]{@link capabilities} (not yet defined). * @type {Object} * @readonly */ this.caps = this.generateCaps(caps); /** * Array of objects containing a URN format type and href. * @type {Object[]} * @readonly */ this.services = this.generateServices(services); return immutable(this, { prototype : Node.prototype }); }
javascript
function Node(id, version, label, href, hostname, caps, services) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * HTTP access href for the Node's API. * @type {string} * @readonly */ this.href = this.generateHref(href); /** * Node hostname - set to null when not present. * @type {string} * @readonly */ this.hostname = this.generateHostname(hostname); /** * [Capabilities]{@link capabilities} (not yet defined). * @type {Object} * @readonly */ this.caps = this.generateCaps(caps); /** * Array of objects containing a URN format type and href. * @type {Object[]} * @readonly */ this.services = this.generateServices(services); return immutable(this, { prototype : Node.prototype }); }
[ "function", "Node", "(", "id", ",", "version", ",", "label", ",", "href", ",", "hostname", ",", "caps", ",", "services", ")", "{", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "/**\r\n * HTTP access href for the Node's API.\r\n * @type {string}\r\n * @readonly\r\n */", "this", ".", "href", "=", "this", ".", "generateHref", "(", "href", ")", ";", "/**\r\n * Node hostname - set to null when not present.\r\n * @type {string}\r\n * @readonly\r\n */", "this", ".", "hostname", "=", "this", ".", "generateHostname", "(", "hostname", ")", ";", "/**\r\n * [Capabilities]{@link capabilities} (not yet defined).\r\n * @type {Object}\r\n * @readonly\r\n */", "this", ".", "caps", "=", "this", ".", "generateCaps", "(", "caps", ")", ";", "/**\r\n * Array of objects containing a URN format type and href.\r\n * @type {Object[]}\r\n * @readonly\r\n */", "this", ".", "services", "=", "this", ".", "generateServices", "(", "services", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Node", ".", "prototype", "}", ")", ";", "}" ]
Describes a Node. Immutable value. @constructor @augments Versionned @param {string} id Globally unique UUID identifier for the Node. @param {string} version String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;) indicating precisely when an attribute of the resource last changed. @param {string} label Freeform string label for the Node. @param {string} href HTTP access href for the Node's API. @param {string} hostname Node hostname - set to null when not present. @param {Object} caps [Capabilities]{@link capabilities} (not yet defined). @param {Object[]} services Array of objects containing a URN format type and href.
[ "Describes", "a", "Node", ".", "Immutable", "value", "." ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Node.js#L37-L66
41,077
Streampunk/ledger
model/Flow.js
Flow
function Flow(id, version, label, description, format, tags, source_id, parents) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * Detailed description of the Flow. * @type {string} * @readonly */ this.description = this.generateDescription(description); /** * [Format]{@link formats} of the data coming from the Flow as a URN. * @type {string} * @readonly */ this.format = this.generateFormat(format); /** * Key value set of freeform string tags to aid in filtering Flows. Can be * empty. * @type {Array.<string, string[]>} * @readonly */ this.tags = this.generateTags(tags); // Treating as a required property /** * Globally unique UUID identifier for the [source]{@link Source} which initially * created the Flow. * @type {string} * @readonly */ this.source_id = this.generateSourceID(source_id); /** * Array of UUIDs representing the Flow IDs of Grains which came together to * generate this Flow. (May change over the lifetime of this Flow.) */ this.parents = this.generateParents(parents); return immutable(this, { prototype: Flow.prototype }); }
javascript
function Flow(id, version, label, description, format, tags, source_id, parents) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * Detailed description of the Flow. * @type {string} * @readonly */ this.description = this.generateDescription(description); /** * [Format]{@link formats} of the data coming from the Flow as a URN. * @type {string} * @readonly */ this.format = this.generateFormat(format); /** * Key value set of freeform string tags to aid in filtering Flows. Can be * empty. * @type {Array.<string, string[]>} * @readonly */ this.tags = this.generateTags(tags); // Treating as a required property /** * Globally unique UUID identifier for the [source]{@link Source} which initially * created the Flow. * @type {string} * @readonly */ this.source_id = this.generateSourceID(source_id); /** * Array of UUIDs representing the Flow IDs of Grains which came together to * generate this Flow. (May change over the lifetime of this Flow.) */ this.parents = this.generateParents(parents); return immutable(this, { prototype: Flow.prototype }); }
[ "function", "Flow", "(", "id", ",", "version", ",", "label", ",", "description", ",", "format", ",", "tags", ",", "source_id", ",", "parents", ")", "{", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "/**\r\n * Detailed description of the Flow.\r\n * @type {string}\r\n * @readonly\r\n */", "this", ".", "description", "=", "this", ".", "generateDescription", "(", "description", ")", ";", "/**\r\n * [Format]{@link formats} of the data coming from the Flow as a URN.\r\n * @type {string}\r\n * @readonly\r\n */", "this", ".", "format", "=", "this", ".", "generateFormat", "(", "format", ")", ";", "/**\r\n * Key value set of freeform string tags to aid in filtering Flows. Can be\r\n * empty.\r\n * @type {Array.<string, string[]>}\r\n * @readonly\r\n */", "this", ".", "tags", "=", "this", ".", "generateTags", "(", "tags", ")", ";", "// Treating as a required property\r", "/**\r\n * Globally unique UUID identifier for the [source]{@link Source} which initially\r\n * created the Flow.\r\n * @type {string}\r\n * @readonly\r\n */", "this", ".", "source_id", "=", "this", ".", "generateSourceID", "(", "source_id", ")", ";", "/**\r\n * Array of UUIDs representing the Flow IDs of Grains which came together to\r\n * generate this Flow. (May change over the lifetime of this Flow.)\r\n */", "this", ".", "parents", "=", "this", ".", "generateParents", "(", "parents", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Flow", ".", "prototype", "}", ")", ";", "}" ]
Describes a Flow Describes a Flow. Immutable value. @constructor @augments Versionned @param {string} id Globally unique UUID identifier for the Flow. @param {string} version String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;) indicating precisely when an attribute of the resource last changed. @param {string} label Freeform string label for the Flow. @param {string} description Detailed description of the Flow. @param {string} format [Format]{@link formats} of the data coming from the Flow as a URN. @param {Object.<string, string[]>} tags Key value set of freeform string tags to aid in filtering Flows. Can be empty. @param {string} source_id Globally unique UUID for the [source]{@link Source} which initially created the Flow. @param {string[]} parents Array of UUIDs representing the Flow IDs of Grains which came together to generate this Flow. (May change over the lifetime of this Flow).
[ "Describes", "a", "Flow", "Describes", "a", "Flow", ".", "Immutable", "value", "." ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Flow.js#L42-L79
41,078
SINTEF-9012/Proto2TypeScript
command.js
generateNames
function generateNames(model, prefix, name) { if (name === void 0) { name = ""; } model.fullPackageName = prefix + (name != "." ? name : ""); // Copies the settings (I'm lazy) model.properties = argv.properties; model.explicitRequired = argv.explicitRequired; model.camelCaseProperties = argv.camelCaseProperties; model.camelCaseGetSet = argv.camelCaseGetSet; model.underscoreGetSet = argv.underscoreGetSet; model.generateBuilders = argv.generateBuilders; var newDefinitions = {}; // Generate names for messages // Recursive call for all messages var key; for (key in model.messages) { var message = model.messages[key]; newDefinitions[message.name] = "Builder"; generateNames(message, model.fullPackageName, "." + (model.name ? model.name : "")); } // Generate names for enums for (key in model.enums) { var currentEnum = model.enums[key]; newDefinitions[currentEnum.name] = ""; currentEnum.fullPackageName = model.fullPackageName + (model.name ? "." + model.name : ""); } // For fields of types which are defined in the same message, // update the field type in consequence for (key in model.fields) { var field = model.fields[key]; if (typeof newDefinitions[field.type] !== "undefined") { field.type = model.name + "." + field.type; } } model.oneofsArray = []; for (key in model.oneofs) { var oneof = model.oneofs[key]; model.oneofsArray.push({ name: key, value: oneof }); } // Add the new definitions in the model for generate builders var definitions = []; for (key in newDefinitions) { definitions.push({ name: key, type: ((model.name ? (model.name + ".") : "") + key) + newDefinitions[key] }); } model.definitions = definitions; }
javascript
function generateNames(model, prefix, name) { if (name === void 0) { name = ""; } model.fullPackageName = prefix + (name != "." ? name : ""); // Copies the settings (I'm lazy) model.properties = argv.properties; model.explicitRequired = argv.explicitRequired; model.camelCaseProperties = argv.camelCaseProperties; model.camelCaseGetSet = argv.camelCaseGetSet; model.underscoreGetSet = argv.underscoreGetSet; model.generateBuilders = argv.generateBuilders; var newDefinitions = {}; // Generate names for messages // Recursive call for all messages var key; for (key in model.messages) { var message = model.messages[key]; newDefinitions[message.name] = "Builder"; generateNames(message, model.fullPackageName, "." + (model.name ? model.name : "")); } // Generate names for enums for (key in model.enums) { var currentEnum = model.enums[key]; newDefinitions[currentEnum.name] = ""; currentEnum.fullPackageName = model.fullPackageName + (model.name ? "." + model.name : ""); } // For fields of types which are defined in the same message, // update the field type in consequence for (key in model.fields) { var field = model.fields[key]; if (typeof newDefinitions[field.type] !== "undefined") { field.type = model.name + "." + field.type; } } model.oneofsArray = []; for (key in model.oneofs) { var oneof = model.oneofs[key]; model.oneofsArray.push({ name: key, value: oneof }); } // Add the new definitions in the model for generate builders var definitions = []; for (key in newDefinitions) { definitions.push({ name: key, type: ((model.name ? (model.name + ".") : "") + key) + newDefinitions[key] }); } model.definitions = definitions; }
[ "function", "generateNames", "(", "model", ",", "prefix", ",", "name", ")", "{", "if", "(", "name", "===", "void", "0", ")", "{", "name", "=", "\"\"", ";", "}", "model", ".", "fullPackageName", "=", "prefix", "+", "(", "name", "!=", "\".\"", "?", "name", ":", "\"\"", ")", ";", "// Copies the settings (I'm lazy)", "model", ".", "properties", "=", "argv", ".", "properties", ";", "model", ".", "explicitRequired", "=", "argv", ".", "explicitRequired", ";", "model", ".", "camelCaseProperties", "=", "argv", ".", "camelCaseProperties", ";", "model", ".", "camelCaseGetSet", "=", "argv", ".", "camelCaseGetSet", ";", "model", ".", "underscoreGetSet", "=", "argv", ".", "underscoreGetSet", ";", "model", ".", "generateBuilders", "=", "argv", ".", "generateBuilders", ";", "var", "newDefinitions", "=", "{", "}", ";", "// Generate names for messages", "// Recursive call for all messages", "var", "key", ";", "for", "(", "key", "in", "model", ".", "messages", ")", "{", "var", "message", "=", "model", ".", "messages", "[", "key", "]", ";", "newDefinitions", "[", "message", ".", "name", "]", "=", "\"Builder\"", ";", "generateNames", "(", "message", ",", "model", ".", "fullPackageName", ",", "\".\"", "+", "(", "model", ".", "name", "?", "model", ".", "name", ":", "\"\"", ")", ")", ";", "}", "// Generate names for enums", "for", "(", "key", "in", "model", ".", "enums", ")", "{", "var", "currentEnum", "=", "model", ".", "enums", "[", "key", "]", ";", "newDefinitions", "[", "currentEnum", ".", "name", "]", "=", "\"\"", ";", "currentEnum", ".", "fullPackageName", "=", "model", ".", "fullPackageName", "+", "(", "model", ".", "name", "?", "\".\"", "+", "model", ".", "name", ":", "\"\"", ")", ";", "}", "// For fields of types which are defined in the same message,", "// update the field type in consequence", "for", "(", "key", "in", "model", ".", "fields", ")", "{", "var", "field", "=", "model", ".", "fields", "[", "key", "]", ";", "if", "(", "typeof", "newDefinitions", "[", "field", ".", "type", "]", "!==", "\"undefined\"", ")", "{", "field", ".", "type", "=", "model", ".", "name", "+", "\".\"", "+", "field", ".", "type", ";", "}", "}", "model", ".", "oneofsArray", "=", "[", "]", ";", "for", "(", "key", "in", "model", ".", "oneofs", ")", "{", "var", "oneof", "=", "model", ".", "oneofs", "[", "key", "]", ";", "model", ".", "oneofsArray", ".", "push", "(", "{", "name", ":", "key", ",", "value", ":", "oneof", "}", ")", ";", "}", "// Add the new definitions in the model for generate builders", "var", "definitions", "=", "[", "]", ";", "for", "(", "key", "in", "newDefinitions", ")", "{", "definitions", ".", "push", "(", "{", "name", ":", "key", ",", "type", ":", "(", "(", "model", ".", "name", "?", "(", "model", ".", "name", "+", "\".\"", ")", ":", "\"\"", ")", "+", "key", ")", "+", "newDefinitions", "[", "key", "]", "}", ")", ";", "}", "model", ".", "definitions", "=", "definitions", ";", "}" ]
Generate the names for the model, the types, and the interfaces
[ "Generate", "the", "names", "for", "the", "model", "the", "types", "and", "the", "interfaces" ]
d96cfd3dc7afcdbea86114cefca1a761fe0d59ca
https://github.com/SINTEF-9012/Proto2TypeScript/blob/d96cfd3dc7afcdbea86114cefca1a761fe0d59ca/command.js#L83-L127
41,079
elsehow/signal-protocol
src/curve25519_wrapper.js
_allocate
function _allocate(bytes) { var address = Module._malloc(bytes.length); Module.HEAPU8.set(bytes, address); return address; }
javascript
function _allocate(bytes) { var address = Module._malloc(bytes.length); Module.HEAPU8.set(bytes, address); return address; }
[ "function", "_allocate", "(", "bytes", ")", "{", "var", "address", "=", "Module", ".", "_malloc", "(", "bytes", ".", "length", ")", ";", "Module", ".", "HEAPU8", ".", "set", "(", "bytes", ",", "address", ")", ";", "return", "address", ";", "}" ]
Insert some bytes into the emscripten memory and return a pointer
[ "Insert", "some", "bytes", "into", "the", "emscripten", "memory", "and", "return", "a", "pointer" ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/src/curve25519_wrapper.js#L7-L12
41,080
elsehow/signal-protocol
build/curve25519_compiled.js
doRun
function doRun() { if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening Module['calledRun'] = true; if (ABORT) return; ensureInitRuntime(); preMain(); if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized'](); if (Module['_main'] && shouldRunNow) Module['callMain'](args); postRun(); }
javascript
function doRun() { if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening Module['calledRun'] = true; if (ABORT) return; ensureInitRuntime(); preMain(); if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized'](); if (Module['_main'] && shouldRunNow) Module['callMain'](args); postRun(); }
[ "function", "doRun", "(", ")", "{", "if", "(", "Module", "[", "'calledRun'", "]", ")", "return", ";", "// run may have just been called while the async setStatus time below was happening", "Module", "[", "'calledRun'", "]", "=", "true", ";", "if", "(", "ABORT", ")", "return", ";", "ensureInitRuntime", "(", ")", ";", "preMain", "(", ")", ";", "if", "(", "Module", "[", "'onRuntimeInitialized'", "]", ")", "Module", "[", "'onRuntimeInitialized'", "]", "(", ")", ";", "if", "(", "Module", "[", "'_main'", "]", "&&", "shouldRunNow", ")", "Module", "[", "'callMain'", "]", "(", "args", ")", ";", "postRun", "(", ")", ";", "}" ]
run may have just been called through dependencies being fulfilled just in this very frame
[ "run", "may", "have", "just", "been", "called", "through", "dependencies", "being", "fulfilled", "just", "in", "this", "very", "frame" ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/curve25519_compiled.js#L20596-L20612
41,081
doublemarked/loopback-console
repl.js
wrapReplEval
function wrapReplEval(replServer) { const defaultEval = replServer.eval; return function(code, context, file, cb) { return defaultEval.call(this, code, context, file, (err, result) => { if (!result || !result.then) { return cb(err, result); } result.then(resolved => { resolvePromises(result, resolved); cb(null, resolved); }).catch(err => { resolvePromises(result, err); console.log('\x1b[31m' + '[Promise Rejection]' + '\x1b[0m'); if (err && err.message) { console.log('\x1b[31m' + err.message + '\x1b[0m'); } // Application errors are not REPL errors cb(null, err); }); }); function resolvePromises(promise, resolved) { Object.keys(context).forEach(key => { // Replace any promise handles in the REPL context with the resolved promise if (context[key] === promise) { context[key] = resolved; } }); } }; }
javascript
function wrapReplEval(replServer) { const defaultEval = replServer.eval; return function(code, context, file, cb) { return defaultEval.call(this, code, context, file, (err, result) => { if (!result || !result.then) { return cb(err, result); } result.then(resolved => { resolvePromises(result, resolved); cb(null, resolved); }).catch(err => { resolvePromises(result, err); console.log('\x1b[31m' + '[Promise Rejection]' + '\x1b[0m'); if (err && err.message) { console.log('\x1b[31m' + err.message + '\x1b[0m'); } // Application errors are not REPL errors cb(null, err); }); }); function resolvePromises(promise, resolved) { Object.keys(context).forEach(key => { // Replace any promise handles in the REPL context with the resolved promise if (context[key] === promise) { context[key] = resolved; } }); } }; }
[ "function", "wrapReplEval", "(", "replServer", ")", "{", "const", "defaultEval", "=", "replServer", ".", "eval", ";", "return", "function", "(", "code", ",", "context", ",", "file", ",", "cb", ")", "{", "return", "defaultEval", ".", "call", "(", "this", ",", "code", ",", "context", ",", "file", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "!", "result", "||", "!", "result", ".", "then", ")", "{", "return", "cb", "(", "err", ",", "result", ")", ";", "}", "result", ".", "then", "(", "resolved", "=>", "{", "resolvePromises", "(", "result", ",", "resolved", ")", ";", "cb", "(", "null", ",", "resolved", ")", ";", "}", ")", ".", "catch", "(", "err", "=>", "{", "resolvePromises", "(", "result", ",", "err", ")", ";", "console", ".", "log", "(", "'\\x1b[31m'", "+", "'[Promise Rejection]'", "+", "'\\x1b[0m'", ")", ";", "if", "(", "err", "&&", "err", ".", "message", ")", "{", "console", ".", "log", "(", "'\\x1b[31m'", "+", "err", ".", "message", "+", "'\\x1b[0m'", ")", ";", "}", "// Application errors are not REPL errors", "cb", "(", "null", ",", "err", ")", ";", "}", ")", ";", "}", ")", ";", "function", "resolvePromises", "(", "promise", ",", "resolved", ")", "{", "Object", ".", "keys", "(", "context", ")", ".", "forEach", "(", "key", "=>", "{", "// Replace any promise handles in the REPL context with the resolved promise", "if", "(", "context", "[", "key", "]", "===", "promise", ")", "{", "context", "[", "key", "]", "=", "resolved", ";", "}", "}", ")", ";", "}", "}", ";", "}" ]
Wrap the default eval with a handler that resolves promises
[ "Wrap", "the", "default", "eval", "with", "a", "handler", "that", "resolves", "promises" ]
b3259ad6bd79ef9c529ca07b2a72bf998925cff4
https://github.com/doublemarked/loopback-console/blob/b3259ad6bd79ef9c529ca07b2a72bf998925cff4/repl.js#L101-L135
41,082
TheRoSS/mongodb-autoincrement
index.js
getNextId
function getNextId(db, collectionName, fieldName, callback) { if (typeof fieldName == "function") { callback = fieldName; fieldName = null; } fieldName = fieldName || getOption(collectionName, "field"); var collection = db.collection(defaultSettings.collection); var step = getOption(collectionName, "step"); collection.findAndModify( {_id: collectionName, field: fieldName}, null, {$inc: {seq: step}}, {upsert: true, new: true}, function (err, result) { if (err) { if (err.code == 11000) { process.nextTick(getNextId.bind(null, db, collectionName, fieldName, callback)); } else { callback(err); } } else { if (result.value && result.value.seq) { callback(null, result.value.seq); } else { callback(null, result.seq); } } } ); }
javascript
function getNextId(db, collectionName, fieldName, callback) { if (typeof fieldName == "function") { callback = fieldName; fieldName = null; } fieldName = fieldName || getOption(collectionName, "field"); var collection = db.collection(defaultSettings.collection); var step = getOption(collectionName, "step"); collection.findAndModify( {_id: collectionName, field: fieldName}, null, {$inc: {seq: step}}, {upsert: true, new: true}, function (err, result) { if (err) { if (err.code == 11000) { process.nextTick(getNextId.bind(null, db, collectionName, fieldName, callback)); } else { callback(err); } } else { if (result.value && result.value.seq) { callback(null, result.value.seq); } else { callback(null, result.seq); } } } ); }
[ "function", "getNextId", "(", "db", ",", "collectionName", ",", "fieldName", ",", "callback", ")", "{", "if", "(", "typeof", "fieldName", "==", "\"function\"", ")", "{", "callback", "=", "fieldName", ";", "fieldName", "=", "null", ";", "}", "fieldName", "=", "fieldName", "||", "getOption", "(", "collectionName", ",", "\"field\"", ")", ";", "var", "collection", "=", "db", ".", "collection", "(", "defaultSettings", ".", "collection", ")", ";", "var", "step", "=", "getOption", "(", "collectionName", ",", "\"step\"", ")", ";", "collection", ".", "findAndModify", "(", "{", "_id", ":", "collectionName", ",", "field", ":", "fieldName", "}", ",", "null", ",", "{", "$inc", ":", "{", "seq", ":", "step", "}", "}", ",", "{", "upsert", ":", "true", ",", "new", ":", "true", "}", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "==", "11000", ")", "{", "process", ".", "nextTick", "(", "getNextId", ".", "bind", "(", "null", ",", "db", ",", "collectionName", ",", "fieldName", ",", "callback", ")", ")", ";", "}", "else", "{", "callback", "(", "err", ")", ";", "}", "}", "else", "{", "if", "(", "result", ".", "value", "&&", "result", ".", "value", ".", "seq", ")", "{", "callback", "(", "null", ",", "result", ".", "value", ".", "seq", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "result", ".", "seq", ")", ";", "}", "}", "}", ")", ";", "}" ]
Get next auto increment index for the given collection @param {MongodbNativeDriver} db @param {String} collectionName @param {String} [fieldName] @param {Function} callback
[ "Get", "next", "auto", "increment", "index", "for", "the", "given", "collection" ]
b36f0a172cc17b7d1bc0bfaa9ee48a7a57c30803
https://github.com/TheRoSS/mongodb-autoincrement/blob/b36f0a172cc17b7d1bc0bfaa9ee48a7a57c30803/index.js#L102-L133
41,083
elsehow/signal-protocol
build/components_concat.js
mkNumber
function mkNumber(val) { var sign = 1; if (val.charAt(0) == '-') { sign = -1; val = val.substring(1); } if (Lang.NUMBER_DEC.test(val)) return sign * parseInt(val, 10); else if (Lang.NUMBER_HEX.test(val)) return sign * parseInt(val.substring(2), 16); else if (Lang.NUMBER_OCT.test(val)) return sign * parseInt(val.substring(1), 8); else if (val === 'inf') return sign * Infinity; else if (val === 'nan') return NaN; else if (Lang.NUMBER_FLT.test(val)) return sign * parseFloat(val); throw Error("illegal number value: " + (sign < 0 ? '-' : '') + val); }
javascript
function mkNumber(val) { var sign = 1; if (val.charAt(0) == '-') { sign = -1; val = val.substring(1); } if (Lang.NUMBER_DEC.test(val)) return sign * parseInt(val, 10); else if (Lang.NUMBER_HEX.test(val)) return sign * parseInt(val.substring(2), 16); else if (Lang.NUMBER_OCT.test(val)) return sign * parseInt(val.substring(1), 8); else if (val === 'inf') return sign * Infinity; else if (val === 'nan') return NaN; else if (Lang.NUMBER_FLT.test(val)) return sign * parseFloat(val); throw Error("illegal number value: " + (sign < 0 ? '-' : '') + val); }
[ "function", "mkNumber", "(", "val", ")", "{", "var", "sign", "=", "1", ";", "if", "(", "val", ".", "charAt", "(", "0", ")", "==", "'-'", ")", "{", "sign", "=", "-", "1", ";", "val", "=", "val", ".", "substring", "(", "1", ")", ";", "}", "if", "(", "Lang", ".", "NUMBER_DEC", ".", "test", "(", "val", ")", ")", "return", "sign", "*", "parseInt", "(", "val", ",", "10", ")", ";", "else", "if", "(", "Lang", ".", "NUMBER_HEX", ".", "test", "(", "val", ")", ")", "return", "sign", "*", "parseInt", "(", "val", ".", "substring", "(", "2", ")", ",", "16", ")", ";", "else", "if", "(", "Lang", ".", "NUMBER_OCT", ".", "test", "(", "val", ")", ")", "return", "sign", "*", "parseInt", "(", "val", ".", "substring", "(", "1", ")", ",", "8", ")", ";", "else", "if", "(", "val", "===", "'inf'", ")", "return", "sign", "*", "Infinity", ";", "else", "if", "(", "val", "===", "'nan'", ")", "return", "NaN", ";", "else", "if", "(", "Lang", ".", "NUMBER_FLT", ".", "test", "(", "val", ")", ")", "return", "sign", "*", "parseFloat", "(", "val", ")", ";", "throw", "Error", "(", "\"illegal number value: \"", "+", "(", "sign", "<", "0", "?", "'-'", ":", "''", ")", "+", "val", ")", ";", "}" ]
Converts a numerical string to a number. @param {string} val @returns {number} @inner
[ "Converts", "a", "numerical", "string", "to", "a", "number", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L5340-L5359
41,084
elsehow/signal-protocol
build/components_concat.js
setOption
function setOption(options, name, value) { if (typeof options[name] === 'undefined') options[name] = value; else { if (!Array.isArray(options[name])) options[name] = [ options[name] ]; options[name].push(value); } }
javascript
function setOption(options, name, value) { if (typeof options[name] === 'undefined') options[name] = value; else { if (!Array.isArray(options[name])) options[name] = [ options[name] ]; options[name].push(value); } }
[ "function", "setOption", "(", "options", ",", "name", ",", "value", ")", "{", "if", "(", "typeof", "options", "[", "name", "]", "===", "'undefined'", ")", "options", "[", "name", "]", "=", "value", ";", "else", "{", "if", "(", "!", "Array", ".", "isArray", "(", "options", "[", "name", "]", ")", ")", "options", "[", "name", "]", "=", "[", "options", "[", "name", "]", "]", ";", "options", "[", "name", "]", ".", "push", "(", "value", ")", ";", "}", "}" ]
Sets an option on the specified options object. @param {!Object.<string,*>} options @param {string} name @param {string|number|boolean} value @inner
[ "Sets", "an", "option", "on", "the", "specified", "options", "object", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L5447-L5455
41,085
elsehow/signal-protocol
build/components_concat.js
function(builder, parent, name) { /** * Builder reference. * @type {!ProtoBuf.Builder} * @expose */ this.builder = builder; /** * Parent object. * @type {?ProtoBuf.Reflect.T} * @expose */ this.parent = parent; /** * Object name in namespace. * @type {string} * @expose */ this.name = name; /** * Fully qualified class name * @type {string} * @expose */ this.className; }
javascript
function(builder, parent, name) { /** * Builder reference. * @type {!ProtoBuf.Builder} * @expose */ this.builder = builder; /** * Parent object. * @type {?ProtoBuf.Reflect.T} * @expose */ this.parent = parent; /** * Object name in namespace. * @type {string} * @expose */ this.name = name; /** * Fully qualified class name * @type {string} * @expose */ this.className; }
[ "function", "(", "builder", ",", "parent", ",", "name", ")", "{", "/**\r\n * Builder reference.\r\n * @type {!ProtoBuf.Builder}\r\n * @expose\r\n */", "this", ".", "builder", "=", "builder", ";", "/**\r\n * Parent object.\r\n * @type {?ProtoBuf.Reflect.T}\r\n * @expose\r\n */", "this", ".", "parent", "=", "parent", ";", "/**\r\n * Object name in namespace.\r\n * @type {string}\r\n * @expose\r\n */", "this", ".", "name", "=", "name", ";", "/**\r\n * Fully qualified class name\r\n * @type {string}\r\n * @expose\r\n */", "this", ".", "className", ";", "}" ]
Constructs a Reflect base class. @exports ProtoBuf.Reflect.T @constructor @abstract @param {!ProtoBuf.Builder} builder Builder reference @param {?ProtoBuf.Reflect.T} parent Parent object @param {string} name Object name
[ "Constructs", "a", "Reflect", "base", "class", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L5910-L5939
41,086
elsehow/signal-protocol
build/components_concat.js
function(builder, parent, name, options, syntax) { T.call(this, builder, parent, name); /** * @override */ this.className = "Namespace"; /** * Children inside the namespace. * @type {!Array.<ProtoBuf.Reflect.T>} */ this.children = []; /** * Options. * @type {!Object.<string, *>} */ this.options = options || {}; /** * Syntax level (e.g., proto2 or proto3). * @type {!string} */ this.syntax = syntax || "proto2"; }
javascript
function(builder, parent, name, options, syntax) { T.call(this, builder, parent, name); /** * @override */ this.className = "Namespace"; /** * Children inside the namespace. * @type {!Array.<ProtoBuf.Reflect.T>} */ this.children = []; /** * Options. * @type {!Object.<string, *>} */ this.options = options || {}; /** * Syntax level (e.g., proto2 or proto3). * @type {!string} */ this.syntax = syntax || "proto2"; }
[ "function", "(", "builder", ",", "parent", ",", "name", ",", "options", ",", "syntax", ")", "{", "T", ".", "call", "(", "this", ",", "builder", ",", "parent", ",", "name", ")", ";", "/**\r\n * @override\r\n */", "this", ".", "className", "=", "\"Namespace\"", ";", "/**\r\n * Children inside the namespace.\r\n * @type {!Array.<ProtoBuf.Reflect.T>}\r\n */", "this", ".", "children", "=", "[", "]", ";", "/**\r\n * Options.\r\n * @type {!Object.<string, *>}\r\n */", "this", ".", "options", "=", "options", "||", "{", "}", ";", "/**\r\n * Syntax level (e.g., proto2 or proto3).\r\n * @type {!string}\r\n */", "this", ".", "syntax", "=", "syntax", "||", "\"proto2\"", ";", "}" ]
Constructs a new Namespace. @exports ProtoBuf.Reflect.Namespace @param {!ProtoBuf.Builder} builder Builder reference @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent @param {string} name Namespace name @param {Object.<string,*>=} options Namespace options @param {string?} syntax The syntax level of this definition (e.g., proto3) @constructor @extends ProtoBuf.Reflect.T
[ "Constructs", "a", "new", "Namespace", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L6000-L6025
41,087
elsehow/signal-protocol
build/components_concat.js
function(type, resolvedType, isMapKey, syntax) { /** * Element type, as a string (e.g., int32). * @type {{name: string, wireType: number}} */ this.type = type; /** * Element type reference to submessage or enum definition, if needed. * @type {ProtoBuf.Reflect.T|null} */ this.resolvedType = resolvedType; /** * Element is a map key. * @type {boolean} */ this.isMapKey = isMapKey; /** * Syntax level of defining message type, e.g., proto2 or proto3. * @type {string} */ this.syntax = syntax; if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0) throw Error("Invalid map key type: " + type.name); }
javascript
function(type, resolvedType, isMapKey, syntax) { /** * Element type, as a string (e.g., int32). * @type {{name: string, wireType: number}} */ this.type = type; /** * Element type reference to submessage or enum definition, if needed. * @type {ProtoBuf.Reflect.T|null} */ this.resolvedType = resolvedType; /** * Element is a map key. * @type {boolean} */ this.isMapKey = isMapKey; /** * Syntax level of defining message type, e.g., proto2 or proto3. * @type {string} */ this.syntax = syntax; if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0) throw Error("Invalid map key type: " + type.name); }
[ "function", "(", "type", ",", "resolvedType", ",", "isMapKey", ",", "syntax", ")", "{", "/**\r\n * Element type, as a string (e.g., int32).\r\n * @type {{name: string, wireType: number}}\r\n */", "this", ".", "type", "=", "type", ";", "/**\r\n * Element type reference to submessage or enum definition, if needed.\r\n * @type {ProtoBuf.Reflect.T|null}\r\n */", "this", ".", "resolvedType", "=", "resolvedType", ";", "/**\r\n * Element is a map key.\r\n * @type {boolean}\r\n */", "this", ".", "isMapKey", "=", "isMapKey", ";", "/**\r\n * Syntax level of defining message type, e.g., proto2 or proto3.\r\n * @type {string}\r\n */", "this", ".", "syntax", "=", "syntax", ";", "if", "(", "isMapKey", "&&", "ProtoBuf", ".", "MAP_KEY_TYPES", ".", "indexOf", "(", "type", ")", "<", "0", ")", "throw", "Error", "(", "\"Invalid map key type: \"", "+", "type", ".", "name", ")", ";", "}" ]
Constructs a new Element implementation that checks and converts values for a particular field type, as appropriate. An Element represents a single value: either the value of a singular field, or a value contained in one entry of a repeated field or map field. This class does not implement these higher-level concepts; it only encapsulates the low-level typechecking and conversion. @exports ProtoBuf.Reflect.Element @param {{name: string, wireType: number}} type Resolved data type @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant (e.g. submessage field). @param {boolean} isMapKey Is this element a Map key? The value will be converted to string form if so. @param {string} syntax Syntax level of defining message type, e.g., proto2 or proto3. @constructor
[ "Constructs", "a", "new", "Element", "implementation", "that", "checks", "and", "converts", "values", "for", "a", "particular", "field", "type", "as", "appropriate", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L6218-L6246
41,088
elsehow/signal-protocol
build/components_concat.js
mkLong
function mkLong(value, unsigned) { if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean' && value.low === value.low && value.high === value.high) return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned); if (typeof value === 'string') return ProtoBuf.Long.fromString(value, unsigned || false, 10); if (typeof value === 'number') return ProtoBuf.Long.fromNumber(value, unsigned || false); throw Error("not convertible to Long"); }
javascript
function mkLong(value, unsigned) { if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean' && value.low === value.low && value.high === value.high) return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned); if (typeof value === 'string') return ProtoBuf.Long.fromString(value, unsigned || false, 10); if (typeof value === 'number') return ProtoBuf.Long.fromNumber(value, unsigned || false); throw Error("not convertible to Long"); }
[ "function", "mkLong", "(", "value", ",", "unsigned", ")", "{", "if", "(", "value", "&&", "typeof", "value", ".", "low", "===", "'number'", "&&", "typeof", "value", ".", "high", "===", "'number'", "&&", "typeof", "value", ".", "unsigned", "===", "'boolean'", "&&", "value", ".", "low", "===", "value", ".", "low", "&&", "value", ".", "high", "===", "value", ".", "high", ")", "return", "new", "ProtoBuf", ".", "Long", "(", "value", ".", "low", ",", "value", ".", "high", ",", "typeof", "unsigned", "===", "'undefined'", "?", "value", ".", "unsigned", ":", "unsigned", ")", ";", "if", "(", "typeof", "value", "===", "'string'", ")", "return", "ProtoBuf", ".", "Long", ".", "fromString", "(", "value", ",", "unsigned", "||", "false", ",", "10", ")", ";", "if", "(", "typeof", "value", "===", "'number'", ")", "return", "ProtoBuf", ".", "Long", ".", "fromNumber", "(", "value", ",", "unsigned", "||", "false", ")", ";", "throw", "Error", "(", "\"not convertible to Long\"", ")", ";", "}" ]
Makes a Long from a value. @param {{low: number, high: number, unsigned: boolean}|string|number} value Value @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for strings and numbers @returns {!Long} @throws {Error} If the value cannot be converted to a Long @inner
[ "Makes", "a", "Long", "from", "a", "value", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L6283-L6292
41,089
elsehow/signal-protocol
build/components_concat.js
function(builder, parent, name, options, isGroup, syntax) { Namespace.call(this, builder, parent, name, options, syntax); /** * @override */ this.className = "Message"; /** * Extensions range. * @type {!Array.<number>|undefined} * @expose */ this.extensions = undefined; /** * Runtime message class. * @type {?function(new:ProtoBuf.Builder.Message)} * @expose */ this.clazz = null; /** * Whether this is a legacy group or not. * @type {boolean} * @expose */ this.isGroup = !!isGroup; // The following cached collections are used to efficiently iterate over or look up fields when decoding. /** * Cached fields. * @type {?Array.<!ProtoBuf.Reflect.Message.Field>} * @private */ this._fields = null; /** * Cached fields by id. * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>} * @private */ this._fieldsById = null; /** * Cached fields by name. * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>} * @private */ this._fieldsByName = null; }
javascript
function(builder, parent, name, options, isGroup, syntax) { Namespace.call(this, builder, parent, name, options, syntax); /** * @override */ this.className = "Message"; /** * Extensions range. * @type {!Array.<number>|undefined} * @expose */ this.extensions = undefined; /** * Runtime message class. * @type {?function(new:ProtoBuf.Builder.Message)} * @expose */ this.clazz = null; /** * Whether this is a legacy group or not. * @type {boolean} * @expose */ this.isGroup = !!isGroup; // The following cached collections are used to efficiently iterate over or look up fields when decoding. /** * Cached fields. * @type {?Array.<!ProtoBuf.Reflect.Message.Field>} * @private */ this._fields = null; /** * Cached fields by id. * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>} * @private */ this._fieldsById = null; /** * Cached fields by name. * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>} * @private */ this._fieldsByName = null; }
[ "function", "(", "builder", ",", "parent", ",", "name", ",", "options", ",", "isGroup", ",", "syntax", ")", "{", "Namespace", ".", "call", "(", "this", ",", "builder", ",", "parent", ",", "name", ",", "options", ",", "syntax", ")", ";", "/**\r\n * @override\r\n */", "this", ".", "className", "=", "\"Message\"", ";", "/**\r\n * Extensions range.\r\n * @type {!Array.<number>|undefined}\r\n * @expose\r\n */", "this", ".", "extensions", "=", "undefined", ";", "/**\r\n * Runtime message class.\r\n * @type {?function(new:ProtoBuf.Builder.Message)}\r\n * @expose\r\n */", "this", ".", "clazz", "=", "null", ";", "/**\r\n * Whether this is a legacy group or not.\r\n * @type {boolean}\r\n * @expose\r\n */", "this", ".", "isGroup", "=", "!", "!", "isGroup", ";", "// The following cached collections are used to efficiently iterate over or look up fields when decoding.\r", "/**\r\n * Cached fields.\r\n * @type {?Array.<!ProtoBuf.Reflect.Message.Field>}\r\n * @private\r\n */", "this", ".", "_fields", "=", "null", ";", "/**\r\n * Cached fields by id.\r\n * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>}\r\n * @private\r\n */", "this", ".", "_fieldsById", "=", "null", ";", "/**\r\n * Cached fields by name.\r\n * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>}\r\n * @private\r\n */", "this", ".", "_fieldsByName", "=", "null", ";", "}" ]
Constructs a new Message. @exports ProtoBuf.Reflect.Message @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace @param {string} name Message name @param {Object.<string,*>=} options Message options @param {boolean=} isGroup `true` if this is a legacy group @param {string?} syntax The syntax level of this definition (e.g., proto3) @constructor @extends ProtoBuf.Reflect.Namespace
[ "Constructs", "a", "new", "Message", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L6786-L6837
41,090
elsehow/signal-protocol
build/components_concat.js
function(values, var_args) { ProtoBuf.Builder.Message.call(this); // Create virtual oneof properties for (var i=0, k=oneofs.length; i<k; ++i) this[oneofs[i].name] = null; // Create fields and set default values for (i=0, k=fields.length; i<k; ++i) { var field = fields[i]; this[field.name] = field.repeated ? [] : (field.map ? new ProtoBuf.Map(field) : null); if ((field.required || T.syntax === 'proto3') && field.defaultValue !== null) this[field.name] = field.defaultValue; } if (arguments.length > 0) { var value; // Set field values from a values object if (arguments.length === 1 && values !== null && typeof values === 'object' && /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) && /* not a repeated field */ !Array.isArray(values) && /* not a Map */ !(values instanceof ProtoBuf.Map) && /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) && /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) && /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) { this.$set(values); } else // Set field values from arguments, in declaration order for (i=0, k=arguments.length; i<k; ++i) if (typeof (value = arguments[i]) !== 'undefined') this.$set(fields[i].name, value); // May throw } }
javascript
function(values, var_args) { ProtoBuf.Builder.Message.call(this); // Create virtual oneof properties for (var i=0, k=oneofs.length; i<k; ++i) this[oneofs[i].name] = null; // Create fields and set default values for (i=0, k=fields.length; i<k; ++i) { var field = fields[i]; this[field.name] = field.repeated ? [] : (field.map ? new ProtoBuf.Map(field) : null); if ((field.required || T.syntax === 'proto3') && field.defaultValue !== null) this[field.name] = field.defaultValue; } if (arguments.length > 0) { var value; // Set field values from a values object if (arguments.length === 1 && values !== null && typeof values === 'object' && /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) && /* not a repeated field */ !Array.isArray(values) && /* not a Map */ !(values instanceof ProtoBuf.Map) && /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) && /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) && /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) { this.$set(values); } else // Set field values from arguments, in declaration order for (i=0, k=arguments.length; i<k; ++i) if (typeof (value = arguments[i]) !== 'undefined') this.$set(fields[i].name, value); // May throw } }
[ "function", "(", "values", ",", "var_args", ")", "{", "ProtoBuf", ".", "Builder", ".", "Message", ".", "call", "(", "this", ")", ";", "// Create virtual oneof properties\r", "for", "(", "var", "i", "=", "0", ",", "k", "=", "oneofs", ".", "length", ";", "i", "<", "k", ";", "++", "i", ")", "this", "[", "oneofs", "[", "i", "]", ".", "name", "]", "=", "null", ";", "// Create fields and set default values\r", "for", "(", "i", "=", "0", ",", "k", "=", "fields", ".", "length", ";", "i", "<", "k", ";", "++", "i", ")", "{", "var", "field", "=", "fields", "[", "i", "]", ";", "this", "[", "field", ".", "name", "]", "=", "field", ".", "repeated", "?", "[", "]", ":", "(", "field", ".", "map", "?", "new", "ProtoBuf", ".", "Map", "(", "field", ")", ":", "null", ")", ";", "if", "(", "(", "field", ".", "required", "||", "T", ".", "syntax", "===", "'proto3'", ")", "&&", "field", ".", "defaultValue", "!==", "null", ")", "this", "[", "field", ".", "name", "]", "=", "field", ".", "defaultValue", ";", "}", "if", "(", "arguments", ".", "length", ">", "0", ")", "{", "var", "value", ";", "// Set field values from a values object\r", "if", "(", "arguments", ".", "length", "===", "1", "&&", "values", "!==", "null", "&&", "typeof", "values", "===", "'object'", "&&", "/* not _another_ Message */", "(", "typeof", "values", ".", "encode", "!==", "'function'", "||", "values", "instanceof", "Message", ")", "&&", "/* not a repeated field */", "!", "Array", ".", "isArray", "(", "values", ")", "&&", "/* not a Map */", "!", "(", "values", "instanceof", "ProtoBuf", ".", "Map", ")", "&&", "/* not a ByteBuffer */", "!", "ByteBuffer", ".", "isByteBuffer", "(", "values", ")", "&&", "/* not an ArrayBuffer */", "!", "(", "values", "instanceof", "ArrayBuffer", ")", "&&", "/* not a Long */", "!", "(", "ProtoBuf", ".", "Long", "&&", "values", "instanceof", "ProtoBuf", ".", "Long", ")", ")", "{", "this", ".", "$set", "(", "values", ")", ";", "}", "else", "// Set field values from arguments, in declaration order\r", "for", "(", "i", "=", "0", ",", "k", "=", "arguments", ".", "length", ";", "i", "<", "k", ";", "++", "i", ")", "if", "(", "typeof", "(", "value", "=", "arguments", "[", "i", "]", ")", "!==", "'undefined'", ")", "this", ".", "$set", "(", "fields", "[", "i", "]", ".", "name", ",", "value", ")", ";", "// May throw\r", "}", "}" ]
Constructs a new runtime Message. @name ProtoBuf.Builder.Message @class Barebone of all runtime messages. @param {!Object.<string,*>|string} values Preset values @param {...string} var_args @constructor @throws {Error} If the message cannot be created
[ "Constructs", "a", "new", "runtime", "Message", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L6872-L6905
41,091
elsehow/signal-protocol
build/components_concat.js
cloneRaw
function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) { if (obj === null || typeof obj !== 'object') { // Convert enum values to their respective names if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) { var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj); if (name !== null) return name; } // Pass-through string, number, boolean, null... return obj; } // Convert ByteBuffers to raw buffer or strings if (ByteBuffer.isByteBuffer(obj)) return binaryAsBase64 ? obj.toBase64() : obj.toBuffer(); // Convert Longs to proper objects or strings if (ProtoBuf.Long.isLong(obj)) return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj); var clone; // Clone arrays if (Array.isArray(obj)) { clone = []; obj.forEach(function(v, k) { clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType); }); return clone; } clone = {}; // Convert maps to objects if (obj instanceof ProtoBuf.Map) { var it = obj.entries(); for (var e = it.next(); !e.done; e = it.next()) clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType); return clone; } // Everything else is a non-null object var type = obj.$type, field = undefined; for (var i in obj) if (obj.hasOwnProperty(i)) { if (type && (field = type.getChild(i))) clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType); else clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings); } return clone; }
javascript
function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) { if (obj === null || typeof obj !== 'object') { // Convert enum values to their respective names if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) { var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj); if (name !== null) return name; } // Pass-through string, number, boolean, null... return obj; } // Convert ByteBuffers to raw buffer or strings if (ByteBuffer.isByteBuffer(obj)) return binaryAsBase64 ? obj.toBase64() : obj.toBuffer(); // Convert Longs to proper objects or strings if (ProtoBuf.Long.isLong(obj)) return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj); var clone; // Clone arrays if (Array.isArray(obj)) { clone = []; obj.forEach(function(v, k) { clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType); }); return clone; } clone = {}; // Convert maps to objects if (obj instanceof ProtoBuf.Map) { var it = obj.entries(); for (var e = it.next(); !e.done; e = it.next()) clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType); return clone; } // Everything else is a non-null object var type = obj.$type, field = undefined; for (var i in obj) if (obj.hasOwnProperty(i)) { if (type && (field = type.getChild(i))) clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType); else clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings); } return clone; }
[ "function", "cloneRaw", "(", "obj", ",", "binaryAsBase64", ",", "longsAsStrings", ",", "resolvedType", ")", "{", "if", "(", "obj", "===", "null", "||", "typeof", "obj", "!==", "'object'", ")", "{", "// Convert enum values to their respective names\r", "if", "(", "resolvedType", "&&", "resolvedType", "instanceof", "ProtoBuf", ".", "Reflect", ".", "Enum", ")", "{", "var", "name", "=", "ProtoBuf", ".", "Reflect", ".", "Enum", ".", "getName", "(", "resolvedType", ".", "object", ",", "obj", ")", ";", "if", "(", "name", "!==", "null", ")", "return", "name", ";", "}", "// Pass-through string, number, boolean, null...\r", "return", "obj", ";", "}", "// Convert ByteBuffers to raw buffer or strings\r", "if", "(", "ByteBuffer", ".", "isByteBuffer", "(", "obj", ")", ")", "return", "binaryAsBase64", "?", "obj", ".", "toBase64", "(", ")", ":", "obj", ".", "toBuffer", "(", ")", ";", "// Convert Longs to proper objects or strings\r", "if", "(", "ProtoBuf", ".", "Long", ".", "isLong", "(", "obj", ")", ")", "return", "longsAsStrings", "?", "obj", ".", "toString", "(", ")", ":", "ProtoBuf", ".", "Long", ".", "fromValue", "(", "obj", ")", ";", "var", "clone", ";", "// Clone arrays\r", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "clone", "=", "[", "]", ";", "obj", ".", "forEach", "(", "function", "(", "v", ",", "k", ")", "{", "clone", "[", "k", "]", "=", "cloneRaw", "(", "v", ",", "binaryAsBase64", ",", "longsAsStrings", ",", "resolvedType", ")", ";", "}", ")", ";", "return", "clone", ";", "}", "clone", "=", "{", "}", ";", "// Convert maps to objects\r", "if", "(", "obj", "instanceof", "ProtoBuf", ".", "Map", ")", "{", "var", "it", "=", "obj", ".", "entries", "(", ")", ";", "for", "(", "var", "e", "=", "it", ".", "next", "(", ")", ";", "!", "e", ".", "done", ";", "e", "=", "it", ".", "next", "(", ")", ")", "clone", "[", "obj", ".", "keyElem", ".", "valueToString", "(", "e", ".", "value", "[", "0", "]", ")", "]", "=", "cloneRaw", "(", "e", ".", "value", "[", "1", "]", ",", "binaryAsBase64", ",", "longsAsStrings", ",", "obj", ".", "valueElem", ".", "resolvedType", ")", ";", "return", "clone", ";", "}", "// Everything else is a non-null object\r", "var", "type", "=", "obj", ".", "$type", ",", "field", "=", "undefined", ";", "for", "(", "var", "i", "in", "obj", ")", "if", "(", "obj", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "if", "(", "type", "&&", "(", "field", "=", "type", ".", "getChild", "(", "i", ")", ")", ")", "clone", "[", "i", "]", "=", "cloneRaw", "(", "obj", "[", "i", "]", ",", "binaryAsBase64", ",", "longsAsStrings", ",", "field", ".", "resolvedType", ")", ";", "else", "clone", "[", "i", "]", "=", "cloneRaw", "(", "obj", "[", "i", "]", ",", "binaryAsBase64", ",", "longsAsStrings", ")", ";", "}", "return", "clone", ";", "}" ]
Clones a message object or field value to a raw object. @param {*} obj Object to clone @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise @param {boolean} longsAsStrings Whether to encode longs as strings @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field @returns {*} Cloned object @inner
[ "Clones", "a", "message", "object", "or", "field", "value", "to", "a", "raw", "object", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L7341-L7386
41,092
elsehow/signal-protocol
build/components_concat.js
skipTillGroupEnd
function skipTillGroupEnd(expectedId, buf) { var tag = buf.readVarint32(), // Throws on OOB wireType = tag & 0x07, id = tag >>> 3; switch (wireType) { case ProtoBuf.WIRE_TYPES.VARINT: do tag = buf.readUint8(); while ((tag & 0x80) === 0x80); break; case ProtoBuf.WIRE_TYPES.BITS64: buf.offset += 8; break; case ProtoBuf.WIRE_TYPES.LDELIM: tag = buf.readVarint32(); // reads the varint buf.offset += tag; // skips n bytes break; case ProtoBuf.WIRE_TYPES.STARTGROUP: skipTillGroupEnd(id, buf); break; case ProtoBuf.WIRE_TYPES.ENDGROUP: if (id === expectedId) return false; else throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)"); case ProtoBuf.WIRE_TYPES.BITS32: buf.offset += 4; break; default: throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType); } return true; }
javascript
function skipTillGroupEnd(expectedId, buf) { var tag = buf.readVarint32(), // Throws on OOB wireType = tag & 0x07, id = tag >>> 3; switch (wireType) { case ProtoBuf.WIRE_TYPES.VARINT: do tag = buf.readUint8(); while ((tag & 0x80) === 0x80); break; case ProtoBuf.WIRE_TYPES.BITS64: buf.offset += 8; break; case ProtoBuf.WIRE_TYPES.LDELIM: tag = buf.readVarint32(); // reads the varint buf.offset += tag; // skips n bytes break; case ProtoBuf.WIRE_TYPES.STARTGROUP: skipTillGroupEnd(id, buf); break; case ProtoBuf.WIRE_TYPES.ENDGROUP: if (id === expectedId) return false; else throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)"); case ProtoBuf.WIRE_TYPES.BITS32: buf.offset += 4; break; default: throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType); } return true; }
[ "function", "skipTillGroupEnd", "(", "expectedId", ",", "buf", ")", "{", "var", "tag", "=", "buf", ".", "readVarint32", "(", ")", ",", "// Throws on OOB\r", "wireType", "=", "tag", "&", "0x07", ",", "id", "=", "tag", ">>>", "3", ";", "switch", "(", "wireType", ")", "{", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "VARINT", ":", "do", "tag", "=", "buf", ".", "readUint8", "(", ")", ";", "while", "(", "(", "tag", "&", "0x80", ")", "===", "0x80", ")", ";", "break", ";", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "BITS64", ":", "buf", ".", "offset", "+=", "8", ";", "break", ";", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "LDELIM", ":", "tag", "=", "buf", ".", "readVarint32", "(", ")", ";", "// reads the varint\r", "buf", ".", "offset", "+=", "tag", ";", "// skips n bytes\r", "break", ";", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "STARTGROUP", ":", "skipTillGroupEnd", "(", "id", ",", "buf", ")", ";", "break", ";", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "ENDGROUP", ":", "if", "(", "id", "===", "expectedId", ")", "return", "false", ";", "else", "throw", "Error", "(", "\"Illegal GROUPEND after unknown group: \"", "+", "id", "+", "\" (\"", "+", "expectedId", "+", "\" expected)\"", ")", ";", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "BITS32", ":", "buf", ".", "offset", "+=", "4", ";", "break", ";", "default", ":", "throw", "Error", "(", "\"Illegal wire type in unknown group \"", "+", "expectedId", "+", "\": \"", "+", "wireType", ")", ";", "}", "return", "true", ";", "}" ]
Skips all data until the end of the specified group has been reached. @param {number} expectedId Expected GROUPEND id @param {!ByteBuffer} buf ByteBuffer @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch) @inner
[ "Skips", "all", "data", "until", "the", "end", "of", "the", "specified", "group", "has", "been", "reached", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L7656-L7687
41,093
elsehow/signal-protocol
build/components_concat.js
function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) { T.call(this, builder, message, name); /** * @override */ this.className = "Message.Field"; /** * Message field required flag. * @type {boolean} * @expose */ this.required = rule === "required"; /** * Message field repeated flag. * @type {boolean} * @expose */ this.repeated = rule === "repeated"; /** * Message field map flag. * @type {boolean} * @expose */ this.map = rule === "map"; /** * Message field key type. Type reference string if unresolved, protobuf * type if resolved. Valid only if this.map === true, null otherwise. * @type {string|{name: string, wireType: number}|null} * @expose */ this.keyType = keytype || null; /** * Message field type. Type reference string if unresolved, protobuf type if * resolved. In a map field, this is the value type. * @type {string|{name: string, wireType: number}} * @expose */ this.type = type; /** * Resolved type reference inside the global namespace. * @type {ProtoBuf.Reflect.T|null} * @expose */ this.resolvedType = null; /** * Unique message field id. * @type {number} * @expose */ this.id = id; /** * Message field options. * @type {!Object.<string,*>} * @dict * @expose */ this.options = options || {}; /** * Default value. * @type {*} * @expose */ this.defaultValue = null; /** * Enclosing OneOf. * @type {?ProtoBuf.Reflect.Message.OneOf} * @expose */ this.oneof = oneof || null; /** * Syntax level of this definition (e.g., proto3). * @type {string} * @expose */ this.syntax = syntax || 'proto2'; /** * Original field name. * @type {string} * @expose */ this.originalName = this.name; // Used to revert camelcase transformation on naming collisions /** * Element implementation. Created in build() after types are resolved. * @type {ProtoBuf.Element} * @expose */ this.element = null; /** * Key element implementation, for map fields. Created in build() after * types are resolved. * @type {ProtoBuf.Element} * @expose */ this.keyElement = null; // Convert field names to camel case notation if the override is set if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField)) this.name = ProtoBuf.Util.toCamelCase(this.name); }
javascript
function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) { T.call(this, builder, message, name); /** * @override */ this.className = "Message.Field"; /** * Message field required flag. * @type {boolean} * @expose */ this.required = rule === "required"; /** * Message field repeated flag. * @type {boolean} * @expose */ this.repeated = rule === "repeated"; /** * Message field map flag. * @type {boolean} * @expose */ this.map = rule === "map"; /** * Message field key type. Type reference string if unresolved, protobuf * type if resolved. Valid only if this.map === true, null otherwise. * @type {string|{name: string, wireType: number}|null} * @expose */ this.keyType = keytype || null; /** * Message field type. Type reference string if unresolved, protobuf type if * resolved. In a map field, this is the value type. * @type {string|{name: string, wireType: number}} * @expose */ this.type = type; /** * Resolved type reference inside the global namespace. * @type {ProtoBuf.Reflect.T|null} * @expose */ this.resolvedType = null; /** * Unique message field id. * @type {number} * @expose */ this.id = id; /** * Message field options. * @type {!Object.<string,*>} * @dict * @expose */ this.options = options || {}; /** * Default value. * @type {*} * @expose */ this.defaultValue = null; /** * Enclosing OneOf. * @type {?ProtoBuf.Reflect.Message.OneOf} * @expose */ this.oneof = oneof || null; /** * Syntax level of this definition (e.g., proto3). * @type {string} * @expose */ this.syntax = syntax || 'proto2'; /** * Original field name. * @type {string} * @expose */ this.originalName = this.name; // Used to revert camelcase transformation on naming collisions /** * Element implementation. Created in build() after types are resolved. * @type {ProtoBuf.Element} * @expose */ this.element = null; /** * Key element implementation, for map fields. Created in build() after * types are resolved. * @type {ProtoBuf.Element} * @expose */ this.keyElement = null; // Convert field names to camel case notation if the override is set if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField)) this.name = ProtoBuf.Util.toCamelCase(this.name); }
[ "function", "(", "builder", ",", "message", ",", "rule", ",", "keytype", ",", "type", ",", "name", ",", "id", ",", "options", ",", "oneof", ",", "syntax", ")", "{", "T", ".", "call", "(", "this", ",", "builder", ",", "message", ",", "name", ")", ";", "/**\r\n * @override\r\n */", "this", ".", "className", "=", "\"Message.Field\"", ";", "/**\r\n * Message field required flag.\r\n * @type {boolean}\r\n * @expose\r\n */", "this", ".", "required", "=", "rule", "===", "\"required\"", ";", "/**\r\n * Message field repeated flag.\r\n * @type {boolean}\r\n * @expose\r\n */", "this", ".", "repeated", "=", "rule", "===", "\"repeated\"", ";", "/**\r\n * Message field map flag.\r\n * @type {boolean}\r\n * @expose\r\n */", "this", ".", "map", "=", "rule", "===", "\"map\"", ";", "/**\r\n * Message field key type. Type reference string if unresolved, protobuf\r\n * type if resolved. Valid only if this.map === true, null otherwise.\r\n * @type {string|{name: string, wireType: number}|null}\r\n * @expose\r\n */", "this", ".", "keyType", "=", "keytype", "||", "null", ";", "/**\r\n * Message field type. Type reference string if unresolved, protobuf type if\r\n * resolved. In a map field, this is the value type.\r\n * @type {string|{name: string, wireType: number}}\r\n * @expose\r\n */", "this", ".", "type", "=", "type", ";", "/**\r\n * Resolved type reference inside the global namespace.\r\n * @type {ProtoBuf.Reflect.T|null}\r\n * @expose\r\n */", "this", ".", "resolvedType", "=", "null", ";", "/**\r\n * Unique message field id.\r\n * @type {number}\r\n * @expose\r\n */", "this", ".", "id", "=", "id", ";", "/**\r\n * Message field options.\r\n * @type {!Object.<string,*>}\r\n * @dict\r\n * @expose\r\n */", "this", ".", "options", "=", "options", "||", "{", "}", ";", "/**\r\n * Default value.\r\n * @type {*}\r\n * @expose\r\n */", "this", ".", "defaultValue", "=", "null", ";", "/**\r\n * Enclosing OneOf.\r\n * @type {?ProtoBuf.Reflect.Message.OneOf}\r\n * @expose\r\n */", "this", ".", "oneof", "=", "oneof", "||", "null", ";", "/**\r\n * Syntax level of this definition (e.g., proto3).\r\n * @type {string}\r\n * @expose\r\n */", "this", ".", "syntax", "=", "syntax", "||", "'proto2'", ";", "/**\r\n * Original field name.\r\n * @type {string}\r\n * @expose\r\n */", "this", ".", "originalName", "=", "this", ".", "name", ";", "// Used to revert camelcase transformation on naming collisions\r", "/**\r\n * Element implementation. Created in build() after types are resolved.\r\n * @type {ProtoBuf.Element}\r\n * @expose\r\n */", "this", ".", "element", "=", "null", ";", "/**\r\n * Key element implementation, for map fields. Created in build() after\r\n * types are resolved.\r\n * @type {ProtoBuf.Element}\r\n * @expose\r\n */", "this", ".", "keyElement", "=", "null", ";", "// Convert field names to camel case notation if the override is set\r", "if", "(", "this", ".", "builder", ".", "options", "[", "'convertFieldsToCamelCase'", "]", "&&", "!", "(", "this", "instanceof", "Message", ".", "ExtensionField", ")", ")", "this", ".", "name", "=", "ProtoBuf", ".", "Util", ".", "toCamelCase", "(", "this", ".", "name", ")", ";", "}" ]
Constructs a new Message Field. @exports ProtoBuf.Reflect.Message.Field @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Message} message Message reference @param {string} rule Rule, one of requried, optional, repeated @param {string?} keytype Key data type, if any. @param {string} type Data type, e.g. int32 @param {string} name Field name @param {number} id Unique field id @param {Object.<string,*>=} options Options @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf @param {string?} syntax The syntax level of this definition (e.g., proto3) @constructor @extends ProtoBuf.Reflect.T
[ "Constructs", "a", "new", "Message", "Field", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L7791-L7904
41,094
elsehow/signal-protocol
build/components_concat.js
function(builder, message, rule, type, name, id, options) { Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options); /** * Extension reference. * @type {!ProtoBuf.Reflect.Extension} * @expose */ this.extension; }
javascript
function(builder, message, rule, type, name, id, options) { Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options); /** * Extension reference. * @type {!ProtoBuf.Reflect.Extension} * @expose */ this.extension; }
[ "function", "(", "builder", ",", "message", ",", "rule", ",", "type", ",", "name", ",", "id", ",", "options", ")", "{", "Field", ".", "call", "(", "this", ",", "builder", ",", "message", ",", "rule", ",", "/* keytype = */", "null", ",", "type", ",", "name", ",", "id", ",", "options", ")", ";", "/**\r\n * Extension reference.\r\n * @type {!ProtoBuf.Reflect.Extension}\r\n * @expose\r\n */", "this", ".", "extension", ";", "}" ]
Constructs a new Message ExtensionField. @exports ProtoBuf.Reflect.Message.ExtensionField @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Message} message Message reference @param {string} rule Rule, one of requried, optional, repeated @param {string} type Data type, e.g. int32 @param {string} name Field name @param {number} id Unique field id @param {!Object.<string,*>=} options Options @constructor @extends ProtoBuf.Reflect.Message.Field
[ "Constructs", "a", "new", "Message", "ExtensionField", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8253-L8262
41,095
elsehow/signal-protocol
build/components_concat.js
function(builder, parent, name, options, syntax) { Namespace.call(this, builder, parent, name, options, syntax); /** * @override */ this.className = "Enum"; /** * Runtime enum object. * @type {Object.<string,number>|null} * @expose */ this.object = null; }
javascript
function(builder, parent, name, options, syntax) { Namespace.call(this, builder, parent, name, options, syntax); /** * @override */ this.className = "Enum"; /** * Runtime enum object. * @type {Object.<string,number>|null} * @expose */ this.object = null; }
[ "function", "(", "builder", ",", "parent", ",", "name", ",", "options", ",", "syntax", ")", "{", "Namespace", ".", "call", "(", "this", ",", "builder", ",", "parent", ",", "name", ",", "options", ",", "syntax", ")", ";", "/**\r\n * @override\r\n */", "this", ".", "className", "=", "\"Enum\"", ";", "/**\r\n * Runtime enum object.\r\n * @type {Object.<string,number>|null}\r\n * @expose\r\n */", "this", ".", "object", "=", "null", ";", "}" ]
Constructs a new Enum. @exports ProtoBuf.Reflect.Enum @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.T} parent Parent Reflect object @param {string} name Enum name @param {Object.<string,*>=} options Enum options @param {string?} syntax The syntax level (e.g., proto3) @constructor @extends ProtoBuf.Reflect.Namespace
[ "Constructs", "a", "new", "Enum", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8310-L8324
41,096
elsehow/signal-protocol
build/components_concat.js
function(builder, enm, name, id) { T.call(this, builder, enm, name); /** * @override */ this.className = "Enum.Value"; /** * Unique enum value id. * @type {number} * @expose */ this.id = id; }
javascript
function(builder, enm, name, id) { T.call(this, builder, enm, name); /** * @override */ this.className = "Enum.Value"; /** * Unique enum value id. * @type {number} * @expose */ this.id = id; }
[ "function", "(", "builder", ",", "enm", ",", "name", ",", "id", ")", "{", "T", ".", "call", "(", "this", ",", "builder", ",", "enm", ",", "name", ")", ";", "/**\r\n * @override\r\n */", "this", ".", "className", "=", "\"Enum.Value\"", ";", "/**\r\n * Unique enum value id.\r\n * @type {number}\r\n * @expose\r\n */", "this", ".", "id", "=", "id", ";", "}" ]
Constructs a new Enum Value. @exports ProtoBuf.Reflect.Enum.Value @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Enum} enm Enum reference @param {string} name Field name @param {number} id Unique field id @constructor @extends ProtoBuf.Reflect.T
[ "Constructs", "a", "new", "Enum", "Value", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8384-L8398
41,097
elsehow/signal-protocol
build/components_concat.js
function(builder, root, name, options) { Namespace.call(this, builder, root, name, options); /** * @override */ this.className = "Service"; /** * Built runtime service class. * @type {?function(new:ProtoBuf.Builder.Service)} */ this.clazz = null; }
javascript
function(builder, root, name, options) { Namespace.call(this, builder, root, name, options); /** * @override */ this.className = "Service"; /** * Built runtime service class. * @type {?function(new:ProtoBuf.Builder.Service)} */ this.clazz = null; }
[ "function", "(", "builder", ",", "root", ",", "name", ",", "options", ")", "{", "Namespace", ".", "call", "(", "this", ",", "builder", ",", "root", ",", "name", ",", "options", ")", ";", "/**\r\n * @override\r\n */", "this", ".", "className", "=", "\"Service\"", ";", "/**\r\n * Built runtime service class.\r\n * @type {?function(new:ProtoBuf.Builder.Service)}\r\n */", "this", ".", "clazz", "=", "null", ";", "}" ]
Constructs a new Service. @exports ProtoBuf.Reflect.Service @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Namespace} root Root @param {string} name Service name @param {Object.<string,*>=} options Options @constructor @extends ProtoBuf.Reflect.Namespace
[ "Constructs", "a", "new", "Service", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8448-L8461
41,098
elsehow/signal-protocol
build/components_concat.js
function(rpcImpl) { ProtoBuf.Builder.Service.call(this); /** * Service implementation. * @name ProtoBuf.Builder.Service#rpcImpl * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} * @expose */ this.rpcImpl = rpcImpl || function(name, msg, callback) { // This is what a user has to implement: A function receiving the method name, the actual message to // send (type checked) and the callback that's either provided with the error as its first // argument or null and the actual response message. setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async! }; }
javascript
function(rpcImpl) { ProtoBuf.Builder.Service.call(this); /** * Service implementation. * @name ProtoBuf.Builder.Service#rpcImpl * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} * @expose */ this.rpcImpl = rpcImpl || function(name, msg, callback) { // This is what a user has to implement: A function receiving the method name, the actual message to // send (type checked) and the callback that's either provided with the error as its first // argument or null and the actual response message. setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async! }; }
[ "function", "(", "rpcImpl", ")", "{", "ProtoBuf", ".", "Builder", ".", "Service", ".", "call", "(", "this", ")", ";", "/**\r\n * Service implementation.\r\n * @name ProtoBuf.Builder.Service#rpcImpl\r\n * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))}\r\n * @expose\r\n */", "this", ".", "rpcImpl", "=", "rpcImpl", "||", "function", "(", "name", ",", "msg", ",", "callback", ")", "{", "// This is what a user has to implement: A function receiving the method name, the actual message to\r", "// send (type checked) and the callback that's either provided with the error as its first\r", "// argument or null and the actual response message.\r", "setTimeout", "(", "callback", ".", "bind", "(", "this", ",", "Error", "(", "\"Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services\"", ")", ")", ",", "0", ")", ";", "// Must be async!\r", "}", ";", "}" ]
Constructs a new runtime Service. @name ProtoBuf.Builder.Service @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message @class Barebone of all runtime services. @constructor @throws {Error} If the service cannot be created
[ "Constructs", "a", "new", "runtime", "Service", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8492-L8507
41,099
elsehow/signal-protocol
build/components_concat.js
function(builder, svc, name, options) { T.call(this, builder, svc, name); /** * @override */ this.className = "Service.Method"; /** * Options. * @type {Object.<string, *>} * @expose */ this.options = options || {}; }
javascript
function(builder, svc, name, options) { T.call(this, builder, svc, name); /** * @override */ this.className = "Service.Method"; /** * Options. * @type {Object.<string, *>} * @expose */ this.options = options || {}; }
[ "function", "(", "builder", ",", "svc", ",", "name", ",", "options", ")", "{", "T", ".", "call", "(", "this", ",", "builder", ",", "svc", ",", "name", ")", ";", "/**\r\n * @override\r\n */", "this", ".", "className", "=", "\"Service.Method\"", ";", "/**\r\n * Options.\r\n * @type {Object.<string, *>}\r\n * @expose\r\n */", "this", ".", "options", "=", "options", "||", "{", "}", ";", "}" ]
Abstract service method. @exports ProtoBuf.Reflect.Service.Method @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Service} svc Service @param {string} name Method name @param {Object.<string,*>=} options Options @constructor @extends ProtoBuf.Reflect.T
[ "Abstract", "service", "method", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8646-L8660