id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
21,100
documentcloud/underscore-contrib
dist/underscore-contrib.js
function(obj, value, ks, defaultValue) { if (!existy(ks)) throw new TypeError("Attempted to set a property at a null path."); return _.updatePath(obj, function() { return value; }, ks, defaultValue); }
javascript
function(obj, value, ks, defaultValue) { if (!existy(ks)) throw new TypeError("Attempted to set a property at a null path."); return _.updatePath(obj, function() { return value; }, ks, defaultValue); }
[ "function", "(", "obj", ",", "value", ",", "ks", ",", "defaultValue", ")", "{", "if", "(", "!", "existy", "(", "ks", ")", ")", "throw", "new", "TypeError", "(", "\"Attempted to set a property at a null path.\"", ")", ";", "return", "_", ".", "updatePath", "(", "obj", ",", "function", "(", ")", "{", "return", "value", ";", "}", ",", "ks", ",", "defaultValue", ")", ";", "}" ]
Sets the value at any depth in a nested object based on the path described by the keys given.
[ "Sets", "the", "value", "at", "any", "depth", "in", "a", "nested", "object", "based", "on", "the", "path", "described", "by", "the", "keys", "given", "." ]
1492ffbe04a62a838da89df6ebdf77d0ed0b9844
https://github.com/documentcloud/underscore-contrib/blob/1492ffbe04a62a838da89df6ebdf77d0ed0b9844/dist/underscore-contrib.js#L1579-L1583
21,101
documentcloud/underscore-contrib
dist/underscore-contrib.js
function (obj, ks) { return _.pick.apply(null, concat.call([obj], ks)); }
javascript
function (obj, ks) { return _.pick.apply(null, concat.call([obj], ks)); }
[ "function", "(", "obj", ",", "ks", ")", "{", "return", "_", ".", "pick", ".", "apply", "(", "null", ",", "concat", ".", "call", "(", "[", "obj", "]", ",", "ks", ")", ")", ";", "}" ]
Like `_.pick` except that it takes an array of keys to pick.
[ "Like", "_", ".", "pick", "except", "that", "it", "takes", "an", "array", "of", "keys", "to", "pick", "." ]
1492ffbe04a62a838da89df6ebdf77d0ed0b9844
https://github.com/documentcloud/underscore-contrib/blob/1492ffbe04a62a838da89df6ebdf77d0ed0b9844/dist/underscore-contrib.js#L1633-L1635
21,102
documentcloud/underscore-contrib
dist/underscore-contrib.js
function(str) { var parameters = str.split('&'), obj = {}, parameter, key, match, lastKey, subKey, depth; // Iterate over key/value pairs _.each(parameters, function(parameter) { parameter = parameter.split('='); key = urlDecode(parameter[0]); lastKey = key; depth = obj; // Reset so we don't have issues when matching the same string bracketRegex.lastIndex = 0; // Attempt to extract nested values while ((match = bracketRegex.exec(key)) !== null) { if (!_.isUndefined(match[1])) { // If we're at the top nested level, no new object needed subKey = match[1]; } else { // If we're at a lower nested level, we need to step down, and make // sure that there is an object to place the value into subKey = match[2]; depth[lastKey] = depth[lastKey] || (subKey ? {} : []); depth = depth[lastKey]; } // Save the correct key as a hash or an array lastKey = subKey || _.size(depth); } // Assign value to nested object depth[lastKey] = urlDecode(parameter[1]); }); return obj; }
javascript
function(str) { var parameters = str.split('&'), obj = {}, parameter, key, match, lastKey, subKey, depth; // Iterate over key/value pairs _.each(parameters, function(parameter) { parameter = parameter.split('='); key = urlDecode(parameter[0]); lastKey = key; depth = obj; // Reset so we don't have issues when matching the same string bracketRegex.lastIndex = 0; // Attempt to extract nested values while ((match = bracketRegex.exec(key)) !== null) { if (!_.isUndefined(match[1])) { // If we're at the top nested level, no new object needed subKey = match[1]; } else { // If we're at a lower nested level, we need to step down, and make // sure that there is an object to place the value into subKey = match[2]; depth[lastKey] = depth[lastKey] || (subKey ? {} : []); depth = depth[lastKey]; } // Save the correct key as a hash or an array lastKey = subKey || _.size(depth); } // Assign value to nested object depth[lastKey] = urlDecode(parameter[1]); }); return obj; }
[ "function", "(", "str", ")", "{", "var", "parameters", "=", "str", ".", "split", "(", "'&'", ")", ",", "obj", "=", "{", "}", ",", "parameter", ",", "key", ",", "match", ",", "lastKey", ",", "subKey", ",", "depth", ";", "// Iterate over key/value pairs", "_", ".", "each", "(", "parameters", ",", "function", "(", "parameter", ")", "{", "parameter", "=", "parameter", ".", "split", "(", "'='", ")", ";", "key", "=", "urlDecode", "(", "parameter", "[", "0", "]", ")", ";", "lastKey", "=", "key", ";", "depth", "=", "obj", ";", "// Reset so we don't have issues when matching the same string", "bracketRegex", ".", "lastIndex", "=", "0", ";", "// Attempt to extract nested values", "while", "(", "(", "match", "=", "bracketRegex", ".", "exec", "(", "key", ")", ")", "!==", "null", ")", "{", "if", "(", "!", "_", ".", "isUndefined", "(", "match", "[", "1", "]", ")", ")", "{", "// If we're at the top nested level, no new object needed", "subKey", "=", "match", "[", "1", "]", ";", "}", "else", "{", "// If we're at a lower nested level, we need to step down, and make", "// sure that there is an object to place the value into", "subKey", "=", "match", "[", "2", "]", ";", "depth", "[", "lastKey", "]", "=", "depth", "[", "lastKey", "]", "||", "(", "subKey", "?", "{", "}", ":", "[", "]", ")", ";", "depth", "=", "depth", "[", "lastKey", "]", ";", "}", "// Save the correct key as a hash or an array", "lastKey", "=", "subKey", "||", "_", ".", "size", "(", "depth", ")", ";", "}", "// Assign value to nested object", "depth", "[", "lastKey", "]", "=", "urlDecode", "(", "parameter", "[", "1", "]", ")", ";", "}", ")", ";", "return", "obj", ";", "}" ]
Parses a query string into a hash
[ "Parses", "a", "query", "string", "into", "a", "hash" ]
1492ffbe04a62a838da89df6ebdf77d0ed0b9844
https://github.com/documentcloud/underscore-contrib/blob/1492ffbe04a62a838da89df6ebdf77d0ed0b9844/dist/underscore-contrib.js#L1951-L1996
21,103
documentcloud/underscore-contrib
underscore.util.operators.js
variaderize
function variaderize(func) { return function (args) { var allArgs = isArrayLike(args) ? args : arguments; return func(allArgs); }; }
javascript
function variaderize(func) { return function (args) { var allArgs = isArrayLike(args) ? args : arguments; return func(allArgs); }; }
[ "function", "variaderize", "(", "func", ")", "{", "return", "function", "(", "args", ")", "{", "var", "allArgs", "=", "isArrayLike", "(", "args", ")", "?", "args", ":", "arguments", ";", "return", "func", "(", "allArgs", ")", ";", "}", ";", "}" ]
Converts a unary function that operates on an array into one that also works with a variable number of arguments
[ "Converts", "a", "unary", "function", "that", "operates", "on", "an", "array", "into", "one", "that", "also", "works", "with", "a", "variable", "number", "of", "arguments" ]
1492ffbe04a62a838da89df6ebdf77d0ed0b9844
https://github.com/documentcloud/underscore-contrib/blob/1492ffbe04a62a838da89df6ebdf77d0ed0b9844/underscore.util.operators.js#L40-L45
21,104
voodootikigod/node-rolling-spider
lib/swarm.js
function(options) { this.ble = noble; var membership = (typeof options === 'string' ? options : undefined); options = options || {}; this.targets = membership || options.membership; this.peripherals = []; this.members = []; this.timeout = (options.timeout || 30) * 1000; // in seconds //define membership if (this.targets && !util.isArray(this.targets)) { this.targets = this.targets.split(','); } else { this.targets = []; } this.logger = options.logger || debug; //use debug instead of console.log this.discovering = false; this.active = false; // handle disconnect gracefully this.ble.on('warning', function(message) { this.onDisconnect(); }.bind(this)); return this; }
javascript
function(options) { this.ble = noble; var membership = (typeof options === 'string' ? options : undefined); options = options || {}; this.targets = membership || options.membership; this.peripherals = []; this.members = []; this.timeout = (options.timeout || 30) * 1000; // in seconds //define membership if (this.targets && !util.isArray(this.targets)) { this.targets = this.targets.split(','); } else { this.targets = []; } this.logger = options.logger || debug; //use debug instead of console.log this.discovering = false; this.active = false; // handle disconnect gracefully this.ble.on('warning', function(message) { this.onDisconnect(); }.bind(this)); return this; }
[ "function", "(", "options", ")", "{", "this", ".", "ble", "=", "noble", ";", "var", "membership", "=", "(", "typeof", "options", "===", "'string'", "?", "options", ":", "undefined", ")", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "targets", "=", "membership", "||", "options", ".", "membership", ";", "this", ".", "peripherals", "=", "[", "]", ";", "this", ".", "members", "=", "[", "]", ";", "this", ".", "timeout", "=", "(", "options", ".", "timeout", "||", "30", ")", "*", "1000", ";", "// in seconds", "//define membership", "if", "(", "this", ".", "targets", "&&", "!", "util", ".", "isArray", "(", "this", ".", "targets", ")", ")", "{", "this", ".", "targets", "=", "this", ".", "targets", ".", "split", "(", "','", ")", ";", "}", "else", "{", "this", ".", "targets", "=", "[", "]", ";", "}", "this", ".", "logger", "=", "options", ".", "logger", "||", "debug", ";", "//use debug instead of console.log", "this", ".", "discovering", "=", "false", ";", "this", ".", "active", "=", "false", ";", "// handle disconnect gracefully", "this", ".", "ble", ".", "on", "(", "'warning'", ",", "function", "(", "message", ")", "{", "this", ".", "onDisconnect", "(", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "return", "this", ";", "}" ]
Constructs a new RollingSpider Swarm @param {Object} options to construct the drone with: - {String} A comma seperated list (as a string) of UUIDs or names to connect to. This could also be an array of the same items. If this is omitted then it will add any device with the manufacturer data value for Parrot.. - logger function to call if/when errors occur. If omitted then uses console#log @constructor
[ "Constructs", "a", "new", "RollingSpider", "Swarm" ]
b9ed55d5016aec55671d328b62c980ca0f9e5ef4
https://github.com/voodootikigod/node-rolling-spider/blob/b9ed55d5016aec55671d328b62c980ca0f9e5ef4/lib/swarm.js#L18-L48
21,105
voodootikigod/node-rolling-spider
lib/drone.js
function(options) { EventEmitter.call(this); var uuid = (typeof options === 'string' ? options : undefined); options = options || {}; this.uuid = null; this.targets = uuid || options.uuid; if (this.targets && !util.isArray(this.targets)) { this.targets = this.targets.split(','); } this.logger = options.logger || debug; //use debug instead of console.log this.forceConnect = options.forceConnect || false; this.connected = false; this.discovered = false; this.ble = noble; this.peripheral = null; this.takenOff = false; this.driveStepsRemaining = 0; this.speeds = { yaw: 0, // turn pitch: 0, // forward/backward roll: 0, // left/right altitude: 0 // up/down }; /** * Used to store the 'counter' that's sent to each characteristic */ this.steps = { 'fa0a': 0, 'fa0b': 0, 'fa0c': 0 }; this.status = { stateValue: 0, flying: false, battery: 100 }; // handle disconnect gracefully this.ble.on('warning', function(message) { this.onDisconnect(); }.bind(this)); }
javascript
function(options) { EventEmitter.call(this); var uuid = (typeof options === 'string' ? options : undefined); options = options || {}; this.uuid = null; this.targets = uuid || options.uuid; if (this.targets && !util.isArray(this.targets)) { this.targets = this.targets.split(','); } this.logger = options.logger || debug; //use debug instead of console.log this.forceConnect = options.forceConnect || false; this.connected = false; this.discovered = false; this.ble = noble; this.peripheral = null; this.takenOff = false; this.driveStepsRemaining = 0; this.speeds = { yaw: 0, // turn pitch: 0, // forward/backward roll: 0, // left/right altitude: 0 // up/down }; /** * Used to store the 'counter' that's sent to each characteristic */ this.steps = { 'fa0a': 0, 'fa0b': 0, 'fa0c': 0 }; this.status = { stateValue: 0, flying: false, battery: 100 }; // handle disconnect gracefully this.ble.on('warning', function(message) { this.onDisconnect(); }.bind(this)); }
[ "function", "(", "options", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "var", "uuid", "=", "(", "typeof", "options", "===", "'string'", "?", "options", ":", "undefined", ")", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "uuid", "=", "null", ";", "this", ".", "targets", "=", "uuid", "||", "options", ".", "uuid", ";", "if", "(", "this", ".", "targets", "&&", "!", "util", ".", "isArray", "(", "this", ".", "targets", ")", ")", "{", "this", ".", "targets", "=", "this", ".", "targets", ".", "split", "(", "','", ")", ";", "}", "this", ".", "logger", "=", "options", ".", "logger", "||", "debug", ";", "//use debug instead of console.log", "this", ".", "forceConnect", "=", "options", ".", "forceConnect", "||", "false", ";", "this", ".", "connected", "=", "false", ";", "this", ".", "discovered", "=", "false", ";", "this", ".", "ble", "=", "noble", ";", "this", ".", "peripheral", "=", "null", ";", "this", ".", "takenOff", "=", "false", ";", "this", ".", "driveStepsRemaining", "=", "0", ";", "this", ".", "speeds", "=", "{", "yaw", ":", "0", ",", "// turn", "pitch", ":", "0", ",", "// forward/backward", "roll", ":", "0", ",", "// left/right", "altitude", ":", "0", "// up/down", "}", ";", "/**\n * Used to store the 'counter' that's sent to each characteristic\n */", "this", ".", "steps", "=", "{", "'fa0a'", ":", "0", ",", "'fa0b'", ":", "0", ",", "'fa0c'", ":", "0", "}", ";", "this", ".", "status", "=", "{", "stateValue", ":", "0", ",", "flying", ":", "false", ",", "battery", ":", "100", "}", ";", "// handle disconnect gracefully", "this", ".", "ble", ".", "on", "(", "'warning'", ",", "function", "(", "message", ")", "{", "this", ".", "onDisconnect", "(", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Constructs a new RollingSpider @param {Object} options to construct the drone with: - {String} uuid to connect to. If this is omitted then it will connect to the first device starting with 'RS_' as the local name. - logger function to call if/when errors occur. If omitted then uses console#log @constructor
[ "Constructs", "a", "new", "RollingSpider" ]
b9ed55d5016aec55671d328b62c980ca0f9e5ef4
https://github.com/voodootikigod/node-rolling-spider/blob/b9ed55d5016aec55671d328b62c980ca0f9e5ef4/lib/drone.js#L22-L71
21,106
voodootikigod/node-rolling-spider
lib/drone.js
takeOff
function takeOff(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#takeOff'); if (this.status.battery < 10) { this.logger('!!! BATTERY LEVEL TOO LOW !!!'); } if (!this.status.flying) { this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x00, 0x01, 0x00]) ); this.status.flying = true; } this.on('flyingStatusChange', function(newStatus) { if (newStatus === 2) { if (typeof callback === 'function') { callback(); } } }); }
javascript
function takeOff(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#takeOff'); if (this.status.battery < 10) { this.logger('!!! BATTERY LEVEL TOO LOW !!!'); } if (!this.status.flying) { this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x00, 0x01, 0x00]) ); this.status.flying = true; } this.on('flyingStatusChange', function(newStatus) { if (newStatus === 2) { if (typeof callback === 'function') { callback(); } } }); }
[ "function", "takeOff", "(", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "this", ".", "logger", "(", "'RollingSpider#takeOff'", ")", ";", "if", "(", "this", ".", "status", ".", "battery", "<", "10", ")", "{", "this", ".", "logger", "(", "'!!! BATTERY LEVEL TOO LOW !!!'", ")", ";", "}", "if", "(", "!", "this", ".", "status", ".", "flying", ")", "{", "this", ".", "writeTo", "(", "'fa0b'", ",", "new", "Buffer", "(", "[", "0x02", ",", "++", "this", ".", "steps", ".", "fa0b", "&", "0xFF", ",", "0x02", ",", "0x00", ",", "0x01", ",", "0x00", "]", ")", ")", ";", "this", ".", "status", ".", "flying", "=", "true", ";", "}", "this", ".", "on", "(", "'flyingStatusChange'", ",", "function", "(", "newStatus", ")", "{", "if", "(", "newStatus", "===", "2", ")", "{", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "callback", "(", ")", ";", "}", "}", "}", ")", ";", "}" ]
Operational Functions Multiple use cases provided to support initial build API as well as NodeCopter API and parity with the ar-drone library. Instructs the drone to take off if it isn't already in the air
[ "Operational", "Functions", "Multiple", "use", "cases", "provided", "to", "support", "initial", "build", "API", "as", "well", "as", "NodeCopter", "API", "and", "parity", "with", "the", "ar", "-", "drone", "library", ".", "Instructs", "the", "drone", "to", "take", "off", "if", "it", "isn", "t", "already", "in", "the", "air" ]
b9ed55d5016aec55671d328b62c980ca0f9e5ef4
https://github.com/voodootikigod/node-rolling-spider/blob/b9ed55d5016aec55671d328b62c980ca0f9e5ef4/lib/drone.js#L507-L533
21,107
voodootikigod/node-rolling-spider
lib/drone.js
wheelOn
function wheelOn(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#wheelOn'); this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x01, 0x02, 0x00, 0x01]) ); if (callback) { callback(); } }
javascript
function wheelOn(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#wheelOn'); this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x01, 0x02, 0x00, 0x01]) ); if (callback) { callback(); } }
[ "function", "wheelOn", "(", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "this", ".", "logger", "(", "'RollingSpider#wheelOn'", ")", ";", "this", ".", "writeTo", "(", "'fa0b'", ",", "new", "Buffer", "(", "[", "0x02", ",", "++", "this", ".", "steps", ".", "fa0b", "&", "0xFF", ",", "0x02", ",", "0x01", ",", "0x02", ",", "0x00", ",", "0x01", "]", ")", ")", ";", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "}" ]
Configures the drone to fly in 'wheel on' or protected mode.
[ "Configures", "the", "drone", "to", "fly", "in", "wheel", "on", "or", "protected", "mode", "." ]
b9ed55d5016aec55671d328b62c980ca0f9e5ef4
https://github.com/voodootikigod/node-rolling-spider/blob/b9ed55d5016aec55671d328b62c980ca0f9e5ef4/lib/drone.js#L542-L556
21,108
voodootikigod/node-rolling-spider
lib/drone.js
wheelOff
function wheelOff(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#wheelOff'); this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x01, 0x02, 0x00, 0x00]) ); if (callback) { callback(); } }
javascript
function wheelOff(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#wheelOff'); this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x01, 0x02, 0x00, 0x00]) ); if (callback) { callback(); } }
[ "function", "wheelOff", "(", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "this", ".", "logger", "(", "'RollingSpider#wheelOff'", ")", ";", "this", ".", "writeTo", "(", "'fa0b'", ",", "new", "Buffer", "(", "[", "0x02", ",", "++", "this", ".", "steps", ".", "fa0b", "&", "0xFF", ",", "0x02", ",", "0x01", ",", "0x02", ",", "0x00", ",", "0x00", "]", ")", ")", ";", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "}" ]
Configures the drone to fly in 'wheel off' or unprotected mode.
[ "Configures", "the", "drone", "to", "fly", "in", "wheel", "off", "or", "unprotected", "mode", "." ]
b9ed55d5016aec55671d328b62c980ca0f9e5ef4
https://github.com/voodootikigod/node-rolling-spider/blob/b9ed55d5016aec55671d328b62c980ca0f9e5ef4/lib/drone.js#L562-L575
21,109
voodootikigod/node-rolling-spider
lib/drone.js
land
function land(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#land'); if (this.status.flying) { this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x00, 0x03, 0x00]) ); this.on('flyingStatusChange', function(newStatus) { if (newStatus === 0) { this.status.flying = false; if (typeof callback === 'function') { callback(); } } }); } else { this.logger('Calling RollingSpider#land when it\'s not in the air isn\'t going to do anything'); if (callback) { callback(); } } }
javascript
function land(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#land'); if (this.status.flying) { this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x00, 0x03, 0x00]) ); this.on('flyingStatusChange', function(newStatus) { if (newStatus === 0) { this.status.flying = false; if (typeof callback === 'function') { callback(); } } }); } else { this.logger('Calling RollingSpider#land when it\'s not in the air isn\'t going to do anything'); if (callback) { callback(); } } }
[ "function", "land", "(", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "this", ".", "logger", "(", "'RollingSpider#land'", ")", ";", "if", "(", "this", ".", "status", ".", "flying", ")", "{", "this", ".", "writeTo", "(", "'fa0b'", ",", "new", "Buffer", "(", "[", "0x02", ",", "++", "this", ".", "steps", ".", "fa0b", "&", "0xFF", ",", "0x02", ",", "0x00", ",", "0x03", ",", "0x00", "]", ")", ")", ";", "this", ".", "on", "(", "'flyingStatusChange'", ",", "function", "(", "newStatus", ")", "{", "if", "(", "newStatus", "===", "0", ")", "{", "this", ".", "status", ".", "flying", "=", "false", ";", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "callback", "(", ")", ";", "}", "}", "}", ")", ";", "}", "else", "{", "this", ".", "logger", "(", "'Calling RollingSpider#land when it\\'s not in the air isn\\'t going to do anything'", ")", ";", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "}", "}" ]
Instructs the drone to land if it's in the air.
[ "Instructs", "the", "drone", "to", "land", "if", "it", "s", "in", "the", "air", "." ]
b9ed55d5016aec55671d328b62c980ca0f9e5ef4
https://github.com/voodootikigod/node-rolling-spider/blob/b9ed55d5016aec55671d328b62c980ca0f9e5ef4/lib/drone.js#L581-L608
21,110
voodootikigod/node-rolling-spider
lib/drone.js
cutOff
function cutOff(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#cutOff'); this.status.flying = false; this.writeTo( 'fa0c', new Buffer([0x02, ++this.steps.fa0c & 0xFF, 0x02, 0x00, 0x04, 0x00]) , callback); }
javascript
function cutOff(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#cutOff'); this.status.flying = false; this.writeTo( 'fa0c', new Buffer([0x02, ++this.steps.fa0c & 0xFF, 0x02, 0x00, 0x04, 0x00]) , callback); }
[ "function", "cutOff", "(", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "this", ".", "logger", "(", "'RollingSpider#cutOff'", ")", ";", "this", ".", "status", ".", "flying", "=", "false", ";", "this", ".", "writeTo", "(", "'fa0c'", ",", "new", "Buffer", "(", "[", "0x02", ",", "++", "this", ".", "steps", ".", "fa0c", "&", "0xFF", ",", "0x02", ",", "0x00", ",", "0x04", ",", "0x00", "]", ")", ",", "callback", ")", ";", "}" ]
Instructs the drone to do an emergency landing.
[ "Instructs", "the", "drone", "to", "do", "an", "emergency", "landing", "." ]
b9ed55d5016aec55671d328b62c980ca0f9e5ef4
https://github.com/voodootikigod/node-rolling-spider/blob/b9ed55d5016aec55671d328b62c980ca0f9e5ef4/lib/drone.js#L627-L638
21,111
voodootikigod/node-rolling-spider
lib/drone.js
flatTrim
function flatTrim(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#flatTrim'); this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x00, 0x00, 0x00]), callback ); }
javascript
function flatTrim(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#flatTrim'); this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x00, 0x00, 0x00]), callback ); }
[ "function", "flatTrim", "(", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "this", ".", "logger", "(", "'RollingSpider#flatTrim'", ")", ";", "this", ".", "writeTo", "(", "'fa0b'", ",", "new", "Buffer", "(", "[", "0x02", ",", "++", "this", ".", "steps", ".", "fa0b", "&", "0xFF", ",", "0x02", ",", "0x00", ",", "0x00", ",", "0x00", "]", ")", ",", "callback", ")", ";", "}" ]
Instructs the drone to trim. Make sure to call this before taking off.
[ "Instructs", "the", "drone", "to", "trim", ".", "Make", "sure", "to", "call", "this", "before", "taking", "off", "." ]
b9ed55d5016aec55671d328b62c980ca0f9e5ef4
https://github.com/voodootikigod/node-rolling-spider/blob/b9ed55d5016aec55671d328b62c980ca0f9e5ef4/lib/drone.js#L643-L654
21,112
voodootikigod/node-rolling-spider
lib/drone.js
frontFlip
function frontFlip(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#frontFlip'); if (this.status.flying) { this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), callback ); } else { this.logger('Calling RollingSpider#frontFlip when it\'s not in the air isn\'t going to do anything'); if (typeof callback === 'function') { callback(); } } if (callback) { callback(); } }
javascript
function frontFlip(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.logger('RollingSpider#frontFlip'); if (this.status.flying) { this.writeTo( 'fa0b', new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), callback ); } else { this.logger('Calling RollingSpider#frontFlip when it\'s not in the air isn\'t going to do anything'); if (typeof callback === 'function') { callback(); } } if (callback) { callback(); } }
[ "function", "frontFlip", "(", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "this", ".", "logger", "(", "'RollingSpider#frontFlip'", ")", ";", "if", "(", "this", ".", "status", ".", "flying", ")", "{", "this", ".", "writeTo", "(", "'fa0b'", ",", "new", "Buffer", "(", "[", "0x02", ",", "++", "this", ".", "steps", ".", "fa0b", "&", "0xFF", ",", "0x02", ",", "0x04", ",", "0x00", ",", "0x00", ",", "0x00", ",", "0x00", ",", "0x00", ",", "0x00", "]", ")", ",", "callback", ")", ";", "}", "else", "{", "this", ".", "logger", "(", "'Calling RollingSpider#frontFlip when it\\'s not in the air isn\\'t going to do anything'", ")", ";", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "callback", "(", ")", ";", "}", "}", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "}" ]
Instructs the drone to do a front flip. It will only do this if it's in the air
[ "Instructs", "the", "drone", "to", "do", "a", "front", "flip", "." ]
b9ed55d5016aec55671d328b62c980ca0f9e5ef4
https://github.com/voodootikigod/node-rolling-spider/blob/b9ed55d5016aec55671d328b62c980ca0f9e5ef4/lib/drone.js#L665-L686
21,113
SAP/cf-nodejs-logging-support
sample/cf-nodejs-shoutboard/web-express.js
mergeMessages
function mergeMessages(data) { lastSync = (new Date()).getTime(); if (messages.length == 0) { messages = data; } else { var i = data.length - 1; var j = messages.length - 1; while (i >= 0 && j >= 0) { if (data[i].timestamp < messages[j].timestamp) { j--; } else { messages.splice(j + 1, 0, data[i--]); } } } }
javascript
function mergeMessages(data) { lastSync = (new Date()).getTime(); if (messages.length == 0) { messages = data; } else { var i = data.length - 1; var j = messages.length - 1; while (i >= 0 && j >= 0) { if (data[i].timestamp < messages[j].timestamp) { j--; } else { messages.splice(j + 1, 0, data[i--]); } } } }
[ "function", "mergeMessages", "(", "data", ")", "{", "lastSync", "=", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", ";", "if", "(", "messages", ".", "length", "==", "0", ")", "{", "messages", "=", "data", ";", "}", "else", "{", "var", "i", "=", "data", ".", "length", "-", "1", ";", "var", "j", "=", "messages", ".", "length", "-", "1", ";", "while", "(", "i", ">=", "0", "&&", "j", ">=", "0", ")", "{", "if", "(", "data", "[", "i", "]", ".", "timestamp", "<", "messages", "[", "j", "]", ".", "timestamp", ")", "{", "j", "--", ";", "}", "else", "{", "messages", ".", "splice", "(", "j", "+", "1", ",", "0", ",", "data", "[", "i", "--", "]", ")", ";", "}", "}", "}", "}" ]
merge messages from different servers after redis restart
[ "merge", "messages", "from", "different", "servers", "after", "redis", "restart" ]
129459d40e3f1c70bdb929118ce7ffd6ab7578c4
https://github.com/SAP/cf-nodejs-logging-support/blob/129459d40e3f1c70bdb929118ce7ffd6ab7578c4/sample/cf-nodejs-shoutboard/web-express.js#L83-L98
21,114
SAP/cf-nodejs-logging-support
sample/cf-nodejs-shoutboard/web-express.js
sendCumulativeMessages
function sendCumulativeMessages(timestamp, clientSync, res) { if (timestamp == null) timestamp = 0; if (clientSync == null) clientSync = 0; var data = getCumulativeMessages(timestamp, clientSync); res.send(data); }
javascript
function sendCumulativeMessages(timestamp, clientSync, res) { if (timestamp == null) timestamp = 0; if (clientSync == null) clientSync = 0; var data = getCumulativeMessages(timestamp, clientSync); res.send(data); }
[ "function", "sendCumulativeMessages", "(", "timestamp", ",", "clientSync", ",", "res", ")", "{", "if", "(", "timestamp", "==", "null", ")", "timestamp", "=", "0", ";", "if", "(", "clientSync", "==", "null", ")", "clientSync", "=", "0", ";", "var", "data", "=", "getCumulativeMessages", "(", "timestamp", ",", "clientSync", ")", ";", "res", ".", "send", "(", "data", ")", ";", "}" ]
send all messages to client it is missing, or resends some messages after redis restart
[ "send", "all", "messages", "to", "client", "it", "is", "missing", "or", "resends", "some", "messages", "after", "redis", "restart" ]
129459d40e3f1c70bdb929118ce7ffd6ab7578c4
https://github.com/SAP/cf-nodejs-logging-support/blob/129459d40e3f1c70bdb929118ce7ffd6ab7578c4/sample/cf-nodejs-shoutboard/web-express.js#L109-L115
21,115
SAP/cf-nodejs-logging-support
sample/cf-nodejs-shoutboard/web-express.js
getCumulativeMessages
function getCumulativeMessages(timestamp, clientSync) { var msgs = []; if (lastSync > clientSync) { msgs = messages; } else { var newMsgs = messages.length; while (newMsgs > 0 && messages[newMsgs - 1].timestamp > timestamp) { newMsgs--; } for (var i = newMsgs; i < messages.length; i++) { msgs.push(messages[i]); } } var data = {}; data.msgs = msgs; data.lastSync = lastSync; return data; }
javascript
function getCumulativeMessages(timestamp, clientSync) { var msgs = []; if (lastSync > clientSync) { msgs = messages; } else { var newMsgs = messages.length; while (newMsgs > 0 && messages[newMsgs - 1].timestamp > timestamp) { newMsgs--; } for (var i = newMsgs; i < messages.length; i++) { msgs.push(messages[i]); } } var data = {}; data.msgs = msgs; data.lastSync = lastSync; return data; }
[ "function", "getCumulativeMessages", "(", "timestamp", ",", "clientSync", ")", "{", "var", "msgs", "=", "[", "]", ";", "if", "(", "lastSync", ">", "clientSync", ")", "{", "msgs", "=", "messages", ";", "}", "else", "{", "var", "newMsgs", "=", "messages", ".", "length", ";", "while", "(", "newMsgs", ">", "0", "&&", "messages", "[", "newMsgs", "-", "1", "]", ".", "timestamp", ">", "timestamp", ")", "{", "newMsgs", "--", ";", "}", "for", "(", "var", "i", "=", "newMsgs", ";", "i", "<", "messages", ".", "length", ";", "i", "++", ")", "{", "msgs", ".", "push", "(", "messages", "[", "i", "]", ")", ";", "}", "}", "var", "data", "=", "{", "}", ";", "data", ".", "msgs", "=", "msgs", ";", "data", ".", "lastSync", "=", "lastSync", ";", "return", "data", ";", "}" ]
get the requested messages from message storage system
[ "get", "the", "requested", "messages", "from", "message", "storage", "system" ]
129459d40e3f1c70bdb929118ce7ffd6ab7578c4
https://github.com/SAP/cf-nodejs-logging-support/blob/129459d40e3f1c70bdb929118ce7ffd6ab7578c4/sample/cf-nodejs-shoutboard/web-express.js#L118-L137
21,116
SAP/cf-nodejs-logging-support
sample/cf-nodejs-shoutboard/web-express.js
synchronize
function synchronize() { if (syncPointer != -1) { log.logMessage("verbose", "redis synchronization!"); var syncMessage = {}; syncMessage.data = messages.splice(syncPointer, messages.length - syncPointer); setTimeout(function () { pub.publish("message", JSON.stringify(syncMessage)); }, 200); syncPointer = -1; } }
javascript
function synchronize() { if (syncPointer != -1) { log.logMessage("verbose", "redis synchronization!"); var syncMessage = {}; syncMessage.data = messages.splice(syncPointer, messages.length - syncPointer); setTimeout(function () { pub.publish("message", JSON.stringify(syncMessage)); }, 200); syncPointer = -1; } }
[ "function", "synchronize", "(", ")", "{", "if", "(", "syncPointer", "!=", "-", "1", ")", "{", "log", ".", "logMessage", "(", "\"verbose\"", ",", "\"redis synchronization!\"", ")", ";", "var", "syncMessage", "=", "{", "}", ";", "syncMessage", ".", "data", "=", "messages", ".", "splice", "(", "syncPointer", ",", "messages", ".", "length", "-", "syncPointer", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "pub", ".", "publish", "(", "\"message\"", ",", "JSON", ".", "stringify", "(", "syncMessage", ")", ")", ";", "}", ",", "200", ")", ";", "syncPointer", "=", "-", "1", ";", "}", "}" ]
synchronizes messages after redis reconnect between server Instances
[ "synchronizes", "messages", "after", "redis", "reconnect", "between", "server", "Instances" ]
129459d40e3f1c70bdb929118ce7ffd6ab7578c4
https://github.com/SAP/cf-nodejs-logging-support/blob/129459d40e3f1c70bdb929118ce7ffd6ab7578c4/sample/cf-nodejs-shoutboard/web-express.js#L166-L176
21,117
stacktracejs/stacktrace-gps
stacktrace-gps.js
_xdr
function _xdr(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('get', url); req.onerror = reject; req.onreadystatechange = function onreadystatechange() { if (req.readyState === 4) { if ((req.status >= 200 && req.status < 300) || (url.substr(0, 7) === 'file://' && req.responseText)) { resolve(req.responseText); } else { reject(new Error('HTTP status: ' + req.status + ' retrieving ' + url)); } } }; req.send(); }); }
javascript
function _xdr(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('get', url); req.onerror = reject; req.onreadystatechange = function onreadystatechange() { if (req.readyState === 4) { if ((req.status >= 200 && req.status < 300) || (url.substr(0, 7) === 'file://' && req.responseText)) { resolve(req.responseText); } else { reject(new Error('HTTP status: ' + req.status + ' retrieving ' + url)); } } }; req.send(); }); }
[ "function", "_xdr", "(", "url", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "req", "=", "new", "XMLHttpRequest", "(", ")", ";", "req", ".", "open", "(", "'get'", ",", "url", ")", ";", "req", ".", "onerror", "=", "reject", ";", "req", ".", "onreadystatechange", "=", "function", "onreadystatechange", "(", ")", "{", "if", "(", "req", ".", "readyState", "===", "4", ")", "{", "if", "(", "(", "req", ".", "status", ">=", "200", "&&", "req", ".", "status", "<", "300", ")", "||", "(", "url", ".", "substr", "(", "0", ",", "7", ")", "===", "'file://'", "&&", "req", ".", "responseText", ")", ")", "{", "resolve", "(", "req", ".", "responseText", ")", ";", "}", "else", "{", "reject", "(", "new", "Error", "(", "'HTTP status: '", "+", "req", ".", "status", "+", "' retrieving '", "+", "url", ")", ")", ";", "}", "}", "}", ";", "req", ".", "send", "(", ")", ";", "}", ")", ";", "}" ]
Make a X-Domain request to url and callback. @param {String} url @returns {Promise} with response text if fulfilled
[ "Make", "a", "X", "-", "Domain", "request", "to", "url", "and", "callback", "." ]
1b80f11a6716dbd189dd08c89049b1efe6f45b65
https://github.com/stacktracejs/stacktrace-gps/blob/1b80f11a6716dbd189dd08c89049b1efe6f45b65/stacktrace-gps.js#L22-L40
21,118
nunofgs/clean-deep
dist/index.js
cleanDeep
function cleanDeep(object) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$emptyArrays = _ref.emptyArrays, emptyArrays = _ref$emptyArrays === undefined ? true : _ref$emptyArrays, _ref$emptyObjects = _ref.emptyObjects, emptyObjects = _ref$emptyObjects === undefined ? true : _ref$emptyObjects, _ref$emptyStrings = _ref.emptyStrings, emptyStrings = _ref$emptyStrings === undefined ? true : _ref$emptyStrings, _ref$nullValues = _ref.nullValues, nullValues = _ref$nullValues === undefined ? true : _ref$nullValues, _ref$undefinedValues = _ref.undefinedValues, undefinedValues = _ref$undefinedValues === undefined ? true : _ref$undefinedValues; return (0, _lodash6.default)(object, function (result, value, key) { // Recurse into arrays and objects. if (Array.isArray(value) || (0, _lodash4.default)(value)) { value = cleanDeep(value, { emptyArrays: emptyArrays, emptyObjects: emptyObjects, emptyStrings: emptyStrings, nullValues: nullValues, undefinedValues: undefinedValues }); } // Exclude empty objects. if (emptyObjects && (0, _lodash4.default)(value) && (0, _lodash2.default)(value)) { return; } // Exclude empty arrays. if (emptyArrays && Array.isArray(value) && !value.length) { return; } // Exclude empty strings. if (emptyStrings && value === '') { return; } // Exclude null values. if (nullValues && value === null) { return; } // Exclude undefined values. if (undefinedValues && value === undefined) { return; } // Append when recursing arrays. if (Array.isArray(result)) { return result.push(value); } result[key] = value; }); }
javascript
function cleanDeep(object) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$emptyArrays = _ref.emptyArrays, emptyArrays = _ref$emptyArrays === undefined ? true : _ref$emptyArrays, _ref$emptyObjects = _ref.emptyObjects, emptyObjects = _ref$emptyObjects === undefined ? true : _ref$emptyObjects, _ref$emptyStrings = _ref.emptyStrings, emptyStrings = _ref$emptyStrings === undefined ? true : _ref$emptyStrings, _ref$nullValues = _ref.nullValues, nullValues = _ref$nullValues === undefined ? true : _ref$nullValues, _ref$undefinedValues = _ref.undefinedValues, undefinedValues = _ref$undefinedValues === undefined ? true : _ref$undefinedValues; return (0, _lodash6.default)(object, function (result, value, key) { // Recurse into arrays and objects. if (Array.isArray(value) || (0, _lodash4.default)(value)) { value = cleanDeep(value, { emptyArrays: emptyArrays, emptyObjects: emptyObjects, emptyStrings: emptyStrings, nullValues: nullValues, undefinedValues: undefinedValues }); } // Exclude empty objects. if (emptyObjects && (0, _lodash4.default)(value) && (0, _lodash2.default)(value)) { return; } // Exclude empty arrays. if (emptyArrays && Array.isArray(value) && !value.length) { return; } // Exclude empty strings. if (emptyStrings && value === '') { return; } // Exclude null values. if (nullValues && value === null) { return; } // Exclude undefined values. if (undefinedValues && value === undefined) { return; } // Append when recursing arrays. if (Array.isArray(result)) { return result.push(value); } result[key] = value; }); }
[ "function", "cleanDeep", "(", "object", ")", "{", "var", "_ref", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "{", "}", ",", "_ref$emptyArrays", "=", "_ref", ".", "emptyArrays", ",", "emptyArrays", "=", "_ref$emptyArrays", "===", "undefined", "?", "true", ":", "_ref$emptyArrays", ",", "_ref$emptyObjects", "=", "_ref", ".", "emptyObjects", ",", "emptyObjects", "=", "_ref$emptyObjects", "===", "undefined", "?", "true", ":", "_ref$emptyObjects", ",", "_ref$emptyStrings", "=", "_ref", ".", "emptyStrings", ",", "emptyStrings", "=", "_ref$emptyStrings", "===", "undefined", "?", "true", ":", "_ref$emptyStrings", ",", "_ref$nullValues", "=", "_ref", ".", "nullValues", ",", "nullValues", "=", "_ref$nullValues", "===", "undefined", "?", "true", ":", "_ref$nullValues", ",", "_ref$undefinedValues", "=", "_ref", ".", "undefinedValues", ",", "undefinedValues", "=", "_ref$undefinedValues", "===", "undefined", "?", "true", ":", "_ref$undefinedValues", ";", "return", "(", "0", ",", "_lodash6", ".", "default", ")", "(", "object", ",", "function", "(", "result", ",", "value", ",", "key", ")", "{", "// Recurse into arrays and objects.", "if", "(", "Array", ".", "isArray", "(", "value", ")", "||", "(", "0", ",", "_lodash4", ".", "default", ")", "(", "value", ")", ")", "{", "value", "=", "cleanDeep", "(", "value", ",", "{", "emptyArrays", ":", "emptyArrays", ",", "emptyObjects", ":", "emptyObjects", ",", "emptyStrings", ":", "emptyStrings", ",", "nullValues", ":", "nullValues", ",", "undefinedValues", ":", "undefinedValues", "}", ")", ";", "}", "// Exclude empty objects.", "if", "(", "emptyObjects", "&&", "(", "0", ",", "_lodash4", ".", "default", ")", "(", "value", ")", "&&", "(", "0", ",", "_lodash2", ".", "default", ")", "(", "value", ")", ")", "{", "return", ";", "}", "// Exclude empty arrays.", "if", "(", "emptyArrays", "&&", "Array", ".", "isArray", "(", "value", ")", "&&", "!", "value", ".", "length", ")", "{", "return", ";", "}", "// Exclude empty strings.", "if", "(", "emptyStrings", "&&", "value", "===", "''", ")", "{", "return", ";", "}", "// Exclude null values.", "if", "(", "nullValues", "&&", "value", "===", "null", ")", "{", "return", ";", "}", "// Exclude undefined values.", "if", "(", "undefinedValues", "&&", "value", "===", "undefined", ")", "{", "return", ";", "}", "// Append when recursing arrays.", "if", "(", "Array", ".", "isArray", "(", "result", ")", ")", "{", "return", "result", ".", "push", "(", "value", ")", ";", "}", "result", "[", "key", "]", "=", "value", ";", "}", ")", ";", "}" ]
Export `cleanDeep` function.
[ "Export", "cleanDeep", "function", "." ]
8cb741ff30613440ea24533308cbb29164272545
https://github.com/nunofgs/clean-deep/blob/8cb741ff30613440ea24533308cbb29164272545/dist/index.js#L26-L77
21,119
ricmoo/scrypt-js
scrypt.js
incrementCounter
function incrementCounter() { for (var i = innerLen-1; i >= innerLen-4; i--) { inner[i]++; if (inner[i] <= 0xff) return; inner[i] = 0; } }
javascript
function incrementCounter() { for (var i = innerLen-1; i >= innerLen-4; i--) { inner[i]++; if (inner[i] <= 0xff) return; inner[i] = 0; } }
[ "function", "incrementCounter", "(", ")", "{", "for", "(", "var", "i", "=", "innerLen", "-", "1", ";", "i", ">=", "innerLen", "-", "4", ";", "i", "--", ")", "{", "inner", "[", "i", "]", "++", ";", "if", "(", "inner", "[", "i", "]", "<=", "0xff", ")", "return", ";", "inner", "[", "i", "]", "=", "0", ";", "}", "}" ]
increments counter inside inner
[ "increments", "counter", "inside", "inner" ]
0eb70873ddf3d24e34b53e0d9a99a0cef06a79c0
https://github.com/ricmoo/scrypt-js/blob/0eb70873ddf3d24e34b53e0d9a99a0cef06a79c0/scrypt.js#L136-L142
21,120
ricmoo/scrypt-js
scrypt.js
blockxor
function blockxor(S, Si, D, len) { for (var i = 0; i < len; i++) { D[i] ^= S[Si + i] } }
javascript
function blockxor(S, Si, D, len) { for (var i = 0; i < len; i++) { D[i] ^= S[Si + i] } }
[ "function", "blockxor", "(", "S", ",", "Si", ",", "D", ",", "len", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "D", "[", "i", "]", "^=", "S", "[", "Si", "+", "i", "]", "}", "}" ]
naive approach... going back to loop unrolling may yield additional performance
[ "naive", "approach", "...", "going", "back", "to", "loop", "unrolling", "may", "yield", "additional", "performance" ]
0eb70873ddf3d24e34b53e0d9a99a0cef06a79c0
https://github.com/ricmoo/scrypt-js/blob/0eb70873ddf3d24e34b53e0d9a99a0cef06a79c0/scrypt.js#L227-L231
21,121
ricmoo/scrypt-js
scrypt.js
function() { if (stop) { return callback(new Error('cancelled'), currentOp / totalOps); } switch (state) { case 0: // for (var i = 0; i < p; i++)... Bi = i0 * 32 * r; arraycopy(B, Bi, XY, 0, Yi); // ROMix - 1 state = 1; // Move to ROMix 2 i1 = 0; // Fall through case 1: // Run up to 1000 steps of the first inner smix loop var steps = N - i1; if (steps > limit) { steps = limit; } for (var i = 0; i < steps; i++) { // ROMix - 2 arraycopy(XY, 0, V, (i1 + i) * Yi, Yi) // ROMix - 3 blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 4 } // for (var i = 0; i < N; i++) i1 += steps; currentOp += steps; // Call the callback with the progress (optionally stopping us) var percent10 = parseInt(1000 * currentOp / totalOps); if (percent10 !== lastPercent10) { stop = callback(null, currentOp / totalOps); if (stop) { break; } lastPercent10 = percent10; } if (i1 < N) { break; } i1 = 0; // Move to ROMix 6 state = 2; // Fall through case 2: // Run up to 1000 steps of the second inner smix loop var steps = N - i1; if (steps > limit) { steps = limit; } for (var i = 0; i < steps; i++) { // ROMix - 6 var offset = (2 * r - 1) * 16; // ROMix - 7 var j = XY[offset] & (N - 1); blockxor(V, j * Yi, XY, Yi); // ROMix - 8 (inner) blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 9 (outer) } // for (var i = 0; i < N; i++)... i1 += steps; currentOp += steps; // Call the callback with the progress (optionally stopping us) var percent10 = parseInt(1000 * currentOp / totalOps); if (percent10 !== lastPercent10) { stop = callback(null, currentOp / totalOps); if (stop) { break; } lastPercent10 = percent10; } if (i1 < N) { break; } arraycopy(XY, 0, B, Bi, Yi); // ROMix - 10 // for (var i = 0; i < p; i++)... i0++; if (i0 < p) { state = 0; break; } b = []; for (var i = 0; i < B.length; i++) { b.push((B[i] >> 0) & 0xff); b.push((B[i] >> 8) & 0xff); b.push((B[i] >> 16) & 0xff); b.push((B[i] >> 24) & 0xff); } var derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen); // Done; don't break (which would reschedule) return callback(null, 1.0, derivedKey); } // Schedule the next steps nextTick(incrementalSMix); }
javascript
function() { if (stop) { return callback(new Error('cancelled'), currentOp / totalOps); } switch (state) { case 0: // for (var i = 0; i < p; i++)... Bi = i0 * 32 * r; arraycopy(B, Bi, XY, 0, Yi); // ROMix - 1 state = 1; // Move to ROMix 2 i1 = 0; // Fall through case 1: // Run up to 1000 steps of the first inner smix loop var steps = N - i1; if (steps > limit) { steps = limit; } for (var i = 0; i < steps; i++) { // ROMix - 2 arraycopy(XY, 0, V, (i1 + i) * Yi, Yi) // ROMix - 3 blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 4 } // for (var i = 0; i < N; i++) i1 += steps; currentOp += steps; // Call the callback with the progress (optionally stopping us) var percent10 = parseInt(1000 * currentOp / totalOps); if (percent10 !== lastPercent10) { stop = callback(null, currentOp / totalOps); if (stop) { break; } lastPercent10 = percent10; } if (i1 < N) { break; } i1 = 0; // Move to ROMix 6 state = 2; // Fall through case 2: // Run up to 1000 steps of the second inner smix loop var steps = N - i1; if (steps > limit) { steps = limit; } for (var i = 0; i < steps; i++) { // ROMix - 6 var offset = (2 * r - 1) * 16; // ROMix - 7 var j = XY[offset] & (N - 1); blockxor(V, j * Yi, XY, Yi); // ROMix - 8 (inner) blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 9 (outer) } // for (var i = 0; i < N; i++)... i1 += steps; currentOp += steps; // Call the callback with the progress (optionally stopping us) var percent10 = parseInt(1000 * currentOp / totalOps); if (percent10 !== lastPercent10) { stop = callback(null, currentOp / totalOps); if (stop) { break; } lastPercent10 = percent10; } if (i1 < N) { break; } arraycopy(XY, 0, B, Bi, Yi); // ROMix - 10 // for (var i = 0; i < p; i++)... i0++; if (i0 < p) { state = 0; break; } b = []; for (var i = 0; i < B.length; i++) { b.push((B[i] >> 0) & 0xff); b.push((B[i] >> 8) & 0xff); b.push((B[i] >> 16) & 0xff); b.push((B[i] >> 24) & 0xff); } var derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen); // Done; don't break (which would reschedule) return callback(null, 1.0, derivedKey); } // Schedule the next steps nextTick(incrementalSMix); }
[ "function", "(", ")", "{", "if", "(", "stop", ")", "{", "return", "callback", "(", "new", "Error", "(", "'cancelled'", ")", ",", "currentOp", "/", "totalOps", ")", ";", "}", "switch", "(", "state", ")", "{", "case", "0", ":", "// for (var i = 0; i < p; i++)...", "Bi", "=", "i0", "*", "32", "*", "r", ";", "arraycopy", "(", "B", ",", "Bi", ",", "XY", ",", "0", ",", "Yi", ")", ";", "// ROMix - 1", "state", "=", "1", ";", "// Move to ROMix 2", "i1", "=", "0", ";", "// Fall through", "case", "1", ":", "// Run up to 1000 steps of the first inner smix loop", "var", "steps", "=", "N", "-", "i1", ";", "if", "(", "steps", ">", "limit", ")", "{", "steps", "=", "limit", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "steps", ";", "i", "++", ")", "{", "// ROMix - 2", "arraycopy", "(", "XY", ",", "0", ",", "V", ",", "(", "i1", "+", "i", ")", "*", "Yi", ",", "Yi", ")", "// ROMix - 3", "blockmix_salsa8", "(", "XY", ",", "Yi", ",", "r", ",", "x", ",", "_X", ")", ";", "// ROMix - 4", "}", "// for (var i = 0; i < N; i++)", "i1", "+=", "steps", ";", "currentOp", "+=", "steps", ";", "// Call the callback with the progress (optionally stopping us)", "var", "percent10", "=", "parseInt", "(", "1000", "*", "currentOp", "/", "totalOps", ")", ";", "if", "(", "percent10", "!==", "lastPercent10", ")", "{", "stop", "=", "callback", "(", "null", ",", "currentOp", "/", "totalOps", ")", ";", "if", "(", "stop", ")", "{", "break", ";", "}", "lastPercent10", "=", "percent10", ";", "}", "if", "(", "i1", "<", "N", ")", "{", "break", ";", "}", "i1", "=", "0", ";", "// Move to ROMix 6", "state", "=", "2", ";", "// Fall through", "case", "2", ":", "// Run up to 1000 steps of the second inner smix loop", "var", "steps", "=", "N", "-", "i1", ";", "if", "(", "steps", ">", "limit", ")", "{", "steps", "=", "limit", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "steps", ";", "i", "++", ")", "{", "// ROMix - 6", "var", "offset", "=", "(", "2", "*", "r", "-", "1", ")", "*", "16", ";", "// ROMix - 7", "var", "j", "=", "XY", "[", "offset", "]", "&", "(", "N", "-", "1", ")", ";", "blockxor", "(", "V", ",", "j", "*", "Yi", ",", "XY", ",", "Yi", ")", ";", "// ROMix - 8 (inner)", "blockmix_salsa8", "(", "XY", ",", "Yi", ",", "r", ",", "x", ",", "_X", ")", ";", "// ROMix - 9 (outer)", "}", "// for (var i = 0; i < N; i++)...", "i1", "+=", "steps", ";", "currentOp", "+=", "steps", ";", "// Call the callback with the progress (optionally stopping us)", "var", "percent10", "=", "parseInt", "(", "1000", "*", "currentOp", "/", "totalOps", ")", ";", "if", "(", "percent10", "!==", "lastPercent10", ")", "{", "stop", "=", "callback", "(", "null", ",", "currentOp", "/", "totalOps", ")", ";", "if", "(", "stop", ")", "{", "break", ";", "}", "lastPercent10", "=", "percent10", ";", "}", "if", "(", "i1", "<", "N", ")", "{", "break", ";", "}", "arraycopy", "(", "XY", ",", "0", ",", "B", ",", "Bi", ",", "Yi", ")", ";", "// ROMix - 10", "// for (var i = 0; i < p; i++)...", "i0", "++", ";", "if", "(", "i0", "<", "p", ")", "{", "state", "=", "0", ";", "break", ";", "}", "b", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "B", ".", "length", ";", "i", "++", ")", "{", "b", ".", "push", "(", "(", "B", "[", "i", "]", ">>", "0", ")", "&", "0xff", ")", ";", "b", ".", "push", "(", "(", "B", "[", "i", "]", ">>", "8", ")", "&", "0xff", ")", ";", "b", ".", "push", "(", "(", "B", "[", "i", "]", ">>", "16", ")", "&", "0xff", ")", ";", "b", ".", "push", "(", "(", "B", "[", "i", "]", ">>", "24", ")", "&", "0xff", ")", ";", "}", "var", "derivedKey", "=", "PBKDF2_HMAC_SHA256_OneIter", "(", "password", ",", "b", ",", "dkLen", ")", ";", "// Done; don't break (which would reschedule)", "return", "callback", "(", "null", ",", "1.0", ",", "derivedKey", ")", ";", "}", "// Schedule the next steps", "nextTick", "(", "incrementalSMix", ")", ";", "}" ]
This is really all I changed; making scryptsy a state machine so we occasionally stop and give other evnts on the evnt loop a chance to run. ~RicMoo
[ "This", "is", "really", "all", "I", "changed", ";", "making", "scryptsy", "a", "state", "machine", "so", "we", "occasionally", "stop", "and", "give", "other", "evnts", "on", "the", "evnt", "loop", "a", "chance", "to", "run", ".", "~RicMoo" ]
0eb70873ddf3d24e34b53e0d9a99a0cef06a79c0
https://github.com/ricmoo/scrypt-js/blob/0eb70873ddf3d24e34b53e0d9a99a0cef06a79c0/scrypt.js#L326-L427
21,122
jshttp/compressible
index.js
compressible
function compressible (type) { if (!type || typeof type !== 'string') { return false } // strip parameters var match = EXTRACT_TYPE_REGEXP.exec(type) var mime = match && match[1].toLowerCase() var data = db[mime] // return database information if (data && data.compressible !== undefined) { return data.compressible } // fallback to regexp or unknown return COMPRESSIBLE_TYPE_REGEXP.test(mime) || undefined }
javascript
function compressible (type) { if (!type || typeof type !== 'string') { return false } // strip parameters var match = EXTRACT_TYPE_REGEXP.exec(type) var mime = match && match[1].toLowerCase() var data = db[mime] // return database information if (data && data.compressible !== undefined) { return data.compressible } // fallback to regexp or unknown return COMPRESSIBLE_TYPE_REGEXP.test(mime) || undefined }
[ "function", "compressible", "(", "type", ")", "{", "if", "(", "!", "type", "||", "typeof", "type", "!==", "'string'", ")", "{", "return", "false", "}", "// strip parameters", "var", "match", "=", "EXTRACT_TYPE_REGEXP", ".", "exec", "(", "type", ")", "var", "mime", "=", "match", "&&", "match", "[", "1", "]", ".", "toLowerCase", "(", ")", "var", "data", "=", "db", "[", "mime", "]", "// return database information", "if", "(", "data", "&&", "data", ".", "compressible", "!==", "undefined", ")", "{", "return", "data", ".", "compressible", "}", "// fallback to regexp or unknown", "return", "COMPRESSIBLE_TYPE_REGEXP", ".", "test", "(", "mime", ")", "||", "undefined", "}" ]
Checks if a type is compressible. @param {string} type @return {Boolean} compressible @public
[ "Checks", "if", "a", "type", "is", "compressible", "." ]
57985690741c2670fb5c171bdefb07114ce1a63f
https://github.com/jshttp/compressible/blob/57985690741c2670fb5c171bdefb07114ce1a63f/index.js#L41-L58
21,123
livechat/sample-apps
lc3-bot-example/public/client.js
function(dream) { const newListItem = document.createElement('li'); newListItem.innerHTML = dream; dreamsList.appendChild(newListItem); }
javascript
function(dream) { const newListItem = document.createElement('li'); newListItem.innerHTML = dream; dreamsList.appendChild(newListItem); }
[ "function", "(", "dream", ")", "{", "const", "newListItem", "=", "document", ".", "createElement", "(", "'li'", ")", ";", "newListItem", ".", "innerHTML", "=", "dream", ";", "dreamsList", ".", "appendChild", "(", "newListItem", ")", ";", "}" ]
a helper function that creates a list item for a given dream
[ "a", "helper", "function", "that", "creates", "a", "list", "item", "for", "a", "given", "dream" ]
69c8fbeecb7df6b287ec300da2b950b486c2baf5
https://github.com/livechat/sample-apps/blob/69c8fbeecb7df6b287ec300da2b950b486c2baf5/lc3-bot-example/public/client.js#L19-L23
21,124
muaz-khan/FileBufferReader
demo/PeerUI.js
onDragOver
function onDragOver() { mainContainer.style.border = '7px solid #98a90f'; mainContainer.style.background = '#ffff13'; mainContainer.style.borderRadisu = '16px'; }
javascript
function onDragOver() { mainContainer.style.border = '7px solid #98a90f'; mainContainer.style.background = '#ffff13'; mainContainer.style.borderRadisu = '16px'; }
[ "function", "onDragOver", "(", ")", "{", "mainContainer", ".", "style", ".", "border", "=", "'7px solid #98a90f'", ";", "mainContainer", ".", "style", ".", "background", "=", "'#ffff13'", ";", "mainContainer", ".", "style", ".", "borderRadisu", "=", "'16px'", ";", "}" ]
drag-drop support
[ "drag", "-", "drop", "support" ]
866987df9a6c5c6924314a01d1aa53f0efc4e9c4
https://github.com/muaz-khan/FileBufferReader/blob/866987df9a6c5c6924314a01d1aa53f0efc4e9c4/demo/PeerUI.js#L584-L588
21,125
jonathanong/ee-first
index.js
first
function first (stuff, done) { if (!Array.isArray(stuff)) { throw new TypeError('arg must be an array of [ee, events...] arrays') } var cleanups = [] for (var i = 0; i < stuff.length; i++) { var arr = stuff[i] if (!Array.isArray(arr) || arr.length < 2) { throw new TypeError('each array member must be [ee, events...]') } var ee = arr[0] for (var j = 1; j < arr.length; j++) { var event = arr[j] var fn = listener(event, callback) // listen to the event ee.on(event, fn) // push this listener to the list of cleanups cleanups.push({ ee: ee, event: event, fn: fn }) } } function callback () { cleanup() done.apply(null, arguments) } function cleanup () { var x for (var i = 0; i < cleanups.length; i++) { x = cleanups[i] x.ee.removeListener(x.event, x.fn) } } function thunk (fn) { done = fn } thunk.cancel = cleanup return thunk }
javascript
function first (stuff, done) { if (!Array.isArray(stuff)) { throw new TypeError('arg must be an array of [ee, events...] arrays') } var cleanups = [] for (var i = 0; i < stuff.length; i++) { var arr = stuff[i] if (!Array.isArray(arr) || arr.length < 2) { throw new TypeError('each array member must be [ee, events...]') } var ee = arr[0] for (var j = 1; j < arr.length; j++) { var event = arr[j] var fn = listener(event, callback) // listen to the event ee.on(event, fn) // push this listener to the list of cleanups cleanups.push({ ee: ee, event: event, fn: fn }) } } function callback () { cleanup() done.apply(null, arguments) } function cleanup () { var x for (var i = 0; i < cleanups.length; i++) { x = cleanups[i] x.ee.removeListener(x.event, x.fn) } } function thunk (fn) { done = fn } thunk.cancel = cleanup return thunk }
[ "function", "first", "(", "stuff", ",", "done", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "stuff", ")", ")", "{", "throw", "new", "TypeError", "(", "'arg must be an array of [ee, events...] arrays'", ")", "}", "var", "cleanups", "=", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "stuff", ".", "length", ";", "i", "++", ")", "{", "var", "arr", "=", "stuff", "[", "i", "]", "if", "(", "!", "Array", ".", "isArray", "(", "arr", ")", "||", "arr", ".", "length", "<", "2", ")", "{", "throw", "new", "TypeError", "(", "'each array member must be [ee, events...]'", ")", "}", "var", "ee", "=", "arr", "[", "0", "]", "for", "(", "var", "j", "=", "1", ";", "j", "<", "arr", ".", "length", ";", "j", "++", ")", "{", "var", "event", "=", "arr", "[", "j", "]", "var", "fn", "=", "listener", "(", "event", ",", "callback", ")", "// listen to the event", "ee", ".", "on", "(", "event", ",", "fn", ")", "// push this listener to the list of cleanups", "cleanups", ".", "push", "(", "{", "ee", ":", "ee", ",", "event", ":", "event", ",", "fn", ":", "fn", "}", ")", "}", "}", "function", "callback", "(", ")", "{", "cleanup", "(", ")", "done", ".", "apply", "(", "null", ",", "arguments", ")", "}", "function", "cleanup", "(", ")", "{", "var", "x", "for", "(", "var", "i", "=", "0", ";", "i", "<", "cleanups", ".", "length", ";", "i", "++", ")", "{", "x", "=", "cleanups", "[", "i", "]", "x", ".", "ee", ".", "removeListener", "(", "x", ".", "event", ",", "x", ".", "fn", ")", "}", "}", "function", "thunk", "(", "fn", ")", "{", "done", "=", "fn", "}", "thunk", ".", "cancel", "=", "cleanup", "return", "thunk", "}" ]
Get the first event in a set of event emitters and event pairs. @param {array} stuff @param {function} done @public
[ "Get", "the", "first", "event", "in", "a", "set", "of", "event", "emitters", "and", "event", "pairs", "." ]
661cfe51c4ad65b968ca909b70772a007a098764
https://github.com/jonathanong/ee-first/blob/661cfe51c4ad65b968ca909b70772a007a098764/index.js#L24-L75
21,126
jonathanong/ee-first
index.js
listener
function listener (event, done) { return function onevent (arg1) { var args = new Array(arguments.length) var ee = this var err = event === 'error' ? arg1 : null // copy args to prevent arguments escaping scope for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } done(err, ee, event, args) } }
javascript
function listener (event, done) { return function onevent (arg1) { var args = new Array(arguments.length) var ee = this var err = event === 'error' ? arg1 : null // copy args to prevent arguments escaping scope for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } done(err, ee, event, args) } }
[ "function", "listener", "(", "event", ",", "done", ")", "{", "return", "function", "onevent", "(", "arg1", ")", "{", "var", "args", "=", "new", "Array", "(", "arguments", ".", "length", ")", "var", "ee", "=", "this", "var", "err", "=", "event", "===", "'error'", "?", "arg1", ":", "null", "// copy args to prevent arguments escaping scope", "for", "(", "var", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "args", "[", "i", "]", "=", "arguments", "[", "i", "]", "}", "done", "(", "err", ",", "ee", ",", "event", ",", "args", ")", "}", "}" ]
Create the event listener. @private
[ "Create", "the", "event", "listener", "." ]
661cfe51c4ad65b968ca909b70772a007a098764
https://github.com/jonathanong/ee-first/blob/661cfe51c4ad65b968ca909b70772a007a098764/index.js#L82-L97
21,127
emailjs/emailjs-mime-builder
dist/utils.js
encodeAddressName
function encodeAddressName(name) { if (!/^[\w ']*$/.test(name)) { if (/^[\x20-\x7e]*$/.test(name)) { return '"' + name.replace(/([\\"])/g, '\\$1') + '"'; } else { return (0, _emailjsMimeCodec.mimeWordEncode)(name, 'Q'); } } return name; }
javascript
function encodeAddressName(name) { if (!/^[\w ']*$/.test(name)) { if (/^[\x20-\x7e]*$/.test(name)) { return '"' + name.replace(/([\\"])/g, '\\$1') + '"'; } else { return (0, _emailjsMimeCodec.mimeWordEncode)(name, 'Q'); } } return name; }
[ "function", "encodeAddressName", "(", "name", ")", "{", "if", "(", "!", "/", "^[\\w ']*$", "/", ".", "test", "(", "name", ")", ")", "{", "if", "(", "/", "^[\\x20-\\x7e]*$", "/", ".", "test", "(", "name", ")", ")", "{", "return", "'\"'", "+", "name", ".", "replace", "(", "/", "([\\\\\"])", "/", "g", ",", "'\\\\$1'", ")", "+", "'\"'", ";", "}", "else", "{", "return", "(", "0", ",", "_emailjsMimeCodec", ".", "mimeWordEncode", ")", "(", "name", ",", "'Q'", ")", ";", "}", "}", "return", "name", ";", "}" ]
If needed, mime encodes the name part @param {String} name Name part of an address @returns {String} Mime word encoded string if needed /* eslint-disable node/no-deprecated-api /* eslint-disable no-control-regex
[ "If", "needed", "mime", "encodes", "the", "name", "part" ]
7090355f1c82c32570640a322d02bacce2a94a2c
https://github.com/emailjs/emailjs-mime-builder/blob/7090355f1c82c32570640a322d02bacce2a94a2c/dist/utils.js#L36-L45
21,128
emailjs/emailjs-mime-builder
dist/utils.js
convertAddresses
function convertAddresses() { var addresses = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var uniqueList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var values = [];[].concat(addresses).forEach(function (address) { if (address.address) { address.address = address.address.replace(/^.*?(?=@)/, function (user) { return (0, _emailjsMimeCodec.mimeWordsEncode)(user, 'Q'); }).replace(/@.+$/, function (domain) { return '@' + (0, _punycode.toASCII)(domain.substr(1)); }); if (!address.name) { values.push(address.address); } else if (address.name) { values.push(encodeAddressName(address.name) + ' <' + address.address + '>'); } if (uniqueList.indexOf(address.address) < 0) { uniqueList.push(address.address); } } else if (address.group) { values.push(encodeAddressName(address.name) + ':' + (address.group.length ? convertAddresses(address.group, uniqueList) : '').trim() + ';'); } }); return values.join(', '); }
javascript
function convertAddresses() { var addresses = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var uniqueList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var values = [];[].concat(addresses).forEach(function (address) { if (address.address) { address.address = address.address.replace(/^.*?(?=@)/, function (user) { return (0, _emailjsMimeCodec.mimeWordsEncode)(user, 'Q'); }).replace(/@.+$/, function (domain) { return '@' + (0, _punycode.toASCII)(domain.substr(1)); }); if (!address.name) { values.push(address.address); } else if (address.name) { values.push(encodeAddressName(address.name) + ' <' + address.address + '>'); } if (uniqueList.indexOf(address.address) < 0) { uniqueList.push(address.address); } } else if (address.group) { values.push(encodeAddressName(address.name) + ':' + (address.group.length ? convertAddresses(address.group, uniqueList) : '').trim() + ';'); } }); return values.join(', '); }
[ "function", "convertAddresses", "(", ")", "{", "var", "addresses", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "[", "]", ";", "var", "uniqueList", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "[", "]", ";", "var", "values", "=", "[", "]", ";", "[", "]", ".", "concat", "(", "addresses", ")", ".", "forEach", "(", "function", "(", "address", ")", "{", "if", "(", "address", ".", "address", ")", "{", "address", ".", "address", "=", "address", ".", "address", ".", "replace", "(", "/", "^.*?(?=@)", "/", ",", "function", "(", "user", ")", "{", "return", "(", "0", ",", "_emailjsMimeCodec", ".", "mimeWordsEncode", ")", "(", "user", ",", "'Q'", ")", ";", "}", ")", ".", "replace", "(", "/", "@.+$", "/", ",", "function", "(", "domain", ")", "{", "return", "'@'", "+", "(", "0", ",", "_punycode", ".", "toASCII", ")", "(", "domain", ".", "substr", "(", "1", ")", ")", ";", "}", ")", ";", "if", "(", "!", "address", ".", "name", ")", "{", "values", ".", "push", "(", "address", ".", "address", ")", ";", "}", "else", "if", "(", "address", ".", "name", ")", "{", "values", ".", "push", "(", "encodeAddressName", "(", "address", ".", "name", ")", "+", "' <'", "+", "address", ".", "address", "+", "'>'", ")", ";", "}", "if", "(", "uniqueList", ".", "indexOf", "(", "address", ".", "address", ")", "<", "0", ")", "{", "uniqueList", ".", "push", "(", "address", ".", "address", ")", ";", "}", "}", "else", "if", "(", "address", ".", "group", ")", "{", "values", ".", "push", "(", "encodeAddressName", "(", "address", ".", "name", ")", "+", "':'", "+", "(", "address", ".", "group", ".", "length", "?", "convertAddresses", "(", "address", ".", "group", ",", "uniqueList", ")", ":", "''", ")", ".", "trim", "(", ")", "+", "';'", ")", ";", "}", "}", ")", ";", "return", "values", ".", "join", "(", "', '", ")", ";", "}" ]
Rebuilds address object using punycode and other adjustments @param {Array} addresses An array of address objects @param {Array} [uniqueList] An array to be populated with addresses @return {String} address string
[ "Rebuilds", "address", "object", "using", "punycode", "and", "other", "adjustments" ]
7090355f1c82c32570640a322d02bacce2a94a2c
https://github.com/emailjs/emailjs-mime-builder/blob/7090355f1c82c32570640a322d02bacce2a94a2c/dist/utils.js#L64-L91
21,129
emailjs/emailjs-mime-builder
dist/utils.js
encodeHeaderValue
function encodeHeaderValue(key) { var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; key = normalizeHeaderKey(key); switch (key) { case 'From': case 'Sender': case 'To': case 'Cc': case 'Bcc': case 'Reply-To': return convertAddresses(parseAddresses(value)); case 'Message-Id': case 'In-Reply-To': case 'Content-Id': value = value.replace(/\r?\n|\r/g, ' '); if (value.charAt(0) !== '<') { value = '<' + value; } if (value.charAt(value.length - 1) !== '>') { value = value + '>'; } return value; case 'References': value = [].concat.apply([], [].concat(value).map(function () { var elm = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; return elm.replace(/\r?\n|\r/g, ' ').trim().replace(/<[^>]*>/g, function (str) { return str.replace(/\s/g, ''); }).split(/\s+/); })).map(function (elm) { if (elm.charAt(0) !== '<') { elm = '<' + elm; } if (elm.charAt(elm.length - 1) !== '>') { elm = elm + '>'; } return elm; }); return value.join(' ').trim(); default: return (0, _emailjsMimeCodec.mimeWordsEncode)((value || '').toString().replace(/\r?\n|\r/g, ' '), 'B'); } }
javascript
function encodeHeaderValue(key) { var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; key = normalizeHeaderKey(key); switch (key) { case 'From': case 'Sender': case 'To': case 'Cc': case 'Bcc': case 'Reply-To': return convertAddresses(parseAddresses(value)); case 'Message-Id': case 'In-Reply-To': case 'Content-Id': value = value.replace(/\r?\n|\r/g, ' '); if (value.charAt(0) !== '<') { value = '<' + value; } if (value.charAt(value.length - 1) !== '>') { value = value + '>'; } return value; case 'References': value = [].concat.apply([], [].concat(value).map(function () { var elm = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; return elm.replace(/\r?\n|\r/g, ' ').trim().replace(/<[^>]*>/g, function (str) { return str.replace(/\s/g, ''); }).split(/\s+/); })).map(function (elm) { if (elm.charAt(0) !== '<') { elm = '<' + elm; } if (elm.charAt(elm.length - 1) !== '>') { elm = elm + '>'; } return elm; }); return value.join(' ').trim(); default: return (0, _emailjsMimeCodec.mimeWordsEncode)((value || '').toString().replace(/\r?\n|\r/g, ' '), 'B'); } }
[ "function", "encodeHeaderValue", "(", "key", ")", "{", "var", "value", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "''", ";", "key", "=", "normalizeHeaderKey", "(", "key", ")", ";", "switch", "(", "key", ")", "{", "case", "'From'", ":", "case", "'Sender'", ":", "case", "'To'", ":", "case", "'Cc'", ":", "case", "'Bcc'", ":", "case", "'Reply-To'", ":", "return", "convertAddresses", "(", "parseAddresses", "(", "value", ")", ")", ";", "case", "'Message-Id'", ":", "case", "'In-Reply-To'", ":", "case", "'Content-Id'", ":", "value", "=", "value", ".", "replace", "(", "/", "\\r?\\n|\\r", "/", "g", ",", "' '", ")", ";", "if", "(", "value", ".", "charAt", "(", "0", ")", "!==", "'<'", ")", "{", "value", "=", "'<'", "+", "value", ";", "}", "if", "(", "value", ".", "charAt", "(", "value", ".", "length", "-", "1", ")", "!==", "'>'", ")", "{", "value", "=", "value", "+", "'>'", ";", "}", "return", "value", ";", "case", "'References'", ":", "value", "=", "[", "]", ".", "concat", ".", "apply", "(", "[", "]", ",", "[", "]", ".", "concat", "(", "value", ")", ".", "map", "(", "function", "(", ")", "{", "var", "elm", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "''", ";", "return", "elm", ".", "replace", "(", "/", "\\r?\\n|\\r", "/", "g", ",", "' '", ")", ".", "trim", "(", ")", ".", "replace", "(", "/", "<[^>]*>", "/", "g", ",", "function", "(", "str", ")", "{", "return", "str", ".", "replace", "(", "/", "\\s", "/", "g", ",", "''", ")", ";", "}", ")", ".", "split", "(", "/", "\\s+", "/", ")", ";", "}", ")", ")", ".", "map", "(", "function", "(", "elm", ")", "{", "if", "(", "elm", ".", "charAt", "(", "0", ")", "!==", "'<'", ")", "{", "elm", "=", "'<'", "+", "elm", ";", "}", "if", "(", "elm", ".", "charAt", "(", "elm", ".", "length", "-", "1", ")", "!==", "'>'", ")", "{", "elm", "=", "elm", "+", "'>'", ";", "}", "return", "elm", ";", "}", ")", ";", "return", "value", ".", "join", "(", "' '", ")", ".", "trim", "(", ")", ";", "default", ":", "return", "(", "0", ",", "_emailjsMimeCodec", ".", "mimeWordsEncode", ")", "(", "(", "value", "||", "''", ")", ".", "toString", "(", ")", ".", "replace", "(", "/", "\\r?\\n|\\r", "/", "g", ",", "' '", ")", ",", "'B'", ")", ";", "}", "}" ]
Encodes a header value for use in the generated rfc2822 email. @param {String} key Header key @param {String} value Header value
[ "Encodes", "a", "header", "value", "for", "use", "in", "the", "generated", "rfc2822", "email", "." ]
7090355f1c82c32570640a322d02bacce2a94a2c
https://github.com/emailjs/emailjs-mime-builder/blob/7090355f1c82c32570640a322d02bacce2a94a2c/dist/utils.js#L117-L166
21,130
emailjs/emailjs-mime-builder
dist/utils.js
normalizeHeaderKey
function normalizeHeaderKey() { var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; return key.replace(/\r?\n|\r/g, ' ') // no newlines in keys .trim().toLowerCase().replace(/^MIME\b|^[a-z]|-[a-z]/ig, function (c) { return c.toUpperCase(); }); // use uppercase words, except MIME }
javascript
function normalizeHeaderKey() { var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; return key.replace(/\r?\n|\r/g, ' ') // no newlines in keys .trim().toLowerCase().replace(/^MIME\b|^[a-z]|-[a-z]/ig, function (c) { return c.toUpperCase(); }); // use uppercase words, except MIME }
[ "function", "normalizeHeaderKey", "(", ")", "{", "var", "key", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "''", ";", "return", "key", ".", "replace", "(", "/", "\\r?\\n|\\r", "/", "g", ",", "' '", ")", "// no newlines in keys", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "^MIME\\b|^[a-z]|-[a-z]", "/", "ig", ",", "function", "(", "c", ")", "{", "return", "c", ".", "toUpperCase", "(", ")", ";", "}", ")", ";", "// use uppercase words, except MIME", "}" ]
Normalizes a header key, uses Camel-Case form, except for uppercase MIME- @param {String} key Key to be normalized @return {String} key in Camel-Case form
[ "Normalizes", "a", "header", "key", "uses", "Camel", "-", "Case", "form", "except", "for", "uppercase", "MIME", "-" ]
7090355f1c82c32570640a322d02bacce2a94a2c
https://github.com/emailjs/emailjs-mime-builder/blob/7090355f1c82c32570640a322d02bacce2a94a2c/dist/utils.js#L174-L181
21,131
emailjs/emailjs-mime-builder
dist/utils.js
buildHeaderValue
function buildHeaderValue(structured) { var paramsArray = []; Object.keys(structured.params || {}).forEach(function (param) { // filename might include unicode characters so it is a special case if (param === 'filename') { (0, _emailjsMimeCodec.continuationEncode)(param, structured.params[param], 50).forEach(function (encodedParam) { // continuation encoded strings are always escaped, so no need to use enclosing quotes // in fact using quotes might end up with invalid filenames in some clients paramsArray.push(encodedParam.key + '=' + encodedParam.value); }); } else { paramsArray.push(param + '=' + escapeHeaderArgument(structured.params[param])); } }); return structured.value + (paramsArray.length ? '; ' + paramsArray.join('; ') : ''); }
javascript
function buildHeaderValue(structured) { var paramsArray = []; Object.keys(structured.params || {}).forEach(function (param) { // filename might include unicode characters so it is a special case if (param === 'filename') { (0, _emailjsMimeCodec.continuationEncode)(param, structured.params[param], 50).forEach(function (encodedParam) { // continuation encoded strings are always escaped, so no need to use enclosing quotes // in fact using quotes might end up with invalid filenames in some clients paramsArray.push(encodedParam.key + '=' + encodedParam.value); }); } else { paramsArray.push(param + '=' + escapeHeaderArgument(structured.params[param])); } }); return structured.value + (paramsArray.length ? '; ' + paramsArray.join('; ') : ''); }
[ "function", "buildHeaderValue", "(", "structured", ")", "{", "var", "paramsArray", "=", "[", "]", ";", "Object", ".", "keys", "(", "structured", ".", "params", "||", "{", "}", ")", ".", "forEach", "(", "function", "(", "param", ")", "{", "// filename might include unicode characters so it is a special case", "if", "(", "param", "===", "'filename'", ")", "{", "(", "0", ",", "_emailjsMimeCodec", ".", "continuationEncode", ")", "(", "param", ",", "structured", ".", "params", "[", "param", "]", ",", "50", ")", ".", "forEach", "(", "function", "(", "encodedParam", ")", "{", "// continuation encoded strings are always escaped, so no need to use enclosing quotes", "// in fact using quotes might end up with invalid filenames in some clients", "paramsArray", ".", "push", "(", "encodedParam", ".", "key", "+", "'='", "+", "encodedParam", ".", "value", ")", ";", "}", ")", ";", "}", "else", "{", "paramsArray", ".", "push", "(", "param", "+", "'='", "+", "escapeHeaderArgument", "(", "structured", ".", "params", "[", "param", "]", ")", ")", ";", "}", "}", ")", ";", "return", "structured", ".", "value", "+", "(", "paramsArray", ".", "length", "?", "'; '", "+", "paramsArray", ".", "join", "(", "'; '", ")", ":", "''", ")", ";", "}" ]
Joins parsed header value together as 'value; param1=value1; param2=value2' @param {Object} structured Parsed header value @return {String} joined header value
[ "Joins", "parsed", "header", "value", "together", "as", "value", ";", "param1", "=", "value1", ";", "param2", "=", "value2" ]
7090355f1c82c32570640a322d02bacce2a94a2c
https://github.com/emailjs/emailjs-mime-builder/blob/7090355f1c82c32570640a322d02bacce2a94a2c/dist/utils.js#L213-L230
21,132
webduinoio/webduino-js
src/transport/NodeMqttTransport.js
NodeMqttTransport
function NodeMqttTransport(options) { Transport.call(this, options); this._options = options; this._client = null; this._sendTimer = null; this._buf = []; this._status = ''; this._connHandler = onConnect.bind(this); this._messageHandler = onMessage.bind(this); this._sendOutHandler = sendOut.bind(this); this._disconnHandler = onDisconnect.bind(this); this._errorHandler = onError.bind(this); init(this); }
javascript
function NodeMqttTransport(options) { Transport.call(this, options); this._options = options; this._client = null; this._sendTimer = null; this._buf = []; this._status = ''; this._connHandler = onConnect.bind(this); this._messageHandler = onMessage.bind(this); this._sendOutHandler = sendOut.bind(this); this._disconnHandler = onDisconnect.bind(this); this._errorHandler = onError.bind(this); init(this); }
[ "function", "NodeMqttTransport", "(", "options", ")", "{", "Transport", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_options", "=", "options", ";", "this", ".", "_client", "=", "null", ";", "this", ".", "_sendTimer", "=", "null", ";", "this", ".", "_buf", "=", "[", "]", ";", "this", ".", "_status", "=", "''", ";", "this", ".", "_connHandler", "=", "onConnect", ".", "bind", "(", "this", ")", ";", "this", ".", "_messageHandler", "=", "onMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "_sendOutHandler", "=", "sendOut", ".", "bind", "(", "this", ")", ";", "this", ".", "_disconnHandler", "=", "onDisconnect", ".", "bind", "(", "this", ")", ";", "this", ".", "_errorHandler", "=", "onError", ".", "bind", "(", "this", ")", ";", "init", "(", "this", ")", ";", "}" ]
Conveying messages over MQTT protocol, in Node.JS. @namespace webduino.transport @class NodeMqttTransport @constructor @param {Object} options Options to build a proper transport @extends webduino.Transport
[ "Conveying", "messages", "over", "MQTT", "protocol", "in", "Node", ".", "JS", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/src/transport/NodeMqttTransport.js#L39-L56
21,133
webduinoio/webduino-js
dist/webduino-all.js
function(error, substitutions) { var text = error.text; if (substitutions) { var field,start; for (var i=0; i<substitutions.length; i++) { field = "{"+i+"}"; start = text.indexOf(field); if(start > 0) { var part1 = text.substring(0,start); var part2 = text.substring(start+field.length); text = part1+substitutions[i]+part2; } } } return text; }
javascript
function(error, substitutions) { var text = error.text; if (substitutions) { var field,start; for (var i=0; i<substitutions.length; i++) { field = "{"+i+"}"; start = text.indexOf(field); if(start > 0) { var part1 = text.substring(0,start); var part2 = text.substring(start+field.length); text = part1+substitutions[i]+part2; } } } return text; }
[ "function", "(", "error", ",", "substitutions", ")", "{", "var", "text", "=", "error", ".", "text", ";", "if", "(", "substitutions", ")", "{", "var", "field", ",", "start", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "substitutions", ".", "length", ";", "i", "++", ")", "{", "field", "=", "\"{\"", "+", "i", "+", "\"}\"", ";", "start", "=", "text", ".", "indexOf", "(", "field", ")", ";", "if", "(", "start", ">", "0", ")", "{", "var", "part1", "=", "text", ".", "substring", "(", "0", ",", "start", ")", ";", "var", "part2", "=", "text", ".", "substring", "(", "start", "+", "field", ".", "length", ")", ";", "text", "=", "part1", "+", "substitutions", "[", "i", "]", "+", "part2", ";", "}", "}", "}", "return", "text", ";", "}" ]
Format an error message text. @private @param {error} ERROR.KEY value above. @param {substitutions} [array] substituted into the text. @return the text with the substitutions made.
[ "Format", "an", "error", "message", "text", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L392-L407
21,134
webduinoio/webduino-js
dist/webduino-all.js
UTF8Length
function UTF8Length(input) { var output = 0; for (var i = 0; i<input.length; i++) { var charCode = input.charCodeAt(i); if (charCode > 0x7FF) { // Surrogate pair means its a 4 byte character if (0xD800 <= charCode && charCode <= 0xDBFF) { i++; output++; } output +=3; } else if (charCode > 0x7F) output +=2; else output++; } return output; }
javascript
function UTF8Length(input) { var output = 0; for (var i = 0; i<input.length; i++) { var charCode = input.charCodeAt(i); if (charCode > 0x7FF) { // Surrogate pair means its a 4 byte character if (0xD800 <= charCode && charCode <= 0xDBFF) { i++; output++; } output +=3; } else if (charCode > 0x7F) output +=2; else output++; } return output; }
[ "function", "UTF8Length", "(", "input", ")", "{", "var", "output", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "input", ".", "length", ";", "i", "++", ")", "{", "var", "charCode", "=", "input", ".", "charCodeAt", "(", "i", ")", ";", "if", "(", "charCode", ">", "0x7FF", ")", "{", "// Surrogate pair means its a 4 byte character", "if", "(", "0xD800", "<=", "charCode", "&&", "charCode", "<=", "0xDBFF", ")", "{", "i", "++", ";", "output", "++", ";", "}", "output", "+=", "3", ";", "}", "else", "if", "(", "charCode", ">", "0x7F", ")", "output", "+=", "2", ";", "else", "output", "++", ";", "}", "return", "output", ";", "}" ]
Takes a String and calculates its length in bytes when encoded in UTF8. @private
[ "Takes", "a", "String", "and", "calculates", "its", "length", "in", "bytes", "when", "encoded", "in", "UTF8", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L752-L773
21,135
webduinoio/webduino-js
dist/webduino-all.js
callback
function callback(ctx, err, result) { if (typeof ctx.custom === 'function') { var cust = function () { // Bind the callback to itself, so the resolve and reject // properties that we bound are available to the callback. // Then we push it onto the end of the arguments array. return ctx.custom.apply(cust, arguments); }; cust.resolve = ctx.resolve; cust.reject = ctx.reject; cust.call(null, err, result); } else { if (err) { return ctx.reject(err); } ctx.resolve(result); } }
javascript
function callback(ctx, err, result) { if (typeof ctx.custom === 'function') { var cust = function () { // Bind the callback to itself, so the resolve and reject // properties that we bound are available to the callback. // Then we push it onto the end of the arguments array. return ctx.custom.apply(cust, arguments); }; cust.resolve = ctx.resolve; cust.reject = ctx.reject; cust.call(null, err, result); } else { if (err) { return ctx.reject(err); } ctx.resolve(result); } }
[ "function", "callback", "(", "ctx", ",", "err", ",", "result", ")", "{", "if", "(", "typeof", "ctx", ".", "custom", "===", "'function'", ")", "{", "var", "cust", "=", "function", "(", ")", "{", "// Bind the callback to itself, so the resolve and reject", "// properties that we bound are available to the callback.", "// Then we push it onto the end of the arguments array.", "return", "ctx", ".", "custom", ".", "apply", "(", "cust", ",", "arguments", ")", ";", "}", ";", "cust", ".", "resolve", "=", "ctx", ".", "resolve", ";", "cust", ".", "reject", "=", "ctx", ".", "reject", ";", "cust", ".", "call", "(", "null", ",", "err", ",", "result", ")", ";", "}", "else", "{", "if", "(", "err", ")", "{", "return", "ctx", ".", "reject", "(", "err", ")", ";", "}", "ctx", ".", "resolve", "(", "result", ")", ";", "}", "}" ]
Default callback function - rejects on truthy error, otherwise resolves
[ "Default", "callback", "function", "-", "rejects", "on", "truthy", "error", "otherwise", "resolves" ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L3098-L3115
21,136
webduinoio/webduino-js
dist/webduino-all.js
MqttTransport
function MqttTransport(options) { Transport.call(this, options); this._options = options; this._client = null; this._timer = null; this._sendTimer = null; this._buf = []; this._status = ''; this._connHandler = onConnect.bind(this); this._connFailedHandler = onConnectFailed.bind(this); this._messageHandler = onMessage.bind(this); this._sendOutHandler = sendOut.bind(this); this._disconnHandler = onDisconnect.bind(this); init(this); }
javascript
function MqttTransport(options) { Transport.call(this, options); this._options = options; this._client = null; this._timer = null; this._sendTimer = null; this._buf = []; this._status = ''; this._connHandler = onConnect.bind(this); this._connFailedHandler = onConnectFailed.bind(this); this._messageHandler = onMessage.bind(this); this._sendOutHandler = sendOut.bind(this); this._disconnHandler = onDisconnect.bind(this); init(this); }
[ "function", "MqttTransport", "(", "options", ")", "{", "Transport", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_options", "=", "options", ";", "this", ".", "_client", "=", "null", ";", "this", ".", "_timer", "=", "null", ";", "this", ".", "_sendTimer", "=", "null", ";", "this", ".", "_buf", "=", "[", "]", ";", "this", ".", "_status", "=", "''", ";", "this", ".", "_connHandler", "=", "onConnect", ".", "bind", "(", "this", ")", ";", "this", ".", "_connFailedHandler", "=", "onConnectFailed", ".", "bind", "(", "this", ")", ";", "this", ".", "_messageHandler", "=", "onMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "_sendOutHandler", "=", "sendOut", ".", "bind", "(", "this", ")", ";", "this", ".", "_disconnHandler", "=", "onDisconnect", ".", "bind", "(", "this", ")", ";", "init", "(", "this", ")", ";", "}" ]
Conveying messages over MQTT protocol. @namespace webduino.transport @class MqttTransport @constructor @param {Object} options Options to build a proper transport @extends webduino.Transport
[ "Conveying", "messages", "over", "MQTT", "protocol", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L3289-L3307
21,137
webduinoio/webduino-js
dist/webduino-all.js
Board
function Board(options) { EventEmitter.call(this); this._options = options; this._buf = []; this._digitalPort = []; this._numPorts = 0; this._analogPinMapping = []; this._digitalPinMapping = []; this._i2cPins = []; this._ioPins = []; this._totalPins = 0; this._totalAnalogPins = 0; this._samplingInterval = 19; this._isReady = false; this._firmwareName = ''; this._firmwareVersion = 0; this._capabilityQueryResponseReceived = false; this._numPinStateRequests = 0; this._numDigitalPortReportRequests = 0; this._transport = null; this._pinStateEventCenter = new EventEmitter(); this._logger = new Logger('Board'); this._initialVersionResultHandler = onInitialVersionResult.bind(this); this._openHandler = onOpen.bind(this); this._reOpenHandler = onReOpen.bind(this); this._messageHandler = onMessage.bind(this); this._errorHandler = onError.bind(this); this._closeHandler = onClose.bind(this); this._cleanupHandler = cleanup.bind(this); attachCleanup(this); this._setTransport(this._options.transport); }
javascript
function Board(options) { EventEmitter.call(this); this._options = options; this._buf = []; this._digitalPort = []; this._numPorts = 0; this._analogPinMapping = []; this._digitalPinMapping = []; this._i2cPins = []; this._ioPins = []; this._totalPins = 0; this._totalAnalogPins = 0; this._samplingInterval = 19; this._isReady = false; this._firmwareName = ''; this._firmwareVersion = 0; this._capabilityQueryResponseReceived = false; this._numPinStateRequests = 0; this._numDigitalPortReportRequests = 0; this._transport = null; this._pinStateEventCenter = new EventEmitter(); this._logger = new Logger('Board'); this._initialVersionResultHandler = onInitialVersionResult.bind(this); this._openHandler = onOpen.bind(this); this._reOpenHandler = onReOpen.bind(this); this._messageHandler = onMessage.bind(this); this._errorHandler = onError.bind(this); this._closeHandler = onClose.bind(this); this._cleanupHandler = cleanup.bind(this); attachCleanup(this); this._setTransport(this._options.transport); }
[ "function", "Board", "(", "options", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_options", "=", "options", ";", "this", ".", "_buf", "=", "[", "]", ";", "this", ".", "_digitalPort", "=", "[", "]", ";", "this", ".", "_numPorts", "=", "0", ";", "this", ".", "_analogPinMapping", "=", "[", "]", ";", "this", ".", "_digitalPinMapping", "=", "[", "]", ";", "this", ".", "_i2cPins", "=", "[", "]", ";", "this", ".", "_ioPins", "=", "[", "]", ";", "this", ".", "_totalPins", "=", "0", ";", "this", ".", "_totalAnalogPins", "=", "0", ";", "this", ".", "_samplingInterval", "=", "19", ";", "this", ".", "_isReady", "=", "false", ";", "this", ".", "_firmwareName", "=", "''", ";", "this", ".", "_firmwareVersion", "=", "0", ";", "this", ".", "_capabilityQueryResponseReceived", "=", "false", ";", "this", ".", "_numPinStateRequests", "=", "0", ";", "this", ".", "_numDigitalPortReportRequests", "=", "0", ";", "this", ".", "_transport", "=", "null", ";", "this", ".", "_pinStateEventCenter", "=", "new", "EventEmitter", "(", ")", ";", "this", ".", "_logger", "=", "new", "Logger", "(", "'Board'", ")", ";", "this", ".", "_initialVersionResultHandler", "=", "onInitialVersionResult", ".", "bind", "(", "this", ")", ";", "this", ".", "_openHandler", "=", "onOpen", ".", "bind", "(", "this", ")", ";", "this", ".", "_reOpenHandler", "=", "onReOpen", ".", "bind", "(", "this", ")", ";", "this", ".", "_messageHandler", "=", "onMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "_errorHandler", "=", "onError", ".", "bind", "(", "this", ")", ";", "this", ".", "_closeHandler", "=", "onClose", ".", "bind", "(", "this", ")", ";", "this", ".", "_cleanupHandler", "=", "cleanup", ".", "bind", "(", "this", ")", ";", "attachCleanup", "(", "this", ")", ";", "this", ".", "_setTransport", "(", "this", ".", "_options", ".", "transport", ")", ";", "}" ]
SYSEX_NON_REALTIME = 0x7E, SYSEX_REALTIME = 0x7F; An abstract development board. @namespace webduino @class Board @constructor @param {Object} options Options to build the board instance. @extends webduino.EventEmitter
[ "SYSEX_NON_REALTIME", "=", "0x7E", "SYSEX_REALTIME", "=", "0x7F", ";", "An", "abstract", "development", "board", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L4098-L4132
21,138
webduinoio/webduino-js
dist/webduino-all.js
Led
function Led(board, pin, driveMode) { Module.call(this); this._board = board; this._pin = pin; this._driveMode = driveMode || Led.SOURCE_DRIVE; this._supportsPWM = undefined; this._blinkTimer = null; this._board.on(BoardEvent.BEFOREDISCONNECT, this._clearBlinkTimer.bind(this)); this._board.on(BoardEvent.ERROR, this._clearBlinkTimer.bind(this)); if (this._driveMode === Led.SOURCE_DRIVE) { this._onValue = 1; this._offValue = 0; } else if (this._driveMode === Led.SYNC_DRIVE) { this._onValue = 0; this._offValue = 1; } else { throw new Error('driveMode should be Led.SOURCE_DRIVE or Led.SYNC_DRIVE'); } if (pin.capabilities[Pin.PWM]) { board.setDigitalPinMode(pin.number, Pin.PWM); this._supportsPWM = true; } else { board.setDigitalPinMode(pin.number, Pin.DOUT); this._supportsPWM = false; } }
javascript
function Led(board, pin, driveMode) { Module.call(this); this._board = board; this._pin = pin; this._driveMode = driveMode || Led.SOURCE_DRIVE; this._supportsPWM = undefined; this._blinkTimer = null; this._board.on(BoardEvent.BEFOREDISCONNECT, this._clearBlinkTimer.bind(this)); this._board.on(BoardEvent.ERROR, this._clearBlinkTimer.bind(this)); if (this._driveMode === Led.SOURCE_DRIVE) { this._onValue = 1; this._offValue = 0; } else if (this._driveMode === Led.SYNC_DRIVE) { this._onValue = 0; this._offValue = 1; } else { throw new Error('driveMode should be Led.SOURCE_DRIVE or Led.SYNC_DRIVE'); } if (pin.capabilities[Pin.PWM]) { board.setDigitalPinMode(pin.number, Pin.PWM); this._supportsPWM = true; } else { board.setDigitalPinMode(pin.number, Pin.DOUT); this._supportsPWM = false; } }
[ "function", "Led", "(", "board", ",", "pin", ",", "driveMode", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_pin", "=", "pin", ";", "this", ".", "_driveMode", "=", "driveMode", "||", "Led", ".", "SOURCE_DRIVE", ";", "this", ".", "_supportsPWM", "=", "undefined", ";", "this", ".", "_blinkTimer", "=", "null", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "BEFOREDISCONNECT", ",", "this", ".", "_clearBlinkTimer", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "ERROR", ",", "this", ".", "_clearBlinkTimer", ".", "bind", "(", "this", ")", ")", ";", "if", "(", "this", ".", "_driveMode", "===", "Led", ".", "SOURCE_DRIVE", ")", "{", "this", ".", "_onValue", "=", "1", ";", "this", ".", "_offValue", "=", "0", ";", "}", "else", "if", "(", "this", ".", "_driveMode", "===", "Led", ".", "SYNC_DRIVE", ")", "{", "this", ".", "_onValue", "=", "0", ";", "this", ".", "_offValue", "=", "1", ";", "}", "else", "{", "throw", "new", "Error", "(", "'driveMode should be Led.SOURCE_DRIVE or Led.SYNC_DRIVE'", ")", ";", "}", "if", "(", "pin", ".", "capabilities", "[", "Pin", ".", "PWM", "]", ")", "{", "board", ".", "setDigitalPinMode", "(", "pin", ".", "number", ",", "Pin", ".", "PWM", ")", ";", "this", ".", "_supportsPWM", "=", "true", ";", "}", "else", "{", "board", ".", "setDigitalPinMode", "(", "pin", ".", "number", ",", "Pin", ".", "DOUT", ")", ";", "this", ".", "_supportsPWM", "=", "false", ";", "}", "}" ]
The Led class. @namespace webduino.module @class Led @constructor @param {webduino.Board} board The board the LED is attached to. @param {webduino.Pin} pin The pin the LED is connected to. @param {Number} [driveMode] Drive mode the LED is operating at, either Led.SOURCE_DRIVE or Led.SYNC_DRIVE. @extends webduino.Module
[ "The", "Led", "class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L6180-L6209
21,139
webduinoio/webduino-js
dist/webduino-all.js
RGBLed
function RGBLed(board, redLedPin, greenLedPin, blueLedPin, driveMode) { Module.call(this); if (driveMode === undefined) { driveMode = RGBLed.COMMON_ANODE; } this._board = board; this._redLed = new Led(board, redLedPin, driveMode); this._greenLed = new Led(board, greenLedPin, driveMode); this._blueLed = new Led(board, blueLedPin, driveMode); this.setColor(0, 0, 0); }
javascript
function RGBLed(board, redLedPin, greenLedPin, blueLedPin, driveMode) { Module.call(this); if (driveMode === undefined) { driveMode = RGBLed.COMMON_ANODE; } this._board = board; this._redLed = new Led(board, redLedPin, driveMode); this._greenLed = new Led(board, greenLedPin, driveMode); this._blueLed = new Led(board, blueLedPin, driveMode); this.setColor(0, 0, 0); }
[ "function", "RGBLed", "(", "board", ",", "redLedPin", ",", "greenLedPin", ",", "blueLedPin", ",", "driveMode", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "if", "(", "driveMode", "===", "undefined", ")", "{", "driveMode", "=", "RGBLed", ".", "COMMON_ANODE", ";", "}", "this", ".", "_board", "=", "board", ";", "this", ".", "_redLed", "=", "new", "Led", "(", "board", ",", "redLedPin", ",", "driveMode", ")", ";", "this", ".", "_greenLed", "=", "new", "Led", "(", "board", ",", "greenLedPin", ",", "driveMode", ")", ";", "this", ".", "_blueLed", "=", "new", "Led", "(", "board", ",", "blueLedPin", ",", "driveMode", ")", ";", "this", ".", "setColor", "(", "0", ",", "0", ",", "0", ")", ";", "}" ]
The RGBLed Class. @namespace webduino.module @class RGBLed @constructor @param {webduino.Board} board The board the RGB LED is attached to. @param {webduino.Pin} redLedPin The pin the red LED is connected to. @param {webduino.Pin} greenLedPin The pin the green LED is connected to. @param {webduino.Pin} blueLedPin The pin the blue LED is connected to. @param {Number} [driveMode] Drive mode the RGB LED is operating at, either RGBLed.COMMON_ANODE or RGBLed.COMMON_CATHODE. @extends webduino.Module
[ "The", "RGBLed", "Class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L6384-L6397
21,140
webduinoio/webduino-js
dist/webduino-all.js
Button
function Button(board, pin, buttonMode, sustainedPressInterval) { Module.call(this); this._board = board; this._pin = pin; this._repeatCount = 0; this._timer = null; this._timeout = null; this._buttonMode = buttonMode || Button.PULL_DOWN; this._sustainedPressInterval = sustainedPressInterval || 1000; this._debounceInterval = 20; this._pressHandler = onPress.bind(this); this._releaseHandler = onRelease.bind(this); this._sustainedPressHandler = onSustainedPress.bind(this); board.setDigitalPinMode(pin.number, Pin.DIN); if (this._buttonMode === Button.INTERNAL_PULL_UP) { board.enablePullUp(pin.number); this._pin.value = Pin.HIGH; } else if (this._buttonMode === Button.PULL_UP) { this._pin.value = Pin.HIGH; } this._pin.on(PinEvent.CHANGE, onPinChange.bind(this)); }
javascript
function Button(board, pin, buttonMode, sustainedPressInterval) { Module.call(this); this._board = board; this._pin = pin; this._repeatCount = 0; this._timer = null; this._timeout = null; this._buttonMode = buttonMode || Button.PULL_DOWN; this._sustainedPressInterval = sustainedPressInterval || 1000; this._debounceInterval = 20; this._pressHandler = onPress.bind(this); this._releaseHandler = onRelease.bind(this); this._sustainedPressHandler = onSustainedPress.bind(this); board.setDigitalPinMode(pin.number, Pin.DIN); if (this._buttonMode === Button.INTERNAL_PULL_UP) { board.enablePullUp(pin.number); this._pin.value = Pin.HIGH; } else if (this._buttonMode === Button.PULL_UP) { this._pin.value = Pin.HIGH; } this._pin.on(PinEvent.CHANGE, onPinChange.bind(this)); }
[ "function", "Button", "(", "board", ",", "pin", ",", "buttonMode", ",", "sustainedPressInterval", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_pin", "=", "pin", ";", "this", ".", "_repeatCount", "=", "0", ";", "this", ".", "_timer", "=", "null", ";", "this", ".", "_timeout", "=", "null", ";", "this", ".", "_buttonMode", "=", "buttonMode", "||", "Button", ".", "PULL_DOWN", ";", "this", ".", "_sustainedPressInterval", "=", "sustainedPressInterval", "||", "1000", ";", "this", ".", "_debounceInterval", "=", "20", ";", "this", ".", "_pressHandler", "=", "onPress", ".", "bind", "(", "this", ")", ";", "this", ".", "_releaseHandler", "=", "onRelease", ".", "bind", "(", "this", ")", ";", "this", ".", "_sustainedPressHandler", "=", "onSustainedPress", ".", "bind", "(", "this", ")", ";", "board", ".", "setDigitalPinMode", "(", "pin", ".", "number", ",", "Pin", ".", "DIN", ")", ";", "if", "(", "this", ".", "_buttonMode", "===", "Button", ".", "INTERNAL_PULL_UP", ")", "{", "board", ".", "enablePullUp", "(", "pin", ".", "number", ")", ";", "this", ".", "_pin", ".", "value", "=", "Pin", ".", "HIGH", ";", "}", "else", "if", "(", "this", ".", "_buttonMode", "===", "Button", ".", "PULL_UP", ")", "{", "this", ".", "_pin", ".", "value", "=", "Pin", ".", "HIGH", ";", "}", "this", ".", "_pin", ".", "on", "(", "PinEvent", ".", "CHANGE", ",", "onPinChange", ".", "bind", "(", "this", ")", ")", ";", "}" ]
The Button Class. @namespace webduino.module @class Button @constructor @param {webduino.Board} board The board the button is attached to. @param {webduino.pin} pin The pin the button is connected to. @param {Number} [buttonMode] Type of resistor the button is connected to, either Button.PULL_DOWN or Button.PULL_UP. @param {Number} [sustainedPressInterval] A period of time when the button is pressed and hold for that long, it would be considered a "sustained press." Measured in ms. @extends webduino.Module
[ "The", "Button", "Class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L6542-L6568
21,141
webduinoio/webduino-js
dist/webduino-all.js
Ultrasonic
function Ultrasonic(board, trigger, echo) { Module.call(this); this._type = 'HC-SR04'; this._board = board; this._trigger = trigger; this._echo = echo; this._distance = null; this._lastRecv = null; this._pingTimer = null; this._pingCallback = function () {}; this._board.on(BoardEvent.BEFOREDISCONNECT, this.stopPing.bind(this)); this._messageHandler = onMessage.bind(this); this._board.on(BoardEvent.ERROR, this.stopPing.bind(this)); }
javascript
function Ultrasonic(board, trigger, echo) { Module.call(this); this._type = 'HC-SR04'; this._board = board; this._trigger = trigger; this._echo = echo; this._distance = null; this._lastRecv = null; this._pingTimer = null; this._pingCallback = function () {}; this._board.on(BoardEvent.BEFOREDISCONNECT, this.stopPing.bind(this)); this._messageHandler = onMessage.bind(this); this._board.on(BoardEvent.ERROR, this.stopPing.bind(this)); }
[ "function", "Ultrasonic", "(", "board", ",", "trigger", ",", "echo", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_type", "=", "'HC-SR04'", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_trigger", "=", "trigger", ";", "this", ".", "_echo", "=", "echo", ";", "this", ".", "_distance", "=", "null", ";", "this", ".", "_lastRecv", "=", "null", ";", "this", ".", "_pingTimer", "=", "null", ";", "this", ".", "_pingCallback", "=", "function", "(", ")", "{", "}", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "BEFOREDISCONNECT", ",", "this", ".", "stopPing", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "_messageHandler", "=", "onMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "ERROR", ",", "this", ".", "stopPing", ".", "bind", "(", "this", ")", ")", ";", "}" ]
The Ultrasonic class. @namespace webduino.module @class Ultrasonic @constructor @param {webduino.Board} board The board the ultrasonic sensor is attached to. @param {webduino.Pin} trigger The trigger pin the sensor is connected to. @param {webduino.Pin} echo The echo pin the sensor is connected to. @extends webduino.Module
[ "The", "Ultrasonic", "class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L6737-L6752
21,142
webduinoio/webduino-js
dist/webduino-all.js
Dht
function Dht(board, pin) { Module.call(this); this._type = 'DHT11'; this._board = board; this._pin = pin; this._humidity = null; this._temperature = null; this._lastRecv = null; this._readTimer = null; this._readCallback = function () {}; this._board.on(BoardEvent.BEFOREDISCONNECT, this.stopRead.bind(this)); this._messageHandler = onMessage.bind(this); this._board.on(BoardEvent.ERROR, this.stopRead.bind(this)); }
javascript
function Dht(board, pin) { Module.call(this); this._type = 'DHT11'; this._board = board; this._pin = pin; this._humidity = null; this._temperature = null; this._lastRecv = null; this._readTimer = null; this._readCallback = function () {}; this._board.on(BoardEvent.BEFOREDISCONNECT, this.stopRead.bind(this)); this._messageHandler = onMessage.bind(this); this._board.on(BoardEvent.ERROR, this.stopRead.bind(this)); }
[ "function", "Dht", "(", "board", ",", "pin", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_type", "=", "'DHT11'", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_pin", "=", "pin", ";", "this", ".", "_humidity", "=", "null", ";", "this", ".", "_temperature", "=", "null", ";", "this", ".", "_lastRecv", "=", "null", ";", "this", ".", "_readTimer", "=", "null", ";", "this", ".", "_readCallback", "=", "function", "(", ")", "{", "}", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "BEFOREDISCONNECT", ",", "this", ".", "stopRead", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "_messageHandler", "=", "onMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "ERROR", ",", "this", ".", "stopRead", ".", "bind", "(", "this", ")", ")", ";", "}" ]
The Dht Class. DHT is sensor for measuring temperature and humidity. @namespace webduino.module @class Dht @constructor @param {webduino.Board} board The board that the DHT is attached to. @param {Integer} pin The pin that the DHT is connected to. @extends webduino.Module
[ "The", "Dht", "Class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L7233-L7248
21,143
webduinoio/webduino-js
dist/webduino-all.js
Buzzer
function Buzzer(board, pin) { Module.call(this); this._board = board; this._pin = pin; this._timer = null; this._sequence = null; this._state = BUZZER_STATE.STOPPED; this._board.on(BoardEvent.BEFOREDISCONNECT, this.stop.bind(this)); this._board.on(BoardEvent.ERROR, this.stop.bind(this)); }
javascript
function Buzzer(board, pin) { Module.call(this); this._board = board; this._pin = pin; this._timer = null; this._sequence = null; this._state = BUZZER_STATE.STOPPED; this._board.on(BoardEvent.BEFOREDISCONNECT, this.stop.bind(this)); this._board.on(BoardEvent.ERROR, this.stop.bind(this)); }
[ "function", "Buzzer", "(", "board", ",", "pin", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_pin", "=", "pin", ";", "this", ".", "_timer", "=", "null", ";", "this", ".", "_sequence", "=", "null", ";", "this", ".", "_state", "=", "BUZZER_STATE", ".", "STOPPED", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "BEFOREDISCONNECT", ",", "this", ".", "stop", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "ERROR", ",", "this", ".", "stop", ".", "bind", "(", "this", ")", ")", ";", "}" ]
The Buzzer Class. @namespace webduino.module @class Buzzer @constructor @param {webduino.Board} board The board that the buzzer is attached to. @param {Integer} pin The pin that the buzzer is connected to. @extends webduino.Module
[ "The", "Buzzer", "Class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L7531-L7542
21,144
webduinoio/webduino-js
dist/webduino-all.js
Max7219
function Max7219(board, din, cs, clk) { Module.call(this); this._board = board; this._din = din; this._cs = cs; this._clk = clk; this._intensity = 0; this._data = 'ffffffffffffffff'; this._board.on(BoardEvent.BEFOREDISCONNECT, this.animateStop.bind(this)); this._board.on(BoardEvent.ERROR, this.animateStop.bind(this)); this._board.send([0xf0, 4, 8, 0, din.number, cs.number, clk.number, 0xf7]); }
javascript
function Max7219(board, din, cs, clk) { Module.call(this); this._board = board; this._din = din; this._cs = cs; this._clk = clk; this._intensity = 0; this._data = 'ffffffffffffffff'; this._board.on(BoardEvent.BEFOREDISCONNECT, this.animateStop.bind(this)); this._board.on(BoardEvent.ERROR, this.animateStop.bind(this)); this._board.send([0xf0, 4, 8, 0, din.number, cs.number, clk.number, 0xf7]); }
[ "function", "Max7219", "(", "board", ",", "din", ",", "cs", ",", "clk", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_din", "=", "din", ";", "this", ".", "_cs", "=", "cs", ";", "this", ".", "_clk", "=", "clk", ";", "this", ".", "_intensity", "=", "0", ";", "this", ".", "_data", "=", "'ffffffffffffffff'", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "BEFOREDISCONNECT", ",", "this", ".", "animateStop", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "ERROR", ",", "this", ".", "animateStop", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "_board", ".", "send", "(", "[", "0xf0", ",", "4", ",", "8", ",", "0", ",", "din", ".", "number", ",", "cs", ".", "number", ",", "clk", ".", "number", ",", "0xf7", "]", ")", ";", "}" ]
The Max7219 Class. MAX7219 is compact, serial input/output common-cathode display drivers that interface microprocessors (µPs) to 7-segment numeric LED displays of up to 8 digits, bar-graph displays, or 64 individual LEDs. @namespace webduino.module @class Max7219 @constructor @param {webduino.Board} board The board that the Max7219 is attached to. @param {Integer} din Pin number of DIn (Data In). @param {Integer} cs Pin number of LOAD/CS. @param {Integer} clk Pin number of CLK. @extends webduino.Module
[ "The", "Max7219", "Class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L7728-L7740
21,145
webduinoio/webduino-js
dist/webduino-all.js
ADXL345
function ADXL345(board) { Module.call(this); this._board = board; this._baseAxis = 'z'; this._sensitive = 10; this._detectTime = 50; this._messageHandler = onMessage.bind(this); this._init = false; this._info = { x: 0, y: 0, z: 0, fXg: 0, fYg: 0, fZg: 0 }; this._callback = function () {}; this._board.send([0xf0, 0x04, 0x0b, 0x00, 0xf7]); }
javascript
function ADXL345(board) { Module.call(this); this._board = board; this._baseAxis = 'z'; this._sensitive = 10; this._detectTime = 50; this._messageHandler = onMessage.bind(this); this._init = false; this._info = { x: 0, y: 0, z: 0, fXg: 0, fYg: 0, fZg: 0 }; this._callback = function () {}; this._board.send([0xf0, 0x04, 0x0b, 0x00, 0xf7]); }
[ "function", "ADXL345", "(", "board", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_baseAxis", "=", "'z'", ";", "this", ".", "_sensitive", "=", "10", ";", "this", ".", "_detectTime", "=", "50", ";", "this", ".", "_messageHandler", "=", "onMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "_init", "=", "false", ";", "this", ".", "_info", "=", "{", "x", ":", "0", ",", "y", ":", "0", ",", "z", ":", "0", ",", "fXg", ":", "0", ",", "fYg", ":", "0", ",", "fZg", ":", "0", "}", ";", "this", ".", "_callback", "=", "function", "(", ")", "{", "}", ";", "this", ".", "_board", ".", "send", "(", "[", "0xf0", ",", "0x04", ",", "0x0b", ",", "0x00", ",", "0xf7", "]", ")", ";", "}" ]
The ADXL345 class. ADXL345 is a small, thin, ultralow power, 3-axis accelerometer. @namespace webduino.module @class ADXL345 @constructor @param {webduino.Board} board The board that the ADXL345 accelerometer is attached to. @extends webduino.Module
[ "The", "ADXL345", "class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L7894-L7912
21,146
webduinoio/webduino-js
dist/webduino-all.js
HX711
function HX711(board, sckPin, dtPin) { Module.call(this); this._board = board; this._dt = !isNaN(dtPin) ? board.getDigitalPin(dtPin) : dtPin; this._sck = !isNaN(sckPin) ? board.getDigitalPin(sckPin) : sckPin; this._init = false; this._weight = 0; this._callback = function() {}; this._messageHandler = onMessage.bind(this); this._board.send([0xf0, 0x04, 0x15, 0x00, this._sck._number, this._dt._number, 0xf7 ]); }
javascript
function HX711(board, sckPin, dtPin) { Module.call(this); this._board = board; this._dt = !isNaN(dtPin) ? board.getDigitalPin(dtPin) : dtPin; this._sck = !isNaN(sckPin) ? board.getDigitalPin(sckPin) : sckPin; this._init = false; this._weight = 0; this._callback = function() {}; this._messageHandler = onMessage.bind(this); this._board.send([0xf0, 0x04, 0x15, 0x00, this._sck._number, this._dt._number, 0xf7 ]); }
[ "function", "HX711", "(", "board", ",", "sckPin", ",", "dtPin", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_dt", "=", "!", "isNaN", "(", "dtPin", ")", "?", "board", ".", "getDigitalPin", "(", "dtPin", ")", ":", "dtPin", ";", "this", ".", "_sck", "=", "!", "isNaN", "(", "sckPin", ")", "?", "board", ".", "getDigitalPin", "(", "sckPin", ")", ":", "sckPin", ";", "this", ".", "_init", "=", "false", ";", "this", ".", "_weight", "=", "0", ";", "this", ".", "_callback", "=", "function", "(", ")", "{", "}", ";", "this", ".", "_messageHandler", "=", "onMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "_board", ".", "send", "(", "[", "0xf0", ",", "0x04", ",", "0x15", ",", "0x00", ",", "this", ".", "_sck", ".", "_number", ",", "this", ".", "_dt", ".", "_number", ",", "0xf7", "]", ")", ";", "}" ]
The HX711 Class. HX711 is a precision 24-bit analogto-digital converter (ADC) designed for weigh scales. @namespace webduino.module @class HX711 @constructor @param {webduino.Board} board The board that the IRLed is attached to. @param {Integer} sckPin The pin that Serial Clock Input is attached to. @param {Integer} dtPin The pin that Data Output is attached to. @extends webduino.Module
[ "The", "HX711", "Class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L8163-L8176
21,147
webduinoio/webduino-js
dist/webduino-all.js
Barcode
function Barcode(board, rxPin, txPin) { Module.call(this); this._board = board; this._rx = !isNaN(rxPin) ? board.getDigitalPin(rxPin) : rxPin; this._tx = !isNaN(txPin) ? board.getDigitalPin(txPin) : txPin; this._init = false; this._scanData = ''; this._callback = function () {}; this._messageHandler = onMessage.bind(this); this._board.send([0xf0, 0x04, 0x16, 0x00, this._rx._number, this._tx._number, 0xf7 ]); }
javascript
function Barcode(board, rxPin, txPin) { Module.call(this); this._board = board; this._rx = !isNaN(rxPin) ? board.getDigitalPin(rxPin) : rxPin; this._tx = !isNaN(txPin) ? board.getDigitalPin(txPin) : txPin; this._init = false; this._scanData = ''; this._callback = function () {}; this._messageHandler = onMessage.bind(this); this._board.send([0xf0, 0x04, 0x16, 0x00, this._rx._number, this._tx._number, 0xf7 ]); }
[ "function", "Barcode", "(", "board", ",", "rxPin", ",", "txPin", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_rx", "=", "!", "isNaN", "(", "rxPin", ")", "?", "board", ".", "getDigitalPin", "(", "rxPin", ")", ":", "rxPin", ";", "this", ".", "_tx", "=", "!", "isNaN", "(", "txPin", ")", "?", "board", ".", "getDigitalPin", "(", "txPin", ")", ":", "txPin", ";", "this", ".", "_init", "=", "false", ";", "this", ".", "_scanData", "=", "''", ";", "this", ".", "_callback", "=", "function", "(", ")", "{", "}", ";", "this", ".", "_messageHandler", "=", "onMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "_board", ".", "send", "(", "[", "0xf0", ",", "0x04", ",", "0x16", ",", "0x00", ",", "this", ".", "_rx", ".", "_number", ",", "this", ".", "_tx", ".", "_number", ",", "0xf7", "]", ")", ";", "}" ]
The Barcode class. @namespace webduino.module @class Barcode @constructor @param {webduino.Board} board The board the barcode scanner is attached to. @param {webduino.Pin | Number} rxPin Receivin pin (number) the barcode scanner is connected to. @param {webduino.Pin | Number} txPin Transmitting pin (number) the barcode scanner is connected to. @extends webduino.Module
[ "The", "Barcode", "class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L8433-L8446
21,148
webduinoio/webduino-js
dist/webduino-all.js
IRLed
function IRLed(board, encode) { Module.call(this); this._board = board; this._encode = encode; this._board.send([0xf4, 0x09, 0x03, 0xe9, 0x00, 0x00]); }
javascript
function IRLed(board, encode) { Module.call(this); this._board = board; this._encode = encode; this._board.send([0xf4, 0x09, 0x03, 0xe9, 0x00, 0x00]); }
[ "function", "IRLed", "(", "board", ",", "encode", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_encode", "=", "encode", ";", "this", ".", "_board", ".", "send", "(", "[", "0xf4", ",", "0x09", ",", "0x03", ",", "0xe9", ",", "0x00", ",", "0x00", "]", ")", ";", "}" ]
The IRLed Class. IR LED (Infrared LED) is widely used for remote controls and night-vision cameras. @namespace webduino.module @class IRLed @constructor @param {webduino.Board} board The board that the IRLed is attached to. @param {String} encode Encode which IRLed used. @extends webduino.Module
[ "The", "IRLed", "Class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L8549-L8554
21,149
webduinoio/webduino-js
dist/webduino-all.js
IRRecv
function IRRecv(board, pin) { Module.call(this); this._board = board; this._pin = pin; this._messageHandler = onMessage.bind(this); this._recvCallback = function () {}; this._recvErrorCallback = function () {}; this._board.send([0xf0, 0x04, 0x0A, 0x01, 0xf7]); }
javascript
function IRRecv(board, pin) { Module.call(this); this._board = board; this._pin = pin; this._messageHandler = onMessage.bind(this); this._recvCallback = function () {}; this._recvErrorCallback = function () {}; this._board.send([0xf0, 0x04, 0x0A, 0x01, 0xf7]); }
[ "function", "IRRecv", "(", "board", ",", "pin", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_pin", "=", "pin", ";", "this", ".", "_messageHandler", "=", "onMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "_recvCallback", "=", "function", "(", ")", "{", "}", ";", "this", ".", "_recvErrorCallback", "=", "function", "(", ")", "{", "}", ";", "this", ".", "_board", ".", "send", "(", "[", "0xf0", ",", "0x04", ",", "0x0A", ",", "0x01", ",", "0xf7", "]", ")", ";", "}" ]
The IRRecv Class. @namespace webduino.module @class IRRecv @constructor @param {webduino.Board} board The board that the IRLed is attached to. @param {Integer} pin The pin that the IRLed is connected to. @extends webduino.Module
[ "The", "IRRecv", "Class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L8642-L8650
21,150
webduinoio/webduino-js
dist/webduino-all.js
RFID
function RFID(board) { Module.call(this); this._board = board; this._isReading = false; this._enterHandlers = []; this._leaveHandlers = []; this._messageHandler = onMessage.bind(this); this._board.on(BoardEvent.BEFOREDISCONNECT, this.destroy.bind(this)); this._board.on(BoardEvent.ERROR, this.destroy.bind(this)); this._board.send([0xf0, 0x04, 0x0f, 0x00, 0xf7]); }
javascript
function RFID(board) { Module.call(this); this._board = board; this._isReading = false; this._enterHandlers = []; this._leaveHandlers = []; this._messageHandler = onMessage.bind(this); this._board.on(BoardEvent.BEFOREDISCONNECT, this.destroy.bind(this)); this._board.on(BoardEvent.ERROR, this.destroy.bind(this)); this._board.send([0xf0, 0x04, 0x0f, 0x00, 0xf7]); }
[ "function", "RFID", "(", "board", ")", "{", "Module", ".", "call", "(", "this", ")", ";", "this", ".", "_board", "=", "board", ";", "this", ".", "_isReading", "=", "false", ";", "this", ".", "_enterHandlers", "=", "[", "]", ";", "this", ".", "_leaveHandlers", "=", "[", "]", ";", "this", ".", "_messageHandler", "=", "onMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "BEFOREDISCONNECT", ",", "this", ".", "destroy", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "_board", ".", "on", "(", "BoardEvent", ".", "ERROR", ",", "this", ".", "destroy", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "_board", ".", "send", "(", "[", "0xf0", ",", "0x04", ",", "0x0f", ",", "0x00", ",", "0xf7", "]", ")", ";", "}" ]
The RFID class. RFID reader is used to track nearby tags by wirelessly reading a tag's unique ID. @namespace webduino.module @class RFID @constructor @param {webduino.Board} board Board that the RFID is attached to. @extends webduino.Module
[ "The", "RFID", "class", "." ]
2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49
https://github.com/webduinoio/webduino-js/blob/2ea8f0cc1005f5a5db62241bd33c0e1823ed1e49/dist/webduino-all.js#L9171-L9183
21,151
IcedFrisby/IcedFrisby
lib/pathMatch.js
setup
function setup(check) { if (!check) { throw new Error('Data to match is not defined') } else if (!check.jsonBody) { throw new Error('jsonBody is not defined') } else if (!check.jsonTest) { throw new Error('jsonTest is not defined') } // define the defaults const defaults = { isNot: false, path: undefined, // jsonBody will be present // jsonTest will be present } // merge the passed in values with the defaults return _.merge(defaults, check) }
javascript
function setup(check) { if (!check) { throw new Error('Data to match is not defined') } else if (!check.jsonBody) { throw new Error('jsonBody is not defined') } else if (!check.jsonTest) { throw new Error('jsonTest is not defined') } // define the defaults const defaults = { isNot: false, path: undefined, // jsonBody will be present // jsonTest will be present } // merge the passed in values with the defaults return _.merge(defaults, check) }
[ "function", "setup", "(", "check", ")", "{", "if", "(", "!", "check", ")", "{", "throw", "new", "Error", "(", "'Data to match is not defined'", ")", "}", "else", "if", "(", "!", "check", ".", "jsonBody", ")", "{", "throw", "new", "Error", "(", "'jsonBody is not defined'", ")", "}", "else", "if", "(", "!", "check", ".", "jsonTest", ")", "{", "throw", "new", "Error", "(", "'jsonTest is not defined'", ")", "}", "// define the defaults", "const", "defaults", "=", "{", "isNot", ":", "false", ",", "path", ":", "undefined", ",", "// jsonBody will be present", "// jsonTest will be present", "}", "// merge the passed in values with the defaults", "return", "_", ".", "merge", "(", "defaults", ",", "check", ")", "}" ]
performs a setup operation by checking the input data and merging the input data with a set of defaults returns the result of merging the default options and the input data
[ "performs", "a", "setup", "operation", "by", "checking", "the", "input", "data", "and", "merging", "the", "input", "data", "with", "a", "set", "of", "defaults", "returns", "the", "result", "of", "merging", "the", "default", "options", "and", "the", "input", "data" ]
ac152b715623fda078116d0963c5b391a9be51a4
https://github.com/IcedFrisby/IcedFrisby/blob/ac152b715623fda078116d0963c5b391a9be51a4/lib/pathMatch.js#L16-L35
21,152
IcedFrisby/IcedFrisby
lib/pathMatch.js
function(jsonBody, lengthSegments) { let len = 0 if (_.isObject(jsonBody)) { len = Object.keys(jsonBody).length } else { len = jsonBody.length } let msg // message for expectation result //TODO: in the future, use expect(jsonBody).to.have.length.below(lengthSegments.count + 1); or similar for non-objects to get better assertion messages switch (lengthSegments.sign) { case '<=': msg = 'Expected length to be less than or equal to ' + lengthSegments.count + ', but got ' + len expect(len).to.be.lessThan(lengthSegments.count + 1, msg) break case '<': msg = 'Expected length to be less than ' + lengthSegments.count + ', but got ' + len expect(len).to.be.lessThan(lengthSegments.count, msg) break case '>=': msg = 'Expected length to be greater than or equal ' + lengthSegments.count + ', but got ' + len expect(len).to.be.greaterThan(lengthSegments.count - 1, msg) break case '>': msg = 'Expected length to be greater than ' + lengthSegments.count + ', but got ' + len expect(len).to.be.greaterThan(lengthSegments.count, msg) break case null: msg = 'Expected length to be ' + lengthSegments.count + ', but got ' + len expect(len).to.equal(lengthSegments.count, msg) break } //end switch }
javascript
function(jsonBody, lengthSegments) { let len = 0 if (_.isObject(jsonBody)) { len = Object.keys(jsonBody).length } else { len = jsonBody.length } let msg // message for expectation result //TODO: in the future, use expect(jsonBody).to.have.length.below(lengthSegments.count + 1); or similar for non-objects to get better assertion messages switch (lengthSegments.sign) { case '<=': msg = 'Expected length to be less than or equal to ' + lengthSegments.count + ', but got ' + len expect(len).to.be.lessThan(lengthSegments.count + 1, msg) break case '<': msg = 'Expected length to be less than ' + lengthSegments.count + ', but got ' + len expect(len).to.be.lessThan(lengthSegments.count, msg) break case '>=': msg = 'Expected length to be greater than or equal ' + lengthSegments.count + ', but got ' + len expect(len).to.be.greaterThan(lengthSegments.count - 1, msg) break case '>': msg = 'Expected length to be greater than ' + lengthSegments.count + ', but got ' + len expect(len).to.be.greaterThan(lengthSegments.count, msg) break case null: msg = 'Expected length to be ' + lengthSegments.count + ', but got ' + len expect(len).to.equal(lengthSegments.count, msg) break } //end switch }
[ "function", "(", "jsonBody", ",", "lengthSegments", ")", "{", "let", "len", "=", "0", "if", "(", "_", ".", "isObject", "(", "jsonBody", ")", ")", "{", "len", "=", "Object", ".", "keys", "(", "jsonBody", ")", ".", "length", "}", "else", "{", "len", "=", "jsonBody", ".", "length", "}", "let", "msg", "// message for expectation result", "//TODO: in the future, use expect(jsonBody).to.have.length.below(lengthSegments.count + 1); or similar for non-objects to get better assertion messages", "switch", "(", "lengthSegments", ".", "sign", ")", "{", "case", "'<='", ":", "msg", "=", "'Expected length to be less than or equal to '", "+", "lengthSegments", ".", "count", "+", "', but got '", "+", "len", "expect", "(", "len", ")", ".", "to", ".", "be", ".", "lessThan", "(", "lengthSegments", ".", "count", "+", "1", ",", "msg", ")", "break", "case", "'<'", ":", "msg", "=", "'Expected length to be less than '", "+", "lengthSegments", ".", "count", "+", "', but got '", "+", "len", "expect", "(", "len", ")", ".", "to", ".", "be", ".", "lessThan", "(", "lengthSegments", ".", "count", ",", "msg", ")", "break", "case", "'>='", ":", "msg", "=", "'Expected length to be greater than or equal '", "+", "lengthSegments", ".", "count", "+", "', but got '", "+", "len", "expect", "(", "len", ")", ".", "to", ".", "be", ".", "greaterThan", "(", "lengthSegments", ".", "count", "-", "1", ",", "msg", ")", "break", "case", "'>'", ":", "msg", "=", "'Expected length to be greater than '", "+", "lengthSegments", ".", "count", "+", "', but got '", "+", "len", "expect", "(", "len", ")", ".", "to", ".", "be", ".", "greaterThan", "(", "lengthSegments", ".", "count", ",", "msg", ")", "break", "case", "null", ":", "msg", "=", "'Expected length to be '", "+", "lengthSegments", ".", "count", "+", "', but got '", "+", "len", "expect", "(", "len", ")", ".", "to", ".", "equal", "(", "lengthSegments", ".", "count", ",", "msg", ")", "break", "}", "//end switch", "}" ]
expect length function for matchJSONLength that does the comparison operations
[ "expect", "length", "function", "for", "matchJSONLength", "that", "does", "the", "comparison", "operations" ]
ac152b715623fda078116d0963c5b391a9be51a4
https://github.com/IcedFrisby/IcedFrisby/blob/ac152b715623fda078116d0963c5b391a9be51a4/lib/pathMatch.js#L503-L552
21,153
IcedFrisby/IcedFrisby
lib/icedfrisby.js
_jsonParse
function _jsonParse(body) { let json = '' try { json = typeof body === 'object' ? body : JSON.parse(body) } catch (e) { throw new Error( 'Error parsing JSON string: ' + e.message + '\n\tGiven: ' + body ) } return json }
javascript
function _jsonParse(body) { let json = '' try { json = typeof body === 'object' ? body : JSON.parse(body) } catch (e) { throw new Error( 'Error parsing JSON string: ' + e.message + '\n\tGiven: ' + body ) } return json }
[ "function", "_jsonParse", "(", "body", ")", "{", "let", "json", "=", "''", "try", "{", "json", "=", "typeof", "body", "===", "'object'", "?", "body", ":", "JSON", ".", "parse", "(", "body", ")", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "'Error parsing JSON string: '", "+", "e", ".", "message", "+", "'\\n\\tGiven: '", "+", "body", ")", "}", "return", "json", "}" ]
Parse body as JSON, ensuring not to re-parse when body is already an object (thanks @dcaylor). @param {object} body - json object @return {object} @desc parse response body as json
[ "Parse", "body", "as", "JSON", "ensuring", "not", "to", "re", "-", "parse", "when", "body", "is", "already", "an", "object", "(", "thanks" ]
ac152b715623fda078116d0963c5b391a9be51a4
https://github.com/IcedFrisby/IcedFrisby/blob/ac152b715623fda078116d0963c5b391a9be51a4/lib/icedfrisby.js#L55-L65
21,154
artsy/scroll-frame
scroll-frame.js
function(url) { var prevHref = location.href; var prevTitle = document.title; // Change the history history.pushState({ scrollFrame: true, href: location.href }, '', url); // Create the wrapper & iframe modal var body = document.getElementsByTagName('body')[0]; var iOS = navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false; var attributes = [ 'position: fixed', 'top: 0', 'left: 0','width: 100%', 'height: 100%', 'z-index: 10000000', 'background-color: white', 'border: 0' ]; //only add scrolling fix for ios devices if (iOS){ attributes.push('overflow-y: scroll'); attributes.push('-webkit-overflow-scrolling: touch'); } //create wrapper for iOS scroll fix var wrapper = document.createElement("div"); wrapper.setAttribute('style',attributes.join(';')); var iframe = document.createElement("iframe"); iframe.className = 'scroll-frame-iframe' iframe.setAttribute('style', [ 'width: 100%', 'height: 100%', 'position:absolute', 'border: 0' ].join(';')); // Lock the body from scrolling & hide the body's scroll bars. body.setAttribute('style', 'overflow: hidden;' + (body.getAttribute('style') || '')); // Add a class to the body while the iframe loads then append it body.className += ' scroll-frame-loading'; iframe.onload = function() { body.className = body.className.replace(' scroll-frame-loading', ''); document.title = iframe.contentDocument.title; } wrapper.appendChild(iframe); body.appendChild(wrapper); iframe.contentWindow.location.replace(url); // On back-button remove the wrapper var onPopState = function(e) { if (location.href != prevHref) return; wrapper.removeChild(iframe); document.title = prevTitle; body.removeChild(wrapper); body.setAttribute('style', body.getAttribute('style').replace('overflow: hidden;', '')); removeEventListener('popstate', onPopState); } addEventListener('popstate', onPopState); }
javascript
function(url) { var prevHref = location.href; var prevTitle = document.title; // Change the history history.pushState({ scrollFrame: true, href: location.href }, '', url); // Create the wrapper & iframe modal var body = document.getElementsByTagName('body')[0]; var iOS = navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false; var attributes = [ 'position: fixed', 'top: 0', 'left: 0','width: 100%', 'height: 100%', 'z-index: 10000000', 'background-color: white', 'border: 0' ]; //only add scrolling fix for ios devices if (iOS){ attributes.push('overflow-y: scroll'); attributes.push('-webkit-overflow-scrolling: touch'); } //create wrapper for iOS scroll fix var wrapper = document.createElement("div"); wrapper.setAttribute('style',attributes.join(';')); var iframe = document.createElement("iframe"); iframe.className = 'scroll-frame-iframe' iframe.setAttribute('style', [ 'width: 100%', 'height: 100%', 'position:absolute', 'border: 0' ].join(';')); // Lock the body from scrolling & hide the body's scroll bars. body.setAttribute('style', 'overflow: hidden;' + (body.getAttribute('style') || '')); // Add a class to the body while the iframe loads then append it body.className += ' scroll-frame-loading'; iframe.onload = function() { body.className = body.className.replace(' scroll-frame-loading', ''); document.title = iframe.contentDocument.title; } wrapper.appendChild(iframe); body.appendChild(wrapper); iframe.contentWindow.location.replace(url); // On back-button remove the wrapper var onPopState = function(e) { if (location.href != prevHref) return; wrapper.removeChild(iframe); document.title = prevTitle; body.removeChild(wrapper); body.setAttribute('style', body.getAttribute('style').replace('overflow: hidden;', '')); removeEventListener('popstate', onPopState); } addEventListener('popstate', onPopState); }
[ "function", "(", "url", ")", "{", "var", "prevHref", "=", "location", ".", "href", ";", "var", "prevTitle", "=", "document", ".", "title", ";", "// Change the history", "history", ".", "pushState", "(", "{", "scrollFrame", ":", "true", ",", "href", ":", "location", ".", "href", "}", ",", "''", ",", "url", ")", ";", "// Create the wrapper & iframe modal", "var", "body", "=", "document", ".", "getElementsByTagName", "(", "'body'", ")", "[", "0", "]", ";", "var", "iOS", "=", "navigator", ".", "userAgent", ".", "match", "(", "/", "(iPad|iPhone|iPod)", "/", "g", ")", "?", "true", ":", "false", ";", "var", "attributes", "=", "[", "'position: fixed'", ",", "'top: 0'", ",", "'left: 0'", ",", "'width: 100%'", ",", "'height: 100%'", ",", "'z-index: 10000000'", ",", "'background-color: white'", ",", "'border: 0'", "]", ";", "//only add scrolling fix for ios devices", "if", "(", "iOS", ")", "{", "attributes", ".", "push", "(", "'overflow-y: scroll'", ")", ";", "attributes", ".", "push", "(", "'-webkit-overflow-scrolling: touch'", ")", ";", "}", "//create wrapper for iOS scroll fix", "var", "wrapper", "=", "document", ".", "createElement", "(", "\"div\"", ")", ";", "wrapper", ".", "setAttribute", "(", "'style'", ",", "attributes", ".", "join", "(", "';'", ")", ")", ";", "var", "iframe", "=", "document", ".", "createElement", "(", "\"iframe\"", ")", ";", "iframe", ".", "className", "=", "'scroll-frame-iframe'", "iframe", ".", "setAttribute", "(", "'style'", ",", "[", "'width: 100%'", ",", "'height: 100%'", ",", "'position:absolute'", ",", "'border: 0'", "]", ".", "join", "(", "';'", ")", ")", ";", "// Lock the body from scrolling & hide the body's scroll bars.", "body", ".", "setAttribute", "(", "'style'", ",", "'overflow: hidden;'", "+", "(", "body", ".", "getAttribute", "(", "'style'", ")", "||", "''", ")", ")", ";", "// Add a class to the body while the iframe loads then append it", "body", ".", "className", "+=", "' scroll-frame-loading'", ";", "iframe", ".", "onload", "=", "function", "(", ")", "{", "body", ".", "className", "=", "body", ".", "className", ".", "replace", "(", "' scroll-frame-loading'", ",", "''", ")", ";", "document", ".", "title", "=", "iframe", ".", "contentDocument", ".", "title", ";", "}", "wrapper", ".", "appendChild", "(", "iframe", ")", ";", "body", ".", "appendChild", "(", "wrapper", ")", ";", "iframe", ".", "contentWindow", ".", "location", ".", "replace", "(", "url", ")", ";", "// On back-button remove the wrapper", "var", "onPopState", "=", "function", "(", "e", ")", "{", "if", "(", "location", ".", "href", "!=", "prevHref", ")", "return", ";", "wrapper", ".", "removeChild", "(", "iframe", ")", ";", "document", ".", "title", "=", "prevTitle", ";", "body", ".", "removeChild", "(", "wrapper", ")", ";", "body", ".", "setAttribute", "(", "'style'", ",", "body", ".", "getAttribute", "(", "'style'", ")", ".", "replace", "(", "'overflow: hidden;'", ",", "''", ")", ")", ";", "removeEventListener", "(", "'popstate'", ",", "onPopState", ")", ";", "}", "addEventListener", "(", "'popstate'", ",", "onPopState", ")", ";", "}" ]
Change pushState and open the iframe modal pointing to this url. @param {String} url
[ "Change", "pushState", "and", "open", "the", "iframe", "modal", "pointing", "to", "this", "url", "." ]
f95bff6dfe0295696daeae1949c84c7f36369d9a
https://github.com/artsy/scroll-frame/blob/f95bff6dfe0295696daeae1949c84c7f36369d9a/scroll-frame.js#L38-L93
21,155
artsy/scroll-frame
scroll-frame.js
function(e) { if (location.href != prevHref) return; wrapper.removeChild(iframe); document.title = prevTitle; body.removeChild(wrapper); body.setAttribute('style', body.getAttribute('style').replace('overflow: hidden;', '')); removeEventListener('popstate', onPopState); }
javascript
function(e) { if (location.href != prevHref) return; wrapper.removeChild(iframe); document.title = prevTitle; body.removeChild(wrapper); body.setAttribute('style', body.getAttribute('style').replace('overflow: hidden;', '')); removeEventListener('popstate', onPopState); }
[ "function", "(", "e", ")", "{", "if", "(", "location", ".", "href", "!=", "prevHref", ")", "return", ";", "wrapper", ".", "removeChild", "(", "iframe", ")", ";", "document", ".", "title", "=", "prevTitle", ";", "body", ".", "removeChild", "(", "wrapper", ")", ";", "body", ".", "setAttribute", "(", "'style'", ",", "body", ".", "getAttribute", "(", "'style'", ")", ".", "replace", "(", "'overflow: hidden;'", ",", "''", ")", ")", ";", "removeEventListener", "(", "'popstate'", ",", "onPopState", ")", ";", "}" ]
On back-button remove the wrapper
[ "On", "back", "-", "button", "remove", "the", "wrapper" ]
f95bff6dfe0295696daeae1949c84c7f36369d9a
https://github.com/artsy/scroll-frame/blob/f95bff6dfe0295696daeae1949c84c7f36369d9a/scroll-frame.js#L83-L91
21,156
Zlobin/es-event-emitter
src/event-emitter.js
internal
function internal(obj) { if (!privateMap.has(obj)) { privateMap.set(obj, {}); } return privateMap.get(obj); }
javascript
function internal(obj) { if (!privateMap.has(obj)) { privateMap.set(obj, {}); } return privateMap.get(obj); }
[ "function", "internal", "(", "obj", ")", "{", "if", "(", "!", "privateMap", ".", "has", "(", "obj", ")", ")", "{", "privateMap", ".", "set", "(", "obj", ",", "{", "}", ")", ";", "}", "return", "privateMap", ".", "get", "(", "obj", ")", ";", "}" ]
For making private properties.
[ "For", "making", "private", "properties", "." ]
6f86b7052402e78dd7cfb26f7d44b105cd81617a
https://github.com/Zlobin/es-event-emitter/blob/6f86b7052402e78dd7cfb26f7d44b105cd81617a/src/event-emitter.js#L6-L12
21,157
WebReflection/ie8
build/ie8.max.js
function (object, descriptors) { for(var key in descriptors) { if (hasOwnProperty.call(descriptors, key)) { try { defineProperty(object, key, descriptors[key]); } catch(o_O) { if (window.console) { console.log(key + ' failed on object:', object, o_O.message); } } } } }
javascript
function (object, descriptors) { for(var key in descriptors) { if (hasOwnProperty.call(descriptors, key)) { try { defineProperty(object, key, descriptors[key]); } catch(o_O) { if (window.console) { console.log(key + ' failed on object:', object, o_O.message); } } } } }
[ "function", "(", "object", ",", "descriptors", ")", "{", "for", "(", "var", "key", "in", "descriptors", ")", "{", "if", "(", "hasOwnProperty", ".", "call", "(", "descriptors", ",", "key", ")", ")", "{", "try", "{", "defineProperty", "(", "object", ",", "key", ",", "descriptors", "[", "key", "]", ")", ";", "}", "catch", "(", "o_O", ")", "{", "if", "(", "window", ".", "console", ")", "{", "console", ".", "log", "(", "key", "+", "' failed on object:'", ",", "object", ",", "o_O", ".", "message", ")", ";", "}", "}", "}", "}", "}" ]
IE8 implemented defineProperty but not the plural...
[ "IE8", "implemented", "defineProperty", "but", "not", "the", "plural", "..." ]
0867473f3379729061764a72e8df2ff25adb303e
https://github.com/WebReflection/ie8/blob/0867473f3379729061764a72e8df2ff25adb303e/build/ie8.max.js#L40-L52
21,158
airbrake/node-airbrake
lib/truncator.js
truncateObj
function truncateObj(obj, level) { var dst = {}; for (var attr in obj) { if (Object.prototype.hasOwnProperty.call(obj, attr)) { dst[attr] = module.exports.truncate(obj[attr], level); } } return dst; }
javascript
function truncateObj(obj, level) { var dst = {}; for (var attr in obj) { if (Object.prototype.hasOwnProperty.call(obj, attr)) { dst[attr] = module.exports.truncate(obj[attr], level); } } return dst; }
[ "function", "truncateObj", "(", "obj", ",", "level", ")", "{", "var", "dst", "=", "{", "}", ";", "for", "(", "var", "attr", "in", "obj", ")", "{", "if", "(", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "obj", ",", "attr", ")", ")", "{", "dst", "[", "attr", "]", "=", "module", ".", "exports", ".", "truncate", "(", "obj", "[", "attr", "]", ",", "level", ")", ";", "}", "}", "return", "dst", ";", "}" ]
truncateObj truncates each key in the object separately, which is useful for handling circular references.
[ "truncateObj", "truncates", "each", "key", "in", "the", "object", "separately", "which", "is", "useful", "for", "handling", "circular", "references", "." ]
24f76f5e73a5cbb379d6a512d980a4b7d608e61d
https://github.com/airbrake/node-airbrake/blob/24f76f5e73a5cbb379d6a512d980a4b7d608e61d/lib/truncator.js#L173-L182
21,159
jacomyal/emmett
emmett.js
shallowMerge
function shallowMerge(o1, o2) { var o = {}, k; for (k in o1) o[k] = o1[k]; for (k in o2) o[k] = o2[k]; return o; }
javascript
function shallowMerge(o1, o2) { var o = {}, k; for (k in o1) o[k] = o1[k]; for (k in o2) o[k] = o2[k]; return o; }
[ "function", "shallowMerge", "(", "o1", ",", "o2", ")", "{", "var", "o", "=", "{", "}", ",", "k", ";", "for", "(", "k", "in", "o1", ")", "o", "[", "k", "]", "=", "o1", "[", "k", "]", ";", "for", "(", "k", "in", "o2", ")", "o", "[", "k", "]", "=", "o2", "[", "k", "]", ";", "return", "o", ";", "}" ]
A simple helper to shallowly merge two objects. The second one will "win" over the first one. @param {object} o1 First target object. @param {object} o2 Second target object. @return {object} Returns the merged object.
[ "A", "simple", "helper", "to", "shallowly", "merge", "two", "objects", ".", "The", "second", "one", "will", "win", "over", "the", "first", "one", "." ]
5af501ff5bfe80d2859683e3547d293514fe3889
https://github.com/jacomyal/emmett/blob/5af501ff5bfe80d2859683e3547d293514fe3889/emmett.js#L26-L34
21,160
jacomyal/emmett
emmett.js
isPlainObject
function isPlainObject(v) { return v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Function) && !(v instanceof RegExp); }
javascript
function isPlainObject(v) { return v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Function) && !(v instanceof RegExp); }
[ "function", "isPlainObject", "(", "v", ")", "{", "return", "v", "&&", "typeof", "v", "===", "'object'", "&&", "!", "Array", ".", "isArray", "(", "v", ")", "&&", "!", "(", "v", "instanceof", "Function", ")", "&&", "!", "(", "v", "instanceof", "RegExp", ")", ";", "}" ]
Is the given variable a plain JavaScript object? @param {mixed} v Target. @return {boolean} The boolean result.
[ "Is", "the", "given", "variable", "a", "plain", "JavaScript", "object?" ]
5af501ff5bfe80d2859683e3547d293514fe3889
https://github.com/jacomyal/emmett/blob/5af501ff5bfe80d2859683e3547d293514fe3889/emmett.js#L42-L48
21,161
jacomyal/emmett
emmett.js
forIn
function forIn(object, fn, scope) { var symbols, k, i, l; for (k in object) fn.call(scope || null, k, object[k]); if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(object); for (i = 0, l = symbols.length; i < l; i++) fn.call(scope || null, symbols[i], object[symbols[i]]); } }
javascript
function forIn(object, fn, scope) { var symbols, k, i, l; for (k in object) fn.call(scope || null, k, object[k]); if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(object); for (i = 0, l = symbols.length; i < l; i++) fn.call(scope || null, symbols[i], object[symbols[i]]); } }
[ "function", "forIn", "(", "object", ",", "fn", ",", "scope", ")", "{", "var", "symbols", ",", "k", ",", "i", ",", "l", ";", "for", "(", "k", "in", "object", ")", "fn", ".", "call", "(", "scope", "||", "null", ",", "k", ",", "object", "[", "k", "]", ")", ";", "if", "(", "Object", ".", "getOwnPropertySymbols", ")", "{", "symbols", "=", "Object", ".", "getOwnPropertySymbols", "(", "object", ")", ";", "for", "(", "i", "=", "0", ",", "l", "=", "symbols", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "fn", ".", "call", "(", "scope", "||", "null", ",", "symbols", "[", "i", "]", ",", "object", "[", "symbols", "[", "i", "]", "]", ")", ";", "}", "}" ]
Iterate over an object that may have ES6 Symbols. @param {object} object Object on which to iterate. @param {function} fn Iterator function. @param {object} [scope] Optional scope.
[ "Iterate", "over", "an", "object", "that", "may", "have", "ES6", "Symbols", "." ]
5af501ff5bfe80d2859683e3547d293514fe3889
https://github.com/jacomyal/emmett/blob/5af501ff5bfe80d2859683e3547d293514fe3889/emmett.js#L57-L72
21,162
jacomyal/emmett
emmett.js
filter
function filter(target, fn) { target = target || []; var a = [], l, i; for (i = 0, l = target.length; i < l; i++) if (target[i].fn !== fn) a.push(target[i]); return a; }
javascript
function filter(target, fn) { target = target || []; var a = [], l, i; for (i = 0, l = target.length; i < l; i++) if (target[i].fn !== fn) a.push(target[i]); return a; }
[ "function", "filter", "(", "target", ",", "fn", ")", "{", "target", "=", "target", "||", "[", "]", ";", "var", "a", "=", "[", "]", ",", "l", ",", "i", ";", "for", "(", "i", "=", "0", ",", "l", "=", "target", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "if", "(", "target", "[", "i", "]", ".", "fn", "!==", "fn", ")", "a", ".", "push", "(", "target", "[", "i", "]", ")", ";", "return", "a", ";", "}" ]
This method unbinds one or more functions from events of the emitter. So, these functions will no more be executed when the related events are emitted. If the functions were not bound to the events, nothing will happen, and no error will be thrown. Variant 1: ********** > myEmitter.off('myEvent', myHandler); @param {string} event The event to unbind the handler from. @param {function} handler The function to unbind. @return {Emitter} Returns this. Variant 2: ********** > myEmitter.off(['myEvent1', 'myEvent2'], myHandler); @param {array} events The events to unbind the handler from. @param {function} handler The function to unbind. @return {Emitter} Returns this. Variant 3: ********** > myEmitter.off({ > myEvent1: myHandler1, > myEvent2: myHandler2 > }); @param {object} bindings An object containing pairs event / function. @return {Emitter} Returns this. Variant 4: ********** > myEmitter.off(myHandler); @param {function} handler The function to unbind from every events. @return {Emitter} Returns this. Variant 5: ********** > myEmitter.off(event); @param {string} event The event we should unbind. @return {Emitter} Returns this.
[ "This", "method", "unbinds", "one", "or", "more", "functions", "from", "events", "of", "the", "emitter", ".", "So", "these", "functions", "will", "no", "more", "be", "executed", "when", "the", "related", "events", "are", "emitted", ".", "If", "the", "functions", "were", "not", "bound", "to", "the", "events", "nothing", "will", "happen", "and", "no", "error", "will", "be", "thrown", "." ]
5af501ff5bfe80d2859683e3547d293514fe3889
https://github.com/jacomyal/emmett/blob/5af501ff5bfe80d2859683e3547d293514fe3889/emmett.js#L312-L324
21,163
metadevpro/baucis-openapi3
src/Controller.js
generateModelOpenApiSchema
function generateModelOpenApiSchema(schema, definitionName) { var oaSchema = { required: [], properties: {} }; mergePaths(oaSchema, schema.paths, definitionName); mergePaths(oaSchema, schema.virtuals, definitionName); //remove empty arrays -> OpenAPI 3.0 validates if (oaSchema.required.length === 0) { delete(oaSchema.required); } if (oaSchema.properties.length === 0) { delete(oaSchema.properties); } return oaSchema; }
javascript
function generateModelOpenApiSchema(schema, definitionName) { var oaSchema = { required: [], properties: {} }; mergePaths(oaSchema, schema.paths, definitionName); mergePaths(oaSchema, schema.virtuals, definitionName); //remove empty arrays -> OpenAPI 3.0 validates if (oaSchema.required.length === 0) { delete(oaSchema.required); } if (oaSchema.properties.length === 0) { delete(oaSchema.properties); } return oaSchema; }
[ "function", "generateModelOpenApiSchema", "(", "schema", ",", "definitionName", ")", "{", "var", "oaSchema", "=", "{", "required", ":", "[", "]", ",", "properties", ":", "{", "}", "}", ";", "mergePaths", "(", "oaSchema", ",", "schema", ".", "paths", ",", "definitionName", ")", ";", "mergePaths", "(", "oaSchema", ",", "schema", ".", "virtuals", ",", "definitionName", ")", ";", "//remove empty arrays -> OpenAPI 3.0 validates ", "if", "(", "oaSchema", ".", "required", ".", "length", "===", "0", ")", "{", "delete", "(", "oaSchema", ".", "required", ")", ";", "}", "if", "(", "oaSchema", ".", "properties", ".", "length", "===", "0", ")", "{", "delete", "(", "oaSchema", ".", "properties", ")", ";", "}", "return", "oaSchema", ";", "}" ]
A method used to generate an OpenAPI model schema for a controller
[ "A", "method", "used", "to", "generate", "an", "OpenAPI", "model", "schema", "for", "a", "controller" ]
d0076ecf0cd989043e26c7d4bec1343ec17bdc23
https://github.com/metadevpro/baucis-openapi3/blob/d0076ecf0cd989043e26c7d4bec1343ec17bdc23/src/Controller.js#L400-L416
21,164
metadevpro/baucis-openapi3
src/Api.js
generateResourceListing
function generateResourceListing(options) { var controllers = options.controllers; var opts = options.options || {}; var listing = { openapi: '3.0.0', info: buildInfo(opts), servers: opts.servers || buildDefaultServers(), tags: buildTags(opts, controllers), paths: buildPaths(opts, controllers), components: buildComponents(opts, controllers) }; mergeIn(listing.paths, opts.paths); if (opts.security) { listing.security = opts.security; } if (opts.externalDocs) { listing.externalDocs = opts.externalDocs; } return listing; }
javascript
function generateResourceListing(options) { var controllers = options.controllers; var opts = options.options || {}; var listing = { openapi: '3.0.0', info: buildInfo(opts), servers: opts.servers || buildDefaultServers(), tags: buildTags(opts, controllers), paths: buildPaths(opts, controllers), components: buildComponents(opts, controllers) }; mergeIn(listing.paths, opts.paths); if (opts.security) { listing.security = opts.security; } if (opts.externalDocs) { listing.externalDocs = opts.externalDocs; } return listing; }
[ "function", "generateResourceListing", "(", "options", ")", "{", "var", "controllers", "=", "options", ".", "controllers", ";", "var", "opts", "=", "options", ".", "options", "||", "{", "}", ";", "var", "listing", "=", "{", "openapi", ":", "'3.0.0'", ",", "info", ":", "buildInfo", "(", "opts", ")", ",", "servers", ":", "opts", ".", "servers", "||", "buildDefaultServers", "(", ")", ",", "tags", ":", "buildTags", "(", "opts", ",", "controllers", ")", ",", "paths", ":", "buildPaths", "(", "opts", ",", "controllers", ")", ",", "components", ":", "buildComponents", "(", "opts", ",", "controllers", ")", "}", ";", "mergeIn", "(", "listing", ".", "paths", ",", "opts", ".", "paths", ")", ";", "if", "(", "opts", ".", "security", ")", "{", "listing", ".", "security", "=", "opts", ".", "security", ";", "}", "if", "(", "opts", ".", "externalDocs", ")", "{", "listing", ".", "externalDocs", "=", "opts", ".", "externalDocs", ";", "}", "return", "listing", ";", "}" ]
A method for generating OpenAPI resource listing
[ "A", "method", "for", "generating", "OpenAPI", "resource", "listing" ]
d0076ecf0cd989043e26c7d4bec1343ec17bdc23
https://github.com/metadevpro/baucis-openapi3/blob/d0076ecf0cd989043e26c7d4bec1343ec17bdc23/src/Api.js#L98-L121
21,165
digitalsadhu/loopback-component-jsonapi
lib/patch.js
fixHttpMethod
function fixHttpMethod (fn, name) { if (fn.http && fn.http.verb && fn.http.verb.toLowerCase() === 'put') { fn.http.verb = 'patch' } }
javascript
function fixHttpMethod (fn, name) { if (fn.http && fn.http.verb && fn.http.verb.toLowerCase() === 'put') { fn.http.verb = 'patch' } }
[ "function", "fixHttpMethod", "(", "fn", ",", "name", ")", "{", "if", "(", "fn", ".", "http", "&&", "fn", ".", "http", ".", "verb", "&&", "fn", ".", "http", ".", "verb", ".", "toLowerCase", "(", ")", "===", "'put'", ")", "{", "fn", ".", "http", ".", "verb", "=", "'patch'", "}", "}" ]
Copied from loopbacks Model class. Changes `PUT` request to `PATCH` @private @memberOf {Patch} @param {Function} fn @param {String} name @return {undefined}
[ "Copied", "from", "loopbacks", "Model", "class", ".", "Changes", "PUT", "request", "to", "PATCH" ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/patch.js#L50-L54
21,166
digitalsadhu/loopback-component-jsonapi
lib/patch.js
convertNullToNotFoundError
function convertNullToNotFoundError (toModelName, ctx, cb) { if (ctx.result !== null) return cb() var fk = ctx.getArgByName('fk') var msg = 'Unknown "' + toModelName + '" id "' + fk + '".' var error = new Error(msg) error.statusCode = error.status = statusCodes.NOT_FOUND error.code = 'MODEL_NOT_FOUND' cb(error) }
javascript
function convertNullToNotFoundError (toModelName, ctx, cb) { if (ctx.result !== null) return cb() var fk = ctx.getArgByName('fk') var msg = 'Unknown "' + toModelName + '" id "' + fk + '".' var error = new Error(msg) error.statusCode = error.status = statusCodes.NOT_FOUND error.code = 'MODEL_NOT_FOUND' cb(error) }
[ "function", "convertNullToNotFoundError", "(", "toModelName", ",", "ctx", ",", "cb", ")", "{", "if", "(", "ctx", ".", "result", "!==", "null", ")", "return", "cb", "(", ")", "var", "fk", "=", "ctx", ".", "getArgByName", "(", "'fk'", ")", "var", "msg", "=", "'Unknown \"'", "+", "toModelName", "+", "'\" id \"'", "+", "fk", "+", "'\".'", "var", "error", "=", "new", "Error", "(", "msg", ")", "error", ".", "statusCode", "=", "error", ".", "status", "=", "statusCodes", ".", "NOT_FOUND", "error", ".", "code", "=", "'MODEL_NOT_FOUND'", "cb", "(", "error", ")", "}" ]
Copied in its entirity from loopbacks Model class. it was necessary to do so as this function is used in the other code below
[ "Copied", "in", "its", "entirity", "from", "loopbacks", "Model", "class", ".", "it", "was", "necessary", "to", "do", "so", "as", "this", "function", "is", "used", "in", "the", "other", "code", "below" ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/patch.js#L61-L70
21,167
digitalsadhu/loopback-component-jsonapi
lib/patch.js
hasOneRemoting
function hasOneRemoting (relationName, relation, define) { var pathName = (relation.options.http && relation.options.http.path) || relationName var toModelName = relation.modelTo.modelName define('__get__' + relationName, { isStatic: false, accessType: 'READ', description: 'Fetches hasOne relation ' + relationName + '.', http: { verb: 'get', path: '/' + pathName }, accepts: { arg: 'refresh', type: 'boolean', http: { source: 'query' } }, returns: { arg: relationName, type: relation.modelTo.modelName, root: true } }) var findHasOneRelationshipsFunc = function (cb) { this['__get__' + pathName](cb) } define( '__findRelationships__' + relationName, { isStatic: false, accessType: 'READ', description: 'Find relations for ' + relationName + '.', http: { verb: 'get', path: '/relationships/' + pathName }, returns: { arg: 'result', type: toModelName, root: true } }, findHasOneRelationshipsFunc ) }
javascript
function hasOneRemoting (relationName, relation, define) { var pathName = (relation.options.http && relation.options.http.path) || relationName var toModelName = relation.modelTo.modelName define('__get__' + relationName, { isStatic: false, accessType: 'READ', description: 'Fetches hasOne relation ' + relationName + '.', http: { verb: 'get', path: '/' + pathName }, accepts: { arg: 'refresh', type: 'boolean', http: { source: 'query' } }, returns: { arg: relationName, type: relation.modelTo.modelName, root: true } }) var findHasOneRelationshipsFunc = function (cb) { this['__get__' + pathName](cb) } define( '__findRelationships__' + relationName, { isStatic: false, accessType: 'READ', description: 'Find relations for ' + relationName + '.', http: { verb: 'get', path: '/relationships/' + pathName }, returns: { arg: 'result', type: toModelName, root: true } }, findHasOneRelationshipsFunc ) }
[ "function", "hasOneRemoting", "(", "relationName", ",", "relation", ",", "define", ")", "{", "var", "pathName", "=", "(", "relation", ".", "options", ".", "http", "&&", "relation", ".", "options", ".", "http", ".", "path", ")", "||", "relationName", "var", "toModelName", "=", "relation", ".", "modelTo", ".", "modelName", "define", "(", "'__get__'", "+", "relationName", ",", "{", "isStatic", ":", "false", ",", "accessType", ":", "'READ'", ",", "description", ":", "'Fetches hasOne relation '", "+", "relationName", "+", "'.'", ",", "http", ":", "{", "verb", ":", "'get'", ",", "path", ":", "'/'", "+", "pathName", "}", ",", "accepts", ":", "{", "arg", ":", "'refresh'", ",", "type", ":", "'boolean'", ",", "http", ":", "{", "source", ":", "'query'", "}", "}", ",", "returns", ":", "{", "arg", ":", "relationName", ",", "type", ":", "relation", ".", "modelTo", ".", "modelName", ",", "root", ":", "true", "}", "}", ")", "var", "findHasOneRelationshipsFunc", "=", "function", "(", "cb", ")", "{", "this", "[", "'__get__'", "+", "pathName", "]", "(", "cb", ")", "}", "define", "(", "'__findRelationships__'", "+", "relationName", ",", "{", "isStatic", ":", "false", ",", "accessType", ":", "'READ'", ",", "description", ":", "'Find relations for '", "+", "relationName", "+", "'.'", ",", "http", ":", "{", "verb", ":", "'get'", ",", "path", ":", "'/relationships/'", "+", "pathName", "}", ",", "returns", ":", "{", "arg", ":", "'result'", ",", "type", ":", "toModelName", ",", "root", ":", "true", "}", "}", ",", "findHasOneRelationshipsFunc", ")", "}" ]
Defines has one remoting. @public @memberOf {Patch} @param {String} relationName @param {Object} relation @param {Function} define @return {undefined}
[ "Defines", "has", "one", "remoting", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/patch.js#L138-L187
21,168
digitalsadhu/loopback-component-jsonapi
lib/patch.js
hasManyRemoting
function hasManyRemoting (relationName, relation, define) { var pathName = (relation.options.http && relation.options.http.path) || relationName var toModelName = relation.modelTo.modelName var findHasManyRelationshipsFunc = function (cb) { this['__get__' + pathName](cb) } define( '__findRelationships__' + relationName, { isStatic: false, accessType: 'READ', description: 'Find relations for ' + relationName + '.', http: { verb: 'get', path: '/relationships/' + pathName }, returns: { arg: 'result', type: toModelName, root: true }, rest: { after: convertNullToNotFoundError.bind(null, toModelName) } }, findHasManyRelationshipsFunc ) // var createRelationshipFunc = function (cb) { // TODO: implement this // this is where we need to implement // POST /:model/:id/relationships/:relatedModel // // this['__get__' + pathName](cb) // } // define('__createRelationships__' + relationName, { // isStatic: false, // accessType: 'READ', // description: 'Create relations for ' + relationName + '.', // http: { // verb: 'post', // path: '/relationships/' + pathName // }, // returns: { // arg: 'result', // type: toModelName, // root: true // }, // rest: { // after: convertNullToNotFoundError.bind(null, toModelName) // } // }, createRelationshipFunc) // var updateRelationshipsFunc = function (cb) { // TODO: implement this // this is where we need to implement // PATCH /:model/:id/relationships/:relatedModel // // this['__get__' + pathName](cb) // } // define('__updateRelationships__' + relationName, { // isStatic: false, // accessType: 'READ', // description: 'Update relations for ' + relationName + '.', // http: { // verb: 'patch', // path: '/relationships/' + pathName // }, // returns: { // arg: 'result', // type: toModelName, // root: true // }, // rest: { // after: convertNullToNotFoundError.bind(null, toModelName) // } // }, updateRelationshipsFunc) // var deleteRelationshipsFunc = function (cb) { // TODO: implement this // this is where we need to implement // DELETE /:model/:id/relationships/:relatedModel // // this['__get__' + pathName](cb) // } // define('__deleteRelationships__' + relationName, { // isStatic: false, // accessType: 'READ', // description: 'Delete relations for ' + relationName + '.', // http: { // verb: 'delete', // path: '/relationships/' + pathName // }, // returns: { // arg: 'result', // type: toModelName, // root: true // }, // rest: { // after: convertNullToNotFoundError.bind(null, toModelName) // } // }, deleteRelationshipsFunc) if (relation.modelThrough || relation.type === 'referencesMany') { var modelThrough = relation.modelThrough || relation.modelTo var accepts = [] if (relation.type === 'hasMany' && relation.modelThrough) { // Restrict: only hasManyThrough relation can have additional properties accepts.push({ arg: 'data', type: modelThrough.modelName, http: { source: 'body' } }) } } }
javascript
function hasManyRemoting (relationName, relation, define) { var pathName = (relation.options.http && relation.options.http.path) || relationName var toModelName = relation.modelTo.modelName var findHasManyRelationshipsFunc = function (cb) { this['__get__' + pathName](cb) } define( '__findRelationships__' + relationName, { isStatic: false, accessType: 'READ', description: 'Find relations for ' + relationName + '.', http: { verb: 'get', path: '/relationships/' + pathName }, returns: { arg: 'result', type: toModelName, root: true }, rest: { after: convertNullToNotFoundError.bind(null, toModelName) } }, findHasManyRelationshipsFunc ) // var createRelationshipFunc = function (cb) { // TODO: implement this // this is where we need to implement // POST /:model/:id/relationships/:relatedModel // // this['__get__' + pathName](cb) // } // define('__createRelationships__' + relationName, { // isStatic: false, // accessType: 'READ', // description: 'Create relations for ' + relationName + '.', // http: { // verb: 'post', // path: '/relationships/' + pathName // }, // returns: { // arg: 'result', // type: toModelName, // root: true // }, // rest: { // after: convertNullToNotFoundError.bind(null, toModelName) // } // }, createRelationshipFunc) // var updateRelationshipsFunc = function (cb) { // TODO: implement this // this is where we need to implement // PATCH /:model/:id/relationships/:relatedModel // // this['__get__' + pathName](cb) // } // define('__updateRelationships__' + relationName, { // isStatic: false, // accessType: 'READ', // description: 'Update relations for ' + relationName + '.', // http: { // verb: 'patch', // path: '/relationships/' + pathName // }, // returns: { // arg: 'result', // type: toModelName, // root: true // }, // rest: { // after: convertNullToNotFoundError.bind(null, toModelName) // } // }, updateRelationshipsFunc) // var deleteRelationshipsFunc = function (cb) { // TODO: implement this // this is where we need to implement // DELETE /:model/:id/relationships/:relatedModel // // this['__get__' + pathName](cb) // } // define('__deleteRelationships__' + relationName, { // isStatic: false, // accessType: 'READ', // description: 'Delete relations for ' + relationName + '.', // http: { // verb: 'delete', // path: '/relationships/' + pathName // }, // returns: { // arg: 'result', // type: toModelName, // root: true // }, // rest: { // after: convertNullToNotFoundError.bind(null, toModelName) // } // }, deleteRelationshipsFunc) if (relation.modelThrough || relation.type === 'referencesMany') { var modelThrough = relation.modelThrough || relation.modelTo var accepts = [] if (relation.type === 'hasMany' && relation.modelThrough) { // Restrict: only hasManyThrough relation can have additional properties accepts.push({ arg: 'data', type: modelThrough.modelName, http: { source: 'body' } }) } } }
[ "function", "hasManyRemoting", "(", "relationName", ",", "relation", ",", "define", ")", "{", "var", "pathName", "=", "(", "relation", ".", "options", ".", "http", "&&", "relation", ".", "options", ".", "http", ".", "path", ")", "||", "relationName", "var", "toModelName", "=", "relation", ".", "modelTo", ".", "modelName", "var", "findHasManyRelationshipsFunc", "=", "function", "(", "cb", ")", "{", "this", "[", "'__get__'", "+", "pathName", "]", "(", "cb", ")", "}", "define", "(", "'__findRelationships__'", "+", "relationName", ",", "{", "isStatic", ":", "false", ",", "accessType", ":", "'READ'", ",", "description", ":", "'Find relations for '", "+", "relationName", "+", "'.'", ",", "http", ":", "{", "verb", ":", "'get'", ",", "path", ":", "'/relationships/'", "+", "pathName", "}", ",", "returns", ":", "{", "arg", ":", "'result'", ",", "type", ":", "toModelName", ",", "root", ":", "true", "}", ",", "rest", ":", "{", "after", ":", "convertNullToNotFoundError", ".", "bind", "(", "null", ",", "toModelName", ")", "}", "}", ",", "findHasManyRelationshipsFunc", ")", "// var createRelationshipFunc = function (cb) {", "// TODO: implement this", "// this is where we need to implement", "// POST /:model/:id/relationships/:relatedModel", "//", "// this['__get__' + pathName](cb)", "// }", "// define('__createRelationships__' + relationName, {", "// isStatic: false,", "// accessType: 'READ',", "// description: 'Create relations for ' + relationName + '.',", "// http: {", "// verb: 'post',", "// path: '/relationships/' + pathName", "// },", "// returns: {", "// arg: 'result',", "// type: toModelName,", "// root: true", "// },", "// rest: {", "// after: convertNullToNotFoundError.bind(null, toModelName)", "// }", "// }, createRelationshipFunc)", "// var updateRelationshipsFunc = function (cb) {", "// TODO: implement this", "// this is where we need to implement", "// PATCH /:model/:id/relationships/:relatedModel", "//", "// this['__get__' + pathName](cb)", "// }", "// define('__updateRelationships__' + relationName, {", "// isStatic: false,", "// accessType: 'READ',", "// description: 'Update relations for ' + relationName + '.',", "// http: {", "// verb: 'patch',", "// path: '/relationships/' + pathName", "// },", "// returns: {", "// arg: 'result',", "// type: toModelName,", "// root: true", "// },", "// rest: {", "// after: convertNullToNotFoundError.bind(null, toModelName)", "// }", "// }, updateRelationshipsFunc)", "// var deleteRelationshipsFunc = function (cb) {", "// TODO: implement this", "// this is where we need to implement", "// DELETE /:model/:id/relationships/:relatedModel", "//", "// this['__get__' + pathName](cb)", "// }", "// define('__deleteRelationships__' + relationName, {", "// isStatic: false,", "// accessType: 'READ',", "// description: 'Delete relations for ' + relationName + '.',", "// http: {", "// verb: 'delete',", "// path: '/relationships/' + pathName", "// },", "// returns: {", "// arg: 'result',", "// type: toModelName,", "// root: true", "// },", "// rest: {", "// after: convertNullToNotFoundError.bind(null, toModelName)", "// }", "// }, deleteRelationshipsFunc)", "if", "(", "relation", ".", "modelThrough", "||", "relation", ".", "type", "===", "'referencesMany'", ")", "{", "var", "modelThrough", "=", "relation", ".", "modelThrough", "||", "relation", ".", "modelTo", "var", "accepts", "=", "[", "]", "if", "(", "relation", ".", "type", "===", "'hasMany'", "&&", "relation", ".", "modelThrough", ")", "{", "// Restrict: only hasManyThrough relation can have additional properties", "accepts", ".", "push", "(", "{", "arg", ":", "'data'", ",", "type", ":", "modelThrough", ".", "modelName", ",", "http", ":", "{", "source", ":", "'body'", "}", "}", ")", "}", "}", "}" ]
Defines has many remoting. @public @memberOf {Patch} @param {String} relationName @param {Object} relation @param {Function} define @return {undefined}
[ "Defines", "has", "many", "remoting", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/patch.js#L198-L319
21,169
digitalsadhu/loopback-component-jsonapi
lib/patch.js
scopeRemoting
function scopeRemoting (scopeName, scope, define) { var pathName = (scope.options && scope.options.http && scope.options.http.path) || scopeName var isStatic = scope.isStatic var toModelName = scope.modelTo.modelName // https://github.com/strongloop/loopback/issues/811 // Check if the scope is for a hasMany relation var relation = this.relations[scopeName] if (relation && relation.modelTo) { // For a relation with through model, the toModelName should be the one // from the target model toModelName = relation.modelTo.modelName } define('__get__' + scopeName, { isStatic: isStatic, accessType: 'READ', description: 'Queries ' + scopeName + ' of ' + this.modelName + '.', http: { verb: 'get', path: '/' + pathName }, accepts: { arg: 'filter', type: 'object' }, returns: { arg: scopeName, type: [toModelName], root: true } }) }
javascript
function scopeRemoting (scopeName, scope, define) { var pathName = (scope.options && scope.options.http && scope.options.http.path) || scopeName var isStatic = scope.isStatic var toModelName = scope.modelTo.modelName // https://github.com/strongloop/loopback/issues/811 // Check if the scope is for a hasMany relation var relation = this.relations[scopeName] if (relation && relation.modelTo) { // For a relation with through model, the toModelName should be the one // from the target model toModelName = relation.modelTo.modelName } define('__get__' + scopeName, { isStatic: isStatic, accessType: 'READ', description: 'Queries ' + scopeName + ' of ' + this.modelName + '.', http: { verb: 'get', path: '/' + pathName }, accepts: { arg: 'filter', type: 'object' }, returns: { arg: scopeName, type: [toModelName], root: true } }) }
[ "function", "scopeRemoting", "(", "scopeName", ",", "scope", ",", "define", ")", "{", "var", "pathName", "=", "(", "scope", ".", "options", "&&", "scope", ".", "options", ".", "http", "&&", "scope", ".", "options", ".", "http", ".", "path", ")", "||", "scopeName", "var", "isStatic", "=", "scope", ".", "isStatic", "var", "toModelName", "=", "scope", ".", "modelTo", ".", "modelName", "// https://github.com/strongloop/loopback/issues/811", "// Check if the scope is for a hasMany relation", "var", "relation", "=", "this", ".", "relations", "[", "scopeName", "]", "if", "(", "relation", "&&", "relation", ".", "modelTo", ")", "{", "// For a relation with through model, the toModelName should be the one", "// from the target model", "toModelName", "=", "relation", ".", "modelTo", ".", "modelName", "}", "define", "(", "'__get__'", "+", "scopeName", ",", "{", "isStatic", ":", "isStatic", ",", "accessType", ":", "'READ'", ",", "description", ":", "'Queries '", "+", "scopeName", "+", "' of '", "+", "this", ".", "modelName", "+", "'.'", ",", "http", ":", "{", "verb", ":", "'get'", ",", "path", ":", "'/'", "+", "pathName", "}", ",", "accepts", ":", "{", "arg", ":", "'filter'", ",", "type", ":", "'object'", "}", ",", "returns", ":", "{", "arg", ":", "scopeName", ",", "type", ":", "[", "toModelName", "]", ",", "root", ":", "true", "}", "}", ")", "}" ]
Defines our scope remoting @public @memberOf {Patch} @param {String} scopeName @param {Object} scope @param {Function} define @return {undefined}
[ "Defines", "our", "scope", "remoting" ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/patch.js#L330-L366
21,170
digitalsadhu/loopback-component-jsonapi
lib/errors.js
JSONAPIErrorHandler
function JSONAPIErrorHandler (err, req, res, next) { debug('Handling error(s) using custom jsonapi error handler') debug('Set Content-Type header to `application/vnd.api+json`') res.set('Content-Type', 'application/vnd.api+json') var errors = [] var statusCode = err.statusCode || err.status || statusCodes.INTERNAL_SERVER_ERROR debug('Raw error object:', err) if (err.details && err.details.messages) { debug('Handling error as a validation error.') // This block is for handling validation errors. // Build up an array of validation errors. errors = Object.keys(err.details.messages).map(function (key) { return buildErrorResponse( statusCode, err.details.messages[key][0], err.details.codes[key][0], err.name, { pointer: 'data/attributes/' + key } ) }) } else if (err.message) { // convert specific errors below to validation errors. // These errors are from checks on the incoming payload to ensure it is // JSON API compliant. If we switch to being able to use the Accept header // to decide whether to handle the request as JSON API, these errors would // need to only be applied when the Accept header is `application/vnd.api+json` var additionalValidationErrors = [ 'JSON API resource object must contain `data` property', 'JSON API resource object must contain `data.type` property', 'JSON API resource object must contain `data.id` property' ] if (additionalValidationErrors.indexOf(err.message) !== -1) { debug('Recasting error as a validation error.') statusCode = statusCodes.UNPROCESSABLE_ENTITY err.code = 'presence' err.name = 'ValidationError' } debug('Handling invalid relationship specified in url') if (/Relation (.*) is not defined for (.*) model/.test(err.message)) { statusCode = statusCodes.BAD_REQUEST err.message = 'Bad Request' err.code = 'INVALID_INCLUDE_TARGET' err.name = 'BadRequest' } var errorSource = err.source && typeof err.source === 'object' ? err.source : {} if (errorStackInResponse) { // We do not want to mutate err.source, so we clone it first errorSource = _.clone(errorSource) errorSource.stack = err.stack } errors.push( buildErrorResponse( statusCode, err.message, err.code, err.name, errorSource, err.meta ) ) } else { debug( 'Unable to determin error type. Treating error as a general 500 server error.' ) // catch all server 500 error if we were unable to understand the error. errors.push( buildErrorResponse( statusCodes.INTERNAL_SERVER_ERROR, 'Internal Server error', 'GENERAL_SERVER_ERROR' ) ) } // send the errors and close out the response. debug('Sending error response') debug('Response Code:', statusCode) debug('Response Object:', { errors: errors }) res.status(statusCode).send({ errors: errors }).end() }
javascript
function JSONAPIErrorHandler (err, req, res, next) { debug('Handling error(s) using custom jsonapi error handler') debug('Set Content-Type header to `application/vnd.api+json`') res.set('Content-Type', 'application/vnd.api+json') var errors = [] var statusCode = err.statusCode || err.status || statusCodes.INTERNAL_SERVER_ERROR debug('Raw error object:', err) if (err.details && err.details.messages) { debug('Handling error as a validation error.') // This block is for handling validation errors. // Build up an array of validation errors. errors = Object.keys(err.details.messages).map(function (key) { return buildErrorResponse( statusCode, err.details.messages[key][0], err.details.codes[key][0], err.name, { pointer: 'data/attributes/' + key } ) }) } else if (err.message) { // convert specific errors below to validation errors. // These errors are from checks on the incoming payload to ensure it is // JSON API compliant. If we switch to being able to use the Accept header // to decide whether to handle the request as JSON API, these errors would // need to only be applied when the Accept header is `application/vnd.api+json` var additionalValidationErrors = [ 'JSON API resource object must contain `data` property', 'JSON API resource object must contain `data.type` property', 'JSON API resource object must contain `data.id` property' ] if (additionalValidationErrors.indexOf(err.message) !== -1) { debug('Recasting error as a validation error.') statusCode = statusCodes.UNPROCESSABLE_ENTITY err.code = 'presence' err.name = 'ValidationError' } debug('Handling invalid relationship specified in url') if (/Relation (.*) is not defined for (.*) model/.test(err.message)) { statusCode = statusCodes.BAD_REQUEST err.message = 'Bad Request' err.code = 'INVALID_INCLUDE_TARGET' err.name = 'BadRequest' } var errorSource = err.source && typeof err.source === 'object' ? err.source : {} if (errorStackInResponse) { // We do not want to mutate err.source, so we clone it first errorSource = _.clone(errorSource) errorSource.stack = err.stack } errors.push( buildErrorResponse( statusCode, err.message, err.code, err.name, errorSource, err.meta ) ) } else { debug( 'Unable to determin error type. Treating error as a general 500 server error.' ) // catch all server 500 error if we were unable to understand the error. errors.push( buildErrorResponse( statusCodes.INTERNAL_SERVER_ERROR, 'Internal Server error', 'GENERAL_SERVER_ERROR' ) ) } // send the errors and close out the response. debug('Sending error response') debug('Response Code:', statusCode) debug('Response Object:', { errors: errors }) res.status(statusCode).send({ errors: errors }).end() }
[ "function", "JSONAPIErrorHandler", "(", "err", ",", "req", ",", "res", ",", "next", ")", "{", "debug", "(", "'Handling error(s) using custom jsonapi error handler'", ")", "debug", "(", "'Set Content-Type header to `application/vnd.api+json`'", ")", "res", ".", "set", "(", "'Content-Type'", ",", "'application/vnd.api+json'", ")", "var", "errors", "=", "[", "]", "var", "statusCode", "=", "err", ".", "statusCode", "||", "err", ".", "status", "||", "statusCodes", ".", "INTERNAL_SERVER_ERROR", "debug", "(", "'Raw error object:'", ",", "err", ")", "if", "(", "err", ".", "details", "&&", "err", ".", "details", ".", "messages", ")", "{", "debug", "(", "'Handling error as a validation error.'", ")", "// This block is for handling validation errors.", "// Build up an array of validation errors.", "errors", "=", "Object", ".", "keys", "(", "err", ".", "details", ".", "messages", ")", ".", "map", "(", "function", "(", "key", ")", "{", "return", "buildErrorResponse", "(", "statusCode", ",", "err", ".", "details", ".", "messages", "[", "key", "]", "[", "0", "]", ",", "err", ".", "details", ".", "codes", "[", "key", "]", "[", "0", "]", ",", "err", ".", "name", ",", "{", "pointer", ":", "'data/attributes/'", "+", "key", "}", ")", "}", ")", "}", "else", "if", "(", "err", ".", "message", ")", "{", "// convert specific errors below to validation errors.", "// These errors are from checks on the incoming payload to ensure it is", "// JSON API compliant. If we switch to being able to use the Accept header", "// to decide whether to handle the request as JSON API, these errors would", "// need to only be applied when the Accept header is `application/vnd.api+json`", "var", "additionalValidationErrors", "=", "[", "'JSON API resource object must contain `data` property'", ",", "'JSON API resource object must contain `data.type` property'", ",", "'JSON API resource object must contain `data.id` property'", "]", "if", "(", "additionalValidationErrors", ".", "indexOf", "(", "err", ".", "message", ")", "!==", "-", "1", ")", "{", "debug", "(", "'Recasting error as a validation error.'", ")", "statusCode", "=", "statusCodes", ".", "UNPROCESSABLE_ENTITY", "err", ".", "code", "=", "'presence'", "err", ".", "name", "=", "'ValidationError'", "}", "debug", "(", "'Handling invalid relationship specified in url'", ")", "if", "(", "/", "Relation (.*) is not defined for (.*) model", "/", ".", "test", "(", "err", ".", "message", ")", ")", "{", "statusCode", "=", "statusCodes", ".", "BAD_REQUEST", "err", ".", "message", "=", "'Bad Request'", "err", ".", "code", "=", "'INVALID_INCLUDE_TARGET'", "err", ".", "name", "=", "'BadRequest'", "}", "var", "errorSource", "=", "err", ".", "source", "&&", "typeof", "err", ".", "source", "===", "'object'", "?", "err", ".", "source", ":", "{", "}", "if", "(", "errorStackInResponse", ")", "{", "// We do not want to mutate err.source, so we clone it first", "errorSource", "=", "_", ".", "clone", "(", "errorSource", ")", "errorSource", ".", "stack", "=", "err", ".", "stack", "}", "errors", ".", "push", "(", "buildErrorResponse", "(", "statusCode", ",", "err", ".", "message", ",", "err", ".", "code", ",", "err", ".", "name", ",", "errorSource", ",", "err", ".", "meta", ")", ")", "}", "else", "{", "debug", "(", "'Unable to determin error type. Treating error as a general 500 server error.'", ")", "// catch all server 500 error if we were unable to understand the error.", "errors", ".", "push", "(", "buildErrorResponse", "(", "statusCodes", ".", "INTERNAL_SERVER_ERROR", ",", "'Internal Server error'", ",", "'GENERAL_SERVER_ERROR'", ")", ")", "}", "// send the errors and close out the response.", "debug", "(", "'Sending error response'", ")", "debug", "(", "'Response Code:'", ",", "statusCode", ")", "debug", "(", "'Response Object:'", ",", "{", "errors", ":", "errors", "}", ")", "res", ".", "status", "(", "statusCode", ")", ".", "send", "(", "{", "errors", ":", "errors", "}", ")", ".", "end", "(", ")", "}" ]
Our JSON API Error handler. @public @memberOf {Errors} @param {Object} err The error object @param {Object} req The request object @param {Object} res The response object @param {Function} next @return {undefined}
[ "Our", "JSON", "API", "Error", "handler", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/errors.js#L33-L123
21,171
digitalsadhu/loopback-component-jsonapi
lib/errors.js
buildErrorResponse
function buildErrorResponse ( httpStatusCode, errorDetail, errorCode, errorName, errorSource, errorMeta ) { var out = { status: httpStatusCode || statusCodes.INTERNAL_SERVER_ERROR, source: errorSource || {}, title: errorName || '', code: errorCode || '', detail: errorDetail || '' } if (errorMeta && typeof errorMeta === 'object') { out.meta = errorMeta } return out }
javascript
function buildErrorResponse ( httpStatusCode, errorDetail, errorCode, errorName, errorSource, errorMeta ) { var out = { status: httpStatusCode || statusCodes.INTERNAL_SERVER_ERROR, source: errorSource || {}, title: errorName || '', code: errorCode || '', detail: errorDetail || '' } if (errorMeta && typeof errorMeta === 'object') { out.meta = errorMeta } return out }
[ "function", "buildErrorResponse", "(", "httpStatusCode", ",", "errorDetail", ",", "errorCode", ",", "errorName", ",", "errorSource", ",", "errorMeta", ")", "{", "var", "out", "=", "{", "status", ":", "httpStatusCode", "||", "statusCodes", ".", "INTERNAL_SERVER_ERROR", ",", "source", ":", "errorSource", "||", "{", "}", ",", "title", ":", "errorName", "||", "''", ",", "code", ":", "errorCode", "||", "''", ",", "detail", ":", "errorDetail", "||", "''", "}", "if", "(", "errorMeta", "&&", "typeof", "errorMeta", "===", "'object'", ")", "{", "out", ".", "meta", "=", "errorMeta", "}", "return", "out", "}" ]
Builds an error object for sending to the user. @private @memberOf {Errors} @param {Number} httpStatusCode specific http status code @param {String} errorDetail error message for the user, human readable @param {String} errorCode internal system error code @param {String} errorName error title for the user, human readable @param {String} errorSource Some information about the source of the issue @param {String} errorMeta Some custom meta information to give to the error response @return {Object}
[ "Builds", "an", "error", "object", "for", "sending", "to", "the", "user", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/errors.js#L137-L158
21,172
digitalsadhu/loopback-component-jsonapi
lib/serializer.js
parseResource
function parseResource (type, data, relations, options) { var resource = {} var attributes = {} var relationships resource.type = type relationships = parseRelations(data, relations, options) if (!_.isEmpty(relationships)) { resource.relationships = relationships } if (options.foreignKeys !== true) { // Remove any foreign keys from this resource options.app.models().forEach(function (model) { _.each(model.relations, function (relation) { var fkModel = relation.modelTo var fkName = relation.keyTo if (utils.relationFkOnModelFrom(relation)) { fkModel = relation.modelFrom fkName = relation.keyFrom } if (fkModel === options.model && fkName !== options.primaryKeyField) { // check options and decide whether to remove foreign keys. if ( options.foreignKeys !== false && Array.isArray(options.foreignKeys) ) { for (var i = 0; i < options.foreignKeys.length; i++) { // if match on model if (options.foreignKeys[i].model === fkModel.sharedClass.name) { // if no method specified if (!options.foreignKeys[i].method) return // if method match if (options.foreignKeys[i].method === options.method) return } } } delete data[fkName] } }) }) } _.each(data, function (value, property) { if (property === options.primaryKeyField) { resource.id = _(value).toString() } else { if ( !options.attributes[type] || _.includes(options.attributes[type], property) ) { attributes[property] = value } } }) if (_.isUndefined(resource.id)) { return null } // if it's a relationship request if (options.isRelationshipRequest) { return resource } resource.attributes = attributes if (options.dataLinks) { resource.links = makeLinks(options.dataLinks, resource) } return resource }
javascript
function parseResource (type, data, relations, options) { var resource = {} var attributes = {} var relationships resource.type = type relationships = parseRelations(data, relations, options) if (!_.isEmpty(relationships)) { resource.relationships = relationships } if (options.foreignKeys !== true) { // Remove any foreign keys from this resource options.app.models().forEach(function (model) { _.each(model.relations, function (relation) { var fkModel = relation.modelTo var fkName = relation.keyTo if (utils.relationFkOnModelFrom(relation)) { fkModel = relation.modelFrom fkName = relation.keyFrom } if (fkModel === options.model && fkName !== options.primaryKeyField) { // check options and decide whether to remove foreign keys. if ( options.foreignKeys !== false && Array.isArray(options.foreignKeys) ) { for (var i = 0; i < options.foreignKeys.length; i++) { // if match on model if (options.foreignKeys[i].model === fkModel.sharedClass.name) { // if no method specified if (!options.foreignKeys[i].method) return // if method match if (options.foreignKeys[i].method === options.method) return } } } delete data[fkName] } }) }) } _.each(data, function (value, property) { if (property === options.primaryKeyField) { resource.id = _(value).toString() } else { if ( !options.attributes[type] || _.includes(options.attributes[type], property) ) { attributes[property] = value } } }) if (_.isUndefined(resource.id)) { return null } // if it's a relationship request if (options.isRelationshipRequest) { return resource } resource.attributes = attributes if (options.dataLinks) { resource.links = makeLinks(options.dataLinks, resource) } return resource }
[ "function", "parseResource", "(", "type", ",", "data", ",", "relations", ",", "options", ")", "{", "var", "resource", "=", "{", "}", "var", "attributes", "=", "{", "}", "var", "relationships", "resource", ".", "type", "=", "type", "relationships", "=", "parseRelations", "(", "data", ",", "relations", ",", "options", ")", "if", "(", "!", "_", ".", "isEmpty", "(", "relationships", ")", ")", "{", "resource", ".", "relationships", "=", "relationships", "}", "if", "(", "options", ".", "foreignKeys", "!==", "true", ")", "{", "// Remove any foreign keys from this resource", "options", ".", "app", ".", "models", "(", ")", ".", "forEach", "(", "function", "(", "model", ")", "{", "_", ".", "each", "(", "model", ".", "relations", ",", "function", "(", "relation", ")", "{", "var", "fkModel", "=", "relation", ".", "modelTo", "var", "fkName", "=", "relation", ".", "keyTo", "if", "(", "utils", ".", "relationFkOnModelFrom", "(", "relation", ")", ")", "{", "fkModel", "=", "relation", ".", "modelFrom", "fkName", "=", "relation", ".", "keyFrom", "}", "if", "(", "fkModel", "===", "options", ".", "model", "&&", "fkName", "!==", "options", ".", "primaryKeyField", ")", "{", "// check options and decide whether to remove foreign keys.", "if", "(", "options", ".", "foreignKeys", "!==", "false", "&&", "Array", ".", "isArray", "(", "options", ".", "foreignKeys", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "options", ".", "foreignKeys", ".", "length", ";", "i", "++", ")", "{", "// if match on model", "if", "(", "options", ".", "foreignKeys", "[", "i", "]", ".", "model", "===", "fkModel", ".", "sharedClass", ".", "name", ")", "{", "// if no method specified", "if", "(", "!", "options", ".", "foreignKeys", "[", "i", "]", ".", "method", ")", "return", "// if method match", "if", "(", "options", ".", "foreignKeys", "[", "i", "]", ".", "method", "===", "options", ".", "method", ")", "return", "}", "}", "}", "delete", "data", "[", "fkName", "]", "}", "}", ")", "}", ")", "}", "_", ".", "each", "(", "data", ",", "function", "(", "value", ",", "property", ")", "{", "if", "(", "property", "===", "options", ".", "primaryKeyField", ")", "{", "resource", ".", "id", "=", "_", "(", "value", ")", ".", "toString", "(", ")", "}", "else", "{", "if", "(", "!", "options", ".", "attributes", "[", "type", "]", "||", "_", ".", "includes", "(", "options", ".", "attributes", "[", "type", "]", ",", "property", ")", ")", "{", "attributes", "[", "property", "]", "=", "value", "}", "}", "}", ")", "if", "(", "_", ".", "isUndefined", "(", "resource", ".", "id", ")", ")", "{", "return", "null", "}", "// if it's a relationship request", "if", "(", "options", ".", "isRelationshipRequest", ")", "{", "return", "resource", "}", "resource", ".", "attributes", "=", "attributes", "if", "(", "options", ".", "dataLinks", ")", "{", "resource", ".", "links", "=", "makeLinks", "(", "options", ".", "dataLinks", ",", "resource", ")", "}", "return", "resource", "}" ]
Parses a a request and returns a resource @private @memberOf {Serializer} @param {String} type @param {Object} data @param {Object} relations @param {Object} options @return {Object|null}
[ "Parses", "a", "a", "request", "and", "returns", "a", "resource" ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/serializer.js#L117-L188
21,173
digitalsadhu/loopback-component-jsonapi
lib/serializer.js
parseCollection
function parseCollection (type, data, relations, options) { var result = [] _.each(data, function (value) { result.push(parseResource(type, value, relations, options)) }) return result }
javascript
function parseCollection (type, data, relations, options) { var result = [] _.each(data, function (value) { result.push(parseResource(type, value, relations, options)) }) return result }
[ "function", "parseCollection", "(", "type", ",", "data", ",", "relations", ",", "options", ")", "{", "var", "result", "=", "[", "]", "_", ".", "each", "(", "data", ",", "function", "(", "value", ")", "{", "result", ".", "push", "(", "parseResource", "(", "type", ",", "value", ",", "relations", ",", "options", ")", ")", "}", ")", "return", "result", "}" ]
Parses a collection of resources @private @memberOf {Serializer} @param {String} type @param {Object} data @param {Object} relations @param {Object} options @return {Array}
[ "Parses", "a", "collection", "of", "resources" ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/serializer.js#L200-L208
21,174
digitalsadhu/loopback-component-jsonapi
lib/serializer.js
parseRelations
function parseRelations (data, relations, options) { var relationships = {} _.each(relations, function (relation, name) { var fkName = relation.keyTo // If relation is belongsTo then fk is the other way around if (utils.relationFkOnModelFrom(relation)) { fkName = relation.keyFrom } var pk = data[options.primaryKeyField] var fk = data[fkName] var toType = '' if (relation.polymorphic && utils.relationFkOnModelFrom(relation)) { var discriminator = relation.polymorphic.discriminator var model = options.app.models[data[discriminator]] toType = utils.pluralForModel(model) } else { toType = utils.pluralForModel(relation.modelTo) } // Relationship `links` should always be defined unless this is a // relationship request if (!options.isRelationshipRequest) { relationships[name] = { links: { related: options.host + options.restApiRoot + '/' + options.modelPath + '/' + pk + '/' + name } } } var relationship = null if (!_.isUndefined(fk) && relation.modelTo !== relation.modelFrom) { if (_.isArray(fk)) { relationship = makeRelations(toType, fk, options) } else { relationship = makeRelation(toType, fk, options) } } // No `data` key should be present unless there is actual relationship data. if (relationship) { relationships[name].data = relationship } else if (relation.type === 'belongsTo') { relationships[name].data = null } }) return relationships }
javascript
function parseRelations (data, relations, options) { var relationships = {} _.each(relations, function (relation, name) { var fkName = relation.keyTo // If relation is belongsTo then fk is the other way around if (utils.relationFkOnModelFrom(relation)) { fkName = relation.keyFrom } var pk = data[options.primaryKeyField] var fk = data[fkName] var toType = '' if (relation.polymorphic && utils.relationFkOnModelFrom(relation)) { var discriminator = relation.polymorphic.discriminator var model = options.app.models[data[discriminator]] toType = utils.pluralForModel(model) } else { toType = utils.pluralForModel(relation.modelTo) } // Relationship `links` should always be defined unless this is a // relationship request if (!options.isRelationshipRequest) { relationships[name] = { links: { related: options.host + options.restApiRoot + '/' + options.modelPath + '/' + pk + '/' + name } } } var relationship = null if (!_.isUndefined(fk) && relation.modelTo !== relation.modelFrom) { if (_.isArray(fk)) { relationship = makeRelations(toType, fk, options) } else { relationship = makeRelation(toType, fk, options) } } // No `data` key should be present unless there is actual relationship data. if (relationship) { relationships[name].data = relationship } else if (relation.type === 'belongsTo') { relationships[name].data = null } }) return relationships }
[ "function", "parseRelations", "(", "data", ",", "relations", ",", "options", ")", "{", "var", "relationships", "=", "{", "}", "_", ".", "each", "(", "relations", ",", "function", "(", "relation", ",", "name", ")", "{", "var", "fkName", "=", "relation", ".", "keyTo", "// If relation is belongsTo then fk is the other way around", "if", "(", "utils", ".", "relationFkOnModelFrom", "(", "relation", ")", ")", "{", "fkName", "=", "relation", ".", "keyFrom", "}", "var", "pk", "=", "data", "[", "options", ".", "primaryKeyField", "]", "var", "fk", "=", "data", "[", "fkName", "]", "var", "toType", "=", "''", "if", "(", "relation", ".", "polymorphic", "&&", "utils", ".", "relationFkOnModelFrom", "(", "relation", ")", ")", "{", "var", "discriminator", "=", "relation", ".", "polymorphic", ".", "discriminator", "var", "model", "=", "options", ".", "app", ".", "models", "[", "data", "[", "discriminator", "]", "]", "toType", "=", "utils", ".", "pluralForModel", "(", "model", ")", "}", "else", "{", "toType", "=", "utils", ".", "pluralForModel", "(", "relation", ".", "modelTo", ")", "}", "// Relationship `links` should always be defined unless this is a", "// relationship request", "if", "(", "!", "options", ".", "isRelationshipRequest", ")", "{", "relationships", "[", "name", "]", "=", "{", "links", ":", "{", "related", ":", "options", ".", "host", "+", "options", ".", "restApiRoot", "+", "'/'", "+", "options", ".", "modelPath", "+", "'/'", "+", "pk", "+", "'/'", "+", "name", "}", "}", "}", "var", "relationship", "=", "null", "if", "(", "!", "_", ".", "isUndefined", "(", "fk", ")", "&&", "relation", ".", "modelTo", "!==", "relation", ".", "modelFrom", ")", "{", "if", "(", "_", ".", "isArray", "(", "fk", ")", ")", "{", "relationship", "=", "makeRelations", "(", "toType", ",", "fk", ",", "options", ")", "}", "else", "{", "relationship", "=", "makeRelation", "(", "toType", ",", "fk", ",", "options", ")", "}", "}", "// No `data` key should be present unless there is actual relationship data.", "if", "(", "relationship", ")", "{", "relationships", "[", "name", "]", ".", "data", "=", "relationship", "}", "else", "if", "(", "relation", ".", "type", "===", "'belongsTo'", ")", "{", "relationships", "[", "name", "]", ".", "data", "=", "null", "}", "}", ")", "return", "relationships", "}" ]
Parses relations from the request. @private @memberOf {Serializer} @param {Object} data @param {Object} relations @param {Object} options @return {Object}
[ "Parses", "relations", "from", "the", "request", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/serializer.js#L219-L278
21,175
digitalsadhu/loopback-component-jsonapi
lib/serializer.js
makeRelation
function makeRelation (type, id, options) { if (!_.includes(['string', 'number'], typeof id) || !id) { return null } return { type: type, id: id } }
javascript
function makeRelation (type, id, options) { if (!_.includes(['string', 'number'], typeof id) || !id) { return null } return { type: type, id: id } }
[ "function", "makeRelation", "(", "type", ",", "id", ",", "options", ")", "{", "if", "(", "!", "_", ".", "includes", "(", "[", "'string'", ",", "'number'", "]", ",", "typeof", "id", ")", "||", "!", "id", ")", "{", "return", "null", "}", "return", "{", "type", ":", "type", ",", "id", ":", "id", "}", "}" ]
Responsible for making a relations. @private @memberOf {Serializer} @param {String} type @param {String|Number} id @param {Object} options @return {Object|null}
[ "Responsible", "for", "making", "a", "relations", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/serializer.js#L289-L298
21,176
digitalsadhu/loopback-component-jsonapi
lib/serializer.js
makeRelations
function makeRelations (type, ids, options) { var res = [] _.each(ids, function (id) { res.push(makeRelation(type, id, options)) }) return res }
javascript
function makeRelations (type, ids, options) { var res = [] _.each(ids, function (id) { res.push(makeRelation(type, id, options)) }) return res }
[ "function", "makeRelations", "(", "type", ",", "ids", ",", "options", ")", "{", "var", "res", "=", "[", "]", "_", ".", "each", "(", "ids", ",", "function", "(", "id", ")", "{", "res", ".", "push", "(", "makeRelation", "(", "type", ",", "id", ",", "options", ")", ")", "}", ")", "return", "res", "}" ]
Handles a creating a collection of relations. @private @memberOf {Serializer} @param {String} type @param {Array} ids @param {Object} options @return {Array}
[ "Handles", "a", "creating", "a", "collection", "of", "relations", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/serializer.js#L309-L317
21,177
digitalsadhu/loopback-component-jsonapi
lib/serializer.js
makeLinks
function makeLinks (links, item) { var retLinks = {} _.each(links, function (value, name) { if (_.isFunction(value)) { retLinks[name] = value(item) } else { retLinks[name] = _(value).toString() } }) return retLinks }
javascript
function makeLinks (links, item) { var retLinks = {} _.each(links, function (value, name) { if (_.isFunction(value)) { retLinks[name] = value(item) } else { retLinks[name] = _(value).toString() } }) return retLinks }
[ "function", "makeLinks", "(", "links", ",", "item", ")", "{", "var", "retLinks", "=", "{", "}", "_", ".", "each", "(", "links", ",", "function", "(", "value", ",", "name", ")", "{", "if", "(", "_", ".", "isFunction", "(", "value", ")", ")", "{", "retLinks", "[", "name", "]", "=", "value", "(", "item", ")", "}", "else", "{", "retLinks", "[", "name", "]", "=", "_", "(", "value", ")", ".", "toString", "(", ")", "}", "}", ")", "return", "retLinks", "}" ]
Makes links to an item. @private @memberOf {Serializer} @param {Object} links @param {Mixed} item @return {Object}
[ "Makes", "links", "to", "an", "item", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/serializer.js#L327-L339
21,178
digitalsadhu/loopback-component-jsonapi
lib/serializer.js
handleIncludes
function handleIncludes (resp, includes, relations, options) { var app = options.app relations = utils.setIncludedRelations(relations, app) var resources = _.isArray(resp.data) ? resp.data : [resp.data] if (typeof includes === 'string') { includes = [includes] } if (!_.isArray(includes)) { throw RelUtils.getInvalidIncludesError( 'JSON API unable to detect valid includes' ) } var embedded = resources.map(function subsituteEmbeddedForIds (resource) { return includes.map(function (include) { var relation = relations[include] var includedRelations = relations[include].relations var propertyKey = relation.keyFrom var plural = '' if (relation.polymorphic && utils.relationFkOnModelFrom(relation)) { var descriminator = relation.polymorphic.discriminator var discriminator = resource.attributes[descriminator] plural = utils.pluralForModel(app.models[discriminator]) } else { plural = utils.pluralForModel(relation.modelTo) } var embeds = [] // If relation is belongsTo then pk and fk are the other way around if (utils.relationFkOnModelFrom(relation)) { propertyKey = relation.keyTo } if (!relation) { throw RelUtils.getInvalidIncludesError( 'Can\'t locate relationship "' + include + '" to include' ) } resource.relationships[include] = resource.relationships[include] || {} if (resource.relationships[include] && resource.attributes[include]) { if (_.isArray(resource.attributes[include])) { embeds = resource.attributes[include].map(function (rel) { rel = utils.clone(rel) return createCompoundIncludes( rel, propertyKey, relation.keyTo, plural, includedRelations, options ) }) embeds = _.compact(embeds) const included = resource.attributes[include] resource.relationships[include].data = included.map(relData => { return { id: String(relData[propertyKey]), type: plural } }) } else { var rel = utils.clone(resource.attributes[include]) var compoundIncludes = createCompoundIncludes( rel, propertyKey, relation.keyFrom, plural, includedRelations, options ) resource.relationships[include].data = { id: String(resource.attributes[include][propertyKey]), type: plural } embeds.push(compoundIncludes) } delete resource.attributes[relation.keyFrom] delete resource.attributes[relation.keyTo] delete resource.attributes[include] } return embeds }) }) if (embedded.length) { // This array may contain duplicate models if the same item is referenced multiple times in 'data' var duplicate = _.flattenDeep(embedded) // So begin with an empty array that will only contain unique items var unique = [] // Iterate through each item in the first array duplicate.forEach(function (d) { // Count the number of items in the unique array with matching 'type' AND 'id' // Since we're adhering to the JSONAPI spec, both 'type' and 'id' can assumed to be present // Both 'type' and 'id' are needed for comparison because we could theoretically have objects of different // types who happen to have the same 'id', and those would not be considered duplicates var count = unique.filter(function (u) { return u.type === d.type && u.id === d.id }).length // If there are no matching entries, then add the item to the unique array if (count === 0) { unique.push(d) } }) resp.included = unique } }
javascript
function handleIncludes (resp, includes, relations, options) { var app = options.app relations = utils.setIncludedRelations(relations, app) var resources = _.isArray(resp.data) ? resp.data : [resp.data] if (typeof includes === 'string') { includes = [includes] } if (!_.isArray(includes)) { throw RelUtils.getInvalidIncludesError( 'JSON API unable to detect valid includes' ) } var embedded = resources.map(function subsituteEmbeddedForIds (resource) { return includes.map(function (include) { var relation = relations[include] var includedRelations = relations[include].relations var propertyKey = relation.keyFrom var plural = '' if (relation.polymorphic && utils.relationFkOnModelFrom(relation)) { var descriminator = relation.polymorphic.discriminator var discriminator = resource.attributes[descriminator] plural = utils.pluralForModel(app.models[discriminator]) } else { plural = utils.pluralForModel(relation.modelTo) } var embeds = [] // If relation is belongsTo then pk and fk are the other way around if (utils.relationFkOnModelFrom(relation)) { propertyKey = relation.keyTo } if (!relation) { throw RelUtils.getInvalidIncludesError( 'Can\'t locate relationship "' + include + '" to include' ) } resource.relationships[include] = resource.relationships[include] || {} if (resource.relationships[include] && resource.attributes[include]) { if (_.isArray(resource.attributes[include])) { embeds = resource.attributes[include].map(function (rel) { rel = utils.clone(rel) return createCompoundIncludes( rel, propertyKey, relation.keyTo, plural, includedRelations, options ) }) embeds = _.compact(embeds) const included = resource.attributes[include] resource.relationships[include].data = included.map(relData => { return { id: String(relData[propertyKey]), type: plural } }) } else { var rel = utils.clone(resource.attributes[include]) var compoundIncludes = createCompoundIncludes( rel, propertyKey, relation.keyFrom, plural, includedRelations, options ) resource.relationships[include].data = { id: String(resource.attributes[include][propertyKey]), type: plural } embeds.push(compoundIncludes) } delete resource.attributes[relation.keyFrom] delete resource.attributes[relation.keyTo] delete resource.attributes[include] } return embeds }) }) if (embedded.length) { // This array may contain duplicate models if the same item is referenced multiple times in 'data' var duplicate = _.flattenDeep(embedded) // So begin with an empty array that will only contain unique items var unique = [] // Iterate through each item in the first array duplicate.forEach(function (d) { // Count the number of items in the unique array with matching 'type' AND 'id' // Since we're adhering to the JSONAPI spec, both 'type' and 'id' can assumed to be present // Both 'type' and 'id' are needed for comparison because we could theoretically have objects of different // types who happen to have the same 'id', and those would not be considered duplicates var count = unique.filter(function (u) { return u.type === d.type && u.id === d.id }).length // If there are no matching entries, then add the item to the unique array if (count === 0) { unique.push(d) } }) resp.included = unique } }
[ "function", "handleIncludes", "(", "resp", ",", "includes", ",", "relations", ",", "options", ")", "{", "var", "app", "=", "options", ".", "app", "relations", "=", "utils", ".", "setIncludedRelations", "(", "relations", ",", "app", ")", "var", "resources", "=", "_", ".", "isArray", "(", "resp", ".", "data", ")", "?", "resp", ".", "data", ":", "[", "resp", ".", "data", "]", "if", "(", "typeof", "includes", "===", "'string'", ")", "{", "includes", "=", "[", "includes", "]", "}", "if", "(", "!", "_", ".", "isArray", "(", "includes", ")", ")", "{", "throw", "RelUtils", ".", "getInvalidIncludesError", "(", "'JSON API unable to detect valid includes'", ")", "}", "var", "embedded", "=", "resources", ".", "map", "(", "function", "subsituteEmbeddedForIds", "(", "resource", ")", "{", "return", "includes", ".", "map", "(", "function", "(", "include", ")", "{", "var", "relation", "=", "relations", "[", "include", "]", "var", "includedRelations", "=", "relations", "[", "include", "]", ".", "relations", "var", "propertyKey", "=", "relation", ".", "keyFrom", "var", "plural", "=", "''", "if", "(", "relation", ".", "polymorphic", "&&", "utils", ".", "relationFkOnModelFrom", "(", "relation", ")", ")", "{", "var", "descriminator", "=", "relation", ".", "polymorphic", ".", "discriminator", "var", "discriminator", "=", "resource", ".", "attributes", "[", "descriminator", "]", "plural", "=", "utils", ".", "pluralForModel", "(", "app", ".", "models", "[", "discriminator", "]", ")", "}", "else", "{", "plural", "=", "utils", ".", "pluralForModel", "(", "relation", ".", "modelTo", ")", "}", "var", "embeds", "=", "[", "]", "// If relation is belongsTo then pk and fk are the other way around", "if", "(", "utils", ".", "relationFkOnModelFrom", "(", "relation", ")", ")", "{", "propertyKey", "=", "relation", ".", "keyTo", "}", "if", "(", "!", "relation", ")", "{", "throw", "RelUtils", ".", "getInvalidIncludesError", "(", "'Can\\'t locate relationship \"'", "+", "include", "+", "'\" to include'", ")", "}", "resource", ".", "relationships", "[", "include", "]", "=", "resource", ".", "relationships", "[", "include", "]", "||", "{", "}", "if", "(", "resource", ".", "relationships", "[", "include", "]", "&&", "resource", ".", "attributes", "[", "include", "]", ")", "{", "if", "(", "_", ".", "isArray", "(", "resource", ".", "attributes", "[", "include", "]", ")", ")", "{", "embeds", "=", "resource", ".", "attributes", "[", "include", "]", ".", "map", "(", "function", "(", "rel", ")", "{", "rel", "=", "utils", ".", "clone", "(", "rel", ")", "return", "createCompoundIncludes", "(", "rel", ",", "propertyKey", ",", "relation", ".", "keyTo", ",", "plural", ",", "includedRelations", ",", "options", ")", "}", ")", "embeds", "=", "_", ".", "compact", "(", "embeds", ")", "const", "included", "=", "resource", ".", "attributes", "[", "include", "]", "resource", ".", "relationships", "[", "include", "]", ".", "data", "=", "included", ".", "map", "(", "relData", "=>", "{", "return", "{", "id", ":", "String", "(", "relData", "[", "propertyKey", "]", ")", ",", "type", ":", "plural", "}", "}", ")", "}", "else", "{", "var", "rel", "=", "utils", ".", "clone", "(", "resource", ".", "attributes", "[", "include", "]", ")", "var", "compoundIncludes", "=", "createCompoundIncludes", "(", "rel", ",", "propertyKey", ",", "relation", ".", "keyFrom", ",", "plural", ",", "includedRelations", ",", "options", ")", "resource", ".", "relationships", "[", "include", "]", ".", "data", "=", "{", "id", ":", "String", "(", "resource", ".", "attributes", "[", "include", "]", "[", "propertyKey", "]", ")", ",", "type", ":", "plural", "}", "embeds", ".", "push", "(", "compoundIncludes", ")", "}", "delete", "resource", ".", "attributes", "[", "relation", ".", "keyFrom", "]", "delete", "resource", ".", "attributes", "[", "relation", ".", "keyTo", "]", "delete", "resource", ".", "attributes", "[", "include", "]", "}", "return", "embeds", "}", ")", "}", ")", "if", "(", "embedded", ".", "length", ")", "{", "// This array may contain duplicate models if the same item is referenced multiple times in 'data'", "var", "duplicate", "=", "_", ".", "flattenDeep", "(", "embedded", ")", "// So begin with an empty array that will only contain unique items", "var", "unique", "=", "[", "]", "// Iterate through each item in the first array", "duplicate", ".", "forEach", "(", "function", "(", "d", ")", "{", "// Count the number of items in the unique array with matching 'type' AND 'id'", "// Since we're adhering to the JSONAPI spec, both 'type' and 'id' can assumed to be present", "// Both 'type' and 'id' are needed for comparison because we could theoretically have objects of different", "// types who happen to have the same 'id', and those would not be considered duplicates", "var", "count", "=", "unique", ".", "filter", "(", "function", "(", "u", ")", "{", "return", "u", ".", "type", "===", "d", ".", "type", "&&", "u", ".", "id", "===", "d", ".", "id", "}", ")", ".", "length", "// If there are no matching entries, then add the item to the unique array", "if", "(", "count", "===", "0", ")", "{", "unique", ".", "push", "(", "d", ")", "}", "}", ")", "resp", ".", "included", "=", "unique", "}", "}" ]
Handles serializing the requested includes to a seperate included property per JSON API spec. @private @memberOf {Serializer} @param {Object} resp @param {Array<String>|String} @throws {Error} @return {undefined}
[ "Handles", "serializing", "the", "requested", "includes", "to", "a", "seperate", "included", "property", "per", "JSON", "API", "spec", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/serializer.js#L351-L463
21,179
digitalsadhu/loopback-component-jsonapi
lib/serializer.js
createCompoundIncludes
function createCompoundIncludes ( relationship, key, fk, type, includedRelations, options ) { var compoundInclude = makeRelation(type, String(relationship[key])) if (options && !_.isEmpty(includedRelations)) { var defaultModelPath = options.modelPath options.modelPath = type compoundInclude.relationships = parseRelations( relationship, includedRelations, options ) options.modelPath = defaultModelPath } // remove the id key since its part of the base compound document, not part of attributes delete relationship[key] delete relationship[fk] // The rest of the data goes in the attributes compoundInclude.attributes = relationship return compoundInclude }
javascript
function createCompoundIncludes ( relationship, key, fk, type, includedRelations, options ) { var compoundInclude = makeRelation(type, String(relationship[key])) if (options && !_.isEmpty(includedRelations)) { var defaultModelPath = options.modelPath options.modelPath = type compoundInclude.relationships = parseRelations( relationship, includedRelations, options ) options.modelPath = defaultModelPath } // remove the id key since its part of the base compound document, not part of attributes delete relationship[key] delete relationship[fk] // The rest of the data goes in the attributes compoundInclude.attributes = relationship return compoundInclude }
[ "function", "createCompoundIncludes", "(", "relationship", ",", "key", ",", "fk", ",", "type", ",", "includedRelations", ",", "options", ")", "{", "var", "compoundInclude", "=", "makeRelation", "(", "type", ",", "String", "(", "relationship", "[", "key", "]", ")", ")", "if", "(", "options", "&&", "!", "_", ".", "isEmpty", "(", "includedRelations", ")", ")", "{", "var", "defaultModelPath", "=", "options", ".", "modelPath", "options", ".", "modelPath", "=", "type", "compoundInclude", ".", "relationships", "=", "parseRelations", "(", "relationship", ",", "includedRelations", ",", "options", ")", "options", ".", "modelPath", "=", "defaultModelPath", "}", "// remove the id key since its part of the base compound document, not part of attributes", "delete", "relationship", "[", "key", "]", "delete", "relationship", "[", "fk", "]", "// The rest of the data goes in the attributes", "compoundInclude", ".", "attributes", "=", "relationship", "return", "compoundInclude", "}" ]
Creates a compound include object. @private @memberOf {Serializer} @param {Object} relationship @param {String} key @param {String} fk @param {String} type @param {Object} includedRelations @param {Object} options @return {Object}
[ "Creates", "a", "compound", "include", "object", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/serializer.js#L477-L508
21,180
digitalsadhu/loopback-component-jsonapi
lib/utils.js
pluralForModel
function pluralForModel (model) { if (model.pluralModelName) { return model.pluralModelName } if (model.settings && model.settings.plural) { return model.settings.plural } if ( model.definition && model.definition.settings && model.definition.settings.plural ) { return model.definition.settings.plural } return inflection.pluralize(model.sharedClass.name) }
javascript
function pluralForModel (model) { if (model.pluralModelName) { return model.pluralModelName } if (model.settings && model.settings.plural) { return model.settings.plural } if ( model.definition && model.definition.settings && model.definition.settings.plural ) { return model.definition.settings.plural } return inflection.pluralize(model.sharedClass.name) }
[ "function", "pluralForModel", "(", "model", ")", "{", "if", "(", "model", ".", "pluralModelName", ")", "{", "return", "model", ".", "pluralModelName", "}", "if", "(", "model", ".", "settings", "&&", "model", ".", "settings", ".", "plural", ")", "{", "return", "model", ".", "settings", ".", "plural", "}", "if", "(", "model", ".", "definition", "&&", "model", ".", "definition", ".", "settings", "&&", "model", ".", "definition", ".", "settings", ".", "plural", ")", "{", "return", "model", ".", "definition", ".", "settings", ".", "plural", "}", "return", "inflection", ".", "pluralize", "(", "model", ".", "sharedClass", ".", "name", ")", "}" ]
Returns the plural for a model. @public @memberOf {Utils} @param {Object} model @return {String}
[ "Returns", "the", "plural", "for", "a", "model", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/utils.js#L40-L58
21,181
digitalsadhu/loopback-component-jsonapi
lib/utils.js
httpPathForModel
function httpPathForModel (model) { if (model.settings && model.settings.http && model.settings.http.path) { return model.settings.http.path } return pluralForModel(model) }
javascript
function httpPathForModel (model) { if (model.settings && model.settings.http && model.settings.http.path) { return model.settings.http.path } return pluralForModel(model) }
[ "function", "httpPathForModel", "(", "model", ")", "{", "if", "(", "model", ".", "settings", "&&", "model", ".", "settings", ".", "http", "&&", "model", ".", "settings", ".", "http", ".", "path", ")", "{", "return", "model", ".", "settings", ".", "http", ".", "path", "}", "return", "pluralForModel", "(", "model", ")", "}" ]
Returns the plural path for a model @public @memberOf {Utils} @param {Object} model @return {String}
[ "Returns", "the", "plural", "path", "for", "a", "model" ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/utils.js#L67-L72
21,182
digitalsadhu/loopback-component-jsonapi
lib/utils.js
urlFromContext
function urlFromContext (context) { return context.req.protocol + '://' + context.req.get('host') + context.req.originalUrl }
javascript
function urlFromContext (context) { return context.req.protocol + '://' + context.req.get('host') + context.req.originalUrl }
[ "function", "urlFromContext", "(", "context", ")", "{", "return", "context", ".", "req", ".", "protocol", "+", "'://'", "+", "context", ".", "req", ".", "get", "(", "'host'", ")", "+", "context", ".", "req", ".", "originalUrl", "}" ]
Returns the fully qualified request url @public @memberOf {Utils} @param {Object} context @return {String}
[ "Returns", "the", "fully", "qualified", "request", "url" ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/utils.js#L114-L119
21,183
digitalsadhu/loopback-component-jsonapi
lib/utils.js
getModelFromContext
function getModelFromContext (context, app) { var type = getTypeFromContext(context) if (app.models[type]) return app.models[type] var name = modelNameFromContext(context) return app.models[name] }
javascript
function getModelFromContext (context, app) { var type = getTypeFromContext(context) if (app.models[type]) return app.models[type] var name = modelNameFromContext(context) return app.models[name] }
[ "function", "getModelFromContext", "(", "context", ",", "app", ")", "{", "var", "type", "=", "getTypeFromContext", "(", "context", ")", "if", "(", "app", ".", "models", "[", "type", "]", ")", "return", "app", ".", "models", "[", "type", "]", "var", "name", "=", "modelNameFromContext", "(", "context", ")", "return", "app", ".", "models", "[", "name", "]", "}" ]
Returns a model from the app object. @public @memberOf {Utils} @param {Object} context @param {Object} app @return {Object}
[ "Returns", "a", "model", "from", "the", "app", "object", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/utils.js#L129-L135
21,184
digitalsadhu/loopback-component-jsonapi
lib/utils.js
getTypeFromContext
function getTypeFromContext (context) { if (!context.method.returns) return undefined const returns = [].concat(context.method.returns) for (var i = 0, l = returns.length; i < l; i++) { if (typeof returns[i] !== 'object' || returns[i].root !== true) continue return returns[i].type } }
javascript
function getTypeFromContext (context) { if (!context.method.returns) return undefined const returns = [].concat(context.method.returns) for (var i = 0, l = returns.length; i < l; i++) { if (typeof returns[i] !== 'object' || returns[i].root !== true) continue return returns[i].type } }
[ "function", "getTypeFromContext", "(", "context", ")", "{", "if", "(", "!", "context", ".", "method", ".", "returns", ")", "return", "undefined", "const", "returns", "=", "[", "]", ".", "concat", "(", "context", ".", "method", ".", "returns", ")", "for", "(", "var", "i", "=", "0", ",", "l", "=", "returns", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "typeof", "returns", "[", "i", "]", "!==", "'object'", "||", "returns", "[", "i", "]", ".", "root", "!==", "true", ")", "continue", "return", "returns", "[", "i", "]", ".", "type", "}", "}" ]
Returns a model type from the context object. Infer the type from the `root` returns in the remote. @public @memberOf {Utils} @param {Object} context @param {Object} app @return {String}
[ "Returns", "a", "model", "type", "from", "the", "context", "object", ".", "Infer", "the", "type", "from", "the", "root", "returns", "in", "the", "remote", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/utils.js#L146-L154
21,185
digitalsadhu/loopback-component-jsonapi
lib/utils.js
buildModelUrl
function buildModelUrl (protocol, host, apiRoot, modelName, id) { var result try { result = url.format({ protocol: protocol, host: host, pathname: url.resolve('/', [apiRoot, modelName, id].join('/')) }) } catch (e) { return '' } return result }
javascript
function buildModelUrl (protocol, host, apiRoot, modelName, id) { var result try { result = url.format({ protocol: protocol, host: host, pathname: url.resolve('/', [apiRoot, modelName, id].join('/')) }) } catch (e) { return '' } return result }
[ "function", "buildModelUrl", "(", "protocol", ",", "host", ",", "apiRoot", ",", "modelName", ",", "id", ")", "{", "var", "result", "try", "{", "result", "=", "url", ".", "format", "(", "{", "protocol", ":", "protocol", ",", "host", ":", "host", ",", "pathname", ":", "url", ".", "resolve", "(", "'/'", ",", "[", "apiRoot", ",", "modelName", ",", "id", "]", ".", "join", "(", "'/'", ")", ")", "}", ")", "}", "catch", "(", "e", ")", "{", "return", "''", "}", "return", "result", "}" ]
Builds a models url @public @memberOf {Utils} @param {String} protocol @param {String} host @param {String} apiRoot @param {String} modelName @param {String|Number} id @return {String}
[ "Builds", "a", "models", "url" ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/utils.js#L201-L215
21,186
digitalsadhu/loopback-component-jsonapi
lib/deserialize.js
validateRequest
function validateRequest (data, requestMethod) { if (!data.data) { return 'JSON API resource object must contain `data` property' } if (!data.data.type) { return 'JSON API resource object must contain `data.type` property' } if (['PATCH', 'PUT'].indexOf(requestMethod) > -1 && !data.data.id) { return 'JSON API resource object must contain `data.id` property' } return false }
javascript
function validateRequest (data, requestMethod) { if (!data.data) { return 'JSON API resource object must contain `data` property' } if (!data.data.type) { return 'JSON API resource object must contain `data.type` property' } if (['PATCH', 'PUT'].indexOf(requestMethod) > -1 && !data.data.id) { return 'JSON API resource object must contain `data.id` property' } return false }
[ "function", "validateRequest", "(", "data", ",", "requestMethod", ")", "{", "if", "(", "!", "data", ".", "data", ")", "{", "return", "'JSON API resource object must contain `data` property'", "}", "if", "(", "!", "data", ".", "data", ".", "type", ")", "{", "return", "'JSON API resource object must contain `data.type` property'", "}", "if", "(", "[", "'PATCH'", ",", "'PUT'", "]", ".", "indexOf", "(", "requestMethod", ")", ">", "-", "1", "&&", "!", "data", ".", "data", ".", "id", ")", "{", "return", "'JSON API resource object must contain `data.id` property'", "}", "return", "false", "}" ]
Check for errors in the request. If it has an error it will return a string, otherwise false. @private @memberOf {Deserialize} @param {Object} data @param {String} requestMethod @return {String|false}
[ "Check", "for", "errors", "in", "the", "request", ".", "If", "it", "has", "an", "error", "it", "will", "return", "a", "string", "otherwise", "false", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/deserialize.js#L119-L133
21,187
digitalsadhu/loopback-component-jsonapi
lib/utilities/relationship-utils.js
getInvalidIncludesError
function getInvalidIncludesError (message) { var error = new Error( message || 'JSON API resource does not support `include`' ) error.statusCode = statusCodes.BAD_REQUEST error.code = statusCodes.BAD_REQUEST error.status = statusCodes.BAD_REQUEST return error }
javascript
function getInvalidIncludesError (message) { var error = new Error( message || 'JSON API resource does not support `include`' ) error.statusCode = statusCodes.BAD_REQUEST error.code = statusCodes.BAD_REQUEST error.status = statusCodes.BAD_REQUEST return error }
[ "function", "getInvalidIncludesError", "(", "message", ")", "{", "var", "error", "=", "new", "Error", "(", "message", "||", "'JSON API resource does not support `include`'", ")", "error", ".", "statusCode", "=", "statusCodes", ".", "BAD_REQUEST", "error", ".", "code", "=", "statusCodes", ".", "BAD_REQUEST", "error", ".", "status", "=", "statusCodes", ".", "BAD_REQUEST", "return", "error", "}" ]
Get the invalid includes error. @public @memberOf {RelationshipUtils} @param {String} message @return {Error}
[ "Get", "the", "invalid", "includes", "error", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/utilities/relationship-utils.js#L36-L45
21,188
digitalsadhu/loopback-component-jsonapi
lib/utilities/relationship-utils.js
getIncludesArray
function getIncludesArray (query) { var relationships = query.include.split(',') return relationships.map(function (val) { return val.trim() }) }
javascript
function getIncludesArray (query) { var relationships = query.include.split(',') return relationships.map(function (val) { return val.trim() }) }
[ "function", "getIncludesArray", "(", "query", ")", "{", "var", "relationships", "=", "query", ".", "include", ".", "split", "(", "','", ")", "return", "relationships", ".", "map", "(", "function", "(", "val", ")", "{", "return", "val", ".", "trim", "(", ")", "}", ")", "}" ]
Returns an array of relationships to include. Per JSON specification, they will be in a comma-separated pattern. @public @memberOf {RelationshipUtils} @param {Object} query @return {Array}
[ "Returns", "an", "array", "of", "relationships", "to", "include", ".", "Per", "JSON", "specification", "they", "will", "be", "in", "a", "comma", "-", "separated", "pattern", "." ]
a7083aad413b3404bc1466650b20b6437983133a
https://github.com/digitalsadhu/loopback-component-jsonapi/blob/a7083aad413b3404bc1466650b20b6437983133a/lib/utilities/relationship-utils.js#L75-L81
21,189
jviereck/regjsparser
parser.js
isIdentifierPart
function isIdentifierPart(ch) { // Generated by `tools/generate-identifier-regex.js`. var NonAsciiIdentifierPartOnly = /[0-9_\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD801[\uDCA0-\uDCA9]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD803[\uDD24-\uDD27\uDD30-\uDD39\uDF46-\uDF50]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC66-\uDC6F\uDC7F-\uDC82\uDCB0-\uDCBA\uDCF0-\uDCF9\uDD00-\uDD02\uDD27-\uDD34\uDD36-\uDD3F\uDD45\uDD46\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDDC9-\uDDCC\uDDD0-\uDDD9\uDE2C-\uDE37\uDE3E\uDEDF-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF3B\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC35-\uDC46\uDC50-\uDC59\uDC5E\uDCB0-\uDCC3\uDCD0-\uDCD9\uDDAF-\uDDB5\uDDB8-\uDDC0\uDDDC\uDDDD\uDE30-\uDE40\uDE50-\uDE59\uDEAB-\uDEB7\uDEC0-\uDEC9\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDC2C-\uDC3A\uDCE0-\uDCE9\uDE01-\uDE0A\uDE33-\uDE39\uDE3B-\uDE3E\uDE47\uDE51-\uDE5B\uDE8A-\uDE99]|\uD807[\uDC2F-\uDC36\uDC38-\uDC3F\uDC50-\uDC59\uDC92-\uDCA7\uDCA9-\uDCB6\uDD31-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD45\uDD47\uDD50-\uDD59\uDD8A-\uDD8E\uDD90\uDD91\uDD93-\uDD97\uDDA0-\uDDA9\uDEF3-\uDEF6]|\uD81A[\uDE60-\uDE69\uDEF0-\uDEF4\uDF30-\uDF36\uDF50-\uDF59]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDCD0-\uDCD6\uDD44-\uDD4A\uDD50-\uDD59]|\uDB40[\uDD00-\uDDEF]/; return isIdentifierStart(ch) || (ch >= 48 && ch <= 57) || // 0..9 ((ch >= 0x80) && NonAsciiIdentifierPartOnly.test(fromCodePoint(ch))); }
javascript
function isIdentifierPart(ch) { // Generated by `tools/generate-identifier-regex.js`. var NonAsciiIdentifierPartOnly = /[0-9_\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD801[\uDCA0-\uDCA9]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD803[\uDD24-\uDD27\uDD30-\uDD39\uDF46-\uDF50]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC66-\uDC6F\uDC7F-\uDC82\uDCB0-\uDCBA\uDCF0-\uDCF9\uDD00-\uDD02\uDD27-\uDD34\uDD36-\uDD3F\uDD45\uDD46\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDDC9-\uDDCC\uDDD0-\uDDD9\uDE2C-\uDE37\uDE3E\uDEDF-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF3B\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC35-\uDC46\uDC50-\uDC59\uDC5E\uDCB0-\uDCC3\uDCD0-\uDCD9\uDDAF-\uDDB5\uDDB8-\uDDC0\uDDDC\uDDDD\uDE30-\uDE40\uDE50-\uDE59\uDEAB-\uDEB7\uDEC0-\uDEC9\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDC2C-\uDC3A\uDCE0-\uDCE9\uDE01-\uDE0A\uDE33-\uDE39\uDE3B-\uDE3E\uDE47\uDE51-\uDE5B\uDE8A-\uDE99]|\uD807[\uDC2F-\uDC36\uDC38-\uDC3F\uDC50-\uDC59\uDC92-\uDCA7\uDCA9-\uDCB6\uDD31-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD45\uDD47\uDD50-\uDD59\uDD8A-\uDD8E\uDD90\uDD91\uDD93-\uDD97\uDDA0-\uDDA9\uDEF3-\uDEF6]|\uD81A[\uDE60-\uDE69\uDEF0-\uDEF4\uDF30-\uDF36\uDF50-\uDF59]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDCD0-\uDCD6\uDD44-\uDD4A\uDD50-\uDD59]|\uDB40[\uDD00-\uDDEF]/; return isIdentifierStart(ch) || (ch >= 48 && ch <= 57) || // 0..9 ((ch >= 0x80) && NonAsciiIdentifierPartOnly.test(fromCodePoint(ch))); }
[ "function", "isIdentifierPart", "(", "ch", ")", "{", "// Generated by `tools/generate-identifier-regex.js`.", "var", "NonAsciiIdentifierPartOnly", "=", "/", "[0-9_\\xB7\\u0300-\\u036F\\u0387\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u0669\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u06F0-\\u06F9\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07C0-\\u07C9\\u07EB-\\u07F3\\u07FD\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u08D3-\\u08E1\\u08E3-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096F\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u09E6-\\u09EF\\u09FE\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A66-\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0AE6-\\u0AEF\\u0AFA-\\u0AFF\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B62\\u0B63\\u0B66-\\u0B6F\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0BE6-\\u0BEF\\u0C00-\\u0C04\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C66-\\u0C6F\\u0C81-\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0CE6-\\u0CEF\\u0D00-\\u0D03\\u0D3B\\u0D3C\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D66-\\u0D6F\\u0D82\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0E50-\\u0E59\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1040-\\u1049\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F-\\u109D\\u135D-\\u135F\\u1369-\\u1371\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u194F\\u19D0-\\u19DA\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AB0-\\u1ABD\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BB0-\\u1BB9\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1C40-\\u1C49\\u1C50-\\u1C59\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF2-\\u1CF4\\u1CF7-\\u1CF9\\u1DC0-\\u1DF9\\u1DFB-\\u1DFF\\u200C\\u200D\\u203F\\u2040\\u2054\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA620-\\uA629\\uA66F\\uA674-\\uA67D\\uA69E\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA880\\uA881\\uA8B4-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F1\\uA8FF-\\uA909\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uA9D0-\\uA9D9\\uA9E5\\uA9F0-\\uA9F9\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA50-\\uAA59\\uAA7B-\\uAA7D\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE2F\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF10-\\uFF19\\uFF3F]|\\uD800[\\uDDFD\\uDEE0\\uDF76-\\uDF7A]|\\uD801[\\uDCA0-\\uDCA9]|\\uD802[\\uDE01-\\uDE03\\uDE05\\uDE06\\uDE0C-\\uDE0F\\uDE38-\\uDE3A\\uDE3F\\uDEE5\\uDEE6]|\\uD803[\\uDD24-\\uDD27\\uDD30-\\uDD39\\uDF46-\\uDF50]|\\uD804[\\uDC00-\\uDC02\\uDC38-\\uDC46\\uDC66-\\uDC6F\\uDC7F-\\uDC82\\uDCB0-\\uDCBA\\uDCF0-\\uDCF9\\uDD00-\\uDD02\\uDD27-\\uDD34\\uDD36-\\uDD3F\\uDD45\\uDD46\\uDD73\\uDD80-\\uDD82\\uDDB3-\\uDDC0\\uDDC9-\\uDDCC\\uDDD0-\\uDDD9\\uDE2C-\\uDE37\\uDE3E\\uDEDF-\\uDEEA\\uDEF0-\\uDEF9\\uDF00-\\uDF03\\uDF3B\\uDF3C\\uDF3E-\\uDF44\\uDF47\\uDF48\\uDF4B-\\uDF4D\\uDF57\\uDF62\\uDF63\\uDF66-\\uDF6C\\uDF70-\\uDF74]|\\uD805[\\uDC35-\\uDC46\\uDC50-\\uDC59\\uDC5E\\uDCB0-\\uDCC3\\uDCD0-\\uDCD9\\uDDAF-\\uDDB5\\uDDB8-\\uDDC0\\uDDDC\\uDDDD\\uDE30-\\uDE40\\uDE50-\\uDE59\\uDEAB-\\uDEB7\\uDEC0-\\uDEC9\\uDF1D-\\uDF2B\\uDF30-\\uDF39]|\\uD806[\\uDC2C-\\uDC3A\\uDCE0-\\uDCE9\\uDE01-\\uDE0A\\uDE33-\\uDE39\\uDE3B-\\uDE3E\\uDE47\\uDE51-\\uDE5B\\uDE8A-\\uDE99]|\\uD807[\\uDC2F-\\uDC36\\uDC38-\\uDC3F\\uDC50-\\uDC59\\uDC92-\\uDCA7\\uDCA9-\\uDCB6\\uDD31-\\uDD36\\uDD3A\\uDD3C\\uDD3D\\uDD3F-\\uDD45\\uDD47\\uDD50-\\uDD59\\uDD8A-\\uDD8E\\uDD90\\uDD91\\uDD93-\\uDD97\\uDDA0-\\uDDA9\\uDEF3-\\uDEF6]|\\uD81A[\\uDE60-\\uDE69\\uDEF0-\\uDEF4\\uDF30-\\uDF36\\uDF50-\\uDF59]|\\uD81B[\\uDF51-\\uDF7E\\uDF8F-\\uDF92]|\\uD82F[\\uDC9D\\uDC9E]|\\uD834[\\uDD65-\\uDD69\\uDD6D-\\uDD72\\uDD7B-\\uDD82\\uDD85-\\uDD8B\\uDDAA-\\uDDAD\\uDE42-\\uDE44]|\\uD835[\\uDFCE-\\uDFFF]|\\uD836[\\uDE00-\\uDE36\\uDE3B-\\uDE6C\\uDE75\\uDE84\\uDE9B-\\uDE9F\\uDEA1-\\uDEAF]|\\uD838[\\uDC00-\\uDC06\\uDC08-\\uDC18\\uDC1B-\\uDC21\\uDC23\\uDC24\\uDC26-\\uDC2A]|\\uD83A[\\uDCD0-\\uDCD6\\uDD44-\\uDD4A\\uDD50-\\uDD59]|\\uDB40[\\uDD00-\\uDDEF]", "/", ";", "return", "isIdentifierStart", "(", "ch", ")", "||", "(", "ch", ">=", "48", "&&", "ch", "<=", "57", ")", "||", "// 0..9", "(", "(", "ch", ">=", "0x80", ")", "&&", "NonAsciiIdentifierPartOnly", ".", "test", "(", "fromCodePoint", "(", "ch", ")", ")", ")", ";", "}" ]
Taken from the Esprima parser.
[ "Taken", "from", "the", "Esprima", "parser", "." ]
0f12db12eb2ecb67143979ddba275c4aa87c40b2
https://github.com/jviereck/regjsparser/blob/0f12db12eb2ecb67143979ddba275c4aa87c40b2/parser.js#L933-L940
21,190
Nike-Inc/lambda-logger-node
src/logger.js
Logger
function Logger ({ minimumLogLevel = null, formatter = JsonFormatter, useBearerRedactor = true, useGlobalErrorHandler = true, forceGlobalErrorHandler = false, redactors = [] } = {}) { const context = { minimumLogLevel, formatter, events: new EventEmitter(), contextPath: [], keys: new Map() } if (useBearerRedactor) { redactors.push(bearerRedactor(context)) } if (useGlobalErrorHandler) { registerErrorHandlers(context, forceGlobalErrorHandler) } context.redact = wrapRedact(context, redactors) context.logger = { handler: wrapHandler(context), setMinimumLogLevel: wrapSetMinimumLogLevel(context), events: context.events, setKey: wrapSetKey(context), ...createLogger(context) } return context.logger }
javascript
function Logger ({ minimumLogLevel = null, formatter = JsonFormatter, useBearerRedactor = true, useGlobalErrorHandler = true, forceGlobalErrorHandler = false, redactors = [] } = {}) { const context = { minimumLogLevel, formatter, events: new EventEmitter(), contextPath: [], keys: new Map() } if (useBearerRedactor) { redactors.push(bearerRedactor(context)) } if (useGlobalErrorHandler) { registerErrorHandlers(context, forceGlobalErrorHandler) } context.redact = wrapRedact(context, redactors) context.logger = { handler: wrapHandler(context), setMinimumLogLevel: wrapSetMinimumLogLevel(context), events: context.events, setKey: wrapSetKey(context), ...createLogger(context) } return context.logger }
[ "function", "Logger", "(", "{", "minimumLogLevel", "=", "null", ",", "formatter", "=", "JsonFormatter", ",", "useBearerRedactor", "=", "true", ",", "useGlobalErrorHandler", "=", "true", ",", "forceGlobalErrorHandler", "=", "false", ",", "redactors", "=", "[", "]", "}", "=", "{", "}", ")", "{", "const", "context", "=", "{", "minimumLogLevel", ",", "formatter", ",", "events", ":", "new", "EventEmitter", "(", ")", ",", "contextPath", ":", "[", "]", ",", "keys", ":", "new", "Map", "(", ")", "}", "if", "(", "useBearerRedactor", ")", "{", "redactors", ".", "push", "(", "bearerRedactor", "(", "context", ")", ")", "}", "if", "(", "useGlobalErrorHandler", ")", "{", "registerErrorHandlers", "(", "context", ",", "forceGlobalErrorHandler", ")", "}", "context", ".", "redact", "=", "wrapRedact", "(", "context", ",", "redactors", ")", "context", ".", "logger", "=", "{", "handler", ":", "wrapHandler", "(", "context", ")", ",", "setMinimumLogLevel", ":", "wrapSetMinimumLogLevel", "(", "context", ")", ",", "events", ":", "context", ".", "events", ",", "setKey", ":", "wrapSetKey", "(", "context", ")", ",", "...", "createLogger", "(", "context", ")", "}", "return", "context", ".", "logger", "}" ]
Construct a new logger. Does not require "new". @param {Object} [{ minimumLogLevel = null, formatter = JsonFormatter, useBearerRedactor = true, useGlobalErrorHandler = true, redactors = [] }={}] options @param {Boolean} [null] options.minimumLogLevel hide log entries of lower severity @param {Formatter} [JsonFormatter] options.formatter thunk that receives the log context, must return a function to handler formatting log messages. Defaults to JsonFormatter @param {Boolean} [true] options.useBearerRedactor add a Bearer token redactor @param {Boolean} [true] options.useGlobalErrorHandler setup global handlers for uncaughtException and unhandledRejection. Only one logger per-lambda can use this option. @param {(string|RegExp|RedactorFunction)[]} [[]] options.redactors array of redactors. A Redactor is a string or regex to globally replace, or a user=supplied function that is invoked during the redaction phase. @returns {Logger}
[ "Construct", "a", "new", "logger", ".", "Does", "not", "require", "new", "." ]
6ec8ca98241e74882c225cdcb4306e942541b4ab
https://github.com/Nike-Inc/lambda-logger-node/blob/6ec8ca98241e74882c225cdcb4306e942541b4ab/src/logger.js#L43-L75
21,191
cheminfo-js/netcdfjs
src/data.js
nonRecord
function nonRecord(buffer, variable) { // variable type const type = types.str2num(variable.type); // size of the data var size = variable.size / types.num2bytes(type); // iterates over the data var data = new Array(size); for (var i = 0; i < size; i++) { data[i] = types.readType(buffer, type, 1); } return data; }
javascript
function nonRecord(buffer, variable) { // variable type const type = types.str2num(variable.type); // size of the data var size = variable.size / types.num2bytes(type); // iterates over the data var data = new Array(size); for (var i = 0; i < size; i++) { data[i] = types.readType(buffer, type, 1); } return data; }
[ "function", "nonRecord", "(", "buffer", ",", "variable", ")", "{", "// variable type", "const", "type", "=", "types", ".", "str2num", "(", "variable", ".", "type", ")", ";", "// size of the data", "var", "size", "=", "variable", ".", "size", "/", "types", ".", "num2bytes", "(", "type", ")", ";", "// iterates over the data", "var", "data", "=", "new", "Array", "(", "size", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "data", "[", "i", "]", "=", "types", ".", "readType", "(", "buffer", ",", "type", ",", "1", ")", ";", "}", "return", "data", ";", "}" ]
const STREAMING = 4294967295; Read data for the given non-record variable @ignore @param {IOBuffer} buffer - Buffer for the file data @param {object} variable - Variable metadata @return {Array} - Data of the element
[ "const", "STREAMING", "=", "4294967295", ";", "Read", "data", "for", "the", "given", "non", "-", "record", "variable" ]
ac528ad0fa6b78de001c3fe86eebb2728d1d27e4
https://github.com/cheminfo-js/netcdfjs/blob/ac528ad0fa6b78de001c3fe86eebb2728d1d27e4/src/data.js#L14-L28
21,192
cheminfo-js/netcdfjs
src/data.js
record
function record(buffer, variable, recordDimension) { // variable type const type = types.str2num(variable.type); const width = variable.size ? variable.size / types.num2bytes(type) : 1; // size of the data // TODO streaming data var size = recordDimension.length; // iterates over the data var data = new Array(size); const step = recordDimension.recordStep; for (var i = 0; i < size; i++) { var currentOffset = buffer.offset; data[i] = types.readType(buffer, type, width); buffer.seek(currentOffset + step); } return data; }
javascript
function record(buffer, variable, recordDimension) { // variable type const type = types.str2num(variable.type); const width = variable.size ? variable.size / types.num2bytes(type) : 1; // size of the data // TODO streaming data var size = recordDimension.length; // iterates over the data var data = new Array(size); const step = recordDimension.recordStep; for (var i = 0; i < size; i++) { var currentOffset = buffer.offset; data[i] = types.readType(buffer, type, width); buffer.seek(currentOffset + step); } return data; }
[ "function", "record", "(", "buffer", ",", "variable", ",", "recordDimension", ")", "{", "// variable type", "const", "type", "=", "types", ".", "str2num", "(", "variable", ".", "type", ")", ";", "const", "width", "=", "variable", ".", "size", "?", "variable", ".", "size", "/", "types", ".", "num2bytes", "(", "type", ")", ":", "1", ";", "// size of the data", "// TODO streaming data", "var", "size", "=", "recordDimension", ".", "length", ";", "// iterates over the data", "var", "data", "=", "new", "Array", "(", "size", ")", ";", "const", "step", "=", "recordDimension", ".", "recordStep", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "var", "currentOffset", "=", "buffer", ".", "offset", ";", "data", "[", "i", "]", "=", "types", ".", "readType", "(", "buffer", ",", "type", ",", "width", ")", ";", "buffer", ".", "seek", "(", "currentOffset", "+", "step", ")", ";", "}", "return", "data", ";", "}" ]
Read data for the given record variable @ignore @param {IOBuffer} buffer - Buffer for the file data @param {object} variable - Variable metadata @param {object} recordDimension - Record dimension metadata @return {Array} - Data of the element
[ "Read", "data", "for", "the", "given", "record", "variable" ]
ac528ad0fa6b78de001c3fe86eebb2728d1d27e4
https://github.com/cheminfo-js/netcdfjs/blob/ac528ad0fa6b78de001c3fe86eebb2728d1d27e4/src/data.js#L38-L58
21,193
cheminfo-js/netcdfjs
src/header.js
header
function header(buffer, version) { // Length of record dimension // sum of the varSize's of all the record variables. var header = { recordDimension: { length: buffer.readUint32() } }; // Version header.version = version; // List of dimensions var dimList = dimensionsList(buffer); header.recordDimension.id = dimList.recordId; // id of the unlimited dimension header.recordDimension.name = dimList.recordName; // name of the unlimited dimension header.dimensions = dimList.dimensions; // List of global attributes header.globalAttributes = attributesList(buffer); // List of variables var variables = variablesList(buffer, dimList.recordId, version); header.variables = variables.variables; header.recordDimension.recordStep = variables.recordStep; return header; }
javascript
function header(buffer, version) { // Length of record dimension // sum of the varSize's of all the record variables. var header = { recordDimension: { length: buffer.readUint32() } }; // Version header.version = version; // List of dimensions var dimList = dimensionsList(buffer); header.recordDimension.id = dimList.recordId; // id of the unlimited dimension header.recordDimension.name = dimList.recordName; // name of the unlimited dimension header.dimensions = dimList.dimensions; // List of global attributes header.globalAttributes = attributesList(buffer); // List of variables var variables = variablesList(buffer, dimList.recordId, version); header.variables = variables.variables; header.recordDimension.recordStep = variables.recordStep; return header; }
[ "function", "header", "(", "buffer", ",", "version", ")", "{", "// Length of record dimension", "// sum of the varSize's of all the record variables.", "var", "header", "=", "{", "recordDimension", ":", "{", "length", ":", "buffer", ".", "readUint32", "(", ")", "}", "}", ";", "// Version", "header", ".", "version", "=", "version", ";", "// List of dimensions", "var", "dimList", "=", "dimensionsList", "(", "buffer", ")", ";", "header", ".", "recordDimension", ".", "id", "=", "dimList", ".", "recordId", ";", "// id of the unlimited dimension", "header", ".", "recordDimension", ".", "name", "=", "dimList", ".", "recordName", ";", "// name of the unlimited dimension", "header", ".", "dimensions", "=", "dimList", ".", "dimensions", ";", "// List of global attributes", "header", ".", "globalAttributes", "=", "attributesList", "(", "buffer", ")", ";", "// List of variables", "var", "variables", "=", "variablesList", "(", "buffer", ",", "dimList", ".", "recordId", ",", "version", ")", ";", "header", ".", "variables", "=", "variables", ".", "variables", ";", "header", ".", "recordDimension", ".", "recordStep", "=", "variables", ".", "recordStep", ";", "return", "header", ";", "}" ]
Read the header of the file @ignore @param {IOBuffer} buffer - Buffer for the file data @param {number} version - Version of the file @return {object} - Object with the fields: * `recordDimension`: Number with the length of record dimension * `dimensions`: List of dimensions * `globalAttributes`: List of global attributes * `variables`: List of variables
[ "Read", "the", "header", "of", "the", "file" ]
ac528ad0fa6b78de001c3fe86eebb2728d1d27e4
https://github.com/cheminfo-js/netcdfjs/blob/ac528ad0fa6b78de001c3fe86eebb2728d1d27e4/src/header.js#L23-L46
21,194
cheminfo-js/netcdfjs
src/header.js
dimensionsList
function dimensionsList(buffer) { var recordId, recordName; const dimList = buffer.readUint32(); if (dimList === ZERO) { utils.notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of dimensions'); return []; } else { utils.notNetcdf((dimList !== NC_DIMENSION), 'wrong tag for list of dimensions'); // Length of dimensions const dimensionSize = buffer.readUint32(); var dimensions = new Array(dimensionSize); for (var dim = 0; dim < dimensionSize; dim++) { // Read name var name = utils.readName(buffer); // Read dimension size const size = buffer.readUint32(); if (size === NC_UNLIMITED) { // in netcdf 3 one field can be of size unlimmited recordId = dim; recordName = name; } dimensions[dim] = { name: name, size: size }; } } return { dimensions: dimensions, recordId: recordId, recordName: recordName }; }
javascript
function dimensionsList(buffer) { var recordId, recordName; const dimList = buffer.readUint32(); if (dimList === ZERO) { utils.notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of dimensions'); return []; } else { utils.notNetcdf((dimList !== NC_DIMENSION), 'wrong tag for list of dimensions'); // Length of dimensions const dimensionSize = buffer.readUint32(); var dimensions = new Array(dimensionSize); for (var dim = 0; dim < dimensionSize; dim++) { // Read name var name = utils.readName(buffer); // Read dimension size const size = buffer.readUint32(); if (size === NC_UNLIMITED) { // in netcdf 3 one field can be of size unlimmited recordId = dim; recordName = name; } dimensions[dim] = { name: name, size: size }; } } return { dimensions: dimensions, recordId: recordId, recordName: recordName }; }
[ "function", "dimensionsList", "(", "buffer", ")", "{", "var", "recordId", ",", "recordName", ";", "const", "dimList", "=", "buffer", ".", "readUint32", "(", ")", ";", "if", "(", "dimList", "===", "ZERO", ")", "{", "utils", ".", "notNetcdf", "(", "(", "buffer", ".", "readUint32", "(", ")", "!==", "ZERO", ")", ",", "'wrong empty tag for list of dimensions'", ")", ";", "return", "[", "]", ";", "}", "else", "{", "utils", ".", "notNetcdf", "(", "(", "dimList", "!==", "NC_DIMENSION", ")", ",", "'wrong tag for list of dimensions'", ")", ";", "// Length of dimensions", "const", "dimensionSize", "=", "buffer", ".", "readUint32", "(", ")", ";", "var", "dimensions", "=", "new", "Array", "(", "dimensionSize", ")", ";", "for", "(", "var", "dim", "=", "0", ";", "dim", "<", "dimensionSize", ";", "dim", "++", ")", "{", "// Read name", "var", "name", "=", "utils", ".", "readName", "(", "buffer", ")", ";", "// Read dimension size", "const", "size", "=", "buffer", ".", "readUint32", "(", ")", ";", "if", "(", "size", "===", "NC_UNLIMITED", ")", "{", "// in netcdf 3 one field can be of size unlimmited", "recordId", "=", "dim", ";", "recordName", "=", "name", ";", "}", "dimensions", "[", "dim", "]", "=", "{", "name", ":", "name", ",", "size", ":", "size", "}", ";", "}", "}", "return", "{", "dimensions", ":", "dimensions", ",", "recordId", ":", "recordId", ",", "recordName", ":", "recordName", "}", ";", "}" ]
List of dimensions @ignore @param {IOBuffer} buffer - Buffer for the file data @return {object} - Ojbect containing the following properties: * `dimensions` that is an array of dimension object: * `name`: String with the name of the dimension * `size`: Number with the size of the dimension dimensions: dimensions * `recordId`: the id of the dimension that has unlimited size or undefined, * `recordName`: name of the dimension that has unlimited size
[ "List", "of", "dimensions" ]
ac528ad0fa6b78de001c3fe86eebb2728d1d27e4
https://github.com/cheminfo-js/netcdfjs/blob/ac528ad0fa6b78de001c3fe86eebb2728d1d27e4/src/header.js#L61-L95
21,195
cheminfo-js/netcdfjs
src/header.js
attributesList
function attributesList(buffer) { const gAttList = buffer.readUint32(); if (gAttList === ZERO) { utils.notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of attributes'); return []; } else { utils.notNetcdf((gAttList !== NC_ATTRIBUTE), 'wrong tag for list of attributes'); // Length of attributes const attributeSize = buffer.readUint32(); var attributes = new Array(attributeSize); for (var gAtt = 0; gAtt < attributeSize; gAtt++) { // Read name var name = utils.readName(buffer); // Read type var type = buffer.readUint32(); utils.notNetcdf(((type < 1) || (type > 6)), `non valid type ${type}`); // Read attribute var size = buffer.readUint32(); var value = types.readType(buffer, type, size); // Apply padding utils.padding(buffer); attributes[gAtt] = { name: name, type: types.num2str(type), value: value }; } } return attributes; }
javascript
function attributesList(buffer) { const gAttList = buffer.readUint32(); if (gAttList === ZERO) { utils.notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of attributes'); return []; } else { utils.notNetcdf((gAttList !== NC_ATTRIBUTE), 'wrong tag for list of attributes'); // Length of attributes const attributeSize = buffer.readUint32(); var attributes = new Array(attributeSize); for (var gAtt = 0; gAtt < attributeSize; gAtt++) { // Read name var name = utils.readName(buffer); // Read type var type = buffer.readUint32(); utils.notNetcdf(((type < 1) || (type > 6)), `non valid type ${type}`); // Read attribute var size = buffer.readUint32(); var value = types.readType(buffer, type, size); // Apply padding utils.padding(buffer); attributes[gAtt] = { name: name, type: types.num2str(type), value: value }; } } return attributes; }
[ "function", "attributesList", "(", "buffer", ")", "{", "const", "gAttList", "=", "buffer", ".", "readUint32", "(", ")", ";", "if", "(", "gAttList", "===", "ZERO", ")", "{", "utils", ".", "notNetcdf", "(", "(", "buffer", ".", "readUint32", "(", ")", "!==", "ZERO", ")", ",", "'wrong empty tag for list of attributes'", ")", ";", "return", "[", "]", ";", "}", "else", "{", "utils", ".", "notNetcdf", "(", "(", "gAttList", "!==", "NC_ATTRIBUTE", ")", ",", "'wrong tag for list of attributes'", ")", ";", "// Length of attributes", "const", "attributeSize", "=", "buffer", ".", "readUint32", "(", ")", ";", "var", "attributes", "=", "new", "Array", "(", "attributeSize", ")", ";", "for", "(", "var", "gAtt", "=", "0", ";", "gAtt", "<", "attributeSize", ";", "gAtt", "++", ")", "{", "// Read name", "var", "name", "=", "utils", ".", "readName", "(", "buffer", ")", ";", "// Read type", "var", "type", "=", "buffer", ".", "readUint32", "(", ")", ";", "utils", ".", "notNetcdf", "(", "(", "(", "type", "<", "1", ")", "||", "(", "type", ">", "6", ")", ")", ",", "`", "${", "type", "}", "`", ")", ";", "// Read attribute", "var", "size", "=", "buffer", ".", "readUint32", "(", ")", ";", "var", "value", "=", "types", ".", "readType", "(", "buffer", ",", "type", ",", "size", ")", ";", "// Apply padding", "utils", ".", "padding", "(", "buffer", ")", ";", "attributes", "[", "gAtt", "]", "=", "{", "name", ":", "name", ",", "type", ":", "types", ".", "num2str", "(", "type", ")", ",", "value", ":", "value", "}", ";", "}", "}", "return", "attributes", ";", "}" ]
List of attributes @ignore @param {IOBuffer} buffer - Buffer for the file data @return {Array<object>} - List of attributes with: * `name`: String with the name of the attribute * `type`: String with the type of the attribute * `value`: A number or string with the value of the attribute
[ "List", "of", "attributes" ]
ac528ad0fa6b78de001c3fe86eebb2728d1d27e4
https://github.com/cheminfo-js/netcdfjs/blob/ac528ad0fa6b78de001c3fe86eebb2728d1d27e4/src/header.js#L106-L140
21,196
cheminfo-js/netcdfjs
src/header.js
variablesList
function variablesList(buffer, recordId, version) { const varList = buffer.readUint32(); var recordStep = 0; if (varList === ZERO) { utils.notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of variables'); return []; } else { utils.notNetcdf((varList !== NC_VARIABLE), 'wrong tag for list of variables'); // Length of variables const variableSize = buffer.readUint32(); var variables = new Array(variableSize); for (var v = 0; v < variableSize; v++) { // Read name var name = utils.readName(buffer); // Read dimensionality of the variable const dimensionality = buffer.readUint32(); // Index into the list of dimensions var dimensionsIds = new Array(dimensionality); for (var dim = 0; dim < dimensionality; dim++) { dimensionsIds[dim] = buffer.readUint32(); } // Read variables size var attributes = attributesList(buffer); // Read type var type = buffer.readUint32(); utils.notNetcdf(((type < 1) && (type > 6)), `non valid type ${type}`); // Read variable size // The 32-bit varSize field is not large enough to contain the size of variables that require // more than 2^32 - 4 bytes, so 2^32 - 1 is used in the varSize field for such variables. const varSize = buffer.readUint32(); // Read offset var offset = buffer.readUint32(); if (version === 2) { utils.notNetcdf((offset > 0), 'offsets larger than 4GB not supported'); offset = buffer.readUint32(); } let record = false; // Count amount of record variables if ((typeof recordId !== 'undefined') && (dimensionsIds[0] === recordId)) { recordStep += varSize; record = true; } variables[v] = { name: name, dimensions: dimensionsIds, attributes, type: types.num2str(type), size: varSize, offset, record }; } } return { variables: variables, recordStep: recordStep }; }
javascript
function variablesList(buffer, recordId, version) { const varList = buffer.readUint32(); var recordStep = 0; if (varList === ZERO) { utils.notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of variables'); return []; } else { utils.notNetcdf((varList !== NC_VARIABLE), 'wrong tag for list of variables'); // Length of variables const variableSize = buffer.readUint32(); var variables = new Array(variableSize); for (var v = 0; v < variableSize; v++) { // Read name var name = utils.readName(buffer); // Read dimensionality of the variable const dimensionality = buffer.readUint32(); // Index into the list of dimensions var dimensionsIds = new Array(dimensionality); for (var dim = 0; dim < dimensionality; dim++) { dimensionsIds[dim] = buffer.readUint32(); } // Read variables size var attributes = attributesList(buffer); // Read type var type = buffer.readUint32(); utils.notNetcdf(((type < 1) && (type > 6)), `non valid type ${type}`); // Read variable size // The 32-bit varSize field is not large enough to contain the size of variables that require // more than 2^32 - 4 bytes, so 2^32 - 1 is used in the varSize field for such variables. const varSize = buffer.readUint32(); // Read offset var offset = buffer.readUint32(); if (version === 2) { utils.notNetcdf((offset > 0), 'offsets larger than 4GB not supported'); offset = buffer.readUint32(); } let record = false; // Count amount of record variables if ((typeof recordId !== 'undefined') && (dimensionsIds[0] === recordId)) { recordStep += varSize; record = true; } variables[v] = { name: name, dimensions: dimensionsIds, attributes, type: types.num2str(type), size: varSize, offset, record }; } } return { variables: variables, recordStep: recordStep }; }
[ "function", "variablesList", "(", "buffer", ",", "recordId", ",", "version", ")", "{", "const", "varList", "=", "buffer", ".", "readUint32", "(", ")", ";", "var", "recordStep", "=", "0", ";", "if", "(", "varList", "===", "ZERO", ")", "{", "utils", ".", "notNetcdf", "(", "(", "buffer", ".", "readUint32", "(", ")", "!==", "ZERO", ")", ",", "'wrong empty tag for list of variables'", ")", ";", "return", "[", "]", ";", "}", "else", "{", "utils", ".", "notNetcdf", "(", "(", "varList", "!==", "NC_VARIABLE", ")", ",", "'wrong tag for list of variables'", ")", ";", "// Length of variables", "const", "variableSize", "=", "buffer", ".", "readUint32", "(", ")", ";", "var", "variables", "=", "new", "Array", "(", "variableSize", ")", ";", "for", "(", "var", "v", "=", "0", ";", "v", "<", "variableSize", ";", "v", "++", ")", "{", "// Read name", "var", "name", "=", "utils", ".", "readName", "(", "buffer", ")", ";", "// Read dimensionality of the variable", "const", "dimensionality", "=", "buffer", ".", "readUint32", "(", ")", ";", "// Index into the list of dimensions", "var", "dimensionsIds", "=", "new", "Array", "(", "dimensionality", ")", ";", "for", "(", "var", "dim", "=", "0", ";", "dim", "<", "dimensionality", ";", "dim", "++", ")", "{", "dimensionsIds", "[", "dim", "]", "=", "buffer", ".", "readUint32", "(", ")", ";", "}", "// Read variables size", "var", "attributes", "=", "attributesList", "(", "buffer", ")", ";", "// Read type", "var", "type", "=", "buffer", ".", "readUint32", "(", ")", ";", "utils", ".", "notNetcdf", "(", "(", "(", "type", "<", "1", ")", "&&", "(", "type", ">", "6", ")", ")", ",", "`", "${", "type", "}", "`", ")", ";", "// Read variable size", "// The 32-bit varSize field is not large enough to contain the size of variables that require", "// more than 2^32 - 4 bytes, so 2^32 - 1 is used in the varSize field for such variables.", "const", "varSize", "=", "buffer", ".", "readUint32", "(", ")", ";", "// Read offset", "var", "offset", "=", "buffer", ".", "readUint32", "(", ")", ";", "if", "(", "version", "===", "2", ")", "{", "utils", ".", "notNetcdf", "(", "(", "offset", ">", "0", ")", ",", "'offsets larger than 4GB not supported'", ")", ";", "offset", "=", "buffer", ".", "readUint32", "(", ")", ";", "}", "let", "record", "=", "false", ";", "// Count amount of record variables", "if", "(", "(", "typeof", "recordId", "!==", "'undefined'", ")", "&&", "(", "dimensionsIds", "[", "0", "]", "===", "recordId", ")", ")", "{", "recordStep", "+=", "varSize", ";", "record", "=", "true", ";", "}", "variables", "[", "v", "]", "=", "{", "name", ":", "name", ",", "dimensions", ":", "dimensionsIds", ",", "attributes", ",", "type", ":", "types", ".", "num2str", "(", "type", ")", ",", "size", ":", "varSize", ",", "offset", ",", "record", "}", ";", "}", "}", "return", "{", "variables", ":", "variables", ",", "recordStep", ":", "recordStep", "}", ";", "}" ]
List of variables @ignore @param {IOBuffer} buffer - Buffer for the file data @param {number} recordId - Id of the unlimited dimension (also called record dimension) This value may be undefined if there is no unlimited dimension @param {number} version - Version of the file @return {object} - Number of recordStep and list of variables with: * `name`: String with the name of the variable * `dimensions`: Array with the dimension IDs of the variable * `attributes`: Array with the attributes of the variable * `type`: String with the type of the variable * `size`: Number with the size of the variable * `offset`: Number with the offset where of the variable begins * `record`: True if is a record variable, false otherwise (unlimited size)
[ "List", "of", "variables" ]
ac528ad0fa6b78de001c3fe86eebb2728d1d27e4
https://github.com/cheminfo-js/netcdfjs/blob/ac528ad0fa6b78de001c3fe86eebb2728d1d27e4/src/header.js#L159-L225
21,197
cheminfo-js/netcdfjs
src/types.js
num2str
function num2str(type) { switch (Number(type)) { case types.BYTE: return 'byte'; case types.CHAR: return 'char'; case types.SHORT: return 'short'; case types.INT: return 'int'; case types.FLOAT: return 'float'; case types.DOUBLE: return 'double'; /* istanbul ignore next */ default: return 'undefined'; } }
javascript
function num2str(type) { switch (Number(type)) { case types.BYTE: return 'byte'; case types.CHAR: return 'char'; case types.SHORT: return 'short'; case types.INT: return 'int'; case types.FLOAT: return 'float'; case types.DOUBLE: return 'double'; /* istanbul ignore next */ default: return 'undefined'; } }
[ "function", "num2str", "(", "type", ")", "{", "switch", "(", "Number", "(", "type", ")", ")", "{", "case", "types", ".", "BYTE", ":", "return", "'byte'", ";", "case", "types", ".", "CHAR", ":", "return", "'char'", ";", "case", "types", ".", "SHORT", ":", "return", "'short'", ";", "case", "types", ".", "INT", ":", "return", "'int'", ";", "case", "types", ".", "FLOAT", ":", "return", "'float'", ";", "case", "types", ".", "DOUBLE", ":", "return", "'double'", ";", "/* istanbul ignore next */", "default", ":", "return", "'undefined'", ";", "}", "}" ]
Parse a number into their respective type @ignore @param {number} type - integer that represents the type @return {string} - parsed value of the type
[ "Parse", "a", "number", "into", "their", "respective", "type" ]
ac528ad0fa6b78de001c3fe86eebb2728d1d27e4
https://github.com/cheminfo-js/netcdfjs/blob/ac528ad0fa6b78de001c3fe86eebb2728d1d27e4/src/types.js#L20-L38
21,198
cheminfo-js/netcdfjs
src/types.js
str2num
function str2num(type) { switch (String(type)) { case 'byte': return types.BYTE; case 'char': return types.CHAR; case 'short': return types.SHORT; case 'int': return types.INT; case 'float': return types.FLOAT; case 'double': return types.DOUBLE; /* istanbul ignore next */ default: return -1; } }
javascript
function str2num(type) { switch (String(type)) { case 'byte': return types.BYTE; case 'char': return types.CHAR; case 'short': return types.SHORT; case 'int': return types.INT; case 'float': return types.FLOAT; case 'double': return types.DOUBLE; /* istanbul ignore next */ default: return -1; } }
[ "function", "str2num", "(", "type", ")", "{", "switch", "(", "String", "(", "type", ")", ")", "{", "case", "'byte'", ":", "return", "types", ".", "BYTE", ";", "case", "'char'", ":", "return", "types", ".", "CHAR", ";", "case", "'short'", ":", "return", "types", ".", "SHORT", ";", "case", "'int'", ":", "return", "types", ".", "INT", ";", "case", "'float'", ":", "return", "types", ".", "FLOAT", ";", "case", "'double'", ":", "return", "types", ".", "DOUBLE", ";", "/* istanbul ignore next */", "default", ":", "return", "-", "1", ";", "}", "}" ]
Reverse search of num2str @ignore @param {string} type - string that represents the type @return {number} - parsed value of the type
[ "Reverse", "search", "of", "num2str" ]
ac528ad0fa6b78de001c3fe86eebb2728d1d27e4
https://github.com/cheminfo-js/netcdfjs/blob/ac528ad0fa6b78de001c3fe86eebb2728d1d27e4/src/types.js#L72-L90
21,199
cheminfo-js/netcdfjs
src/types.js
readNumber
function readNumber(size, bufferReader) { if (size !== 1) { var numbers = new Array(size); for (var i = 0; i < size; i++) { numbers[i] = bufferReader(); } return numbers; } else { return bufferReader(); } }
javascript
function readNumber(size, bufferReader) { if (size !== 1) { var numbers = new Array(size); for (var i = 0; i < size; i++) { numbers[i] = bufferReader(); } return numbers; } else { return bufferReader(); } }
[ "function", "readNumber", "(", "size", ",", "bufferReader", ")", "{", "if", "(", "size", "!==", "1", ")", "{", "var", "numbers", "=", "new", "Array", "(", "size", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "numbers", "[", "i", "]", "=", "bufferReader", "(", ")", ";", "}", "return", "numbers", ";", "}", "else", "{", "return", "bufferReader", "(", ")", ";", "}", "}" ]
Auxiliary function to read numeric data @ignore @param {number} size - Size of the element to read @param {function} bufferReader - Function to read next value @return {Array<number>|number}
[ "Auxiliary", "function", "to", "read", "numeric", "data" ]
ac528ad0fa6b78de001c3fe86eebb2728d1d27e4
https://github.com/cheminfo-js/netcdfjs/blob/ac528ad0fa6b78de001c3fe86eebb2728d1d27e4/src/types.js#L99-L109