id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
17,200
ucbl/HyLAR-Reasoner
hylar/core/ReasoningEngine.js
function(F) { var validSet = []; for (var i = 0; i < F.length; i++) { if (F[i].isValid()) { validSet.push(F[i]); } } return validSet; }
javascript
function(F) { var validSet = []; for (var i = 0; i < F.length; i++) { if (F[i].isValid()) { validSet.push(F[i]); } } return validSet; }
[ "function", "(", "F", ")", "{", "var", "validSet", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "F", ".", "length", ";", "i", "++", ")", "{", "if", "(", "F", "[", "i", "]", ".", "isValid", "(", ")", ")", "{", "validSet", ".", "push", "(", "F", "[", "i", "]", ")", ";", "}", "}", "return", "validSet", ";", "}" ]
Returns valid facts using explicit facts' validity tags. @param F @param refs @returns {Array}
[ "Returns", "valid", "facts", "using", "explicit", "facts", "validity", "tags", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/ReasoningEngine.js#L144-L152
17,201
ucbl/HyLAR-Reasoner
hylar/core/Logics/Logics.js
function(fs, subset) { for (var i = 0; i < fs.length; i++) { for (var j = 0; j < subset.length; j++) { if ((subset[j] !== undefined) && (fs[i].equivalentTo(subset[j]))) { fs[i].causedBy = this.uniquesCausedBy(fs[i].causedBy, subset[j].causedBy); fs[i].consequences = fs[i].consequences.concat(subset[j].consequences); subset[j].doPropagate(fs[i]); delete subset[j]; } } } for (i = 0; i < subset.length; i++) { if (subset[i] !== undefined) fs.push(subset[i]); } }
javascript
function(fs, subset) { for (var i = 0; i < fs.length; i++) { for (var j = 0; j < subset.length; j++) { if ((subset[j] !== undefined) && (fs[i].equivalentTo(subset[j]))) { fs[i].causedBy = this.uniquesCausedBy(fs[i].causedBy, subset[j].causedBy); fs[i].consequences = fs[i].consequences.concat(subset[j].consequences); subset[j].doPropagate(fs[i]); delete subset[j]; } } } for (i = 0; i < subset.length; i++) { if (subset[i] !== undefined) fs.push(subset[i]); } }
[ "function", "(", "fs", ",", "subset", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "fs", ".", "length", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "subset", ".", "length", ";", "j", "++", ")", "{", "if", "(", "(", "subset", "[", "j", "]", "!==", "undefined", ")", "&&", "(", "fs", "[", "i", "]", ".", "equivalentTo", "(", "subset", "[", "j", "]", ")", ")", ")", "{", "fs", "[", "i", "]", ".", "causedBy", "=", "this", ".", "uniquesCausedBy", "(", "fs", "[", "i", "]", ".", "causedBy", ",", "subset", "[", "j", "]", ".", "causedBy", ")", ";", "fs", "[", "i", "]", ".", "consequences", "=", "fs", "[", "i", "]", ".", "consequences", ".", "concat", "(", "subset", "[", "j", "]", ".", "consequences", ")", ";", "subset", "[", "j", "]", ".", "doPropagate", "(", "fs", "[", "i", "]", ")", ";", "delete", "subset", "[", "j", "]", ";", "}", "}", "}", "for", "(", "i", "=", "0", ";", "i", "<", "subset", ".", "length", ";", "i", "++", ")", "{", "if", "(", "subset", "[", "i", "]", "!==", "undefined", ")", "fs", ".", "push", "(", "subset", "[", "i", "]", ")", ";", "}", "}" ]
True-like merge of two facts sets, which also merges identical facts causedBy properties. @param fs1 @param fs2
[ "True", "-", "like", "merge", "of", "two", "facts", "sets", "which", "also", "merges", "identical", "facts", "causedBy", "properties", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Logics.js#L26-L40
17,202
ucbl/HyLAR-Reasoner
hylar/core/Logics/Logics.js
function(fs) { var fR = []; for (var key in fs) { var fact = fs[key]; if(!fact.explicit) { fR.push(fact); } } return fR; }
javascript
function(fs) { var fR = []; for (var key in fs) { var fact = fs[key]; if(!fact.explicit) { fR.push(fact); } } return fR; }
[ "function", "(", "fs", ")", "{", "var", "fR", "=", "[", "]", ";", "for", "(", "var", "key", "in", "fs", ")", "{", "var", "fact", "=", "fs", "[", "key", "]", ";", "if", "(", "!", "fact", ".", "explicit", ")", "{", "fR", ".", "push", "(", "fact", ")", ";", "}", "}", "return", "fR", ";", "}" ]
Returns implicit facts from the set. @param fs @returns {Array}
[ "Returns", "implicit", "facts", "from", "the", "set", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Logics.js#L47-L56
17,203
ucbl/HyLAR-Reasoner
hylar/core/Logics/Logics.js
function(rs, fs) { var restriction = []; for (var i = 0; i < rs.length; i++) { var rule = rs[i], matches = false; for (var j = 0; j < rule.causes.length; j++) { var cause = rule.causes[j]; for (var k = 0; k < fs.length; k++) { var fact = fs[k]; if (this.causeMatchesFact(cause, fact)) { matches = true; break; } } if (matches) { restriction.push(rule); break; } } } return restriction; }
javascript
function(rs, fs) { var restriction = []; for (var i = 0; i < rs.length; i++) { var rule = rs[i], matches = false; for (var j = 0; j < rule.causes.length; j++) { var cause = rule.causes[j]; for (var k = 0; k < fs.length; k++) { var fact = fs[k]; if (this.causeMatchesFact(cause, fact)) { matches = true; break; } } if (matches) { restriction.push(rule); break; } } } return restriction; }
[ "function", "(", "rs", ",", "fs", ")", "{", "var", "restriction", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rs", ".", "length", ";", "i", "++", ")", "{", "var", "rule", "=", "rs", "[", "i", "]", ",", "matches", "=", "false", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "rule", ".", "causes", ".", "length", ";", "j", "++", ")", "{", "var", "cause", "=", "rule", ".", "causes", "[", "j", "]", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "fs", ".", "length", ";", "k", "++", ")", "{", "var", "fact", "=", "fs", "[", "k", "]", ";", "if", "(", "this", ".", "causeMatchesFact", "(", "cause", ",", "fact", ")", ")", "{", "matches", "=", "true", ";", "break", ";", "}", "}", "if", "(", "matches", ")", "{", "restriction", ".", "push", "(", "rule", ")", ";", "break", ";", "}", "}", "}", "return", "restriction", ";", "}" ]
Returns a restricted rule set, in which at least one fact from the fact set matches all rules. @param rs @param fs @returns {Array}
[ "Returns", "a", "restricted", "rule", "set", "in", "which", "at", "least", "one", "fact", "from", "the", "fact", "set", "matches", "all", "rules", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Logics.js#L82-L108
17,204
ucbl/HyLAR-Reasoner
hylar/core/Logics/Logics.js
function(cause, fact) { return this.causeMemberMatchesFactMember(cause.predicate, fact.predicate) && this.causeMemberMatchesFactMember(cause.subject, fact.subject) && this.causeMemberMatchesFactMember(cause.object, fact.object); }
javascript
function(cause, fact) { return this.causeMemberMatchesFactMember(cause.predicate, fact.predicate) && this.causeMemberMatchesFactMember(cause.subject, fact.subject) && this.causeMemberMatchesFactMember(cause.object, fact.object); }
[ "function", "(", "cause", ",", "fact", ")", "{", "return", "this", ".", "causeMemberMatchesFactMember", "(", "cause", ".", "predicate", ",", "fact", ".", "predicate", ")", "&&", "this", ".", "causeMemberMatchesFactMember", "(", "cause", ".", "subject", ",", "fact", ".", "subject", ")", "&&", "this", ".", "causeMemberMatchesFactMember", "(", "cause", ".", "object", ",", "fact", ".", "object", ")", ";", "}" ]
Checks if a cause matches a fact, i.e. is the cause's pattern can be satisfied by the fact. @param cause @param fact @returns {*}
[ "Checks", "if", "a", "cause", "matches", "a", "fact", "i", ".", "e", ".", "is", "the", "cause", "s", "pattern", "can", "be", "satisfied", "by", "the", "fact", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Logics.js#L117-L121
17,205
ucbl/HyLAR-Reasoner
hylar/core/Logics/Logics.js
function(atom1, atom2) { if (this.isVariable(atom1) && this.isVariable(atom2) ) { return true; } else if(atom1 == atom2) { return true; } else { return false; } }
javascript
function(atom1, atom2) { if (this.isVariable(atom1) && this.isVariable(atom2) ) { return true; } else if(atom1 == atom2) { return true; } else { return false; } }
[ "function", "(", "atom1", ",", "atom2", ")", "{", "if", "(", "this", ".", "isVariable", "(", "atom1", ")", "&&", "this", ".", "isVariable", "(", "atom2", ")", ")", "{", "return", "true", ";", "}", "else", "if", "(", "atom1", "==", "atom2", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Return true if the two atoms are either both variables, or identical URIs. @returns {boolean}
[ "Return", "true", "if", "the", "two", "atoms", "are", "either", "both", "variables", "or", "identical", "URIs", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Logics.js#L145-L153
17,206
ucbl/HyLAR-Reasoner
hylar/core/Logics/Logics.js
function(fs1, fs2) { if(!fs2 || (fs2.length > fs1.length)) return false; for (var key in fs2) { var fact = fs2[key]; if(!(fact.appearsIn(fs1))) { return false; } } return true; }
javascript
function(fs1, fs2) { if(!fs2 || (fs2.length > fs1.length)) return false; for (var key in fs2) { var fact = fs2[key]; if(!(fact.appearsIn(fs1))) { return false; } } return true; }
[ "function", "(", "fs1", ",", "fs2", ")", "{", "if", "(", "!", "fs2", "||", "(", "fs2", ".", "length", ">", "fs1", ".", "length", ")", ")", "return", "false", ";", "for", "(", "var", "key", "in", "fs2", ")", "{", "var", "fact", "=", "fs2", "[", "key", "]", ";", "if", "(", "!", "(", "fact", ".", "appearsIn", "(", "fs1", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if a set of facts is a subset of another set of facts. @param fs1 the superset @param fs2 the potential subset
[ "Checks", "if", "a", "set", "of", "facts", "is", "a", "subset", "of", "another", "set", "of", "facts", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Logics.js#L160-L169
17,207
ucbl/HyLAR-Reasoner
hylar/core/Logics/Logics.js
function(_set1, _set2) { var flagEquals, newSet = []; for (var i = 0; i < _set1.length; i++) { flagEquals = false; for(var j = 0; j < _set2.length; j++) { if (_set1[i].asString == _set2[j].asString) { flagEquals = true; break; } } if (!flagEquals) { newSet.push(_set1[i]); } } return newSet; }
javascript
function(_set1, _set2) { var flagEquals, newSet = []; for (var i = 0; i < _set1.length; i++) { flagEquals = false; for(var j = 0; j < _set2.length; j++) { if (_set1[i].asString == _set2[j].asString) { flagEquals = true; break; } } if (!flagEquals) { newSet.push(_set1[i]); } } return newSet; }
[ "function", "(", "_set1", ",", "_set2", ")", "{", "var", "flagEquals", ",", "newSet", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "_set1", ".", "length", ";", "i", "++", ")", "{", "flagEquals", "=", "false", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "_set2", ".", "length", ";", "j", "++", ")", "{", "if", "(", "_set1", "[", "i", "]", ".", "asString", "==", "_set2", "[", "j", "]", ".", "asString", ")", "{", "flagEquals", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "flagEquals", ")", "{", "newSet", ".", "push", "(", "_set1", "[", "i", "]", ")", ";", "}", "}", "return", "newSet", ";", "}" ]
Substracts each set. Not to be used in tag-based reasoning. @param _set1 @param _set2 @returns {Array}
[ "Substracts", "each", "set", ".", "Not", "to", "be", "used", "in", "tag", "-", "based", "reasoning", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Logics.js#L178-L195
17,208
ucbl/HyLAR-Reasoner
hylar/server/controller.js
function(req, res, next) { var initialTime = req.query.time, receivedReqTime = new Date().getTime(), filename = req.params.filename, absolutePathToFile = ontoDir + '/' + filename, extension = path.extname(absolutePathToFile), contentType = mime.contentType(extension); if(contentType) { req.mimeType = contentType.replace(/;.*/g, ''); } else { req.mimeType = contentType; } req.requestDelay = receivedReqTime - initialTime; fs.readFile(absolutePathToFile, function(err, data) { if(err) { res.status(500).send(err.toString()); } else { req.rawOntology = data.toString().replace(/(&)([a-z0-9]+)(;)/gi, '$2:'); next(); }; }); }
javascript
function(req, res, next) { var initialTime = req.query.time, receivedReqTime = new Date().getTime(), filename = req.params.filename, absolutePathToFile = ontoDir + '/' + filename, extension = path.extname(absolutePathToFile), contentType = mime.contentType(extension); if(contentType) { req.mimeType = contentType.replace(/;.*/g, ''); } else { req.mimeType = contentType; } req.requestDelay = receivedReqTime - initialTime; fs.readFile(absolutePathToFile, function(err, data) { if(err) { res.status(500).send(err.toString()); } else { req.rawOntology = data.toString().replace(/(&)([a-z0-9]+)(;)/gi, '$2:'); next(); }; }); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "initialTime", "=", "req", ".", "query", ".", "time", ",", "receivedReqTime", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ",", "filename", "=", "req", ".", "params", ".", "filename", ",", "absolutePathToFile", "=", "ontoDir", "+", "'/'", "+", "filename", ",", "extension", "=", "path", ".", "extname", "(", "absolutePathToFile", ")", ",", "contentType", "=", "mime", ".", "contentType", "(", "extension", ")", ";", "if", "(", "contentType", ")", "{", "req", ".", "mimeType", "=", "contentType", ".", "replace", "(", "/", ";.*", "/", "g", ",", "''", ")", ";", "}", "else", "{", "req", ".", "mimeType", "=", "contentType", ";", "}", "req", ".", "requestDelay", "=", "receivedReqTime", "-", "initialTime", ";", "fs", ".", "readFile", "(", "absolutePathToFile", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "res", ".", "status", "(", "500", ")", ".", "send", "(", "err", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "req", ".", "rawOntology", "=", "data", ".", "toString", "(", ")", ".", "replace", "(", "/", "(&)([a-z0-9]+)(;)", "/", "gi", ",", "'$2:'", ")", ";", "next", "(", ")", ";", "}", ";", "}", ")", ";", "}" ]
OWL File content to text @param req @param res @param next
[ "OWL", "File", "content", "to", "text" ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/server/controller.js#L73-L97
17,209
ucbl/HyLAR-Reasoner
hylar/server/controller.js
function(req, res) { if (req.headers.accept == 'application/json') { res.header('Content-Type', 'application/json'); res.status(200).json({ data: { ontologyTxt: req.rawOntology, mimeType: req.mimeType }, requestDelay: req.requestDelay, serverTime: new Date().getTime() }); } else { res.header('Content-Type', req.mimeType); res.status(200).send(req.rawOntology); } }
javascript
function(req, res) { if (req.headers.accept == 'application/json') { res.header('Content-Type', 'application/json'); res.status(200).json({ data: { ontologyTxt: req.rawOntology, mimeType: req.mimeType }, requestDelay: req.requestDelay, serverTime: new Date().getTime() }); } else { res.header('Content-Type', req.mimeType); res.status(200).send(req.rawOntology); } }
[ "function", "(", "req", ",", "res", ")", "{", "if", "(", "req", ".", "headers", ".", "accept", "==", "'application/json'", ")", "{", "res", ".", "header", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "res", ".", "status", "(", "200", ")", ".", "json", "(", "{", "data", ":", "{", "ontologyTxt", ":", "req", ".", "rawOntology", ",", "mimeType", ":", "req", ".", "mimeType", "}", ",", "requestDelay", ":", "req", ".", "requestDelay", ",", "serverTime", ":", "new", "Date", "(", ")", ".", "getTime", "(", ")", "}", ")", ";", "}", "else", "{", "res", ".", "header", "(", "'Content-Type'", ",", "req", ".", "mimeType", ")", ";", "res", ".", "status", "(", "200", ")", ".", "send", "(", "req", ".", "rawOntology", ")", ";", "}", "}" ]
End-method returning an ontology @param req @param res
[ "End", "-", "method", "returning", "an", "ontology" ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/server/controller.js#L158-L173
17,210
ucbl/HyLAR-Reasoner
hylar/server/controller.js
function(req, res, next) { var initialTime = 0, receivedReqTime = new Date().getTime(); req.requestDelay = receivedReqTime - initialTime; var url = req.body.url; request.get(url, function (error, response, body) { if (!error && response.statusCode == 200) { req.rawOntology = body.toString().replace(/(&)([a-z0-9]+)(;)/gi, '$2:'); next(); } }); }
javascript
function(req, res, next) { var initialTime = 0, receivedReqTime = new Date().getTime(); req.requestDelay = receivedReqTime - initialTime; var url = req.body.url; request.get(url, function (error, response, body) { if (!error && response.statusCode == 200) { req.rawOntology = body.toString().replace(/(&)([a-z0-9]+)(;)/gi, '$2:'); next(); } }); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "initialTime", "=", "0", ",", "receivedReqTime", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "req", ".", "requestDelay", "=", "receivedReqTime", "-", "initialTime", ";", "var", "url", "=", "req", ".", "body", ".", "url", ";", "request", ".", "get", "(", "url", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "if", "(", "!", "error", "&&", "response", ".", "statusCode", "==", "200", ")", "{", "req", ".", "rawOntology", "=", "body", ".", "toString", "(", ")", ".", "replace", "(", "/", "(&)([a-z0-9]+)(;)", "/", "gi", ",", "'$2:'", ")", ";", "next", "(", ")", ";", "}", "}", ")", ";", "}" ]
External OWL File content to text @param req @param res @param next
[ "External", "OWL", "File", "content", "to", "text" ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/server/controller.js#L230-L243
17,211
ucbl/HyLAR-Reasoner
hylar/core/Logics/Solver.js
function(rs, facts, doTagging, resolvedImplicitFactSet) { var deferred = q.defer(), promises = [], cons = [], filteredFacts; for (var key in rs) { if (doTagging) { promises.push(this.evaluateThroughRestrictionWithTagging(rs[key], facts, resolvedImplicitFactSet)); } else { promises.push(this.evaluateThroughRestriction(rs[key], facts)); } } try { q.all(promises).then(function (consTab) { for (var i = 0; i < consTab.length; i++) { cons = cons.concat(consTab[i]); } deferred.resolve({cons: cons}); }); } catch(e) { deferred.reject(e); } return deferred.promise; }
javascript
function(rs, facts, doTagging, resolvedImplicitFactSet) { var deferred = q.defer(), promises = [], cons = [], filteredFacts; for (var key in rs) { if (doTagging) { promises.push(this.evaluateThroughRestrictionWithTagging(rs[key], facts, resolvedImplicitFactSet)); } else { promises.push(this.evaluateThroughRestriction(rs[key], facts)); } } try { q.all(promises).then(function (consTab) { for (var i = 0; i < consTab.length; i++) { cons = cons.concat(consTab[i]); } deferred.resolve({cons: cons}); }); } catch(e) { deferred.reject(e); } return deferred.promise; }
[ "function", "(", "rs", ",", "facts", ",", "doTagging", ",", "resolvedImplicitFactSet", ")", "{", "var", "deferred", "=", "q", ".", "defer", "(", ")", ",", "promises", "=", "[", "]", ",", "cons", "=", "[", "]", ",", "filteredFacts", ";", "for", "(", "var", "key", "in", "rs", ")", "{", "if", "(", "doTagging", ")", "{", "promises", ".", "push", "(", "this", ".", "evaluateThroughRestrictionWithTagging", "(", "rs", "[", "key", "]", ",", "facts", ",", "resolvedImplicitFactSet", ")", ")", ";", "}", "else", "{", "promises", ".", "push", "(", "this", ".", "evaluateThroughRestriction", "(", "rs", "[", "key", "]", ",", "facts", ")", ")", ";", "}", "}", "try", "{", "q", ".", "all", "(", "promises", ")", ".", "then", "(", "function", "(", "consTab", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "consTab", ".", "length", ";", "i", "++", ")", "{", "cons", "=", "cons", ".", "concat", "(", "consTab", "[", "i", "]", ")", ";", "}", "deferred", ".", "resolve", "(", "{", "cons", ":", "cons", "}", ")", ";", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "deferred", ".", "reject", "(", "e", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
Evaluates a set of rules over a set of facts. @param rs @param facts @returns Array of the evaluation.
[ "Evaluates", "a", "set", "of", "rules", "over", "a", "set", "of", "facts", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Solver.js#L26-L46
17,212
ucbl/HyLAR-Reasoner
hylar/core/Logics/Solver.js
function(rule, facts) { var mappingList = this.getMappings(rule, facts), consequences = [], deferred = q.defer(); try { this.checkOperators(rule, mappingList); for (var i = 0; i < mappingList.length; i++) { if (mappingList[i]) { // Replace mappings on all consequences for (var j = 0; j < rule.consequences.length; j++) { consequences.push(this.substituteFactVariables(mappingList[i], rule.consequences[j], [], rule)); } } } deferred.resolve(consequences); } catch(e) { deferred.reject(e); } return deferred.promise; }
javascript
function(rule, facts) { var mappingList = this.getMappings(rule, facts), consequences = [], deferred = q.defer(); try { this.checkOperators(rule, mappingList); for (var i = 0; i < mappingList.length; i++) { if (mappingList[i]) { // Replace mappings on all consequences for (var j = 0; j < rule.consequences.length; j++) { consequences.push(this.substituteFactVariables(mappingList[i], rule.consequences[j], [], rule)); } } } deferred.resolve(consequences); } catch(e) { deferred.reject(e); } return deferred.promise; }
[ "function", "(", "rule", ",", "facts", ")", "{", "var", "mappingList", "=", "this", ".", "getMappings", "(", "rule", ",", "facts", ")", ",", "consequences", "=", "[", "]", ",", "deferred", "=", "q", ".", "defer", "(", ")", ";", "try", "{", "this", ".", "checkOperators", "(", "rule", ",", "mappingList", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "mappingList", ".", "length", ";", "i", "++", ")", "{", "if", "(", "mappingList", "[", "i", "]", ")", "{", "// Replace mappings on all consequences", "for", "(", "var", "j", "=", "0", ";", "j", "<", "rule", ".", "consequences", ".", "length", ";", "j", "++", ")", "{", "consequences", ".", "push", "(", "this", ".", "substituteFactVariables", "(", "mappingList", "[", "i", "]", ",", "rule", ".", "consequences", "[", "j", "]", ",", "[", "]", ",", "rule", ")", ")", ";", "}", "}", "}", "deferred", ".", "resolve", "(", "consequences", ")", ";", "}", "catch", "(", "e", ")", "{", "deferred", ".", "reject", "(", "e", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
Evaluates a rule over a set of facts through restriction of the rule's causes. @param rule @param facts @returns {Array}
[ "Evaluates", "a", "rule", "over", "a", "set", "of", "facts", "through", "restriction", "of", "the", "rule", "s", "causes", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Solver.js#L55-L77
17,213
ucbl/HyLAR-Reasoner
hylar/core/Logics/Solver.js
function(rule, kb) { var mappingList = this.getMappings(rule, kb), deferred = q.defer(), consequences = [], consequence, causes, iterationConsequences; this.checkOperators(rule, mappingList); try { for (var i = 0; i < mappingList.length; i++) { if (mappingList[i]) { // Replace mappings on all consequences causes = Logics.buildCauses(mappingList[i].__facts__); iterationConsequences = []; for (var j = 0; j < rule.consequences.length; j++) { consequence = this.substituteFactVariables(mappingList[i], rule.consequences[j], causes, rule); //if (Logics.filterKnownOrAlternativeImplicitFact(consequence, kb, resolvedImplicitFacts)) { consequences.push(consequence); iterationConsequences.push(consequence); //} } try { Logics.addConsequences(mappingList[i].__facts__, iterationConsequences); } catch(e) { throw "Error when trying to add consequences on the implicit fact."; } } } deferred.resolve(consequences); } catch(e) { deferred.reject(e); } return deferred.promise; }
javascript
function(rule, kb) { var mappingList = this.getMappings(rule, kb), deferred = q.defer(), consequences = [], consequence, causes, iterationConsequences; this.checkOperators(rule, mappingList); try { for (var i = 0; i < mappingList.length; i++) { if (mappingList[i]) { // Replace mappings on all consequences causes = Logics.buildCauses(mappingList[i].__facts__); iterationConsequences = []; for (var j = 0; j < rule.consequences.length; j++) { consequence = this.substituteFactVariables(mappingList[i], rule.consequences[j], causes, rule); //if (Logics.filterKnownOrAlternativeImplicitFact(consequence, kb, resolvedImplicitFacts)) { consequences.push(consequence); iterationConsequences.push(consequence); //} } try { Logics.addConsequences(mappingList[i].__facts__, iterationConsequences); } catch(e) { throw "Error when trying to add consequences on the implicit fact."; } } } deferred.resolve(consequences); } catch(e) { deferred.reject(e); } return deferred.promise; }
[ "function", "(", "rule", ",", "kb", ")", "{", "var", "mappingList", "=", "this", ".", "getMappings", "(", "rule", ",", "kb", ")", ",", "deferred", "=", "q", ".", "defer", "(", ")", ",", "consequences", "=", "[", "]", ",", "consequence", ",", "causes", ",", "iterationConsequences", ";", "this", ".", "checkOperators", "(", "rule", ",", "mappingList", ")", ";", "try", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "mappingList", ".", "length", ";", "i", "++", ")", "{", "if", "(", "mappingList", "[", "i", "]", ")", "{", "// Replace mappings on all consequences", "causes", "=", "Logics", ".", "buildCauses", "(", "mappingList", "[", "i", "]", ".", "__facts__", ")", ";", "iterationConsequences", "=", "[", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "rule", ".", "consequences", ".", "length", ";", "j", "++", ")", "{", "consequence", "=", "this", ".", "substituteFactVariables", "(", "mappingList", "[", "i", "]", ",", "rule", ".", "consequences", "[", "j", "]", ",", "causes", ",", "rule", ")", ";", "//if (Logics.filterKnownOrAlternativeImplicitFact(consequence, kb, resolvedImplicitFacts)) {", "consequences", ".", "push", "(", "consequence", ")", ";", "iterationConsequences", ".", "push", "(", "consequence", ")", ";", "//}", "}", "try", "{", "Logics", ".", "addConsequences", "(", "mappingList", "[", "i", "]", ".", "__facts__", ",", "iterationConsequences", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "\"Error when trying to add consequences on the implicit fact.\"", ";", "}", "}", "}", "deferred", ".", "resolve", "(", "consequences", ")", ";", "}", "catch", "(", "e", ")", "{", "deferred", ".", "reject", "(", "e", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
Evaluates a rule over a set of facts through restriction of the rule's causes with tagging. @param rule @param kb @returns {Array}
[ "Evaluates", "a", "rule", "over", "a", "set", "of", "facts", "through", "restriction", "of", "the", "rule", "s", "causes", "with", "tagging", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Solver.js#L86-L118
17,214
ucbl/HyLAR-Reasoner
hylar/core/Logics/Solver.js
function(currentCauses, nextCause, facts, constants, rule) { var substitutedNextCauses = [], mappings = []; for (var i = 0; i < currentCauses.length; i++) { for (var j = 0; j < facts.length; j++) { // Get the mapping of the current cause ... var mapping = currentCauses[i].mapping, substitutedNextCause, newMapping; // ... or build a fresh one if it does not exist if (mapping === undefined) { mapping = {}; mapping.__facts__ = []; } // Update the mapping using pattern matching newMapping = this.factMatches(facts[j], currentCauses[i], mapping, constants, rule); // If the current fact matches the current cause ... if (newMapping) { // If there are other causes to be checked... if (nextCause) { // Substitute the next cause's variable with the new mapping substitutedNextCause = this.substituteFactVariables(newMapping, nextCause); substitutedNextCause.mapping = newMapping; substitutedNextCauses.push(substitutedNextCause); } else { // Otherwise, add the new mapping to the global mapping array mappings.push(newMapping); } } } } if(nextCause) { return substitutedNextCauses; } else { return mappings; } }
javascript
function(currentCauses, nextCause, facts, constants, rule) { var substitutedNextCauses = [], mappings = []; for (var i = 0; i < currentCauses.length; i++) { for (var j = 0; j < facts.length; j++) { // Get the mapping of the current cause ... var mapping = currentCauses[i].mapping, substitutedNextCause, newMapping; // ... or build a fresh one if it does not exist if (mapping === undefined) { mapping = {}; mapping.__facts__ = []; } // Update the mapping using pattern matching newMapping = this.factMatches(facts[j], currentCauses[i], mapping, constants, rule); // If the current fact matches the current cause ... if (newMapping) { // If there are other causes to be checked... if (nextCause) { // Substitute the next cause's variable with the new mapping substitutedNextCause = this.substituteFactVariables(newMapping, nextCause); substitutedNextCause.mapping = newMapping; substitutedNextCauses.push(substitutedNextCause); } else { // Otherwise, add the new mapping to the global mapping array mappings.push(newMapping); } } } } if(nextCause) { return substitutedNextCauses; } else { return mappings; } }
[ "function", "(", "currentCauses", ",", "nextCause", ",", "facts", ",", "constants", ",", "rule", ")", "{", "var", "substitutedNextCauses", "=", "[", "]", ",", "mappings", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "currentCauses", ".", "length", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "facts", ".", "length", ";", "j", "++", ")", "{", "// Get the mapping of the current cause ...", "var", "mapping", "=", "currentCauses", "[", "i", "]", ".", "mapping", ",", "substitutedNextCause", ",", "newMapping", ";", "// ... or build a fresh one if it does not exist", "if", "(", "mapping", "===", "undefined", ")", "{", "mapping", "=", "{", "}", ";", "mapping", ".", "__facts__", "=", "[", "]", ";", "}", "// Update the mapping using pattern matching", "newMapping", "=", "this", ".", "factMatches", "(", "facts", "[", "j", "]", ",", "currentCauses", "[", "i", "]", ",", "mapping", ",", "constants", ",", "rule", ")", ";", "// If the current fact matches the current cause ...", "if", "(", "newMapping", ")", "{", "// If there are other causes to be checked...", "if", "(", "nextCause", ")", "{", "// Substitute the next cause's variable with the new mapping", "substitutedNextCause", "=", "this", ".", "substituteFactVariables", "(", "newMapping", ",", "nextCause", ")", ";", "substitutedNextCause", ".", "mapping", "=", "newMapping", ";", "substitutedNextCauses", ".", "push", "(", "substitutedNextCause", ")", ";", "}", "else", "{", "// Otherwise, add the new mapping to the global mapping array", "mappings", ".", "push", "(", "newMapping", ")", ";", "}", "}", "}", "}", "if", "(", "nextCause", ")", "{", "return", "substitutedNextCauses", ";", "}", "else", "{", "return", "mappings", ";", "}", "}" ]
Updates the mapping of the current cause given the next cause of a rule, over a set of facts. @param currentCauses @param nextCause @param facts @returns {Array}
[ "Updates", "the", "mapping", "of", "the", "current", "cause", "given", "the", "next", "cause", "of", "a", "rule", "over", "a", "set", "of", "facts", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Solver.js#L166-L208
17,215
ucbl/HyLAR-Reasoner
hylar/core/Logics/Solver.js
function(fact, ruleFact, mapping, constants, rule) { var localMapping = {}; // Checks and update localMapping if matches if (!this.factElemMatches(fact.predicate, ruleFact.predicate, mapping, localMapping)) { return false; } if (!this.factElemMatches(fact.object, ruleFact.object, mapping, localMapping)) { return false; } if (!this.factElemMatches(fact.subject, ruleFact.subject, mapping, localMapping)) { return false; } emitter.emit('rule-fired', rule.name); // If an already existing uri has been mapped... for (var key in localMapping) { if(constants.indexOf(localMapping[key]) !== -1) { return false; } } // Merges local and global mapping for (var mapKey in mapping) { if (mapKey == '__facts__') { localMapping[mapKey] = Utils.uniques(mapping[mapKey], [fact]); } else { for (key in localMapping) { if (mapping[mapKey] == localMapping[key]) { if (mapKey != key) { return false; } } } localMapping[mapKey] = mapping[mapKey]; } } // The new mapping is updated return localMapping; }
javascript
function(fact, ruleFact, mapping, constants, rule) { var localMapping = {}; // Checks and update localMapping if matches if (!this.factElemMatches(fact.predicate, ruleFact.predicate, mapping, localMapping)) { return false; } if (!this.factElemMatches(fact.object, ruleFact.object, mapping, localMapping)) { return false; } if (!this.factElemMatches(fact.subject, ruleFact.subject, mapping, localMapping)) { return false; } emitter.emit('rule-fired', rule.name); // If an already existing uri has been mapped... for (var key in localMapping) { if(constants.indexOf(localMapping[key]) !== -1) { return false; } } // Merges local and global mapping for (var mapKey in mapping) { if (mapKey == '__facts__') { localMapping[mapKey] = Utils.uniques(mapping[mapKey], [fact]); } else { for (key in localMapping) { if (mapping[mapKey] == localMapping[key]) { if (mapKey != key) { return false; } } } localMapping[mapKey] = mapping[mapKey]; } } // The new mapping is updated return localMapping; }
[ "function", "(", "fact", ",", "ruleFact", ",", "mapping", ",", "constants", ",", "rule", ")", "{", "var", "localMapping", "=", "{", "}", ";", "// Checks and update localMapping if matches ", "if", "(", "!", "this", ".", "factElemMatches", "(", "fact", ".", "predicate", ",", "ruleFact", ".", "predicate", ",", "mapping", ",", "localMapping", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "this", ".", "factElemMatches", "(", "fact", ".", "object", ",", "ruleFact", ".", "object", ",", "mapping", ",", "localMapping", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "this", ".", "factElemMatches", "(", "fact", ".", "subject", ",", "ruleFact", ".", "subject", ",", "mapping", ",", "localMapping", ")", ")", "{", "return", "false", ";", "}", "emitter", ".", "emit", "(", "'rule-fired'", ",", "rule", ".", "name", ")", ";", "// If an already existing uri has been mapped...", "for", "(", "var", "key", "in", "localMapping", ")", "{", "if", "(", "constants", ".", "indexOf", "(", "localMapping", "[", "key", "]", ")", "!==", "-", "1", ")", "{", "return", "false", ";", "}", "}", "// Merges local and global mapping", "for", "(", "var", "mapKey", "in", "mapping", ")", "{", "if", "(", "mapKey", "==", "'__facts__'", ")", "{", "localMapping", "[", "mapKey", "]", "=", "Utils", ".", "uniques", "(", "mapping", "[", "mapKey", "]", ",", "[", "fact", "]", ")", ";", "}", "else", "{", "for", "(", "key", "in", "localMapping", ")", "{", "if", "(", "mapping", "[", "mapKey", "]", "==", "localMapping", "[", "key", "]", ")", "{", "if", "(", "mapKey", "!=", "key", ")", "{", "return", "false", ";", "}", "}", "}", "localMapping", "[", "mapKey", "]", "=", "mapping", "[", "mapKey", "]", ";", "}", "}", "// The new mapping is updated", "return", "localMapping", ";", "}" ]
Returns a new or updated mapping if a fact matches a rule cause or consequence, return false otherwise. @param fact @param ruleFact @param mapping @returns {*}
[ "Returns", "a", "new", "or", "updated", "mapping", "if", "a", "fact", "matches", "a", "rule", "cause", "or", "consequence", "return", "false", "otherwise", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Solver.js#L218-L259
17,216
ucbl/HyLAR-Reasoner
hylar/core/Logics/Solver.js
function(elem, mapping) { if(Logics.isBNode(elem)) { return Logics.skolemize(mapping.__facts__, elem); } else if(Logics.isVariable(elem)) { if (mapping[elem] !== undefined) { return mapping[elem] } } return elem; }
javascript
function(elem, mapping) { if(Logics.isBNode(elem)) { return Logics.skolemize(mapping.__facts__, elem); } else if(Logics.isVariable(elem)) { if (mapping[elem] !== undefined) { return mapping[elem] } } return elem; }
[ "function", "(", "elem", ",", "mapping", ")", "{", "if", "(", "Logics", ".", "isBNode", "(", "elem", ")", ")", "{", "return", "Logics", ".", "skolemize", "(", "mapping", ".", "__facts__", ",", "elem", ")", ";", "}", "else", "if", "(", "Logics", ".", "isVariable", "(", "elem", ")", ")", "{", "if", "(", "mapping", "[", "elem", "]", "!==", "undefined", ")", "{", "return", "mapping", "[", "elem", "]", "}", "}", "return", "elem", ";", "}" ]
Substitutes an element given the mapping. @param elem @param mapping @returns {*}
[ "Substitutes", "an", "element", "given", "the", "mapping", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Solver.js#L283-L292
17,217
ucbl/HyLAR-Reasoner
hylar/core/ParsingInterface.js
function(t, explicit, notUsingValid) { if(explicit === undefined) { explicit = true; } return new Fact(t.predicate.toString(), t.subject.toString(), t.object.toString()/*.format()*/, [], explicit, [], [], notUsingValid, t.toString()) }
javascript
function(t, explicit, notUsingValid) { if(explicit === undefined) { explicit = true; } return new Fact(t.predicate.toString(), t.subject.toString(), t.object.toString()/*.format()*/, [], explicit, [], [], notUsingValid, t.toString()) }
[ "function", "(", "t", ",", "explicit", ",", "notUsingValid", ")", "{", "if", "(", "explicit", "===", "undefined", ")", "{", "explicit", "=", "true", ";", "}", "return", "new", "Fact", "(", "t", ".", "predicate", ".", "toString", "(", ")", ",", "t", ".", "subject", ".", "toString", "(", ")", ",", "t", ".", "object", ".", "toString", "(", ")", "/*.format()*/", ",", "[", "]", ",", "explicit", ",", "[", "]", ",", "[", "]", ",", "notUsingValid", ",", "t", ".", "toString", "(", ")", ")", "}" ]
Transforms a triple into a fact. @param t The triple @param explicit True if the resulting fact is explicit, false otherwise (default: true) @returns Object resulting fact
[ "Transforms", "a", "triple", "into", "a", "fact", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/ParsingInterface.js#L43-L48
17,218
ucbl/HyLAR-Reasoner
hylar/core/ParsingInterface.js
function(fact) { var subject, predicate, object; /*if (fact.fromTriple !== undefined) { return fact.fromTriple; }*/ if(fact.falseFact) { return ''; } subject = this.parseStrEntityToTurtle(fact.subject); predicate = this.parseStrEntityToTurtle(fact.predicate); object = this.parseStrEntityToTurtle(fact.object); if (subject && predicate && object) { return subject + ' ' + predicate + ' ' + object + ' . '; } else { return ''; } }
javascript
function(fact) { var subject, predicate, object; /*if (fact.fromTriple !== undefined) { return fact.fromTriple; }*/ if(fact.falseFact) { return ''; } subject = this.parseStrEntityToTurtle(fact.subject); predicate = this.parseStrEntityToTurtle(fact.predicate); object = this.parseStrEntityToTurtle(fact.object); if (subject && predicate && object) { return subject + ' ' + predicate + ' ' + object + ' . '; } else { return ''; } }
[ "function", "(", "fact", ")", "{", "var", "subject", ",", "predicate", ",", "object", ";", "/*if (fact.fromTriple !== undefined) {\n return fact.fromTriple;\n }*/", "if", "(", "fact", ".", "falseFact", ")", "{", "return", "''", ";", "}", "subject", "=", "this", ".", "parseStrEntityToTurtle", "(", "fact", ".", "subject", ")", ";", "predicate", "=", "this", ".", "parseStrEntityToTurtle", "(", "fact", ".", "predicate", ")", ";", "object", "=", "this", ".", "parseStrEntityToTurtle", "(", "fact", ".", "object", ")", ";", "if", "(", "subject", "&&", "predicate", "&&", "object", ")", "{", "return", "subject", "+", "' '", "+", "predicate", "+", "' '", "+", "object", "+", "' . '", ";", "}", "else", "{", "return", "''", ";", "}", "}" ]
Transforms a fact into turtle. @param fact @returns {string}
[ "Transforms", "a", "fact", "into", "turtle", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/ParsingInterface.js#L109-L129
17,219
ucbl/HyLAR-Reasoner
hylar/core/ParsingInterface.js
function(facts) { var ttl = '', fact, that = this; for (var i = 0; i < facts.length; i++) { fact = facts[i]; ttl += that.factToTurtle(fact); } return ttl; }
javascript
function(facts) { var ttl = '', fact, that = this; for (var i = 0; i < facts.length; i++) { fact = facts[i]; ttl += that.factToTurtle(fact); } return ttl; }
[ "function", "(", "facts", ")", "{", "var", "ttl", "=", "''", ",", "fact", ",", "that", "=", "this", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "facts", ".", "length", ";", "i", "++", ")", "{", "fact", "=", "facts", "[", "i", "]", ";", "ttl", "+=", "that", ".", "factToTurtle", "(", "fact", ")", ";", "}", "return", "ttl", ";", "}" ]
Transforms a set of facts into turtle. @param facts @returns {string}
[ "Transforms", "a", "set", "of", "facts", "into", "turtle", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/ParsingInterface.js#L136-L144
17,220
ucbl/HyLAR-Reasoner
hylar/core/Logics/Fact.js
function() { var e, spo; if(this.falseFact) { spo = 'FALSE'; } else { spo = '(' + Utils.removeBeforeSharp(this.subject) + ', ' + Utils.removeBeforeSharp(this.predicate) + ', ' + Utils.removeBeforeSharp(this.object) + ')' } this.explicit ? e = 'E' : e = 'I'; return e + spo; }
javascript
function() { var e, spo; if(this.falseFact) { spo = 'FALSE'; } else { spo = '(' + Utils.removeBeforeSharp(this.subject) + ', ' + Utils.removeBeforeSharp(this.predicate) + ', ' + Utils.removeBeforeSharp(this.object) + ')' } this.explicit ? e = 'E' : e = 'I'; return e + spo; }
[ "function", "(", ")", "{", "var", "e", ",", "spo", ";", "if", "(", "this", ".", "falseFact", ")", "{", "spo", "=", "'FALSE'", ";", "}", "else", "{", "spo", "=", "'('", "+", "Utils", ".", "removeBeforeSharp", "(", "this", ".", "subject", ")", "+", "', '", "+", "Utils", ".", "removeBeforeSharp", "(", "this", ".", "predicate", ")", "+", "', '", "+", "Utils", ".", "removeBeforeSharp", "(", "this", ".", "object", ")", "+", "')'", "}", "this", ".", "explicit", "?", "e", "=", "'E'", ":", "e", "=", "'I'", ";", "return", "e", "+", "spo", ";", "}" ]
Convenient method to stringify a fact. @returns {string}
[ "Convenient", "method", "to", "stringify", "a", "fact", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Fact.js#L65-L76
17,221
ucbl/HyLAR-Reasoner
hylar/core/Logics/Fact.js
function(fact) { if ((this.explicit != fact.explicit) || (this.subject != fact.subject) || (this.predicate != fact.predicate) || (this.object != fact.object)) { return false; } return true; }
javascript
function(fact) { if ((this.explicit != fact.explicit) || (this.subject != fact.subject) || (this.predicate != fact.predicate) || (this.object != fact.object)) { return false; } return true; }
[ "function", "(", "fact", ")", "{", "if", "(", "(", "this", ".", "explicit", "!=", "fact", ".", "explicit", ")", "||", "(", "this", ".", "subject", "!=", "fact", ".", "subject", ")", "||", "(", "this", ".", "predicate", "!=", "fact", ".", "predicate", ")", "||", "(", "this", ".", "object", "!=", "fact", ".", "object", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks if the fact is equivalent to another fact. @param fact @returns {boolean}
[ "Checks", "if", "the", "fact", "is", "equivalent", "to", "another", "fact", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Fact.js#L144-L152
17,222
ucbl/HyLAR-Reasoner
hylar/core/Logics/Fact.js
function(factSet) { var that = this; for (var key in factSet) { if(that.equivalentTo(factSet[key])){ return key; } } return false; }
javascript
function(factSet) { var that = this; for (var key in factSet) { if(that.equivalentTo(factSet[key])){ return key; } } return false; }
[ "function", "(", "factSet", ")", "{", "var", "that", "=", "this", ";", "for", "(", "var", "key", "in", "factSet", ")", "{", "if", "(", "that", ".", "equivalentTo", "(", "factSet", "[", "key", "]", ")", ")", "{", "return", "key", ";", "}", "}", "return", "false", ";", "}" ]
Returns the fact if it appears in a set of facts. Returns false otherwise. @param factSet
[ "Returns", "the", "fact", "if", "it", "appears", "in", "a", "set", "of", "facts", ".", "Returns", "false", "otherwise", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Fact.js#L167-L175
17,223
ucbl/HyLAR-Reasoner
hylar/core/Logics/Fact.js
function() { if (this.explicit) { return this.valid; } else if (this.causedBy === undefined || this.causedBy.length == 0) { return undefined; } else { var valid, causes = this.causedBy, explicitFact; for (var i = 0; i < causes.length; i++) { valid = true; for (var j = 0; j < causes[i].length; j++) { explicitFact = causes[i][j]; valid = valid && explicitFact.valid; } if (valid) { return true; } } return false; } }
javascript
function() { if (this.explicit) { return this.valid; } else if (this.causedBy === undefined || this.causedBy.length == 0) { return undefined; } else { var valid, causes = this.causedBy, explicitFact; for (var i = 0; i < causes.length; i++) { valid = true; for (var j = 0; j < causes[i].length; j++) { explicitFact = causes[i][j]; valid = valid && explicitFact.valid; } if (valid) { return true; } } return false; } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "explicit", ")", "{", "return", "this", ".", "valid", ";", "}", "else", "if", "(", "this", ".", "causedBy", "===", "undefined", "||", "this", ".", "causedBy", ".", "length", "==", "0", ")", "{", "return", "undefined", ";", "}", "else", "{", "var", "valid", ",", "causes", "=", "this", ".", "causedBy", ",", "explicitFact", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "causes", ".", "length", ";", "i", "++", ")", "{", "valid", "=", "true", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "causes", "[", "i", "]", ".", "length", ";", "j", "++", ")", "{", "explicitFact", "=", "causes", "[", "i", "]", "[", "j", "]", ";", "valid", "=", "valid", "&&", "explicitFact", ".", "valid", ";", "}", "if", "(", "valid", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "}" ]
Checks the validity of an implicit fact by exploring its explicit causes' validity tags. An implicit fact is valid iff the disjunction of its explicit causes' validity tags is true, i.e. if at least one of its causes is valid. @param fe @returns {boolean}
[ "Checks", "the", "validity", "of", "an", "implicit", "fact", "by", "exploring", "its", "explicit", "causes", "validity", "tags", ".", "An", "implicit", "fact", "is", "valid", "iff", "the", "disjunction", "of", "its", "explicit", "causes", "validity", "tags", "is", "true", "i", ".", "e", ".", "if", "at", "least", "one", "of", "its", "causes", "is", "valid", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Fact.js#L186-L207
17,224
ucbl/HyLAR-Reasoner
hylar/core/Utils.js
function(_set1, _set2) { var hash = {}, uniq = [], fullSet = _set1.concat(_set2); for (var i = 0; i < fullSet.length; i++) { if (fullSet[i] !== undefined) hash[fullSet[i].toString()] = fullSet[i]; } for (var key in hash) { uniq.push(hash[key]); } return uniq; }
javascript
function(_set1, _set2) { var hash = {}, uniq = [], fullSet = _set1.concat(_set2); for (var i = 0; i < fullSet.length; i++) { if (fullSet[i] !== undefined) hash[fullSet[i].toString()] = fullSet[i]; } for (var key in hash) { uniq.push(hash[key]); } return uniq; }
[ "function", "(", "_set1", ",", "_set2", ")", "{", "var", "hash", "=", "{", "}", ",", "uniq", "=", "[", "]", ",", "fullSet", "=", "_set1", ".", "concat", "(", "_set2", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "fullSet", ".", "length", ";", "i", "++", ")", "{", "if", "(", "fullSet", "[", "i", "]", "!==", "undefined", ")", "hash", "[", "fullSet", "[", "i", "]", ".", "toString", "(", ")", "]", "=", "fullSet", "[", "i", "]", ";", "}", "for", "(", "var", "key", "in", "hash", ")", "{", "uniq", ".", "push", "(", "hash", "[", "key", "]", ")", ";", "}", "return", "uniq", ";", "}" ]
Returns a set of elements with distinct string representation. @param _set1 @param _set2 @returns {Array}
[ "Returns", "a", "set", "of", "elements", "with", "distinct", "string", "representation", "." ]
a66cd396de89cc2e1921b18f23ec9a8906313df2
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Utils.js#L35-L47
17,225
elavoie/webrtc-tree-overlay
src/index.js
Channel
function Channel (id, socket) { var log = debug('webrtc-tree-overlay:channel(' + id + ')') this._log = log var self = this this.id = id this._socket = socket .on('data', function (data) { log('received data:') log(data.toString()) var message = JSON.parse(data) if (message.type === 'DATA') { log('data: ' + message.data) self.emit('data', message.data) } else if (message.type === 'JOIN-REQUEST') { log('join-request: ' + JSON.stringify(message)) self.emit('join-request', message) } else { throw new Error('Invalid message type on channel(' + id + ')') } }) .on('connect', function () { self.emit('connect', self) }) .on('close', function () { log('closing') self.emit('close') }) .on('error', function (err) { log(err.message) log(err.stack) }) }
javascript
function Channel (id, socket) { var log = debug('webrtc-tree-overlay:channel(' + id + ')') this._log = log var self = this this.id = id this._socket = socket .on('data', function (data) { log('received data:') log(data.toString()) var message = JSON.parse(data) if (message.type === 'DATA') { log('data: ' + message.data) self.emit('data', message.data) } else if (message.type === 'JOIN-REQUEST') { log('join-request: ' + JSON.stringify(message)) self.emit('join-request', message) } else { throw new Error('Invalid message type on channel(' + id + ')') } }) .on('connect', function () { self.emit('connect', self) }) .on('close', function () { log('closing') self.emit('close') }) .on('error', function (err) { log(err.message) log(err.stack) }) }
[ "function", "Channel", "(", "id", ",", "socket", ")", "{", "var", "log", "=", "debug", "(", "'webrtc-tree-overlay:channel('", "+", "id", "+", "')'", ")", "this", ".", "_log", "=", "log", "var", "self", "=", "this", "this", ".", "id", "=", "id", "this", ".", "_socket", "=", "socket", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "log", "(", "'received data:'", ")", "log", "(", "data", ".", "toString", "(", ")", ")", "var", "message", "=", "JSON", ".", "parse", "(", "data", ")", "if", "(", "message", ".", "type", "===", "'DATA'", ")", "{", "log", "(", "'data: '", "+", "message", ".", "data", ")", "self", ".", "emit", "(", "'data'", ",", "message", ".", "data", ")", "}", "else", "if", "(", "message", ".", "type", "===", "'JOIN-REQUEST'", ")", "{", "log", "(", "'join-request: '", "+", "JSON", ".", "stringify", "(", "message", ")", ")", "self", ".", "emit", "(", "'join-request'", ",", "message", ")", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid message type on channel('", "+", "id", "+", "')'", ")", "}", "}", ")", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'connect'", ",", "self", ")", "}", ")", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "log", "(", "'closing'", ")", "self", ".", "emit", "(", "'close'", ")", "}", ")", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "log", "(", "err", ".", "message", ")", "log", "(", "err", ".", "stack", ")", "}", ")", "}" ]
Wraps the WebRTC socket inside a channel to encapsulate the join-request protocol while allowing application-defined control protocols to be multiplexed
[ "Wraps", "the", "WebRTC", "socket", "inside", "a", "channel", "to", "encapsulate", "the", "join", "-", "request", "protocol", "while", "allowing", "application", "-", "defined", "control", "protocols", "to", "be", "multiplexed" ]
19c2bededf646f88972a0c79f45e66f62ceccd2e
https://github.com/elavoie/webrtc-tree-overlay/blob/19c2bededf646f88972a0c79f45e66f62ceccd2e/src/index.js#L18-L49
17,226
nating/react-native-custom-qr-codes
lib/QRCodeGenerator.js
_getErrorCorrectLevel
function _getErrorCorrectLevel(ecl) { switch (ecl) { case "L": return QRErrorCorrectLevel.L; case "M": return QRErrorCorrectLevel.M; case "Q": return QRErrorCorrectLevel.Q; case "H": return QRErrorCorrectLevel.H; default: throw new Error("Unknown error correction level: " + ecl); } }
javascript
function _getErrorCorrectLevel(ecl) { switch (ecl) { case "L": return QRErrorCorrectLevel.L; case "M": return QRErrorCorrectLevel.M; case "Q": return QRErrorCorrectLevel.Q; case "H": return QRErrorCorrectLevel.H; default: throw new Error("Unknown error correction level: " + ecl); } }
[ "function", "_getErrorCorrectLevel", "(", "ecl", ")", "{", "switch", "(", "ecl", ")", "{", "case", "\"L\"", ":", "return", "QRErrorCorrectLevel", ".", "L", ";", "case", "\"M\"", ":", "return", "QRErrorCorrectLevel", ".", "M", ";", "case", "\"Q\"", ":", "return", "QRErrorCorrectLevel", ".", "Q", ";", "case", "\"H\"", ":", "return", "QRErrorCorrectLevel", ".", "H", ";", "default", ":", "throw", "new", "Error", "(", "\"Unknown error correction level: \"", "+", "ecl", ")", ";", "}", "}" ]
Gets the error correction level
[ "Gets", "the", "error", "correction", "level" ]
5dc8b8659cee5d64dc400c4e22d148a0daa4fade
https://github.com/nating/react-native-custom-qr-codes/blob/5dc8b8659cee5d64dc400c4e22d148a0daa4fade/lib/QRCodeGenerator.js#L211-L228
17,227
nating/react-native-custom-qr-codes
lib/QRCodeGenerator.js
_getTypeNumber
function _getTypeNumber(content, ecl) { var length = _getUTF8Length(content); var type = 1; var limit = 0; for (var i = 0, len = QRCodeLimitLength.length; i <= len; i++) { var table = QRCodeLimitLength[i]; if (!table) { throw new Error("Content too long: expected " + limit + " but got " + length); } switch (ecl) { case "L": limit = table[0]; break; case "M": limit = table[1]; break; case "Q": limit = table[2]; break; case "H": limit = table[3]; break; default: throw new Error("Unknwon error correction level: " + ecl); } if (length <= limit) { break; } type++; } if (type > QRCodeLimitLength.length) { throw new Error("Content too long"); } return type; }
javascript
function _getTypeNumber(content, ecl) { var length = _getUTF8Length(content); var type = 1; var limit = 0; for (var i = 0, len = QRCodeLimitLength.length; i <= len; i++) { var table = QRCodeLimitLength[i]; if (!table) { throw new Error("Content too long: expected " + limit + " but got " + length); } switch (ecl) { case "L": limit = table[0]; break; case "M": limit = table[1]; break; case "Q": limit = table[2]; break; case "H": limit = table[3]; break; default: throw new Error("Unknwon error correction level: " + ecl); } if (length <= limit) { break; } type++; } if (type > QRCodeLimitLength.length) { throw new Error("Content too long"); } return type; }
[ "function", "_getTypeNumber", "(", "content", ",", "ecl", ")", "{", "var", "length", "=", "_getUTF8Length", "(", "content", ")", ";", "var", "type", "=", "1", ";", "var", "limit", "=", "0", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "QRCodeLimitLength", ".", "length", ";", "i", "<=", "len", ";", "i", "++", ")", "{", "var", "table", "=", "QRCodeLimitLength", "[", "i", "]", ";", "if", "(", "!", "table", ")", "{", "throw", "new", "Error", "(", "\"Content too long: expected \"", "+", "limit", "+", "\" but got \"", "+", "length", ")", ";", "}", "switch", "(", "ecl", ")", "{", "case", "\"L\"", ":", "limit", "=", "table", "[", "0", "]", ";", "break", ";", "case", "\"M\"", ":", "limit", "=", "table", "[", "1", "]", ";", "break", ";", "case", "\"Q\"", ":", "limit", "=", "table", "[", "2", "]", ";", "break", ";", "case", "\"H\"", ":", "limit", "=", "table", "[", "3", "]", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "\"Unknwon error correction level: \"", "+", "ecl", ")", ";", "}", "if", "(", "length", "<=", "limit", ")", "{", "break", ";", "}", "type", "++", ";", "}", "if", "(", "type", ">", "QRCodeLimitLength", ".", "length", ")", "{", "throw", "new", "Error", "(", "\"Content too long\"", ")", ";", "}", "return", "type", ";", "}" ]
Get type number
[ "Get", "type", "number" ]
5dc8b8659cee5d64dc400c4e22d148a0daa4fade
https://github.com/nating/react-native-custom-qr-codes/blob/5dc8b8659cee5d64dc400c4e22d148a0daa4fade/lib/QRCodeGenerator.js#L231-L275
17,228
nating/react-native-custom-qr-codes
lib/QRCodeGenerator.js
_getUTF8Length
function _getUTF8Length(content) { var result = encodeURI(content).toString().replace(/\%[0-9a-fA-F]{2}/g, 'a'); return result.length + (result.length != content ? 3 : 0); }
javascript
function _getUTF8Length(content) { var result = encodeURI(content).toString().replace(/\%[0-9a-fA-F]{2}/g, 'a'); return result.length + (result.length != content ? 3 : 0); }
[ "function", "_getUTF8Length", "(", "content", ")", "{", "var", "result", "=", "encodeURI", "(", "content", ")", ".", "toString", "(", ")", ".", "replace", "(", "/", "\\%[0-9a-fA-F]{2}", "/", "g", ",", "'a'", ")", ";", "return", "result", ".", "length", "+", "(", "result", ".", "length", "!=", "content", "?", "3", ":", "0", ")", ";", "}" ]
Gets text length
[ "Gets", "text", "length" ]
5dc8b8659cee5d64dc400c4e22d148a0daa4fade
https://github.com/nating/react-native-custom-qr-codes/blob/5dc8b8659cee5d64dc400c4e22d148a0daa4fade/lib/QRCodeGenerator.js#L278-L281
17,229
nating/react-native-custom-qr-codes
lib/QRCodeGenerator.js
getShapeZero
function getShapeZero(x,y,options,modules){ var EOL = '\r\n'; var width = options.width; var height = options.height; var length = modules.length; var style = options.style; var xsize = width / (length + 2 * options.padding); var ysize = height / (length + 2 * options.padding); var px = (x * xsize + options.padding * xsize); var py = (y * ysize + options.padding * ysize); switch(options.style){ case 'square': return '<rect x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL; case 'circle': return '<rect rx="'+xsize+'" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL; case 'sharp-edge': return '<rect transform="rotate(45 '+(px+xsize/2)+' '+(py+ysize/2)+')" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL; case 'ninja': return '<g transform="translate('+px+','+py+') scale('+1+','+1+')"><g transform="" style="fill: rgb(255, 0, 0);"><path d="M0,14V0c0,0,9.15,4.38,14,0.55C14,0.55,14.24,14,0,14z"/></g></g>' } }
javascript
function getShapeZero(x,y,options,modules){ var EOL = '\r\n'; var width = options.width; var height = options.height; var length = modules.length; var style = options.style; var xsize = width / (length + 2 * options.padding); var ysize = height / (length + 2 * options.padding); var px = (x * xsize + options.padding * xsize); var py = (y * ysize + options.padding * ysize); switch(options.style){ case 'square': return '<rect x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL; case 'circle': return '<rect rx="'+xsize+'" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL; case 'sharp-edge': return '<rect transform="rotate(45 '+(px+xsize/2)+' '+(py+ysize/2)+')" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL; case 'ninja': return '<g transform="translate('+px+','+py+') scale('+1+','+1+')"><g transform="" style="fill: rgb(255, 0, 0);"><path d="M0,14V0c0,0,9.15,4.38,14,0.55C14,0.55,14.24,14,0,14z"/></g></g>' } }
[ "function", "getShapeZero", "(", "x", ",", "y", ",", "options", ",", "modules", ")", "{", "var", "EOL", "=", "'\\r\\n'", ";", "var", "width", "=", "options", ".", "width", ";", "var", "height", "=", "options", ".", "height", ";", "var", "length", "=", "modules", ".", "length", ";", "var", "style", "=", "options", ".", "style", ";", "var", "xsize", "=", "width", "/", "(", "length", "+", "2", "*", "options", ".", "padding", ")", ";", "var", "ysize", "=", "height", "/", "(", "length", "+", "2", "*", "options", ".", "padding", ")", ";", "var", "px", "=", "(", "x", "*", "xsize", "+", "options", ".", "padding", "*", "xsize", ")", ";", "var", "py", "=", "(", "y", "*", "ysize", "+", "options", ".", "padding", "*", "ysize", ")", ";", "switch", "(", "options", ".", "style", ")", "{", "case", "'square'", ":", "return", "'<rect x=\"'", "+", "px", "+", "'\" y=\"'", "+", "py", "+", "'\" width=\"'", "+", "xsize", "+", "'\" height=\"'", "+", "ysize", "+", "'\" style=\"fill:'", "+", "options", ".", "color", "+", "';shape-rendering:crispEdges;\"/>'", "+", "EOL", ";", "case", "'circle'", ":", "return", "'<rect rx=\"'", "+", "xsize", "+", "'\" x=\"'", "+", "px", "+", "'\" y=\"'", "+", "py", "+", "'\" width=\"'", "+", "xsize", "+", "'\" height=\"'", "+", "ysize", "+", "'\" style=\"fill:'", "+", "options", ".", "color", "+", "';shape-rendering:crispEdges;\"/>'", "+", "EOL", ";", "case", "'sharp-edge'", ":", "return", "'<rect transform=\"rotate(45 '", "+", "(", "px", "+", "xsize", "/", "2", ")", "+", "' '", "+", "(", "py", "+", "ysize", "/", "2", ")", "+", "')\" x=\"'", "+", "px", "+", "'\" y=\"'", "+", "py", "+", "'\" width=\"'", "+", "xsize", "+", "'\" height=\"'", "+", "ysize", "+", "'\" style=\"fill:'", "+", "options", ".", "color", "+", "';shape-rendering:crispEdges;\"/>'", "+", "EOL", ";", "case", "'ninja'", ":", "return", "'<g transform=\"translate('", "+", "px", "+", "','", "+", "py", "+", "') scale('", "+", "1", "+", "','", "+", "1", "+", "')\"><g transform=\"\" style=\"fill: rgb(255, 0, 0);\"><path d=\"M0,14V0c0,0,9.15,4.38,14,0.55C14,0.55,14.24,14,0,14z\"/></g></g>'", "}", "}" ]
Returns an SVG element for a box with no surrounding boxes
[ "Returns", "an", "SVG", "element", "for", "a", "box", "with", "no", "surrounding", "boxes" ]
5dc8b8659cee5d64dc400c4e22d148a0daa4fade
https://github.com/nating/react-native-custom-qr-codes/blob/5dc8b8659cee5d64dc400c4e22d148a0daa4fade/lib/QRCodeGenerator.js#L393-L415
17,230
yahoo/monitr
lib/monitor.js
setupReqCounter
function setupReqCounter() { reqCounter = reqCounter || new ReqCounter(); process.monitor.getRequestCount = function () { return reqCounter._requests; }; process.monitor.getTotalRequestCount = function () { return reqCounter._totalRequests; }; process.monitor.getTransferred = function () { return reqCounter._transferred; }; process.monitor.getOpenConnections = function () { return reqCounter._connections; }; }
javascript
function setupReqCounter() { reqCounter = reqCounter || new ReqCounter(); process.monitor.getRequestCount = function () { return reqCounter._requests; }; process.monitor.getTotalRequestCount = function () { return reqCounter._totalRequests; }; process.monitor.getTransferred = function () { return reqCounter._transferred; }; process.monitor.getOpenConnections = function () { return reqCounter._connections; }; }
[ "function", "setupReqCounter", "(", ")", "{", "reqCounter", "=", "reqCounter", "||", "new", "ReqCounter", "(", ")", ";", "process", ".", "monitor", ".", "getRequestCount", "=", "function", "(", ")", "{", "return", "reqCounter", ".", "_requests", ";", "}", ";", "process", ".", "monitor", ".", "getTotalRequestCount", "=", "function", "(", ")", "{", "return", "reqCounter", ".", "_totalRequests", ";", "}", ";", "process", ".", "monitor", ".", "getTransferred", "=", "function", "(", ")", "{", "return", "reqCounter", ".", "_transferred", ";", "}", ";", "process", ".", "monitor", ".", "getOpenConnections", "=", "function", "(", ")", "{", "return", "reqCounter", ".", "_connections", ";", "}", ";", "}" ]
Instantiate the request counter Add methods to process object
[ "Instantiate", "the", "request", "counter", "Add", "methods", "to", "process", "object" ]
38849c3a88a0b0521c0f0559bd81ebe2da46ecb1
https://github.com/yahoo/monitr/blob/38849c3a88a0b0521c0f0559bd81ebe2da46ecb1/lib/monitor.js#L159-L178
17,231
evothings/cordova-ble
examples/webbluetooth/tisensortag/app.js
startLuxometerNotifications
function startLuxometerNotifications() { showMessage('Scanning...') bleat.requestDevice( { filters:[{ name: 'CC2650 SensorTag' }] }) .then(function(device) { showMessage('Found device: ' + device.name) return device.gatt.connect() }) .then(function(server) { gattServer = server showMessage('Connected') return gattServer.getPrimaryService(LUXOMETER_SERVICE) }) .then(function(service) { // Get config characteristic. luxometerService = service return luxometerService.getCharacteristic(LUXOMETER_CONFIG) }) .then(function(characteristic) { // Turn luxometer config to ON. return characteristic.writeValue(new Uint8Array([1])) }) .then(function() { // Get data characteristic. return luxometerService.getCharacteristic(LUXOMETER_DATA) }) .then(function(characteristic) { // Start sensor notification. showMessage('Starting notfications') characteristic.addEventListener('characteristicvaluechanged', onLuxometerChanged) return characteristic.startNotifications() }) .catch(function(error) { showMessage(error) }) }
javascript
function startLuxometerNotifications() { showMessage('Scanning...') bleat.requestDevice( { filters:[{ name: 'CC2650 SensorTag' }] }) .then(function(device) { showMessage('Found device: ' + device.name) return device.gatt.connect() }) .then(function(server) { gattServer = server showMessage('Connected') return gattServer.getPrimaryService(LUXOMETER_SERVICE) }) .then(function(service) { // Get config characteristic. luxometerService = service return luxometerService.getCharacteristic(LUXOMETER_CONFIG) }) .then(function(characteristic) { // Turn luxometer config to ON. return characteristic.writeValue(new Uint8Array([1])) }) .then(function() { // Get data characteristic. return luxometerService.getCharacteristic(LUXOMETER_DATA) }) .then(function(characteristic) { // Start sensor notification. showMessage('Starting notfications') characteristic.addEventListener('characteristicvaluechanged', onLuxometerChanged) return characteristic.startNotifications() }) .catch(function(error) { showMessage(error) }) }
[ "function", "startLuxometerNotifications", "(", ")", "{", "showMessage", "(", "'Scanning...'", ")", "bleat", ".", "requestDevice", "(", "{", "filters", ":", "[", "{", "name", ":", "'CC2650 SensorTag'", "}", "]", "}", ")", ".", "then", "(", "function", "(", "device", ")", "{", "showMessage", "(", "'Found device: '", "+", "device", ".", "name", ")", "return", "device", ".", "gatt", ".", "connect", "(", ")", "}", ")", ".", "then", "(", "function", "(", "server", ")", "{", "gattServer", "=", "server", "showMessage", "(", "'Connected'", ")", "return", "gattServer", ".", "getPrimaryService", "(", "LUXOMETER_SERVICE", ")", "}", ")", ".", "then", "(", "function", "(", "service", ")", "{", "// Get config characteristic.", "luxometerService", "=", "service", "return", "luxometerService", ".", "getCharacteristic", "(", "LUXOMETER_CONFIG", ")", "}", ")", ".", "then", "(", "function", "(", "characteristic", ")", "{", "// Turn luxometer config to ON.", "return", "characteristic", ".", "writeValue", "(", "new", "Uint8Array", "(", "[", "1", "]", ")", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "// Get data characteristic.", "return", "luxometerService", ".", "getCharacteristic", "(", "LUXOMETER_DATA", ")", "}", ")", ".", "then", "(", "function", "(", "characteristic", ")", "{", "// Start sensor notification.", "showMessage", "(", "'Starting notfications'", ")", "characteristic", ".", "addEventListener", "(", "'characteristicvaluechanged'", ",", "onLuxometerChanged", ")", "return", "characteristic", ".", "startNotifications", "(", ")", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "showMessage", "(", "error", ")", "}", ")", "}" ]
Main application function.
[ "Main", "application", "function", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/examples/webbluetooth/tisensortag/app.js#L18-L64
17,232
evothings/cordova-ble
examples/webbluetooth/tisensortag/app.js
onLuxometerChanged
function onLuxometerChanged(event) { var characteristic = event.target var lux = calculateLux(characteristic.value) showMessage('Luxometer value: ' + lux) }
javascript
function onLuxometerChanged(event) { var characteristic = event.target var lux = calculateLux(characteristic.value) showMessage('Luxometer value: ' + lux) }
[ "function", "onLuxometerChanged", "(", "event", ")", "{", "var", "characteristic", "=", "event", ".", "target", "var", "lux", "=", "calculateLux", "(", "characteristic", ".", "value", ")", "showMessage", "(", "'Luxometer value: '", "+", "lux", ")", "}" ]
Notification callback function.
[ "Notification", "callback", "function", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/examples/webbluetooth/tisensortag/app.js#L78-L83
17,233
evothings/cordova-ble
examples/webbluetooth/tisensortag/app.js
calculateLux
function calculateLux(data) { // Get 16 bit value from data buffer in little endian format. var value = data.getUint16(0, true) // Extraction of luxometer value, based on sfloatExp2ToDouble // from BLEUtility.m in Texas Instruments TI BLE SensorTag // iOS app source code. var mantissa = value & 0x0FFF var exponent = value >> 12 var magnitude = Math.pow(2, exponent) var output = (mantissa * magnitude) var lux = output / 100.0 // Return result. return lux }
javascript
function calculateLux(data) { // Get 16 bit value from data buffer in little endian format. var value = data.getUint16(0, true) // Extraction of luxometer value, based on sfloatExp2ToDouble // from BLEUtility.m in Texas Instruments TI BLE SensorTag // iOS app source code. var mantissa = value & 0x0FFF var exponent = value >> 12 var magnitude = Math.pow(2, exponent) var output = (mantissa * magnitude) var lux = output / 100.0 // Return result. return lux }
[ "function", "calculateLux", "(", "data", ")", "{", "// Get 16 bit value from data buffer in little endian format.", "var", "value", "=", "data", ".", "getUint16", "(", "0", ",", "true", ")", "// Extraction of luxometer value, based on sfloatExp2ToDouble", "// from BLEUtility.m in Texas Instruments TI BLE SensorTag", "// iOS app source code.", "var", "mantissa", "=", "value", "&", "0x0FFF", "var", "exponent", "=", "value", ">>", "12", "var", "magnitude", "=", "Math", ".", "pow", "(", "2", ",", "exponent", ")", "var", "output", "=", "(", "mantissa", "*", "magnitude", ")", "var", "lux", "=", "output", "/", "100.0", "// Return result.", "return", "lux", "}" ]
Calculate the light level from raw sensor data. Return light level in lux.
[ "Calculate", "the", "light", "level", "from", "raw", "sensor", "data", ".", "Return", "light", "level", "in", "lux", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/examples/webbluetooth/tisensortag/app.js#L87-L105
17,234
evothings/cordova-ble
examples/core-api/hexiwear-bonding/app.js
findDevice
function findDevice() { disconnectDevice() // Used for debugging/testing. //scanForDevice() //return searchForBondedDevice({ name: 'HEXIWEAR', serviceUUIDs: [INFO_SERVICE], onFound: connectToDevice, onNotFound: scanForDevice, }) }
javascript
function findDevice() { disconnectDevice() // Used for debugging/testing. //scanForDevice() //return searchForBondedDevice({ name: 'HEXIWEAR', serviceUUIDs: [INFO_SERVICE], onFound: connectToDevice, onNotFound: scanForDevice, }) }
[ "function", "findDevice", "(", ")", "{", "disconnectDevice", "(", ")", "// Used for debugging/testing.", "//scanForDevice()", "//return", "searchForBondedDevice", "(", "{", "name", ":", "'HEXIWEAR'", ",", "serviceUUIDs", ":", "[", "INFO_SERVICE", "]", ",", "onFound", ":", "connectToDevice", ",", "onNotFound", ":", "scanForDevice", ",", "}", ")", "}" ]
End of code used for testing.
[ "End", "of", "code", "used", "for", "testing", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/examples/core-api/hexiwear-bonding/app.js#L96-L110
17,235
evothings/cordova-ble
examples/core-api/hexiwear-bonding/app.js
searchForBondedDevice
function searchForBondedDevice(params) { console.log('Searching for bonded device') evothings.ble.getBondedDevices( // Success function. function(devices) { for (var i in devices) { var device = devices[i] if (device.name == params.name) { console.log('Found bonded device: ' + device.name) params.onFound(device) return // bonded device found } } params.onNotFound() }, // Error function. function(error) { params.onNotFound() }, { serviceUUIDs: params.serviceUUIDs }) }
javascript
function searchForBondedDevice(params) { console.log('Searching for bonded device') evothings.ble.getBondedDevices( // Success function. function(devices) { for (var i in devices) { var device = devices[i] if (device.name == params.name) { console.log('Found bonded device: ' + device.name) params.onFound(device) return // bonded device found } } params.onNotFound() }, // Error function. function(error) { params.onNotFound() }, { serviceUUIDs: params.serviceUUIDs }) }
[ "function", "searchForBondedDevice", "(", "params", ")", "{", "console", ".", "log", "(", "'Searching for bonded device'", ")", "evothings", ".", "ble", ".", "getBondedDevices", "(", "// Success function.", "function", "(", "devices", ")", "{", "for", "(", "var", "i", "in", "devices", ")", "{", "var", "device", "=", "devices", "[", "i", "]", "if", "(", "device", ".", "name", "==", "params", ".", "name", ")", "{", "console", ".", "log", "(", "'Found bonded device: '", "+", "device", ".", "name", ")", "params", ".", "onFound", "(", "device", ")", "return", "// bonded device found", "}", "}", "params", ".", "onNotFound", "(", ")", "}", ",", "// Error function.", "function", "(", "error", ")", "{", "params", ".", "onNotFound", "(", ")", "}", ",", "{", "serviceUUIDs", ":", "params", ".", "serviceUUIDs", "}", ")", "}" ]
Search for bonded device with a given name. Useful if the address is not known.
[ "Search", "for", "bonded", "device", "with", "a", "given", "name", ".", "Useful", "if", "the", "address", "is", "not", "known", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/examples/core-api/hexiwear-bonding/app.js#L125-L150
17,236
evothings/cordova-ble
ble.js
getCanonicalUUIDArray
function getCanonicalUUIDArray(uuidArray) { var result = []; for (var i in uuidArray) { result.push(exports.getCanonicalUUID(uuidArray[i])); } return result; }
javascript
function getCanonicalUUIDArray(uuidArray) { var result = []; for (var i in uuidArray) { result.push(exports.getCanonicalUUID(uuidArray[i])); } return result; }
[ "function", "getCanonicalUUIDArray", "(", "uuidArray", ")", "{", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "in", "uuidArray", ")", "{", "result", ".", "push", "(", "exports", ".", "getCanonicalUUID", "(", "uuidArray", "[", "i", "]", ")", ")", ";", "}", "return", "result", ";", "}" ]
Ensure that all UUIDs in an array has canonical form. @private
[ "Ensure", "that", "all", "UUIDs", "in", "an", "array", "has", "canonical", "form", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/ble.js#L154-L164
17,237
evothings/cordova-ble
ble.js
littleEndianToUint32
function littleEndianToUint32(data, offset) { return (littleEndianToUint8(data, offset + 3) << 24) + (littleEndianToUint8(data, offset + 2) << 16) + (littleEndianToUint8(data, offset + 1) << 8) + littleEndianToUint8(data, offset) }
javascript
function littleEndianToUint32(data, offset) { return (littleEndianToUint8(data, offset + 3) << 24) + (littleEndianToUint8(data, offset + 2) << 16) + (littleEndianToUint8(data, offset + 1) << 8) + littleEndianToUint8(data, offset) }
[ "function", "littleEndianToUint32", "(", "data", ",", "offset", ")", "{", "return", "(", "littleEndianToUint8", "(", "data", ",", "offset", "+", "3", ")", "<<", "24", ")", "+", "(", "littleEndianToUint8", "(", "data", ",", "offset", "+", "2", ")", "<<", "16", ")", "+", "(", "littleEndianToUint8", "(", "data", ",", "offset", "+", "1", ")", "<<", "8", ")", "+", "littleEndianToUint8", "(", "data", ",", "offset", ")", "}" ]
Interpret byte buffer as unsigned little endian 32 bit integer. Returns converted number. @param {ArrayBuffer} data - Input buffer. @param {number} offset - Start of data. @return Converted number. @public
[ "Interpret", "byte", "buffer", "as", "unsigned", "little", "endian", "32", "bit", "integer", ".", "Returns", "converted", "number", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/ble.js#L506-L512
17,238
evothings/cordova-ble
ble.js
littleEndianToInt8
function littleEndianToInt8(data, offset) { var x = littleEndianToUint8(data, offset) if (x & 0x80) x = x - 256 return x }
javascript
function littleEndianToInt8(data, offset) { var x = littleEndianToUint8(data, offset) if (x & 0x80) x = x - 256 return x }
[ "function", "littleEndianToInt8", "(", "data", ",", "offset", ")", "{", "var", "x", "=", "littleEndianToUint8", "(", "data", ",", "offset", ")", "if", "(", "x", "&", "0x80", ")", "x", "=", "x", "-", "256", "return", "x", "}" ]
Interpret byte buffer as little endian 8 bit integer. Returns converted number. @param {ArrayBuffer} data - Input buffer. @param {number} offset - Start of data. @return Converted number. @public
[ "Interpret", "byte", "buffer", "as", "little", "endian", "8", "bit", "integer", ".", "Returns", "converted", "number", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/ble.js#L522-L527
17,239
evothings/cordova-ble
ble.js
gattServerCallbackHandler
function gattServerCallbackHandler(winFunc, settings) { // collect read/write callbacks and add handles, so the native side can tell us which one to call. var readCallbacks = {}; var writeCallbacks = {}; var nextHandle = 1; function handleCallback(object, name, callbacks) { if(!object[name]) { throw name+" missing!"; } callbacks[nextHandle] = object[name]; object[name+"Handle"] = nextHandle; nextHandle += 1; } function handleReadWrite(object) { /* // primitive version if(!object.readRequestCallback) { throw "readRequestCallback missing!"); } readCallbacks[nextHandle] = object.readRequestCallback; */ handleCallback(object, "onReadRequest", readCallbacks); handleCallback(object, "onWriteRequest", writeCallbacks); } for(var i=0; i<settings.services.length; i++) { var service = settings.services[i]; for(var j=0; j<service.characteristics.length; j++) { var characteristic = service.characteristics[j]; handleReadWrite(characteristic); for(var k=0; k<characteristic.descriptors.length; k++) { var descriptor = characteristic.descriptors[k]; handleReadWrite(descriptor); } } } settings.nextHandle = nextHandle; return function(args) { // primitive version /*if(args.name == "win") { winFunc(); return; }*/ var funcs = { win: winFunc, connection: function() { settings.onConnectionStateChange(args.deviceHandle, args.connected); }, write: function() { writeCallbacks[args.callbackHandle](args.deviceHandle, args.requestId, args.data); }, read: function() { readCallbacks[args.callbackHandle](args.deviceHandle, args.requestId); }, }; funcs[args.name](); }; }
javascript
function gattServerCallbackHandler(winFunc, settings) { // collect read/write callbacks and add handles, so the native side can tell us which one to call. var readCallbacks = {}; var writeCallbacks = {}; var nextHandle = 1; function handleCallback(object, name, callbacks) { if(!object[name]) { throw name+" missing!"; } callbacks[nextHandle] = object[name]; object[name+"Handle"] = nextHandle; nextHandle += 1; } function handleReadWrite(object) { /* // primitive version if(!object.readRequestCallback) { throw "readRequestCallback missing!"); } readCallbacks[nextHandle] = object.readRequestCallback; */ handleCallback(object, "onReadRequest", readCallbacks); handleCallback(object, "onWriteRequest", writeCallbacks); } for(var i=0; i<settings.services.length; i++) { var service = settings.services[i]; for(var j=0; j<service.characteristics.length; j++) { var characteristic = service.characteristics[j]; handleReadWrite(characteristic); for(var k=0; k<characteristic.descriptors.length; k++) { var descriptor = characteristic.descriptors[k]; handleReadWrite(descriptor); } } } settings.nextHandle = nextHandle; return function(args) { // primitive version /*if(args.name == "win") { winFunc(); return; }*/ var funcs = { win: winFunc, connection: function() { settings.onConnectionStateChange(args.deviceHandle, args.connected); }, write: function() { writeCallbacks[args.callbackHandle](args.deviceHandle, args.requestId, args.data); }, read: function() { readCallbacks[args.callbackHandle](args.deviceHandle, args.requestId); }, }; funcs[args.name](); }; }
[ "function", "gattServerCallbackHandler", "(", "winFunc", ",", "settings", ")", "{", "// collect read/write callbacks and add handles, so the native side can tell us which one to call.", "var", "readCallbacks", "=", "{", "}", ";", "var", "writeCallbacks", "=", "{", "}", ";", "var", "nextHandle", "=", "1", ";", "function", "handleCallback", "(", "object", ",", "name", ",", "callbacks", ")", "{", "if", "(", "!", "object", "[", "name", "]", ")", "{", "throw", "name", "+", "\" missing!\"", ";", "}", "callbacks", "[", "nextHandle", "]", "=", "object", "[", "name", "]", ";", "object", "[", "name", "+", "\"Handle\"", "]", "=", "nextHandle", ";", "nextHandle", "+=", "1", ";", "}", "function", "handleReadWrite", "(", "object", ")", "{", "/* // primitive version\n\t\tif(!object.readRequestCallback) {\n\t\t\tthrow \"readRequestCallback missing!\");\n\t\t}\n\t\treadCallbacks[nextHandle] = object.readRequestCallback;\n\t\t*/", "handleCallback", "(", "object", ",", "\"onReadRequest\"", ",", "readCallbacks", ")", ";", "handleCallback", "(", "object", ",", "\"onWriteRequest\"", ",", "writeCallbacks", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "settings", ".", "services", ".", "length", ";", "i", "++", ")", "{", "var", "service", "=", "settings", ".", "services", "[", "i", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "service", ".", "characteristics", ".", "length", ";", "j", "++", ")", "{", "var", "characteristic", "=", "service", ".", "characteristics", "[", "j", "]", ";", "handleReadWrite", "(", "characteristic", ")", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "characteristic", ".", "descriptors", ".", "length", ";", "k", "++", ")", "{", "var", "descriptor", "=", "characteristic", ".", "descriptors", "[", "k", "]", ";", "handleReadWrite", "(", "descriptor", ")", ";", "}", "}", "}", "settings", ".", "nextHandle", "=", "nextHandle", ";", "return", "function", "(", "args", ")", "{", "// primitive version", "/*if(args.name == \"win\") {\n\t\t\twinFunc();\n\t\t\treturn;\n\t\t}*/", "var", "funcs", "=", "{", "win", ":", "winFunc", ",", "connection", ":", "function", "(", ")", "{", "settings", ".", "onConnectionStateChange", "(", "args", ".", "deviceHandle", ",", "args", ".", "connected", ")", ";", "}", ",", "write", ":", "function", "(", ")", "{", "writeCallbacks", "[", "args", ".", "callbackHandle", "]", "(", "args", ".", "deviceHandle", ",", "args", ".", "requestId", ",", "args", ".", "data", ")", ";", "}", ",", "read", ":", "function", "(", ")", "{", "readCallbacks", "[", "args", ".", "callbackHandle", "]", "(", "args", ".", "deviceHandle", ",", "args", ".", "requestId", ")", ";", "}", ",", "}", ";", "funcs", "[", "args", ".", "name", "]", "(", ")", ";", "}", ";", "}" ]
Internal. Returns a function that will handle GATT server callbacks.
[ "Internal", ".", "Returns", "a", "function", "that", "will", "handle", "GATT", "server", "callbacks", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/ble.js#L1874-L1934
17,240
evothings/cordova-ble
src/windows/bleProxy.js
function (containerId) { for (var property in winble.deviceManager.deviceList) { if (winble.deviceManager.deviceList[property] && winble.deviceManager.deviceList[property].containerId == containerId) return (winble.deviceManager.deviceList[property]); } return (null); }
javascript
function (containerId) { for (var property in winble.deviceManager.deviceList) { if (winble.deviceManager.deviceList[property] && winble.deviceManager.deviceList[property].containerId == containerId) return (winble.deviceManager.deviceList[property]); } return (null); }
[ "function", "(", "containerId", ")", "{", "for", "(", "var", "property", "in", "winble", ".", "deviceManager", ".", "deviceList", ")", "{", "if", "(", "winble", ".", "deviceManager", ".", "deviceList", "[", "property", "]", "&&", "winble", ".", "deviceManager", ".", "deviceList", "[", "property", "]", ".", "containerId", "==", "containerId", ")", "return", "(", "winble", ".", "deviceManager", ".", "deviceList", "[", "property", "]", ")", ";", "}", "return", "(", "null", ")", ";", "}" ]
Called internally to look up a previously discovered BLE device by its Windows container ID. Look up the requested device and complain if we can't find it.
[ "Called", "internally", "to", "look", "up", "a", "previously", "discovered", "BLE", "device", "by", "its", "Windows", "container", "ID", ".", "Look", "up", "the", "requested", "device", "and", "complain", "if", "we", "can", "t", "find", "it", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L290-L296
17,241
evothings/cordova-ble
src/windows/bleProxy.js
function (deviceHandle, functionName, errorCallback) { var device = winble.deviceManager.deviceList[deviceHandle]; if (device == null) { var msg = "Could not find the requested device handle '" + deviceHandle + "'"; winble.logger.logError(functionName, msg); errorCallback(winble.DEVICE_NOT_FOUND); } return (device); }
javascript
function (deviceHandle, functionName, errorCallback) { var device = winble.deviceManager.deviceList[deviceHandle]; if (device == null) { var msg = "Could not find the requested device handle '" + deviceHandle + "'"; winble.logger.logError(functionName, msg); errorCallback(winble.DEVICE_NOT_FOUND); } return (device); }
[ "function", "(", "deviceHandle", ",", "functionName", ",", "errorCallback", ")", "{", "var", "device", "=", "winble", ".", "deviceManager", ".", "deviceList", "[", "deviceHandle", "]", ";", "if", "(", "device", "==", "null", ")", "{", "var", "msg", "=", "\"Could not find the requested device handle '\"", "+", "deviceHandle", "+", "\"'\"", ";", "winble", ".", "logger", ".", "logError", "(", "functionName", ",", "msg", ")", ";", "errorCallback", "(", "winble", ".", "DEVICE_NOT_FOUND", ")", ";", "}", "return", "(", "device", ")", ";", "}" ]
Called internally to look up a previously discovered BLE device by handle. Look up the requested device and complain if we can't find it.
[ "Called", "internally", "to", "look", "up", "a", "previously", "discovered", "BLE", "device", "by", "handle", ".", "Look", "up", "the", "requested", "device", "and", "complain", "if", "we", "can", "t", "find", "it", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L300-L308
17,242
evothings/cordova-ble
src/windows/bleProxy.js
function (device, serviceHandle, functionName, errorCallback) { var service = device.serviceList[serviceHandle]; if (service == null) { var msg = "Could not find the requested service handle '" + serviceHandle + "'"; winble.logger.logError(functionName, msg); errorCallback(msg); } return (service); }
javascript
function (device, serviceHandle, functionName, errorCallback) { var service = device.serviceList[serviceHandle]; if (service == null) { var msg = "Could not find the requested service handle '" + serviceHandle + "'"; winble.logger.logError(functionName, msg); errorCallback(msg); } return (service); }
[ "function", "(", "device", ",", "serviceHandle", ",", "functionName", ",", "errorCallback", ")", "{", "var", "service", "=", "device", ".", "serviceList", "[", "serviceHandle", "]", ";", "if", "(", "service", "==", "null", ")", "{", "var", "msg", "=", "\"Could not find the requested service handle '\"", "+", "serviceHandle", "+", "\"'\"", ";", "winble", ".", "logger", ".", "logError", "(", "functionName", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "}", "return", "(", "service", ")", ";", "}" ]
Called internally to look up a previously discovered service by handle. Look up the requested service and complain if we can't find it.
[ "Called", "internally", "to", "look", "up", "a", "previously", "discovered", "service", "by", "handle", ".", "Look", "up", "the", "requested", "service", "and", "complain", "if", "we", "can", "t", "find", "it", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L312-L320
17,243
evothings/cordova-ble
src/windows/bleProxy.js
function (device, charHandle, functionName, errorCallback) { var characteristic = device.charList[charHandle]; if (characteristic == null) { var msg = "Could not find the requested characteristic handle '" + charHandle + "'"; winble.logger.logError(functionName, msg); errorCallback(msg); } return (characteristic); }
javascript
function (device, charHandle, functionName, errorCallback) { var characteristic = device.charList[charHandle]; if (characteristic == null) { var msg = "Could not find the requested characteristic handle '" + charHandle + "'"; winble.logger.logError(functionName, msg); errorCallback(msg); } return (characteristic); }
[ "function", "(", "device", ",", "charHandle", ",", "functionName", ",", "errorCallback", ")", "{", "var", "characteristic", "=", "device", ".", "charList", "[", "charHandle", "]", ";", "if", "(", "characteristic", "==", "null", ")", "{", "var", "msg", "=", "\"Could not find the requested characteristic handle '\"", "+", "charHandle", "+", "\"'\"", ";", "winble", ".", "logger", ".", "logError", "(", "functionName", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "}", "return", "(", "characteristic", ")", ";", "}" ]
Called internally to look up a previously discovered characteristic by handle. Look up the requested characteristic and complain if we can't find it.
[ "Called", "internally", "to", "look", "up", "a", "previously", "discovered", "characteristic", "by", "handle", ".", "Look", "up", "the", "requested", "characteristic", "and", "complain", "if", "we", "can", "t", "find", "it", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L324-L332
17,244
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback) { if (!winble.deviceManager.isScanning) { winble.deviceManager.scanSuccessCallback = successCallback; winble.deviceManager.scanErrorCallback = errorCallback; winble.deviceManager.isScanning = true; setTimeout(function () { winble.deviceManager.scanDevices(successCallback, errorCallback); }, 500); } }
javascript
function (successCallback, errorCallback) { if (!winble.deviceManager.isScanning) { winble.deviceManager.scanSuccessCallback = successCallback; winble.deviceManager.scanErrorCallback = errorCallback; winble.deviceManager.isScanning = true; setTimeout(function () { winble.deviceManager.scanDevices(successCallback, errorCallback); }, 500); } }
[ "function", "(", "successCallback", ",", "errorCallback", ")", "{", "if", "(", "!", "winble", ".", "deviceManager", ".", "isScanning", ")", "{", "winble", ".", "deviceManager", ".", "scanSuccessCallback", "=", "successCallback", ";", "winble", ".", "deviceManager", ".", "scanErrorCallback", "=", "errorCallback", ";", "winble", ".", "deviceManager", ".", "isScanning", "=", "true", ";", "setTimeout", "(", "function", "(", ")", "{", "winble", ".", "deviceManager", ".", "scanDevices", "(", "successCallback", ",", "errorCallback", ")", ";", "}", ",", "500", ")", ";", "}", "}" ]
Called from the startScan API; start scanning for available BLE devices
[ "Called", "from", "the", "startScan", "API", ";", "start", "scanning", "for", "available", "BLE", "devices" ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L335-L344
17,245
evothings/cordova-ble
src/windows/bleProxy.js
function () { if (winble.deviceManager.isScanning) winble.deviceManager.isScanning = false; if (winble.deviceManager.connectionWatcher !== null) winble.deviceManager.stopConnectionWatcher(); }
javascript
function () { if (winble.deviceManager.isScanning) winble.deviceManager.isScanning = false; if (winble.deviceManager.connectionWatcher !== null) winble.deviceManager.stopConnectionWatcher(); }
[ "function", "(", ")", "{", "if", "(", "winble", ".", "deviceManager", ".", "isScanning", ")", "winble", ".", "deviceManager", ".", "isScanning", "=", "false", ";", "if", "(", "winble", ".", "deviceManager", ".", "connectionWatcher", "!==", "null", ")", "winble", ".", "deviceManager", ".", "stopConnectionWatcher", "(", ")", ";", "}" ]
Called from the stopScan API; stop scanning for available BLE devices.
[ "Called", "from", "the", "stopScan", "API", ";", "stop", "scanning", "for", "available", "BLE", "devices", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L347-L352
17,246
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback) { // If the caller told us to stop scanning since our last scan, or all devices have been removed from the list, nothing to do if (!winble.deviceManager.isScanning || (winble.deviceManager.reportList.length == 0)) { winble.deviceManager.isReporting = false; return; } // Report the next device in our list var device = winble.deviceManager.getNextReportableDevice(); if (device != null) { winble.logger.logDebug("reportNextDevice", "Reporting scan for " + device.gattDevice.name); var deviceOut = { "address": device.gattDevice.id, "name": device.gattDevice.name, "rssi": device.rssi, "scanRecord": "" // Base64 string, iOS only }; successCallback(deviceOut, { keepCallback: true }); } // Set up the next report setTimeout(function () { winble.deviceManager.reportNextDevice(successCallback); }, winble.deviceManager.REPORT_INTERVAL); }
javascript
function (successCallback) { // If the caller told us to stop scanning since our last scan, or all devices have been removed from the list, nothing to do if (!winble.deviceManager.isScanning || (winble.deviceManager.reportList.length == 0)) { winble.deviceManager.isReporting = false; return; } // Report the next device in our list var device = winble.deviceManager.getNextReportableDevice(); if (device != null) { winble.logger.logDebug("reportNextDevice", "Reporting scan for " + device.gattDevice.name); var deviceOut = { "address": device.gattDevice.id, "name": device.gattDevice.name, "rssi": device.rssi, "scanRecord": "" // Base64 string, iOS only }; successCallback(deviceOut, { keepCallback: true }); } // Set up the next report setTimeout(function () { winble.deviceManager.reportNextDevice(successCallback); }, winble.deviceManager.REPORT_INTERVAL); }
[ "function", "(", "successCallback", ")", "{", "// If the caller told us to stop scanning since our last scan, or all devices have been removed from the list, nothing to do", "if", "(", "!", "winble", ".", "deviceManager", ".", "isScanning", "||", "(", "winble", ".", "deviceManager", ".", "reportList", ".", "length", "==", "0", ")", ")", "{", "winble", ".", "deviceManager", ".", "isReporting", "=", "false", ";", "return", ";", "}", "// Report the next device in our list", "var", "device", "=", "winble", ".", "deviceManager", ".", "getNextReportableDevice", "(", ")", ";", "if", "(", "device", "!=", "null", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"reportNextDevice\"", ",", "\"Reporting scan for \"", "+", "device", ".", "gattDevice", ".", "name", ")", ";", "var", "deviceOut", "=", "{", "\"address\"", ":", "device", ".", "gattDevice", ".", "id", ",", "\"name\"", ":", "device", ".", "gattDevice", ".", "name", ",", "\"rssi\"", ":", "device", ".", "rssi", ",", "\"scanRecord\"", ":", "\"\"", "// Base64 string, iOS only", "}", ";", "successCallback", "(", "deviceOut", ",", "{", "keepCallback", ":", "true", "}", ")", ";", "}", "// Set up the next report", "setTimeout", "(", "function", "(", ")", "{", "winble", ".", "deviceManager", ".", "reportNextDevice", "(", "successCallback", ")", ";", "}", ",", "winble", ".", "deviceManager", ".", "REPORT_INTERVAL", ")", ";", "}" ]
This function is called on a timed basis to report the next scanned device in our list to the caller
[ "This", "function", "is", "called", "on", "a", "timed", "basis", "to", "report", "the", "next", "scanned", "device", "in", "our", "list", "to", "the", "caller" ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L565-L590
17,247
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback, deviceId) { // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromId(deviceId, "connectToDevice", errorCallback); if (device == null) { errorCallback(winble.DEVICE_NOT_FOUND); return; } // Save the success callback; we will need to call this whenever the connection status changes. if (device.connectSuccessCallback == null) device.connectSuccessCallback = successCallback; // Call the success callback if the device is connected, error callback if not if (device.isReachable && device.isConnected) { winble.logger.logDebug("connectToDevice", "Connection successful"); var connectInfo = { "deviceHandle": device.handle, "state": 2 // 0 = Disconnected, 1 = Connecting, 2 = Connected, 3 = Disconnecting }; device.connectSuccessCallback(connectInfo, { keepCallback: true }); } else { winble.logger.logDebug("connectToDevice", "Connection failed"); errorCallback(winble.DEVICE_NOT_CONNECTED); } }
javascript
function (successCallback, errorCallback, deviceId) { // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromId(deviceId, "connectToDevice", errorCallback); if (device == null) { errorCallback(winble.DEVICE_NOT_FOUND); return; } // Save the success callback; we will need to call this whenever the connection status changes. if (device.connectSuccessCallback == null) device.connectSuccessCallback = successCallback; // Call the success callback if the device is connected, error callback if not if (device.isReachable && device.isConnected) { winble.logger.logDebug("connectToDevice", "Connection successful"); var connectInfo = { "deviceHandle": device.handle, "state": 2 // 0 = Disconnected, 1 = Connecting, 2 = Connected, 3 = Disconnecting }; device.connectSuccessCallback(connectInfo, { keepCallback: true }); } else { winble.logger.logDebug("connectToDevice", "Connection failed"); errorCallback(winble.DEVICE_NOT_CONNECTED); } }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "deviceId", ")", "{", "// Find the requested device in our list of discovered devices", "var", "device", "=", "winble", ".", "deviceManager", ".", "getDeviceFromId", "(", "deviceId", ",", "\"connectToDevice\"", ",", "errorCallback", ")", ";", "if", "(", "device", "==", "null", ")", "{", "errorCallback", "(", "winble", ".", "DEVICE_NOT_FOUND", ")", ";", "return", ";", "}", "// Save the success callback; we will need to call this whenever the connection status changes.", "if", "(", "device", ".", "connectSuccessCallback", "==", "null", ")", "device", ".", "connectSuccessCallback", "=", "successCallback", ";", "// Call the success callback if the device is connected, error callback if not", "if", "(", "device", ".", "isReachable", "&&", "device", ".", "isConnected", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"connectToDevice\"", ",", "\"Connection successful\"", ")", ";", "var", "connectInfo", "=", "{", "\"deviceHandle\"", ":", "device", ".", "handle", ",", "\"state\"", ":", "2", "// 0 = Disconnected, 1 = Connecting, 2 = Connected, 3 = Disconnecting", "}", ";", "device", ".", "connectSuccessCallback", "(", "connectInfo", ",", "{", "keepCallback", ":", "true", "}", ")", ";", "}", "else", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"connectToDevice\"", ",", "\"Connection failed\"", ")", ";", "errorCallback", "(", "winble", ".", "DEVICE_NOT_CONNECTED", ")", ";", "}", "}" ]
Called from the connect API; caller wants to connect to a previously discovered BLE device
[ "Called", "from", "the", "connect", "API", ";", "caller", "wants", "to", "connect", "to", "a", "previously", "discovered", "BLE", "device" ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L619-L644
17,248
evothings/cordova-ble
src/windows/bleProxy.js
function () { winble.deviceManager.connectionWatcher = Windows.Devices.Enumeration.Pnp.PnpObject.createWatcher( Windows.Devices.Enumeration.Pnp.PnpObjectType.deviceContainer, ["System.Devices.Connected"], ""); winble.deviceManager.connectionWatcher.onupdated = winble.deviceManager.onDeviceConnectionUpdated; winble.deviceManager.connectionWatcher.start(); }
javascript
function () { winble.deviceManager.connectionWatcher = Windows.Devices.Enumeration.Pnp.PnpObject.createWatcher( Windows.Devices.Enumeration.Pnp.PnpObjectType.deviceContainer, ["System.Devices.Connected"], ""); winble.deviceManager.connectionWatcher.onupdated = winble.deviceManager.onDeviceConnectionUpdated; winble.deviceManager.connectionWatcher.start(); }
[ "function", "(", ")", "{", "winble", ".", "deviceManager", ".", "connectionWatcher", "=", "Windows", ".", "Devices", ".", "Enumeration", ".", "Pnp", ".", "PnpObject", ".", "createWatcher", "(", "Windows", ".", "Devices", ".", "Enumeration", ".", "Pnp", ".", "PnpObjectType", ".", "deviceContainer", ",", "[", "\"System.Devices.Connected\"", "]", ",", "\"\"", ")", ";", "winble", ".", "deviceManager", ".", "connectionWatcher", ".", "onupdated", "=", "winble", ".", "deviceManager", ".", "onDeviceConnectionUpdated", ";", "winble", ".", "deviceManager", ".", "connectionWatcher", ".", "start", "(", ")", ";", "}" ]
Tell Windows to notify us whenever the connection status of a BLE device changes. It appears that IRL Windows only tells us when a device has been disconnected and not so much when newly connected.
[ "Tell", "Windows", "to", "notify", "us", "whenever", "the", "connection", "status", "of", "a", "BLE", "device", "changes", ".", "It", "appears", "that", "IRL", "Windows", "only", "tells", "us", "when", "a", "device", "has", "been", "disconnected", "and", "not", "so", "much", "when", "newly", "connected", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L648-L655
17,249
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback, deviceHandle) { // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "closeDevice", errorCallback); if (device == null) return; // Remove the device from our list winble.deviceManager.deviceList[deviceHandle] = null; }
javascript
function (successCallback, errorCallback, deviceHandle) { // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "closeDevice", errorCallback); if (device == null) return; // Remove the device from our list winble.deviceManager.deviceList[deviceHandle] = null; }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "deviceHandle", ")", "{", "// Find the requested device in our list of discovered devices", "var", "device", "=", "winble", ".", "deviceManager", ".", "getDeviceFromHandle", "(", "deviceHandle", ",", "\"closeDevice\"", ",", "errorCallback", ")", ";", "if", "(", "device", "==", "null", ")", "return", ";", "// Remove the device from our list", "winble", ".", "deviceManager", ".", "deviceList", "[", "deviceHandle", "]", "=", "null", ";", "}" ]
Called from the close API
[ "Called", "from", "the", "close", "API" ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L679-L688
17,250
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback, deviceHandle) { // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getDeviceRssi", errorCallback); if (device == null) return; // Return the RSSI value winble.logger.logDebug("getDeviceRssi", "Warning: Windows BLE does not currently provide RSSI"); successCallback(device.rssi); }
javascript
function (successCallback, errorCallback, deviceHandle) { // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getDeviceRssi", errorCallback); if (device == null) return; // Return the RSSI value winble.logger.logDebug("getDeviceRssi", "Warning: Windows BLE does not currently provide RSSI"); successCallback(device.rssi); }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "deviceHandle", ")", "{", "// Find the requested device in our list of discovered devices", "var", "device", "=", "winble", ".", "deviceManager", ".", "getDeviceFromHandle", "(", "deviceHandle", ",", "\"getDeviceRssi\"", ",", "errorCallback", ")", ";", "if", "(", "device", "==", "null", ")", "return", ";", "// Return the RSSI value", "winble", ".", "logger", ".", "logDebug", "(", "\"getDeviceRssi\"", ",", "\"Warning: Windows BLE does not currently provide RSSI\"", ")", ";", "successCallback", "(", "device", ".", "rssi", ")", ";", "}" ]
Called from the rssi API. Windows does not give us access to a device's RSSI, but the Evothings API expects it to be available, so we will always return DEFAULT_RSSI here, which is a non-real-world RSSI value.
[ "Called", "from", "the", "rssi", "API", ".", "Windows", "does", "not", "give", "us", "access", "to", "a", "device", "s", "RSSI", "but", "the", "Evothings", "API", "expects", "it", "to", "be", "available", "so", "we", "will", "always", "return", "DEFAULT_RSSI", "here", "which", "is", "a", "non", "-", "real", "-", "world", "RSSI", "value", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L692-L702
17,251
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback, deviceHandle) { // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getDeviceServices", errorCallback); if (device == null) return; // Enumerate the services winble.bleDevice.fromIdAsync(device.gattDevice.id).done( function (bleDevice) { winble.logger.logDebug("getDeviceServices", "BluetoothLEDevice.fromIdAsync completed with success"); // Store the services and return an API-specified list to the caller var serviceListOut = []; for (var i = 0; i < bleDevice.gattServices.length; i++) { // Add service internally to the device so we can retrieve it later by its handle winble.logger.logDebug("getDeviceServices", "Found " + device.gattDevice.name + " service '" + bleDevice.gattServices[i].uuid + "'"); var serviceStore = { "gattService": bleDevice.gattServices[i], "handle": winble.nextGattHandle++ }; device.serviceList[serviceStore.handle] = serviceStore; // Add service to return list var serviceOut = { "handle": serviceStore.handle, "uuid": serviceStore.gattService.uuid, "type": 0 // 0 = Primary, 1 = Secondary (Windows only returns primary services in the ble.gattServices list) }; serviceListOut.push(serviceOut); } // Report the list of services back to the caller successCallback(serviceListOut); }, function (error) { var msg = "BluetoothLEDevice.fromIdAsync('" + device.gattDevice.id + "') failed: " + error; winble.logger.logError("getDeviceServices", msg); errorCallback(msg); }); }
javascript
function (successCallback, errorCallback, deviceHandle) { // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getDeviceServices", errorCallback); if (device == null) return; // Enumerate the services winble.bleDevice.fromIdAsync(device.gattDevice.id).done( function (bleDevice) { winble.logger.logDebug("getDeviceServices", "BluetoothLEDevice.fromIdAsync completed with success"); // Store the services and return an API-specified list to the caller var serviceListOut = []; for (var i = 0; i < bleDevice.gattServices.length; i++) { // Add service internally to the device so we can retrieve it later by its handle winble.logger.logDebug("getDeviceServices", "Found " + device.gattDevice.name + " service '" + bleDevice.gattServices[i].uuid + "'"); var serviceStore = { "gattService": bleDevice.gattServices[i], "handle": winble.nextGattHandle++ }; device.serviceList[serviceStore.handle] = serviceStore; // Add service to return list var serviceOut = { "handle": serviceStore.handle, "uuid": serviceStore.gattService.uuid, "type": 0 // 0 = Primary, 1 = Secondary (Windows only returns primary services in the ble.gattServices list) }; serviceListOut.push(serviceOut); } // Report the list of services back to the caller successCallback(serviceListOut); }, function (error) { var msg = "BluetoothLEDevice.fromIdAsync('" + device.gattDevice.id + "') failed: " + error; winble.logger.logError("getDeviceServices", msg); errorCallback(msg); }); }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "deviceHandle", ")", "{", "// Find the requested device in our list of discovered devices", "var", "device", "=", "winble", ".", "deviceManager", ".", "getDeviceFromHandle", "(", "deviceHandle", ",", "\"getDeviceServices\"", ",", "errorCallback", ")", ";", "if", "(", "device", "==", "null", ")", "return", ";", "// Enumerate the services", "winble", ".", "bleDevice", ".", "fromIdAsync", "(", "device", ".", "gattDevice", ".", "id", ")", ".", "done", "(", "function", "(", "bleDevice", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"getDeviceServices\"", ",", "\"BluetoothLEDevice.fromIdAsync completed with success\"", ")", ";", "// Store the services and return an API-specified list to the caller", "var", "serviceListOut", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "bleDevice", ".", "gattServices", ".", "length", ";", "i", "++", ")", "{", "// Add service internally to the device so we can retrieve it later by its handle", "winble", ".", "logger", ".", "logDebug", "(", "\"getDeviceServices\"", ",", "\"Found \"", "+", "device", ".", "gattDevice", ".", "name", "+", "\" service '\"", "+", "bleDevice", ".", "gattServices", "[", "i", "]", ".", "uuid", "+", "\"'\"", ")", ";", "var", "serviceStore", "=", "{", "\"gattService\"", ":", "bleDevice", ".", "gattServices", "[", "i", "]", ",", "\"handle\"", ":", "winble", ".", "nextGattHandle", "++", "}", ";", "device", ".", "serviceList", "[", "serviceStore", ".", "handle", "]", "=", "serviceStore", ";", "// Add service to return list", "var", "serviceOut", "=", "{", "\"handle\"", ":", "serviceStore", ".", "handle", ",", "\"uuid\"", ":", "serviceStore", ".", "gattService", ".", "uuid", ",", "\"type\"", ":", "0", "// 0 = Primary, 1 = Secondary (Windows only returns primary services in the ble.gattServices list)", "}", ";", "serviceListOut", ".", "push", "(", "serviceOut", ")", ";", "}", "// Report the list of services back to the caller", "successCallback", "(", "serviceListOut", ")", ";", "}", ",", "function", "(", "error", ")", "{", "var", "msg", "=", "\"BluetoothLEDevice.fromIdAsync('\"", "+", "device", ".", "gattDevice", ".", "id", "+", "\"') failed: \"", "+", "error", ";", "winble", ".", "logger", ".", "logError", "(", "\"getDeviceServices\"", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "}", ")", ";", "}" ]
Called from the services API; return a list of all BLE services supported by the specified device.
[ "Called", "from", "the", "services", "API", ";", "return", "a", "list", "of", "all", "BLE", "services", "supported", "by", "the", "specified", "device", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L705-L746
17,252
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback, deviceHandle, serviceHandle) { winble.logger.logDebug("getServiceCharacteristics", "deviceHandle='" + deviceHandle + ", serviceHandle='" + serviceHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getServiceCharacteristics", errorCallback); if (device == null) return; // Find the requested service in the device's list of services var service = winble.deviceManager.getServiceFromHandle(device, serviceHandle, "getServiceCharacteristics", errorCallback); if (service == null) return; // Enumerate the characteristics on this service var charList = service.gattService.getAllCharacteristics(); // Store the characteristics and return an API-specified list to the caller var charListOut = []; for (var i = 0; i < charList.length; i++) { // Add characteristic internally to the device so we can retrieve it later by its handle winble.logger.logDebug("getServiceCharacteristics", "Found " + service.gattService.uuid + " characteristic '" + charList[i].uuid + "'"); var charStore = { "gattChar": charList[i], "handle": winble.nextGattHandle++ }; device.charList[charStore.handle] = charStore; // Add characteristic to return list var charOut = { "handle": charStore.handle, "uuid": charStore.gattChar.uuid, // TODO: Not at all sure if this is right as Microsoft has 1 of 4 values in this field and iOS/Android // TODO: have a bitfield, but see code in winble.deviceManager.permissionsFromProtectionLevel // TODO: as I try to map Microsoft's number to a bitfield. "permissions": winble.deviceManager.permissionsFromProtectionLevel(charStore.gattChar.protectionLevel), "properties": charStore.gattChar.characteristicProperties, // Microsoft's bitfield matches the BLE 4.2 spec "writeType": 3 // So (1+2), where 1: WRITE_TYPE_NO_RESPONSE, 2: WRITE_TYPE_DEFAULT, 4: WRITE_TYPE_SIGNED }; charListOut.push(charOut); } // Report the list of characteristics back to the caller successCallback(charListOut); }
javascript
function (successCallback, errorCallback, deviceHandle, serviceHandle) { winble.logger.logDebug("getServiceCharacteristics", "deviceHandle='" + deviceHandle + ", serviceHandle='" + serviceHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getServiceCharacteristics", errorCallback); if (device == null) return; // Find the requested service in the device's list of services var service = winble.deviceManager.getServiceFromHandle(device, serviceHandle, "getServiceCharacteristics", errorCallback); if (service == null) return; // Enumerate the characteristics on this service var charList = service.gattService.getAllCharacteristics(); // Store the characteristics and return an API-specified list to the caller var charListOut = []; for (var i = 0; i < charList.length; i++) { // Add characteristic internally to the device so we can retrieve it later by its handle winble.logger.logDebug("getServiceCharacteristics", "Found " + service.gattService.uuid + " characteristic '" + charList[i].uuid + "'"); var charStore = { "gattChar": charList[i], "handle": winble.nextGattHandle++ }; device.charList[charStore.handle] = charStore; // Add characteristic to return list var charOut = { "handle": charStore.handle, "uuid": charStore.gattChar.uuid, // TODO: Not at all sure if this is right as Microsoft has 1 of 4 values in this field and iOS/Android // TODO: have a bitfield, but see code in winble.deviceManager.permissionsFromProtectionLevel // TODO: as I try to map Microsoft's number to a bitfield. "permissions": winble.deviceManager.permissionsFromProtectionLevel(charStore.gattChar.protectionLevel), "properties": charStore.gattChar.characteristicProperties, // Microsoft's bitfield matches the BLE 4.2 spec "writeType": 3 // So (1+2), where 1: WRITE_TYPE_NO_RESPONSE, 2: WRITE_TYPE_DEFAULT, 4: WRITE_TYPE_SIGNED }; charListOut.push(charOut); } // Report the list of characteristics back to the caller successCallback(charListOut); }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "deviceHandle", ",", "serviceHandle", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"getServiceCharacteristics\"", ",", "\"deviceHandle='\"", "+", "deviceHandle", "+", "\", serviceHandle='\"", "+", "serviceHandle", "+", "\"'\"", ")", ";", "// Find the requested device in our list of discovered devices", "var", "device", "=", "winble", ".", "deviceManager", ".", "getDeviceFromHandle", "(", "deviceHandle", ",", "\"getServiceCharacteristics\"", ",", "errorCallback", ")", ";", "if", "(", "device", "==", "null", ")", "return", ";", "// Find the requested service in the device's list of services", "var", "service", "=", "winble", ".", "deviceManager", ".", "getServiceFromHandle", "(", "device", ",", "serviceHandle", ",", "\"getServiceCharacteristics\"", ",", "errorCallback", ")", ";", "if", "(", "service", "==", "null", ")", "return", ";", "// Enumerate the characteristics on this service", "var", "charList", "=", "service", ".", "gattService", ".", "getAllCharacteristics", "(", ")", ";", "// Store the characteristics and return an API-specified list to the caller", "var", "charListOut", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "charList", ".", "length", ";", "i", "++", ")", "{", "// Add characteristic internally to the device so we can retrieve it later by its handle", "winble", ".", "logger", ".", "logDebug", "(", "\"getServiceCharacteristics\"", ",", "\"Found \"", "+", "service", ".", "gattService", ".", "uuid", "+", "\" characteristic '\"", "+", "charList", "[", "i", "]", ".", "uuid", "+", "\"'\"", ")", ";", "var", "charStore", "=", "{", "\"gattChar\"", ":", "charList", "[", "i", "]", ",", "\"handle\"", ":", "winble", ".", "nextGattHandle", "++", "}", ";", "device", ".", "charList", "[", "charStore", ".", "handle", "]", "=", "charStore", ";", "// Add characteristic to return list", "var", "charOut", "=", "{", "\"handle\"", ":", "charStore", ".", "handle", ",", "\"uuid\"", ":", "charStore", ".", "gattChar", ".", "uuid", ",", "// TODO: Not at all sure if this is right as Microsoft has 1 of 4 values in this field and iOS/Android", "// TODO: have a bitfield, but see code in winble.deviceManager.permissionsFromProtectionLevel", "// TODO: as I try to map Microsoft's number to a bitfield.", "\"permissions\"", ":", "winble", ".", "deviceManager", ".", "permissionsFromProtectionLevel", "(", "charStore", ".", "gattChar", ".", "protectionLevel", ")", ",", "\"properties\"", ":", "charStore", ".", "gattChar", ".", "characteristicProperties", ",", "// Microsoft's bitfield matches the BLE 4.2 spec", "\"writeType\"", ":", "3", "// So (1+2), where 1: WRITE_TYPE_NO_RESPONSE, 2: WRITE_TYPE_DEFAULT, 4: WRITE_TYPE_SIGNED", "}", ";", "charListOut", ".", "push", "(", "charOut", ")", ";", "}", "// Report the list of characteristics back to the caller", "successCallback", "(", "charListOut", ")", ";", "}" ]
Called from the characteristics API; return a list of all BLE characteristics associated with the specified device+service.
[ "Called", "from", "the", "characteristics", "API", ";", "return", "a", "list", "of", "all", "BLE", "characteristics", "associated", "with", "the", "specified", "device", "+", "service", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L749-L796
17,253
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback, deviceHandle, charHandle) { winble.logger.logDebug("getCharacteristicDescriptors", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getCharacteristicDescriptors", errorCallback); if (device == null) return; // Find the requested characteristic in the device's list of characteristics var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "getCharacteristicDescriptors", errorCallback); if (characteristic == null) return; // Enumerate the descriptors on this characteristic var descList = characteristic.gattChar.getAllDescriptors(); // Store the descriptors and return an API-specified list to the caller var descListOut = []; for (var i = 0; i < descList.length; i++) { // Add descriptor internally to the device so we can retrieve it later by its handle winble.logger.logDebug("getCharacteristicDescriptors", "Found " + characteristic.gattChar.uuid + " descriptor '" + descList[i].uuid + "'"); var descStore = { "gattDesc": descList[i], "handle": winble.nextGattHandle++ }; device.descList[descStore.handle] = descStore; // Add characteristic to return list var charOut = { "handle": descStore.handle, "uuid": descStore.gattDesc.uuid, // TODO: Not at all sure if this is right as Microsoft has 1 of 4 values in this field and iOS/Android // TODO: have a bitfield, but see code in winble.deviceManager.permissionsFromProtectionLevel // TODO: as I try to map Microsoft's number to a bitfield. "permissions": winble.deviceManager.permissionsFromProtectionLevel(descStore.gattDesc.protectionLevel) }; descListOut.push(charOut); } // Report the list of descriptors back to the caller successCallback(descListOut); }
javascript
function (successCallback, errorCallback, deviceHandle, charHandle) { winble.logger.logDebug("getCharacteristicDescriptors", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getCharacteristicDescriptors", errorCallback); if (device == null) return; // Find the requested characteristic in the device's list of characteristics var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "getCharacteristicDescriptors", errorCallback); if (characteristic == null) return; // Enumerate the descriptors on this characteristic var descList = characteristic.gattChar.getAllDescriptors(); // Store the descriptors and return an API-specified list to the caller var descListOut = []; for (var i = 0; i < descList.length; i++) { // Add descriptor internally to the device so we can retrieve it later by its handle winble.logger.logDebug("getCharacteristicDescriptors", "Found " + characteristic.gattChar.uuid + " descriptor '" + descList[i].uuid + "'"); var descStore = { "gattDesc": descList[i], "handle": winble.nextGattHandle++ }; device.descList[descStore.handle] = descStore; // Add characteristic to return list var charOut = { "handle": descStore.handle, "uuid": descStore.gattDesc.uuid, // TODO: Not at all sure if this is right as Microsoft has 1 of 4 values in this field and iOS/Android // TODO: have a bitfield, but see code in winble.deviceManager.permissionsFromProtectionLevel // TODO: as I try to map Microsoft's number to a bitfield. "permissions": winble.deviceManager.permissionsFromProtectionLevel(descStore.gattDesc.protectionLevel) }; descListOut.push(charOut); } // Report the list of descriptors back to the caller successCallback(descListOut); }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "deviceHandle", ",", "charHandle", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"getCharacteristicDescriptors\"", ",", "\"deviceHandle='\"", "+", "deviceHandle", "+", "\", charHandle='\"", "+", "charHandle", "+", "\"'\"", ")", ";", "// Find the requested device in our list of discovered devices", "var", "device", "=", "winble", ".", "deviceManager", ".", "getDeviceFromHandle", "(", "deviceHandle", ",", "\"getCharacteristicDescriptors\"", ",", "errorCallback", ")", ";", "if", "(", "device", "==", "null", ")", "return", ";", "// Find the requested characteristic in the device's list of characteristics", "var", "characteristic", "=", "winble", ".", "deviceManager", ".", "getCharacteristicFromHandle", "(", "device", ",", "charHandle", ",", "\"getCharacteristicDescriptors\"", ",", "errorCallback", ")", ";", "if", "(", "characteristic", "==", "null", ")", "return", ";", "// Enumerate the descriptors on this characteristic", "var", "descList", "=", "characteristic", ".", "gattChar", ".", "getAllDescriptors", "(", ")", ";", "// Store the descriptors and return an API-specified list to the caller", "var", "descListOut", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "descList", ".", "length", ";", "i", "++", ")", "{", "// Add descriptor internally to the device so we can retrieve it later by its handle", "winble", ".", "logger", ".", "logDebug", "(", "\"getCharacteristicDescriptors\"", ",", "\"Found \"", "+", "characteristic", ".", "gattChar", ".", "uuid", "+", "\" descriptor '\"", "+", "descList", "[", "i", "]", ".", "uuid", "+", "\"'\"", ")", ";", "var", "descStore", "=", "{", "\"gattDesc\"", ":", "descList", "[", "i", "]", ",", "\"handle\"", ":", "winble", ".", "nextGattHandle", "++", "}", ";", "device", ".", "descList", "[", "descStore", ".", "handle", "]", "=", "descStore", ";", "// Add characteristic to return list", "var", "charOut", "=", "{", "\"handle\"", ":", "descStore", ".", "handle", ",", "\"uuid\"", ":", "descStore", ".", "gattDesc", ".", "uuid", ",", "// TODO: Not at all sure if this is right as Microsoft has 1 of 4 values in this field and iOS/Android", "// TODO: have a bitfield, but see code in winble.deviceManager.permissionsFromProtectionLevel", "// TODO: as I try to map Microsoft's number to a bitfield.", "\"permissions\"", ":", "winble", ".", "deviceManager", ".", "permissionsFromProtectionLevel", "(", "descStore", ".", "gattDesc", ".", "protectionLevel", ")", "}", ";", "descListOut", ".", "push", "(", "charOut", ")", ";", "}", "// Report the list of descriptors back to the caller", "successCallback", "(", "descListOut", ")", ";", "}" ]
Called from the descriptors API; return a list of all BLE descriptors associated with the specified device+characteristic.
[ "Called", "from", "the", "descriptors", "API", ";", "return", "a", "list", "of", "all", "BLE", "descriptors", "associated", "with", "the", "specified", "device", "+", "characteristic", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L833-L877
17,254
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback, deviceHandle, charHandle) { winble.logger.logDebug("readCharacteristic", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "readCharacteristic", errorCallback); if (device == null) return; // Find the requested characteristic in the device's list of characteristics var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "readCharacteristic", errorCallback); if (characteristic == null) return; // Read and return the data // https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattcharacteristic.readvalueasync.aspx //characteristic.gattChar.readValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.uncached).done( characteristic.gattChar.readValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.cached).done( function (readResult) { if (readResult.status == winble.gatt.GattCommunicationStatus.success) { var dataOut = new Uint8Array(readResult.value.length); var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(readResult.value); dataReader.readBytes(dataOut); winble.logger.logDebug("readCharacteristic", "gattChar.readValueAsync completed with success, returning '" + dataOut + "'"); successCallback(dataOut); } else { winble.logger.logDebug("readCharacteristic", "gattChar.readValueAsync completed with error"); var msg = "Read failed or device unreachable, GattCommunicationStatus = " + readResult.status; winble.logger.logError("readCharacteristic", msg); errorCallback(msg); } }, function (error) { var msg = "gattChar.readValueAsync() failed: " + error; winble.logger.logError("readCharacteristic", msg); errorCallback(msg); }); }
javascript
function (successCallback, errorCallback, deviceHandle, charHandle) { winble.logger.logDebug("readCharacteristic", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "readCharacteristic", errorCallback); if (device == null) return; // Find the requested characteristic in the device's list of characteristics var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "readCharacteristic", errorCallback); if (characteristic == null) return; // Read and return the data // https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattcharacteristic.readvalueasync.aspx //characteristic.gattChar.readValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.uncached).done( characteristic.gattChar.readValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.cached).done( function (readResult) { if (readResult.status == winble.gatt.GattCommunicationStatus.success) { var dataOut = new Uint8Array(readResult.value.length); var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(readResult.value); dataReader.readBytes(dataOut); winble.logger.logDebug("readCharacteristic", "gattChar.readValueAsync completed with success, returning '" + dataOut + "'"); successCallback(dataOut); } else { winble.logger.logDebug("readCharacteristic", "gattChar.readValueAsync completed with error"); var msg = "Read failed or device unreachable, GattCommunicationStatus = " + readResult.status; winble.logger.logError("readCharacteristic", msg); errorCallback(msg); } }, function (error) { var msg = "gattChar.readValueAsync() failed: " + error; winble.logger.logError("readCharacteristic", msg); errorCallback(msg); }); }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "deviceHandle", ",", "charHandle", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"readCharacteristic\"", ",", "\"deviceHandle='\"", "+", "deviceHandle", "+", "\", charHandle='\"", "+", "charHandle", "+", "\"'\"", ")", ";", "// Find the requested device in our list of discovered devices", "var", "device", "=", "winble", ".", "deviceManager", ".", "getDeviceFromHandle", "(", "deviceHandle", ",", "\"readCharacteristic\"", ",", "errorCallback", ")", ";", "if", "(", "device", "==", "null", ")", "return", ";", "// Find the requested characteristic in the device's list of characteristics", "var", "characteristic", "=", "winble", ".", "deviceManager", ".", "getCharacteristicFromHandle", "(", "device", ",", "charHandle", ",", "\"readCharacteristic\"", ",", "errorCallback", ")", ";", "if", "(", "characteristic", "==", "null", ")", "return", ";", "// Read and return the data", "// https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattcharacteristic.readvalueasync.aspx", "//characteristic.gattChar.readValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.uncached).done(", "characteristic", ".", "gattChar", ".", "readValueAsync", "(", "Windows", ".", "Devices", ".", "Bluetooth", ".", "BluetoothCacheMode", ".", "cached", ")", ".", "done", "(", "function", "(", "readResult", ")", "{", "if", "(", "readResult", ".", "status", "==", "winble", ".", "gatt", ".", "GattCommunicationStatus", ".", "success", ")", "{", "var", "dataOut", "=", "new", "Uint8Array", "(", "readResult", ".", "value", ".", "length", ")", ";", "var", "dataReader", "=", "Windows", ".", "Storage", ".", "Streams", ".", "DataReader", ".", "fromBuffer", "(", "readResult", ".", "value", ")", ";", "dataReader", ".", "readBytes", "(", "dataOut", ")", ";", "winble", ".", "logger", ".", "logDebug", "(", "\"readCharacteristic\"", ",", "\"gattChar.readValueAsync completed with success, returning '\"", "+", "dataOut", "+", "\"'\"", ")", ";", "successCallback", "(", "dataOut", ")", ";", "}", "else", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"readCharacteristic\"", ",", "\"gattChar.readValueAsync completed with error\"", ")", ";", "var", "msg", "=", "\"Read failed or device unreachable, GattCommunicationStatus = \"", "+", "readResult", ".", "status", ";", "winble", ".", "logger", ".", "logError", "(", "\"readCharacteristic\"", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "}", "}", ",", "function", "(", "error", ")", "{", "var", "msg", "=", "\"gattChar.readValueAsync() failed: \"", "+", "error", ";", "winble", ".", "logger", ".", "logError", "(", "\"readCharacteristic\"", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "}", ")", ";", "}" ]
Called from the readCharacteristic API; return the specified characteristic.
[ "Called", "from", "the", "readCharacteristic", "API", ";", "return", "the", "specified", "characteristic", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L880-L917
17,255
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback, deviceHandle, charHandle, dataBuffer) { winble.logger.logDebug("writeCharacteristic", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "writeCharacteristic", errorCallback); if (device == null) return; // Find the requested characteristic in the device's list of characteristics var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "writeCharacteristic", errorCallback); if (characteristic == null) return; // Write the data. The incoming buffer is and ArrayBuffer, and the writeValueAsync() function takes an iBuffer as its // parameter, so we need to do some conversion here. // https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.cryptographicbuffer.createfrombytearray // https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattcharacteristic.readvalueasync.aspx var data = new Uint8Array(dataBuffer); var dataOut = Windows.Security.Cryptography.CryptographicBuffer.createFromByteArray(data); var writeOption; if (characteristic.gattChar.characteristicProperties & winble.gatt.GattCharacteristicProperties.writeWithoutResponse) writeOption = winble.gatt.GattWriteOption.writeWithoutResponse; else writeOption = winble.gatt.GattWriteOption.writeWithResponse; characteristic.gattChar.writeValueAsync(dataOut, writeOption).done( function (commStatus) { if (commStatus == winble.gatt.GattCommunicationStatus.success) { winble.logger.logDebug("writeCharacteristic", "gattChar.writeValueAsync completed with success"); successCallback(); } else { winble.logger.logDebug("writeCharacteristic", "gattChar.writeValueAsync completed with error"); var msg = "Write failed or device unreachable, GattCommunicationStatus = " + commStatus; winble.logger.logError("writeCharacteristic", msg); errorCallback(msg); } }, function (error) { var msg = "gattChar.writeValueAsync() failed: " + error; winble.logger.logError("writeCharacteristic", msg); errorCallback(msg); }); }
javascript
function (successCallback, errorCallback, deviceHandle, charHandle, dataBuffer) { winble.logger.logDebug("writeCharacteristic", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "writeCharacteristic", errorCallback); if (device == null) return; // Find the requested characteristic in the device's list of characteristics var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "writeCharacteristic", errorCallback); if (characteristic == null) return; // Write the data. The incoming buffer is and ArrayBuffer, and the writeValueAsync() function takes an iBuffer as its // parameter, so we need to do some conversion here. // https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.cryptographicbuffer.createfrombytearray // https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattcharacteristic.readvalueasync.aspx var data = new Uint8Array(dataBuffer); var dataOut = Windows.Security.Cryptography.CryptographicBuffer.createFromByteArray(data); var writeOption; if (characteristic.gattChar.characteristicProperties & winble.gatt.GattCharacteristicProperties.writeWithoutResponse) writeOption = winble.gatt.GattWriteOption.writeWithoutResponse; else writeOption = winble.gatt.GattWriteOption.writeWithResponse; characteristic.gattChar.writeValueAsync(dataOut, writeOption).done( function (commStatus) { if (commStatus == winble.gatt.GattCommunicationStatus.success) { winble.logger.logDebug("writeCharacteristic", "gattChar.writeValueAsync completed with success"); successCallback(); } else { winble.logger.logDebug("writeCharacteristic", "gattChar.writeValueAsync completed with error"); var msg = "Write failed or device unreachable, GattCommunicationStatus = " + commStatus; winble.logger.logError("writeCharacteristic", msg); errorCallback(msg); } }, function (error) { var msg = "gattChar.writeValueAsync() failed: " + error; winble.logger.logError("writeCharacteristic", msg); errorCallback(msg); }); }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "deviceHandle", ",", "charHandle", ",", "dataBuffer", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"writeCharacteristic\"", ",", "\"deviceHandle='\"", "+", "deviceHandle", "+", "\", charHandle='\"", "+", "charHandle", "+", "\"'\"", ")", ";", "// Find the requested device in our list of discovered devices", "var", "device", "=", "winble", ".", "deviceManager", ".", "getDeviceFromHandle", "(", "deviceHandle", ",", "\"writeCharacteristic\"", ",", "errorCallback", ")", ";", "if", "(", "device", "==", "null", ")", "return", ";", "// Find the requested characteristic in the device's list of characteristics", "var", "characteristic", "=", "winble", ".", "deviceManager", ".", "getCharacteristicFromHandle", "(", "device", ",", "charHandle", ",", "\"writeCharacteristic\"", ",", "errorCallback", ")", ";", "if", "(", "characteristic", "==", "null", ")", "return", ";", "// Write the data. The incoming buffer is and ArrayBuffer, and the writeValueAsync() function takes an iBuffer as its", "// parameter, so we need to do some conversion here.", "// https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.cryptographicbuffer.createfrombytearray", "// https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattcharacteristic.readvalueasync.aspx", "var", "data", "=", "new", "Uint8Array", "(", "dataBuffer", ")", ";", "var", "dataOut", "=", "Windows", ".", "Security", ".", "Cryptography", ".", "CryptographicBuffer", ".", "createFromByteArray", "(", "data", ")", ";", "var", "writeOption", ";", "if", "(", "characteristic", ".", "gattChar", ".", "characteristicProperties", "&", "winble", ".", "gatt", ".", "GattCharacteristicProperties", ".", "writeWithoutResponse", ")", "writeOption", "=", "winble", ".", "gatt", ".", "GattWriteOption", ".", "writeWithoutResponse", ";", "else", "writeOption", "=", "winble", ".", "gatt", ".", "GattWriteOption", ".", "writeWithResponse", ";", "characteristic", ".", "gattChar", ".", "writeValueAsync", "(", "dataOut", ",", "writeOption", ")", ".", "done", "(", "function", "(", "commStatus", ")", "{", "if", "(", "commStatus", "==", "winble", ".", "gatt", ".", "GattCommunicationStatus", ".", "success", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"writeCharacteristic\"", ",", "\"gattChar.writeValueAsync completed with success\"", ")", ";", "successCallback", "(", ")", ";", "}", "else", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"writeCharacteristic\"", ",", "\"gattChar.writeValueAsync completed with error\"", ")", ";", "var", "msg", "=", "\"Write failed or device unreachable, GattCommunicationStatus = \"", "+", "commStatus", ";", "winble", ".", "logger", ".", "logError", "(", "\"writeCharacteristic\"", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "}", "}", ",", "function", "(", "error", ")", "{", "var", "msg", "=", "\"gattChar.writeValueAsync() failed: \"", "+", "error", ";", "winble", ".", "logger", ".", "logError", "(", "\"writeCharacteristic\"", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "}", ")", ";", "}" ]
Called from the writeCharacteristic API; write the data to the specified characteristic.
[ "Called", "from", "the", "writeCharacteristic", "API", ";", "write", "the", "data", "to", "the", "specified", "characteristic", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L960-L1002
17,256
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback, deviceHandle, descHandle, dataBuffer) { winble.logger.logDebug("writeDescriptor", "deviceHandle='" + deviceHandle + ", descHandle='" + descHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "writeDescriptor", errorCallback); if (device == null) return; // Find the requested descriptor in the device's list of descriptors var descriptor = winble.deviceManager.getDescriptorFromHandle(device, descHandle, "writeDescriptor", errorCallback); if (descriptor == null) return; // Write the data. The incoming buffer is and ArrayBuffer, and the writeValueAsync() function takes an iBuffer as its // parameter, so we need to do some conversion here. // https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.cryptographicbuffer.createfrombytearray // https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattdescriptor.writevalueasync.aspx var data = new Uint8Array(dataBuffer); var dataOut = Windows.Security.Cryptography.CryptographicBuffer.createFromByteArray(data); descriptor.gattDesc.writeValueAsync(dataOut).done( function (commStatus) { if (commStatus == winble.gatt.GattCommunicationStatus.success) { winble.logger.logDebug("writeDescriptor", "gattDesc.writeValueAsync completed with success"); successCallback(); } else { winble.logger.logDebug("writeDescriptor", "gattDesc.writeValueAsync completed with error"); var msg = "Write failed or device unreachable, GattCommunicationStatus = " + commStatus; winble.logger.logError("writeDescriptor", msg); errorCallback(msg); } }, function (error) { var msg = "gattDesc.writeValueAsync() failed: " + error; winble.logger.logError("writeDescriptor", msg); errorCallback(msg); }); }
javascript
function (successCallback, errorCallback, deviceHandle, descHandle, dataBuffer) { winble.logger.logDebug("writeDescriptor", "deviceHandle='" + deviceHandle + ", descHandle='" + descHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "writeDescriptor", errorCallback); if (device == null) return; // Find the requested descriptor in the device's list of descriptors var descriptor = winble.deviceManager.getDescriptorFromHandle(device, descHandle, "writeDescriptor", errorCallback); if (descriptor == null) return; // Write the data. The incoming buffer is and ArrayBuffer, and the writeValueAsync() function takes an iBuffer as its // parameter, so we need to do some conversion here. // https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.cryptographicbuffer.createfrombytearray // https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattdescriptor.writevalueasync.aspx var data = new Uint8Array(dataBuffer); var dataOut = Windows.Security.Cryptography.CryptographicBuffer.createFromByteArray(data); descriptor.gattDesc.writeValueAsync(dataOut).done( function (commStatus) { if (commStatus == winble.gatt.GattCommunicationStatus.success) { winble.logger.logDebug("writeDescriptor", "gattDesc.writeValueAsync completed with success"); successCallback(); } else { winble.logger.logDebug("writeDescriptor", "gattDesc.writeValueAsync completed with error"); var msg = "Write failed or device unreachable, GattCommunicationStatus = " + commStatus; winble.logger.logError("writeDescriptor", msg); errorCallback(msg); } }, function (error) { var msg = "gattDesc.writeValueAsync() failed: " + error; winble.logger.logError("writeDescriptor", msg); errorCallback(msg); }); }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "deviceHandle", ",", "descHandle", ",", "dataBuffer", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"writeDescriptor\"", ",", "\"deviceHandle='\"", "+", "deviceHandle", "+", "\", descHandle='\"", "+", "descHandle", "+", "\"'\"", ")", ";", "// Find the requested device in our list of discovered devices", "var", "device", "=", "winble", ".", "deviceManager", ".", "getDeviceFromHandle", "(", "deviceHandle", ",", "\"writeDescriptor\"", ",", "errorCallback", ")", ";", "if", "(", "device", "==", "null", ")", "return", ";", "// Find the requested descriptor in the device's list of descriptors", "var", "descriptor", "=", "winble", ".", "deviceManager", ".", "getDescriptorFromHandle", "(", "device", ",", "descHandle", ",", "\"writeDescriptor\"", ",", "errorCallback", ")", ";", "if", "(", "descriptor", "==", "null", ")", "return", ";", "// Write the data. The incoming buffer is and ArrayBuffer, and the writeValueAsync() function takes an iBuffer as its", "// parameter, so we need to do some conversion here.", "// https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.cryptographicbuffer.createfrombytearray", "// https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattdescriptor.writevalueasync.aspx", "var", "data", "=", "new", "Uint8Array", "(", "dataBuffer", ")", ";", "var", "dataOut", "=", "Windows", ".", "Security", ".", "Cryptography", ".", "CryptographicBuffer", ".", "createFromByteArray", "(", "data", ")", ";", "descriptor", ".", "gattDesc", ".", "writeValueAsync", "(", "dataOut", ")", ".", "done", "(", "function", "(", "commStatus", ")", "{", "if", "(", "commStatus", "==", "winble", ".", "gatt", ".", "GattCommunicationStatus", ".", "success", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"writeDescriptor\"", ",", "\"gattDesc.writeValueAsync completed with success\"", ")", ";", "successCallback", "(", ")", ";", "}", "else", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"writeDescriptor\"", ",", "\"gattDesc.writeValueAsync completed with error\"", ")", ";", "var", "msg", "=", "\"Write failed or device unreachable, GattCommunicationStatus = \"", "+", "commStatus", ";", "winble", ".", "logger", ".", "logError", "(", "\"writeDescriptor\"", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "}", "}", ",", "function", "(", "error", ")", "{", "var", "msg", "=", "\"gattDesc.writeValueAsync() failed: \"", "+", "error", ";", "winble", ".", "logger", ".", "logError", "(", "\"writeDescriptor\"", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "}", ")", ";", "}" ]
Called from the writeDescriptor API; write the data to the specified descriptor.
[ "Called", "from", "the", "writeDescriptor", "API", ";", "write", "the", "data", "to", "the", "specified", "descriptor", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L1005-L1042
17,257
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback, deviceHandle, charHandle) { winble.logger.logDebug("enableCharacteristicNotification", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "enableCharacteristicNotification", errorCallback); if (device == null) return; // Find the requested characteristic in the device's list of characteristics var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "enableCharacteristicNotification", errorCallback); if (characteristic == null) return; // Make sure this characteristic supports sending of notifications, notify caller if not. if (!(characteristic.gattChar.characteristicProperties & winble.gatt.GattCharacteristicProperties.notify)) { var msg = "This characteristic does not support notifications"; winble.logger.logDebug("enableCharacteristicNotification", msg); errorCallback(msg); return; } // Create callback to handle notifications; here we will get the new value into a UTF8 buffer and send it to the caller characteristic.onValueChanged = function (args) { winble.logger.logDebug("enableCharacteristicNotification", "** Windows called our callback! **"); var data = Uint8Array(args.characteristicValue.length); Windows.Storage.Streams.DataReader.fromBuffer(args.characteristicValue).readBytes(data); successCallback(data, { keepCallback: true }); }; // Register the callback try { characteristic.gattChar.addEventListener("valuechanged", characteristic.onValueChanged, false); } catch (e) { var msg = "Could not add event listener:" + e; winble.logger.logError("enableCharacteristicNotification", msg); errorCallback(msg); return; } // Tell the characteristic to start sending us notifications. // In order to avoid unnecessary communication with the device, first determine if the device is already // correctly configured to send notifications. By default ReadClientCharacteristicConfigurationDescriptorAsync // will attempt to get the current value from the system cache, so physical communication with the device // is not typically required. characteristic.gattChar.readClientCharacteristicConfigurationDescriptorAsync().then( function (currentDescriptorValue) { // No need to configure characteristic to send notifications if it's already configured if ((currentDescriptorValue.status !== winble.gatt.GattCommunicationStatus.success) || (currentDescriptorValue.clientCharacteristicConfigurationDescriptor !== winble.gatt.GattClientCharacteristicConfigurationDescriptorValue.notify)) { // Set the Client Characteristic Configuration Descriptor to enable the device to send // notifications when the Characteristic value changes. winble.logger.logDebug("enableCharacteristicNotification", "Configuring characteristic for notifications"); characteristic.gattChar.writeClientCharacteristicConfigurationDescriptorAsync( winble.gatt.GattClientCharacteristicConfigurationDescriptorValue.notify).then( function (commStatus) { if (commStatus == winble.gatt.GattCommunicationStatus.success) { winble.logger.logDebug("enableCharacteristicNotification", "gattChar.writeClientCharacteristicConfigurationDescriptorAsync completed with success"); } else { var msg = "Could not configure characteristic for notifications, device unreachable. GattCommunicationStatus = " + commStatus; winble.logger.logError("enableCharacteristicNotification", "enableCharacteristicNotification", msg); errorCallback(msg); } }); } else { winble.logger.logDebug("enableCharacteristicNotification", "Characteristic is already configured for notifications"); } }); }
javascript
function (successCallback, errorCallback, deviceHandle, charHandle) { winble.logger.logDebug("enableCharacteristicNotification", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "enableCharacteristicNotification", errorCallback); if (device == null) return; // Find the requested characteristic in the device's list of characteristics var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "enableCharacteristicNotification", errorCallback); if (characteristic == null) return; // Make sure this characteristic supports sending of notifications, notify caller if not. if (!(characteristic.gattChar.characteristicProperties & winble.gatt.GattCharacteristicProperties.notify)) { var msg = "This characteristic does not support notifications"; winble.logger.logDebug("enableCharacteristicNotification", msg); errorCallback(msg); return; } // Create callback to handle notifications; here we will get the new value into a UTF8 buffer and send it to the caller characteristic.onValueChanged = function (args) { winble.logger.logDebug("enableCharacteristicNotification", "** Windows called our callback! **"); var data = Uint8Array(args.characteristicValue.length); Windows.Storage.Streams.DataReader.fromBuffer(args.characteristicValue).readBytes(data); successCallback(data, { keepCallback: true }); }; // Register the callback try { characteristic.gattChar.addEventListener("valuechanged", characteristic.onValueChanged, false); } catch (e) { var msg = "Could not add event listener:" + e; winble.logger.logError("enableCharacteristicNotification", msg); errorCallback(msg); return; } // Tell the characteristic to start sending us notifications. // In order to avoid unnecessary communication with the device, first determine if the device is already // correctly configured to send notifications. By default ReadClientCharacteristicConfigurationDescriptorAsync // will attempt to get the current value from the system cache, so physical communication with the device // is not typically required. characteristic.gattChar.readClientCharacteristicConfigurationDescriptorAsync().then( function (currentDescriptorValue) { // No need to configure characteristic to send notifications if it's already configured if ((currentDescriptorValue.status !== winble.gatt.GattCommunicationStatus.success) || (currentDescriptorValue.clientCharacteristicConfigurationDescriptor !== winble.gatt.GattClientCharacteristicConfigurationDescriptorValue.notify)) { // Set the Client Characteristic Configuration Descriptor to enable the device to send // notifications when the Characteristic value changes. winble.logger.logDebug("enableCharacteristicNotification", "Configuring characteristic for notifications"); characteristic.gattChar.writeClientCharacteristicConfigurationDescriptorAsync( winble.gatt.GattClientCharacteristicConfigurationDescriptorValue.notify).then( function (commStatus) { if (commStatus == winble.gatt.GattCommunicationStatus.success) { winble.logger.logDebug("enableCharacteristicNotification", "gattChar.writeClientCharacteristicConfigurationDescriptorAsync completed with success"); } else { var msg = "Could not configure characteristic for notifications, device unreachable. GattCommunicationStatus = " + commStatus; winble.logger.logError("enableCharacteristicNotification", "enableCharacteristicNotification", msg); errorCallback(msg); } }); } else { winble.logger.logDebug("enableCharacteristicNotification", "Characteristic is already configured for notifications"); } }); }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "deviceHandle", ",", "charHandle", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"enableCharacteristicNotification\"", ",", "\"deviceHandle='\"", "+", "deviceHandle", "+", "\", charHandle='\"", "+", "charHandle", "+", "\"'\"", ")", ";", "// Find the requested device in our list of discovered devices", "var", "device", "=", "winble", ".", "deviceManager", ".", "getDeviceFromHandle", "(", "deviceHandle", ",", "\"enableCharacteristicNotification\"", ",", "errorCallback", ")", ";", "if", "(", "device", "==", "null", ")", "return", ";", "// Find the requested characteristic in the device's list of characteristics", "var", "characteristic", "=", "winble", ".", "deviceManager", ".", "getCharacteristicFromHandle", "(", "device", ",", "charHandle", ",", "\"enableCharacteristicNotification\"", ",", "errorCallback", ")", ";", "if", "(", "characteristic", "==", "null", ")", "return", ";", "// Make sure this characteristic supports sending of notifications, notify caller if not.", "if", "(", "!", "(", "characteristic", ".", "gattChar", ".", "characteristicProperties", "&", "winble", ".", "gatt", ".", "GattCharacteristicProperties", ".", "notify", ")", ")", "{", "var", "msg", "=", "\"This characteristic does not support notifications\"", ";", "winble", ".", "logger", ".", "logDebug", "(", "\"enableCharacteristicNotification\"", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "return", ";", "}", "// Create callback to handle notifications; here we will get the new value into a UTF8 buffer and send it to the caller", "characteristic", ".", "onValueChanged", "=", "function", "(", "args", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"enableCharacteristicNotification\"", ",", "\"** Windows called our callback! **\"", ")", ";", "var", "data", "=", "Uint8Array", "(", "args", ".", "characteristicValue", ".", "length", ")", ";", "Windows", ".", "Storage", ".", "Streams", ".", "DataReader", ".", "fromBuffer", "(", "args", ".", "characteristicValue", ")", ".", "readBytes", "(", "data", ")", ";", "successCallback", "(", "data", ",", "{", "keepCallback", ":", "true", "}", ")", ";", "}", ";", "// Register the callback", "try", "{", "characteristic", ".", "gattChar", ".", "addEventListener", "(", "\"valuechanged\"", ",", "characteristic", ".", "onValueChanged", ",", "false", ")", ";", "}", "catch", "(", "e", ")", "{", "var", "msg", "=", "\"Could not add event listener:\"", "+", "e", ";", "winble", ".", "logger", ".", "logError", "(", "\"enableCharacteristicNotification\"", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "return", ";", "}", "// Tell the characteristic to start sending us notifications.", "// In order to avoid unnecessary communication with the device, first determine if the device is already", "// correctly configured to send notifications. By default ReadClientCharacteristicConfigurationDescriptorAsync", "// will attempt to get the current value from the system cache, so physical communication with the device", "// is not typically required.", "characteristic", ".", "gattChar", ".", "readClientCharacteristicConfigurationDescriptorAsync", "(", ")", ".", "then", "(", "function", "(", "currentDescriptorValue", ")", "{", "// No need to configure characteristic to send notifications if it's already configured", "if", "(", "(", "currentDescriptorValue", ".", "status", "!==", "winble", ".", "gatt", ".", "GattCommunicationStatus", ".", "success", ")", "||", "(", "currentDescriptorValue", ".", "clientCharacteristicConfigurationDescriptor", "!==", "winble", ".", "gatt", ".", "GattClientCharacteristicConfigurationDescriptorValue", ".", "notify", ")", ")", "{", "// Set the Client Characteristic Configuration Descriptor to enable the device to send", "// notifications when the Characteristic value changes.", "winble", ".", "logger", ".", "logDebug", "(", "\"enableCharacteristicNotification\"", ",", "\"Configuring characteristic for notifications\"", ")", ";", "characteristic", ".", "gattChar", ".", "writeClientCharacteristicConfigurationDescriptorAsync", "(", "winble", ".", "gatt", ".", "GattClientCharacteristicConfigurationDescriptorValue", ".", "notify", ")", ".", "then", "(", "function", "(", "commStatus", ")", "{", "if", "(", "commStatus", "==", "winble", ".", "gatt", ".", "GattCommunicationStatus", ".", "success", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"enableCharacteristicNotification\"", ",", "\"gattChar.writeClientCharacteristicConfigurationDescriptorAsync completed with success\"", ")", ";", "}", "else", "{", "var", "msg", "=", "\"Could not configure characteristic for notifications, device unreachable. GattCommunicationStatus = \"", "+", "commStatus", ";", "winble", ".", "logger", ".", "logError", "(", "\"enableCharacteristicNotification\"", ",", "\"enableCharacteristicNotification\"", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "}", "}", ")", ";", "}", "else", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"enableCharacteristicNotification\"", ",", "\"Characteristic is already configured for notifications\"", ")", ";", "}", "}", ")", ";", "}" ]
Called from the enableCharacteristicNotification API; set things up such that the caller's callback function is invoked whenever the value of the specified characteristic changes.
[ "Called", "from", "the", "enableCharacteristicNotification", "API", ";", "set", "things", "up", "such", "that", "the", "caller", "s", "callback", "function", "is", "invoked", "whenever", "the", "value", "of", "the", "specified", "characteristic", "changes", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L1046-L1117
17,258
evothings/cordova-ble
src/windows/bleProxy.js
function (successCallback, errorCallback, deviceHandle, charHandle) { winble.logger.logDebug("disableCharacteristicNotification", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "disableCharacteristicNotification", errorCallback); if (device == null) return; // Find the requested characteristic in the device's list of characteristics var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "disableCharacteristicNotification", errorCallback); if (characteristic == null) return; // Unregister the callback try { characteristic.gattChar.removeEventListener("valuechanged", characteristic.onValueChanged, false); } catch (e) { var msg = "Could not remove event listener:" + e; winble.logger.logError("disableCharacteristicNotification", msg); errorCallback(msg); return; } }
javascript
function (successCallback, errorCallback, deviceHandle, charHandle) { winble.logger.logDebug("disableCharacteristicNotification", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'"); // Find the requested device in our list of discovered devices var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "disableCharacteristicNotification", errorCallback); if (device == null) return; // Find the requested characteristic in the device's list of characteristics var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "disableCharacteristicNotification", errorCallback); if (characteristic == null) return; // Unregister the callback try { characteristic.gattChar.removeEventListener("valuechanged", characteristic.onValueChanged, false); } catch (e) { var msg = "Could not remove event listener:" + e; winble.logger.logError("disableCharacteristicNotification", msg); errorCallback(msg); return; } }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "deviceHandle", ",", "charHandle", ")", "{", "winble", ".", "logger", ".", "logDebug", "(", "\"disableCharacteristicNotification\"", ",", "\"deviceHandle='\"", "+", "deviceHandle", "+", "\", charHandle='\"", "+", "charHandle", "+", "\"'\"", ")", ";", "// Find the requested device in our list of discovered devices", "var", "device", "=", "winble", ".", "deviceManager", ".", "getDeviceFromHandle", "(", "deviceHandle", ",", "\"disableCharacteristicNotification\"", ",", "errorCallback", ")", ";", "if", "(", "device", "==", "null", ")", "return", ";", "// Find the requested characteristic in the device's list of characteristics", "var", "characteristic", "=", "winble", ".", "deviceManager", ".", "getCharacteristicFromHandle", "(", "device", ",", "charHandle", ",", "\"disableCharacteristicNotification\"", ",", "errorCallback", ")", ";", "if", "(", "characteristic", "==", "null", ")", "return", ";", "// Unregister the callback", "try", "{", "characteristic", ".", "gattChar", ".", "removeEventListener", "(", "\"valuechanged\"", ",", "characteristic", ".", "onValueChanged", ",", "false", ")", ";", "}", "catch", "(", "e", ")", "{", "var", "msg", "=", "\"Could not remove event listener:\"", "+", "e", ";", "winble", ".", "logger", ".", "logError", "(", "\"disableCharacteristicNotification\"", ",", "msg", ")", ";", "errorCallback", "(", "msg", ")", ";", "return", ";", "}", "}" ]
Called from the disableCharacteristicNotification API; stop calling the caller's callback function when the value of the specified characteristic changes.
[ "Called", "from", "the", "disableCharacteristicNotification", "API", ";", "stop", "calling", "the", "caller", "s", "callback", "function", "when", "the", "value", "of", "the", "specified", "characteristic", "changes", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/src/windows/bleProxy.js#L1121-L1144
17,259
evothings/cordova-ble
examples/deprecated/easyble/tisensortag/easyble.dist.js
arrayToUUID
function arrayToUUID(array, offset) { var k=0; var string = ''; var UUID_format = [4, 2, 2, 2, 6]; for (var l=0; l<UUID_format.length; l++) { if (l != 0) { string += '-'; } for (var j=0; j<UUID_format[l]; j++, k++) { string += evothings.util.toHexString(array[offset+k], 1); } } return string; }
javascript
function arrayToUUID(array, offset) { var k=0; var string = ''; var UUID_format = [4, 2, 2, 2, 6]; for (var l=0; l<UUID_format.length; l++) { if (l != 0) { string += '-'; } for (var j=0; j<UUID_format[l]; j++, k++) { string += evothings.util.toHexString(array[offset+k], 1); } } return string; }
[ "function", "arrayToUUID", "(", "array", ",", "offset", ")", "{", "var", "k", "=", "0", ";", "var", "string", "=", "''", ";", "var", "UUID_format", "=", "[", "4", ",", "2", ",", "2", ",", "2", ",", "6", "]", ";", "for", "(", "var", "l", "=", "0", ";", "l", "<", "UUID_format", ".", "length", ";", "l", "++", ")", "{", "if", "(", "l", "!=", "0", ")", "{", "string", "+=", "'-'", ";", "}", "for", "(", "var", "j", "=", "0", ";", "j", "<", "UUID_format", "[", "l", "]", ";", "j", "++", ",", "k", "++", ")", "{", "string", "+=", "evothings", ".", "util", ".", "toHexString", "(", "array", "[", "offset", "+", "k", "]", ",", "1", ")", ";", "}", "}", "return", "string", ";", "}" ]
Convert 16-byte Uint8Array to RFC-4122-formatted UUID.
[ "Convert", "16", "-", "byte", "Uint8Array", "to", "RFC", "-", "4122", "-", "formatted", "UUID", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/examples/deprecated/easyble/tisensortag/easyble.dist.js#L919-L936
17,260
evothings/cordova-ble
examples/deprecated/easyble/tisensortag/easyble.dist.js
function(connectInfo) { // DEBUG LOG console.log('BLE connect state: ' + connectInfo.state); if (connectInfo.state == 2) // connected { device.deviceHandle = connectInfo.deviceHandle; device.__uuidMap = {}; device.__serviceMap = {}; device.__isConnected = true; internal.connectedDevices[device.address] = device; success(device); } else if (connectInfo.state == 0) // disconnected { device.__isConnected = false; internal.connectedDevices[device.address] = null; // TODO: Perhaps this should be redesigned, as disconnect is // more of a status change than an error? What do you think? fail && fail(evothings.easyble.error.DISCONNECTED); } }
javascript
function(connectInfo) { // DEBUG LOG console.log('BLE connect state: ' + connectInfo.state); if (connectInfo.state == 2) // connected { device.deviceHandle = connectInfo.deviceHandle; device.__uuidMap = {}; device.__serviceMap = {}; device.__isConnected = true; internal.connectedDevices[device.address] = device; success(device); } else if (connectInfo.state == 0) // disconnected { device.__isConnected = false; internal.connectedDevices[device.address] = null; // TODO: Perhaps this should be redesigned, as disconnect is // more of a status change than an error? What do you think? fail && fail(evothings.easyble.error.DISCONNECTED); } }
[ "function", "(", "connectInfo", ")", "{", "// DEBUG LOG", "console", ".", "log", "(", "'BLE connect state: '", "+", "connectInfo", ".", "state", ")", ";", "if", "(", "connectInfo", ".", "state", "==", "2", ")", "// connected", "{", "device", ".", "deviceHandle", "=", "connectInfo", ".", "deviceHandle", ";", "device", ".", "__uuidMap", "=", "{", "}", ";", "device", ".", "__serviceMap", "=", "{", "}", ";", "device", ".", "__isConnected", "=", "true", ";", "internal", ".", "connectedDevices", "[", "device", ".", "address", "]", "=", "device", ";", "success", "(", "device", ")", ";", "}", "else", "if", "(", "connectInfo", ".", "state", "==", "0", ")", "// disconnected", "{", "device", ".", "__isConnected", "=", "false", ";", "internal", ".", "connectedDevices", "[", "device", ".", "address", "]", "=", "null", ";", "// TODO: Perhaps this should be redesigned, as disconnect is", "// more of a status change than an error? What do you think?", "fail", "&&", "fail", "(", "evothings", ".", "easyble", ".", "error", ".", "DISCONNECTED", ")", ";", "}", "}" ]
Success callback.
[ "Success", "callback", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/examples/deprecated/easyble/tisensortag/easyble.dist.js#L1762-L1786
17,261
evothings/cordova-ble
examples/deprecated/easyble/tisensortag/easyble.dist.js
function(errorCode) { // DEBUG LOG console.log('BLE connect error: ' + errorCode); // Set isConnected to false on error. device.__isConnected = false; internal.connectedDevices[device.address] = null; fail(errorCode); }
javascript
function(errorCode) { // DEBUG LOG console.log('BLE connect error: ' + errorCode); // Set isConnected to false on error. device.__isConnected = false; internal.connectedDevices[device.address] = null; fail(errorCode); }
[ "function", "(", "errorCode", ")", "{", "// DEBUG LOG", "console", ".", "log", "(", "'BLE connect error: '", "+", "errorCode", ")", ";", "// Set isConnected to false on error.", "device", ".", "__isConnected", "=", "false", ";", "internal", ".", "connectedDevices", "[", "device", ".", "address", "]", "=", "null", ";", "fail", "(", "errorCode", ")", ";", "}" ]
Error callback.
[ "Error", "callback", "." ]
0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5
https://github.com/evothings/cordova-ble/blob/0ca2a3bfa18b5a83e929eb89dcbfb55c96843dd5/examples/deprecated/easyble/tisensortag/easyble.dist.js#L1788-L1797
17,262
jackmoore/wheelzoom
wheelzoom.js
draggable
function draggable(e) { e.preventDefault(); previousEvent = e; document.addEventListener('mousemove', drag); document.addEventListener('mouseup', removeDrag); }
javascript
function draggable(e) { e.preventDefault(); previousEvent = e; document.addEventListener('mousemove', drag); document.addEventListener('mouseup', removeDrag); }
[ "function", "draggable", "(", "e", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "previousEvent", "=", "e", ";", "document", ".", "addEventListener", "(", "'mousemove'", ",", "drag", ")", ";", "document", ".", "addEventListener", "(", "'mouseup'", ",", "removeDrag", ")", ";", "}" ]
Make the background draggable
[ "Make", "the", "background", "draggable" ]
9243fce7f45ebc20887f3f797bffbc780eb0f856
https://github.com/jackmoore/wheelzoom/blob/9243fce7f45ebc20887f3f797bffbc780eb0f856/wheelzoom.js#L123-L128
17,263
matthewnau/libmoji
src/index.js
buildPreviewUrl
function buildPreviewUrl (pose, scale, gender, style, rotation, traits, outfit) { // use string templating to build the url let url = `${basePreviewUrl}${pose}?scale=${scale}&gender=${gender}&style=${style}` url += `&rotation=${rotation}${mapTraits(traits).join("")}&outfit=${outfit}` return url; }
javascript
function buildPreviewUrl (pose, scale, gender, style, rotation, traits, outfit) { // use string templating to build the url let url = `${basePreviewUrl}${pose}?scale=${scale}&gender=${gender}&style=${style}` url += `&rotation=${rotation}${mapTraits(traits).join("")}&outfit=${outfit}` return url; }
[ "function", "buildPreviewUrl", "(", "pose", ",", "scale", ",", "gender", ",", "style", ",", "rotation", ",", "traits", ",", "outfit", ")", "{", "// use string templating to build the url", "let", "url", "=", "`", "${", "basePreviewUrl", "}", "${", "pose", "}", "${", "scale", "}", "${", "gender", "}", "${", "style", "}", "`", "url", "+=", "`", "${", "rotation", "}", "${", "mapTraits", "(", "traits", ")", ".", "join", "(", "\"\"", ")", "}", "${", "outfit", "}", "`", "return", "url", ";", "}" ]
returns the image url of a bitmoji avatar with the specified parameters
[ "returns", "the", "image", "url", "of", "a", "bitmoji", "avatar", "with", "the", "specified", "parameters" ]
17d2a20c3e3e0c11b4c805a37a59b68335982022
https://github.com/matthewnau/libmoji/blob/17d2a20c3e3e0c11b4c805a37a59b68335982022/src/index.js#L110-L116
17,264
matthewnau/libmoji
src/index.js
buildFriendmojiUrl
function buildFriendmojiUrl (comicId, avatarId1, avatarId2, transparent, scale) { return `${baseCpanelUrl}${comicId}-${avatarId1}-${avatarId2}-v3.png?transparent=${transparent}&scale=${scale}`; }
javascript
function buildFriendmojiUrl (comicId, avatarId1, avatarId2, transparent, scale) { return `${baseCpanelUrl}${comicId}-${avatarId1}-${avatarId2}-v3.png?transparent=${transparent}&scale=${scale}`; }
[ "function", "buildFriendmojiUrl", "(", "comicId", ",", "avatarId1", ",", "avatarId2", ",", "transparent", ",", "scale", ")", "{", "return", "`", "${", "baseCpanelUrl", "}", "${", "comicId", "}", "${", "avatarId1", "}", "${", "avatarId2", "}", "${", "transparent", "}", "${", "scale", "}", "`", ";", "}" ]
returns the image url of a friendmoji comic with the specified paramters
[ "returns", "the", "image", "url", "of", "a", "friendmoji", "comic", "with", "the", "specified", "paramters" ]
17d2a20c3e3e0c11b4c805a37a59b68335982022
https://github.com/matthewnau/libmoji/blob/17d2a20c3e3e0c11b4c805a37a59b68335982022/src/index.js#L129-L131
17,265
pfefferf/grunt-nwabap-ui5uploader
tasks/lib/filestoreutil.js
structureResolve
function structureResolve(resolve, sPathStartWith) { var aToResolve = []; var aResolved = []; if (typeof resolve === 'object' && resolve instanceof Array) { aToResolve = resolve; } else if (typeof resolve === 'string') { aToResolve.push(resolve); } else { return null; } // resolve aToResolve.forEach(function (item) { var aSplit = item.split('/'); for (var i = 0; i < aSplit.length; i++) { var aConc = aSplit.slice(0, i + 1); var sConc = (aConc.length > 1) ? aConc.join('/') : aConc[0]; if (sConc.length > 0) { aResolved.push({ type: (i < (aSplit.length - 1)) ? OBJECT_TYPE.folder : OBJECT_TYPE.file, id: (sConc.charAt(0) !== sPathStartWith) ? sPathStartWith + sConc : sConc }); } } }); // remove dups aResolved = aResolved.sort(function (sVal1, sVal2) { var sA = JSON.stringify(sVal1); var sB = JSON.stringify(sVal2); if (sA === sB) { return 0; } else if (sA <= sB) { return -1; } else { return 1; } }) .filter(function (oItem, iPos) { if (iPos > 0) { return JSON.stringify(aResolved[iPos - 1]) !== JSON.stringify(oItem); } else { return true; } }); return aResolved; }
javascript
function structureResolve(resolve, sPathStartWith) { var aToResolve = []; var aResolved = []; if (typeof resolve === 'object' && resolve instanceof Array) { aToResolve = resolve; } else if (typeof resolve === 'string') { aToResolve.push(resolve); } else { return null; } // resolve aToResolve.forEach(function (item) { var aSplit = item.split('/'); for (var i = 0; i < aSplit.length; i++) { var aConc = aSplit.slice(0, i + 1); var sConc = (aConc.length > 1) ? aConc.join('/') : aConc[0]; if (sConc.length > 0) { aResolved.push({ type: (i < (aSplit.length - 1)) ? OBJECT_TYPE.folder : OBJECT_TYPE.file, id: (sConc.charAt(0) !== sPathStartWith) ? sPathStartWith + sConc : sConc }); } } }); // remove dups aResolved = aResolved.sort(function (sVal1, sVal2) { var sA = JSON.stringify(sVal1); var sB = JSON.stringify(sVal2); if (sA === sB) { return 0; } else if (sA <= sB) { return -1; } else { return 1; } }) .filter(function (oItem, iPos) { if (iPos > 0) { return JSON.stringify(aResolved[iPos - 1]) !== JSON.stringify(oItem); } else { return true; } }); return aResolved; }
[ "function", "structureResolve", "(", "resolve", ",", "sPathStartWith", ")", "{", "var", "aToResolve", "=", "[", "]", ";", "var", "aResolved", "=", "[", "]", ";", "if", "(", "typeof", "resolve", "===", "'object'", "&&", "resolve", "instanceof", "Array", ")", "{", "aToResolve", "=", "resolve", ";", "}", "else", "if", "(", "typeof", "resolve", "===", "'string'", ")", "{", "aToResolve", ".", "push", "(", "resolve", ")", ";", "}", "else", "{", "return", "null", ";", "}", "// resolve", "aToResolve", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "aSplit", "=", "item", ".", "split", "(", "'/'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "aSplit", ".", "length", ";", "i", "++", ")", "{", "var", "aConc", "=", "aSplit", ".", "slice", "(", "0", ",", "i", "+", "1", ")", ";", "var", "sConc", "=", "(", "aConc", ".", "length", ">", "1", ")", "?", "aConc", ".", "join", "(", "'/'", ")", ":", "aConc", "[", "0", "]", ";", "if", "(", "sConc", ".", "length", ">", "0", ")", "{", "aResolved", ".", "push", "(", "{", "type", ":", "(", "i", "<", "(", "aSplit", ".", "length", "-", "1", ")", ")", "?", "OBJECT_TYPE", ".", "folder", ":", "OBJECT_TYPE", ".", "file", ",", "id", ":", "(", "sConc", ".", "charAt", "(", "0", ")", "!==", "sPathStartWith", ")", "?", "sPathStartWith", "+", "sConc", ":", "sConc", "}", ")", ";", "}", "}", "}", ")", ";", "// remove dups", "aResolved", "=", "aResolved", ".", "sort", "(", "function", "(", "sVal1", ",", "sVal2", ")", "{", "var", "sA", "=", "JSON", ".", "stringify", "(", "sVal1", ")", ";", "var", "sB", "=", "JSON", ".", "stringify", "(", "sVal2", ")", ";", "if", "(", "sA", "===", "sB", ")", "{", "return", "0", ";", "}", "else", "if", "(", "sA", "<=", "sB", ")", "{", "return", "-", "1", ";", "}", "else", "{", "return", "1", ";", "}", "}", ")", ".", "filter", "(", "function", "(", "oItem", ",", "iPos", ")", "{", "if", "(", "iPos", ">", "0", ")", "{", "return", "JSON", ".", "stringify", "(", "aResolved", "[", "iPos", "-", "1", "]", ")", "!==", "JSON", ".", "stringify", "(", "oItem", ")", ";", "}", "else", "{", "return", "true", ";", "}", "}", ")", ";", "return", "aResolved", ";", "}" ]
Resolves file structure into single folders and files @param {(string|string)} resolve file or file array @param {string} sPathStartWith path has to start with that value @return {Array} array with resolved folders and files
[ "Resolves", "file", "structure", "into", "single", "folders", "and", "files" ]
722ca80763f1d0850e9f2beb99a27237c2ee3e3b
https://github.com/pfefferf/grunt-nwabap-ui5uploader/blob/722ca80763f1d0850e9f2beb99a27237c2ee3e3b/tasks/lib/filestoreutil.js#L49-L100
17,266
pfefferf/grunt-nwabap-ui5uploader
tasks/lib/filestoreutil.js
splitIntoPathAndObject
function splitIntoPathAndObject(sValue) { var aValues = sValue.split('/'); var sObject = aValues.pop(); var sPath = aValues.join('/'); if (sPath.length > 0 && sPath.charAt(0) !== '/') { sPath = '/' + sPath; } return { path: sPath, obj: sObject }; }
javascript
function splitIntoPathAndObject(sValue) { var aValues = sValue.split('/'); var sObject = aValues.pop(); var sPath = aValues.join('/'); if (sPath.length > 0 && sPath.charAt(0) !== '/') { sPath = '/' + sPath; } return { path: sPath, obj: sObject }; }
[ "function", "splitIntoPathAndObject", "(", "sValue", ")", "{", "var", "aValues", "=", "sValue", ".", "split", "(", "'/'", ")", ";", "var", "sObject", "=", "aValues", ".", "pop", "(", ")", ";", "var", "sPath", "=", "aValues", ".", "join", "(", "'/'", ")", ";", "if", "(", "sPath", ".", "length", ">", "0", "&&", "sPath", ".", "charAt", "(", "0", ")", "!==", "'/'", ")", "{", "sPath", "=", "'/'", "+", "sPath", ";", "}", "return", "{", "path", ":", "sPath", ",", "obj", ":", "sObject", "}", ";", "}" ]
Split a value into the path and object information @param {string} sValue values like /test/test1.txt @return {{path: string, obj: string}} Path object
[ "Split", "a", "value", "into", "the", "path", "and", "object", "information" ]
722ca80763f1d0850e9f2beb99a27237c2ee3e3b
https://github.com/pfefferf/grunt-nwabap-ui5uploader/blob/722ca80763f1d0850e9f2beb99a27237c2ee3e3b/tasks/lib/filestoreutil.js#L107-L118
17,267
pfefferf/grunt-nwabap-ui5uploader
tasks/lib/transports.js
Transports
function Transports(oOptions, oLogger) { this._client = new AdtClient(oOptions.conn, oOptions.auth, undefined, oLogger); }
javascript
function Transports(oOptions, oLogger) { this._client = new AdtClient(oOptions.conn, oOptions.auth, undefined, oLogger); }
[ "function", "Transports", "(", "oOptions", ",", "oLogger", ")", "{", "this", ".", "_client", "=", "new", "AdtClient", "(", "oOptions", ".", "conn", ",", "oOptions", ".", "auth", ",", "undefined", ",", "oLogger", ")", ";", "}" ]
creates and releases transport requests @param {object} oOptions @param {object} oOptions.conn connection info @param {string} oOptions.conn.server server url @param {string} oOptions.conn.client sap client id @param {boolean} oOptions.conn.useStrictSSL force encrypted connection @param {string} oOptions.conn.proxy set connection proxy @param {string} oOptions.auth.user username @param {string} oOptions.auth.pwd password @param {Logger} oLogger @constructor
[ "creates", "and", "releases", "transport", "requests" ]
722ca80763f1d0850e9f2beb99a27237c2ee3e3b
https://github.com/pfefferf/grunt-nwabap-ui5uploader/blob/722ca80763f1d0850e9f2beb99a27237c2ee3e3b/tasks/lib/transports.js#L30-L32
17,268
baudehlo/node-fs-ext
fs-ext.js
stringToFlockFlags
function stringToFlockFlags(flag) { // Only mess with strings if (typeof flag !== 'string') { return flag; } switch (flag) { case 'sh': return binding.LOCK_SH; case 'ex': return binding.LOCK_EX; case 'shnb': return binding.LOCK_SH | binding.LOCK_NB; case 'exnb': return binding.LOCK_EX | binding.LOCK_NB; case 'un': return binding.LOCK_UN; default: throw new Error('Unknown flock flag: ' + flag); } }
javascript
function stringToFlockFlags(flag) { // Only mess with strings if (typeof flag !== 'string') { return flag; } switch (flag) { case 'sh': return binding.LOCK_SH; case 'ex': return binding.LOCK_EX; case 'shnb': return binding.LOCK_SH | binding.LOCK_NB; case 'exnb': return binding.LOCK_EX | binding.LOCK_NB; case 'un': return binding.LOCK_UN; default: throw new Error('Unknown flock flag: ' + flag); } }
[ "function", "stringToFlockFlags", "(", "flag", ")", "{", "// Only mess with strings", "if", "(", "typeof", "flag", "!==", "'string'", ")", "{", "return", "flag", ";", "}", "switch", "(", "flag", ")", "{", "case", "'sh'", ":", "return", "binding", ".", "LOCK_SH", ";", "case", "'ex'", ":", "return", "binding", ".", "LOCK_EX", ";", "case", "'shnb'", ":", "return", "binding", ".", "LOCK_SH", "|", "binding", ".", "LOCK_NB", ";", "case", "'exnb'", ":", "return", "binding", ".", "LOCK_EX", "|", "binding", ".", "LOCK_NB", ";", "case", "'un'", ":", "return", "binding", ".", "LOCK_UN", ";", "default", ":", "throw", "new", "Error", "(", "'Unknown flock flag: '", "+", "flag", ")", ";", "}", "}" ]
Used by flock
[ "Used", "by", "flock" ]
2ba366d9fc67ef3ab165e239068924b276ecf249
https://github.com/baudehlo/node-fs-ext/blob/2ba366d9fc67ef3ab165e239068924b276ecf249/fs-ext.js#L27-L51
17,269
baudehlo/node-fs-ext
fs-ext.js
stringToFcntlFlags
function stringToFcntlFlags(flag) { if (typeof flag !== 'string') { return flag; } switch (flag) { case 'getfd': return binding.F_GETFD; case 'setfd': return binding.F_SETFD; case 'setlk': return binding.F_SETLK; case 'setlkw': return binding.F_SETLKW; case 'getlk': return binding.F_GETLK; default: throw new Error('Unknown fcntl flag: ' + flag); } }
javascript
function stringToFcntlFlags(flag) { if (typeof flag !== 'string') { return flag; } switch (flag) { case 'getfd': return binding.F_GETFD; case 'setfd': return binding.F_SETFD; case 'setlk': return binding.F_SETLK; case 'setlkw': return binding.F_SETLKW; case 'getlk': return binding.F_GETLK; default: throw new Error('Unknown fcntl flag: ' + flag); } }
[ "function", "stringToFcntlFlags", "(", "flag", ")", "{", "if", "(", "typeof", "flag", "!==", "'string'", ")", "{", "return", "flag", ";", "}", "switch", "(", "flag", ")", "{", "case", "'getfd'", ":", "return", "binding", ".", "F_GETFD", ";", "case", "'setfd'", ":", "return", "binding", ".", "F_SETFD", ";", "case", "'setlk'", ":", "return", "binding", ".", "F_SETLK", ";", "case", "'setlkw'", ":", "return", "binding", ".", "F_SETLKW", ";", "case", "'getlk'", ":", "return", "binding", ".", "F_GETLK", ";", "default", ":", "throw", "new", "Error", "(", "'Unknown fcntl flag: '", "+", "flag", ")", ";", "}", "}" ]
used by Fcntl
[ "used", "by", "Fcntl" ]
2ba366d9fc67ef3ab165e239068924b276ecf249
https://github.com/baudehlo/node-fs-ext/blob/2ba366d9fc67ef3ab165e239068924b276ecf249/fs-ext.js#L54-L78
17,270
baudehlo/node-fs-ext
example.js
getCurrentFileSize
function getCurrentFileSize(counter, timeout, cb) { var fd = fs.openSync(__filename, 'r'); console.log("Trying to aquire lock for the %s time", counter); fs.flock(fd, 'exnb', function(err) { if (err) { return console.log("Couldn't lock file", counter); } console.log('Aquired lock', counter); // unlock after `timeout` setTimeout(function() { fs.flock(fd, 'un', function(err) { if (err) { return console.log("Couldn't unlock file", counter); } if (cb) { cb(); } }); }, timeout); }); }
javascript
function getCurrentFileSize(counter, timeout, cb) { var fd = fs.openSync(__filename, 'r'); console.log("Trying to aquire lock for the %s time", counter); fs.flock(fd, 'exnb', function(err) { if (err) { return console.log("Couldn't lock file", counter); } console.log('Aquired lock', counter); // unlock after `timeout` setTimeout(function() { fs.flock(fd, 'un', function(err) { if (err) { return console.log("Couldn't unlock file", counter); } if (cb) { cb(); } }); }, timeout); }); }
[ "function", "getCurrentFileSize", "(", "counter", ",", "timeout", ",", "cb", ")", "{", "var", "fd", "=", "fs", ".", "openSync", "(", "__filename", ",", "'r'", ")", ";", "console", ".", "log", "(", "\"Trying to aquire lock for the %s time\"", ",", "counter", ")", ";", "fs", ".", "flock", "(", "fd", ",", "'exnb'", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "console", ".", "log", "(", "\"Couldn't lock file\"", ",", "counter", ")", ";", "}", "console", ".", "log", "(", "'Aquired lock'", ",", "counter", ")", ";", "// unlock after `timeout`", "setTimeout", "(", "function", "(", ")", "{", "fs", ".", "flock", "(", "fd", ",", "'un'", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "console", ".", "log", "(", "\"Couldn't unlock file\"", ",", "counter", ")", ";", "}", "if", "(", "cb", ")", "{", "cb", "(", ")", ";", "}", "}", ")", ";", "}", ",", "timeout", ")", ";", "}", ")", ";", "}" ]
Function that locks the current file for `timeout` miliseconds The `counter` represents an index of how many times the function has been called so far (it acts as an id) The callback `cb` is optional
[ "Function", "that", "locks", "the", "current", "file", "for", "timeout", "miliseconds" ]
2ba366d9fc67ef3ab165e239068924b276ecf249
https://github.com/baudehlo/node-fs-ext/blob/2ba366d9fc67ef3ab165e239068924b276ecf249/example.js#L15-L38
17,271
node-sc2/core
utils/map/cluster.js
createClusters
function createClusters(units, distanceApart = 15.0) { const squaredDistanceApart = distanceApart * distanceApart; return units.reduce((clusters, u) => { const isGeyser = vespeneGeyserTypes.includes(u.unitType); /** * @type {{ distance: number, target: Cluster }} */ const { distance, target } = clusters.reduce((acc, b) => { const d = distanceSquared(u.pos, b.centroid); if (d < acc.distance) { return { distance: d, target: b }; } else { return acc; } }, { distance: Infinity, target: null }); if (distance > squaredDistanceApart) { return clusters.concat([{ centroid: u.pos, mineralFields: isGeyser ? [] : [u], vespeneGeysers: isGeyser ? [u] : [], }]); } else { if (isGeyser) { target.vespeneGeysers = [...target.vespeneGeysers, u]; } else { target.mineralFields = [...target.mineralFields, u]; } const size = target.mineralFields.length + target.vespeneGeysers.length; target.centroid = divide(add(multiply(target.centroid, (size - 1)), u.pos), size); return clusters; } }, []); }
javascript
function createClusters(units, distanceApart = 15.0) { const squaredDistanceApart = distanceApart * distanceApart; return units.reduce((clusters, u) => { const isGeyser = vespeneGeyserTypes.includes(u.unitType); /** * @type {{ distance: number, target: Cluster }} */ const { distance, target } = clusters.reduce((acc, b) => { const d = distanceSquared(u.pos, b.centroid); if (d < acc.distance) { return { distance: d, target: b }; } else { return acc; } }, { distance: Infinity, target: null }); if (distance > squaredDistanceApart) { return clusters.concat([{ centroid: u.pos, mineralFields: isGeyser ? [] : [u], vespeneGeysers: isGeyser ? [u] : [], }]); } else { if (isGeyser) { target.vespeneGeysers = [...target.vespeneGeysers, u]; } else { target.mineralFields = [...target.mineralFields, u]; } const size = target.mineralFields.length + target.vespeneGeysers.length; target.centroid = divide(add(multiply(target.centroid, (size - 1)), u.pos), size); return clusters; } }, []); }
[ "function", "createClusters", "(", "units", ",", "distanceApart", "=", "15.0", ")", "{", "const", "squaredDistanceApart", "=", "distanceApart", "*", "distanceApart", ";", "return", "units", ".", "reduce", "(", "(", "clusters", ",", "u", ")", "=>", "{", "const", "isGeyser", "=", "vespeneGeyserTypes", ".", "includes", "(", "u", ".", "unitType", ")", ";", "/**\n * @type {{ distance: number, target: Cluster }}\n */", "const", "{", "distance", ",", "target", "}", "=", "clusters", ".", "reduce", "(", "(", "acc", ",", "b", ")", "=>", "{", "const", "d", "=", "distanceSquared", "(", "u", ".", "pos", ",", "b", ".", "centroid", ")", ";", "if", "(", "d", "<", "acc", ".", "distance", ")", "{", "return", "{", "distance", ":", "d", ",", "target", ":", "b", "}", ";", "}", "else", "{", "return", "acc", ";", "}", "}", ",", "{", "distance", ":", "Infinity", ",", "target", ":", "null", "}", ")", ";", "if", "(", "distance", ">", "squaredDistanceApart", ")", "{", "return", "clusters", ".", "concat", "(", "[", "{", "centroid", ":", "u", ".", "pos", ",", "mineralFields", ":", "isGeyser", "?", "[", "]", ":", "[", "u", "]", ",", "vespeneGeysers", ":", "isGeyser", "?", "[", "u", "]", ":", "[", "]", ",", "}", "]", ")", ";", "}", "else", "{", "if", "(", "isGeyser", ")", "{", "target", ".", "vespeneGeysers", "=", "[", "...", "target", ".", "vespeneGeysers", ",", "u", "]", ";", "}", "else", "{", "target", ".", "mineralFields", "=", "[", "...", "target", ".", "mineralFields", ",", "u", "]", ";", "}", "const", "size", "=", "target", ".", "mineralFields", ".", "length", "+", "target", ".", "vespeneGeysers", ".", "length", ";", "target", ".", "centroid", "=", "divide", "(", "add", "(", "multiply", "(", "target", ".", "centroid", ",", "(", "size", "-", "1", ")", ")", ",", "u", ".", "pos", ")", ",", "size", ")", ";", "return", "clusters", ";", "}", "}", ",", "[", "]", ")", ";", "}" ]
Creates clusters of units by distance between them. Right now only used for expansions. @param {Unit[]} units @param {number} distanceApart @returns {Cluster[]}
[ "Creates", "clusters", "of", "units", "by", "distance", "between", "them", ".", "Right", "now", "only", "used", "for", "expansions", "." ]
eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3
https://github.com/node-sc2/core/blob/eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3/utils/map/cluster.js#L12-L48
17,272
node-sc2/core
utils/map/cluster.js
clusterByNeighbor
function clusterByNeighbor(points) { const sorted = points.slice().sort((a, b) => { if (a.y < b.y) { return -1; } else if (a.y > b.y) { return 1; } else { if (a.x < b.x) { return -1; } else if (a.x > b.x) { return 1; } else { return 0; } } }); const cluster = sorted.reduce((sets, point) => { const setContainingNeighbors = sets.find(set => set.some((setPoint) => { return getNeighbors(setPoint).some(spn => areEqual(spn, point)); })); if (setContainingNeighbors) { setContainingNeighbors.push(point); } else { sets.push([point]); } return sets; }, []); return cluster; }
javascript
function clusterByNeighbor(points) { const sorted = points.slice().sort((a, b) => { if (a.y < b.y) { return -1; } else if (a.y > b.y) { return 1; } else { if (a.x < b.x) { return -1; } else if (a.x > b.x) { return 1; } else { return 0; } } }); const cluster = sorted.reduce((sets, point) => { const setContainingNeighbors = sets.find(set => set.some((setPoint) => { return getNeighbors(setPoint).some(spn => areEqual(spn, point)); })); if (setContainingNeighbors) { setContainingNeighbors.push(point); } else { sets.push([point]); } return sets; }, []); return cluster; }
[ "function", "clusterByNeighbor", "(", "points", ")", "{", "const", "sorted", "=", "points", ".", "slice", "(", ")", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "{", "if", "(", "a", ".", "y", "<", "b", ".", "y", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "a", ".", "y", ">", "b", ".", "y", ")", "{", "return", "1", ";", "}", "else", "{", "if", "(", "a", ".", "x", "<", "b", ".", "x", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "a", ".", "x", ">", "b", ".", "x", ")", "{", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}", "}", ")", ";", "const", "cluster", "=", "sorted", ".", "reduce", "(", "(", "sets", ",", "point", ")", "=>", "{", "const", "setContainingNeighbors", "=", "sets", ".", "find", "(", "set", "=>", "set", ".", "some", "(", "(", "setPoint", ")", "=>", "{", "return", "getNeighbors", "(", "setPoint", ")", ".", "some", "(", "spn", "=>", "areEqual", "(", "spn", ",", "point", ")", ")", ";", "}", ")", ")", ";", "if", "(", "setContainingNeighbors", ")", "{", "setContainingNeighbors", ".", "push", "(", "point", ")", ";", "}", "else", "{", "sets", ".", "push", "(", "[", "point", "]", ")", ";", "}", "return", "sets", ";", "}", ",", "[", "]", ")", ";", "return", "cluster", ";", "}" ]
returns a cluster set where each cluster contains neighbor chains @param {Array<Point2D>} points @returns {Point2D[][]}
[ "returns", "a", "cluster", "set", "where", "each", "cluster", "contains", "neighbor", "chains" ]
eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3
https://github.com/node-sc2/core/blob/eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3/utils/map/cluster.js#L55-L87
17,273
node-sc2/core
utils/geometry/plane.js
distanceAAShapes
function distanceAAShapes(shapeA, shapeB) { const dx = Math.max(Math.abs(shapeA.pos.x - shapeB.pos.x) - ((shapeA.w / 2) + (shapeB.w / 2)), 0); const dy = Math.max(Math.abs(shapeA.pos.y - shapeB.pos.y) - ((shapeA.h / 2) + (shapeB.h / 2)), 0); return Math.sqrt(dx * dx + dy * dy); }
javascript
function distanceAAShapes(shapeA, shapeB) { const dx = Math.max(Math.abs(shapeA.pos.x - shapeB.pos.x) - ((shapeA.w / 2) + (shapeB.w / 2)), 0); const dy = Math.max(Math.abs(shapeA.pos.y - shapeB.pos.y) - ((shapeA.h / 2) + (shapeB.h / 2)), 0); return Math.sqrt(dx * dx + dy * dy); }
[ "function", "distanceAAShapes", "(", "shapeA", ",", "shapeB", ")", "{", "const", "dx", "=", "Math", ".", "max", "(", "Math", ".", "abs", "(", "shapeA", ".", "pos", ".", "x", "-", "shapeB", ".", "pos", ".", "x", ")", "-", "(", "(", "shapeA", ".", "w", "/", "2", ")", "+", "(", "shapeB", ".", "w", "/", "2", ")", ")", ",", "0", ")", ";", "const", "dy", "=", "Math", ".", "max", "(", "Math", ".", "abs", "(", "shapeA", ".", "pos", ".", "y", "-", "shapeB", ".", "pos", ".", "y", ")", "-", "(", "(", "shapeA", ".", "h", "/", "2", ")", "+", "(", "shapeB", ".", "h", "/", "2", ")", ")", ",", "0", ")", ";", "return", "Math", ".", "sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", ";", "}" ]
AA = Axis Aligned, distance from AA shape to AA shape @param {{ pos: Point2D, w, h }} shapeA AA shape A @param {{ pos: Point2D, w, h }} shapeB AA shape B
[ "AA", "=", "Axis", "Aligned", "distance", "from", "AA", "shape", "to", "AA", "shape" ]
eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3
https://github.com/node-sc2/core/blob/eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3/utils/geometry/plane.js#L26-L30
17,274
node-sc2/core
utils/geometry/plane.js
distanceAAShapeAndPoint
function distanceAAShapeAndPoint(shape, point) { const dx = Math.max(Math.abs(shape.pos.x - point.x) - (shape.w / 2), 0); const dy = Math.max(Math.abs(shape.pos.y - point.y) - (shape.h / 2), 0); return Math.sqrt(dx * dx + dy * dy); }
javascript
function distanceAAShapeAndPoint(shape, point) { const dx = Math.max(Math.abs(shape.pos.x - point.x) - (shape.w / 2), 0); const dy = Math.max(Math.abs(shape.pos.y - point.y) - (shape.h / 2), 0); return Math.sqrt(dx * dx + dy * dy); }
[ "function", "distanceAAShapeAndPoint", "(", "shape", ",", "point", ")", "{", "const", "dx", "=", "Math", ".", "max", "(", "Math", ".", "abs", "(", "shape", ".", "pos", ".", "x", "-", "point", ".", "x", ")", "-", "(", "shape", ".", "w", "/", "2", ")", ",", "0", ")", ";", "const", "dy", "=", "Math", ".", "max", "(", "Math", ".", "abs", "(", "shape", ".", "pos", ".", "y", "-", "point", ".", "y", ")", "-", "(", "shape", ".", "h", "/", "2", ")", ",", "0", ")", ";", "return", "Math", ".", "sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", ";", "}" ]
AA = Axis Aligned, distance from point to AA shape @param {{ pos: Point2D, w, h }} shape AA Shape @param {Point2D} point map position
[ "AA", "=", "Axis", "Aligned", "distance", "from", "point", "to", "AA", "shape" ]
eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3
https://github.com/node-sc2/core/blob/eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3/utils/geometry/plane.js#L37-L41
17,275
node-sc2/core
utils/geometry/point.js
subtract
function subtract(point, rhs) { if (typeof rhs === 'number') { return { x: point.x - rhs, y: point.y - rhs, }; } else { return { x: point.x - rhs.x, y: point.y - rhs.y, }; } }
javascript
function subtract(point, rhs) { if (typeof rhs === 'number') { return { x: point.x - rhs, y: point.y - rhs, }; } else { return { x: point.x - rhs.x, y: point.y - rhs.y, }; } }
[ "function", "subtract", "(", "point", ",", "rhs", ")", "{", "if", "(", "typeof", "rhs", "===", "'number'", ")", "{", "return", "{", "x", ":", "point", ".", "x", "-", "rhs", ",", "y", ":", "point", ".", "y", "-", "rhs", ",", "}", ";", "}", "else", "{", "return", "{", "x", ":", "point", ".", "x", "-", "rhs", ".", "x", ",", "y", ":", "point", ".", "y", "-", "rhs", ".", "y", ",", "}", ";", "}", "}" ]
subtract point or number from point @param {Point2D} point @param {(Point2D | number)} rhs
[ "subtract", "point", "or", "number", "from", "point" ]
eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3
https://github.com/node-sc2/core/blob/eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3/utils/geometry/point.js#L77-L89
17,276
node-sc2/core
utils/geometry/point.js
multiply
function multiply(point, rhs) { if (typeof rhs === 'number') { return { x: point.x * rhs, y: point.y * rhs, }; } else { return { x: point.x * rhs.x, y: point.y * rhs.y, }; } }
javascript
function multiply(point, rhs) { if (typeof rhs === 'number') { return { x: point.x * rhs, y: point.y * rhs, }; } else { return { x: point.x * rhs.x, y: point.y * rhs.y, }; } }
[ "function", "multiply", "(", "point", ",", "rhs", ")", "{", "if", "(", "typeof", "rhs", "===", "'number'", ")", "{", "return", "{", "x", ":", "point", ".", "x", "*", "rhs", ",", "y", ":", "point", ".", "y", "*", "rhs", ",", "}", ";", "}", "else", "{", "return", "{", "x", ":", "point", ".", "x", "*", "rhs", ".", "x", ",", "y", ":", "point", ".", "y", "*", "rhs", ".", "y", ",", "}", ";", "}", "}" ]
multiply point by point or number @param {Point2D} point @param {(Point2D | number)} rhs
[ "multiply", "point", "by", "point", "or", "number" ]
eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3
https://github.com/node-sc2/core/blob/eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3/utils/geometry/point.js#L96-L108
17,277
node-sc2/core
utils/geometry/point.js
divide
function divide(point, rhs) { if (typeof rhs === 'number') { return { x: point.x / rhs, y: point.y / rhs, }; } else { return { x: point.x / rhs.x, y: point.y / rhs.y, }; } }
javascript
function divide(point, rhs) { if (typeof rhs === 'number') { return { x: point.x / rhs, y: point.y / rhs, }; } else { return { x: point.x / rhs.x, y: point.y / rhs.y, }; } }
[ "function", "divide", "(", "point", ",", "rhs", ")", "{", "if", "(", "typeof", "rhs", "===", "'number'", ")", "{", "return", "{", "x", ":", "point", ".", "x", "/", "rhs", ",", "y", ":", "point", ".", "y", "/", "rhs", ",", "}", ";", "}", "else", "{", "return", "{", "x", ":", "point", ".", "x", "/", "rhs", ".", "x", ",", "y", ":", "point", ".", "y", "/", "rhs", ".", "y", ",", "}", ";", "}", "}" ]
divide point by point or number @param {Point2D} point @param {(Point2D | number)} rhs
[ "divide", "point", "by", "point", "or", "number" ]
eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3
https://github.com/node-sc2/core/blob/eccdd88111fa9f0dfe228ff4fb404fbcc363a4a3/utils/geometry/point.js#L115-L128
17,278
nodecg/nodecg
lib/replicant/shared.js
proxyRecursive
function proxyRecursive(replicant, value, path) { if (typeof value === 'object' && value !== null) { let p; assertSingleOwner(replicant, value); // If "value" is already a Proxy, don't re-proxy it. if (proxySet.has(value)) { p = value; const metadata = proxyMetadataMap.get(value); metadata.path = path; // Update the path, as it may have changed. } else if (metadataMap.has(value)) { const metadata = metadataMap.get(value); p = metadata.proxy; metadata.path = path; // Update the path, as it may have changed. } else { const handler = Array.isArray(value) ? CHILD_ARRAY_HANDLER : CHILD_OBJECT_HANDLER; p = new Proxy(value, handler); proxySet.add(p); const metadata = { replicant, path, proxy: p }; metadataMap.set(value, metadata); proxyMetadataMap.set(p, metadata); } for (const key in value) { /* istanbul ignore if */ if (!{}.hasOwnProperty.call(value, key)) { continue; } const escapedKey = key.replace(/\//g, '~1'); if (path) { const joinedPath = joinPathParts(path, escapedKey); value[key] = proxyRecursive(replicant, value[key], joinedPath); } else { value[key] = proxyRecursive(replicant, value[key], escapedKey); } } return p; } return value; }
javascript
function proxyRecursive(replicant, value, path) { if (typeof value === 'object' && value !== null) { let p; assertSingleOwner(replicant, value); // If "value" is already a Proxy, don't re-proxy it. if (proxySet.has(value)) { p = value; const metadata = proxyMetadataMap.get(value); metadata.path = path; // Update the path, as it may have changed. } else if (metadataMap.has(value)) { const metadata = metadataMap.get(value); p = metadata.proxy; metadata.path = path; // Update the path, as it may have changed. } else { const handler = Array.isArray(value) ? CHILD_ARRAY_HANDLER : CHILD_OBJECT_HANDLER; p = new Proxy(value, handler); proxySet.add(p); const metadata = { replicant, path, proxy: p }; metadataMap.set(value, metadata); proxyMetadataMap.set(p, metadata); } for (const key in value) { /* istanbul ignore if */ if (!{}.hasOwnProperty.call(value, key)) { continue; } const escapedKey = key.replace(/\//g, '~1'); if (path) { const joinedPath = joinPathParts(path, escapedKey); value[key] = proxyRecursive(replicant, value[key], joinedPath); } else { value[key] = proxyRecursive(replicant, value[key], escapedKey); } } return p; } return value; }
[ "function", "proxyRecursive", "(", "replicant", ",", "value", ",", "path", ")", "{", "if", "(", "typeof", "value", "===", "'object'", "&&", "value", "!==", "null", ")", "{", "let", "p", ";", "assertSingleOwner", "(", "replicant", ",", "value", ")", ";", "// If \"value\" is already a Proxy, don't re-proxy it.", "if", "(", "proxySet", ".", "has", "(", "value", ")", ")", "{", "p", "=", "value", ";", "const", "metadata", "=", "proxyMetadataMap", ".", "get", "(", "value", ")", ";", "metadata", ".", "path", "=", "path", ";", "// Update the path, as it may have changed.", "}", "else", "if", "(", "metadataMap", ".", "has", "(", "value", ")", ")", "{", "const", "metadata", "=", "metadataMap", ".", "get", "(", "value", ")", ";", "p", "=", "metadata", ".", "proxy", ";", "metadata", ".", "path", "=", "path", ";", "// Update the path, as it may have changed.", "}", "else", "{", "const", "handler", "=", "Array", ".", "isArray", "(", "value", ")", "?", "CHILD_ARRAY_HANDLER", ":", "CHILD_OBJECT_HANDLER", ";", "p", "=", "new", "Proxy", "(", "value", ",", "handler", ")", ";", "proxySet", ".", "add", "(", "p", ")", ";", "const", "metadata", "=", "{", "replicant", ",", "path", ",", "proxy", ":", "p", "}", ";", "metadataMap", ".", "set", "(", "value", ",", "metadata", ")", ";", "proxyMetadataMap", ".", "set", "(", "p", ",", "metadata", ")", ";", "}", "for", "(", "const", "key", "in", "value", ")", "{", "/* istanbul ignore if */", "if", "(", "!", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "value", ",", "key", ")", ")", "{", "continue", ";", "}", "const", "escapedKey", "=", "key", ".", "replace", "(", "/", "\\/", "/", "g", ",", "'~1'", ")", ";", "if", "(", "path", ")", "{", "const", "joinedPath", "=", "joinPathParts", "(", "path", ",", "escapedKey", ")", ";", "value", "[", "key", "]", "=", "proxyRecursive", "(", "replicant", ",", "value", "[", "key", "]", ",", "joinedPath", ")", ";", "}", "else", "{", "value", "[", "key", "]", "=", "proxyRecursive", "(", "replicant", ",", "value", "[", "key", "]", ",", "escapedKey", ")", ";", "}", "}", "return", "p", ";", "}", "return", "value", ";", "}" ]
Recursively Proxies an Array or Object. Does nothing to primitive values. @param replicant {object} - The Replicant in which to do the work. @param value {*} - The value to recursively Proxy. @param path {string} - The objectPath to this value. @returns {*} - The recursively Proxied value (or just `value` unchanged, if `value` is a primitive) @private
[ "Recursively", "Proxies", "an", "Array", "or", "Object", ".", "Does", "nothing", "to", "primitive", "values", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/replicant/shared.js#L305-L352
17,279
nodecg/nodecg
lib/replicant/shared.js
assertSingleOwner
function assertSingleOwner(replicant, value) { let metadata; if (proxySet.has(value)) { metadata = proxyMetadataMap.get(value); } else if (metadataMap.has(value)) { metadata = metadataMap.get(value); } else { // If there's no metadata for this value, then it doesn't belong to any Replicants yet, // and we're okay to continue. return; } if (metadata.replicant !== replicant) { /* eslint-disable function-paren-newline */ throw new Error( `This object belongs to another Replicant, ${metadata.replicant.namespace}::${metadata.replicant.name}.` + `\nA given object cannot belong to multiple Replicants. Object value:\n${JSON.stringify(value, null, 2)}` ); /* eslint-enable function-paren-newline */ } }
javascript
function assertSingleOwner(replicant, value) { let metadata; if (proxySet.has(value)) { metadata = proxyMetadataMap.get(value); } else if (metadataMap.has(value)) { metadata = metadataMap.get(value); } else { // If there's no metadata for this value, then it doesn't belong to any Replicants yet, // and we're okay to continue. return; } if (metadata.replicant !== replicant) { /* eslint-disable function-paren-newline */ throw new Error( `This object belongs to another Replicant, ${metadata.replicant.namespace}::${metadata.replicant.name}.` + `\nA given object cannot belong to multiple Replicants. Object value:\n${JSON.stringify(value, null, 2)}` ); /* eslint-enable function-paren-newline */ } }
[ "function", "assertSingleOwner", "(", "replicant", ",", "value", ")", "{", "let", "metadata", ";", "if", "(", "proxySet", ".", "has", "(", "value", ")", ")", "{", "metadata", "=", "proxyMetadataMap", ".", "get", "(", "value", ")", ";", "}", "else", "if", "(", "metadataMap", ".", "has", "(", "value", ")", ")", "{", "metadata", "=", "metadataMap", ".", "get", "(", "value", ")", ";", "}", "else", "{", "// If there's no metadata for this value, then it doesn't belong to any Replicants yet,", "// and we're okay to continue.", "return", ";", "}", "if", "(", "metadata", ".", "replicant", "!==", "replicant", ")", "{", "/* eslint-disable function-paren-newline */", "throw", "new", "Error", "(", "`", "${", "metadata", ".", "replicant", ".", "namespace", "}", "${", "metadata", ".", "replicant", ".", "name", "}", "`", "+", "`", "\\n", "\\n", "${", "JSON", ".", "stringify", "(", "value", ",", "null", ",", "2", ")", "}", "`", ")", ";", "/* eslint-enable function-paren-newline */", "}", "}" ]
Throws an exception if an object belongs to more than one Replicant. @param replicant {object} - The Replicant that this value should belong to. @param value {*} - The value to check ownership of.
[ "Throws", "an", "exception", "if", "an", "object", "belongs", "to", "more", "than", "one", "Replicant", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/replicant/shared.js#L397-L417
17,280
nodecg/nodecg
gulpfile.js
waitFor
function waitFor(stream) { return new Promise((resolve, reject) => { stream.on('end', resolve); stream.on('error', reject); }); }
javascript
function waitFor(stream) { return new Promise((resolve, reject) => { stream.on('end', resolve); stream.on('error', reject); }); }
[ "function", "waitFor", "(", "stream", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "stream", ".", "on", "(", "'end'", ",", "resolve", ")", ";", "stream", ".", "on", "(", "'error'", ",", "reject", ")", ";", "}", ")", ";", "}" ]
Waits for the given ReadableStream
[ "Waits", "for", "the", "given", "ReadableStream" ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/gulpfile.js#L26-L31
17,281
nodecg/nodecg
lib/replicator.js
declare
function declare(name, namespace, opts) { // Delay requiring the Replicant class until here, otherwise cryptic errors are thrown. Not sure why! const Replicant = require('./replicant'); return new Replicant(name, namespace, opts); }
javascript
function declare(name, namespace, opts) { // Delay requiring the Replicant class until here, otherwise cryptic errors are thrown. Not sure why! const Replicant = require('./replicant'); return new Replicant(name, namespace, opts); }
[ "function", "declare", "(", "name", ",", "namespace", ",", "opts", ")", "{", "// Delay requiring the Replicant class until here, otherwise cryptic errors are thrown. Not sure why!", "const", "Replicant", "=", "require", "(", "'./replicant'", ")", ";", "return", "new", "Replicant", "(", "name", ",", "namespace", ",", "opts", ")", ";", "}" ]
Declares a Replicant. @param {string} name - The name of the Replicant to declare. @param {string} namespace - The namespace to which this Replicant belongs. @param {object} [opts] - The options for this replicant. @param {*} [opts.defaultValue] - The default value to instantiate this Replicant with. The default value is only applied if this Replicant has not previously been declared and if it has no persisted value. @param {boolean} [opts.persistent=true] - Whether to persist the Replicant's value to disk on every change. Persisted values are re-loaded on startup. @param {string} [opts.schemaPath] - The filepath at which to look for a JSON Schema for this Replicant. Defaults to `nodecg/bundles/${bundleName}/schemas/${replicantName}.json`. @returns {object}
[ "Declares", "a", "Replicant", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/replicator.js#L130-L134
17,282
nodecg/nodecg
lib/replicator.js
assign
function assign(replicant, value) { const oldValue = replicant.value; replicant._ignoreProxy = true; replicant.__value = shared._proxyRecursive(replicant, value, '/'); replicant._ignoreProxy = false; replicant.revision++; replicant.emit('change', value, oldValue); replicant.log.replicants('Assigned:', value); emitToClients(replicant.namespace, 'replicant:assignment', { name: replicant.name, namespace: replicant.namespace, newValue: value, revision: replicant.revision }); saveReplicant(replicant); }
javascript
function assign(replicant, value) { const oldValue = replicant.value; replicant._ignoreProxy = true; replicant.__value = shared._proxyRecursive(replicant, value, '/'); replicant._ignoreProxy = false; replicant.revision++; replicant.emit('change', value, oldValue); replicant.log.replicants('Assigned:', value); emitToClients(replicant.namespace, 'replicant:assignment', { name: replicant.name, namespace: replicant.namespace, newValue: value, revision: replicant.revision }); saveReplicant(replicant); }
[ "function", "assign", "(", "replicant", ",", "value", ")", "{", "const", "oldValue", "=", "replicant", ".", "value", ";", "replicant", ".", "_ignoreProxy", "=", "true", ";", "replicant", ".", "__value", "=", "shared", ".", "_proxyRecursive", "(", "replicant", ",", "value", ",", "'/'", ")", ";", "replicant", ".", "_ignoreProxy", "=", "false", ";", "replicant", ".", "revision", "++", ";", "replicant", ".", "emit", "(", "'change'", ",", "value", ",", "oldValue", ")", ";", "replicant", ".", "log", ".", "replicants", "(", "'Assigned:'", ",", "value", ")", ";", "emitToClients", "(", "replicant", ".", "namespace", ",", "'replicant:assignment'", ",", "{", "name", ":", "replicant", ".", "name", ",", "namespace", ":", "replicant", ".", "namespace", ",", "newValue", ":", "value", ",", "revision", ":", "replicant", ".", "revision", "}", ")", ";", "saveReplicant", "(", "replicant", ")", ";", "}" ]
Assigns a new value to a Replicant. @param replicant {object} - The Replicant to assign. @param value {*} - The new value to assign.
[ "Assigns", "a", "new", "value", "to", "a", "Replicant", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/replicator.js#L141-L159
17,283
nodecg/nodecg
lib/replicator.js
applyOperations
function applyOperations(replicant, operations) { const oldValue = clone(replicant.value); operations.forEach(operation => shared.applyOperation(replicant, operation)); replicant.revision++; replicant.emit('change', replicant.value, oldValue, operations); emitToClients(replicant.namespace, 'replicant:operations', { name: replicant.name, namespace: replicant.namespace, revision: replicant.revision, operations }); saveReplicant(replicant); }
javascript
function applyOperations(replicant, operations) { const oldValue = clone(replicant.value); operations.forEach(operation => shared.applyOperation(replicant, operation)); replicant.revision++; replicant.emit('change', replicant.value, oldValue, operations); emitToClients(replicant.namespace, 'replicant:operations', { name: replicant.name, namespace: replicant.namespace, revision: replicant.revision, operations }); saveReplicant(replicant); }
[ "function", "applyOperations", "(", "replicant", ",", "operations", ")", "{", "const", "oldValue", "=", "clone", "(", "replicant", ".", "value", ")", ";", "operations", ".", "forEach", "(", "operation", "=>", "shared", ".", "applyOperation", "(", "replicant", ",", "operation", ")", ")", ";", "replicant", ".", "revision", "++", ";", "replicant", ".", "emit", "(", "'change'", ",", "replicant", ".", "value", ",", "oldValue", ",", "operations", ")", ";", "emitToClients", "(", "replicant", ".", "namespace", ",", "'replicant:operations'", ",", "{", "name", ":", "replicant", ".", "name", ",", "namespace", ":", "replicant", ".", "namespace", ",", "revision", ":", "replicant", ".", "revision", ",", "operations", "}", ")", ";", "saveReplicant", "(", "replicant", ")", ";", "}" ]
Applies an array of operations to a replicant. @param replicant {object} - The Replicant to perform these operation on. @param operations {array} - An array of operations.
[ "Applies", "an", "array", "of", "operations", "to", "a", "replicant", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/replicator.js#L166-L180
17,284
nodecg/nodecg
lib/replicator.js
find
function find(name, namespace) { // If there are no replicants for that namespace, return undefined if (!{}.hasOwnProperty.call(declaredReplicants, namespace)) { return undefined; } // If that replicant doesn't exist for that namespace, return undefined if (!{}.hasOwnProperty.call(declaredReplicants[namespace], name)) { return undefined; } // Return the replicant. return declaredReplicants[namespace][name]; }
javascript
function find(name, namespace) { // If there are no replicants for that namespace, return undefined if (!{}.hasOwnProperty.call(declaredReplicants, namespace)) { return undefined; } // If that replicant doesn't exist for that namespace, return undefined if (!{}.hasOwnProperty.call(declaredReplicants[namespace], name)) { return undefined; } // Return the replicant. return declaredReplicants[namespace][name]; }
[ "function", "find", "(", "name", ",", "namespace", ")", "{", "// If there are no replicants for that namespace, return undefined", "if", "(", "!", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "declaredReplicants", ",", "namespace", ")", ")", "{", "return", "undefined", ";", "}", "// If that replicant doesn't exist for that namespace, return undefined", "if", "(", "!", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "declaredReplicants", "[", "namespace", "]", ",", "name", ")", ")", "{", "return", "undefined", ";", "}", "// Return the replicant.", "return", "declaredReplicants", "[", "namespace", "]", "[", "name", "]", ";", "}" ]
Finds a Replicant, returns undefined if not found. @param name {string} - The name of the Replicant to find. @param namespace {string} - The namespace in which to search. @returns {*}
[ "Finds", "a", "Replicant", "returns", "undefined", "if", "not", "found", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/replicator.js#L188-L201
17,285
nodecg/nodecg
lib/replicator.js
findOrDeclare
function findOrDeclare(name, namespace, opts) { const existingReplicant = find(name, namespace); if (typeof existingReplicant !== 'undefined') { return existingReplicant; } return declare(name, namespace, opts); }
javascript
function findOrDeclare(name, namespace, opts) { const existingReplicant = find(name, namespace); if (typeof existingReplicant !== 'undefined') { return existingReplicant; } return declare(name, namespace, opts); }
[ "function", "findOrDeclare", "(", "name", ",", "namespace", ",", "opts", ")", "{", "const", "existingReplicant", "=", "find", "(", "name", ",", "namespace", ")", ";", "if", "(", "typeof", "existingReplicant", "!==", "'undefined'", ")", "{", "return", "existingReplicant", ";", "}", "return", "declare", "(", "name", ",", "namespace", ",", "opts", ")", ";", "}" ]
Finds or declares a Replicant. If a Replicant with the given `name` is already present in `namespace`, returns that existing Replicant. Else, declares a new Replicant. @param name {string} - The name of the Replicant. @param namespace {string} - The namespace that the Replicant belongs to. @param {object} [opts] - The options for this replicant. @param {*} [opts.defaultValue] - The default value to instantiate this Replicant with. The default value is only applied if this Replicant has not previously been declared and if it has no persisted value. @param {boolean} [opts.persistent=true] - Whether to persist the Replicant's value to disk on every change. Persisted values are re-loaded on startup. @param {string} [opts.schemaPath] - The filepath at which to look for a JSON Schema for this Replicant. Defaults to `nodecg/bundles/${bundleName}/schemas/${replicantName}.json`.
[ "Finds", "or", "declares", "a", "Replicant", ".", "If", "a", "Replicant", "with", "the", "given", "name", "is", "already", "present", "in", "namespace", "returns", "that", "existing", "Replicant", ".", "Else", "declares", "a", "new", "Replicant", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/replicator.js#L216-L223
17,286
nodecg/nodecg
lib/replicator.js
emitToClients
function emitToClients(namespace, eventName, data) { // Emit to clients (in the given namespace's room) using Socket.IO log.replicants('emitting %s to %s:', eventName, namespace, data); io.to(`replicant:${namespace}`).emit(eventName, data); }
javascript
function emitToClients(namespace, eventName, data) { // Emit to clients (in the given namespace's room) using Socket.IO log.replicants('emitting %s to %s:', eventName, namespace, data); io.to(`replicant:${namespace}`).emit(eventName, data); }
[ "function", "emitToClients", "(", "namespace", ",", "eventName", ",", "data", ")", "{", "// Emit to clients (in the given namespace's room) using Socket.IO", "log", ".", "replicants", "(", "'emitting %s to %s:'", ",", "eventName", ",", "namespace", ",", "data", ")", ";", "io", ".", "to", "(", "`", "${", "namespace", "}", "`", ")", ".", "emit", "(", "eventName", ",", "data", ")", ";", "}" ]
Emits an event to all remote Socket.IO listeners. @param namespace {string} - The namespace in which to emit this event. Only applies to Socket.IO listeners. @param eventName {string} - The name of the event to emit. @param data {*} - The data to emit with the event.
[ "Emits", "an", "event", "to", "all", "remote", "Socket", ".", "IO", "listeners", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/replicator.js#L231-L235
17,287
nodecg/nodecg
lib/bundle-manager.js
resetBackoffTimer
function resetBackoffTimer() { clearTimeout(backoffTimer); backoffTimer = setTimeout(() => { backoffTimer = null; for (const bundleName in hasChanged) { /* istanbul ignore if: Standard hasOwnProperty check, doesn't need to be tested */ if (!{}.hasOwnProperty.call(hasChanged, bundleName)) { continue; } log.debug('Backoff finished, emitting change event for', bundleName); handleChange(bundleName); } hasChanged = {}; }, 500); }
javascript
function resetBackoffTimer() { clearTimeout(backoffTimer); backoffTimer = setTimeout(() => { backoffTimer = null; for (const bundleName in hasChanged) { /* istanbul ignore if: Standard hasOwnProperty check, doesn't need to be tested */ if (!{}.hasOwnProperty.call(hasChanged, bundleName)) { continue; } log.debug('Backoff finished, emitting change event for', bundleName); handleChange(bundleName); } hasChanged = {}; }, 500); }
[ "function", "resetBackoffTimer", "(", ")", "{", "clearTimeout", "(", "backoffTimer", ")", ";", "backoffTimer", "=", "setTimeout", "(", "(", ")", "=>", "{", "backoffTimer", "=", "null", ";", "for", "(", "const", "bundleName", "in", "hasChanged", ")", "{", "/* istanbul ignore if: Standard hasOwnProperty check, doesn't need to be tested */", "if", "(", "!", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "hasChanged", ",", "bundleName", ")", ")", "{", "continue", ";", "}", "log", ".", "debug", "(", "'Backoff finished, emitting change event for'", ",", "bundleName", ")", ";", "handleChange", "(", "bundleName", ")", ";", "}", "hasChanged", "=", "{", "}", ";", "}", ",", "500", ")", ";", "}" ]
Resets the backoff timer used to avoid event thrashing when many files change rapidly.
[ "Resets", "the", "backoff", "timer", "used", "to", "avoid", "event", "thrashing", "when", "many", "files", "change", "rapidly", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/bundle-manager.js#L311-L327
17,288
nodecg/nodecg
lib/bundle-manager.js
isPanelHTMLFile
function isPanelHTMLFile(bundleName, filePath) { const bundle = module.exports.find(bundleName); if (bundle) { return bundle.dashboard.panels.some(panel => { return panel.path.endsWith(filePath); }); } return false; }
javascript
function isPanelHTMLFile(bundleName, filePath) { const bundle = module.exports.find(bundleName); if (bundle) { return bundle.dashboard.panels.some(panel => { return panel.path.endsWith(filePath); }); } return false; }
[ "function", "isPanelHTMLFile", "(", "bundleName", ",", "filePath", ")", "{", "const", "bundle", "=", "module", ".", "exports", ".", "find", "(", "bundleName", ")", ";", "if", "(", "bundle", ")", "{", "return", "bundle", ".", "dashboard", ".", "panels", ".", "some", "(", "panel", "=>", "{", "return", "panel", ".", "path", ".", "endsWith", "(", "filePath", ")", ";", "}", ")", ";", "}", "return", "false", ";", "}" ]
Checks if a given path is a panel HTML file of a given bundle. @param bundleName {String} @param filePath {String} @returns {Boolean} @private
[ "Checks", "if", "a", "given", "path", "is", "a", "panel", "HTML", "file", "of", "a", "given", "bundle", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/bundle-manager.js#L346-L355
17,289
nodecg/nodecg
lib/bundle-manager.js
isManifest
function isManifest(bundleName, filePath) { return path.dirname(filePath).endsWith(bundleName) && path.basename(filePath) === 'package.json'; }
javascript
function isManifest(bundleName, filePath) { return path.dirname(filePath).endsWith(bundleName) && path.basename(filePath) === 'package.json'; }
[ "function", "isManifest", "(", "bundleName", ",", "filePath", ")", "{", "return", "path", ".", "dirname", "(", "filePath", ")", ".", "endsWith", "(", "bundleName", ")", "&&", "path", ".", "basename", "(", "filePath", ")", "===", "'package.json'", ";", "}" ]
Checks if a given path is the manifest file for a given bundle. @param bundleName {String} @param filePath {String} @returns {Boolean} @private
[ "Checks", "if", "a", "given", "path", "is", "the", "manifest", "file", "for", "a", "given", "bundle", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/bundle-manager.js#L364-L366
17,290
nodecg/nodecg
lib/api.js
_wrapAcknowledgement
function _wrapAcknowledgement(ack) { let handled = false; const wrappedAck = function (firstArg, ...restArgs) { if (handled) { throw new Error('Acknowledgement already handled'); } handled = true; if (isError(firstArg)) { firstArg = serializeError(firstArg); } ack(firstArg, ...restArgs); }; Object.defineProperty(wrappedAck, 'handled', { get() { return handled; } }); return wrappedAck; }
javascript
function _wrapAcknowledgement(ack) { let handled = false; const wrappedAck = function (firstArg, ...restArgs) { if (handled) { throw new Error('Acknowledgement already handled'); } handled = true; if (isError(firstArg)) { firstArg = serializeError(firstArg); } ack(firstArg, ...restArgs); }; Object.defineProperty(wrappedAck, 'handled', { get() { return handled; } }); return wrappedAck; }
[ "function", "_wrapAcknowledgement", "(", "ack", ")", "{", "let", "handled", "=", "false", ";", "const", "wrappedAck", "=", "function", "(", "firstArg", ",", "...", "restArgs", ")", "{", "if", "(", "handled", ")", "{", "throw", "new", "Error", "(", "'Acknowledgement already handled'", ")", ";", "}", "handled", "=", "true", ";", "if", "(", "isError", "(", "firstArg", ")", ")", "{", "firstArg", "=", "serializeError", "(", "firstArg", ")", ";", "}", "ack", "(", "firstArg", ",", "...", "restArgs", ")", ";", "}", ";", "Object", ".", "defineProperty", "(", "wrappedAck", ",", "'handled'", ",", "{", "get", "(", ")", "{", "return", "handled", ";", "}", "}", ")", ";", "return", "wrappedAck", ";", "}" ]
By default, Errors get serialized to empty objects when run through JSON.stringify. This function wraps an "acknowledgement" callback and checks if the first argument is an Error. If it is, that Error is serialized _before_ being sent off to Socket.IO for serialization to be sent across the wire. @param ack {Function} @private @ignore @returns {Function}
[ "By", "default", "Errors", "get", "serialized", "to", "empty", "objects", "when", "run", "through", "JSON", ".", "stringify", ".", "This", "function", "wraps", "an", "acknowledgement", "callback", "and", "checks", "if", "the", "first", "argument", "is", "an", "Error", ".", "If", "it", "is", "that", "Error", "is", "serialized", "_before_", "being", "sent", "off", "to", "Socket", ".", "IO", "for", "serialization", "to", "be", "sent", "across", "the", "wire", "." ]
a15fe3bc2069fc1b4495ceba9d885abb7b429763
https://github.com/nodecg/nodecg/blob/a15fe3bc2069fc1b4495ceba9d885abb7b429763/lib/api.js#L833-L856
17,291
dtao/autodoc
autodoc.js
Autodoc
function Autodoc(options) { options = Lazy(options || {}) .defaults(Autodoc.options) .toObject(); this.codeParser = wrapParser(options.codeParser); this.commentParser = wrapParser(options.commentParser); this.markdownParser = wrapParser(options.markdownParser, Autodoc.processInternalLinks); this.highlighter = options.highlighter; this.language = options.language || 'javascript'; this.compiler = options.compiler[this.language]; this.namespaces = options.namespaces || []; this.tags = options.tags || []; this.grep = options.grep; this.javascripts = options.javascripts || []; this.exampleHandlers = exampleHandlers(options.exampleHandlers); this.template = options.template; this.templateEngine = options.templateEngine; this.templatePartials = options.templatePartials; this.extraOptions = options.extraOptions || {}; this.errors = []; if (this.highlighter) { this.highlighter.loadMode(this.language); } }
javascript
function Autodoc(options) { options = Lazy(options || {}) .defaults(Autodoc.options) .toObject(); this.codeParser = wrapParser(options.codeParser); this.commentParser = wrapParser(options.commentParser); this.markdownParser = wrapParser(options.markdownParser, Autodoc.processInternalLinks); this.highlighter = options.highlighter; this.language = options.language || 'javascript'; this.compiler = options.compiler[this.language]; this.namespaces = options.namespaces || []; this.tags = options.tags || []; this.grep = options.grep; this.javascripts = options.javascripts || []; this.exampleHandlers = exampleHandlers(options.exampleHandlers); this.template = options.template; this.templateEngine = options.templateEngine; this.templatePartials = options.templatePartials; this.extraOptions = options.extraOptions || {}; this.errors = []; if (this.highlighter) { this.highlighter.loadMode(this.language); } }
[ "function", "Autodoc", "(", "options", ")", "{", "options", "=", "Lazy", "(", "options", "||", "{", "}", ")", ".", "defaults", "(", "Autodoc", ".", "options", ")", ".", "toObject", "(", ")", ";", "this", ".", "codeParser", "=", "wrapParser", "(", "options", ".", "codeParser", ")", ";", "this", ".", "commentParser", "=", "wrapParser", "(", "options", ".", "commentParser", ")", ";", "this", ".", "markdownParser", "=", "wrapParser", "(", "options", ".", "markdownParser", ",", "Autodoc", ".", "processInternalLinks", ")", ";", "this", ".", "highlighter", "=", "options", ".", "highlighter", ";", "this", ".", "language", "=", "options", ".", "language", "||", "'javascript'", ";", "this", ".", "compiler", "=", "options", ".", "compiler", "[", "this", ".", "language", "]", ";", "this", ".", "namespaces", "=", "options", ".", "namespaces", "||", "[", "]", ";", "this", ".", "tags", "=", "options", ".", "tags", "||", "[", "]", ";", "this", ".", "grep", "=", "options", ".", "grep", ";", "this", ".", "javascripts", "=", "options", ".", "javascripts", "||", "[", "]", ";", "this", ".", "exampleHandlers", "=", "exampleHandlers", "(", "options", ".", "exampleHandlers", ")", ";", "this", ".", "template", "=", "options", ".", "template", ";", "this", ".", "templateEngine", "=", "options", ".", "templateEngine", ";", "this", ".", "templatePartials", "=", "options", ".", "templatePartials", ";", "this", ".", "extraOptions", "=", "options", ".", "extraOptions", "||", "{", "}", ";", "this", ".", "errors", "=", "[", "]", ";", "if", "(", "this", ".", "highlighter", ")", "{", "this", ".", "highlighter", ".", "loadMode", "(", "this", ".", "language", ")", ";", "}", "}" ]
All of the options Autodoc supports. @typedef {Object} AutodocOptions @property {Parser|function(string):*} codeParser @property {Parser|function(string):*} commentParser @property {Parser|function(string):*} markdownParser @property {Array.<string>} namespaces @property {Array.<string>} tags @property {string} grep @property {Array.<string>} javascripts @property {string} template @property {TemplateEngine} templateEngine @property {Object.<string, string>} templatePartials @property {Array.<ExampleHandler>} exampleHandlers @property {Object} extraOptions @constructor @param {AutodocOptions=} options
[ "All", "of", "the", "options", "Autodoc", "supports", "." ]
6742cf126f2ba4b35126e5984074ce7a89c6826b
https://github.com/dtao/autodoc/blob/6742cf126f2ba4b35126e5984074ce7a89c6826b/autodoc.js#L64-L89
17,292
dtao/autodoc
autodoc.js
splitCamelCase
function splitCamelCase(string) { var matcher = /[^A-Z]([A-Z])|([A-Z])[^A-Z]/g, tokens = [], position = 0, index, match; string || (string = ''); while (match = matcher.exec(string)) { index = typeof match[1] === 'string' ? match.index + 1 : match.index; if (position === index) { continue; } tokens.push(string.substring(position, index).toLowerCase()); position = index; } if (position < string.length) { tokens.push(string.substring(position).toLowerCase()); } return tokens; }
javascript
function splitCamelCase(string) { var matcher = /[^A-Z]([A-Z])|([A-Z])[^A-Z]/g, tokens = [], position = 0, index, match; string || (string = ''); while (match = matcher.exec(string)) { index = typeof match[1] === 'string' ? match.index + 1 : match.index; if (position === index) { continue; } tokens.push(string.substring(position, index).toLowerCase()); position = index; } if (position < string.length) { tokens.push(string.substring(position).toLowerCase()); } return tokens; }
[ "function", "splitCamelCase", "(", "string", ")", "{", "var", "matcher", "=", "/", "[^A-Z]([A-Z])|([A-Z])[^A-Z]", "/", "g", ",", "tokens", "=", "[", "]", ",", "position", "=", "0", ",", "index", ",", "match", ";", "string", "||", "(", "string", "=", "''", ")", ";", "while", "(", "match", "=", "matcher", ".", "exec", "(", "string", ")", ")", "{", "index", "=", "typeof", "match", "[", "1", "]", "===", "'string'", "?", "match", ".", "index", "+", "1", ":", "match", ".", "index", ";", "if", "(", "position", "===", "index", ")", "{", "continue", ";", "}", "tokens", ".", "push", "(", "string", ".", "substring", "(", "position", ",", "index", ")", ".", "toLowerCase", "(", ")", ")", ";", "position", "=", "index", ";", "}", "if", "(", "position", "<", "string", ".", "length", ")", "{", "tokens", ".", "push", "(", "string", ".", "substring", "(", "position", ")", ".", "toLowerCase", "(", ")", ")", ";", "}", "return", "tokens", ";", "}" ]
Splits apart a camelCased string. @private @param {string} string The string to split. @returns {Array.<string>} An array containing the parts of the string. @examples splitCamelCase('fooBarBaz'); // => ['foo', 'bar', 'baz'] splitCamelCase('Foo123Bar'); // => ['foo123', 'bar'] splitCamelCase('XMLHttpRequest'); // => ['xml', 'http', 'request']
[ "Splits", "apart", "a", "camelCased", "string", "." ]
6742cf126f2ba4b35126e5984074ce7a89c6826b
https://github.com/dtao/autodoc/blob/6742cf126f2ba4b35126e5984074ce7a89c6826b/autodoc.js#L1660-L1680
17,293
dtao/autodoc
autodoc.js
divide
function divide(string, divider) { var seam = string.indexOf(divider); if (seam === -1) { return [string]; } return [string.substring(0, seam), string.substring(seam + divider.length)]; }
javascript
function divide(string, divider) { var seam = string.indexOf(divider); if (seam === -1) { return [string]; } return [string.substring(0, seam), string.substring(seam + divider.length)]; }
[ "function", "divide", "(", "string", ",", "divider", ")", "{", "var", "seam", "=", "string", ".", "indexOf", "(", "divider", ")", ";", "if", "(", "seam", "===", "-", "1", ")", "{", "return", "[", "string", "]", ";", "}", "return", "[", "string", ".", "substring", "(", "0", ",", "seam", ")", ",", "string", ".", "substring", "(", "seam", "+", "divider", ".", "length", ")", "]", ";", "}" ]
Splits a string into two parts on either side of a specified divider. @private @param {string} string The string to divide into two parts. @param {string} divider The string used as the pivot point. @returns {Array.<string>} The parts of the string before and after the first occurrence of `divider`, or a 1-element array containing `string` if `divider` wasn't found. @examples divide('hello', 'll') // => ['he', 'o'] divide('banana', 'n') // => ['ba', 'ana'] divide('a->b->c', '->') // => ['a', 'b->c'] divide('foo', 'xyz') // => ['foo'] divide('abc', 'abc') // => ['', '']
[ "Splits", "a", "string", "into", "two", "parts", "on", "either", "side", "of", "a", "specified", "divider", "." ]
6742cf126f2ba4b35126e5984074ce7a89c6826b
https://github.com/dtao/autodoc/blob/6742cf126f2ba4b35126e5984074ce7a89c6826b/autodoc.js#L1733-L1740
17,294
dtao/autodoc
autodoc.js
unindent
function unindent(string, skipFirstLine) { var lines = string.split('\n'), skipFirst = typeof skipFirstLine !== 'undefined' ? skipFirstLine : true, start = skipFirst ? 1 : 0; var indentation, smallestIndentation = Infinity; for (var i = start, len = lines.length; i < len; ++i) { if (isBlank(lines[i])) { continue; } indentation = getIndentation(lines[i]); if (indentation < smallestIndentation) { smallestIndentation = indentation; } } var result = [lines[0]] .concat( lines .slice(1) .map(function(line) { return decreaseIndent(line, smallestIndentation); }) ) .join('\n'); return result; }
javascript
function unindent(string, skipFirstLine) { var lines = string.split('\n'), skipFirst = typeof skipFirstLine !== 'undefined' ? skipFirstLine : true, start = skipFirst ? 1 : 0; var indentation, smallestIndentation = Infinity; for (var i = start, len = lines.length; i < len; ++i) { if (isBlank(lines[i])) { continue; } indentation = getIndentation(lines[i]); if (indentation < smallestIndentation) { smallestIndentation = indentation; } } var result = [lines[0]] .concat( lines .slice(1) .map(function(line) { return decreaseIndent(line, smallestIndentation); }) ) .join('\n'); return result; }
[ "function", "unindent", "(", "string", ",", "skipFirstLine", ")", "{", "var", "lines", "=", "string", ".", "split", "(", "'\\n'", ")", ",", "skipFirst", "=", "typeof", "skipFirstLine", "!==", "'undefined'", "?", "skipFirstLine", ":", "true", ",", "start", "=", "skipFirst", "?", "1", ":", "0", ";", "var", "indentation", ",", "smallestIndentation", "=", "Infinity", ";", "for", "(", "var", "i", "=", "start", ",", "len", "=", "lines", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "if", "(", "isBlank", "(", "lines", "[", "i", "]", ")", ")", "{", "continue", ";", "}", "indentation", "=", "getIndentation", "(", "lines", "[", "i", "]", ")", ";", "if", "(", "indentation", "<", "smallestIndentation", ")", "{", "smallestIndentation", "=", "indentation", ";", "}", "}", "var", "result", "=", "[", "lines", "[", "0", "]", "]", ".", "concat", "(", "lines", ".", "slice", "(", "1", ")", ".", "map", "(", "function", "(", "line", ")", "{", "return", "decreaseIndent", "(", "line", ",", "smallestIndentation", ")", ";", "}", ")", ")", ".", "join", "(", "'\\n'", ")", ";", "return", "result", ";", "}" ]
Unindents a multiline string based on the indentation level of the least- indented line. @private @param {string} string The string to unindent. @param {boolean} skipFirstLine Whether or not to skip the first line for the purpose of determining proper indentation (defaults to `true`). @returns {string} A new string that has effectively been unindented. @examples unindent('foo\n bar\n baz'); // => 'foo\nbar\nbaz' unindent('foo\n bar\n baz'); // => 'foo\nbar\n baz' unindent('foo\n\n bar\n baz'); // => 'foo\n\nbar\nbaz' unindent('foo\n\n bar\n baz'); // => 'foo\n\n bar\nbaz'
[ "Unindents", "a", "multiline", "string", "based", "on", "the", "indentation", "level", "of", "the", "least", "-", "indented", "line", "." ]
6742cf126f2ba4b35126e5984074ce7a89c6826b
https://github.com/dtao/autodoc/blob/6742cf126f2ba4b35126e5984074ce7a89c6826b/autodoc.js#L1758-L1784
17,295
dtao/autodoc
autodoc.js
firstLine
function firstLine(string) { var lineBreak = string.indexOf('\n'); if (lineBreak === -1) { return string; } return string.substring(0, lineBreak) + ' (...)'; }
javascript
function firstLine(string) { var lineBreak = string.indexOf('\n'); if (lineBreak === -1) { return string; } return string.substring(0, lineBreak) + ' (...)'; }
[ "function", "firstLine", "(", "string", ")", "{", "var", "lineBreak", "=", "string", ".", "indexOf", "(", "'\\n'", ")", ";", "if", "(", "lineBreak", "===", "-", "1", ")", "{", "return", "string", ";", "}", "return", "string", ".", "substring", "(", "0", ",", "lineBreak", ")", "+", "' (...)'", ";", "}" ]
Takes the first line of a string and, if there's more, appends '...' to indicate as much. @private @param {string} string The string whose first line you want to get. @returns {string} The first line of the string. @examples firstLine('foo'); // => 'foo' firstLine('foo\nbar'); // => 'foo (...)'
[ "Takes", "the", "first", "line", "of", "a", "string", "and", "if", "there", "s", "more", "appends", "...", "to", "indicate", "as", "much", "." ]
6742cf126f2ba4b35126e5984074ce7a89c6826b
https://github.com/dtao/autodoc/blob/6742cf126f2ba4b35126e5984074ce7a89c6826b/autodoc.js#L1869-L1877
17,296
dtao/autodoc
autodoc.js
exampleHandlers
function exampleHandlers(customHandlers) { return (customHandlers || []).concat([ { pattern: /^(\w[\w\.\(\)\[\]'"]*)\s*===?\s*(.*)$/, template: 'equality', data: function(match) { return { left: match[1], right: match[2] }; } }, { pattern: /^(\w[\w\.\(\)\[\]'"]*)\s*!==?\s*(.*)$/, template: 'inequality', data: function(match) { return { left: match[1], right: match[2] }; } }, { pattern: /^instanceof (.*)$/, template: 'instanceof', data: function(match) { return { type: match[1] }; } }, { pattern: /^NaN$/, template: 'nan' }, { pattern: /^throws$/, template: 'throws' }, { pattern: /^calls\s+(\w+)\s+(\d+)(?:\s+times?)?$/, template: 'calls', data: function(match) { return { callback: match[1], count: getCount(match[2]) }; } }, { pattern: /^calls\s+(\w+)\s+(\d+)\s+times? asynchronously$/, template: 'calls_async', data: function(match) { return { callback: match[1], count: getCount(match[2]) }; } }, { pattern: /^=~\s+\/(.*)\/$/, template: 'string_proximity', data: function(match) { return { pattern: match[1] }; } }, { pattern: /^=~\s+\[(.*),?\s*\.\.\.\s*\]$/, template: 'array_inclusion', data: function(match) { return { elements: match[1] }; } }, { pattern: /^one of (.*)$/, template: 'array_membership', data: function(match) { return { values: match[1] }; } }, { pattern: /^=~\s+\[(.*)\]$/, template: 'array_proximity', data: function(match) { return { elements: match[1] }; } }, { pattern: /^\[(.*),?\s*\.\.\.\s*\]$/, template: 'array_head', data: function(match) { return { head: match[1] }; } }, { pattern: /^\[\s*\.\.\.,?\s*(.*)\]$/, template: 'array_tail', data: function(match) { return { tail: match[1] }; } }, { pattern: /\{([\s\S]*),?[\s\n]*\.\.\.[\s\n]*\}/, template: 'object_proximity', data: function(match) { return { properties: match[1] }; } } ]); }
javascript
function exampleHandlers(customHandlers) { return (customHandlers || []).concat([ { pattern: /^(\w[\w\.\(\)\[\]'"]*)\s*===?\s*(.*)$/, template: 'equality', data: function(match) { return { left: match[1], right: match[2] }; } }, { pattern: /^(\w[\w\.\(\)\[\]'"]*)\s*!==?\s*(.*)$/, template: 'inequality', data: function(match) { return { left: match[1], right: match[2] }; } }, { pattern: /^instanceof (.*)$/, template: 'instanceof', data: function(match) { return { type: match[1] }; } }, { pattern: /^NaN$/, template: 'nan' }, { pattern: /^throws$/, template: 'throws' }, { pattern: /^calls\s+(\w+)\s+(\d+)(?:\s+times?)?$/, template: 'calls', data: function(match) { return { callback: match[1], count: getCount(match[2]) }; } }, { pattern: /^calls\s+(\w+)\s+(\d+)\s+times? asynchronously$/, template: 'calls_async', data: function(match) { return { callback: match[1], count: getCount(match[2]) }; } }, { pattern: /^=~\s+\/(.*)\/$/, template: 'string_proximity', data: function(match) { return { pattern: match[1] }; } }, { pattern: /^=~\s+\[(.*),?\s*\.\.\.\s*\]$/, template: 'array_inclusion', data: function(match) { return { elements: match[1] }; } }, { pattern: /^one of (.*)$/, template: 'array_membership', data: function(match) { return { values: match[1] }; } }, { pattern: /^=~\s+\[(.*)\]$/, template: 'array_proximity', data: function(match) { return { elements: match[1] }; } }, { pattern: /^\[(.*),?\s*\.\.\.\s*\]$/, template: 'array_head', data: function(match) { return { head: match[1] }; } }, { pattern: /^\[\s*\.\.\.,?\s*(.*)\]$/, template: 'array_tail', data: function(match) { return { tail: match[1] }; } }, { pattern: /\{([\s\S]*),?[\s\n]*\.\.\.[\s\n]*\}/, template: 'object_proximity', data: function(match) { return { properties: match[1] }; } } ]); }
[ "function", "exampleHandlers", "(", "customHandlers", ")", "{", "return", "(", "customHandlers", "||", "[", "]", ")", ".", "concat", "(", "[", "{", "pattern", ":", "/", "^(\\w[\\w\\.\\(\\)\\[\\]'\"]*)\\s*===?\\s*(.*)$", "/", ",", "template", ":", "'equality'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "left", ":", "match", "[", "1", "]", ",", "right", ":", "match", "[", "2", "]", "}", ";", "}", "}", ",", "{", "pattern", ":", "/", "^(\\w[\\w\\.\\(\\)\\[\\]'\"]*)\\s*!==?\\s*(.*)$", "/", ",", "template", ":", "'inequality'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "left", ":", "match", "[", "1", "]", ",", "right", ":", "match", "[", "2", "]", "}", ";", "}", "}", ",", "{", "pattern", ":", "/", "^instanceof (.*)$", "/", ",", "template", ":", "'instanceof'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "type", ":", "match", "[", "1", "]", "}", ";", "}", "}", ",", "{", "pattern", ":", "/", "^NaN$", "/", ",", "template", ":", "'nan'", "}", ",", "{", "pattern", ":", "/", "^throws$", "/", ",", "template", ":", "'throws'", "}", ",", "{", "pattern", ":", "/", "^calls\\s+(\\w+)\\s+(\\d+)(?:\\s+times?)?$", "/", ",", "template", ":", "'calls'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "callback", ":", "match", "[", "1", "]", ",", "count", ":", "getCount", "(", "match", "[", "2", "]", ")", "}", ";", "}", "}", ",", "{", "pattern", ":", "/", "^calls\\s+(\\w+)\\s+(\\d+)\\s+times? asynchronously$", "/", ",", "template", ":", "'calls_async'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "callback", ":", "match", "[", "1", "]", ",", "count", ":", "getCount", "(", "match", "[", "2", "]", ")", "}", ";", "}", "}", ",", "{", "pattern", ":", "/", "^=~\\s+\\/(.*)\\/$", "/", ",", "template", ":", "'string_proximity'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "pattern", ":", "match", "[", "1", "]", "}", ";", "}", "}", ",", "{", "pattern", ":", "/", "^=~\\s+\\[(.*),?\\s*\\.\\.\\.\\s*\\]$", "/", ",", "template", ":", "'array_inclusion'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "elements", ":", "match", "[", "1", "]", "}", ";", "}", "}", ",", "{", "pattern", ":", "/", "^one of (.*)$", "/", ",", "template", ":", "'array_membership'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "values", ":", "match", "[", "1", "]", "}", ";", "}", "}", ",", "{", "pattern", ":", "/", "^=~\\s+\\[(.*)\\]$", "/", ",", "template", ":", "'array_proximity'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "elements", ":", "match", "[", "1", "]", "}", ";", "}", "}", ",", "{", "pattern", ":", "/", "^\\[(.*),?\\s*\\.\\.\\.\\s*\\]$", "/", ",", "template", ":", "'array_head'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "head", ":", "match", "[", "1", "]", "}", ";", "}", "}", ",", "{", "pattern", ":", "/", "^\\[\\s*\\.\\.\\.,?\\s*(.*)\\]$", "/", ",", "template", ":", "'array_tail'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "tail", ":", "match", "[", "1", "]", "}", ";", "}", "}", ",", "{", "pattern", ":", "/", "\\{([\\s\\S]*),?[\\s\\n]*\\.\\.\\.[\\s\\n]*\\}", "/", ",", "template", ":", "'object_proximity'", ",", "data", ":", "function", "(", "match", ")", "{", "return", "{", "properties", ":", "match", "[", "1", "]", "}", ";", "}", "}", "]", ")", ";", "}" ]
The default handlers defined for examples.
[ "The", "default", "handlers", "defined", "for", "examples", "." ]
6742cf126f2ba4b35126e5984074ce7a89c6826b
https://github.com/dtao/autodoc/blob/6742cf126f2ba4b35126e5984074ce7a89c6826b/autodoc.js#L1993-L2100
17,297
dtao/autodoc
example/redundant.js
function(string, delimiter) { var start = 0, parts = [], index = string.indexOf(delimiter); if (delimiter === '') { while (index < string.length) { parts.push(string.charAt(index++)); } return parts; } while (index !== -1 & index < string.length) { parts.push(string.substring(start, index)); start = index + delimiter.length; index = string.indexOf(delimiter, start); } if (start < string.length) { parts.push(string.substring(start)); } return parts; }
javascript
function(string, delimiter) { var start = 0, parts = [], index = string.indexOf(delimiter); if (delimiter === '') { while (index < string.length) { parts.push(string.charAt(index++)); } return parts; } while (index !== -1 & index < string.length) { parts.push(string.substring(start, index)); start = index + delimiter.length; index = string.indexOf(delimiter, start); } if (start < string.length) { parts.push(string.substring(start)); } return parts; }
[ "function", "(", "string", ",", "delimiter", ")", "{", "var", "start", "=", "0", ",", "parts", "=", "[", "]", ",", "index", "=", "string", ".", "indexOf", "(", "delimiter", ")", ";", "if", "(", "delimiter", "===", "''", ")", "{", "while", "(", "index", "<", "string", ".", "length", ")", "{", "parts", ".", "push", "(", "string", ".", "charAt", "(", "index", "++", ")", ")", ";", "}", "return", "parts", ";", "}", "while", "(", "index", "!==", "-", "1", "&", "index", "<", "string", ".", "length", ")", "{", "parts", ".", "push", "(", "string", ".", "substring", "(", "start", ",", "index", ")", ")", ";", "start", "=", "index", "+", "delimiter", ".", "length", ";", "index", "=", "string", ".", "indexOf", "(", "delimiter", ",", "start", ")", ";", "}", "if", "(", "start", "<", "string", ".", "length", ")", "{", "parts", ".", "push", "(", "string", ".", "substring", "(", "start", ")", ")", ";", "}", "return", "parts", ";", "}" ]
Splits a string by a given delimiter. This duplicates `String.prototype.split`. @memberOf R.strings @param {string} string The string to split. @param {string} delimiter The delimiter used to split the string. @returns {Array.<string>} An array of the parts separated by the given delimiter. @examples R.strings.split('1,2,3', ',') // => ['1', '2', '3'] R.strings.split('hello', 'ell') // => ['h', 'o'] R.strings.split('hello', '') // => ['h', 'e', ...] R.strings.split('goodbye', '') // => [..., 'b', 'y', 'e'] R.strings.split('12345', '') // =~ ['5', '4', '3', '2', '1'] @benchmarks R.strings.split('foo bar baz', ' ') // redundant.js 'foo bar baz'.split(' ') // native
[ "Splits", "a", "string", "by", "a", "given", "delimiter", ".", "This", "duplicates", "String", ".", "prototype", ".", "split", "." ]
6742cf126f2ba4b35126e5984074ce7a89c6826b
https://github.com/dtao/autodoc/blob/6742cf126f2ba4b35126e5984074ce7a89c6826b/example/redundant.js#L251-L274
17,298
dtao/autodoc
example/redundant.js
function(string) { var chars = new Array(string.length); var charCode; for (var i = 0, len = chars.length; i < len; ++i) { charCode = string.charCodeAt(i); if (charCode > 96 && charCode < 123) { charCode -= 32; } chars[i] = String.fromCharCode(charCode); } return chars.join(''); }
javascript
function(string) { var chars = new Array(string.length); var charCode; for (var i = 0, len = chars.length; i < len; ++i) { charCode = string.charCodeAt(i); if (charCode > 96 && charCode < 123) { charCode -= 32; } chars[i] = String.fromCharCode(charCode); } return chars.join(''); }
[ "function", "(", "string", ")", "{", "var", "chars", "=", "new", "Array", "(", "string", ".", "length", ")", ";", "var", "charCode", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "chars", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "charCode", "=", "string", ".", "charCodeAt", "(", "i", ")", ";", "if", "(", "charCode", ">", "96", "&&", "charCode", "<", "123", ")", "{", "charCode", "-=", "32", ";", "}", "chars", "[", "i", "]", "=", "String", ".", "fromCharCode", "(", "charCode", ")", ";", "}", "return", "chars", ".", "join", "(", "''", ")", ";", "}" ]
Converts all of a string's characters to uppercase. This duplicates `String.prototype.toUpperCase`. @memberOf R.strings @param {string} string The string to upcase. @returns {string} The string w/ characters capitalized. @examples R.strings.toUpperCase('foo') // => 'FOO' R.strings.toUpperCase(' foo ') // =~ /FOO/
[ "Converts", "all", "of", "a", "string", "s", "characters", "to", "uppercase", ".", "This", "duplicates", "String", ".", "prototype", ".", "toUpperCase", "." ]
6742cf126f2ba4b35126e5984074ce7a89c6826b
https://github.com/dtao/autodoc/blob/6742cf126f2ba4b35126e5984074ce7a89c6826b/example/redundant.js#L288-L302
17,299
dtao/autodoc
example/nodeTypes.js
printEvens
function printEvens(N) { try { var i = -1; beginning: do { if (++i < N) { if (i % 2 !== 0) { continue beginning; } printNumber(i); } break; } while (true); } catch (e) { debugger; } }
javascript
function printEvens(N) { try { var i = -1; beginning: do { if (++i < N) { if (i % 2 !== 0) { continue beginning; } printNumber(i); } break; } while (true); } catch (e) { debugger; } }
[ "function", "printEvens", "(", "N", ")", "{", "try", "{", "var", "i", "=", "-", "1", ";", "beginning", ":", "do", "{", "if", "(", "++", "i", "<", "N", ")", "{", "if", "(", "i", "%", "2", "!==", "0", ")", "{", "continue", "beginning", ";", "}", "printNumber", "(", "i", ")", ";", "}", "break", ";", "}", "while", "(", "true", ")", ";", "}", "catch", "(", "e", ")", "{", "debugger", ";", "}", "}" ]
Prints the even numbers up to N. @global @param {number} N
[ "Prints", "the", "even", "numbers", "up", "to", "N", "." ]
6742cf126f2ba4b35126e5984074ce7a89c6826b
https://github.com/dtao/autodoc/blob/6742cf126f2ba4b35126e5984074ce7a89c6826b/example/nodeTypes.js#L12-L33