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
17,500
ruddell/ignite-jhipster
boilerplate/app/shared/websockets/websocket.service.js
subscribeToChat
function subscribeToChat () { console.tron.log('Subscribing to Chat') if (!subscriptions.hasOwnProperty('chat')) { subscriptions.chat = { subscribed: true } connection.then(() => { chatSubscriber = stompClient.subscribe('/topic/chat', onMessage.bind(this, 'chat')) }) } }
javascript
function subscribeToChat () { console.tron.log('Subscribing to Chat') if (!subscriptions.hasOwnProperty('chat')) { subscriptions.chat = { subscribed: true } connection.then(() => { chatSubscriber = stompClient.subscribe('/topic/chat', onMessage.bind(this, 'chat')) }) } }
[ "function", "subscribeToChat", "(", ")", "{", "console", ".", "tron", ".", "log", "(", "'Subscribing to Chat'", ")", "if", "(", "!", "subscriptions", ".", "hasOwnProperty", "(", "'chat'", ")", ")", "{", "subscriptions", ".", "chat", "=", "{", "subscribed", ":", "true", "}", "connection", ".", "then", "(", "(", ")", "=>", "{", "chatSubscriber", "=", "stompClient", ".", "subscribe", "(", "'/topic/chat'", ",", "onMessage", ".", "bind", "(", "this", ",", "'chat'", ")", ")", "}", ")", "}", "}" ]
methods for subscribing
[ "methods", "for", "subscribing" ]
301c3aa9e4286715b0f5ad6f32f516672ea8d09d
https://github.com/ruddell/ignite-jhipster/blob/301c3aa9e4286715b0f5ad6f32f516672ea8d09d/boilerplate/app/shared/websockets/websocket.service.js#L93-L101
17,501
ruddell/ignite-jhipster
boilerplate/app/shared/websockets/websocket.service.js
sendChat
function sendChat (ev) { if (stompClient !== null && stompClient.connected) { var p = '/topic/chat' stompClient.send(p, {}, JSON.stringify(ev)) } }
javascript
function sendChat (ev) { if (stompClient !== null && stompClient.connected) { var p = '/topic/chat' stompClient.send(p, {}, JSON.stringify(ev)) } }
[ "function", "sendChat", "(", "ev", ")", "{", "if", "(", "stompClient", "!==", "null", "&&", "stompClient", ".", "connected", ")", "{", "var", "p", "=", "'/topic/chat'", "stompClient", ".", "send", "(", "p", ",", "{", "}", ",", "JSON", ".", "stringify", "(", "ev", ")", ")", "}", "}" ]
methods for sending
[ "methods", "for", "sending" ]
301c3aa9e4286715b0f5ad6f32f516672ea8d09d
https://github.com/ruddell/ignite-jhipster/blob/301c3aa9e4286715b0f5ad6f32f516672ea8d09d/boilerplate/app/shared/websockets/websocket.service.js#L112-L117
17,502
ruddell/ignite-jhipster
boilerplate/app/shared/websockets/websocket.service.js
onMessage
function onMessage (subscription, fullMessage) { let msg = null try { msg = JSON.parse(fullMessage.body) } catch (fullMessage) { console.tron.error(`Error parsing : ${fullMessage}`) } if (msg) { return em({ subscription, msg }) } }
javascript
function onMessage (subscription, fullMessage) { let msg = null try { msg = JSON.parse(fullMessage.body) } catch (fullMessage) { console.tron.error(`Error parsing : ${fullMessage}`) } if (msg) { return em({ subscription, msg }) } }
[ "function", "onMessage", "(", "subscription", ",", "fullMessage", ")", "{", "let", "msg", "=", "null", "try", "{", "msg", "=", "JSON", ".", "parse", "(", "fullMessage", ".", "body", ")", "}", "catch", "(", "fullMessage", ")", "{", "console", ".", "tron", ".", "error", "(", "`", "${", "fullMessage", "}", "`", ")", "}", "if", "(", "msg", ")", "{", "return", "em", "(", "{", "subscription", ",", "msg", "}", ")", "}", "}" ]
when the message is received, send it to the WebsocketSaga
[ "when", "the", "message", "is", "received", "send", "it", "to", "the", "WebsocketSaga" ]
301c3aa9e4286715b0f5ad6f32f516672ea8d09d
https://github.com/ruddell/ignite-jhipster/blob/301c3aa9e4286715b0f5ad6f32f516672ea8d09d/boilerplate/app/shared/websockets/websocket.service.js#L120-L130
17,503
ruddell/ignite-jhipster
boilerplate/app/shared/websockets/websocket.service.js
generateInterval
function generateInterval (k) { let maxInterval = (Math.pow(2, k) - 1) * 1000 if (maxInterval > 30 * 1000) { // If the generated interval is more than 30 seconds, truncate it down to 30 seconds. maxInterval = 30 * 1000 } // generate the interval to a random number between 0 and the maxInterval determined from above return Math.random() * maxInterval }
javascript
function generateInterval (k) { let maxInterval = (Math.pow(2, k) - 1) * 1000 if (maxInterval > 30 * 1000) { // If the generated interval is more than 30 seconds, truncate it down to 30 seconds. maxInterval = 30 * 1000 } // generate the interval to a random number between 0 and the maxInterval determined from above return Math.random() * maxInterval }
[ "function", "generateInterval", "(", "k", ")", "{", "let", "maxInterval", "=", "(", "Math", ".", "pow", "(", "2", ",", "k", ")", "-", "1", ")", "*", "1000", "if", "(", "maxInterval", ">", "30", "*", "1000", ")", "{", "// If the generated interval is more than 30 seconds, truncate it down to 30 seconds.", "maxInterval", "=", "30", "*", "1000", "}", "// generate the interval to a random number between 0 and the maxInterval determined from above", "return", "Math", ".", "random", "(", ")", "*", "maxInterval", "}" ]
exponential backoff for reconnections
[ "exponential", "backoff", "for", "reconnections" ]
301c3aa9e4286715b0f5ad6f32f516672ea8d09d
https://github.com/ruddell/ignite-jhipster/blob/301c3aa9e4286715b0f5ad6f32f516672ea8d09d/boilerplate/app/shared/websockets/websocket.service.js#L164-L173
17,504
ztoben/assets-webpack-plugin
lib/pathTemplate.js
function (data) { return this.fields.reduce(function (output, field) { var replacement = '' var placeholder = field.placeholder var width = field.width if (field.prefix) { output += field.prefix } if (placeholder) { replacement = data[placeholder] || '' if (width && (placeholder === 'hash' || placeholder === 'chunkhash')) { replacement = replacement.slice(0, width) } output += replacement } return output }, '') }
javascript
function (data) { return this.fields.reduce(function (output, field) { var replacement = '' var placeholder = field.placeholder var width = field.width if (field.prefix) { output += field.prefix } if (placeholder) { replacement = data[placeholder] || '' if (width && (placeholder === 'hash' || placeholder === 'chunkhash')) { replacement = replacement.slice(0, width) } output += replacement } return output }, '') }
[ "function", "(", "data", ")", "{", "return", "this", ".", "fields", ".", "reduce", "(", "function", "(", "output", ",", "field", ")", "{", "var", "replacement", "=", "''", "var", "placeholder", "=", "field", ".", "placeholder", "var", "width", "=", "field", ".", "width", "if", "(", "field", ".", "prefix", ")", "{", "output", "+=", "field", ".", "prefix", "}", "if", "(", "placeholder", ")", "{", "replacement", "=", "data", "[", "placeholder", "]", "||", "''", "if", "(", "width", "&&", "(", "placeholder", "===", "'hash'", "||", "placeholder", "===", "'chunkhash'", ")", ")", "{", "replacement", "=", "replacement", ".", "slice", "(", "0", ",", "width", ")", "}", "output", "+=", "replacement", "}", "return", "output", "}", ",", "''", ")", "}" ]
Applies data to this template and outputs a filename. @param Object data
[ "Applies", "data", "to", "this", "template", "and", "outputs", "a", "filename", "." ]
1a3239f3f7f01301154e51ba0a7ce6fd362a629a
https://github.com/ztoben/assets-webpack-plugin/blob/1a3239f3f7f01301154e51ba0a7ce6fd362a629a/lib/pathTemplate.js#L40-L59
17,505
IonicaBizau/medium-editor-markdown
dist/me-markdown.standalone.js
Rules
function Rules (options) { this.options = options; this._keep = []; this._remove = []; this.blankRule = { replacement: options.blankReplacement }; this.keepReplacement = options.keepReplacement; this.defaultRule = { replacement: options.defaultReplacement }; this.array = []; for (var key in options.rules) this.array.push(options.rules[key]); }
javascript
function Rules (options) { this.options = options; this._keep = []; this._remove = []; this.blankRule = { replacement: options.blankReplacement }; this.keepReplacement = options.keepReplacement; this.defaultRule = { replacement: options.defaultReplacement }; this.array = []; for (var key in options.rules) this.array.push(options.rules[key]); }
[ "function", "Rules", "(", "options", ")", "{", "this", ".", "options", "=", "options", ";", "this", ".", "_keep", "=", "[", "]", ";", "this", ".", "_remove", "=", "[", "]", ";", "this", ".", "blankRule", "=", "{", "replacement", ":", "options", ".", "blankReplacement", "}", ";", "this", ".", "keepReplacement", "=", "options", ".", "keepReplacement", ";", "this", ".", "defaultRule", "=", "{", "replacement", ":", "options", ".", "defaultReplacement", "}", ";", "this", ".", "array", "=", "[", "]", ";", "for", "(", "var", "key", "in", "options", ".", "rules", ")", "this", ".", "array", ".", "push", "(", "options", ".", "rules", "[", "key", "]", ")", ";", "}" ]
Manages a collection of rules used to convert HTML to Markdown
[ "Manages", "a", "collection", "of", "rules", "used", "to", "convert", "HTML", "to", "Markdown" ]
e35601361d4708c8077199e58b8b09700c6bd059
https://github.com/IonicaBizau/medium-editor-markdown/blob/e35601361d4708c8077199e58b8b09700c6bd059/dist/me-markdown.standalone.js#L299-L316
17,506
IonicaBizau/medium-editor-markdown
dist/me-markdown.standalone.js
function (input) { if (!canConvert(input)) { throw new TypeError( input + ' is not a string, or an element/document/fragment node.' ) } if (input === '') return '' var output = process.call(this, new RootNode(input)); return postProcess.call(this, output) }
javascript
function (input) { if (!canConvert(input)) { throw new TypeError( input + ' is not a string, or an element/document/fragment node.' ) } if (input === '') return '' var output = process.call(this, new RootNode(input)); return postProcess.call(this, output) }
[ "function", "(", "input", ")", "{", "if", "(", "!", "canConvert", "(", "input", ")", ")", "{", "throw", "new", "TypeError", "(", "input", "+", "' is not a string, or an element/document/fragment node.'", ")", "}", "if", "(", "input", "===", "''", ")", "return", "''", "var", "output", "=", "process", ".", "call", "(", "this", ",", "new", "RootNode", "(", "input", ")", ")", ";", "return", "postProcess", ".", "call", "(", "this", ",", "output", ")", "}" ]
The entry point for converting a string or DOM node to Markdown @public @param {String|HTMLElement} input The string or DOM node to convert @returns A Markdown representation of the input @type String
[ "The", "entry", "point", "for", "converting", "a", "string", "or", "DOM", "node", "to", "Markdown" ]
e35601361d4708c8077199e58b8b09700c6bd059
https://github.com/IonicaBizau/medium-editor-markdown/blob/e35601361d4708c8077199e58b8b09700c6bd059/dist/me-markdown.standalone.js#L699-L710
17,507
IonicaBizau/medium-editor-markdown
dist/me-markdown.standalone.js
function (plugin) { if (Array.isArray(plugin)) { for (var i = 0; i < plugin.length; i++) this.use(plugin[i]); } else if (typeof plugin === 'function') { plugin(this); } else { throw new TypeError('plugin must be a Function or an Array of Functions') } return this }
javascript
function (plugin) { if (Array.isArray(plugin)) { for (var i = 0; i < plugin.length; i++) this.use(plugin[i]); } else if (typeof plugin === 'function') { plugin(this); } else { throw new TypeError('plugin must be a Function or an Array of Functions') } return this }
[ "function", "(", "plugin", ")", "{", "if", "(", "Array", ".", "isArray", "(", "plugin", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "plugin", ".", "length", ";", "i", "++", ")", "this", ".", "use", "(", "plugin", "[", "i", "]", ")", ";", "}", "else", "if", "(", "typeof", "plugin", "===", "'function'", ")", "{", "plugin", "(", "this", ")", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "'plugin must be a Function or an Array of Functions'", ")", "}", "return", "this", "}" ]
Add one or more plugins @public @param {Function|Array} plugin The plugin or array of plugins to add @returns The Turndown instance for chaining @type Object
[ "Add", "one", "or", "more", "plugins" ]
e35601361d4708c8077199e58b8b09700c6bd059
https://github.com/IonicaBizau/medium-editor-markdown/blob/e35601361d4708c8077199e58b8b09700c6bd059/dist/me-markdown.standalone.js#L720-L729
17,508
IonicaBizau/medium-editor-markdown
dist/me-markdown.standalone.js
function (string) { return ( string // Escape backslash escapes! .replace(/\\(\S)/g, '\\\\$1') // Escape headings .replace(/^(#{1,6} )/gm, '\\$1') // Escape hr .replace(/^([-*_] *){3,}$/gm, function (match, character) { return match.split(character).join('\\' + character) }) // Escape ol bullet points .replace(/^(\W* {0,3})(\d+)\. /gm, '$1$2\\. ') // Escape ul bullet points .replace(/^([^\\\w]*)[*+-] /gm, function (match) { return match.replace(/([*+-])/g, '\\$1') }) // Escape blockquote indents .replace(/^(\W* {0,3})> /gm, '$1\\> ') // Escape em/strong * .replace(/\*+(?![*\s\W]).+?\*+/g, function (match) { return match.replace(/\*/g, '\\*') }) // Escape em/strong _ .replace(/_+(?![_\s\W]).+?_+/g, function (match) { return match.replace(/_/g, '\\_') }) // Escape code _ .replace(/`+(?![`\s\W]).+?`+/g, function (match) { return match.replace(/`/g, '\\`') }) // Escape link brackets .replace(/[\[\]]/g, '\\{{{toMarkdown}}}') // eslint-disable-line no-useless-escape ) }
javascript
function (string) { return ( string // Escape backslash escapes! .replace(/\\(\S)/g, '\\\\$1') // Escape headings .replace(/^(#{1,6} )/gm, '\\$1') // Escape hr .replace(/^([-*_] *){3,}$/gm, function (match, character) { return match.split(character).join('\\' + character) }) // Escape ol bullet points .replace(/^(\W* {0,3})(\d+)\. /gm, '$1$2\\. ') // Escape ul bullet points .replace(/^([^\\\w]*)[*+-] /gm, function (match) { return match.replace(/([*+-])/g, '\\$1') }) // Escape blockquote indents .replace(/^(\W* {0,3})> /gm, '$1\\> ') // Escape em/strong * .replace(/\*+(?![*\s\W]).+?\*+/g, function (match) { return match.replace(/\*/g, '\\*') }) // Escape em/strong _ .replace(/_+(?![_\s\W]).+?_+/g, function (match) { return match.replace(/_/g, '\\_') }) // Escape code _ .replace(/`+(?![`\s\W]).+?`+/g, function (match) { return match.replace(/`/g, '\\`') }) // Escape link brackets .replace(/[\[\]]/g, '\\{{{toMarkdown}}}') // eslint-disable-line no-useless-escape ) }
[ "function", "(", "string", ")", "{", "return", "(", "string", "// Escape backslash escapes!", ".", "replace", "(", "/", "\\\\(\\S)", "/", "g", ",", "'\\\\\\\\$1'", ")", "// Escape headings", ".", "replace", "(", "/", "^(#{1,6} )", "/", "gm", ",", "'\\\\$1'", ")", "// Escape hr", ".", "replace", "(", "/", "^([-*_] *){3,}$", "/", "gm", ",", "function", "(", "match", ",", "character", ")", "{", "return", "match", ".", "split", "(", "character", ")", ".", "join", "(", "'\\\\'", "+", "character", ")", "}", ")", "// Escape ol bullet points", ".", "replace", "(", "/", "^(\\W* {0,3})(\\d+)\\. ", "/", "gm", ",", "'$1$2\\\\. '", ")", "// Escape ul bullet points", ".", "replace", "(", "/", "^([^\\\\\\w]*)[*+-] ", "/", "gm", ",", "function", "(", "match", ")", "{", "return", "match", ".", "replace", "(", "/", "([*+-])", "/", "g", ",", "'\\\\$1'", ")", "}", ")", "// Escape blockquote indents", ".", "replace", "(", "/", "^(\\W* {0,3})> ", "/", "gm", ",", "'$1\\\\> '", ")", "// Escape em/strong *", ".", "replace", "(", "/", "\\*+(?![*\\s\\W]).+?\\*+", "/", "g", ",", "function", "(", "match", ")", "{", "return", "match", ".", "replace", "(", "/", "\\*", "/", "g", ",", "'\\\\*'", ")", "}", ")", "// Escape em/strong _", ".", "replace", "(", "/", "_+(?![_\\s\\W]).+?_+", "/", "g", ",", "function", "(", "match", ")", "{", "return", "match", ".", "replace", "(", "/", "_", "/", "g", ",", "'\\\\_'", ")", "}", ")", "// Escape code _", ".", "replace", "(", "/", "`+(?![`\\s\\W]).+?`+", "/", "g", ",", "function", "(", "match", ")", "{", "return", "match", ".", "replace", "(", "/", "`", "/", "g", ",", "'\\\\`'", ")", "}", ")", "// Escape link brackets", ".", "replace", "(", "/", "[\\[\\]]", "/", "g", ",", "'\\\\{{{toMarkdown}}}'", ")", "// eslint-disable-line no-useless-escape", ")", "}" ]
Escapes Markdown syntax @public @param {String} string The string to escape @returns A string with Markdown syntax escaped @type String
[ "Escapes", "Markdown", "syntax" ]
e35601361d4708c8077199e58b8b09700c6bd059
https://github.com/IonicaBizau/medium-editor-markdown/blob/e35601361d4708c8077199e58b8b09700c6bd059/dist/me-markdown.standalone.js#L779-L822
17,509
IonicaBizau/medium-editor-markdown
dist/me-markdown.standalone.js
process
function process (parentNode) { var self = this; return reduce.call(parentNode.childNodes, function (output, node) { node = new Node(node); var replacement = ''; if (node.nodeType === 3) { replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue); } else if (node.nodeType === 1) { replacement = replacementForNode.call(self, node); } return join(output, replacement) }, '') }
javascript
function process (parentNode) { var self = this; return reduce.call(parentNode.childNodes, function (output, node) { node = new Node(node); var replacement = ''; if (node.nodeType === 3) { replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue); } else if (node.nodeType === 1) { replacement = replacementForNode.call(self, node); } return join(output, replacement) }, '') }
[ "function", "process", "(", "parentNode", ")", "{", "var", "self", "=", "this", ";", "return", "reduce", ".", "call", "(", "parentNode", ".", "childNodes", ",", "function", "(", "output", ",", "node", ")", "{", "node", "=", "new", "Node", "(", "node", ")", ";", "var", "replacement", "=", "''", ";", "if", "(", "node", ".", "nodeType", "===", "3", ")", "{", "replacement", "=", "node", ".", "isCode", "?", "node", ".", "nodeValue", ":", "self", ".", "escape", "(", "node", ".", "nodeValue", ")", ";", "}", "else", "if", "(", "node", ".", "nodeType", "===", "1", ")", "{", "replacement", "=", "replacementForNode", ".", "call", "(", "self", ",", "node", ")", ";", "}", "return", "join", "(", "output", ",", "replacement", ")", "}", ",", "''", ")", "}" ]
Reduces a DOM node down to its Markdown string equivalent @private @param {HTMLElement} parentNode The node to convert @returns A Markdown representation of the node @type String
[ "Reduces", "a", "DOM", "node", "down", "to", "its", "Markdown", "string", "equivalent" ]
e35601361d4708c8077199e58b8b09700c6bd059
https://github.com/IonicaBizau/medium-editor-markdown/blob/e35601361d4708c8077199e58b8b09700c6bd059/dist/me-markdown.standalone.js#L833-L847
17,510
IonicaBizau/medium-editor-markdown
dist/me-markdown.standalone.js
postProcess
function postProcess (output) { var self = this; this.rules.forEach(function (rule) { if (typeof rule.append === 'function') { output = join(output, rule.append(self.options)); } }); return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '') }
javascript
function postProcess (output) { var self = this; this.rules.forEach(function (rule) { if (typeof rule.append === 'function') { output = join(output, rule.append(self.options)); } }); return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '') }
[ "function", "postProcess", "(", "output", ")", "{", "var", "self", "=", "this", ";", "this", ".", "rules", ".", "forEach", "(", "function", "(", "rule", ")", "{", "if", "(", "typeof", "rule", ".", "append", "===", "'function'", ")", "{", "output", "=", "join", "(", "output", ",", "rule", ".", "append", "(", "self", ".", "options", ")", ")", ";", "}", "}", ")", ";", "return", "output", ".", "replace", "(", "/", "^[\\t\\r\\n]+", "/", ",", "''", ")", ".", "replace", "(", "/", "[\\t\\r\\n\\s]+$", "/", ",", "''", ")", "}" ]
Appends strings as each rule requires and trims the output @private @param {String} output The conversion output @returns A trimmed version of the ouput @type String
[ "Appends", "strings", "as", "each", "rule", "requires", "and", "trims", "the", "output" ]
e35601361d4708c8077199e58b8b09700c6bd059
https://github.com/IonicaBizau/medium-editor-markdown/blob/e35601361d4708c8077199e58b8b09700c6bd059/dist/me-markdown.standalone.js#L857-L866
17,511
wix/protractor-helpers
dist/protractor-helpers.js
function (matchedValue, expectedValue, currencySymbol, isFraction) { // get value with fraction expectedValue = getNumberWithCommas(expectedValue); if (isFraction === true && expectedValue.indexOf('.') === -1) { expectedValue += '.00'; } // add minus and symbol if needed var expression = '^'; if (matchedValue.indexOf('-') !== -1) { expression += '-'; } expression += '\\s*'; if (typeof currencySymbol === 'string') { expression += '\\' + currencySymbol + '\\s*'; } return new RegExp(expression + expectedValue + '$'); }
javascript
function (matchedValue, expectedValue, currencySymbol, isFraction) { // get value with fraction expectedValue = getNumberWithCommas(expectedValue); if (isFraction === true && expectedValue.indexOf('.') === -1) { expectedValue += '.00'; } // add minus and symbol if needed var expression = '^'; if (matchedValue.indexOf('-') !== -1) { expression += '-'; } expression += '\\s*'; if (typeof currencySymbol === 'string') { expression += '\\' + currencySymbol + '\\s*'; } return new RegExp(expression + expectedValue + '$'); }
[ "function", "(", "matchedValue", ",", "expectedValue", ",", "currencySymbol", ",", "isFraction", ")", "{", "// get value with fraction", "expectedValue", "=", "getNumberWithCommas", "(", "expectedValue", ")", ";", "if", "(", "isFraction", "===", "true", "&&", "expectedValue", ".", "indexOf", "(", "'.'", ")", "===", "-", "1", ")", "{", "expectedValue", "+=", "'.00'", ";", "}", "// add minus and symbol if needed", "var", "expression", "=", "'^'", ";", "if", "(", "matchedValue", ".", "indexOf", "(", "'-'", ")", "!==", "-", "1", ")", "{", "expression", "+=", "'-'", ";", "}", "expression", "+=", "'\\\\s*'", ";", "if", "(", "typeof", "currencySymbol", "===", "'string'", ")", "{", "expression", "+=", "'\\\\'", "+", "currencySymbol", "+", "'\\\\s*'", ";", "}", "return", "new", "RegExp", "(", "expression", "+", "expectedValue", "+", "'$'", ")", ";", "}" ]
Creates a regular expression to match money representation with or without spaces in between @param matchedValue - the number that is tested @param expectedValue - the number to match against @param currencySymbol[optional] {string} - the symbol to match against. if not specify - validate that there is no symbol. @param isFraction[optional] {boolean} - flag to add the necessary postfix to expectedValue @returns {RegExp}
[ "Creates", "a", "regular", "expression", "to", "match", "money", "representation", "with", "or", "without", "spaces", "in", "between" ]
f496e47c38e4de2e847c300bfead6c9f17a52bcc
https://github.com/wix/protractor-helpers/blob/f496e47c38e4de2e847c300bfead6c9f17a52bcc/dist/protractor-helpers.js#L297-L314
17,512
hsluv/hsluv
website/generate-images.js
round
function round(num, places) { const n = Math.pow(10, places); return Math.round(num * n) / n; }
javascript
function round(num, places) { const n = Math.pow(10, places); return Math.round(num * n) / n; }
[ "function", "round", "(", "num", ",", "places", ")", "{", "const", "n", "=", "Math", ".", "pow", "(", "10", ",", "places", ")", ";", "return", "Math", ".", "round", "(", "num", "*", "n", ")", "/", "n", ";", "}" ]
Rounds number to a given number of decimal places
[ "Rounds", "number", "to", "a", "given", "number", "of", "decimal", "places" ]
ba6a9ee7d80eb669ba90de975902b0bf574fd045
https://github.com/hsluv/hsluv/blob/ba6a9ee7d80eb669ba90de975902b0bf574fd045/website/generate-images.js#L64-L67
17,513
bbecquet/Leaflet.PolylineDecorator
src/L.PolylineDecorator.js
function(patternDef, latLngs) { return { symbolFactory: patternDef.symbol, // Parse offset and repeat values, managing the two cases: // absolute (in pixels) or relative (in percentage of the polyline length) offset: parseRelativeOrAbsoluteValue(patternDef.offset), endOffset: parseRelativeOrAbsoluteValue(patternDef.endOffset), repeat: parseRelativeOrAbsoluteValue(patternDef.repeat), }; }
javascript
function(patternDef, latLngs) { return { symbolFactory: patternDef.symbol, // Parse offset and repeat values, managing the two cases: // absolute (in pixels) or relative (in percentage of the polyline length) offset: parseRelativeOrAbsoluteValue(patternDef.offset), endOffset: parseRelativeOrAbsoluteValue(patternDef.endOffset), repeat: parseRelativeOrAbsoluteValue(patternDef.repeat), }; }
[ "function", "(", "patternDef", ",", "latLngs", ")", "{", "return", "{", "symbolFactory", ":", "patternDef", ".", "symbol", ",", "// Parse offset and repeat values, managing the two cases:", "// absolute (in pixels) or relative (in percentage of the polyline length)", "offset", ":", "parseRelativeOrAbsoluteValue", "(", "patternDef", ".", "offset", ")", ",", "endOffset", ":", "parseRelativeOrAbsoluteValue", "(", "patternDef", ".", "endOffset", ")", ",", "repeat", ":", "parseRelativeOrAbsoluteValue", "(", "patternDef", ".", "repeat", ")", ",", "}", ";", "}" ]
Parse the pattern definition
[ "Parse", "the", "pattern", "definition" ]
96858e837a07c08e08dbba1c6751abdec9a85433
https://github.com/bbecquet/Leaflet.PolylineDecorator/blob/96858e837a07c08e08dbba1c6751abdec9a85433/src/L.PolylineDecorator.js#L80-L89
17,514
bbecquet/Leaflet.PolylineDecorator
src/L.PolylineDecorator.js
function() { const allPathCoords = this._paths.reduce((acc, path) => acc.concat(path), []); return L.latLngBounds(allPathCoords); }
javascript
function() { const allPathCoords = this._paths.reduce((acc, path) => acc.concat(path), []); return L.latLngBounds(allPathCoords); }
[ "function", "(", ")", "{", "const", "allPathCoords", "=", "this", ".", "_paths", ".", "reduce", "(", "(", "acc", ",", "path", ")", "=>", "acc", ".", "concat", "(", "path", ")", ",", "[", "]", ")", ";", "return", "L", ".", "latLngBounds", "(", "allPathCoords", ")", ";", "}" ]
As real pattern bounds depends on map zoom and bounds, we just compute the total bounds of all paths decorated by this instance.
[ "As", "real", "pattern", "bounds", "depends", "on", "map", "zoom", "and", "bounds", "we", "just", "compute", "the", "total", "bounds", "of", "all", "paths", "decorated", "by", "this", "instance", "." ]
96858e837a07c08e08dbba1c6751abdec9a85433
https://github.com/bbecquet/Leaflet.PolylineDecorator/blob/96858e837a07c08e08dbba1c6751abdec9a85433/src/L.PolylineDecorator.js#L107-L110
17,515
bbecquet/Leaflet.PolylineDecorator
src/L.PolylineDecorator.js
function(latLngs, symbolFactory, directionPoints) { return directionPoints.map((directionPoint, i) => symbolFactory.buildSymbol(directionPoint, latLngs, this._map, i, directionPoints.length) ); }
javascript
function(latLngs, symbolFactory, directionPoints) { return directionPoints.map((directionPoint, i) => symbolFactory.buildSymbol(directionPoint, latLngs, this._map, i, directionPoints.length) ); }
[ "function", "(", "latLngs", ",", "symbolFactory", ",", "directionPoints", ")", "{", "return", "directionPoints", ".", "map", "(", "(", "directionPoint", ",", "i", ")", "=>", "symbolFactory", ".", "buildSymbol", "(", "directionPoint", ",", "latLngs", ",", "this", ".", "_map", ",", "i", ",", "directionPoints", ".", "length", ")", ")", ";", "}" ]
Returns an array of ILayers object
[ "Returns", "an", "array", "of", "ILayers", "object" ]
96858e837a07c08e08dbba1c6751abdec9a85433
https://github.com/bbecquet/Leaflet.PolylineDecorator/blob/96858e837a07c08e08dbba1c6751abdec9a85433/src/L.PolylineDecorator.js#L119-L123
17,516
bbecquet/Leaflet.PolylineDecorator
src/L.PolylineDecorator.js
function(latLngs, pattern) { if (latLngs.length < 2) { return []; } const pathAsPoints = latLngs.map(latLng => this._map.project(latLng)); return projectPatternOnPointPath(pathAsPoints, pattern) .map(point => ({ latLng: this._map.unproject(L.point(point.pt)), heading: point.heading, })); }
javascript
function(latLngs, pattern) { if (latLngs.length < 2) { return []; } const pathAsPoints = latLngs.map(latLng => this._map.project(latLng)); return projectPatternOnPointPath(pathAsPoints, pattern) .map(point => ({ latLng: this._map.unproject(L.point(point.pt)), heading: point.heading, })); }
[ "function", "(", "latLngs", ",", "pattern", ")", "{", "if", "(", "latLngs", ".", "length", "<", "2", ")", "{", "return", "[", "]", ";", "}", "const", "pathAsPoints", "=", "latLngs", ".", "map", "(", "latLng", "=>", "this", ".", "_map", ".", "project", "(", "latLng", ")", ")", ";", "return", "projectPatternOnPointPath", "(", "pathAsPoints", ",", "pattern", ")", ".", "map", "(", "point", "=>", "(", "{", "latLng", ":", "this", ".", "_map", ".", "unproject", "(", "L", ".", "point", "(", "point", ".", "pt", ")", ")", ",", "heading", ":", "point", ".", "heading", ",", "}", ")", ")", ";", "}" ]
Compute pairs of LatLng and heading angle, that define positions and directions of the symbols on the path
[ "Compute", "pairs", "of", "LatLng", "and", "heading", "angle", "that", "define", "positions", "and", "directions", "of", "the", "symbols", "on", "the", "path" ]
96858e837a07c08e08dbba1c6751abdec9a85433
https://github.com/bbecquet/Leaflet.PolylineDecorator/blob/96858e837a07c08e08dbba1c6751abdec9a85433/src/L.PolylineDecorator.js#L129-L139
17,517
bbecquet/Leaflet.PolylineDecorator
src/L.PolylineDecorator.js
function(pattern) { const mapBounds = this._map.getBounds().pad(0.1); return this._paths.map(path => { const directionPoints = this._getDirectionPoints(path, pattern) // filter out invisible points .filter(point => mapBounds.contains(point.latLng)); return L.featureGroup(this._buildSymbols(path, pattern.symbolFactory, directionPoints)); }); }
javascript
function(pattern) { const mapBounds = this._map.getBounds().pad(0.1); return this._paths.map(path => { const directionPoints = this._getDirectionPoints(path, pattern) // filter out invisible points .filter(point => mapBounds.contains(point.latLng)); return L.featureGroup(this._buildSymbols(path, pattern.symbolFactory, directionPoints)); }); }
[ "function", "(", "pattern", ")", "{", "const", "mapBounds", "=", "this", ".", "_map", ".", "getBounds", "(", ")", ".", "pad", "(", "0.1", ")", ";", "return", "this", ".", "_paths", ".", "map", "(", "path", "=>", "{", "const", "directionPoints", "=", "this", ".", "_getDirectionPoints", "(", "path", ",", "pattern", ")", "// filter out invisible points", ".", "filter", "(", "point", "=>", "mapBounds", ".", "contains", "(", "point", ".", "latLng", ")", ")", ";", "return", "L", ".", "featureGroup", "(", "this", ".", "_buildSymbols", "(", "path", ",", "pattern", ".", "symbolFactory", ",", "directionPoints", ")", ")", ";", "}", ")", ";", "}" ]
Returns all symbols for a given pattern as an array of FeatureGroup
[ "Returns", "all", "symbols", "for", "a", "given", "pattern", "as", "an", "array", "of", "FeatureGroup" ]
96858e837a07c08e08dbba1c6751abdec9a85433
https://github.com/bbecquet/Leaflet.PolylineDecorator/blob/96858e837a07c08e08dbba1c6751abdec9a85433/src/L.PolylineDecorator.js#L152-L160
17,518
bbecquet/Leaflet.PolylineDecorator
src/L.PolylineDecorator.js
function () { this._patterns .map(pattern => this._getPatternLayers(pattern)) .forEach(layers => { this.addLayer(L.featureGroup(layers)); }); }
javascript
function () { this._patterns .map(pattern => this._getPatternLayers(pattern)) .forEach(layers => { this.addLayer(L.featureGroup(layers)); }); }
[ "function", "(", ")", "{", "this", ".", "_patterns", ".", "map", "(", "pattern", "=>", "this", ".", "_getPatternLayers", "(", "pattern", ")", ")", ".", "forEach", "(", "layers", "=>", "{", "this", ".", "addLayer", "(", "L", ".", "featureGroup", "(", "layers", ")", ")", ";", "}", ")", ";", "}" ]
Draw all patterns
[ "Draw", "all", "patterns" ]
96858e837a07c08e08dbba1c6751abdec9a85433
https://github.com/bbecquet/Leaflet.PolylineDecorator/blob/96858e837a07c08e08dbba1c6751abdec9a85433/src/L.PolylineDecorator.js#L165-L169
17,519
AndiDittrich/NodeMCU-Tool
lib/cli/nodemcu-tool.js
getConnection
async function getConnection(){ // already connected ? if (_nodeMcuConnector.isConnected()){ return; } // create new connector try{ const msg = await _nodeMcuConnector.connect(_options.device, _options.baudrate, true, _options.connectionDelay); // status message _logger.log('Connected'); _mculogger.log(msg); }catch(e){ _logger.error('Unable to establish connection'); throw e; } }
javascript
async function getConnection(){ // already connected ? if (_nodeMcuConnector.isConnected()){ return; } // create new connector try{ const msg = await _nodeMcuConnector.connect(_options.device, _options.baudrate, true, _options.connectionDelay); // status message _logger.log('Connected'); _mculogger.log(msg); }catch(e){ _logger.error('Unable to establish connection'); throw e; } }
[ "async", "function", "getConnection", "(", ")", "{", "// already connected ?", "if", "(", "_nodeMcuConnector", ".", "isConnected", "(", ")", ")", "{", "return", ";", "}", "// create new connector", "try", "{", "const", "msg", "=", "await", "_nodeMcuConnector", ".", "connect", "(", "_options", ".", "device", ",", "_options", ".", "baudrate", ",", "true", ",", "_options", ".", "connectionDelay", ")", ";", "// status message", "_logger", ".", "log", "(", "'Connected'", ")", ";", "_mculogger", ".", "log", "(", "msg", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "error", "(", "'Unable to establish connection'", ")", ";", "throw", "e", ";", "}", "}" ]
helper function to create a NodeMCU Tool Connection
[ "helper", "function", "to", "create", "a", "NodeMCU", "Tool", "Connection" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/cli/nodemcu-tool.js#L38-L56
17,520
AndiDittrich/NodeMCU-Tool
lib/cli/nodemcu-tool.js
fsinfo
async function fsinfo(format){ // try to establish a connection to the module await getConnection(); const {metadata, files} = await _nodeMcuConnector.fsinfo(); // json output - third party applications if (format == 'json') { writeOutput(JSON.stringify({ files: files, meta: metadata })); // raw format - suitable for use in bash scripts }else if (format == 'raw'){ // print fileinfo files.forEach(function(file){ writeOutput(file.name); }); }else{ _mculogger.log('Free Disk Space: ' + metadata.remaining + ' KB | Total: ' + metadata.total + ' KB | ' + files.length + ' Files'); // files found ? if (files.length==0){ _mculogger.log('No Files found - have you created the file-system?'); }else{ _mculogger.log('Files stored into Flash (SPIFFS)'); // print fileinfo files.forEach(function(file){ _mculogger.log(' - ' + file.name + ' (' + file.size + ' Bytes)'); }); } } }
javascript
async function fsinfo(format){ // try to establish a connection to the module await getConnection(); const {metadata, files} = await _nodeMcuConnector.fsinfo(); // json output - third party applications if (format == 'json') { writeOutput(JSON.stringify({ files: files, meta: metadata })); // raw format - suitable for use in bash scripts }else if (format == 'raw'){ // print fileinfo files.forEach(function(file){ writeOutput(file.name); }); }else{ _mculogger.log('Free Disk Space: ' + metadata.remaining + ' KB | Total: ' + metadata.total + ' KB | ' + files.length + ' Files'); // files found ? if (files.length==0){ _mculogger.log('No Files found - have you created the file-system?'); }else{ _mculogger.log('Files stored into Flash (SPIFFS)'); // print fileinfo files.forEach(function(file){ _mculogger.log(' - ' + file.name + ' (' + file.size + ' Bytes)'); }); } } }
[ "async", "function", "fsinfo", "(", "format", ")", "{", "// try to establish a connection to the module", "await", "getConnection", "(", ")", ";", "const", "{", "metadata", ",", "files", "}", "=", "await", "_nodeMcuConnector", ".", "fsinfo", "(", ")", ";", "// json output - third party applications", "if", "(", "format", "==", "'json'", ")", "{", "writeOutput", "(", "JSON", ".", "stringify", "(", "{", "files", ":", "files", ",", "meta", ":", "metadata", "}", ")", ")", ";", "// raw format - suitable for use in bash scripts", "}", "else", "if", "(", "format", "==", "'raw'", ")", "{", "// print fileinfo", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "writeOutput", "(", "file", ".", "name", ")", ";", "}", ")", ";", "}", "else", "{", "_mculogger", ".", "log", "(", "'Free Disk Space: '", "+", "metadata", ".", "remaining", "+", "' KB | Total: '", "+", "metadata", ".", "total", "+", "' KB | '", "+", "files", ".", "length", "+", "' Files'", ")", ";", "// files found ?", "if", "(", "files", ".", "length", "==", "0", ")", "{", "_mculogger", ".", "log", "(", "'No Files found - have you created the file-system?'", ")", ";", "}", "else", "{", "_mculogger", ".", "log", "(", "'Files stored into Flash (SPIFFS)'", ")", ";", "// print fileinfo", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "_mculogger", ".", "log", "(", "' - '", "+", "file", ".", "name", "+", "' ('", "+", "file", ".", "size", "+", "' Bytes)'", ")", ";", "}", ")", ";", "}", "}", "}" ]
show file-system info
[ "show", "file", "-", "system", "info" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/cli/nodemcu-tool.js#L63-L99
17,521
AndiDittrich/NodeMCU-Tool
lib/cli/nodemcu-tool.js
upload
async function upload(localFiles, options, onProgess){ // the index of the current uploaded file let fileUploadIndex = 0; async function uploadFile(localFile, remoteFilename){ // increment upload index fileUploadIndex++; // get file stats try{ const stats = await _fs.statx(localFile); // check if file is directory if (stats.isDirectory()) { _mculogger.error('Path "' + localFile + '" is a directory.'); return; } // local file available }catch (err){ _logger.error('Local file not found "' + localFile + '" skipping...'); _logger.debug(err); return; } // display filename _logger.log('Uploading "' + localFile + '" >> "' + remoteFilename + '"...'); // normalize the remote filename (strip relative parts) remoteFilename = remoteFilename.replace(/\.\.\//g, '').replace(/\.\./g, '').replace(/^\.\//, ''); // delete old file (may existent) await _nodeMcuConnector.remove(remoteFilename); // start file transfer await _nodeMcuConnector.upload(localFile, remoteFilename, options, function(current, total){ // proxy and append file-number onProgess(current, total, fileUploadIndex); }); // compile flag set ? and is a lua file ? if (options.compile && _path.extname(localFile).toLowerCase() == '.lua'){ _mculogger.log(' |- compiling lua file..'); await _nodeMcuConnector.compile(remoteFilename); _mculogger.log(' |- success'); // drop original lua file await _nodeMcuConnector.remove(remoteFilename); _mculogger.log(' |- original Lua file removed'); } } // try to establish a connection to the module await getConnection(); // single file upload ? if (localFiles.length == 1){ // extract first element const localFile = localFiles[0]; // filename defaults to original filename minus path. // this behaviour can be overridden by --keeppath and --remotename options const remoteFile = options.remotename ? options.remotename : (options.keeppath ? localFile : _path.basename(localFile)); // start single file upload await uploadFile(localFile, remoteFile); // log message _logger.log('File Transfer complete!'); // run file ? if (options.run === true){ await run(remoteFile); } // bulk upload ? }else{ // file available ? while (localFiles.length > 0){ // extract file const localFile = localFiles.shift(); // keep-path option set ? const remoteFile = (options.keeppath ? localFile : _path.basename(localFile)); // trigger upload await uploadFile(localFile, remoteFile); } // log message _logger.log('Bulk File Transfer complete!'); } }
javascript
async function upload(localFiles, options, onProgess){ // the index of the current uploaded file let fileUploadIndex = 0; async function uploadFile(localFile, remoteFilename){ // increment upload index fileUploadIndex++; // get file stats try{ const stats = await _fs.statx(localFile); // check if file is directory if (stats.isDirectory()) { _mculogger.error('Path "' + localFile + '" is a directory.'); return; } // local file available }catch (err){ _logger.error('Local file not found "' + localFile + '" skipping...'); _logger.debug(err); return; } // display filename _logger.log('Uploading "' + localFile + '" >> "' + remoteFilename + '"...'); // normalize the remote filename (strip relative parts) remoteFilename = remoteFilename.replace(/\.\.\//g, '').replace(/\.\./g, '').replace(/^\.\//, ''); // delete old file (may existent) await _nodeMcuConnector.remove(remoteFilename); // start file transfer await _nodeMcuConnector.upload(localFile, remoteFilename, options, function(current, total){ // proxy and append file-number onProgess(current, total, fileUploadIndex); }); // compile flag set ? and is a lua file ? if (options.compile && _path.extname(localFile).toLowerCase() == '.lua'){ _mculogger.log(' |- compiling lua file..'); await _nodeMcuConnector.compile(remoteFilename); _mculogger.log(' |- success'); // drop original lua file await _nodeMcuConnector.remove(remoteFilename); _mculogger.log(' |- original Lua file removed'); } } // try to establish a connection to the module await getConnection(); // single file upload ? if (localFiles.length == 1){ // extract first element const localFile = localFiles[0]; // filename defaults to original filename minus path. // this behaviour can be overridden by --keeppath and --remotename options const remoteFile = options.remotename ? options.remotename : (options.keeppath ? localFile : _path.basename(localFile)); // start single file upload await uploadFile(localFile, remoteFile); // log message _logger.log('File Transfer complete!'); // run file ? if (options.run === true){ await run(remoteFile); } // bulk upload ? }else{ // file available ? while (localFiles.length > 0){ // extract file const localFile = localFiles.shift(); // keep-path option set ? const remoteFile = (options.keeppath ? localFile : _path.basename(localFile)); // trigger upload await uploadFile(localFile, remoteFile); } // log message _logger.log('Bulk File Transfer complete!'); } }
[ "async", "function", "upload", "(", "localFiles", ",", "options", ",", "onProgess", ")", "{", "// the index of the current uploaded file", "let", "fileUploadIndex", "=", "0", ";", "async", "function", "uploadFile", "(", "localFile", ",", "remoteFilename", ")", "{", "// increment upload index", "fileUploadIndex", "++", ";", "// get file stats", "try", "{", "const", "stats", "=", "await", "_fs", ".", "statx", "(", "localFile", ")", ";", "// check if file is directory", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "_mculogger", ".", "error", "(", "'Path \"'", "+", "localFile", "+", "'\" is a directory.'", ")", ";", "return", ";", "}", "// local file available", "}", "catch", "(", "err", ")", "{", "_logger", ".", "error", "(", "'Local file not found \"'", "+", "localFile", "+", "'\" skipping...'", ")", ";", "_logger", ".", "debug", "(", "err", ")", ";", "return", ";", "}", "// display filename", "_logger", ".", "log", "(", "'Uploading \"'", "+", "localFile", "+", "'\" >> \"'", "+", "remoteFilename", "+", "'\"...'", ")", ";", "// normalize the remote filename (strip relative parts)", "remoteFilename", "=", "remoteFilename", ".", "replace", "(", "/", "\\.\\.\\/", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "\\.\\.", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "^\\.\\/", "/", ",", "''", ")", ";", "// delete old file (may existent)", "await", "_nodeMcuConnector", ".", "remove", "(", "remoteFilename", ")", ";", "// start file transfer", "await", "_nodeMcuConnector", ".", "upload", "(", "localFile", ",", "remoteFilename", ",", "options", ",", "function", "(", "current", ",", "total", ")", "{", "// proxy and append file-number", "onProgess", "(", "current", ",", "total", ",", "fileUploadIndex", ")", ";", "}", ")", ";", "// compile flag set ? and is a lua file ?", "if", "(", "options", ".", "compile", "&&", "_path", ".", "extname", "(", "localFile", ")", ".", "toLowerCase", "(", ")", "==", "'.lua'", ")", "{", "_mculogger", ".", "log", "(", "' |- compiling lua file..'", ")", ";", "await", "_nodeMcuConnector", ".", "compile", "(", "remoteFilename", ")", ";", "_mculogger", ".", "log", "(", "' |- success'", ")", ";", "// drop original lua file", "await", "_nodeMcuConnector", ".", "remove", "(", "remoteFilename", ")", ";", "_mculogger", ".", "log", "(", "' |- original Lua file removed'", ")", ";", "}", "}", "// try to establish a connection to the module", "await", "getConnection", "(", ")", ";", "// single file upload ?", "if", "(", "localFiles", ".", "length", "==", "1", ")", "{", "// extract first element", "const", "localFile", "=", "localFiles", "[", "0", "]", ";", "// filename defaults to original filename minus path.", "// this behaviour can be overridden by --keeppath and --remotename options", "const", "remoteFile", "=", "options", ".", "remotename", "?", "options", ".", "remotename", ":", "(", "options", ".", "keeppath", "?", "localFile", ":", "_path", ".", "basename", "(", "localFile", ")", ")", ";", "// start single file upload", "await", "uploadFile", "(", "localFile", ",", "remoteFile", ")", ";", "// log message", "_logger", ".", "log", "(", "'File Transfer complete!'", ")", ";", "// run file ?", "if", "(", "options", ".", "run", "===", "true", ")", "{", "await", "run", "(", "remoteFile", ")", ";", "}", "// bulk upload ?", "}", "else", "{", "// file available ?", "while", "(", "localFiles", ".", "length", ">", "0", ")", "{", "// extract file", "const", "localFile", "=", "localFiles", ".", "shift", "(", ")", ";", "// keep-path option set ?", "const", "remoteFile", "=", "(", "options", ".", "keeppath", "?", "localFile", ":", "_path", ".", "basename", "(", "localFile", ")", ")", ";", "// trigger upload", "await", "uploadFile", "(", "localFile", ",", "remoteFile", ")", ";", "}", "// log message", "_logger", ".", "log", "(", "'Bulk File Transfer complete!'", ")", ";", "}", "}" ]
upload a local file to nodemcu
[ "upload", "a", "local", "file", "to", "nodemcu" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/cli/nodemcu-tool.js#L117-L213
17,522
AndiDittrich/NodeMCU-Tool
lib/cli/nodemcu-tool.js
download
async function download(remoteFile){ // strip path let localFilename = _path.basename(remoteFile); // local file with same name already available ? if (await _fs.exists(remoteFile)){ // change filename localFilename += '.' + (new Date().getTime()); _logger.log('Local file "' + remoteFile + '" already exist - new file renamed to "' + localFilename + '"'); } // try to establish a connection to the module await getConnection(); _logger.log('Downloading "' + remoteFile + '" ...'); let data = null; // download the file try{ data = await _nodeMcuConnector.download(remoteFile); _logger.log('Data Transfer complete!'); }catch(e){ _logger.debug(e); throw new Error('Data Transfer FAILED!'); } // store the file try{ await _fs.writeFile(localFilename, data); _logger.log('File "' + localFilename + '" created'); }catch(e){ _logger.debug(e); throw new Error('i/o error - cannot save file'); } }
javascript
async function download(remoteFile){ // strip path let localFilename = _path.basename(remoteFile); // local file with same name already available ? if (await _fs.exists(remoteFile)){ // change filename localFilename += '.' + (new Date().getTime()); _logger.log('Local file "' + remoteFile + '" already exist - new file renamed to "' + localFilename + '"'); } // try to establish a connection to the module await getConnection(); _logger.log('Downloading "' + remoteFile + '" ...'); let data = null; // download the file try{ data = await _nodeMcuConnector.download(remoteFile); _logger.log('Data Transfer complete!'); }catch(e){ _logger.debug(e); throw new Error('Data Transfer FAILED!'); } // store the file try{ await _fs.writeFile(localFilename, data); _logger.log('File "' + localFilename + '" created'); }catch(e){ _logger.debug(e); throw new Error('i/o error - cannot save file'); } }
[ "async", "function", "download", "(", "remoteFile", ")", "{", "// strip path", "let", "localFilename", "=", "_path", ".", "basename", "(", "remoteFile", ")", ";", "// local file with same name already available ?", "if", "(", "await", "_fs", ".", "exists", "(", "remoteFile", ")", ")", "{", "// change filename", "localFilename", "+=", "'.'", "+", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", ")", ";", "_logger", ".", "log", "(", "'Local file \"'", "+", "remoteFile", "+", "'\" already exist - new file renamed to \"'", "+", "localFilename", "+", "'\"'", ")", ";", "}", "// try to establish a connection to the module", "await", "getConnection", "(", ")", ";", "_logger", ".", "log", "(", "'Downloading \"'", "+", "remoteFile", "+", "'\" ...'", ")", ";", "let", "data", "=", "null", ";", "// download the file", "try", "{", "data", "=", "await", "_nodeMcuConnector", ".", "download", "(", "remoteFile", ")", ";", "_logger", ".", "log", "(", "'Data Transfer complete!'", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'Data Transfer FAILED!'", ")", ";", "}", "// store the file", "try", "{", "await", "_fs", ".", "writeFile", "(", "localFilename", ",", "data", ")", ";", "_logger", ".", "log", "(", "'File \"'", "+", "localFilename", "+", "'\" created'", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'i/o error - cannot save file'", ")", ";", "}", "}" ]
download a remote file from nodemcu
[ "download", "a", "remote", "file", "from", "nodemcu" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/cli/nodemcu-tool.js#L216-L253
17,523
AndiDittrich/NodeMCU-Tool
lib/cli/nodemcu-tool.js
remove
async function remove(filename){ // try to establish a connection to the module await getConnection(); // remove the file await _nodeMcuConnector.remove(filename); // just show complete message (no feedback from nodemcu) _mculogger.log('File "' + filename + '" removed!'); }
javascript
async function remove(filename){ // try to establish a connection to the module await getConnection(); // remove the file await _nodeMcuConnector.remove(filename); // just show complete message (no feedback from nodemcu) _mculogger.log('File "' + filename + '" removed!'); }
[ "async", "function", "remove", "(", "filename", ")", "{", "// try to establish a connection to the module", "await", "getConnection", "(", ")", ";", "// remove the file", "await", "_nodeMcuConnector", ".", "remove", "(", "filename", ")", ";", "// just show complete message (no feedback from nodemcu)", "_mculogger", ".", "log", "(", "'File \"'", "+", "filename", "+", "'\" removed!'", ")", ";", "}" ]
removes a file from NodeMCU
[ "removes", "a", "file", "from", "NodeMCU" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/cli/nodemcu-tool.js#L256-L266
17,524
AndiDittrich/NodeMCU-Tool
lib/cli/nodemcu-tool.js
mkfs
async function mkfs(){ // try to establish a connection to the module await getConnection(); _mculogger.log('Formatting the file system...this will take around ~30s'); try{ const response = await _nodeMcuConnector.format(); // just show complete message _mculogger.log('File System created | ' + response); }catch(e){ _mculogger.error('Formatting failed'); _logger.debug(e); } }
javascript
async function mkfs(){ // try to establish a connection to the module await getConnection(); _mculogger.log('Formatting the file system...this will take around ~30s'); try{ const response = await _nodeMcuConnector.format(); // just show complete message _mculogger.log('File System created | ' + response); }catch(e){ _mculogger.error('Formatting failed'); _logger.debug(e); } }
[ "async", "function", "mkfs", "(", ")", "{", "// try to establish a connection to the module", "await", "getConnection", "(", ")", ";", "_mculogger", ".", "log", "(", "'Formatting the file system...this will take around ~30s'", ")", ";", "try", "{", "const", "response", "=", "await", "_nodeMcuConnector", ".", "format", "(", ")", ";", "// just show complete message", "_mculogger", ".", "log", "(", "'File System created | '", "+", "response", ")", ";", "}", "catch", "(", "e", ")", "{", "_mculogger", ".", "error", "(", "'Formatting failed'", ")", ";", "_logger", ".", "debug", "(", "e", ")", ";", "}", "}" ]
format the file system
[ "format", "the", "file", "system" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/cli/nodemcu-tool.js#L269-L285
17,525
AndiDittrich/NodeMCU-Tool
lib/cli/nodemcu-tool.js
devices
async function devices(showAll, jsonOutput){ try{ const serialDevices = await _nodeMcuConnector.listDevices(showAll); if (jsonOutput){ writeOutput(JSON.stringify(serialDevices)); }else{ // just show complete message if (serialDevices.length == 0){ _mculogger.error('No Connected Devices found | Total: ' + serialDevices.length); }else{ _mculogger.log('Connected Devices | Total: ' + serialDevices.length); // print fileinfo serialDevices.forEach(function(device){ _mculogger.log('- ' + device.comName + ' (' + device.manufacturer + ', ' + device.pnpId + ')'); }); } } }catch(e){ _mculogger.alert('Cannot retrieve serial device list - '); _logger.debug(e); } }
javascript
async function devices(showAll, jsonOutput){ try{ const serialDevices = await _nodeMcuConnector.listDevices(showAll); if (jsonOutput){ writeOutput(JSON.stringify(serialDevices)); }else{ // just show complete message if (serialDevices.length == 0){ _mculogger.error('No Connected Devices found | Total: ' + serialDevices.length); }else{ _mculogger.log('Connected Devices | Total: ' + serialDevices.length); // print fileinfo serialDevices.forEach(function(device){ _mculogger.log('- ' + device.comName + ' (' + device.manufacturer + ', ' + device.pnpId + ')'); }); } } }catch(e){ _mculogger.alert('Cannot retrieve serial device list - '); _logger.debug(e); } }
[ "async", "function", "devices", "(", "showAll", ",", "jsonOutput", ")", "{", "try", "{", "const", "serialDevices", "=", "await", "_nodeMcuConnector", ".", "listDevices", "(", "showAll", ")", ";", "if", "(", "jsonOutput", ")", "{", "writeOutput", "(", "JSON", ".", "stringify", "(", "serialDevices", ")", ")", ";", "}", "else", "{", "// just show complete message", "if", "(", "serialDevices", ".", "length", "==", "0", ")", "{", "_mculogger", ".", "error", "(", "'No Connected Devices found | Total: '", "+", "serialDevices", ".", "length", ")", ";", "}", "else", "{", "_mculogger", ".", "log", "(", "'Connected Devices | Total: '", "+", "serialDevices", ".", "length", ")", ";", "// print fileinfo", "serialDevices", ".", "forEach", "(", "function", "(", "device", ")", "{", "_mculogger", ".", "log", "(", "'- '", "+", "device", ".", "comName", "+", "' ('", "+", "device", ".", "manufacturer", "+", "', '", "+", "device", ".", "pnpId", "+", "')'", ")", ";", "}", ")", ";", "}", "}", "}", "catch", "(", "e", ")", "{", "_mculogger", ".", "alert", "(", "'Cannot retrieve serial device list - '", ")", ";", "_logger", ".", "debug", "(", "e", ")", ";", "}", "}" ]
show serial devices connected to the system
[ "show", "serial", "devices", "connected", "to", "the", "system" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/cli/nodemcu-tool.js#L321-L346
17,526
AndiDittrich/NodeMCU-Tool
lib/cli/nodemcu-tool.js
function(opt){ // merge with default options Object.keys(_options).forEach(function(key){ _options[key] = opt[key] || _options[key]; }); }
javascript
function(opt){ // merge with default options Object.keys(_options).forEach(function(key){ _options[key] = opt[key] || _options[key]; }); }
[ "function", "(", "opt", ")", "{", "// merge with default options", "Object", ".", "keys", "(", "_options", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "_options", "[", "key", "]", "=", "opt", "[", "key", "]", "||", "_options", "[", "key", "]", ";", "}", ")", ";", "}" ]
set connector options
[ "set", "connector", "options" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/cli/nodemcu-tool.js#L359-L364
17,527
AndiDittrich/NodeMCU-Tool
lib/lua/command-builder.js
luaPrepare
function luaPrepare(commandName, args){ // get command by name let command = _esp8266_commands[commandName] || null; // valid command name provided ? if (command == null){ return null; } // replace all placeholders with given args args.forEach(function(arg){ // simple escaping quotes arg = arg.replace(/[^\\]"/g, '"'); // apply arg command = command.replace(/\?/, arg); }); return command; }
javascript
function luaPrepare(commandName, args){ // get command by name let command = _esp8266_commands[commandName] || null; // valid command name provided ? if (command == null){ return null; } // replace all placeholders with given args args.forEach(function(arg){ // simple escaping quotes arg = arg.replace(/[^\\]"/g, '"'); // apply arg command = command.replace(/\?/, arg); }); return command; }
[ "function", "luaPrepare", "(", "commandName", ",", "args", ")", "{", "// get command by name", "let", "command", "=", "_esp8266_commands", "[", "commandName", "]", "||", "null", ";", "// valid command name provided ?", "if", "(", "command", "==", "null", ")", "{", "return", "null", ";", "}", "// replace all placeholders with given args", "args", ".", "forEach", "(", "function", "(", "arg", ")", "{", "// simple escaping quotes", "arg", "=", "arg", ".", "replace", "(", "/", "[^\\\\]\"", "/", "g", ",", "'\"'", ")", ";", "// apply arg", "command", "=", "command", ".", "replace", "(", "/", "\\?", "/", ",", "arg", ")", ";", "}", ")", ";", "return", "command", ";", "}" ]
prepare command be escaping args
[ "prepare", "command", "be", "escaping", "args" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/lua/command-builder.js#L4-L23
17,528
AndiDittrich/NodeMCU-Tool
lib/cli/prompt.js
prompt
function prompt(menu){ return new Promise(function(resolve, reject){ // user confirmation required! _prompt.start(); _prompt.message = ''; _prompt.delimiter = ''; _prompt.colors = false; _prompt.get(menu, function (err, result){ if (err){ reject(err); }else{ resolve(result); } }); }); }
javascript
function prompt(menu){ return new Promise(function(resolve, reject){ // user confirmation required! _prompt.start(); _prompt.message = ''; _prompt.delimiter = ''; _prompt.colors = false; _prompt.get(menu, function (err, result){ if (err){ reject(err); }else{ resolve(result); } }); }); }
[ "function", "prompt", "(", "menu", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "// user confirmation required!", "_prompt", ".", "start", "(", ")", ";", "_prompt", ".", "message", "=", "''", ";", "_prompt", ".", "delimiter", "=", "''", ";", "_prompt", ".", "colors", "=", "false", ";", "_prompt", ".", "get", "(", "menu", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "result", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
async prompt wrapper
[ "async", "prompt", "wrapper" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/cli/prompt.js#L4-L22
17,529
AndiDittrich/NodeMCU-Tool
lib/connector/device-info.js
fetchDeviceInfo
async function fetchDeviceInfo(){ // run the node.info() command let {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.nodeInfo); // replace whitespaces with single delimiter const p = response.replace(/\s+/gi, '-').split('-'); // 8 elements found ? nodemcu on esp8266 if (p.length === 8){ return { version: p[0] + '.' + p[1] + '.' + p[2], arch: 'esp8266', chipID: parseInt(p[3]).toString(16), flashID: parseInt(p[4]).toString(16), flashsize: p[5] + 'kB', flashmode: p[6], flashspeed: parseInt(p[7]) / 1000000 + 'MHz' }; // maybe an esp32 module with missing node.info() }else{ try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.chipid)); // esp32 chipid (hex with '0x' prefix)? const chipid = response.match(/^0x(\w+)/); if (chipid){ return { version: 'unknown', arch: 'esp32', chipID: chipid[1], flashID: 'unknown', flashsize: 'unknown', flashmode:'unknown', flashspeed: 'unknown' }; }else{ throw new Error('Invalid node.chipid() Response: ' + response); } }catch(e){ _logger.debug(e); throw new Error('Invalid node.chipid() Response: ' + response); } } }
javascript
async function fetchDeviceInfo(){ // run the node.info() command let {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.nodeInfo); // replace whitespaces with single delimiter const p = response.replace(/\s+/gi, '-').split('-'); // 8 elements found ? nodemcu on esp8266 if (p.length === 8){ return { version: p[0] + '.' + p[1] + '.' + p[2], arch: 'esp8266', chipID: parseInt(p[3]).toString(16), flashID: parseInt(p[4]).toString(16), flashsize: p[5] + 'kB', flashmode: p[6], flashspeed: parseInt(p[7]) / 1000000 + 'MHz' }; // maybe an esp32 module with missing node.info() }else{ try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.chipid)); // esp32 chipid (hex with '0x' prefix)? const chipid = response.match(/^0x(\w+)/); if (chipid){ return { version: 'unknown', arch: 'esp32', chipID: chipid[1], flashID: 'unknown', flashsize: 'unknown', flashmode:'unknown', flashspeed: 'unknown' }; }else{ throw new Error('Invalid node.chipid() Response: ' + response); } }catch(e){ _logger.debug(e); throw new Error('Invalid node.chipid() Response: ' + response); } } }
[ "async", "function", "fetchDeviceInfo", "(", ")", "{", "// run the node.info() command", "let", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "command", ".", "nodeInfo", ")", ";", "// replace whitespaces with single delimiter", "const", "p", "=", "response", ".", "replace", "(", "/", "\\s+", "/", "gi", ",", "'-'", ")", ".", "split", "(", "'-'", ")", ";", "// 8 elements found ? nodemcu on esp8266", "if", "(", "p", ".", "length", "===", "8", ")", "{", "return", "{", "version", ":", "p", "[", "0", "]", "+", "'.'", "+", "p", "[", "1", "]", "+", "'.'", "+", "p", "[", "2", "]", ",", "arch", ":", "'esp8266'", ",", "chipID", ":", "parseInt", "(", "p", "[", "3", "]", ")", ".", "toString", "(", "16", ")", ",", "flashID", ":", "parseInt", "(", "p", "[", "4", "]", ")", ".", "toString", "(", "16", ")", ",", "flashsize", ":", "p", "[", "5", "]", "+", "'kB'", ",", "flashmode", ":", "p", "[", "6", "]", ",", "flashspeed", ":", "parseInt", "(", "p", "[", "7", "]", ")", "/", "1000000", "+", "'MHz'", "}", ";", "// maybe an esp32 module with missing node.info()", "}", "else", "{", "try", "{", "(", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "command", ".", "chipid", ")", ")", ";", "// esp32 chipid (hex with '0x' prefix)?", "const", "chipid", "=", "response", ".", "match", "(", "/", "^0x(\\w+)", "/", ")", ";", "if", "(", "chipid", ")", "{", "return", "{", "version", ":", "'unknown'", ",", "arch", ":", "'esp32'", ",", "chipID", ":", "chipid", "[", "1", "]", ",", "flashID", ":", "'unknown'", ",", "flashsize", ":", "'unknown'", ",", "flashmode", ":", "'unknown'", ",", "flashspeed", ":", "'unknown'", "}", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid node.chipid() Response: '", "+", "response", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'Invalid node.chipid() Response: '", "+", "response", ")", ";", "}", "}", "}" ]
fetch nodemcu device info
[ "fetch", "nodemcu", "device", "info" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/connector/device-info.js#L6-L52
17,530
AndiDittrich/NodeMCU-Tool
lib/connector/fsinfo.js
fsinfo
async function fsinfo(){ // get file system info (size) let {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fsInfo); // extract size (remaining, used, total) response = response.replace(/\s+/gi, '-').split('-'); const meta = { remaining: toKB(response[0]), used: toKB(response[1]), total: toKB(response[2]) }; // print a full file-list including size ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.listFiles)); // file-list to return const files = []; // files available (list not empty) ? if (response.length > 0){ // split the file-list by ";" const entries = response.trim().split(';'); // process each entry entries.forEach(function(entry){ // entry format: <name>:<size> const matches = /^(.*):(\d+)$/gi.exec(entry); // valid format ? if (matches){ // append file entry to list files.push({ name: matches[1], size: parseInt(matches[2]) }); } }); } return {metadata: meta, files: files} }
javascript
async function fsinfo(){ // get file system info (size) let {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fsInfo); // extract size (remaining, used, total) response = response.replace(/\s+/gi, '-').split('-'); const meta = { remaining: toKB(response[0]), used: toKB(response[1]), total: toKB(response[2]) }; // print a full file-list including size ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.listFiles)); // file-list to return const files = []; // files available (list not empty) ? if (response.length > 0){ // split the file-list by ";" const entries = response.trim().split(';'); // process each entry entries.forEach(function(entry){ // entry format: <name>:<size> const matches = /^(.*):(\d+)$/gi.exec(entry); // valid format ? if (matches){ // append file entry to list files.push({ name: matches[1], size: parseInt(matches[2]) }); } }); } return {metadata: meta, files: files} }
[ "async", "function", "fsinfo", "(", ")", "{", "// get file system info (size)", "let", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "command", ".", "fsInfo", ")", ";", "// extract size (remaining, used, total)", "response", "=", "response", ".", "replace", "(", "/", "\\s+", "/", "gi", ",", "'-'", ")", ".", "split", "(", "'-'", ")", ";", "const", "meta", "=", "{", "remaining", ":", "toKB", "(", "response", "[", "0", "]", ")", ",", "used", ":", "toKB", "(", "response", "[", "1", "]", ")", ",", "total", ":", "toKB", "(", "response", "[", "2", "]", ")", "}", ";", "// print a full file-list including size", "(", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "command", ".", "listFiles", ")", ")", ";", "// file-list to return", "const", "files", "=", "[", "]", ";", "// files available (list not empty) ?", "if", "(", "response", ".", "length", ">", "0", ")", "{", "// split the file-list by \";\"", "const", "entries", "=", "response", ".", "trim", "(", ")", ".", "split", "(", "';'", ")", ";", "// process each entry", "entries", ".", "forEach", "(", "function", "(", "entry", ")", "{", "// entry format: <name>:<size>", "const", "matches", "=", "/", "^(.*):(\\d+)$", "/", "gi", ".", "exec", "(", "entry", ")", ";", "// valid format ?", "if", "(", "matches", ")", "{", "// append file entry to list", "files", ".", "push", "(", "{", "name", ":", "matches", "[", "1", "]", ",", "size", ":", "parseInt", "(", "matches", "[", "2", "]", ")", "}", ")", ";", "}", "}", ")", ";", "}", "return", "{", "metadata", ":", "meta", ",", "files", ":", "files", "}", "}" ]
show filesystem information
[ "show", "filesystem", "information" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/connector/fsinfo.js#L9-L51
17,531
AndiDittrich/NodeMCU-Tool
lib/connector/format.js
format
async function format(){ // create new filesystem const {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fsFormat); return response; }
javascript
async function format(){ // create new filesystem const {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fsFormat); return response; }
[ "async", "function", "format", "(", ")", "{", "// create new filesystem", "const", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "command", ".", "fsFormat", ")", ";", "return", "response", ";", "}" ]
format the filesystem
[ "format", "the", "filesystem" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/connector/format.js#L5-L10
17,532
AndiDittrich/NodeMCU-Tool
lib/connector/compile.js
compile
async function compile(remoteName){ // run the lua compiler/interpreter to cache the file as bytecode const {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.prepare('compile', [remoteName])); return response; }
javascript
async function compile(remoteName){ // run the lua compiler/interpreter to cache the file as bytecode const {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.prepare('compile', [remoteName])); return response; }
[ "async", "function", "compile", "(", "remoteName", ")", "{", "// run the lua compiler/interpreter to cache the file as bytecode", "const", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "prepare", "(", "'compile'", ",", "[", "remoteName", "]", ")", ")", ";", "return", "response", ";", "}" ]
compile a remote file
[ "compile", "a", "remote", "file" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/connector/compile.js#L5-L10
17,533
AndiDittrich/NodeMCU-Tool
lib/transport/scriptable-serial-terminal.js
onData
function onData(rawData){ // strip delimiter sequence from array const input = rawData.toString(_encoding); // response data object - default no response data const data = { echo: input, response: null }; // response found ? split echo and response const splitIndex = input.indexOf('\n'); if (splitIndex > 0){ data.echo = input.substr(0, splitIndex).trim(); data.response = input.substr(splitIndex + 1).trim(); } // process waiting for input ? if (_waitingForInput !== null){ const resolver = _waitingForInput; _waitingForInput = null; resolver(data); }else{ _inputbuffer.push(data); } }
javascript
function onData(rawData){ // strip delimiter sequence from array const input = rawData.toString(_encoding); // response data object - default no response data const data = { echo: input, response: null }; // response found ? split echo and response const splitIndex = input.indexOf('\n'); if (splitIndex > 0){ data.echo = input.substr(0, splitIndex).trim(); data.response = input.substr(splitIndex + 1).trim(); } // process waiting for input ? if (_waitingForInput !== null){ const resolver = _waitingForInput; _waitingForInput = null; resolver(data); }else{ _inputbuffer.push(data); } }
[ "function", "onData", "(", "rawData", ")", "{", "// strip delimiter sequence from array", "const", "input", "=", "rawData", ".", "toString", "(", "_encoding", ")", ";", "// response data object - default no response data", "const", "data", "=", "{", "echo", ":", "input", ",", "response", ":", "null", "}", ";", "// response found ? split echo and response", "const", "splitIndex", "=", "input", ".", "indexOf", "(", "'\\n'", ")", ";", "if", "(", "splitIndex", ">", "0", ")", "{", "data", ".", "echo", "=", "input", ".", "substr", "(", "0", ",", "splitIndex", ")", ".", "trim", "(", ")", ";", "data", ".", "response", "=", "input", ".", "substr", "(", "splitIndex", "+", "1", ")", ".", "trim", "(", ")", ";", "}", "// process waiting for input ?", "if", "(", "_waitingForInput", "!==", "null", ")", "{", "const", "resolver", "=", "_waitingForInput", ";", "_waitingForInput", "=", "null", ";", "resolver", "(", "data", ")", ";", "}", "else", "{", "_inputbuffer", ".", "push", "(", "data", ")", ";", "}", "}" ]
listen on incoming data
[ "listen", "on", "incoming", "data" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/transport/scriptable-serial-terminal.js#L33-L59
17,534
AndiDittrich/NodeMCU-Tool
lib/transport/scriptable-serial-terminal.js
getNextResponse
function getNextResponse(){ if (_waitingForInput !== null){ throw new Error('concurreny error - receive listener already in-queue'); } return new Promise(function(resolve){ // data received ? if (_inputbuffer.length > 0){ resolve(_inputbuffer.shift()); }else{ // add as waiting instance (no concurrent!) _waitingForInput = resolve; } }); }
javascript
function getNextResponse(){ if (_waitingForInput !== null){ throw new Error('concurreny error - receive listener already in-queue'); } return new Promise(function(resolve){ // data received ? if (_inputbuffer.length > 0){ resolve(_inputbuffer.shift()); }else{ // add as waiting instance (no concurrent!) _waitingForInput = resolve; } }); }
[ "function", "getNextResponse", "(", ")", "{", "if", "(", "_waitingForInput", "!==", "null", ")", "{", "throw", "new", "Error", "(", "'concurreny error - receive listener already in-queue'", ")", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "// data received ?", "if", "(", "_inputbuffer", ".", "length", ">", "0", ")", "{", "resolve", "(", "_inputbuffer", ".", "shift", "(", ")", ")", ";", "}", "else", "{", "// add as waiting instance (no concurrent!)", "_waitingForInput", "=", "resolve", ";", "}", "}", ")", ";", "}" ]
wait for next echo + response line
[ "wait", "for", "next", "echo", "+", "response", "line" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/transport/scriptable-serial-terminal.js#L71-L85
17,535
AndiDittrich/NodeMCU-Tool
lib/transport/scriptable-serial-terminal.js
write
async function write(data){ await _serialport.write(data); await _serialport.drain(); }
javascript
async function write(data){ await _serialport.write(data); await _serialport.drain(); }
[ "async", "function", "write", "(", "data", ")", "{", "await", "_serialport", ".", "write", "(", "data", ")", ";", "await", "_serialport", ".", "drain", "(", ")", ";", "}" ]
write data to serial port and wait for transmission complete
[ "write", "data", "to", "serial", "port", "and", "wait", "for", "transmission", "complete" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/transport/scriptable-serial-terminal.js#L88-L91
17,536
AndiDittrich/NodeMCU-Tool
lib/connector/upload.js
startTransfer
async function startTransfer(rawContent, localName, remoteName, progressCb){ // convert buffer to hex or base64 const content = rawContent.toString(_transferEncoding); // get absolute filesize const absoluteFilesize = content.length; // split file content into chunks const chunks = content.match(/[\s\S]{1,232}/g) || []; // command response buffer let response = null; // current upload size in bytes let currentUploadSize = 0; // open remote file for write try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.prepare('fileOpen', [remoteName, 'w+']))); // valid handle ? if (response == 'nil'){ throw new Error('i/o error - cannot open nodemcu file-handle for write'); } }catch(e){ _logger.debug(e); throw new Error('Cannot open remote file "' + remoteName + '" for write'); } // initial progress update progressCb.apply(progressCb, [0, absoluteFilesize]); // internal helper to write chunks async function writeChunk(){ if (chunks.length > 0){ // get first element const l = chunks.shift(); // increment size counter currentUploadSize += l.length; // write first element to file try{ await _virtualTerminal.executeCommand('__nmtwrite("' + l + '")'); }catch(e){ _logger.debug(e); throw new Error('cannot write chunk to remote file'); } // run progress callback progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]); // write next await writeChunk(); }else{ // ensure that the progress callback is called, even for empty files progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]); // send file close command try{ await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fileCloseFlush); }catch(e){ _logger.debug(e); throw new Error('cannot flush/close remote file'); } } } // start transfer return writeChunk(); }
javascript
async function startTransfer(rawContent, localName, remoteName, progressCb){ // convert buffer to hex or base64 const content = rawContent.toString(_transferEncoding); // get absolute filesize const absoluteFilesize = content.length; // split file content into chunks const chunks = content.match(/[\s\S]{1,232}/g) || []; // command response buffer let response = null; // current upload size in bytes let currentUploadSize = 0; // open remote file for write try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.prepare('fileOpen', [remoteName, 'w+']))); // valid handle ? if (response == 'nil'){ throw new Error('i/o error - cannot open nodemcu file-handle for write'); } }catch(e){ _logger.debug(e); throw new Error('Cannot open remote file "' + remoteName + '" for write'); } // initial progress update progressCb.apply(progressCb, [0, absoluteFilesize]); // internal helper to write chunks async function writeChunk(){ if (chunks.length > 0){ // get first element const l = chunks.shift(); // increment size counter currentUploadSize += l.length; // write first element to file try{ await _virtualTerminal.executeCommand('__nmtwrite("' + l + '")'); }catch(e){ _logger.debug(e); throw new Error('cannot write chunk to remote file'); } // run progress callback progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]); // write next await writeChunk(); }else{ // ensure that the progress callback is called, even for empty files progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]); // send file close command try{ await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fileCloseFlush); }catch(e){ _logger.debug(e); throw new Error('cannot flush/close remote file'); } } } // start transfer return writeChunk(); }
[ "async", "function", "startTransfer", "(", "rawContent", ",", "localName", ",", "remoteName", ",", "progressCb", ")", "{", "// convert buffer to hex or base64", "const", "content", "=", "rawContent", ".", "toString", "(", "_transferEncoding", ")", ";", "// get absolute filesize", "const", "absoluteFilesize", "=", "content", ".", "length", ";", "// split file content into chunks", "const", "chunks", "=", "content", ".", "match", "(", "/", "[\\s\\S]{1,232}", "/", "g", ")", "||", "[", "]", ";", "// command response buffer", "let", "response", "=", "null", ";", "// current upload size in bytes", "let", "currentUploadSize", "=", "0", ";", "// open remote file for write", "try", "{", "(", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "prepare", "(", "'fileOpen'", ",", "[", "remoteName", ",", "'w+'", "]", ")", ")", ")", ";", "// valid handle ?", "if", "(", "response", "==", "'nil'", ")", "{", "throw", "new", "Error", "(", "'i/o error - cannot open nodemcu file-handle for write'", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'Cannot open remote file \"'", "+", "remoteName", "+", "'\" for write'", ")", ";", "}", "// initial progress update", "progressCb", ".", "apply", "(", "progressCb", ",", "[", "0", ",", "absoluteFilesize", "]", ")", ";", "// internal helper to write chunks", "async", "function", "writeChunk", "(", ")", "{", "if", "(", "chunks", ".", "length", ">", "0", ")", "{", "// get first element", "const", "l", "=", "chunks", ".", "shift", "(", ")", ";", "// increment size counter", "currentUploadSize", "+=", "l", ".", "length", ";", "// write first element to file", "try", "{", "await", "_virtualTerminal", ".", "executeCommand", "(", "'__nmtwrite(\"'", "+", "l", "+", "'\")'", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'cannot write chunk to remote file'", ")", ";", "}", "// run progress callback", "progressCb", ".", "apply", "(", "progressCb", ",", "[", "currentUploadSize", ",", "absoluteFilesize", "]", ")", ";", "// write next", "await", "writeChunk", "(", ")", ";", "}", "else", "{", "// ensure that the progress callback is called, even for empty files", "progressCb", ".", "apply", "(", "progressCb", ",", "[", "currentUploadSize", ",", "absoluteFilesize", "]", ")", ";", "// send file close command", "try", "{", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "command", ".", "fileCloseFlush", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'cannot flush/close remote file'", ")", ";", "}", "}", "}", "// start transfer", "return", "writeChunk", "(", ")", ";", "}" ]
utility function to handle the file transfer
[ "utility", "function", "to", "handle", "the", "file", "transfer" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/connector/upload.js#L13-L84
17,537
AndiDittrich/NodeMCU-Tool
lib/connector/upload.js
writeChunk
async function writeChunk(){ if (chunks.length > 0){ // get first element const l = chunks.shift(); // increment size counter currentUploadSize += l.length; // write first element to file try{ await _virtualTerminal.executeCommand('__nmtwrite("' + l + '")'); }catch(e){ _logger.debug(e); throw new Error('cannot write chunk to remote file'); } // run progress callback progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]); // write next await writeChunk(); }else{ // ensure that the progress callback is called, even for empty files progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]); // send file close command try{ await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fileCloseFlush); }catch(e){ _logger.debug(e); throw new Error('cannot flush/close remote file'); } } }
javascript
async function writeChunk(){ if (chunks.length > 0){ // get first element const l = chunks.shift(); // increment size counter currentUploadSize += l.length; // write first element to file try{ await _virtualTerminal.executeCommand('__nmtwrite("' + l + '")'); }catch(e){ _logger.debug(e); throw new Error('cannot write chunk to remote file'); } // run progress callback progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]); // write next await writeChunk(); }else{ // ensure that the progress callback is called, even for empty files progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]); // send file close command try{ await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fileCloseFlush); }catch(e){ _logger.debug(e); throw new Error('cannot flush/close remote file'); } } }
[ "async", "function", "writeChunk", "(", ")", "{", "if", "(", "chunks", ".", "length", ">", "0", ")", "{", "// get first element", "const", "l", "=", "chunks", ".", "shift", "(", ")", ";", "// increment size counter", "currentUploadSize", "+=", "l", ".", "length", ";", "// write first element to file", "try", "{", "await", "_virtualTerminal", ".", "executeCommand", "(", "'__nmtwrite(\"'", "+", "l", "+", "'\")'", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'cannot write chunk to remote file'", ")", ";", "}", "// run progress callback", "progressCb", ".", "apply", "(", "progressCb", ",", "[", "currentUploadSize", ",", "absoluteFilesize", "]", ")", ";", "// write next", "await", "writeChunk", "(", ")", ";", "}", "else", "{", "// ensure that the progress callback is called, even for empty files", "progressCb", ".", "apply", "(", "progressCb", ",", "[", "currentUploadSize", ",", "absoluteFilesize", "]", ")", ";", "// send file close command", "try", "{", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "command", ".", "fileCloseFlush", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'cannot flush/close remote file'", ")", ";", "}", "}", "}" ]
internal helper to write chunks
[ "internal", "helper", "to", "write", "chunks" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/connector/upload.js#L46-L80
17,538
AndiDittrich/NodeMCU-Tool
lib/connector/upload.js
requireTransferHelper
async function requireTransferHelper(){ // hex write helper already uploaded within current session ? // otherwise upload helper if (_isTransferWriteHelperUploaded !== true){ let response = null; try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.transferWriteHelper)); }catch(e){ _logger.debug(e); throw new Error('cannot upload transfer helper function'); } // get transfer encoding if (response == 'b'){ _transferEncoding = 'base64' }else if (response == 'h'){ _transferEncoding = 'hex' }else{ throw new Error('unknown transfer encoding - ' + response); } // show encoding _logger.log('Transfer-Mode: ' + _transferEncoding); // set flag _isTransferWriteHelperUploaded = true; } }
javascript
async function requireTransferHelper(){ // hex write helper already uploaded within current session ? // otherwise upload helper if (_isTransferWriteHelperUploaded !== true){ let response = null; try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.transferWriteHelper)); }catch(e){ _logger.debug(e); throw new Error('cannot upload transfer helper function'); } // get transfer encoding if (response == 'b'){ _transferEncoding = 'base64' }else if (response == 'h'){ _transferEncoding = 'hex' }else{ throw new Error('unknown transfer encoding - ' + response); } // show encoding _logger.log('Transfer-Mode: ' + _transferEncoding); // set flag _isTransferWriteHelperUploaded = true; } }
[ "async", "function", "requireTransferHelper", "(", ")", "{", "// hex write helper already uploaded within current session ?", "// otherwise upload helper", "if", "(", "_isTransferWriteHelperUploaded", "!==", "true", ")", "{", "let", "response", "=", "null", ";", "try", "{", "(", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "command", ".", "transferWriteHelper", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'cannot upload transfer helper function'", ")", ";", "}", "// get transfer encoding", "if", "(", "response", "==", "'b'", ")", "{", "_transferEncoding", "=", "'base64'", "}", "else", "if", "(", "response", "==", "'h'", ")", "{", "_transferEncoding", "=", "'hex'", "}", "else", "{", "throw", "new", "Error", "(", "'unknown transfer encoding - '", "+", "response", ")", ";", "}", "// show encoding", "_logger", ".", "log", "(", "'Transfer-Mode: '", "+", "_transferEncoding", ")", ";", "// set flag", "_isTransferWriteHelperUploaded", "=", "true", ";", "}", "}" ]
utility function to upload file transfer helper
[ "utility", "function", "to", "upload", "file", "transfer", "helper" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/connector/upload.js#L87-L116
17,539
AndiDittrich/NodeMCU-Tool
lib/transport/serial-terminal.js
passthrough
function passthrough(devicename, baudrate, initialCommand=null){ return new Promise(function(resolve, reject){ // try to open the serial port const _device = new _serialport(devicename, { baudRate: parseInt(baudrate), autoOpen: false }); // new length parser const parser = _device.pipe(new _lengthParser({length: 1})); // handle low-level errors _device.on('error', reject); // listen on incomming data parser.on('data', function(input){ // passthrough process.stdout.write(input.toString('utf8')); }); // open connection _device.open(function(err){ if (err){ reject(err); }else{ // prepare if (process.stdin.isTTY){ process.stdin.setRawMode(true); } process.stdin.setEncoding('utf8'); // initial command set ? if (initialCommand !== null){ _device.write(initialCommand + '\n'); } // pass-through process.stdin.on('data', function(data){ // ctrl-c ? if (data == '\u0003'){ _device.close(function(e){ if (e){ reject(e); }else{ resolve(); } }); }else{ // passthrough stdin->serial _device.write(data); } }); } }); }); }
javascript
function passthrough(devicename, baudrate, initialCommand=null){ return new Promise(function(resolve, reject){ // try to open the serial port const _device = new _serialport(devicename, { baudRate: parseInt(baudrate), autoOpen: false }); // new length parser const parser = _device.pipe(new _lengthParser({length: 1})); // handle low-level errors _device.on('error', reject); // listen on incomming data parser.on('data', function(input){ // passthrough process.stdout.write(input.toString('utf8')); }); // open connection _device.open(function(err){ if (err){ reject(err); }else{ // prepare if (process.stdin.isTTY){ process.stdin.setRawMode(true); } process.stdin.setEncoding('utf8'); // initial command set ? if (initialCommand !== null){ _device.write(initialCommand + '\n'); } // pass-through process.stdin.on('data', function(data){ // ctrl-c ? if (data == '\u0003'){ _device.close(function(e){ if (e){ reject(e); }else{ resolve(); } }); }else{ // passthrough stdin->serial _device.write(data); } }); } }); }); }
[ "function", "passthrough", "(", "devicename", ",", "baudrate", ",", "initialCommand", "=", "null", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "// try to open the serial port", "const", "_device", "=", "new", "_serialport", "(", "devicename", ",", "{", "baudRate", ":", "parseInt", "(", "baudrate", ")", ",", "autoOpen", ":", "false", "}", ")", ";", "// new length parser", "const", "parser", "=", "_device", ".", "pipe", "(", "new", "_lengthParser", "(", "{", "length", ":", "1", "}", ")", ")", ";", "// handle low-level errors", "_device", ".", "on", "(", "'error'", ",", "reject", ")", ";", "// listen on incomming data", "parser", ".", "on", "(", "'data'", ",", "function", "(", "input", ")", "{", "// passthrough", "process", ".", "stdout", ".", "write", "(", "input", ".", "toString", "(", "'utf8'", ")", ")", ";", "}", ")", ";", "// open connection", "_device", ".", "open", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "// prepare", "if", "(", "process", ".", "stdin", ".", "isTTY", ")", "{", "process", ".", "stdin", ".", "setRawMode", "(", "true", ")", ";", "}", "process", ".", "stdin", ".", "setEncoding", "(", "'utf8'", ")", ";", "// initial command set ?", "if", "(", "initialCommand", "!==", "null", ")", "{", "_device", ".", "write", "(", "initialCommand", "+", "'\\n'", ")", ";", "}", "// pass-through", "process", ".", "stdin", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "// ctrl-c ?", "if", "(", "data", "==", "'\\u0003'", ")", "{", "_device", ".", "close", "(", "function", "(", "e", ")", "{", "if", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "else", "{", "resolve", "(", ")", ";", "}", "}", ")", ";", "}", "else", "{", "// passthrough stdin->serial", "_device", ".", "write", "(", "data", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
serial connection to stdout;stdin
[ "serial", "connection", "to", "stdout", ";", "stdin" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/transport/serial-terminal.js#L5-L62
17,540
AndiDittrich/NodeMCU-Tool
bin/nodemcu-tool.js
asyncWrapper
function asyncWrapper(promise){ return function(...args){ // extract options (last argument) _optionsManager.parse(args.pop()) // trigger command .then(options => { // re-merge return promise(...args, options) }) // trigger disconnect .then(() => { if (_nodemcutool.Connector.isConnected()){ _logger.log('disconnecting'); return _nodemcutool.disconnect(); } }) // gracefull exit .then(() => { process.exit(0) }) // handle low-level errors .catch(err => { _logger.error(err.message); _logger.debug(err.stack); process.exit(1); }); } }
javascript
function asyncWrapper(promise){ return function(...args){ // extract options (last argument) _optionsManager.parse(args.pop()) // trigger command .then(options => { // re-merge return promise(...args, options) }) // trigger disconnect .then(() => { if (_nodemcutool.Connector.isConnected()){ _logger.log('disconnecting'); return _nodemcutool.disconnect(); } }) // gracefull exit .then(() => { process.exit(0) }) // handle low-level errors .catch(err => { _logger.error(err.message); _logger.debug(err.stack); process.exit(1); }); } }
[ "function", "asyncWrapper", "(", "promise", ")", "{", "return", "function", "(", "...", "args", ")", "{", "// extract options (last argument)", "_optionsManager", ".", "parse", "(", "args", ".", "pop", "(", ")", ")", "// trigger command", ".", "then", "(", "options", "=>", "{", "// re-merge", "return", "promise", "(", "...", "args", ",", "options", ")", "}", ")", "// trigger disconnect", ".", "then", "(", "(", ")", "=>", "{", "if", "(", "_nodemcutool", ".", "Connector", ".", "isConnected", "(", ")", ")", "{", "_logger", ".", "log", "(", "'disconnecting'", ")", ";", "return", "_nodemcutool", ".", "disconnect", "(", ")", ";", "}", "}", ")", "// gracefull exit", ".", "then", "(", "(", ")", "=>", "{", "process", ".", "exit", "(", "0", ")", "}", ")", "// handle low-level errors", ".", "catch", "(", "err", "=>", "{", "_logger", ".", "error", "(", "err", ".", "message", ")", ";", "_logger", ".", "debug", "(", "err", ".", "stack", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", ")", ";", "}", "}" ]
wrap async tasks
[ "wrap", "async", "tasks" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/bin/nodemcu-tool.js#L25-L57
17,541
AndiDittrich/NodeMCU-Tool
lib/connector/check-connection.js
checkConnection
function checkConnection(){ return new Promise(function(resolve, reject){ // 1.5s connection timeout const watchdog = setTimeout(function(){ // throw error reject(new Error('Timeout, no response detected - is NodeMCU online and the Lua interpreter ready ?')); }, 1500); // send a simple print command to the lua engine _virtualTerminal.executeCommand(_luaCommandBuilder.command.echo) .then(({echo, response}) => { // clear watchdog clearTimeout(watchdog); // validate command echo and command output if (response == 'echo1337' && echo == 'print("echo1337")') { resolve(); } else { _logger.log('Echo:', echo); _logger.debug('Response:', response); reject(new Error('No response detected - is NodeMCU online and the Lua interpreter ready ?')); } }) .catch(reject) }); }
javascript
function checkConnection(){ return new Promise(function(resolve, reject){ // 1.5s connection timeout const watchdog = setTimeout(function(){ // throw error reject(new Error('Timeout, no response detected - is NodeMCU online and the Lua interpreter ready ?')); }, 1500); // send a simple print command to the lua engine _virtualTerminal.executeCommand(_luaCommandBuilder.command.echo) .then(({echo, response}) => { // clear watchdog clearTimeout(watchdog); // validate command echo and command output if (response == 'echo1337' && echo == 'print("echo1337")') { resolve(); } else { _logger.log('Echo:', echo); _logger.debug('Response:', response); reject(new Error('No response detected - is NodeMCU online and the Lua interpreter ready ?')); } }) .catch(reject) }); }
[ "function", "checkConnection", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "// 1.5s connection timeout", "const", "watchdog", "=", "setTimeout", "(", "function", "(", ")", "{", "// throw error", "reject", "(", "new", "Error", "(", "'Timeout, no response detected - is NodeMCU online and the Lua interpreter ready ?'", ")", ")", ";", "}", ",", "1500", ")", ";", "// send a simple print command to the lua engine", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "command", ".", "echo", ")", ".", "then", "(", "(", "{", "echo", ",", "response", "}", ")", "=>", "{", "// clear watchdog", "clearTimeout", "(", "watchdog", ")", ";", "// validate command echo and command output", "if", "(", "response", "==", "'echo1337'", "&&", "echo", "==", "'print(\"echo1337\")'", ")", "{", "resolve", "(", ")", ";", "}", "else", "{", "_logger", ".", "log", "(", "'Echo:'", ",", "echo", ")", ";", "_logger", ".", "debug", "(", "'Response:'", ",", "response", ")", ";", "reject", "(", "new", "Error", "(", "'No response detected - is NodeMCU online and the Lua interpreter ready ?'", ")", ")", ";", "}", "}", ")", ".", "catch", "(", "reject", ")", "}", ")", ";", "}" ]
checks the node-mcu connection
[ "checks", "the", "node", "-", "mcu", "connection" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/connector/check-connection.js#L6-L34
17,542
AndiDittrich/NodeMCU-Tool
lib/connector/download.js
download
async function download(remoteName){ let response = null; let data = null; // transfer helper function to encode hex data try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.transferReadHelper)); }catch(e){ _logger.debug(e); throw new Error('Cannot transfer hex.encode helper function'); } // open remote file for read try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.prepare('fileOpen', [remoteName, 'r']))); }catch(e){ _logger.debug(e); throw new Error('Cannot open remote file "' + remoteName + '" for read'); } // read content try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fileRead)); // encoding const tEncoding = response.match(/^[0-9A-F]+$/gi) ? 'hex' : 'base64'; _logger.log('Transfer-Encoding: ' + tEncoding); // decode file content + detect encoding data = new Buffer(response, tEncoding); }catch(e){ _logger.debug(e); throw new Error('Cannot read remote file content'); } // close remote file for read try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.fileClose)); }catch(e){ _logger.debug(e); throw new Error('Cannot close remote file "' + remoteName + '"'); } return data; }
javascript
async function download(remoteName){ let response = null; let data = null; // transfer helper function to encode hex data try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.transferReadHelper)); }catch(e){ _logger.debug(e); throw new Error('Cannot transfer hex.encode helper function'); } // open remote file for read try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.prepare('fileOpen', [remoteName, 'r']))); }catch(e){ _logger.debug(e); throw new Error('Cannot open remote file "' + remoteName + '" for read'); } // read content try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fileRead)); // encoding const tEncoding = response.match(/^[0-9A-F]+$/gi) ? 'hex' : 'base64'; _logger.log('Transfer-Encoding: ' + tEncoding); // decode file content + detect encoding data = new Buffer(response, tEncoding); }catch(e){ _logger.debug(e); throw new Error('Cannot read remote file content'); } // close remote file for read try{ ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.fileClose)); }catch(e){ _logger.debug(e); throw new Error('Cannot close remote file "' + remoteName + '"'); } return data; }
[ "async", "function", "download", "(", "remoteName", ")", "{", "let", "response", "=", "null", ";", "let", "data", "=", "null", ";", "// transfer helper function to encode hex data", "try", "{", "(", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "command", ".", "transferReadHelper", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'Cannot transfer hex.encode helper function'", ")", ";", "}", "// open remote file for read", "try", "{", "(", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "prepare", "(", "'fileOpen'", ",", "[", "remoteName", ",", "'r'", "]", ")", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'Cannot open remote file \"'", "+", "remoteName", "+", "'\" for read'", ")", ";", "}", "// read content", "try", "{", "(", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "command", ".", "fileRead", ")", ")", ";", "// encoding", "const", "tEncoding", "=", "response", ".", "match", "(", "/", "^[0-9A-F]+$", "/", "gi", ")", "?", "'hex'", ":", "'base64'", ";", "_logger", ".", "log", "(", "'Transfer-Encoding: '", "+", "tEncoding", ")", ";", "// decode file content + detect encoding", "data", "=", "new", "Buffer", "(", "response", ",", "tEncoding", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'Cannot read remote file content'", ")", ";", "}", "// close remote file for read", "try", "{", "(", "{", "response", "}", "=", "await", "_virtualTerminal", ".", "executeCommand", "(", "_luaCommandBuilder", ".", "fileClose", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "_logger", ".", "debug", "(", "e", ")", ";", "throw", "new", "Error", "(", "'Cannot close remote file \"'", "+", "remoteName", "+", "'\"'", ")", ";", "}", "return", "data", ";", "}" ]
download a file from NodeMCU
[ "download", "a", "file", "from", "NodeMCU" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/connector/download.js#L6-L51
17,543
AndiDittrich/NodeMCU-Tool
lib/connector/list-devices.js
listDevices
async function listDevices(showAll){ // get all available serial ports const ports = (await _serialport.list()) || []; // just pass-through if (showAll){ return ports; // filter by vendorIDs }else{ return ports.filter(function(item){ // return knownVendorIDs.includes(item.vendorId && item.vendorId.toUpperCase()); }); } }
javascript
async function listDevices(showAll){ // get all available serial ports const ports = (await _serialport.list()) || []; // just pass-through if (showAll){ return ports; // filter by vendorIDs }else{ return ports.filter(function(item){ // return knownVendorIDs.includes(item.vendorId && item.vendorId.toUpperCase()); }); } }
[ "async", "function", "listDevices", "(", "showAll", ")", "{", "// get all available serial ports", "const", "ports", "=", "(", "await", "_serialport", ".", "list", "(", ")", ")", "||", "[", "]", ";", "// just pass-through", "if", "(", "showAll", ")", "{", "return", "ports", ";", "// filter by vendorIDs", "}", "else", "{", "return", "ports", ".", "filter", "(", "function", "(", "item", ")", "{", "// ", "return", "knownVendorIDs", ".", "includes", "(", "item", ".", "vendorId", "&&", "item", ".", "vendorId", ".", "toUpperCase", "(", ")", ")", ";", "}", ")", ";", "}", "}" ]
show connected serial devices
[ "show", "connected", "serial", "devices" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/connector/list-devices.js#L16-L30
17,544
AndiDittrich/NodeMCU-Tool
lib/cli/options-manager.js
mergeOptions
function mergeOptions(...opt){ // extract default (last argument) const result = opt.pop(); // try to find first match while (opt.length > 0){ // extract first argument (priority) const o = opt.shift(); // value set ? if (typeof o !== 'undefined' && o !== null){ return o; } } return result; }
javascript
function mergeOptions(...opt){ // extract default (last argument) const result = opt.pop(); // try to find first match while (opt.length > 0){ // extract first argument (priority) const o = opt.shift(); // value set ? if (typeof o !== 'undefined' && o !== null){ return o; } } return result; }
[ "function", "mergeOptions", "(", "...", "opt", ")", "{", "// extract default (last argument)", "const", "result", "=", "opt", ".", "pop", "(", ")", ";", "// try to find first match", "while", "(", "opt", ".", "length", ">", "0", ")", "{", "// extract first argument (priority)", "const", "o", "=", "opt", ".", "shift", "(", ")", ";", "// value set ?", "if", "(", "typeof", "o", "!==", "'undefined'", "&&", "o", "!==", "null", ")", "{", "return", "o", ";", "}", "}", "return", "result", ";", "}" ]
utility function to merge different options cli args take presendence over config
[ "utility", "function", "to", "merge", "different", "options", "cli", "args", "take", "presendence", "over", "config" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/cli/options-manager.js#L54-L70
17,545
AndiDittrich/NodeMCU-Tool
lib/cli/options-manager.js
storeOptions
async function storeOptions(options){ await _fs.writeFile(_configFilename, JSON.stringify(options, null, 4)); }
javascript
async function storeOptions(options){ await _fs.writeFile(_configFilename, JSON.stringify(options, null, 4)); }
[ "async", "function", "storeOptions", "(", "options", ")", "{", "await", "_fs", ".", "writeFile", "(", "_configFilename", ",", "JSON", ".", "stringify", "(", "options", ",", "null", ",", "4", ")", ")", ";", "}" ]
write options to file
[ "write", "options", "to", "file" ]
93670a062d38dd65e868295b0b071be503714b7c
https://github.com/AndiDittrich/NodeMCU-Tool/blob/93670a062d38dd65e868295b0b071be503714b7c/lib/cli/options-manager.js#L107-L109
17,546
Diokuz/baron
src/autoUpdate.js
startWatch
function startWatch() { if (watcher) return watcher = setInterval(function() { if (self.root[self.origin.offset]) { stopWatch() self.update() } }, 300) // is it good enought for you?) }
javascript
function startWatch() { if (watcher) return watcher = setInterval(function() { if (self.root[self.origin.offset]) { stopWatch() self.update() } }, 300) // is it good enought for you?) }
[ "function", "startWatch", "(", ")", "{", "if", "(", "watcher", ")", "return", "watcher", "=", "setInterval", "(", "function", "(", ")", "{", "if", "(", "self", ".", "root", "[", "self", ".", "origin", ".", "offset", "]", ")", "{", "stopWatch", "(", ")", "self", ".", "update", "(", ")", "}", "}", ",", "300", ")", "// is it good enought for you?)", "}" ]
Set interval timeout for watching when root node will be visible
[ "Set", "interval", "timeout", "for", "watching", "when", "root", "node", "will", "be", "visible" ]
2403ec98582c624da7671fff6c44b864a64caf5f
https://github.com/Diokuz/baron/blob/2403ec98582c624da7671fff6c44b864a64caf5f/src/autoUpdate.js#L22-L31
17,547
Diokuz/baron
src/core.js
baron
function baron(user) { var withParams = !!user var tryNode = (user && user[0]) || user var isNode = typeof user == 'string' || tryNode instanceof HTMLElement var params = isNode ? { root: user } : clone(user) var jQueryMode var rootNode var defaultParams = { direction: 'v', barOnCls: '_scrollbar', resizeDebounce: 0, event: event, cssGuru: false, impact: 'scroller', position: 'static' } params = params || {} // Extending default params by user-defined params for (var key in defaultParams) { if (params[key] == null) { // eslint-disable-line params[key] = defaultParams[key] } } if (process.env.NODE_ENV !== 'production') { if (params.position == 'absolute' && params.impact == 'clipper') { log('error', [ 'Simultaneous use of `absolute` position and `clipper` impact values detected.', 'Those values cannot be used together.', 'See more https://github.com/Diokuz/baron/issues/138' ].join(' '), params) } } // `this` could be a jQuery instance jQueryMode = this && this instanceof scopedWindow.jQuery if (params._chain) { rootNode = params.root } else if (jQueryMode) { params.root = rootNode = this[0] } else { rootNode = qs(params.root || params.scroller) } if (process.env.NODE_ENV !== 'production') { if (!rootNode) { log('error', [ 'Baron initialization failed: root node not found.' ].join(', '), params) return // or return baron-shell? } } var attr = manageAttr(rootNode, params.direction) var id = +attr // Could be NaN params.index = id // baron() can return existing instances, // @TODO update params on-the-fly // https://github.com/Diokuz/baron/issues/124 if (id == id && attr !== null && instances[id]) { if (process.env.NODE_ENV !== 'production') { if (withParams) { log('error', [ 'repeated initialization for html-node detected', 'https://github.com/Diokuz/baron/blob/master/docs/logs/repeated.md' ].join(', '), params.root) } } return instances[id] } // root and scroller can be different nodes if (params.root && params.scroller) { params.scroller = qs(params.scroller, rootNode) if (process.env.NODE_ENV !== 'production') { if (!params.scroller) { log('error', 'Scroller not found!', rootNode, params.scroller) } } } else { params.scroller = rootNode } params.root = rootNode var instance = init(params) if (instance.autoUpdate) { instance.autoUpdate() } return instance }
javascript
function baron(user) { var withParams = !!user var tryNode = (user && user[0]) || user var isNode = typeof user == 'string' || tryNode instanceof HTMLElement var params = isNode ? { root: user } : clone(user) var jQueryMode var rootNode var defaultParams = { direction: 'v', barOnCls: '_scrollbar', resizeDebounce: 0, event: event, cssGuru: false, impact: 'scroller', position: 'static' } params = params || {} // Extending default params by user-defined params for (var key in defaultParams) { if (params[key] == null) { // eslint-disable-line params[key] = defaultParams[key] } } if (process.env.NODE_ENV !== 'production') { if (params.position == 'absolute' && params.impact == 'clipper') { log('error', [ 'Simultaneous use of `absolute` position and `clipper` impact values detected.', 'Those values cannot be used together.', 'See more https://github.com/Diokuz/baron/issues/138' ].join(' '), params) } } // `this` could be a jQuery instance jQueryMode = this && this instanceof scopedWindow.jQuery if (params._chain) { rootNode = params.root } else if (jQueryMode) { params.root = rootNode = this[0] } else { rootNode = qs(params.root || params.scroller) } if (process.env.NODE_ENV !== 'production') { if (!rootNode) { log('error', [ 'Baron initialization failed: root node not found.' ].join(', '), params) return // or return baron-shell? } } var attr = manageAttr(rootNode, params.direction) var id = +attr // Could be NaN params.index = id // baron() can return existing instances, // @TODO update params on-the-fly // https://github.com/Diokuz/baron/issues/124 if (id == id && attr !== null && instances[id]) { if (process.env.NODE_ENV !== 'production') { if (withParams) { log('error', [ 'repeated initialization for html-node detected', 'https://github.com/Diokuz/baron/blob/master/docs/logs/repeated.md' ].join(', '), params.root) } } return instances[id] } // root and scroller can be different nodes if (params.root && params.scroller) { params.scroller = qs(params.scroller, rootNode) if (process.env.NODE_ENV !== 'production') { if (!params.scroller) { log('error', 'Scroller not found!', rootNode, params.scroller) } } } else { params.scroller = rootNode } params.root = rootNode var instance = init(params) if (instance.autoUpdate) { instance.autoUpdate() } return instance }
[ "function", "baron", "(", "user", ")", "{", "var", "withParams", "=", "!", "!", "user", "var", "tryNode", "=", "(", "user", "&&", "user", "[", "0", "]", ")", "||", "user", "var", "isNode", "=", "typeof", "user", "==", "'string'", "||", "tryNode", "instanceof", "HTMLElement", "var", "params", "=", "isNode", "?", "{", "root", ":", "user", "}", ":", "clone", "(", "user", ")", "var", "jQueryMode", "var", "rootNode", "var", "defaultParams", "=", "{", "direction", ":", "'v'", ",", "barOnCls", ":", "'_scrollbar'", ",", "resizeDebounce", ":", "0", ",", "event", ":", "event", ",", "cssGuru", ":", "false", ",", "impact", ":", "'scroller'", ",", "position", ":", "'static'", "}", "params", "=", "params", "||", "{", "}", "// Extending default params by user-defined params", "for", "(", "var", "key", "in", "defaultParams", ")", "{", "if", "(", "params", "[", "key", "]", "==", "null", ")", "{", "// eslint-disable-line", "params", "[", "key", "]", "=", "defaultParams", "[", "key", "]", "}", "}", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "if", "(", "params", ".", "position", "==", "'absolute'", "&&", "params", ".", "impact", "==", "'clipper'", ")", "{", "log", "(", "'error'", ",", "[", "'Simultaneous use of `absolute` position and `clipper` impact values detected.'", ",", "'Those values cannot be used together.'", ",", "'See more https://github.com/Diokuz/baron/issues/138'", "]", ".", "join", "(", "' '", ")", ",", "params", ")", "}", "}", "// `this` could be a jQuery instance", "jQueryMode", "=", "this", "&&", "this", "instanceof", "scopedWindow", ".", "jQuery", "if", "(", "params", ".", "_chain", ")", "{", "rootNode", "=", "params", ".", "root", "}", "else", "if", "(", "jQueryMode", ")", "{", "params", ".", "root", "=", "rootNode", "=", "this", "[", "0", "]", "}", "else", "{", "rootNode", "=", "qs", "(", "params", ".", "root", "||", "params", ".", "scroller", ")", "}", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "if", "(", "!", "rootNode", ")", "{", "log", "(", "'error'", ",", "[", "'Baron initialization failed: root node not found.'", "]", ".", "join", "(", "', '", ")", ",", "params", ")", "return", "// or return baron-shell?", "}", "}", "var", "attr", "=", "manageAttr", "(", "rootNode", ",", "params", ".", "direction", ")", "var", "id", "=", "+", "attr", "// Could be NaN", "params", ".", "index", "=", "id", "// baron() can return existing instances,", "// @TODO update params on-the-fly", "// https://github.com/Diokuz/baron/issues/124", "if", "(", "id", "==", "id", "&&", "attr", "!==", "null", "&&", "instances", "[", "id", "]", ")", "{", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "if", "(", "withParams", ")", "{", "log", "(", "'error'", ",", "[", "'repeated initialization for html-node detected'", ",", "'https://github.com/Diokuz/baron/blob/master/docs/logs/repeated.md'", "]", ".", "join", "(", "', '", ")", ",", "params", ".", "root", ")", "}", "}", "return", "instances", "[", "id", "]", "}", "// root and scroller can be different nodes", "if", "(", "params", ".", "root", "&&", "params", ".", "scroller", ")", "{", "params", ".", "scroller", "=", "qs", "(", "params", ".", "scroller", ",", "rootNode", ")", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "if", "(", "!", "params", ".", "scroller", ")", "{", "log", "(", "'error'", ",", "'Scroller not found!'", ",", "rootNode", ",", "params", ".", "scroller", ")", "}", "}", "}", "else", "{", "params", ".", "scroller", "=", "rootNode", "}", "params", ".", "root", "=", "rootNode", "var", "instance", "=", "init", "(", "params", ")", "if", "(", "instance", ".", "autoUpdate", ")", "{", "instance", ".", "autoUpdate", "(", ")", "}", "return", "instance", "}" ]
window.baron and jQuery.fn.baron points to this function
[ "window", ".", "baron", "and", "jQuery", ".", "fn", ".", "baron", "points", "to", "this", "function" ]
2403ec98582c624da7671fff6c44b864a64caf5f
https://github.com/Diokuz/baron/blob/2403ec98582c624da7671fff6c44b864a64caf5f/src/core.js#L61-L160
17,548
Diokuz/baron
src/core.js
manageAttr
function manageAttr(node, direction, mode, id) { var attrName = 'data-baron-' + direction + '-id' if (mode == 'on') { node.setAttribute(attrName, id) } else if (mode == 'off') { node.removeAttribute(attrName) } return node.getAttribute(attrName) }
javascript
function manageAttr(node, direction, mode, id) { var attrName = 'data-baron-' + direction + '-id' if (mode == 'on') { node.setAttribute(attrName, id) } else if (mode == 'off') { node.removeAttribute(attrName) } return node.getAttribute(attrName) }
[ "function", "manageAttr", "(", "node", ",", "direction", ",", "mode", ",", "id", ")", "{", "var", "attrName", "=", "'data-baron-'", "+", "direction", "+", "'-id'", "if", "(", "mode", "==", "'on'", ")", "{", "node", ".", "setAttribute", "(", "attrName", ",", "id", ")", "}", "else", "if", "(", "mode", "==", "'off'", ")", "{", "node", ".", "removeAttribute", "(", "attrName", ")", "}", "return", "node", ".", "getAttribute", "(", "attrName", ")", "}" ]
set, remove or read baron-specific id-attribute @returns {String|null} - id node value, or null, if there is no attr
[ "set", "remove", "or", "read", "baron", "-", "specific", "id", "-", "attribute" ]
2403ec98582c624da7671fff6c44b864a64caf5f
https://github.com/Diokuz/baron/blob/2403ec98582c624da7671fff6c44b864a64caf5f/src/core.js#L326-L336
17,549
Diokuz/baron
src/core.js
function(func, wait) { var self = this, timeout, // args, // right now there is no need for arguments // context, // and for context timestamp // result // and for result var later = function() { if (self._disposed) { clearTimeout(timeout) timeout = self = null return } var last = getTime() - timestamp if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last) } else { timeout = null // result = func.apply(context, args) func() // context = args = null } } return function() { // context = this // args = arguments timestamp = getTime() if (!timeout) { timeout = setTimeout(later, wait) } // return result } }
javascript
function(func, wait) { var self = this, timeout, // args, // right now there is no need for arguments // context, // and for context timestamp // result // and for result var later = function() { if (self._disposed) { clearTimeout(timeout) timeout = self = null return } var last = getTime() - timestamp if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last) } else { timeout = null // result = func.apply(context, args) func() // context = args = null } } return function() { // context = this // args = arguments timestamp = getTime() if (!timeout) { timeout = setTimeout(later, wait) } // return result } }
[ "function", "(", "func", ",", "wait", ")", "{", "var", "self", "=", "this", ",", "timeout", ",", "// args, // right now there is no need for arguments", "// context, // and for context", "timestamp", "// result // and for result", "var", "later", "=", "function", "(", ")", "{", "if", "(", "self", ".", "_disposed", ")", "{", "clearTimeout", "(", "timeout", ")", "timeout", "=", "self", "=", "null", "return", "}", "var", "last", "=", "getTime", "(", ")", "-", "timestamp", "if", "(", "last", "<", "wait", "&&", "last", ">=", "0", ")", "{", "timeout", "=", "setTimeout", "(", "later", ",", "wait", "-", "last", ")", "}", "else", "{", "timeout", "=", "null", "// result = func.apply(context, args)", "func", "(", ")", "// context = args = null", "}", "}", "return", "function", "(", ")", "{", "// context = this", "// args = arguments", "timestamp", "=", "getTime", "(", ")", "if", "(", "!", "timeout", ")", "{", "timeout", "=", "setTimeout", "(", "later", ",", "wait", ")", "}", "// return result", "}", "}" ]
underscore.js realization used in autoUpdate plugin
[ "underscore", ".", "js", "realization", "used", "in", "autoUpdate", "plugin" ]
2403ec98582c624da7671fff6c44b864a64caf5f
https://github.com/Diokuz/baron/blob/2403ec98582c624da7671fff6c44b864a64caf5f/src/core.js#L385-L423
17,550
Diokuz/baron
src/core.js
setBarSize
function setBarSize(_size) { var barMinSize = this.barMinSize || 20 var size = _size if (size > 0 && size < barMinSize) { size = barMinSize } if (this.bar) { css(this.bar, this.origin.size, parseInt(size, 10) + 'px') } }
javascript
function setBarSize(_size) { var barMinSize = this.barMinSize || 20 var size = _size if (size > 0 && size < barMinSize) { size = barMinSize } if (this.bar) { css(this.bar, this.origin.size, parseInt(size, 10) + 'px') } }
[ "function", "setBarSize", "(", "_size", ")", "{", "var", "barMinSize", "=", "this", ".", "barMinSize", "||", "20", "var", "size", "=", "_size", "if", "(", "size", ">", "0", "&&", "size", "<", "barMinSize", ")", "{", "size", "=", "barMinSize", "}", "if", "(", "this", ".", "bar", ")", "{", "css", "(", "this", ".", "bar", ",", "this", ".", "origin", ".", "size", ",", "parseInt", "(", "size", ",", "10", ")", "+", "'px'", ")", "}", "}" ]
Updating height or width of bar
[ "Updating", "height", "or", "width", "of", "bar" ]
2403ec98582c624da7671fff6c44b864a64caf5f
https://github.com/Diokuz/baron/blob/2403ec98582c624da7671fff6c44b864a64caf5f/src/core.js#L472-L483
17,551
Diokuz/baron
src/core.js
posBar
function posBar(_pos) { if (this.bar) { var was = css(this.bar, this.origin.pos), will = +_pos + 'px' if (will && will != was) { css(this.bar, this.origin.pos, will) } } }
javascript
function posBar(_pos) { if (this.bar) { var was = css(this.bar, this.origin.pos), will = +_pos + 'px' if (will && will != was) { css(this.bar, this.origin.pos, will) } } }
[ "function", "posBar", "(", "_pos", ")", "{", "if", "(", "this", ".", "bar", ")", "{", "var", "was", "=", "css", "(", "this", ".", "bar", ",", "this", ".", "origin", ".", "pos", ")", ",", "will", "=", "+", "_pos", "+", "'px'", "if", "(", "will", "&&", "will", "!=", "was", ")", "{", "css", "(", "this", ".", "bar", ",", "this", ".", "origin", ".", "pos", ",", "will", ")", "}", "}", "}" ]
Updating top or left bar position
[ "Updating", "top", "or", "left", "bar", "position" ]
2403ec98582c624da7671fff6c44b864a64caf5f
https://github.com/Diokuz/baron/blob/2403ec98582c624da7671fff6c44b864a64caf5f/src/core.js#L486-L495
17,552
Diokuz/baron
src/core.js
function(params) { if (process.env.NODE_ENV !== 'production') { if (this._disposed) { log('error', [ 'Update on disposed baron instance detected.', 'You should clear your stored baron value for this instance:', this ].join(' '), params) } } fire.call(this, 'upd', params) // Update all plugins' params this.resize(1) this.updatePositions(1) return this }
javascript
function(params) { if (process.env.NODE_ENV !== 'production') { if (this._disposed) { log('error', [ 'Update on disposed baron instance detected.', 'You should clear your stored baron value for this instance:', this ].join(' '), params) } } fire.call(this, 'upd', params) // Update all plugins' params this.resize(1) this.updatePositions(1) return this }
[ "function", "(", "params", ")", "{", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "if", "(", "this", ".", "_disposed", ")", "{", "log", "(", "'error'", ",", "[", "'Update on disposed baron instance detected.'", ",", "'You should clear your stored baron value for this instance:'", ",", "this", "]", ".", "join", "(", "' '", ")", ",", "params", ")", "}", "}", "fire", ".", "call", "(", "this", ",", "'upd'", ",", "params", ")", "// Update all plugins' params", "this", ".", "resize", "(", "1", ")", "this", ".", "updatePositions", "(", "1", ")", "return", "this", "}" ]
fires on any update and on init
[ "fires", "on", "any", "update", "and", "on", "init" ]
2403ec98582c624da7671fff6c44b864a64caf5f
https://github.com/Diokuz/baron/blob/2403ec98582c624da7671fff6c44b864a64caf5f/src/core.js#L790-L807
17,553
HelloFax/hellosign-nodejs-sdk
lib/HelloSignResource.js
HelloSignResource
function HelloSignResource(hellosign, urlData) { this._hellosign = hellosign; this._urlData = urlData || {}; this.basePath = utils.makeURLInterpolator(hellosign.getApiField('basePath')); this.path = utils.makeURLInterpolator(this.path); if (this.includeBasic) { this.includeBasic.forEach(function(methodName) { this[methodName] = HelloSignResource.BASIC_METHODS[methodName]; }, this); } this.initialize.apply(this, arguments); }
javascript
function HelloSignResource(hellosign, urlData) { this._hellosign = hellosign; this._urlData = urlData || {}; this.basePath = utils.makeURLInterpolator(hellosign.getApiField('basePath')); this.path = utils.makeURLInterpolator(this.path); if (this.includeBasic) { this.includeBasic.forEach(function(methodName) { this[methodName] = HelloSignResource.BASIC_METHODS[methodName]; }, this); } this.initialize.apply(this, arguments); }
[ "function", "HelloSignResource", "(", "hellosign", ",", "urlData", ")", "{", "this", ".", "_hellosign", "=", "hellosign", ";", "this", ".", "_urlData", "=", "urlData", "||", "{", "}", ";", "this", ".", "basePath", "=", "utils", ".", "makeURLInterpolator", "(", "hellosign", ".", "getApiField", "(", "'basePath'", ")", ")", ";", "this", ".", "path", "=", "utils", ".", "makeURLInterpolator", "(", "this", ".", "path", ")", ";", "if", "(", "this", ".", "includeBasic", ")", "{", "this", ".", "includeBasic", ".", "forEach", "(", "function", "(", "methodName", ")", "{", "this", "[", "methodName", "]", "=", "HelloSignResource", ".", "BASIC_METHODS", "[", "methodName", "]", ";", "}", ",", "this", ")", ";", "}", "this", ".", "initialize", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}" ]
Encapsulates request logic for a HelloSign Resource
[ "Encapsulates", "request", "logic", "for", "a", "HelloSign", "Resource" ]
5ab3e27896986602fa9613ccb3e7d2997f02539a
https://github.com/HelloFax/hellosign-nodejs-sdk/blob/5ab3e27896986602fa9613ccb3e7d2997f02539a/lib/HelloSignResource.js#L49-L65
17,554
silas/node-consul
lib/agent.js
Agent
function Agent(consul) { this.consul = consul; this.check = new Agent.Check(consul); this.service = new Agent.Service(consul); }
javascript
function Agent(consul) { this.consul = consul; this.check = new Agent.Check(consul); this.service = new Agent.Service(consul); }
[ "function", "Agent", "(", "consul", ")", "{", "this", ".", "consul", "=", "consul", ";", "this", ".", "check", "=", "new", "Agent", ".", "Check", "(", "consul", ")", ";", "this", ".", "service", "=", "new", "Agent", ".", "Service", "(", "consul", ")", ";", "}" ]
Initialize a new `Agent` client.
[ "Initialize", "a", "new", "Agent", "client", "." ]
d009af5b05a1543fa7bd7aa58a6325d1aae93308
https://github.com/silas/node-consul/blob/d009af5b05a1543fa7bd7aa58a6325d1aae93308/lib/agent.js#L20-L24
17,555
silas/node-consul
lib/lock.js
Lock
function Lock(consul, opts) { events.EventEmitter.call(this); opts = utils.normalizeKeys(opts); this.consul = consul; this._opts = opts; this._defaults = utils.defaultCommonOptions(opts); if (opts.session) { switch (typeof opts.session) { case 'string': opts.session = { id: opts.session }; break; case 'object': opts.session = utils.normalizeKeys(opts.session); break; default: throw errors.Validation('session must be an object or string'); } } else { opts.session = {}; } if (!opts.key) { throw errors.Validation('key required'); } else if (typeof opts.key !== 'string') { throw errors.Validation('key must be a string'); } }
javascript
function Lock(consul, opts) { events.EventEmitter.call(this); opts = utils.normalizeKeys(opts); this.consul = consul; this._opts = opts; this._defaults = utils.defaultCommonOptions(opts); if (opts.session) { switch (typeof opts.session) { case 'string': opts.session = { id: opts.session }; break; case 'object': opts.session = utils.normalizeKeys(opts.session); break; default: throw errors.Validation('session must be an object or string'); } } else { opts.session = {}; } if (!opts.key) { throw errors.Validation('key required'); } else if (typeof opts.key !== 'string') { throw errors.Validation('key must be a string'); } }
[ "function", "Lock", "(", "consul", ",", "opts", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "opts", "=", "utils", ".", "normalizeKeys", "(", "opts", ")", ";", "this", ".", "consul", "=", "consul", ";", "this", ".", "_opts", "=", "opts", ";", "this", ".", "_defaults", "=", "utils", ".", "defaultCommonOptions", "(", "opts", ")", ";", "if", "(", "opts", ".", "session", ")", "{", "switch", "(", "typeof", "opts", ".", "session", ")", "{", "case", "'string'", ":", "opts", ".", "session", "=", "{", "id", ":", "opts", ".", "session", "}", ";", "break", ";", "case", "'object'", ":", "opts", ".", "session", "=", "utils", ".", "normalizeKeys", "(", "opts", ".", "session", ")", ";", "break", ";", "default", ":", "throw", "errors", ".", "Validation", "(", "'session must be an object or string'", ")", ";", "}", "}", "else", "{", "opts", ".", "session", "=", "{", "}", ";", "}", "if", "(", "!", "opts", ".", "key", ")", "{", "throw", "errors", ".", "Validation", "(", "'key required'", ")", ";", "}", "else", "if", "(", "typeof", "opts", ".", "key", "!==", "'string'", ")", "{", "throw", "errors", ".", "Validation", "(", "'key must be a string'", ")", ";", "}", "}" ]
Initialize a new `Lock` instance.
[ "Initialize", "a", "new", "Lock", "instance", "." ]
d009af5b05a1543fa7bd7aa58a6325d1aae93308
https://github.com/silas/node-consul/blob/d009af5b05a1543fa7bd7aa58a6325d1aae93308/lib/lock.js#L34-L63
17,556
silas/node-consul
lib/utils.js
bodyItem
function bodyItem(request, next) { if (request.err) return next(false, request.err, undefined, request.res); if (request.res.body && request.res.body.length) { return next(false, undefined, request.res.body[0], request.res); } next(false, undefined, undefined, request.res); }
javascript
function bodyItem(request, next) { if (request.err) return next(false, request.err, undefined, request.res); if (request.res.body && request.res.body.length) { return next(false, undefined, request.res.body[0], request.res); } next(false, undefined, undefined, request.res); }
[ "function", "bodyItem", "(", "request", ",", "next", ")", "{", "if", "(", "request", ".", "err", ")", "return", "next", "(", "false", ",", "request", ".", "err", ",", "undefined", ",", "request", ".", "res", ")", ";", "if", "(", "request", ".", "res", ".", "body", "&&", "request", ".", "res", ".", "body", ".", "length", ")", "{", "return", "next", "(", "false", ",", "undefined", ",", "request", ".", "res", ".", "body", "[", "0", "]", ",", "request", ".", "res", ")", ";", "}", "next", "(", "false", ",", "undefined", ",", "undefined", ",", "request", ".", "res", ")", ";", "}" ]
First item in body
[ "First", "item", "in", "body" ]
d009af5b05a1543fa7bd7aa58a6325d1aae93308
https://github.com/silas/node-consul/blob/d009af5b05a1543fa7bd7aa58a6325d1aae93308/lib/utils.js#L27-L35
17,557
silas/node-consul
lib/utils.js
defaultCommonOptions
function defaultCommonOptions(opts) { opts = normalizeKeys(opts); var defaults; constants.DEFAULT_OPTIONS.forEach(function(key) { if (!opts.hasOwnProperty(key)) return; if (!defaults) defaults = {}; defaults[key] = opts[key]; }); return defaults; }
javascript
function defaultCommonOptions(opts) { opts = normalizeKeys(opts); var defaults; constants.DEFAULT_OPTIONS.forEach(function(key) { if (!opts.hasOwnProperty(key)) return; if (!defaults) defaults = {}; defaults[key] = opts[key]; }); return defaults; }
[ "function", "defaultCommonOptions", "(", "opts", ")", "{", "opts", "=", "normalizeKeys", "(", "opts", ")", ";", "var", "defaults", ";", "constants", ".", "DEFAULT_OPTIONS", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "!", "opts", ".", "hasOwnProperty", "(", "key", ")", ")", "return", ";", "if", "(", "!", "defaults", ")", "defaults", "=", "{", "}", ";", "defaults", "[", "key", "]", "=", "opts", "[", "key", "]", ";", "}", ")", ";", "return", "defaults", ";", "}" ]
Default common options
[ "Default", "common", "options" ]
d009af5b05a1543fa7bd7aa58a6325d1aae93308
https://github.com/silas/node-consul/blob/d009af5b05a1543fa7bd7aa58a6325d1aae93308/lib/utils.js#L160-L171
17,558
silas/node-consul
lib/utils.js
setTimeoutContext
function setTimeoutContext(fn, ctx, timeout) { var id; var cancel = function() { clearTimeout(id); }; id = setTimeout(function() { ctx.removeListener('cancel', cancel); fn(); }, timeout); ctx.once('cancel', cancel); }
javascript
function setTimeoutContext(fn, ctx, timeout) { var id; var cancel = function() { clearTimeout(id); }; id = setTimeout(function() { ctx.removeListener('cancel', cancel); fn(); }, timeout); ctx.once('cancel', cancel); }
[ "function", "setTimeoutContext", "(", "fn", ",", "ctx", ",", "timeout", ")", "{", "var", "id", ";", "var", "cancel", "=", "function", "(", ")", "{", "clearTimeout", "(", "id", ")", ";", "}", ";", "id", "=", "setTimeout", "(", "function", "(", ")", "{", "ctx", ".", "removeListener", "(", "'cancel'", ",", "cancel", ")", ";", "fn", "(", ")", ";", "}", ",", "timeout", ")", ";", "ctx", ".", "once", "(", "'cancel'", ",", "cancel", ")", ";", "}" ]
Set timeout with cancel support
[ "Set", "timeout", "with", "cancel", "support" ]
d009af5b05a1543fa7bd7aa58a6325d1aae93308
https://github.com/silas/node-consul/blob/d009af5b05a1543fa7bd7aa58a6325d1aae93308/lib/utils.js#L204-L218
17,559
silas/node-consul
lib/utils.js
setIntervalContext
function setIntervalContext(fn, ctx, timeout) { var id; var cancel = function() { clearInterval(id); }; id = setInterval(function() { fn(); }, timeout); ctx.once('cancel', cancel); }
javascript
function setIntervalContext(fn, ctx, timeout) { var id; var cancel = function() { clearInterval(id); }; id = setInterval(function() { fn(); }, timeout); ctx.once('cancel', cancel); }
[ "function", "setIntervalContext", "(", "fn", ",", "ctx", ",", "timeout", ")", "{", "var", "id", ";", "var", "cancel", "=", "function", "(", ")", "{", "clearInterval", "(", "id", ")", ";", "}", ";", "id", "=", "setInterval", "(", "function", "(", ")", "{", "fn", "(", ")", ";", "}", ",", "timeout", ")", ";", "ctx", ".", "once", "(", "'cancel'", ",", "cancel", ")", ";", "}" ]
Set interval with cancel support
[ "Set", "interval", "with", "cancel", "support" ]
d009af5b05a1543fa7bd7aa58a6325d1aae93308
https://github.com/silas/node-consul/blob/d009af5b05a1543fa7bd7aa58a6325d1aae93308/lib/utils.js#L224-L234
17,560
silas/node-consul
lib/utils.js
hasIndexChanged
function hasIndexChanged(index, prevIndex) { if (typeof index !== 'string' || !index) return false; if (typeof prevIndex !== 'string' || !prevIndex) return true; return index !== prevIndex; }
javascript
function hasIndexChanged(index, prevIndex) { if (typeof index !== 'string' || !index) return false; if (typeof prevIndex !== 'string' || !prevIndex) return true; return index !== prevIndex; }
[ "function", "hasIndexChanged", "(", "index", ",", "prevIndex", ")", "{", "if", "(", "typeof", "index", "!==", "'string'", "||", "!", "index", ")", "return", "false", ";", "if", "(", "typeof", "prevIndex", "!==", "'string'", "||", "!", "prevIndex", ")", "return", "true", ";", "return", "index", "!==", "prevIndex", ";", "}" ]
Has the Consul index changed.
[ "Has", "the", "Consul", "index", "changed", "." ]
d009af5b05a1543fa7bd7aa58a6325d1aae93308
https://github.com/silas/node-consul/blob/d009af5b05a1543fa7bd7aa58a6325d1aae93308/lib/utils.js#L316-L320
17,561
silas/node-consul
lib/utils.js
parseQueryMeta
function parseQueryMeta(res) { var meta = {}; if (res && res.headers) { if (res.headers['x-consul-index']) { meta.LastIndex = res.headers['x-consul-index']; } if (res.headers['x-consul-lastcontact']) { meta.LastContact = parseInt(res.headers['x-consul-lastcontact'], 10); } if (res.headers['x-consul-knownleader']) { meta.KnownLeader = res.headers['x-consul-knownleader'] === 'true'; } if (res.headers['x-consul-translate-addresses']) { meta.AddressTranslationEnabled = res.headers['x-consul-translate-addresses'] === 'true'; } } return meta; }
javascript
function parseQueryMeta(res) { var meta = {}; if (res && res.headers) { if (res.headers['x-consul-index']) { meta.LastIndex = res.headers['x-consul-index']; } if (res.headers['x-consul-lastcontact']) { meta.LastContact = parseInt(res.headers['x-consul-lastcontact'], 10); } if (res.headers['x-consul-knownleader']) { meta.KnownLeader = res.headers['x-consul-knownleader'] === 'true'; } if (res.headers['x-consul-translate-addresses']) { meta.AddressTranslationEnabled = res.headers['x-consul-translate-addresses'] === 'true'; } } return meta; }
[ "function", "parseQueryMeta", "(", "res", ")", "{", "var", "meta", "=", "{", "}", ";", "if", "(", "res", "&&", "res", ".", "headers", ")", "{", "if", "(", "res", ".", "headers", "[", "'x-consul-index'", "]", ")", "{", "meta", ".", "LastIndex", "=", "res", ".", "headers", "[", "'x-consul-index'", "]", ";", "}", "if", "(", "res", ".", "headers", "[", "'x-consul-lastcontact'", "]", ")", "{", "meta", ".", "LastContact", "=", "parseInt", "(", "res", ".", "headers", "[", "'x-consul-lastcontact'", "]", ",", "10", ")", ";", "}", "if", "(", "res", ".", "headers", "[", "'x-consul-knownleader'", "]", ")", "{", "meta", ".", "KnownLeader", "=", "res", ".", "headers", "[", "'x-consul-knownleader'", "]", "===", "'true'", ";", "}", "if", "(", "res", ".", "headers", "[", "'x-consul-translate-addresses'", "]", ")", "{", "meta", ".", "AddressTranslationEnabled", "=", "res", ".", "headers", "[", "'x-consul-translate-addresses'", "]", "===", "'true'", ";", "}", "}", "return", "meta", ";", "}" ]
Parse query meta
[ "Parse", "query", "meta" ]
d009af5b05a1543fa7bd7aa58a6325d1aae93308
https://github.com/silas/node-consul/blob/d009af5b05a1543fa7bd7aa58a6325d1aae93308/lib/utils.js#L326-L345
17,562
silas/node-consul
lib/catalog.js
Catalog
function Catalog(consul) { this.consul = consul; this.connect = new Catalog.Connect(consul); this.node = new Catalog.Node(consul); this.service = new Catalog.Service(consul); }
javascript
function Catalog(consul) { this.consul = consul; this.connect = new Catalog.Connect(consul); this.node = new Catalog.Node(consul); this.service = new Catalog.Service(consul); }
[ "function", "Catalog", "(", "consul", ")", "{", "this", ".", "consul", "=", "consul", ";", "this", ".", "connect", "=", "new", "Catalog", ".", "Connect", "(", "consul", ")", ";", "this", ".", "node", "=", "new", "Catalog", ".", "Node", "(", "consul", ")", ";", "this", ".", "service", "=", "new", "Catalog", ".", "Service", "(", "consul", ")", ";", "}" ]
Initialize a new `Catalog` client.
[ "Initialize", "a", "new", "Catalog", "client", "." ]
d009af5b05a1543fa7bd7aa58a6325d1aae93308
https://github.com/silas/node-consul/blob/d009af5b05a1543fa7bd7aa58a6325d1aae93308/lib/catalog.js#L20-L25
17,563
silas/node-consul
lib/consul.js
Consul
function Consul(opts) { if (!(this instanceof Consul)) { return new Consul(opts); } opts = utils.defaults({}, opts); if (!opts.baseUrl) { opts.baseUrl = (opts.secure ? 'https:' : 'http:') + '//' + (opts.host || '127.0.0.1') + ':' + (opts.port || 8500) + '/v1'; } opts.name = 'consul'; opts.type = 'json'; if (opts.defaults) { var defaults = utils.defaultCommonOptions(opts.defaults); if (defaults) this._defaults = defaults; } delete opts.defaults; papi.Client.call(this, opts); this.acl = new Consul.Acl(this); this.agent = new Consul.Agent(this); this.catalog = new Consul.Catalog(this); this.event = new Consul.Event(this); this.health = new Consul.Health(this); this.kv = new Consul.Kv(this); this.query = new Consul.Query(this); this.session = new Consul.Session(this); this.status = new Consul.Status(this); try { if (opts.promisify) { if (typeof opts.promisify === 'function') { papi.tools.promisify(this, opts.promisify); } else { papi.tools.promisify(this); } } } catch (err) { err.message = 'promisify: ' + err.message; throw err; } }
javascript
function Consul(opts) { if (!(this instanceof Consul)) { return new Consul(opts); } opts = utils.defaults({}, opts); if (!opts.baseUrl) { opts.baseUrl = (opts.secure ? 'https:' : 'http:') + '//' + (opts.host || '127.0.0.1') + ':' + (opts.port || 8500) + '/v1'; } opts.name = 'consul'; opts.type = 'json'; if (opts.defaults) { var defaults = utils.defaultCommonOptions(opts.defaults); if (defaults) this._defaults = defaults; } delete opts.defaults; papi.Client.call(this, opts); this.acl = new Consul.Acl(this); this.agent = new Consul.Agent(this); this.catalog = new Consul.Catalog(this); this.event = new Consul.Event(this); this.health = new Consul.Health(this); this.kv = new Consul.Kv(this); this.query = new Consul.Query(this); this.session = new Consul.Session(this); this.status = new Consul.Status(this); try { if (opts.promisify) { if (typeof opts.promisify === 'function') { papi.tools.promisify(this, opts.promisify); } else { papi.tools.promisify(this); } } } catch (err) { err.message = 'promisify: ' + err.message; throw err; } }
[ "function", "Consul", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Consul", ")", ")", "{", "return", "new", "Consul", "(", "opts", ")", ";", "}", "opts", "=", "utils", ".", "defaults", "(", "{", "}", ",", "opts", ")", ";", "if", "(", "!", "opts", ".", "baseUrl", ")", "{", "opts", ".", "baseUrl", "=", "(", "opts", ".", "secure", "?", "'https:'", ":", "'http:'", ")", "+", "'//'", "+", "(", "opts", ".", "host", "||", "'127.0.0.1'", ")", "+", "':'", "+", "(", "opts", ".", "port", "||", "8500", ")", "+", "'/v1'", ";", "}", "opts", ".", "name", "=", "'consul'", ";", "opts", ".", "type", "=", "'json'", ";", "if", "(", "opts", ".", "defaults", ")", "{", "var", "defaults", "=", "utils", ".", "defaultCommonOptions", "(", "opts", ".", "defaults", ")", ";", "if", "(", "defaults", ")", "this", ".", "_defaults", "=", "defaults", ";", "}", "delete", "opts", ".", "defaults", ";", "papi", ".", "Client", ".", "call", "(", "this", ",", "opts", ")", ";", "this", ".", "acl", "=", "new", "Consul", ".", "Acl", "(", "this", ")", ";", "this", ".", "agent", "=", "new", "Consul", ".", "Agent", "(", "this", ")", ";", "this", ".", "catalog", "=", "new", "Consul", ".", "Catalog", "(", "this", ")", ";", "this", ".", "event", "=", "new", "Consul", ".", "Event", "(", "this", ")", ";", "this", ".", "health", "=", "new", "Consul", ".", "Health", "(", "this", ")", ";", "this", ".", "kv", "=", "new", "Consul", ".", "Kv", "(", "this", ")", ";", "this", ".", "query", "=", "new", "Consul", ".", "Query", "(", "this", ")", ";", "this", ".", "session", "=", "new", "Consul", ".", "Session", "(", "this", ")", ";", "this", ".", "status", "=", "new", "Consul", ".", "Status", "(", "this", ")", ";", "try", "{", "if", "(", "opts", ".", "promisify", ")", "{", "if", "(", "typeof", "opts", ".", "promisify", "===", "'function'", ")", "{", "papi", ".", "tools", ".", "promisify", "(", "this", ",", "opts", ".", "promisify", ")", ";", "}", "else", "{", "papi", ".", "tools", ".", "promisify", "(", "this", ")", ";", "}", "}", "}", "catch", "(", "err", ")", "{", "err", ".", "message", "=", "'promisify: '", "+", "err", ".", "message", ";", "throw", "err", ";", "}", "}" ]
Initialize a new `Consul` client.
[ "Initialize", "a", "new", "Consul", "client", "." ]
d009af5b05a1543fa7bd7aa58a6325d1aae93308
https://github.com/silas/node-consul/blob/d009af5b05a1543fa7bd7aa58a6325d1aae93308/lib/consul.js#L31-L76
17,564
silas/node-consul
lib/watch.js
Watch
function Watch(consul, opts) { var self = this; events.EventEmitter.call(self); opts = utils.normalizeKeys(opts); var options = utils.normalizeKeys(opts.options || {}); options = utils.defaults(options, consul._defaults); options.wait = options.wait || '30s'; options.index = options.index || '0'; if (typeof options.timeout !== 'string' && typeof options.timeout !== 'number') { var wait = utils.parseDuration(options.wait); // A small random amount of additional wait time is added to the supplied // maximum wait time to spread out the wake up time of any concurrent // requests. This adds up to wait / 16 additional time to the maximum duration. options.timeout = Math.ceil(wait + Math.max(wait * 0.1, 500)); } var backoffFactor = 100; if (opts.hasOwnProperty('backofffactor') && typeof opts.backofffactor === 'number') { backoffFactor = opts.backofffactor; } var backoffMax = 30 * 1000; if (opts.hasOwnProperty('backoffmax') && typeof opts.backoffmax === 'number') { backoffMax = opts.backoffmax; } var maxAttempts = -1; if (opts.hasOwnProperty('maxattempts') && typeof opts.maxattempts === 'number') { maxAttempts = opts.maxattempts; } self._context = { consul: consul }; self._options = options; self._attempts = 0; self._maxAttempts = maxAttempts; self._backoffMax = backoffMax; self._backoffFactor = backoffFactor; self._method = opts.method; if (typeof opts.method !== 'function') { throw errors.Validation('method required'); } process.nextTick(function() { self._run(); }); }
javascript
function Watch(consul, opts) { var self = this; events.EventEmitter.call(self); opts = utils.normalizeKeys(opts); var options = utils.normalizeKeys(opts.options || {}); options = utils.defaults(options, consul._defaults); options.wait = options.wait || '30s'; options.index = options.index || '0'; if (typeof options.timeout !== 'string' && typeof options.timeout !== 'number') { var wait = utils.parseDuration(options.wait); // A small random amount of additional wait time is added to the supplied // maximum wait time to spread out the wake up time of any concurrent // requests. This adds up to wait / 16 additional time to the maximum duration. options.timeout = Math.ceil(wait + Math.max(wait * 0.1, 500)); } var backoffFactor = 100; if (opts.hasOwnProperty('backofffactor') && typeof opts.backofffactor === 'number') { backoffFactor = opts.backofffactor; } var backoffMax = 30 * 1000; if (opts.hasOwnProperty('backoffmax') && typeof opts.backoffmax === 'number') { backoffMax = opts.backoffmax; } var maxAttempts = -1; if (opts.hasOwnProperty('maxattempts') && typeof opts.maxattempts === 'number') { maxAttempts = opts.maxattempts; } self._context = { consul: consul }; self._options = options; self._attempts = 0; self._maxAttempts = maxAttempts; self._backoffMax = backoffMax; self._backoffFactor = backoffFactor; self._method = opts.method; if (typeof opts.method !== 'function') { throw errors.Validation('method required'); } process.nextTick(function() { self._run(); }); }
[ "function", "Watch", "(", "consul", ",", "opts", ")", "{", "var", "self", "=", "this", ";", "events", ".", "EventEmitter", ".", "call", "(", "self", ")", ";", "opts", "=", "utils", ".", "normalizeKeys", "(", "opts", ")", ";", "var", "options", "=", "utils", ".", "normalizeKeys", "(", "opts", ".", "options", "||", "{", "}", ")", ";", "options", "=", "utils", ".", "defaults", "(", "options", ",", "consul", ".", "_defaults", ")", ";", "options", ".", "wait", "=", "options", ".", "wait", "||", "'30s'", ";", "options", ".", "index", "=", "options", ".", "index", "||", "'0'", ";", "if", "(", "typeof", "options", ".", "timeout", "!==", "'string'", "&&", "typeof", "options", ".", "timeout", "!==", "'number'", ")", "{", "var", "wait", "=", "utils", ".", "parseDuration", "(", "options", ".", "wait", ")", ";", "// A small random amount of additional wait time is added to the supplied", "// maximum wait time to spread out the wake up time of any concurrent", "// requests. This adds up to wait / 16 additional time to the maximum duration.", "options", ".", "timeout", "=", "Math", ".", "ceil", "(", "wait", "+", "Math", ".", "max", "(", "wait", "*", "0.1", ",", "500", ")", ")", ";", "}", "var", "backoffFactor", "=", "100", ";", "if", "(", "opts", ".", "hasOwnProperty", "(", "'backofffactor'", ")", "&&", "typeof", "opts", ".", "backofffactor", "===", "'number'", ")", "{", "backoffFactor", "=", "opts", ".", "backofffactor", ";", "}", "var", "backoffMax", "=", "30", "*", "1000", ";", "if", "(", "opts", ".", "hasOwnProperty", "(", "'backoffmax'", ")", "&&", "typeof", "opts", ".", "backoffmax", "===", "'number'", ")", "{", "backoffMax", "=", "opts", ".", "backoffmax", ";", "}", "var", "maxAttempts", "=", "-", "1", ";", "if", "(", "opts", ".", "hasOwnProperty", "(", "'maxattempts'", ")", "&&", "typeof", "opts", ".", "maxattempts", "===", "'number'", ")", "{", "maxAttempts", "=", "opts", ".", "maxattempts", ";", "}", "self", ".", "_context", "=", "{", "consul", ":", "consul", "}", ";", "self", ".", "_options", "=", "options", ";", "self", ".", "_attempts", "=", "0", ";", "self", ".", "_maxAttempts", "=", "maxAttempts", ";", "self", ".", "_backoffMax", "=", "backoffMax", ";", "self", ".", "_backoffFactor", "=", "backoffFactor", ";", "self", ".", "_method", "=", "opts", ".", "method", ";", "if", "(", "typeof", "opts", ".", "method", "!==", "'function'", ")", "{", "throw", "errors", ".", "Validation", "(", "'method required'", ")", ";", "}", "process", ".", "nextTick", "(", "function", "(", ")", "{", "self", ".", "_run", "(", ")", ";", "}", ")", ";", "}" ]
Initialize a new `Watch` instance.
[ "Initialize", "a", "new", "Watch", "instance", "." ]
d009af5b05a1543fa7bd7aa58a6325d1aae93308
https://github.com/silas/node-consul/blob/d009af5b05a1543fa7bd7aa58a6325d1aae93308/lib/watch.js#L21-L67
17,565
pbojinov/request-ip
src/index.js
getClientIpFromXForwardedFor
function getClientIpFromXForwardedFor(value) { if (!is.existy(value)) { return null; } if (is.not.string(value)) { throw new TypeError(`Expected a string, got "${typeof value}"`); } // x-forwarded-for may return multiple IP addresses in the format: // "client IP, proxy 1 IP, proxy 2 IP" // Therefore, the right-most IP address is the IP address of the most recent proxy // and the left-most IP address is the IP address of the originating client. // source: http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html // Azure Web App's also adds a port for some reason, so we'll only use the first part (the IP) const forwardedIps = value.split(',').map((e) => { const ip = e.trim(); if (ip.includes(':')) { const splitted = ip.split(':'); // make sure we only use this if it's ipv4 (ip:port) if (splitted.length === 2) { return splitted[0]; } } return ip; }); // Sometimes IP addresses in this header can be 'unknown' (http://stackoverflow.com/a/11285650). // Therefore taking the left-most IP address that is not unknown // A Squid configuration directive can also set the value to "unknown" (http://www.squid-cache.org/Doc/config/forwarded_for/) return forwardedIps.find(is.ip); }
javascript
function getClientIpFromXForwardedFor(value) { if (!is.existy(value)) { return null; } if (is.not.string(value)) { throw new TypeError(`Expected a string, got "${typeof value}"`); } // x-forwarded-for may return multiple IP addresses in the format: // "client IP, proxy 1 IP, proxy 2 IP" // Therefore, the right-most IP address is the IP address of the most recent proxy // and the left-most IP address is the IP address of the originating client. // source: http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html // Azure Web App's also adds a port for some reason, so we'll only use the first part (the IP) const forwardedIps = value.split(',').map((e) => { const ip = e.trim(); if (ip.includes(':')) { const splitted = ip.split(':'); // make sure we only use this if it's ipv4 (ip:port) if (splitted.length === 2) { return splitted[0]; } } return ip; }); // Sometimes IP addresses in this header can be 'unknown' (http://stackoverflow.com/a/11285650). // Therefore taking the left-most IP address that is not unknown // A Squid configuration directive can also set the value to "unknown" (http://www.squid-cache.org/Doc/config/forwarded_for/) return forwardedIps.find(is.ip); }
[ "function", "getClientIpFromXForwardedFor", "(", "value", ")", "{", "if", "(", "!", "is", ".", "existy", "(", "value", ")", ")", "{", "return", "null", ";", "}", "if", "(", "is", ".", "not", ".", "string", "(", "value", ")", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "typeof", "value", "}", "`", ")", ";", "}", "// x-forwarded-for may return multiple IP addresses in the format:", "// \"client IP, proxy 1 IP, proxy 2 IP\"", "// Therefore, the right-most IP address is the IP address of the most recent proxy", "// and the left-most IP address is the IP address of the originating client.", "// source: http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html", "// Azure Web App's also adds a port for some reason, so we'll only use the first part (the IP)", "const", "forwardedIps", "=", "value", ".", "split", "(", "','", ")", ".", "map", "(", "(", "e", ")", "=>", "{", "const", "ip", "=", "e", ".", "trim", "(", ")", ";", "if", "(", "ip", ".", "includes", "(", "':'", ")", ")", "{", "const", "splitted", "=", "ip", ".", "split", "(", "':'", ")", ";", "// make sure we only use this if it's ipv4 (ip:port)", "if", "(", "splitted", ".", "length", "===", "2", ")", "{", "return", "splitted", "[", "0", "]", ";", "}", "}", "return", "ip", ";", "}", ")", ";", "// Sometimes IP addresses in this header can be 'unknown' (http://stackoverflow.com/a/11285650).", "// Therefore taking the left-most IP address that is not unknown", "// A Squid configuration directive can also set the value to \"unknown\" (http://www.squid-cache.org/Doc/config/forwarded_for/)", "return", "forwardedIps", ".", "find", "(", "is", ".", "ip", ")", ";", "}" ]
Parse x-forwarded-for headers. @param {string} value - The value to be parsed. @return {string|null} First known IP address, if any.
[ "Parse", "x", "-", "forwarded", "-", "for", "headers", "." ]
915d984b46d262e4418a889abc7601c38d47f049
https://github.com/pbojinov/request-ip/blob/915d984b46d262e4418a889abc7601c38d47f049/src/index.js#L9-L40
17,566
pbojinov/request-ip
src/index.js
getClientIp
function getClientIp(req) { // Server is probably behind a proxy. if (req.headers) { // Standard headers used by Amazon EC2, Heroku, and others. if (is.ip(req.headers['x-client-ip'])) { return req.headers['x-client-ip']; } // Load-balancers (AWS ELB) or proxies. const xForwardedFor = getClientIpFromXForwardedFor(req.headers['x-forwarded-for']); if (is.ip(xForwardedFor)) { return xForwardedFor; } // Cloudflare. // @see https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers- // CF-Connecting-IP - applied to every request to the origin. if (is.ip(req.headers['cf-connecting-ip'])) { return req.headers['cf-connecting-ip']; } // Fastly and Firebase hosting header (When forwared to cloud function) if (is.ip(req.headers['fastly-client-ip'])) { return req.headers['fastly-client-ip']; } // Akamai and Cloudflare: True-Client-IP. if (is.ip(req.headers['true-client-ip'])) { return req.headers['true-client-ip']; } // Default nginx proxy/fcgi; alternative to x-forwarded-for, used by some proxies. if (is.ip(req.headers['x-real-ip'])) { return req.headers['x-real-ip']; } // (Rackspace LB and Riverbed's Stingray) // http://www.rackspace.com/knowledge_center/article/controlling-access-to-linux-cloud-sites-based-on-the-client-ip-address // https://splash.riverbed.com/docs/DOC-1926 if (is.ip(req.headers['x-cluster-client-ip'])) { return req.headers['x-cluster-client-ip']; } if (is.ip(req.headers['x-forwarded'])) { return req.headers['x-forwarded']; } if (is.ip(req.headers['forwarded-for'])) { return req.headers['forwarded-for']; } if (is.ip(req.headers.forwarded)) { return req.headers.forwarded; } } // Remote address checks. if (is.existy(req.connection)) { if (is.ip(req.connection.remoteAddress)) { return req.connection.remoteAddress; } if (is.existy(req.connection.socket) && is.ip(req.connection.socket.remoteAddress)) { return req.connection.socket.remoteAddress; } } if (is.existy(req.socket) && is.ip(req.socket.remoteAddress)) { return req.socket.remoteAddress; } if (is.existy(req.info) && is.ip(req.info.remoteAddress)) { return req.info.remoteAddress; } // AWS Api Gateway + Lambda if (is.existy(req.requestContext) && is.existy(req.requestContext.identity) && is.ip(req.requestContext.identity.sourceIp)) { return req.requestContext.identity.sourceIp; } return null; }
javascript
function getClientIp(req) { // Server is probably behind a proxy. if (req.headers) { // Standard headers used by Amazon EC2, Heroku, and others. if (is.ip(req.headers['x-client-ip'])) { return req.headers['x-client-ip']; } // Load-balancers (AWS ELB) or proxies. const xForwardedFor = getClientIpFromXForwardedFor(req.headers['x-forwarded-for']); if (is.ip(xForwardedFor)) { return xForwardedFor; } // Cloudflare. // @see https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers- // CF-Connecting-IP - applied to every request to the origin. if (is.ip(req.headers['cf-connecting-ip'])) { return req.headers['cf-connecting-ip']; } // Fastly and Firebase hosting header (When forwared to cloud function) if (is.ip(req.headers['fastly-client-ip'])) { return req.headers['fastly-client-ip']; } // Akamai and Cloudflare: True-Client-IP. if (is.ip(req.headers['true-client-ip'])) { return req.headers['true-client-ip']; } // Default nginx proxy/fcgi; alternative to x-forwarded-for, used by some proxies. if (is.ip(req.headers['x-real-ip'])) { return req.headers['x-real-ip']; } // (Rackspace LB and Riverbed's Stingray) // http://www.rackspace.com/knowledge_center/article/controlling-access-to-linux-cloud-sites-based-on-the-client-ip-address // https://splash.riverbed.com/docs/DOC-1926 if (is.ip(req.headers['x-cluster-client-ip'])) { return req.headers['x-cluster-client-ip']; } if (is.ip(req.headers['x-forwarded'])) { return req.headers['x-forwarded']; } if (is.ip(req.headers['forwarded-for'])) { return req.headers['forwarded-for']; } if (is.ip(req.headers.forwarded)) { return req.headers.forwarded; } } // Remote address checks. if (is.existy(req.connection)) { if (is.ip(req.connection.remoteAddress)) { return req.connection.remoteAddress; } if (is.existy(req.connection.socket) && is.ip(req.connection.socket.remoteAddress)) { return req.connection.socket.remoteAddress; } } if (is.existy(req.socket) && is.ip(req.socket.remoteAddress)) { return req.socket.remoteAddress; } if (is.existy(req.info) && is.ip(req.info.remoteAddress)) { return req.info.remoteAddress; } // AWS Api Gateway + Lambda if (is.existy(req.requestContext) && is.existy(req.requestContext.identity) && is.ip(req.requestContext.identity.sourceIp)) { return req.requestContext.identity.sourceIp; } return null; }
[ "function", "getClientIp", "(", "req", ")", "{", "// Server is probably behind a proxy.", "if", "(", "req", ".", "headers", ")", "{", "// Standard headers used by Amazon EC2, Heroku, and others.", "if", "(", "is", ".", "ip", "(", "req", ".", "headers", "[", "'x-client-ip'", "]", ")", ")", "{", "return", "req", ".", "headers", "[", "'x-client-ip'", "]", ";", "}", "// Load-balancers (AWS ELB) or proxies.", "const", "xForwardedFor", "=", "getClientIpFromXForwardedFor", "(", "req", ".", "headers", "[", "'x-forwarded-for'", "]", ")", ";", "if", "(", "is", ".", "ip", "(", "xForwardedFor", ")", ")", "{", "return", "xForwardedFor", ";", "}", "// Cloudflare.", "// @see https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers-", "// CF-Connecting-IP - applied to every request to the origin.", "if", "(", "is", ".", "ip", "(", "req", ".", "headers", "[", "'cf-connecting-ip'", "]", ")", ")", "{", "return", "req", ".", "headers", "[", "'cf-connecting-ip'", "]", ";", "}", "// Fastly and Firebase hosting header (When forwared to cloud function)", "if", "(", "is", ".", "ip", "(", "req", ".", "headers", "[", "'fastly-client-ip'", "]", ")", ")", "{", "return", "req", ".", "headers", "[", "'fastly-client-ip'", "]", ";", "}", "// Akamai and Cloudflare: True-Client-IP.", "if", "(", "is", ".", "ip", "(", "req", ".", "headers", "[", "'true-client-ip'", "]", ")", ")", "{", "return", "req", ".", "headers", "[", "'true-client-ip'", "]", ";", "}", "// Default nginx proxy/fcgi; alternative to x-forwarded-for, used by some proxies.", "if", "(", "is", ".", "ip", "(", "req", ".", "headers", "[", "'x-real-ip'", "]", ")", ")", "{", "return", "req", ".", "headers", "[", "'x-real-ip'", "]", ";", "}", "// (Rackspace LB and Riverbed's Stingray)", "// http://www.rackspace.com/knowledge_center/article/controlling-access-to-linux-cloud-sites-based-on-the-client-ip-address", "// https://splash.riverbed.com/docs/DOC-1926", "if", "(", "is", ".", "ip", "(", "req", ".", "headers", "[", "'x-cluster-client-ip'", "]", ")", ")", "{", "return", "req", ".", "headers", "[", "'x-cluster-client-ip'", "]", ";", "}", "if", "(", "is", ".", "ip", "(", "req", ".", "headers", "[", "'x-forwarded'", "]", ")", ")", "{", "return", "req", ".", "headers", "[", "'x-forwarded'", "]", ";", "}", "if", "(", "is", ".", "ip", "(", "req", ".", "headers", "[", "'forwarded-for'", "]", ")", ")", "{", "return", "req", ".", "headers", "[", "'forwarded-for'", "]", ";", "}", "if", "(", "is", ".", "ip", "(", "req", ".", "headers", ".", "forwarded", ")", ")", "{", "return", "req", ".", "headers", ".", "forwarded", ";", "}", "}", "// Remote address checks.", "if", "(", "is", ".", "existy", "(", "req", ".", "connection", ")", ")", "{", "if", "(", "is", ".", "ip", "(", "req", ".", "connection", ".", "remoteAddress", ")", ")", "{", "return", "req", ".", "connection", ".", "remoteAddress", ";", "}", "if", "(", "is", ".", "existy", "(", "req", ".", "connection", ".", "socket", ")", "&&", "is", ".", "ip", "(", "req", ".", "connection", ".", "socket", ".", "remoteAddress", ")", ")", "{", "return", "req", ".", "connection", ".", "socket", ".", "remoteAddress", ";", "}", "}", "if", "(", "is", ".", "existy", "(", "req", ".", "socket", ")", "&&", "is", ".", "ip", "(", "req", ".", "socket", ".", "remoteAddress", ")", ")", "{", "return", "req", ".", "socket", ".", "remoteAddress", ";", "}", "if", "(", "is", ".", "existy", "(", "req", ".", "info", ")", "&&", "is", ".", "ip", "(", "req", ".", "info", ".", "remoteAddress", ")", ")", "{", "return", "req", ".", "info", ".", "remoteAddress", ";", "}", "// AWS Api Gateway + Lambda", "if", "(", "is", ".", "existy", "(", "req", ".", "requestContext", ")", "&&", "is", ".", "existy", "(", "req", ".", "requestContext", ".", "identity", ")", "&&", "is", ".", "ip", "(", "req", ".", "requestContext", ".", "identity", ".", "sourceIp", ")", ")", "{", "return", "req", ".", "requestContext", ".", "identity", ".", "sourceIp", ";", "}", "return", "null", ";", "}" ]
Determine client IP address. @param req @returns {string} ip - The IP address if known, defaulting to empty string if unknown.
[ "Determine", "client", "IP", "address", "." ]
915d984b46d262e4418a889abc7601c38d47f049
https://github.com/pbojinov/request-ip/blob/915d984b46d262e4418a889abc7601c38d47f049/src/index.js#L48-L130
17,567
pbojinov/request-ip
src/index.js
mw
function mw(options) { // Defaults. const configuration = is.not.existy(options) ? {} : options; // Validation. if (is.not.object(configuration)) { throw new TypeError('Options must be an object!'); } const attributeName = configuration.attributeName || 'clientIp'; return (req, res, next) => { const ip = getClientIp(req); Object.defineProperty(req, attributeName, { get: () => ip, configurable: true }); next(); }; }
javascript
function mw(options) { // Defaults. const configuration = is.not.existy(options) ? {} : options; // Validation. if (is.not.object(configuration)) { throw new TypeError('Options must be an object!'); } const attributeName = configuration.attributeName || 'clientIp'; return (req, res, next) => { const ip = getClientIp(req); Object.defineProperty(req, attributeName, { get: () => ip, configurable: true }); next(); }; }
[ "function", "mw", "(", "options", ")", "{", "// Defaults.", "const", "configuration", "=", "is", ".", "not", ".", "existy", "(", "options", ")", "?", "{", "}", ":", "options", ";", "// Validation.", "if", "(", "is", ".", "not", ".", "object", "(", "configuration", ")", ")", "{", "throw", "new", "TypeError", "(", "'Options must be an object!'", ")", ";", "}", "const", "attributeName", "=", "configuration", ".", "attributeName", "||", "'clientIp'", ";", "return", "(", "req", ",", "res", ",", "next", ")", "=>", "{", "const", "ip", "=", "getClientIp", "(", "req", ")", ";", "Object", ".", "defineProperty", "(", "req", ",", "attributeName", ",", "{", "get", ":", "(", ")", "=>", "ip", ",", "configurable", ":", "true", "}", ")", ";", "next", "(", ")", ";", "}", ";", "}" ]
Expose request IP as a middleware. @param {object} [options] - Configuration. @param {string} [options.attributeName] - Name of attribute to augment request object with. @return {*}
[ "Expose", "request", "IP", "as", "a", "middleware", "." ]
915d984b46d262e4418a889abc7601c38d47f049
https://github.com/pbojinov/request-ip/blob/915d984b46d262e4418a889abc7601c38d47f049/src/index.js#L139-L157
17,568
anandthakker/doiuse
src/missing-support.js
missingSupport
function missingSupport (browserRequest, from) { const browsers = new BrowserSelection(browserRequest, from) let result = {} Object.keys(features).forEach(function (feature) { const featureData = caniuse.feature(caniuse.features[feature]) const lackData = filterStats(browsers, featureData.stats) const missingData = lackData.missing const partialData = lackData.partial // browsers with missing or partial support for this feature const missing = lackingBrowsers(missingData) const partial = lackingBrowsers(partialData) if (missing.length > 0 || partial.length > 0) { result[feature] = { title: featureData.title, caniuseData: featureData } if (missing.length > 0) { result[feature].missingData = missingData result[feature].missing = missing } if (partial.length > 0) { result[feature].partialData = partialData result[feature].partial = partial } } }) return { browsers: browsers.list(), features: result } }
javascript
function missingSupport (browserRequest, from) { const browsers = new BrowserSelection(browserRequest, from) let result = {} Object.keys(features).forEach(function (feature) { const featureData = caniuse.feature(caniuse.features[feature]) const lackData = filterStats(browsers, featureData.stats) const missingData = lackData.missing const partialData = lackData.partial // browsers with missing or partial support for this feature const missing = lackingBrowsers(missingData) const partial = lackingBrowsers(partialData) if (missing.length > 0 || partial.length > 0) { result[feature] = { title: featureData.title, caniuseData: featureData } if (missing.length > 0) { result[feature].missingData = missingData result[feature].missing = missing } if (partial.length > 0) { result[feature].partialData = partialData result[feature].partial = partial } } }) return { browsers: browsers.list(), features: result } }
[ "function", "missingSupport", "(", "browserRequest", ",", "from", ")", "{", "const", "browsers", "=", "new", "BrowserSelection", "(", "browserRequest", ",", "from", ")", "let", "result", "=", "{", "}", "Object", ".", "keys", "(", "features", ")", ".", "forEach", "(", "function", "(", "feature", ")", "{", "const", "featureData", "=", "caniuse", ".", "feature", "(", "caniuse", ".", "features", "[", "feature", "]", ")", "const", "lackData", "=", "filterStats", "(", "browsers", ",", "featureData", ".", "stats", ")", "const", "missingData", "=", "lackData", ".", "missing", "const", "partialData", "=", "lackData", ".", "partial", "// browsers with missing or partial support for this feature", "const", "missing", "=", "lackingBrowsers", "(", "missingData", ")", "const", "partial", "=", "lackingBrowsers", "(", "partialData", ")", "if", "(", "missing", ".", "length", ">", "0", "||", "partial", ".", "length", ">", "0", ")", "{", "result", "[", "feature", "]", "=", "{", "title", ":", "featureData", ".", "title", ",", "caniuseData", ":", "featureData", "}", "if", "(", "missing", ".", "length", ">", "0", ")", "{", "result", "[", "feature", "]", ".", "missingData", "=", "missingData", "result", "[", "feature", "]", ".", "missing", "=", "missing", "}", "if", "(", "partial", ".", "length", ">", "0", ")", "{", "result", "[", "feature", "]", ".", "partialData", "=", "partialData", "result", "[", "feature", "]", ".", "partial", "=", "partial", "}", "}", "}", ")", "return", "{", "browsers", ":", "browsers", ".", "list", "(", ")", ",", "features", ":", "result", "}", "}" ]
Get data on CSS features not supported by the given autoprefixer-like browser selection. @returns `{browsers, features}`, where `features` is an array of: ``` { 'feature-name': { title: 'Title of feature' missing: "IE (8), Chrome (31)" missingData: { // map of browser -> version -> (lack of)support code ie: { '8': 'n' }, chrome: { '31': 'n' } } partialData: { // map of browser -> version -> (partial)support code ie: { '7': 'a' }, ff: { '29': 'a #1' } } caniuseData: { // caniuse-db json data for this feature } }, 'feature-name-2': {} // etc. } ``` `feature-name` is a caniuse-db slug.
[ "Get", "data", "on", "CSS", "features", "not", "supported", "by", "the", "given", "autoprefixer", "-", "like", "browser", "selection", "." ]
7525e72dbc86914600e96710c1a5c34b8cb3f8ac
https://github.com/anandthakker/doiuse/blob/7525e72dbc86914600e96710c1a5c34b8cb3f8ac/src/missing-support.js#L76-L109
17,569
joewalnes/filtrex
filtrex.js
removeErrorRecovery
function removeErrorRecovery (fn) { var parseFn = String(fn); try { var JSONSelect = require("JSONSelect"); var Reflect = require("reflect"); var ast = Reflect.parse(parseFn); var labeled = JSONSelect.match(':has(:root > .label > .name:val("_handle_error"))', ast); labeled[0].body.consequent.body = [labeled[0].body.consequent.body[0], labeled[0].body.consequent.body[1]]; return Reflect.stringify(ast).replace(/_handle_error:\s?/,"").replace(/\\\\n/g,"\\n"); } catch (e) { return parseFn; } }
javascript
function removeErrorRecovery (fn) { var parseFn = String(fn); try { var JSONSelect = require("JSONSelect"); var Reflect = require("reflect"); var ast = Reflect.parse(parseFn); var labeled = JSONSelect.match(':has(:root > .label > .name:val("_handle_error"))', ast); labeled[0].body.consequent.body = [labeled[0].body.consequent.body[0], labeled[0].body.consequent.body[1]]; return Reflect.stringify(ast).replace(/_handle_error:\s?/,"").replace(/\\\\n/g,"\\n"); } catch (e) { return parseFn; } }
[ "function", "removeErrorRecovery", "(", "fn", ")", "{", "var", "parseFn", "=", "String", "(", "fn", ")", ";", "try", "{", "var", "JSONSelect", "=", "require", "(", "\"JSONSelect\"", ")", ";", "var", "Reflect", "=", "require", "(", "\"reflect\"", ")", ";", "var", "ast", "=", "Reflect", ".", "parse", "(", "parseFn", ")", ";", "var", "labeled", "=", "JSONSelect", ".", "match", "(", "':has(:root > .label > .name:val(\"_handle_error\"))'", ",", "ast", ")", ";", "labeled", "[", "0", "]", ".", "body", ".", "consequent", ".", "body", "=", "[", "labeled", "[", "0", "]", ".", "body", ".", "consequent", ".", "body", "[", "0", "]", ",", "labeled", "[", "0", "]", ".", "body", ".", "consequent", ".", "body", "[", "1", "]", "]", ";", "return", "Reflect", ".", "stringify", "(", "ast", ")", ".", "replace", "(", "/", "_handle_error:\\s?", "/", ",", "\"\"", ")", ".", "replace", "(", "/", "\\\\\\\\n", "/", "g", ",", "\"\\\\n\"", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "parseFn", ";", "}", "}" ]
returns parse function without error recovery code
[ "returns", "parse", "function", "without", "error", "recovery", "code" ]
685f5796211353623269de02b43bb6bc68e556a0
https://github.com/joewalnes/filtrex/blob/685f5796211353623269de02b43bb6bc68e556a0/filtrex.js#L1178-L1192
17,570
joewalnes/filtrex
filtrex.js
layerMethod
function layerMethod(k, fun) { var pos = k.match(position)[0], key = k.replace(position, ''), prop = this[key]; if (pos === 'after') { this[key] = function () { var ret = prop.apply(this, arguments); var args = [].slice.call(arguments); args.splice(0, 0, ret); fun.apply(this, args); return ret; }; } else if (pos === 'before') { this[key] = function () { fun.apply(this, arguments); var ret = prop.apply(this, arguments); return ret; }; } }
javascript
function layerMethod(k, fun) { var pos = k.match(position)[0], key = k.replace(position, ''), prop = this[key]; if (pos === 'after') { this[key] = function () { var ret = prop.apply(this, arguments); var args = [].slice.call(arguments); args.splice(0, 0, ret); fun.apply(this, args); return ret; }; } else if (pos === 'before') { this[key] = function () { fun.apply(this, arguments); var ret = prop.apply(this, arguments); return ret; }; } }
[ "function", "layerMethod", "(", "k", ",", "fun", ")", "{", "var", "pos", "=", "k", ".", "match", "(", "position", ")", "[", "0", "]", ",", "key", "=", "k", ".", "replace", "(", "position", ",", "''", ")", ",", "prop", "=", "this", "[", "key", "]", ";", "if", "(", "pos", "===", "'after'", ")", "{", "this", "[", "key", "]", "=", "function", "(", ")", "{", "var", "ret", "=", "prop", ".", "apply", "(", "this", ",", "arguments", ")", ";", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ";", "args", ".", "splice", "(", "0", ",", "0", ",", "ret", ")", ";", "fun", ".", "apply", "(", "this", ",", "args", ")", ";", "return", "ret", ";", "}", ";", "}", "else", "if", "(", "pos", "===", "'before'", ")", "{", "this", "[", "key", "]", "=", "function", "(", ")", "{", "fun", ".", "apply", "(", "this", ",", "arguments", ")", ";", "var", "ret", "=", "prop", ".", "apply", "(", "this", ",", "arguments", ")", ";", "return", "ret", ";", "}", ";", "}", "}" ]
basic method layering always returns original method's return value
[ "basic", "method", "layering", "always", "returns", "original", "method", "s", "return", "value" ]
685f5796211353623269de02b43bb6bc68e556a0
https://github.com/joewalnes/filtrex/blob/685f5796211353623269de02b43bb6bc68e556a0/filtrex.js#L2392-L2412
17,571
joewalnes/filtrex
filtrex.js
typal_construct
function typal_construct() { var o = typal_mix.apply(create(this), arguments); var constructor = o.constructor; var Klass = o.constructor = function () { return constructor.apply(this, arguments); }; Klass.prototype = o; Klass.mix = typal_mix; // allow for easy singleton property extension return Klass; }
javascript
function typal_construct() { var o = typal_mix.apply(create(this), arguments); var constructor = o.constructor; var Klass = o.constructor = function () { return constructor.apply(this, arguments); }; Klass.prototype = o; Klass.mix = typal_mix; // allow for easy singleton property extension return Klass; }
[ "function", "typal_construct", "(", ")", "{", "var", "o", "=", "typal_mix", ".", "apply", "(", "create", "(", "this", ")", ",", "arguments", ")", ";", "var", "constructor", "=", "o", ".", "constructor", ";", "var", "Klass", "=", "o", ".", "constructor", "=", "function", "(", ")", "{", "return", "constructor", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "Klass", ".", "prototype", "=", "o", ";", "Klass", ".", "mix", "=", "typal_mix", ";", "// allow for easy singleton property extension", "return", "Klass", ";", "}" ]
Creates a new Class function based on an object with a constructor method
[ "Creates", "a", "new", "Class", "function", "based", "on", "an", "object", "with", "a", "constructor", "method" ]
685f5796211353623269de02b43bb6bc68e556a0
https://github.com/joewalnes/filtrex/blob/685f5796211353623269de02b43bb6bc68e556a0/filtrex.js#L2450-L2457
17,572
joewalnes/filtrex
example/highlight.js
buildTable
function buildTable(tbody, data) { tbody.empty(); data.forEach(function(item) { var row = $('<tr>').appendTo(tbody); $('<td>').appendTo(row).text(item.price); $('<td>').appendTo(row).text(item.weight); $('<td>').appendTo(row).text(item.taste); // Associate underlying data with row node so we can access it later // for filtering. row.data('item', item); }); }
javascript
function buildTable(tbody, data) { tbody.empty(); data.forEach(function(item) { var row = $('<tr>').appendTo(tbody); $('<td>').appendTo(row).text(item.price); $('<td>').appendTo(row).text(item.weight); $('<td>').appendTo(row).text(item.taste); // Associate underlying data with row node so we can access it later // for filtering. row.data('item', item); }); }
[ "function", "buildTable", "(", "tbody", ",", "data", ")", "{", "tbody", ".", "empty", "(", ")", ";", "data", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "row", "=", "$", "(", "'<tr>'", ")", ".", "appendTo", "(", "tbody", ")", ";", "$", "(", "'<td>'", ")", ".", "appendTo", "(", "row", ")", ".", "text", "(", "item", ".", "price", ")", ";", "$", "(", "'<td>'", ")", ".", "appendTo", "(", "row", ")", ".", "text", "(", "item", ".", "weight", ")", ";", "$", "(", "'<td>'", ")", ".", "appendTo", "(", "row", ")", ".", "text", "(", "item", ".", "taste", ")", ";", "// Associate underlying data with row node so we can access it later", "// for filtering.", "row", ".", "data", "(", "'item'", ",", "item", ")", ";", "}", ")", ";", "}" ]
Build table on page with items.
[ "Build", "table", "on", "page", "with", "items", "." ]
685f5796211353623269de02b43bb6bc68e556a0
https://github.com/joewalnes/filtrex/blob/685f5796211353623269de02b43bb6bc68e556a0/example/highlight.js#L27-L39
17,573
joewalnes/filtrex
example/highlight.js
updateExpression
function updateExpression() { // Default highlighter will not highlight anything var nullHighlighter = function(item) { return false; } var input = $('.expression'); var expression = input.val(); var highlighter; if (!expression) { // No expression specified. Don't highlight anything. highlighter = nullHighlighter; input.css('background-color', '#fff'); } else { try { // Build highlighter from user's expression highlighter = compileExpression(expression); // <-- Filtrex! input.css('background-color', '#dfd'); } catch (e) { // Failed to parse expression. Don't highlight anything. highlighter = nullHighlighter; input.css('background-color', '#fdd'); } } highlightRows(highlighter); }
javascript
function updateExpression() { // Default highlighter will not highlight anything var nullHighlighter = function(item) { return false; } var input = $('.expression'); var expression = input.val(); var highlighter; if (!expression) { // No expression specified. Don't highlight anything. highlighter = nullHighlighter; input.css('background-color', '#fff'); } else { try { // Build highlighter from user's expression highlighter = compileExpression(expression); // <-- Filtrex! input.css('background-color', '#dfd'); } catch (e) { // Failed to parse expression. Don't highlight anything. highlighter = nullHighlighter; input.css('background-color', '#fdd'); } } highlightRows(highlighter); }
[ "function", "updateExpression", "(", ")", "{", "// Default highlighter will not highlight anything", "var", "nullHighlighter", "=", "function", "(", "item", ")", "{", "return", "false", ";", "}", "var", "input", "=", "$", "(", "'.expression'", ")", ";", "var", "expression", "=", "input", ".", "val", "(", ")", ";", "var", "highlighter", ";", "if", "(", "!", "expression", ")", "{", "// No expression specified. Don't highlight anything.", "highlighter", "=", "nullHighlighter", ";", "input", ".", "css", "(", "'background-color'", ",", "'#fff'", ")", ";", "}", "else", "{", "try", "{", "// Build highlighter from user's expression", "highlighter", "=", "compileExpression", "(", "expression", ")", ";", "// <-- Filtrex!", "input", ".", "css", "(", "'background-color'", ",", "'#dfd'", ")", ";", "}", "catch", "(", "e", ")", "{", "// Failed to parse expression. Don't highlight anything.", "highlighter", "=", "nullHighlighter", ";", "input", ".", "css", "(", "'background-color'", ",", "'#fdd'", ")", ";", "}", "}", "highlightRows", "(", "highlighter", ")", ";", "}" ]
When user entered expression changes, attempt to parse it and apply highlights to rows that match filter.
[ "When", "user", "entered", "expression", "changes", "attempt", "to", "parse", "it", "and", "apply", "highlights", "to", "rows", "that", "match", "filter", "." ]
685f5796211353623269de02b43bb6bc68e556a0
https://github.com/joewalnes/filtrex/blob/685f5796211353623269de02b43bb6bc68e556a0/example/highlight.js#L45-L71
17,574
kristerkari/stylelint-scss
src/utils/sassValueParser/index.js
isInsideFunctionCall
function isInsideFunctionCall(string, index) { const result = { is: false, fn: null }; const before = string.substring(0, index).trim(); const after = string.substring(index + 1).trim(); const beforeMatch = before.match(/([a-zA-Z_-][a-zA-Z0-9_-]*)\([^(){},]+$/); if (beforeMatch && beforeMatch[0] && after.search(/^[^(,]+\)/) !== -1) { result.is = true; result.fn = beforeMatch[1]; } return result; }
javascript
function isInsideFunctionCall(string, index) { const result = { is: false, fn: null }; const before = string.substring(0, index).trim(); const after = string.substring(index + 1).trim(); const beforeMatch = before.match(/([a-zA-Z_-][a-zA-Z0-9_-]*)\([^(){},]+$/); if (beforeMatch && beforeMatch[0] && after.search(/^[^(,]+\)/) !== -1) { result.is = true; result.fn = beforeMatch[1]; } return result; }
[ "function", "isInsideFunctionCall", "(", "string", ",", "index", ")", "{", "const", "result", "=", "{", "is", ":", "false", ",", "fn", ":", "null", "}", ";", "const", "before", "=", "string", ".", "substring", "(", "0", ",", "index", ")", ".", "trim", "(", ")", ";", "const", "after", "=", "string", ".", "substring", "(", "index", "+", "1", ")", ".", "trim", "(", ")", ";", "const", "beforeMatch", "=", "before", ".", "match", "(", "/", "([a-zA-Z_-][a-zA-Z0-9_-]*)\\([^(){},]+$", "/", ")", ";", "if", "(", "beforeMatch", "&&", "beforeMatch", "[", "0", "]", "&&", "after", ".", "search", "(", "/", "^[^(,]+\\)", "/", ")", "!==", "-", "1", ")", "{", "result", ".", "is", "=", "true", ";", "result", ".", "fn", "=", "beforeMatch", "[", "1", "]", ";", "}", "return", "result", ";", "}" ]
Checks if the character is inside a function agruments @param {String} string - the input string @param {Number} index - current character index @return {Object} return {Boolean} return.is - if inside a function arguments {String} return.fn - function name
[ "Checks", "if", "the", "character", "is", "inside", "a", "function", "agruments" ]
c8a0f2ff85a588424b02a154be3811b16029ecc0
https://github.com/kristerkari/stylelint-scss/blob/c8a0f2ff85a588424b02a154be3811b16029ecc0/src/utils/sassValueParser/index.js#L690-L702
17,575
kristerkari/stylelint-scss
src/utils/sassValueParser/index.js
isStringBefore
function isStringBefore(before) { const result = { is: false, opsBetween: false }; const stringOpsClipped = before.replace(/(\s*[+/*%]|\s+-)+$/, ""); if (stringOpsClipped !== before) { result.opsBetween = true; } // If it is quoted if ( stringOpsClipped[stringOpsClipped.length - 1] === '"' || stringOpsClipped[stringOpsClipped.length - 1] === "'" ) { result.is = true; } else if ( stringOpsClipped.search( /(?:^|[/(){},: ])([a-zA-Z_][a-zA-Z_0-9-]*|-+[a-zA-Z_]+[a-zA-Z_0-9-]*)$/ ) !== -1 ) { // First pattern: a1, a1a, a-1, result.is = true; } return result; }
javascript
function isStringBefore(before) { const result = { is: false, opsBetween: false }; const stringOpsClipped = before.replace(/(\s*[+/*%]|\s+-)+$/, ""); if (stringOpsClipped !== before) { result.opsBetween = true; } // If it is quoted if ( stringOpsClipped[stringOpsClipped.length - 1] === '"' || stringOpsClipped[stringOpsClipped.length - 1] === "'" ) { result.is = true; } else if ( stringOpsClipped.search( /(?:^|[/(){},: ])([a-zA-Z_][a-zA-Z_0-9-]*|-+[a-zA-Z_]+[a-zA-Z_0-9-]*)$/ ) !== -1 ) { // First pattern: a1, a1a, a-1, result.is = true; } return result; }
[ "function", "isStringBefore", "(", "before", ")", "{", "const", "result", "=", "{", "is", ":", "false", ",", "opsBetween", ":", "false", "}", ";", "const", "stringOpsClipped", "=", "before", ".", "replace", "(", "/", "(\\s*[+/*%]|\\s+-)+$", "/", ",", "\"\"", ")", ";", "if", "(", "stringOpsClipped", "!==", "before", ")", "{", "result", ".", "opsBetween", "=", "true", ";", "}", "// If it is quoted", "if", "(", "stringOpsClipped", "[", "stringOpsClipped", ".", "length", "-", "1", "]", "===", "'\"'", "||", "stringOpsClipped", "[", "stringOpsClipped", ".", "length", "-", "1", "]", "===", "\"'\"", ")", "{", "result", ".", "is", "=", "true", ";", "}", "else", "if", "(", "stringOpsClipped", ".", "search", "(", "/", "(?:^|[/(){},: ])([a-zA-Z_][a-zA-Z_0-9-]*|-+[a-zA-Z_]+[a-zA-Z_0-9-]*)$", "/", ")", "!==", "-", "1", ")", "{", "// First pattern: a1, a1a, a-1,", "result", ".", "is", "=", "true", ";", "}", "return", "result", ";", "}" ]
Checks if there is a string before the character. Also checks if there is a math operator in between @param {String} before - the input string that preceses the character @return {Object} return {Boolean} return.is - if there is a string {String} return.opsBetween - if there are operators in between
[ "Checks", "if", "there", "is", "a", "string", "before", "the", "character", ".", "Also", "checks", "if", "there", "is", "a", "math", "operator", "in", "between" ]
c8a0f2ff85a588424b02a154be3811b16029ecc0
https://github.com/kristerkari/stylelint-scss/blob/c8a0f2ff85a588424b02a154be3811b16029ecc0/src/utils/sassValueParser/index.js#L713-L737
17,576
kristerkari/stylelint-scss
src/utils/sassValueParser/index.js
isInterpolationBefore
function isInterpolationBefore(before) { const result = { is: false, opsBetween: false }; // Removing preceding operators if any const beforeOpsClipped = before.replace(/(\s*[+/*%-])+$/, ""); if (beforeOpsClipped !== before) { result.opsBetween = true; } if (beforeOpsClipped[beforeOpsClipped.length - 1] === "}") { result.is = true; } return result; }
javascript
function isInterpolationBefore(before) { const result = { is: false, opsBetween: false }; // Removing preceding operators if any const beforeOpsClipped = before.replace(/(\s*[+/*%-])+$/, ""); if (beforeOpsClipped !== before) { result.opsBetween = true; } if (beforeOpsClipped[beforeOpsClipped.length - 1] === "}") { result.is = true; } return result; }
[ "function", "isInterpolationBefore", "(", "before", ")", "{", "const", "result", "=", "{", "is", ":", "false", ",", "opsBetween", ":", "false", "}", ";", "// Removing preceding operators if any", "const", "beforeOpsClipped", "=", "before", ".", "replace", "(", "/", "(\\s*[+/*%-])+$", "/", ",", "\"\"", ")", ";", "if", "(", "beforeOpsClipped", "!==", "before", ")", "{", "result", ".", "opsBetween", "=", "true", ";", "}", "if", "(", "beforeOpsClipped", "[", "beforeOpsClipped", ".", "length", "-", "1", "]", "===", "\"}\"", ")", "{", "result", ".", "is", "=", "true", ";", "}", "return", "result", ";", "}" ]
Checks if there is an interpolation before the character. Also checks if there is a math operator in between @param {String} before - the input string that preceses the character @return {Object} return {Boolean} return.is - if there is an interpolation {String} return.opsBetween - if there are operators in between
[ "Checks", "if", "there", "is", "an", "interpolation", "before", "the", "character", ".", "Also", "checks", "if", "there", "is", "a", "math", "operator", "in", "between" ]
c8a0f2ff85a588424b02a154be3811b16029ecc0
https://github.com/kristerkari/stylelint-scss/blob/c8a0f2ff85a588424b02a154be3811b16029ecc0/src/utils/sassValueParser/index.js#L803-L817
17,577
elpheria/rpc-websockets
dist/lib/utils.js
createError
function createError(code, details) { var error = { code: code, message: errors.get(code) || "Internal Server Error" }; if (details) error["data"] = details; return error; }
javascript
function createError(code, details) { var error = { code: code, message: errors.get(code) || "Internal Server Error" }; if (details) error["data"] = details; return error; }
[ "function", "createError", "(", "code", ",", "details", ")", "{", "var", "error", "=", "{", "code", ":", "code", ",", "message", ":", "errors", ".", "get", "(", "code", ")", "||", "\"Internal Server Error\"", "}", ";", "if", "(", "details", ")", "error", "[", "\"data\"", "]", "=", "details", ";", "return", "error", ";", "}" ]
Creates a JSON-RPC 2.0-compliant error. @param {Number} code - error code @param {String} details - error details @return {Object}
[ "Creates", "a", "JSON", "-", "RPC", "2", ".", "0", "-", "compliant", "error", "." ]
b9430f04593d42161dd19b8ca7e01f877587497f
https://github.com/elpheria/rpc-websockets/blob/b9430f04593d42161dd19b8ca7e01f877587497f/dist/lib/utils.js#L22-L31
17,578
filerjs/filer
src/filesystem/implementation.js
create_node_in_parent
function create_node_in_parent(error, parentDirectoryNode) { if(error) { callback(error); } else if(parentDirectoryNode.type !== NODE_TYPE_DIRECTORY) { callback(new Errors.ENOTDIR('a component of the path prefix is not a directory', path)); } else { parentNode = parentDirectoryNode; find_node(context, path, check_if_node_exists); } }
javascript
function create_node_in_parent(error, parentDirectoryNode) { if(error) { callback(error); } else if(parentDirectoryNode.type !== NODE_TYPE_DIRECTORY) { callback(new Errors.ENOTDIR('a component of the path prefix is not a directory', path)); } else { parentNode = parentDirectoryNode; find_node(context, path, check_if_node_exists); } }
[ "function", "create_node_in_parent", "(", "error", ",", "parentDirectoryNode", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "}", "else", "if", "(", "parentDirectoryNode", ".", "type", "!==", "NODE_TYPE_DIRECTORY", ")", "{", "callback", "(", "new", "Errors", ".", "ENOTDIR", "(", "'a component of the path prefix is not a directory'", ",", "path", ")", ")", ";", "}", "else", "{", "parentNode", "=", "parentDirectoryNode", ";", "find_node", "(", "context", ",", "path", ",", "check_if_node_exists", ")", ";", "}", "}" ]
Check if the parent node exists
[ "Check", "if", "the", "parent", "node", "exists" ]
4aae53839a8da2ca5da9f4e92c33eaab50094352
https://github.com/filerjs/filer/blob/4aae53839a8da2ca5da9f4e92c33eaab50094352/src/filesystem/implementation.js#L106-L115
17,579
filerjs/filer
src/filesystem/implementation.js
check_if_node_exists
function check_if_node_exists(error, result) { if(!error && result) { callback(new Errors.EEXIST('path name already exists', path)); } else if(error && !(error instanceof Errors.ENOENT)) { callback(error); } else { context.getObject(parentNode.data, create_node); } }
javascript
function check_if_node_exists(error, result) { if(!error && result) { callback(new Errors.EEXIST('path name already exists', path)); } else if(error && !(error instanceof Errors.ENOENT)) { callback(error); } else { context.getObject(parentNode.data, create_node); } }
[ "function", "check_if_node_exists", "(", "error", ",", "result", ")", "{", "if", "(", "!", "error", "&&", "result", ")", "{", "callback", "(", "new", "Errors", ".", "EEXIST", "(", "'path name already exists'", ",", "path", ")", ")", ";", "}", "else", "if", "(", "error", "&&", "!", "(", "error", "instanceof", "Errors", ".", "ENOENT", ")", ")", "{", "callback", "(", "error", ")", ";", "}", "else", "{", "context", ".", "getObject", "(", "parentNode", ".", "data", ",", "create_node", ")", ";", "}", "}" ]
Check if the node to be created already exists
[ "Check", "if", "the", "node", "to", "be", "created", "already", "exists" ]
4aae53839a8da2ca5da9f4e92c33eaab50094352
https://github.com/filerjs/filer/blob/4aae53839a8da2ca5da9f4e92c33eaab50094352/src/filesystem/implementation.js#L118-L126
17,580
filerjs/filer
src/filesystem/implementation.js
create_node
function create_node(error, result) { if(error) { callback(error); } else { parentNodeData = result; Node.create({ guid: context.guid, type: type }, function(error, result) { if(error) { callback(error); return; } node = result; node.nlinks += 1; context.putObject(node.id, node, update_parent_node_data); }); } }
javascript
function create_node(error, result) { if(error) { callback(error); } else { parentNodeData = result; Node.create({ guid: context.guid, type: type }, function(error, result) { if(error) { callback(error); return; } node = result; node.nlinks += 1; context.putObject(node.id, node, update_parent_node_data); }); } }
[ "function", "create_node", "(", "error", ",", "result", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "}", "else", "{", "parentNodeData", "=", "result", ";", "Node", ".", "create", "(", "{", "guid", ":", "context", ".", "guid", ",", "type", ":", "type", "}", ",", "function", "(", "error", ",", "result", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "return", ";", "}", "node", "=", "result", ";", "node", ".", "nlinks", "+=", "1", ";", "context", ".", "putObject", "(", "node", ".", "id", ",", "node", ",", "update_parent_node_data", ")", ";", "}", ")", ";", "}", "}" ]
Create the new node
[ "Create", "the", "new", "node" ]
4aae53839a8da2ca5da9f4e92c33eaab50094352
https://github.com/filerjs/filer/blob/4aae53839a8da2ca5da9f4e92c33eaab50094352/src/filesystem/implementation.js#L129-L147
17,581
filerjs/filer
src/filesystem/implementation.js
update_parent_node_data
function update_parent_node_data(error) { if(error) { callback(error); } else { parentNodeData[name] = new DirectoryEntry(node.id, type); context.putObject(parentNode.data, parentNodeData, update_time); } }
javascript
function update_parent_node_data(error) { if(error) { callback(error); } else { parentNodeData[name] = new DirectoryEntry(node.id, type); context.putObject(parentNode.data, parentNodeData, update_time); } }
[ "function", "update_parent_node_data", "(", "error", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "}", "else", "{", "parentNodeData", "[", "name", "]", "=", "new", "DirectoryEntry", "(", "node", ".", "id", ",", "type", ")", ";", "context", ".", "putObject", "(", "parentNode", ".", "data", ",", "parentNodeData", ",", "update_time", ")", ";", "}", "}" ]
Update the parent nodes data
[ "Update", "the", "parent", "nodes", "data" ]
4aae53839a8da2ca5da9f4e92c33eaab50094352
https://github.com/filerjs/filer/blob/4aae53839a8da2ca5da9f4e92c33eaab50094352/src/filesystem/implementation.js#L160-L167
17,582
filerjs/filer
src/filesystem/implementation.js
ensure_root_directory
function ensure_root_directory(context, callback) { var superNode; var directoryNode; var directoryData; function ensure_super_node(error, existingNode) { if(!error && existingNode) { // Another instance has beat us and already created the super node. callback(); } else if(error && !(error instanceof Errors.ENOENT)) { callback(error); } else { SuperNode.create({guid: context.guid}, function(error, result) { if(error) { callback(error); return; } superNode = result; context.putObject(superNode.id, superNode, write_directory_node); }); } } function write_directory_node(error) { if(error) { callback(error); } else { Node.create({ guid: context.guid, id: superNode.rnode, type: NODE_TYPE_DIRECTORY }, function(error, result) { if(error) { callback(error); return; } directoryNode = result; directoryNode.nlinks += 1; context.putObject(directoryNode.id, directoryNode, write_directory_data); }); } } function write_directory_data(error) { if(error) { callback(error); } else { directoryData = {}; context.putObject(directoryNode.data, directoryData, callback); } } context.getObject(SUPER_NODE_ID, ensure_super_node); }
javascript
function ensure_root_directory(context, callback) { var superNode; var directoryNode; var directoryData; function ensure_super_node(error, existingNode) { if(!error && existingNode) { // Another instance has beat us and already created the super node. callback(); } else if(error && !(error instanceof Errors.ENOENT)) { callback(error); } else { SuperNode.create({guid: context.guid}, function(error, result) { if(error) { callback(error); return; } superNode = result; context.putObject(superNode.id, superNode, write_directory_node); }); } } function write_directory_node(error) { if(error) { callback(error); } else { Node.create({ guid: context.guid, id: superNode.rnode, type: NODE_TYPE_DIRECTORY }, function(error, result) { if(error) { callback(error); return; } directoryNode = result; directoryNode.nlinks += 1; context.putObject(directoryNode.id, directoryNode, write_directory_data); }); } } function write_directory_data(error) { if(error) { callback(error); } else { directoryData = {}; context.putObject(directoryNode.data, directoryData, callback); } } context.getObject(SUPER_NODE_ID, ensure_super_node); }
[ "function", "ensure_root_directory", "(", "context", ",", "callback", ")", "{", "var", "superNode", ";", "var", "directoryNode", ";", "var", "directoryData", ";", "function", "ensure_super_node", "(", "error", ",", "existingNode", ")", "{", "if", "(", "!", "error", "&&", "existingNode", ")", "{", "// Another instance has beat us and already created the super node.", "callback", "(", ")", ";", "}", "else", "if", "(", "error", "&&", "!", "(", "error", "instanceof", "Errors", ".", "ENOENT", ")", ")", "{", "callback", "(", "error", ")", ";", "}", "else", "{", "SuperNode", ".", "create", "(", "{", "guid", ":", "context", ".", "guid", "}", ",", "function", "(", "error", ",", "result", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "return", ";", "}", "superNode", "=", "result", ";", "context", ".", "putObject", "(", "superNode", ".", "id", ",", "superNode", ",", "write_directory_node", ")", ";", "}", ")", ";", "}", "}", "function", "write_directory_node", "(", "error", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "}", "else", "{", "Node", ".", "create", "(", "{", "guid", ":", "context", ".", "guid", ",", "id", ":", "superNode", ".", "rnode", ",", "type", ":", "NODE_TYPE_DIRECTORY", "}", ",", "function", "(", "error", ",", "result", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "return", ";", "}", "directoryNode", "=", "result", ";", "directoryNode", ".", "nlinks", "+=", "1", ";", "context", ".", "putObject", "(", "directoryNode", ".", "id", ",", "directoryNode", ",", "write_directory_data", ")", ";", "}", ")", ";", "}", "}", "function", "write_directory_data", "(", "error", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "}", "else", "{", "directoryData", "=", "{", "}", ";", "context", ".", "putObject", "(", "directoryNode", ".", "data", ",", "directoryData", ",", "callback", ")", ";", "}", "}", "context", ".", "getObject", "(", "SUPER_NODE_ID", ",", "ensure_super_node", ")", ";", "}" ]
ensure_root_directory. Creates a root node if necessary. Note: this should only be invoked when formatting a new file system. Multiple invocations of this by separate instances will still result in only a single super node.
[ "ensure_root_directory", ".", "Creates", "a", "root", "node", "if", "necessary", "." ]
4aae53839a8da2ca5da9f4e92c33eaab50094352
https://github.com/filerjs/filer/blob/4aae53839a8da2ca5da9f4e92c33eaab50094352/src/filesystem/implementation.js#L315-L368
17,583
filerjs/filer
src/node.js
ensureID
function ensureID(options, prop, callback) { if(options[prop]) { return callback(); } options.guid(function(err, id) { if(err) { return callback(err); } options[prop] = id; callback(); }); }
javascript
function ensureID(options, prop, callback) { if(options[prop]) { return callback(); } options.guid(function(err, id) { if(err) { return callback(err); } options[prop] = id; callback(); }); }
[ "function", "ensureID", "(", "options", ",", "prop", ",", "callback", ")", "{", "if", "(", "options", "[", "prop", "]", ")", "{", "return", "callback", "(", ")", ";", "}", "options", ".", "guid", "(", "function", "(", "err", ",", "id", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "options", "[", "prop", "]", "=", "id", ";", "callback", "(", ")", ";", "}", ")", ";", "}" ]
Make sure the options object has an id on property, either from caller or one we generate using supplied guid fn.
[ "Make", "sure", "the", "options", "object", "has", "an", "id", "on", "property", "either", "from", "caller", "or", "one", "we", "generate", "using", "supplied", "guid", "fn", "." ]
4aae53839a8da2ca5da9f4e92c33eaab50094352
https://github.com/filerjs/filer/blob/4aae53839a8da2ca5da9f4e92c33eaab50094352/src/node.js#L18-L30
17,584
filerjs/filer
src/filesystem/interface.js
wrappedGuidFn
function wrappedGuidFn(context) { return function (callback) { // Skip the duplicate ID check if asked to if (flags.includes(FS_NODUPEIDCHECK)) { callback(null, guid()); return; } // Otherwise (default) make sure this id is unused first function guidWithCheck(callback) { const id = guid(); context.getObject(id, function (err, value) { if (err) { callback(err); return; } // If this id is unused, use it, otherwise find another if (!value) { callback(null, id); } else { guidWithCheck(callback); } }); } guidWithCheck(callback); }; }
javascript
function wrappedGuidFn(context) { return function (callback) { // Skip the duplicate ID check if asked to if (flags.includes(FS_NODUPEIDCHECK)) { callback(null, guid()); return; } // Otherwise (default) make sure this id is unused first function guidWithCheck(callback) { const id = guid(); context.getObject(id, function (err, value) { if (err) { callback(err); return; } // If this id is unused, use it, otherwise find another if (!value) { callback(null, id); } else { guidWithCheck(callback); } }); } guidWithCheck(callback); }; }
[ "function", "wrappedGuidFn", "(", "context", ")", "{", "return", "function", "(", "callback", ")", "{", "// Skip the duplicate ID check if asked to", "if", "(", "flags", ".", "includes", "(", "FS_NODUPEIDCHECK", ")", ")", "{", "callback", "(", "null", ",", "guid", "(", ")", ")", ";", "return", ";", "}", "// Otherwise (default) make sure this id is unused first", "function", "guidWithCheck", "(", "callback", ")", "{", "const", "id", "=", "guid", "(", ")", ";", "context", ".", "getObject", "(", "id", ",", "function", "(", "err", ",", "value", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "return", ";", "}", "// If this id is unused, use it, otherwise find another", "if", "(", "!", "value", ")", "{", "callback", "(", "null", ",", "id", ")", ";", "}", "else", "{", "guidWithCheck", "(", "callback", ")", ";", "}", "}", ")", ";", "}", "guidWithCheck", "(", "callback", ")", ";", "}", ";", "}" ]
Deal with various approaches to node ID creation
[ "Deal", "with", "various", "approaches", "to", "node", "ID", "creation" ]
4aae53839a8da2ca5da9f4e92c33eaab50094352
https://github.com/filerjs/filer/blob/4aae53839a8da2ca5da9f4e92c33eaab50094352/src/filesystem/interface.js#L210-L237
17,585
country-regions/country-region-selector
source/source-jquery.crs.js
function (countries, preferred, preferredDelim) { var preferredShortCodes = preferred.split(',').reverse(); var preferredMap = {}; var foundPreferred = false; var updatedCountries = countries.filter(function (c) { if (preferredShortCodes.indexOf(c[1]) !== -1) { preferredMap[c[1]] = c; foundPreferred = true; return false; } return true; }); if (foundPreferred && preferredDelim) { updatedCountries.unshift([preferredDelim, "", "", {}, true]); } // now prepend the preferred countries for (var i=0; i<preferredShortCodes.length; i++) { var code = preferredShortCodes[i]; updatedCountries.unshift(preferredMap[code]); } return updatedCountries; }
javascript
function (countries, preferred, preferredDelim) { var preferredShortCodes = preferred.split(',').reverse(); var preferredMap = {}; var foundPreferred = false; var updatedCountries = countries.filter(function (c) { if (preferredShortCodes.indexOf(c[1]) !== -1) { preferredMap[c[1]] = c; foundPreferred = true; return false; } return true; }); if (foundPreferred && preferredDelim) { updatedCountries.unshift([preferredDelim, "", "", {}, true]); } // now prepend the preferred countries for (var i=0; i<preferredShortCodes.length; i++) { var code = preferredShortCodes[i]; updatedCountries.unshift(preferredMap[code]); } return updatedCountries; }
[ "function", "(", "countries", ",", "preferred", ",", "preferredDelim", ")", "{", "var", "preferredShortCodes", "=", "preferred", ".", "split", "(", "','", ")", ".", "reverse", "(", ")", ";", "var", "preferredMap", "=", "{", "}", ";", "var", "foundPreferred", "=", "false", ";", "var", "updatedCountries", "=", "countries", ".", "filter", "(", "function", "(", "c", ")", "{", "if", "(", "preferredShortCodes", ".", "indexOf", "(", "c", "[", "1", "]", ")", "!==", "-", "1", ")", "{", "preferredMap", "[", "c", "[", "1", "]", "]", "=", "c", ";", "foundPreferred", "=", "true", ";", "return", "false", ";", "}", "return", "true", ";", "}", ")", ";", "if", "(", "foundPreferred", "&&", "preferredDelim", ")", "{", "updatedCountries", ".", "unshift", "(", "[", "preferredDelim", ",", "\"\"", ",", "\"\"", ",", "{", "}", ",", "true", "]", ")", ";", "}", "// now prepend the preferred countries", "for", "(", "var", "i", "=", "0", ";", "i", "<", "preferredShortCodes", ".", "length", ";", "i", "++", ")", "{", "var", "code", "=", "preferredShortCodes", "[", "i", "]", ";", "updatedCountries", ".", "unshift", "(", "preferredMap", "[", "code", "]", ")", ";", "}", "return", "updatedCountries", ";", "}" ]
in 0.5.0 we added the option for "preferred" countries that get listed first. This just causes the preferred countries to get listed at the top of the list with an optional delimiter row following them
[ "in", "0", ".", "5", ".", "0", "we", "added", "the", "option", "for", "preferred", "countries", "that", "get", "listed", "first", ".", "This", "just", "causes", "the", "preferred", "countries", "to", "get", "listed", "at", "the", "top", "of", "the", "list", "with", "an", "optional", "delimiter", "row", "following", "them" ]
619110c162b6b68e427798b8c049135802ebf0c5
https://github.com/country-regions/country-region-selector/blob/619110c162b6b68e427798b8c049135802ebf0c5/source/source-jquery.crs.js#L229-L254
17,586
country-regions/country-region-selector
gruntfile.js
getCountryList
function getCountryList() { var countries = grunt.option("countries"); if (!countries) { grunt.fail.fatal("Country list not passed. Example usage: `grunt customBuild --countries=Canada,United States`"); } // countries may contain commas in their names. Bit ugly, but simple. This swiches out those escaped commas // and replaces them later var commaReplaced = countries.replace(/\\,/g, '{COMMA}'); var targetCountries = _.map(commaReplaced.split(","), function (country) { return country.replace(/\{COMMA\}/, ',').trim(); }); var countryData = []; var foundCountryNames = []; var formattedData = minifyJSON(countriesJSON); _.each(formattedData, function (countryInfo) { var countryName = countryInfo[0]; if (_.contains(targetCountries, countryName)) { countryData.push(countryInfo); foundCountryNames.push(countryName); } }); // if one or more of the countries wasn't found, they probably made a typo: throw a warning but continue if (targetCountries.length !== countryData.length) { grunt.log.error("The following countries weren't found (check the source/data.json file to ensure you entered the exact country string):"); var missing = _.difference(targetCountries, foundCountryNames); _.each(missing, function (countryName) { grunt.log.error("--", countryName); }); // all good! Let the user know what bundle is being created, just to remove any ambiguity } else { grunt.log.writeln(""); grunt.log.writeln("Creating bundle with following countries:"); _.each(targetCountries, function (country) { grunt.log.writeln("* " + country); }); } config.template.customBuild.options.data.__DATA__ = "\nvar _data = " + JSON.stringify(countryData); }
javascript
function getCountryList() { var countries = grunt.option("countries"); if (!countries) { grunt.fail.fatal("Country list not passed. Example usage: `grunt customBuild --countries=Canada,United States`"); } // countries may contain commas in their names. Bit ugly, but simple. This swiches out those escaped commas // and replaces them later var commaReplaced = countries.replace(/\\,/g, '{COMMA}'); var targetCountries = _.map(commaReplaced.split(","), function (country) { return country.replace(/\{COMMA\}/, ',').trim(); }); var countryData = []; var foundCountryNames = []; var formattedData = minifyJSON(countriesJSON); _.each(formattedData, function (countryInfo) { var countryName = countryInfo[0]; if (_.contains(targetCountries, countryName)) { countryData.push(countryInfo); foundCountryNames.push(countryName); } }); // if one or more of the countries wasn't found, they probably made a typo: throw a warning but continue if (targetCountries.length !== countryData.length) { grunt.log.error("The following countries weren't found (check the source/data.json file to ensure you entered the exact country string):"); var missing = _.difference(targetCountries, foundCountryNames); _.each(missing, function (countryName) { grunt.log.error("--", countryName); }); // all good! Let the user know what bundle is being created, just to remove any ambiguity } else { grunt.log.writeln(""); grunt.log.writeln("Creating bundle with following countries:"); _.each(targetCountries, function (country) { grunt.log.writeln("* " + country); }); } config.template.customBuild.options.data.__DATA__ = "\nvar _data = " + JSON.stringify(countryData); }
[ "function", "getCountryList", "(", ")", "{", "var", "countries", "=", "grunt", ".", "option", "(", "\"countries\"", ")", ";", "if", "(", "!", "countries", ")", "{", "grunt", ".", "fail", ".", "fatal", "(", "\"Country list not passed. Example usage: `grunt customBuild --countries=Canada,United States`\"", ")", ";", "}", "// countries may contain commas in their names. Bit ugly, but simple. This swiches out those escaped commas", "// and replaces them later", "var", "commaReplaced", "=", "countries", ".", "replace", "(", "/", "\\\\,", "/", "g", ",", "'{COMMA}'", ")", ";", "var", "targetCountries", "=", "_", ".", "map", "(", "commaReplaced", ".", "split", "(", "\",\"", ")", ",", "function", "(", "country", ")", "{", "return", "country", ".", "replace", "(", "/", "\\{COMMA\\}", "/", ",", "','", ")", ".", "trim", "(", ")", ";", "}", ")", ";", "var", "countryData", "=", "[", "]", ";", "var", "foundCountryNames", "=", "[", "]", ";", "var", "formattedData", "=", "minifyJSON", "(", "countriesJSON", ")", ";", "_", ".", "each", "(", "formattedData", ",", "function", "(", "countryInfo", ")", "{", "var", "countryName", "=", "countryInfo", "[", "0", "]", ";", "if", "(", "_", ".", "contains", "(", "targetCountries", ",", "countryName", ")", ")", "{", "countryData", ".", "push", "(", "countryInfo", ")", ";", "foundCountryNames", ".", "push", "(", "countryName", ")", ";", "}", "}", ")", ";", "// if one or more of the countries wasn't found, they probably made a typo: throw a warning but continue", "if", "(", "targetCountries", ".", "length", "!==", "countryData", ".", "length", ")", "{", "grunt", ".", "log", ".", "error", "(", "\"The following countries weren't found (check the source/data.json file to ensure you entered the exact country string):\"", ")", ";", "var", "missing", "=", "_", ".", "difference", "(", "targetCountries", ",", "foundCountryNames", ")", ";", "_", ".", "each", "(", "missing", ",", "function", "(", "countryName", ")", "{", "grunt", ".", "log", ".", "error", "(", "\"--\"", ",", "countryName", ")", ";", "}", ")", ";", "// all good! Let the user know what bundle is being created, just to remove any ambiguity", "}", "else", "{", "grunt", ".", "log", ".", "writeln", "(", "\"\"", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "\"Creating bundle with following countries:\"", ")", ";", "_", ".", "each", "(", "targetCountries", ",", "function", "(", "country", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "\"* \"", "+", "country", ")", ";", "}", ")", ";", "}", "config", ".", "template", ".", "customBuild", ".", "options", ".", "data", ".", "__DATA__", "=", "\"\\nvar _data = \"", "+", "JSON", ".", "stringify", "(", "countryData", ")", ";", "}" ]
used for the customBuild target. This generates a custom build of CRS with the list of countries specified by the user
[ "used", "for", "the", "customBuild", "target", ".", "This", "generates", "a", "custom", "build", "of", "CRS", "with", "the", "list", "of", "countries", "specified", "by", "the", "user" ]
619110c162b6b68e427798b8c049135802ebf0c5
https://github.com/country-regions/country-region-selector/blob/619110c162b6b68e427798b8c049135802ebf0c5/gruntfile.js#L15-L58
17,587
country-regions/country-region-selector
gruntfile.js
minifyJSON
function minifyJSON(json) { var js = []; json.forEach(function (countryData) { var pairs = []; countryData.regions.forEach(function (info) { if (_.has(info, 'shortCode')) { pairs.push(info.name + '~' + info.shortCode); } else { pairs.push(info.name); } }); var regionListStr = pairs.join('|'); js.push([ countryData.countryName, countryData.countryShortCode, regionListStr ]); }); return js; }
javascript
function minifyJSON(json) { var js = []; json.forEach(function (countryData) { var pairs = []; countryData.regions.forEach(function (info) { if (_.has(info, 'shortCode')) { pairs.push(info.name + '~' + info.shortCode); } else { pairs.push(info.name); } }); var regionListStr = pairs.join('|'); js.push([ countryData.countryName, countryData.countryShortCode, regionListStr ]); }); return js; }
[ "function", "minifyJSON", "(", "json", ")", "{", "var", "js", "=", "[", "]", ";", "json", ".", "forEach", "(", "function", "(", "countryData", ")", "{", "var", "pairs", "=", "[", "]", ";", "countryData", ".", "regions", ".", "forEach", "(", "function", "(", "info", ")", "{", "if", "(", "_", ".", "has", "(", "info", ",", "'shortCode'", ")", ")", "{", "pairs", ".", "push", "(", "info", ".", "name", "+", "'~'", "+", "info", ".", "shortCode", ")", ";", "}", "else", "{", "pairs", ".", "push", "(", "info", ".", "name", ")", ";", "}", "}", ")", ";", "var", "regionListStr", "=", "pairs", ".", "join", "(", "'|'", ")", ";", "js", ".", "push", "(", "[", "countryData", ".", "countryName", ",", "countryData", ".", "countryShortCode", ",", "regionListStr", "]", ")", ";", "}", ")", ";", "return", "js", ";", "}" ]
converts the data.json content from the country-region-data
[ "converts", "the", "data", ".", "json", "content", "from", "the", "country", "-", "region", "-", "data" ]
619110c162b6b68e427798b8c049135802ebf0c5
https://github.com/country-regions/country-region-selector/blob/619110c162b6b68e427798b8c049135802ebf0c5/gruntfile.js#L62-L84
17,588
Mikhus/domurl
url.js
urlConfig
function urlConfig (url) { var config = { path: true, query: true, hash: true }; if (!url) { return config; } if (RX_PROTOCOL.test(url)) { config.protocol = true; config.host = true; if (RX_PORT.test(url)) { config.port = true; } if (RX_CREDS.test(url)) { config.user = true; config.pass = true; } } return config; }
javascript
function urlConfig (url) { var config = { path: true, query: true, hash: true }; if (!url) { return config; } if (RX_PROTOCOL.test(url)) { config.protocol = true; config.host = true; if (RX_PORT.test(url)) { config.port = true; } if (RX_CREDS.test(url)) { config.user = true; config.pass = true; } } return config; }
[ "function", "urlConfig", "(", "url", ")", "{", "var", "config", "=", "{", "path", ":", "true", ",", "query", ":", "true", ",", "hash", ":", "true", "}", ";", "if", "(", "!", "url", ")", "{", "return", "config", ";", "}", "if", "(", "RX_PROTOCOL", ".", "test", "(", "url", ")", ")", "{", "config", ".", "protocol", "=", "true", ";", "config", ".", "host", "=", "true", ";", "if", "(", "RX_PORT", ".", "test", "(", "url", ")", ")", "{", "config", ".", "port", "=", "true", ";", "}", "if", "(", "RX_CREDS", ".", "test", "(", "url", ")", ")", "{", "config", ".", "user", "=", "true", ";", "config", ".", "pass", "=", "true", ";", "}", "}", "return", "config", ";", "}" ]
configure given url options
[ "configure", "given", "url", "options" ]
6da9d172cfed40b126a7f53f87645e85124814a8
https://github.com/Mikhus/domurl/blob/6da9d172cfed40b126a7f53f87645e85124814a8/url.js#L32-L58
17,589
medialab/artoo
src/artoo.writers.js
keysIndex
function keysIndex(a) { var keys = [], l, k, i; for (i = 0, l = a.length; i < l; i++) for (k in a[i]) if (!~keys.indexOf(k)) keys.push(k); return keys; }
javascript
function keysIndex(a) { var keys = [], l, k, i; for (i = 0, l = a.length; i < l; i++) for (k in a[i]) if (!~keys.indexOf(k)) keys.push(k); return keys; }
[ "function", "keysIndex", "(", "a", ")", "{", "var", "keys", "=", "[", "]", ",", "l", ",", "k", ",", "i", ";", "for", "(", "i", "=", "0", ",", "l", "=", "a", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "for", "(", "k", "in", "a", "[", "i", "]", ")", "if", "(", "!", "~", "keys", ".", "indexOf", "(", "k", ")", ")", "keys", ".", "push", "(", "k", ")", ";", "return", "keys", ";", "}" ]
Retrieve an index of keys present in an array of objects
[ "Retrieve", "an", "index", "of", "keys", "present", "in", "an", "array", "of", "objects" ]
89fe334cb2c2ec38b16012edfab2977822e1ecda
https://github.com/medialab/artoo/blob/89fe334cb2c2ec38b16012edfab2977822e1ecda/src/artoo.writers.js#L40-L52
17,590
medialab/artoo
src/artoo.writers.js
toCSVString
function toCSVString(data, params) { if (data.length === 0) { return ''; } params = params || {}; var header = params.headers || [], plainObject = isPlainObject(data[0]), keys = plainObject && (params.order || keysIndex(data)), oData, i; // Defaults var escape = params.escape || '"', delimiter = params.delimiter || ','; // Dealing with headers polymorphism if (!header.length) if (plainObject && params.headers !== false) header = keys; // Should we append headers oData = (header.length ? [header] : []).concat( plainObject ? data.map(function(e) { return objectToArray(e, keys); }) : data ); // Converting to string return oData.map(function(row) { return row.map(function(item) { // Wrapping escaping characters var i = ('' + (typeof item === 'undefined' ? '' : item)).replace( new RegExp(rescape(escape), 'g'), escape + escape ); // Escaping if needed return ~i.indexOf(delimiter) || ~i.indexOf(escape) || ~i.indexOf('\n') ? escape + i + escape : i; }).join(delimiter); }).join('\n'); }
javascript
function toCSVString(data, params) { if (data.length === 0) { return ''; } params = params || {}; var header = params.headers || [], plainObject = isPlainObject(data[0]), keys = plainObject && (params.order || keysIndex(data)), oData, i; // Defaults var escape = params.escape || '"', delimiter = params.delimiter || ','; // Dealing with headers polymorphism if (!header.length) if (plainObject && params.headers !== false) header = keys; // Should we append headers oData = (header.length ? [header] : []).concat( plainObject ? data.map(function(e) { return objectToArray(e, keys); }) : data ); // Converting to string return oData.map(function(row) { return row.map(function(item) { // Wrapping escaping characters var i = ('' + (typeof item === 'undefined' ? '' : item)).replace( new RegExp(rescape(escape), 'g'), escape + escape ); // Escaping if needed return ~i.indexOf(delimiter) || ~i.indexOf(escape) || ~i.indexOf('\n') ? escape + i + escape : i; }).join(delimiter); }).join('\n'); }
[ "function", "toCSVString", "(", "data", ",", "params", ")", "{", "if", "(", "data", ".", "length", "===", "0", ")", "{", "return", "''", ";", "}", "params", "=", "params", "||", "{", "}", ";", "var", "header", "=", "params", ".", "headers", "||", "[", "]", ",", "plainObject", "=", "isPlainObject", "(", "data", "[", "0", "]", ")", ",", "keys", "=", "plainObject", "&&", "(", "params", ".", "order", "||", "keysIndex", "(", "data", ")", ")", ",", "oData", ",", "i", ";", "// Defaults", "var", "escape", "=", "params", ".", "escape", "||", "'\"'", ",", "delimiter", "=", "params", ".", "delimiter", "||", "','", ";", "// Dealing with headers polymorphism", "if", "(", "!", "header", ".", "length", ")", "if", "(", "plainObject", "&&", "params", ".", "headers", "!==", "false", ")", "header", "=", "keys", ";", "// Should we append headers", "oData", "=", "(", "header", ".", "length", "?", "[", "header", "]", ":", "[", "]", ")", ".", "concat", "(", "plainObject", "?", "data", ".", "map", "(", "function", "(", "e", ")", "{", "return", "objectToArray", "(", "e", ",", "keys", ")", ";", "}", ")", ":", "data", ")", ";", "// Converting to string", "return", "oData", ".", "map", "(", "function", "(", "row", ")", "{", "return", "row", ".", "map", "(", "function", "(", "item", ")", "{", "// Wrapping escaping characters", "var", "i", "=", "(", "''", "+", "(", "typeof", "item", "===", "'undefined'", "?", "''", ":", "item", ")", ")", ".", "replace", "(", "new", "RegExp", "(", "rescape", "(", "escape", ")", ",", "'g'", ")", ",", "escape", "+", "escape", ")", ";", "// Escaping if needed", "return", "~", "i", ".", "indexOf", "(", "delimiter", ")", "||", "~", "i", ".", "indexOf", "(", "escape", ")", "||", "~", "i", ".", "indexOf", "(", "'\\n'", ")", "?", "escape", "+", "i", "+", "escape", ":", "i", ";", "}", ")", ".", "join", "(", "delimiter", ")", ";", "}", ")", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Converting an array of arrays into a CSV string
[ "Converting", "an", "array", "of", "arrays", "into", "a", "CSV", "string" ]
89fe334cb2c2ec38b16012edfab2977822e1ecda
https://github.com/medialab/artoo/blob/89fe334cb2c2ec38b16012edfab2977822e1ecda/src/artoo.writers.js#L60-L104
17,591
medialab/artoo
src/artoo.writers.js
repeatString
function repeatString(string, nb) { var s = string, l, i; if (nb <= 0) return ''; for (i = 1, l = nb | 0; i < l; i++) s += string; return s; }
javascript
function repeatString(string, nb) { var s = string, l, i; if (nb <= 0) return ''; for (i = 1, l = nb | 0; i < l; i++) s += string; return s; }
[ "function", "repeatString", "(", "string", ",", "nb", ")", "{", "var", "s", "=", "string", ",", "l", ",", "i", ";", "if", "(", "nb", "<=", "0", ")", "return", "''", ";", "for", "(", "i", "=", "1", ",", "l", "=", "nb", "|", "0", ";", "i", "<", "l", ";", "i", "++", ")", "s", "+=", "string", ";", "return", "s", ";", "}" ]
Creating repeating sequences
[ "Creating", "repeating", "sequences" ]
89fe334cb2c2ec38b16012edfab2977822e1ecda
https://github.com/medialab/artoo/blob/89fe334cb2c2ec38b16012edfab2977822e1ecda/src/artoo.writers.js#L119-L130
17,592
medialab/artoo
src/artoo.writers.js
processYAMLVariable
function processYAMLVariable(v, lvl, indent) { // Scalars if (typeof v === 'string') return yml.string(v); else if (typeof v === 'number') return yml.number(v); else if (typeof v === 'boolean') return yml.boolean(v); else if (typeof v === 'undefined' || v === null || isRealNaN(v)) return yml.nullValue(v); // Nonscalars else if (isPlainObject(v)) return yml.object(v, lvl, indent); else if (isArray(v)) return yml.array(v, lvl); else if (typeof v === 'function') return yml.fn(v); // Error else throw TypeError('artoo.writers.processYAMLVariable: wrong type.'); }
javascript
function processYAMLVariable(v, lvl, indent) { // Scalars if (typeof v === 'string') return yml.string(v); else if (typeof v === 'number') return yml.number(v); else if (typeof v === 'boolean') return yml.boolean(v); else if (typeof v === 'undefined' || v === null || isRealNaN(v)) return yml.nullValue(v); // Nonscalars else if (isPlainObject(v)) return yml.object(v, lvl, indent); else if (isArray(v)) return yml.array(v, lvl); else if (typeof v === 'function') return yml.fn(v); // Error else throw TypeError('artoo.writers.processYAMLVariable: wrong type.'); }
[ "function", "processYAMLVariable", "(", "v", ",", "lvl", ",", "indent", ")", "{", "// Scalars", "if", "(", "typeof", "v", "===", "'string'", ")", "return", "yml", ".", "string", "(", "v", ")", ";", "else", "if", "(", "typeof", "v", "===", "'number'", ")", "return", "yml", ".", "number", "(", "v", ")", ";", "else", "if", "(", "typeof", "v", "===", "'boolean'", ")", "return", "yml", ".", "boolean", "(", "v", ")", ";", "else", "if", "(", "typeof", "v", "===", "'undefined'", "||", "v", "===", "null", "||", "isRealNaN", "(", "v", ")", ")", "return", "yml", ".", "nullValue", "(", "v", ")", ";", "// Nonscalars", "else", "if", "(", "isPlainObject", "(", "v", ")", ")", "return", "yml", ".", "object", "(", "v", ",", "lvl", ",", "indent", ")", ";", "else", "if", "(", "isArray", "(", "v", ")", ")", "return", "yml", ".", "array", "(", "v", ",", "lvl", ")", ";", "else", "if", "(", "typeof", "v", "===", "'function'", ")", "return", "yml", ".", "fn", "(", "v", ")", ";", "// Error", "else", "throw", "TypeError", "(", "'artoo.writers.processYAMLVariable: wrong type.'", ")", ";", "}" ]
Get the correct handler corresponding to variable type
[ "Get", "the", "correct", "handler", "corresponding", "to", "variable", "type" ]
89fe334cb2c2ec38b16012edfab2977822e1ecda
https://github.com/medialab/artoo/blob/89fe334cb2c2ec38b16012edfab2977822e1ecda/src/artoo.writers.js#L204-L227
17,593
medialab/artoo
src/artoo.helpers.js
extend
function extend() { var i, k, res = {}, l = arguments.length; for (i = l - 1; i >= 0; i--) for (k in arguments[i]) if (res[k] && isPlainObject(arguments[i][k])) res[k] = extend(arguments[i][k], res[k]); else res[k] = arguments[i][k]; return res; }
javascript
function extend() { var i, k, res = {}, l = arguments.length; for (i = l - 1; i >= 0; i--) for (k in arguments[i]) if (res[k] && isPlainObject(arguments[i][k])) res[k] = extend(arguments[i][k], res[k]); else res[k] = arguments[i][k]; return res; }
[ "function", "extend", "(", ")", "{", "var", "i", ",", "k", ",", "res", "=", "{", "}", ",", "l", "=", "arguments", ".", "length", ";", "for", "(", "i", "=", "l", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "for", "(", "k", "in", "arguments", "[", "i", "]", ")", "if", "(", "res", "[", "k", "]", "&&", "isPlainObject", "(", "arguments", "[", "i", "]", "[", "k", "]", ")", ")", "res", "[", "k", "]", "=", "extend", "(", "arguments", "[", "i", "]", "[", "k", "]", ",", "res", "[", "k", "]", ")", ";", "else", "res", "[", "k", "]", "=", "arguments", "[", "i", "]", "[", "k", "]", ";", "return", "res", ";", "}" ]
Recursively extend objects
[ "Recursively", "extend", "objects" ]
89fe334cb2c2ec38b16012edfab2977822e1ecda
https://github.com/medialab/artoo/blob/89fe334cb2c2ec38b16012edfab2977822e1ecda/src/artoo.helpers.js#L41-L55
17,594
medialab/artoo
src/artoo.helpers.js
first
function first(a, fn, scope) { for (var i = 0, l = a.length; i < l; i++) { if (fn.call(scope || null, a[i])) return a[i]; } return; }
javascript
function first(a, fn, scope) { for (var i = 0, l = a.length; i < l; i++) { if (fn.call(scope || null, a[i])) return a[i]; } return; }
[ "function", "first", "(", "a", ",", "fn", ",", "scope", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "a", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "fn", ".", "call", "(", "scope", "||", "null", ",", "a", "[", "i", "]", ")", ")", "return", "a", "[", "i", "]", ";", "}", "return", ";", "}" ]
Get first item of array returning true to given function
[ "Get", "first", "item", "of", "array", "returning", "true", "to", "given", "function" ]
89fe334cb2c2ec38b16012edfab2977822e1ecda
https://github.com/medialab/artoo/blob/89fe334cb2c2ec38b16012edfab2977822e1ecda/src/artoo.helpers.js#L90-L96
17,595
medialab/artoo
src/artoo.helpers.js
getExtension
function getExtension(url) { var a = url.split('.'); if (a.length === 1 || (a[0] === '' && a.length === 2)) return ''; return a.pop(); }
javascript
function getExtension(url) { var a = url.split('.'); if (a.length === 1 || (a[0] === '' && a.length === 2)) return ''; return a.pop(); }
[ "function", "getExtension", "(", "url", ")", "{", "var", "a", "=", "url", ".", "split", "(", "'.'", ")", ";", "if", "(", "a", ".", "length", "===", "1", "||", "(", "a", "[", "0", "]", "===", "''", "&&", "a", ".", "length", "===", "2", ")", ")", "return", "''", ";", "return", "a", ".", "pop", "(", ")", ";", "}" ]
Retrieve a file extenstion from filename or url
[ "Retrieve", "a", "file", "extenstion", "from", "filename", "or", "url" ]
89fe334cb2c2ec38b16012edfab2977822e1ecda
https://github.com/medialab/artoo/blob/89fe334cb2c2ec38b16012edfab2977822e1ecda/src/artoo.helpers.js#L108-L114
17,596
medialab/artoo
src/artoo.helpers.js
createDocument
function createDocument(root, namespace) { if (!root) return document.implementation.createHTMLDocument(); else return document.implementation.createDocument( namespace || null, root, null ); }
javascript
function createDocument(root, namespace) { if (!root) return document.implementation.createHTMLDocument(); else return document.implementation.createDocument( namespace || null, root, null ); }
[ "function", "createDocument", "(", "root", ",", "namespace", ")", "{", "if", "(", "!", "root", ")", "return", "document", ".", "implementation", ".", "createHTMLDocument", "(", ")", ";", "else", "return", "document", ".", "implementation", ".", "createDocument", "(", "namespace", "||", "null", ",", "root", ",", "null", ")", ";", "}" ]
Creating an HTML or XML document
[ "Creating", "an", "HTML", "or", "XML", "document" ]
89fe334cb2c2ec38b16012edfab2977822e1ecda
https://github.com/medialab/artoo/blob/89fe334cb2c2ec38b16012edfab2977822e1ecda/src/artoo.helpers.js#L146-L155
17,597
medialab/artoo
src/artoo.helpers.js
getScript
function getScript(url, async, cb) { if (typeof async === 'function') { cb = async; async = false; } var el = document.createElement('script'); // Script attributes el.type = 'text/javascript'; el.src = url; // Should the script be loaded asynchronously? if (async) el.async = true; // Defining callbacks el.onload = el.onreadystatechange = function() { if ((!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { el.onload = el.onreadystatechange = null; // Removing element from head artoo.mountNode.removeChild(el); if (typeof cb === 'function') cb(); } }; // Appending the script to head artoo.mountNode.appendChild(el); }
javascript
function getScript(url, async, cb) { if (typeof async === 'function') { cb = async; async = false; } var el = document.createElement('script'); // Script attributes el.type = 'text/javascript'; el.src = url; // Should the script be loaded asynchronously? if (async) el.async = true; // Defining callbacks el.onload = el.onreadystatechange = function() { if ((!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { el.onload = el.onreadystatechange = null; // Removing element from head artoo.mountNode.removeChild(el); if (typeof cb === 'function') cb(); } }; // Appending the script to head artoo.mountNode.appendChild(el); }
[ "function", "getScript", "(", "url", ",", "async", ",", "cb", ")", "{", "if", "(", "typeof", "async", "===", "'function'", ")", "{", "cb", "=", "async", ";", "async", "=", "false", ";", "}", "var", "el", "=", "document", ".", "createElement", "(", "'script'", ")", ";", "// Script attributes", "el", ".", "type", "=", "'text/javascript'", ";", "el", ".", "src", "=", "url", ";", "// Should the script be loaded asynchronously?", "if", "(", "async", ")", "el", ".", "async", "=", "true", ";", "// Defining callbacks", "el", ".", "onload", "=", "el", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "(", "!", "this", ".", "readyState", "||", "this", ".", "readyState", "==", "'loaded'", "||", "this", ".", "readyState", "==", "'complete'", ")", ")", "{", "el", ".", "onload", "=", "el", ".", "onreadystatechange", "=", "null", ";", "// Removing element from head", "artoo", ".", "mountNode", ".", "removeChild", "(", "el", ")", ";", "if", "(", "typeof", "cb", "===", "'function'", ")", "cb", "(", ")", ";", "}", "}", ";", "// Appending the script to head", "artoo", ".", "mountNode", ".", "appendChild", "(", "el", ")", ";", "}" ]
Loading an external file the same way the browser would load it from page
[ "Loading", "an", "external", "file", "the", "same", "way", "the", "browser", "would", "load", "it", "from", "page" ]
89fe334cb2c2ec38b16012edfab2977822e1ecda
https://github.com/medialab/artoo/blob/89fe334cb2c2ec38b16012edfab2977822e1ecda/src/artoo.helpers.js#L158-L191
17,598
medialab/artoo
src/artoo.helpers.js
getStylesheet
function getStylesheet(data, isUrl, cb) { var el = document.createElement(isUrl ? 'link' : 'style'), head = document.getElementsByTagName('head')[0]; el.type = 'text/css'; if (isUrl) { el.href = data; el.rel = 'stylesheet'; // Waiting for script to load el.onload = el.onreadystatechange = function() { if ((!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { el.onload = el.onreadystatechange = null; if (typeof cb === 'function') cb(); } }; } else { el.innerHTML = data; } // Appending the stylesheet to head head.appendChild(el); }
javascript
function getStylesheet(data, isUrl, cb) { var el = document.createElement(isUrl ? 'link' : 'style'), head = document.getElementsByTagName('head')[0]; el.type = 'text/css'; if (isUrl) { el.href = data; el.rel = 'stylesheet'; // Waiting for script to load el.onload = el.onreadystatechange = function() { if ((!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { el.onload = el.onreadystatechange = null; if (typeof cb === 'function') cb(); } }; } else { el.innerHTML = data; } // Appending the stylesheet to head head.appendChild(el); }
[ "function", "getStylesheet", "(", "data", ",", "isUrl", ",", "cb", ")", "{", "var", "el", "=", "document", ".", "createElement", "(", "isUrl", "?", "'link'", ":", "'style'", ")", ",", "head", "=", "document", ".", "getElementsByTagName", "(", "'head'", ")", "[", "0", "]", ";", "el", ".", "type", "=", "'text/css'", ";", "if", "(", "isUrl", ")", "{", "el", ".", "href", "=", "data", ";", "el", ".", "rel", "=", "'stylesheet'", ";", "// Waiting for script to load", "el", ".", "onload", "=", "el", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "(", "!", "this", ".", "readyState", "||", "this", ".", "readyState", "==", "'loaded'", "||", "this", ".", "readyState", "==", "'complete'", ")", ")", "{", "el", ".", "onload", "=", "el", ".", "onreadystatechange", "=", "null", ";", "if", "(", "typeof", "cb", "===", "'function'", ")", "cb", "(", ")", ";", "}", "}", ";", "}", "else", "{", "el", ".", "innerHTML", "=", "data", ";", "}", "// Appending the stylesheet to head", "head", ".", "appendChild", "(", "el", ")", ";", "}" ]
Loading an external stylesheet
[ "Loading", "an", "external", "stylesheet" ]
89fe334cb2c2ec38b16012edfab2977822e1ecda
https://github.com/medialab/artoo/blob/89fe334cb2c2ec38b16012edfab2977822e1ecda/src/artoo.helpers.js#L194-L222
17,599
medialab/artoo
src/artoo.helpers.js
async
function async() { var args = Array.prototype.slice.call(arguments); return setTimeout.apply(null, [args[0], 0].concat(args.slice(1))); }
javascript
function async() { var args = Array.prototype.slice.call(arguments); return setTimeout.apply(null, [args[0], 0].concat(args.slice(1))); }
[ "function", "async", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "return", "setTimeout", ".", "apply", "(", "null", ",", "[", "args", "[", "0", "]", ",", "0", "]", ".", "concat", "(", "args", ".", "slice", "(", "1", ")", ")", ")", ";", "}" ]
Dispatch asynchronous function
[ "Dispatch", "asynchronous", "function" ]
89fe334cb2c2ec38b16012edfab2977822e1ecda
https://github.com/medialab/artoo/blob/89fe334cb2c2ec38b16012edfab2977822e1ecda/src/artoo.helpers.js#L318-L321