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
44,100
Wozacosta/classificator
lib/classificator.js
Naivebayes
function Naivebayes(options) { // set options object this.options = {}; if (typeof options !== 'undefined') { if (!options || typeof options !== 'object' || Array.isArray(options)) { throw TypeError( `NaiveBayes got invalid 'options': ${options}'. Pass in an object.` ); } this.options = options; } this.tokenizer = this.options.tokenizer || defaultTokenizer; this.alpha = this.options.alpha || DEFAULT_ALPHA; this.fitPrior = this.options.fitPrior === undefined ? DEFAULT_FIT_PRIOR : this.options.fitPrior; // initialize our vocabulary and its size this.vocabulary = {}; this.vocabularySize = 0; // number of documents we have learned from this.totalDocuments = 0; // document frequency table for each of our categories //= > for each category, how often were documents mapped to it this.docCount = {}; // for each category, how many words total were mapped to it this.wordCount = {}; // word frequency table for each category //= > for each category, how frequent was a given word mapped to it this.wordFrequencyCount = {}; // hashmap of our category names this.categories = {}; }
javascript
function Naivebayes(options) { // set options object this.options = {}; if (typeof options !== 'undefined') { if (!options || typeof options !== 'object' || Array.isArray(options)) { throw TypeError( `NaiveBayes got invalid 'options': ${options}'. Pass in an object.` ); } this.options = options; } this.tokenizer = this.options.tokenizer || defaultTokenizer; this.alpha = this.options.alpha || DEFAULT_ALPHA; this.fitPrior = this.options.fitPrior === undefined ? DEFAULT_FIT_PRIOR : this.options.fitPrior; // initialize our vocabulary and its size this.vocabulary = {}; this.vocabularySize = 0; // number of documents we have learned from this.totalDocuments = 0; // document frequency table for each of our categories //= > for each category, how often were documents mapped to it this.docCount = {}; // for each category, how many words total were mapped to it this.wordCount = {}; // word frequency table for each category //= > for each category, how frequent was a given word mapped to it this.wordFrequencyCount = {}; // hashmap of our category names this.categories = {}; }
[ "function", "Naivebayes", "(", "options", ")", "{", "// set options object", "this", ".", "options", "=", "{", "}", ";", "if", "(", "typeof", "options", "!==", "'undefined'", ")", "{", "if", "(", "!", "options", "||", "typeof", "options", "!==", "'object'", "||", "Array", ".", "isArray", "(", "options", ")", ")", "{", "throw", "TypeError", "(", "`", "${", "options", "}", "`", ")", ";", "}", "this", ".", "options", "=", "options", ";", "}", "this", ".", "tokenizer", "=", "this", ".", "options", ".", "tokenizer", "||", "defaultTokenizer", ";", "this", ".", "alpha", "=", "this", ".", "options", ".", "alpha", "||", "DEFAULT_ALPHA", ";", "this", ".", "fitPrior", "=", "this", ".", "options", ".", "fitPrior", "===", "undefined", "?", "DEFAULT_FIT_PRIOR", ":", "this", ".", "options", ".", "fitPrior", ";", "// initialize our vocabulary and its size", "this", ".", "vocabulary", "=", "{", "}", ";", "this", ".", "vocabularySize", "=", "0", ";", "// number of documents we have learned from", "this", ".", "totalDocuments", "=", "0", ";", "// document frequency table for each of our categories", "//= > for each category, how often were documents mapped to it", "this", ".", "docCount", "=", "{", "}", ";", "// for each category, how many words total were mapped to it", "this", ".", "wordCount", "=", "{", "}", ";", "// word frequency table for each category", "//= > for each category, how frequent was a given word mapped to it", "this", ".", "wordFrequencyCount", "=", "{", "}", ";", "// hashmap of our category names", "this", ".", "categories", "=", "{", "}", ";", "}" ]
Naive-Bayes Classifier This is a naive-bayes classifier that uses Laplace Smoothing. Takes an (optional) options object containing: - `tokenizer` => custom tokenization function
[ "Naive", "-", "Bayes", "Classifier" ]
39cc8883dd18474c72e161bc6698888ba8b867e4
https://github.com/Wozacosta/classificator/blob/39cc8883dd18474c72e161bc6698888ba8b867e4/lib/classificator.js#L97-L132
44,101
rcasto/adaptive-html
turndown/adaptivecard-rules.js
function (listItemContainers, node) { var isOrdered = node.nodeName === 'OL'; var startIndex = parseInt(node.getAttribute('start'), 10) || 1; // only applicable to ordered lists var blocks = (listItemContainers || []).map((listItemContainer, listItemIndex) => { var listItemElems = unwrap(listItemContainer); var firstListItemElem = listItemElems[0]; if (firstListItemElem && isTextBlock(firstListItemElem)) { let firstListItemPrefix = isOrdered ? `${startIndex + listItemIndex}. ` : `- `; firstListItemElem.text = firstListItemPrefix + firstListItemElem.text; } return listItemElems; }).reduce((prevBlocks, listItemBlocks) => { return prevBlocks.concat(listItemBlocks); }, []); return wrap(blocks); }
javascript
function (listItemContainers, node) { var isOrdered = node.nodeName === 'OL'; var startIndex = parseInt(node.getAttribute('start'), 10) || 1; // only applicable to ordered lists var blocks = (listItemContainers || []).map((listItemContainer, listItemIndex) => { var listItemElems = unwrap(listItemContainer); var firstListItemElem = listItemElems[0]; if (firstListItemElem && isTextBlock(firstListItemElem)) { let firstListItemPrefix = isOrdered ? `${startIndex + listItemIndex}. ` : `- `; firstListItemElem.text = firstListItemPrefix + firstListItemElem.text; } return listItemElems; }).reduce((prevBlocks, listItemBlocks) => { return prevBlocks.concat(listItemBlocks); }, []); return wrap(blocks); }
[ "function", "(", "listItemContainers", ",", "node", ")", "{", "var", "isOrdered", "=", "node", ".", "nodeName", "===", "'OL'", ";", "var", "startIndex", "=", "parseInt", "(", "node", ".", "getAttribute", "(", "'start'", ")", ",", "10", ")", "||", "1", ";", "// only applicable to ordered lists", "var", "blocks", "=", "(", "listItemContainers", "||", "[", "]", ")", ".", "map", "(", "(", "listItemContainer", ",", "listItemIndex", ")", "=>", "{", "var", "listItemElems", "=", "unwrap", "(", "listItemContainer", ")", ";", "var", "firstListItemElem", "=", "listItemElems", "[", "0", "]", ";", "if", "(", "firstListItemElem", "&&", "isTextBlock", "(", "firstListItemElem", ")", ")", "{", "let", "firstListItemPrefix", "=", "isOrdered", "?", "`", "${", "startIndex", "+", "listItemIndex", "}", "`", ":", "`", "`", ";", "firstListItemElem", ".", "text", "=", "firstListItemPrefix", "+", "firstListItemElem", ".", "text", ";", "}", "return", "listItemElems", ";", "}", ")", ".", "reduce", "(", "(", "prevBlocks", ",", "listItemBlocks", ")", "=>", "{", "return", "prevBlocks", ".", "concat", "(", "listItemBlocks", ")", ";", "}", ",", "[", "]", ")", ";", "return", "wrap", "(", "blocks", ")", ";", "}" ]
content = array of listitem containers
[ "content", "=", "array", "of", "listitem", "containers" ]
79586cebfd0e34f31418c9cbd186ad568652c3ca
https://github.com/rcasto/adaptive-html/blob/79586cebfd0e34f31418c9cbd186ad568652c3ca/turndown/adaptivecard-rules.js#L77-L92
44,102
jsguy/mithril.bindings
dist/version/mithril.bindings-0.0.1.js
function(name, eve){ // Bi-directional binding of value m.addBinding(name, function(prop) { if (typeof prop == "function") { this.value = prop(); this[eve] = m.withAttr("value", prop); } else { this.value = prop; } }, true); }
javascript
function(name, eve){ // Bi-directional binding of value m.addBinding(name, function(prop) { if (typeof prop == "function") { this.value = prop(); this[eve] = m.withAttr("value", prop); } else { this.value = prop; } }, true); }
[ "function", "(", "name", ",", "eve", ")", "{", "//\tBi-directional binding of value", "m", ".", "addBinding", "(", "name", ",", "function", "(", "prop", ")", "{", "if", "(", "typeof", "prop", "==", "\"function\"", ")", "{", "this", ".", "value", "=", "prop", "(", ")", ";", "this", "[", "eve", "]", "=", "m", ".", "withAttr", "(", "\"value\"", ",", "prop", ")", ";", "}", "else", "{", "this", ".", "value", "=", "prop", ";", "}", "}", ",", "true", ")", ";", "}" ]
Add value bindings for various event types
[ "Add", "value", "bindings", "for", "various", "event", "types" ]
4ba83da49cea2309929058fd31866df2651ec6a1
https://github.com/jsguy/mithril.bindings/blob/4ba83da49cea2309929058fd31866df2651ec6a1/dist/version/mithril.bindings-0.0.1.js#L165-L175
44,103
kmalakoff/knockback-navigators
examples/vendor/xui-2.3.2.js
getTag
function getTag(el) { return (el.firstChild === null) ? {'UL':'LI','DL':'DT','TR':'TD'}[el.tagName] || el.tagName : el.firstChild.tagName; }
javascript
function getTag(el) { return (el.firstChild === null) ? {'UL':'LI','DL':'DT','TR':'TD'}[el.tagName] || el.tagName : el.firstChild.tagName; }
[ "function", "getTag", "(", "el", ")", "{", "return", "(", "el", ".", "firstChild", "===", "null", ")", "?", "{", "'UL'", ":", "'LI'", ",", "'DL'", ":", "'DT'", ",", "'TR'", ":", "'TD'", "}", "[", "el", ".", "tagName", "]", "||", "el", ".", "tagName", ":", "el", ".", "firstChild", ".", "tagName", ";", "}" ]
private method for finding a dom element
[ "private", "method", "for", "finding", "a", "dom", "element" ]
6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125
https://github.com/kmalakoff/knockback-navigators/blob/6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125/examples/vendor/xui-2.3.2.js#L578-L580
44,104
kmalakoff/knockback-navigators
examples/vendor/xui-2.3.2.js
wrap
function wrap(xhtml, tag) { var e = document.createElement('div'); e.innerHTML = xhtml; return e; }
javascript
function wrap(xhtml, tag) { var e = document.createElement('div'); e.innerHTML = xhtml; return e; }
[ "function", "wrap", "(", "xhtml", ",", "tag", ")", "{", "var", "e", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "e", ".", "innerHTML", "=", "xhtml", ";", "return", "e", ";", "}" ]
private method Wraps the HTML in a TAG, Tag is optional If the html starts with a Tag, it will wrap the context in that tag.
[ "private", "method", "Wraps", "the", "HTML", "in", "a", "TAG", "Tag", "is", "optional", "If", "the", "html", "starts", "with", "a", "Tag", "it", "will", "wrap", "the", "context", "in", "that", "tag", "." ]
6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125
https://github.com/kmalakoff/knockback-navigators/blob/6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125/examples/vendor/xui-2.3.2.js#L590-L594
44,105
kmalakoff/knockback-navigators
examples/vendor/xui-2.3.2.js
function(o) { var options = {}; "duration after easing".split(' ').forEach( function(p) { if (props[p]) { options[p] = props[p]; delete props[p]; } }); return options; }
javascript
function(o) { var options = {}; "duration after easing".split(' ').forEach( function(p) { if (props[p]) { options[p] = props[p]; delete props[p]; } }); return options; }
[ "function", "(", "o", ")", "{", "var", "options", "=", "{", "}", ";", "\"duration after easing\"", ".", "split", "(", "' '", ")", ".", "forEach", "(", "function", "(", "p", ")", "{", "if", "(", "props", "[", "p", "]", ")", "{", "options", "[", "p", "]", "=", "props", "[", "p", "]", ";", "delete", "props", "[", "p", "]", ";", "}", "}", ")", ";", "return", "options", ";", "}" ]
creates an options obj for emile
[ "creates", "an", "options", "obj", "for", "emile" ]
6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125
https://github.com/kmalakoff/knockback-navigators/blob/6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125/examples/vendor/xui-2.3.2.js#L934-L943
44,106
kmalakoff/knockback-navigators
examples/vendor/xui-2.3.2.js
function(props) { var serialisedProps = [], key; if (typeof props != string) { for (key in props) { serialisedProps.push(cssstyle(key) + ':' + props[key]); } serialisedProps = serialisedProps.join(';'); } else { serialisedProps = props; } return serialisedProps; }
javascript
function(props) { var serialisedProps = [], key; if (typeof props != string) { for (key in props) { serialisedProps.push(cssstyle(key) + ':' + props[key]); } serialisedProps = serialisedProps.join(';'); } else { serialisedProps = props; } return serialisedProps; }
[ "function", "(", "props", ")", "{", "var", "serialisedProps", "=", "[", "]", ",", "key", ";", "if", "(", "typeof", "props", "!=", "string", ")", "{", "for", "(", "key", "in", "props", ")", "{", "serialisedProps", ".", "push", "(", "cssstyle", "(", "key", ")", "+", "':'", "+", "props", "[", "key", "]", ")", ";", "}", "serialisedProps", "=", "serialisedProps", ".", "join", "(", "';'", ")", ";", "}", "else", "{", "serialisedProps", "=", "props", ";", "}", "return", "serialisedProps", ";", "}" ]
serialize the properties into a string for emile
[ "serialize", "the", "properties", "into", "a", "string", "for", "emile" ]
6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125
https://github.com/kmalakoff/knockback-navigators/blob/6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125/examples/vendor/xui-2.3.2.js#L946-L957
44,107
royaltm/kafka-tools
lib/config.js
checkMax
function checkMax(value, max) { if (max) { if (max.charAt(0) === '-') { if (value.charAt(0) !== '-') return false; return checkMax(max.substr(1), value.substr(1)); } else { if (value.charAt(0) === '-') return true; } var len = Math.max(value.length, max.length); max = left0pad(max, len); value = left0pad(value, len); return value <= max; } return true; }
javascript
function checkMax(value, max) { if (max) { if (max.charAt(0) === '-') { if (value.charAt(0) !== '-') return false; return checkMax(max.substr(1), value.substr(1)); } else { if (value.charAt(0) === '-') return true; } var len = Math.max(value.length, max.length); max = left0pad(max, len); value = left0pad(value, len); return value <= max; } return true; }
[ "function", "checkMax", "(", "value", ",", "max", ")", "{", "if", "(", "max", ")", "{", "if", "(", "max", ".", "charAt", "(", "0", ")", "===", "'-'", ")", "{", "if", "(", "value", ".", "charAt", "(", "0", ")", "!==", "'-'", ")", "return", "false", ";", "return", "checkMax", "(", "max", ".", "substr", "(", "1", ")", ",", "value", ".", "substr", "(", "1", ")", ")", ";", "}", "else", "{", "if", "(", "value", ".", "charAt", "(", "0", ")", "===", "'-'", ")", "return", "true", ";", "}", "var", "len", "=", "Math", ".", "max", "(", "value", ".", "length", ",", "max", ".", "length", ")", ";", "max", "=", "left0pad", "(", "max", ",", "len", ")", ";", "value", "=", "left0pad", "(", "value", ",", "len", ")", ";", "return", "value", "<=", "max", ";", "}", "return", "true", ";", "}" ]
max must be a 0 or positive number string
[ "max", "must", "be", "a", "0", "or", "positive", "number", "string" ]
a8718fcc3cc5bc06e9974665344a815b7a9e2a56
https://github.com/royaltm/kafka-tools/blob/a8718fcc3cc5bc06e9974665344a815b7a9e2a56/lib/config.js#L59-L75
44,108
royaltm/kafka-tools
lib/zookeeper.js
writeTopicConfig
function writeTopicConfig(client, topic, configs, callback) { debug('writeTopicConfig: "%s", %j', topic, configs); updateEntityConfig(client, getTopicConfigPath(topic), configs, callback); }
javascript
function writeTopicConfig(client, topic, configs, callback) { debug('writeTopicConfig: "%s", %j', topic, configs); updateEntityConfig(client, getTopicConfigPath(topic), configs, callback); }
[ "function", "writeTopicConfig", "(", "client", ",", "topic", ",", "configs", ",", "callback", ")", "{", "debug", "(", "'writeTopicConfig: \"%s\", %j'", ",", "topic", ",", "configs", ")", ";", "updateEntityConfig", "(", "client", ",", "getTopicConfigPath", "(", "topic", ")", ",", "configs", ",", "callback", ")", ";", "}" ]
Write out the topic config to zk, if there is any @param {ZkClient} client @param {String} topic @param {Object} configs @param {Function} callback
[ "Write", "out", "the", "topic", "config", "to", "zk", "if", "there", "is", "any" ]
a8718fcc3cc5bc06e9974665344a815b7a9e2a56
https://github.com/royaltm/kafka-tools/blob/a8718fcc3cc5bc06e9974665344a815b7a9e2a56/lib/zookeeper.js#L356-L359
44,109
royaltm/kafka-tools
lib/zookeeper.js
writeClientConfig
function writeClientConfig(client, clientId, configs, callback) { debug('writeClientConfig: "%s", %j', clientId, configs); updateEntityConfig(client, getClientConfigPath(clientId), configs, callback); }
javascript
function writeClientConfig(client, clientId, configs, callback) { debug('writeClientConfig: "%s", %j', clientId, configs); updateEntityConfig(client, getClientConfigPath(clientId), configs, callback); }
[ "function", "writeClientConfig", "(", "client", ",", "clientId", ",", "configs", ",", "callback", ")", "{", "debug", "(", "'writeClientConfig: \"%s\", %j'", ",", "clientId", ",", "configs", ")", ";", "updateEntityConfig", "(", "client", ",", "getClientConfigPath", "(", "clientId", ")", ",", "configs", ",", "callback", ")", ";", "}" ]
Write out the client config to zk, if there is any @param {ZkClient} client @param {String} clientId @param {Object} configs @param {Function} callback
[ "Write", "out", "the", "client", "config", "to", "zk", "if", "there", "is", "any" ]
a8718fcc3cc5bc06e9974665344a815b7a9e2a56
https://github.com/royaltm/kafka-tools/blob/a8718fcc3cc5bc06e9974665344a815b7a9e2a56/lib/zookeeper.js#L369-L372
44,110
royaltm/kafka-tools
lib/zookeeper.js
createParentPath
function createParentPath(client, path, callback) { var parentDir = path.substring(0, path.lastIndexOf('/')); debug('createParentPath: "%s"', parentDir); if (parentDir.length != 0) { client.create(parentDir, function(err) { if (err) { if (err.code === NO_NODE) { return createParentPath(client, parentDir, function(err) { if (err) return callback(err); createParentPath(client, path, callback); }); } else if (err.code !== NODE_EXISTS) return callback(err); } callback(null, path); }); } else callback(null, path); }
javascript
function createParentPath(client, path, callback) { var parentDir = path.substring(0, path.lastIndexOf('/')); debug('createParentPath: "%s"', parentDir); if (parentDir.length != 0) { client.create(parentDir, function(err) { if (err) { if (err.code === NO_NODE) { return createParentPath(client, parentDir, function(err) { if (err) return callback(err); createParentPath(client, path, callback); }); } else if (err.code !== NODE_EXISTS) return callback(err); } callback(null, path); }); } else callback(null, path); }
[ "function", "createParentPath", "(", "client", ",", "path", ",", "callback", ")", "{", "var", "parentDir", "=", "path", ".", "substring", "(", "0", ",", "path", ".", "lastIndexOf", "(", "'/'", ")", ")", ";", "debug", "(", "'createParentPath: \"%s\"'", ",", "parentDir", ")", ";", "if", "(", "parentDir", ".", "length", "!=", "0", ")", "{", "client", ".", "create", "(", "parentDir", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "===", "NO_NODE", ")", "{", "return", "createParentPath", "(", "client", ",", "parentDir", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "createParentPath", "(", "client", ",", "path", ",", "callback", ")", ";", "}", ")", ";", "}", "else", "if", "(", "err", ".", "code", "!==", "NODE_EXISTS", ")", "return", "callback", "(", "err", ")", ";", "}", "callback", "(", "null", ",", "path", ")", ";", "}", ")", ";", "}", "else", "callback", "(", "null", ",", "path", ")", ";", "}" ]
Create the parent path @param {ZkClient} client @param {String} path @param {Function} callback
[ "Create", "the", "parent", "path" ]
a8718fcc3cc5bc06e9974665344a815b7a9e2a56
https://github.com/royaltm/kafka-tools/blob/a8718fcc3cc5bc06e9974665344a815b7a9e2a56/lib/zookeeper.js#L387-L408
44,111
royaltm/kafka-tools
lib/zookeeper.js
createPersistentPath
function createPersistentPath(client, path, data, callback) { debug('createPersistentPath: "%s" "%s"', path, data); data = ensureBuffer(data); client.create(path, data, function(err) { if (err) { if (err.code !== NO_NODE) return callback(err); createParentPath(client, path, function(err) { if (err) return callback(err); client.create(path, data, callback); }); } else callback(null, path); }) }
javascript
function createPersistentPath(client, path, data, callback) { debug('createPersistentPath: "%s" "%s"', path, data); data = ensureBuffer(data); client.create(path, data, function(err) { if (err) { if (err.code !== NO_NODE) return callback(err); createParentPath(client, path, function(err) { if (err) return callback(err); client.create(path, data, callback); }); } else callback(null, path); }) }
[ "function", "createPersistentPath", "(", "client", ",", "path", ",", "data", ",", "callback", ")", "{", "debug", "(", "'createPersistentPath: \"%s\" \"%s\"'", ",", "path", ",", "data", ")", ";", "data", "=", "ensureBuffer", "(", "data", ")", ";", "client", ".", "create", "(", "path", ",", "data", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "!==", "NO_NODE", ")", "return", "callback", "(", "err", ")", ";", "createParentPath", "(", "client", ",", "path", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "client", ".", "create", "(", "path", ",", "data", ",", "callback", ")", ";", "}", ")", ";", "}", "else", "callback", "(", "null", ",", "path", ")", ";", "}", ")", "}" ]
Create an persistent node with the given path and data. Create parents if necessary. @param {ZkClient} client @param {String} path @param {String|Buffer} data @param {Function} callback
[ "Create", "an", "persistent", "node", "with", "the", "given", "path", "and", "data", ".", "Create", "parents", "if", "necessary", "." ]
a8718fcc3cc5bc06e9974665344a815b7a9e2a56
https://github.com/royaltm/kafka-tools/blob/a8718fcc3cc5bc06e9974665344a815b7a9e2a56/lib/zookeeper.js#L418-L436
44,112
royaltm/kafka-tools
lib/zookeeper.js
updatePersistentPath
function updatePersistentPath(client, path, data, callback) { debug('updatePersistentPath: "%s" "%s"', path, data); data = ensureBuffer(data); client.setData(path, data, function (err) { if (err) { if (err.code !== NO_NODE) return callback(err); createParentPath(client, path, function(err) { if (err) return callback(err); client.create(path, data, function(err) { if (err) { if (err.code !== NODE_EXISTS) return callback(err); client.setData(path, data, callback); } else callback(null); }); }); } else callback(null); }); }
javascript
function updatePersistentPath(client, path, data, callback) { debug('updatePersistentPath: "%s" "%s"', path, data); data = ensureBuffer(data); client.setData(path, data, function (err) { if (err) { if (err.code !== NO_NODE) return callback(err); createParentPath(client, path, function(err) { if (err) return callback(err); client.create(path, data, function(err) { if (err) { if (err.code !== NODE_EXISTS) return callback(err); client.setData(path, data, callback); } else callback(null); }); }); } else callback(null); }); }
[ "function", "updatePersistentPath", "(", "client", ",", "path", ",", "data", ",", "callback", ")", "{", "debug", "(", "'updatePersistentPath: \"%s\" \"%s\"'", ",", "path", ",", "data", ")", ";", "data", "=", "ensureBuffer", "(", "data", ")", ";", "client", ".", "setData", "(", "path", ",", "data", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "!==", "NO_NODE", ")", "return", "callback", "(", "err", ")", ";", "createParentPath", "(", "client", ",", "path", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "client", ".", "create", "(", "path", ",", "data", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "!==", "NODE_EXISTS", ")", "return", "callback", "(", "err", ")", ";", "client", ".", "setData", "(", "path", ",", "data", ",", "callback", ")", ";", "}", "else", "callback", "(", "null", ")", ";", "}", ")", ";", "}", ")", ";", "}", "else", "callback", "(", "null", ")", ";", "}", ")", ";", "}" ]
Update the value of a persistent node with the given path and data. create parrent directory if necessary. Never return NO_NODE error. @param {ZkClient} client @param {String} path @param {String|Buffer} data @param {Function} callback
[ "Update", "the", "value", "of", "a", "persistent", "node", "with", "the", "given", "path", "and", "data", ".", "create", "parrent", "directory", "if", "necessary", ".", "Never", "return", "NO_NODE", "error", "." ]
a8718fcc3cc5bc06e9974665344a815b7a9e2a56
https://github.com/royaltm/kafka-tools/blob/a8718fcc3cc5bc06e9974665344a815b7a9e2a56/lib/zookeeper.js#L446-L471
44,113
arqex/fluxify
src/xDispatcher.js
function( id, callback ){ var ID = id; // If the callback is the first parameter if( typeof id == 'function' ){ ID = 'ID_' + this._ID; callback = id; } this._callbacks[ID] = callback; this._ID++; return ID; }
javascript
function( id, callback ){ var ID = id; // If the callback is the first parameter if( typeof id == 'function' ){ ID = 'ID_' + this._ID; callback = id; } this._callbacks[ID] = callback; this._ID++; return ID; }
[ "function", "(", "id", ",", "callback", ")", "{", "var", "ID", "=", "id", ";", "// If the callback is the first parameter", "if", "(", "typeof", "id", "==", "'function'", ")", "{", "ID", "=", "'ID_'", "+", "this", ".", "_ID", ";", "callback", "=", "id", ";", "}", "this", ".", "_callbacks", "[", "ID", "]", "=", "callback", ";", "this", ".", "_ID", "++", ";", "return", "ID", ";", "}" ]
Register a callback that will be called when an action is dispatched. @param {String | Function} id If a string is passed, it will be the id of the callback. If a function is passed, it will be used as callback, and id is generated automatically. @param {Function} callback If an id is passed as a first argument, this will be the callback. @return {String} The id of the callback to be used with the waitFor method.
[ "Register", "a", "callback", "that", "will", "be", "called", "when", "an", "action", "is", "dispatched", "." ]
8915033a150ce86f851efdf114886e9adcbb5eed
https://github.com/arqex/fluxify/blob/8915033a150ce86f851efdf114886e9adcbb5eed/src/xDispatcher.js#L34-L47
44,114
arqex/fluxify
src/xDispatcher.js
function( id, xStore ){ Object.defineProperty(xStore, '_dispatcher', { value: this }); return this.register( id, xStore.callback ); }
javascript
function( id, xStore ){ Object.defineProperty(xStore, '_dispatcher', { value: this }); return this.register( id, xStore.callback ); }
[ "function", "(", "id", ",", "xStore", ")", "{", "Object", ".", "defineProperty", "(", "xStore", ",", "'_dispatcher'", ",", "{", "value", ":", "this", "}", ")", ";", "return", "this", ".", "register", "(", "id", ",", "xStore", ".", "callback", ")", ";", "}" ]
Register a XStore in the dispacher. XStores has a method called callback. The dispatcher register that function as a regular callback. @param {String} id The id for the store to be used in the waitFor method. @param {XStore} xStore Store to register in the dispatcher @return {String} The id of the callback to be used with the waitFor method.
[ "Register", "a", "XStore", "in", "the", "dispacher", ".", "XStores", "has", "a", "method", "called", "callback", ".", "The", "dispatcher", "register", "that", "function", "as", "a", "regular", "callback", "." ]
8915033a150ce86f851efdf114886e9adcbb5eed
https://github.com/arqex/fluxify/blob/8915033a150ce86f851efdf114886e9adcbb5eed/src/xDispatcher.js#L57-L64
44,115
arqex/fluxify
src/xDispatcher.js
function( ids ) { var promises = [], i = 0 ; if( !Array.isArray( ids ) ) ids = [ ids ]; for(; i<ids.length; i++ ){ if( this._promises[ ids[i] ] ) promises.push( this._promises[ ids[i] ] ); } if( !promises.length ) return this._Promise.resolve(); return this._Promise.all( promises ); }
javascript
function( ids ) { var promises = [], i = 0 ; if( !Array.isArray( ids ) ) ids = [ ids ]; for(; i<ids.length; i++ ){ if( this._promises[ ids[i] ] ) promises.push( this._promises[ ids[i] ] ); } if( !promises.length ) return this._Promise.resolve(); return this._Promise.all( promises ); }
[ "function", "(", "ids", ")", "{", "var", "promises", "=", "[", "]", ",", "i", "=", "0", ";", "if", "(", "!", "Array", ".", "isArray", "(", "ids", ")", ")", "ids", "=", "[", "ids", "]", ";", "for", "(", ";", "i", "<", "ids", ".", "length", ";", "i", "++", ")", "{", "if", "(", "this", ".", "_promises", "[", "ids", "[", "i", "]", "]", ")", "promises", ".", "push", "(", "this", ".", "_promises", "[", "ids", "[", "i", "]", "]", ")", ";", "}", "if", "(", "!", "promises", ".", "length", ")", "return", "this", ".", "_Promise", ".", "resolve", "(", ")", ";", "return", "this", ".", "_Promise", ".", "all", "(", "promises", ")", ";", "}" ]
Creates a promise and waits for the callbacks specified to complete before resolve it. If it is used by an actionCallback, the promise should be resolved to let other callbacks wait for it if needed. Be careful of not to wait by a callback that is waiting by the current callback, or the promises will never fulfill. @param {String<Array>|String} ids The id or ids of the callbacks/stores to wait for. @return {Promise} A promise to be resolved when the specified callbacks are completed.
[ "Creates", "a", "promise", "and", "waits", "for", "the", "callbacks", "specified", "to", "complete", "before", "resolve", "it", ".", "If", "it", "is", "used", "by", "an", "actionCallback", "the", "promise", "should", "be", "resolved", "to", "let", "other", "callbacks", "wait", "for", "it", "if", "needed", "." ]
8915033a150ce86f851efdf114886e9adcbb5eed
https://github.com/arqex/fluxify/blob/8915033a150ce86f851efdf114886e9adcbb5eed/src/xDispatcher.js#L87-L104
44,116
arqex/fluxify
src/xDispatcher.js
function(){ var me = this, dispatchArguments = arguments, promises = [] ; this._promises = []; // A closure is needed for the callback id Object.keys( this._callbacks ).forEach( function( id ){ // All the promises must be set in me._promises before trying to resolve // in order to make waitFor work ok me._promises[ id ] = me._Promise.resolve() .then( function(){ return me._callbacks[ id ].apply( me, dispatchArguments ); }) .catch( function( err ){ console.error( err.stack || err ); }) ; promises.push( me._promises[ id ] ); }); // var dequeue = function(){ me._dispatchQueue.shift(); if( !me._dispatchQueue.length ) me._currentDispatch = false; }; return this._Promise.all( promises ) .then( dequeue, dequeue ) ; }
javascript
function(){ var me = this, dispatchArguments = arguments, promises = [] ; this._promises = []; // A closure is needed for the callback id Object.keys( this._callbacks ).forEach( function( id ){ // All the promises must be set in me._promises before trying to resolve // in order to make waitFor work ok me._promises[ id ] = me._Promise.resolve() .then( function(){ return me._callbacks[ id ].apply( me, dispatchArguments ); }) .catch( function( err ){ console.error( err.stack || err ); }) ; promises.push( me._promises[ id ] ); }); // var dequeue = function(){ me._dispatchQueue.shift(); if( !me._dispatchQueue.length ) me._currentDispatch = false; }; return this._Promise.all( promises ) .then( dequeue, dequeue ) ; }
[ "function", "(", ")", "{", "var", "me", "=", "this", ",", "dispatchArguments", "=", "arguments", ",", "promises", "=", "[", "]", ";", "this", ".", "_promises", "=", "[", "]", ";", "// A closure is needed for the callback id", "Object", ".", "keys", "(", "this", ".", "_callbacks", ")", ".", "forEach", "(", "function", "(", "id", ")", "{", "// All the promises must be set in me._promises before trying to resolve", "// in order to make waitFor work ok", "me", ".", "_promises", "[", "id", "]", "=", "me", ".", "_Promise", ".", "resolve", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "me", ".", "_callbacks", "[", "id", "]", ".", "apply", "(", "me", ",", "dispatchArguments", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "console", ".", "error", "(", "err", ".", "stack", "||", "err", ")", ";", "}", ")", ";", "promises", ".", "push", "(", "me", ".", "_promises", "[", "id", "]", ")", ";", "}", ")", ";", "//", "var", "dequeue", "=", "function", "(", ")", "{", "me", ".", "_dispatchQueue", ".", "shift", "(", ")", ";", "if", "(", "!", "me", ".", "_dispatchQueue", ".", "length", ")", "me", ".", "_currentDispatch", "=", "false", ";", "}", ";", "return", "this", ".", "_Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "dequeue", ",", "dequeue", ")", ";", "}" ]
Dispatches an action inmediatelly. @return {Promise} A promise to be resolved when all the callbacks have finised.
[ "Dispatches", "an", "action", "inmediatelly", "." ]
8915033a150ce86f851efdf114886e9adcbb5eed
https://github.com/arqex/fluxify/blob/8915033a150ce86f851efdf114886e9adcbb5eed/src/xDispatcher.js#L144-L179
44,117
sasaplus1/ipc-promise
ipc-promise.js
commonEventHandler
function commonEventHandler(event, arg) { // NOTE: send from renderer process always. var successEventName = getSuccessEventName(arg.eventName, arg.id); var failureEventName = getFailureEventName(arg.eventName, arg.id); var onSuccess = function(result) { // send success to ipc for renderer process. event.sender.send(COMMON_SUCCESS_EVENT_NAME, { data: result, eventName: arg.eventName, id: arg.id }); cee.removeListener(successEventName, onSuccess); cee.removeListener(failureEventName, onFailure); }; var onFailure = function(result) { // send failure to ipc for renderer process. event.sender.send(COMMON_FAILURE_EVENT_NAME, { data: result, eventName: arg.eventName, id: arg.id }); cee.removeListener(successEventName, onSuccess); cee.removeListener(failureEventName, onFailure); }; // add listener to common event emitter for main process. cee.on(successEventName, onSuccess); cee.on(failureEventName, onFailure); // emit to common event emitter for main process. cee.emit(arg.eventName, arg.id, arg.data, event); }
javascript
function commonEventHandler(event, arg) { // NOTE: send from renderer process always. var successEventName = getSuccessEventName(arg.eventName, arg.id); var failureEventName = getFailureEventName(arg.eventName, arg.id); var onSuccess = function(result) { // send success to ipc for renderer process. event.sender.send(COMMON_SUCCESS_EVENT_NAME, { data: result, eventName: arg.eventName, id: arg.id }); cee.removeListener(successEventName, onSuccess); cee.removeListener(failureEventName, onFailure); }; var onFailure = function(result) { // send failure to ipc for renderer process. event.sender.send(COMMON_FAILURE_EVENT_NAME, { data: result, eventName: arg.eventName, id: arg.id }); cee.removeListener(successEventName, onSuccess); cee.removeListener(failureEventName, onFailure); }; // add listener to common event emitter for main process. cee.on(successEventName, onSuccess); cee.on(failureEventName, onFailure); // emit to common event emitter for main process. cee.emit(arg.eventName, arg.id, arg.data, event); }
[ "function", "commonEventHandler", "(", "event", ",", "arg", ")", "{", "// NOTE: send from renderer process always.", "var", "successEventName", "=", "getSuccessEventName", "(", "arg", ".", "eventName", ",", "arg", ".", "id", ")", ";", "var", "failureEventName", "=", "getFailureEventName", "(", "arg", ".", "eventName", ",", "arg", ".", "id", ")", ";", "var", "onSuccess", "=", "function", "(", "result", ")", "{", "// send success to ipc for renderer process.", "event", ".", "sender", ".", "send", "(", "COMMON_SUCCESS_EVENT_NAME", ",", "{", "data", ":", "result", ",", "eventName", ":", "arg", ".", "eventName", ",", "id", ":", "arg", ".", "id", "}", ")", ";", "cee", ".", "removeListener", "(", "successEventName", ",", "onSuccess", ")", ";", "cee", ".", "removeListener", "(", "failureEventName", ",", "onFailure", ")", ";", "}", ";", "var", "onFailure", "=", "function", "(", "result", ")", "{", "// send failure to ipc for renderer process.", "event", ".", "sender", ".", "send", "(", "COMMON_FAILURE_EVENT_NAME", ",", "{", "data", ":", "result", ",", "eventName", ":", "arg", ".", "eventName", ",", "id", ":", "arg", ".", "id", "}", ")", ";", "cee", ".", "removeListener", "(", "successEventName", ",", "onSuccess", ")", ";", "cee", ".", "removeListener", "(", "failureEventName", ",", "onFailure", ")", ";", "}", ";", "// add listener to common event emitter for main process.", "cee", ".", "on", "(", "successEventName", ",", "onSuccess", ")", ";", "cee", ".", "on", "(", "failureEventName", ",", "onFailure", ")", ";", "// emit to common event emitter for main process.", "cee", ".", "emit", "(", "arg", ".", "eventName", ",", "arg", ".", "id", ",", "arg", ".", "data", ",", "event", ")", ";", "}" ]
common event handler for ipc. @private @param {Event} event event object. @param {Object} arg argument object.
[ "common", "event", "handler", "for", "ipc", "." ]
6b20756bc604a2fc2ca0f4bcfd1267621d216176
https://github.com/sasaplus1/ipc-promise/blob/6b20756bc604a2fc2ca0f4bcfd1267621d216176/ipc-promise.js#L56-L88
44,118
sasaplus1/ipc-promise
ipc-promise.js
on
function on(event, listener) { // call from main process always. // add listener to common event emitter for main process. cee.on(event, function(id, data, ipcEvent) { listener(data, ipcEvent) .then(function(result) { cee.emit(getSuccessEventName(event, id), result); }) .catch(function(result) { cee.emit(getFailureEventName(event, id), result); }); }); }
javascript
function on(event, listener) { // call from main process always. // add listener to common event emitter for main process. cee.on(event, function(id, data, ipcEvent) { listener(data, ipcEvent) .then(function(result) { cee.emit(getSuccessEventName(event, id), result); }) .catch(function(result) { cee.emit(getFailureEventName(event, id), result); }); }); }
[ "function", "on", "(", "event", ",", "listener", ")", "{", "// call from main process always.", "// add listener to common event emitter for main process.", "cee", ".", "on", "(", "event", ",", "function", "(", "id", ",", "data", ",", "ipcEvent", ")", "{", "listener", "(", "data", ",", "ipcEvent", ")", ".", "then", "(", "function", "(", "result", ")", "{", "cee", ".", "emit", "(", "getSuccessEventName", "(", "event", ",", "id", ")", ",", "result", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "result", ")", "{", "cee", ".", "emit", "(", "getFailureEventName", "(", "event", ",", "id", ")", ",", "result", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
listen event. @param {String} event event name. @param {Function} listener listener function.
[ "listen", "event", "." ]
6b20756bc604a2fc2ca0f4bcfd1267621d216176
https://github.com/sasaplus1/ipc-promise/blob/6b20756bc604a2fc2ca0f4bcfd1267621d216176/ipc-promise.js#L144-L157
44,119
egoist/install-packages
lib/index.js
installPeerDependencies
async function installPeerDependencies(cwd, installDir, options) { const { data: pkg } = await joycon.load({ files: ['package.json'], cwd }) const peers = pkg.peerDependencies || {} const packages = [] for (const peer in peers) { if (!options.peerFilter || options.peerFilter(peer, peers[peer])) { packages.push(`${peer}@${peers[peer]}`) } } if (packages.length > 0) { await install( Object.assign({}, options, { packages, cwd: installDir, installPeers: false }) ) } }
javascript
async function installPeerDependencies(cwd, installDir, options) { const { data: pkg } = await joycon.load({ files: ['package.json'], cwd }) const peers = pkg.peerDependencies || {} const packages = [] for (const peer in peers) { if (!options.peerFilter || options.peerFilter(peer, peers[peer])) { packages.push(`${peer}@${peers[peer]}`) } } if (packages.length > 0) { await install( Object.assign({}, options, { packages, cwd: installDir, installPeers: false }) ) } }
[ "async", "function", "installPeerDependencies", "(", "cwd", ",", "installDir", ",", "options", ")", "{", "const", "{", "data", ":", "pkg", "}", "=", "await", "joycon", ".", "load", "(", "{", "files", ":", "[", "'package.json'", "]", ",", "cwd", "}", ")", "const", "peers", "=", "pkg", ".", "peerDependencies", "||", "{", "}", "const", "packages", "=", "[", "]", "for", "(", "const", "peer", "in", "peers", ")", "{", "if", "(", "!", "options", ".", "peerFilter", "||", "options", ".", "peerFilter", "(", "peer", ",", "peers", "[", "peer", "]", ")", ")", "{", "packages", ".", "push", "(", "`", "${", "peer", "}", "${", "peers", "[", "peer", "]", "}", "`", ")", "}", "}", "if", "(", "packages", ".", "length", ">", "0", ")", "{", "await", "install", "(", "Object", ".", "assign", "(", "{", "}", ",", "options", ",", "{", "packages", ",", "cwd", ":", "installDir", ",", "installPeers", ":", "false", "}", ")", ")", "}", "}" ]
Install peer dependencies @param {string} cwd The directory to find package.json @param {string} installDir The directory to install peer dependencies @param {*} options
[ "Install", "peer", "dependencies" ]
b69a44f15452027b4c2ad0d12c9df5dcb9295603
https://github.com/egoist/install-packages/blob/b69a44f15452027b4c2ad0d12c9df5dcb9295603/lib/index.js#L97-L119
44,120
dtex/tharp
index.js
Robot
function Robot(opts) { if (!(this instanceof Robot)) { return new Robot(opts); } this.chains = opts.chains; this.offset = opts.offset || [0, 0, 0]; if (!opts.orientation) { opts.orientation = {}; } this.orientation = { pitch: opts.orientation.pitch || 0, yaw: opts.orientation.yaw || 0, roll: opts.orientation.roll || 0 }; }
javascript
function Robot(opts) { if (!(this instanceof Robot)) { return new Robot(opts); } this.chains = opts.chains; this.offset = opts.offset || [0, 0, 0]; if (!opts.orientation) { opts.orientation = {}; } this.orientation = { pitch: opts.orientation.pitch || 0, yaw: opts.orientation.yaw || 0, roll: opts.orientation.roll || 0 }; }
[ "function", "Robot", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Robot", ")", ")", "{", "return", "new", "Robot", "(", "opts", ")", ";", "}", "this", ".", "chains", "=", "opts", ".", "chains", ";", "this", ".", "offset", "=", "opts", ".", "offset", "||", "[", "0", ",", "0", ",", "0", "]", ";", "if", "(", "!", "opts", ".", "orientation", ")", "{", "opts", ".", "orientation", "=", "{", "}", ";", "}", "this", ".", "orientation", "=", "{", "pitch", ":", "opts", ".", "orientation", ".", "pitch", "||", "0", ",", "yaw", ":", "opts", ".", "orientation", ".", "yaw", "||", "0", ",", "roll", ":", "opts", ".", "orientation", ".", "roll", "||", "0", "}", ";", "}" ]
Wrap our chains into a single object we can control @param {Object} opts Options: {chains, offset, orientation} - opts.chains {Array} An array of chains that makeup this robot - opts.robotType {String} One of the predefined robot types. - opts.offset {Array} A three element array describing an offset for the robot's origin point. This can be used to shift the robot's position relative to its origin point (picture the robot shifting it's weight along the x/z plane or stretching to be taller without moving the end effectors) - opts.orientation {Array} A three element array of Numbers giving the rotation of the robot's chassis around its origin point (make it dance! )
[ "Wrap", "our", "chains", "into", "a", "single", "object", "we", "can", "control" ]
87c0b54544e9e9f4e35275247ea551ccd29cda66
https://github.com/dtex/tharp/blob/87c0b54544e9e9f4e35275247ea551ccd29cda66/index.js#L21-L41
44,121
dtex/tharp
index.js
Chain
function Chain(opts) { if (!(this instanceof Chain)) { return new Chain(opts); } if (opts.constructor) { this.devices = new opts.constructor(opts.actuators); } else { this.devices = opts.actuators; } this.chainType = opts.chainType; this.links = opts.links; this.origin = opts.origin || [0, 0, 0]; this.position = opts.startAt || [0, 0, 0]; this.require = opts.require || true; }
javascript
function Chain(opts) { if (!(this instanceof Chain)) { return new Chain(opts); } if (opts.constructor) { this.devices = new opts.constructor(opts.actuators); } else { this.devices = opts.actuators; } this.chainType = opts.chainType; this.links = opts.links; this.origin = opts.origin || [0, 0, 0]; this.position = opts.startAt || [0, 0, 0]; this.require = opts.require || true; }
[ "function", "Chain", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Chain", ")", ")", "{", "return", "new", "Chain", "(", "opts", ")", ";", "}", "if", "(", "opts", ".", "constructor", ")", "{", "this", ".", "devices", "=", "new", "opts", ".", "constructor", "(", "opts", ".", "actuators", ")", ";", "}", "else", "{", "this", ".", "devices", "=", "opts", ".", "actuators", ";", "}", "this", ".", "chainType", "=", "opts", ".", "chainType", ";", "this", ".", "links", "=", "opts", ".", "links", ";", "this", ".", "origin", "=", "opts", ".", "origin", "||", "[", "0", ",", "0", ",", "0", "]", ";", "this", ".", "position", "=", "opts", ".", "startAt", "||", "[", "0", ",", "0", ",", "0", "]", ";", "this", ".", "require", "=", "opts", ".", "require", "||", "true", ";", "}" ]
Wrap our servos object so that we have all the info and methods we need to define and solve our the kinematic system @param {Object} opts Options: {actuators, systemType, origin, bones } - opts.actuators {Servos}: The Servos() object that contains the chain's actuators - opts.chainType {String}: One of the pre-defined chain types. Don't see your system type? Open an issue, or better yet a Pull Request! - opts.origin {Array}: A three-tuple representing the x, y and z offset of the chain's origin point from the robot's origin point. - opts.links {Object}: An array with the link lengths for our system The names vary with the systemType returns this chain
[ "Wrap", "our", "servos", "object", "so", "that", "we", "have", "all", "the", "info", "and", "methods", "we", "need", "to", "define", "and", "solve", "our", "the", "kinematic", "system" ]
87c0b54544e9e9f4e35275247ea551ccd29cda66
https://github.com/dtex/tharp/blob/87c0b54544e9e9f4e35275247ea551ccd29cda66/index.js#L90-L111
44,122
sadams/lite-url
dist/lite-url.js
splitOnFirst
function splitOnFirst(str, splitter, callback) { var parts = str.split(splitter); var first = parts.shift(); return callback(first, parts.join(splitter)); }
javascript
function splitOnFirst(str, splitter, callback) { var parts = str.split(splitter); var first = parts.shift(); return callback(first, parts.join(splitter)); }
[ "function", "splitOnFirst", "(", "str", ",", "splitter", ",", "callback", ")", "{", "var", "parts", "=", "str", ".", "split", "(", "splitter", ")", ";", "var", "first", "=", "parts", ".", "shift", "(", ")", ";", "return", "callback", "(", "first", ",", "parts", ".", "join", "(", "splitter", ")", ")", ";", "}" ]
splits a string on the first occurrence of 'splitter' and calls back with the two entries. @param {string} str @param {string} splitter @param {function} callback @return *
[ "splits", "a", "string", "on", "the", "first", "occurrence", "of", "splitter", "and", "calls", "back", "with", "the", "two", "entries", "." ]
10cb29a1b38b747629bc0f1739ea4bf60d758f8a
https://github.com/sadams/lite-url/blob/10cb29a1b38b747629bc0f1739ea4bf60d758f8a/dist/lite-url.js#L28-L32
44,123
sadams/lite-url
dist/lite-url.js
liteURL
function liteURL(str) { // We first check if we have parsed this URL before, to avoid running the // monster regex over and over (which is expensive!) var uri = memo[str]; if (typeof uri !== 'undefined') { return uri; } //parsed url uri = uriParser(str); uri.params = queryParser(uri); // Stored parsed values memo[str] = uri; return uri; }
javascript
function liteURL(str) { // We first check if we have parsed this URL before, to avoid running the // monster regex over and over (which is expensive!) var uri = memo[str]; if (typeof uri !== 'undefined') { return uri; } //parsed url uri = uriParser(str); uri.params = queryParser(uri); // Stored parsed values memo[str] = uri; return uri; }
[ "function", "liteURL", "(", "str", ")", "{", "// We first check if we have parsed this URL before, to avoid running the", "// monster regex over and over (which is expensive!)", "var", "uri", "=", "memo", "[", "str", "]", ";", "if", "(", "typeof", "uri", "!==", "'undefined'", ")", "{", "return", "uri", ";", "}", "//parsed url", "uri", "=", "uriParser", "(", "str", ")", ";", "uri", ".", "params", "=", "queryParser", "(", "uri", ")", ";", "// Stored parsed values", "memo", "[", "str", "]", "=", "uri", ";", "return", "uri", ";", "}" ]
Uri parsing method. @param {string} str @returns {{ href:string, origin:string, protocol:string, username:string, password:string, host:string, hostname:string, port:string, path:string, search:string, hash:string, params:{} }}
[ "Uri", "parsing", "method", "." ]
10cb29a1b38b747629bc0f1739ea4bf60d758f8a
https://github.com/sadams/lite-url/blob/10cb29a1b38b747629bc0f1739ea4bf60d758f8a/dist/lite-url.js#L165-L183
44,124
uttesh/ngu-utility
dist/ngu-utility.esm.js
dateGetter
function dateGetter(name, size, offset, trim, negWrap) { if (offset === void 0) { offset = 0; } if (trim === void 0) { trim = false; } if (negWrap === void 0) { negWrap = false; } return function (date, locale) { var /** @type {?} */ part = getDatePart(name, date, size); if (offset > 0 || part > -offset) { part += offset; } if (name === DateType.Hours && part === 0 && offset === -12) { part = 12; } return padNumber(part, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign), trim, negWrap); }; }
javascript
function dateGetter(name, size, offset, trim, negWrap) { if (offset === void 0) { offset = 0; } if (trim === void 0) { trim = false; } if (negWrap === void 0) { negWrap = false; } return function (date, locale) { var /** @type {?} */ part = getDatePart(name, date, size); if (offset > 0 || part > -offset) { part += offset; } if (name === DateType.Hours && part === 0 && offset === -12) { part = 12; } return padNumber(part, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign), trim, negWrap); }; }
[ "function", "dateGetter", "(", "name", ",", "size", ",", "offset", ",", "trim", ",", "negWrap", ")", "{", "if", "(", "offset", "===", "void", "0", ")", "{", "offset", "=", "0", ";", "}", "if", "(", "trim", "===", "void", "0", ")", "{", "trim", "=", "false", ";", "}", "if", "(", "negWrap", "===", "void", "0", ")", "{", "negWrap", "=", "false", ";", "}", "return", "function", "(", "date", ",", "locale", ")", "{", "var", "/** @type {?} */", "part", "=", "getDatePart", "(", "name", ",", "date", ",", "size", ")", ";", "if", "(", "offset", ">", "0", "||", "part", ">", "-", "offset", ")", "{", "part", "+=", "offset", ";", "}", "if", "(", "name", "===", "DateType", ".", "Hours", "&&", "part", "===", "0", "&&", "offset", "===", "-", "12", ")", "{", "part", "=", "12", ";", "}", "return", "padNumber", "(", "part", ",", "size", ",", "getLocaleNumberSymbol", "(", "locale", ",", "NumberSymbol", ".", "MinusSign", ")", ",", "trim", ",", "negWrap", ")", ";", "}", ";", "}" ]
Returns a date formatter that transforms a date into its locale digit representation @param {?} name @param {?} size @param {?=} offset @param {?=} trim @param {?=} negWrap @return {?}
[ "Returns", "a", "date", "formatter", "that", "transforms", "a", "date", "into", "its", "locale", "digit", "representation" ]
8a9bd6eef91f4862b6e9ca1c6dd2bee8aa79ecca
https://github.com/uttesh/ngu-utility/blob/8a9bd6eef91f4862b6e9ca1c6dd2bee8aa79ecca/dist/ngu-utility.esm.js#L3340-L3354
44,125
uttesh/ngu-utility
dist/ngu-utility.esm.js
getDateTranslation
function getDateTranslation(date, locale, name, width, form, extended) { switch (name) { case TranslationType.Months: return getLocaleMonthNames(locale, form, width)[date.getMonth()]; case TranslationType.Days: return getLocaleDayNames(locale, form, width)[date.getDay()]; case TranslationType.DayPeriods: var /** @type {?} */ currentHours_1 = date.getHours(); var /** @type {?} */ currentMinutes_1 = date.getMinutes(); if (extended) { var /** @type {?} */ rules = getLocaleExtraDayPeriodRules(locale); var /** @type {?} */ dayPeriods_1 = getLocaleExtraDayPeriods(locale, form, width); var /** @type {?} */ result_1; rules.forEach(function (rule, index) { if (Array.isArray(rule)) { // morning, afternoon, evening, night var _a = rule[0], hoursFrom = _a.hours, minutesFrom = _a.minutes; var _b = rule[1], hoursTo = _b.hours, minutesTo = _b.minutes; if (currentHours_1 >= hoursFrom && currentMinutes_1 >= minutesFrom && (currentHours_1 < hoursTo || (currentHours_1 === hoursTo && currentMinutes_1 < minutesTo))) { result_1 = dayPeriods_1[index]; } } else { // noon or midnight var hours = rule.hours, minutes = rule.minutes; if (hours === currentHours_1 && minutes === currentMinutes_1) { result_1 = dayPeriods_1[index]; } } }); if (result_1) { return result_1; } } // if no rules for the day periods, we use am/pm by default return getLocaleDayPeriods(locale, form, /** @type {?} */ (width))[currentHours_1 < 12 ? 0 : 1]; case TranslationType.Eras: return getLocaleEraNames(locale, /** @type {?} */ (width))[date.getFullYear() <= 0 ? 0 : 1]; } }
javascript
function getDateTranslation(date, locale, name, width, form, extended) { switch (name) { case TranslationType.Months: return getLocaleMonthNames(locale, form, width)[date.getMonth()]; case TranslationType.Days: return getLocaleDayNames(locale, form, width)[date.getDay()]; case TranslationType.DayPeriods: var /** @type {?} */ currentHours_1 = date.getHours(); var /** @type {?} */ currentMinutes_1 = date.getMinutes(); if (extended) { var /** @type {?} */ rules = getLocaleExtraDayPeriodRules(locale); var /** @type {?} */ dayPeriods_1 = getLocaleExtraDayPeriods(locale, form, width); var /** @type {?} */ result_1; rules.forEach(function (rule, index) { if (Array.isArray(rule)) { // morning, afternoon, evening, night var _a = rule[0], hoursFrom = _a.hours, minutesFrom = _a.minutes; var _b = rule[1], hoursTo = _b.hours, minutesTo = _b.minutes; if (currentHours_1 >= hoursFrom && currentMinutes_1 >= minutesFrom && (currentHours_1 < hoursTo || (currentHours_1 === hoursTo && currentMinutes_1 < minutesTo))) { result_1 = dayPeriods_1[index]; } } else { // noon or midnight var hours = rule.hours, minutes = rule.minutes; if (hours === currentHours_1 && minutes === currentMinutes_1) { result_1 = dayPeriods_1[index]; } } }); if (result_1) { return result_1; } } // if no rules for the day periods, we use am/pm by default return getLocaleDayPeriods(locale, form, /** @type {?} */ (width))[currentHours_1 < 12 ? 0 : 1]; case TranslationType.Eras: return getLocaleEraNames(locale, /** @type {?} */ (width))[date.getFullYear() <= 0 ? 0 : 1]; } }
[ "function", "getDateTranslation", "(", "date", ",", "locale", ",", "name", ",", "width", ",", "form", ",", "extended", ")", "{", "switch", "(", "name", ")", "{", "case", "TranslationType", ".", "Months", ":", "return", "getLocaleMonthNames", "(", "locale", ",", "form", ",", "width", ")", "[", "date", ".", "getMonth", "(", ")", "]", ";", "case", "TranslationType", ".", "Days", ":", "return", "getLocaleDayNames", "(", "locale", ",", "form", ",", "width", ")", "[", "date", ".", "getDay", "(", ")", "]", ";", "case", "TranslationType", ".", "DayPeriods", ":", "var", "/** @type {?} */", "currentHours_1", "=", "date", ".", "getHours", "(", ")", ";", "var", "/** @type {?} */", "currentMinutes_1", "=", "date", ".", "getMinutes", "(", ")", ";", "if", "(", "extended", ")", "{", "var", "/** @type {?} */", "rules", "=", "getLocaleExtraDayPeriodRules", "(", "locale", ")", ";", "var", "/** @type {?} */", "dayPeriods_1", "=", "getLocaleExtraDayPeriods", "(", "locale", ",", "form", ",", "width", ")", ";", "var", "/** @type {?} */", "result_1", ";", "rules", ".", "forEach", "(", "function", "(", "rule", ",", "index", ")", "{", "if", "(", "Array", ".", "isArray", "(", "rule", ")", ")", "{", "// morning, afternoon, evening, night", "var", "_a", "=", "rule", "[", "0", "]", ",", "hoursFrom", "=", "_a", ".", "hours", ",", "minutesFrom", "=", "_a", ".", "minutes", ";", "var", "_b", "=", "rule", "[", "1", "]", ",", "hoursTo", "=", "_b", ".", "hours", ",", "minutesTo", "=", "_b", ".", "minutes", ";", "if", "(", "currentHours_1", ">=", "hoursFrom", "&&", "currentMinutes_1", ">=", "minutesFrom", "&&", "(", "currentHours_1", "<", "hoursTo", "||", "(", "currentHours_1", "===", "hoursTo", "&&", "currentMinutes_1", "<", "minutesTo", ")", ")", ")", "{", "result_1", "=", "dayPeriods_1", "[", "index", "]", ";", "}", "}", "else", "{", "// noon or midnight", "var", "hours", "=", "rule", ".", "hours", ",", "minutes", "=", "rule", ".", "minutes", ";", "if", "(", "hours", "===", "currentHours_1", "&&", "minutes", "===", "currentMinutes_1", ")", "{", "result_1", "=", "dayPeriods_1", "[", "index", "]", ";", "}", "}", "}", ")", ";", "if", "(", "result_1", ")", "{", "return", "result_1", ";", "}", "}", "// if no rules for the day periods, we use am/pm by default", "return", "getLocaleDayPeriods", "(", "locale", ",", "form", ",", "/** @type {?} */", "(", "width", ")", ")", "[", "currentHours_1", "<", "12", "?", "0", ":", "1", "]", ";", "case", "TranslationType", ".", "Eras", ":", "return", "getLocaleEraNames", "(", "locale", ",", "/** @type {?} */", "(", "width", ")", ")", "[", "date", ".", "getFullYear", "(", ")", "<=", "0", "?", "0", ":", "1", "]", ";", "}", "}" ]
Returns the locale translation of a date for a given form, type and width @param {?} date @param {?} locale @param {?} name @param {?} width @param {?} form @param {?} extended @return {?}
[ "Returns", "the", "locale", "translation", "of", "a", "date", "for", "a", "given", "form", "type", "and", "width" ]
8a9bd6eef91f4862b6e9ca1c6dd2bee8aa79ecca
https://github.com/uttesh/ngu-utility/blob/8a9bd6eef91f4862b6e9ca1c6dd2bee8aa79ecca/dist/ngu-utility.esm.js#L3409-L3450
44,126
uttesh/ngu-utility
dist/ngu-utility.esm.js
getRandomColors
function getRandomColors() { var letters = '0123456789ABCDEF'.split(''); var _color = '#'; for (var i = 0; i < 6; i++) { _color += letters[Math.floor(Math.random() * 16)]; } return _color; }
javascript
function getRandomColors() { var letters = '0123456789ABCDEF'.split(''); var _color = '#'; for (var i = 0; i < 6; i++) { _color += letters[Math.floor(Math.random() * 16)]; } return _color; }
[ "function", "getRandomColors", "(", ")", "{", "var", "letters", "=", "'0123456789ABCDEF'", ".", "split", "(", "''", ")", ";", "var", "_color", "=", "'#'", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "6", ";", "i", "++", ")", "{", "_color", "+=", "letters", "[", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "16", ")", "]", ";", "}", "return", "_color", ";", "}" ]
Get the random colors @returns {String}
[ "Get", "the", "random", "colors" ]
8a9bd6eef91f4862b6e9ca1c6dd2bee8aa79ecca
https://github.com/uttesh/ngu-utility/blob/8a9bd6eef91f4862b6e9ca1c6dd2bee8aa79ecca/dist/ngu-utility.esm.js#L5799-L5806
44,127
uttesh/ngu-utility
dist/ngu-utility.esm.js
getFirstAndLastName
function getFirstAndLastName(data) { var names = data.split(" "); if (names && names.length >= 2) { var firstName = names[0]; var lastName = names[1]; if (firstName && lastName) { var text = firstName.substr(0, 1) + lastName.substr(0, 1); return text; } else { return data.substr(0, 2); } } }
javascript
function getFirstAndLastName(data) { var names = data.split(" "); if (names && names.length >= 2) { var firstName = names[0]; var lastName = names[1]; if (firstName && lastName) { var text = firstName.substr(0, 1) + lastName.substr(0, 1); return text; } else { return data.substr(0, 2); } } }
[ "function", "getFirstAndLastName", "(", "data", ")", "{", "var", "names", "=", "data", ".", "split", "(", "\" \"", ")", ";", "if", "(", "names", "&&", "names", ".", "length", ">=", "2", ")", "{", "var", "firstName", "=", "names", "[", "0", "]", ";", "var", "lastName", "=", "names", "[", "1", "]", ";", "if", "(", "firstName", "&&", "lastName", ")", "{", "var", "text", "=", "firstName", ".", "substr", "(", "0", ",", "1", ")", "+", "lastName", ".", "substr", "(", "0", ",", "1", ")", ";", "return", "text", ";", "}", "else", "{", "return", "data", ".", "substr", "(", "0", ",", "2", ")", ";", "}", "}", "}" ]
get the first name and last name first letters and combined and form the letter avatar @param {type} data @returns {unresolved}
[ "get", "the", "first", "name", "and", "last", "name", "first", "letters", "and", "combined", "and", "form", "the", "letter", "avatar" ]
8a9bd6eef91f4862b6e9ca1c6dd2bee8aa79ecca
https://github.com/uttesh/ngu-utility/blob/8a9bd6eef91f4862b6e9ca1c6dd2bee8aa79ecca/dist/ngu-utility.esm.js#L5812-L5825
44,128
rcasto/adaptive-html
dist/adaptive-html.es.js
wrap
function wrap(elements, options) { elements = toArray(elements); /* Don't wrap only a container in a container */ if (elements.length === 1 && isContainer(elements[0])) { return elements[0]; } var container = { type: cardTypes.container, items: elements }; setOptions(container, options); return container; }
javascript
function wrap(elements, options) { elements = toArray(elements); /* Don't wrap only a container in a container */ if (elements.length === 1 && isContainer(elements[0])) { return elements[0]; } var container = { type: cardTypes.container, items: elements }; setOptions(container, options); return container; }
[ "function", "wrap", "(", "elements", ",", "options", ")", "{", "elements", "=", "toArray", "(", "elements", ")", ";", "/* Don't wrap only a container in a container */", "if", "(", "elements", ".", "length", "===", "1", "&&", "isContainer", "(", "elements", "[", "0", "]", ")", ")", "{", "return", "elements", "[", "0", "]", ";", "}", "var", "container", "=", "{", "type", ":", "cardTypes", ".", "container", ",", "items", ":", "elements", "}", ";", "setOptions", "(", "container", ",", "options", ")", ";", "return", "container", ";", "}" ]
Wrap adaptive card elements in a container
[ "Wrap", "adaptive", "card", "elements", "in", "a", "container" ]
79586cebfd0e34f31418c9cbd186ad568652c3ca
https://github.com/rcasto/adaptive-html/blob/79586cebfd0e34f31418c9cbd186ad568652c3ca/dist/adaptive-html.es.js#L157-L169
44,129
rcasto/adaptive-html
dist/adaptive-html.es.js
turndown
function turndown(input) { if (!canConvert(input)) { throw new TypeError(input + ' is not a string, or an element/document/fragment node.'); } var cardElems = process.call(this, new RootNode(input)); return createCard(cardElems); }
javascript
function turndown(input) { if (!canConvert(input)) { throw new TypeError(input + ' is not a string, or an element/document/fragment node.'); } var cardElems = process.call(this, new RootNode(input)); return createCard(cardElems); }
[ "function", "turndown", "(", "input", ")", "{", "if", "(", "!", "canConvert", "(", "input", ")", ")", "{", "throw", "new", "TypeError", "(", "input", "+", "' is not a string, or an element/document/fragment node.'", ")", ";", "}", "var", "cardElems", "=", "process", ".", "call", "(", "this", ",", "new", "RootNode", "(", "input", ")", ")", ";", "return", "createCard", "(", "cardElems", ")", ";", "}" ]
The entry point for converting a string or DOM node to JSON @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", "JSON" ]
79586cebfd0e34f31418c9cbd186ad568652c3ca
https://github.com/rcasto/adaptive-html/blob/79586cebfd0e34f31418c9cbd186ad568652c3ca/dist/adaptive-html.es.js#L605-L611
44,130
rcasto/adaptive-html
dist/adaptive-html.es.js
replacementForNode
function replacementForNode(node) { var rule = this.rules.forNode(node); var content = process.call(this, node); // get's internal content of node return rule.replacement(content, node); }
javascript
function replacementForNode(node) { var rule = this.rules.forNode(node); var content = process.call(this, node); // get's internal content of node return rule.replacement(content, node); }
[ "function", "replacementForNode", "(", "node", ")", "{", "var", "rule", "=", "this", ".", "rules", ".", "forNode", "(", "node", ")", ";", "var", "content", "=", "process", ".", "call", "(", "this", ",", "node", ")", ";", "// get's internal content of node", "return", "rule", ".", "replacement", "(", "content", ",", "node", ")", ";", "}" ]
Converts an element node to its Adaptive Card equivalent @private @param {HTMLElement} node The node to convert @returns An Adaptive Card representation of the node @type String
[ "Converts", "an", "element", "node", "to", "its", "Adaptive", "Card", "equivalent" ]
79586cebfd0e34f31418c9cbd186ad568652c3ca
https://github.com/rcasto/adaptive-html/blob/79586cebfd0e34f31418c9cbd186ad568652c3ca/dist/adaptive-html.es.js#L661-L665
44,131
rcasto/adaptive-html
dist/adaptive-html.es.js
canConvert
function canConvert(input) { return input != null && (typeof input === 'string' || input.nodeType && (input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11)); }
javascript
function canConvert(input) { return input != null && (typeof input === 'string' || input.nodeType && (input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11)); }
[ "function", "canConvert", "(", "input", ")", "{", "return", "input", "!=", "null", "&&", "(", "typeof", "input", "===", "'string'", "||", "input", ".", "nodeType", "&&", "(", "input", ".", "nodeType", "===", "1", "||", "input", ".", "nodeType", "===", "9", "||", "input", ".", "nodeType", "===", "11", ")", ")", ";", "}" ]
Determines whether an input can be converted @private @param {String|HTMLElement} input Describe this parameter @returns Describe what it returns @type String|Object|Array|Boolean|Number
[ "Determines", "whether", "an", "input", "can", "be", "converted" ]
79586cebfd0e34f31418c9cbd186ad568652c3ca
https://github.com/rcasto/adaptive-html/blob/79586cebfd0e34f31418c9cbd186ad568652c3ca/dist/adaptive-html.es.js#L674-L676
44,132
thlorenz/prange
prange.js
prange
function prange(s) { const set = new Set() const subs = s // correct things like AJs -A9s to AJs-A9s .replace( /([A,K,Q,J,T,2-9]{2}[o,s]?)\s*-\s*([A,K,Q,J,T,2-9]{2}[o,s]?)/g , '$1-$2' ) // correct AK + to AK+ .replace( /([A,K,Q,J,T,2-9]{2}[o,s]?)\s\+/g , '$1+' ) // split at any white space or comma (any errornous space was removed via replace) .split(/[,\s]+/).map(x => x.trim()) for (let i = 0; i < subs.length; i++) { const res = subrange(subs[i]) res.forEach(x => set.add(x)) } return Array.from(set).sort(byCodeRankDescending) }
javascript
function prange(s) { const set = new Set() const subs = s // correct things like AJs -A9s to AJs-A9s .replace( /([A,K,Q,J,T,2-9]{2}[o,s]?)\s*-\s*([A,K,Q,J,T,2-9]{2}[o,s]?)/g , '$1-$2' ) // correct AK + to AK+ .replace( /([A,K,Q,J,T,2-9]{2}[o,s]?)\s\+/g , '$1+' ) // split at any white space or comma (any errornous space was removed via replace) .split(/[,\s]+/).map(x => x.trim()) for (let i = 0; i < subs.length; i++) { const res = subrange(subs[i]) res.forEach(x => set.add(x)) } return Array.from(set).sort(byCodeRankDescending) }
[ "function", "prange", "(", "s", ")", "{", "const", "set", "=", "new", "Set", "(", ")", "const", "subs", "=", "s", "// correct things like AJs -A9s to AJs-A9s", ".", "replace", "(", "/", "([A,K,Q,J,T,2-9]{2}[o,s]?)\\s*-\\s*([A,K,Q,J,T,2-9]{2}[o,s]?)", "/", "g", ",", "'$1-$2'", ")", "// correct AK + to AK+", ".", "replace", "(", "/", "([A,K,Q,J,T,2-9]{2}[o,s]?)\\s\\+", "/", "g", ",", "'$1+'", ")", "// split at any white space or comma (any errornous space was removed via replace)", ".", "split", "(", "/", "[,\\s]+", "/", ")", ".", "map", "(", "x", "=>", "x", ".", "trim", "(", ")", ")", "for", "(", "let", "i", "=", "0", ";", "i", "<", "subs", ".", "length", ";", "i", "++", ")", "{", "const", "res", "=", "subrange", "(", "subs", "[", "i", "]", ")", "res", ".", "forEach", "(", "x", "=>", "set", ".", "add", "(", "x", ")", ")", "}", "return", "Array", ".", "from", "(", "set", ")", ".", "sort", "(", "byCodeRankDescending", ")", "}" ]
Converts a short notation for poker hand ranges into an array filled with the matching combos. Each range specifier is separated by a comma. The following notations are supported: - single combos `KK, AK, ATs` - plus notation - `QQ+` = `[ AA, KK, QQ ]` - `KTs+` = `[ KQs, KJs, KTs ]` - `KTo+` = `[ KQo, KJo, KTo ]` - `KT+` = `[ KQs, KQo, KJo, KJs, KTo, KTs ]` - dash notation - `KK-JJ` = `[ KK, QQ, JJ ]` - `AKo-ATo` = `[ AK, AQ, AJ, AT ]` - `AKs-JTs` = `[ AKs, KQs, JTs ]` @name prange @function @param {String} s the short notation for the range @return {Array.<String>} all hand combos satisfying the given range
[ "Converts", "a", "short", "notation", "for", "poker", "hand", "ranges", "into", "an", "array", "filled", "with", "the", "matching", "combos", "." ]
6cbf10c3594970a1e1a0de9400ae1ef9dadfdb4c
https://github.com/thlorenz/prange/blob/6cbf10c3594970a1e1a0de9400ae1ef9dadfdb4c/prange.js#L164-L184
44,133
jotak/mipod
javascript/Library.js
organizer
function organizer(flat, tags, treeDescriptor, leafDescriptor) { var tree = {}; flat.forEach(function (song) { var treePtr = tree; var depth = 1; // strPossibleKeys can be like "albumArtist|artist", or just "album" for instance treeDescriptor.forEach(function (strPossibleKeys) { var possibleKeys = strPossibleKeys.split("|"); var valueForKey = undefined; for (var key in possibleKeys) { valueForKey = song[possibleKeys[key]]; if (valueForKey !== undefined && valueForKey !== "") { break; } } if (valueForKey === undefined) { valueForKey = ""; } if (!treePtr[valueForKey]) { if (depth === treeDescriptor.length) { treePtr[valueForKey] = { tags: {}, mpd: [] }; } else { treePtr[valueForKey] = { tags: {}, mpd: {} }; } var mostCommonKey = possibleKeys[possibleKeys.length - 1]; if (tags[mostCommonKey] && tags[mostCommonKey][valueForKey]) { treePtr[valueForKey].tags = tags[mostCommonKey][valueForKey]; } } treePtr = treePtr[valueForKey].mpd; depth++; }); var leaf = {}; if (leafDescriptor) { leafDescriptor.forEach(function (key) { leaf[key] = song[key]; }); } else { leaf = song; } if (tags["song"] && tags["song"][song.file]) { leaf.tags = tags["song"][song.file]; } treePtr.push(leaf); }); return { root: tree }; }
javascript
function organizer(flat, tags, treeDescriptor, leafDescriptor) { var tree = {}; flat.forEach(function (song) { var treePtr = tree; var depth = 1; // strPossibleKeys can be like "albumArtist|artist", or just "album" for instance treeDescriptor.forEach(function (strPossibleKeys) { var possibleKeys = strPossibleKeys.split("|"); var valueForKey = undefined; for (var key in possibleKeys) { valueForKey = song[possibleKeys[key]]; if (valueForKey !== undefined && valueForKey !== "") { break; } } if (valueForKey === undefined) { valueForKey = ""; } if (!treePtr[valueForKey]) { if (depth === treeDescriptor.length) { treePtr[valueForKey] = { tags: {}, mpd: [] }; } else { treePtr[valueForKey] = { tags: {}, mpd: {} }; } var mostCommonKey = possibleKeys[possibleKeys.length - 1]; if (tags[mostCommonKey] && tags[mostCommonKey][valueForKey]) { treePtr[valueForKey].tags = tags[mostCommonKey][valueForKey]; } } treePtr = treePtr[valueForKey].mpd; depth++; }); var leaf = {}; if (leafDescriptor) { leafDescriptor.forEach(function (key) { leaf[key] = song[key]; }); } else { leaf = song; } if (tags["song"] && tags["song"][song.file]) { leaf.tags = tags["song"][song.file]; } treePtr.push(leaf); }); return { root: tree }; }
[ "function", "organizer", "(", "flat", ",", "tags", ",", "treeDescriptor", ",", "leafDescriptor", ")", "{", "var", "tree", "=", "{", "}", ";", "flat", ".", "forEach", "(", "function", "(", "song", ")", "{", "var", "treePtr", "=", "tree", ";", "var", "depth", "=", "1", ";", "// strPossibleKeys can be like \"albumArtist|artist\", or just \"album\" for instance", "treeDescriptor", ".", "forEach", "(", "function", "(", "strPossibleKeys", ")", "{", "var", "possibleKeys", "=", "strPossibleKeys", ".", "split", "(", "\"|\"", ")", ";", "var", "valueForKey", "=", "undefined", ";", "for", "(", "var", "key", "in", "possibleKeys", ")", "{", "valueForKey", "=", "song", "[", "possibleKeys", "[", "key", "]", "]", ";", "if", "(", "valueForKey", "!==", "undefined", "&&", "valueForKey", "!==", "\"\"", ")", "{", "break", ";", "}", "}", "if", "(", "valueForKey", "===", "undefined", ")", "{", "valueForKey", "=", "\"\"", ";", "}", "if", "(", "!", "treePtr", "[", "valueForKey", "]", ")", "{", "if", "(", "depth", "===", "treeDescriptor", ".", "length", ")", "{", "treePtr", "[", "valueForKey", "]", "=", "{", "tags", ":", "{", "}", ",", "mpd", ":", "[", "]", "}", ";", "}", "else", "{", "treePtr", "[", "valueForKey", "]", "=", "{", "tags", ":", "{", "}", ",", "mpd", ":", "{", "}", "}", ";", "}", "var", "mostCommonKey", "=", "possibleKeys", "[", "possibleKeys", ".", "length", "-", "1", "]", ";", "if", "(", "tags", "[", "mostCommonKey", "]", "&&", "tags", "[", "mostCommonKey", "]", "[", "valueForKey", "]", ")", "{", "treePtr", "[", "valueForKey", "]", ".", "tags", "=", "tags", "[", "mostCommonKey", "]", "[", "valueForKey", "]", ";", "}", "}", "treePtr", "=", "treePtr", "[", "valueForKey", "]", ".", "mpd", ";", "depth", "++", ";", "}", ")", ";", "var", "leaf", "=", "{", "}", ";", "if", "(", "leafDescriptor", ")", "{", "leafDescriptor", ".", "forEach", "(", "function", "(", "key", ")", "{", "leaf", "[", "key", "]", "=", "song", "[", "key", "]", ";", "}", ")", ";", "}", "else", "{", "leaf", "=", "song", ";", "}", "if", "(", "tags", "[", "\"song\"", "]", "&&", "tags", "[", "\"song\"", "]", "[", "song", ".", "file", "]", ")", "{", "leaf", ".", "tags", "=", "tags", "[", "\"song\"", "]", "[", "song", ".", "file", "]", ";", "}", "treePtr", ".", "push", "(", "leaf", ")", ";", "}", ")", ";", "return", "{", "root", ":", "tree", "}", ";", "}" ]
Returns a custom object tree corresponding to the descriptor
[ "Returns", "a", "custom", "object", "tree", "corresponding", "to", "the", "descriptor" ]
42e37f1ca0813d402ec27663b228340a8c2f3c0e
https://github.com/jotak/mipod/blob/42e37f1ca0813d402ec27663b228340a8c2f3c0e/javascript/Library.js#L480-L527
44,134
erikhagreis/fb-sdk-wrapper
lib/load.js
load
function load() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; params = (0, _lodash.defaults)({}, params, { locale: 'en_US' }); return new Promise(function (resolve, reject) { if (window.FB) { return resolve(window.FB); } var src = '//connect.facebook.net/' + params.locale + '/sdk.js'; var script = document.createElement('script'); script.id = 'facebook-jssdk'; script.src = src; script.async = true; script.addEventListener('load', function () { return resolve(window.FB); }, false); script.addEventListener('error', function () { return reject('Error loading Facebook JS SDK from ' + src); }, false); var sibling = document.getElementsByTagName('script')[0]; sibling.parentNode.insertBefore(script, sibling); }); }
javascript
function load() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; params = (0, _lodash.defaults)({}, params, { locale: 'en_US' }); return new Promise(function (resolve, reject) { if (window.FB) { return resolve(window.FB); } var src = '//connect.facebook.net/' + params.locale + '/sdk.js'; var script = document.createElement('script'); script.id = 'facebook-jssdk'; script.src = src; script.async = true; script.addEventListener('load', function () { return resolve(window.FB); }, false); script.addEventListener('error', function () { return reject('Error loading Facebook JS SDK from ' + src); }, false); var sibling = document.getElementsByTagName('script')[0]; sibling.parentNode.insertBefore(script, sibling); }); }
[ "function", "load", "(", ")", "{", "var", "params", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "{", "}", ";", "params", "=", "(", "0", ",", "_lodash", ".", "defaults", ")", "(", "{", "}", ",", "params", ",", "{", "locale", ":", "'en_US'", "}", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "window", ".", "FB", ")", "{", "return", "resolve", "(", "window", ".", "FB", ")", ";", "}", "var", "src", "=", "'//connect.facebook.net/'", "+", "params", ".", "locale", "+", "'/sdk.js'", ";", "var", "script", "=", "document", ".", "createElement", "(", "'script'", ")", ";", "script", ".", "id", "=", "'facebook-jssdk'", ";", "script", ".", "src", "=", "src", ";", "script", ".", "async", "=", "true", ";", "script", ".", "addEventListener", "(", "'load'", ",", "function", "(", ")", "{", "return", "resolve", "(", "window", ".", "FB", ")", ";", "}", ",", "false", ")", ";", "script", ".", "addEventListener", "(", "'error'", ",", "function", "(", ")", "{", "return", "reject", "(", "'Error loading Facebook JS SDK from '", "+", "src", ")", ";", "}", ",", "false", ")", ";", "var", "sibling", "=", "document", ".", "getElementsByTagName", "(", "'script'", ")", "[", "0", "]", ";", "sibling", ".", "parentNode", ".", "insertBefore", "(", "script", ",", "sibling", ")", ";", "}", ")", ";", "}" ]
Injects the script for the FB JS SDK into the page. @param {Object} params containing optional settings @return {Promise} for the global window.FB object
[ "Injects", "the", "script", "for", "the", "FB", "JS", "SDK", "into", "the", "page", "." ]
dfaf53de1c11191c73ea9e8438a0542276996acf
https://github.com/erikhagreis/fb-sdk-wrapper/blob/dfaf53de1c11191c73ea9e8438a0542276996acf/lib/load.js#L17-L43
44,135
thlorenz/prange
prange.reverse.js
reverse
function reverse(combos) { const { offsuit, suited, pairs } = sortOut(combos) const ps = reversePairs(pairs) const os = reverseNonPairs(offsuit, 'o') const su = reverseNonPairs(suited, 's') const nonpairs = unsuitWhenPossible(new Set(os), new Set(su)) return ps.concat(nonpairs).join(', ') }
javascript
function reverse(combos) { const { offsuit, suited, pairs } = sortOut(combos) const ps = reversePairs(pairs) const os = reverseNonPairs(offsuit, 'o') const su = reverseNonPairs(suited, 's') const nonpairs = unsuitWhenPossible(new Set(os), new Set(su)) return ps.concat(nonpairs).join(', ') }
[ "function", "reverse", "(", "combos", ")", "{", "const", "{", "offsuit", ",", "suited", ",", "pairs", "}", "=", "sortOut", "(", "combos", ")", "const", "ps", "=", "reversePairs", "(", "pairs", ")", "const", "os", "=", "reverseNonPairs", "(", "offsuit", ",", "'o'", ")", "const", "su", "=", "reverseNonPairs", "(", "suited", ",", "'s'", ")", "const", "nonpairs", "=", "unsuitWhenPossible", "(", "new", "Set", "(", "os", ")", ",", "new", "Set", "(", "su", ")", ")", "return", "ps", ".", "concat", "(", "nonpairs", ")", ".", "join", "(", "', '", ")", "}" ]
Converts a poker hand range to short notation. It's the opposite of `prange`. @name prange.reverse @function @param {Array.<String>} combos hand combos to be converted to short notation @param {String} the short notation for the range
[ "Converts", "a", "poker", "hand", "range", "to", "short", "notation", ".", "It", "s", "the", "opposite", "of", "prange", "." ]
6cbf10c3594970a1e1a0de9400ae1ef9dadfdb4c
https://github.com/thlorenz/prange/blob/6cbf10c3594970a1e1a0de9400ae1ef9dadfdb4c/prange.reverse.js#L54-L63
44,136
prettier/prettier-linter-helpers
index.js
showInvisibles
function showInvisibles(str) { let ret = ''; for (let i = 0; i < str.length; i++) { switch (str[i]) { case ' ': ret += '·'; // Middle Dot, \u00B7 break; case '\n': ret += '⏎'; // Return Symbol, \u23ce break; case '\t': ret += '↹'; // Left Arrow To Bar Over Right Arrow To Bar, \u21b9 break; case '\r': ret += '␍'; // Carriage Return Symbol, \u240D break; default: ret += str[i]; break; } } return ret; }
javascript
function showInvisibles(str) { let ret = ''; for (let i = 0; i < str.length; i++) { switch (str[i]) { case ' ': ret += '·'; // Middle Dot, \u00B7 break; case '\n': ret += '⏎'; // Return Symbol, \u23ce break; case '\t': ret += '↹'; // Left Arrow To Bar Over Right Arrow To Bar, \u21b9 break; case '\r': ret += '␍'; // Carriage Return Symbol, \u240D break; default: ret += str[i]; break; } } return ret; }
[ "function", "showInvisibles", "(", "str", ")", "{", "let", "ret", "=", "''", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "str", ".", "length", ";", "i", "++", ")", "{", "switch", "(", "str", "[", "i", "]", ")", "{", "case", "' '", ":", "ret", "+=", "'·';", " ", "/ Middle Dot, \\u00B7", "break", ";", "case", "'\\n'", ":", "ret", "+=", "'⏎'; ", "/", " Return Symbol, \\u23ce", "break", ";", "case", "'\\t'", ":", "ret", "+=", "'↹'; ", "/", " Left Arrow To Bar Over Right Arrow To Bar, \\u21b9", "break", ";", "case", "'\\r'", ":", "ret", "+=", "'␍'; ", "/", " Carriage Return Symbol, \\u240D", "break", ";", "default", ":", "ret", "+=", "str", "[", "i", "]", ";", "break", ";", "}", "}", "return", "ret", ";", "}" ]
Converts invisible characters to a commonly recognizable visible form. @param {string} str - The string with invisibles to convert. @returns {string} The converted string.
[ "Converts", "invisible", "characters", "to", "a", "commonly", "recognizable", "visible", "form", "." ]
0c45ee13356f4d178def1c27ba22731bd93c563b
https://github.com/prettier/prettier-linter-helpers/blob/0c45ee13356f4d178def1c27ba22731bd93c563b/index.js#L10-L32
44,137
prettier/prettier-linter-helpers
index.js
generateDifferences
function generateDifferences(source, prettierSource) { // fast-diff returns the differences between two texts as a series of // INSERT, DELETE or EQUAL operations. The results occur only in these // sequences: // /-> INSERT -> EQUAL // EQUAL | /-> EQUAL // \-> DELETE | // \-> INSERT -> EQUAL // Instead of reporting issues at each INSERT or DELETE, certain sequences // are batched together and are reported as a friendlier "replace" operation: // - A DELETE immediately followed by an INSERT. // - Any number of INSERTs and DELETEs where the joining EQUAL of one's end // and another's beginning does not have line endings (i.e. issues that occur // on contiguous lines). const results = diff(source, prettierSource); const differences = []; const batch = []; let offset = 0; // NOTE: INSERT never advances the offset. while (results.length) { const result = results.shift(); const op = result[0]; const text = result[1]; switch (op) { case diff.INSERT: case diff.DELETE: batch.push(result); break; case diff.EQUAL: if (results.length) { if (batch.length) { if (LINE_ENDING_RE.test(text)) { flush(); offset += text.length; } else { batch.push(result); } } else { offset += text.length; } } break; default: throw new Error(`Unexpected fast-diff operation "${op}"`); } if (batch.length && !results.length) { flush(); } } return differences; function flush() { let aheadDeleteText = ''; let aheadInsertText = ''; while (batch.length) { const next = batch.shift(); const op = next[0]; const text = next[1]; switch (op) { case diff.INSERT: aheadInsertText += text; break; case diff.DELETE: aheadDeleteText += text; break; case diff.EQUAL: aheadDeleteText += text; aheadInsertText += text; break; } } if (aheadDeleteText && aheadInsertText) { differences.push({ offset, operation: generateDifferences.REPLACE, insertText: aheadInsertText, deleteText: aheadDeleteText, }); } else if (!aheadDeleteText && aheadInsertText) { differences.push({ offset, operation: generateDifferences.INSERT, insertText: aheadInsertText, }); } else if (aheadDeleteText && !aheadInsertText) { differences.push({ offset, operation: generateDifferences.DELETE, deleteText: aheadDeleteText, }); } offset += aheadDeleteText.length; } }
javascript
function generateDifferences(source, prettierSource) { // fast-diff returns the differences between two texts as a series of // INSERT, DELETE or EQUAL operations. The results occur only in these // sequences: // /-> INSERT -> EQUAL // EQUAL | /-> EQUAL // \-> DELETE | // \-> INSERT -> EQUAL // Instead of reporting issues at each INSERT or DELETE, certain sequences // are batched together and are reported as a friendlier "replace" operation: // - A DELETE immediately followed by an INSERT. // - Any number of INSERTs and DELETEs where the joining EQUAL of one's end // and another's beginning does not have line endings (i.e. issues that occur // on contiguous lines). const results = diff(source, prettierSource); const differences = []; const batch = []; let offset = 0; // NOTE: INSERT never advances the offset. while (results.length) { const result = results.shift(); const op = result[0]; const text = result[1]; switch (op) { case diff.INSERT: case diff.DELETE: batch.push(result); break; case diff.EQUAL: if (results.length) { if (batch.length) { if (LINE_ENDING_RE.test(text)) { flush(); offset += text.length; } else { batch.push(result); } } else { offset += text.length; } } break; default: throw new Error(`Unexpected fast-diff operation "${op}"`); } if (batch.length && !results.length) { flush(); } } return differences; function flush() { let aheadDeleteText = ''; let aheadInsertText = ''; while (batch.length) { const next = batch.shift(); const op = next[0]; const text = next[1]; switch (op) { case diff.INSERT: aheadInsertText += text; break; case diff.DELETE: aheadDeleteText += text; break; case diff.EQUAL: aheadDeleteText += text; aheadInsertText += text; break; } } if (aheadDeleteText && aheadInsertText) { differences.push({ offset, operation: generateDifferences.REPLACE, insertText: aheadInsertText, deleteText: aheadDeleteText, }); } else if (!aheadDeleteText && aheadInsertText) { differences.push({ offset, operation: generateDifferences.INSERT, insertText: aheadInsertText, }); } else if (aheadDeleteText && !aheadInsertText) { differences.push({ offset, operation: generateDifferences.DELETE, deleteText: aheadDeleteText, }); } offset += aheadDeleteText.length; } }
[ "function", "generateDifferences", "(", "source", ",", "prettierSource", ")", "{", "// fast-diff returns the differences between two texts as a series of", "// INSERT, DELETE or EQUAL operations. The results occur only in these", "// sequences:", "// /-> INSERT -> EQUAL", "// EQUAL | /-> EQUAL", "// \\-> DELETE |", "// \\-> INSERT -> EQUAL", "// Instead of reporting issues at each INSERT or DELETE, certain sequences", "// are batched together and are reported as a friendlier \"replace\" operation:", "// - A DELETE immediately followed by an INSERT.", "// - Any number of INSERTs and DELETEs where the joining EQUAL of one's end", "// and another's beginning does not have line endings (i.e. issues that occur", "// on contiguous lines).", "const", "results", "=", "diff", "(", "source", ",", "prettierSource", ")", ";", "const", "differences", "=", "[", "]", ";", "const", "batch", "=", "[", "]", ";", "let", "offset", "=", "0", ";", "// NOTE: INSERT never advances the offset.", "while", "(", "results", ".", "length", ")", "{", "const", "result", "=", "results", ".", "shift", "(", ")", ";", "const", "op", "=", "result", "[", "0", "]", ";", "const", "text", "=", "result", "[", "1", "]", ";", "switch", "(", "op", ")", "{", "case", "diff", ".", "INSERT", ":", "case", "diff", ".", "DELETE", ":", "batch", ".", "push", "(", "result", ")", ";", "break", ";", "case", "diff", ".", "EQUAL", ":", "if", "(", "results", ".", "length", ")", "{", "if", "(", "batch", ".", "length", ")", "{", "if", "(", "LINE_ENDING_RE", ".", "test", "(", "text", ")", ")", "{", "flush", "(", ")", ";", "offset", "+=", "text", ".", "length", ";", "}", "else", "{", "batch", ".", "push", "(", "result", ")", ";", "}", "}", "else", "{", "offset", "+=", "text", ".", "length", ";", "}", "}", "break", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "op", "}", "`", ")", ";", "}", "if", "(", "batch", ".", "length", "&&", "!", "results", ".", "length", ")", "{", "flush", "(", ")", ";", "}", "}", "return", "differences", ";", "function", "flush", "(", ")", "{", "let", "aheadDeleteText", "=", "''", ";", "let", "aheadInsertText", "=", "''", ";", "while", "(", "batch", ".", "length", ")", "{", "const", "next", "=", "batch", ".", "shift", "(", ")", ";", "const", "op", "=", "next", "[", "0", "]", ";", "const", "text", "=", "next", "[", "1", "]", ";", "switch", "(", "op", ")", "{", "case", "diff", ".", "INSERT", ":", "aheadInsertText", "+=", "text", ";", "break", ";", "case", "diff", ".", "DELETE", ":", "aheadDeleteText", "+=", "text", ";", "break", ";", "case", "diff", ".", "EQUAL", ":", "aheadDeleteText", "+=", "text", ";", "aheadInsertText", "+=", "text", ";", "break", ";", "}", "}", "if", "(", "aheadDeleteText", "&&", "aheadInsertText", ")", "{", "differences", ".", "push", "(", "{", "offset", ",", "operation", ":", "generateDifferences", ".", "REPLACE", ",", "insertText", ":", "aheadInsertText", ",", "deleteText", ":", "aheadDeleteText", ",", "}", ")", ";", "}", "else", "if", "(", "!", "aheadDeleteText", "&&", "aheadInsertText", ")", "{", "differences", ".", "push", "(", "{", "offset", ",", "operation", ":", "generateDifferences", ".", "INSERT", ",", "insertText", ":", "aheadInsertText", ",", "}", ")", ";", "}", "else", "if", "(", "aheadDeleteText", "&&", "!", "aheadInsertText", ")", "{", "differences", ".", "push", "(", "{", "offset", ",", "operation", ":", "generateDifferences", ".", "DELETE", ",", "deleteText", ":", "aheadDeleteText", ",", "}", ")", ";", "}", "offset", "+=", "aheadDeleteText", ".", "length", ";", "}", "}" ]
Generate results for differences between source code and formatted version. @param {string} source - The original source. @param {string} prettierSource - The Prettier formatted source. @returns {Array} - An array containing { operation, offset, insertText, deleteText }
[ "Generate", "results", "for", "differences", "between", "source", "code", "and", "formatted", "version", "." ]
0c45ee13356f4d178def1c27ba22731bd93c563b
https://github.com/prettier/prettier-linter-helpers/blob/0c45ee13356f4d178def1c27ba22731bd93c563b/index.js#L41-L136
44,138
goliatone/influx-line-protocol-parser
lib/index.js
cast
function cast(value){ if(value === undefined) return undefined; /* * Integers: 344i */ if(value.match(/^\d+i$/m)){ value = value.slice(0, -1); return parseInt(value); } /* boolean true * t, T, true, True, or TRUE */ if(value.match(/^t$|^true$/im)){ return true; } /* boolean false * f, F, false, False, or FALSE */ if(value.match(/^f$|^false$/im)){ return false; } /* * match strings */ if(value.match(/^"(.*)"$/)){ value = value.match(/^"(.*)"$/); if(value.length === 2){ return value[1]; } } if(!isNaN(value)) return parseFloat(value); return undefined; }
javascript
function cast(value){ if(value === undefined) return undefined; /* * Integers: 344i */ if(value.match(/^\d+i$/m)){ value = value.slice(0, -1); return parseInt(value); } /* boolean true * t, T, true, True, or TRUE */ if(value.match(/^t$|^true$/im)){ return true; } /* boolean false * f, F, false, False, or FALSE */ if(value.match(/^f$|^false$/im)){ return false; } /* * match strings */ if(value.match(/^"(.*)"$/)){ value = value.match(/^"(.*)"$/); if(value.length === 2){ return value[1]; } } if(!isNaN(value)) return parseFloat(value); return undefined; }
[ "function", "cast", "(", "value", ")", "{", "if", "(", "value", "===", "undefined", ")", "return", "undefined", ";", "/*\n * Integers: 344i\n */", "if", "(", "value", ".", "match", "(", "/", "^\\d+i$", "/", "m", ")", ")", "{", "value", "=", "value", ".", "slice", "(", "0", ",", "-", "1", ")", ";", "return", "parseInt", "(", "value", ")", ";", "}", "/* boolean true\n * t, T, true, True, or TRUE\n */", "if", "(", "value", ".", "match", "(", "/", "^t$|^true$", "/", "im", ")", ")", "{", "return", "true", ";", "}", "/* boolean false\n * f, F, false, False, or FALSE\n */", "if", "(", "value", ".", "match", "(", "/", "^f$|^false$", "/", "im", ")", ")", "{", "return", "false", ";", "}", "/*\n * match strings\n */", "if", "(", "value", ".", "match", "(", "/", "^\"(.*)\"$", "/", ")", ")", "{", "value", "=", "value", ".", "match", "(", "/", "^\"(.*)\"$", "/", ")", ";", "if", "(", "value", ".", "length", "===", "2", ")", "{", "return", "value", "[", "1", "]", ";", "}", "}", "if", "(", "!", "isNaN", "(", "value", ")", ")", "return", "parseFloat", "(", "value", ")", ";", "return", "undefined", ";", "}" ]
Cast each element in it's equivalent JS type. Note that for fields, without knowing the type it was stored as in InfluxDB we have to guess it's type. This can be an issue in cases where we have fields that are alphanumeric with a chance of having a instance being all digits. Tags are all strings. @param {Mixed} value @return {Mixed}
[ "Cast", "each", "element", "in", "it", "s", "equivalent", "JS", "type", "." ]
f8c3c75ced9aaa7a39623449cd454bdb7e4c83df
https://github.com/goliatone/influx-line-protocol-parser/blob/f8c3c75ced9aaa7a39623449cd454bdb7e4c83df/lib/index.js#L151-L189
44,139
erikhagreis/fb-sdk-wrapper
lib/loadEnforcer.js
loadEnforcer
function loadEnforcer(method) { return function () { for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) { rest[_key] = arguments[_key]; } var FB = (0, _getGlobalFB2.default)(); if (!FB) { throw new Error('FB SDK Wrapper cannot call method ' + method.name + '; the ' + 'SDK is not loaded yet. Call load() first and wait for its promise ' + 'to resolve.'); } else { return method.apply(undefined, [FB].concat(rest)); } }; }
javascript
function loadEnforcer(method) { return function () { for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) { rest[_key] = arguments[_key]; } var FB = (0, _getGlobalFB2.default)(); if (!FB) { throw new Error('FB SDK Wrapper cannot call method ' + method.name + '; the ' + 'SDK is not loaded yet. Call load() first and wait for its promise ' + 'to resolve.'); } else { return method.apply(undefined, [FB].concat(rest)); } }; }
[ "function", "loadEnforcer", "(", "method", ")", "{", "return", "function", "(", ")", "{", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "rest", "=", "Array", "(", "_len", ")", ",", "_key", "=", "0", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "rest", "[", "_key", "]", "=", "arguments", "[", "_key", "]", ";", "}", "var", "FB", "=", "(", "0", ",", "_getGlobalFB2", ".", "default", ")", "(", ")", ";", "if", "(", "!", "FB", ")", "{", "throw", "new", "Error", "(", "'FB SDK Wrapper cannot call method '", "+", "method", ".", "name", "+", "'; the '", "+", "'SDK is not loaded yet. Call load() first and wait for its promise '", "+", "'to resolve.'", ")", ";", "}", "else", "{", "return", "method", ".", "apply", "(", "undefined", ",", "[", "FB", "]", ".", "concat", "(", "rest", ")", ")", ";", "}", "}", ";", "}" ]
Injects the global FB SDK object into all methods in this package which depend on it. Throws an error if FB has not been loaded yet. @param {Function} method
[ "Injects", "the", "global", "FB", "SDK", "object", "into", "all", "methods", "in", "this", "package", "which", "depend", "on", "it", ".", "Throws", "an", "error", "if", "FB", "has", "not", "been", "loaded", "yet", "." ]
dfaf53de1c11191c73ea9e8438a0542276996acf
https://github.com/erikhagreis/fb-sdk-wrapper/blob/dfaf53de1c11191c73ea9e8438a0542276996acf/lib/loadEnforcer.js#L21-L34
44,140
hildjj/node-abnf
lib/abnf.js
rule
function rule() { var ret = this.seq(rulename, defined_as, elements, c_nl); var da = ret[2]; if (da === "=") { return this.rules.addRule(ret[1], ret[3]); } if (da === "=/") { return this.rules.addAlternate(ret[1], ret[3]); } return this.fail(); }
javascript
function rule() { var ret = this.seq(rulename, defined_as, elements, c_nl); var da = ret[2]; if (da === "=") { return this.rules.addRule(ret[1], ret[3]); } if (da === "=/") { return this.rules.addAlternate(ret[1], ret[3]); } return this.fail(); }
[ "function", "rule", "(", ")", "{", "var", "ret", "=", "this", ".", "seq", "(", "rulename", ",", "defined_as", ",", "elements", ",", "c_nl", ")", ";", "var", "da", "=", "ret", "[", "2", "]", ";", "if", "(", "da", "===", "\"=\"", ")", "{", "return", "this", ".", "rules", ".", "addRule", "(", "ret", "[", "1", "]", ",", "ret", "[", "3", "]", ")", ";", "}", "if", "(", "da", "===", "\"=/\"", ")", "{", "return", "this", ".", "rules", ".", "addAlternate", "(", "ret", "[", "1", "]", ",", "ret", "[", "3", "]", ")", ";", "}", "return", "this", ".", "fail", "(", ")", ";", "}" ]
rule = rulename defined-as elements c-nl ; continues if next line starts ; with white space
[ "rule", "=", "rulename", "defined", "-", "as", "elements", "c", "-", "nl", ";", "continues", "if", "next", "line", "starts", ";", "with", "white", "space" ]
5c7046478f0965b54ab13057e33a65d780a83bc9
https://github.com/hildjj/node-abnf/blob/5c7046478f0965b54ab13057e33a65d780a83bc9/lib/abnf.js#L181-L192
44,141
kmalakoff/knockback-navigators
examples/vendor/knockback-core-stack-0.16.7.js
function(bindingsString, bindingContext) { try { var viewModel = bindingContext['$data'], scopes = (typeof viewModel == 'object' && viewModel != null) ? [viewModel, bindingContext] : [bindingContext], bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, scopes.length, this.bindingCache); return bindingFunction(scopes); } catch (ex) { throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString); } }
javascript
function(bindingsString, bindingContext) { try { var viewModel = bindingContext['$data'], scopes = (typeof viewModel == 'object' && viewModel != null) ? [viewModel, bindingContext] : [bindingContext], bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, scopes.length, this.bindingCache); return bindingFunction(scopes); } catch (ex) { throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString); } }
[ "function", "(", "bindingsString", ",", "bindingContext", ")", "{", "try", "{", "var", "viewModel", "=", "bindingContext", "[", "'$data'", "]", ",", "scopes", "=", "(", "typeof", "viewModel", "==", "'object'", "&&", "viewModel", "!=", "null", ")", "?", "[", "viewModel", ",", "bindingContext", "]", ":", "[", "bindingContext", "]", ",", "bindingFunction", "=", "createBindingsStringEvaluatorViaCache", "(", "bindingsString", ",", "scopes", ".", "length", ",", "this", ".", "bindingCache", ")", ";", "return", "bindingFunction", "(", "scopes", ")", ";", "}", "catch", "(", "ex", ")", "{", "throw", "new", "Error", "(", "\"Unable to parse bindings.\\nMessage: \"", "+", "ex", "+", "\";\\nBindings value: \"", "+", "bindingsString", ")", ";", "}", "}" ]
The following function is only used internally by this default provider. It's not part of the interface definition for a general binding provider.
[ "The", "following", "function", "is", "only", "used", "internally", "by", "this", "default", "provider", ".", "It", "s", "not", "part", "of", "the", "interface", "definition", "for", "a", "general", "binding", "provider", "." ]
6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125
https://github.com/kmalakoff/knockback-navigators/blob/6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125/examples/vendor/knockback-core-stack-0.16.7.js#L4333-L4342
44,142
kmalakoff/knockback-navigators
examples/vendor/knockback-core-stack-0.16.7.js
calculateEditDistanceMatrix
function calculateEditDistanceMatrix(oldArray, newArray, maxAllowedDistance) { var distances = []; for (var i = 0; i <= newArray.length; i++) distances[i] = []; // Top row - transform old array into empty array via deletions for (var i = 0, j = Math.min(oldArray.length, maxAllowedDistance); i <= j; i++) distances[0][i] = i; // Left row - transform empty array into new array via additions for (var i = 1, j = Math.min(newArray.length, maxAllowedDistance); i <= j; i++) { distances[i][0] = i; } // Fill out the body of the array var oldIndex, oldIndexMax = oldArray.length, newIndex, newIndexMax = newArray.length; var distanceViaAddition, distanceViaDeletion; for (oldIndex = 1; oldIndex <= oldIndexMax; oldIndex++) { var newIndexMinForRow = Math.max(1, oldIndex - maxAllowedDistance); var newIndexMaxForRow = Math.min(newIndexMax, oldIndex + maxAllowedDistance); for (newIndex = newIndexMinForRow; newIndex <= newIndexMaxForRow; newIndex++) { if (oldArray[oldIndex - 1] === newArray[newIndex - 1]) distances[newIndex][oldIndex] = distances[newIndex - 1][oldIndex - 1]; else { var northDistance = distances[newIndex - 1][oldIndex] === undefined ? Number.MAX_VALUE : distances[newIndex - 1][oldIndex] + 1; var westDistance = distances[newIndex][oldIndex - 1] === undefined ? Number.MAX_VALUE : distances[newIndex][oldIndex - 1] + 1; distances[newIndex][oldIndex] = Math.min(northDistance, westDistance); } } } return distances; }
javascript
function calculateEditDistanceMatrix(oldArray, newArray, maxAllowedDistance) { var distances = []; for (var i = 0; i <= newArray.length; i++) distances[i] = []; // Top row - transform old array into empty array via deletions for (var i = 0, j = Math.min(oldArray.length, maxAllowedDistance); i <= j; i++) distances[0][i] = i; // Left row - transform empty array into new array via additions for (var i = 1, j = Math.min(newArray.length, maxAllowedDistance); i <= j; i++) { distances[i][0] = i; } // Fill out the body of the array var oldIndex, oldIndexMax = oldArray.length, newIndex, newIndexMax = newArray.length; var distanceViaAddition, distanceViaDeletion; for (oldIndex = 1; oldIndex <= oldIndexMax; oldIndex++) { var newIndexMinForRow = Math.max(1, oldIndex - maxAllowedDistance); var newIndexMaxForRow = Math.min(newIndexMax, oldIndex + maxAllowedDistance); for (newIndex = newIndexMinForRow; newIndex <= newIndexMaxForRow; newIndex++) { if (oldArray[oldIndex - 1] === newArray[newIndex - 1]) distances[newIndex][oldIndex] = distances[newIndex - 1][oldIndex - 1]; else { var northDistance = distances[newIndex - 1][oldIndex] === undefined ? Number.MAX_VALUE : distances[newIndex - 1][oldIndex] + 1; var westDistance = distances[newIndex][oldIndex - 1] === undefined ? Number.MAX_VALUE : distances[newIndex][oldIndex - 1] + 1; distances[newIndex][oldIndex] = Math.min(northDistance, westDistance); } } } return distances; }
[ "function", "calculateEditDistanceMatrix", "(", "oldArray", ",", "newArray", ",", "maxAllowedDistance", ")", "{", "var", "distances", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<=", "newArray", ".", "length", ";", "i", "++", ")", "distances", "[", "i", "]", "=", "[", "]", ";", "// Top row - transform old array into empty array via deletions", "for", "(", "var", "i", "=", "0", ",", "j", "=", "Math", ".", "min", "(", "oldArray", ".", "length", ",", "maxAllowedDistance", ")", ";", "i", "<=", "j", ";", "i", "++", ")", "distances", "[", "0", "]", "[", "i", "]", "=", "i", ";", "// Left row - transform empty array into new array via additions", "for", "(", "var", "i", "=", "1", ",", "j", "=", "Math", ".", "min", "(", "newArray", ".", "length", ",", "maxAllowedDistance", ")", ";", "i", "<=", "j", ";", "i", "++", ")", "{", "distances", "[", "i", "]", "[", "0", "]", "=", "i", ";", "}", "// Fill out the body of the array", "var", "oldIndex", ",", "oldIndexMax", "=", "oldArray", ".", "length", ",", "newIndex", ",", "newIndexMax", "=", "newArray", ".", "length", ";", "var", "distanceViaAddition", ",", "distanceViaDeletion", ";", "for", "(", "oldIndex", "=", "1", ";", "oldIndex", "<=", "oldIndexMax", ";", "oldIndex", "++", ")", "{", "var", "newIndexMinForRow", "=", "Math", ".", "max", "(", "1", ",", "oldIndex", "-", "maxAllowedDistance", ")", ";", "var", "newIndexMaxForRow", "=", "Math", ".", "min", "(", "newIndexMax", ",", "oldIndex", "+", "maxAllowedDistance", ")", ";", "for", "(", "newIndex", "=", "newIndexMinForRow", ";", "newIndex", "<=", "newIndexMaxForRow", ";", "newIndex", "++", ")", "{", "if", "(", "oldArray", "[", "oldIndex", "-", "1", "]", "===", "newArray", "[", "newIndex", "-", "1", "]", ")", "distances", "[", "newIndex", "]", "[", "oldIndex", "]", "=", "distances", "[", "newIndex", "-", "1", "]", "[", "oldIndex", "-", "1", "]", ";", "else", "{", "var", "northDistance", "=", "distances", "[", "newIndex", "-", "1", "]", "[", "oldIndex", "]", "===", "undefined", "?", "Number", ".", "MAX_VALUE", ":", "distances", "[", "newIndex", "-", "1", "]", "[", "oldIndex", "]", "+", "1", ";", "var", "westDistance", "=", "distances", "[", "newIndex", "]", "[", "oldIndex", "-", "1", "]", "===", "undefined", "?", "Number", ".", "MAX_VALUE", ":", "distances", "[", "newIndex", "]", "[", "oldIndex", "-", "1", "]", "+", "1", ";", "distances", "[", "newIndex", "]", "[", "oldIndex", "]", "=", "Math", ".", "min", "(", "northDistance", ",", "westDistance", ")", ";", "}", "}", "}", "return", "distances", ";", "}" ]
Simple calculation based on Levenshtein distance.
[ "Simple", "calculation", "based", "on", "Levenshtein", "distance", "." ]
6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125
https://github.com/kmalakoff/knockback-navigators/blob/6dd5344f2d1f8b95e91b31aa29a3dc56b5a36125/examples/vendor/knockback-core-stack-0.16.7.js#L5588-L5620
44,143
lambtron/medium-cli
lib/logger.js
log
function log(type, args, color){ pad(); var msg = format.apply(format, args); if (color) msg = chalk[color](msg); var pre = prefix(); console[type](pre, msg); }
javascript
function log(type, args, color){ pad(); var msg = format.apply(format, args); if (color) msg = chalk[color](msg); var pre = prefix(); console[type](pre, msg); }
[ "function", "log", "(", "type", ",", "args", ",", "color", ")", "{", "pad", "(", ")", ";", "var", "msg", "=", "format", ".", "apply", "(", "format", ",", "args", ")", ";", "if", "(", "color", ")", "msg", "=", "chalk", "[", "color", "]", "(", "msg", ")", ";", "var", "pre", "=", "prefix", "(", ")", ";", "console", "[", "type", "]", "(", "pre", ",", "msg", ")", ";", "}" ]
Log by `type` with `args`. @param {String} type @param {Arguments} args @param {String} color
[ "Log", "by", "type", "with", "args", "." ]
a2d4baea4f5665e42dedd72b5ed7ae97f6de79eb
https://github.com/lambtron/medium-cli/blob/a2d4baea4f5665e42dedd72b5ed7ae97f6de79eb/lib/logger.js#L41-L47
44,144
kchapelier/decode-dxt
index.js
decode
function decode (imageDataView, width, height, format) { var result; format = format ? format.toLowerCase() : 'dxt1'; if (format === decode.dxt1) { result = decodeBC1(imageDataView, width, height); } else if(format === decode.dxt2) { result = decodeBC2(imageDataView, width, height, true); } else if(format === decode.dxt3) { result = decodeBC2(imageDataView, width, height, false); } else if(format === decode.dxt4) { result = decodeBC3(imageDataView, width, height, true); } else if(format === decode.dxt5) { result = decodeBC3(imageDataView, width, height, false); } else { throw new Error('Unknown DXT format : \'' + format + '\''); } return result; }
javascript
function decode (imageDataView, width, height, format) { var result; format = format ? format.toLowerCase() : 'dxt1'; if (format === decode.dxt1) { result = decodeBC1(imageDataView, width, height); } else if(format === decode.dxt2) { result = decodeBC2(imageDataView, width, height, true); } else if(format === decode.dxt3) { result = decodeBC2(imageDataView, width, height, false); } else if(format === decode.dxt4) { result = decodeBC3(imageDataView, width, height, true); } else if(format === decode.dxt5) { result = decodeBC3(imageDataView, width, height, false); } else { throw new Error('Unknown DXT format : \'' + format + '\''); } return result; }
[ "function", "decode", "(", "imageDataView", ",", "width", ",", "height", ",", "format", ")", "{", "var", "result", ";", "format", "=", "format", "?", "format", ".", "toLowerCase", "(", ")", ":", "'dxt1'", ";", "if", "(", "format", "===", "decode", ".", "dxt1", ")", "{", "result", "=", "decodeBC1", "(", "imageDataView", ",", "width", ",", "height", ")", ";", "}", "else", "if", "(", "format", "===", "decode", ".", "dxt2", ")", "{", "result", "=", "decodeBC2", "(", "imageDataView", ",", "width", ",", "height", ",", "true", ")", ";", "}", "else", "if", "(", "format", "===", "decode", ".", "dxt3", ")", "{", "result", "=", "decodeBC2", "(", "imageDataView", ",", "width", ",", "height", ",", "false", ")", ";", "}", "else", "if", "(", "format", "===", "decode", ".", "dxt4", ")", "{", "result", "=", "decodeBC3", "(", "imageDataView", ",", "width", ",", "height", ",", "true", ")", ";", "}", "else", "if", "(", "format", "===", "decode", ".", "dxt5", ")", "{", "result", "=", "decodeBC3", "(", "imageDataView", ",", "width", ",", "height", ",", "false", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Unknown DXT format : \\''", "+", "format", "+", "'\\''", ")", ";", "}", "return", "result", ";", "}" ]
Decode a DXT image to RGBA data. @param {DataView} imageDataView A DataView pointing directly to the data of the DXT image @param {int} width Width of the image @param {int} height Height of the image @param {string} [format='dxt1'] Format of the image (dxt1, dxt2, dxt3, dxt4 or dxt5) @returns {Uint8Array} Decoded RGBA data @throws Will throw if the format is not recognized
[ "Decode", "a", "DXT", "image", "to", "RGBA", "data", "." ]
254dfb0348b3fdc8b1e4df3bb7b74620dbddd2a4
https://github.com/kchapelier/decode-dxt/blob/254dfb0348b3fdc8b1e4df3bb7b74620dbddd2a4/index.js#L16-L36
44,145
doowb/async-helpers
examples/example.js
lower
function lower(str, options, cb) { // handle Handlebars or Lodash templates if (typeof options === 'function') { cb = options; options = {}; } cb(null, str.toLowerCase()); }
javascript
function lower(str, options, cb) { // handle Handlebars or Lodash templates if (typeof options === 'function') { cb = options; options = {}; } cb(null, str.toLowerCase()); }
[ "function", "lower", "(", "str", ",", "options", ",", "cb", ")", "{", "// handle Handlebars or Lodash templates", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "cb", "=", "options", ";", "options", "=", "{", "}", ";", "}", "cb", "(", "null", ",", "str", ".", "toLowerCase", "(", ")", ")", ";", "}" ]
some simple async helpers
[ "some", "simple", "async", "helpers" ]
ea33b6e2062ec49a9b4780f847f6f24eb52fd43e
https://github.com/doowb/async-helpers/blob/ea33b6e2062ec49a9b4780f847f6f24eb52fd43e/examples/example.js#L14-L21
44,146
dutchenkoOleg/node-w3c-validator
lib/render-html.js
extractParts
function extractParts (str, indexA, indexB) { let part = str.substr(indexA, indexB); part = part.replace(/</g, '&lt;').replace(/>/g, '&gt;'); part = part.replace(/\n/g, '<span class="invisible"> \u21A9</span>\n'); part = part.replace(/\t/g, '<span class="invisible tab">\u2192</span>'); return part; }
javascript
function extractParts (str, indexA, indexB) { let part = str.substr(indexA, indexB); part = part.replace(/</g, '&lt;').replace(/>/g, '&gt;'); part = part.replace(/\n/g, '<span class="invisible"> \u21A9</span>\n'); part = part.replace(/\t/g, '<span class="invisible tab">\u2192</span>'); return part; }
[ "function", "extractParts", "(", "str", ",", "indexA", ",", "indexB", ")", "{", "let", "part", "=", "str", ".", "substr", "(", "indexA", ",", "indexB", ")", ";", "part", "=", "part", ".", "replace", "(", "/", "<", "/", "g", ",", "'&lt;'", ")", ".", "replace", "(", "/", ">", "/", "g", ",", "'&gt;'", ")", ";", "part", "=", "part", ".", "replace", "(", "/", "\\n", "/", "g", ",", "'<span class=\"invisible\"> \\u21A9</span>\\n'", ")", ";", "part", "=", "part", ".", "replace", "(", "/", "\\t", "/", "g", ",", "'<span class=\"invisible tab\">\\u2192</span>'", ")", ";", "return", "part", ";", "}" ]
Get part of string and replace special symbols there @param {string} str @param {number} indexA @param {number} [indexB] @returns {string} @private @sourceCode
[ "Get", "part", "of", "string", "and", "replace", "special", "symbols", "there" ]
79bc6ee63bdfad0208c6c6d8dcd5e25a629b006e
https://github.com/dutchenkoOleg/node-w3c-validator/blob/79bc6ee63bdfad0208c6c6d8dcd5e25a629b006e/lib/render-html.js#L38-L45
44,147
Raynos/discovery-network
example/direct/static/index.js
handleStream
function handleStream(remotePeerId, stream) { if (opened[remotePeerId] !== true) { stream.write("hello!") stream.on("data", log) } function log(data) { console.log("[PEER2]", remotePeerId, data) } }
javascript
function handleStream(remotePeerId, stream) { if (opened[remotePeerId] !== true) { stream.write("hello!") stream.on("data", log) } function log(data) { console.log("[PEER2]", remotePeerId, data) } }
[ "function", "handleStream", "(", "remotePeerId", ",", "stream", ")", "{", "if", "(", "opened", "[", "remotePeerId", "]", "!==", "true", ")", "{", "stream", ".", "write", "(", "\"hello!\"", ")", "stream", ".", "on", "(", "\"data\"", ",", "log", ")", "}", "function", "log", "(", "data", ")", "{", "console", ".", "log", "(", "\"[PEER2]\"", ",", "remotePeerId", ",", "data", ")", "}", "}" ]
When the relay emits a stream handle it
[ "When", "the", "relay", "emits", "a", "stream", "handle", "it" ]
fa61c50b2baf188be7abb7d1c684a01a9fc43690
https://github.com/Raynos/discovery-network/blob/fa61c50b2baf188be7abb7d1c684a01a9fc43690/example/direct/static/index.js#L34-L44
44,148
fullstackers/socket.io-logger
lib/index.js
Logger
function Logger (options) { if (!(this instanceof Logger)) return new Logger(options); options = options || {}; debug('new logger v%s', pkg.version); var router = Router(); router.on(function (sock, args, cb) { debug('logger args.length %s', arguments.length); try { // "this" is the "socket" logger.stream().write(logger.format(sock, args) + "\n"); cb(); } catch (e) { debug('caught an error %s', e); console.trace(e); cb(e); } }); function logger (sock, cb) { debug('logger sock', sock, cb.toString()); router(sock, cb); } logger.__proto__ = Logger.prototype; if (options.stream) { logger.stream(options.stream); } if (options.format) { logger.format(options.format); } return logger; }
javascript
function Logger (options) { if (!(this instanceof Logger)) return new Logger(options); options = options || {}; debug('new logger v%s', pkg.version); var router = Router(); router.on(function (sock, args, cb) { debug('logger args.length %s', arguments.length); try { // "this" is the "socket" logger.stream().write(logger.format(sock, args) + "\n"); cb(); } catch (e) { debug('caught an error %s', e); console.trace(e); cb(e); } }); function logger (sock, cb) { debug('logger sock', sock, cb.toString()); router(sock, cb); } logger.__proto__ = Logger.prototype; if (options.stream) { logger.stream(options.stream); } if (options.format) { logger.format(options.format); } return logger; }
[ "function", "Logger", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Logger", ")", ")", "return", "new", "Logger", "(", "options", ")", ";", "options", "=", "options", "||", "{", "}", ";", "debug", "(", "'new logger v%s'", ",", "pkg", ".", "version", ")", ";", "var", "router", "=", "Router", "(", ")", ";", "router", ".", "on", "(", "function", "(", "sock", ",", "args", ",", "cb", ")", "{", "debug", "(", "'logger args.length %s'", ",", "arguments", ".", "length", ")", ";", "try", "{", "// \"this\" is the \"socket\"", "logger", ".", "stream", "(", ")", ".", "write", "(", "logger", ".", "format", "(", "sock", ",", "args", ")", "+", "\"\\n\"", ")", ";", "cb", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "'caught an error %s'", ",", "e", ")", ";", "console", ".", "trace", "(", "e", ")", ";", "cb", "(", "e", ")", ";", "}", "}", ")", ";", "function", "logger", "(", "sock", ",", "cb", ")", "{", "debug", "(", "'logger sock'", ",", "sock", ",", "cb", ".", "toString", "(", ")", ")", ";", "router", "(", "sock", ",", "cb", ")", ";", "}", "logger", ".", "__proto__", "=", "Logger", ".", "prototype", ";", "if", "(", "options", ".", "stream", ")", "{", "logger", ".", "stream", "(", "options", ".", "stream", ")", ";", "}", "if", "(", "options", ".", "format", ")", "{", "logger", ".", "format", "(", "options", ".", "format", ")", ";", "}", "return", "logger", ";", "}" ]
A very simple middleware for socket.io that will record the events and log them to a stream. @return Logger
[ "A", "very", "simple", "middleware", "for", "socket", ".", "io", "that", "will", "record", "the", "events", "and", "log", "them", "to", "a", "stream", "." ]
94e49139a84d804d46e8b2f1de350e73416b56ad
https://github.com/fullstackers/socket.io-logger/blob/94e49139a84d804d46e8b2f1de350e73416b56ad/lib/index.js#L16-L54
44,149
infusionsoft/bower-locker
bower-locker-unlock.js
unlock
function unlock(isVerbose) { if (isVerbose) { console.log('Start unlocking ...'); } // Load bower.json and make sure it is a locked bower.json file var bowerConfigStr = fs.readFileSync('bower.json', {encoding: 'utf8'}); var bowerConfig = JSON.parse(bowerConfigStr); if (!bowerConfig.bowerLocker) { console.warn('The bower.json is already unlocked.\n' + "Run 'bower-locker lock' to create a locked file."); process.exit(1); } // Load original bower file var originalBowerConfigStr = fs.readFileSync('bower-locker.bower.json', {encoding: 'utf8'}); // Write it back as bower.json fs.writeFileSync('bower.json', originalBowerConfigStr, {encoding: 'utf8'}); console.log('Unlocking completed.'); }
javascript
function unlock(isVerbose) { if (isVerbose) { console.log('Start unlocking ...'); } // Load bower.json and make sure it is a locked bower.json file var bowerConfigStr = fs.readFileSync('bower.json', {encoding: 'utf8'}); var bowerConfig = JSON.parse(bowerConfigStr); if (!bowerConfig.bowerLocker) { console.warn('The bower.json is already unlocked.\n' + "Run 'bower-locker lock' to create a locked file."); process.exit(1); } // Load original bower file var originalBowerConfigStr = fs.readFileSync('bower-locker.bower.json', {encoding: 'utf8'}); // Write it back as bower.json fs.writeFileSync('bower.json', originalBowerConfigStr, {encoding: 'utf8'}); console.log('Unlocking completed.'); }
[ "function", "unlock", "(", "isVerbose", ")", "{", "if", "(", "isVerbose", ")", "{", "console", ".", "log", "(", "'Start unlocking ...'", ")", ";", "}", "// Load bower.json and make sure it is a locked bower.json file", "var", "bowerConfigStr", "=", "fs", ".", "readFileSync", "(", "'bower.json'", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "var", "bowerConfig", "=", "JSON", ".", "parse", "(", "bowerConfigStr", ")", ";", "if", "(", "!", "bowerConfig", ".", "bowerLocker", ")", "{", "console", ".", "warn", "(", "'The bower.json is already unlocked.\\n'", "+", "\"Run 'bower-locker lock' to create a locked file.\"", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "// Load original bower file", "var", "originalBowerConfigStr", "=", "fs", ".", "readFileSync", "(", "'bower-locker.bower.json'", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "// Write it back as bower.json", "fs", ".", "writeFileSync", "(", "'bower.json'", ",", "originalBowerConfigStr", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "console", ".", "log", "(", "'Unlocking completed.'", ")", ";", "}" ]
Function to unlock the `bower.json` file by returning it to its unlocked version The unlocked version is stored at `bower-locker.bower.json` @param {Boolean} isVerbose Flag to indicate whether we should log verbosely or not
[ "Function", "to", "unlock", "the", "bower", ".", "json", "file", "by", "returning", "it", "to", "its", "unlocked", "version", "The", "unlocked", "version", "is", "stored", "at", "bower", "-", "locker", ".", "bower", ".", "json" ]
9da98159684015ca872b4c35a1a72eb17ee93b37
https://github.com/infusionsoft/bower-locker/blob/9da98159684015ca872b4c35a1a72eb17ee93b37/bower-locker-unlock.js#L11-L31
44,150
andreypopp/rrouter
src/descriptors.js
Route
function Route(props) { props = props ? merge({}, props) : {}; var path = props.path; if (typeof path === 'string') { path = path.replace(slashes, ''); } delete props.path; var view = props.view; delete props.view; var viewPromise = props.viewPromise; delete props.viewPromise; var name = props.name; delete props.name; var __scope = props.__scope; delete props.__scope; var args = Array.prototype.slice.call(arguments, 1); var children = []; // so we support passing routes as arguments and arrays for (var i = 0, len = args.length; i < len; i++) { if (Array.isArray(args[i])) { children = children.concat(args[i]); } else { children.push(args[i]); } } var route = {path, name, view, viewPromise, props, children, __scope}; buildNameIndex(route); return route; }
javascript
function Route(props) { props = props ? merge({}, props) : {}; var path = props.path; if (typeof path === 'string') { path = path.replace(slashes, ''); } delete props.path; var view = props.view; delete props.view; var viewPromise = props.viewPromise; delete props.viewPromise; var name = props.name; delete props.name; var __scope = props.__scope; delete props.__scope; var args = Array.prototype.slice.call(arguments, 1); var children = []; // so we support passing routes as arguments and arrays for (var i = 0, len = args.length; i < len; i++) { if (Array.isArray(args[i])) { children = children.concat(args[i]); } else { children.push(args[i]); } } var route = {path, name, view, viewPromise, props, children, __scope}; buildNameIndex(route); return route; }
[ "function", "Route", "(", "props", ")", "{", "props", "=", "props", "?", "merge", "(", "{", "}", ",", "props", ")", ":", "{", "}", ";", "var", "path", "=", "props", ".", "path", ";", "if", "(", "typeof", "path", "===", "'string'", ")", "{", "path", "=", "path", ".", "replace", "(", "slashes", ",", "''", ")", ";", "}", "delete", "props", ".", "path", ";", "var", "view", "=", "props", ".", "view", ";", "delete", "props", ".", "view", ";", "var", "viewPromise", "=", "props", ".", "viewPromise", ";", "delete", "props", ".", "viewPromise", ";", "var", "name", "=", "props", ".", "name", ";", "delete", "props", ".", "name", ";", "var", "__scope", "=", "props", ".", "__scope", ";", "delete", "props", ".", "__scope", ";", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "var", "children", "=", "[", "]", ";", "// so we support passing routes as arguments and arrays", "for", "(", "var", "i", "=", "0", ",", "len", "=", "args", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "Array", ".", "isArray", "(", "args", "[", "i", "]", ")", ")", "{", "children", "=", "children", ".", "concat", "(", "args", "[", "i", "]", ")", ";", "}", "else", "{", "children", ".", "push", "(", "args", "[", "i", "]", ")", ";", "}", "}", "var", "route", "=", "{", "path", ",", "name", ",", "view", ",", "viewPromise", ",", "props", ",", "children", ",", "__scope", "}", ";", "buildNameIndex", "(", "route", ")", ";", "return", "route", ";", "}" ]
Route desriptor constructor @param {Object} props @param {Object...} children @returns {Route}
[ "Route", "desriptor", "constructor" ]
4287dc666254af61f1d169c12fb61a1bfd7e2623
https://github.com/andreypopp/rrouter/blob/4287dc666254af61f1d169c12fb61a1bfd7e2623/src/descriptors.js#L17-L56
44,151
jay-hodgson/markdown-it-center-text
index.js
postProcess
function postProcess(state) { var i, foundStart = false, foundEnd = false, delim, token, delimiters = state.delimiters, max = state.delimiters.length; for (i = 0; i < max; i++) { delim = delimiters[i]; if (delim.marker === '->') { foundStart = true; } else if (delim.marker === '<-') { foundEnd = true; } } if (foundStart && foundEnd) { for (i = 0; i < max; i++) { delim = delimiters[i]; if (delim.marker === '->') { foundStart = true; token = state.tokens[delim.token]; token.type = 'centertext_open'; token.tag = 'div'; token.nesting = 1; token.markup = '->'; token.content = ''; token.attrs = [ [ 'class', 'text-align-center' ] ]; } else if (delim.marker === '<-') { if (foundStart) { token = state.tokens[delim.token]; token.type = 'centertext_close'; token.tag = 'div'; token.nesting = -1; token.markup = '<-'; token.content = ''; } } } } }
javascript
function postProcess(state) { var i, foundStart = false, foundEnd = false, delim, token, delimiters = state.delimiters, max = state.delimiters.length; for (i = 0; i < max; i++) { delim = delimiters[i]; if (delim.marker === '->') { foundStart = true; } else if (delim.marker === '<-') { foundEnd = true; } } if (foundStart && foundEnd) { for (i = 0; i < max; i++) { delim = delimiters[i]; if (delim.marker === '->') { foundStart = true; token = state.tokens[delim.token]; token.type = 'centertext_open'; token.tag = 'div'; token.nesting = 1; token.markup = '->'; token.content = ''; token.attrs = [ [ 'class', 'text-align-center' ] ]; } else if (delim.marker === '<-') { if (foundStart) { token = state.tokens[delim.token]; token.type = 'centertext_close'; token.tag = 'div'; token.nesting = -1; token.markup = '<-'; token.content = ''; } } } } }
[ "function", "postProcess", "(", "state", ")", "{", "var", "i", ",", "foundStart", "=", "false", ",", "foundEnd", "=", "false", ",", "delim", ",", "token", ",", "delimiters", "=", "state", ".", "delimiters", ",", "max", "=", "state", ".", "delimiters", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "max", ";", "i", "++", ")", "{", "delim", "=", "delimiters", "[", "i", "]", ";", "if", "(", "delim", ".", "marker", "===", "'->'", ")", "{", "foundStart", "=", "true", ";", "}", "else", "if", "(", "delim", ".", "marker", "===", "'<-'", ")", "{", "foundEnd", "=", "true", ";", "}", "}", "if", "(", "foundStart", "&&", "foundEnd", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "max", ";", "i", "++", ")", "{", "delim", "=", "delimiters", "[", "i", "]", ";", "if", "(", "delim", ".", "marker", "===", "'->'", ")", "{", "foundStart", "=", "true", ";", "token", "=", "state", ".", "tokens", "[", "delim", ".", "token", "]", ";", "token", ".", "type", "=", "'centertext_open'", ";", "token", ".", "tag", "=", "'div'", ";", "token", ".", "nesting", "=", "1", ";", "token", ".", "markup", "=", "'->'", ";", "token", ".", "content", "=", "''", ";", "token", ".", "attrs", "=", "[", "[", "'class'", ",", "'text-align-center'", "]", "]", ";", "}", "else", "if", "(", "delim", ".", "marker", "===", "'<-'", ")", "{", "if", "(", "foundStart", ")", "{", "token", "=", "state", ".", "tokens", "[", "delim", ".", "token", "]", ";", "token", ".", "type", "=", "'centertext_close'", ";", "token", ".", "tag", "=", "'div'", ";", "token", ".", "nesting", "=", "-", "1", ";", "token", ".", "markup", "=", "'<-'", ";", "token", ".", "content", "=", "''", ";", "}", "}", "}", "}", "}" ]
Walk through delimiter list and replace text tokens with tags
[ "Walk", "through", "delimiter", "list", "and", "replace", "text", "tokens", "with", "tags" ]
843d6cdda10699d045b0ba2dfe8fb6e7e06511ef
https://github.com/jay-hodgson/markdown-it-center-text/blob/843d6cdda10699d045b0ba2dfe8fb6e7e06511ef/index.js#L59-L101
44,152
zeljkoX/react-native-pseudo-localization
src/PseudoText.js
procesArray
function procesArray(array) { if (!array || !Array.isArray(array)) { return array; } return array.map((item, index) => { if (typeof item === "string") { return localizeString(item); } return item; }); }
javascript
function procesArray(array) { if (!array || !Array.isArray(array)) { return array; } return array.map((item, index) => { if (typeof item === "string") { return localizeString(item); } return item; }); }
[ "function", "procesArray", "(", "array", ")", "{", "if", "(", "!", "array", "||", "!", "Array", ".", "isArray", "(", "array", ")", ")", "{", "return", "array", ";", "}", "return", "array", ".", "map", "(", "(", "item", ",", "index", ")", "=>", "{", "if", "(", "typeof", "item", "===", "\"string\"", ")", "{", "return", "localizeString", "(", "item", ")", ";", "}", "return", "item", ";", "}", ")", ";", "}" ]
flag to check if render is already overwritten process children array and localize strings
[ "flag", "to", "check", "if", "render", "is", "already", "overwritten", "process", "children", "array", "and", "localize", "strings" ]
96bae9ff62765a397ade9254ebd38e16396fba5f
https://github.com/zeljkoX/react-native-pseudo-localization/blob/96bae9ff62765a397ade9254ebd38e16396fba5f/src/PseudoText.js#L19-L29
44,153
zeljkoX/react-native-pseudo-localization
src/PseudoText.js
renderText
function renderText(args, that) { if (isNewTextVersion) { args[0] = { ...args[0], children: pseudoText(args[0].children) }; return defaultTextRender.apply(that, args); } else { const element = defaultTextRender.apply(that, args); return React.cloneElement(element, { children: pseudoText(element.props.children) }); } }
javascript
function renderText(args, that) { if (isNewTextVersion) { args[0] = { ...args[0], children: pseudoText(args[0].children) }; return defaultTextRender.apply(that, args); } else { const element = defaultTextRender.apply(that, args); return React.cloneElement(element, { children: pseudoText(element.props.children) }); } }
[ "function", "renderText", "(", "args", ",", "that", ")", "{", "if", "(", "isNewTextVersion", ")", "{", "args", "[", "0", "]", "=", "{", "...", "args", "[", "0", "]", ",", "children", ":", "pseudoText", "(", "args", "[", "0", "]", ".", "children", ")", "}", ";", "return", "defaultTextRender", ".", "apply", "(", "that", ",", "args", ")", ";", "}", "else", "{", "const", "element", "=", "defaultTextRender", ".", "apply", "(", "that", ",", "args", ")", ";", "return", "React", ".", "cloneElement", "(", "element", ",", "{", "children", ":", "pseudoText", "(", "element", ".", "props", ".", "children", ")", "}", ")", ";", "}", "}" ]
React native text render logic
[ "React", "native", "text", "render", "logic" ]
96bae9ff62765a397ade9254ebd38e16396fba5f
https://github.com/zeljkoX/react-native-pseudo-localization/blob/96bae9ff62765a397ade9254ebd38e16396fba5f/src/PseudoText.js#L38-L48
44,154
zeljkoX/react-native-pseudo-localization
src/PseudoText.js
render
function render() { return function(...args) { return ( <PseudoContext.Consumer> {value => { if (!value) { return defaultTextRender.apply(this, args); } return renderText(args, this); }} </PseudoContext.Consumer> ); }; }
javascript
function render() { return function(...args) { return ( <PseudoContext.Consumer> {value => { if (!value) { return defaultTextRender.apply(this, args); } return renderText(args, this); }} </PseudoContext.Consumer> ); }; }
[ "function", "render", "(", ")", "{", "return", "function", "(", "...", "args", ")", "{", "return", "(", "<", "PseudoContext", ".", "Consumer", ">", "\n ", "{", "value", "=>", "{", "if", "(", "!", "value", ")", "{", "return", "defaultTextRender", ".", "apply", "(", "this", ",", "args", ")", ";", "}", "return", "renderText", "(", "args", ",", "this", ")", ";", "}", "}", "\n ", "<", "/", "PseudoContext", ".", "Consumer", ">", ")", ";", "}", ";", "}" ]
main render function that is connected to PseudoContext
[ "main", "render", "function", "that", "is", "connected", "to", "PseudoContext" ]
96bae9ff62765a397ade9254ebd38e16396fba5f
https://github.com/zeljkoX/react-native-pseudo-localization/blob/96bae9ff62765a397ade9254ebd38e16396fba5f/src/PseudoText.js#L51-L64
44,155
lambtron/medium-cli
lib/medium.js
clean
function clean(post) { return reject({ title: post.title, contentFormat: post.contentFormat, content: post.content, tags: post.tags, canonicalUrl: post.canonicalUrl, publishStatus: post.publishStatus, license: post.license }); }
javascript
function clean(post) { return reject({ title: post.title, contentFormat: post.contentFormat, content: post.content, tags: post.tags, canonicalUrl: post.canonicalUrl, publishStatus: post.publishStatus, license: post.license }); }
[ "function", "clean", "(", "post", ")", "{", "return", "reject", "(", "{", "title", ":", "post", ".", "title", ",", "contentFormat", ":", "post", ".", "contentFormat", ",", "content", ":", "post", ".", "content", ",", "tags", ":", "post", ".", "tags", ",", "canonicalUrl", ":", "post", ".", "canonicalUrl", ",", "publishStatus", ":", "post", ".", "publishStatus", ",", "license", ":", "post", ".", "license", "}", ")", ";", "}" ]
Remove unneeded attributes from `post`.
[ "Remove", "unneeded", "attributes", "from", "post", "." ]
a2d4baea4f5665e42dedd72b5ed7ae97f6de79eb
https://github.com/lambtron/medium-cli/blob/a2d4baea4f5665e42dedd72b5ed7ae97f6de79eb/lib/medium.js#L52-L62
44,156
andreypopp/rrouter
src/fetchViews.js
fetchViews
function fetchViews(match) { var activeTrace = match.activeTrace.map(fetchViewsStep); return activeTrace.some(Promise.is) ? Promise.all(activeTrace).then((activeTrace) => merge(match, {activeTrace})) : Promise.resolve(merge(match, {activeTrace})); }
javascript
function fetchViews(match) { var activeTrace = match.activeTrace.map(fetchViewsStep); return activeTrace.some(Promise.is) ? Promise.all(activeTrace).then((activeTrace) => merge(match, {activeTrace})) : Promise.resolve(merge(match, {activeTrace})); }
[ "function", "fetchViews", "(", "match", ")", "{", "var", "activeTrace", "=", "match", ".", "activeTrace", ".", "map", "(", "fetchViewsStep", ")", ";", "return", "activeTrace", ".", "some", "(", "Promise", ".", "is", ")", "?", "Promise", ".", "all", "(", "activeTrace", ")", ".", "then", "(", "(", "activeTrace", ")", "=>", "merge", "(", "match", ",", "{", "activeTrace", "}", ")", ")", ":", "Promise", ".", "resolve", "(", "merge", "(", "match", ",", "{", "activeTrace", "}", ")", ")", ";", "}" ]
Fetch views for match @param {Match} match @returns {Match}
[ "Fetch", "views", "for", "match" ]
4287dc666254af61f1d169c12fb61a1bfd7e2623
https://github.com/andreypopp/rrouter/blob/4287dc666254af61f1d169c12fb61a1bfd7e2623/src/fetchViews.js#L22-L28
44,157
jacksonrayhamilton/tern-jsx
jsx.js
function (node) { var key = node.property || node.key; if (!node.computed && key.type === 'JSXIdentifier') { return key.name; } // Delegate to original method. return infer.propName.apply(infer, arguments); }
javascript
function (node) { var key = node.property || node.key; if (!node.computed && key.type === 'JSXIdentifier') { return key.name; } // Delegate to original method. return infer.propName.apply(infer, arguments); }
[ "function", "(", "node", ")", "{", "var", "key", "=", "node", ".", "property", "||", "node", ".", "key", ";", "if", "(", "!", "node", ".", "computed", "&&", "key", ".", "type", "===", "'JSXIdentifier'", ")", "{", "return", "key", ".", "name", ";", "}", "// Delegate to original method.", "return", "infer", ".", "propName", ".", "apply", "(", "infer", ",", "arguments", ")", ";", "}" ]
infer.propName, but treat JSXIdentifier like Identifier.
[ "infer", ".", "propName", "but", "treat", "JSXIdentifier", "like", "Identifier", "." ]
6988e4c20363645ccc757b34d432c25a8340bd9c
https://github.com/jacksonrayhamilton/tern-jsx/blob/6988e4c20363645ccc757b34d432c25a8340bd9c/jsx.js#L55-L62
44,158
jacksonrayhamilton/tern-jsx
jsx.js
function (node, scope) { var finder = infer.typeFinder[node.type]; return finder ? finder(node, scope) : infer.ANull; }
javascript
function (node, scope) { var finder = infer.typeFinder[node.type]; return finder ? finder(node, scope) : infer.ANull; }
[ "function", "(", "node", ",", "scope", ")", "{", "var", "finder", "=", "infer", ".", "typeFinder", "[", "node", ".", "type", "]", ";", "return", "finder", "?", "finder", "(", "node", ",", "scope", ")", ":", "infer", ".", "ANull", ";", "}" ]
Re-implement Tern's internal findType.
[ "Re", "-", "implement", "Tern", "s", "internal", "findType", "." ]
6988e4c20363645ccc757b34d432c25a8340bd9c
https://github.com/jacksonrayhamilton/tern-jsx/blob/6988e4c20363645ccc757b34d432c25a8340bd9c/jsx.js#L65-L68
44,159
infusionsoft/bower-locker
bower-locker-status.js
status
function status(isVerbose) { // Load bower.json and make sure it is a locked bower.json file var bowerConfigStr = fs.readFileSync('bower.json', {encoding: 'utf8'}); var bowerConfig = JSON.parse(bowerConfigStr); var locked = bowerConfig.bowerLocker; if (locked) { var timeDiff = (new Date()).getTime() - (new Date(locked.lastUpdated)).getTime(); console.log('bower.json was locked as of %s (%s)', locked.lastUpdated, formatTimeDiff(timeDiff)); if (isVerbose) { console.log('Currently locked dependencies:'); Object.keys(locked.lockedVersions).forEach(function(key) { console.log(' %s (%s): %s', key, locked.lockedVersions[key], bowerConfig.resolutions[key]); }); } } else { console.log('The bower.json is currently unlocked.\n'); } }
javascript
function status(isVerbose) { // Load bower.json and make sure it is a locked bower.json file var bowerConfigStr = fs.readFileSync('bower.json', {encoding: 'utf8'}); var bowerConfig = JSON.parse(bowerConfigStr); var locked = bowerConfig.bowerLocker; if (locked) { var timeDiff = (new Date()).getTime() - (new Date(locked.lastUpdated)).getTime(); console.log('bower.json was locked as of %s (%s)', locked.lastUpdated, formatTimeDiff(timeDiff)); if (isVerbose) { console.log('Currently locked dependencies:'); Object.keys(locked.lockedVersions).forEach(function(key) { console.log(' %s (%s): %s', key, locked.lockedVersions[key], bowerConfig.resolutions[key]); }); } } else { console.log('The bower.json is currently unlocked.\n'); } }
[ "function", "status", "(", "isVerbose", ")", "{", "// Load bower.json and make sure it is a locked bower.json file", "var", "bowerConfigStr", "=", "fs", ".", "readFileSync", "(", "'bower.json'", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "var", "bowerConfig", "=", "JSON", ".", "parse", "(", "bowerConfigStr", ")", ";", "var", "locked", "=", "bowerConfig", ".", "bowerLocker", ";", "if", "(", "locked", ")", "{", "var", "timeDiff", "=", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", "-", "(", "new", "Date", "(", "locked", ".", "lastUpdated", ")", ")", ".", "getTime", "(", ")", ";", "console", ".", "log", "(", "'bower.json was locked as of %s (%s)'", ",", "locked", ".", "lastUpdated", ",", "formatTimeDiff", "(", "timeDiff", ")", ")", ";", "if", "(", "isVerbose", ")", "{", "console", ".", "log", "(", "'Currently locked dependencies:'", ")", ";", "Object", ".", "keys", "(", "locked", ".", "lockedVersions", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "console", ".", "log", "(", "' %s (%s): %s'", ",", "key", ",", "locked", ".", "lockedVersions", "[", "key", "]", ",", "bowerConfig", ".", "resolutions", "[", "key", "]", ")", ";", "}", ")", ";", "}", "}", "else", "{", "console", ".", "log", "(", "'The bower.json is currently unlocked.\\n'", ")", ";", "}", "}" ]
Function to output the current status of the `bower.json` file. Indicates whether it is locked, when it was locked, and if verbose the locked version of the dependencies. @param {Boolean} isVerbose Flag to indicate whether we should log verbosely or not
[ "Function", "to", "output", "the", "current", "status", "of", "the", "bower", ".", "json", "file", ".", "Indicates", "whether", "it", "is", "locked", "when", "it", "was", "locked", "and", "if", "verbose", "the", "locked", "version", "of", "the", "dependencies", "." ]
9da98159684015ca872b4c35a1a72eb17ee93b37
https://github.com/infusionsoft/bower-locker/blob/9da98159684015ca872b4c35a1a72eb17ee93b37/bower-locker-status.js#L35-L52
44,160
TNRIS/weather-alerts-geojson
lib/feature-transform.js
polygonize
function polygonize (str, properties) { var coordinates = str.split(' ').map(function (pairStr) { return pairStr.split(',').reverse().map(Number); }); return polygon([coordinates], properties); }
javascript
function polygonize (str, properties) { var coordinates = str.split(' ').map(function (pairStr) { return pairStr.split(',').reverse().map(Number); }); return polygon([coordinates], properties); }
[ "function", "polygonize", "(", "str", ",", "properties", ")", "{", "var", "coordinates", "=", "str", ".", "split", "(", "' '", ")", ".", "map", "(", "function", "(", "pairStr", ")", "{", "return", "pairStr", ".", "split", "(", "','", ")", ".", "reverse", "(", ")", ".", "map", "(", "Number", ")", ";", "}", ")", ";", "return", "polygon", "(", "[", "coordinates", "]", ",", "properties", ")", ";", "}" ]
converts an alert polygon string to a GeoJSON polygon geometry
[ "converts", "an", "alert", "polygon", "string", "to", "a", "GeoJSON", "polygon", "geometry" ]
ccc91f033e5bc91957c9903763d4593a2a97a3d1
https://github.com/TNRIS/weather-alerts-geojson/blob/ccc91f033e5bc91957c9903763d4593a2a97a3d1/lib/feature-transform.js#L8-L14
44,161
TNRIS/weather-alerts-geojson
lib/feature-transform.js
decodify
function decodify (featureCollection, code, properties) { var feature = find(featureCollection.features, {'id': code}); if (feature) { feature.properties = properties; } return feature; }
javascript
function decodify (featureCollection, code, properties) { var feature = find(featureCollection.features, {'id': code}); if (feature) { feature.properties = properties; } return feature; }
[ "function", "decodify", "(", "featureCollection", ",", "code", ",", "properties", ")", "{", "var", "feature", "=", "find", "(", "featureCollection", ".", "features", ",", "{", "'id'", ":", "code", "}", ")", ";", "if", "(", "feature", ")", "{", "feature", ".", "properties", "=", "properties", ";", "}", "return", "feature", ";", "}" ]
pulls feature from featureCollection with ID matching code, and creates a new feature from that geometry with properties substituted in
[ "pulls", "feature", "from", "featureCollection", "with", "ID", "matching", "code", "and", "creates", "a", "new", "feature", "from", "that", "geometry", "with", "properties", "substituted", "in" ]
ccc91f033e5bc91957c9903763d4593a2a97a3d1
https://github.com/TNRIS/weather-alerts-geojson/blob/ccc91f033e5bc91957c9903763d4593a2a97a3d1/lib/feature-transform.js#L19-L27
44,162
rtsao/scope-styles
lib/inline-prop-to-css.js
toCSSProp
function toCSSProp(prop) { var dashed = prop.replace(regex, '-$&').toLowerCase(); return dashed[0] === 'm' && dashed[1] === 's' ? '-' + dashed : dashed; }
javascript
function toCSSProp(prop) { var dashed = prop.replace(regex, '-$&').toLowerCase(); return dashed[0] === 'm' && dashed[1] === 's' ? '-' + dashed : dashed; }
[ "function", "toCSSProp", "(", "prop", ")", "{", "var", "dashed", "=", "prop", ".", "replace", "(", "regex", ",", "'-$&'", ")", ".", "toLowerCase", "(", ")", ";", "return", "dashed", "[", "0", "]", "===", "'m'", "&&", "dashed", "[", "1", "]", "===", "'s'", "?", "'-'", "+", "dashed", ":", "dashed", ";", "}" ]
Converts a style object property name to its CSS property name equivalent, taking into account the exception of `-ms` vendor prefixes @param {string} prop - Style object property name, e.g. `WebkitTransition` @return {string} - CSS property name, e.g. `-webkit-transition`
[ "Converts", "a", "style", "object", "property", "name", "to", "its", "CSS", "property", "name", "equivalent", "taking", "into", "account", "the", "exception", "of", "-", "ms", "vendor", "prefixes" ]
4ea0b959f4b58e7736408d746fca78f8747bd476
https://github.com/rtsao/scope-styles/blob/4ea0b959f4b58e7736408d746fca78f8747bd476/lib/inline-prop-to-css.js#L11-L14
44,163
MoOx/reduce-function-call
index.js
reduceFunctionCall
function reduceFunctionCall(string, functionRE, callback) { var call = string return getFunctionCalls(string, functionRE).reduce(function(string, obj) { return string.replace(obj.functionIdentifier + "(" + obj.matches.body + ")", evalFunctionCall(obj.matches.body, obj.functionIdentifier, callback, call, functionRE)) }, string) }
javascript
function reduceFunctionCall(string, functionRE, callback) { var call = string return getFunctionCalls(string, functionRE).reduce(function(string, obj) { return string.replace(obj.functionIdentifier + "(" + obj.matches.body + ")", evalFunctionCall(obj.matches.body, obj.functionIdentifier, callback, call, functionRE)) }, string) }
[ "function", "reduceFunctionCall", "(", "string", ",", "functionRE", ",", "callback", ")", "{", "var", "call", "=", "string", "return", "getFunctionCalls", "(", "string", ",", "functionRE", ")", ".", "reduce", "(", "function", "(", "string", ",", "obj", ")", "{", "return", "string", ".", "replace", "(", "obj", ".", "functionIdentifier", "+", "\"(\"", "+", "obj", ".", "matches", ".", "body", "+", "\")\"", ",", "evalFunctionCall", "(", "obj", ".", "matches", ".", "body", ",", "obj", ".", "functionIdentifier", ",", "callback", ",", "call", ",", "functionRE", ")", ")", "}", ",", "string", ")", "}" ]
Walkthrough all expressions, evaluate them and insert them into the declaration @param {Array} expressions @param {Object} declaration
[ "Walkthrough", "all", "expressions", "evaluate", "them", "and", "insert", "them", "into", "the", "declaration" ]
d947e59b75e5c01502993c1f8aaae4741ca35d0f
https://github.com/MoOx/reduce-function-call/blob/d947e59b75e5c01502993c1f8aaae4741ca35d0f/index.js#L20-L25
44,164
MoOx/reduce-function-call
index.js
getFunctionCalls
function getFunctionCalls(call, functionRE) { var expressions = [] var fnRE = typeof functionRE === "string" ? new RegExp("\\b(" + functionRE + ")\\(") : functionRE do { var searchMatch = fnRE.exec(call) if (!searchMatch) { return expressions } if (searchMatch[1] === undefined) { throw new Error("Missing the first couple of parenthesis to get the function identifier in " + functionRE) } var fn = searchMatch[1] var startIndex = searchMatch.index var matches = balanced("(", ")", call.substring(startIndex)) if (!matches || matches.start !== searchMatch[0].length - 1) { throw new SyntaxError(fn + "(): missing closing ')' in the value '" + call + "'") } expressions.push({matches: matches, functionIdentifier: fn}) call = matches.post } while (fnRE.test(call)) return expressions }
javascript
function getFunctionCalls(call, functionRE) { var expressions = [] var fnRE = typeof functionRE === "string" ? new RegExp("\\b(" + functionRE + ")\\(") : functionRE do { var searchMatch = fnRE.exec(call) if (!searchMatch) { return expressions } if (searchMatch[1] === undefined) { throw new Error("Missing the first couple of parenthesis to get the function identifier in " + functionRE) } var fn = searchMatch[1] var startIndex = searchMatch.index var matches = balanced("(", ")", call.substring(startIndex)) if (!matches || matches.start !== searchMatch[0].length - 1) { throw new SyntaxError(fn + "(): missing closing ')' in the value '" + call + "'") } expressions.push({matches: matches, functionIdentifier: fn}) call = matches.post } while (fnRE.test(call)) return expressions }
[ "function", "getFunctionCalls", "(", "call", ",", "functionRE", ")", "{", "var", "expressions", "=", "[", "]", "var", "fnRE", "=", "typeof", "functionRE", "===", "\"string\"", "?", "new", "RegExp", "(", "\"\\\\b(\"", "+", "functionRE", "+", "\")\\\\(\"", ")", ":", "functionRE", "do", "{", "var", "searchMatch", "=", "fnRE", ".", "exec", "(", "call", ")", "if", "(", "!", "searchMatch", ")", "{", "return", "expressions", "}", "if", "(", "searchMatch", "[", "1", "]", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "\"Missing the first couple of parenthesis to get the function identifier in \"", "+", "functionRE", ")", "}", "var", "fn", "=", "searchMatch", "[", "1", "]", "var", "startIndex", "=", "searchMatch", ".", "index", "var", "matches", "=", "balanced", "(", "\"(\"", ",", "\")\"", ",", "call", ".", "substring", "(", "startIndex", ")", ")", "if", "(", "!", "matches", "||", "matches", ".", "start", "!==", "searchMatch", "[", "0", "]", ".", "length", "-", "1", ")", "{", "throw", "new", "SyntaxError", "(", "fn", "+", "\"(): missing closing ')' in the value '\"", "+", "call", "+", "\"'\"", ")", "}", "expressions", ".", "push", "(", "{", "matches", ":", "matches", ",", "functionIdentifier", ":", "fn", "}", ")", "call", "=", "matches", ".", "post", "}", "while", "(", "fnRE", ".", "test", "(", "call", ")", ")", "return", "expressions", "}" ]
Parses expressions in a value @param {String} value @returns {Array} @api private
[ "Parses", "expressions", "in", "a", "value" ]
d947e59b75e5c01502993c1f8aaae4741ca35d0f
https://github.com/MoOx/reduce-function-call/blob/d947e59b75e5c01502993c1f8aaae4741ca35d0f/index.js#L35-L61
44,165
MoOx/reduce-function-call
index.js
evalFunctionCall
function evalFunctionCall (string, functionIdentifier, callback, call, functionRE) { // allow recursivity return callback(reduceFunctionCall(string, functionRE, callback), functionIdentifier, call) }
javascript
function evalFunctionCall (string, functionIdentifier, callback, call, functionRE) { // allow recursivity return callback(reduceFunctionCall(string, functionRE, callback), functionIdentifier, call) }
[ "function", "evalFunctionCall", "(", "string", ",", "functionIdentifier", ",", "callback", ",", "call", ",", "functionRE", ")", "{", "// allow recursivity", "return", "callback", "(", "reduceFunctionCall", "(", "string", ",", "functionRE", ",", "callback", ")", ",", "functionIdentifier", ",", "call", ")", "}" ]
Evaluates an expression @param {String} expression @returns {String} @api private
[ "Evaluates", "an", "expression" ]
d947e59b75e5c01502993c1f8aaae4741ca35d0f
https://github.com/MoOx/reduce-function-call/blob/d947e59b75e5c01502993c1f8aaae4741ca35d0f/index.js#L71-L74
44,166
OLIOEX/gulp-json-modify
index.js
space
function space(json) { var match = json.match(/^(?:(\t+)|( +))"/m) return match ? (match[1] ? '\t' : match[2].length) : '' }
javascript
function space(json) { var match = json.match(/^(?:(\t+)|( +))"/m) return match ? (match[1] ? '\t' : match[2].length) : '' }
[ "function", "space", "(", "json", ")", "{", "var", "match", "=", "json", ".", "match", "(", "/", "^(?:(\\t+)|( +))\"", "/", "m", ")", "return", "match", "?", "(", "match", "[", "1", "]", "?", "'\\t'", ":", "match", "[", "2", "]", ".", "length", ")", ":", "''", "}" ]
Figured out which "space" params to be used for JSON.stringfiy.
[ "Figured", "out", "which", "space", "params", "to", "be", "used", "for", "JSON", ".", "stringfiy", "." ]
a26a66e9139bba2ac1849abdf4c38d09e7ec10fe
https://github.com/OLIOEX/gulp-json-modify/blob/a26a66e9139bba2ac1849abdf4c38d09e7ec10fe/index.js#L89-L92
44,167
andreypopp/rrouter
src/mergeInto.js
mergeInto
function mergeInto(one, two) { checkMergeObjectArg(one); if (two != null) { checkMergeObjectArg(two); for (var key in two) { if (!two.hasOwnProperty(key)) { continue; } one[key] = two[key]; } } }
javascript
function mergeInto(one, two) { checkMergeObjectArg(one); if (two != null) { checkMergeObjectArg(two); for (var key in two) { if (!two.hasOwnProperty(key)) { continue; } one[key] = two[key]; } } }
[ "function", "mergeInto", "(", "one", ",", "two", ")", "{", "checkMergeObjectArg", "(", "one", ")", ";", "if", "(", "two", "!=", "null", ")", "{", "checkMergeObjectArg", "(", "two", ")", ";", "for", "(", "var", "key", "in", "two", ")", "{", "if", "(", "!", "two", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "continue", ";", "}", "one", "[", "key", "]", "=", "two", "[", "key", "]", ";", "}", "}", "}" ]
Shallow merges two structures by mutating the first parameter. @param {object} one Object to be merged into. @param {?object} two Optional object with properties to merge from.
[ "Shallow", "merges", "two", "structures", "by", "mutating", "the", "first", "parameter", "." ]
4287dc666254af61f1d169c12fb61a1bfd7e2623
https://github.com/andreypopp/rrouter/blob/4287dc666254af61f1d169c12fb61a1bfd7e2623/src/mergeInto.js#L32-L43
44,168
tralves/ns-vue-loader
lib/loader.js
getRawRequest
function getRawRequest ( { resource, loaderIndex, loaders }, excludedPreLoaders = /eslint-loader/ ) { return loaderUtils.getRemainingRequest({ resource: resource, loaderIndex: loaderIndex, loaders: loaders.filter(loader => !excludedPreLoaders.test(loader.path)) }) }
javascript
function getRawRequest ( { resource, loaderIndex, loaders }, excludedPreLoaders = /eslint-loader/ ) { return loaderUtils.getRemainingRequest({ resource: resource, loaderIndex: loaderIndex, loaders: loaders.filter(loader => !excludedPreLoaders.test(loader.path)) }) }
[ "function", "getRawRequest", "(", "{", "resource", ",", "loaderIndex", ",", "loaders", "}", ",", "excludedPreLoaders", "=", "/", "eslint-loader", "/", ")", "{", "return", "loaderUtils", ".", "getRemainingRequest", "(", "{", "resource", ":", "resource", ",", "loaderIndex", ":", "loaderIndex", ",", "loaders", ":", "loaders", ".", "filter", "(", "loader", "=>", "!", "excludedPreLoaders", ".", "test", "(", "loader", ".", "path", ")", ")", "}", ")", "}" ]
When extracting parts from the source vue file, we want to apply the loaders chained before ns-vue-loader, but exclude some loaders that simply produces side effects such as linting.
[ "When", "extracting", "parts", "from", "the", "source", "vue", "file", "we", "want", "to", "apply", "the", "loaders", "chained", "before", "ns", "-", "vue", "-", "loader", "but", "exclude", "some", "loaders", "that", "simply", "produces", "side", "effects", "such", "as", "linting", "." ]
6ff08bcae22bc37bcc394fb55181f76924eeb49c
https://github.com/tralves/ns-vue-loader/blob/6ff08bcae22bc37bcc394fb55181f76924eeb49c/lib/loader.js#L36-L45
44,169
tralves/ns-vue-loader
lib/loader.js
stringifyLoaders
function stringifyLoaders (loaders) { return loaders .map( obj => obj && typeof obj === 'object' && typeof obj.loader === 'string' ? obj.loader + (obj.options ? '?' + JSON.stringify(obj.options) : '') : obj ) .join('!') }
javascript
function stringifyLoaders (loaders) { return loaders .map( obj => obj && typeof obj === 'object' && typeof obj.loader === 'string' ? obj.loader + (obj.options ? '?' + JSON.stringify(obj.options) : '') : obj ) .join('!') }
[ "function", "stringifyLoaders", "(", "loaders", ")", "{", "return", "loaders", ".", "map", "(", "obj", "=>", "obj", "&&", "typeof", "obj", "===", "'object'", "&&", "typeof", "obj", ".", "loader", "===", "'string'", "?", "obj", ".", "loader", "+", "(", "obj", ".", "options", "?", "'?'", "+", "JSON", ".", "stringify", "(", "obj", ".", "options", ")", ":", "''", ")", ":", "obj", ")", ".", "join", "(", "'!'", ")", "}" ]
stringify an Array of loader objects
[ "stringify", "an", "Array", "of", "loader", "objects" ]
6ff08bcae22bc37bcc394fb55181f76924eeb49c
https://github.com/tralves/ns-vue-loader/blob/6ff08bcae22bc37bcc394fb55181f76924eeb49c/lib/loader.js#L516-L526
44,170
zxqfox/reserved-words
lib/reserved-words.js
_hash
function _hash() { var set = Array.prototype.map.call(arguments, function(v) { return typeof v === 'string' ? v : Object.keys(v).join(' '); }).join(' '); return set.split(/\s+/) .reduce(function(res, keyword) { res[keyword] = true; return res; }, {}); }
javascript
function _hash() { var set = Array.prototype.map.call(arguments, function(v) { return typeof v === 'string' ? v : Object.keys(v).join(' '); }).join(' '); return set.split(/\s+/) .reduce(function(res, keyword) { res[keyword] = true; return res; }, {}); }
[ "function", "_hash", "(", ")", "{", "var", "set", "=", "Array", ".", "prototype", ".", "map", ".", "call", "(", "arguments", ",", "function", "(", "v", ")", "{", "return", "typeof", "v", "===", "'string'", "?", "v", ":", "Object", ".", "keys", "(", "v", ")", ".", "join", "(", "' '", ")", ";", "}", ")", ".", "join", "(", "' '", ")", ";", "return", "set", ".", "split", "(", "/", "\\s+", "/", ")", ".", "reduce", "(", "function", "(", "res", ",", "keyword", ")", "{", "res", "[", "keyword", "]", "=", "true", ";", "return", "res", ";", "}", ",", "{", "}", ")", ";", "}" ]
Generates hash from strings @private @param {...String|KeywordsHash} keywords - Space-delimited string or previous result of _hash @return {KeywordsHash} - Object with keywords in keys and true in values
[ "Generates", "hash", "from", "strings" ]
d4dcf840d14efa590158364374d0ad20b2474485
https://github.com/zxqfox/reserved-words/blob/d4dcf840d14efa590158364374d0ad20b2474485/lib/reserved-words.js#L167-L177
44,171
andreypopp/rrouter
src/matchRoutes.js
matchRoute
function matchRoute(route, path) { if (route.pattern === undefined && route.path !== undefined) { var routePattern; if (route.path instanceof RegExp) { routePattern = route.path; } else { var routePath = normalize(route.path); routePattern = route.children.length > 0 ? routePath + '*' : routePath; } Object.defineProperty(route, 'pattern', { enumerable: false, value: pattern.newPattern(routePattern) }); } if (route.pattern) { var match = route.pattern.match(path); if (match) { if (route.pattern.isRegex) { match = {_: match}; } if (!match._ || match._[0] === '/' || match._[0] === '') { delete match._; } } return match; } else { return path === '/' || path === '' ? {} : {_: [path]}; } }
javascript
function matchRoute(route, path) { if (route.pattern === undefined && route.path !== undefined) { var routePattern; if (route.path instanceof RegExp) { routePattern = route.path; } else { var routePath = normalize(route.path); routePattern = route.children.length > 0 ? routePath + '*' : routePath; } Object.defineProperty(route, 'pattern', { enumerable: false, value: pattern.newPattern(routePattern) }); } if (route.pattern) { var match = route.pattern.match(path); if (match) { if (route.pattern.isRegex) { match = {_: match}; } if (!match._ || match._[0] === '/' || match._[0] === '') { delete match._; } } return match; } else { return path === '/' || path === '' ? {} : {_: [path]}; } }
[ "function", "matchRoute", "(", "route", ",", "path", ")", "{", "if", "(", "route", ".", "pattern", "===", "undefined", "&&", "route", ".", "path", "!==", "undefined", ")", "{", "var", "routePattern", ";", "if", "(", "route", ".", "path", "instanceof", "RegExp", ")", "{", "routePattern", "=", "route", ".", "path", ";", "}", "else", "{", "var", "routePath", "=", "normalize", "(", "route", ".", "path", ")", ";", "routePattern", "=", "route", ".", "children", ".", "length", ">", "0", "?", "routePath", "+", "'*'", ":", "routePath", ";", "}", "Object", ".", "defineProperty", "(", "route", ",", "'pattern'", ",", "{", "enumerable", ":", "false", ",", "value", ":", "pattern", ".", "newPattern", "(", "routePattern", ")", "}", ")", ";", "}", "if", "(", "route", ".", "pattern", ")", "{", "var", "match", "=", "route", ".", "pattern", ".", "match", "(", "path", ")", ";", "if", "(", "match", ")", "{", "if", "(", "route", ".", "pattern", ".", "isRegex", ")", "{", "match", "=", "{", "_", ":", "match", "}", ";", "}", "if", "(", "!", "match", ".", "_", "||", "match", ".", "_", "[", "0", "]", "===", "'/'", "||", "match", ".", "_", "[", "0", "]", "===", "''", ")", "{", "delete", "match", ".", "_", ";", "}", "}", "return", "match", ";", "}", "else", "{", "return", "path", "===", "'/'", "||", "path", "===", "''", "?", "{", "}", ":", "{", "_", ":", "[", "path", "]", "}", ";", "}", "}" ]
Match route against path @param {Route} route @param {String} path @returns {Match|Null}
[ "Match", "route", "against", "path" ]
4287dc666254af61f1d169c12fb61a1bfd7e2623
https://github.com/andreypopp/rrouter/blob/4287dc666254af61f1d169c12fb61a1bfd7e2623/src/matchRoutes.js#L37-L73
44,172
andreypopp/rrouter
src/matchRoutes.js
matchRoutes
function matchRoutes(routes, path, query) { query = query === undefined ? {} : isString(query) ? qs.parse(query) : query; return matchRoutesImpl(routes, path, query); }
javascript
function matchRoutes(routes, path, query) { query = query === undefined ? {} : isString(query) ? qs.parse(query) : query; return matchRoutesImpl(routes, path, query); }
[ "function", "matchRoutes", "(", "routes", ",", "path", ",", "query", ")", "{", "query", "=", "query", "===", "undefined", "?", "{", "}", ":", "isString", "(", "query", ")", "?", "qs", ".", "parse", "(", "query", ")", ":", "query", ";", "return", "matchRoutesImpl", "(", "routes", ",", "path", ",", "query", ")", ";", "}" ]
Match routes against path @param {Route} routes @param {String} path @returns {Match}
[ "Match", "routes", "against", "path" ]
4287dc666254af61f1d169c12fb61a1bfd7e2623
https://github.com/andreypopp/rrouter/blob/4287dc666254af61f1d169c12fb61a1bfd7e2623/src/matchRoutes.js#L121-L124
44,173
doowb/async-helpers
index.js
AsyncHelpers
function AsyncHelpers(options) { if (!(this instanceof AsyncHelpers)) { return new AsyncHelpers(options); } this.options = Object.assign({}, options); this.prefix = this.options.prefix || '{$ASYNCID$'; this.globalCounter = AsyncHelpers.globalCounter++; this.helpers = {}; this.counter = 0; this.prefixRegex = toRegex(this.prefix); }
javascript
function AsyncHelpers(options) { if (!(this instanceof AsyncHelpers)) { return new AsyncHelpers(options); } this.options = Object.assign({}, options); this.prefix = this.options.prefix || '{$ASYNCID$'; this.globalCounter = AsyncHelpers.globalCounter++; this.helpers = {}; this.counter = 0; this.prefixRegex = toRegex(this.prefix); }
[ "function", "AsyncHelpers", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AsyncHelpers", ")", ")", "{", "return", "new", "AsyncHelpers", "(", "options", ")", ";", "}", "this", ".", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "this", ".", "prefix", "=", "this", ".", "options", ".", "prefix", "||", "'{$ASYNCID$'", ";", "this", ".", "globalCounter", "=", "AsyncHelpers", ".", "globalCounter", "++", ";", "this", ".", "helpers", "=", "{", "}", ";", "this", ".", "counter", "=", "0", ";", "this", ".", "prefixRegex", "=", "toRegex", "(", "this", ".", "prefix", ")", ";", "}" ]
Create a new instance of AsyncHelpers ```js var asyncHelpers = new AsyncHelpers(); ``` @param {Object} `options` options to pass to instance @return {Object} new AsyncHelpers instance @api public
[ "Create", "a", "new", "instance", "of", "AsyncHelpers" ]
ea33b6e2062ec49a9b4780f847f6f24eb52fd43e
https://github.com/doowb/async-helpers/blob/ea33b6e2062ec49a9b4780f847f6f24eb52fd43e/index.js#L32-L42
44,174
doowb/async-helpers
index.js
wrapper
function wrapper() { var num = self.counter++; var id = createId(prefix, num); var token = { name: name, async: !!fn.async, prefix: prefix, num: num, id: id, fn: fn, args: [].slice.call(arguments) }; define(token, 'context', this); stash[id] = token; return id; }
javascript
function wrapper() { var num = self.counter++; var id = createId(prefix, num); var token = { name: name, async: !!fn.async, prefix: prefix, num: num, id: id, fn: fn, args: [].slice.call(arguments) }; define(token, 'context', this); stash[id] = token; return id; }
[ "function", "wrapper", "(", ")", "{", "var", "num", "=", "self", ".", "counter", "++", ";", "var", "id", "=", "createId", "(", "prefix", ",", "num", ")", ";", "var", "token", "=", "{", "name", ":", "name", ",", "async", ":", "!", "!", "fn", ".", "async", ",", "prefix", ":", "prefix", ",", "num", ":", "num", ",", "id", ":", "id", ",", "fn", ":", "fn", ",", "args", ":", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", "}", ";", "define", "(", "token", ",", "'context'", ",", "this", ")", ";", "stash", "[", "id", "]", "=", "token", ";", "return", "id", ";", "}" ]
wrap the helper and generate a unique ID for resolving it
[ "wrap", "the", "helper", "and", "generate", "a", "unique", "ID", "for", "resolving", "it" ]
ea33b6e2062ec49a9b4780f847f6f24eb52fd43e
https://github.com/doowb/async-helpers/blob/ea33b6e2062ec49a9b4780f847f6f24eb52fd43e/index.js#L198-L215
44,175
doowb/async-helpers
index.js
formatError
function formatError(err, helper, args) { err.helper = helper; define(err, 'args', args); return err; }
javascript
function formatError(err, helper, args) { err.helper = helper; define(err, 'args', args); return err; }
[ "function", "formatError", "(", "err", ",", "helper", ",", "args", ")", "{", "err", ".", "helper", "=", "helper", ";", "define", "(", "err", ",", "'args'", ",", "args", ")", ";", "return", "err", ";", "}" ]
Format an error message to provide better information about the helper and the arguments passed to the helper when the error occurred. @param {Object} `err` Error object @param {Object} `helper` helper object to provide more information @param {Array} `args` Array of arguments passed to the helper. @return {Object} Formatted Error object
[ "Format", "an", "error", "message", "to", "provide", "better", "information", "about", "the", "helper", "and", "the", "arguments", "passed", "to", "the", "helper", "when", "the", "error", "occurred", "." ]
ea33b6e2062ec49a9b4780f847f6f24eb52fd43e
https://github.com/doowb/async-helpers/blob/ea33b6e2062ec49a9b4780f847f6f24eb52fd43e/index.js#L460-L464
44,176
doowb/async-helpers
index.js
toRegex
function toRegex(prefix) { var key = appendPrefix(prefix, '(\\d+)'); if (cache.hasOwnProperty(key)) { return cache[key]; } var regex = new RegExp(createRegexString(key), 'g'); cache[key] = regex; return regex; }
javascript
function toRegex(prefix) { var key = appendPrefix(prefix, '(\\d+)'); if (cache.hasOwnProperty(key)) { return cache[key]; } var regex = new RegExp(createRegexString(key), 'g'); cache[key] = regex; return regex; }
[ "function", "toRegex", "(", "prefix", ")", "{", "var", "key", "=", "appendPrefix", "(", "prefix", ",", "'(\\\\d+)'", ")", ";", "if", "(", "cache", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "return", "cache", "[", "key", "]", ";", "}", "var", "regex", "=", "new", "RegExp", "(", "createRegexString", "(", "key", ")", ",", "'g'", ")", ";", "cache", "[", "key", "]", "=", "regex", ";", "return", "regex", ";", "}" ]
Create a regular expression based on the given `prefix`. @param {String} `prefix` @return {RegExp}
[ "Create", "a", "regular", "expression", "based", "on", "the", "given", "prefix", "." ]
ea33b6e2062ec49a9b4780f847f6f24eb52fd43e
https://github.com/doowb/async-helpers/blob/ea33b6e2062ec49a9b4780f847f6f24eb52fd43e/index.js#L496-L504
44,177
doowb/async-helpers
index.js
createRegexString
function createRegexString(prefix) { var key = 'createRegexString:' + prefix; if (cache.hasOwnProperty(key)) { return cache[key]; } var str = (prefix + '(\\d+)$}').replace(/\\?([${}])/g, '\\$1'); cache[key] = str; return str; }
javascript
function createRegexString(prefix) { var key = 'createRegexString:' + prefix; if (cache.hasOwnProperty(key)) { return cache[key]; } var str = (prefix + '(\\d+)$}').replace(/\\?([${}])/g, '\\$1'); cache[key] = str; return str; }
[ "function", "createRegexString", "(", "prefix", ")", "{", "var", "key", "=", "'createRegexString:'", "+", "prefix", ";", "if", "(", "cache", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "return", "cache", "[", "key", "]", ";", "}", "var", "str", "=", "(", "prefix", "+", "'(\\\\d+)$}'", ")", ".", "replace", "(", "/", "\\\\?([${}])", "/", "g", ",", "'\\\\$1'", ")", ";", "cache", "[", "key", "]", "=", "str", ";", "return", "str", ";", "}" ]
Create a string to pass into `RegExp` for checking for and finding async ids. @param {String} `prefix` prefix to use for the first part of the regex @return {String} string to pass into `RegExp`
[ "Create", "a", "string", "to", "pass", "into", "RegExp", "for", "checking", "for", "and", "finding", "async", "ids", "." ]
ea33b6e2062ec49a9b4780f847f6f24eb52fd43e
https://github.com/doowb/async-helpers/blob/ea33b6e2062ec49a9b4780f847f6f24eb52fd43e/index.js#L512-L520
44,178
jostinsu/postcss-svg-sprite
index.js
getCss
function getCss(shapes, options) { const spriteRelative = path.relative(options.styleOutput, options.spritePath); return new CSS(shapes, { nameSpace: options.nameSpace, block: options.dirname, separator: options.cssSeparator, spriteRelative: path.normalize(spriteRelative).replace(/\\/g, '/') }).getCss(); }
javascript
function getCss(shapes, options) { const spriteRelative = path.relative(options.styleOutput, options.spritePath); return new CSS(shapes, { nameSpace: options.nameSpace, block: options.dirname, separator: options.cssSeparator, spriteRelative: path.normalize(spriteRelative).replace(/\\/g, '/') }).getCss(); }
[ "function", "getCss", "(", "shapes", ",", "options", ")", "{", "const", "spriteRelative", "=", "path", ".", "relative", "(", "options", ".", "styleOutput", ",", "options", ".", "spritePath", ")", ";", "return", "new", "CSS", "(", "shapes", ",", "{", "nameSpace", ":", "options", ".", "nameSpace", ",", "block", ":", "options", ".", "dirname", ",", "separator", ":", "options", ".", "cssSeparator", ",", "spriteRelative", ":", "path", ".", "normalize", "(", "spriteRelative", ")", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'/'", ")", "}", ")", ".", "getCss", "(", ")", ";", "}" ]
Get css code which corresponding to svg sprite @param {Object} shapes @param {Object} options @return {String} cssStr
[ "Get", "css", "code", "which", "corresponding", "to", "svg", "sprite" ]
8d19ac5b93a9a1177adcbe06249b7d37b39f1a67
https://github.com/jostinsu/postcss-svg-sprite/blob/8d19ac5b93a9a1177adcbe06249b7d37b39f1a67/index.js#L174-L182
44,179
jostinsu/postcss-svg-sprite
index.js
_isSvgFile
function _isSvgFile(file, dirPath) { let flag = false, isFile = fs.statSync(path.resolve(dirPath, file)).isFile(); if (isFile) { // Exclude directory if (path.extname(file) === '.svg') { // Only accept files which with svg suffix flag = true; } } return flag; }
javascript
function _isSvgFile(file, dirPath) { let flag = false, isFile = fs.statSync(path.resolve(dirPath, file)).isFile(); if (isFile) { // Exclude directory if (path.extname(file) === '.svg') { // Only accept files which with svg suffix flag = true; } } return flag; }
[ "function", "_isSvgFile", "(", "file", ",", "dirPath", ")", "{", "let", "flag", "=", "false", ",", "isFile", "=", "fs", ".", "statSync", "(", "path", ".", "resolve", "(", "dirPath", ",", "file", ")", ")", ".", "isFile", "(", ")", ";", "if", "(", "isFile", ")", "{", "// Exclude directory", "if", "(", "path", ".", "extname", "(", "file", ")", "===", "'.svg'", ")", "{", "// Only accept files which with svg suffix", "flag", "=", "true", ";", "}", "}", "return", "flag", ";", "}" ]
Determine whether the current file is an svg file @param {String} file @param {String} dirPath @return {Boolean}
[ "Determine", "whether", "the", "current", "file", "is", "an", "svg", "file" ]
8d19ac5b93a9a1177adcbe06249b7d37b39f1a67
https://github.com/jostinsu/postcss-svg-sprite/blob/8d19ac5b93a9a1177adcbe06249b7d37b39f1a67/index.js#L220-L230
44,180
jostinsu/postcss-svg-sprite
index.js
log
function log(msg, type) { switch (type) { case 'error': fancyLog(`${PLUGINNAME}: ${colors.red(`Error, ${msg}`)}`); break; case 'warn': fancyLog(`${PLUGINNAME}: ${colors.yellow(`Warning, ${msg}`)}`); break; case 'info': fancyLog(`${PLUGINNAME}: ${colors.green(`Info, ${msg}`)}`); break; default: fancyLog(`${PLUGINNAME}: ${colors.green(`Info, ${msg}`)}`); break; } }
javascript
function log(msg, type) { switch (type) { case 'error': fancyLog(`${PLUGINNAME}: ${colors.red(`Error, ${msg}`)}`); break; case 'warn': fancyLog(`${PLUGINNAME}: ${colors.yellow(`Warning, ${msg}`)}`); break; case 'info': fancyLog(`${PLUGINNAME}: ${colors.green(`Info, ${msg}`)}`); break; default: fancyLog(`${PLUGINNAME}: ${colors.green(`Info, ${msg}`)}`); break; } }
[ "function", "log", "(", "msg", ",", "type", ")", "{", "switch", "(", "type", ")", "{", "case", "'error'", ":", "fancyLog", "(", "`", "${", "PLUGINNAME", "}", "${", "colors", ".", "red", "(", "`", "${", "msg", "}", "`", ")", "}", "`", ")", ";", "break", ";", "case", "'warn'", ":", "fancyLog", "(", "`", "${", "PLUGINNAME", "}", "${", "colors", ".", "yellow", "(", "`", "${", "msg", "}", "`", ")", "}", "`", ")", ";", "break", ";", "case", "'info'", ":", "fancyLog", "(", "`", "${", "PLUGINNAME", "}", "${", "colors", ".", "green", "(", "`", "${", "msg", "}", "`", ")", "}", "`", ")", ";", "break", ";", "default", ":", "fancyLog", "(", "`", "${", "PLUGINNAME", "}", "${", "colors", ".", "green", "(", "`", "${", "msg", "}", "`", ")", "}", "`", ")", ";", "break", ";", "}", "}" ]
Format log based on different types @param {String} msg @param {String} type
[ "Format", "log", "based", "on", "different", "types" ]
8d19ac5b93a9a1177adcbe06249b7d37b39f1a67
https://github.com/jostinsu/postcss-svg-sprite/blob/8d19ac5b93a9a1177adcbe06249b7d37b39f1a67/index.js#L239-L258
44,181
zzarcon/psaux
lib/psaux.js
parseProcesses
function parseProcesses(list, ps) { var p = ps.split(/ +/); list.push({ user: p[0], pid: p[1], cpu: parseFloat(p[2]), mem: parseFloat(p[3]), vsz: p[4], rss: p[5], tt: p[6], stat: p[7], started: p[8], time: p[9], command: p.slice(10).join(' ') }); return list; }
javascript
function parseProcesses(list, ps) { var p = ps.split(/ +/); list.push({ user: p[0], pid: p[1], cpu: parseFloat(p[2]), mem: parseFloat(p[3]), vsz: p[4], rss: p[5], tt: p[6], stat: p[7], started: p[8], time: p[9], command: p.slice(10).join(' ') }); return list; }
[ "function", "parseProcesses", "(", "list", ",", "ps", ")", "{", "var", "p", "=", "ps", ".", "split", "(", "/", " +", "/", ")", ";", "list", ".", "push", "(", "{", "user", ":", "p", "[", "0", "]", ",", "pid", ":", "p", "[", "1", "]", ",", "cpu", ":", "parseFloat", "(", "p", "[", "2", "]", ")", ",", "mem", ":", "parseFloat", "(", "p", "[", "3", "]", ")", ",", "vsz", ":", "p", "[", "4", "]", ",", "rss", ":", "p", "[", "5", "]", ",", "tt", ":", "p", "[", "6", "]", ",", "stat", ":", "p", "[", "7", "]", ",", "started", ":", "p", "[", "8", "]", ",", "time", ":", "p", "[", "9", "]", ",", "command", ":", "p", ".", "slice", "(", "10", ")", ".", "join", "(", "' '", ")", "}", ")", ";", "return", "list", ";", "}" ]
Normalizes the process payload into a readable object. @param {Array} list @param {Array} ps @return {Array}
[ "Normalizes", "the", "process", "payload", "into", "a", "readable", "object", "." ]
616ee237ecdada422e540b466eda8f097001330d
https://github.com/zzarcon/psaux/blob/616ee237ecdada422e540b466eda8f097001330d/lib/psaux.js#L90-L108
44,182
zzarcon/psaux
lib/psaux.js
cleanValue
function cleanValue(val, char) { var num; var conditions = val.split(' '); var i = 0; while (!num && i < conditions.length) { if (conditions[i].indexOf(char) > -1) { num = conditions[i].replace(/<|>|~/g, ''); } i++; } return parseFloat(num); }
javascript
function cleanValue(val, char) { var num; var conditions = val.split(' '); var i = 0; while (!num && i < conditions.length) { if (conditions[i].indexOf(char) > -1) { num = conditions[i].replace(/<|>|~/g, ''); } i++; } return parseFloat(num); }
[ "function", "cleanValue", "(", "val", ",", "char", ")", "{", "var", "num", ";", "var", "conditions", "=", "val", ".", "split", "(", "' '", ")", ";", "var", "i", "=", "0", ";", "while", "(", "!", "num", "&&", "i", "<", "conditions", ".", "length", ")", "{", "if", "(", "conditions", "[", "i", "]", ".", "indexOf", "(", "char", ")", ">", "-", "1", ")", "{", "num", "=", "conditions", "[", "i", "]", ".", "replace", "(", "/", "<|>|~", "/", "g", ",", "''", ")", ";", "}", "i", "++", ";", "}", "return", "parseFloat", "(", "num", ")", ";", "}" ]
Return the value for a certain condition @example cleanValue('foo <100', '<') == 100 cleanValue('>5 <1 bar', '>') == 5 @param {String} val @param {String} char @return {Float}
[ "Return", "the", "value", "for", "a", "certain", "condition" ]
616ee237ecdada422e540b466eda8f097001330d
https://github.com/zzarcon/psaux/blob/616ee237ecdada422e540b466eda8f097001330d/lib/psaux.js#L171-L184
44,183
benekastah/oppo
website/js/ender.js
ancestorMatch
function ancestorMatch(el, tokens, dividedTokens, root) { var cand // recursively work backwards through the tokens and up the dom, covering all options function crawl(e, i, p) { while (p = walker[dividedTokens[i]](p, e)) { if (isNode(p) && (found = interpret.apply(p, q(tokens[i])))) { if (i) { if (cand = crawl(p, i - 1, p)) return cand } else return p } } } return (cand = crawl(el, tokens.length - 1, el)) && (!root || isAncestor(cand, root)) }
javascript
function ancestorMatch(el, tokens, dividedTokens, root) { var cand // recursively work backwards through the tokens and up the dom, covering all options function crawl(e, i, p) { while (p = walker[dividedTokens[i]](p, e)) { if (isNode(p) && (found = interpret.apply(p, q(tokens[i])))) { if (i) { if (cand = crawl(p, i - 1, p)) return cand } else return p } } } return (cand = crawl(el, tokens.length - 1, el)) && (!root || isAncestor(cand, root)) }
[ "function", "ancestorMatch", "(", "el", ",", "tokens", ",", "dividedTokens", ",", "root", ")", "{", "var", "cand", "// recursively work backwards through the tokens and up the dom, covering all options", "function", "crawl", "(", "e", ",", "i", ",", "p", ")", "{", "while", "(", "p", "=", "walker", "[", "dividedTokens", "[", "i", "]", "]", "(", "p", ",", "e", ")", ")", "{", "if", "(", "isNode", "(", "p", ")", "&&", "(", "found", "=", "interpret", ".", "apply", "(", "p", ",", "q", "(", "tokens", "[", "i", "]", ")", ")", ")", ")", "{", "if", "(", "i", ")", "{", "if", "(", "cand", "=", "crawl", "(", "p", ",", "i", "-", "1", ",", "p", ")", ")", "return", "cand", "}", "else", "return", "p", "}", "}", "}", "return", "(", "cand", "=", "crawl", "(", "el", ",", "tokens", ".", "length", "-", "1", ",", "el", ")", ")", "&&", "(", "!", "root", "||", "isAncestor", "(", "cand", ",", "root", ")", ")", "}" ]
given elements matching the right-most part of a selector, filter out any that don't match the rest
[ "given", "elements", "matching", "the", "right", "-", "most", "part", "of", "a", "selector", "filter", "out", "any", "that", "don", "t", "match", "the", "rest" ]
5cfc3dfd47c71a28b597de2a75fffc9d28880178
https://github.com/benekastah/oppo/blob/5cfc3dfd47c71a28b597de2a75fffc9d28880178/website/js/ender.js#L2863-L2876
44,184
nwtn/grunt-respimg
tasks/respimg.js
function(callback) { async.each(task.files, function(file, callback2) { var srcPath = file.src[0], extName = path.extname(srcPath).toLowerCase(); // if it’s an SVG or a PDF, copy the file to the output dir if (extName === '.svg' || extName === '.pdf') { var dstPath = getDestination(srcPath, file.dest, false, options); fs.copy(srcPath, dstPath, function(err){ if (err) { grunt.fail.fatal(err); } outputFiles.push(dstPath); callback2(null); }); } else { callback2(null); } }, callback); }
javascript
function(callback) { async.each(task.files, function(file, callback2) { var srcPath = file.src[0], extName = path.extname(srcPath).toLowerCase(); // if it’s an SVG or a PDF, copy the file to the output dir if (extName === '.svg' || extName === '.pdf') { var dstPath = getDestination(srcPath, file.dest, false, options); fs.copy(srcPath, dstPath, function(err){ if (err) { grunt.fail.fatal(err); } outputFiles.push(dstPath); callback2(null); }); } else { callback2(null); } }, callback); }
[ "function", "(", "callback", ")", "{", "async", ".", "each", "(", "task", ".", "files", ",", "function", "(", "file", ",", "callback2", ")", "{", "var", "srcPath", "=", "file", ".", "src", "[", "0", "]", ",", "extName", "=", "path", ".", "extname", "(", "srcPath", ")", ".", "toLowerCase", "(", ")", ";", "// if it’s an SVG or a PDF, copy the file to the output dir", "if", "(", "extName", "===", "'.svg'", "||", "extName", "===", "'.pdf'", ")", "{", "var", "dstPath", "=", "getDestination", "(", "srcPath", ",", "file", ".", "dest", ",", "false", ",", "options", ")", ";", "fs", ".", "copy", "(", "srcPath", ",", "dstPath", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "grunt", ".", "fail", ".", "fatal", "(", "err", ")", ";", "}", "outputFiles", ".", "push", "(", "dstPath", ")", ";", "callback2", "(", "null", ")", ";", "}", ")", ";", "}", "else", "{", "callback2", "(", "null", ")", ";", "}", "}", ",", "callback", ")", ";", "}" ]
copy SVGs and PDFs
[ "copy", "SVGs", "and", "PDFs" ]
0f3a95d68737d63ac9ff062b2bf83f8d610b3bea
https://github.com/nwtn/grunt-respimg/blob/0f3a95d68737d63ac9ff062b2bf83f8d610b3bea/tasks/respimg.js#L1470-L1491
44,185
wanderview/node-netbios-name-service
lib/broadcast.js
function(response) { delete self._requestState[transactionId]; if (typeof callback === 'function') { // negative response if (response.error) { var owner = response.answerRecords[0].nb.entries[0].address; callback(null, false, owner); // positive response } else { // ignore as this should not happen for 'broadcast' nodes } } }
javascript
function(response) { delete self._requestState[transactionId]; if (typeof callback === 'function') { // negative response if (response.error) { var owner = response.answerRecords[0].nb.entries[0].address; callback(null, false, owner); // positive response } else { // ignore as this should not happen for 'broadcast' nodes } } }
[ "function", "(", "response", ")", "{", "delete", "self", ".", "_requestState", "[", "transactionId", "]", ";", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "// negative response", "if", "(", "response", ".", "error", ")", "{", "var", "owner", "=", "response", ".", "answerRecords", "[", "0", "]", ".", "nb", ".", "entries", "[", "0", "]", ".", "address", ";", "callback", "(", "null", ",", "false", ",", "owner", ")", ";", "// positive response", "}", "else", "{", "// ignore as this should not happen for 'broadcast' nodes", "}", "}", "}" ]
In broadcast mode if we get a response then that means someone is disputing our claim to this name.
[ "In", "broadcast", "mode", "if", "we", "get", "a", "response", "then", "that", "means", "someone", "is", "disputing", "our", "claim", "to", "this", "name", "." ]
90cd3c36b5625123ec435577bad1d054de420961
https://github.com/wanderview/node-netbios-name-service/blob/90cd3c36b5625123ec435577bad1d054de420961/lib/broadcast.js#L116-L129
44,186
wanderview/node-netbios-name-service
lib/broadcast.js
function() { delete self._requestState[transactionId]; self._localMap.add(nbname, group, address, ttl, self._type); self._sendRefresh(nbname, function(error) { if (typeof callback === 'function') { callback(error, !error); } }); }
javascript
function() { delete self._requestState[transactionId]; self._localMap.add(nbname, group, address, ttl, self._type); self._sendRefresh(nbname, function(error) { if (typeof callback === 'function') { callback(error, !error); } }); }
[ "function", "(", ")", "{", "delete", "self", ".", "_requestState", "[", "transactionId", "]", ";", "self", ".", "_localMap", ".", "add", "(", "nbname", ",", "group", ",", "address", ",", "ttl", ",", "self", ".", "_type", ")", ";", "self", ".", "_sendRefresh", "(", "nbname", ",", "function", "(", "error", ")", "{", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "callback", "(", "error", ",", "!", "error", ")", ";", "}", "}", ")", ";", "}" ]
If we send the required number of registration requests and do not get a conflict response from any other nodes then we can safely declare this name ours.
[ "If", "we", "send", "the", "required", "number", "of", "registration", "requests", "and", "do", "not", "get", "a", "conflict", "response", "from", "any", "other", "nodes", "then", "we", "can", "safely", "declare", "this", "name", "ours", "." ]
90cd3c36b5625123ec435577bad1d054de420961
https://github.com/wanderview/node-netbios-name-service/blob/90cd3c36b5625123ec435577bad1d054de420961/lib/broadcast.js#L134-L142
44,187
thingtrack/node-red-contrib-inotify
inotify/inotify.js
getWatcherByPath
function getWatcherByPath(path) { var rlt = undefined; watchers.forEach(function(watcher) { if (watcher.path == path) rlt = watcher; }); return rlt; }
javascript
function getWatcherByPath(path) { var rlt = undefined; watchers.forEach(function(watcher) { if (watcher.path == path) rlt = watcher; }); return rlt; }
[ "function", "getWatcherByPath", "(", "path", ")", "{", "var", "rlt", "=", "undefined", ";", "watchers", ".", "forEach", "(", "function", "(", "watcher", ")", "{", "if", "(", "watcher", ".", "path", "==", "path", ")", "rlt", "=", "watcher", ";", "}", ")", ";", "return", "rlt", ";", "}" ]
global watcher list
[ "global", "watcher", "list" ]
376d61dd00ef34e4b61c681e6011618c75ada6e1
https://github.com/thingtrack/node-red-contrib-inotify/blob/376d61dd00ef34e4b61c681e6011618c75ada6e1/inotify/inotify.js#L6-L15
44,188
andreypopp/rrouter
src/makeViewFactoryForMatch.js
makeViewFactoryForMatch
function makeViewFactoryForMatch(match) { var views = {}; for (var i = match.activeTrace.length - 1; i >= 0; i--) { var step = match.activeTrace[i]; var stepProps = getStepProps(step); views = merge(views, collectSubViews(stepProps, views)); if (step.route.view !== undefined) { return makeViewFactory(step.route.view, merge(stepProps, views)); } } }
javascript
function makeViewFactoryForMatch(match) { var views = {}; for (var i = match.activeTrace.length - 1; i >= 0; i--) { var step = match.activeTrace[i]; var stepProps = getStepProps(step); views = merge(views, collectSubViews(stepProps, views)); if (step.route.view !== undefined) { return makeViewFactory(step.route.view, merge(stepProps, views)); } } }
[ "function", "makeViewFactoryForMatch", "(", "match", ")", "{", "var", "views", "=", "{", "}", ";", "for", "(", "var", "i", "=", "match", ".", "activeTrace", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "var", "step", "=", "match", ".", "activeTrace", "[", "i", "]", ";", "var", "stepProps", "=", "getStepProps", "(", "step", ")", ";", "views", "=", "merge", "(", "views", ",", "collectSubViews", "(", "stepProps", ",", "views", ")", ")", ";", "if", "(", "step", ".", "route", ".", "view", "!==", "undefined", ")", "{", "return", "makeViewFactory", "(", "step", ".", "route", ".", "view", ",", "merge", "(", "stepProps", ",", "views", ")", ")", ";", "}", "}", "}" ]
Make view factory for a match object @param {Match} match @param {Object} props @returns {ReactComponent}
[ "Make", "view", "factory", "for", "a", "match", "object" ]
4287dc666254af61f1d169c12fb61a1bfd7e2623
https://github.com/andreypopp/rrouter/blob/4287dc666254af61f1d169c12fb61a1bfd7e2623/src/makeViewFactoryForMatch.js#L62-L75
44,189
andreypopp/rrouter
examples/async-code-loading/index.js
AsyncRoute
function AsyncRoute(props) { props = merge(props, { viewPromise: loadViewModule, viewModule: props.view, view: undefined }) return Route(props); }
javascript
function AsyncRoute(props) { props = merge(props, { viewPromise: loadViewModule, viewModule: props.view, view: undefined }) return Route(props); }
[ "function", "AsyncRoute", "(", "props", ")", "{", "props", "=", "merge", "(", "props", ",", "{", "viewPromise", ":", "loadViewModule", ",", "viewModule", ":", "props", ".", "view", ",", "view", ":", "undefined", "}", ")", "return", "Route", "(", "props", ")", ";", "}" ]
a "syntax sugar" which shortcuts defining view code loading
[ "a", "syntax", "sugar", "which", "shortcuts", "defining", "view", "code", "loading" ]
4287dc666254af61f1d169c12fb61a1bfd7e2623
https://github.com/andreypopp/rrouter/blob/4287dc666254af61f1d169c12fb61a1bfd7e2623/examples/async-code-loading/index.js#L21-L28
44,190
markogresak/canihazip
index.js
CanIHazIp
function CanIHazIp(callback) { return new Promise(function (resolve) { var httpCallback = function (response) { var responseData = ''; // When data is received, append it to `responseData`. response.on('data', function (chunk) { responseData += chunk; }); // When response ends, resolve returned Promise and call `callback` if it's a function. response.on('end', function () { resolve(responseData); if (typeof callback === 'function') { callback(responseData); } }); }; // Connect options for canihazip API, GET method is implicit. var canihazipOptions = { host: 'canihazip.com', path: '/s' }; // Make a request to canihazip and end it immediately. protocol.request(canihazipOptions, httpCallback) .end(); }); }
javascript
function CanIHazIp(callback) { return new Promise(function (resolve) { var httpCallback = function (response) { var responseData = ''; // When data is received, append it to `responseData`. response.on('data', function (chunk) { responseData += chunk; }); // When response ends, resolve returned Promise and call `callback` if it's a function. response.on('end', function () { resolve(responseData); if (typeof callback === 'function') { callback(responseData); } }); }; // Connect options for canihazip API, GET method is implicit. var canihazipOptions = { host: 'canihazip.com', path: '/s' }; // Make a request to canihazip and end it immediately. protocol.request(canihazipOptions, httpCallback) .end(); }); }
[ "function", "CanIHazIp", "(", "callback", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "var", "httpCallback", "=", "function", "(", "response", ")", "{", "var", "responseData", "=", "''", ";", "// When data is received, append it to `responseData`.", "response", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "responseData", "+=", "chunk", ";", "}", ")", ";", "// When response ends, resolve returned Promise and call `callback` if it's a function.", "response", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "resolve", "(", "responseData", ")", ";", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "callback", "(", "responseData", ")", ";", "}", "}", ")", ";", "}", ";", "// Connect options for canihazip API, GET method is implicit.", "var", "canihazipOptions", "=", "{", "host", ":", "'canihazip.com'", ",", "path", ":", "'/s'", "}", ";", "// Make a request to canihazip and end it immediately.", "protocol", ".", "request", "(", "canihazipOptions", ",", "httpCallback", ")", ".", "end", "(", ")", ";", "}", ")", ";", "}" ]
CanIHazIp constructor function. @param {Function=} callback (optional) Function to be called with IP data after server responds. @returns {Promise} Promise which is resolved with IP data after server responds.
[ "CanIHazIp", "constructor", "function", "." ]
8d930ee990f3572a304be0205bf7c7d5f2c3cdf4
https://github.com/markogresak/canihazip/blob/8d930ee990f3572a304be0205bf7c7d5f2c3cdf4/index.js#L22-L51
44,191
infusionsoft/bower-locker
bower-locker-common.js
mapDependencyData
function mapDependencyData(bowerInfo) { return { name: bowerInfo.name, commit: bowerInfo._resolution !== undefined ? bowerInfo._resolution.commit : undefined, release: bowerInfo._release, src: bowerInfo._source, originalSrc: bowerInfo._originalSource }; }
javascript
function mapDependencyData(bowerInfo) { return { name: bowerInfo.name, commit: bowerInfo._resolution !== undefined ? bowerInfo._resolution.commit : undefined, release: bowerInfo._release, src: bowerInfo._source, originalSrc: bowerInfo._originalSource }; }
[ "function", "mapDependencyData", "(", "bowerInfo", ")", "{", "return", "{", "name", ":", "bowerInfo", ".", "name", ",", "commit", ":", "bowerInfo", ".", "_resolution", "!==", "undefined", "?", "bowerInfo", ".", "_resolution", ".", "commit", ":", "undefined", ",", "release", ":", "bowerInfo", ".", "_release", ",", "src", ":", "bowerInfo", ".", "_source", ",", "originalSrc", ":", "bowerInfo", ".", "_originalSource", "}", ";", "}" ]
Function to pull out and map the specific bower component metadata to our preferred form @param {Object} bowerInfo @returns {{name: String, commit: String, release: String, src: String, originalSrc: String}}
[ "Function", "to", "pull", "out", "and", "map", "the", "specific", "bower", "component", "metadata", "to", "our", "preferred", "form" ]
9da98159684015ca872b4c35a1a72eb17ee93b37
https://github.com/infusionsoft/bower-locker/blob/9da98159684015ca872b4c35a1a72eb17ee93b37/bower-locker-common.js#L13-L21
44,192
infusionsoft/bower-locker
bower-locker-common.js
getDependency
function getDependency(filepath) { var bowerInfoStr = fs.readFileSync(filepath, {encoding: 'utf8'}); var bowerInfo = JSON.parse(bowerInfoStr); return mapDependencyData(bowerInfo); }
javascript
function getDependency(filepath) { var bowerInfoStr = fs.readFileSync(filepath, {encoding: 'utf8'}); var bowerInfo = JSON.parse(bowerInfoStr); return mapDependencyData(bowerInfo); }
[ "function", "getDependency", "(", "filepath", ")", "{", "var", "bowerInfoStr", "=", "fs", ".", "readFileSync", "(", "filepath", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "var", "bowerInfo", "=", "JSON", ".", "parse", "(", "bowerInfoStr", ")", ";", "return", "mapDependencyData", "(", "bowerInfo", ")", ";", "}" ]
Function to read and return the specific metadata of a bower component @param {String} filepath Filepath pointing to the JSON metadata @returns {Object} Returns dependency metadata object (dirName, commit, release, src, etc.)
[ "Function", "to", "read", "and", "return", "the", "specific", "metadata", "of", "a", "bower", "component" ]
9da98159684015ca872b4c35a1a72eb17ee93b37
https://github.com/infusionsoft/bower-locker/blob/9da98159684015ca872b4c35a1a72eb17ee93b37/bower-locker-common.js#L28-L32
44,193
infusionsoft/bower-locker
bower-locker-common.js
getBowerFolder
function getBowerFolder() { var bowerRC = getBowerRC(); if (bowerRC === null || bowerRC.directory === undefined) { return 'bower_components'; } return bowerRC.directory; }
javascript
function getBowerFolder() { var bowerRC = getBowerRC(); if (bowerRC === null || bowerRC.directory === undefined) { return 'bower_components'; } return bowerRC.directory; }
[ "function", "getBowerFolder", "(", ")", "{", "var", "bowerRC", "=", "getBowerRC", "(", ")", ";", "if", "(", "bowerRC", "===", "null", "||", "bowerRC", ".", "directory", "===", "undefined", ")", "{", "return", "'bower_components'", ";", "}", "return", "bowerRC", ".", "directory", ";", "}" ]
Gets the folder in which Bower components are stored @returns {String}
[ "Gets", "the", "folder", "in", "which", "Bower", "components", "are", "stored" ]
9da98159684015ca872b4c35a1a72eb17ee93b37
https://github.com/infusionsoft/bower-locker/blob/9da98159684015ca872b4c35a1a72eb17ee93b37/bower-locker-common.js#L50-L57
44,194
infusionsoft/bower-locker
bower-locker-common.js
getAllDependencies
function getAllDependencies() { var folder = './' + getBowerFolder(); var bowerDependencies = fs.readdirSync(folder, {encoding: 'utf8'}); var dependencyInfos = []; bowerDependencies.forEach(function(dirname) { var filepath = nodePath.resolve(cwd, folder, dirname, '.bower.json'); if (fs.existsSync(filepath)) { var dependencyInfo = getDependency(filepath); dependencyInfo.dirName = dirname; dependencyInfos.push(dependencyInfo); } }); return dependencyInfos; }
javascript
function getAllDependencies() { var folder = './' + getBowerFolder(); var bowerDependencies = fs.readdirSync(folder, {encoding: 'utf8'}); var dependencyInfos = []; bowerDependencies.forEach(function(dirname) { var filepath = nodePath.resolve(cwd, folder, dirname, '.bower.json'); if (fs.existsSync(filepath)) { var dependencyInfo = getDependency(filepath); dependencyInfo.dirName = dirname; dependencyInfos.push(dependencyInfo); } }); return dependencyInfos; }
[ "function", "getAllDependencies", "(", ")", "{", "var", "folder", "=", "'./'", "+", "getBowerFolder", "(", ")", ";", "var", "bowerDependencies", "=", "fs", ".", "readdirSync", "(", "folder", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "var", "dependencyInfos", "=", "[", "]", ";", "bowerDependencies", ".", "forEach", "(", "function", "(", "dirname", ")", "{", "var", "filepath", "=", "nodePath", ".", "resolve", "(", "cwd", ",", "folder", ",", "dirname", ",", "'.bower.json'", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "filepath", ")", ")", "{", "var", "dependencyInfo", "=", "getDependency", "(", "filepath", ")", ";", "dependencyInfo", ".", "dirName", "=", "dirname", ";", "dependencyInfos", ".", "push", "(", "dependencyInfo", ")", ";", "}", "}", ")", ";", "return", "dependencyInfos", ";", "}" ]
Function to return the metadata for all the dependencies loaded within the `bower_components` directory @returns {Object} Returns dependency object for each dependency containing (dirName, commit, release, src, etc.)
[ "Function", "to", "return", "the", "metadata", "for", "all", "the", "dependencies", "loaded", "within", "the", "bower_components", "directory" ]
9da98159684015ca872b4c35a1a72eb17ee93b37
https://github.com/infusionsoft/bower-locker/blob/9da98159684015ca872b4c35a1a72eb17ee93b37/bower-locker-common.js#L63-L78
44,195
cavinsmith/bdsm.js
src/bdsm.js
optimizeHistogram
function optimizeHistogram(histogram, options) { options = _.defaults(options || {}, { colorDistanceThreshold: 22 }); for (var i = 0; i < histogram.length - 1; i++) { if (histogram[i].count === 0) { continue; } for (var j = i + 1; j < histogram.length; j++) { var distance = getColorDistance(histogram[i].color, histogram[j].color); if (distance <= options.colorDistanceThreshold) { histogram[i].count += histogram[j].count; histogram[j].count = 0; } } } histogram = _.filter(histogram, function (group) { return group.count > 0; }); return sortByCountDesc(histogram); }
javascript
function optimizeHistogram(histogram, options) { options = _.defaults(options || {}, { colorDistanceThreshold: 22 }); for (var i = 0; i < histogram.length - 1; i++) { if (histogram[i].count === 0) { continue; } for (var j = i + 1; j < histogram.length; j++) { var distance = getColorDistance(histogram[i].color, histogram[j].color); if (distance <= options.colorDistanceThreshold) { histogram[i].count += histogram[j].count; histogram[j].count = 0; } } } histogram = _.filter(histogram, function (group) { return group.count > 0; }); return sortByCountDesc(histogram); }
[ "function", "optimizeHistogram", "(", "histogram", ",", "options", ")", "{", "options", "=", "_", ".", "defaults", "(", "options", "||", "{", "}", ",", "{", "colorDistanceThreshold", ":", "22", "}", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "histogram", ".", "length", "-", "1", ";", "i", "++", ")", "{", "if", "(", "histogram", "[", "i", "]", ".", "count", "===", "0", ")", "{", "continue", ";", "}", "for", "(", "var", "j", "=", "i", "+", "1", ";", "j", "<", "histogram", ".", "length", ";", "j", "++", ")", "{", "var", "distance", "=", "getColorDistance", "(", "histogram", "[", "i", "]", ".", "color", ",", "histogram", "[", "j", "]", ".", "color", ")", ";", "if", "(", "distance", "<=", "options", ".", "colorDistanceThreshold", ")", "{", "histogram", "[", "i", "]", ".", "count", "+=", "histogram", "[", "j", "]", ".", "count", ";", "histogram", "[", "j", "]", ".", "count", "=", "0", ";", "}", "}", "}", "histogram", "=", "_", ".", "filter", "(", "histogram", ",", "function", "(", "group", ")", "{", "return", "group", ".", "count", ">", "0", ";", "}", ")", ";", "return", "sortByCountDesc", "(", "histogram", ")", ";", "}" ]
Merges groups with colors that are close enough into single group.
[ "Merges", "groups", "with", "colors", "that", "are", "close", "enough", "into", "single", "group", "." ]
3707073d9d382e4c4eca30243ec3d94ce632b39d
https://github.com/cavinsmith/bdsm.js/blob/3707073d9d382e4c4eca30243ec3d94ce632b39d/src/bdsm.js#L68-L93
44,196
ben-yip/grunt-html-imports
tasks/html_imports.js
function (filepath) { // console.log('processing: ' + filepath); // read file source, saved in RAM var content = grunt.file.read(filepath); /* * Reset pattern's last search index to 0 * at the beginning for each file content. * * NOTE: * Since the pattern is always the same regex instance, * property 'lastIndex' changes each time when .exec() is performed. * To avoid 'lastIndex' affected by recursive function call, * its value MUST be cached for each file content. */ var cacheLastIndex = 0; _.pattern.lastIndex = cacheLastIndex; var matches = _.pattern.exec(content); cacheLastIndex = _.pattern.lastIndex; // While there are matches (of import-links) in file content while (matches !== null) { /* * Construct the imported file's absolute path * (doesn't matter whether or not a relative path), * and recursively search in imported file. (dept-first) * * NOTE: * - the regex uses capture group, the first match is the fragment file path. */ var currentDir = path.dirname(filepath), relativeFilepath = matches[1].trim(), importedFilepath = path.resolve(currentDir, relativeFilepath); var returnContent = getReplacedFileContent(importedFilepath); /* * For current file content, * replace import-link tag with return value. * * NOTE: * Because of dept-first search, * should ONLY replace the first match in current content. * rather than search globally. */ content = content.replace(_.patternNonGlobal, returnContent); // console.log(content); // console.log(matches); // console.log('-----'); /* * Keep searching in current file. * * NOTE: * After replacing part of the content (the step above), * the content's length changes accordingly. * Thus the 'lastIndex' property should shift to * the proper position to ensure next search. */ var deltaLength = returnContent.length - matches[0].length; _.pattern.lastIndex = cacheLastIndex + deltaLength; matches = _.pattern.exec(content); cacheLastIndex = _.pattern.lastIndex; } // When searching and replacing is done, return the result. return content; }
javascript
function (filepath) { // console.log('processing: ' + filepath); // read file source, saved in RAM var content = grunt.file.read(filepath); /* * Reset pattern's last search index to 0 * at the beginning for each file content. * * NOTE: * Since the pattern is always the same regex instance, * property 'lastIndex' changes each time when .exec() is performed. * To avoid 'lastIndex' affected by recursive function call, * its value MUST be cached for each file content. */ var cacheLastIndex = 0; _.pattern.lastIndex = cacheLastIndex; var matches = _.pattern.exec(content); cacheLastIndex = _.pattern.lastIndex; // While there are matches (of import-links) in file content while (matches !== null) { /* * Construct the imported file's absolute path * (doesn't matter whether or not a relative path), * and recursively search in imported file. (dept-first) * * NOTE: * - the regex uses capture group, the first match is the fragment file path. */ var currentDir = path.dirname(filepath), relativeFilepath = matches[1].trim(), importedFilepath = path.resolve(currentDir, relativeFilepath); var returnContent = getReplacedFileContent(importedFilepath); /* * For current file content, * replace import-link tag with return value. * * NOTE: * Because of dept-first search, * should ONLY replace the first match in current content. * rather than search globally. */ content = content.replace(_.patternNonGlobal, returnContent); // console.log(content); // console.log(matches); // console.log('-----'); /* * Keep searching in current file. * * NOTE: * After replacing part of the content (the step above), * the content's length changes accordingly. * Thus the 'lastIndex' property should shift to * the proper position to ensure next search. */ var deltaLength = returnContent.length - matches[0].length; _.pattern.lastIndex = cacheLastIndex + deltaLength; matches = _.pattern.exec(content); cacheLastIndex = _.pattern.lastIndex; } // When searching and replacing is done, return the result. return content; }
[ "function", "(", "filepath", ")", "{", "// console.log('processing: ' + filepath);", "// read file source, saved in RAM", "var", "content", "=", "grunt", ".", "file", ".", "read", "(", "filepath", ")", ";", "/*\n * Reset pattern's last search index to 0\n * at the beginning for each file content.\n *\n * NOTE:\n * Since the pattern is always the same regex instance,\n * property 'lastIndex' changes each time when .exec() is performed.\n * To avoid 'lastIndex' affected by recursive function call,\n * its value MUST be cached for each file content.\n */", "var", "cacheLastIndex", "=", "0", ";", "_", ".", "pattern", ".", "lastIndex", "=", "cacheLastIndex", ";", "var", "matches", "=", "_", ".", "pattern", ".", "exec", "(", "content", ")", ";", "cacheLastIndex", "=", "_", ".", "pattern", ".", "lastIndex", ";", "// While there are matches (of import-links) in file content", "while", "(", "matches", "!==", "null", ")", "{", "/*\n * Construct the imported file's absolute path\n * (doesn't matter whether or not a relative path),\n * and recursively search in imported file. (dept-first)\n *\n * NOTE:\n * - the regex uses capture group, the first match is the fragment file path.\n */", "var", "currentDir", "=", "path", ".", "dirname", "(", "filepath", ")", ",", "relativeFilepath", "=", "matches", "[", "1", "]", ".", "trim", "(", ")", ",", "importedFilepath", "=", "path", ".", "resolve", "(", "currentDir", ",", "relativeFilepath", ")", ";", "var", "returnContent", "=", "getReplacedFileContent", "(", "importedFilepath", ")", ";", "/*\n * For current file content,\n * replace import-link tag with return value.\n *\n * NOTE:\n * Because of dept-first search,\n * should ONLY replace the first match in current content.\n * rather than search globally.\n */", "content", "=", "content", ".", "replace", "(", "_", ".", "patternNonGlobal", ",", "returnContent", ")", ";", "// console.log(content);", "// console.log(matches);", "// console.log('-----');", "/*\n * Keep searching in current file.\n *\n * NOTE:\n * After replacing part of the content (the step above),\n * the content's length changes accordingly.\n * Thus the 'lastIndex' property should shift to\n * the proper position to ensure next search.\n */", "var", "deltaLength", "=", "returnContent", ".", "length", "-", "matches", "[", "0", "]", ".", "length", ";", "_", ".", "pattern", ".", "lastIndex", "=", "cacheLastIndex", "+", "deltaLength", ";", "matches", "=", "_", ".", "pattern", ".", "exec", "(", "content", ")", ";", "cacheLastIndex", "=", "_", ".", "pattern", ".", "lastIndex", ";", "}", "// When searching and replacing is done, return the result.", "return", "content", ";", "}" ]
Search and replace import-link tag with its file content recursively until no more import-link detected in the source file. @param filepath @returns {*}
[ "Search", "and", "replace", "import", "-", "link", "tag", "with", "its", "file", "content", "recursively", "until", "no", "more", "import", "-", "link", "detected", "in", "the", "source", "file", "." ]
9dd6815f3b4dc511c017463c84ecd10cacec7931
https://github.com/ben-yip/grunt-html-imports/blob/9dd6815f3b4dc511c017463c84ecd10cacec7931/tasks/html_imports.js#L59-L132
44,197
wanderview/node-netbios-name-service
lib/unpack.js
unpackQuestion
function unpackQuestion(buf, offset) { var bytes = 0; var question = {}; // - variable length compressed question name var nbname = NBName.fromBuffer(buf, offset + bytes); if (nbname.error) { return {error: nbname.error}; } question.nbname = nbname; bytes += nbname.bytesRead; // Ensure we have enough space left before proceeding to avoid throwing if (offset + bytes + 4 > buf.length) { return { error: new Error('Question section is too large to fit in remaining ' + 'packet bytes.') }; } // - 16-bit question type var t = buf.readUInt16BE(offset + bytes); bytes += 2; question.type = con.QUESTION_TYPE_TO_STRING[t]; if (question.type === undefined) { return { error: new Error('Unexpected question type [' + t + '] for name [' + question.nbname + ']; should be either [nb] or ' + '[nbstat]') }; } // - 16-bit question class var clazz = buf.readUInt16BE(offset + bytes); bytes += 2; if (clazz !== con.CLASS_IN) { return { error: new Error('Unexpected question class [' + clazz + '] for name [' + question.nbname + ']; should be [' + CLASS_IN + ']') }; } return {bytesRead: bytes, record: question}; }
javascript
function unpackQuestion(buf, offset) { var bytes = 0; var question = {}; // - variable length compressed question name var nbname = NBName.fromBuffer(buf, offset + bytes); if (nbname.error) { return {error: nbname.error}; } question.nbname = nbname; bytes += nbname.bytesRead; // Ensure we have enough space left before proceeding to avoid throwing if (offset + bytes + 4 > buf.length) { return { error: new Error('Question section is too large to fit in remaining ' + 'packet bytes.') }; } // - 16-bit question type var t = buf.readUInt16BE(offset + bytes); bytes += 2; question.type = con.QUESTION_TYPE_TO_STRING[t]; if (question.type === undefined) { return { error: new Error('Unexpected question type [' + t + '] for name [' + question.nbname + ']; should be either [nb] or ' + '[nbstat]') }; } // - 16-bit question class var clazz = buf.readUInt16BE(offset + bytes); bytes += 2; if (clazz !== con.CLASS_IN) { return { error: new Error('Unexpected question class [' + clazz + '] for name [' + question.nbname + ']; should be [' + CLASS_IN + ']') }; } return {bytesRead: bytes, record: question}; }
[ "function", "unpackQuestion", "(", "buf", ",", "offset", ")", "{", "var", "bytes", "=", "0", ";", "var", "question", "=", "{", "}", ";", "// - variable length compressed question name", "var", "nbname", "=", "NBName", ".", "fromBuffer", "(", "buf", ",", "offset", "+", "bytes", ")", ";", "if", "(", "nbname", ".", "error", ")", "{", "return", "{", "error", ":", "nbname", ".", "error", "}", ";", "}", "question", ".", "nbname", "=", "nbname", ";", "bytes", "+=", "nbname", ".", "bytesRead", ";", "// Ensure we have enough space left before proceeding to avoid throwing", "if", "(", "offset", "+", "bytes", "+", "4", ">", "buf", ".", "length", ")", "{", "return", "{", "error", ":", "new", "Error", "(", "'Question section is too large to fit in remaining '", "+", "'packet bytes.'", ")", "}", ";", "}", "// - 16-bit question type", "var", "t", "=", "buf", ".", "readUInt16BE", "(", "offset", "+", "bytes", ")", ";", "bytes", "+=", "2", ";", "question", ".", "type", "=", "con", ".", "QUESTION_TYPE_TO_STRING", "[", "t", "]", ";", "if", "(", "question", ".", "type", "===", "undefined", ")", "{", "return", "{", "error", ":", "new", "Error", "(", "'Unexpected question type ['", "+", "t", "+", "'] for name ['", "+", "question", ".", "nbname", "+", "']; should be either [nb] or '", "+", "'[nbstat]'", ")", "}", ";", "}", "// - 16-bit question class", "var", "clazz", "=", "buf", ".", "readUInt16BE", "(", "offset", "+", "bytes", ")", ";", "bytes", "+=", "2", ";", "if", "(", "clazz", "!==", "con", ".", "CLASS_IN", ")", "{", "return", "{", "error", ":", "new", "Error", "(", "'Unexpected question class ['", "+", "clazz", "+", "'] for name ['", "+", "question", ".", "nbname", "+", "']; should be ['", "+", "CLASS_IN", "+", "']'", ")", "}", ";", "}", "return", "{", "bytesRead", ":", "bytes", ",", "record", ":", "question", "}", ";", "}" ]
Parse question section - variable length compressed question name - 16-bit question type - 16-bit question class
[ "Parse", "question", "section", "-", "variable", "length", "compressed", "question", "name", "-", "16", "-", "bit", "question", "type", "-", "16", "-", "bit", "question", "class" ]
90cd3c36b5625123ec435577bad1d054de420961
https://github.com/wanderview/node-netbios-name-service/blob/90cd3c36b5625123ec435577bad1d054de420961/lib/unpack.js#L145-L192
44,198
dutchenkoOleg/node-w3c-validator
bin/cmd.js
detectUserOptions
function detectUserOptions () { let outputPath = program.output; let userOptions = { output: false }; cliProps.forEach(prop => { let value = program[prop]; if ((prop === 'stream' || prop === 'langdetect') && value) { return; } if (value !== undefined) { userOptions[prop] = value; } }); if (typeof outputPath === 'string' && outputPath.length) { userOptions.output = outputPath; } return userOptions; }
javascript
function detectUserOptions () { let outputPath = program.output; let userOptions = { output: false }; cliProps.forEach(prop => { let value = program[prop]; if ((prop === 'stream' || prop === 'langdetect') && value) { return; } if (value !== undefined) { userOptions[prop] = value; } }); if (typeof outputPath === 'string' && outputPath.length) { userOptions.output = outputPath; } return userOptions; }
[ "function", "detectUserOptions", "(", ")", "{", "let", "outputPath", "=", "program", ".", "output", ";", "let", "userOptions", "=", "{", "output", ":", "false", "}", ";", "cliProps", ".", "forEach", "(", "prop", "=>", "{", "let", "value", "=", "program", "[", "prop", "]", ";", "if", "(", "(", "prop", "===", "'stream'", "||", "prop", "===", "'langdetect'", ")", "&&", "value", ")", "{", "return", ";", "}", "if", "(", "value", "!==", "undefined", ")", "{", "userOptions", "[", "prop", "]", "=", "value", ";", "}", "}", ")", ";", "if", "(", "typeof", "outputPath", "===", "'string'", "&&", "outputPath", ".", "length", ")", "{", "userOptions", ".", "output", "=", "outputPath", ";", "}", "return", "userOptions", ";", "}" ]
Detect user's specified properties @returns {Object} @private @sourceCode
[ "Detect", "user", "s", "specified", "properties" ]
79bc6ee63bdfad0208c6c6d8dcd5e25a629b006e
https://github.com/dutchenkoOleg/node-w3c-validator/blob/79bc6ee63bdfad0208c6c6d8dcd5e25a629b006e/bin/cmd.js#L59-L79
44,199
dutchenkoOleg/node-w3c-validator
bin/cmd.js
detectUserInput
function detectUserInput () { let validatePath = program.input; if (typeof validatePath !== 'string') { validatePath = process.cwd(); } else { if (!(/^(http(s)?:)?\/\//i.test(validatePath))) { if (/^\//.test(validatePath)) { validatePath = path.resolve(validatePath); } } } return validatePath; }
javascript
function detectUserInput () { let validatePath = program.input; if (typeof validatePath !== 'string') { validatePath = process.cwd(); } else { if (!(/^(http(s)?:)?\/\//i.test(validatePath))) { if (/^\//.test(validatePath)) { validatePath = path.resolve(validatePath); } } } return validatePath; }
[ "function", "detectUserInput", "(", ")", "{", "let", "validatePath", "=", "program", ".", "input", ";", "if", "(", "typeof", "validatePath", "!==", "'string'", ")", "{", "validatePath", "=", "process", ".", "cwd", "(", ")", ";", "}", "else", "{", "if", "(", "!", "(", "/", "^(http(s)?:)?\\/\\/", "/", "i", ".", "test", "(", "validatePath", ")", ")", ")", "{", "if", "(", "/", "^\\/", "/", ".", "test", "(", "validatePath", ")", ")", "{", "validatePath", "=", "path", ".", "resolve", "(", "validatePath", ")", ";", "}", "}", "}", "return", "validatePath", ";", "}" ]
Detect input path where testing files lies @returns {*}
[ "Detect", "input", "path", "where", "testing", "files", "lies" ]
79bc6ee63bdfad0208c6c6d8dcd5e25a629b006e
https://github.com/dutchenkoOleg/node-w3c-validator/blob/79bc6ee63bdfad0208c6c6d8dcd5e25a629b006e/bin/cmd.js#L85-L98