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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
ciena-frost/ember-frost-demo-components
broccoli-raw.js
readDirectory
function readDirectory (srcDir) { let srcTree = {} const entries = fs.readdirSync(srcDir) entries.forEach(function (entry) { const filePath = path.join(srcDir, entry) if (fs.lstatSync(filePath).isDirectory()) { srcTree[entry] = readDirectory(filePath) } else { srcTree[entry] = fs.readFileSync(filePath, { encoding: 'utf8' }) } }) return srcTree }
javascript
function readDirectory (srcDir) { let srcTree = {} const entries = fs.readdirSync(srcDir) entries.forEach(function (entry) { const filePath = path.join(srcDir, entry) if (fs.lstatSync(filePath).isDirectory()) { srcTree[entry] = readDirectory(filePath) } else { srcTree[entry] = fs.readFileSync(filePath, { encoding: 'utf8' }) } }) return srcTree }
[ "function", "readDirectory", "(", "srcDir", ")", "{", "let", "srcTree", "=", "{", "}", "const", "entries", "=", "fs", ".", "readdirSync", "(", "srcDir", ")", "entries", ".", "forEach", "(", "function", "(", "entry", ")", "{", "const", "filePath", "=", "path", ".", "join", "(", "srcDir", ",", "entry", ")", "if", "(", "fs", ".", "lstatSync", "(", "filePath", ")", ".", "isDirectory", "(", ")", ")", "{", "srcTree", "[", "entry", "]", "=", "readDirectory", "(", "filePath", ")", "}", "else", "{", "srcTree", "[", "entry", "]", "=", "fs", ".", "readFileSync", "(", "filePath", ",", "{", "encoding", ":", "'utf8'", "}", ")", "}", "}", ")", "return", "srcTree", "}" ]
reads a directory into an object @param {String} srcDir - source directory @returns {Object} an object containing the directory file contents
[ "reads", "a", "directory", "into", "an", "object" ]
152466e82fb7e2a880cd166140b32f8912309e36
https://github.com/ciena-frost/ember-frost-demo-components/blob/152466e82fb7e2a880cd166140b32f8912309e36/broccoli-raw.js#L15-L31
train
NatLibFi/marc-record-serializers
src/iso2709.js
parseDirectory
function parseDirectory(dataStr) { let currChar = ''; let directory = ''; let pos = 24; while (currChar !== '\x1E') { currChar = dataStr.charAt(pos); if (currChar !== 'x1E') { directory += currChar; } pos++; if (pos > dataStr.length) { throw new Error('Invalid record'); } } return directory; }
javascript
function parseDirectory(dataStr) { let currChar = ''; let directory = ''; let pos = 24; while (currChar !== '\x1E') { currChar = dataStr.charAt(pos); if (currChar !== 'x1E') { directory += currChar; } pos++; if (pos > dataStr.length) { throw new Error('Invalid record'); } } return directory; }
[ "function", "parseDirectory", "(", "dataStr", ")", "{", "let", "currChar", "=", "''", ";", "let", "directory", "=", "''", ";", "let", "pos", "=", "24", ";", "while", "(", "currChar", "!==", "'\\x1E'", ")", "\\x1E", "{", "currChar", "=", "dataStr", ".", "charAt", "(", "pos", ")", ";", "if", "(", "currChar", "!==", "'x1E'", ")", "{", "directory", "+=", "currChar", ";", "}", "pos", "++", ";", "if", "(", "pos", ">", "dataStr", ".", "length", ")", "{", "throw", "new", "Error", "(", "'Invalid record'", ")", ";", "}", "}", "}" ]
Returns the entire directory starting at position 24. Control character '\x1E' marks the end of directory.
[ "Returns", "the", "entire", "directory", "starting", "at", "position", "24", ".", "Control", "character", "\\", "x1E", "marks", "the", "end", "of", "directory", "." ]
cb1f2cb43d90c596c52c350de1e3798ecc2c90b5
https://github.com/NatLibFi/marc-record-serializers/blob/cb1f2cb43d90c596c52c350de1e3798ecc2c90b5/src/iso2709.js#L143-L162
train
NatLibFi/marc-record-serializers
src/iso2709.js
parseDirectoryEntries
function parseDirectoryEntries(directoryStr) { const directoryEntries = []; let pos = 0; let count = 0; while (directoryStr.length - pos >= 12) { directoryEntries[count] = directoryStr.substring(pos, pos + 12); pos += 12; count++; } return directoryEntries; }
javascript
function parseDirectoryEntries(directoryStr) { const directoryEntries = []; let pos = 0; let count = 0; while (directoryStr.length - pos >= 12) { directoryEntries[count] = directoryStr.substring(pos, pos + 12); pos += 12; count++; } return directoryEntries; }
[ "function", "parseDirectoryEntries", "(", "directoryStr", ")", "{", "const", "directoryEntries", "=", "[", "]", ";", "let", "pos", "=", "0", ";", "let", "count", "=", "0", ";", "while", "(", "directoryStr", ".", "length", "-", "pos", ">=", "12", ")", "{", "directoryEntries", "[", "count", "]", "=", "directoryStr", ".", "substring", "(", "pos", ",", "pos", "+", "12", ")", ";", "pos", "+=", "12", ";", "count", "++", ";", "}", "return", "directoryEntries", ";", "}" ]
Returns an array of 12-character directory entries.
[ "Returns", "an", "array", "of", "12", "-", "character", "directory", "entries", "." ]
cb1f2cb43d90c596c52c350de1e3798ecc2c90b5
https://github.com/NatLibFi/marc-record-serializers/blob/cb1f2cb43d90c596c52c350de1e3798ecc2c90b5/src/iso2709.js#L165-L177
train
NatLibFi/marc-record-serializers
src/iso2709.js
trimNumericField
function trimNumericField(input) { while (input.length > 1 && input.charAt(0) === '0') { input = input.substring(1); } return input; }
javascript
function trimNumericField(input) { while (input.length > 1 && input.charAt(0) === '0') { input = input.substring(1); } return input; }
[ "function", "trimNumericField", "(", "input", ")", "{", "while", "(", "input", ".", "length", ">", "1", "&&", "input", ".", "charAt", "(", "0", ")", "===", "'0'", ")", "{", "input", "=", "input", ".", "substring", "(", "1", ")", ";", "}", "return", "input", ";", "}" ]
Removes leading zeros from a numeric data field.
[ "Removes", "leading", "zeros", "from", "a", "numeric", "data", "field", "." ]
cb1f2cb43d90c596c52c350de1e3798ecc2c90b5
https://github.com/NatLibFi/marc-record-serializers/blob/cb1f2cb43d90c596c52c350de1e3798ecc2c90b5/src/iso2709.js#L180-L186
train
NatLibFi/marc-record-serializers
src/iso2709.js
addLeadingZeros
function addLeadingZeros(numField, length) { while (numField.toString().length < length) { numField = '0' + numField.toString(); } return numField; }
javascript
function addLeadingZeros(numField, length) { while (numField.toString().length < length) { numField = '0' + numField.toString(); } return numField; }
[ "function", "addLeadingZeros", "(", "numField", ",", "length", ")", "{", "while", "(", "numField", ".", "toString", "(", ")", ".", "length", "<", "length", ")", "{", "numField", "=", "'0'", "+", "numField", ".", "toString", "(", ")", ";", "}", "return", "numField", ";", "}" ]
Adds leading zeros to the specified numeric field.
[ "Adds", "leading", "zeros", "to", "the", "specified", "numeric", "field", "." ]
cb1f2cb43d90c596c52c350de1e3798ecc2c90b5
https://github.com/NatLibFi/marc-record-serializers/blob/cb1f2cb43d90c596c52c350de1e3798ecc2c90b5/src/iso2709.js#L289-L295
train
NatLibFi/marc-record-serializers
src/iso2709.js
lengthInUtf8Bytes
function lengthInUtf8Bytes(str) { const m = encodeURIComponent(str).match(/%[89ABab]/g); return str.length + (m ? m.length : 0); }
javascript
function lengthInUtf8Bytes(str) { const m = encodeURIComponent(str).match(/%[89ABab]/g); return str.length + (m ? m.length : 0); }
[ "function", "lengthInUtf8Bytes", "(", "str", ")", "{", "const", "m", "=", "encodeURIComponent", "(", "str", ")", ".", "match", "(", "/", "%[89ABab]", "/", "g", ")", ";", "return", "str", ".", "length", "+", "(", "m", "?", "m", ".", "length", ":", "0", ")", ";", "}" ]
Returns the length of the input string in UTF8 bytes.
[ "Returns", "the", "length", "of", "the", "input", "string", "in", "UTF8", "bytes", "." ]
cb1f2cb43d90c596c52c350de1e3798ecc2c90b5
https://github.com/NatLibFi/marc-record-serializers/blob/cb1f2cb43d90c596c52c350de1e3798ecc2c90b5/src/iso2709.js#L298-L301
train
NatLibFi/marc-record-serializers
src/iso2709.js
utf8Substr
function utf8Substr(str, startInBytes, lengthInBytes) { const strBytes = stringToByteArray(str); const subStrBytes = []; let count = 0; for (let i = startInBytes; count < lengthInBytes; i++) { subStrBytes.push(strBytes[i]); count++; } return byteArrayToString(subStrBytes); // Converts the byte array to a UTF-8 string. // From http://stackoverflow.com/questions/1240408/reading-bytes-from-a-javascript-string?lq=1 function byteArrayToString(byteArray) { let str = ''; for (let i = 0; i < byteArray.length; i++) { str += byteArray[i] <= 0x7F ? byteArray[i] === 0x25 ? '%25' : // % String.fromCharCode(byteArray[i]) : '%' + byteArray[i].toString(16).toUpperCase(); } return decodeURIComponent(str); } }
javascript
function utf8Substr(str, startInBytes, lengthInBytes) { const strBytes = stringToByteArray(str); const subStrBytes = []; let count = 0; for (let i = startInBytes; count < lengthInBytes; i++) { subStrBytes.push(strBytes[i]); count++; } return byteArrayToString(subStrBytes); // Converts the byte array to a UTF-8 string. // From http://stackoverflow.com/questions/1240408/reading-bytes-from-a-javascript-string?lq=1 function byteArrayToString(byteArray) { let str = ''; for (let i = 0; i < byteArray.length; i++) { str += byteArray[i] <= 0x7F ? byteArray[i] === 0x25 ? '%25' : // % String.fromCharCode(byteArray[i]) : '%' + byteArray[i].toString(16).toUpperCase(); } return decodeURIComponent(str); } }
[ "function", "utf8Substr", "(", "str", ",", "startInBytes", ",", "lengthInBytes", ")", "{", "const", "strBytes", "=", "stringToByteArray", "(", "str", ")", ";", "const", "subStrBytes", "=", "[", "]", ";", "let", "count", "=", "0", ";", "for", "(", "let", "i", "=", "startInBytes", ";", "count", "<", "lengthInBytes", ";", "i", "++", ")", "{", "subStrBytes", ".", "push", "(", "strBytes", "[", "i", "]", ")", ";", "count", "++", ";", "}", "return", "byteArrayToString", "(", "subStrBytes", ")", ";", "function", "byteArrayToString", "(", "byteArray", ")", "{", "let", "str", "=", "''", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "byteArray", ".", "length", ";", "i", "++", ")", "{", "str", "+=", "byteArray", "[", "i", "]", "<=", "0x7F", "?", "byteArray", "[", "i", "]", "===", "0x25", "?", "'%25'", ":", "String", ".", "fromCharCode", "(", "byteArray", "[", "i", "]", ")", ":", "'%'", "+", "byteArray", "[", "i", "]", ".", "toString", "(", "16", ")", ".", "toUpperCase", "(", ")", ";", "}", "return", "decodeURIComponent", "(", "str", ")", ";", "}", "}" ]
Returns a UTF-8 substring.
[ "Returns", "a", "UTF", "-", "8", "substring", "." ]
cb1f2cb43d90c596c52c350de1e3798ecc2c90b5
https://github.com/NatLibFi/marc-record-serializers/blob/cb1f2cb43d90c596c52c350de1e3798ecc2c90b5/src/iso2709.js#L305-L328
train
IcarusWorks/ember-cli-deploy-bugsnag
index.js
fetchFilePathsByType
function fetchFilePathsByType(distFiles, basePath, type) { return distFiles .filter(function(filePath) { return new RegExp('assets/.*\\.' + type + '$').test(filePath); }) .map(function(filePath) { return path.join(basePath, filePath); }); }
javascript
function fetchFilePathsByType(distFiles, basePath, type) { return distFiles .filter(function(filePath) { return new RegExp('assets/.*\\.' + type + '$').test(filePath); }) .map(function(filePath) { return path.join(basePath, filePath); }); }
[ "function", "fetchFilePathsByType", "(", "distFiles", ",", "basePath", ",", "type", ")", "{", "return", "distFiles", ".", "filter", "(", "function", "(", "filePath", ")", "{", "return", "new", "RegExp", "(", "'assets/.*\\\\.'", "+", "\\\\", "+", "type", ")", ".", "'$'", "test", ";", "}", ")", ".", "(", "filePath", ")", "map", ";", "}" ]
This function finds all files of a given type inside the `assets` folder of a given build and returns them with a new basePath prepended
[ "This", "function", "finds", "all", "files", "of", "a", "given", "type", "inside", "the", "assets", "folder", "of", "a", "given", "build", "and", "returns", "them", "with", "a", "new", "basePath", "prepended" ]
1153069f19480833808536b7756166b83ff8d275
https://github.com/IcarusWorks/ember-cli-deploy-bugsnag/blob/1153069f19480833808536b7756166b83ff8d275/index.js#L208-L216
train
fanout/node-pubcontrol
etc/browser-demo/src/index.js
main
async function main() { const { window } = webContext(); if (window) { await windowReadiness(window); render(window); bootWebWorker(window); } else { console.warn("No web window. Can't run browser-demo."); } }
javascript
async function main() { const { window } = webContext(); if (window) { await windowReadiness(window); render(window); bootWebWorker(window); } else { console.warn("No web window. Can't run browser-demo."); } }
[ "async", "function", "main", "(", ")", "{", "const", "{", "window", "}", "=", "webContext", "(", ")", ";", "if", "(", "window", ")", "{", "await", "windowReadiness", "(", "window", ")", ";", "render", "(", "window", ")", ";", "bootWebWorker", "(", "window", ")", ";", "}", "else", "{", "console", ".", "warn", "(", "\"No web window. Can't run browser-demo.\"", ")", ";", "}", "}" ]
Main browser-demo. Render a message and boot the web worker.
[ "Main", "browser", "-", "demo", ".", "Render", "a", "message", "and", "boot", "the", "web", "worker", "." ]
e3543553a09e5f62ffedf17bb9b28216c3a987b1
https://github.com/fanout/node-pubcontrol/blob/e3543553a09e5f62ffedf17bb9b28216c3a987b1/etc/browser-demo/src/index.js#L14-L23
train
fanout/node-pubcontrol
etc/browser-demo/src/index.js
render
function render({ document }) { console.debug("rendering"); document.querySelectorAll(".replace-with-pubcontrol").forEach(el => { el.innerHTML = ` <div> <h2>pubcontrol default export</h2> <pre>${JSON.stringify(objectSchema(PubControl), null, 2)}</pre> </div> `; }); }
javascript
function render({ document }) { console.debug("rendering"); document.querySelectorAll(".replace-with-pubcontrol").forEach(el => { el.innerHTML = ` <div> <h2>pubcontrol default export</h2> <pre>${JSON.stringify(objectSchema(PubControl), null, 2)}</pre> </div> `; }); }
[ "function", "render", "(", "{", "document", "}", ")", "{", "console", ".", "debug", "(", "\"rendering\"", ")", ";", "document", ".", "querySelectorAll", "(", "\".replace-with-pubcontrol\"", ")", ".", "forEach", "(", "el", "=>", "{", "el", ".", "innerHTML", "=", "`", "${", "JSON", ".", "stringify", "(", "objectSchema", "(", "PubControl", ")", ",", "null", ",", "2", ")", "}", "`", ";", "}", ")", ";", "}" ]
Render a message showing off pubcontrol. Show it wherever the html has opted into replacement.
[ "Render", "a", "message", "showing", "off", "pubcontrol", ".", "Show", "it", "wherever", "the", "html", "has", "opted", "into", "replacement", "." ]
e3543553a09e5f62ffedf17bb9b28216c3a987b1
https://github.com/fanout/node-pubcontrol/blob/e3543553a09e5f62ffedf17bb9b28216c3a987b1/etc/browser-demo/src/index.js#L29-L39
train
fanout/node-pubcontrol
etc/browser-demo/src/index.js
windowReadiness
function windowReadiness({ document }) { if (document.readyState === "loading") { // Loading hasn't finished yet return new Promise((resolve, reject) => document.addEventListener("DOMContentLoaded", resolve) ); } // it's ready }
javascript
function windowReadiness({ document }) { if (document.readyState === "loading") { // Loading hasn't finished yet return new Promise((resolve, reject) => document.addEventListener("DOMContentLoaded", resolve) ); } // it's ready }
[ "function", "windowReadiness", "(", "{", "document", "}", ")", "{", "if", "(", "document", ".", "readyState", "===", "\"loading\"", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "document", ".", "addEventListener", "(", "\"DOMContentLoaded\"", ",", "resolve", ")", ")", ";", "}", "}" ]
Promise of DOM ready event in the provided document
[ "Promise", "of", "DOM", "ready", "event", "in", "the", "provided", "document" ]
e3543553a09e5f62ffedf17bb9b28216c3a987b1
https://github.com/fanout/node-pubcontrol/blob/e3543553a09e5f62ffedf17bb9b28216c3a987b1/etc/browser-demo/src/index.js#L42-L50
train
fanout/node-pubcontrol
etc/browser-demo/src/index.js
objectSchema
function objectSchema(obj) { const props = Object.entries(obj).reduce( (reduced, [key, val]) => Object.assign(reduced, { [key]: typeof val }), {} ); return props; }
javascript
function objectSchema(obj) { const props = Object.entries(obj).reduce( (reduced, [key, val]) => Object.assign(reduced, { [key]: typeof val }), {} ); return props; }
[ "function", "objectSchema", "(", "obj", ")", "{", "const", "props", "=", "Object", ".", "entries", "(", "obj", ")", ".", "reduce", "(", "(", "reduced", ",", "[", "key", ",", "val", "]", ")", "=>", "Object", ".", "assign", "(", "reduced", ",", "{", "[", "key", "]", ":", "typeof", "val", "}", ")", ",", "{", "}", ")", ";", "return", "props", ";", "}" ]
given an object, return some JSON that describes its structure
[ "given", "an", "object", "return", "some", "JSON", "that", "describes", "its", "structure" ]
e3543553a09e5f62ffedf17bb9b28216c3a987b1
https://github.com/fanout/node-pubcontrol/blob/e3543553a09e5f62ffedf17bb9b28216c3a987b1/etc/browser-demo/src/index.js#L53-L59
train
fanout/node-pubcontrol
etc/browser-demo/src/index.js
bootWebWorker
function bootWebWorker({ Worker }) { const webWorker = Object.assign( new Worker("pubcontrol-browser-demo.webworker.js"), { onmessage: event => { console.debug("Message received from worker", event.data.type, event); } } ); webWorker.postMessage({ type: "Hello", from: "browser", content: "Hello worker. I booted you out here in pubcontrol-browser-demo." }); const url = new URL(global.location.href); const epcp = { uri: url.searchParams.get("epcp.uri"), defaultChannel: url.searchParams.get("epcp.defaultChannel") }; if (![epcp.uri, epcp.defaultChannel].every(Boolean)) { console.warn( "Missing one of ?epcp.uri or ?epcp.defaultChannel query params." ); } webWorker.postMessage({ type: "EPCPConfiguration", ...epcp }); }
javascript
function bootWebWorker({ Worker }) { const webWorker = Object.assign( new Worker("pubcontrol-browser-demo.webworker.js"), { onmessage: event => { console.debug("Message received from worker", event.data.type, event); } } ); webWorker.postMessage({ type: "Hello", from: "browser", content: "Hello worker. I booted you out here in pubcontrol-browser-demo." }); const url = new URL(global.location.href); const epcp = { uri: url.searchParams.get("epcp.uri"), defaultChannel: url.searchParams.get("epcp.defaultChannel") }; if (![epcp.uri, epcp.defaultChannel].every(Boolean)) { console.warn( "Missing one of ?epcp.uri or ?epcp.defaultChannel query params." ); } webWorker.postMessage({ type: "EPCPConfiguration", ...epcp }); }
[ "function", "bootWebWorker", "(", "{", "Worker", "}", ")", "{", "const", "webWorker", "=", "Object", ".", "assign", "(", "new", "Worker", "(", "\"pubcontrol-browser-demo.webworker.js\"", ")", ",", "{", "onmessage", ":", "event", "=>", "{", "console", ".", "debug", "(", "\"Message received from worker\"", ",", "event", ".", "data", ".", "type", ",", "event", ")", ";", "}", "}", ")", ";", "webWorker", ".", "postMessage", "(", "{", "type", ":", "\"Hello\"", ",", "from", ":", "\"browser\"", ",", "content", ":", "\"Hello worker. I booted you out here in pubcontrol-browser-demo.\"", "}", ")", ";", "const", "url", "=", "new", "URL", "(", "global", ".", "location", ".", "href", ")", ";", "const", "epcp", "=", "{", "uri", ":", "url", ".", "searchParams", ".", "get", "(", "\"epcp.uri\"", ")", ",", "defaultChannel", ":", "url", ".", "searchParams", ".", "get", "(", "\"epcp.defaultChannel\"", ")", "}", ";", "if", "(", "!", "[", "epcp", ".", "uri", ",", "epcp", ".", "defaultChannel", "]", ".", "every", "(", "Boolean", ")", ")", "{", "console", ".", "warn", "(", "\"Missing one of ?epcp.uri or ?epcp.defaultChannel query params.\"", ")", ";", "}", "webWorker", ".", "postMessage", "(", "{", "type", ":", "\"EPCPConfiguration\"", ",", "...", "epcp", "}", ")", ";", "}" ]
Create and initialize the browser-demo web worker in a DOM Worker. Send the worker some configuration from this url's query params.
[ "Create", "and", "initialize", "the", "browser", "-", "demo", "web", "worker", "in", "a", "DOM", "Worker", ".", "Send", "the", "worker", "some", "configuration", "from", "this", "url", "s", "query", "params", "." ]
e3543553a09e5f62ffedf17bb9b28216c3a987b1
https://github.com/fanout/node-pubcontrol/blob/e3543553a09e5f62ffedf17bb9b28216c3a987b1/etc/browser-demo/src/index.js#L78-L106
train
gjtorikian/panino-docs
lib/panino/plugins/parsers/javascript/jsd/serializer.js
func
function func(ast) { var params = list(ast["params"]) var id = ast["id"] ? to_s(ast["id"]) : "" return "function " + id + "(" + params + ") " + to_s(ast["body"]) }
javascript
function func(ast) { var params = list(ast["params"]) var id = ast["id"] ? to_s(ast["id"]) : "" return "function " + id + "(" + params + ") " + to_s(ast["body"]) }
[ "function", "func", "(", "ast", ")", "{", "var", "params", "=", "list", "(", "ast", "[", "\"params\"", "]", ")", "var", "id", "=", "ast", "[", "\"id\"", "]", "?", "to_s", "(", "ast", "[", "\"id\"", "]", ")", ":", "\"\"", "return", "\"function \"", "+", "id", "+", "\"(\"", "+", "params", "+", "\") \"", "+", "to_s", "(", "ast", "[", "\"body\"", "]", ")", "}" ]
serializes function declaration or expression
[ "serializes", "function", "declaration", "or", "expression" ]
23ea0355d42875a59f14a065ac3c06d096112ced
https://github.com/gjtorikian/panino-docs/blob/23ea0355d42875a59f14a065ac3c06d096112ced/lib/panino/plugins/parsers/javascript/jsd/serializer.js#L164-L168
train
gjtorikian/panino-docs
lib/panino/plugins/parsers/javascript/jsd/serializer.js
parens
function parens(parent, child) { if (precedence(parent) >= precedence(child)) return to_s(child); else return "(" + to_s(child) + ")"; }
javascript
function parens(parent, child) { if (precedence(parent) >= precedence(child)) return to_s(child); else return "(" + to_s(child) + ")"; }
[ "function", "parens", "(", "parent", ",", "child", ")", "{", "if", "(", "precedence", "(", "parent", ")", ">=", "precedence", "(", "child", ")", ")", "return", "to_s", "(", "child", ")", ";", "else", "return", "\"(\"", "+", "to_s", "(", "child", ")", "+", "\")\"", ";", "}" ]
serializes child node and wraps it inside parenthesis if the precedence rules compared to parent node would require so.
[ "serializes", "child", "node", "and", "wraps", "it", "inside", "parenthesis", "if", "the", "precedence", "rules", "compared", "to", "parent", "node", "would", "require", "so", "." ]
23ea0355d42875a59f14a065ac3c06d096112ced
https://github.com/gjtorikian/panino-docs/blob/23ea0355d42875a59f14a065ac3c06d096112ced/lib/panino/plugins/parsers/javascript/jsd/serializer.js#L187-L192
train
gjtorikian/panino-docs
lib/panino/plugins/parsers/javascript/jsd/serializer.js
precedence
function precedence(ast) { var p = PRECEDENCE[ast["type"]]; if ( _.isNumber(p) ) // represents Fixnum? I'm so sorry. return p; else if ( p && p.constructor === Object ) // p is a {} object return p[ast["operator"]]; else return 0; }
javascript
function precedence(ast) { var p = PRECEDENCE[ast["type"]]; if ( _.isNumber(p) ) // represents Fixnum? I'm so sorry. return p; else if ( p && p.constructor === Object ) // p is a {} object return p[ast["operator"]]; else return 0; }
[ "function", "precedence", "(", "ast", ")", "{", "var", "p", "=", "PRECEDENCE", "[", "ast", "[", "\"type\"", "]", "]", ";", "if", "(", "_", ".", "isNumber", "(", "p", ")", ")", "return", "p", ";", "else", "if", "(", "p", "&&", "p", ".", "constructor", "===", "Object", ")", "return", "p", "[", "ast", "[", "\"operator\"", "]", "]", ";", "else", "return", "0", ";", "}" ]
Returns the precedence of operator represented by given AST node
[ "Returns", "the", "precedence", "of", "operator", "represented", "by", "given", "AST", "node" ]
23ea0355d42875a59f14a065ac3c06d096112ced
https://github.com/gjtorikian/panino-docs/blob/23ea0355d42875a59f14a065ac3c06d096112ced/lib/panino/plugins/parsers/javascript/jsd/serializer.js#L195-L203
train
kaelzhang/neuron.js
lib/module.js
generate_exports
function generate_exports (module) { // # 85 // Before module factory being invoked, mark the module as `loaded` // so we will not execute the factory function again. // `mod.loaded` indicates that a module has already been `require()`d // When there are cyclic dependencies, neuron will not fail. module.loaded = true; // During the execution of factory, // the reference of `module.exports` might be changed. // But we still set the `module.exports` as `{}`, // because the module might be `require()`d during the execution of factory // if cyclic dependency occurs. var exports = module.exports = {}; // TODO: // Calculate `filename` ahead of time var __filename // = module.filename = NEURON_CONF.resolve(module.id); var __dirname = dirname(__filename); // to keep the object mod away from the executing context of factory, // use `factory` instead `mod.factory`, // preventing user from fetching runtime data by 'this' var factory = module.factory; factory(create_require(module), exports, module, __filename, __dirname); return module.exports; }
javascript
function generate_exports (module) { // # 85 // Before module factory being invoked, mark the module as `loaded` // so we will not execute the factory function again. // `mod.loaded` indicates that a module has already been `require()`d // When there are cyclic dependencies, neuron will not fail. module.loaded = true; // During the execution of factory, // the reference of `module.exports` might be changed. // But we still set the `module.exports` as `{}`, // because the module might be `require()`d during the execution of factory // if cyclic dependency occurs. var exports = module.exports = {}; // TODO: // Calculate `filename` ahead of time var __filename // = module.filename = NEURON_CONF.resolve(module.id); var __dirname = dirname(__filename); // to keep the object mod away from the executing context of factory, // use `factory` instead `mod.factory`, // preventing user from fetching runtime data by 'this' var factory = module.factory; factory(create_require(module), exports, module, __filename, __dirname); return module.exports; }
[ "function", "generate_exports", "(", "module", ")", "{", "module", ".", "loaded", "=", "true", ";", "var", "exports", "=", "module", ".", "exports", "=", "{", "}", ";", "var", "__filename", "=", "NEURON_CONF", ".", "resolve", "(", "module", ".", "id", ")", ";", "var", "__dirname", "=", "dirname", "(", "__filename", ")", ";", "var", "factory", "=", "module", ".", "factory", ";", "factory", "(", "create_require", "(", "module", ")", ",", "exports", ",", "module", ",", "__filename", ",", "__dirname", ")", ";", "return", "module", ".", "exports", ";", "}" ]
Generate the exports of the module
[ "Generate", "the", "exports", "of", "the", "module" ]
3e1eed28f08ab14f289f476f886ac7f095036e66
https://github.com/kaelzhang/neuron.js/blob/3e1eed28f08ab14f289f476f886ac7f095036e66/lib/module.js#L135-L164
train
kaelzhang/neuron.js
lib/module.js
get_mod
function get_mod (parsed) { var id = parsed.id; // id -> '@kael/[email protected]/b' return mods[id] || (mods[id] = { // package scope: s: parsed.s, // package name: 'a' n: parsed.n, // package version: '1.1.0' v: parsed.v, // module path: '/b' p: parsed.p, // module id: '[email protected]/b' id: id, // package id: '[email protected]' k: parsed.k, // version map of the current module m: {}, // loading queue l: [], // If there is no path, it must be a main entry. // Actually, there will always be a path when defining a module, // but `get_mod` method is called when a module has been required, // and not loaded and defined. // When we `require('foo')`, `foo` must be a main module of a package. main: !parsed.p // map: {Object} The map of aliases to real module id }); }
javascript
function get_mod (parsed) { var id = parsed.id; // id -> '@kael/[email protected]/b' return mods[id] || (mods[id] = { // package scope: s: parsed.s, // package name: 'a' n: parsed.n, // package version: '1.1.0' v: parsed.v, // module path: '/b' p: parsed.p, // module id: '[email protected]/b' id: id, // package id: '[email protected]' k: parsed.k, // version map of the current module m: {}, // loading queue l: [], // If there is no path, it must be a main entry. // Actually, there will always be a path when defining a module, // but `get_mod` method is called when a module has been required, // and not loaded and defined. // When we `require('foo')`, `foo` must be a main module of a package. main: !parsed.p // map: {Object} The map of aliases to real module id }); }
[ "function", "get_mod", "(", "parsed", ")", "{", "var", "id", "=", "parsed", ".", "id", ";", "return", "mods", "[", "id", "]", "||", "(", "mods", "[", "id", "]", "=", "{", "s", ":", "parsed", ".", "s", ",", "n", ":", "parsed", ".", "n", ",", "v", ":", "parsed", ".", "v", ",", "p", ":", "parsed", ".", "p", ",", "id", ":", "id", ",", "k", ":", "parsed", ".", "k", ",", "m", ":", "{", "}", ",", "l", ":", "[", "]", ",", "main", ":", "!", "parsed", ".", "p", "}", ")", ";", "}" ]
Create a mod
[ "Create", "a", "mod" ]
3e1eed28f08ab14f289f476f886ac7f095036e66
https://github.com/kaelzhang/neuron.js/blob/3e1eed28f08ab14f289f476f886ac7f095036e66/lib/module.js#L207-L236
train
kaelzhang/neuron.js
lib/module.js
create_require
function create_require (env) { function require (id) { // `require('[email protected]')` is prohibited. prohibit_require_id_with_version(id); // When `require()` another module inside the factory, // the module of depdendencies must already been created var module = get_module(id, env, true); return get_exports(module); } // @param {string} id Module identifier. // Since 4.2.0, we only allow to asynchronously load a single module require.async = function(id, callback) { if (callback) { // `require.async('[email protected]')` is prohibited prohibit_require_id_with_version(id); var module = get_module(id, env); // If `require.async` a foreign module, it must be a main entry if (!module.main) { // Or it should be a module inside the current package if (module.n !== env.n) { // Otherwise, we will stop that. return; } module.a = true; } use_module(module, callback); } }; // @param {string} path require.resolve = function (path) { return NEURON_CONF.resolve(parse_id(path, env).id); }; return require; }
javascript
function create_require (env) { function require (id) { // `require('[email protected]')` is prohibited. prohibit_require_id_with_version(id); // When `require()` another module inside the factory, // the module of depdendencies must already been created var module = get_module(id, env, true); return get_exports(module); } // @param {string} id Module identifier. // Since 4.2.0, we only allow to asynchronously load a single module require.async = function(id, callback) { if (callback) { // `require.async('[email protected]')` is prohibited prohibit_require_id_with_version(id); var module = get_module(id, env); // If `require.async` a foreign module, it must be a main entry if (!module.main) { // Or it should be a module inside the current package if (module.n !== env.n) { // Otherwise, we will stop that. return; } module.a = true; } use_module(module, callback); } }; // @param {string} path require.resolve = function (path) { return NEURON_CONF.resolve(parse_id(path, env).id); }; return require; }
[ "function", "create_require", "(", "env", ")", "{", "function", "require", "(", "id", ")", "{", "prohibit_require_id_with_version", "(", "id", ")", ";", "var", "module", "=", "get_module", "(", "id", ",", "env", ",", "true", ")", ";", "return", "get_exports", "(", "module", ")", ";", "}", "require", ".", "async", "=", "function", "(", "id", ",", "callback", ")", "{", "if", "(", "callback", ")", "{", "prohibit_require_id_with_version", "(", "id", ")", ";", "var", "module", "=", "get_module", "(", "id", ",", "env", ")", ";", "if", "(", "!", "module", ".", "main", ")", "{", "if", "(", "module", ".", "n", "!==", "env", ".", "n", ")", "{", "return", ";", "}", "module", ".", "a", "=", "true", ";", "}", "use_module", "(", "module", ",", "callback", ")", ";", "}", "}", ";", "require", ".", "resolve", "=", "function", "(", "path", ")", "{", "return", "NEURON_CONF", ".", "resolve", "(", "parse_id", "(", "path", ",", "env", ")", ".", "id", ")", ";", "}", ";", "return", "require", ";", "}" ]
use the sandbox to specify the environment for every id that required in the current module @param {Object} env The object of the current module. @return {function}
[ "use", "the", "sandbox", "to", "specify", "the", "environment", "for", "every", "id", "that", "required", "in", "the", "current", "module" ]
3e1eed28f08ab14f289f476f886ac7f095036e66
https://github.com/kaelzhang/neuron.js/blob/3e1eed28f08ab14f289f476f886ac7f095036e66/lib/module.js#L261-L301
train
observing/devnull
index.js
type
function type (prop) { var rs = Object.prototype.toString.call(prop); return rs.slice(8, rs.length - 1).toLowerCase(); }
javascript
function type (prop) { var rs = Object.prototype.toString.call(prop); return rs.slice(8, rs.length - 1).toLowerCase(); }
[ "function", "type", "(", "prop", ")", "{", "var", "rs", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "prop", ")", ";", "return", "rs", ".", "slice", "(", "8", ",", "rs", ".", "length", "-", "1", ")", ".", "toLowerCase", "(", ")", ";", "}" ]
Strict type checking. @param {Mixed} prop @returns {String} @api private
[ "Strict", "type", "checking", "." ]
ff99281602feca0cf3bdf0e6d36fedbf1b566523
https://github.com/observing/devnull/blob/ff99281602feca0cf3bdf0e6d36fedbf1b566523/index.js#L21-L24
train
attester/attester
lib/util/child-processes.js
function () { if (processes && processes.length > 0) { for (var i = processes.length - 1; i >= 0; i--) { processes[i].kill(); } } }
javascript
function () { if (processes && processes.length > 0) { for (var i = processes.length - 1; i >= 0; i--) { processes[i].kill(); } } }
[ "function", "(", ")", "{", "if", "(", "processes", "&&", "processes", ".", "length", ">", "0", ")", "{", "for", "(", "var", "i", "=", "processes", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "processes", "[", "i", "]", ".", "kill", "(", ")", ";", "}", "}", "}" ]
Q defer resolving when all processes are closed
[ "Q", "defer", "resolving", "when", "all", "processes", "are", "closed" ]
4ed16ca2e8c1af577b47b6bcfc9575589fc87f83
https://github.com/attester/attester/blob/4ed16ca2e8c1af577b47b6bcfc9575589fc87f83/lib/util/child-processes.js#L21-L27
train
deskpro/apps-dpat
src/main/javascript/Installer/buildStrategies.js
defaultStrategy
function defaultStrategy(projectDir, builder, cb) { const pkg = fs.realpathSync(INSTALLER_PACKAGE); builder.buildFromPackage(pkg, projectDir, cb); }
javascript
function defaultStrategy(projectDir, builder, cb) { const pkg = fs.realpathSync(INSTALLER_PACKAGE); builder.buildFromPackage(pkg, projectDir, cb); }
[ "function", "defaultStrategy", "(", "projectDir", ",", "builder", ",", "cb", ")", "{", "const", "pkg", "=", "fs", ".", "realpathSync", "(", "INSTALLER_PACKAGE", ")", ";", "builder", ".", "buildFromPackage", "(", "pkg", ",", "projectDir", ",", "cb", ")", ";", "}" ]
Builds the installer from a tgz package that comes with dpat. This is the default cause when the app does not have its own installer @param {String} projectDir @param {InstallerBuilder} builder @param {Function} cb
[ "Builds", "the", "installer", "from", "a", "tgz", "package", "that", "comes", "with", "dpat", ".", "This", "is", "the", "default", "cause", "when", "the", "app", "does", "not", "have", "its", "own", "installer" ]
18801791ed5873d511adaa1d91a65ae8cdad2281
https://github.com/deskpro/apps-dpat/blob/18801791ed5873d511adaa1d91a65ae8cdad2281/src/main/javascript/Installer/buildStrategies.js#L17-L21
train
deskpro/apps-dpat
src/main/javascript/Installer/buildStrategies.js
customStrategyInPlace
function customStrategyInPlace(projectDir, builder, cb) { const installerDir = path.resolve(projectDir, "node_modules", "@deskpro", INSTALLER_PACKAGE_NAME); const customInstallerTarget = path.resolve(installerDir, "src", "settings"); shelljs.rm('-rf', customInstallerTarget); const copyOptions = { overwrite: true, expand: true, dot: true }; function onCustomInstallerFilesReady (err) { builder.buildFromSource(installerDir, projectDir); cb(); } let customInstallerSrc = path.resolve(projectDir, "src", "installer"); customInstallerSrc = fs.realpathSync(customInstallerSrc); copy(customInstallerSrc, customInstallerTarget, copyOptions, onCustomInstallerFilesReady); }
javascript
function customStrategyInPlace(projectDir, builder, cb) { const installerDir = path.resolve(projectDir, "node_modules", "@deskpro", INSTALLER_PACKAGE_NAME); const customInstallerTarget = path.resolve(installerDir, "src", "settings"); shelljs.rm('-rf', customInstallerTarget); const copyOptions = { overwrite: true, expand: true, dot: true }; function onCustomInstallerFilesReady (err) { builder.buildFromSource(installerDir, projectDir); cb(); } let customInstallerSrc = path.resolve(projectDir, "src", "installer"); customInstallerSrc = fs.realpathSync(customInstallerSrc); copy(customInstallerSrc, customInstallerTarget, copyOptions, onCustomInstallerFilesReady); }
[ "function", "customStrategyInPlace", "(", "projectDir", ",", "builder", ",", "cb", ")", "{", "const", "installerDir", "=", "path", ".", "resolve", "(", "projectDir", ",", "\"node_modules\"", ",", "\"@deskpro\"", ",", "INSTALLER_PACKAGE_NAME", ")", ";", "const", "customInstallerTarget", "=", "path", ".", "resolve", "(", "installerDir", ",", "\"src\"", ",", "\"settings\"", ")", ";", "shelljs", ".", "rm", "(", "'-rf'", ",", "customInstallerTarget", ")", ";", "const", "copyOptions", "=", "{", "overwrite", ":", "true", ",", "expand", ":", "true", ",", "dot", ":", "true", "}", ";", "function", "onCustomInstallerFilesReady", "(", "err", ")", "{", "builder", ".", "buildFromSource", "(", "installerDir", ",", "projectDir", ")", ";", "cb", "(", ")", ";", "}", "let", "customInstallerSrc", "=", "path", ".", "resolve", "(", "projectDir", ",", "\"src\"", ",", "\"installer\"", ")", ";", "customInstallerSrc", "=", "fs", ".", "realpathSync", "(", "customInstallerSrc", ")", ";", "copy", "(", "customInstallerSrc", ",", "customInstallerTarget", ",", "copyOptions", ",", "onCustomInstallerFilesReady", ")", ";", "}" ]
Builds the installer in its own dist folder, useful in dev mode because it does not copy all 4k packages @param {String} projectDir @param {InstallerBuilder} builder @param {Function} cb
[ "Builds", "the", "installer", "in", "its", "own", "dist", "folder", "useful", "in", "dev", "mode", "because", "it", "does", "not", "copy", "all", "4k", "packages" ]
18801791ed5873d511adaa1d91a65ae8cdad2281
https://github.com/deskpro/apps-dpat/blob/18801791ed5873d511adaa1d91a65ae8cdad2281/src/main/javascript/Installer/buildStrategies.js#L30-L47
train
deskpro/apps-dpat
src/main/javascript/Installer/buildStrategies.js
customStrategy
function customStrategy(projectDir, builder, cb) { const dest = builder.getTargetDestination(projectDir); shelljs.rm('-rf', dest); const copyOptions = { overwrite: true, expand: true, dot: true }; const onCustomInstallerFilesReady = function (err) { builder.buildFromSource(dest, projectDir); cb(); }; const onInstallerFilesReady = function (err) { if (err) { cb(err); return; } let customInstallerSrc = path.resolve(projectDir, "src", "installer"); customInstallerSrc = fs.realpathSync(customInstallerSrc); const customInstallerTarget = path.resolve(dest, "src", "settings"); copy(customInstallerSrc, customInstallerTarget, copyOptions, onCustomInstallerFilesReady); }; let installerDir = path.resolve(projectDir, "node_modules", "@deskpro", INSTALLER_PACKAGE_NAME); installerDir = fs.realpathSync(installerDir); copy(installerDir, dest, copyOptions, onInstallerFilesReady); }
javascript
function customStrategy(projectDir, builder, cb) { const dest = builder.getTargetDestination(projectDir); shelljs.rm('-rf', dest); const copyOptions = { overwrite: true, expand: true, dot: true }; const onCustomInstallerFilesReady = function (err) { builder.buildFromSource(dest, projectDir); cb(); }; const onInstallerFilesReady = function (err) { if (err) { cb(err); return; } let customInstallerSrc = path.resolve(projectDir, "src", "installer"); customInstallerSrc = fs.realpathSync(customInstallerSrc); const customInstallerTarget = path.resolve(dest, "src", "settings"); copy(customInstallerSrc, customInstallerTarget, copyOptions, onCustomInstallerFilesReady); }; let installerDir = path.resolve(projectDir, "node_modules", "@deskpro", INSTALLER_PACKAGE_NAME); installerDir = fs.realpathSync(installerDir); copy(installerDir, dest, copyOptions, onInstallerFilesReady); }
[ "function", "customStrategy", "(", "projectDir", ",", "builder", ",", "cb", ")", "{", "const", "dest", "=", "builder", ".", "getTargetDestination", "(", "projectDir", ")", ";", "shelljs", ".", "rm", "(", "'-rf'", ",", "dest", ")", ";", "const", "copyOptions", "=", "{", "overwrite", ":", "true", ",", "expand", ":", "true", ",", "dot", ":", "true", "}", ";", "const", "onCustomInstallerFilesReady", "=", "function", "(", "err", ")", "{", "builder", ".", "buildFromSource", "(", "dest", ",", "projectDir", ")", ";", "cb", "(", ")", ";", "}", ";", "const", "onInstallerFilesReady", "=", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "return", ";", "}", "let", "customInstallerSrc", "=", "path", ".", "resolve", "(", "projectDir", ",", "\"src\"", ",", "\"installer\"", ")", ";", "customInstallerSrc", "=", "fs", ".", "realpathSync", "(", "customInstallerSrc", ")", ";", "const", "customInstallerTarget", "=", "path", ".", "resolve", "(", "dest", ",", "\"src\"", ",", "\"settings\"", ")", ";", "copy", "(", "customInstallerSrc", ",", "customInstallerTarget", ",", "copyOptions", ",", "onCustomInstallerFilesReady", ")", ";", "}", ";", "let", "installerDir", "=", "path", ".", "resolve", "(", "projectDir", ",", "\"node_modules\"", ",", "\"@deskpro\"", ",", "INSTALLER_PACKAGE_NAME", ")", ";", "installerDir", "=", "fs", ".", "realpathSync", "(", "installerDir", ")", ";", "copy", "(", "installerDir", ",", "dest", ",", "copyOptions", ",", "onInstallerFilesReady", ")", ";", "}" ]
Builds the installer under the app's own target folder @param {String} projectDir @param {InstallerBuilder} builder @param {Function} cb
[ "Builds", "the", "installer", "under", "the", "app", "s", "own", "target", "folder" ]
18801791ed5873d511adaa1d91a65ae8cdad2281
https://github.com/deskpro/apps-dpat/blob/18801791ed5873d511adaa1d91a65ae8cdad2281/src/main/javascript/Installer/buildStrategies.js#L57-L85
train
deskpro/apps-dpat
src/main/javascript/Build/BuildUtils.js
function (projectDir) { "use strict"; const packageJson = readPackageJson(projectDir); const extracted = extractVendors(packageJson); return extracted.filter(function (packageName) { return startsWith(packageName, '@deskpro/'); }); }
javascript
function (projectDir) { "use strict"; const packageJson = readPackageJson(projectDir); const extracted = extractVendors(packageJson); return extracted.filter(function (packageName) { return startsWith(packageName, '@deskpro/'); }); }
[ "function", "(", "projectDir", ")", "{", "\"use strict\"", ";", "const", "packageJson", "=", "readPackageJson", "(", "projectDir", ")", ";", "const", "extracted", "=", "extractVendors", "(", "packageJson", ")", ";", "return", "extracted", ".", "filter", "(", "function", "(", "packageName", ")", "{", "return", "startsWith", "(", "packageName", ",", "'@deskpro/'", ")", ";", "}", ")", ";", "}" ]
Scans the package.json manifest for deskpro packages and returns their names @param projectDir @return {Array<String>}
[ "Scans", "the", "package", ".", "json", "manifest", "for", "deskpro", "packages", "and", "returns", "their", "names" ]
18801791ed5873d511adaa1d91a65ae8cdad2281
https://github.com/deskpro/apps-dpat/blob/18801791ed5873d511adaa1d91a65ae8cdad2281/src/main/javascript/Build/BuildUtils.js#L87-L94
train
canjs/can-kefir
can-kefir.js
getCurrentValue
function getCurrentValue(stream, key) { if (stream._currentEvent && stream._currentEvent.type === key) { return stream._currentEvent.value; } else { var names = keyNames[key]; if (!names) { return stream[key]; } var VALUE, valueHandler = function(value) { VALUE = value; }; stream[names.on](valueHandler); stream[names.off](valueHandler); return VALUE; } }
javascript
function getCurrentValue(stream, key) { if (stream._currentEvent && stream._currentEvent.type === key) { return stream._currentEvent.value; } else { var names = keyNames[key]; if (!names) { return stream[key]; } var VALUE, valueHandler = function(value) { VALUE = value; }; stream[names.on](valueHandler); stream[names.off](valueHandler); return VALUE; } }
[ "function", "getCurrentValue", "(", "stream", ",", "key", ")", "{", "if", "(", "stream", ".", "_currentEvent", "&&", "stream", ".", "_currentEvent", ".", "type", "===", "key", ")", "{", "return", "stream", ".", "_currentEvent", ".", "value", ";", "}", "else", "{", "var", "names", "=", "keyNames", "[", "key", "]", ";", "if", "(", "!", "names", ")", "{", "return", "stream", "[", "key", "]", ";", "}", "var", "VALUE", ",", "valueHandler", "=", "function", "(", "value", ")", "{", "VALUE", "=", "value", ";", "}", ";", "stream", "[", "names", ".", "on", "]", "(", "valueHandler", ")", ";", "stream", "[", "names", ".", "off", "]", "(", "valueHandler", ")", ";", "return", "VALUE", ";", "}", "}" ]
get the current value from a stream
[ "get", "the", "current", "value", "from", "a", "stream" ]
918dd1c0bc2ad9255bdf456c384392c55a80086e
https://github.com/canjs/can-kefir/blob/918dd1c0bc2ad9255bdf456c384392c55a80086e/can-kefir.js#L39-L55
train
attester/attester
lib/util/browser-detection.js
function (version) { var splitDots = version.split("."); var nbDots = splitDots.length - 1; if (nbDots === 0) { return version + ".0.0"; } else if (nbDots === 1) { return version + ".0"; } else if (nbDots === 2) { return version; } else { return splitDots.slice(0, 3).join(".") + "-" + splitDots.slice(3).join("."); } }
javascript
function (version) { var splitDots = version.split("."); var nbDots = splitDots.length - 1; if (nbDots === 0) { return version + ".0.0"; } else if (nbDots === 1) { return version + ".0"; } else if (nbDots === 2) { return version; } else { return splitDots.slice(0, 3).join(".") + "-" + splitDots.slice(3).join("."); } }
[ "function", "(", "version", ")", "{", "var", "splitDots", "=", "version", ".", "split", "(", "\".\"", ")", ";", "var", "nbDots", "=", "splitDots", ".", "length", "-", "1", ";", "if", "(", "nbDots", "===", "0", ")", "{", "return", "version", "+", "\".0.0\"", ";", "}", "else", "if", "(", "nbDots", "===", "1", ")", "{", "return", "version", "+", "\".0\"", ";", "}", "else", "if", "(", "nbDots", "===", "2", ")", "{", "return", "version", ";", "}", "else", "{", "return", "splitDots", ".", "slice", "(", "0", ",", "3", ")", ".", "join", "(", "\".\"", ")", "+", "\"-\"", "+", "splitDots", ".", "slice", "(", "3", ")", ".", "join", "(", "\".\"", ")", ";", "}", "}" ]
semver-compliant version must be x.y.z
[ "semver", "-", "compliant", "version", "must", "be", "x", ".", "y", ".", "z" ]
4ed16ca2e8c1af577b47b6bcfc9575589fc87f83
https://github.com/attester/attester/blob/4ed16ca2e8c1af577b47b6bcfc9575589fc87f83/lib/util/browser-detection.js#L20-L32
train
attester/attester
lib/launchers/browser-launcher.js
onLauncherConnect
function onLauncherConnect(slaveURL) { var browsers = attester.config["run-browser"]; if (browsers) { if (!Array.isArray(browsers)) { browsers = [browsers]; } var args = [slaveURL]; for (var i = 0, l = browsers.length; i < l; i++) { var curProcess = spawn(browsers[i], args, { stdio: "pipe" }); curProcess.stdout.pipe(process.stdout); curProcess.stderr.pipe(process.stderr); } } }
javascript
function onLauncherConnect(slaveURL) { var browsers = attester.config["run-browser"]; if (browsers) { if (!Array.isArray(browsers)) { browsers = [browsers]; } var args = [slaveURL]; for (var i = 0, l = browsers.length; i < l; i++) { var curProcess = spawn(browsers[i], args, { stdio: "pipe" }); curProcess.stdout.pipe(process.stdout); curProcess.stderr.pipe(process.stderr); } } }
[ "function", "onLauncherConnect", "(", "slaveURL", ")", "{", "var", "browsers", "=", "attester", ".", "config", "[", "\"run-browser\"", "]", ";", "if", "(", "browsers", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "browsers", ")", ")", "{", "browsers", "=", "[", "browsers", "]", ";", "}", "var", "args", "=", "[", "slaveURL", "]", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "browsers", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "curProcess", "=", "spawn", "(", "browsers", "[", "i", "]", ",", "args", ",", "{", "stdio", ":", "\"pipe\"", "}", ")", ";", "curProcess", ".", "stdout", ".", "pipe", "(", "process", ".", "stdout", ")", ";", "curProcess", ".", "stderr", ".", "pipe", "(", "process", ".", "stderr", ")", ";", "}", "}", "}" ]
Generic launcher for browsers specified on the command line. It spawns a child process for each path in the configuration
[ "Generic", "launcher", "for", "browsers", "specified", "on", "the", "command", "line", ".", "It", "spawns", "a", "child", "process", "for", "each", "path", "in", "the", "configuration" ]
4ed16ca2e8c1af577b47b6bcfc9575589fc87f83
https://github.com/attester/attester/blob/4ed16ca2e8c1af577b47b6bcfc9575589fc87f83/lib/launchers/browser-launcher.js#L24-L39
train
deskpro/apps-dpat
src/main/javascript/Build/Babel.js
function (options, overrides) { let resolved = null; if (typeof options === 'string') { //we've been give a path to a project dir or babelrc let babelrcPath; const stats = fs.statSync(options); if (stats.isDirectory()) { babelrcPath = path.join(options, '.babelrc'); } else if (stats.isFile()) { babelrcPath = options; } if (babelrcPath) { try { const babelOptions = JSON.parse(fs.readFileSync(babelrcPath)); resolved = resolveOptions(babelOptions); } catch (e) { console.log(e); } } } else if (typeof options === 'object') { resolved = resolveOptions(options); } if (resolved) { Object.keys(overrides).forEach(function (key) { resolved[key] = overrides[key]; }); return resolved; } return null; }
javascript
function (options, overrides) { let resolved = null; if (typeof options === 'string') { //we've been give a path to a project dir or babelrc let babelrcPath; const stats = fs.statSync(options); if (stats.isDirectory()) { babelrcPath = path.join(options, '.babelrc'); } else if (stats.isFile()) { babelrcPath = options; } if (babelrcPath) { try { const babelOptions = JSON.parse(fs.readFileSync(babelrcPath)); resolved = resolveOptions(babelOptions); } catch (e) { console.log(e); } } } else if (typeof options === 'object') { resolved = resolveOptions(options); } if (resolved) { Object.keys(overrides).forEach(function (key) { resolved[key] = overrides[key]; }); return resolved; } return null; }
[ "function", "(", "options", ",", "overrides", ")", "{", "let", "resolved", "=", "null", ";", "if", "(", "typeof", "options", "===", "'string'", ")", "{", "let", "babelrcPath", ";", "const", "stats", "=", "fs", ".", "statSync", "(", "options", ")", ";", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "babelrcPath", "=", "path", ".", "join", "(", "options", ",", "'.babelrc'", ")", ";", "}", "else", "if", "(", "stats", ".", "isFile", "(", ")", ")", "{", "babelrcPath", "=", "options", ";", "}", "if", "(", "babelrcPath", ")", "{", "try", "{", "const", "babelOptions", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "babelrcPath", ")", ")", ";", "resolved", "=", "resolveOptions", "(", "babelOptions", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "e", ")", ";", "}", "}", "}", "else", "if", "(", "typeof", "options", "===", "'object'", ")", "{", "resolved", "=", "resolveOptions", "(", "options", ")", ";", "}", "if", "(", "resolved", ")", "{", "Object", ".", "keys", "(", "overrides", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "resolved", "[", "key", "]", "=", "overrides", "[", "key", "]", ";", "}", ")", ";", "return", "resolved", ";", "}", "return", "null", ";", "}" ]
Replaces plugin and presets short names with absolute paths @param {{}|String} options @param {{}} overrides @return {*}
[ "Replaces", "plugin", "and", "presets", "short", "names", "with", "absolute", "paths" ]
18801791ed5873d511adaa1d91a65ae8cdad2281
https://github.com/deskpro/apps-dpat/blob/18801791ed5873d511adaa1d91a65ae8cdad2281/src/main/javascript/Build/Babel.js#L40-L73
train
attester/attester
lib/launchers/phantom-launcher.js
function (cfg, state, n) { cfg.args = cfg.args || {}; var phantomPath = cfg.phantomPath; var controlScript = pathUtil.join(__dirname, '../browsers/phantomjs-control-script.js'); var args = []; args.push(controlScript); args.push("--auto-exit"); if (cfg.args.autoExitPolling) { args.push("--auto-exit-polling=" + cfg.args.autoExitPolling); } if (typeof n == "undefined") { n = Math.round(Math.random() * 1000) % 1000; } args.push("--instance-id=" + n); args.push(cfg.slaveURL); var phantomProcess = spawn(phantomPath, args, { stdio: "pipe" }); if (cfg.pipeStdOut) { phantomProcess.stdout.pipe(process.stdout); phantomProcess.stderr.pipe(process.stderr); } if (cfg.onData) { phantomProcess.stdout.on("data", cfg.onData); } phantomProcess.on("exit", cfg.onExit || this.createPhantomExitCb(cfg, state, n).bind(this)); phantomProcess.on("error", cfg.onError || this.createPhantomErrorCb(cfg, state, n).bind(this)); return phantomProcess; }
javascript
function (cfg, state, n) { cfg.args = cfg.args || {}; var phantomPath = cfg.phantomPath; var controlScript = pathUtil.join(__dirname, '../browsers/phantomjs-control-script.js'); var args = []; args.push(controlScript); args.push("--auto-exit"); if (cfg.args.autoExitPolling) { args.push("--auto-exit-polling=" + cfg.args.autoExitPolling); } if (typeof n == "undefined") { n = Math.round(Math.random() * 1000) % 1000; } args.push("--instance-id=" + n); args.push(cfg.slaveURL); var phantomProcess = spawn(phantomPath, args, { stdio: "pipe" }); if (cfg.pipeStdOut) { phantomProcess.stdout.pipe(process.stdout); phantomProcess.stderr.pipe(process.stderr); } if (cfg.onData) { phantomProcess.stdout.on("data", cfg.onData); } phantomProcess.on("exit", cfg.onExit || this.createPhantomExitCb(cfg, state, n).bind(this)); phantomProcess.on("error", cfg.onError || this.createPhantomErrorCb(cfg, state, n).bind(this)); return phantomProcess; }
[ "function", "(", "cfg", ",", "state", ",", "n", ")", "{", "cfg", ".", "args", "=", "cfg", ".", "args", "||", "{", "}", ";", "var", "phantomPath", "=", "cfg", ".", "phantomPath", ";", "var", "controlScript", "=", "pathUtil", ".", "join", "(", "__dirname", ",", "'../browsers/phantomjs-control-script.js'", ")", ";", "var", "args", "=", "[", "]", ";", "args", ".", "push", "(", "controlScript", ")", ";", "args", ".", "push", "(", "\"--auto-exit\"", ")", ";", "if", "(", "cfg", ".", "args", ".", "autoExitPolling", ")", "{", "args", ".", "push", "(", "\"--auto-exit-polling=\"", "+", "cfg", ".", "args", ".", "autoExitPolling", ")", ";", "}", "if", "(", "typeof", "n", "==", "\"undefined\"", ")", "{", "n", "=", "Math", ".", "round", "(", "Math", ".", "random", "(", ")", "*", "1000", ")", "%", "1000", ";", "}", "args", ".", "push", "(", "\"--instance-id=\"", "+", "n", ")", ";", "args", ".", "push", "(", "cfg", ".", "slaveURL", ")", ";", "var", "phantomProcess", "=", "spawn", "(", "phantomPath", ",", "args", ",", "{", "stdio", ":", "\"pipe\"", "}", ")", ";", "if", "(", "cfg", ".", "pipeStdOut", ")", "{", "phantomProcess", ".", "stdout", ".", "pipe", "(", "process", ".", "stdout", ")", ";", "phantomProcess", ".", "stderr", ".", "pipe", "(", "process", ".", "stderr", ")", ";", "}", "if", "(", "cfg", ".", "onData", ")", "{", "phantomProcess", ".", "stdout", ".", "on", "(", "\"data\"", ",", "cfg", ".", "onData", ")", ";", "}", "phantomProcess", ".", "on", "(", "\"exit\"", ",", "cfg", ".", "onExit", "||", "this", ".", "createPhantomExitCb", "(", "cfg", ",", "state", ",", "n", ")", ".", "bind", "(", "this", ")", ")", ";", "phantomProcess", ".", "on", "(", "\"error\"", ",", "cfg", ".", "onError", "||", "this", ".", "createPhantomErrorCb", "(", "cfg", ",", "state", ",", "n", ")", ".", "bind", "(", "this", ")", ")", ";", "return", "phantomProcess", ";", "}" ]
Starts PhantomJS child process with instance number `n` using `cfg.path` as PhantomJS path and connects it to `cfg.slaveURL` @param {Object} cfg @param {Object} state @param {Integer} n
[ "Starts", "PhantomJS", "child", "process", "with", "instance", "number", "n", "using", "cfg", ".", "path", "as", "PhantomJS", "path", "and", "connects", "it", "to", "cfg", ".", "slaveURL" ]
4ed16ca2e8c1af577b47b6bcfc9575589fc87f83
https://github.com/attester/attester/blob/4ed16ca2e8c1af577b47b6bcfc9575589fc87f83/lib/launchers/phantom-launcher.js#L68-L98
train
attester/attester
lib/launchers/phantom-launcher.js
function (cfg, state, n) { // Node 0.8 and 0.10 differently handle spawning errors ('exit' vs 'error'), but errors that happened after // launching the command are both handled in 'exit' callback return function (code, signal) { // See http://tldp.org/LDP/abs/html/exitcodes.html and http://stackoverflow.com/a/1535733/ if (code === 0 || signal == "SIGTERM" || state.resetCalled) { return; } var isNotRecoverable = (code == 127 || code == 126); if (isNotRecoverable) { ++state.erroredPhantomInstances; var path = cfg.phantomPath; if (code == 127) { logger.logError("Spawn: exited with code 127. PhantomJS executable not found. Make sure to download PhantomJS and add its folder to your system's PATH, or pass the full path directly to Attester via --phantomjs-path.\nUsed command: '" + path + "'"); } else if (code == 126) { logger.logError("Spawn: exited with code 126. Unable to execute PhantomJS. Make sure to have proper read & execute permissions set.\nUsed command: '" + path + "'"); } checkIfAllPhantomsDied(cfg, state); return; } // Now, try to recover unless retried too many times // prepare error message var errMsg; if (code == 75) { errMsg = "Spawn: PhantomJS[" + n + "] exited with code 75: unable to load attester page within specified timeout, or errors happened while loading."; if (cfg.phantomInstances > 1) { errMsg += " You may try decreasing the number of PhantomJS instances in attester config to avoid that problem."; } } else { errMsg = "Spawn: PhantomJS[" + n + "] exited with code " + code + " and signal " + signal; } // check how many retries happened for this instance var retries = state.retries; retries[n] = (retries[n] || 0) + 1; if (retries[n] < cfg.maxRetries) { // log just a warning and try rebooting logger.logWarn(errMsg); logger.logWarn("Trying to reboot instance nr " + n + "..."); this.bootPhantom(cfg, state, n); } else { logger.logError(errMsg); ++state.erroredPhantomInstances; checkIfAllPhantomsDied(cfg, state); } }; }
javascript
function (cfg, state, n) { // Node 0.8 and 0.10 differently handle spawning errors ('exit' vs 'error'), but errors that happened after // launching the command are both handled in 'exit' callback return function (code, signal) { // See http://tldp.org/LDP/abs/html/exitcodes.html and http://stackoverflow.com/a/1535733/ if (code === 0 || signal == "SIGTERM" || state.resetCalled) { return; } var isNotRecoverable = (code == 127 || code == 126); if (isNotRecoverable) { ++state.erroredPhantomInstances; var path = cfg.phantomPath; if (code == 127) { logger.logError("Spawn: exited with code 127. PhantomJS executable not found. Make sure to download PhantomJS and add its folder to your system's PATH, or pass the full path directly to Attester via --phantomjs-path.\nUsed command: '" + path + "'"); } else if (code == 126) { logger.logError("Spawn: exited with code 126. Unable to execute PhantomJS. Make sure to have proper read & execute permissions set.\nUsed command: '" + path + "'"); } checkIfAllPhantomsDied(cfg, state); return; } // Now, try to recover unless retried too many times // prepare error message var errMsg; if (code == 75) { errMsg = "Spawn: PhantomJS[" + n + "] exited with code 75: unable to load attester page within specified timeout, or errors happened while loading."; if (cfg.phantomInstances > 1) { errMsg += " You may try decreasing the number of PhantomJS instances in attester config to avoid that problem."; } } else { errMsg = "Spawn: PhantomJS[" + n + "] exited with code " + code + " and signal " + signal; } // check how many retries happened for this instance var retries = state.retries; retries[n] = (retries[n] || 0) + 1; if (retries[n] < cfg.maxRetries) { // log just a warning and try rebooting logger.logWarn(errMsg); logger.logWarn("Trying to reboot instance nr " + n + "..."); this.bootPhantom(cfg, state, n); } else { logger.logError(errMsg); ++state.erroredPhantomInstances; checkIfAllPhantomsDied(cfg, state); } }; }
[ "function", "(", "cfg", ",", "state", ",", "n", ")", "{", "return", "function", "(", "code", ",", "signal", ")", "{", "if", "(", "code", "===", "0", "||", "signal", "==", "\"SIGTERM\"", "||", "state", ".", "resetCalled", ")", "{", "return", ";", "}", "var", "isNotRecoverable", "=", "(", "code", "==", "127", "||", "code", "==", "126", ")", ";", "if", "(", "isNotRecoverable", ")", "{", "++", "state", ".", "erroredPhantomInstances", ";", "var", "path", "=", "cfg", ".", "phantomPath", ";", "if", "(", "code", "==", "127", ")", "{", "logger", ".", "logError", "(", "\"Spawn: exited with code 127. PhantomJS executable not found. Make sure to download PhantomJS and add its folder to your system's PATH, or pass the full path directly to Attester via --phantomjs-path.\\nUsed command: '\"", "+", "\\n", "+", "path", ")", ";", "}", "else", "\"'\"", "if", "(", "code", "==", "126", ")", "{", "logger", ".", "logError", "(", "\"Spawn: exited with code 126. Unable to execute PhantomJS. Make sure to have proper read & execute permissions set.\\nUsed command: '\"", "+", "\\n", "+", "path", ")", ";", "}", "\"'\"", "}", "checkIfAllPhantomsDied", "(", "cfg", ",", "state", ")", ";", "return", ";", "var", "errMsg", ";", "if", "(", "code", "==", "75", ")", "{", "errMsg", "=", "\"Spawn: PhantomJS[\"", "+", "n", "+", "\"] exited with code 75: unable to load attester page within specified timeout, or errors happened while loading.\"", ";", "if", "(", "cfg", ".", "phantomInstances", ">", "1", ")", "{", "errMsg", "+=", "\" You may try decreasing the number of PhantomJS instances in attester config to avoid that problem.\"", ";", "}", "}", "else", "{", "errMsg", "=", "\"Spawn: PhantomJS[\"", "+", "n", "+", "\"] exited with code \"", "+", "code", "+", "\" and signal \"", "+", "signal", ";", "}", "var", "retries", "=", "state", ".", "retries", ";", "}", ";", "}" ]
Factory of callback functions to be used as 'exit' listener by PhantomJS processes. @param {Object} cfg @param {Object} state @param {Integer} n @return {Function}
[ "Factory", "of", "callback", "functions", "to", "be", "used", "as", "exit", "listener", "by", "PhantomJS", "processes", "." ]
4ed16ca2e8c1af577b47b6bcfc9575589fc87f83
https://github.com/attester/attester/blob/4ed16ca2e8c1af577b47b6bcfc9575589fc87f83/lib/launchers/phantom-launcher.js#L107-L156
train
attester/attester
lib/launchers/phantom-launcher.js
function (cfg, state, n) { return function (err) { if (err.code == "ENOENT") { logger.logError("Spawn: exited with code ENOENT. PhantomJS executable not found. Make sure to download PhantomJS and add its folder to your system's PATH, or pass the full path directly to Attester via --phantomjs-path.\nUsed command: '" + cfg.phantomPath + "'"); } else { logger.logError("Unable to spawn PhantomJS; error code " + err.code); } }; }
javascript
function (cfg, state, n) { return function (err) { if (err.code == "ENOENT") { logger.logError("Spawn: exited with code ENOENT. PhantomJS executable not found. Make sure to download PhantomJS and add its folder to your system's PATH, or pass the full path directly to Attester via --phantomjs-path.\nUsed command: '" + cfg.phantomPath + "'"); } else { logger.logError("Unable to spawn PhantomJS; error code " + err.code); } }; }
[ "function", "(", "cfg", ",", "state", ",", "n", ")", "{", "return", "function", "(", "err", ")", "{", "if", "(", "err", ".", "code", "==", "\"ENOENT\"", ")", "{", "logger", ".", "logError", "(", "\"Spawn: exited with code ENOENT. PhantomJS executable not found. Make sure to download PhantomJS and add its folder to your system's PATH, or pass the full path directly to Attester via --phantomjs-path.\\nUsed command: '\"", "+", "\\n", "+", "cfg", ".", "phantomPath", ")", ";", "}", "else", "\"'\"", "}", ";", "}" ]
Factory of callback functions to be used as 'error' listener by PhantomJS processes. @param {Object} cfg @param {Object} state @param {Integer} n @return {Function}
[ "Factory", "of", "callback", "functions", "to", "be", "used", "as", "error", "listener", "by", "PhantomJS", "processes", "." ]
4ed16ca2e8c1af577b47b6bcfc9575589fc87f83
https://github.com/attester/attester/blob/4ed16ca2e8c1af577b47b6bcfc9575589fc87f83/lib/launchers/phantom-launcher.js#L165-L173
train
attester/attester
spec/server/middleware.spec.js
function () { this.addResult = function (event) { var fullUrl = event.homeURL + url; http.get(fullUrl, function (response) { var content = ""; response.on("data", function (chunk) { content += chunk; }); response.on("end", function () { callback(content); }); }); }; this.checkFinished = function () { return false; }; events.EventEmitter.call(this); }
javascript
function () { this.addResult = function (event) { var fullUrl = event.homeURL + url; http.get(fullUrl, function (response) { var content = ""; response.on("data", function (chunk) { content += chunk; }); response.on("end", function () { callback(content); }); }); }; this.checkFinished = function () { return false; }; events.EventEmitter.call(this); }
[ "function", "(", ")", "{", "this", ".", "addResult", "=", "function", "(", "event", ")", "{", "var", "fullUrl", "=", "event", ".", "homeURL", "+", "url", ";", "http", ".", "get", "(", "fullUrl", ",", "function", "(", "response", ")", "{", "var", "content", "=", "\"\"", ";", "response", ".", "on", "(", "\"data\"", ",", "function", "(", "chunk", ")", "{", "content", "+=", "chunk", ";", "}", ")", ";", "response", ".", "on", "(", "\"end\"", ",", "function", "(", ")", "{", "callback", "(", "content", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "this", ".", "checkFinished", "=", "function", "(", ")", "{", "return", "false", ";", "}", ";", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "}" ]
Add a fake campaign to get the slave URL
[ "Add", "a", "fake", "campaign", "to", "get", "the", "slave", "URL" ]
4ed16ca2e8c1af577b47b6bcfc9575589fc87f83
https://github.com/attester/attester/blob/4ed16ca2e8c1af577b47b6bcfc9575589fc87f83/spec/server/middleware.spec.js#L73-L90
train
deskpro/apps-dpat
src/main/javascript/webpack/resolvers.js
resolvePath
function resolvePath (moduleName, relativePath) { if (! moduleName) { return null; } if (! relativePath) { return null; } const mainPath = require.resolve(moduleName); if (! mainPath) { return null; } const rootLocations = []; const dirs = mainPath.split(path.sep); let lastSegment = dirs.pop(); while (lastSegment) { const location = dirs.concat(['package.json']).join(path.sep); rootLocations.push(location); lastSegment = dirs.pop(); } for(const location of rootLocations) { if (fs.existsSync(location)) { const cli = path.resolve(path.dirname(location), relativePath); if (fs.existsSync(cli)) { return cli; } } } return null; }
javascript
function resolvePath (moduleName, relativePath) { if (! moduleName) { return null; } if (! relativePath) { return null; } const mainPath = require.resolve(moduleName); if (! mainPath) { return null; } const rootLocations = []; const dirs = mainPath.split(path.sep); let lastSegment = dirs.pop(); while (lastSegment) { const location = dirs.concat(['package.json']).join(path.sep); rootLocations.push(location); lastSegment = dirs.pop(); } for(const location of rootLocations) { if (fs.existsSync(location)) { const cli = path.resolve(path.dirname(location), relativePath); if (fs.existsSync(cli)) { return cli; } } } return null; }
[ "function", "resolvePath", "(", "moduleName", ",", "relativePath", ")", "{", "if", "(", "!", "moduleName", ")", "{", "return", "null", ";", "}", "if", "(", "!", "relativePath", ")", "{", "return", "null", ";", "}", "const", "mainPath", "=", "require", ".", "resolve", "(", "moduleName", ")", ";", "if", "(", "!", "mainPath", ")", "{", "return", "null", ";", "}", "const", "rootLocations", "=", "[", "]", ";", "const", "dirs", "=", "mainPath", ".", "split", "(", "path", ".", "sep", ")", ";", "let", "lastSegment", "=", "dirs", ".", "pop", "(", ")", ";", "while", "(", "lastSegment", ")", "{", "const", "location", "=", "dirs", ".", "concat", "(", "[", "'package.json'", "]", ")", ".", "join", "(", "path", ".", "sep", ")", ";", "rootLocations", ".", "push", "(", "location", ")", ";", "lastSegment", "=", "dirs", ".", "pop", "(", ")", ";", "}", "for", "(", "const", "location", "of", "rootLocations", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "location", ")", ")", "{", "const", "cli", "=", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "location", ")", ",", "relativePath", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "cli", ")", ")", "{", "return", "cli", ";", "}", "}", "}", "return", "null", ";", "}" ]
Resolves a relative path in the context of a module into an absolute path @param {string} moduleName @param {string} relativePath the relative path inside the module @returns {string|null}
[ "Resolves", "a", "relative", "path", "in", "the", "context", "of", "a", "module", "into", "an", "absolute", "path" ]
18801791ed5873d511adaa1d91a65ae8cdad2281
https://github.com/deskpro/apps-dpat/blob/18801791ed5873d511adaa1d91a65ae8cdad2281/src/main/javascript/webpack/resolvers.js#L11-L45
train
bigeasy/arguable
arguable.js
Arguable
function Arguable (usage, argv, options) { this._usage = usage // These are the merged defintion and invocation options provided by the // user. this.options = options.options // The key used to create the `Destructible`. this.identifier = options.identifier // We'll use this for an exit code if it is set and if we exit normally. this.exitCode = null // Are we running as a main module? this.isMainModule = options.isMainModule // Use environment `LANG` or else language of first usage definition. this.lang = coalesce(options.lang, this._usage.language) // Extract argument patterns from usage. var patterns = this._usage.getPattern() // Extract the arguments that accept values, TODO maybe call `valuable`. this.arguable = patterns.filter(function (pattern) { return pattern.arguable }).map(function (pattern) { return pattern.verbose }) // Parse arguments and save the remaining arguments. try { var gotopts = getopt(patterns, argv) } catch (error) { this.abend(error.abend, error.context) } // Extract an argument end sigil and note that it was there. if (this.terminal = argv[0] == '--') { argv.shift() } // Slice and dice results into convenience structures. this._setParameters(gotopts) // Remaining arguments. this.argv = argv // Assign standard I/O provide in `options`. this.stdout = options.stdout this.stderr = options.stderr this.stdin = options.stdin // Assign pipes open to our parent. this.pipes = options.pipes // Set after we get our arguments. this.scram = 0 // Called when we exit with no arguments. this.exited = new Signal }
javascript
function Arguable (usage, argv, options) { this._usage = usage // These are the merged defintion and invocation options provided by the // user. this.options = options.options // The key used to create the `Destructible`. this.identifier = options.identifier // We'll use this for an exit code if it is set and if we exit normally. this.exitCode = null // Are we running as a main module? this.isMainModule = options.isMainModule // Use environment `LANG` or else language of first usage definition. this.lang = coalesce(options.lang, this._usage.language) // Extract argument patterns from usage. var patterns = this._usage.getPattern() // Extract the arguments that accept values, TODO maybe call `valuable`. this.arguable = patterns.filter(function (pattern) { return pattern.arguable }).map(function (pattern) { return pattern.verbose }) // Parse arguments and save the remaining arguments. try { var gotopts = getopt(patterns, argv) } catch (error) { this.abend(error.abend, error.context) } // Extract an argument end sigil and note that it was there. if (this.terminal = argv[0] == '--') { argv.shift() } // Slice and dice results into convenience structures. this._setParameters(gotopts) // Remaining arguments. this.argv = argv // Assign standard I/O provide in `options`. this.stdout = options.stdout this.stderr = options.stderr this.stdin = options.stdin // Assign pipes open to our parent. this.pipes = options.pipes // Set after we get our arguments. this.scram = 0 // Called when we exit with no arguments. this.exited = new Signal }
[ "function", "Arguable", "(", "usage", ",", "argv", ",", "options", ")", "{", "this", ".", "_usage", "=", "usage", "this", ".", "options", "=", "options", ".", "options", "this", ".", "identifier", "=", "options", ".", "identifier", "this", ".", "exitCode", "=", "null", "this", ".", "isMainModule", "=", "options", ".", "isMainModule", "this", ".", "lang", "=", "coalesce", "(", "options", ".", "lang", ",", "this", ".", "_usage", ".", "language", ")", "var", "patterns", "=", "this", ".", "_usage", ".", "getPattern", "(", ")", "this", ".", "arguable", "=", "patterns", ".", "filter", "(", "function", "(", "pattern", ")", "{", "return", "pattern", ".", "arguable", "}", ")", ".", "map", "(", "function", "(", "pattern", ")", "{", "return", "pattern", ".", "verbose", "}", ")", "try", "{", "var", "gotopts", "=", "getopt", "(", "patterns", ",", "argv", ")", "}", "catch", "(", "error", ")", "{", "this", ".", "abend", "(", "error", ".", "abend", ",", "error", ".", "context", ")", "}", "if", "(", "this", ".", "terminal", "=", "argv", "[", "0", "]", "==", "'--'", ")", "{", "argv", ".", "shift", "(", ")", "}", "this", ".", "_setParameters", "(", "gotopts", ")", "this", ".", "argv", "=", "argv", "this", ".", "stdout", "=", "options", ".", "stdout", "this", ".", "stderr", "=", "options", ".", "stderr", "this", ".", "stdin", "=", "options", ".", "stdin", "this", ".", "pipes", "=", "options", ".", "pipes", "this", ".", "scram", "=", "0", "this", ".", "exited", "=", "new", "Signal", "}" ]
This will never be pretty. Let it be ugly. Let it swallow all the sins before they enter your program, so that your program can be a garden of pure ideology.
[ "This", "will", "never", "be", "pretty", ".", "Let", "it", "be", "ugly", ".", "Let", "it", "swallow", "all", "the", "sins", "before", "they", "enter", "your", "program", "so", "that", "your", "program", "can", "be", "a", "garden", "of", "pure", "ideology", "." ]
368e86513f03d3eac2a401377dcc033a94e721d4
https://github.com/bigeasy/arguable/blob/368e86513f03d3eac2a401377dcc033a94e721d4/arguable.js#L17-L77
train
attester/attester
lib/util/page-generator.js
normalizePage
function normalizePage(content) { var data = { "head-start": [], "head": [], "head-end": [], body: [] }; if (typeof content === "string") { data.body.push(content); } else { ["head-start", "head", "head-end", "body"].forEach(function (section) { var sectionContent = content[section]; if (!sectionContent) { return; } if (!_.isArray(sectionContent)) { data[section].push(sectionContent); } else { data[section] = sectionContent; } }); } return data; }
javascript
function normalizePage(content) { var data = { "head-start": [], "head": [], "head-end": [], body: [] }; if (typeof content === "string") { data.body.push(content); } else { ["head-start", "head", "head-end", "body"].forEach(function (section) { var sectionContent = content[section]; if (!sectionContent) { return; } if (!_.isArray(sectionContent)) { data[section].push(sectionContent); } else { data[section] = sectionContent; } }); } return data; }
[ "function", "normalizePage", "(", "content", ")", "{", "var", "data", "=", "{", "\"head-start\"", ":", "[", "]", ",", "\"head\"", ":", "[", "]", ",", "\"head-end\"", ":", "[", "]", ",", "body", ":", "[", "]", "}", ";", "if", "(", "typeof", "content", "===", "\"string\"", ")", "{", "data", ".", "body", ".", "push", "(", "content", ")", ";", "}", "else", "{", "[", "\"head-start\"", ",", "\"head\"", ",", "\"head-end\"", ",", "\"body\"", "]", ".", "forEach", "(", "function", "(", "section", ")", "{", "var", "sectionContent", "=", "content", "[", "section", "]", ";", "if", "(", "!", "sectionContent", ")", "{", "return", ";", "}", "if", "(", "!", "_", ".", "isArray", "(", "sectionContent", ")", ")", "{", "data", "[", "section", "]", ".", "push", "(", "sectionContent", ")", ";", "}", "else", "{", "data", "[", "section", "]", "=", "sectionContent", ";", "}", "}", ")", ";", "}", "return", "data", ";", "}" ]
Given any acceptable page description, generate an object with head and body as arrays. Normalized pages can be merged easily
[ "Given", "any", "acceptable", "page", "description", "generate", "an", "object", "with", "head", "and", "body", "as", "arrays", ".", "Normalized", "pages", "can", "be", "merged", "easily" ]
4ed16ca2e8c1af577b47b6bcfc9575589fc87f83
https://github.com/attester/attester/blob/4ed16ca2e8c1af577b47b6bcfc9575589fc87f83/lib/util/page-generator.js#L167-L193
train
attester/attester
lib/util/page-generator.js
flattenHead
function flattenHead(obj) { var newHead = []; _arrayCopy(newHead, obj["head-start"]); _arrayCopy(newHead, obj["head"]); _arrayCopy(newHead, obj["head-end"]); delete obj["head-start"]; delete obj["head-end"]; obj.head = newHead; return obj; }
javascript
function flattenHead(obj) { var newHead = []; _arrayCopy(newHead, obj["head-start"]); _arrayCopy(newHead, obj["head"]); _arrayCopy(newHead, obj["head-end"]); delete obj["head-start"]; delete obj["head-end"]; obj.head = newHead; return obj; }
[ "function", "flattenHead", "(", "obj", ")", "{", "var", "newHead", "=", "[", "]", ";", "_arrayCopy", "(", "newHead", ",", "obj", "[", "\"head-start\"", "]", ")", ";", "_arrayCopy", "(", "newHead", ",", "obj", "[", "\"head\"", "]", ")", ";", "_arrayCopy", "(", "newHead", ",", "obj", "[", "\"head-end\"", "]", ")", ";", "delete", "obj", "[", "\"head-start\"", "]", ";", "delete", "obj", "[", "\"head-end\"", "]", ";", "obj", ".", "head", "=", "newHead", ";", "return", "obj", ";", "}" ]
Merges `head-start`, `head`, and `head-end` subnodes of the input object into a one `head` subnode and removes the other two subnodes. @param {Object} obj Object to be manipulated @return {Object} the input param object with its `head` node flattened
[ "Merges", "head", "-", "start", "head", "and", "head", "-", "end", "subnodes", "of", "the", "input", "object", "into", "a", "one", "head", "subnode", "and", "removes", "the", "other", "two", "subnodes", "." ]
4ed16ca2e8c1af577b47b6bcfc9575589fc87f83
https://github.com/attester/attester/blob/4ed16ca2e8c1af577b47b6bcfc9575589fc87f83/lib/util/page-generator.js#L202-L214
train
attester/attester
lib/util/page-generator.js
_arrayCopy
function _arrayCopy(dest, src) { if (Array.isArray(src)) { src.forEach(function (item) { dest.push(item); }); } }
javascript
function _arrayCopy(dest, src) { if (Array.isArray(src)) { src.forEach(function (item) { dest.push(item); }); } }
[ "function", "_arrayCopy", "(", "dest", ",", "src", ")", "{", "if", "(", "Array", ".", "isArray", "(", "src", ")", ")", "{", "src", ".", "forEach", "(", "function", "(", "item", ")", "{", "dest", ".", "push", "(", "item", ")", ";", "}", ")", ";", "}", "}" ]
Push all elements from one array to another, in-place. @param {Array} dest @param {Array} src
[ "Push", "all", "elements", "from", "one", "array", "to", "another", "in", "-", "place", "." ]
4ed16ca2e8c1af577b47b6bcfc9575589fc87f83
https://github.com/attester/attester/blob/4ed16ca2e8c1af577b47b6bcfc9575589fc87f83/lib/util/page-generator.js#L222-L228
train
CodeTanzania/majifix-service-group
docs/vendor/path-to-regexp/index.js
replacePath
function replacePath (path, keys) { var index = 0; function replace (_, escaped, prefix, key, capture, group, suffix, escape) { if (escaped) { return escaped; } if (escape) { return '\\' + escape; } var repeat = suffix === '+' || suffix === '*'; var optional = suffix === '?' || suffix === '*'; keys.push({ name: key || index++, delimiter: prefix || '/', optional: optional, repeat: repeat }); prefix = prefix ? ('\\' + prefix) : ''; capture = escapeGroup(capture || group || '[^' + (prefix || '\\/') + ']+?'); if (repeat) { capture = capture + '(?:' + prefix + capture + ')*'; } if (optional) { return '(?:' + prefix + '(' + capture + '))?'; } // Basic parameter support. return prefix + '(' + capture + ')'; } return path.replace(PATH_REGEXP, replace); }
javascript
function replacePath (path, keys) { var index = 0; function replace (_, escaped, prefix, key, capture, group, suffix, escape) { if (escaped) { return escaped; } if (escape) { return '\\' + escape; } var repeat = suffix === '+' || suffix === '*'; var optional = suffix === '?' || suffix === '*'; keys.push({ name: key || index++, delimiter: prefix || '/', optional: optional, repeat: repeat }); prefix = prefix ? ('\\' + prefix) : ''; capture = escapeGroup(capture || group || '[^' + (prefix || '\\/') + ']+?'); if (repeat) { capture = capture + '(?:' + prefix + capture + ')*'; } if (optional) { return '(?:' + prefix + '(' + capture + '))?'; } // Basic parameter support. return prefix + '(' + capture + ')'; } return path.replace(PATH_REGEXP, replace); }
[ "function", "replacePath", "(", "path", ",", "keys", ")", "{", "var", "index", "=", "0", ";", "function", "replace", "(", "_", ",", "escaped", ",", "prefix", ",", "key", ",", "capture", ",", "group", ",", "suffix", ",", "escape", ")", "{", "if", "(", "escaped", ")", "{", "return", "escaped", ";", "}", "if", "(", "escape", ")", "{", "return", "'\\\\'", "+", "\\\\", ";", "}", "escape", "var", "repeat", "=", "suffix", "===", "'+'", "||", "suffix", "===", "'*'", ";", "var", "optional", "=", "suffix", "===", "'?'", "||", "suffix", "===", "'*'", ";", "keys", ".", "push", "(", "{", "name", ":", "key", "||", "index", "++", ",", "delimiter", ":", "prefix", "||", "'/'", ",", "optional", ":", "optional", ",", "repeat", ":", "repeat", "}", ")", ";", "prefix", "=", "prefix", "?", "(", "'\\\\'", "+", "\\\\", ")", ":", "prefix", ";", "''", "capture", "=", "escapeGroup", "(", "capture", "||", "group", "||", "'[^'", "+", "(", "prefix", "||", "'\\\\/'", ")", "+", "\\\\", ")", ";", "']+?'", "}", "if", "(", "repeat", ")", "{", "capture", "=", "capture", "+", "'(?:'", "+", "prefix", "+", "capture", "+", "')*'", ";", "}", "}" ]
Replace the specific tags with regexp strings. @param {String} path @param {Array} keys @return {String}
[ "Replace", "the", "specific", "tags", "with", "regexp", "strings", "." ]
bce41249dd31e57cf19fd9df5cbd2c3e141b0cf8
https://github.com/CodeTanzania/majifix-service-group/blob/bce41249dd31e57cf19fd9df5cbd2c3e141b0cf8/docs/vendor/path-to-regexp/index.js#L112-L150
train
benne/gulp-mongodb-data
index.js
function (cb) { if (opts.dropCollection) { db.listCollections({name: collectionName}) .toArray(function (err, items) { if (err) return cb(err) if (items.length) return coll.drop(cb) cb() }) } else cb() }
javascript
function (cb) { if (opts.dropCollection) { db.listCollections({name: collectionName}) .toArray(function (err, items) { if (err) return cb(err) if (items.length) return coll.drop(cb) cb() }) } else cb() }
[ "function", "(", "cb", ")", "{", "if", "(", "opts", ".", "dropCollection", ")", "{", "db", ".", "listCollections", "(", "{", "name", ":", "collectionName", "}", ")", ".", "toArray", "(", "function", "(", "err", ",", "items", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "if", "(", "items", ".", "length", ")", "return", "coll", ".", "drop", "(", "cb", ")", "cb", "(", ")", "}", ")", "}", "else", "cb", "(", ")", "}" ]
Drop collection if option is set and collection exists
[ "Drop", "collection", "if", "option", "is", "set", "and", "collection", "exists" ]
05a0be34b84ab8879590e44a6a8b9d012572a30e
https://github.com/benne/gulp-mongodb-data/blob/05a0be34b84ab8879590e44a6a8b9d012572a30e/index.js#L100-L109
train
jwerle/shamirs-secret-sharing
split.js
split
function split(secret, opts) { if (!secret || (secret && 0 === secret.length)) { throw new TypeError('Secret cannot be empty.') } if ('string' === typeof secret) { secret = Buffer.from(secret) } if (false === Buffer.isBuffer(secret)) { throw new TypeError('Expecting secret to be a buffer.') } if (!opts || 'object' !== typeof opts) { throw new TypeError('Expecting options to be an object.') } if ('number' !== typeof opts.shares) { throw new TypeError('Expecting shares to be a number.') } if (!opts.shares || opts.shares < 0 || opts.shares > MAX_SHARES) { throw new RangeError(`Shares must be 0 < shares <= ${MAX_SHARES}.`) } if ('number' !== typeof opts.threshold) { throw new TypeError('Expecting threshold to be a number.') } if (!opts.threshold || opts.threshold < 0 || opts.threshold > opts.shares) { throw new RangeError(`Threshold must be 0 < threshold <= ${opts.shares}.`) } if (!opts.random || 'function' !== typeof opts.random) { opts.random = random } const hex = codec.hex(secret) const bin = codec.bin(hex, 16) // prepend 1 to get extra padding, we'll account for this later const parts = codec.split('1' + bin, BIT_PADDING, 2) for (let i = 0; i < parts.length; ++i) { const p = points(parts[i], opts) for (let j = 0; j < opts.shares; ++j) { if (!scratch[j]) { scratch[j] = p[j].x.toString(16) } const z = p[j].y.toString(2) const y = scratch[j + MAX_SHARES] || '' // y[j] = p[j][y] + y[j] scratch[j + MAX_SHARES] = codec.pad(z) + y } } for (let i = 0; i < opts.shares; ++i) { const x = scratch[i] const y = codec.hex(scratch[i + MAX_SHARES], BIN_ENCODING) scratch[i] = codec.encode(x, y) scratch[i] = Buffer.from('0' + scratch[i], 'hex') } const result = scratch.slice(0, opts.shares) scratch.fill(0) return result }
javascript
function split(secret, opts) { if (!secret || (secret && 0 === secret.length)) { throw new TypeError('Secret cannot be empty.') } if ('string' === typeof secret) { secret = Buffer.from(secret) } if (false === Buffer.isBuffer(secret)) { throw new TypeError('Expecting secret to be a buffer.') } if (!opts || 'object' !== typeof opts) { throw new TypeError('Expecting options to be an object.') } if ('number' !== typeof opts.shares) { throw new TypeError('Expecting shares to be a number.') } if (!opts.shares || opts.shares < 0 || opts.shares > MAX_SHARES) { throw new RangeError(`Shares must be 0 < shares <= ${MAX_SHARES}.`) } if ('number' !== typeof opts.threshold) { throw new TypeError('Expecting threshold to be a number.') } if (!opts.threshold || opts.threshold < 0 || opts.threshold > opts.shares) { throw new RangeError(`Threshold must be 0 < threshold <= ${opts.shares}.`) } if (!opts.random || 'function' !== typeof opts.random) { opts.random = random } const hex = codec.hex(secret) const bin = codec.bin(hex, 16) // prepend 1 to get extra padding, we'll account for this later const parts = codec.split('1' + bin, BIT_PADDING, 2) for (let i = 0; i < parts.length; ++i) { const p = points(parts[i], opts) for (let j = 0; j < opts.shares; ++j) { if (!scratch[j]) { scratch[j] = p[j].x.toString(16) } const z = p[j].y.toString(2) const y = scratch[j + MAX_SHARES] || '' // y[j] = p[j][y] + y[j] scratch[j + MAX_SHARES] = codec.pad(z) + y } } for (let i = 0; i < opts.shares; ++i) { const x = scratch[i] const y = codec.hex(scratch[i + MAX_SHARES], BIN_ENCODING) scratch[i] = codec.encode(x, y) scratch[i] = Buffer.from('0' + scratch[i], 'hex') } const result = scratch.slice(0, opts.shares) scratch.fill(0) return result }
[ "function", "split", "(", "secret", ",", "opts", ")", "{", "if", "(", "!", "secret", "||", "(", "secret", "&&", "0", "===", "secret", ".", "length", ")", ")", "{", "throw", "new", "TypeError", "(", "'Secret cannot be empty.'", ")", "}", "if", "(", "'string'", "===", "typeof", "secret", ")", "{", "secret", "=", "Buffer", ".", "from", "(", "secret", ")", "}", "if", "(", "false", "===", "Buffer", ".", "isBuffer", "(", "secret", ")", ")", "{", "throw", "new", "TypeError", "(", "'Expecting secret to be a buffer.'", ")", "}", "if", "(", "!", "opts", "||", "'object'", "!==", "typeof", "opts", ")", "{", "throw", "new", "TypeError", "(", "'Expecting options to be an object.'", ")", "}", "if", "(", "'number'", "!==", "typeof", "opts", ".", "shares", ")", "{", "throw", "new", "TypeError", "(", "'Expecting shares to be a number.'", ")", "}", "if", "(", "!", "opts", ".", "shares", "||", "opts", ".", "shares", "<", "0", "||", "opts", ".", "shares", ">", "MAX_SHARES", ")", "{", "throw", "new", "RangeError", "(", "`", "${", "MAX_SHARES", "}", "`", ")", "}", "if", "(", "'number'", "!==", "typeof", "opts", ".", "threshold", ")", "{", "throw", "new", "TypeError", "(", "'Expecting threshold to be a number.'", ")", "}", "if", "(", "!", "opts", ".", "threshold", "||", "opts", ".", "threshold", "<", "0", "||", "opts", ".", "threshold", ">", "opts", ".", "shares", ")", "{", "throw", "new", "RangeError", "(", "`", "${", "opts", ".", "shares", "}", "`", ")", "}", "if", "(", "!", "opts", ".", "random", "||", "'function'", "!==", "typeof", "opts", ".", "random", ")", "{", "opts", ".", "random", "=", "random", "}", "const", "hex", "=", "codec", ".", "hex", "(", "secret", ")", "const", "bin", "=", "codec", ".", "bin", "(", "hex", ",", "16", ")", "const", "parts", "=", "codec", ".", "split", "(", "'1'", "+", "bin", ",", "BIT_PADDING", ",", "2", ")", "for", "(", "let", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "++", "i", ")", "{", "const", "p", "=", "points", "(", "parts", "[", "i", "]", ",", "opts", ")", "for", "(", "let", "j", "=", "0", ";", "j", "<", "opts", ".", "shares", ";", "++", "j", ")", "{", "if", "(", "!", "scratch", "[", "j", "]", ")", "{", "scratch", "[", "j", "]", "=", "p", "[", "j", "]", ".", "x", ".", "toString", "(", "16", ")", "}", "const", "z", "=", "p", "[", "j", "]", ".", "y", ".", "toString", "(", "2", ")", "const", "y", "=", "scratch", "[", "j", "+", "MAX_SHARES", "]", "||", "''", "scratch", "[", "j", "+", "MAX_SHARES", "]", "=", "codec", ".", "pad", "(", "z", ")", "+", "y", "}", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "opts", ".", "shares", ";", "++", "i", ")", "{", "const", "x", "=", "scratch", "[", "i", "]", "const", "y", "=", "codec", ".", "hex", "(", "scratch", "[", "i", "+", "MAX_SHARES", "]", ",", "BIN_ENCODING", ")", "scratch", "[", "i", "]", "=", "codec", ".", "encode", "(", "x", ",", "y", ")", "scratch", "[", "i", "]", "=", "Buffer", ".", "from", "(", "'0'", "+", "scratch", "[", "i", "]", ",", "'hex'", ")", "}", "const", "result", "=", "scratch", ".", "slice", "(", "0", ",", "opts", ".", "shares", ")", "scratch", ".", "fill", "(", "0", ")", "return", "result", "}" ]
Split a secret into a set of distinct shares with a configured threshold of shares needed for construction. @public @param {String|Buffer} secret @param {Object} opts @param {Object} opts.shares @param {Object} opts.threshold @param {?(Function)} opts.random @returns {Array<Buffer>} @throws TypeError @throws RangeError
[ "Split", "a", "secret", "into", "a", "set", "of", "distinct", "shares", "with", "a", "configured", "threshold", "of", "shares", "needed", "for", "construction", "." ]
1d7f2166854462c711c2f074f560e19ce8cf507c
https://github.com/jwerle/shamirs-secret-sharing/blob/1d7f2166854462c711c2f074f560e19ce8cf507c/split.js#L31-L99
train
jwerle/shamirs-secret-sharing
combine.js
combine
function combine(shares) { const chunks = [] const x = [] const y = [] const t = shares.length for (let i = 0; i < t; ++i) { const share = parse(shares[i]) if (-1 === x.indexOf(share.id)) { x.push(share.id) const bin = codec.bin(share.data, 16) const parts = codec.split(bin, 0, 2) for (let j = 0; j < parts.length; ++j) { if (!y[j]) { y[j] = [] } y[j][x.length - 1] = parts[j] } } } for (let i = 0; i < y.length; ++i) { const p = lagrange(0, [x, y[i]]) chunks.unshift(codec.pad(p.toString(2))) } const string = chunks.join('') const bin = string.slice(1 + string.indexOf('1')) // >= 0 const hex = codec.hex(bin, BIN_ENCODING) const value = codec.decode(hex) return Buffer.from(value) }
javascript
function combine(shares) { const chunks = [] const x = [] const y = [] const t = shares.length for (let i = 0; i < t; ++i) { const share = parse(shares[i]) if (-1 === x.indexOf(share.id)) { x.push(share.id) const bin = codec.bin(share.data, 16) const parts = codec.split(bin, 0, 2) for (let j = 0; j < parts.length; ++j) { if (!y[j]) { y[j] = [] } y[j][x.length - 1] = parts[j] } } } for (let i = 0; i < y.length; ++i) { const p = lagrange(0, [x, y[i]]) chunks.unshift(codec.pad(p.toString(2))) } const string = chunks.join('') const bin = string.slice(1 + string.indexOf('1')) // >= 0 const hex = codec.hex(bin, BIN_ENCODING) const value = codec.decode(hex) return Buffer.from(value) }
[ "function", "combine", "(", "shares", ")", "{", "const", "chunks", "=", "[", "]", "const", "x", "=", "[", "]", "const", "y", "=", "[", "]", "const", "t", "=", "shares", ".", "length", "for", "(", "let", "i", "=", "0", ";", "i", "<", "t", ";", "++", "i", ")", "{", "const", "share", "=", "parse", "(", "shares", "[", "i", "]", ")", "if", "(", "-", "1", "===", "x", ".", "indexOf", "(", "share", ".", "id", ")", ")", "{", "x", ".", "push", "(", "share", ".", "id", ")", "const", "bin", "=", "codec", ".", "bin", "(", "share", ".", "data", ",", "16", ")", "const", "parts", "=", "codec", ".", "split", "(", "bin", ",", "0", ",", "2", ")", "for", "(", "let", "j", "=", "0", ";", "j", "<", "parts", ".", "length", ";", "++", "j", ")", "{", "if", "(", "!", "y", "[", "j", "]", ")", "{", "y", "[", "j", "]", "=", "[", "]", "}", "y", "[", "j", "]", "[", "x", ".", "length", "-", "1", "]", "=", "parts", "[", "j", "]", "}", "}", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "y", ".", "length", ";", "++", "i", ")", "{", "const", "p", "=", "lagrange", "(", "0", ",", "[", "x", ",", "y", "[", "i", "]", "]", ")", "chunks", ".", "unshift", "(", "codec", ".", "pad", "(", "p", ".", "toString", "(", "2", ")", ")", ")", "}", "const", "string", "=", "chunks", ".", "join", "(", "''", ")", "const", "bin", "=", "string", ".", "slice", "(", "1", "+", "string", ".", "indexOf", "(", "'1'", ")", ")", "const", "hex", "=", "codec", ".", "hex", "(", "bin", ",", "BIN_ENCODING", ")", "const", "value", "=", "codec", ".", "decode", "(", "hex", ")", "return", "Buffer", ".", "from", "(", "value", ")", "}" ]
Reconstruct a secret from a distinct set of shares. @public @param {Array<String|Buffer>} shares @return {Buffer}
[ "Reconstruct", "a", "secret", "from", "a", "distinct", "set", "of", "shares", "." ]
1d7f2166854462c711c2f074f560e19ce8cf507c
https://github.com/jwerle/shamirs-secret-sharing/blob/1d7f2166854462c711c2f074f560e19ce8cf507c/combine.js#L12-L45
train
Redsmin/proxy
lib/Endpoint.js
function(sourceWasAnError, shouldNotReconnect) { log.error("[Endpoint] Connection closed " + (sourceWasAnError ? 'because of an error:' + sourceWasAnError : '')); this.connected = false; this.handshaken = false; this.connecting = false; if (!shouldNotReconnect) { log.debug('onClose():: reconnecting...'); this.handshakenBackoff.reset(); this.reconnectBackoff.backoff(); } else { log.debug('onClose():: don\'t reconnect'); this.handshakenBackoff.reset(); this.reconnectBackoff.reset(); } this.emit('close', sourceWasAnError); }
javascript
function(sourceWasAnError, shouldNotReconnect) { log.error("[Endpoint] Connection closed " + (sourceWasAnError ? 'because of an error:' + sourceWasAnError : '')); this.connected = false; this.handshaken = false; this.connecting = false; if (!shouldNotReconnect) { log.debug('onClose():: reconnecting...'); this.handshakenBackoff.reset(); this.reconnectBackoff.backoff(); } else { log.debug('onClose():: don\'t reconnect'); this.handshakenBackoff.reset(); this.reconnectBackoff.reset(); } this.emit('close', sourceWasAnError); }
[ "function", "(", "sourceWasAnError", ",", "shouldNotReconnect", ")", "{", "log", ".", "error", "(", "\"[Endpoint] Connection closed \"", "+", "(", "sourceWasAnError", "?", "'because of an error:'", "+", "sourceWasAnError", ":", "''", ")", ")", ";", "this", ".", "connected", "=", "false", ";", "this", ".", "handshaken", "=", "false", ";", "this", ".", "connecting", "=", "false", ";", "if", "(", "!", "shouldNotReconnect", ")", "{", "log", ".", "debug", "(", "'onClose():: reconnecting...'", ")", ";", "this", ".", "handshakenBackoff", ".", "reset", "(", ")", ";", "this", ".", "reconnectBackoff", ".", "backoff", "(", ")", ";", "}", "else", "{", "log", ".", "debug", "(", "'onClose():: don\\'t reconnect'", ")", ";", "\\'", "this", ".", "handshakenBackoff", ".", "reset", "(", ")", ";", "}", "this", ".", "reconnectBackoff", ".", "reset", "(", ")", ";", "}" ]
If the connection to redsmin just closed, try to reconnect @param {Error} err @param {Boolean} true if after the on close the Endpoint should not reconnect
[ "If", "the", "connection", "to", "redsmin", "just", "closed", "try", "to", "reconnect" ]
5f652d5382f0a38921679027e82053676d5fd89e
https://github.com/Redsmin/proxy/blob/5f652d5382f0a38921679027e82053676d5fd89e/lib/Endpoint.js#L238-L256
train
Redsmin/proxy
lib/RedisClient.js
function (err) { log.error("Redis client closed " + (err ? err.message : '')); this.connected = false; this.emit('close', err); this.backoff.reset(); this.backoff.backoff(); }
javascript
function (err) { log.error("Redis client closed " + (err ? err.message : '')); this.connected = false; this.emit('close', err); this.backoff.reset(); this.backoff.backoff(); }
[ "function", "(", "err", ")", "{", "log", ".", "error", "(", "\"Redis client closed \"", "+", "(", "err", "?", "err", ".", "message", ":", "''", ")", ")", ";", "this", ".", "connected", "=", "false", ";", "this", ".", "emit", "(", "'close'", ",", "err", ")", ";", "this", ".", "backoff", ".", "reset", "(", ")", ";", "this", ".", "backoff", ".", "backoff", "(", ")", ";", "}" ]
If the connection to redis just closed, try to reconnect @param {Error} err
[ "If", "the", "connection", "to", "redis", "just", "closed", "try", "to", "reconnect" ]
5f652d5382f0a38921679027e82053676d5fd89e
https://github.com/Redsmin/proxy/blob/5f652d5382f0a38921679027e82053676d5fd89e/lib/RedisClient.js#L148-L154
train
jugglinmike/srcdoc-polyfill
srcdoc-polyfill.js
function( iframe, options ) { var sandbox = iframe.getAttribute("sandbox"); if (typeof sandbox === "string" && !sandboxAllow.test(sandbox)) { if (options && options.force) { iframe.removeAttribute("sandbox"); } else if (!options || options.force !== false) { logError(sandboxMsg); iframe.setAttribute("data-srcdoc-polyfill", sandboxMsg); } } }
javascript
function( iframe, options ) { var sandbox = iframe.getAttribute("sandbox"); if (typeof sandbox === "string" && !sandboxAllow.test(sandbox)) { if (options && options.force) { iframe.removeAttribute("sandbox"); } else if (!options || options.force !== false) { logError(sandboxMsg); iframe.setAttribute("data-srcdoc-polyfill", sandboxMsg); } } }
[ "function", "(", "iframe", ",", "options", ")", "{", "var", "sandbox", "=", "iframe", ".", "getAttribute", "(", "\"sandbox\"", ")", ";", "if", "(", "typeof", "sandbox", "===", "\"string\"", "&&", "!", "sandboxAllow", ".", "test", "(", "sandbox", ")", ")", "{", "if", "(", "options", "&&", "options", ".", "force", ")", "{", "iframe", ".", "removeAttribute", "(", "\"sandbox\"", ")", ";", "}", "else", "if", "(", "!", "options", "||", "options", ".", "force", "!==", "false", ")", "{", "logError", "(", "sandboxMsg", ")", ";", "iframe", ".", "setAttribute", "(", "\"data-srcdoc-polyfill\"", ",", "sandboxMsg", ")", ";", "}", "}", "}" ]
Determine if the operation may be blocked by the `sandbox` attribute in some environments, and optionally issue a warning or remove the attribute.
[ "Determine", "if", "the", "operation", "may", "be", "blocked", "by", "the", "sandbox", "attribute", "in", "some", "environments", "and", "optionally", "issue", "a", "warning", "or", "remove", "the", "attribute", "." ]
af5a41ca819ceeb77bf6ee7aaf152d987b8aab92
https://github.com/jugglinmike/srcdoc-polyfill/blob/af5a41ca819ceeb77bf6ee7aaf152d987b8aab92/srcdoc-polyfill.js#L28-L38
train
dfsq/json-server-init
src/create/add-another.js
addAnother
function addAnother(schema) { var config = { properties: { another: { description: 'Add another collection? (y/n)'.magenta } } }; prompt.start(); prompt.message = ' > '; prompt.delimiter = ''; return new Promise(function(resolve, reject) { prompt.get(config, function(err, result) { if (err) return reject(err); switch (result.another.toLowerCase()) { case 'n': return resolve({ answer: false, schema: schema }); case 'y': default: return resolve({ answer: true, schema: schema }); } }); }); }
javascript
function addAnother(schema) { var config = { properties: { another: { description: 'Add another collection? (y/n)'.magenta } } }; prompt.start(); prompt.message = ' > '; prompt.delimiter = ''; return new Promise(function(resolve, reject) { prompt.get(config, function(err, result) { if (err) return reject(err); switch (result.another.toLowerCase()) { case 'n': return resolve({ answer: false, schema: schema }); case 'y': default: return resolve({ answer: true, schema: schema }); } }); }); }
[ "function", "addAnother", "(", "schema", ")", "{", "var", "config", "=", "{", "properties", ":", "{", "another", ":", "{", "description", ":", "'Add another collection? (y/n)'", ".", "magenta", "}", "}", "}", ";", "prompt", ".", "start", "(", ")", ";", "prompt", ".", "message", "=", "' > '", ";", "prompt", ".", "delimiter", "=", "''", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "prompt", ".", "get", "(", "config", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "switch", "(", "result", ".", "another", ".", "toLowerCase", "(", ")", ")", "{", "case", "'n'", ":", "return", "resolve", "(", "{", "answer", ":", "false", ",", "schema", ":", "schema", "}", ")", ";", "case", "'y'", ":", "default", ":", "return", "resolve", "(", "{", "answer", ":", "true", ",", "schema", ":", "schema", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Prompt to ask if another collection should be added to schema. @return {Promise}
[ "Prompt", "to", "ask", "if", "another", "collection", "should", "be", "added", "to", "schema", "." ]
1daf20c9014794fb2c6e9f16759946367078b55f
https://github.com/dfsq/json-server-init/blob/1daf20c9014794fb2c6e9f16759946367078b55f/src/create/add-another.js#L8-L42
train
dfsq/json-server-init
src/create/add-collection.js
getCollection
function getCollection() { var config = { properties: { collection: { description: 'Collection name and number of rows, 5 if omitted (ex: posts 10): '.magenta, type: 'string', required: true } } }; prompt.start(); prompt.message = ' > '; prompt.delimiter = ''; return new Promise(function(resolve, reject) { prompt.get(config, function(err, result) { if (err) return reject(err); return resolve(result.collection); }); }); }
javascript
function getCollection() { var config = { properties: { collection: { description: 'Collection name and number of rows, 5 if omitted (ex: posts 10): '.magenta, type: 'string', required: true } } }; prompt.start(); prompt.message = ' > '; prompt.delimiter = ''; return new Promise(function(resolve, reject) { prompt.get(config, function(err, result) { if (err) return reject(err); return resolve(result.collection); }); }); }
[ "function", "getCollection", "(", ")", "{", "var", "config", "=", "{", "properties", ":", "{", "collection", ":", "{", "description", ":", "'Collection name and number of rows, 5 if omitted (ex: posts 10): '", ".", "magenta", ",", "type", ":", "'string'", ",", "required", ":", "true", "}", "}", "}", ";", "prompt", ".", "start", "(", ")", ";", "prompt", ".", "message", "=", "' > '", ";", "prompt", ".", "delimiter", "=", "''", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "prompt", ".", "get", "(", "config", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "return", "resolve", "(", "result", ".", "collection", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Prompt for collection name. @return {Promise}
[ "Prompt", "for", "collection", "name", "." ]
1daf20c9014794fb2c6e9f16759946367078b55f
https://github.com/dfsq/json-server-init/blob/1daf20c9014794fb2c6e9f16759946367078b55f/src/create/add-collection.js#L10-L32
train
dfsq/json-server-init
src/create/add-collection.js
getFields
function getFields(collection) { var message = 'What fields should "' + collection + '" have?\n', config; config = { properties: { fields: { description: message.magenta + ' Comma-separated fieldname:fieldtype pairs (ex: id:index, username:username)\n'.grey, type: 'string', required: true, pattern: FIELDS_REGEXP } } }; prompt.start(); prompt.message = ' >> '; prompt.delimiter = ''; return new Promise(function(resolve, reject) { prompt.get(config, function(err, result) { if (err) return reject(err); return resolve(result.fields); }); }).then(function(input) { return (input.match(FIELDS_REGEXP) || []).reduce(function(prev, curr) { var parts = curr.split(':'); prev[parts[0]] = parts[1].replace(/\+/g, '}~{'); // with "+" also support name={fistName}~{lastName} concatenations return prev; }, {}); }); }
javascript
function getFields(collection) { var message = 'What fields should "' + collection + '" have?\n', config; config = { properties: { fields: { description: message.magenta + ' Comma-separated fieldname:fieldtype pairs (ex: id:index, username:username)\n'.grey, type: 'string', required: true, pattern: FIELDS_REGEXP } } }; prompt.start(); prompt.message = ' >> '; prompt.delimiter = ''; return new Promise(function(resolve, reject) { prompt.get(config, function(err, result) { if (err) return reject(err); return resolve(result.fields); }); }).then(function(input) { return (input.match(FIELDS_REGEXP) || []).reduce(function(prev, curr) { var parts = curr.split(':'); prev[parts[0]] = parts[1].replace(/\+/g, '}~{'); // with "+" also support name={fistName}~{lastName} concatenations return prev; }, {}); }); }
[ "function", "getFields", "(", "collection", ")", "{", "var", "message", "=", "'What fields should \"'", "+", "collection", "+", "'\" have?\\n'", ",", "\\n", ";", "config", "config", "=", "{", "properties", ":", "{", "fields", ":", "{", "description", ":", "message", ".", "magenta", "+", "' Comma-separated fieldname:fieldtype pairs (ex: id:index, username:username)\\n'", ".", "\\n", ",", "grey", ",", "type", ":", "'string'", ",", "required", ":", "true", "}", "}", "}", ";", "pattern", ":", "FIELDS_REGEXP", "prompt", ".", "start", "(", ")", ";", "prompt", ".", "message", "=", "' >> '", ";", "}" ]
Prompt for collection fields. @return {Promise}
[ "Prompt", "for", "collection", "fields", "." ]
1daf20c9014794fb2c6e9f16759946367078b55f
https://github.com/dfsq/json-server-init/blob/1daf20c9014794fb2c6e9f16759946367078b55f/src/create/add-collection.js#L38-L71
train
dfsq/json-server-init
src/create/write-json.js
writeJSON
function writeJSON(dbName, schema) { var baseUrl = 'http://www.filltext.com/?', promises = [], collection; for (collection in schema) { var meta = schema[collection].meta, fields = meta.fields, url; url = Object.keys(fields).map(function(key) { if (fields[key][0] === '[' && fields[key].slice(-1) === ']') { return key + '=' + fields[key]; } return key + '={' + fields[key] + '}'; }).join('&') + '&rows=' + meta.rows; console.log('Url for', collection, url); (function(c) { promises.push(fetch(baseUrl + url).then(function(response) { return response.json(); }) .then(function(rows) { schema[c] = rows; })); })(collection); } return Promise.all(promises).then(function() { fs.writeFile(dbName, JSON.stringify(schema, null, 4), function(err) { if (err) { Promise.reject('Failed to save JSON file: ' + err); } }); }); }
javascript
function writeJSON(dbName, schema) { var baseUrl = 'http://www.filltext.com/?', promises = [], collection; for (collection in schema) { var meta = schema[collection].meta, fields = meta.fields, url; url = Object.keys(fields).map(function(key) { if (fields[key][0] === '[' && fields[key].slice(-1) === ']') { return key + '=' + fields[key]; } return key + '={' + fields[key] + '}'; }).join('&') + '&rows=' + meta.rows; console.log('Url for', collection, url); (function(c) { promises.push(fetch(baseUrl + url).then(function(response) { return response.json(); }) .then(function(rows) { schema[c] = rows; })); })(collection); } return Promise.all(promises).then(function() { fs.writeFile(dbName, JSON.stringify(schema, null, 4), function(err) { if (err) { Promise.reject('Failed to save JSON file: ' + err); } }); }); }
[ "function", "writeJSON", "(", "dbName", ",", "schema", ")", "{", "var", "baseUrl", "=", "'http://www.filltext.com/?'", ",", "promises", "=", "[", "]", ",", "collection", ";", "for", "(", "collection", "in", "schema", ")", "{", "var", "meta", "=", "schema", "[", "collection", "]", ".", "meta", ",", "fields", "=", "meta", ".", "fields", ",", "url", ";", "url", "=", "Object", ".", "keys", "(", "fields", ")", ".", "map", "(", "function", "(", "key", ")", "{", "if", "(", "fields", "[", "key", "]", "[", "0", "]", "===", "'['", "&&", "fields", "[", "key", "]", ".", "slice", "(", "-", "1", ")", "===", "']'", ")", "{", "return", "key", "+", "'='", "+", "fields", "[", "key", "]", ";", "}", "return", "key", "+", "'={'", "+", "fields", "[", "key", "]", "+", "'}'", ";", "}", ")", ".", "join", "(", "'&'", ")", "+", "'&rows='", "+", "meta", ".", "rows", ";", "console", ".", "log", "(", "'Url for'", ",", "collection", ",", "url", ")", ";", "(", "function", "(", "c", ")", "{", "promises", ".", "push", "(", "fetch", "(", "baseUrl", "+", "url", ")", ".", "then", "(", "function", "(", "response", ")", "{", "return", "response", ".", "json", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "rows", ")", "{", "schema", "[", "c", "]", "=", "rows", ";", "}", ")", ")", ";", "}", ")", "(", "collection", ")", ";", "}", "return", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "function", "(", ")", "{", "fs", ".", "writeFile", "(", "dbName", ",", "JSON", ".", "stringify", "(", "schema", ",", "null", ",", "4", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "Promise", ".", "reject", "(", "'Failed to save JSON file: '", "+", "err", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Writes generated JSON into file. @param dbName {String} Name of the file to create. @param schema {Object} Populated object of collections. @return {Promise}
[ "Writes", "generated", "JSON", "into", "file", "." ]
1daf20c9014794fb2c6e9f16759946367078b55f
https://github.com/dfsq/json-server-init/blob/1daf20c9014794fb2c6e9f16759946367078b55f/src/create/write-json.js#L15-L53
train
teambition/merge2
index.js
pauseStreams
function pauseStreams (streams, options) { if (!Array.isArray(streams)) { // Backwards-compat with old-style streams if (!streams._readableState && streams.pipe) streams = streams.pipe(PassThrough(options)) if (!streams._readableState || !streams.pause || !streams.pipe) { throw new Error('Only readable stream can be merged.') } streams.pause() } else { for (let i = 0, len = streams.length; i < len; i++) streams[i] = pauseStreams(streams[i], options) } return streams }
javascript
function pauseStreams (streams, options) { if (!Array.isArray(streams)) { // Backwards-compat with old-style streams if (!streams._readableState && streams.pipe) streams = streams.pipe(PassThrough(options)) if (!streams._readableState || !streams.pause || !streams.pipe) { throw new Error('Only readable stream can be merged.') } streams.pause() } else { for (let i = 0, len = streams.length; i < len; i++) streams[i] = pauseStreams(streams[i], options) } return streams }
[ "function", "pauseStreams", "(", "streams", ",", "options", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "streams", ")", ")", "{", "if", "(", "!", "streams", ".", "_readableState", "&&", "streams", ".", "pipe", ")", "streams", "=", "streams", ".", "pipe", "(", "PassThrough", "(", "options", ")", ")", "if", "(", "!", "streams", ".", "_readableState", "||", "!", "streams", ".", "pause", "||", "!", "streams", ".", "pipe", ")", "{", "throw", "new", "Error", "(", "'Only readable stream can be merged.'", ")", "}", "streams", ".", "pause", "(", ")", "}", "else", "{", "for", "(", "let", "i", "=", "0", ",", "len", "=", "streams", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "streams", "[", "i", "]", "=", "pauseStreams", "(", "streams", "[", "i", "]", ",", "options", ")", "}", "return", "streams", "}" ]
check and pause streams for pipe.
[ "check", "and", "pause", "streams", "for", "pipe", "." ]
d2f21832a16c8eb24c853b3e7cb133040688c898
https://github.com/teambition/merge2/blob/d2f21832a16c8eb24c853b3e7cb133040688c898/index.js#L95-L107
train
reelyactive/advlib
lib/reelyactive/data/index.js
process
function process(payload) { var batteryRaw = parseInt(payload.substr(2,2),16) % 64; var temperatureRaw = (parseInt(payload.substr(0,3),16) >> 2) % 256; var battery = ((batteryRaw / 34) + 1.8).toFixed(2) + "V"; var temperature = ((temperatureRaw - 80) / 2).toFixed(1) + "C"; return { battery: battery, temperature: temperature }; }
javascript
function process(payload) { var batteryRaw = parseInt(payload.substr(2,2),16) % 64; var temperatureRaw = (parseInt(payload.substr(0,3),16) >> 2) % 256; var battery = ((batteryRaw / 34) + 1.8).toFixed(2) + "V"; var temperature = ((temperatureRaw - 80) / 2).toFixed(1) + "C"; return { battery: battery, temperature: temperature }; }
[ "function", "process", "(", "payload", ")", "{", "var", "batteryRaw", "=", "parseInt", "(", "payload", ".", "substr", "(", "2", ",", "2", ")", ",", "16", ")", "%", "64", ";", "var", "temperatureRaw", "=", "(", "parseInt", "(", "payload", ".", "substr", "(", "0", ",", "3", ")", ",", "16", ")", ">>", "2", ")", "%", "256", ";", "var", "battery", "=", "(", "(", "batteryRaw", "/", "34", ")", "+", "1.8", ")", ".", "toFixed", "(", "2", ")", "+", "\"V\"", ";", "var", "temperature", "=", "(", "(", "temperatureRaw", "-", "80", ")", "/", "2", ")", ".", "toFixed", "(", "1", ")", "+", "\"C\"", ";", "return", "{", "battery", ":", "battery", ",", "temperature", ":", "temperature", "}", ";", "}" ]
Convert a raw radio sensor data payload. @param {string} payload The raw payload as a hexadecimal-string. @return {object} Sensor data.
[ "Convert", "a", "raw", "radio", "sensor", "data", "payload", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/reelyactive/data/index.js#L6-L15
train
reelyactive/advlib
lib/ble/index.js
process
function process(payload) { payload = payload.toLowerCase(); var advA48 = address.process(payload.substr(4,12)); advA48.advHeader = header.process(payload.substr(0,4)); advA48.advData = data.process(payload.substr(16)); return advA48; }
javascript
function process(payload) { payload = payload.toLowerCase(); var advA48 = address.process(payload.substr(4,12)); advA48.advHeader = header.process(payload.substr(0,4)); advA48.advData = data.process(payload.substr(16)); return advA48; }
[ "function", "process", "(", "payload", ")", "{", "payload", "=", "payload", ".", "toLowerCase", "(", ")", ";", "var", "advA48", "=", "address", ".", "process", "(", "payload", ".", "substr", "(", "4", ",", "12", ")", ")", ";", "advA48", ".", "advHeader", "=", "header", ".", "process", "(", "payload", ".", "substr", "(", "0", ",", "4", ")", ")", ";", "advA48", ".", "advData", "=", "data", ".", "process", "(", "payload", ".", "substr", "(", "16", ")", ")", ";", "return", "advA48", ";", "}" ]
Process a raw Bluetooth Low Energy radio payload into semantically meaningful information. address. Note that the payload is LSB first. @param {string} payload The raw payload as a hexadecimal-string. @return {AdvA48} Advertiser address identifier.
[ "Process", "a", "raw", "Bluetooth", "Low", "Energy", "radio", "payload", "into", "semantically", "meaningful", "information", ".", "address", ".", "Note", "that", "the", "payload", "is", "LSB", "first", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/index.js#L21-L28
train
reelyactive/advlib
lib/ble/data/gap/servicedata.js
process
function process(data) { var uuid = data.substr(2,2) + data.substr(0,2); // NOTE: this is for legacy compatibility var advertiserData = { serviceData: { uuid: uuid, data: data.substr(4) } }; gattservices.process(advertiserData); return advertiserData.serviceData; }
javascript
function process(data) { var uuid = data.substr(2,2) + data.substr(0,2); // NOTE: this is for legacy compatibility var advertiserData = { serviceData: { uuid: uuid, data: data.substr(4) } }; gattservices.process(advertiserData); return advertiserData.serviceData; }
[ "function", "process", "(", "data", ")", "{", "var", "uuid", "=", "data", ".", "substr", "(", "2", ",", "2", ")", "+", "data", ".", "substr", "(", "0", ",", "2", ")", ";", "var", "advertiserData", "=", "{", "serviceData", ":", "{", "uuid", ":", "uuid", ",", "data", ":", "data", ".", "substr", "(", "4", ")", "}", "}", ";", "gattservices", ".", "process", "(", "advertiserData", ")", ";", "return", "advertiserData", ".", "serviceData", ";", "}" ]
Parse BLE advertiser service data. @param {string} data The raw service data as a hexadecimal-string.
[ "Parse", "BLE", "advertiser", "service", "data", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/data/gap/servicedata.js#L14-L28
train
reelyactive/advlib
lib/ble/common/manufacturers/apple/index.js
process
function process(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var cursor = 0; // Apple sometimes includes more than one service data while(cursor < data.length) { var appleType = data.substr(cursor,2); switch(appleType) { case '01': return; // TODO: decipher this type (one bit set in fixed length?) case '02': cursor = ibeacon.process(advertiserData, cursor); break; case '05': cursor = airdrop.process(advertiserData, cursor); break; case '07': cursor = airpods.process(advertiserData, cursor); break; case '08': cursor = service.process(advertiserData, cursor); // TODO: decipher break; case '09': cursor = airplay.process(advertiserData, cursor); break; case '0a': cursor = airplay.process(advertiserData, cursor); break; case '0b': cursor = service.process(advertiserData, cursor); // TODO: decipher break; case '0c': cursor = handoff.process(advertiserData, cursor); break; case '10': cursor = nearby.process(advertiserData, cursor); break; default: return; // Don't trust types that haven't yet been observed } } }
javascript
function process(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var cursor = 0; // Apple sometimes includes more than one service data while(cursor < data.length) { var appleType = data.substr(cursor,2); switch(appleType) { case '01': return; // TODO: decipher this type (one bit set in fixed length?) case '02': cursor = ibeacon.process(advertiserData, cursor); break; case '05': cursor = airdrop.process(advertiserData, cursor); break; case '07': cursor = airpods.process(advertiserData, cursor); break; case '08': cursor = service.process(advertiserData, cursor); // TODO: decipher break; case '09': cursor = airplay.process(advertiserData, cursor); break; case '0a': cursor = airplay.process(advertiserData, cursor); break; case '0b': cursor = service.process(advertiserData, cursor); // TODO: decipher break; case '0c': cursor = handoff.process(advertiserData, cursor); break; case '10': cursor = nearby.process(advertiserData, cursor); break; default: return; // Don't trust types that haven't yet been observed } } }
[ "function", "process", "(", "advertiserData", ")", "{", "var", "data", "=", "advertiserData", ".", "manufacturerSpecificData", ".", "data", ";", "var", "cursor", "=", "0", ";", "while", "(", "cursor", "<", "data", ".", "length", ")", "{", "var", "appleType", "=", "data", ".", "substr", "(", "cursor", ",", "2", ")", ";", "switch", "(", "appleType", ")", "{", "case", "'01'", ":", "return", ";", "case", "'02'", ":", "cursor", "=", "ibeacon", ".", "process", "(", "advertiserData", ",", "cursor", ")", ";", "break", ";", "case", "'05'", ":", "cursor", "=", "airdrop", ".", "process", "(", "advertiserData", ",", "cursor", ")", ";", "break", ";", "case", "'07'", ":", "cursor", "=", "airpods", ".", "process", "(", "advertiserData", ",", "cursor", ")", ";", "break", ";", "case", "'08'", ":", "cursor", "=", "service", ".", "process", "(", "advertiserData", ",", "cursor", ")", ";", "break", ";", "case", "'09'", ":", "cursor", "=", "airplay", ".", "process", "(", "advertiserData", ",", "cursor", ")", ";", "break", ";", "case", "'0a'", ":", "cursor", "=", "airplay", ".", "process", "(", "advertiserData", ",", "cursor", ")", ";", "break", ";", "case", "'0b'", ":", "cursor", "=", "service", ".", "process", "(", "advertiserData", ",", "cursor", ")", ";", "break", ";", "case", "'0c'", ":", "cursor", "=", "handoff", ".", "process", "(", "advertiserData", ",", "cursor", ")", ";", "break", ";", "case", "'10'", ":", "cursor", "=", "nearby", ".", "process", "(", "advertiserData", ",", "cursor", ")", ";", "break", ";", "default", ":", "return", ";", "}", "}", "}" ]
Parse BLE advertiser manufacturer specific data for Apple. @param {Object} advertiserData The object containing all parsed data.
[ "Parse", "BLE", "advertiser", "manufacturer", "specific", "data", "for", "Apple", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/common/manufacturers/apple/index.js#L19-L61
train
reelyactive/advlib
lib/ble/header/index.js
process
function process(payload) { var addressType = parseInt(payload.substr(0,1),16); var typeCode = payload.substr(1,1); var length = parseInt(payload.substr(2,2),16) % 64; var rxAdd = "public"; var txAdd = "public"; if(addressType & 0x8) { rxAdd = "random"; } if(addressType & 0x4) { txAdd = "random"; } var type; switch(typeCode) { case("0"): type = TYPE0_NAME; break; case("1"): type = TYPE1_NAME; break; case("2"): type = TYPE2_NAME; break; case("3"): type = TYPE3_NAME; break; case("4"): type = TYPE4_NAME; break; case("5"): type = TYPE5_NAME; break; case("6"): type = TYPE6_NAME; break; default: type = TYPE_UNDEFINED_NAME; } return { type: type, length: length, txAdd: txAdd, rxAdd: rxAdd }; }
javascript
function process(payload) { var addressType = parseInt(payload.substr(0,1),16); var typeCode = payload.substr(1,1); var length = parseInt(payload.substr(2,2),16) % 64; var rxAdd = "public"; var txAdd = "public"; if(addressType & 0x8) { rxAdd = "random"; } if(addressType & 0x4) { txAdd = "random"; } var type; switch(typeCode) { case("0"): type = TYPE0_NAME; break; case("1"): type = TYPE1_NAME; break; case("2"): type = TYPE2_NAME; break; case("3"): type = TYPE3_NAME; break; case("4"): type = TYPE4_NAME; break; case("5"): type = TYPE5_NAME; break; case("6"): type = TYPE6_NAME; break; default: type = TYPE_UNDEFINED_NAME; } return { type: type, length: length, txAdd: txAdd, rxAdd: rxAdd }; }
[ "function", "process", "(", "payload", ")", "{", "var", "addressType", "=", "parseInt", "(", "payload", ".", "substr", "(", "0", ",", "1", ")", ",", "16", ")", ";", "var", "typeCode", "=", "payload", ".", "substr", "(", "1", ",", "1", ")", ";", "var", "length", "=", "parseInt", "(", "payload", ".", "substr", "(", "2", ",", "2", ")", ",", "16", ")", "%", "64", ";", "var", "rxAdd", "=", "\"public\"", ";", "var", "txAdd", "=", "\"public\"", ";", "if", "(", "addressType", "&", "0x8", ")", "{", "rxAdd", "=", "\"random\"", ";", "}", "if", "(", "addressType", "&", "0x4", ")", "{", "txAdd", "=", "\"random\"", ";", "}", "var", "type", ";", "switch", "(", "typeCode", ")", "{", "case", "(", "\"0\"", ")", ":", "type", "=", "TYPE0_NAME", ";", "break", ";", "case", "(", "\"1\"", ")", ":", "type", "=", "TYPE1_NAME", ";", "break", ";", "case", "(", "\"2\"", ")", ":", "type", "=", "TYPE2_NAME", ";", "break", ";", "case", "(", "\"3\"", ")", ":", "type", "=", "TYPE3_NAME", ";", "break", ";", "case", "(", "\"4\"", ")", ":", "type", "=", "TYPE4_NAME", ";", "break", ";", "case", "(", "\"5\"", ")", ":", "type", "=", "TYPE5_NAME", ";", "break", ";", "case", "(", "\"6\"", ")", ":", "type", "=", "TYPE6_NAME", ";", "break", ";", "default", ":", "type", "=", "TYPE_UNDEFINED_NAME", ";", "}", "return", "{", "type", ":", "type", ",", "length", ":", "length", ",", "txAdd", ":", "txAdd", ",", "rxAdd", ":", "rxAdd", "}", ";", "}" ]
Convert a raw Bluetooth Low Energy advertiser header into its meaningful parts. @param {string} payload The raw payload as a hexadecimal-string. @return {Object} Semantically meaningful advertiser header.
[ "Convert", "a", "raw", "Bluetooth", "Low", "Energy", "advertiser", "header", "into", "its", "meaningful", "parts", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/header/index.js#L23-L66
train
reelyactive/advlib
lib/ble/data/gatt/services/members/google.js
processEddystone
function processEddystone(advertiserData) { var data = advertiserData.serviceData.data; var eddystone = {}; var frameType = data.substr(0,2); switch(frameType) { // UID case '00': eddystone.type = 'UID'; eddystone.txPower = pdu.convertTxPower(data.substr(2,2)); eddystone.uid = {}; eddystone.uid.namespace = data.substr(4,20); eddystone.uid.instance = data.substr(24,12); break; // URI case '10': eddystone.type = 'URL'; eddystone.txPower = pdu.convertTxPower(data.substr(2,2)); eddystone.url = parseSchemePrefix(data.substr(4,2)); eddystone.url += parseEncodedUrl(data.substr(6)); break; // TLM case '20': eddystone.type = 'TLM'; eddystone.version = data.substr(2,2); if(eddystone.version === '00') { eddystone.batteryVoltage = parseInt(data.substr(4,4),16) + 'mV'; // TODO: export 8:8 fixed point representation interpreter to pdu eddystone.temperature = parseInt(data.substr(8,4),16); if(eddystone.temperature > 0x7fff) { eddystone.temperature = 0x7fff - eddystone.temperature; } eddystone.temperature = (eddystone.temperature / 256) + 'C'; eddystone.advertisingCount = parseInt(data.substr(12,8),16); eddystone.uptime = (parseInt(data.substr(20,8),16) / 10) + 's'; } else if(eddystone.version === '01') { eddystone.etlm = data.substr(4,24); eddystone.salt = data.substr(28,4); eddystone.mic = data.substr(32,4); } break; // EID case '30': eddystone.type = 'EID'; eddystone.txPower = pdu.convertTxPower(data.substr(2,2)); eddystone.eid = data.substr(4,16); break; } advertiserData.serviceData.eddystone = eddystone; }
javascript
function processEddystone(advertiserData) { var data = advertiserData.serviceData.data; var eddystone = {}; var frameType = data.substr(0,2); switch(frameType) { // UID case '00': eddystone.type = 'UID'; eddystone.txPower = pdu.convertTxPower(data.substr(2,2)); eddystone.uid = {}; eddystone.uid.namespace = data.substr(4,20); eddystone.uid.instance = data.substr(24,12); break; // URI case '10': eddystone.type = 'URL'; eddystone.txPower = pdu.convertTxPower(data.substr(2,2)); eddystone.url = parseSchemePrefix(data.substr(4,2)); eddystone.url += parseEncodedUrl(data.substr(6)); break; // TLM case '20': eddystone.type = 'TLM'; eddystone.version = data.substr(2,2); if(eddystone.version === '00') { eddystone.batteryVoltage = parseInt(data.substr(4,4),16) + 'mV'; // TODO: export 8:8 fixed point representation interpreter to pdu eddystone.temperature = parseInt(data.substr(8,4),16); if(eddystone.temperature > 0x7fff) { eddystone.temperature = 0x7fff - eddystone.temperature; } eddystone.temperature = (eddystone.temperature / 256) + 'C'; eddystone.advertisingCount = parseInt(data.substr(12,8),16); eddystone.uptime = (parseInt(data.substr(20,8),16) / 10) + 's'; } else if(eddystone.version === '01') { eddystone.etlm = data.substr(4,24); eddystone.salt = data.substr(28,4); eddystone.mic = data.substr(32,4); } break; // EID case '30': eddystone.type = 'EID'; eddystone.txPower = pdu.convertTxPower(data.substr(2,2)); eddystone.eid = data.substr(4,16); break; } advertiserData.serviceData.eddystone = eddystone; }
[ "function", "processEddystone", "(", "advertiserData", ")", "{", "var", "data", "=", "advertiserData", ".", "serviceData", ".", "data", ";", "var", "eddystone", "=", "{", "}", ";", "var", "frameType", "=", "data", ".", "substr", "(", "0", ",", "2", ")", ";", "switch", "(", "frameType", ")", "{", "case", "'00'", ":", "eddystone", ".", "type", "=", "'UID'", ";", "eddystone", ".", "txPower", "=", "pdu", ".", "convertTxPower", "(", "data", ".", "substr", "(", "2", ",", "2", ")", ")", ";", "eddystone", ".", "uid", "=", "{", "}", ";", "eddystone", ".", "uid", ".", "namespace", "=", "data", ".", "substr", "(", "4", ",", "20", ")", ";", "eddystone", ".", "uid", ".", "instance", "=", "data", ".", "substr", "(", "24", ",", "12", ")", ";", "break", ";", "case", "'10'", ":", "eddystone", ".", "type", "=", "'URL'", ";", "eddystone", ".", "txPower", "=", "pdu", ".", "convertTxPower", "(", "data", ".", "substr", "(", "2", ",", "2", ")", ")", ";", "eddystone", ".", "url", "=", "parseSchemePrefix", "(", "data", ".", "substr", "(", "4", ",", "2", ")", ")", ";", "eddystone", ".", "url", "+=", "parseEncodedUrl", "(", "data", ".", "substr", "(", "6", ")", ")", ";", "break", ";", "case", "'20'", ":", "eddystone", ".", "type", "=", "'TLM'", ";", "eddystone", ".", "version", "=", "data", ".", "substr", "(", "2", ",", "2", ")", ";", "if", "(", "eddystone", ".", "version", "===", "'00'", ")", "{", "eddystone", ".", "batteryVoltage", "=", "parseInt", "(", "data", ".", "substr", "(", "4", ",", "4", ")", ",", "16", ")", "+", "'mV'", ";", "eddystone", ".", "temperature", "=", "parseInt", "(", "data", ".", "substr", "(", "8", ",", "4", ")", ",", "16", ")", ";", "if", "(", "eddystone", ".", "temperature", ">", "0x7fff", ")", "{", "eddystone", ".", "temperature", "=", "0x7fff", "-", "eddystone", ".", "temperature", ";", "}", "eddystone", ".", "temperature", "=", "(", "eddystone", ".", "temperature", "/", "256", ")", "+", "'C'", ";", "eddystone", ".", "advertisingCount", "=", "parseInt", "(", "data", ".", "substr", "(", "12", ",", "8", ")", ",", "16", ")", ";", "eddystone", ".", "uptime", "=", "(", "parseInt", "(", "data", ".", "substr", "(", "20", ",", "8", ")", ",", "16", ")", "/", "10", ")", "+", "'s'", ";", "}", "else", "if", "(", "eddystone", ".", "version", "===", "'01'", ")", "{", "eddystone", ".", "etlm", "=", "data", ".", "substr", "(", "4", ",", "24", ")", ";", "eddystone", ".", "salt", "=", "data", ".", "substr", "(", "28", ",", "4", ")", ";", "eddystone", ".", "mic", "=", "data", ".", "substr", "(", "32", ",", "4", ")", ";", "}", "break", ";", "case", "'30'", ":", "eddystone", ".", "type", "=", "'EID'", ";", "eddystone", ".", "txPower", "=", "pdu", ".", "convertTxPower", "(", "data", ".", "substr", "(", "2", ",", "2", ")", ")", ";", "eddystone", ".", "eid", "=", "data", ".", "substr", "(", "4", ",", "16", ")", ";", "break", ";", "}", "advertiserData", ".", "serviceData", ".", "eddystone", "=", "eddystone", ";", "}" ]
Parse BLE advertiser Eddystone data. @param {Object} advertiserData The object containing all parsed data.
[ "Parse", "BLE", "advertiser", "Eddystone", "data", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/data/gatt/services/members/google.js#L57-L113
train
reelyactive/advlib
lib/ble/data/gatt/services/members/google.js
parseEncodedUrl
function parseEncodedUrl(encodedUrl) { var url = ''; for(var cChar = 0; cChar < (encodedUrl.length / 2); cChar++) { var charCode = parseInt(encodedUrl.substr(cChar*2,2),16); switch(charCode) { case 0x00: url += ".com/"; break; case 0x01: url += ".org/"; break; case 0x02: url += ".edu/"; break; case 0x03: url += ".net/"; break; case 0x04: url += ".info/"; break; case 0x05: url += ".biz/"; break; case 0x06: url += ".gov/"; break; case 0x07: url += ".com"; break; case 0x08: url += ".org"; break; case 0x09: url += ".edu"; break; case 0x0a: url += ".net"; break; case 0x0b: url += ".info"; break; case 0x0c: url += ".biz"; break; case 0x0d: url += ".gov"; break; default: url += String.fromCharCode(charCode); } } return url; }
javascript
function parseEncodedUrl(encodedUrl) { var url = ''; for(var cChar = 0; cChar < (encodedUrl.length / 2); cChar++) { var charCode = parseInt(encodedUrl.substr(cChar*2,2),16); switch(charCode) { case 0x00: url += ".com/"; break; case 0x01: url += ".org/"; break; case 0x02: url += ".edu/"; break; case 0x03: url += ".net/"; break; case 0x04: url += ".info/"; break; case 0x05: url += ".biz/"; break; case 0x06: url += ".gov/"; break; case 0x07: url += ".com"; break; case 0x08: url += ".org"; break; case 0x09: url += ".edu"; break; case 0x0a: url += ".net"; break; case 0x0b: url += ".info"; break; case 0x0c: url += ".biz"; break; case 0x0d: url += ".gov"; break; default: url += String.fromCharCode(charCode); } } return url; }
[ "function", "parseEncodedUrl", "(", "encodedUrl", ")", "{", "var", "url", "=", "''", ";", "for", "(", "var", "cChar", "=", "0", ";", "cChar", "<", "(", "encodedUrl", ".", "length", "/", "2", ")", ";", "cChar", "++", ")", "{", "var", "charCode", "=", "parseInt", "(", "encodedUrl", ".", "substr", "(", "cChar", "*", "2", ",", "2", ")", ",", "16", ")", ";", "switch", "(", "charCode", ")", "{", "case", "0x00", ":", "url", "+=", "\".com/\"", ";", "break", ";", "case", "0x01", ":", "url", "+=", "\".org/\"", ";", "break", ";", "case", "0x02", ":", "url", "+=", "\".edu/\"", ";", "break", ";", "case", "0x03", ":", "url", "+=", "\".net/\"", ";", "break", ";", "case", "0x04", ":", "url", "+=", "\".info/\"", ";", "break", ";", "case", "0x05", ":", "url", "+=", "\".biz/\"", ";", "break", ";", "case", "0x06", ":", "url", "+=", "\".gov/\"", ";", "break", ";", "case", "0x07", ":", "url", "+=", "\".com\"", ";", "break", ";", "case", "0x08", ":", "url", "+=", "\".org\"", ";", "break", ";", "case", "0x09", ":", "url", "+=", "\".edu\"", ";", "break", ";", "case", "0x0a", ":", "url", "+=", "\".net\"", ";", "break", ";", "case", "0x0b", ":", "url", "+=", "\".info\"", ";", "break", ";", "case", "0x0c", ":", "url", "+=", "\".biz\"", ";", "break", ";", "case", "0x0d", ":", "url", "+=", "\".gov\"", ";", "break", ";", "default", ":", "url", "+=", "String", ".", "fromCharCode", "(", "charCode", ")", ";", "}", "}", "return", "url", ";", "}" ]
Parse encoded URL. @param {String} encodedUrl The encoded URL as a hexadecimal string. @return {String} The suffix of the URL.
[ "Parse", "encoded", "URL", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/data/gatt/services/members/google.js#L149-L203
train
reelyactive/advlib
lib/reelyactive/common/util/identifier.js
Identifier
function Identifier(type, value) { var isValue = (value != null); // Constructor for EUI-64 if((type == TYPE_EUI64) && isValue) { this.type = TYPE_EUI64; this.value = value; } // Constructor for RA-28 else if((type == TYPE_RA28) && isValue) { this.type = TYPE_RA28; this.value = value.substr(value.length - 7, 7); } // Constructor for ADVA-48 else if((type == TYPE_ADVA48) && isValue) { this.type = TYPE_ADVA48; this.value = value; } // Constructor for RadioPayload else if((type = TYPE_RADIO_PAYLOAD) && isValue) { this.type = TYPE_RADIO_PAYLOAD; this.value = value.payload; this.lengthBytes = value.payloadLengthBytes; } // Constructor for Undefined else { this.type = TYPE_UNDEFINED; this.value = null; } }
javascript
function Identifier(type, value) { var isValue = (value != null); // Constructor for EUI-64 if((type == TYPE_EUI64) && isValue) { this.type = TYPE_EUI64; this.value = value; } // Constructor for RA-28 else if((type == TYPE_RA28) && isValue) { this.type = TYPE_RA28; this.value = value.substr(value.length - 7, 7); } // Constructor for ADVA-48 else if((type == TYPE_ADVA48) && isValue) { this.type = TYPE_ADVA48; this.value = value; } // Constructor for RadioPayload else if((type = TYPE_RADIO_PAYLOAD) && isValue) { this.type = TYPE_RADIO_PAYLOAD; this.value = value.payload; this.lengthBytes = value.payloadLengthBytes; } // Constructor for Undefined else { this.type = TYPE_UNDEFINED; this.value = null; } }
[ "function", "Identifier", "(", "type", ",", "value", ")", "{", "var", "isValue", "=", "(", "value", "!=", "null", ")", ";", "if", "(", "(", "type", "==", "TYPE_EUI64", ")", "&&", "isValue", ")", "{", "this", ".", "type", "=", "TYPE_EUI64", ";", "this", ".", "value", "=", "value", ";", "}", "else", "if", "(", "(", "type", "==", "TYPE_RA28", ")", "&&", "isValue", ")", "{", "this", ".", "type", "=", "TYPE_RA28", ";", "this", ".", "value", "=", "value", ".", "substr", "(", "value", ".", "length", "-", "7", ",", "7", ")", ";", "}", "else", "if", "(", "(", "type", "==", "TYPE_ADVA48", ")", "&&", "isValue", ")", "{", "this", ".", "type", "=", "TYPE_ADVA48", ";", "this", ".", "value", "=", "value", ";", "}", "else", "if", "(", "(", "type", "=", "TYPE_RADIO_PAYLOAD", ")", "&&", "isValue", ")", "{", "this", ".", "type", "=", "TYPE_RADIO_PAYLOAD", ";", "this", ".", "value", "=", "value", ".", "payload", ";", "this", ".", "lengthBytes", "=", "value", ".", "payloadLengthBytes", ";", "}", "else", "{", "this", ".", "type", "=", "TYPE_UNDEFINED", ";", "this", ".", "value", "=", "null", ";", "}", "}" ]
Identifier Class Represents an identifier @param {string} type Type of identifier. @param {Object} value The value of the given identifier. @constructor
[ "Identifier", "Class", "Represents", "an", "identifier" ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/reelyactive/common/util/identifier.js#L25-L58
train
reelyactive/advlib
lib/ble/data/gap/manufacturerspecificdata.js
process
function process(data) { var companyIdentifierCode = data.substr(2,2); companyIdentifierCode += data.substr(0,2); var companyName = companyIdentifierCodes.companyNames[companyIdentifierCode]; if(typeof companyName === 'undefined') { companyName = 'Unknown'; } // NOTE: this is for legacy compatibility var advertiserData = { manufacturerSpecificData: { companyName : companyName, companyIdentifierCode: companyIdentifierCode, data: data.substr(4) } }; // Handle the unique case of AltBeacon if(altbeacon.isAltBeacon(advertiserData)) { altbeacon.process(advertiserData); return advertiserData.manufacturerSpecificData; } // Interpret the manufacturer specific data, if possible // Kindly respect ascending order of company identifier codes switch(companyIdentifierCode) { case '004c': apple.process(advertiserData); return advertiserData.manufacturerSpecificData; case '00f9': sticknfind.process(advertiserData); return advertiserData.manufacturerSpecificData; case '015d': estimote.process(advertiserData); return advertiserData.manufacturerSpecificData; case '0274': motsai.process(advertiserData); return advertiserData.manufacturerSpecificData; case '0583': codebluecommunications.process(advertiserData); return advertiserData.manufacturerSpecificData; default: return advertiserData.manufacturerSpecificData; } }
javascript
function process(data) { var companyIdentifierCode = data.substr(2,2); companyIdentifierCode += data.substr(0,2); var companyName = companyIdentifierCodes.companyNames[companyIdentifierCode]; if(typeof companyName === 'undefined') { companyName = 'Unknown'; } // NOTE: this is for legacy compatibility var advertiserData = { manufacturerSpecificData: { companyName : companyName, companyIdentifierCode: companyIdentifierCode, data: data.substr(4) } }; // Handle the unique case of AltBeacon if(altbeacon.isAltBeacon(advertiserData)) { altbeacon.process(advertiserData); return advertiserData.manufacturerSpecificData; } // Interpret the manufacturer specific data, if possible // Kindly respect ascending order of company identifier codes switch(companyIdentifierCode) { case '004c': apple.process(advertiserData); return advertiserData.manufacturerSpecificData; case '00f9': sticknfind.process(advertiserData); return advertiserData.manufacturerSpecificData; case '015d': estimote.process(advertiserData); return advertiserData.manufacturerSpecificData; case '0274': motsai.process(advertiserData); return advertiserData.manufacturerSpecificData; case '0583': codebluecommunications.process(advertiserData); return advertiserData.manufacturerSpecificData; default: return advertiserData.manufacturerSpecificData; } }
[ "function", "process", "(", "data", ")", "{", "var", "companyIdentifierCode", "=", "data", ".", "substr", "(", "2", ",", "2", ")", ";", "companyIdentifierCode", "+=", "data", ".", "substr", "(", "0", ",", "2", ")", ";", "var", "companyName", "=", "companyIdentifierCodes", ".", "companyNames", "[", "companyIdentifierCode", "]", ";", "if", "(", "typeof", "companyName", "===", "'undefined'", ")", "{", "companyName", "=", "'Unknown'", ";", "}", "var", "advertiserData", "=", "{", "manufacturerSpecificData", ":", "{", "companyName", ":", "companyName", ",", "companyIdentifierCode", ":", "companyIdentifierCode", ",", "data", ":", "data", ".", "substr", "(", "4", ")", "}", "}", ";", "if", "(", "altbeacon", ".", "isAltBeacon", "(", "advertiserData", ")", ")", "{", "altbeacon", ".", "process", "(", "advertiserData", ")", ";", "return", "advertiserData", ".", "manufacturerSpecificData", ";", "}", "switch", "(", "companyIdentifierCode", ")", "{", "case", "'004c'", ":", "apple", ".", "process", "(", "advertiserData", ")", ";", "return", "advertiserData", ".", "manufacturerSpecificData", ";", "case", "'00f9'", ":", "sticknfind", ".", "process", "(", "advertiserData", ")", ";", "return", "advertiserData", ".", "manufacturerSpecificData", ";", "case", "'015d'", ":", "estimote", ".", "process", "(", "advertiserData", ")", ";", "return", "advertiserData", ".", "manufacturerSpecificData", ";", "case", "'0274'", ":", "motsai", ".", "process", "(", "advertiserData", ")", ";", "return", "advertiserData", ".", "manufacturerSpecificData", ";", "case", "'0583'", ":", "codebluecommunications", ".", "process", "(", "advertiserData", ")", ";", "return", "advertiserData", ".", "manufacturerSpecificData", ";", "default", ":", "return", "advertiserData", ".", "manufacturerSpecificData", ";", "}", "}" ]
Parse BLE advertiser data manufacturer specific data. @param {string} data The raw manufacturer data as a hexadecimal-string. @param {number} cursor The start index within the payload. @param {Object} advertiserData The object containing all parsed data.
[ "Parse", "BLE", "advertiser", "data", "manufacturer", "specific", "data", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/data/gap/manufacturerspecificdata.js#L25-L70
train
reelyactive/advlib
lib/ble/address/index.js
process
function process(payload) { var advAString = payload.substr(10,2); advAString += payload.substr(8,2); advAString += payload.substr(6,2); advAString += payload.substr(4,2); advAString += payload.substr(2,2); advAString += payload.substr(0,2); return new identifier(identifier.ADVA48, advAString); }
javascript
function process(payload) { var advAString = payload.substr(10,2); advAString += payload.substr(8,2); advAString += payload.substr(6,2); advAString += payload.substr(4,2); advAString += payload.substr(2,2); advAString += payload.substr(0,2); return new identifier(identifier.ADVA48, advAString); }
[ "function", "process", "(", "payload", ")", "{", "var", "advAString", "=", "payload", ".", "substr", "(", "10", ",", "2", ")", ";", "advAString", "+=", "payload", ".", "substr", "(", "8", ",", "2", ")", ";", "advAString", "+=", "payload", ".", "substr", "(", "6", ",", "2", ")", ";", "advAString", "+=", "payload", ".", "substr", "(", "4", ",", "2", ")", ";", "advAString", "+=", "payload", ".", "substr", "(", "2", ",", "2", ")", ";", "advAString", "+=", "payload", ".", "substr", "(", "0", ",", "2", ")", ";", "return", "new", "identifier", "(", "identifier", ".", "ADVA48", ",", "advAString", ")", ";", "}" ]
Convert a raw Bluetooth Low Energy advertiser address. @param {string} payload The raw payload as a hexadecimal-string. @return {Object} 48-bit advertiser address.
[ "Convert", "a", "raw", "Bluetooth", "Low", "Energy", "advertiser", "address", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/address/index.js#L13-L21
train
reelyactive/advlib
lib/ble/data/gap/flags.js
process
function process(data) { var flags = parseInt(data, 16); var result = []; if(flags & 0x01) { result.push(BIT0_NAME); } if(flags & 0x02) { result.push(BIT1_NAME); } if(flags & 0x04) { result.push(BIT2_NAME); } if(flags & 0x08) { result.push(BIT3_NAME); } if(flags & 0x10) { result.push(BIT4_NAME); } if(flags & 0x20) { result.push(BIT5_NAME); } return result; }
javascript
function process(data) { var flags = parseInt(data, 16); var result = []; if(flags & 0x01) { result.push(BIT0_NAME); } if(flags & 0x02) { result.push(BIT1_NAME); } if(flags & 0x04) { result.push(BIT2_NAME); } if(flags & 0x08) { result.push(BIT3_NAME); } if(flags & 0x10) { result.push(BIT4_NAME); } if(flags & 0x20) { result.push(BIT5_NAME); } return result; }
[ "function", "process", "(", "data", ")", "{", "var", "flags", "=", "parseInt", "(", "data", ",", "16", ")", ";", "var", "result", "=", "[", "]", ";", "if", "(", "flags", "&", "0x01", ")", "{", "result", ".", "push", "(", "BIT0_NAME", ")", ";", "}", "if", "(", "flags", "&", "0x02", ")", "{", "result", ".", "push", "(", "BIT1_NAME", ")", ";", "}", "if", "(", "flags", "&", "0x04", ")", "{", "result", ".", "push", "(", "BIT2_NAME", ")", ";", "}", "if", "(", "flags", "&", "0x08", ")", "{", "result", ".", "push", "(", "BIT3_NAME", ")", ";", "}", "if", "(", "flags", "&", "0x10", ")", "{", "result", ".", "push", "(", "BIT4_NAME", ")", ";", "}", "if", "(", "flags", "&", "0x20", ")", "{", "result", ".", "push", "(", "BIT5_NAME", ")", ";", "}", "return", "result", ";", "}" ]
Parse BLE advertiser data flags. @param {string} data The raw flag data as a hexadecimal-string.
[ "Parse", "BLE", "advertiser", "data", "flags", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/data/gap/flags.js#L19-L41
train
reelyactive/advlib
lib/ble/common/manufacturers/sticknfind/index.js
process
function process(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var packetType = data.substr(0,2); switch(packetType) { case '01': snfsingle.process(advertiserData); break; case '42': snsmotion.process(advertiserData); break; default: } }
javascript
function process(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var packetType = data.substr(0,2); switch(packetType) { case '01': snfsingle.process(advertiserData); break; case '42': snsmotion.process(advertiserData); break; default: } }
[ "function", "process", "(", "advertiserData", ")", "{", "var", "data", "=", "advertiserData", ".", "manufacturerSpecificData", ".", "data", ";", "var", "packetType", "=", "data", ".", "substr", "(", "0", ",", "2", ")", ";", "switch", "(", "packetType", ")", "{", "case", "'01'", ":", "snfsingle", ".", "process", "(", "advertiserData", ")", ";", "break", ";", "case", "'42'", ":", "snsmotion", ".", "process", "(", "advertiserData", ")", ";", "break", ";", "default", ":", "}", "}" ]
Parse BLE advertiser manufacturer specific data for StickNFind. @param {Object} advertiserData The object containing all parsed data.
[ "Parse", "BLE", "advertiser", "manufacturer", "specific", "data", "for", "StickNFind", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/common/manufacturers/sticknfind/index.js#L14-L27
train
reelyactive/advlib
lib/ble/common/manufacturers/apple/ibeacon.js
process
function process(advertiserData, cursor) { var iBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; iBeacon.uuid = data.substr(4,32); iBeacon.major = data.substr(36,4); iBeacon.minor = data.substr(40,4); iBeacon.txPower = pdu.convertTxPower(data.substr(44,2)); var licenseeName = licenseeNames[iBeacon.uuid]; if(typeof licenseeName === 'undefined') { licenseeName = 'Unknown'; } iBeacon.licenseeName = licenseeName; advertiserData.manufacturerSpecificData.iBeacon = iBeacon; return cursor + 46; }
javascript
function process(advertiserData, cursor) { var iBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; iBeacon.uuid = data.substr(4,32); iBeacon.major = data.substr(36,4); iBeacon.minor = data.substr(40,4); iBeacon.txPower = pdu.convertTxPower(data.substr(44,2)); var licenseeName = licenseeNames[iBeacon.uuid]; if(typeof licenseeName === 'undefined') { licenseeName = 'Unknown'; } iBeacon.licenseeName = licenseeName; advertiserData.manufacturerSpecificData.iBeacon = iBeacon; return cursor + 46; }
[ "function", "process", "(", "advertiserData", ",", "cursor", ")", "{", "var", "iBeacon", "=", "{", "}", ";", "var", "data", "=", "advertiserData", ".", "manufacturerSpecificData", ".", "data", ";", "iBeacon", ".", "uuid", "=", "data", ".", "substr", "(", "4", ",", "32", ")", ";", "iBeacon", ".", "major", "=", "data", ".", "substr", "(", "36", ",", "4", ")", ";", "iBeacon", ".", "minor", "=", "data", ".", "substr", "(", "40", ",", "4", ")", ";", "iBeacon", ".", "txPower", "=", "pdu", ".", "convertTxPower", "(", "data", ".", "substr", "(", "44", ",", "2", ")", ")", ";", "var", "licenseeName", "=", "licenseeNames", "[", "iBeacon", ".", "uuid", "]", ";", "if", "(", "typeof", "licenseeName", "===", "'undefined'", ")", "{", "licenseeName", "=", "'Unknown'", ";", "}", "iBeacon", ".", "licenseeName", "=", "licenseeName", ";", "advertiserData", ".", "manufacturerSpecificData", ".", "iBeacon", "=", "iBeacon", ";", "return", "cursor", "+", "46", ";", "}" ]
Parse Apple iBeacon manufacturer specific data. @param {Object} advertiserData The object containing all parsed data. @param {Number} cursor The current index into the raw data.
[ "Parse", "Apple", "iBeacon", "manufacturer", "specific", "data", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/common/manufacturers/apple/ibeacon.js#L39-L57
train
reelyactive/advlib
lib/ble/common/manufacturers/radiusnetworks/altbeacon.js
process
function process(advertiserData) { var altBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; altBeacon.id = data.substr(4,40); altBeacon.refRSSI = pdu.convertTxPower(data.substr(44,2)); altBeacon.mfgReserved = data.substr(46,2); advertiserData.manufacturerSpecificData.altBeacon = altBeacon; }
javascript
function process(advertiserData) { var altBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; altBeacon.id = data.substr(4,40); altBeacon.refRSSI = pdu.convertTxPower(data.substr(44,2)); altBeacon.mfgReserved = data.substr(46,2); advertiserData.manufacturerSpecificData.altBeacon = altBeacon; }
[ "function", "process", "(", "advertiserData", ")", "{", "var", "altBeacon", "=", "{", "}", ";", "var", "data", "=", "advertiserData", ".", "manufacturerSpecificData", ".", "data", ";", "altBeacon", ".", "id", "=", "data", ".", "substr", "(", "4", ",", "40", ")", ";", "altBeacon", ".", "refRSSI", "=", "pdu", ".", "convertTxPower", "(", "data", ".", "substr", "(", "44", ",", "2", ")", ")", ";", "altBeacon", ".", "mfgReserved", "=", "data", ".", "substr", "(", "46", ",", "2", ")", ";", "advertiserData", ".", "manufacturerSpecificData", ".", "altBeacon", "=", "altBeacon", ";", "}" ]
Parse AltBeacon manufacturer specific data. @param {Object} advertiserData The object containing all parsed data.
[ "Parse", "AltBeacon", "manufacturer", "specific", "data", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/common/manufacturers/radiusnetworks/altbeacon.js#L18-L27
train
reelyactive/advlib
lib/ble/common/manufacturers/radiusnetworks/altbeacon.js
isAltBeacon
function isAltBeacon(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var isCorrectLength = ((data.length + 6) === (LENGTH * 2)); var isCorrectCode = (data.substr(0,4) === CODE); return isCorrectLength && isCorrectCode; }
javascript
function isAltBeacon(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var isCorrectLength = ((data.length + 6) === (LENGTH * 2)); var isCorrectCode = (data.substr(0,4) === CODE); return isCorrectLength && isCorrectCode; }
[ "function", "isAltBeacon", "(", "advertiserData", ")", "{", "var", "data", "=", "advertiserData", ".", "manufacturerSpecificData", ".", "data", ";", "var", "isCorrectLength", "=", "(", "(", "data", ".", "length", "+", "6", ")", "===", "(", "LENGTH", "*", "2", ")", ")", ";", "var", "isCorrectCode", "=", "(", "data", ".", "substr", "(", "0", ",", "4", ")", "===", "CODE", ")", ";", "return", "isCorrectLength", "&&", "isCorrectCode", ";", "}" ]
Verify if the given manufacturerSpecificData represents an AltBeacon. @param {Object} advertiserData The object containing all parsed data.
[ "Verify", "if", "the", "given", "manufacturerSpecificData", "represents", "an", "AltBeacon", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/common/manufacturers/radiusnetworks/altbeacon.js#L34-L40
train
reelyactive/advlib
lib/ble/data/gap/localname.js
process
function process(data) { var result = ''; for(var cChar = 0; cChar < data.length; cChar += 2) { result += String.fromCharCode(parseInt(data.substr(cChar,2),16)); } return result; }
javascript
function process(data) { var result = ''; for(var cChar = 0; cChar < data.length; cChar += 2) { result += String.fromCharCode(parseInt(data.substr(cChar,2),16)); } return result; }
[ "function", "process", "(", "data", ")", "{", "var", "result", "=", "''", ";", "for", "(", "var", "cChar", "=", "0", ";", "cChar", "<", "data", ".", "length", ";", "cChar", "+=", "2", ")", "{", "result", "+=", "String", ".", "fromCharCode", "(", "parseInt", "(", "data", ".", "substr", "(", "cChar", ",", "2", ")", ",", "16", ")", ")", ";", "}", "return", "result", ";", "}" ]
Parse BLE advertiser data non-complete shortened local name. @param {string} data The raw name data as a hexadecimal-string.
[ "Parse", "BLE", "advertiser", "data", "non", "-", "complete", "shortened", "local", "name", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/data/gap/localname.js#L14-L20
train
reelyactive/advlib
lib/ble/common/manufacturers/sticknfind/snsmotion.js
process
function process(advertiserData) { var snfBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; snfBeacon.type = 'SnS Motion'; snfBeacon.timestamp = parseInt(pdu.reverseBytes(data.substr(2,8)),16); snfBeacon.temperature = parseInt(data.substr(10,2),16); if(snfBeacon.temperature > 127) { snfBeacon.temperature = 127 - snfBeacon.temperature; } snfBeacon.temperature = snfBeacon.temperature / 2; snfBeacon.temperature += (parseInt(data.substr(41,1),16)) / 4; snfBeacon.batteryVoltage = data.substr(12,2); snfBeacon.eventCounters = []; snfBeacon.eventCounters.push(data.substr(26,1) + data.substr(14,2)); snfBeacon.eventCounters.push(data.substr(27,1) + data.substr(16,2)); snfBeacon.eventCounters.push(data.substr(28,1) + data.substr(18,2)); snfBeacon.eventCounters.push(data.substr(29,1) + data.substr(20,2)); snfBeacon.eventCounters.push(data.substr(30,1) + data.substr(22,2)); snfBeacon.eventCounters.push(data.substr(31,1) + data.substr(24,2)); for(var cCounter = 0; cCounter < 6; cCounter++) { var hexStringCount = snfBeacon.eventCounters[cCounter]; snfBeacon.eventCounters[cCounter] = parseInt(hexStringCount,16); } snfBeacon.accelerationX = parseInt((data.substr(32,2) + data.substr(38,1)), 16); snfBeacon.accelerationY = parseInt((data.substr(34,2) + data.substr(39,1)), 16); snfBeacon.accelerationZ = parseInt((data.substr(36,2) + data.substr(40,1)), 16); advertiserData.manufacturerSpecificData.snfBeacon = snfBeacon; }
javascript
function process(advertiserData) { var snfBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; snfBeacon.type = 'SnS Motion'; snfBeacon.timestamp = parseInt(pdu.reverseBytes(data.substr(2,8)),16); snfBeacon.temperature = parseInt(data.substr(10,2),16); if(snfBeacon.temperature > 127) { snfBeacon.temperature = 127 - snfBeacon.temperature; } snfBeacon.temperature = snfBeacon.temperature / 2; snfBeacon.temperature += (parseInt(data.substr(41,1),16)) / 4; snfBeacon.batteryVoltage = data.substr(12,2); snfBeacon.eventCounters = []; snfBeacon.eventCounters.push(data.substr(26,1) + data.substr(14,2)); snfBeacon.eventCounters.push(data.substr(27,1) + data.substr(16,2)); snfBeacon.eventCounters.push(data.substr(28,1) + data.substr(18,2)); snfBeacon.eventCounters.push(data.substr(29,1) + data.substr(20,2)); snfBeacon.eventCounters.push(data.substr(30,1) + data.substr(22,2)); snfBeacon.eventCounters.push(data.substr(31,1) + data.substr(24,2)); for(var cCounter = 0; cCounter < 6; cCounter++) { var hexStringCount = snfBeacon.eventCounters[cCounter]; snfBeacon.eventCounters[cCounter] = parseInt(hexStringCount,16); } snfBeacon.accelerationX = parseInt((data.substr(32,2) + data.substr(38,1)), 16); snfBeacon.accelerationY = parseInt((data.substr(34,2) + data.substr(39,1)), 16); snfBeacon.accelerationZ = parseInt((data.substr(36,2) + data.substr(40,1)), 16); advertiserData.manufacturerSpecificData.snfBeacon = snfBeacon; }
[ "function", "process", "(", "advertiserData", ")", "{", "var", "snfBeacon", "=", "{", "}", ";", "var", "data", "=", "advertiserData", ".", "manufacturerSpecificData", ".", "data", ";", "snfBeacon", ".", "type", "=", "'SnS Motion'", ";", "snfBeacon", ".", "timestamp", "=", "parseInt", "(", "pdu", ".", "reverseBytes", "(", "data", ".", "substr", "(", "2", ",", "8", ")", ")", ",", "16", ")", ";", "snfBeacon", ".", "temperature", "=", "parseInt", "(", "data", ".", "substr", "(", "10", ",", "2", ")", ",", "16", ")", ";", "if", "(", "snfBeacon", ".", "temperature", ">", "127", ")", "{", "snfBeacon", ".", "temperature", "=", "127", "-", "snfBeacon", ".", "temperature", ";", "}", "snfBeacon", ".", "temperature", "=", "snfBeacon", ".", "temperature", "/", "2", ";", "snfBeacon", ".", "temperature", "+=", "(", "parseInt", "(", "data", ".", "substr", "(", "41", ",", "1", ")", ",", "16", ")", ")", "/", "4", ";", "snfBeacon", ".", "batteryVoltage", "=", "data", ".", "substr", "(", "12", ",", "2", ")", ";", "snfBeacon", ".", "eventCounters", "=", "[", "]", ";", "snfBeacon", ".", "eventCounters", ".", "push", "(", "data", ".", "substr", "(", "26", ",", "1", ")", "+", "data", ".", "substr", "(", "14", ",", "2", ")", ")", ";", "snfBeacon", ".", "eventCounters", ".", "push", "(", "data", ".", "substr", "(", "27", ",", "1", ")", "+", "data", ".", "substr", "(", "16", ",", "2", ")", ")", ";", "snfBeacon", ".", "eventCounters", ".", "push", "(", "data", ".", "substr", "(", "28", ",", "1", ")", "+", "data", ".", "substr", "(", "18", ",", "2", ")", ")", ";", "snfBeacon", ".", "eventCounters", ".", "push", "(", "data", ".", "substr", "(", "29", ",", "1", ")", "+", "data", ".", "substr", "(", "20", ",", "2", ")", ")", ";", "snfBeacon", ".", "eventCounters", ".", "push", "(", "data", ".", "substr", "(", "30", ",", "1", ")", "+", "data", ".", "substr", "(", "22", ",", "2", ")", ")", ";", "snfBeacon", ".", "eventCounters", ".", "push", "(", "data", ".", "substr", "(", "31", ",", "1", ")", "+", "data", ".", "substr", "(", "24", ",", "2", ")", ")", ";", "for", "(", "var", "cCounter", "=", "0", ";", "cCounter", "<", "6", ";", "cCounter", "++", ")", "{", "var", "hexStringCount", "=", "snfBeacon", ".", "eventCounters", "[", "cCounter", "]", ";", "snfBeacon", ".", "eventCounters", "[", "cCounter", "]", "=", "parseInt", "(", "hexStringCount", ",", "16", ")", ";", "}", "snfBeacon", ".", "accelerationX", "=", "parseInt", "(", "(", "data", ".", "substr", "(", "32", ",", "2", ")", "+", "data", ".", "substr", "(", "38", ",", "1", ")", ")", ",", "16", ")", ";", "snfBeacon", ".", "accelerationY", "=", "parseInt", "(", "(", "data", ".", "substr", "(", "34", ",", "2", ")", "+", "data", ".", "substr", "(", "39", ",", "1", ")", ")", ",", "16", ")", ";", "snfBeacon", ".", "accelerationZ", "=", "parseInt", "(", "(", "data", ".", "substr", "(", "36", ",", "2", ")", "+", "data", ".", "substr", "(", "40", ",", "1", ")", ")", ",", "16", ")", ";", "advertiserData", ".", "manufacturerSpecificData", ".", "snfBeacon", "=", "snfBeacon", ";", "}" ]
Parse StickNSense 'motion' manufacturer specific data. @param {Object} advertiserData The object containing all parsed data.
[ "Parse", "StickNSense", "motion", "manufacturer", "specific", "data", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/common/manufacturers/sticknfind/snsmotion.js#L14-L46
train
reelyactive/advlib
lib/ble/common/manufacturers/sticknfind/snfsingle.js
process
function process(advertiserData) { var snfBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; snfBeacon.type = 'V2 Single Payload'; snfBeacon.id = pdu.reverseBytes(data.substr(2,16)); snfBeacon.time = parseInt(pdu.reverseBytes(data.substr(18,8)),16); snfBeacon.scanCount = parseInt(data.substr(26,2),16) / 4; snfBeacon.batteryVoltage = data.substr(28,2); snfBeacon.temperature = parseInt(data.substr(30,2),16); if(snfBeacon.temperature > 127) { snfBeacon.temperature = 127 - snfBeacon.temperature; } snfBeacon.temperature += (parseInt(data.substr(26,2),16) % 4) / 4; snfBeacon.calibration = data.substr(32,2); snfBeacon.checksum = data.substr(34,6); advertiserData.manufacturerSpecificData.snfBeacon = snfBeacon; }
javascript
function process(advertiserData) { var snfBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; snfBeacon.type = 'V2 Single Payload'; snfBeacon.id = pdu.reverseBytes(data.substr(2,16)); snfBeacon.time = parseInt(pdu.reverseBytes(data.substr(18,8)),16); snfBeacon.scanCount = parseInt(data.substr(26,2),16) / 4; snfBeacon.batteryVoltage = data.substr(28,2); snfBeacon.temperature = parseInt(data.substr(30,2),16); if(snfBeacon.temperature > 127) { snfBeacon.temperature = 127 - snfBeacon.temperature; } snfBeacon.temperature += (parseInt(data.substr(26,2),16) % 4) / 4; snfBeacon.calibration = data.substr(32,2); snfBeacon.checksum = data.substr(34,6); advertiserData.manufacturerSpecificData.snfBeacon = snfBeacon; }
[ "function", "process", "(", "advertiserData", ")", "{", "var", "snfBeacon", "=", "{", "}", ";", "var", "data", "=", "advertiserData", ".", "manufacturerSpecificData", ".", "data", ";", "snfBeacon", ".", "type", "=", "'V2 Single Payload'", ";", "snfBeacon", ".", "id", "=", "pdu", ".", "reverseBytes", "(", "data", ".", "substr", "(", "2", ",", "16", ")", ")", ";", "snfBeacon", ".", "time", "=", "parseInt", "(", "pdu", ".", "reverseBytes", "(", "data", ".", "substr", "(", "18", ",", "8", ")", ")", ",", "16", ")", ";", "snfBeacon", ".", "scanCount", "=", "parseInt", "(", "data", ".", "substr", "(", "26", ",", "2", ")", ",", "16", ")", "/", "4", ";", "snfBeacon", ".", "batteryVoltage", "=", "data", ".", "substr", "(", "28", ",", "2", ")", ";", "snfBeacon", ".", "temperature", "=", "parseInt", "(", "data", ".", "substr", "(", "30", ",", "2", ")", ",", "16", ")", ";", "if", "(", "snfBeacon", ".", "temperature", ">", "127", ")", "{", "snfBeacon", ".", "temperature", "=", "127", "-", "snfBeacon", ".", "temperature", ";", "}", "snfBeacon", ".", "temperature", "+=", "(", "parseInt", "(", "data", ".", "substr", "(", "26", ",", "2", ")", ",", "16", ")", "%", "4", ")", "/", "4", ";", "snfBeacon", ".", "calibration", "=", "data", ".", "substr", "(", "32", ",", "2", ")", ";", "snfBeacon", ".", "checksum", "=", "data", ".", "substr", "(", "34", ",", "6", ")", ";", "advertiserData", ".", "manufacturerSpecificData", ".", "snfBeacon", "=", "snfBeacon", ";", "}" ]
Parse StickNFind 'single payload' manufacturer specific data. @param {Object} advertiserData The object containing all parsed data.
[ "Parse", "StickNFind", "single", "payload", "manufacturer", "specific", "data", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/common/manufacturers/sticknfind/snfsingle.js#L14-L32
train
reelyactive/advlib
lib/reelyactive/index.js
process
function process(payload) { payload = payload.toLowerCase(); var ra28 = new identifier(identifier.RA28, payload.substr(0, 7)); var eui64 = ra28.toType(identifier.EUI64); eui64.flags = flags.process(payload.substr(7, 1)); if (payload.length === 12) { eui64.data = data.process(payload.substr(8, 4)); } return eui64; }
javascript
function process(payload) { payload = payload.toLowerCase(); var ra28 = new identifier(identifier.RA28, payload.substr(0, 7)); var eui64 = ra28.toType(identifier.EUI64); eui64.flags = flags.process(payload.substr(7, 1)); if (payload.length === 12) { eui64.data = data.process(payload.substr(8, 4)); } return eui64; }
[ "function", "process", "(", "payload", ")", "{", "payload", "=", "payload", ".", "toLowerCase", "(", ")", ";", "var", "ra28", "=", "new", "identifier", "(", "identifier", ".", "RA28", ",", "payload", ".", "substr", "(", "0", ",", "7", ")", ")", ";", "var", "eui64", "=", "ra28", ".", "toType", "(", "identifier", ".", "EUI64", ")", ";", "eui64", ".", "flags", "=", "flags", ".", "process", "(", "payload", ".", "substr", "(", "7", ",", "1", ")", ")", ";", "if", "(", "payload", ".", "length", "===", "12", ")", "{", "eui64", ".", "data", "=", "data", ".", "process", "(", "payload", ".", "substr", "(", "8", ",", "4", ")", ")", ";", "}", "return", "eui64", ";", "}" ]
Process a raw reelyActive radio payload into semantically meaningful information. @param {string} payload The raw payload as a hexadecimal-string. @return {EUI64} EUI-64 identifier.
[ "Process", "a", "raw", "reelyActive", "radio", "payload", "into", "semantically", "meaningful", "information", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/reelyactive/index.js#L18-L28
train
reelyactive/advlib
lib/ble/common/manufacturers/estimote/index.js
process
function process(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var packetType = data.substr(0,2); switch(packetType) { // Update when we have manufacturer documentation case '01': default: nearable.process(advertiserData); } }
javascript
function process(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var packetType = data.substr(0,2); switch(packetType) { // Update when we have manufacturer documentation case '01': default: nearable.process(advertiserData); } }
[ "function", "process", "(", "advertiserData", ")", "{", "var", "data", "=", "advertiserData", ".", "manufacturerSpecificData", ".", "data", ";", "var", "packetType", "=", "data", ".", "substr", "(", "0", ",", "2", ")", ";", "switch", "(", "packetType", ")", "{", "case", "'01'", ":", "default", ":", "nearable", ".", "process", "(", "advertiserData", ")", ";", "}", "}" ]
Parse BLE advertiser manufacturer specific data for Estimote. @param {Object} advertiserData The object containing all parsed data.
[ "Parse", "BLE", "advertiser", "manufacturer", "specific", "data", "for", "Estimote", "." ]
4c8eeb8bdb9c465536b257b51a908da20d6fff27
https://github.com/reelyactive/advlib/blob/4c8eeb8bdb9c465536b257b51a908da20d6fff27/lib/ble/common/manufacturers/estimote/index.js#L13-L22
train
santilland/plotty
src/plotty.js
addColorScale
function addColorScale(name, colors, positions) { if (colors.length !== positions.length) { throw new Error('Invalid color scale.'); } colorscales[name] = { colors, positions }; }
javascript
function addColorScale(name, colors, positions) { if (colors.length !== positions.length) { throw new Error('Invalid color scale.'); } colorscales[name] = { colors, positions }; }
[ "function", "addColorScale", "(", "name", ",", "colors", ",", "positions", ")", "{", "if", "(", "colors", ".", "length", "!==", "positions", ".", "length", ")", "{", "throw", "new", "Error", "(", "'Invalid color scale.'", ")", ";", "}", "colorscales", "[", "name", "]", "=", "{", "colors", ",", "positions", "}", ";", "}" ]
Add a new colorscale to the list of available colorscales. @memberof module:plotty @param {String} name the name of the newly defined color scale @param {String[]} colors the array containing the colors. Each entry shall adhere to the CSS color definitions. @param {Number[]} positions the value position for each of the colors
[ "Add", "a", "new", "colorscale", "to", "the", "list", "of", "available", "colorscales", "." ]
342f5f34a7053d17b6ca8ef2ae7646e716bffd1b
https://github.com/santilland/plotty/blob/342f5f34a7053d17b6ca8ef2ae7646e716bffd1b/src/plotty.js#L110-L115
train
santilland/plotty
src/plotty.js
renderColorScaleToCanvas
function renderColorScaleToCanvas(name, canvas) { /* eslint-disable no-param-reassign */ const csDef = colorscales[name]; canvas.height = 1; const ctx = canvas.getContext('2d'); if (Object.prototype.toString.call(csDef) === '[object Object]') { canvas.width = 256; const gradient = ctx.createLinearGradient(0, 0, 256, 1); for (let i = 0; i < csDef.colors.length; ++i) { gradient.addColorStop(csDef.positions[i], csDef.colors[i]); } ctx.fillStyle = gradient; ctx.fillRect(0, 0, 256, 1); } else if (Object.prototype.toString.call(csDef) === '[object Uint8Array]') { canvas.width = 256; const imgData = ctx.createImageData(256, 1); imgData.data.set(csDef); ctx.putImageData(imgData, 0, 0); } else { throw new Error('Color scale not defined.'); } /* eslint-enable no-param-reassign */ }
javascript
function renderColorScaleToCanvas(name, canvas) { /* eslint-disable no-param-reassign */ const csDef = colorscales[name]; canvas.height = 1; const ctx = canvas.getContext('2d'); if (Object.prototype.toString.call(csDef) === '[object Object]') { canvas.width = 256; const gradient = ctx.createLinearGradient(0, 0, 256, 1); for (let i = 0; i < csDef.colors.length; ++i) { gradient.addColorStop(csDef.positions[i], csDef.colors[i]); } ctx.fillStyle = gradient; ctx.fillRect(0, 0, 256, 1); } else if (Object.prototype.toString.call(csDef) === '[object Uint8Array]') { canvas.width = 256; const imgData = ctx.createImageData(256, 1); imgData.data.set(csDef); ctx.putImageData(imgData, 0, 0); } else { throw new Error('Color scale not defined.'); } /* eslint-enable no-param-reassign */ }
[ "function", "renderColorScaleToCanvas", "(", "name", ",", "canvas", ")", "{", "const", "csDef", "=", "colorscales", "[", "name", "]", ";", "canvas", ".", "height", "=", "1", ";", "const", "ctx", "=", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "csDef", ")", "===", "'[object Object]'", ")", "{", "canvas", ".", "width", "=", "256", ";", "const", "gradient", "=", "ctx", ".", "createLinearGradient", "(", "0", ",", "0", ",", "256", ",", "1", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "csDef", ".", "colors", ".", "length", ";", "++", "i", ")", "{", "gradient", ".", "addColorStop", "(", "csDef", ".", "positions", "[", "i", "]", ",", "csDef", ".", "colors", "[", "i", "]", ")", ";", "}", "ctx", ".", "fillStyle", "=", "gradient", ";", "ctx", ".", "fillRect", "(", "0", ",", "0", ",", "256", ",", "1", ")", ";", "}", "else", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "csDef", ")", "===", "'[object Uint8Array]'", ")", "{", "canvas", ".", "width", "=", "256", ";", "const", "imgData", "=", "ctx", ".", "createImageData", "(", "256", ",", "1", ")", ";", "imgData", ".", "data", ".", "set", "(", "csDef", ")", ";", "ctx", ".", "putImageData", "(", "imgData", ",", "0", ",", "0", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Color scale not defined.'", ")", ";", "}", "}" ]
Render the colorscale to the specified canvas. @memberof module:plotty @param {String} name the name of the color scale to render @param {HTMLCanvasElement} canvas the canvas to render to
[ "Render", "the", "colorscale", "to", "the", "specified", "canvas", "." ]
342f5f34a7053d17b6ca8ef2ae7646e716bffd1b
https://github.com/santilland/plotty/blob/342f5f34a7053d17b6ca8ef2ae7646e716bffd1b/src/plotty.js#L123-L147
train
sentanos/roblox-js
examples/copacetic.js
clear
function clear () { var str = ''; for (var i = 0; i < 20; i++) { if (Math.random() < 0.5) { str += '\u200B'; } else { str += ' '; } } return str; }
javascript
function clear () { var str = ''; for (var i = 0; i < 20; i++) { if (Math.random() < 0.5) { str += '\u200B'; } else { str += ' '; } } return str; }
[ "function", "clear", "(", ")", "{", "var", "str", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "20", ";", "i", "++", ")", "{", "if", "(", "Math", ".", "random", "(", ")", "<", "0.5", ")", "{", "str", "+=", "'\\u200B'", ";", "}", "else", "\\u200B", "}", "{", "str", "+=", "' '", ";", "}", "}" ]
Bypass duplicate post blocking
[ "Bypass", "duplicate", "post", "blocking" ]
ded0d976e0691cf7bb771d06fee196e621633e29
https://github.com/sentanos/roblox-js/blob/ded0d976e0691cf7bb771d06fee196e621633e29/examples/copacetic.js#L13-L23
train
curran/model
examples/d3LinkedViews/main.js
setSizes
function setSizes(){ // Put the scatter plot on the left. scatterPlot.box = { x: 0, y: 0, width: div.clientWidth / 2, height: div.clientHeight }; // Put the bar chart on the right. barChart.box = { x: div.clientWidth / 2, y: 0, width: div.clientWidth / 2, height: div.clientHeight }; }
javascript
function setSizes(){ // Put the scatter plot on the left. scatterPlot.box = { x: 0, y: 0, width: div.clientWidth / 2, height: div.clientHeight }; // Put the bar chart on the right. barChart.box = { x: div.clientWidth / 2, y: 0, width: div.clientWidth / 2, height: div.clientHeight }; }
[ "function", "setSizes", "(", ")", "{", "scatterPlot", ".", "box", "=", "{", "x", ":", "0", ",", "y", ":", "0", ",", "width", ":", "div", ".", "clientWidth", "/", "2", ",", "height", ":", "div", ".", "clientHeight", "}", ";", "barChart", ".", "box", "=", "{", "x", ":", "div", ".", "clientWidth", "/", "2", ",", "y", ":", "0", ",", "width", ":", "div", ".", "clientWidth", "/", "2", ",", "height", ":", "div", ".", "clientHeight", "}", ";", "}" ]
Sets the `box` property on each visualization to arrange them within the container div.
[ "Sets", "the", "box", "property", "on", "each", "visualization", "to", "arrange", "them", "within", "the", "container", "div", "." ]
ad971f0d912e6f31cca33c467629c0c6f5279f9a
https://github.com/curran/model/blob/ad971f0d912e6f31cca33c467629c0c6f5279f9a/examples/d3LinkedViews/main.js#L74-L91
train
curran/model
examples/d3ParallelCoordinates/parallelCoordinates.js
path
function path(d) { return line(dimensions.map(function(p) { return [position(p), y[p](d[p])]; })); }
javascript
function path(d) { return line(dimensions.map(function(p) { return [position(p), y[p](d[p])]; })); }
[ "function", "path", "(", "d", ")", "{", "return", "line", "(", "dimensions", ".", "map", "(", "function", "(", "p", ")", "{", "return", "[", "position", "(", "p", ")", ",", "y", "[", "p", "]", "(", "d", "[", "p", "]", ")", "]", ";", "}", ")", ")", ";", "}" ]
Returns the path for a given data point.
[ "Returns", "the", "path", "for", "a", "given", "data", "point", "." ]
ad971f0d912e6f31cca33c467629c0c6f5279f9a
https://github.com/curran/model/blob/ad971f0d912e6f31cca33c467629c0c6f5279f9a/examples/d3ParallelCoordinates/parallelCoordinates.js#L138-L140
train
curran/model
examples/d3ParallelCoordinates/parallelCoordinates.js
brush
function brush() { var actives = dimensions.filter(function(p) { return !y[p].brush.empty(); }), extents = actives.map(function(p) { return y[p].brush.extent(); }), selectedPaths = foregroundPaths.filter(function(d) { return actives.every(function(p, i) { return extents[i][0] <= d[p] && d[p] <= extents[i][1]; }); }); foregroundPaths.style('display', 'none'); selectedPaths.style('display', null); model.selectedData = selectedPaths.data(); }
javascript
function brush() { var actives = dimensions.filter(function(p) { return !y[p].brush.empty(); }), extents = actives.map(function(p) { return y[p].brush.extent(); }), selectedPaths = foregroundPaths.filter(function(d) { return actives.every(function(p, i) { return extents[i][0] <= d[p] && d[p] <= extents[i][1]; }); }); foregroundPaths.style('display', 'none'); selectedPaths.style('display', null); model.selectedData = selectedPaths.data(); }
[ "function", "brush", "(", ")", "{", "var", "actives", "=", "dimensions", ".", "filter", "(", "function", "(", "p", ")", "{", "return", "!", "y", "[", "p", "]", ".", "brush", ".", "empty", "(", ")", ";", "}", ")", ",", "extents", "=", "actives", ".", "map", "(", "function", "(", "p", ")", "{", "return", "y", "[", "p", "]", ".", "brush", ".", "extent", "(", ")", ";", "}", ")", ",", "selectedPaths", "=", "foregroundPaths", ".", "filter", "(", "function", "(", "d", ")", "{", "return", "actives", ".", "every", "(", "function", "(", "p", ",", "i", ")", "{", "return", "extents", "[", "i", "]", "[", "0", "]", "<=", "d", "[", "p", "]", "&&", "d", "[", "p", "]", "<=", "extents", "[", "i", "]", "[", "1", "]", ";", "}", ")", ";", "}", ")", ";", "foregroundPaths", ".", "style", "(", "'display'", ",", "'none'", ")", ";", "selectedPaths", ".", "style", "(", "'display'", ",", "null", ")", ";", "model", ".", "selectedData", "=", "selectedPaths", ".", "data", "(", ")", ";", "}" ]
Handles a brush event, toggling the display of foreground lines.
[ "Handles", "a", "brush", "event", "toggling", "the", "display", "of", "foreground", "lines", "." ]
ad971f0d912e6f31cca33c467629c0c6f5279f9a
https://github.com/curran/model/blob/ad971f0d912e6f31cca33c467629c0c6f5279f9a/examples/d3ParallelCoordinates/parallelCoordinates.js#L143-L154
train
curran/model
examples/d3Bootstrap/main.js
type
function type(d) { // The '+' notation parses the string as a Number. d.sepalLength = +d.sepalLength; d.sepalWidth = +d.sepalWidth; return d; }
javascript
function type(d) { // The '+' notation parses the string as a Number. d.sepalLength = +d.sepalLength; d.sepalWidth = +d.sepalWidth; return d; }
[ "function", "type", "(", "d", ")", "{", "d", ".", "sepalLength", "=", "+", "d", ".", "sepalLength", ";", "d", ".", "sepalWidth", "=", "+", "d", ".", "sepalWidth", ";", "return", "d", ";", "}" ]
Called on each data element from the original table.
[ "Called", "on", "each", "data", "element", "from", "the", "original", "table", "." ]
ad971f0d912e6f31cca33c467629c0c6f5279f9a
https://github.com/curran/model/blob/ad971f0d912e6f31cca33c467629c0c6f5279f9a/examples/d3Bootstrap/main.js#L35-L40
train
curran/model
examples/bootstrapTable/main.js
setRandomData
function setRandomData(data){ // Include each key with a small chance var randomKeys = Object.keys(data[0]).filter(function(d){ return Math.random() < 0.5; }), // Make a copy of the objects with only the // random keys included. dataWithRandomKeys = data.map(function (d) { var e = {}; randomKeys.forEach(function (key) { e[key] = d[key]; }); return e; }), // Include each element with a small chance randomSample = dataWithRandomKeys.filter(function(d){ return Math.random() < 0.1; }); // Update the table with the random data. table.set({ data: randomSample, columns: randomKeys.map(function (key) { return { title: capitalize(key), property: key }; }) }); }
javascript
function setRandomData(data){ // Include each key with a small chance var randomKeys = Object.keys(data[0]).filter(function(d){ return Math.random() < 0.5; }), // Make a copy of the objects with only the // random keys included. dataWithRandomKeys = data.map(function (d) { var e = {}; randomKeys.forEach(function (key) { e[key] = d[key]; }); return e; }), // Include each element with a small chance randomSample = dataWithRandomKeys.filter(function(d){ return Math.random() < 0.1; }); // Update the table with the random data. table.set({ data: randomSample, columns: randomKeys.map(function (key) { return { title: capitalize(key), property: key }; }) }); }
[ "function", "setRandomData", "(", "data", ")", "{", "var", "randomKeys", "=", "Object", ".", "keys", "(", "data", "[", "0", "]", ")", ".", "filter", "(", "function", "(", "d", ")", "{", "return", "Math", ".", "random", "(", ")", "<", "0.5", ";", "}", ")", ",", "dataWithRandomKeys", "=", "data", ".", "map", "(", "function", "(", "d", ")", "{", "var", "e", "=", "{", "}", ";", "randomKeys", ".", "forEach", "(", "function", "(", "key", ")", "{", "e", "[", "key", "]", "=", "d", "[", "key", "]", ";", "}", ")", ";", "return", "e", ";", "}", ")", ",", "randomSample", "=", "dataWithRandomKeys", ".", "filter", "(", "function", "(", "d", ")", "{", "return", "Math", ".", "random", "(", ")", "<", "0.1", ";", "}", ")", ";", "table", ".", "set", "(", "{", "data", ":", "randomSample", ",", "columns", ":", "randomKeys", ".", "map", "(", "function", "(", "key", ")", "{", "return", "{", "title", ":", "capitalize", "(", "key", ")", ",", "property", ":", "key", "}", ";", "}", ")", "}", ")", ";", "}" ]
Sets a random sample of rows and columns on the table, for checking that the table responds properly.
[ "Sets", "a", "random", "sample", "of", "rows", "and", "columns", "on", "the", "table", "for", "checking", "that", "the", "table", "responds", "properly", "." ]
ad971f0d912e6f31cca33c467629c0c6f5279f9a
https://github.com/curran/model/blob/ad971f0d912e6f31cca33c467629c0c6f5279f9a/examples/bootstrapTable/main.js#L22-L54
train
curran/model
examples/d3LineChart/main.js
randomString
function randomString() { var possibilities = ['Frequency', 'Population', 'Alpha', 'Beta'], i = Math.round(Math.random() * possibilities.length); return possibilities[i]; }
javascript
function randomString() { var possibilities = ['Frequency', 'Population', 'Alpha', 'Beta'], i = Math.round(Math.random() * possibilities.length); return possibilities[i]; }
[ "function", "randomString", "(", ")", "{", "var", "possibilities", "=", "[", "'Frequency'", ",", "'Population'", ",", "'Alpha'", ",", "'Beta'", "]", ",", "i", "=", "Math", ".", "round", "(", "Math", ".", "random", "(", ")", "*", "possibilities", ".", "length", ")", ";", "return", "possibilities", "[", "i", "]", ";", "}" ]
Change the Y axis label every 600 ms.
[ "Change", "the", "Y", "axis", "label", "every", "600", "ms", "." ]
ad971f0d912e6f31cca33c467629c0c6f5279f9a
https://github.com/curran/model/blob/ad971f0d912e6f31cca33c467629c0c6f5279f9a/examples/d3LineChart/main.js#L58-L62
train
curran/model
src/model.js
track
function track(property, thisArg){ if(!(property in trackedProperties)){ trackedProperties[property] = true; values[property] = model[property]; Object.defineProperty(model, property, { get: function () { return values[property]; }, set: function(newValue) { var oldValue = values[property]; values[property] = newValue; getListeners(property).forEach(function(callback){ callback.call(thisArg, newValue, oldValue); }); } }); } }
javascript
function track(property, thisArg){ if(!(property in trackedProperties)){ trackedProperties[property] = true; values[property] = model[property]; Object.defineProperty(model, property, { get: function () { return values[property]; }, set: function(newValue) { var oldValue = values[property]; values[property] = newValue; getListeners(property).forEach(function(callback){ callback.call(thisArg, newValue, oldValue); }); } }); } }
[ "function", "track", "(", "property", ",", "thisArg", ")", "{", "if", "(", "!", "(", "property", "in", "trackedProperties", ")", ")", "{", "trackedProperties", "[", "property", "]", "=", "true", ";", "values", "[", "property", "]", "=", "model", "[", "property", "]", ";", "Object", ".", "defineProperty", "(", "model", ",", "property", ",", "{", "get", ":", "function", "(", ")", "{", "return", "values", "[", "property", "]", ";", "}", ",", "set", ":", "function", "(", "newValue", ")", "{", "var", "oldValue", "=", "values", "[", "property", "]", ";", "values", "[", "property", "]", "=", "newValue", ";", "getListeners", "(", "property", ")", ".", "forEach", "(", "function", "(", "callback", ")", "{", "callback", ".", "call", "(", "thisArg", ",", "newValue", ",", "oldValue", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", "}" ]
Tracks a property if it is not already tracked.
[ "Tracks", "a", "property", "if", "it", "is", "not", "already", "tracked", "." ]
ad971f0d912e6f31cca33c467629c0c6f5279f9a
https://github.com/curran/model/blob/ad971f0d912e6f31cca33c467629c0c6f5279f9a/src/model.js#L112-L127
train
curran/model
src/model.js
off
function off(property, callback){ listeners[property] = listeners[property].filter(function (listener) { return listener !== callback; }); }
javascript
function off(property, callback){ listeners[property] = listeners[property].filter(function (listener) { return listener !== callback; }); }
[ "function", "off", "(", "property", ",", "callback", ")", "{", "listeners", "[", "property", "]", "=", "listeners", "[", "property", "]", ".", "filter", "(", "function", "(", "listener", ")", "{", "return", "listener", "!==", "callback", ";", "}", ")", ";", "}" ]
Removes a change listener added using `on`.
[ "Removes", "a", "change", "listener", "added", "using", "on", "." ]
ad971f0d912e6f31cca33c467629c0c6f5279f9a
https://github.com/curran/model/blob/ad971f0d912e6f31cca33c467629c0c6f5279f9a/src/model.js#L137-L141
train
curran/model
cdn/model-v0.2.4.js
Model
function Model(defaults){ // Make sure "new" is always used, // so we can use "instanceof" to check if something is a Model. if (!(this instanceof Model)) { return new Model(defaults); } // `model` is the public API object returned from invoking `new Model()`. var model = this, // The internal stored values for tracked properties. { property -> value } values = {}, // The callback functions for each tracked property. { property -> [callback] } listeners = {}, // The set of tracked properties. { property -> true } trackedProperties = {}; // The functional reactive "when" operator. // // * `properties` An array of property names (can also be a single property string). // * `callback` A callback function that is called: // * with property values as arguments, ordered corresponding to the properties array, // * only if all specified properties have values, // * once for initialization, // * whenever one or more specified properties change, // * on the next tick of the JavaScript event loop after properties change, // * only once as a result of one or more synchronous changes to dependency properties. function when(properties, callback, thisArg){ // Make sure the default `this` becomes // the object you called `.on` on. thisArg = thisArg || this; // Handle either an array or a single string. properties = (properties instanceof Array) ? properties : [properties]; // This function will trigger the callback to be invoked. var listener = debounce(function (){ var args = properties.map(function(property){ return values[property]; }); if(allAreDefined(args)){ callback.apply(thisArg, args); } }); // Trigger the callback once for initialization. listener(); // Trigger the callback whenever specified properties change. properties.forEach(function(property){ on(property, listener); }); // Return this function so it can be removed later with `model.cancel(listener)`. return listener; } // Adds a change listener for a given property with Backbone-like behavior. // Similar to http://backbonejs.org/#Events-on function on(property, callback, thisArg){ thisArg = thisArg || this; getListeners(property).push(callback); track(property, thisArg); } // Gets or creates the array of listener functions for a given property. function getListeners(property){ return listeners[property] || (listeners[property] = []); } // Tracks a property if it is not already tracked. function track(property, thisArg){ if(!(property in trackedProperties)){ trackedProperties[property] = true; values[property] = model[property]; Object.defineProperty(model, property, { get: function () { return values[property]; }, set: function(newValue) { var oldValue = values[property]; values[property] = newValue; getListeners(property).forEach(function(callback){ callback.call(thisArg, newValue, oldValue); }); } }); } } // Cancels a listener returned by a call to `model.when(...)`. function cancel(listener){ for(var property in listeners){ off(property, listener); } } // Removes a change listener added using `on`. function off(property, callback){ listeners[property] = listeners[property].filter(function (listener) { return listener !== callback; }); } // Sets all of the given values on the model. // `newValues` is an object { property -> value }. function set(newValues){ for(var property in newValues){ model[property] = newValues[property]; } } // Transfer defaults passed into the constructor to the model. set(defaults); // Public API. model.when = when; model.cancel = cancel; model.on = on; model.off = off; model.set = set; }
javascript
function Model(defaults){ // Make sure "new" is always used, // so we can use "instanceof" to check if something is a Model. if (!(this instanceof Model)) { return new Model(defaults); } // `model` is the public API object returned from invoking `new Model()`. var model = this, // The internal stored values for tracked properties. { property -> value } values = {}, // The callback functions for each tracked property. { property -> [callback] } listeners = {}, // The set of tracked properties. { property -> true } trackedProperties = {}; // The functional reactive "when" operator. // // * `properties` An array of property names (can also be a single property string). // * `callback` A callback function that is called: // * with property values as arguments, ordered corresponding to the properties array, // * only if all specified properties have values, // * once for initialization, // * whenever one or more specified properties change, // * on the next tick of the JavaScript event loop after properties change, // * only once as a result of one or more synchronous changes to dependency properties. function when(properties, callback, thisArg){ // Make sure the default `this` becomes // the object you called `.on` on. thisArg = thisArg || this; // Handle either an array or a single string. properties = (properties instanceof Array) ? properties : [properties]; // This function will trigger the callback to be invoked. var listener = debounce(function (){ var args = properties.map(function(property){ return values[property]; }); if(allAreDefined(args)){ callback.apply(thisArg, args); } }); // Trigger the callback once for initialization. listener(); // Trigger the callback whenever specified properties change. properties.forEach(function(property){ on(property, listener); }); // Return this function so it can be removed later with `model.cancel(listener)`. return listener; } // Adds a change listener for a given property with Backbone-like behavior. // Similar to http://backbonejs.org/#Events-on function on(property, callback, thisArg){ thisArg = thisArg || this; getListeners(property).push(callback); track(property, thisArg); } // Gets or creates the array of listener functions for a given property. function getListeners(property){ return listeners[property] || (listeners[property] = []); } // Tracks a property if it is not already tracked. function track(property, thisArg){ if(!(property in trackedProperties)){ trackedProperties[property] = true; values[property] = model[property]; Object.defineProperty(model, property, { get: function () { return values[property]; }, set: function(newValue) { var oldValue = values[property]; values[property] = newValue; getListeners(property).forEach(function(callback){ callback.call(thisArg, newValue, oldValue); }); } }); } } // Cancels a listener returned by a call to `model.when(...)`. function cancel(listener){ for(var property in listeners){ off(property, listener); } } // Removes a change listener added using `on`. function off(property, callback){ listeners[property] = listeners[property].filter(function (listener) { return listener !== callback; }); } // Sets all of the given values on the model. // `newValues` is an object { property -> value }. function set(newValues){ for(var property in newValues){ model[property] = newValues[property]; } } // Transfer defaults passed into the constructor to the model. set(defaults); // Public API. model.when = when; model.cancel = cancel; model.on = on; model.off = off; model.set = set; }
[ "function", "Model", "(", "defaults", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Model", ")", ")", "{", "return", "new", "Model", "(", "defaults", ")", ";", "}", "var", "model", "=", "this", ",", "values", "=", "{", "}", ",", "listeners", "=", "{", "}", ",", "trackedProperties", "=", "{", "}", ";", "function", "when", "(", "properties", ",", "callback", ",", "thisArg", ")", "{", "thisArg", "=", "thisArg", "||", "this", ";", "properties", "=", "(", "properties", "instanceof", "Array", ")", "?", "properties", ":", "[", "properties", "]", ";", "var", "listener", "=", "debounce", "(", "function", "(", ")", "{", "var", "args", "=", "properties", ".", "map", "(", "function", "(", "property", ")", "{", "return", "values", "[", "property", "]", ";", "}", ")", ";", "if", "(", "allAreDefined", "(", "args", ")", ")", "{", "callback", ".", "apply", "(", "thisArg", ",", "args", ")", ";", "}", "}", ")", ";", "listener", "(", ")", ";", "properties", ".", "forEach", "(", "function", "(", "property", ")", "{", "on", "(", "property", ",", "listener", ")", ";", "}", ")", ";", "return", "listener", ";", "}", "function", "on", "(", "property", ",", "callback", ",", "thisArg", ")", "{", "thisArg", "=", "thisArg", "||", "this", ";", "getListeners", "(", "property", ")", ".", "push", "(", "callback", ")", ";", "track", "(", "property", ",", "thisArg", ")", ";", "}", "function", "getListeners", "(", "property", ")", "{", "return", "listeners", "[", "property", "]", "||", "(", "listeners", "[", "property", "]", "=", "[", "]", ")", ";", "}", "function", "track", "(", "property", ",", "thisArg", ")", "{", "if", "(", "!", "(", "property", "in", "trackedProperties", ")", ")", "{", "trackedProperties", "[", "property", "]", "=", "true", ";", "values", "[", "property", "]", "=", "model", "[", "property", "]", ";", "Object", ".", "defineProperty", "(", "model", ",", "property", ",", "{", "get", ":", "function", "(", ")", "{", "return", "values", "[", "property", "]", ";", "}", ",", "set", ":", "function", "(", "newValue", ")", "{", "var", "oldValue", "=", "values", "[", "property", "]", ";", "values", "[", "property", "]", "=", "newValue", ";", "getListeners", "(", "property", ")", ".", "forEach", "(", "function", "(", "callback", ")", "{", "callback", ".", "call", "(", "thisArg", ",", "newValue", ",", "oldValue", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", "}", "function", "cancel", "(", "listener", ")", "{", "for", "(", "var", "property", "in", "listeners", ")", "{", "off", "(", "property", ",", "listener", ")", ";", "}", "}", "function", "off", "(", "property", ",", "callback", ")", "{", "listeners", "[", "property", "]", "=", "listeners", "[", "property", "]", ".", "filter", "(", "function", "(", "listener", ")", "{", "return", "listener", "!==", "callback", ";", "}", ")", ";", "}", "function", "set", "(", "newValues", ")", "{", "for", "(", "var", "property", "in", "newValues", ")", "{", "model", "[", "property", "]", "=", "newValues", "[", "property", "]", ";", "}", "}", "set", "(", "defaults", ")", ";", "model", ".", "when", "=", "when", ";", "model", ".", "cancel", "=", "cancel", ";", "model", ".", "on", "=", "on", ";", "model", ".", "off", "=", "off", ";", "model", ".", "set", "=", "set", ";", "}" ]
The constructor function, accepting default values.
[ "The", "constructor", "function", "accepting", "default", "values", "." ]
ad971f0d912e6f31cca33c467629c0c6f5279f9a
https://github.com/curran/model/blob/ad971f0d912e6f31cca33c467629c0c6f5279f9a/cdn/model-v0.2.4.js#L41-L164
train
resonance-audio/resonance-audio-web-sdk
examples/resources/js/benchmark.js
selectDimensionsAndMaterials
function selectDimensionsAndMaterials() { let reverbLength = document.getElementById('reverbLengthSelect').value; switch (reverbLength) { case 'none': default: { return { dimensions: { width: 0, height: 0, depth: 0, }, materials: { left: 'transparent', right: 'transparent', front: 'transparent', back: 'transparent', up: 'transparent', down: 'transparent', }, }; } break; case 'short': { return { dimensions: { width: 1.5, height: 1.5, depth: 1.5, }, materials: { left: 'uniform', right: 'uniform', front: 'uniform', back: 'uniform', up: 'uniform', down: 'uniform', }, }; } break; case 'medium': { return { dimensions: { width: 6, height: 6, depth: 6, }, materials: { left: 'uniform', right: 'uniform', front: 'uniform', back: 'uniform', up: 'uniform', down: 'uniform', }, }; } break; case 'long': { return { dimensions: { width: 24, height: 24, depth: 24, }, materials: { left: 'uniform', right: 'uniform', front: 'uniform', back: 'uniform', up: 'uniform', down: 'uniform', }, }; } break; } }
javascript
function selectDimensionsAndMaterials() { let reverbLength = document.getElementById('reverbLengthSelect').value; switch (reverbLength) { case 'none': default: { return { dimensions: { width: 0, height: 0, depth: 0, }, materials: { left: 'transparent', right: 'transparent', front: 'transparent', back: 'transparent', up: 'transparent', down: 'transparent', }, }; } break; case 'short': { return { dimensions: { width: 1.5, height: 1.5, depth: 1.5, }, materials: { left: 'uniform', right: 'uniform', front: 'uniform', back: 'uniform', up: 'uniform', down: 'uniform', }, }; } break; case 'medium': { return { dimensions: { width: 6, height: 6, depth: 6, }, materials: { left: 'uniform', right: 'uniform', front: 'uniform', back: 'uniform', up: 'uniform', down: 'uniform', }, }; } break; case 'long': { return { dimensions: { width: 24, height: 24, depth: 24, }, materials: { left: 'uniform', right: 'uniform', front: 'uniform', back: 'uniform', up: 'uniform', down: 'uniform', }, }; } break; } }
[ "function", "selectDimensionsAndMaterials", "(", ")", "{", "let", "reverbLength", "=", "document", ".", "getElementById", "(", "'reverbLengthSelect'", ")", ".", "value", ";", "switch", "(", "reverbLength", ")", "{", "case", "'none'", ":", "default", ":", "{", "return", "{", "dimensions", ":", "{", "width", ":", "0", ",", "height", ":", "0", ",", "depth", ":", "0", ",", "}", ",", "materials", ":", "{", "left", ":", "'transparent'", ",", "right", ":", "'transparent'", ",", "front", ":", "'transparent'", ",", "back", ":", "'transparent'", ",", "up", ":", "'transparent'", ",", "down", ":", "'transparent'", ",", "}", ",", "}", ";", "}", "break", ";", "case", "'short'", ":", "{", "return", "{", "dimensions", ":", "{", "width", ":", "1.5", ",", "height", ":", "1.5", ",", "depth", ":", "1.5", ",", "}", ",", "materials", ":", "{", "left", ":", "'uniform'", ",", "right", ":", "'uniform'", ",", "front", ":", "'uniform'", ",", "back", ":", "'uniform'", ",", "up", ":", "'uniform'", ",", "down", ":", "'uniform'", ",", "}", ",", "}", ";", "}", "break", ";", "case", "'medium'", ":", "{", "return", "{", "dimensions", ":", "{", "width", ":", "6", ",", "height", ":", "6", ",", "depth", ":", "6", ",", "}", ",", "materials", ":", "{", "left", ":", "'uniform'", ",", "right", ":", "'uniform'", ",", "front", ":", "'uniform'", ",", "back", ":", "'uniform'", ",", "up", ":", "'uniform'", ",", "down", ":", "'uniform'", ",", "}", ",", "}", ";", "}", "break", ";", "case", "'long'", ":", "{", "return", "{", "dimensions", ":", "{", "width", ":", "24", ",", "height", ":", "24", ",", "depth", ":", "24", ",", "}", ",", "materials", ":", "{", "left", ":", "'uniform'", ",", "right", ":", "'uniform'", ",", "front", ":", "'uniform'", ",", "back", ":", "'uniform'", ",", "up", ":", "'uniform'", ",", "down", ":", "'uniform'", ",", "}", ",", "}", ";", "}", "break", ";", "}", "}" ]
Select appropriate dimensions and materials. @return {Object} @private
[ "Select", "appropriate", "dimensions", "and", "materials", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/examples/resources/js/benchmark.js#L12-L93
train
resonance-audio/resonance-audio-web-sdk
src/resonance-audio.js
ResonanceAudio
function ResonanceAudio(context, options) { // Public variables. /** * Binaurally-rendered stereo (2-channel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} output * @memberof ResonanceAudio * @instance */ /** * Ambisonic (multichannel) input {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode} * (For rendering input soundfields). * @member {AudioNode} ambisonicInput * @memberof ResonanceAudio * @instance */ /** * Ambisonic (multichannel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode} * (For allowing external rendering / post-processing). * @member {AudioNode} ambisonicOutput * @memberof ResonanceAudio * @instance */ // Use defaults for undefined arguments. if (options == undefined) { options = {}; } if (options.ambisonicOrder == undefined) { options.ambisonicOrder = Utils.DEFAULT_AMBISONIC_ORDER; } if (options.listenerPosition == undefined) { options.listenerPosition = Utils.DEFAULT_POSITION.slice(); } if (options.listenerForward == undefined) { options.listenerForward = Utils.DEFAULT_FORWARD.slice(); } if (options.listenerUp == undefined) { options.listenerUp = Utils.DEFAULT_UP.slice(); } if (options.dimensions == undefined) { options.dimensions = {}; Object.assign(options.dimensions, Utils.DEFAULT_ROOM_DIMENSIONS); } if (options.materials == undefined) { options.materials = {}; Object.assign(options.materials, Utils.DEFAULT_ROOM_MATERIALS); } if (options.speedOfSound == undefined) { options.speedOfSound = Utils.DEFAULT_SPEED_OF_SOUND; } // Create member submodules. this._ambisonicOrder = Encoder.validateAmbisonicOrder(options.ambisonicOrder); this._sources = []; this._room = new Room(context, { listenerPosition: options.listenerPosition, dimensions: options.dimensions, materials: options.materials, speedOfSound: options.speedOfSound, }); this._listener = new Listener(context, { ambisonicOrder: options.ambisonicOrder, position: options.listenerPosition, forward: options.listenerForward, up: options.listenerUp, }); // Create auxillary audio nodes. this._context = context; this.output = context.createGain(); this.ambisonicOutput = context.createGain(); this.ambisonicInput = this._listener.input; // Connect audio graph. this._room.output.connect(this._listener.input); this._listener.output.connect(this.output); this._listener.ambisonicOutput.connect(this.ambisonicOutput); }
javascript
function ResonanceAudio(context, options) { // Public variables. /** * Binaurally-rendered stereo (2-channel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} output * @memberof ResonanceAudio * @instance */ /** * Ambisonic (multichannel) input {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode} * (For rendering input soundfields). * @member {AudioNode} ambisonicInput * @memberof ResonanceAudio * @instance */ /** * Ambisonic (multichannel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode} * (For allowing external rendering / post-processing). * @member {AudioNode} ambisonicOutput * @memberof ResonanceAudio * @instance */ // Use defaults for undefined arguments. if (options == undefined) { options = {}; } if (options.ambisonicOrder == undefined) { options.ambisonicOrder = Utils.DEFAULT_AMBISONIC_ORDER; } if (options.listenerPosition == undefined) { options.listenerPosition = Utils.DEFAULT_POSITION.slice(); } if (options.listenerForward == undefined) { options.listenerForward = Utils.DEFAULT_FORWARD.slice(); } if (options.listenerUp == undefined) { options.listenerUp = Utils.DEFAULT_UP.slice(); } if (options.dimensions == undefined) { options.dimensions = {}; Object.assign(options.dimensions, Utils.DEFAULT_ROOM_DIMENSIONS); } if (options.materials == undefined) { options.materials = {}; Object.assign(options.materials, Utils.DEFAULT_ROOM_MATERIALS); } if (options.speedOfSound == undefined) { options.speedOfSound = Utils.DEFAULT_SPEED_OF_SOUND; } // Create member submodules. this._ambisonicOrder = Encoder.validateAmbisonicOrder(options.ambisonicOrder); this._sources = []; this._room = new Room(context, { listenerPosition: options.listenerPosition, dimensions: options.dimensions, materials: options.materials, speedOfSound: options.speedOfSound, }); this._listener = new Listener(context, { ambisonicOrder: options.ambisonicOrder, position: options.listenerPosition, forward: options.listenerForward, up: options.listenerUp, }); // Create auxillary audio nodes. this._context = context; this.output = context.createGain(); this.ambisonicOutput = context.createGain(); this.ambisonicInput = this._listener.input; // Connect audio graph. this._room.output.connect(this._listener.input); this._listener.output.connect(this.output); this._listener.ambisonicOutput.connect(this.ambisonicOutput); }
[ "function", "ResonanceAudio", "(", "context", ",", "options", ")", "{", "if", "(", "options", "==", "undefined", ")", "{", "options", "=", "{", "}", ";", "}", "if", "(", "options", ".", "ambisonicOrder", "==", "undefined", ")", "{", "options", ".", "ambisonicOrder", "=", "Utils", ".", "DEFAULT_AMBISONIC_ORDER", ";", "}", "if", "(", "options", ".", "listenerPosition", "==", "undefined", ")", "{", "options", ".", "listenerPosition", "=", "Utils", ".", "DEFAULT_POSITION", ".", "slice", "(", ")", ";", "}", "if", "(", "options", ".", "listenerForward", "==", "undefined", ")", "{", "options", ".", "listenerForward", "=", "Utils", ".", "DEFAULT_FORWARD", ".", "slice", "(", ")", ";", "}", "if", "(", "options", ".", "listenerUp", "==", "undefined", ")", "{", "options", ".", "listenerUp", "=", "Utils", ".", "DEFAULT_UP", ".", "slice", "(", ")", ";", "}", "if", "(", "options", ".", "dimensions", "==", "undefined", ")", "{", "options", ".", "dimensions", "=", "{", "}", ";", "Object", ".", "assign", "(", "options", ".", "dimensions", ",", "Utils", ".", "DEFAULT_ROOM_DIMENSIONS", ")", ";", "}", "if", "(", "options", ".", "materials", "==", "undefined", ")", "{", "options", ".", "materials", "=", "{", "}", ";", "Object", ".", "assign", "(", "options", ".", "materials", ",", "Utils", ".", "DEFAULT_ROOM_MATERIALS", ")", ";", "}", "if", "(", "options", ".", "speedOfSound", "==", "undefined", ")", "{", "options", ".", "speedOfSound", "=", "Utils", ".", "DEFAULT_SPEED_OF_SOUND", ";", "}", "this", ".", "_ambisonicOrder", "=", "Encoder", ".", "validateAmbisonicOrder", "(", "options", ".", "ambisonicOrder", ")", ";", "this", ".", "_sources", "=", "[", "]", ";", "this", ".", "_room", "=", "new", "Room", "(", "context", ",", "{", "listenerPosition", ":", "options", ".", "listenerPosition", ",", "dimensions", ":", "options", ".", "dimensions", ",", "materials", ":", "options", ".", "materials", ",", "speedOfSound", ":", "options", ".", "speedOfSound", ",", "}", ")", ";", "this", ".", "_listener", "=", "new", "Listener", "(", "context", ",", "{", "ambisonicOrder", ":", "options", ".", "ambisonicOrder", ",", "position", ":", "options", ".", "listenerPosition", ",", "forward", ":", "options", ".", "listenerForward", ",", "up", ":", "options", ".", "listenerUp", ",", "}", ")", ";", "this", ".", "_context", "=", "context", ";", "this", ".", "output", "=", "context", ".", "createGain", "(", ")", ";", "this", ".", "ambisonicOutput", "=", "context", ".", "createGain", "(", ")", ";", "this", ".", "ambisonicInput", "=", "this", ".", "_listener", ".", "input", ";", "this", ".", "_room", ".", "output", ".", "connect", "(", "this", ".", "_listener", ".", "input", ")", ";", "this", ".", "_listener", ".", "output", ".", "connect", "(", "this", ".", "output", ")", ";", "this", ".", "_listener", ".", "ambisonicOutput", ".", "connect", "(", "this", ".", "ambisonicOutput", ")", ";", "}" ]
Options for constructing a new ResonanceAudio scene. @typedef {Object} ResonanceAudio~ResonanceAudioOptions @property {Number} ambisonicOrder Desired ambisonic Order. Defaults to {@linkcode Utils.DEFAULT_AMBISONIC_ORDER DEFAULT_AMBISONIC_ORDER}. @property {Float32Array} listenerPosition The listener's initial position (in meters), where origin is the center of the room. Defaults to {@linkcode Utils.DEFAULT_POSITION DEFAULT_POSITION}. @property {Float32Array} listenerForward The listener's initial forward vector. Defaults to {@linkcode Utils.DEFAULT_FORWARD DEFAULT_FORWARD}. @property {Float32Array} listenerUp The listener's initial up vector. Defaults to {@linkcode Utils.DEFAULT_UP DEFAULT_UP}. @property {Utils~RoomDimensions} dimensions Room dimensions (in meters). Defaults to {@linkcode Utils.DEFAULT_ROOM_DIMENSIONS DEFAULT_ROOM_DIMENSIONS}. @property {Utils~RoomMaterials} materials Named acoustic materials per wall. Defaults to {@linkcode Utils.DEFAULT_ROOM_MATERIALS DEFAULT_ROOM_MATERIALS}. @property {Number} speedOfSound (in meters/second). Defaults to {@linkcode Utils.DEFAULT_SPEED_OF_SOUND DEFAULT_SPEED_OF_SOUND}. @class ResonanceAudio @description Main class for managing sources, room and listener models. @param {AudioContext} context Associated {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioContext AudioContext}. @param {ResonanceAudio~ResonanceAudioOptions} options Options for constructing a new ResonanceAudio scene.
[ "Options", "for", "constructing", "a", "new", "ResonanceAudio", "scene", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/resonance-audio.js#L67-L147
train
resonance-audio/resonance-audio-web-sdk
examples/resources/js/treasure-hunt.js
updateAngles
function updateAngles(xAngle, yAngle, zAngle) { let deg2rad = Math.PI / 180; let euler = new THREE.Euler( xAngle * deg2rad, yAngle * deg2rad, zAngle * deg2rad, 'YXZ'); let matrix = new THREE.Matrix4().makeRotationFromEuler(euler); camera.setRotationFromMatrix(matrix); if (!audioReady) return; if (Date.now() - lastMatrixUpdate > 100) { audioScene.setListenerFromMatrix(camera.matrixWorld); } }
javascript
function updateAngles(xAngle, yAngle, zAngle) { let deg2rad = Math.PI / 180; let euler = new THREE.Euler( xAngle * deg2rad, yAngle * deg2rad, zAngle * deg2rad, 'YXZ'); let matrix = new THREE.Matrix4().makeRotationFromEuler(euler); camera.setRotationFromMatrix(matrix); if (!audioReady) return; if (Date.now() - lastMatrixUpdate > 100) { audioScene.setListenerFromMatrix(camera.matrixWorld); } }
[ "function", "updateAngles", "(", "xAngle", ",", "yAngle", ",", "zAngle", ")", "{", "let", "deg2rad", "=", "Math", ".", "PI", "/", "180", ";", "let", "euler", "=", "new", "THREE", ".", "Euler", "(", "xAngle", "*", "deg2rad", ",", "yAngle", "*", "deg2rad", ",", "zAngle", "*", "deg2rad", ",", "'YXZ'", ")", ";", "let", "matrix", "=", "new", "THREE", ".", "Matrix4", "(", ")", ".", "makeRotationFromEuler", "(", "euler", ")", ";", "camera", ".", "setRotationFromMatrix", "(", "matrix", ")", ";", "if", "(", "!", "audioReady", ")", "return", ";", "if", "(", "Date", ".", "now", "(", ")", "-", "lastMatrixUpdate", ">", "100", ")", "{", "audioScene", ".", "setListenerFromMatrix", "(", "camera", ".", "matrixWorld", ")", ";", "}", "}" ]
Compute rotation matrix. @param {Number} xAngle @param {Number} yAngle @param {Number} zAngle @private
[ "Compute", "rotation", "matrix", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/examples/resources/js/treasure-hunt.js#L41-L56
train
resonance-audio/resonance-audio-web-sdk
examples/resources/js/treasure-hunt.js
getCursorPosition
function getCursorPosition(event) { let cursorX; let cursorY; let rect = htmlElement.getBoundingClientRect(); if (event.touches !== undefined) { cursorX = event.touches[0].clientX; cursorY = event.touches[0].clientY; } else { cursorX = event.clientX; cursorY = event.clientY; } return { x: cursorX - rect.left, y: cursorY - rect.top, }; }
javascript
function getCursorPosition(event) { let cursorX; let cursorY; let rect = htmlElement.getBoundingClientRect(); if (event.touches !== undefined) { cursorX = event.touches[0].clientX; cursorY = event.touches[0].clientY; } else { cursorX = event.clientX; cursorY = event.clientY; } return { x: cursorX - rect.left, y: cursorY - rect.top, }; }
[ "function", "getCursorPosition", "(", "event", ")", "{", "let", "cursorX", ";", "let", "cursorY", ";", "let", "rect", "=", "htmlElement", ".", "getBoundingClientRect", "(", ")", ";", "if", "(", "event", ".", "touches", "!==", "undefined", ")", "{", "cursorX", "=", "event", ".", "touches", "[", "0", "]", ".", "clientX", ";", "cursorY", "=", "event", ".", "touches", "[", "0", "]", ".", "clientY", ";", "}", "else", "{", "cursorX", "=", "event", ".", "clientX", ";", "cursorY", "=", "event", ".", "clientY", ";", "}", "return", "{", "x", ":", "cursorX", "-", "rect", ".", "left", ",", "y", ":", "cursorY", "-", "rect", ".", "top", ",", "}", ";", "}" ]
Get cursor position on canvas. @param {Object} event @return {Object} @private
[ "Get", "cursor", "position", "on", "canvas", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/examples/resources/js/treasure-hunt.js#L64-L79
train
resonance-audio/resonance-audio-web-sdk
examples/resources/js/vs-pannernode.js
selectRenderingMode
function selectRenderingMode(event) { if (!audioReady) return; switch (document.getElementById('renderingMode').value) { case 'toa': { noneGain.gain.value = 0; pannerGain.gain.value = 0; foaGain.gain.value = 0; toaGain.gain.value = 1; } break; case 'foa': { noneGain.gain.value = 0; pannerGain.gain.value = 0; foaGain.gain.value = 1; toaGain.gain.value = 0; } break; case 'panner-node': { noneGain.gain.value = 0; pannerGain.gain.value = 1; foaGain.gain.value = 0; toaGain.gain.value = 0; } break; case 'none': default: { noneGain.gain.value = 1; pannerGain.gain.value = 0; foaGain.gain.value = 0; toaGain.gain.value = 0; } break; } }
javascript
function selectRenderingMode(event) { if (!audioReady) return; switch (document.getElementById('renderingMode').value) { case 'toa': { noneGain.gain.value = 0; pannerGain.gain.value = 0; foaGain.gain.value = 0; toaGain.gain.value = 1; } break; case 'foa': { noneGain.gain.value = 0; pannerGain.gain.value = 0; foaGain.gain.value = 1; toaGain.gain.value = 0; } break; case 'panner-node': { noneGain.gain.value = 0; pannerGain.gain.value = 1; foaGain.gain.value = 0; toaGain.gain.value = 0; } break; case 'none': default: { noneGain.gain.value = 1; pannerGain.gain.value = 0; foaGain.gain.value = 0; toaGain.gain.value = 0; } break; } }
[ "function", "selectRenderingMode", "(", "event", ")", "{", "if", "(", "!", "audioReady", ")", "return", ";", "switch", "(", "document", ".", "getElementById", "(", "'renderingMode'", ")", ".", "value", ")", "{", "case", "'toa'", ":", "{", "noneGain", ".", "gain", ".", "value", "=", "0", ";", "pannerGain", ".", "gain", ".", "value", "=", "0", ";", "foaGain", ".", "gain", ".", "value", "=", "0", ";", "toaGain", ".", "gain", ".", "value", "=", "1", ";", "}", "break", ";", "case", "'foa'", ":", "{", "noneGain", ".", "gain", ".", "value", "=", "0", ";", "pannerGain", ".", "gain", ".", "value", "=", "0", ";", "foaGain", ".", "gain", ".", "value", "=", "1", ";", "toaGain", ".", "gain", ".", "value", "=", "0", ";", "}", "break", ";", "case", "'panner-node'", ":", "{", "noneGain", ".", "gain", ".", "value", "=", "0", ";", "pannerGain", ".", "gain", ".", "value", "=", "1", ";", "foaGain", ".", "gain", ".", "value", "=", "0", ";", "toaGain", ".", "gain", ".", "value", "=", "0", ";", "}", "break", ";", "case", "'none'", ":", "default", ":", "{", "noneGain", ".", "gain", ".", "value", "=", "1", ";", "pannerGain", ".", "gain", ".", "value", "=", "0", ";", "foaGain", ".", "gain", ".", "value", "=", "0", ";", "toaGain", ".", "gain", ".", "value", "=", "0", ";", "}", "break", ";", "}", "}" ]
Select the desired rendering mode. @param {Object} event @private
[ "Select", "the", "desired", "rendering", "mode", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/examples/resources/js/vs-pannernode.js#L21-L60
train
resonance-audio/resonance-audio-web-sdk
examples/resources/js/vs-pannernode.js
updatePositions
function updatePositions(elements) { if (!audioReady) return; for (let i = 0; i < elements.length; i++) { let x = (elements[i].x - 0.5) * dimensions.width / 2; let y = 0; let z = (elements[i].y - 0.5) * dimensions.depth / 2; if (i == 0) { pannerNode.setPosition(x, y, z); foaSource.setPosition(x, y, z); toaSource.setPosition(x, y, z); } else { audioContext.listener.setPosition(x, y, z); foaScene.setListenerPosition(x, y, z); toaScene.setListenerPosition(x, y, z); } } }
javascript
function updatePositions(elements) { if (!audioReady) return; for (let i = 0; i < elements.length; i++) { let x = (elements[i].x - 0.5) * dimensions.width / 2; let y = 0; let z = (elements[i].y - 0.5) * dimensions.depth / 2; if (i == 0) { pannerNode.setPosition(x, y, z); foaSource.setPosition(x, y, z); toaSource.setPosition(x, y, z); } else { audioContext.listener.setPosition(x, y, z); foaScene.setListenerPosition(x, y, z); toaScene.setListenerPosition(x, y, z); } } }
[ "function", "updatePositions", "(", "elements", ")", "{", "if", "(", "!", "audioReady", ")", "return", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "++", ")", "{", "let", "x", "=", "(", "elements", "[", "i", "]", ".", "x", "-", "0.5", ")", "*", "dimensions", ".", "width", "/", "2", ";", "let", "y", "=", "0", ";", "let", "z", "=", "(", "elements", "[", "i", "]", ".", "y", "-", "0.5", ")", "*", "dimensions", ".", "depth", "/", "2", ";", "if", "(", "i", "==", "0", ")", "{", "pannerNode", ".", "setPosition", "(", "x", ",", "y", ",", "z", ")", ";", "foaSource", ".", "setPosition", "(", "x", ",", "y", ",", "z", ")", ";", "toaSource", ".", "setPosition", "(", "x", ",", "y", ",", "z", ")", ";", "}", "else", "{", "audioContext", ".", "listener", ".", "setPosition", "(", "x", ",", "y", ",", "z", ")", ";", "foaScene", ".", "setListenerPosition", "(", "x", ",", "y", ",", "z", ")", ";", "toaScene", ".", "setListenerPosition", "(", "x", ",", "y", ",", "z", ")", ";", "}", "}", "}" ]
Update the audio sound objects' positions. @param {Object} elements @private
[ "Update", "the", "audio", "sound", "objects", "positions", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/examples/resources/js/vs-pannernode.js#L67-L85
train
resonance-audio/resonance-audio-web-sdk
src/room.js
_getCoefficientsFromMaterials
function _getCoefficientsFromMaterials(materials) { // Initialize coefficients to use defaults. let coefficients = {}; for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (Utils.DEFAULT_ROOM_MATERIALS.hasOwnProperty(property)) { coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[ Utils.DEFAULT_ROOM_MATERIALS[property]]; } } // Sanitize materials. if (materials == undefined) { materials = {}; Object.assign(materials, Utils.DEFAULT_ROOM_MATERIALS); } // Assign coefficients using provided materials. for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (Utils.DEFAULT_ROOM_MATERIALS.hasOwnProperty(property) && materials.hasOwnProperty(property)) { if (materials[property] in Utils.ROOM_MATERIAL_COEFFICIENTS) { coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[materials[property]]; } else { Utils.log('Material \"' + materials[property] + '\" on wall \"' + property + '\" not found. Using \"' + Utils.DEFAULT_ROOM_MATERIALS[property] + '\".'); } } else { Utils.log('Wall \"' + property + '\" is not defined. Default used.'); } } return coefficients; }
javascript
function _getCoefficientsFromMaterials(materials) { // Initialize coefficients to use defaults. let coefficients = {}; for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (Utils.DEFAULT_ROOM_MATERIALS.hasOwnProperty(property)) { coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[ Utils.DEFAULT_ROOM_MATERIALS[property]]; } } // Sanitize materials. if (materials == undefined) { materials = {}; Object.assign(materials, Utils.DEFAULT_ROOM_MATERIALS); } // Assign coefficients using provided materials. for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (Utils.DEFAULT_ROOM_MATERIALS.hasOwnProperty(property) && materials.hasOwnProperty(property)) { if (materials[property] in Utils.ROOM_MATERIAL_COEFFICIENTS) { coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[materials[property]]; } else { Utils.log('Material \"' + materials[property] + '\" on wall \"' + property + '\" not found. Using \"' + Utils.DEFAULT_ROOM_MATERIALS[property] + '\".'); } } else { Utils.log('Wall \"' + property + '\" is not defined. Default used.'); } } return coefficients; }
[ "function", "_getCoefficientsFromMaterials", "(", "materials", ")", "{", "let", "coefficients", "=", "{", "}", ";", "for", "(", "let", "property", "in", "Utils", ".", "DEFAULT_ROOM_MATERIALS", ")", "{", "if", "(", "Utils", ".", "DEFAULT_ROOM_MATERIALS", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "coefficients", "[", "property", "]", "=", "Utils", ".", "ROOM_MATERIAL_COEFFICIENTS", "[", "Utils", ".", "DEFAULT_ROOM_MATERIALS", "[", "property", "]", "]", ";", "}", "}", "if", "(", "materials", "==", "undefined", ")", "{", "materials", "=", "{", "}", ";", "Object", ".", "assign", "(", "materials", ",", "Utils", ".", "DEFAULT_ROOM_MATERIALS", ")", ";", "}", "for", "(", "let", "property", "in", "Utils", ".", "DEFAULT_ROOM_MATERIALS", ")", "{", "if", "(", "Utils", ".", "DEFAULT_ROOM_MATERIALS", ".", "hasOwnProperty", "(", "property", ")", "&&", "materials", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "if", "(", "materials", "[", "property", "]", "in", "Utils", ".", "ROOM_MATERIAL_COEFFICIENTS", ")", "{", "coefficients", "[", "property", "]", "=", "Utils", ".", "ROOM_MATERIAL_COEFFICIENTS", "[", "materials", "[", "property", "]", "]", ";", "}", "else", "{", "Utils", ".", "log", "(", "'Material \\\"'", "+", "\\\"", "+", "materials", "[", "property", "]", "+", "'\\\" on wall \\\"'", "+", "\\\"", "+", "\\\"", "+", "property", ")", ";", "}", "}", "else", "'\\\" not found. Using \\\"'", "}", "\\\"", "}" ]
Generate absorption coefficients from material names. @param {Object} materials @return {Object}
[ "Generate", "absorption", "coefficients", "from", "material", "names", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/room.js#L36-L69
train
resonance-audio/resonance-audio-web-sdk
src/room.js
_sanitizeCoefficients
function _sanitizeCoefficients(coefficients) { if (coefficients == undefined) { coefficients = {}; } for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (!(coefficients.hasOwnProperty(property))) { // If element is not present, use default coefficients. coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[ Utils.DEFAULT_ROOM_MATERIALS[property]]; } } return coefficients; }
javascript
function _sanitizeCoefficients(coefficients) { if (coefficients == undefined) { coefficients = {}; } for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (!(coefficients.hasOwnProperty(property))) { // If element is not present, use default coefficients. coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[ Utils.DEFAULT_ROOM_MATERIALS[property]]; } } return coefficients; }
[ "function", "_sanitizeCoefficients", "(", "coefficients", ")", "{", "if", "(", "coefficients", "==", "undefined", ")", "{", "coefficients", "=", "{", "}", ";", "}", "for", "(", "let", "property", "in", "Utils", ".", "DEFAULT_ROOM_MATERIALS", ")", "{", "if", "(", "!", "(", "coefficients", ".", "hasOwnProperty", "(", "property", ")", ")", ")", "{", "coefficients", "[", "property", "]", "=", "Utils", ".", "ROOM_MATERIAL_COEFFICIENTS", "[", "Utils", ".", "DEFAULT_ROOM_MATERIALS", "[", "property", "]", "]", ";", "}", "}", "return", "coefficients", ";", "}" ]
Sanitize coefficients. @param {Object} coefficients @return {Object}
[ "Sanitize", "coefficients", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/room.js#L76-L88
train
resonance-audio/resonance-audio-web-sdk
src/room.js
_sanitizeDimensions
function _sanitizeDimensions(dimensions) { if (dimensions == undefined) { dimensions = {}; } for (let property in Utils.DEFAULT_ROOM_DIMENSIONS) { if (!(dimensions.hasOwnProperty(property))) { dimensions[property] = Utils.DEFAULT_ROOM_DIMENSIONS[property]; } } return dimensions; }
javascript
function _sanitizeDimensions(dimensions) { if (dimensions == undefined) { dimensions = {}; } for (let property in Utils.DEFAULT_ROOM_DIMENSIONS) { if (!(dimensions.hasOwnProperty(property))) { dimensions[property] = Utils.DEFAULT_ROOM_DIMENSIONS[property]; } } return dimensions; }
[ "function", "_sanitizeDimensions", "(", "dimensions", ")", "{", "if", "(", "dimensions", "==", "undefined", ")", "{", "dimensions", "=", "{", "}", ";", "}", "for", "(", "let", "property", "in", "Utils", ".", "DEFAULT_ROOM_DIMENSIONS", ")", "{", "if", "(", "!", "(", "dimensions", ".", "hasOwnProperty", "(", "property", ")", ")", ")", "{", "dimensions", "[", "property", "]", "=", "Utils", ".", "DEFAULT_ROOM_DIMENSIONS", "[", "property", "]", ";", "}", "}", "return", "dimensions", ";", "}" ]
Sanitize dimensions. @param {Utils~RoomDimensions} dimensions @return {Utils~RoomDimensions}
[ "Sanitize", "dimensions", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/room.js#L95-L105
train
resonance-audio/resonance-audio-web-sdk
src/room.js
_getDurationsFromProperties
function _getDurationsFromProperties(dimensions, coefficients, speedOfSound) { let durations = new Float32Array(Utils.NUMBER_REVERB_FREQUENCY_BANDS); // Sanitize inputs. dimensions = _sanitizeDimensions(dimensions); coefficients = _sanitizeCoefficients(coefficients); if (speedOfSound == undefined) { speedOfSound = Utils.DEFAULT_SPEED_OF_SOUND; } // Acoustic constant. let k = Utils.TWENTY_FOUR_LOG10 / speedOfSound; // Compute volume, skip if room is not present. let volume = dimensions.width * dimensions.height * dimensions.depth; if (volume < Utils.ROOM_MIN_VOLUME) { return durations; } // Room surface area. let leftRightArea = dimensions.width * dimensions.height; let floorCeilingArea = dimensions.width * dimensions.depth; let frontBackArea = dimensions.depth * dimensions.height; let totalArea = 2 * (leftRightArea + floorCeilingArea + frontBackArea); for (let i = 0; i < Utils.NUMBER_REVERB_FREQUENCY_BANDS; i++) { // Effective absorptive area. let absorbtionArea = (coefficients.left[i] + coefficients.right[i]) * leftRightArea + (coefficients.down[i] + coefficients.up[i]) * floorCeilingArea + (coefficients.front[i] + coefficients.back[i]) * frontBackArea; let meanAbsorbtionArea = absorbtionArea / totalArea; // Compute reverberation using Eyring equation [1]. // [1] Beranek, Leo L. "Analysis of Sabine and Eyring equations and their // application to concert hall audience and chair absorption." The // Journal of the Acoustical Society of America, Vol. 120, No. 3. // (2006), pp. 1399-1399. durations[i] = Utils.ROOM_EYRING_CORRECTION_COEFFICIENT * k * volume / (-totalArea * Math.log(1 - meanAbsorbtionArea) + 4 * Utils.ROOM_AIR_ABSORPTION_COEFFICIENTS[i] * volume); } return durations; }
javascript
function _getDurationsFromProperties(dimensions, coefficients, speedOfSound) { let durations = new Float32Array(Utils.NUMBER_REVERB_FREQUENCY_BANDS); // Sanitize inputs. dimensions = _sanitizeDimensions(dimensions); coefficients = _sanitizeCoefficients(coefficients); if (speedOfSound == undefined) { speedOfSound = Utils.DEFAULT_SPEED_OF_SOUND; } // Acoustic constant. let k = Utils.TWENTY_FOUR_LOG10 / speedOfSound; // Compute volume, skip if room is not present. let volume = dimensions.width * dimensions.height * dimensions.depth; if (volume < Utils.ROOM_MIN_VOLUME) { return durations; } // Room surface area. let leftRightArea = dimensions.width * dimensions.height; let floorCeilingArea = dimensions.width * dimensions.depth; let frontBackArea = dimensions.depth * dimensions.height; let totalArea = 2 * (leftRightArea + floorCeilingArea + frontBackArea); for (let i = 0; i < Utils.NUMBER_REVERB_FREQUENCY_BANDS; i++) { // Effective absorptive area. let absorbtionArea = (coefficients.left[i] + coefficients.right[i]) * leftRightArea + (coefficients.down[i] + coefficients.up[i]) * floorCeilingArea + (coefficients.front[i] + coefficients.back[i]) * frontBackArea; let meanAbsorbtionArea = absorbtionArea / totalArea; // Compute reverberation using Eyring equation [1]. // [1] Beranek, Leo L. "Analysis of Sabine and Eyring equations and their // application to concert hall audience and chair absorption." The // Journal of the Acoustical Society of America, Vol. 120, No. 3. // (2006), pp. 1399-1399. durations[i] = Utils.ROOM_EYRING_CORRECTION_COEFFICIENT * k * volume / (-totalArea * Math.log(1 - meanAbsorbtionArea) + 4 * Utils.ROOM_AIR_ABSORPTION_COEFFICIENTS[i] * volume); } return durations; }
[ "function", "_getDurationsFromProperties", "(", "dimensions", ",", "coefficients", ",", "speedOfSound", ")", "{", "let", "durations", "=", "new", "Float32Array", "(", "Utils", ".", "NUMBER_REVERB_FREQUENCY_BANDS", ")", ";", "dimensions", "=", "_sanitizeDimensions", "(", "dimensions", ")", ";", "coefficients", "=", "_sanitizeCoefficients", "(", "coefficients", ")", ";", "if", "(", "speedOfSound", "==", "undefined", ")", "{", "speedOfSound", "=", "Utils", ".", "DEFAULT_SPEED_OF_SOUND", ";", "}", "let", "k", "=", "Utils", ".", "TWENTY_FOUR_LOG10", "/", "speedOfSound", ";", "let", "volume", "=", "dimensions", ".", "width", "*", "dimensions", ".", "height", "*", "dimensions", ".", "depth", ";", "if", "(", "volume", "<", "Utils", ".", "ROOM_MIN_VOLUME", ")", "{", "return", "durations", ";", "}", "let", "leftRightArea", "=", "dimensions", ".", "width", "*", "dimensions", ".", "height", ";", "let", "floorCeilingArea", "=", "dimensions", ".", "width", "*", "dimensions", ".", "depth", ";", "let", "frontBackArea", "=", "dimensions", ".", "depth", "*", "dimensions", ".", "height", ";", "let", "totalArea", "=", "2", "*", "(", "leftRightArea", "+", "floorCeilingArea", "+", "frontBackArea", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "Utils", ".", "NUMBER_REVERB_FREQUENCY_BANDS", ";", "i", "++", ")", "{", "let", "absorbtionArea", "=", "(", "coefficients", ".", "left", "[", "i", "]", "+", "coefficients", ".", "right", "[", "i", "]", ")", "*", "leftRightArea", "+", "(", "coefficients", ".", "down", "[", "i", "]", "+", "coefficients", ".", "up", "[", "i", "]", ")", "*", "floorCeilingArea", "+", "(", "coefficients", ".", "front", "[", "i", "]", "+", "coefficients", ".", "back", "[", "i", "]", ")", "*", "frontBackArea", ";", "let", "meanAbsorbtionArea", "=", "absorbtionArea", "/", "totalArea", ";", "durations", "[", "i", "]", "=", "Utils", ".", "ROOM_EYRING_CORRECTION_COEFFICIENT", "*", "k", "*", "volume", "/", "(", "-", "totalArea", "*", "Math", ".", "log", "(", "1", "-", "meanAbsorbtionArea", ")", "+", "4", "*", "Utils", ".", "ROOM_AIR_ABSORPTION_COEFFICIENTS", "[", "i", "]", "*", "volume", ")", ";", "}", "return", "durations", ";", "}" ]
Compute frequency-dependent reverb durations. @param {Utils~RoomDimensions} dimensions @param {Object} coefficients @param {Number} speedOfSound @return {Array}
[ "Compute", "frequency", "-", "dependent", "reverb", "durations", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/room.js#L114-L156
train
resonance-audio/resonance-audio-web-sdk
src/room.js
_computeReflectionCoefficients
function _computeReflectionCoefficients(absorptionCoefficients) { let reflectionCoefficients = []; for (let property in Utils.DEFAULT_REFLECTION_COEFFICIENTS) { if (Utils.DEFAULT_REFLECTION_COEFFICIENTS .hasOwnProperty(property)) { // Compute average absorption coefficient (per wall). reflectionCoefficients[property] = 0; for (let j = 0; j < Utils.NUMBER_REFLECTION_AVERAGING_BANDS; j++) { let bandIndex = j + Utils.ROOM_STARTING_AVERAGING_BAND; reflectionCoefficients[property] += absorptionCoefficients[property][bandIndex]; } reflectionCoefficients[property] /= Utils.NUMBER_REFLECTION_AVERAGING_BANDS; // Convert absorption coefficient to reflection coefficient. reflectionCoefficients[property] = Math.sqrt(1 - reflectionCoefficients[property]); } } return reflectionCoefficients; }
javascript
function _computeReflectionCoefficients(absorptionCoefficients) { let reflectionCoefficients = []; for (let property in Utils.DEFAULT_REFLECTION_COEFFICIENTS) { if (Utils.DEFAULT_REFLECTION_COEFFICIENTS .hasOwnProperty(property)) { // Compute average absorption coefficient (per wall). reflectionCoefficients[property] = 0; for (let j = 0; j < Utils.NUMBER_REFLECTION_AVERAGING_BANDS; j++) { let bandIndex = j + Utils.ROOM_STARTING_AVERAGING_BAND; reflectionCoefficients[property] += absorptionCoefficients[property][bandIndex]; } reflectionCoefficients[property] /= Utils.NUMBER_REFLECTION_AVERAGING_BANDS; // Convert absorption coefficient to reflection coefficient. reflectionCoefficients[property] = Math.sqrt(1 - reflectionCoefficients[property]); } } return reflectionCoefficients; }
[ "function", "_computeReflectionCoefficients", "(", "absorptionCoefficients", ")", "{", "let", "reflectionCoefficients", "=", "[", "]", ";", "for", "(", "let", "property", "in", "Utils", ".", "DEFAULT_REFLECTION_COEFFICIENTS", ")", "{", "if", "(", "Utils", ".", "DEFAULT_REFLECTION_COEFFICIENTS", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "reflectionCoefficients", "[", "property", "]", "=", "0", ";", "for", "(", "let", "j", "=", "0", ";", "j", "<", "Utils", ".", "NUMBER_REFLECTION_AVERAGING_BANDS", ";", "j", "++", ")", "{", "let", "bandIndex", "=", "j", "+", "Utils", ".", "ROOM_STARTING_AVERAGING_BAND", ";", "reflectionCoefficients", "[", "property", "]", "+=", "absorptionCoefficients", "[", "property", "]", "[", "bandIndex", "]", ";", "}", "reflectionCoefficients", "[", "property", "]", "/=", "Utils", ".", "NUMBER_REFLECTION_AVERAGING_BANDS", ";", "reflectionCoefficients", "[", "property", "]", "=", "Math", ".", "sqrt", "(", "1", "-", "reflectionCoefficients", "[", "property", "]", ")", ";", "}", "}", "return", "reflectionCoefficients", ";", "}" ]
Compute reflection coefficients from absorption coefficients. @param {Object} absorptionCoefficients @return {Object}
[ "Compute", "reflection", "coefficients", "from", "absorption", "coefficients", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/room.js#L164-L185
train
resonance-audio/resonance-audio-web-sdk
src/source.js
_computeDistanceOutsideRoom
function _computeDistanceOutsideRoom(distance) { // We apply a linear ramp from 1 to 0 as the source is up to 1m outside. let gain = 1; if (distance > Utils.EPSILON_FLOAT) { gain = 1 - distance / Utils.SOURCE_MAX_OUTSIDE_ROOM_DISTANCE; // Clamp gain between 0 and 1. gain = Math.max(0, Math.min(1, gain)); } return gain; }
javascript
function _computeDistanceOutsideRoom(distance) { // We apply a linear ramp from 1 to 0 as the source is up to 1m outside. let gain = 1; if (distance > Utils.EPSILON_FLOAT) { gain = 1 - distance / Utils.SOURCE_MAX_OUTSIDE_ROOM_DISTANCE; // Clamp gain between 0 and 1. gain = Math.max(0, Math.min(1, gain)); } return gain; }
[ "function", "_computeDistanceOutsideRoom", "(", "distance", ")", "{", "let", "gain", "=", "1", ";", "if", "(", "distance", ">", "Utils", ".", "EPSILON_FLOAT", ")", "{", "gain", "=", "1", "-", "distance", "/", "Utils", ".", "SOURCE_MAX_OUTSIDE_ROOM_DISTANCE", ";", "gain", "=", "Math", ".", "max", "(", "0", ",", "Math", ".", "min", "(", "1", ",", "gain", ")", ")", ";", "}", "return", "gain", ";", "}" ]
Determine the distance a source is outside of a room. Attenuate gain going to the reflections and reverb when the source is outside of the room. @param {Number} distance Distance in meters. @return {Number} Gain (linear) of source. @private
[ "Determine", "the", "distance", "a", "source", "is", "outside", "of", "a", "room", ".", "Attenuate", "gain", "going", "to", "the", "reflections", "and", "reverb", "when", "the", "source", "is", "outside", "of", "the", "room", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/source.js#L344-L354
train
feedhenry/fh-forms
lib/impl/importForms/inputValidator.js
validateJSonStructure
function validateJSonStructure(filePath, cb) { fs.readFile(filePath, function(err, data) { if (err) { return cb(err); } try { var jsonObject = JSON.parse(data); cb(null, jsonObject); } catch (e) { cb('Invalid JSON file: ' + path.basename(filePath)); } }); }
javascript
function validateJSonStructure(filePath, cb) { fs.readFile(filePath, function(err, data) { if (err) { return cb(err); } try { var jsonObject = JSON.parse(data); cb(null, jsonObject); } catch (e) { cb('Invalid JSON file: ' + path.basename(filePath)); } }); }
[ "function", "validateJSonStructure", "(", "filePath", ",", "cb", ")", "{", "fs", ".", "readFile", "(", "filePath", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "try", "{", "var", "jsonObject", "=", "JSON", ".", "parse", "(", "data", ")", ";", "cb", "(", "null", ",", "jsonObject", ")", ";", "}", "catch", "(", "e", ")", "{", "cb", "(", "'Invalid JSON file: '", "+", "path", ".", "basename", "(", "filePath", ")", ")", ";", "}", "}", ")", ";", "}" ]
Checks that the received file is a well formed json @param {string} filePath path to the JSon file @param {function} cb callback
[ "Checks", "that", "the", "received", "file", "is", "a", "well", "formed", "json" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/inputValidator.js#L11-L24
train
feedhenry/fh-forms
lib/impl/importForms/inputValidator.js
validateMetadata
function validateMetadata(metadataPath, cb) { validateJSonStructure(metadataPath, function(err, metadataObject) { if (err) { cb(err, null); } else { cb(null, metadataObject.files); } }); }
javascript
function validateMetadata(metadataPath, cb) { validateJSonStructure(metadataPath, function(err, metadataObject) { if (err) { cb(err, null); } else { cb(null, metadataObject.files); } }); }
[ "function", "validateMetadata", "(", "metadataPath", ",", "cb", ")", "{", "validateJSonStructure", "(", "metadataPath", ",", "function", "(", "err", ",", "metadataObject", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ",", "null", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "metadataObject", ".", "files", ")", ";", "}", "}", ")", ";", "}" ]
Validates the metadata.json file @param {string} metadataPath path to themetadata.json file @param {function} cb callback
[ "Validates", "the", "metadata", ".", "json", "file" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/inputValidator.js#L32-L40
train
feedhenry/fh-forms
lib/impl/importForms/inputValidator.js
validateForm
function validateForm(form, cb) { async.series([function(callback) { fs.exists(form, function(exists) { if (exists) { callback(null); } else { callback('File ' + path.basename(form) + ' referenced by metadata.json does not exists'); } }); }, function(callback) { validateJSonStructure(form, callback); } ], function(err, data) { cb(err, data); }); }
javascript
function validateForm(form, cb) { async.series([function(callback) { fs.exists(form, function(exists) { if (exists) { callback(null); } else { callback('File ' + path.basename(form) + ' referenced by metadata.json does not exists'); } }); }, function(callback) { validateJSonStructure(form, callback); } ], function(err, data) { cb(err, data); }); }
[ "function", "validateForm", "(", "form", ",", "cb", ")", "{", "async", ".", "series", "(", "[", "function", "(", "callback", ")", "{", "fs", ".", "exists", "(", "form", ",", "function", "(", "exists", ")", "{", "if", "(", "exists", ")", "{", "callback", "(", "null", ")", ";", "}", "else", "{", "callback", "(", "'File '", "+", "path", ".", "basename", "(", "form", ")", "+", "' referenced by metadata.json does not exists'", ")", ";", "}", "}", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "validateJSonStructure", "(", "form", ",", "callback", ")", ";", "}", "]", ",", "function", "(", "err", ",", "data", ")", "{", "cb", "(", "err", ",", "data", ")", ";", "}", ")", ";", "}" ]
Validate the received form file. @param {string} form path to the form file to be validated @param {function} cb callback
[ "Validate", "the", "received", "form", "file", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/inputValidator.js#L48-L65
train
feedhenry/fh-forms
lib/impl/importForms/inputValidator.js
validate
function validate(archiveDirectory, strict, cb) { // Root validation checks fs.readdir(archiveDirectory, function(err, files) { if (err) { return cb(err); } if (files.length < 2 || (files.length !== 2 && strict)) { return cb('Root directory must contain exactly one metadata file and one forms directory'); } if (files.indexOf('forms') === -1) { return cb('A forms directory should be present in the root of the zip file'); } if (files.indexOf('metadata.json') === -1) { return cb('A metadata.json file must be present in the root of the zip file'); } var metadataPath = path.join(archiveDirectory, 'metadata.json'); async.waterfall([ function(callback) { validateMetadata(metadataPath, function(err, formFiles) { callback(err, formFiles); }); }, function(formFiles, callback) { var forms = []; _.each(formFiles, function(formFile) { forms.push(path.join(archiveDirectory, formFile.path)); }); async.each(forms, validateForm, callback); } ], function(err) { cb(err); }); }); }
javascript
function validate(archiveDirectory, strict, cb) { // Root validation checks fs.readdir(archiveDirectory, function(err, files) { if (err) { return cb(err); } if (files.length < 2 || (files.length !== 2 && strict)) { return cb('Root directory must contain exactly one metadata file and one forms directory'); } if (files.indexOf('forms') === -1) { return cb('A forms directory should be present in the root of the zip file'); } if (files.indexOf('metadata.json') === -1) { return cb('A metadata.json file must be present in the root of the zip file'); } var metadataPath = path.join(archiveDirectory, 'metadata.json'); async.waterfall([ function(callback) { validateMetadata(metadataPath, function(err, formFiles) { callback(err, formFiles); }); }, function(formFiles, callback) { var forms = []; _.each(formFiles, function(formFile) { forms.push(path.join(archiveDirectory, formFile.path)); }); async.each(forms, validateForm, callback); } ], function(err) { cb(err); }); }); }
[ "function", "validate", "(", "archiveDirectory", ",", "strict", ",", "cb", ")", "{", "fs", ".", "readdir", "(", "archiveDirectory", ",", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "if", "(", "files", ".", "length", "<", "2", "||", "(", "files", ".", "length", "!==", "2", "&&", "strict", ")", ")", "{", "return", "cb", "(", "'Root directory must contain exactly one metadata file and one forms directory'", ")", ";", "}", "if", "(", "files", ".", "indexOf", "(", "'forms'", ")", "===", "-", "1", ")", "{", "return", "cb", "(", "'A forms directory should be present in the root of the zip file'", ")", ";", "}", "if", "(", "files", ".", "indexOf", "(", "'metadata.json'", ")", "===", "-", "1", ")", "{", "return", "cb", "(", "'A metadata.json file must be present in the root of the zip file'", ")", ";", "}", "var", "metadataPath", "=", "path", ".", "join", "(", "archiveDirectory", ",", "'metadata.json'", ")", ";", "async", ".", "waterfall", "(", "[", "function", "(", "callback", ")", "{", "validateMetadata", "(", "metadataPath", ",", "function", "(", "err", ",", "formFiles", ")", "{", "callback", "(", "err", ",", "formFiles", ")", ";", "}", ")", ";", "}", ",", "function", "(", "formFiles", ",", "callback", ")", "{", "var", "forms", "=", "[", "]", ";", "_", ".", "each", "(", "formFiles", ",", "function", "(", "formFile", ")", "{", "forms", ".", "push", "(", "path", ".", "join", "(", "archiveDirectory", ",", "formFile", ".", "path", ")", ")", ";", "}", ")", ";", "async", ".", "each", "(", "forms", ",", "validateForm", ",", "callback", ")", ";", "}", "]", ",", "function", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Validates the content of the extracted ZIP to check that it is a valid archive to be imported. @param {string} archiveDirectory The directory where the ZIP archive has been unzipped @param {boolean} strict if true, strict checks must be performed: no extraneous files will be admitted. @param {function} cb callback
[ "Validates", "the", "content", "of", "the", "extracted", "ZIP", "to", "check", "that", "it", "is", "a", "valid", "archive", "to", "be", "imported", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/inputValidator.js#L75-L115
train
back4app/back4app-entity
src/back/models/attributes/Attribute.js
resolve
function resolve() { expect(arguments).to.have.length.within( 1, 4, 'Invalid arguments length when resolving an Attribute (it has to be ' + 'passed from 1 to 4 arguments)' ); var argumentArray = Array.prototype.slice.call(arguments); var TypedAttribute = attributes.types.ObjectAttribute; if (arguments.length === 1 && typeof arguments[0] !== 'string') { var attribute = objects.copy(arguments[0]); argumentArray[0] = attribute; expect(attribute).to.be.an( 'object', 'Invalid argument type when resolving an Attribute (it has to be an ' + 'object)' ); if (attribute.type) { expect(attribute.type).to.be.a( 'string', 'Invalid argument "type" when resolving an Attribute' + (attribute.name ? ' called' + attribute.name : '') + ' (it has to be a string)' ); try { TypedAttribute = attributes.types.get(attribute.type); } catch (e) { if (e instanceof errors.AttributeTypeNotFoundError) { TypedAttribute = attributes.types.AssociationAttribute; attribute.entity = attribute.type; } else { throw e; } } delete attribute.type; } } else { if (arguments.length > 1) { expect(arguments[1]).to.be.a( 'string', 'Invalid argument "type" when resolving an Attribute' + (arguments[0] ? ' called' + arguments[0] : '') + ' (it has to be a string)' ); try { TypedAttribute = attributes.types.get(arguments[1]); } catch (e) { if (e instanceof errors.AttributeTypeNotFoundError) { TypedAttribute = attributes.types.AssociationAttribute; argumentArray.splice(2, 0, arguments[1]); } else { throw e; } } argumentArray.splice(1,1); } } return new (Function.prototype.bind.apply( TypedAttribute, [null].concat(argumentArray) ))(); }
javascript
function resolve() { expect(arguments).to.have.length.within( 1, 4, 'Invalid arguments length when resolving an Attribute (it has to be ' + 'passed from 1 to 4 arguments)' ); var argumentArray = Array.prototype.slice.call(arguments); var TypedAttribute = attributes.types.ObjectAttribute; if (arguments.length === 1 && typeof arguments[0] !== 'string') { var attribute = objects.copy(arguments[0]); argumentArray[0] = attribute; expect(attribute).to.be.an( 'object', 'Invalid argument type when resolving an Attribute (it has to be an ' + 'object)' ); if (attribute.type) { expect(attribute.type).to.be.a( 'string', 'Invalid argument "type" when resolving an Attribute' + (attribute.name ? ' called' + attribute.name : '') + ' (it has to be a string)' ); try { TypedAttribute = attributes.types.get(attribute.type); } catch (e) { if (e instanceof errors.AttributeTypeNotFoundError) { TypedAttribute = attributes.types.AssociationAttribute; attribute.entity = attribute.type; } else { throw e; } } delete attribute.type; } } else { if (arguments.length > 1) { expect(arguments[1]).to.be.a( 'string', 'Invalid argument "type" when resolving an Attribute' + (arguments[0] ? ' called' + arguments[0] : '') + ' (it has to be a string)' ); try { TypedAttribute = attributes.types.get(arguments[1]); } catch (e) { if (e instanceof errors.AttributeTypeNotFoundError) { TypedAttribute = attributes.types.AssociationAttribute; argumentArray.splice(2, 0, arguments[1]); } else { throw e; } } argumentArray.splice(1,1); } } return new (Function.prototype.bind.apply( TypedAttribute, [null].concat(argumentArray) ))(); }
[ "function", "resolve", "(", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "within", "(", "1", ",", "4", ",", "'Invalid arguments length when resolving an Attribute (it has to be '", "+", "'passed from 1 to 4 arguments)'", ")", ";", "var", "argumentArray", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "var", "TypedAttribute", "=", "attributes", ".", "types", ".", "ObjectAttribute", ";", "if", "(", "arguments", ".", "length", "===", "1", "&&", "typeof", "arguments", "[", "0", "]", "!==", "'string'", ")", "{", "var", "attribute", "=", "objects", ".", "copy", "(", "arguments", "[", "0", "]", ")", ";", "argumentArray", "[", "0", "]", "=", "attribute", ";", "expect", "(", "attribute", ")", ".", "to", ".", "be", ".", "an", "(", "'object'", ",", "'Invalid argument type when resolving an Attribute (it has to be an '", "+", "'object)'", ")", ";", "if", "(", "attribute", ".", "type", ")", "{", "expect", "(", "attribute", ".", "type", ")", ".", "to", ".", "be", ".", "a", "(", "'string'", ",", "'Invalid argument \"type\" when resolving an Attribute'", "+", "(", "attribute", ".", "name", "?", "' called'", "+", "attribute", ".", "name", ":", "''", ")", "+", "' (it has to be a string)'", ")", ";", "try", "{", "TypedAttribute", "=", "attributes", ".", "types", ".", "get", "(", "attribute", ".", "type", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", "instanceof", "errors", ".", "AttributeTypeNotFoundError", ")", "{", "TypedAttribute", "=", "attributes", ".", "types", ".", "AssociationAttribute", ";", "attribute", ".", "entity", "=", "attribute", ".", "type", ";", "}", "else", "{", "throw", "e", ";", "}", "}", "delete", "attribute", ".", "type", ";", "}", "}", "else", "{", "if", "(", "arguments", ".", "length", ">", "1", ")", "{", "expect", "(", "arguments", "[", "1", "]", ")", ".", "to", ".", "be", ".", "a", "(", "'string'", ",", "'Invalid argument \"type\" when resolving an Attribute'", "+", "(", "arguments", "[", "0", "]", "?", "' called'", "+", "arguments", "[", "0", "]", ":", "''", ")", "+", "' (it has to be a string)'", ")", ";", "try", "{", "TypedAttribute", "=", "attributes", ".", "types", ".", "get", "(", "arguments", "[", "1", "]", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", "instanceof", "errors", ".", "AttributeTypeNotFoundError", ")", "{", "TypedAttribute", "=", "attributes", ".", "types", ".", "AssociationAttribute", ";", "argumentArray", ".", "splice", "(", "2", ",", "0", ",", "arguments", "[", "1", "]", ")", ";", "}", "else", "{", "throw", "e", ";", "}", "}", "argumentArray", ".", "splice", "(", "1", ",", "1", ")", ";", "}", "}", "return", "new", "(", "Function", ".", "prototype", ".", "bind", ".", "apply", "(", "TypedAttribute", ",", "[", "null", "]", ".", "concat", "(", "argumentArray", ")", ")", ")", "(", ")", ";", "}" ]
Resolves the arguments and create a new instance of Attribute. It tries to find the Attribute type. It it is not possible, it assumes that it is an AssociationAttribute. @memberof module:back4app-entity/models/attributes.Attribute @name resolve @param {!Object} attribute This is the attribute to be resolved. It can be passed as an Object. @param {!string} attribute.name It is the name of the attribute. @param {!string} [attribute.type='Object'] It is the type of the attribute. It is optional and if not passed it will assume 'Object' as the default value. @param {!string} [attribute.multiplicity='1'] It is the multiplicity of the attribute. It is optional and if not passed it will assume '1' as the default value. @param {?(boolean|number|string|Object|function)} [attribute.default] It is the default expression of the attribute. @returns {module:back4app-entity/models/attributes.Attribute} The new Attribute instance. @throws {module:back4app-entity/models/errors.AttributeTypeNotFoundError} @example Attribute.resolve({ name: 'attribute', type: 'String', multiplicity: '0..1', default: null }); Resolves the arguments and create a new instance of Attribute. It tries to find the Attribute type. It it is not possible, it assumes that it is an AssociationAttribute. @memberof module:back4app-entity/models/attributes.Attribute @name resolve @param {!string} name It is the name of the attribute. @param {!string} [type='Object'] It is the type of the attribute. It is optional and if not passed it will assume 'Object' as the default value. @param {!string} [multiplicity='1'] It is the multiplicity of the attribute. It is optional and if not passed it will assume '1' as the default value. @param {?(boolean|number|string|Object|function)} [default] It is the default expression of the attribute. @returns {module:back4app-entity/models/attributes.Attribute} The new Attribute instance. @throws {module:back4app-entity/models/errors.AttributeTypeNotFoundError} @example Attribute.resolve( this, 'attribute', 'String', '0..1', null );
[ "Resolves", "the", "arguments", "and", "create", "a", "new", "instance", "of", "Attribute", ".", "It", "tries", "to", "find", "the", "Attribute", "type", ".", "It", "it", "is", "not", "possible", "it", "assumes", "that", "it", "is", "an", "AssociationAttribute", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/attributes/Attribute.js#L456-L526
train
back4app/back4app-entity
src/back/models/attributes/Attribute.js
getDefaultValue
function getDefaultValue(entity) { expect(arguments).to.have.length( 1, 'Invalid arguments length when getting the default value of an Attribute ' + 'to an Entity instance (it has to be given 1 argument)' ); expect(entity).to.be.an.instanceOf( models.Entity, 'Invalid type of argument "entity" when getting the default value of an ' + 'Attribute to an Entity instance (it has to be an Entity)' ); if (typeof this.default === 'function') { return this.default.call(entity); } else { return this.default; } }
javascript
function getDefaultValue(entity) { expect(arguments).to.have.length( 1, 'Invalid arguments length when getting the default value of an Attribute ' + 'to an Entity instance (it has to be given 1 argument)' ); expect(entity).to.be.an.instanceOf( models.Entity, 'Invalid type of argument "entity" when getting the default value of an ' + 'Attribute to an Entity instance (it has to be an Entity)' ); if (typeof this.default === 'function') { return this.default.call(entity); } else { return this.default; } }
[ "function", "getDefaultValue", "(", "entity", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", "(", "1", ",", "'Invalid arguments length when getting the default value of an Attribute '", "+", "'to an Entity instance (it has to be given 1 argument)'", ")", ";", "expect", "(", "entity", ")", ".", "to", ".", "be", ".", "an", ".", "instanceOf", "(", "models", ".", "Entity", ",", "'Invalid type of argument \"entity\" when getting the default value of an '", "+", "'Attribute to an Entity instance (it has to be an Entity)'", ")", ";", "if", "(", "typeof", "this", ".", "default", "===", "'function'", ")", "{", "return", "this", ".", "default", ".", "call", "(", "entity", ")", ";", "}", "else", "{", "return", "this", ".", "default", ";", "}", "}" ]
Gets the default value of the current Attribute to a given Entity instance. @name module:back4app-entity/models/attributes.Attribute#getDefaultValue @function @param {!module:back4app-entity/models.Entity} entity The Entity instance to which the default value will be get. @returns {boolean|number|string|Object|function} The default value. @example var defaultValue = MyEntity.attributes.myAttribute.getDefaultValue( new MyEntity() );
[ "Gets", "the", "default", "value", "of", "the", "current", "Attribute", "to", "a", "given", "Entity", "instance", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/attributes/Attribute.js#L540-L558
train